datafusion 54.0.0

DataFusion is an in-memory query engine that uses Apache Arrow as the memory model
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

use arrow::array::{ArrayRef, RecordBatch};
use arrow_schema::DataType;
use arrow_schema::TimeUnit::Nanosecond;
use criterion::{BenchmarkId, Criterion, criterion_group, criterion_main};
use datafusion::prelude::{DataFrame, SessionContext};
use datafusion_catalog::MemTable;
use datafusion_common::ScalarValue;
use datafusion_expr::Expr::Literal;
use datafusion_expr::{cast, col, lit, not, try_cast, when};
use datafusion_functions::expr_fn::{
    btrim, length, regexp_like, regexp_replace, to_timestamp, upper,
};
use std::fmt::Write;
use std::hint::black_box;
use std::ops::Rem;
use std::sync::Arc;
use tokio::runtime::Runtime;

// This benchmark suite is designed to test the performance of
// logical planning with a large plan containing unions, many columns
// with a variety of operations in it.
//
// Since it is (currently) very slow to execute it has been separated
// out from the sql_planner benchmark suite to this file.
//
// See https://github.com/apache/datafusion/issues/17261 for details.

/// Registers a table like this:
/// c0,c1,c2...,c99
/// "0","100"..."9900"
/// "0","200"..."19800"
/// "0","300"..."29700"
fn register_string_table(ctx: &SessionContext, num_columns: usize, num_rows: usize) {
    // ("c0", ["0", "0", ...])
    // ("c1": ["100", "200", ...])
    // etc
    let iter = (0..num_columns).map(|i| i as u64).map(|i| {
        let array: ArrayRef = Arc::new(arrow::array::StringViewArray::from_iter_values(
            (0..num_rows)
                .map(|j| format!("c{}", j as u64 * 100 + i))
                .collect::<Vec<_>>(),
        ));
        (format!("c{i}"), array)
    });
    let batch = RecordBatch::try_from_iter(iter).unwrap();
    let schema = batch.schema();
    let partitions = vec![vec![batch]];

    // create the table
    let table = MemTable::try_new(schema, partitions).unwrap();

    ctx.register_table("t", Arc::new(table)).unwrap();
}

/// Build a dataframe for testing logical plan optimization
fn build_test_data_frame(ctx: &SessionContext, rt: &Runtime) -> DataFrame {
    register_string_table(ctx, 100, 1000);

    rt.block_on(async {
        let mut df = ctx.table("t").await.unwrap();
        // add some columns in
        for i in 100..150 {
            df = df
                .with_column(&format!("c{i}"), Literal(ScalarValue::Utf8(None), None))
                .unwrap();
        }
        // add in some columns with string encoded timestamps
        for i in 150..175 {
            df = df
                .with_column(
                    &format!("c{i}"),
                    Literal(ScalarValue::Utf8(Some("2025-08-21 09:43:17".into())), None),
                )
                .unwrap();
        }
        // do a bunch of ops on the columns
        for i in 0..175 {
            // trim the columns
            df = df
                .with_column(&format!("c{i}"), btrim(vec![col(format!("c{i}"))]))
                .unwrap();
        }

        for i in 0..175 {
            let c_name = format!("c{i}");
            let c = col(&c_name);

            // random ops
            if i % 5 == 0 && i < 150 {
                // the actual ops here are largely unimportant as they are just a sample
                // of ops that could occur on a dataframe
                df = df
                    .with_column(&c_name, cast(c.clone(), DataType::Utf8))
                    .unwrap()
                    .with_column(
                        &c_name,
                        when(
                            cast(c.clone(), DataType::Int32).gt(lit(135)),
                            cast(
                                cast(c.clone(), DataType::Int32) - lit(i + 3),
                                DataType::Utf8,
                            ),
                        )
                        .otherwise(c.clone())
                        .unwrap(),
                    )
                    .unwrap()
                    .with_column(
                        &c_name,
                        when(
                            c.clone().is_not_null().and(
                                cast(c.clone(), DataType::Int32)
                                    .between(lit(120), lit(130)),
                            ),
                            Literal(ScalarValue::Utf8(None), None),
                        )
                        .otherwise(
                            when(
                                c.clone().is_not_null().and(regexp_like(
                                    cast(c.clone(), DataType::Utf8View),
                                    lit("[0-9]*"),
                                    None,
                                )),
                                upper(c.clone()),
                            )
                            .otherwise(c.clone())
                            .unwrap(),
                        )
                        .unwrap(),
                    )
                    .unwrap()
                    .with_column(
                        &c_name,
                        when(
                            c.clone().is_not_null().and(
                                cast(c.clone(), DataType::Int32)
                                    .between(lit(90), lit(100)),
                            ),
                            cast(c.clone(), DataType::Utf8View),
                        )
                        .otherwise(Literal(ScalarValue::Date32(None), None))
                        .unwrap(),
                    )
                    .unwrap()
                    .with_column(
                        &c_name,
                        when(
                            c.clone().is_not_null().and(
                                cast(c.clone(), DataType::Int32).rem(lit(10)).gt(lit(7)),
                            ),
                            regexp_replace(
                                cast(c.clone(), DataType::Utf8View),
                                lit("1"),
                                lit("a"),
                                None,
                            ),
                        )
                        .otherwise(Literal(ScalarValue::Date32(None), None))
                        .unwrap(),
                    )
                    .unwrap()
            }
            if i >= 150 {
                df = df
                    .with_column(
                        &c_name,
                        try_cast(
                            to_timestamp(vec![c.clone(), lit("%Y-%m-%d %H:%M:%S")]),
                            DataType::Timestamp(Nanosecond, Some("UTC".into())),
                        ),
                    )
                    .unwrap()
                    .with_column(&c_name, try_cast(c.clone(), DataType::Date32))
                    .unwrap()
            }

            // add in a few unions
            if i % 30 == 0 {
                let df1 = df
                    .clone()
                    .filter(length(c.clone()).gt(lit(2)))
                    .unwrap()
                    .with_column(&format!("c{i}_filtered"), lit(true))
                    .unwrap();
                let df2 = df
                    .filter(not(length(c.clone()).gt(lit(2))))
                    .unwrap()
                    .with_column(&format!("c{i}_filtered"), lit(false))
                    .unwrap();

                df = df1.union_by_name(df2).unwrap()
            }
        }

        df
    })
}

