Apache DataFusion SQL Query Engine
refactor: replace `OnceLock` with `LazyLock` (round 2) (#13674)
Jonah Gaoce330ec2a9e5
diff --git a/benchmarks/src/bin/external_aggr.rs b/benchmarks/src/bin/external_aggr.rsindex f1d8337585..a2fb75dd19 100644--- a/benchmarks/src/bin/external_aggr.rs+++ b/benchmarks/src/bin/external_aggr.rs@@ -20,7 +20,7 @@use std::collections::HashMap;use std::path::PathBuf;use std::sync::Arc;-use std::sync::OnceLock;+use std::sync::LazyLock;use structopt::StructOpt;use arrow::record_batch::RecordBatch;@@ -91,7 +91,13 @@ struct QueryResult {/// Memory limits to run: 64MiB, 32MiB, 16MiB/// Q2 requires 250MiB for aggregation/// Memory limits to run: 512MiB, 256MiB, 128MiB, 64MiB, 32MiB-static QUERY_MEMORY_LIMITS: OnceLock<HashMap<usize, Vec<u64>>> = OnceLock::new();+static QUERY_MEMORY_LIMITS: LazyLock<HashMap<usize, Vec<u64>>> = LazyLock::new(|| {+ use units::*;+ let mut map = HashMap::new();+ map.insert(1, vec![64 * MB, 32 * MB, 16 * MB]);+ map.insert(2, vec![512 * MB, 256 * MB, 128 * MB, 64 * MB, 32 * MB]);+ map+});impl ExternalAggrConfig {const AGGR_TABLES: [&'static str; 1] = ["lineitem"];@@ -114,16 +120,6 @@ impl ExternalAggrConfig {"#,];- fn init_query_memory_limits() -> &'static HashMap<usize, Vec<u64>> {- use units::*;- QUERY_MEMORY_LIMITS.get_or_init(|| {- let mut map = HashMap::new();- map.insert(1, vec![64 * MB, 32 * MB, 16 * MB]);- map.insert(2, vec![512 * MB, 256 * MB, 128 * MB, 64 * MB, 32 * MB]);- map- })- }-/// If `--query` and `--memory-limit` is not speicified, run all queries/// with pre-configured memory limits/// If only `--query` is specified, run the query with all memory limits@@ -161,8 +157,7 @@ impl ExternalAggrConfig {query_executions.push((query_id, limit));}None => {- let memory_limits_table = Self::init_query_memory_limits();- let memory_limits = memory_limits_table.get(&query_id).unwrap();+ let memory_limits = QUERY_MEMORY_LIMITS.get(&query_id).unwrap();for limit in memory_limits {query_executions.push((query_id, *limit));}diff --git a/datafusion-cli/src/main.rs b/datafusion-cli/src/main.rsindex d5dd2c4b33..52665df375 100644--- a/datafusion-cli/src/main.rs+++ b/datafusion-cli/src/main.rs@@ -19,7 +19,7 @@ use std::collections::HashMap;use std::env;use std::path::Path;use std::process::ExitCode;-use std::sync::{Arc, OnceLock};+use std::sync::{Arc, LazyLock};use datafusion::error::{DataFusionError, Result};use datafusion::execution::context::SessionConfig;@@ -279,9 +279,8 @@ impl ByteUnit {}fn extract_memory_pool_size(size: &str) -> Result<usize, String> {- fn byte_suffixes() -> &'static HashMap<&'static str, ByteUnit> {- static BYTE_SUFFIXES: OnceLock<HashMap<&'static str, ByteUnit>> = OnceLock::new();- BYTE_SUFFIXES.get_or_init(|| {+ static BYTE_SUFFIXES: LazyLock<HashMap<&'static str, ByteUnit>> =+ LazyLock::new(|| {let mut m = HashMap::new();m.insert("b", ByteUnit::Byte);m.insert("k", ByteUnit::KiB);@@ -293,23 +292,20 @@ fn extract_memory_pool_size(size: &str) -> Result<usize, String> {m.insert("t", ByteUnit::TiB);m.insert("tb", ByteUnit::TiB);m- })- }+ });- fn suffix_re() -> &'static regex::Regex {- static SUFFIX_REGEX: OnceLock<regex::Regex> = OnceLock::new();- SUFFIX_REGEX.get_or_init(|| regex::Regex::new(r"^(-?[0-9]+)([a-z]+)?$").unwrap())- }+ static SUFFIX_REGEX: LazyLock<regex::Regex> =+ LazyLock::new(|| regex::Regex::new(r"^(-?[0-9]+)([a-z]+)?$").unwrap());let lower = size.to_lowercase();- if let Some(caps) = suffix_re().captures(&lower) {+ if let Some(caps) = SUFFIX_REGEX.captures(&lower) {let num_str = caps.get(1).unwrap().as_str();let num = num_str.parse::<usize>().map_err(|_| {format!("Invalid numeric value in memory pool size '{}'", size)})?;let suffix = caps.get(2).map(|m| m.as_str()).unwrap_or("b");- let unit = byte_suffixes()+ let unit = &BYTE_SUFFIXES.get(suffix).ok_or_else(|| format!("Invalid memory pool size '{}'", size))?;let memory_pool_size = usize::try_from(unit.multiplier())diff --git a/datafusion/core/src/datasource/physical_plan/parquet/access_plan.rs b/datafusion/core/src/datasource/physical_plan/parquet/access_plan.rsindex ea3030664b..0d77a99699 100644--- a/datafusion/core/src/datasource/physical_plan/parquet/access_plan.rs+++ b/datafusion/core/src/datasource/physical_plan/parquet/access_plan.rs@@ -345,7 +345,7 @@ mod test {use parquet::basic::LogicalType;use parquet::file::metadata::ColumnChunkMetaData;use parquet::schema::types::{SchemaDescPtr, SchemaDescriptor};- use std::sync::{Arc, OnceLock};+ use std::sync::{Arc, LazyLock};#[test]fn test_only_scans() {@@ -358,7 +358,7 @@ mod test {let row_group_indexes = access_plan.row_group_indexes();let row_selection = access_plan- .into_overall_row_selection(row_group_metadata())+ .into_overall_row_selection(&ROW_GROUP_METADATA).unwrap();// scan all row groups, no selection@@ -377,7 +377,7 @@ mod test {let row_group_indexes = access_plan.row_group_indexes();let row_selection = access_plan- .into_overall_row_selection(row_group_metadata())+ .into_overall_row_selection(&ROW_GROUP_METADATA).unwrap();// skip all row groups, no selection@@ -403,7 +403,7 @@ mod test {let row_group_indexes = access_plan.row_group_indexes();let row_selection = access_plan- .into_overall_row_selection(row_group_metadata())+ .into_overall_row_selection(&ROW_GROUP_METADATA).unwrap();assert_eq!(row_group_indexes, vec![0, 1]);@@ -442,7 +442,7 @@ mod test {let row_group_indexes = access_plan.row_group_indexes();let row_selection = access_plan- .into_overall_row_selection(row_group_metadata())+ .into_overall_row_selection(&ROW_GROUP_METADATA).unwrap();assert_eq!(row_group_indexes, vec![1, 2, 3]);@@ -478,7 +478,7 @@ mod test {let row_group_indexes = access_plan.row_group_indexes();let err = access_plan- .into_overall_row_selection(row_group_metadata())+ .into_overall_row_selection(&ROW_GROUP_METADATA).unwrap_err().to_string();assert_eq!(row_group_indexes, vec![0, 1, 2, 3]);@@ -504,39 +504,35 @@ mod test {let row_group_indexes = access_plan.row_group_indexes();let err = access_plan- .into_overall_row_selection(row_group_metadata())+ .into_overall_row_selection(&ROW_GROUP_METADATA).unwrap_err().to_string();assert_eq!(row_group_indexes, vec![0, 1, 2, 3]);assert_contains!(err, "Invalid ParquetAccessPlan Selection. Row group 1 has 20 rows but selection only specifies 22 rows");}- static ROW_GROUP_METADATA: OnceLock<Vec<RowGroupMetaData>> = OnceLock::new();-/// [`RowGroupMetaData`] that returns 4 row groups with 10, 20, 30, 40 rows/// respectively- fn row_group_metadata() -> &'static [RowGroupMetaData] {- ROW_GROUP_METADATA.get_or_init(|| {- let schema_descr = get_test_schema_descr();- let row_counts = [10, 20, 30, 40];-- row_counts- .into_iter()- .map(|num_rows| {- let column = ColumnChunkMetaData::builder(schema_descr.column(0))- .set_num_values(num_rows)- .build()- .unwrap();-- RowGroupMetaData::builder(schema_descr.clone())- .set_num_rows(num_rows)- .set_column_metadata(vec![column])- .build()- .unwrap()- })- .collect()- })- }+ static ROW_GROUP_METADATA: LazyLock<Vec<RowGroupMetaData>> = LazyLock::new(|| {+ let schema_descr = get_test_schema_descr();+ let row_counts = [10, 20, 30, 40];++ row_counts+ .into_iter()+ .map(|num_rows| {+ let column = ColumnChunkMetaData::builder(schema_descr.column(0))+ .set_num_values(num_rows)+ .build()+ .unwrap();++ RowGroupMetaData::builder(schema_descr.clone())+ .set_num_rows(num_rows)+ .set_column_metadata(vec![column])+ .build()+ .unwrap()+ })+ .collect()+ });/// Single column schema with a single column named "a" of type `BYTE_ARRAY`/`String`fn get_test_schema_descr() -> SchemaDescPtr {diff --git a/datafusion/core/tests/expr_api/mod.rs b/datafusion/core/tests/expr_api/mod.rsindex 81a3336100..b9f1632ea6 100644--- a/datafusion/core/tests/expr_api/mod.rs+++ b/datafusion/core/tests/expr_api/mod.rs@@ -28,7 +28,7 @@ use datafusion_functions_aggregate::sum::sum_udaf;use datafusion_functions_nested::expr_ext::{IndexAccessor, SliceAccessor};use sqlparser::ast::NullTreatment;/// Tests of using and evaluating `Expr`s outside the context of a LogicalPlan-use std::sync::{Arc, OnceLock};+use std::sync::{Arc, LazyLock};mod parse_sql_expr;mod simplification;@@ -305,13 +305,11 @@ async fn test_aggregate_ext_null_treatment() {/// Evaluates the specified expr as an aggregate and compares the result to the/// expected result.async fn evaluate_agg_test(expr: Expr, expected_lines: Vec<&str>) {- let batch = test_batch();-let ctx = SessionContext::new();let group_expr = vec![];let agg_expr = vec![expr];let result = ctx- .read_batch(batch)+ .read_batch(TEST_BATCH.clone()).unwrap().aggregate(group_expr, agg_expr).unwrap()@@ -332,13 +330,13 @@ async fn evaluate_agg_test(expr: Expr, expected_lines: Vec<&str>) {/// Converts the `Expr` to a `PhysicalExpr`, evaluates it against the provided/// `RecordBatch` and compares the result to the expected result.fn evaluate_expr_test(expr: Expr, expected_lines: Vec<&str>) {- let batch = test_batch();+ let batch = &TEST_BATCH;let df_schema = DFSchema::try_from(batch.schema()).unwrap();let physical_expr = SessionContext::new().create_physical_expr(expr, &df_schema).unwrap();- let result = physical_expr.evaluate(&batch).unwrap();+ let result = physical_expr.evaluate(batch).unwrap();let array = result.into_array(1).unwrap();let result = pretty_format_columns("expr", &[array]).unwrap().to_string();let actual_lines = result.lines().collect::<Vec<_>>();@@ -350,39 +348,33 @@ fn evaluate_expr_test(expr: Expr, expected_lines: Vec<&str>) {);}-static TEST_BATCH: OnceLock<RecordBatch> = OnceLock::new();--fn test_batch() -> RecordBatch {- TEST_BATCH- .get_or_init(|| {- let string_array: ArrayRef = Arc::new(StringArray::from(vec!["1", "2", "3"]));- let int_array: ArrayRef =- Arc::new(Int64Array::from_iter(vec![Some(10), None, Some(5)]));-- // { a: "2021-02-01" } { a: "2021-02-02" } { a: "2021-02-03" }- let struct_array: ArrayRef = Arc::from(StructArray::from(vec![(- Arc::new(Field::new("a", DataType::Utf8, false)),- Arc::new(StringArray::from(vec![- "2021-02-01",- "2021-02-02",- "2021-02-03",- ])) as _,- )]));-- // ["one"] ["two", "three", "four"] ["five"]- let mut builder = ListBuilder::new(StringBuilder::new());- builder.append_value([Some("one")]);- builder.append_value([Some("two"), Some("three"), Some("four")]);- builder.append_value([Some("five")]);- let list_array: ArrayRef = Arc::new(builder.finish());-- RecordBatch::try_from_iter(vec![- ("id", string_array),- ("i", int_array),- ("props", struct_array),- ("list", list_array),- ])- .unwrap()- })- .clone()-}+static TEST_BATCH: LazyLock<RecordBatch> = LazyLock::new(|| {+ let string_array: ArrayRef = Arc::new(StringArray::from(vec!["1", "2", "3"]));+ let int_array: ArrayRef =+ Arc::new(Int64Array::from_iter(vec![Some(10), None, Some(5)]));++ // { a: "2021-02-01" } { a: "2021-02-02" } { a: "2021-02-03" }+ let struct_array: ArrayRef = Arc::from(StructArray::from(vec![(+ Arc::new(Field::new("a", DataType::Utf8, false)),+ Arc::new(StringArray::from(vec![+ "2021-02-01",+ "2021-02-02",+ "2021-02-03",+ ])) as _,+ )]));++ // ["one"] ["two", "three", "four"] ["five"]+ let mut builder = ListBuilder::new(StringBuilder::new());+ builder.append_value([Some("one")]);+ builder.append_value([Some("two"), Some("three"), Some("four")]);+ builder.append_value([Some("five")]);+ let list_array: ArrayRef = Arc::new(builder.finish());++ RecordBatch::try_from_iter(vec![+ ("id", string_array),+ ("i", int_array),+ ("props", struct_array),+ ("list", list_array),+ ])+ .unwrap()+});diff --git a/datafusion/core/tests/memory_limit/mod.rs b/datafusion/core/tests/memory_limit/mod.rsindex c431cd6303..c7514d1c24 100644--- a/datafusion/core/tests/memory_limit/mod.rs+++ b/datafusion/core/tests/memory_limit/mod.rs@@ -35,7 +35,7 @@ use datafusion_physical_plan::spill::get_record_batch_memory_size;use futures::StreamExt;use std::any::Any;use std::num::NonZeroUsize;-use std::sync::{Arc, OnceLock};+use std::sync::{Arc, LazyLock};use tokio::fs::File;use datafusion::datasource::streaming::StreamingTable;@@ -730,15 +730,14 @@ fn maybe_split_batches(.collect()}-static DICT_BATCHES: OnceLock<Vec<RecordBatch>> = OnceLock::new();-/// Returns 5 sorted string dictionary batches each with 50 rows with/// this schema.////// a: Dictionary<Utf8, Int32>,/// b: Dictionary<Utf8, Int32>,fn dict_batches() -> Vec<RecordBatch> {- DICT_BATCHES.get_or_init(make_dict_batches).clone()+ static DICT_BATCHES: LazyLock<Vec<RecordBatch>> = LazyLock::new(make_dict_batches);+ DICT_BATCHES.clone()}fn make_dict_batches() -> Vec<RecordBatch> {diff --git a/datafusion/expr/src/logical_plan/plan.rs b/datafusion/expr/src/logical_plan/plan.rsindex fe725e7d96..31bf4c5734 100644--- a/datafusion/expr/src/logical_plan/plan.rs+++ b/datafusion/expr/src/logical_plan/plan.rs@@ -21,7 +21,7 @@ use std::cmp::Ordering;use std::collections::{HashMap, HashSet};use std::fmt::{self, Debug, Display, Formatter};use std::hash::{Hash, Hasher};-use std::sync::{Arc, OnceLock};+use std::sync::{Arc, LazyLock};use super::dml::CopyTo;use super::DdlStatement;@@ -3067,12 +3067,12 @@ impl Aggregate {/// Get the output expressions.fn output_expressions(&self) -> Result<Vec<&Expr>> {- static INTERNAL_ID_EXPR: OnceLock<Expr> = OnceLock::new();+ static INTERNAL_ID_EXPR: LazyLock<Expr> = LazyLock::new(|| {+ Expr::Column(Column::from_name(Aggregate::INTERNAL_GROUPING_ID))+ });let mut exprs = grouping_set_to_exprlist(self.group_expr.as_slice())?;if self.is_grouping_set() {- exprs.push(INTERNAL_ID_EXPR.get_or_init(|| {- Expr::Column(Column::from_name(Self::INTERNAL_GROUPING_ID))- }));+ exprs.push(&INTERNAL_ID_EXPR);}exprs.extend(self.aggr_expr.iter());debug_assert!(exprs.len() == self.schema.fields().len());diff --git a/datafusion/expr/src/test/function_stub.rs b/datafusion/expr/src/test/function_stub.rsindex 262aa99e50..d597326be0 100644--- a/datafusion/expr/src/test/function_stub.rs+++ b/datafusion/expr/src/test/function_stub.rs@@ -39,19 +39,14 @@ use crate::{macro_rules! create_func {($UDAF:ty, $AGGREGATE_UDF_FN:ident) => {paste::paste! {- /// Singleton instance of [$UDAF], ensures the UDAF is only created once- /// named STATIC_$(UDAF). For example `STATIC_FirstValue`- #[allow(non_upper_case_globals)]- static [< STATIC_ $UDAF >]: std::sync::OnceLock<std::sync::Arc<crate::AggregateUDF>> =- std::sync::OnceLock::new();-#[doc = concat!("AggregateFunction that returns a [AggregateUDF](crate::AggregateUDF) for [`", stringify!($UDAF), "`]")]pub fn $AGGREGATE_UDF_FN() -> std::sync::Arc<crate::AggregateUDF> {- [< STATIC_ $UDAF >]- .get_or_init(|| {+ // Singleton instance of [$UDAF], ensures the UDAF is only created once+ static INSTANCE: std::sync::LazyLock<std::sync::Arc<crate::AggregateUDF>> =+ std::sync::LazyLock::new(|| {std::sync::Arc::new(crate::AggregateUDF::from(<$UDAF>::default()))- })- .clone()+ });+ std::sync::Arc::clone(&INSTANCE)}}}diff --git a/datafusion/functions-aggregate/src/macros.rs b/datafusion/functions-aggregate/src/macros.rsindex ffb5183278..b464dde6cc 100644--- a/datafusion/functions-aggregate/src/macros.rs+++ b/datafusion/functions-aggregate/src/macros.rs@@ -65,19 +65,14 @@ macro_rules! create_func {};($UDAF:ty, $AGGREGATE_UDF_FN:ident, $CREATE:expr) => {paste::paste! {- /// Singleton instance of [$UDAF], ensures the UDAF is only created once- /// named STATIC_$(UDAF). For example `STATIC_FirstValue`- #[allow(non_upper_case_globals)]- static [< STATIC_ $UDAF >]: std::sync::OnceLock<std::sync::Arc<datafusion_expr::AggregateUDF>> =- std::sync::OnceLock::new();-#[doc = concat!("AggregateFunction that returns a [`AggregateUDF`](datafusion_expr::AggregateUDF) for [`", stringify!($UDAF), "`]")]pub fn $AGGREGATE_UDF_FN() -> std::sync::Arc<datafusion_expr::AggregateUDF> {- [< STATIC_ $UDAF >]- .get_or_init(|| {+ // Singleton instance of [$UDAF], ensures the UDAF is only created once+ static INSTANCE: std::sync::LazyLock<std::sync::Arc<datafusion_expr::AggregateUDF>> =+ std::sync::LazyLock::new(|| {std::sync::Arc::new(datafusion_expr::AggregateUDF::from($CREATE))- })- .clone()+ });+ std::sync::Arc::clone(&INSTANCE)}}}diff --git a/datafusion/functions-nested/src/macros.rs b/datafusion/functions-nested/src/macros.rsindex 00247f39ac..cec7f2fd56 100644--- a/datafusion/functions-nested/src/macros.rs+++ b/datafusion/functions-nested/src/macros.rs@@ -85,22 +85,17 @@ macro_rules! make_udf_expr_and_func {macro_rules! create_func {($UDF:ty, $SCALAR_UDF_FN:ident) => {paste::paste! {- /// Singleton instance of [`$UDF`], ensures the UDF is only created once- /// named STATIC_$(UDF). For example `STATIC_ArrayToString`- #[allow(non_upper_case_globals)]- static [< STATIC_ $UDF >]: std::sync::OnceLock<std::sync::Arc<datafusion_expr::ScalarUDF>> =- std::sync::OnceLock::new();-#[doc = concat!("ScalarFunction that returns a [`ScalarUDF`](datafusion_expr::ScalarUDF) for ")]#[doc = stringify!($UDF)]pub fn $SCALAR_UDF_FN() -> std::sync::Arc<datafusion_expr::ScalarUDF> {- [< STATIC_ $UDF >]- .get_or_init(|| {+ // Singleton instance of [`$UDF`], ensures the UDF is only created once+ static INSTANCE: std::sync::LazyLock<std::sync::Arc<datafusion_expr::ScalarUDF>> =+ std::sync::LazyLock::new(|| {std::sync::Arc::new(datafusion_expr::ScalarUDF::new_from_impl(<$UDF>::new(),))- })- .clone()+ });+ std::sync::Arc::clone(&INSTANCE)}}};diff --git a/datafusion/functions-table/src/lib.rs b/datafusion/functions-table/src/lib.rsindex 9ea4c0c899..f5436f7bf8 100644--- a/datafusion/functions-table/src/lib.rs+++ b/datafusion/functions-table/src/lib.rs@@ -34,15 +34,15 @@ pub fn all_default_table_functions() -> Vec<Arc<TableFunction>> {macro_rules! create_udtf_function {($module:path, $name:expr) => {paste::paste! {- static INSTANCE: std::sync::OnceLock<Arc<TableFunction>> = std::sync::OnceLock::new();-pub fn [<$name:lower>]() -> Arc<TableFunction> {- INSTANCE.get_or_init(|| {- Arc::new(TableFunction::new(- $name.to_string(),- Arc::new($module {}),- ))- }).clone()+ static INSTANCE: std::sync::LazyLock<Arc<TableFunction>> =+ std::sync::LazyLock::new(|| {+ std::sync::Arc::new(TableFunction::new(+ $name.to_string(),+ Arc::new($module {}),+ ))+ });+ std::sync::Arc::clone(&INSTANCE)}}};diff --git a/datafusion/functions-window/src/macros.rs b/datafusion/functions-window/src/macros.rsindex 2905ccf4c2..0a86ba6255 100644--- a/datafusion/functions-window/src/macros.rs+++ b/datafusion/functions-window/src/macros.rs@@ -99,21 +99,16 @@ macro_rules! get_or_init_udwf {($UDWF:ident, $OUT_FN_NAME:ident, $DOC:expr, $CTOR:path) => {paste::paste! {- #[doc = concat!(" Singleton instance of [`", stringify!($OUT_FN_NAME), "`], ensures the user-defined")]- #[doc = concat!(" window function is only created once.")]- #[allow(non_upper_case_globals)]- static [<STATIC_ $UDWF>]: std::sync::OnceLock<std::sync::Arc<datafusion_expr::WindowUDF>> =- std::sync::OnceLock::new();-#[doc = concat!(" Returns a [`WindowUDF`](datafusion_expr::WindowUDF) for [`", stringify!($OUT_FN_NAME), "`].")]#[doc = ""]#[doc = concat!(" ", $DOC)]pub fn [<$OUT_FN_NAME _udwf>]() -> std::sync::Arc<datafusion_expr::WindowUDF> {- [<STATIC_ $UDWF>]- .get_or_init(|| {+ // Singleton instance of UDWF, ensures it is only created once.+ static INSTANCE: std::sync::LazyLock<std::sync::Arc<datafusion_expr::WindowUDF>> =+ std::sync::LazyLock::new(|| {std::sync::Arc::new(datafusion_expr::WindowUDF::from($CTOR()))- })- .clone()+ });+ std::sync::Arc::clone(&INSTANCE)}}};diff --git a/datafusion/functions/src/macros.rs b/datafusion/functions/src/macros.rsindex bc66855890..bedec9bb2e 100644--- a/datafusion/functions/src/macros.rs+++ b/datafusion/functions/src/macros.rs@@ -71,20 +71,18 @@ macro_rules! export_functions {/// This is used to ensure creating the list of `ScalarUDF` only happens once.macro_rules! make_udf_function {($UDF:ty, $GNAME:ident, $NAME:ident) => {- /// Singleton instance of the function- static $GNAME: std::sync::OnceLock<std::sync::Arc<datafusion_expr::ScalarUDF>> =- std::sync::OnceLock::new();-#[doc = "Return a [`ScalarUDF`](datafusion_expr::ScalarUDF) implementation "]#[doc = stringify!($UDF)]pub fn $NAME() -> std::sync::Arc<datafusion_expr::ScalarUDF> {- $GNAME- .get_or_init(|| {- std::sync::Arc::new(datafusion_expr::ScalarUDF::new_from_impl(- <$UDF>::new(),- ))- })- .clone()+ // Singleton instance of the function+ static $GNAME: std::sync::LazyLock<+ std::sync::Arc<datafusion_expr::ScalarUDF>,+ > = std::sync::LazyLock::new(|| {+ std::sync::Arc::new(datafusion_expr::ScalarUDF::new_from_impl(+ <$UDF>::new(),+ ))+ });+ std::sync::Arc::clone(&$GNAME)}};}diff --git a/datafusion/functions/src/regex/regexpreplace.rs b/datafusion/functions/src/regex/regexpreplace.rsindex af02fa4934..9b4a7b0455 100644--- a/datafusion/functions/src/regex/regexpreplace.rs+++ b/datafusion/functions/src/regex/regexpreplace.rs@@ -39,7 +39,7 @@ use datafusion_expr::{Documentation, ScalarUDFImpl, Signature, Volatility};use regex::Regex;use std::any::Any;use std::collections::HashMap;-use std::sync::{Arc, OnceLock};+use std::sync::{Arc, LazyLock, OnceLock};#[derive(Debug)]pub struct RegexpReplaceFunc {@@ -188,11 +188,9 @@ fn regexp_replace_func(args: &[ColumnarValue]) -> Result<ArrayRef> {/// replace POSIX capture groups (like \1) with Rust Regex group (like ${1})/// used by regexp_replacefn regex_replace_posix_groups(replacement: &str) -> String {- fn capture_groups_re() -> &'static Regex {- static CAPTURE_GROUPS_RE_LOCK: OnceLock<Regex> = OnceLock::new();- CAPTURE_GROUPS_RE_LOCK.get_or_init(|| Regex::new(r"(\\)(\d*)").unwrap())- }- capture_groups_re()+ static CAPTURE_GROUPS_RE_LOCK: LazyLock<Regex> =+ LazyLock::new(|| Regex::new(r"(\\)(\d*)").unwrap());+ CAPTURE_GROUPS_RE_LOCK.replace_all(replacement, "$${$2}").into_owned()}diff --git a/datafusion/physical-expr-common/src/sort_expr.rs b/datafusion/physical-expr-common/src/sort_expr.rsindex bf06296ba3..0d75016106 100644--- a/datafusion/physical-expr-common/src/sort_expr.rs+++ b/datafusion/physical-expr-common/src/sort_expr.rs@@ -22,7 +22,7 @@ use std::fmt;use std::fmt::{Display, Formatter};use std::hash::{Hash, Hasher};use std::ops::{Deref, Index, Range, RangeFrom, RangeTo};-use std::sync::{Arc, OnceLock};+use std::sync::{Arc, LazyLock};use std::vec::IntoIter;use arrow::compute::kernels::sort::{SortColumn, SortOptions};@@ -336,8 +336,6 @@ impl AsRef<LexOrdering> for LexOrdering {}}-static EMPTY_ORDER: OnceLock<LexOrdering> = OnceLock::new();-impl LexOrdering {// Creates a new [`LexOrdering`] from a vectorpub fn new(inner: Vec<PhysicalSortExpr>) -> Self {@@ -346,7 +344,8 @@ impl LexOrdering {/// Return an empty LexOrdering (no expressions)pub fn empty() -> &'static LexOrdering {- EMPTY_ORDER.get_or_init(LexOrdering::default)+ static EMPTY_ORDER: LazyLock<LexOrdering> = LazyLock::new(LexOrdering::default);+ &EMPTY_ORDER}pub fn capacity(&self) -> usize {diff --git a/datafusion/physical-expr/src/expressions/not.rs b/datafusion/physical-expr/src/expressions/not.rsindex cc35c91c98..440c4e9557 100644--- a/datafusion/physical-expr/src/expressions/not.rs+++ b/datafusion/physical-expr/src/expressions/not.rs@@ -127,7 +127,7 @@ mod tests {use super::*;use crate::expressions::col;use arrow::{array::BooleanArray, datatypes::*};- use std::sync::OnceLock;+ use std::sync::LazyLock;#[test]fn neg_op() -> Result<()> {@@ -190,10 +190,9 @@ mod tests {}fn schema() -> SchemaRef {- Arc::clone(SCHEMA.get_or_init(|| {+ static SCHEMA: LazyLock<SchemaRef> = LazyLock::new(|| {Arc::new(Schema::new(vec![Field::new("a", DataType::Boolean, true)]))- }))+ });+ Arc::clone(&SCHEMA)}-- static SCHEMA: OnceLock<SchemaRef> = OnceLock::new();}diff --git a/datafusion/physical-expr/src/utils/guarantee.rs b/datafusion/physical-expr/src/utils/guarantee.rsindex 75ad5d22af..2c73df7cfd 100644--- a/datafusion/physical-expr/src/utils/guarantee.rs+++ b/datafusion/physical-expr/src/utils/guarantee.rs@@ -412,7 +412,7 @@ impl<'a> ColOpLit<'a> {#[cfg(test)]mod test {- use std::sync::OnceLock;+ use std::sync::LazyLock;use super::*;use crate::planner::logical2physical;@@ -863,13 +863,12 @@ mod test {// Schema for testingfn schema() -> SchemaRef {- Arc::clone(SCHEMA.get_or_init(|| {+ static SCHEMA: LazyLock<SchemaRef> = LazyLock::new(|| {Arc::new(Schema::new(vec![Field::new("a", DataType::Utf8, false),Field::new("b", DataType::Int32, false),]))- }))+ });+ Arc::clone(&SCHEMA)}-- static SCHEMA: OnceLock<SchemaRef> = OnceLock::new();}diff --git a/datafusion/sqllogictest/src/engines/datafusion_engine/normalize.rs b/datafusion/sqllogictest/src/engines/datafusion_engine/normalize.rsindex 8337d2e9a3..4146c7cf80 100644--- a/datafusion/sqllogictest/src/engines/datafusion_engine/normalize.rs+++ b/datafusion/sqllogictest/src/engines/datafusion_engine/normalize.rs@@ -23,7 +23,7 @@ use arrow::{array, array::ArrayRef, datatypes::DataType, record_batch::RecordBatuse datafusion_common::format::DEFAULT_FORMAT_OPTIONS;use datafusion_common::DataFusionError;use std::path::PathBuf;-use std::sync::OnceLock;+use std::sync::LazyLock;use super::super::conversion::*;use super::error::{DFSqlLogicTestError, Result};@@ -130,7 +130,7 @@ fn expand_row(mut row: Vec<String>) -> impl Iterator<Item = Vec<String>> {/// ```fn normalize_paths(mut row: Vec<String>) -> Vec<String> {row.iter_mut().for_each(|s| {- let workspace_root: &str = workspace_root().as_ref();+ let workspace_root: &str = WORKSPACE_ROOT.as_ref();if s.contains(workspace_root) {*s = s.replace(workspace_root, "WORKSPACE_ROOT");}@@ -138,34 +138,30 @@ fn normalize_paths(mut row: Vec<String>) -> Vec<String> {row}-/// return the location of the datafusion checkout-fn workspace_root() -> &'static object_store::path::Path {- static WORKSPACE_ROOT_LOCK: OnceLock<object_store::path::Path> = OnceLock::new();- WORKSPACE_ROOT_LOCK.get_or_init(|| {- // e.g. /Software/datafusion/datafusion/core- let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));+/// The location of the datafusion checkout+static WORKSPACE_ROOT: LazyLock<object_store::path::Path> = LazyLock::new(|| {+ // e.g. /Software/datafusion/datafusion/core+ let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR"));- // e.g. /Software/datafusion/datafusion- let workspace_root = dir- .parent()- .expect("Can not find parent of datafusion/core")- // e.g. /Software/datafusion- .parent()- .expect("parent of datafusion")- .to_string_lossy();+ // e.g. /Software/datafusion/datafusion+ let workspace_root = dir+ .parent()+ .expect("Can not find parent of datafusion/core")+ // e.g. /Software/datafusion+ .parent()+ .expect("parent of datafusion")+ .to_string_lossy();- let sanitized_workplace_root = if cfg!(windows) {- // Object store paths are delimited with `/`, e.g. `/datafusion/datafusion/testing/data/csv/aggregate_test_100.csv`.- // The default windows delimiter is `\`, so the workplace path is `datafusion\datafusion`.- workspace_root- .replace(std::path::MAIN_SEPARATOR, object_store::path::DELIMITER)- } else {- workspace_root.to_string()- };+ let sanitized_workplace_root = if cfg!(windows) {+ // Object store paths are delimited with `/`, e.g. `/datafusion/datafusion/testing/data/csv/aggregate_test_100.csv`.+ // The default windows delimiter is `\`, so the workplace path is `datafusion\datafusion`.+ workspace_root.replace(std::path::MAIN_SEPARATOR, object_store::path::DELIMITER)+ } else {+ workspace_root.to_string()+ };- object_store::path::Path::parse(sanitized_workplace_root).unwrap()- })-}+ object_store::path::Path::parse(sanitized_workplace_root).unwrap()+});/// Convert a single batch to a `Vec<Vec<String>>` for comparisonfn convert_batch(batch: RecordBatch) -> Result<Vec<Vec<String>>> {