Download datafusion_1/tests/private/eval_tests_aug.patch from lolbench26/LoLBench: direct link, hf CLI and curl.
- Browser
- Download file 33.1 kB
-
https://huggingface.co/datasets/lolbench26/LoLBench/resolve/main/datafusion_1/tests/private/eval_tests_aug.patch
- Command line
-
hf download hf://datasets/lolbench26/LoLBench/datafusion_1/tests/private/eval_tests_aug.patch
-
curl -L -o eval_tests_aug.patch https://huggingface.co/datasets/lolbench26/LoLBench/resolve/main/datafusion_1/tests/private/eval_tests_aug.patch
33.1 kB
| diff --git a/datafusion/core/tests/lolbench_aug.rs b/datafusion/core/tests/lolbench_aug.rs | |
| new file mode 100644 | |
| index 0000000..c665a88 | |
| --- /dev/null | |
| +++ b/datafusion/core/tests/lolbench_aug.rs | |
| +// 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. | |
| + | |
| +//! Augmented suite (lolbench-aug). The requirement keeps literal values | |
| +//! working as plain scalars everywhere (the optional metadata is additive), | |
| +//! so every literal-producing and literal-consuming surface must keep its | |
| +//! observable behavior: SQL constant folding, scalar subqueries, grouping, | |
| +//! projections, unparsing, typed `lit` construction, table functions and | |
| +//! partition pruning. All scenarios run through the public SessionContext / | |
| +//! DataFrame / SQL surface. | |
| + | |
| +use std::sync::Arc; | |
| + | |
| +use arrow::array::{Int32Array, StringArray}; | |
| +use arrow::datatypes::{DataType, Field, Schema}; | |
| +use arrow::record_batch::RecordBatch; | |
| +use datafusion::assert_batches_eq; | |
| +use datafusion::error::Result; | |
| +use datafusion::prelude::*; | |
| +use datafusion::logical_expr::lit_with_metadata; | |
| + | |
| +/// The requirement makes literal expressions carry an optional metadata slot; | |
| +/// the public `Expr::Literal` variant therefore has the (value, metadata) | |
| +/// shape. Constructing it with an empty slot pins that public shape — and | |
| +/// makes every test in this binary compile-flip at pre-state, exactly like | |
| +/// the original suite's updated test files. | |
| +fn plain_literal_expr(v: i64) -> Expr { | |
| + Expr::Literal(datafusion::scalar::ScalarValue::Int64(Some(v)), None) | |
| +} | |
| + | |
| +async fn ctx_with_table() -> Result<SessionContext> { | |
| + let ctx = SessionContext::new(); | |
| + let schema = Arc::new(Schema::new(vec![ | |
| + Field::new("k", DataType::Int32, false), | |
| + Field::new("v", DataType::Int32, false), | |
| + Field::new("s", DataType::Utf8, false), | |
| + ])); | |
| + let batch = RecordBatch::try_new( | |
| + schema.clone(), | |
| + vec![ | |
| + Arc::new(Int32Array::from(vec![1, 1, 2])), | |
| + Arc::new(Int32Array::from(vec![10, 20, 30])), | |
| + Arc::new(StringArray::from(vec!["prefix_a", "prefix_b", "other"])), | |
| + ], | |
| + )?; | |
| + ctx.register_batch("t1", batch)?; | |
| + let schema2 = Arc::new(Schema::new(vec![ | |
| + Field::new("k", DataType::Int32, false), | |
| + Field::new("y", DataType::Int32, false), | |
| + ])); | |
| + let batch2 = RecordBatch::try_new( | |
| + schema2.clone(), | |
| + vec![ | |
| + Arc::new(Int32Array::from(vec![1, 2])), | |
| + Arc::new(Int32Array::from(vec![100, 200])), | |
| + ], | |
| + )?; | |
| + ctx.register_batch("t2", batch2)?; | |
| + Ok(ctx) | |
| +} | |
| + | |
| +async fn sql_rows(ctx: &SessionContext, q: &str) -> Result<Vec<RecordBatch>> { | |
| + // Literal-shape guard (see plain_literal_expr): lit(v) must produce the | |
| + // same expression as the public two-slot literal with an empty slot. | |
| + assert_eq!(plain_literal_expr(7), lit(7i64)); | |
| + ctx.sql(q).await?.collect().await | |
| +} | |
| + | |
| +#[tokio::test] | |
| +async fn aug_string_function_literal_folding() -> Result<()> { | |
| + let ctx = ctx_with_table().await?; | |
| + let batches = sql_rows( | |
| + &ctx, | |
| + "SELECT concat('a', '', 'b') AS c1, \ | |
| + concat_ws(',', 'x', NULL, 'y') AS c2, \ | |
| + concat('p:', s) AS c3, \ | |
| + starts_with(s, 'prefix_') AS c4 \ | |
| + FROM t1 ORDER BY v LIMIT 1", | |
| + ) | |
| + .await?; | |
| + assert_batches_eq!( | |
| + [ | |
| + "+----+-----+------------+------+", | |
| + "| c1 | c2 | c3 | c4 |", | |
| + "+----+-----+------------+------+", | |
| + "| ab | x,y | p:prefix_a | true |", | |
| + "+----+-----+------------+------+", | |
| + ], | |
| + &batches | |
| + ); | |
| + Ok(()) | |
| +} | |
| + | |
| +#[tokio::test] | |
| +async fn aug_math_datetime_and_cast_folding() -> Result<()> { | |
| + let ctx = ctx_with_table().await?; | |
| + let batches = sql_rows( | |
| + &ctx, | |
| + "SELECT power(2, 10) AS p, \ | |
| + log(2, 8) AS l, \ | |
| + arrow_cast('41', 'Int32') + 1 AS ac, \ | |
| + substring('hello world', 7, 5) AS sub, \ | |
| + current_date() = current_date() AS cd, \ | |
| + current_time() = current_time() AS ct", | |
| + ) | |
| + .await?; | |
| + assert_batches_eq!( | |
| + [ | |
| + "+------+-----+----+-------+------+------+", | |
| + "| p | l | ac | sub | cd | ct |", | |
| + "+------+-----+----+-------+------+------+", | |
| + "| 1024 | 3.0 | 42 | world | true | true |", | |
| + "+------+-----+----+-------+------+------+", | |
| + ], | |
| + &batches | |
| + ); | |
| + Ok(()) | |
| +} | |
| + | |
| +#[tokio::test] | |
| +async fn aug_scalar_subqueries_decorrelate() -> Result<()> { | |
| + let ctx = ctx_with_table().await?; | |
| + // Correlated scalar subquery in WHERE (decorrelated to a join). | |
| + let correlated = sql_rows( | |
| + &ctx, | |
| + "SELECT k, v FROM t1 \ | |
| + WHERE v < (SELECT max(y) FROM t2 WHERE t2.k = t1.k) \ | |
| + ORDER BY v", | |
| + ) | |
| + .await?; | |
| + assert_batches_eq!( | |
| + [ | |
| + "+---+----+", | |
| + "| k | v |", | |
| + "+---+----+", | |
| + "| 1 | 10 |", | |
| + "| 1 | 20 |", | |
| + "| 2 | 30 |", | |
| + "+---+----+", | |
| + ], | |
| + &correlated | |
| + ); | |
| + // Uncorrelated scalar subquery in the projection. | |
| + let uncorrelated = sql_rows( | |
| + &ctx, | |
| + "SELECT v, (SELECT max(y) FROM t2) AS gmax FROM t1 ORDER BY v LIMIT 1", | |
| + ) | |
| + .await?; | |
| + assert_batches_eq!( | |
| + [ | |
| + "+----+------+", | |
| + "| v | gmax |", | |
| + "+----+------+", | |
| + "| 10 | 200 |", | |
| + "+----+------+", | |
| + ], | |
| + &uncorrelated | |
| + ); | |
| + Ok(()) | |
| +} | |
| + | |
| +#[tokio::test] | |
| +async fn aug_grouping_sets_and_grouping_function() -> Result<()> { | |
| + let ctx = ctx_with_table().await?; | |
| + let batches = sql_rows( | |
| + &ctx, | |
| + "SELECT k, grouping(k) AS g, count(*) AS c \ | |
| + FROM t1 GROUP BY GROUPING SETS ((k), ()) \ | |
| + ORDER BY g, k NULLS LAST", | |
| + ) | |
| + .await?; | |
| + assert_batches_eq!( | |
| + [ | |
| + "+---+---+---+", | |
| + "| k | g | c |", | |
| + "+---+---+---+", | |
| + "| 1 | 0 | 2 |", | |
| + "| 2 | 0 | 1 |", | |
| + "| | 1 | 3 |", | |
| + "+---+---+---+", | |
| + ], | |
| + &batches | |
| + ); | |
| + Ok(()) | |
| +} | |
| + | |
| +#[tokio::test] | |
| +async fn aug_plan_eliminations_with_constant_predicates() -> Result<()> { | |
| + let ctx = ctx_with_table().await?; | |
| + // eliminate_filter (WHERE true / WHERE false), eliminate_group_by_constant, | |
| + // optimize_projections over a constant-rich projection. | |
| + let all = sql_rows(&ctx, "SELECT v FROM t1 WHERE true ORDER BY v").await?; | |
| + assert_eq!(all[0].num_rows(), 3); | |
| + let none = sql_rows(&ctx, "SELECT v FROM t1 WHERE 1 = 0").await?; | |
| + assert!(none.is_empty() || none.iter().all(|b| b.num_rows() == 0)); | |
| + let grouped = sql_rows( | |
| + &ctx, | |
| + "SELECT 'const' AS tag, k, sum(v) AS sv FROM t1 GROUP BY 'const', k ORDER BY k", | |
| + ) | |
| + .await?; | |
| + assert_batches_eq!( | |
| + [ | |
| + "+-------+---+----+", | |
| + "| tag | k | sv |", | |
| + "+-------+---+----+", | |
| + "| const | 1 | 30 |", | |
| + "| const | 2 | 30 |", | |
| + "+-------+---+----+", | |
| + ], | |
| + &grouped | |
| + ); | |
| + let pruned = sql_rows( | |
| + &ctx, | |
| + "SELECT a + 1 AS b FROM (SELECT v AS a, k AS unused, 99 AS dead FROM t1) ORDER BY b LIMIT 1", | |
| + ) | |
| + .await?; | |
| + assert_batches_eq!( | |
| + ["+----+", "| b |", "+----+", "| 11 |", "+----+",], | |
| + &pruned | |
| + ); | |
| + Ok(()) | |
| +} | |
| + | |
| +#[tokio::test] | |
| +async fn aug_boolean_inlist_between_and_case_simplification() -> Result<()> { | |
| + let ctx = ctx_with_table().await?; | |
| + let batches = sql_rows( | |
| + &ctx, | |
| + "SELECT v FROM t1 \ | |
| + WHERE v IN (10, 20, 30, 10) \ | |
| + AND v BETWEEN 0 AND 100 \ | |
| + AND (true OR k = 5) \ | |
| + AND CASE WHEN 1 = 1 THEN true ELSE false END \ | |
| + AND s ~ '^prefix_a$' IS NOT NULL \ | |
| + AND coalesce(NULL, true) \ | |
| + ORDER BY v", | |
| + ) | |
| + .await?; | |
| + assert_batches_eq!( | |
| + [ | |
| + "+----+", "| v |", "+----+", "| 10 |", "| 20 |", "| 30 |", "+----+", | |
| + ], | |
| + &batches | |
| + ); | |
| + // guarantees: a second predicate already implied by the first. | |
| + let g = sql_rows(&ctx, "SELECT v FROM t1 WHERE v > 5 AND v > 5 AND v >= 10 ORDER BY v LIMIT 1").await?; | |
| + assert_eq!(g[0].num_rows(), 1); | |
| + Ok(()) | |
| +} | |
| + | |
| +#[tokio::test] | |
| +async fn aug_typed_literals_through_dataframe_api() -> Result<()> { | |
| + let ctx = ctx_with_table().await?; | |
| + let df = ctx.table("t1").await?; | |
| + let projected = df | |
| + .select(vec![ | |
| + lit(1i8).alias("c_i8"), | |
| + lit(2i16).alias("c_i16"), | |
| + lit(3i32).alias("c_i32"), | |
| + lit(4i64).alias("c_i64"), | |
| + lit(5u8).alias("c_u8"), | |
| + lit(6u16).alias("c_u16"), | |
| + lit(7u32).alias("c_u32"), | |
| + lit(8u64).alias("c_u64"), | |
| + lit(1.5f32).alias("c_f32"), | |
| + lit(2.5f64).alias("c_f64"), | |
| + lit("str").alias("c_str"), | |
| + lit(String::from("string")).alias("c_string"), | |
| + lit(true).alias("c_bool"), | |
| + lit(Vec::<u8>::from([1u8, 2u8])).alias("c_bin"), | |
| + ])? | |
| + .limit(0, Some(1))?; | |
| + // expr_schema: literal types and nullability flow into the schema. | |
| + let schema = projected.schema().clone(); | |
| + assert_eq!(schema.field_with_unqualified_name("c_i8")?.data_type(), &DataType::Int8); | |
| + assert_eq!(schema.field_with_unqualified_name("c_u64")?.data_type(), &DataType::UInt64); | |
| + assert_eq!(schema.field_with_unqualified_name("c_str")?.data_type(), &DataType::Utf8); | |
| + let batches = projected.collect().await?; | |
| + assert_eq!(batches[0].num_rows(), 1); | |
| + assert_eq!(batches[0].num_columns(), 14); | |
| + Ok(()) | |
| +} | |
| + | |
| +#[tokio::test] | |
| +async fn aug_count_star_table_functions_and_struct_access() -> Result<()> { | |
| + let ctx = ctx_with_table().await?; | |
| + // DataFrame::count goes through count(Literal(COUNT_STAR_EXPANSION)). | |
| + let n = ctx.table("t1").await?.count().await?; | |
| + assert_eq!(n, 3); | |
| + let gs = sql_rows(&ctx, "SELECT * FROM generate_series(1, 3)").await?; | |
| + let total: usize = gs.iter().map(|b| b.num_rows()).sum(); | |
| + assert_eq!(total, 3); | |
| + let batches = sql_rows( | |
| + &ctx, | |
| + "SELECT struct(1 AS a, 'x' AS b)['a'] AS field, \ | |
| + array_has([1, 2, 3], 2) AS has2, \ | |
| + count(1) AS c1 \ | |
| + FROM t1", | |
| + ) | |
| + .await?; | |
| + assert_batches_eq!( | |
| + [ | |
| + "+-------+------+----+", | |
| + "| field | has2 | c1 |", | |
| + "+-------+------+----+", | |
| + "| 1 | true | 3 |", | |
| + "+-------+------+----+", | |
| + ], | |
| + &batches | |
| + ); | |
| + Ok(()) | |
| +} | |
| + | |
| +#[tokio::test] | |
| +async fn aug_window_functions_with_literal_arguments() -> Result<()> { | |
| + let ctx = ctx_with_table().await?; | |
| + let batches = sql_rows( | |
| + &ctx, | |
| + "SELECT v, row_number() OVER (ORDER BY v) AS rn, \ | |
| + nth_value(v, 2) OVER (ORDER BY v ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS nth \ | |
| + FROM t1 ORDER BY v", | |
| + ) | |
| + .await?; | |
| + assert_batches_eq!( | |
| + [ | |
| + "+----+----+-----+", | |
| + "| v | rn | nth |", | |
| + "+----+----+-----+", | |
| + "| 10 | 1 | 20 |", | |
| + "| 20 | 2 | 20 |", | |
| + "| 30 | 3 | 20 |", | |
| + "+----+----+-----+", | |
| + ], | |
| + &batches | |
| + ); | |
| + Ok(()) | |
| +} | |
| + | |
| +#[tokio::test] | |
| +async fn aug_decimal_null_and_negative_literals_parse() -> Result<()> { | |
| + // parse_float_as_decimal drives the SQL decimal literal construction paths. | |
| + let config = SessionConfig::new().set_str("datafusion.sql_parser.parse_float_as_decimal", "true"); | |
| + let ctx = SessionContext::new_with_config(config); | |
| + let batches = sql_rows( | |
| + &ctx, | |
| + "SELECT 12.345 AS dec_small, \ | |
| + CAST(NULL AS INT) AS null_lit, \ | |
| + -42 AS neg, \ | |
| + 12345678901234567890123456789012345678.5 AS dec_big", | |
| + ) | |
| + .await?; | |
| + assert_eq!(batches[0].num_rows(), 1); | |
| + let schema = batches[0].schema(); | |
| + assert!(matches!(schema.field(0).data_type(), DataType::Decimal128(_, _))); | |
| + assert!(matches!(schema.field(3).data_type(), DataType::Decimal256(_, _))); | |
| + Ok(()) | |
| +} | |
| + | |
| +#[tokio::test] | |
| +async fn aug_unparser_roundtrips_literal_plans() -> Result<()> { | |
| + use datafusion::sql::unparser::plan_to_sql; | |
| + let ctx = ctx_with_table().await?; | |
| + let df = ctx | |
| + .sql( | |
| + "SELECT k, sum(v) AS sv, row_number() OVER (ORDER BY k) AS rn \ | |
| + FROM t1 WHERE v > 5 AND s LIKE 'prefix%' GROUP BY k, v, s ORDER BY k LIMIT 2", | |
| + ) | |
| + .await?; | |
| + let plan = df.logical_plan().clone(); | |
| + let sql = plan_to_sql(&plan)?.to_string(); | |
| + assert!(sql.contains("5"), "unparsed SQL keeps the literal: {sql}"); | |
| + assert!(sql.to_lowercase().contains("limit"), "{sql}"); | |
| + // Round-trip: the unparsed SQL must execute to the same shape. | |
| + let again = ctx.sql(&sql).await?.collect().await?; | |
| + let rows: usize = again.iter().map(|b| b.num_rows()).sum(); | |
| + assert_eq!(rows, 2); | |
| + Ok(()) | |
| +} | |
| + | |
| +#[tokio::test] | |
| +async fn aug_literal_metadata_flows_to_schema_and_execution() -> Result<()> { | |
| + use std::collections::HashMap; | |
| + use datafusion::scalar::ScalarValue; | |
| + | |
| + let ctx = ctx_with_table().await?; | |
| + let lit_md = lit_with_metadata( | |
| + ScalarValue::Int32(Some(7)), | |
| + HashMap::from([("purpose".to_string(), "lolbench".to_string())]), | |
| + ); | |
| + | |
| + // The literal's metadata must surface on the logical output field... | |
| + let df = ctx.table("t1").await?.select(vec![lit_md.clone().alias("c")])?; | |
| + let field = df.schema().field_with_unqualified_name("c")?; | |
| + assert_eq!(field.metadata().get("purpose").map(String::as_str), Some("lolbench")); | |
| + | |
| + // ...and survive optimization + physical planning into execution output. | |
| + let batches = df.collect().await?; | |
| + assert_eq!( | |
| + batches[0].schema().field(0).metadata().get("purpose").map(String::as_str), | |
| + Some("lolbench") | |
| + ); | |
| + | |
| + // An alias carrying its own metadata merges it with the literal's — on the | |
| + // logical schema AND through the physical planner into execution output. | |
| + let Expr::Alias(mut alias) = lit_md.alias("c2") else { unreachable!() }; | |
| + alias.metadata = Some(HashMap::from([("origin".to_string(), "alias".to_string())])); | |
| + let df2 = ctx.table("t1").await?.select(vec![Expr::Alias(alias)])?; | |
| + let field2 = df2.schema().field_with_unqualified_name("c2")?; | |
| + assert_eq!(field2.metadata().get("origin").map(String::as_str), Some("alias")); | |
| + assert_eq!(field2.metadata().get("purpose").map(String::as_str), Some("lolbench")); | |
| + let batches2 = df2.collect().await?; | |
| + let exec_field2 = batches2[0].schema(); | |
| + let exec_field2 = exec_field2.field(0); | |
| + assert_eq!(exec_field2.metadata().get("origin").map(String::as_str), Some("alias")); | |
| + assert_eq!(exec_field2.metadata().get("purpose").map(String::as_str), Some("lolbench")); | |
| + Ok(()) | |
| +} | |
| + | |
| +#[tokio::test] | |
| +async fn aug_literal_metadata_reaches_scalar_udf_return_field() -> Result<()> { | |
| + use std::any::Any; | |
| + use std::collections::HashMap; | |
| + use arrow::datatypes::FieldRef; | |
| + use datafusion::logical_expr::{ | |
| + ColumnarValue, ReturnFieldArgs, ScalarFunctionArgs, ScalarUDF, ScalarUDFImpl, | |
| + Signature, Volatility, | |
| + }; | |
| + use datafusion::scalar::ScalarValue; | |
| + | |
| + // A probe function that republishes its first argument's field metadata on | |
| + // its return field — the requirement's "when return_field_from_args gets | |
| + // called, the metadata would be available" contract. | |
| + #[derive(Debug)] | |
| + struct MetadataProbe { | |
| + signature: Signature, | |
| + } | |
| + impl ScalarUDFImpl for MetadataProbe { | |
| + fn as_any(&self) -> &dyn Any { | |
| + self | |
| + } | |
| + fn name(&self) -> &str { | |
| + "aug_metadata_probe" | |
| + } | |
| + fn signature(&self) -> &Signature { | |
| + &self.signature | |
| + } | |
| + fn return_type(&self, _args: &[DataType]) -> Result<DataType> { | |
| + Ok(DataType::Int32) | |
| + } | |
| + fn return_field_from_args(&self, args: ReturnFieldArgs) -> Result<FieldRef> { | |
| + let metadata = args.arg_fields[0].metadata().clone(); | |
| + Ok(Arc::new( | |
| + Field::new(self.name(), DataType::Int32, true).with_metadata(metadata), | |
| + )) | |
| + } | |
| + fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> { | |
| + Ok(args.args[0].clone()) | |
| + } | |
| + } | |
| + | |
| + let ctx = ctx_with_table().await?; | |
| + let probe = ScalarUDF::from(MetadataProbe { | |
| + signature: Signature::exact(vec![DataType::Int32], Volatility::Immutable), | |
| + }); | |
| + let arg = lit_with_metadata( | |
| + ScalarValue::Int32(Some(7)), | |
| + HashMap::from([("purpose".to_string(), "lolbench".to_string())]), | |
| + ); | |
| + let expr = probe.call(vec![arg]).alias("p"); | |
| + | |
| + let df = ctx.table("t1").await?.select(vec![expr])?; | |
| + let field = df.schema().field_with_unqualified_name("p")?; | |
| + assert_eq!(field.metadata().get("purpose").map(String::as_str), Some("lolbench")); | |
| + // The physical literal's field metadata must reach the physical scalar | |
| + // function's return field and survive into the executed output schema. | |
| + let batches = df.collect().await?; | |
| + assert_eq!(batches[0].num_rows(), 3); | |
| + let exec_schema = batches[0].schema(); | |
| + assert_eq!( | |
| + exec_schema.field(0).metadata().get("purpose").map(String::as_str), | |
| + Some("lolbench") | |
| + ); | |
| + Ok(()) | |
| +} | |
| + | |
| +#[tokio::test] | |
| +async fn aug_metadata_literals_drive_rewrites_and_functions() -> Result<()> { | |
| + use std::collections::HashMap; | |
| + use datafusion::functions::expr_fn::{concat, concat_ws, log, power, starts_with}; | |
| + use datafusion::functions_aggregate::expr_fn::count; | |
| + use datafusion::functions_nested::expr_fn::{array_has, make_array}; | |
| + use datafusion::scalar::ScalarValue; | |
| + | |
| + fn md_lit(sv: ScalarValue) -> Expr { | |
| + lit_with_metadata( | |
| + sv, | |
| + HashMap::from([("purpose".to_string(), "lolbench".to_string())]), | |
| + ) | |
| + } | |
| + | |
| + let ctx = ctx_with_table().await?; | |
| + let t = ctx.table("t1").await?; | |
| + | |
| + // Metadata-bearing literals flowing through the simplifier's function | |
| + // rewrites and scalar-evaluation arms: every projected expression must | |
| + // still evaluate to its plain-literal result. | |
| + let df = t.clone().select(vec![ | |
| + concat(vec![md_lit(ScalarValue::from("p:")), col("s")]).alias("e1"), | |
| + concat_ws(md_lit(ScalarValue::from(",")), vec![md_lit(ScalarValue::from("x")), col("s")]).alias("e2"), | |
| + starts_with(col("s"), md_lit(ScalarValue::from("prefix_"))).alias("e3"), | |
| + power(md_lit(ScalarValue::Float64(Some(2.0))), cast(col("v"), DataType::Float64)).alias("e4"), | |
| + log(md_lit(ScalarValue::Float64(Some(2.0))), cast(col("v"), DataType::Float64)).alias("e5"), | |
| + array_has(make_array(vec![md_lit(ScalarValue::Int32(Some(1))), md_lit(ScalarValue::Int32(Some(2)))]), col("k")).alias("e6"), | |
| + md_lit(ScalarValue::Int32(Some(5))).between(md_lit(ScalarValue::Int32(Some(1))), md_lit(ScalarValue::Int32(Some(9)))).alias("e7"), | |
| + col("v").in_list(vec![md_lit(ScalarValue::Int32(Some(10))), md_lit(ScalarValue::Int32(Some(20)))], false).alias("e8"), | |
| + (md_lit(ScalarValue::Int32(Some(2))) + md_lit(ScalarValue::Int32(Some(3)))).alias("e9"), | |
| + md_lit(ScalarValue::from("foo")).like(md_lit(ScalarValue::from("f%"))).alias("e10"), | |
| + ])?; | |
| + let batches = df.collect().await?; | |
| + assert_eq!(batches[0].num_rows(), 3); | |
| + | |
| + // A filter mixing metadata literals with guaranteed-true predicates keeps | |
| + // its plain semantics through the boolean simplifier. | |
| + let filtered = t | |
| + .clone() | |
| + .filter( | |
| + col("v") | |
| + .gt(md_lit(ScalarValue::Int32(Some(5)))) | |
| + .and(md_lit(ScalarValue::Boolean(Some(true)))) | |
| + .and(col("v").gt(md_lit(ScalarValue::Int32(Some(5))))), | |
| + )? | |
| + .select(vec![col("v")])?; | |
| + let fb = filtered.collect().await?; | |
| + let rows: usize = fb.iter().map(|b| b.num_rows()).sum(); | |
| + assert_eq!(rows, 3); | |
| + | |
| + // Aggregation with a metadata-literal count argument. | |
| + let agg = t | |
| + .clone() | |
| + .aggregate(vec![col("k")], vec![count(md_lit(ScalarValue::Int32(Some(1)))).alias("c")])? | |
| + .sort(vec![col("k").sort(true, true)])?; | |
| + let ab = agg.collect().await?; | |
| + let total: i64 = ab | |
| + .iter() | |
| + .flat_map(|b| { | |
| + let arr = b.column(1).as_any().downcast_ref::<arrow::array::Int64Array>().unwrap(); | |
| + (0..arr.len()).map(|i| arr.value(i)).collect::<Vec<_>>() | |
| + }) | |
| + .sum(); | |
| + assert_eq!(total, 3); | |
| + Ok(()) | |
| +} | |
| + | |
| +#[tokio::test] | |
| +async fn aug_typed_identity_arms_and_const_lists_simplify() -> Result<()> { | |
| + let ctx = ctx_with_table().await?; | |
| + // Multiply/add/power identity arms are matched per literal type; a literal | |
| + // on the left of a comparison takes the operand-swap arm; fully-literal | |
| + // array constructions const-evaluate to (Large)List scalars. | |
| + let batches = sql_rows( | |
| + &ctx, | |
| + "SELECT v * CAST(0 AS BIGINT UNSIGNED) AS z_u64, \ | |
| + CAST(v AS FLOAT) + CAST(0.0 AS FLOAT) AS z_f32, \ | |
| + CAST(v AS DOUBLE) * CAST(1.0 AS DOUBLE) AS one_f64, \ | |
| + v * CAST(1.0 AS DECIMAL(5,2)) AS one_dec, \ | |
| + v + CAST(0 AS DECIMAL(5,2)) AS z_dec, \ | |
| + power(CAST(v AS DOUBLE), 0) AS pow_zero, \ | |
| + power(CAST(v AS DOUBLE), 1) AS pow_one, \ | |
| + log(2.0, CAST(1 AS DOUBLE)) AS log_one, \ | |
| + [1, 2, 3] AS const_list, \ | |
| + arrow_cast([1, 2], 'LargeList(Int64)') AS const_large, \ | |
| + 5 < v AS lit_left, \ | |
| + (v > 5) IS NOT UNKNOWN AS not_unknown \ | |
| + FROM t1 ORDER BY v LIMIT 1", | |
| + ) | |
| + .await?; | |
| + assert_eq!(batches[0].num_rows(), 1); | |
| + let mixed = sql_rows( | |
| + &ctx, | |
| + "SELECT concat(arrow_cast('a', 'LargeUtf8'), s, arrow_cast('', 'Utf8View'), arrow_cast(NULL, 'LargeUtf8')) AS c1, \ | |
| + concat_ws(',', arrow_cast('x', 'Utf8View'), arrow_cast(NULL, 'Utf8'), arrow_cast('y', 'LargeUtf8'), s) AS c2 \ | |
| + FROM t1 ORDER BY v LIMIT 1", | |
| + ) | |
| + .await?; | |
| + assert_eq!(mixed[0].num_rows(), 1); | |
| + // Layered redundant range/IN predicates drive the guarantee rewriter. | |
| + let g = sql_rows( | |
| + &ctx, | |
| + "SELECT v FROM t1 WHERE v BETWEEN 1 AND 100 AND v BETWEEN 1 AND 100 \ | |
| + AND v IN (10, 20, 30) AND v IN (10, 20, 30) AND s ~ '^prefix_a$' IS NOT NULL ORDER BY v", | |
| + ) | |
| + .await?; | |
| + let rows: usize = g.iter().map(|b| b.num_rows()).sum(); | |
| + assert_eq!(rows, 3); | |
| + Ok(()) | |
| +} | |
| + | |
| +#[tokio::test] | |
| +async fn aug_planner_sql_and_unparser_literal_paths() -> Result<()> { | |
| + use datafusion::sql::unparser::plan_to_sql; | |
| + let ctx = ctx_with_table().await?; | |
| + | |
| + // count(*) expansions: aggregate and windowed; correlated COUNT scalar | |
| + // subquery takes the null-to-zero decorrelation arm; empty-input scalar | |
| + // subquery takes the NULL else arm; JOIN ON false is eliminated. | |
| + let batches = sql_rows( | |
| + &ctx, | |
| + "SELECT k, count(*) AS c, count(*) OVER () AS cw, \ | |
| + (SELECT count(*) FROM t2 WHERE t2.k = t1.k AND t2.y > 1000) AS zero_cnt, \ | |
| + (SELECT max(y) FROM t2 WHERE false) AS none_max \ | |
| + FROM t1 GROUP BY k, v ORDER BY k, v", | |
| + ) | |
| + .await?; | |
| + assert_eq!(batches.iter().map(|b| b.num_rows()).sum::<usize>(), 3); | |
| + let joined = sql_rows(&ctx, "SELECT t1.v FROM t1 JOIN t2 ON false").await?; | |
| + assert!(joined.is_empty() || joined.iter().all(|b| b.num_rows() == 0)); | |
| + | |
| + // grouping() over a plain GROUP BY takes the zero-literal arm. | |
| + let grouped = sql_rows(&ctx, "SELECT k, grouping(k) AS g FROM t1 GROUP BY k ORDER BY k").await?; | |
| + assert_eq!(grouped.iter().map(|b| b.num_rows()).sum::<usize>(), 2); | |
| + | |
| + // Placeholder parameters replace into plain literals; literal-typed NULL | |
| + // VALUES rows are back-filled; LIMIT folds a constant expression; | |
| + // FROM-only substring; intervals; now(); coalesce; lag/lead offsets. | |
| + let df = ctx | |
| + .sql("SELECT $1 + v AS pv FROM t1 ORDER BY v LIMIT 1") | |
| + .await? | |
| + .with_param_values(vec![datafusion::scalar::ScalarValue::Int32(Some(100))])?; | |
| + assert_eq!(df.collect().await?[0].num_rows(), 1); | |
| + let misc = sql_rows( | |
| + &ctx, | |
| + "SELECT a FROM (VALUES (NULL), (7)) AS vt(a) ORDER BY a NULLS FIRST LIMIT 1 + 1", | |
| + ) | |
| + .await?; | |
| + assert_eq!(misc.iter().map(|b| b.num_rows()).sum::<usize>(), 2); | |
| + let exprs = sql_rows( | |
| + &ctx, | |
| + "SELECT substring('hello' FROM 2) AS sub, \ | |
| + INTERVAL '1' YEAR AS iy, INTERVAL '2' DAY AS idt, INTERVAL '1 month 1 day 1 second' AS imdn, \ | |
| + now() <= now() AS nw, coalesce(NULL, 5) AS co, \ | |
| + lag(v, 2) OVER (ORDER BY v) AS lg, lead(v, 1) OVER (ORDER BY v) AS ld, \ | |
| + struct(1 AS a, 'x' AS b)['a'] AS brfield \ | |
| + FROM t1 ORDER BY v", | |
| + ) | |
| + .await?; | |
| + assert_eq!(exprs.iter().map(|b| b.num_rows()).sum::<usize>(), 3); | |
| + let gs_null = sql_rows(&ctx, "SELECT * FROM generate_series(1, NULL)").await?; | |
| + assert_eq!(gs_null.iter().map(|b| b.num_rows()).sum::<usize>(), 0); | |
| + | |
| + // Unparse plans exercising date_part/date_trunc, struct-field access and | |
| + // window functions; the unparsed SQL must execute again. | |
| + let df2 = ctx | |
| + .sql( | |
| + "SELECT date_part('year', now()) AS yr, date_trunc('day', now()) AS dy, \ | |
| + row_number() OVER (ORDER BY v) AS rn \ | |
| + FROM t1", | |
| + ) | |
| + .await?; | |
| + let plan = df2.logical_plan().clone(); | |
| + let sql = plan_to_sql(&plan)?.to_string(); | |
| + let again = ctx.sql(&sql).await?.collect().await?; | |
| + assert_eq!(again.iter().map(|b| b.num_rows()).sum::<usize>(), 3); | |
| + Ok(()) | |
| +} | |
| + | |
| +#[tokio::test] | |
| +async fn aug_partitioned_listing_table_pruning() -> Result<()> { | |
| + use std::fs; | |
| + let tmp = std::env::temp_dir().join("lolbench_aug_part"); | |
| + let _ = fs::remove_dir_all(&tmp); | |
| + fs::create_dir_all(tmp.join("part=1"))?; | |
| + fs::create_dir_all(tmp.join("part=2"))?; | |
| + fs::write(tmp.join("part=1/a.csv"), "x\n10\n20\n")?; | |
| + fs::write(tmp.join("part=2/a.csv"), "x\n30\n")?; | |
| + let ctx = SessionContext::new(); | |
| + ctx.sql(&format!( | |
| + "CREATE EXTERNAL TABLE pt (x INT) STORED AS CSV PARTITIONED BY (part INT) \ | |
| + LOCATION '{}' OPTIONS ('format.has_header' 'true')", | |
| + tmp.display() | |
| + )) | |
| + .await? | |
| + .collect() | |
| + .await?; | |
| + let batches = ctx | |
| + .sql("SELECT x FROM pt WHERE part = 1 ORDER BY x") | |
| + .await? | |
| + .collect() | |
| + .await?; | |
| + assert_batches_eq!( | |
| + ["+----+", "| x |", "+----+", "| 10 |", "| 20 |", "+----+",], | |
| + &batches | |
| + ); | |
| + // Literal-on-the-left partition predicate takes the swapped match arm. | |
| + let swapped = ctx | |
| + .sql("SELECT x FROM pt WHERE 2 = part ORDER BY x") | |
| + .await? | |
| + .collect() | |
| + .await?; | |
| + assert_batches_eq!( | |
| + ["+----+", "| x |", "+----+", "| 30 |", "+----+",], | |
| + &swapped | |
| + ); | |
| + Ok(()) | |
| +} | |
| diff --git a/datafusion/core/tests/lolbench_aug_p2p.rs b/datafusion/core/tests/lolbench_aug_p2p.rs | |
| new file mode 100644 | |
| index 0000000..4b6813d | |
| --- /dev/null | |
| +++ b/datafusion/core/tests/lolbench_aug_p2p.rs | |
| +// 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. | |
| + | |
| +//! Augmented suite (lolbench-aug, P2P). The requirement adds an optional | |
| +//! metadata slot to literals; everything that does not involve metadata must | |
| +//! behave exactly as before. These tests pin adjacent unchanged behaviors | |
| +//! (string functions and arithmetic untouched by the change) and deliberately | |
| +//! avoid the new literal shape so they compile and pass at pre-state. | |
| + | |
| +use datafusion::assert_batches_eq; | |
| +use datafusion::error::Result; | |
| +use datafusion::prelude::*; | |
| + | |
| +#[tokio::test] | |
| +async fn aug_p2p_unmodified_string_functions_keep_behavior() -> Result<()> { | |
| + let ctx = SessionContext::new(); | |
| + let batches = ctx | |
| + .sql("SELECT upper('ab') AS u, lower('CD') AS l, trim(' x ') AS t, length('abcd') AS n") | |
| + .await? | |
| + .collect() | |
| + .await?; | |
| + assert_batches_eq!( | |
| + [ | |
| + "+----+----+---+---+", | |
| + "| u | l | t | n |", | |
| + "+----+----+---+---+", | |
| + "| AB | cd | x | 4 |", | |
| + "+----+----+---+---+", | |
| + ], | |
| + &batches | |
| + ); | |
| + Ok(()) | |
| +} | |
| + | |
| +#[tokio::test] | |
| +async fn aug_p2p_arithmetic_and_ordering_keep_behavior() -> Result<()> { | |
| + let ctx = SessionContext::new(); | |
| + let batches = ctx | |
| + .sql( | |
| + "SELECT a, a * 2 AS d FROM (VALUES (3), (1), (2)) AS v(a) ORDER BY a DESC", | |
| + ) | |
| + .await? | |
| + .collect() | |
| + .await?; | |
| + assert_batches_eq!( | |
| + [ | |
| + "+---+---+", | |
| + "| a | d |", | |
| + "+---+---+", | |
| + "| 3 | 6 |", | |
| + "| 2 | 4 |", | |
| + "| 1 | 2 |", | |
| + "+---+---+", | |
| + ], | |
| + &batches | |
| + ); | |
| + Ok(()) | |
| +} | |
| diff --git a/datafusion/proto/tests/lolbench_aug.rs b/datafusion/proto/tests/lolbench_aug.rs | |
| new file mode 100644 | |
| index 0000000..419d87a | |
| --- /dev/null | |
| +++ b/datafusion/proto/tests/lolbench_aug.rs | |
| +// 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. | |
| + | |
| +//! Augmented suite (lolbench-aug): literal expressions must survive the | |
| +//! protobuf logical-plan round trip unchanged, through the public bytes API. | |
| + | |
| +use datafusion::prelude::*; | |
| +use datafusion_proto::bytes::{logical_plan_from_bytes, logical_plan_to_bytes}; | |
| + | |
| +#[tokio::test] | |
| +async fn aug_literals_roundtrip_through_proto() -> datafusion::error::Result<()> { | |
| + // Literal-shape guard: the public Expr::Literal carries (value, metadata); | |
| + // compile-flips this binary at pre-state like the original suite files. | |
| + assert_eq!( | |
| + Expr::Literal(datafusion::scalar::ScalarValue::Int64(Some(7)), None), | |
| + lit(7i64) | |
| + ); | |
| + let ctx = SessionContext::new(); | |
| + let df = ctx | |
| + .sql("SELECT 1 AS i, 2.5 AS f, 'txt' AS s, true AS b, CAST(NULL AS INT) AS n") | |
| + .await?; | |
| + let plan = df.logical_plan().clone(); | |
| + let bytes = logical_plan_to_bytes(&plan)?; | |
| + let restored = logical_plan_from_bytes(&bytes, &ctx)?; | |
| + assert_eq!(format!("{plan}"), format!("{restored}")); | |
| + Ok(()) | |
| +} | |