/// Build a CASE-heavy dataframe over a non-inner join to stress
/// planner-time filter pushdown and nullability/type inference.
fn build_case_heavy_left_join_df(ctx: &SessionContext, rt: &Runtime) -> DataFrame {
    register_string_table(ctx, 100, 1000);
    let query = build_case_heavy_left_join_query(30, 1);
    rt.block_on(async { ctx.sql(&query).await.unwrap() })
}

fn build_case_heavy_left_join_query(predicate_count: usize, case_depth: usize) -> String {
    let mut query = String::from(
        "SELECT l.c0, r.c0 AS rc0 FROM t l LEFT JOIN t r ON l.c0 = r.c0 WHERE ",
    );

    if predicate_count == 0 {
        query.push_str("TRUE");
        return query;
    }

    // Keep this deterministic so comparisons between profiles are stable.
    for i in 0..predicate_count {
        if i > 0 {
            query.push_str(" AND ");
        }

        let mut expr = format!("length(l.c{})", i % 20);
        for depth in 0..case_depth {
            let left_col = (i + depth + 1) % 20;
            let right_col = (i + depth + 2) % 20;
            expr = format!(
                "CASE WHEN l.c{left_col} IS NOT NULL THEN {expr} ELSE length(r.c{right_col}) END"
            );
        }

        let _ = write!(&mut query, "{expr} > 2");
    }

    query
}

fn build_case_heavy_left_join_df_with_push_down_filter(
    rt: &Runtime,
    predicate_count: usize,
    case_depth: usize,
    push_down_filter_enabled: bool,
) -> DataFrame {
    let ctx = SessionContext::new();
    register_string_table(&ctx, 100, 1000);
    if !push_down_filter_enabled {
        let removed = ctx.remove_optimizer_rule("push_down_filter");
        assert!(
            removed,
            "push_down_filter rule should be present in the default optimizer"
        );
    }

    let query = build_case_heavy_left_join_query(predicate_count, case_depth);
    rt.block_on(async { ctx.sql(&query).await.unwrap() })
}

fn build_non_case_left_join_query(
    predicate_count: usize,
    nesting_depth: usize,
) -> String {
    let mut query = String::from(
        "SELECT l.c0, r.c0 AS rc0 FROM t l LEFT JOIN t r ON l.c0 = r.c0 WHERE ",
    );

    if predicate_count == 0 {
        query.push_str("TRUE");
        return query;
    }

    // Keep this deterministic so comparisons between profiles are stable.
    for i in 0..predicate_count {
        if i > 0 {
            query.push_str(" AND ");
        }

        let left_col = i % 20;
        let mut expr = format!("l.c{left_col}");
        for depth in 0..nesting_depth {
            let right_col = (i + depth + 1) % 20;
            expr = format!("coalesce({expr}, r.c{right_col})");
        }

        let _ = write!(&mut query, "length({expr}) > 2");
    }

    query
}

fn build_non_case_left_join_df_with_push_down_filter(
    rt: &Runtime,
    predicate_count: usize,
    nesting_depth: usize,
    push_down_filter_enabled: bool,
) -> DataFrame {
    let ctx = SessionContext::new();
    register_string_table(&ctx, 100, 1000);
    if !push_down_filter_enabled {
        let removed = ctx.remove_optimizer_rule("push_down_filter");
        assert!(
            removed,
            "push_down_filter rule should be present in the default optimizer"
        );
    }

    let query = build_non_case_left_join_query(predicate_count, nesting_depth);
    rt.block_on(async { ctx.sql(&query).await.unwrap() })
}

fn criterion_benchmark(c: &mut Criterion) {
    let baseline_ctx = SessionContext::new();
    let case_heavy_ctx = SessionContext::new();
    let rt = Runtime::new().unwrap();

    // validate logical plan optimize performance
    // https://github.com/apache/datafusion/issues/17261

    let df = build_test_data_frame(&baseline_ctx, &rt);
    let case_heavy_left_join_df = build_case_heavy_left_join_df(&case_heavy_ctx, &rt);

    c.bench_function("logical_plan_optimize", |b| {
        b.iter(|| {
            let df_clone = df.clone();
            black_box(rt.block_on(async { df_clone.into_optimized_plan().unwrap() }));
        })
    });

    c.bench_function("logical_plan_optimize_hotspot_case_heavy_left_join", |b| {
        b.iter(|| {
            let df_clone = case_heavy_left_join_df.clone();
            black_box(rt.block_on(async { df_clone.into_optimized_plan().unwrap() }));
        })
    });

    let predicate_sweep = [10, 20, 30, 40, 60];
    let case_depth_sweep = [1, 2, 3];

    let mut hotspot_group =
        c.benchmark_group("push_down_filter_hotspot_case_heavy_left_join_ab");
    for case_depth in case_depth_sweep {
        for predicate_count in predicate_sweep {
            let with_push_down_filter =
                build_case_heavy_left_join_df_with_push_down_filter(
                    &rt,
                    predicate_count,
                    case_depth,
                    true,
                );
            let without_push_down_filter =
                build_case_heavy_left_join_df_with_push_down_filter(
                    &rt,
                    predicate_count,
                    case_depth,
                    false,
                );

            let input_label =
                format!("predicates={predicate_count},case_depth={case_depth}");
            // A/B interpretation:
            // - with_push_down_filter: default optimizer path (rule enabled)
            // - without_push_down_filter: control path with the rule removed
            // Compare both IDs at the same sweep point to isolate rule impact.
            hotspot_group.bench_with_input(
                BenchmarkId::new("with_push_down_filter", &input_label),
                &with_push_down_filter,
                |b, df| {
                    b.iter(|| {
                        let df_clone = df.clone();
                        black_box(
                            rt.block_on(async {
                                df_clone.into_optimized_plan().unwrap()
                            }),
                        );
                    })
                },
            );
            hotspot_group.bench_with_input(
                BenchmarkId::new("without_push_down_filter", &input_label),
                &without_push_down_filter,
                |b, df| {
                    b.iter(|| {
                        let df_clone = df.clone();
                        black_box(
                            rt.block_on(async {
                                df_clone.into_optimized_plan().unwrap()
                            }),
                        );
                    })
                },
            );
        }
    }
    hotspot_group.finish();

    let mut control_group =
        c.benchmark_group("push_down_filter_control_non_case_left_join_ab");
    for nesting_depth in case_depth_sweep {
        for predicate_count in predicate_sweep {
            let with_push_down_filter = build_non_case_left_join_df_with_push_down_filter(
                &rt,
                predicate_count,
                nesting_depth,
                true,
            );
            let without_push_down_filter =
                build_non_case_left_join_df_with_push_down_filter(
                    &rt,
                    predicate_count,
                    nesting_depth,
                    false,
                );

            let input_label =
                format!("predicates={predicate_count},nesting_depth={nesting_depth}");
            control_group.bench_with_input(
                BenchmarkId::new("with_push_down_filter", &input_label),
                &with_push_down_filter,
                |b, df| {
                    b.iter(|| {
                        let df_clone = df.clone();
                        black_box(
                            rt.block_on(async {
                                df_clone.into_optimized_plan().unwrap()
                            }),
                        );
                    })
                },
            );
            control_group.bench_with_input(
                BenchmarkId::new("without_push_down_filter", &input_label),
                &without_push_down_filter,
                |b, df| {
                    b.iter(|| {
                        let df_clone = df.clone();
                        black_box(
                            rt.block_on(async {
                                df_clone.into_optimized_plan().unwrap()
                            }),
                        );
                    })
                },
            );
        }
    }
    control_group.finish();
}

criterion_group!(benches, criterion_benchmark);
criterion_main!(benches);