Skip to content

Apache DataFusion SQL Query Engine

feat: support spark udf format_string (#17561)

Chen Chongchend76a1e0bed98
diff --git a/Cargo.lock b/Cargo.lock
index a2939f4257..19d5615158 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2567,6 +2567,7 @@ name = "datafusion-spark"
version = "50.1.0"
dependencies = [
"arrow",
+ "bigdecimal",
"chrono",
"crc32fast",
"criterion",
diff --git a/datafusion/spark/Cargo.toml b/datafusion/spark/Cargo.toml
index 78a1742cee..b95cc31cae 100644
--- a/datafusion/spark/Cargo.toml
+++ b/datafusion/spark/Cargo.toml
@@ -37,6 +37,7 @@ name = "datafusion_spark"
[dependencies]
arrow = { workspace = true }
+bigdecimal = { workspace = true }
chrono = { workspace = true }
crc32fast = "1.4"
datafusion-catalog = { workspace = true }
diff --git a/datafusion/spark/src/function/string/format_string.rs b/datafusion/spark/src/function/string/format_string.rs
new file mode 100644
index 0000000000..9809456af9
--- /dev/null
+++ b/datafusion/spark/src/function/string/format_string.rs
@@ -0,0 +1,2350 @@
+// 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 std::any::Any;
+use std::fmt::Write;
+use std::sync::Arc;
+
+use core::num::FpCategory;
+
+use arrow::{
+ array::{Array, ArrayRef, LargeStringArray, StringArray, StringViewArray},
+ datatypes::DataType,
+};
+use bigdecimal::{
+ num_bigint::{BigInt, Sign},
+ BigDecimal, ToPrimitive,
+};
+use chrono::{DateTime, Datelike, Timelike, Utc};
+use datafusion_common::{
+ exec_datafusion_err, exec_err, plan_err, DataFusionError, Result, ScalarValue,
+};
+use datafusion_expr::{
+ ColumnarValue, ScalarFunctionArgs, ScalarUDFImpl, Signature, TypeSignature,
+ Volatility,
+};
+
+/// Spark-compatible `format_string` expression
+/// <https://spark.apache.org/docs/latest/api/sql/index.html#format_string>
+#[derive(Debug, PartialEq, Eq, Hash)]
+pub struct FormatStringFunc {
+ signature: Signature,
+ aliases: Vec<String>,
+}
+
+impl Default for FormatStringFunc {
+ fn default() -> Self {
+ Self::new()
+ }
+}
+
+impl FormatStringFunc {
+ pub fn new() -> Self {
+ Self {
+ signature: Signature::new(TypeSignature::VariadicAny, Volatility::Immutable),
+ aliases: vec![String::from("printf")],
+ }
+ }
+}
+
+impl ScalarUDFImpl for FormatStringFunc {
+ fn as_any(&self) -> &dyn Any {
+ self
+ }
+
+ fn name(&self) -> &str {
+ "format_string"
+ }
+
+ fn aliases(&self) -> &[String] {
+ &self.aliases
+ }
+
+ fn signature(&self) -> &Signature {
+ &self.signature
+ }
+
+ fn return_type(&self, arg_types: &[DataType]) -> Result<DataType> {
+ match arg_types[0] {
+ DataType::Null => Ok(DataType::Utf8),
+ DataType::Utf8 | DataType::LargeUtf8 | DataType::Utf8View => Ok(arg_types[0].clone()),
+ _ => plan_err!("The format_string function expects the first argument to be Utf8, LargeUtf8 or Utf8View")
+ }
+ }
+
+ fn invoke_with_args(&self, args: ScalarFunctionArgs) -> Result<ColumnarValue> {
+ let len = args.args.iter().find_map(|arg| match arg {
+ ColumnarValue::Scalar(_) => None,
+ ColumnarValue::Array(a) => Some(a.len()),
+ });
+ let is_scalar = len.is_none();
+ let data_types = args.args[1..]
+ .iter()
+ .map(|arg| arg.data_type())
+ .collect::<Vec<_>>();
+ let fmt_type = args.args[0].data_type();
+
+ match &args.args[0] {
+ ColumnarValue::Scalar(ScalarValue::Null) => {
+ Ok(ColumnarValue::Scalar(ScalarValue::Utf8(None)))
+ }
+ ColumnarValue::Scalar(ScalarValue::Utf8(None)) => {
+ Ok(ColumnarValue::Scalar(ScalarValue::Utf8(None)))
+ }
+ ColumnarValue::Scalar(ScalarValue::LargeUtf8(None)) => {
+ Ok(ColumnarValue::Scalar(ScalarValue::LargeUtf8(None)))
+ }
+ ColumnarValue::Scalar(ScalarValue::Utf8View(None)) => {
+ Ok(ColumnarValue::Scalar(ScalarValue::Utf8View(None)))
+ }
+ ColumnarValue::Scalar(ScalarValue::Utf8(Some(fmt)))
+ | ColumnarValue::Scalar(ScalarValue::LargeUtf8(Some(fmt)))
+ | ColumnarValue::Scalar(ScalarValue::Utf8View(Some(fmt))) => {
+ let formatter = Formatter::parse(fmt, &data_types)?;
+ let mut result = Vec::with_capacity(len.unwrap_or(1));
+ for i in 0..len.unwrap_or(1) {
+ let scalars = args.args[1..]
+ .iter()
+ .map(|arg| try_to_scalar(arg.clone(), i))
+ .collect::<Result<Vec<_>>>()?;
+ let formatted = formatter.format(&scalars)?;
+ result.push(formatted);
+ }
+ if is_scalar {
+ let scalar_result = result.pop().unwrap();
+ match fmt_type {
+ DataType::Utf8 => Ok(ColumnarValue::Scalar(ScalarValue::Utf8(
+ Some(scalar_result),
+ ))),
+ DataType::LargeUtf8 => Ok(ColumnarValue::Scalar(
+ ScalarValue::LargeUtf8(Some(scalar_result)),
+ )),
+ DataType::Utf8View => Ok(ColumnarValue::Scalar(
+ ScalarValue::Utf8View(Some(scalar_result)),
+ )),
+ _ => unreachable!(),
+ }
+ } else {
+ let array: ArrayRef = match fmt_type {
+ DataType::Utf8 => Arc::new(StringArray::from(result)),
+ DataType::LargeUtf8 => Arc::new(LargeStringArray::from(result)),
+ DataType::Utf8View => Arc::new(StringViewArray::from(result)),
+ _ => unreachable!(),
+ };
+ Ok(ColumnarValue::Array(array))
+ }
+ }
+ ColumnarValue::Array(fmts) => {
+ let mut result = Vec::with_capacity(len.unwrap());
+ for i in 0..len.unwrap() {
+ let fmt = ScalarValue::try_from_array(fmts, i)?;
+ match fmt.try_as_str() {
+ Some(Some(fmt)) => {
+ let formatter = Formatter::parse(fmt, &data_types)?;
+ let scalars = args.args[1..]
+ .iter()
+ .map(|arg| try_to_scalar(arg.clone(), i))
+ .collect::<Result<Vec<_>>>()?;
+ let formatted = formatter.format(&scalars)?;
+ result.push(Some(formatted));
+ }
+ Some(None) => {
+ result.push(None);
+ }
+ _ => unreachable!(),
+ }
+ }
+ let array: ArrayRef = match fmt_type {
+ DataType::Utf8 => Arc::new(StringArray::from(result)),
+ DataType::LargeUtf8 => Arc::new(LargeStringArray::from(result)),
+ DataType::Utf8View => Arc::new(StringViewArray::from(result)),
+ _ => unreachable!(),
+ };
+ Ok(ColumnarValue::Array(array))
+ }
+ _ => exec_err!(
+ "The format_string function expects the first argument to be a string"
+ ),
+ }
+ }
+}
+
+fn try_to_scalar(arg: ColumnarValue, index: usize) -> Result<ScalarValue> {
+ match arg {
+ ColumnarValue::Scalar(scalar) => Ok(scalar),
+ ColumnarValue::Array(array) => ScalarValue::try_from_array(&array, index),
+ }
+}
+
+/// Compatible with `java.util.Formatter`
+#[derive(Debug)]
+pub struct Formatter<'a> {
+ pub elements: Vec<FormatElement<'a>>,
+ pub arg_num: usize,
+}
+
+impl<'a> Formatter<'a> {
+ pub fn new(elements: Vec<FormatElement<'a>>) -> Self {
+ let arg_num = elements
+ .iter()
+ .map(|element| match element {
+ FormatElement::Format(spec) => spec.argument_index,
+ _ => 0,
+ })
+ .max()
+ .unwrap_or(0);
+ Self { elements, arg_num }
+ }
+
+ /// Parses a printf-style format string into a Formatter with validation.
+ ///
+ /// This method implements a comprehensive parser for Java `java.util.Formatter` syntax,
+ /// processing the format string character by character to identify and validate format
+ /// specifiers against the provided argument types.
+ ///
+ /// # Arguments
+ ///
+ /// * `fmt` - The format string containing literal text and format specifiers
+ /// * `arg_types` - Array of DataFusion DataTypes corresponding to the arguments
+ ///
+ /// # Parsing Process
+ ///
+ /// The parser operates in several phases:
+ ///
+ /// 1. **String Scanning**: Iterates through the format string looking for '%' characters
+ /// that mark the beginning of format specifiers or special sequences.
+ ///
+ /// 2. **Special Sequence Handling**: Processes escape sequences:
+ /// - `%%` becomes a literal '%' character
+ /// - `%n` becomes a newline character
+ /// - `%<` indicates reuse of the previous argument with a new format specifier
+ ///
+ /// 3. **Argument Index Resolution**: Determines which argument each format specifier refers to:
+ /// - Sequential indexing: arguments are consumed in order (1, 2, 3, ...)
+ /// - Positional indexing: explicit argument position using `%n$` syntax
+ /// - Previous argument reuse: `%<` references the last used argument
+ ///
+ /// 4. **Format Specifier Parsing**: For each format specifier, extracts:
+ /// - Flags (-, +, space, #, 0, ',', '(')
+ /// - Width specification (minimum field width)
+ /// - Precision specification (decimal places or maximum characters)
+ /// - Conversion type (d, s, f, x, etc.)
+ ///
+ /// 5. **Type Validation**: Verifies that each format specifier's conversion type
+ /// is compatible with the corresponding argument's DataType. For example:
+ /// - Integer conversions (%d, %x, %o) require integer DataTypes
+ /// - String conversions (%s, %S) accept any DataType
+ /// - Float conversions (%f, %e, %g) require numeric DataTypes
+ ///
+ /// 6. **Element Construction**: Creates FormatElement instances for:
+ /// - Verbatim text sections (copied directly to output)
+ /// - Validated format specifiers with their parsed parameters
+ ///
+ /// # Internal State Management
+ ///
+ /// The parser maintains several state variables:
+ /// - `argument_index`: Tracks the current sequential argument position
+ /// - `prev`: Remembers the last used argument index for `%<` references
+ /// - `res`: Accumulates the parsed FormatElement instances
+ /// - `rem`: Points to the remaining unparsed portion of the format string
+ ///
+ /// # Validation and Error Handling
+ ///
+ /// The parser performs extensive validation including:
+ /// - Argument index bounds checking against the provided arg_types array
+ /// - Format specifier syntax validation
+ /// - Type compatibility verification between conversion types and DataTypes
+ /// - Detection of malformed numeric parameters and invalid flag combinations
+ ///
+ /// # Returns
+ ///
+ /// Returns a Formatter containing the parsed elements and the maximum argument
+ /// index encountered, enabling efficient argument validation during formatting.
+ pub fn parse(fmt: &'a str, arg_types: &[DataType]) -> Result<Self> {
+ // find the first %
+ let mut res = Vec::new();
+
+ let mut rem = fmt;
+ let mut argument_index = 0;
+
+ let mut prev: Option<usize> = None;
+
+ while !rem.is_empty() {
+ if let Some((verbatim_prefix, rest)) = rem.split_once('%') {
+ if !verbatim_prefix.is_empty() {
+ res.push(FormatElement::Verbatim(verbatim_prefix));
+ }
+ if let Some(rest) = rest.strip_prefix('%') {
+ res.push(FormatElement::Verbatim("%"));
+ rem = rest;
+ continue;
+ }
+ if let Some(rest) = rest.strip_prefix('n') {
+ res.push(FormatElement::Verbatim("\n"));
+ rem = rest;
+ continue;
+ }
+ if let Some(rest) = rest.strip_prefix('<') {
+ // %< means reuse the previous argument
+ let Some(p) = prev else {
+ return exec_err!("No previous argument to reference");
+ };
+ let (spec, rest) =
+ take_conversion_specifier(rest, p, arg_types[p - 1].clone())?;
+ res.push(FormatElement::Format(spec));
+ rem = rest;
+ continue;
+ }
+
+ let (current_argument_index, rest2) = take_numeric_param(rest, false);
+ let (current_argument_index, rest) =
+ match (current_argument_index, rest2.starts_with('$')) {
+ (NumericParam::Literal(index), true) => {
+ (index as usize, &rest2[1..])
+ }
+ (NumericParam::FromArgument, true) => {
+ return exec_err!("Invalid numeric parameter")
+ }
+ (_, false) => {
+ argument_index += 1;
+ (argument_index, rest)
+ }
+ };
+ if current_argument_index == 0 || current_argument_index > arg_types.len()
+ {
+ return exec_err!(
+ "Argument index {} is out of bounds",
+ current_argument_index
+ );
+ }
+
+ let (spec, rest) = take_conversion_specifier(
+ rest,
+ current_argument_index,
+ arg_types[current_argument_index - 1].clone(),
+ )
+ .map_err(|e| exec_datafusion_err!("{:?}, format string: {:?}", e, fmt))?;
+ res.push(FormatElement::Format(spec));
+ prev = Some(spec.argument_index);
+ rem = rest;
+ } else {
+ res.push(FormatElement::Verbatim(rem));
+ break;
+ }
+ }
+
+ Ok(Self::new(res))
+ }
+
+ pub fn format(&self, args: &[ScalarValue]) -> Result<String> {
+ if args.len() < self.arg_num {
+ return exec_err!(
+ "Expected at least {} arguments, got {}",
+ self.arg_num,
+ args.len()
+ );
+ }
+ let mut string = String::new();
+ for element in &self.elements {
+ match element {
+ FormatElement::Verbatim(text) => {
+ string.push_str(text);
+ }
+ FormatElement::Format(spec) => {
+ spec.format(&mut string, &args[spec.argument_index - 1])?;
+ }
+ }
+ }
+ Ok(string)
+ }
+}
+
+#[derive(Debug)]
+pub enum FormatElement<'a> {
+ /// Some characters that are copied to the output as-is
+ Verbatim(&'a str),
+ /// A format specifier
+ Format(ConversionSpecifier),
+}
+
+/// Parsed printf conversion specifier
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct ConversionSpecifier {
+ pub argument_index: usize,
+ /// flag `#`: use `0x`, etc?
+ pub alt_form: bool,
+ /// flag `0`: left-pad with zeros?
+ pub zero_pad: bool,
+ /// flag `-`: left-adjust (pad with spaces on the right)
+ pub left_adj: bool,
+ /// flag `' '` (space): indicate sign with a space?
+ pub space_sign: bool,
+ /// flag `+`: Always show sign? (for signed numbers)
+ pub force_sign: bool,
+ /// flag `,`: include locale-specific grouping separators
+ pub grouping_separator: bool,
+ /// flag `(`: enclose negative numbers in parentheses
+ pub negative_in_parentheses: bool,
+ /// field width
+ pub width: NumericParam,
+ /// floating point field precision
+ pub precision: NumericParam,
+ /// data type
+ pub conversion_type: ConversionType,
+}
+
+/// Width / precision parameter
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum NumericParam {
+ /// The literal width
+ Literal(i32),
+ /// Get the width from the previous argument
+ FromArgument,
+}
+
+/// Printf data type
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum ConversionType {
+ /// `B`
+ BooleanUpper,
+ /// `b`
+ BooleanLower,
+ /// Not implemented yet. Can be implemented after <https://github.com/apache/datafusion/pull/17093> is merged
+ /// `h`
+ HexHashLower,
+ /// `H`
+ HexHashUpper,
+ /// `d`
+ DecInt,
+ /// `o`
+ OctInt,
+ /// `x`
+ HexIntLower,
+ /// `X`
+ HexIntUpper,
+ /// `e`
+ SciFloatLower,
+ /// `E`
+ SciFloatUpper,
+ /// `f`
+ DecFloatLower,
+ /// `g`
+ CompactFloatLower,
+ /// `G`
+ CompactFloatUpper,
+ /// `a`
+ HexFloatLower,
+ /// `A`
+ HexFloatUpper,
+ /// `t`
+ TimeLower(TimeFormat),
+ /// `T`
+ TimeUpper(TimeFormat),
+ /// `c`
+ CharLower,
+ /// `C`
+ CharUpper,
+ /// `s`
+ StringLower,
+ /// `S`
+ StringUpper,
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum TimeFormat {
+ // Hour of the day for the 24-hour clock,
+ // formatted as two digits with a leading zero as necessary i.e. 00 - 23. 00 corresponds to midnight.
+ HUpper,
+ // Hour for the 12-hour clock,
+ // formatted as two digits with a leading zero as necessary, i.e. 01 - 12. 01 corresponds to one o'clock (either morning or afternoon).
+ IUpper,
+ // Hour of the day for the 24-hour clock,
+ // i.e. 0 - 23. 0 corresponds to midnight.
+ KLower,
+ // Hour for the 12-hour clock,
+ // i.e. 1 - 12. 1 corresponds to one o'clock (either morning or afternoon).
+ LLower,
+ // Minute within the hour formatted as two digits with a leading zero as necessary, i.e. 00 - 59.
+ MUpper,
+ // Seconds within the minute, formatted as two digits with a leading zero as necessary,
+ // i.e. 00 - 60 ("60" is a special value required to support leap seconds).
+ SUpper,
+ // Millisecond within the second formatted as three digits with leading zeros as necessary, i.e. 000 - 999.
+ LUpper,
+ // Nanosecond within the second, formatted as nine digits with leading zeros as necessary,
+ // i.e. 000000000 - 999999999. The precision of this value is limited by the resolution of the underlying operating system or hardware.
+ NUpper,
+ // Locale-specific morning or afternoon marker in lower case, e.g."am" or "pm".
+ // Use of the conversion prefix 'T' forces this output to upper case. (Note that 'p' produces lower-case output.
+ // This is different from GNU date and POSIX strftime(3c) which produce upper-case output.)
+ PLower,
+ // RFC 822 style numeric time zone offset from GMT,
+ // e.g. -0800. This value will be adjusted as necessary for Daylight Saving Time.
+ // For long, Long, and Date the time zone used is the default time zone for this instance of the Java virtual machine.
+ ZLower,
+ // A string representing the abbreviation for the time zone. This value will be adjusted as necessary for Daylight Saving Time.
+ // For long, Long, and Date the time zone used is the default time zone for this instance of the Java virtual machine.
+ // The Formatter's locale will supersede the locale of the argument (if any).
+ ZUpper,
+ // Seconds since the beginning of the epoch starting at 1 January 1970 00:00:00 UTC,
+ // i.e. Long.MIN_VALUE/1000 to Long.MAX_VALUE/1000.
+ SLower,
+ // Milliseconds since the beginning of the epoch starting at 1 January 1970 00:00:00 UTC,
+ // i.e. Long.MIN_VALUE to Long.MAX_VALUE. The precision of this value is limited by the resolution of the underlying operating system or hardware.
+ QUpper,
+ // Locale-specific full month name, e.g. "January", "February".
+ BUpper,
+ // Locale-specific abbreviated month name, e.g. "Jan", "Feb".
+ BLower,
+ // Locale-specific full weekday name, e.g. "Monday", "Tuesday".
+ AUpper,
+ // Locale-specific abbreviated weekday name, e.g. "Mon", "Tue".
+ ALower,
+ // Four-digit year divided by 100, formatted as two digits with leading zero as necessary, i.e. 00 - 99
+ CUpper,
+ // Year, formatted to at least four digits with leading zeros as necessary, e.g. 0092 equals 92 CE for the Gregorian calendar.
+ YUpper,
+ // Last two digits of the year, formatted with leading zeros as necessary, i.e. 00 - 99.
+ YLower,
+ // Day of year, formatted as three digits with leading zeros as necessary, e.g. 001 - 366 for the Gregorian calendar. 001 corresponds to the first day of the year.
+ JLower,
+ // Month, formatted as two digits with leading zeros as necessary, i.e. 01 - 13, where "01" is the first month of the year and ("13" is a special value required to support lunar calendars).
+ MLower,
+ // Day of month, formatted as two digits with leading zeros as necessary, i.e. 01 - 31, where "01" is the first day of the month.
+ DLower,
+ // Day of month, formatted as two digits, i.e. 1 - 31 where "1" is the first day of the month.
+ ELower,
+ // Time formatted for the 24-hour clock as "%tH:%tM"
+ RUpper,
+ // Time formatted for the 24-hour clock as "%tH:%tM:%tS"
+ TUpper,
+ // Time formatted for the 12-hour clock as "%tI:%tM:%tS %Tp". The location of the morning or afternoon marker ('%Tp') may be locale-dependent.
+ RLower,
+ // Date formatted as "%tm/%td/%ty"
+ DUpper,
+ // ISO 8601 complete date formatted as "%tY-%tm-%td"
+ FUpper,
+ // Date and time formatted as "%ta %tb %td %tT %tZ %tY", e.g. "Sun Jul 20 16:17:00 EDT 1969"
+ CLower,
+}
+
+impl TryFrom<char> for TimeFormat {
+ type Error = DataFusionError;
+ fn try_from(value: char) -> Result<Self, Self::Error> {
+ match value {
+ 'H' => Ok(TimeFormat::HUpper),
+ 'I' => Ok(TimeFormat::IUpper),
+ 'k' => Ok(TimeFormat::KLower),
+ 'l' => Ok(TimeFormat::LLower),
+ 'M' => Ok(TimeFormat::MUpper),
+ 'S' => Ok(TimeFormat::SUpper),
+ 'L' => Ok(TimeFormat::LUpper),
+ 'N' => Ok(TimeFormat::NUpper),
+ 'p' => Ok(TimeFormat::PLower),
+ 'z' => Ok(TimeFormat::ZLower),
+ 'Z' => Ok(TimeFormat::ZUpper),
+ 's' => Ok(TimeFormat::SLower),
+ 'Q' => Ok(TimeFormat::QUpper),
+ 'B' => Ok(TimeFormat::BUpper),
+ 'b' | 'h' => Ok(TimeFormat::BLower),
+ 'A' => Ok(TimeFormat::AUpper),
+ 'a' => Ok(TimeFormat::ALower),
+ 'C' => Ok(TimeFormat::CUpper),
+ 'Y' => Ok(TimeFormat::YUpper),
+ 'y' => Ok(TimeFormat::YLower),
+ 'j' => Ok(TimeFormat::JLower),
+ 'm' => Ok(TimeFormat::MLower),
+ 'd' => Ok(TimeFormat::DLower),
+ 'e' => Ok(TimeFormat::ELower),
+ 'R' => Ok(TimeFormat::RUpper),
+ 'T' => Ok(TimeFormat::TUpper),
+ 'r' => Ok(TimeFormat::RLower),
+ 'D' => Ok(TimeFormat::DUpper),
+ 'F' => Ok(TimeFormat::FUpper),
+ 'c' => Ok(TimeFormat::CLower),
+ _ => exec_err!("Invalid time format: {}", value),
+ }
+ }
+}
+
+impl ConversionType {
+ pub fn validate(&self, arg_type: DataType) -> Result<()> {
+ match self {
+ ConversionType::BooleanLower | ConversionType::BooleanUpper => {
+ if !matches!(arg_type, DataType::Boolean) {
+ return exec_err!(
+ "Invalid argument type for boolean conversion: {:?}",
+ arg_type
+ );
+ }
+ }
+ ConversionType::CharLower | ConversionType::CharUpper => {
+ if !matches!(
+ arg_type,
+ DataType::Int8
+ | DataType::UInt8
+ | DataType::Int16
+ | DataType::UInt16
+ | DataType::Int32
+ | DataType::UInt32
+ | DataType::Int64
+ | DataType::UInt64
+ ) {
+ return exec_err!(
+ "Invalid argument type for char conversion: {:?}",
+ arg_type
+ );
+ }
+ }
+ ConversionType::DecInt
+ | ConversionType::OctInt
+ | ConversionType::HexIntLower
+ | ConversionType::HexIntUpper => {
+ if !arg_type.is_integer() {
+ return exec_err!(
+ "Invalid argument type for integer conversion: {:?}",
+ arg_type
+ );
+ }
+ }
+ ConversionType::SciFloatLower
+ | ConversionType::SciFloatUpper
+ | ConversionType::DecFloatLower
+ | ConversionType::CompactFloatLower
+ | ConversionType::CompactFloatUpper
+ | ConversionType::HexFloatLower
+ | ConversionType::HexFloatUpper => {
+ if !arg_type.is_numeric() {
+ return exec_err!(
+ "Invalid argument type for float conversion: {:?}",
+ arg_type
+ );
+ }
+ }
+ ConversionType::TimeLower(_) | ConversionType::TimeUpper(_) => {
+ if !arg_type.is_temporal() {
+ return exec_err!(
+ "Invalid argument type for time conversion: {:?}",
+ arg_type
+ );
+ }
+ }
+ _ => {}
+ }
+ Ok(())
+ }
+
+ fn supports_integer(&self) -> bool {
+ matches!(
+ self,
+ ConversionType::DecInt
+ | ConversionType::HexIntLower
+ | ConversionType::HexIntUpper
+ | ConversionType::OctInt
+ | ConversionType::CharLower
+ | ConversionType::CharUpper
+ | ConversionType::StringLower
+ | ConversionType::StringUpper
+ )
+ }
+
+ fn supports_float(&self) -> bool {
+ matches!(
+ self,
+ ConversionType::DecFloatLower
+ | ConversionType::SciFloatLower
+ | ConversionType::SciFloatUpper
+ | ConversionType::CompactFloatLower
+ | ConversionType::CompactFloatUpper
+ | ConversionType::StringLower
+ | ConversionType::StringUpper
+ | ConversionType::HexFloatLower
+ | ConversionType::HexFloatUpper
+ )
+ }
+
+ fn supports_decimal(&self) -> bool {
+ matches!(
+ self,
+ ConversionType::DecFloatLower
+ | ConversionType::SciFloatLower
+ | ConversionType::SciFloatUpper
+ | ConversionType::CompactFloatLower
+ | ConversionType::CompactFloatUpper
+ | ConversionType::StringLower
+ | ConversionType::StringUpper
+ )
+ }
+
+ fn supports_time(&self) -> bool {
+ matches!(
+ self,
+ ConversionType::TimeLower(_)
+ | ConversionType::TimeUpper(_)
+ | ConversionType::StringLower
+ | ConversionType::StringUpper
+ )
+ }
+
+ fn is_upper(&self) -> bool {
+ matches!(
+ self,
+ ConversionType::BooleanUpper
+ | ConversionType::HexHashUpper
+ | ConversionType::HexIntUpper
+ | ConversionType::SciFloatUpper
+ | ConversionType::CompactFloatUpper
+ | ConversionType::HexFloatUpper
+ | ConversionType::TimeUpper(_)
+ | ConversionType::CharUpper
+ | ConversionType::StringUpper
+ )
+ }
+}
+
+fn take_conversion_specifier(
+ mut s: &str,
+ argument_index: usize,
+ arg_type: DataType,
+) -> Result<(ConversionSpecifier, &str)> {
+ let mut spec = ConversionSpecifier {
+ argument_index,
+ alt_form: false,
+ zero_pad: false,
+ left_adj: false,
+ space_sign: false,
+ force_sign: false,
+ grouping_separator: false,
+ negative_in_parentheses: false,
+ width: NumericParam::Literal(0),
+ precision: NumericParam::FromArgument, // Placeholder - must not be returned!
+ // ignore length modifier
+ conversion_type: ConversionType::DecInt,
+ };
+
+ // parse flags
+ loop {
+ match s.chars().next() {
+ Some('#') => {
+ spec.alt_form = true;
+ }
+ Some('0') => {
+ if spec.left_adj {
+ return exec_err!("Invalid flag combination: '0' and '-'");
+ }
+ spec.zero_pad = true;
+ }
+ Some('-') => {
+ spec.left_adj = true;
+ }
+ Some(' ') => {
+ if spec.force_sign {
+ return exec_err!("Invalid flag combination: '+' and ' '");
+ }
+ spec.space_sign = true;
+ }
+ Some('+') => {
+ if spec.space_sign {
+ return exec_err!("Invalid flag combination: '+' and ' '");
+ }
+ spec.force_sign = true;
+ }
+ Some(',') => {
+ spec.grouping_separator = true;
+ }
+ Some('(') => {
+ spec.negative_in_parentheses = true;
+ }
+ _ => {
+ break;
+ }
+ }
+ s = &s[1..];
+ }
+ // parse width
+ let (w, mut s) = take_numeric_param(s, false);
+ spec.width = w;
+ // parse precision
+ if matches!(s.chars().next(), Some('.')) {
+ s = &s[1..];
+ let (p, s2) = take_numeric_param(s, true);
+ spec.precision = p;
+ s = s2;
+ }
+ let mut chars = s.chars();
+ let mut offset = 1;
+ // parse conversion type
+ spec.conversion_type = match chars.next() {
+ Some('b') => ConversionType::BooleanLower,
+ Some('B') => ConversionType::BooleanUpper,
+ Some('h') => ConversionType::HexHashLower,
+ Some('H') => ConversionType::HexHashUpper,
+ Some('s') => ConversionType::StringLower,
+ Some('S') => ConversionType::StringUpper,
+ Some('c') => ConversionType::CharLower,
+ Some('C') => ConversionType::CharUpper,
+ Some('d') => ConversionType::DecInt,
+ Some('o') => ConversionType::OctInt,
+ Some('x') => ConversionType::HexIntLower,
+ Some('X') => ConversionType::HexIntUpper,
+ Some('e') => ConversionType::SciFloatLower,
+ Some('E') => ConversionType::SciFloatUpper,
+ Some('f') => ConversionType::DecFloatLower,
+ Some('g') => ConversionType::CompactFloatLower,
+ Some('G') => ConversionType::CompactFloatUpper,
+ Some('a') => ConversionType::HexFloatLower,
+ Some('A') => ConversionType::HexFloatUpper,
+ Some('t') => {
+ let Some(chr) = chars.next() else {
+ return exec_err!("Invalid time format: {}", s);
+ };
+ offset += 1;
+ ConversionType::TimeLower(chr.try_into()?)
+ }
+ Some('T') => {
+ let Some(chr) = chars.next() else {
+ return exec_err!("Invalid time format: {}", s);
+ };
+ offset += 1;
+ ConversionType::TimeUpper(chr.try_into()?)
+ }
+ chr => {
+ return plan_err!("Invalid conversion type: {:?}", chr);
+ }
+ };
+
+ spec.conversion_type.validate(arg_type)?;
+ Ok((spec, &s[offset..]))
+}
+
+fn take_numeric_param(s: &str, zero: bool) -> (NumericParam, &str) {
+ match s.chars().next() {
+ Some(digit) if (if zero { '0'..='9' } else { '1'..='9' }).contains(&digit) => {
+ let mut s = s;
+ let mut w = 0;
+ loop {
+ match s.chars().next() {
+ Some(digit) if digit.is_ascii_digit() => {
+ w = 10 * w + (digit as i32 - '0' as i32);
+ }
+ _ => {
+ break;
+ }
+ }
+ s = &s[1..];
+ }
+ (NumericParam::Literal(w), s)
+ }
+ _ => (NumericParam::FromArgument, s),
+ }
+}
+
+impl ConversionSpecifier {
+ pub fn format(&self, string: &mut String, value: &ScalarValue) -> Result<()> {
+ match value {
+ ScalarValue::Boolean(value) => match self.conversion_type {
+ ConversionType::StringLower | ConversionType::StringUpper => {
+ self.format_string(string, &value.unwrap_or(false).to_string())
+ }
+
+ _ => self.format_boolean(string, value),
+ },
+ ScalarValue::Int8(value) => match (self.conversion_type, value) {
+ (ConversionType::DecInt, Some(value)) => {
+ self.format_signed(string, *value as i64)
+ }
+ (
+ ConversionType::HexIntLower
+ | ConversionType::HexIntUpper
+ | ConversionType::OctInt,
+ Some(value),
+ ) => self.format_unsigned(string, (*value as u8) as u64),
+ (ConversionType::CharLower | ConversionType::CharUpper, Some(value)) => {
+ self.format_char(string, *value as u8 as char)
+ }
+ (
+ ConversionType::StringLower | ConversionType::StringUpper,
+ Some(value),
+ ) => self.format_string(string, &value.to_string()),
+ (t, None) if t.supports_integer() => self.format_string(string, "null"),
+ _ => {
+ exec_err!(
+ "Invalid conversion type: {:?} for Int8",
+ self.conversion_type
+ )
+ }
+ },
+ ScalarValue::Int16(value) => match (self.conversion_type, value) {
+ (ConversionType::DecInt, Some(value)) => {
+ self.format_signed(string, *value as i64)
+ }
+ (ConversionType::CharLower | ConversionType::CharUpper, Some(value)) => {
+ self.format_char(
+ string,
+ char::from_u32((*value as u16) as u32).unwrap(),
+ )
+ }
+ (
+ ConversionType::HexIntLower
+ | ConversionType::HexIntUpper
+ | ConversionType::OctInt,
+ Some(value),
+ ) => self.format_unsigned(string, (*value as u16) as u64),
+ (
+ ConversionType::StringLower | ConversionType::StringUpper,
+ Some(value),
+ ) => self.format_string(string, &value.to_string()),
+ (t, None) if t.supports_integer() => self.format_string(string, "null"),
+ _ => {
+ exec_err!(
+ "Invalid conversion type: {:?} for Int16",
+ self.conversion_type
+ )
+ }
+ },
+ ScalarValue::Int32(value) => match (self.conversion_type, value) {
+ (ConversionType::DecInt, Some(value)) => {
+ self.format_signed(string, *value as i64)
+ }
+ (
+ ConversionType::HexIntLower
+ | ConversionType::HexIntUpper
+ | ConversionType::OctInt,
+ Some(value),
+ ) => self.format_unsigned(string, (*value as u32) as u64),
+ (ConversionType::CharLower | ConversionType::CharUpper, Some(value)) => {
+ self.format_char(string, char::from_u32(*value as u32).unwrap())
+ }
+ (
+ ConversionType::StringLower | ConversionType::StringUpper,
+ Some(value),
+ ) => self.format_string(string, &value.to_string()),
+ (t, None) if t.supports_integer() => self.format_string(string, "null"),
+ _ => {
+ exec_err!(
+ "Invalid conversion type: {:?} for Int32",
+ self.conversion_type
+ )
+ }
+ },
+ ScalarValue::Int64(value) => match (self.conversion_type, value) {
+ (ConversionType::DecInt, Some(value)) => {
+ self.format_signed(string, *value)
+ }
+ (
+ ConversionType::HexIntLower
+ | ConversionType::HexIntUpper
+ | ConversionType::OctInt,
+ Some(value),
+ ) => self.format_unsigned(string, *value as u64),
+ (ConversionType::CharLower | ConversionType::CharUpper, Some(value)) => {
+ self.format_char(
+ string,
+ char::from_u32((*value as u64) as u32).unwrap(),
+ )
+ }
+ (
+ ConversionType::StringLower | ConversionType::StringUpper,
+ Some(value),
+ ) => self.format_string(string, &value.to_string()),
+ (t, None) if t.supports_integer() => self.format_string(string, "null"),
+ _ => {
+ exec_err!(
+ "Invalid conversion type: {:?} for Int64",
+ self.conversion_type
+ )
+ }
+ },
+ ScalarValue::UInt8(value) => match (self.conversion_type, value) {
+ (
+ ConversionType::DecInt
+ | ConversionType::HexIntLower
+ | ConversionType::HexIntUpper
+ | ConversionType::OctInt,
+ Some(value),
+ ) => self.format_unsigned(string, *value as u64),
+ (ConversionType::CharLower | ConversionType::CharUpper, Some(value)) => {
+ self.format_char(string, *value as char)
+ }
+ (
+ ConversionType::StringLower | ConversionType::StringUpper,
+ Some(value),
+ ) => self.format_string(string, &value.to_string()),
+ (t, None) if t.supports_integer() => self.format_string(string, "null"),
+ _ => {
+ exec_err!(
+ "Invalid conversion type: {:?} for UInt8",
+ self.conversion_type
+ )
+ }
+ },
+ ScalarValue::UInt16(value) => match (self.conversion_type, value) {
+ (
+ ConversionType::DecInt
+ | ConversionType::HexIntLower
+ | ConversionType::HexIntUpper
+ | ConversionType::OctInt,
+ Some(value),
+ ) => self.format_unsigned(string, *value as u64),
+ (ConversionType::CharLower | ConversionType::CharUpper, Some(value)) => {
+ self.format_char(string, char::from_u32(*value as u32).unwrap())
+ }
+ (
+ ConversionType::StringLower | ConversionType::StringUpper,
+ Some(value),
+ ) => self.format_string(string, &value.to_string()),
+ (t, None) if t.supports_integer() => self.format_string(string, "null"),
+ _ => {
+ exec_err!(
+ "Invalid conversion type: {:?} for UInt16",
+ self.conversion_type
+ )
+ }
+ },
+ ScalarValue::UInt32(value) => match (self.conversion_type, value) {
+ (
+ ConversionType::DecInt
+ | ConversionType::HexIntLower
+ | ConversionType::HexIntUpper
+ | ConversionType::OctInt,
+ Some(value),
+ ) => self.format_unsigned(string, *value as u64),
+ (ConversionType::CharLower | ConversionType::CharUpper, Some(value)) => {
+ self.format_char(string, char::from_u32(*value).unwrap())
+ }
+ (
+ ConversionType::StringLower | ConversionType::StringUpper,
+ Some(value),
+ ) => self.format_string(string, &value.to_string()),
+ (t, None) if t.supports_integer() => self.format_string(string, "null"),
+ _ => {
+ exec_err!(
+ "Invalid conversion type: {:?} for UInt32",
+ self.conversion_type
+ )
+ }
+ },
+ ScalarValue::UInt64(value) => match (self.conversion_type, value) {
+ (
+ ConversionType::DecInt
+ | ConversionType::HexIntLower
+ | ConversionType::HexIntUpper
+ | ConversionType::OctInt,
+ Some(value),
+ ) => self.format_unsigned(string, *value),
+ (ConversionType::CharLower | ConversionType::CharUpper, Some(value)) => {
+ self.format_char(string, char::from_u32(*value as u32).unwrap())
+ }
+ (
+ ConversionType::StringLower | ConversionType::StringUpper,
+ Some(value),
+ ) => self.format_string(string, &value.to_string()),
+ (t, None) if t.supports_integer() => self.format_string(string, "null"),
+ _ => {
+ exec_err!(
+ "Invalid conversion type: {:?} for UInt64",
+ self.conversion_type
+ )
+ }
+ },
+ ScalarValue::Float16(value) => match (self.conversion_type, value) {
+ (
+ ConversionType::DecFloatLower
+ | ConversionType::SciFloatLower
+ | ConversionType::SciFloatUpper
+ | ConversionType::CompactFloatLower
+ | ConversionType::CompactFloatUpper,
+ Some(value),
+ ) => self.format_float(string, value.to_f64().unwrap()),
+ (
+ ConversionType::StringLower | ConversionType::StringUpper,
+ Some(value),
+ ) => self.format_string(string, &value.to_f32().unwrap().spark_string()),
+ (
+ ConversionType::HexFloatLower | ConversionType::HexFloatUpper,
+ Some(value),
+ ) => self.format_hex_float(string, value.to_f64().unwrap()),
+ (t, None) if t.supports_float() => self.format_string(string, "null"),
+ _ => {
+ exec_err!(
+ "Invalid conversion type: {:?} for Float16",
+ self.conversion_type
+ )
+ }
+ },
+ ScalarValue::Float32(value) => match (self.conversion_type, value) {
+ (
+ ConversionType::DecFloatLower
+ | ConversionType::SciFloatLower
+ | ConversionType::SciFloatUpper
+ | ConversionType::CompactFloatLower
+ | ConversionType::CompactFloatUpper,
+ Some(value),
+ ) => self.format_float(string, *value as f64),
+ (
+ ConversionType::StringLower | ConversionType::StringUpper,
+ Some(value),
+ ) => self.format_string(string, &value.spark_string()),
+ (
+ ConversionType::HexFloatLower | ConversionType::HexFloatUpper,
+ Some(value),
+ ) => self.format_hex_float(string, *value as f64),
+ (t, None) if t.supports_float() => self.format_string(string, "null"),
+ _ => {
+ exec_err!(
+ "Invalid conversion type: {:?} for Float32",
+ self.conversion_type
+ )
+ }
+ },
+ ScalarValue::Float64(value) => match (self.conversion_type, value) {
+ (
+ ConversionType::DecFloatLower
+ | ConversionType::SciFloatLower
+ | ConversionType::SciFloatUpper
+ | ConversionType::CompactFloatLower
+ | ConversionType::CompactFloatUpper,
+ Some(value),
+ ) => self.format_float(string, *value),
+ (
+ ConversionType::StringLower | ConversionType::StringUpper,
+ Some(value),
+ ) => self.format_string(string, &value.spark_string()),
+ (
+ ConversionType::HexFloatLower | ConversionType::HexFloatUpper,
+ Some(value),
+ ) => self.format_hex_float(string, *value),
+ (t, None) if t.supports_float() => self.format_string(string, "null"),
+ _ => {
+ exec_err!(
+ "Invalid conversion type: {:?} for Float64",
+ self.conversion_type
+ )
+ }
+ },
+ ScalarValue::Utf8(value) => {
+ let value: &str = match value {
+ Some(value) => value.as_str(),
+ None => "null",
+ };
+ if matches!(
+ self.conversion_type,
+ ConversionType::StringLower | ConversionType::StringUpper
+ ) {
+ self.format_string(string, value)
+ } else {
+ exec_err!(
+ "Invalid conversion type: {:?} for Utf8",
+ self.conversion_type
+ )
+ }
+ }
+ ScalarValue::LargeUtf8(value) => {
+ let value: &str = match value {
+ Some(value) => value.as_str(),
+ None => "null",
+ };
+ if matches!(
+ self.conversion_type,
+ ConversionType::StringLower | ConversionType::StringUpper
+ ) {
+ self.format_string(string, value)
+ } else {
+ exec_err!(
+ "Invalid conversion type: {:?} for LargeUtf8",
+ self.conversion_type
+ )
+ }
+ }
+ ScalarValue::Utf8View(value) => {
+ let value: &str = match value {
+ Some(value) => value.as_str(),
+ None => "null",
+ };
+ self.format_string(string, value)
+ }
+ ScalarValue::Decimal128(value, _, scale) => {
+ match (self.conversion_type, value) {
+ (
+ ConversionType::DecFloatLower
+ | ConversionType::SciFloatLower
+ | ConversionType::SciFloatUpper
+ | ConversionType::CompactFloatLower
+ | ConversionType::CompactFloatUpper,
+ Some(value),
+ ) => self.format_decimal(string, value.to_string(), *scale as i64),
+ (
+ ConversionType::StringLower | ConversionType::StringUpper,
+ Some(value),
+ ) => self.format_string(string, &value.to_string()),
+ (t, None) if t.supports_decimal() => {
+ self.format_string(string, "null")
+ }
+
+ _ => {
+ exec_err!(
+ "Invalid conversion type: {:?} for Decimal128",
+ self.conversion_type
+ )
+ }
+ }
+ }
+ ScalarValue::Decimal256(value, _, scale) => {
+ match (self.conversion_type, value) {
+ (
+ ConversionType::DecFloatLower
+ | ConversionType::SciFloatLower
+ | ConversionType::SciFloatUpper
+ | ConversionType::CompactFloatLower
+ | ConversionType::CompactFloatUpper,
+ Some(value),
+ ) => self.format_decimal(string, value.to_string(), *scale as i64),
+ (
+ ConversionType::StringLower | ConversionType::StringUpper,
+ Some(value),
+ ) => self.format_string(string, &value.to_string()),
+ (t, None) if t.supports_decimal() => {
+ self.format_string(string, "null")
+ }
+
+ _ => {
+ exec_err!(
+ "Invalid conversion type: {:?} for Decimal256",
+ self.conversion_type
+ )
+ }
+ }
+ }
+
+ ScalarValue::Time32Second(value) => match (self.conversion_type, value) {
+ (
+ ConversionType::TimeLower(_) | ConversionType::TimeUpper(_),
+ Some(value),
+ ) => self.format_time(string, *value as i64 * 1000000000, &None),
+ (
+ ConversionType::StringLower | ConversionType::StringUpper,
+ Some(value),
+ ) => self.format_string(string, &value.to_string()),
+ (t, None) if t.supports_time() => self.format_string(string, "null"),
+ _ => {
+ exec_err!(
+ "Invalid conversion type: {:?} for Time32Second",
+ self.conversion_type
+ )
+ }
+ },
+ ScalarValue::Time32Millisecond(value) => {
+ match (self.conversion_type, value) {
+ (
+ ConversionType::TimeLower(_) | ConversionType::TimeUpper(_),
+ Some(value),
+ ) => self.format_time(string, *value as i64 * 1000000, &None),
+ (
+ ConversionType::StringLower | ConversionType::StringUpper,
+ Some(value),
+ ) => self.format_string(string, &value.to_string()),
+ (t, None) if t.supports_time() => self.format_string(string, "null"),
+ _ => {
+ exec_err!(
+ "Invalid conversion type: {:?} for Time32Millisecond",
+ self.conversion_type
+ )
+ }
+ }
+ }
+ ScalarValue::Time64Microsecond(value) => {
+ match (self.conversion_type, value) {
+ (
+ ConversionType::TimeLower(_) | ConversionType::TimeUpper(_),
+ Some(value),
+ ) => self.format_time(string, *value * 1000, &None),
+ (
+ ConversionType::StringLower | ConversionType::StringUpper,
+ Some(value),
+ ) => self.format_string(string, &value.to_string()),
+ (t, None) if t.supports_time() => self.format_string(string, "null"),
+ _ => {
+ exec_err!(
+ "Invalid conversion type: {:?} for Time64Microsecond",
+ self.conversion_type
+ )
+ }
+ }
+ }
+ ScalarValue::Time64Nanosecond(value) => match (self.conversion_type, value) {
+ (
+ ConversionType::TimeLower(_) | ConversionType::TimeUpper(_),
+ Some(value),
+ ) => self.format_time(string, *value, &None),
+ (
+ ConversionType::StringLower | ConversionType::StringUpper,
+ Some(value),
+ ) => self.format_string(string, &value.to_string()),
+ (t, None) if t.supports_time() => self.format_string(string, "null"),
+ _ => {
+ exec_err!(
+ "Invalid conversion type: {:?} for Time64Nanosecond",
+ self.conversion_type
+ )
+ }
+ },
+ ScalarValue::TimestampSecond(value, zone) => {
+ match (self.conversion_type, value) {
+ (
+ ConversionType::TimeLower(_) | ConversionType::TimeUpper(_),
+ Some(value),
+ ) => self.format_time(string, value * 1000000000, zone),
+ (
+ ConversionType::StringLower | ConversionType::StringUpper,
+ Some(value),
+ ) => self.format_string(string, &value.to_string()),
+ (t, None) if t.supports_time() => self.format_string(string, "null"),
+ _ => {
+ exec_err!(
+ "Invalid conversion type: {:?} for TimestampSecond",
+ self.conversion_type
+ )
+ }
+ }
+ }
+ ScalarValue::TimestampMillisecond(value, zone) => {
+ match (self.conversion_type, value) {
+ (
+ ConversionType::TimeLower(_) | ConversionType::TimeUpper(_),
+ Some(value),
+ ) => self.format_time(string, *value * 1000000, zone),
+ (
+ ConversionType::StringLower | ConversionType::StringUpper,
+ Some(value),
+ ) => self.format_string(string, &value.to_string()),
+
+ (t, None) if t.supports_time() => self.format_string(string, "null"),
+ _ => {
+ exec_err!(
+ "Invalid conversion type: {:?} for TimestampMillisecond",
+ self.conversion_type
+ )
+ }
+ }
+ }
+ ScalarValue::TimestampMicrosecond(value, zone) => {
+ match (self.conversion_type, value) {
+ (
+ ConversionType::TimeLower(_) | ConversionType::TimeUpper(_),
+ Some(value),
+ ) => self.format_time(string, value * 1000, zone),
+ (
+ ConversionType::StringLower | ConversionType::StringUpper,
+ Some(value),
+ ) => self.format_string(string, &value.to_string()),
+ (t, None) if t.supports_time() => self.format_string(string, "null"),
+ _ => {
+ exec_err!(
+ "Invalid conversion type: {:?} for timestampmicrosecond",
+ self.conversion_type
+ )
+ }
+ }
+ }
+
+ ScalarValue::TimestampNanosecond(value, zone) => {
+ match (self.conversion_type, value) {
+ (
+ ConversionType::TimeLower(_) | ConversionType::TimeUpper(_),
+ Some(value),
+ ) => self.format_time(string, *value, zone),
+ (
+ ConversionType::StringLower | ConversionType::StringUpper,
+ Some(value),
+ ) => self.format_string(string, &value.to_string()),
+ (t, None) if t.supports_time() => self.format_string(string, "null"),
+ _ => {
+ exec_err!(
+ "Invalid conversion type: {:?} for TimestampNanosecond",
+ self.conversion_type
+ )
+ }
+ }
+ }
+ ScalarValue::Date32(value) => match (self.conversion_type, value) {
+ (
+ ConversionType::TimeLower(_) | ConversionType::TimeUpper(_),
+ Some(value),
+ ) => self.format_date(string, *value as i64),
+ (
+ ConversionType::StringLower | ConversionType::StringUpper,
+ Some(value),
+ ) => self.format_string(string, &value.to_string()),
+ (t, None) if t.supports_time() => self.format_string(string, "null"),
+ _ => {
+ exec_err!(
+ "Invalid conversion type: {:?} for Date32",
+ self.conversion_type
+ )
+ }
+ },
+ ScalarValue::Date64(value) => match (self.conversion_type, value) {
+ (
+ ConversionType::TimeLower(_) | ConversionType::TimeUpper(_),
+ Some(value),
+ ) => self.format_date(string, *value),
+ (
+ ConversionType::StringLower | ConversionType::StringUpper,
+ Some(value),
+ ) => self.format_string(string, &value.to_string()),
+ (t, None) if t.supports_time() => self.format_string(string, "null"),
+ _ => {
+ exec_err!(
+ "Invalid conversion type: {:?} for Date64",
+ self.conversion_type
+ )
+ }
+ },
+ ScalarValue::Null => {
+ let value = "null".to_string();
+ self.format_string(string, &value)
+ }
+ _ => exec_err!("Invalid scalar value: {:?}", value),
+ }
+ }
+
+ fn format_hex_float(&self, writer: &mut String, value: f64) -> Result<()> {
+ // Handle special cases first
+ let (sign, raw_exponent, mantissa) = value.to_parts();
+ let is_subnormal = raw_exponent == 0;
+
+ let precision = match self.precision {
+ NumericParam::FromArgument => None,
+ NumericParam::Literal(p) => Some(p),
+ };
+
+ // Determine if we need to normalize subnormal numbers
+ // Only normalize when precision is specified and less than full mantissa width
+ let mantissa_hex_digits = f64::MANTISSA_BITS.div_ceil(4); // 13 for f64
+ let should_normalize = is_subnormal
+ && precision.is_some()
+ && precision.unwrap() < mantissa_hex_digits as i32;
+
+ let (value, raw_exponent, mantissa) = if should_normalize {
+ let value = value * f64::SCALEUP;
+ let (_, raw_exponent, mantissa) = value.to_parts();
+ (value, raw_exponent, mantissa)
+ } else {
+ (value, raw_exponent, mantissa)
+ };
+
+ let mut temp = String::new();
+
+ let sign_char = if sign {
+ "-"
+ } else if self.force_sign {
+ "+"
+ } else if self.space_sign {
+ " "
+ } else {
+ ""
+ };
+ match value.category() {
+ FpCategory::Nan => {
+ write!(&mut temp, "NaN")?;
+ }
+ FpCategory::Infinite => {
+ write!(&mut temp, "{sign_char}Infinity")?;
+ }
+ FpCategory::Zero => {
+ write!(&mut temp, "{sign_char}0x0.0p0")?;
+ }
+ _ => {
+ let bias = i32::from(f64::EXPONENT_BIAS);
+ // Calculate actual exponent
+ // For subnormal numbers, the exponent is 1 - bias (not 0 - bias)
+ let exponent = if is_subnormal && !should_normalize {
+ 1 - bias
+ } else {
+ raw_exponent as i32 - bias
+ };
+
+ // Handle precision for rounding
+ let final_mantissa = if let Some(p) = precision {
+ if p == 0 {
+ // For precision 0, we still need at least 1 hex digit
+ // Round to the nearest integer mantissa value
+ let shift_distance = f64::MANTISSA_BITS as i32 - 4; // Keep 1 hex digit (4 bits)
+ let shifted = mantissa >> shift_distance;
+ let rounding_bits = mantissa & ((1u64 << shift_distance) - 1);
+ let round_bit = 1u64 << (shift_distance - 1);
+
+ // Round to nearest, ties to even
+ if rounding_bits > round_bit
+ || (rounding_bits == round_bit && (shifted & 1) != 0)
+ {
+ (shifted + 1) << shift_distance
+ } else {
+ shifted << shift_distance
+ }
+ } else {
+ // Apply rounding based on precision
+ let precision_bits = p * 4; // Each hex digit is 4 bits
+ let keep_bits = f64::MANTISSA_BITS as i32;
+ let shift_distance = keep_bits - precision_bits;
+
+ if shift_distance > 0 {
+ let shifted = mantissa >> shift_distance;
+ let rounding_bits = mantissa & ((1u64 << shift_distance) - 1);
+ let round_bit = 1u64 << (shift_distance - 1);
+
+ // Round to nearest, ties to even
+ if rounding_bits > round_bit
+ || (rounding_bits == round_bit && (shifted & 1) != 0)
+ {
+ (shifted + 1) << shift_distance
+ } else {
+ shifted << shift_distance
+ }
+ } else {
+ mantissa
+ }
+ }
+ } else {
+ mantissa
+ };
+
+ if is_subnormal && !should_normalize {
+ // Original subnormal format: 0x0.xxxp-1022
+ if precision.is_some() {
+ // precision >= 13, show as subnormal
+ let full_hex = format!(
+ "{:0width$x}",
+ final_mantissa,
+ width = mantissa_hex_digits as usize
+ );
+ write!(&mut temp, "{sign_char}0x0.{full_hex}p{exponent}")?;
+ } else {
+ // No precision specified, show full subnormal
+ let hex_digits = format!(
+ "{:0width$x}",
+ final_mantissa,
+ width = mantissa_hex_digits as usize
+ );
+ write!(&mut temp, "{sign_char}0x0.{hex_digits}p{exponent}")?;
+ }
+ } else {
+ // Normal format or normalized subnormal: 0x1.xxxpN
+ if let Some(p) = precision {
+ let p = if p == 0 { 1 } else { p };
+ let hex_digits = format!("{final_mantissa:x}");
+ let formatted_digits = if p as usize >= hex_digits.len() {
+ // Pad with zeros to match precision
+ format!("{:0<width$}", hex_digits, width = p as usize)
+ } else {
+ hex_digits[..p as usize].to_string()
+ };
+ write!(
+ &mut temp,
+ "{sign_char}0x1.{formatted_digits}p{exponent}"
+ )?;
+ } else {
+ // Default: show all significant digits
+ let mut hex_digits = format!("{final_mantissa:x}");
+ hex_digits = trim_trailing_0s_hex(&hex_digits).to_owned();
+ if hex_digits.is_empty() {
+ write!(&mut temp, "{sign_char}0x1.0p{exponent}")?;
+ } else {
+ write!(&mut temp, "{sign_char}0x1.{hex_digits}p{exponent}")?;
+ }
+ }
+ }
+ if should_normalize {
+ let (prefix, exp) = temp.split_once('p').unwrap();
+ let iexp = exp.parse::<i32>().unwrap() - f64::SCALEUP_POWER as i32;
+ temp = format!("{prefix}p{iexp}");
+ }
+ }
+ };
+
+ if self.conversion_type.is_upper() {
+ temp = temp.to_ascii_uppercase();
+ }
+
+ let NumericParam::Literal(width) = self.width else {
+ writer.push_str(&temp);
+ return Ok(());
+ };
+ if self.left_adj {
+ writer.push_str(&temp);
+ for _ in temp.len()..width as usize {
+ writer.push(' ');
+ }
+ } else if self.zero_pad && value.is_finite() {
+ let delimiter = if self.conversion_type.is_upper() {
+ "0X"
+ } else {
+ "0x"
+ };
+ let (prefix, suffix) = temp.split_once(delimiter).unwrap();
+ writer.push_str(prefix);
+ writer.push_str(delimiter);
+ for _ in temp.len()..width as usize {
+ writer.push('0');
+ }
+ writer.push_str(suffix);
+ } else {
+ while temp.len() < width as usize {
+ temp = " ".to_owned() + &temp;
+ }
+ writer.push_str(&temp);
+ };
+ Ok(())
+ }
+
+ fn format_char(&self, writer: &mut String, value: char) -> Result<()> {
+ let upper = self.conversion_type.is_upper();
+ match self.conversion_type {
+ ConversionType::CharLower | ConversionType::CharUpper => {
+ let NumericParam::Literal(width) = self.width else {
+ if upper {
+ writer.push(value.to_ascii_uppercase());
+ } else {
+ writer.push(value);
+ }
+ return Ok(());
+ };
+
+ let start_len = writer.len();
+ if self.left_adj {
+ if upper {
+ writer.push(value.to_ascii_uppercase());
+ } else {
+ writer.push(value);
+ }
+ while writer.len() - start_len < width as usize {
+ writer.push(' ');
+ }
+ } else {
+ while writer.len() - start_len + value.len_utf8() < width as usize {
+ writer.push(' ');
+ }
+ if upper {
+ writer.push(value.to_ascii_uppercase());
+ } else {
+ writer.push(value);
+ }
+ }
+ Ok(())
+ }
+ _ => exec_err!(
+ "Invalid conversion type: {:?} for char",
+ self.conversion_type
+ ),
+ }
+ }
+
+ fn format_boolean(&self, writer: &mut String, value: &Option<bool>) -> Result<()> {
+ let value = value.unwrap_or(false);
+
+ let formatted = match self.conversion_type {
+ ConversionType::BooleanUpper => {
+ if value {
+ "TRUE"
+ } else {
+ "FALSE"
+ }
+ }
+ ConversionType::BooleanLower => {
+ if value {
+ "true"
+ } else {
+ "false"
+ }
+ }
+ _ => {
+ return exec_err!(
+ "Invalid conversion type: {:?} for boolean array",
+ self.conversion_type
+ )
+ }
+ };
+ self.format_str(writer, formatted)
+ }
+
+ fn format_float(&self, writer: &mut String, value: f64) -> Result<()> {
+ let mut prefix = String::new();
+ let mut suffix = String::new();
+ let mut number = String::new();
+ let upper = self.conversion_type.is_upper();
+
+ // set up the sign
+ if value.is_sign_negative() {
+ if self.negative_in_parentheses {
+ prefix.push('(');
+ suffix.push(')');
+ } else {
+ prefix.push('-');
+ }
+ } else if self.space_sign {
+ prefix.push(' ');
+ } else if self.force_sign {
+ prefix.push('+');
+ }
+
+ if value.is_finite() {
+ let mut use_scientific = false;
+ let mut strip_trailing_0s = false;
+ let mut abs = value.abs();
+ let mut exponent = abs.log10().floor() as i32;
+ let mut precision = match self.precision {
+ NumericParam::Literal(p) => p,
+ _ => 6,
+ };
+ match self.conversion_type {
+ ConversionType::DecFloatLower => {
+ // default
+ }
+ ConversionType::SciFloatLower => {
+ use_scientific = true;
+ }
+ ConversionType::SciFloatUpper => {
+ use_scientific = true;
+ }
+ ConversionType::CompactFloatLower | ConversionType::CompactFloatUpper => {
+ strip_trailing_0s = true;
+ if precision == 0 {
+ precision = 1;
+ }
+ // exponent signifies significant digits - we must round now
+ // to (re)calculate the exponent
+ let rounding_factor =
+ 10.0_f64.powf((precision - 1 - exponent) as f64);
+ let rounded_fixed = (abs * rounding_factor).round();
+ abs = rounded_fixed / rounding_factor;
+ exponent = abs.log10().floor() as i32;
+ if exponent < -4 || exponent >= precision {
+ use_scientific = true;
+ precision -= 1;
+ } else {
+ // precision specifies the number of significant digits
+ precision -= 1 + exponent;
+ }
+ }
+ _ => {
+ return exec_err!(
+ "Invalid conversion type: {:?} for float",
+ self.conversion_type
+ )
+ }
+ }
+
+ if use_scientific {
+ // Manual scientific notation formatting for uppercase E
+ let mantissa = abs / 10.0_f64.powf(exponent as f64);
+ let exp_char = if upper { 'E' } else { 'e' };
+ number = format!("{mantissa:.prec$}", prec = precision as usize);
+ if strip_trailing_0s {
+ number = trim_trailing_0s(&number).to_owned();
+ }
+ number = format!("{number}{exp_char}{exponent:+03}");
+ } else {
+ number = format!("{abs:.prec$}", prec = precision as usize);
+ if strip_trailing_0s {
+ number = trim_trailing_0s(&number).to_owned();
+ }
+ }
+ if self.alt_form && !number.contains('.') {
+ number += ".";
+ }
+ } else {
+ // not finite
+ match self.conversion_type {
+ ConversionType::DecFloatLower
+ | ConversionType::SciFloatLower
+ | ConversionType::CompactFloatLower => {
+ if value.is_infinite() {
+ number.push_str("Infinity")
+ } else {
+ number.push_str("NaN")
+ }
+ }
+ ConversionType::SciFloatUpper | ConversionType::CompactFloatUpper => {
+ if value.is_infinite() {
+ number.push_str("INFINITY")
+ } else {
+ number.push_str("NAN")
+ }
+ }
+ _ => {
+ return exec_err!(
+ "Invalid conversion type: {:?} for float",
+ self.conversion_type
+ )
+ }
+ }
+ }
+ // Take care of padding
+ let NumericParam::Literal(width) = self.width else {
+ writer.push_str(&prefix);
+ writer.push_str(&number);
+ writer.push_str(&suffix);
+ return Ok(());
+ };
+ if self.left_adj {
+ let mut full_num = prefix + &number + &suffix;
+ while full_num.len() < width as usize {
+ full_num.push(' ');
+ }
+ writer.push_str(&full_num);
+ } else if self.zero_pad && value.is_finite() {
+ while prefix.len() + number.len() + suffix.len() < width as usize {
+ prefix.push('0');
+ }
+ writer.push_str(&prefix);
+ writer.push_str(&number);
+ writer.push_str(&suffix);
+ } else {
+ let mut full_num = prefix + &number + &suffix;
+ while full_num.len() < width as usize {
+ full_num = " ".to_owned() + &full_num;
+ }
+ writer.push_str(&full_num);
+ };
+
+ Ok(())
+ }
+
+ fn format_signed(&self, writer: &mut String, value: i64) -> Result<()> {
+ let negative = value < 0;
+ let abs_val = value.abs();
+
+ let (sign_prefix, sign_suffix) = if negative && self.negative_in_parentheses {
+ ("(".to_owned(), ")".to_owned())
+ } else if negative {
+ ("-".to_owned(), "".to_owned())
+ } else if self.force_sign {
+ ("+".to_owned(), "".to_owned())
+ } else if self.space_sign {
+ (" ".to_owned(), "".to_owned())
+ } else {
+ ("".to_owned(), "".to_owned())
+ };
+
+ let mut mod_spec = *self;
+ mod_spec.width = match self.width {
+ NumericParam::Literal(w) => NumericParam::Literal(
+ w - sign_prefix.len() as i32 - sign_suffix.len() as i32,
+ ),
+ _ => NumericParam::FromArgument,
+ };
+ let mut formatted = String::new();
+ mod_spec.format_unsigned(&mut formatted, abs_val as u64)?;
+ // put the sign a after any leading spaces
+ let mut actual_number = &formatted[0..];
+ let mut leading_spaces = &formatted[0..0];
+ if let Some(first_non_space) = formatted.find(|c| c != ' ') {
+ actual_number = &formatted[first_non_space..];
+ leading_spaces = &formatted[0..first_non_space];
+ }
+ write!(
+ writer,
+ "{}{}{}{}",
+ leading_spaces.to_owned(),
+ sign_prefix,
+ actual_number,
+ sign_suffix
+ )
+ .map_err(|e| exec_datafusion_err!("Write error: {}", e))?;
+ Ok(())
+ }
+
+ fn format_unsigned(&self, writer: &mut String, value: u64) -> Result<()> {
+ let mut s = String::new();
+ let mut alt_prefix = "";
+ match self.conversion_type {
+ ConversionType::DecInt => {
+ let num_str = format!("{value}");
+ if self.grouping_separator {
+ // Add thousands separators
+ let mut result = String::new();
+ let chars: Vec<char> = num_str.chars().collect();
+ for (i, c) in chars.iter().enumerate() {
+ if i > 0 && (chars.len() - i).is_multiple_of(3) {
+ result.push(',');
+ }
+ result.push(*c);
+ }
+ s = result;
+ } else {
+ s = num_str;
+ }
+ }
+ ConversionType::HexIntLower => {
+ alt_prefix = "0x";
+ write!(&mut s, "{value:x}")
+ .map_err(|e| exec_datafusion_err!("Write error: {}", e))?;
+ }
+ ConversionType::HexIntUpper => {
+ alt_prefix = "0X";
+ write!(&mut s, "{value:X}")
+ .map_err(|e| exec_datafusion_err!("Write error: {}", e))?;
+ }
+ ConversionType::OctInt => {
+ alt_prefix = "0";
+ write!(&mut s, "{value:o}")
+ .map_err(|e| exec_datafusion_err!("Write error: {}", e))?;
+ }
+ _ => {
+ return exec_err!(
+ "Invalid conversion type: {:?} for u64",
+ self.conversion_type
+ )
+ }
+ }
+ let mut prefix = if self.alt_form {
+ alt_prefix.to_owned()
+ } else {
+ String::new()
+ };
+
+ let formatted = if let NumericParam::Literal(width) = self.width {
+ if self.left_adj {
+ let mut num_str = prefix + &s;
+ while num_str.len() < width as usize {
+ num_str.push(' ');
+ }
+ num_str
+ } else if self.zero_pad {
+ while prefix.len() + s.len() < width as usize {
+ prefix.push('0');
+ }
+ prefix + &s
+ } else {
+ let mut num_str = prefix + &s;
+ while num_str.len() < width as usize {
+ num_str = " ".to_owned() + &num_str;
+ }
+ num_str
+ }
+ } else {
+ prefix + &s
+ };
+ write!(writer, "{formatted}")
+ .map_err(|e| exec_datafusion_err!("Write error: {}", e))?;
+ Ok(())
+ }
+
+ fn format_str(&self, writer: &mut String, value: &str) -> Result<()> {
+ // Take care of precision, putting the truncated string in `content`
+ let precision: usize = match self.precision {
+ NumericParam::Literal(p) => p,
+ _ => i32::MAX,
+ }
+ .try_into()
+ .unwrap_or_default();
+ let content_len = {
+ let mut content_len = precision.min(value.len());
+ while !value.is_char_boundary(content_len) {
+ content_len -= 1;
+ }
+ content_len
+ };
+ let content = &value[..content_len];
+
+ // Pad to width if needed, putting the padded string in `s`
+
+ if let NumericParam::Literal(width) = self.width {
+ let start_len = writer.len();
+ if self.left_adj {
+ writer.push_str(content);
+ while writer.len() - start_len < width as usize {
+ writer.push(' ');
+ }
+ } else {
+ while writer.len() - start_len + content.len() < width as usize {
+ writer.push(' ');
+ }
+ writer.push_str(content);
+ }
+ } else {
+ writer.push_str(content);
+ }
+ Ok(())
+ }
+
+ fn format_string(&self, writer: &mut String, value: &str) -> Result<()> {
+ if self.conversion_type.is_upper() {
+ let upper = value.to_ascii_uppercase();
+ self.format_str(writer, &upper)
+ } else {
+ self.format_str(writer, value)
+ }
+ }
+
+ fn format_decimal(
+ &self,
+ writer: &mut String,
+ value: String,
+ scale: i64,
+ ) -> Result<()> {
+ let mut prefix = String::new();
+ let upper = self.conversion_type.is_upper();
+
+ // Parse as BigDecimal
+ let decimal = value
+ .parse::<BigInt>()
+ .map_err(|e| exec_datafusion_err!("Failed to parse decimal: {}", e))?;
+ let decimal = BigDecimal::from_bigint(decimal, scale);
+
+ // Handle sign
+ let is_negative = decimal.sign() == Sign::Minus;
+ let abs_decimal = decimal.abs();
+
+ if is_negative {
+ prefix.push('-');
+ } else if self.space_sign {
+ prefix.push(' ');
+ } else if self.force_sign {
+ prefix.push('+');
+ }
+
+ let exp_symb = if upper { 'E' } else { 'e' };
+ let mut strip_trailing_0s = false;
+
+ // Get precision setting
+ let mut precision = match self.precision {
+ NumericParam::Literal(p) => p,
+ _ => 6,
+ };
+
+ let number = match self.conversion_type {
+ ConversionType::DecFloatLower => {
+ // Format as fixed-point decimal
+ self.format_decimal_fixed(&abs_decimal, precision, strip_trailing_0s)?
+ }
+ ConversionType::SciFloatLower => self.format_decimal_scientific(
+ &abs_decimal,
+ precision,
+ 'e',
+ strip_trailing_0s,
+ )?,
+ ConversionType::SciFloatUpper => self.format_decimal_scientific(
+ &abs_decimal,
+ precision,
+ 'E',
+ strip_trailing_0s,
+ )?,
+ ConversionType::CompactFloatLower | ConversionType::CompactFloatUpper => {
+ strip_trailing_0s = true;
+ if precision == 0 {
+ precision = 1;
+ }
+ // Determine if we should use scientific notation
+ let log10_val = abs_decimal.to_f64().map(|f| f.log10()).unwrap_or(0.0);
+ if log10_val < -4.0 || log10_val >= precision as f64 {
+ self.format_decimal_scientific(
+ &abs_decimal,
+ precision - 1,
+ exp_symb,
+ strip_trailing_0s,
+ )?
+ } else {
+ self.format_decimal_fixed(
+ &abs_decimal,
+ precision - 1 - log10_val.floor() as i32,
+ strip_trailing_0s,
+ )?
+ }
+ }
+ _ => {
+ return exec_err!(
+ "Invalid conversion type: {:?} for decimal",
+ self.conversion_type
+ )
+ }
+ };
+
+ // Handle padding
+ let NumericParam::Literal(width) = self.width else {
+ writer.push_str(&prefix);
+ writer.push_str(&number);
+ return Ok(());
+ };
+
+ if self.left_adj {
+ let mut full_num = prefix + &number;
+ while full_num.len() < width as usize {
+ full_num.push(' ');
+ }
+ writer.push_str(&full_num);
+ } else if self.zero_pad {
+ while prefix.len() + number.len() < width as usize {
+ prefix.push('0');
+ }
+ writer.push_str(&prefix);
+ writer.push_str(&number);
+ } else {
+ let mut full_num = prefix + &number;
+ while full_num.len() < width as usize {
+ full_num = " ".to_owned() + &full_num;
+ }
+ writer.push_str(&full_num);
+ }
+
+ Ok(())
+ }
+
+ fn format_decimal_fixed(
+ &self,
+ decimal: &BigDecimal,
+ precision: i32,
+ strip_trailing_0s: bool,
+ ) -> Result<String> {
+ if precision <= 0 {
+ Ok(decimal.round(0).to_string())
+ } else {
+ // Use BigDecimal's with_scale method for precise decimal formatting
+ let scaled = decimal.round(precision as i64);
+ let mut number = scaled.to_string();
+ if strip_trailing_0s {
+ number = trim_trailing_0s(&number).to_owned();
+ }
+ Ok(number)
+ }
+ }
+
+ fn format_decimal_scientific(
+ &self,
+ decimal: &BigDecimal,
+ precision: i32,
+ exp_char: char,
+ strip_trailing_0s: bool,
+ ) -> Result<String> {
+ // Convert to f64 for scientific notation (may lose precision for very large numbers)
+ let float_val = decimal.to_f64().unwrap_or(0.0);
+ if float_val == 0.0 {
+ return Ok(format!("0{exp_char}+00"));
+ }
+
+ let abs_val = float_val.abs();
+ let exponent = abs_val.log10().floor() as i32;
+ let mantissa = abs_val / 10.0_f64.powf(exponent as f64);
+
+ let mut number = if precision <= 0 {
+ format!("{mantissa:.0}")
+ } else {
+ format!("{mantissa:.prec$}", prec = precision as usize)
+ };
+
+ if strip_trailing_0s {
+ number = trim_trailing_0s(&number).to_owned();
+ }
+
+ Ok(format!("{number}{exp_char}{exponent:+03}"))
+ }
+
+ fn format_time(
+ &self,
+ writer: &mut String,
+ timestamp_nanos: i64,
+ timezone: &Option<Arc<str>>,
+ ) -> Result<()> {
+ let upper = self.conversion_type.is_upper();
+ match &self.conversion_type {
+ ConversionType::TimeLower(time_format)
+ | ConversionType::TimeUpper(time_format) => {
+ let formatted =
+ self.format_time_component(timestamp_nanos, *time_format, timezone)?;
+ let result = if upper {
+ formatted.to_uppercase()
+ } else {
+ formatted
+ };
+ write!(writer, "{result}")
+ .map_err(|e| exec_datafusion_err!("Write error: {}", e))?;
+ Ok(())
+ }
+ _ => exec_err!(
+ "Invalid conversion type for time: {:?}",
+ self.conversion_type
+ ),
+ }
+ }
+
+ fn format_date(&self, writer: &mut String, date_days: i64) -> Result<()> {
+ // Convert days since epoch to timestamp in nanoseconds
+ let timestamp_nanos = date_days * 24 * 60 * 60 * 1_000_000_000;
+ self.format_time(writer, timestamp_nanos, &None)
+ }
+
+ fn format_time_component(
+ &self,
+ timestamp_nanos: i64,
+ time_format: TimeFormat,
+ _timezone: &Option<Arc<str>>,
+ ) -> Result<String> {
+ // Convert nanoseconds to seconds and nanoseconds remainder
+ let secs = timestamp_nanos / 1_000_000_000;
+ let nanos = (timestamp_nanos % 1_000_000_000) as u32;
+
+ // Create DateTime from timestamp
+ let dt = DateTime::<Utc>::from_timestamp(secs, nanos).ok_or_else(|| {
+ exec_datafusion_err!("Invalid timestamp: {}", timestamp_nanos)
+ })?;
+
+ match time_format {
+ TimeFormat::HUpper => Ok(format!("{:02}", dt.hour())),
+ TimeFormat::IUpper => {
+ let hour_12 = match dt.hour12() {
+ (true, h) => h, // PM
+ (false, h) => h, // AM
+ };
+ Ok(format!("{hour_12:02}"))
+ }
+ TimeFormat::KLower => Ok(format!("{}", dt.hour())),
+ TimeFormat::LLower => {
+ let hour_12 = match dt.hour12() {
+ (true, h) => h, // PM
+ (false, h) => h, // AM
+ };
+ Ok(format!("{hour_12}"))
+ }
+ TimeFormat::MUpper => Ok(format!("{:02}", dt.minute())),
+ TimeFormat::SUpper => Ok(format!("{:02}", dt.second())),
+ TimeFormat::LUpper => Ok(format!("{:03}", dt.timestamp_millis() % 1000)),
+ TimeFormat::NUpper => Ok(format!("{:09}", dt.nanosecond())),
+ TimeFormat::PLower => {
+ let (is_pm, _) = dt.hour12();
+ Ok(if is_pm {
+ "pm".to_string()
+ } else {
+ "am".to_string()
+ })
+ }
+ TimeFormat::ZLower => Ok("+0000".to_string()), // UTC timezone offset
+ TimeFormat::ZUpper => Ok("UTC".to_string()), // UTC timezone name
+ TimeFormat::SLower => Ok(format!("{}", dt.timestamp())),
+ TimeFormat::QUpper => Ok(format!("{}", dt.timestamp_millis())),
+ TimeFormat::BUpper => Ok(dt.format("%B").to_string()), // Full month name
+ TimeFormat::BLower => Ok(dt.format("%b").to_string()), // Abbreviated month name
+ TimeFormat::AUpper => Ok(dt.format("%A").to_string()), // Full weekday name
+ TimeFormat::ALower => Ok(dt.format("%a").to_string()), // Abbreviated weekday name
+ TimeFormat::CUpper => Ok(format!("{:02}", dt.year() / 100)),
+ TimeFormat::YUpper => Ok(format!("{:04}", dt.year())),
+ TimeFormat::YLower => Ok(format!("{:02}", dt.year() % 100)),
+ TimeFormat::JLower => Ok(format!("{:03}", dt.ordinal())), // Day of year
+ TimeFormat::MLower => Ok(format!("{:02}", dt.month())),
+ TimeFormat::DLower => Ok(format!("{:02}", dt.day())),
+ TimeFormat::ELower => Ok(format!("{}", dt.day())),
+ TimeFormat::RUpper => Ok(dt.format("%H:%M").to_string()),
+ TimeFormat::TUpper => Ok(dt.format("%H:%M:%S").to_string()),
+ TimeFormat::RLower => {
+ let (is_pm, hour_12) = dt.hour12();
+ let am_pm = if is_pm { "PM" } else { "AM" };
+ Ok(format!(
+ "{:02}:{:02}:{:02} {}",
+ hour_12,
+ dt.minute(),
+ dt.second(),
+ am_pm
+ ))
+ }
+ TimeFormat::DUpper => Ok(dt.format("%m/%d/%y").to_string()),
+ TimeFormat::FUpper => Ok(dt.format("%Y-%m-%d").to_string()),
+ TimeFormat::CLower => Ok(dt.format("%a %b %d %H:%M:%S UTC %Y").to_string()),
+ }
+ }
+}
+
+trait FloatFormattable: std::fmt::Display {
+ fn category(&self) -> FpCategory;
+
+ fn spark_string(&self) -> String {
+ match self.category() {
+ FpCategory::Nan => "NaN".to_string(),
+ FpCategory::Infinite => {
+ if self.negative() {
+ "-Infinity".to_string()
+ } else {
+ "Infinity".to_string()
+ }
+ }
+ _ => self.to_string(),
+ }
+ }
+ fn negative(&self) -> bool;
+}
+
+impl FloatFormattable for f32 {
+ fn category(&self) -> FpCategory {
+ self.classify()
+ }
+
+ fn negative(&self) -> bool {
+ self.is_sign_negative()
+ }
+}
+
+impl FloatFormattable for f64 {
+ fn category(&self) -> FpCategory {
+ self.classify()
+ }
+
+ fn negative(&self) -> bool {
+ self.is_sign_negative()
+ }
+}
+
+trait FloatBits: FloatFormattable {
+ const MANTISSA_BITS: u8;
+ const EXPONENT_BIAS: u16;
+ const SCALEUP_POWER: u8;
+ const SCALEUP: Self;
+
+ fn to_parts(&self) -> (bool, u16, u64);
+}
+
+impl FloatBits for f64 {
+ const MANTISSA_BITS: u8 = 52;
+ const EXPONENT_BIAS: u16 = 1023;
+ const SCALEUP_POWER: u8 = 54;
+ const SCALEUP: f64 = (1_i64 << Self::SCALEUP_POWER) as f64;
+
+ fn to_parts(&self) -> (bool, u16, u64) {
+ let bits = self.to_bits();
+ let sign: bool = (bits >> 63) == 1;
+ let exponent = ((bits >> 52) & 0x7FF) as u16;
+ let mantissa = bits & 0x000F_FFFF_FFFF_FFFF;
+ (sign, exponent, mantissa)
+ }
+}
+
+fn trim_trailing_0s(number: &str) -> &str {
+ if number.contains('.') {
+ for (i, c) in number.chars().rev().enumerate() {
+ if c != '0' {
+ return &number[..number.len() - i];
+ }
+ }
+ }
+ number
+}
+
+fn trim_trailing_0s_hex(number: &str) -> &str {
+ for (i, c) in number.chars().rev().enumerate() {
+ if c != '0' {
+ return &number[..number.len() - i];
+ }
+ }
+ number
+}
diff --git a/datafusion/spark/src/function/string/mod.rs b/datafusion/spark/src/function/string/mod.rs
index 48bf77c1ca..8885dff170 100644
--- a/datafusion/spark/src/function/string/mod.rs
+++ b/datafusion/spark/src/function/string/mod.rs
@@ -17,6 +17,7 @@
pub mod ascii;
pub mod char;
+pub mod format_string;
pub mod ilike;
pub mod length;
pub mod like;
@@ -32,6 +33,7 @@ make_udf_function!(ilike::SparkILike, ilike);
make_udf_function!(length::SparkLengthFunc, length);
make_udf_function!(like::SparkLike, like);
make_udf_function!(luhn_check::SparkLuhnCheck, luhn_check);
+make_udf_function!(format_string::FormatStringFunc, format_string);
pub mod expr_fn {
use datafusion_functions::export_functions;
@@ -66,8 +68,21 @@ pub mod expr_fn {
"Returns whether the input string of digits is valid according to the Luhn algorithm.",
arg1
));
+ export_functions!((
+ format_string,
+ "Returns a formatted string from printf-style format strings.",
+ strfmt args
+ ));
}
pub fn functions() -> Vec<Arc<ScalarUDF>> {
- vec![ascii(), char(), ilike(), length(), like(), luhn_check()]
+ vec![
+ ascii(),
+ char(),
+ ilike(),
+ length(),
+ like(),
+ luhn_check(),
+ format_string(),
+ ]
}
diff --git a/datafusion/sqllogictest/test_files/spark/string/format_string.slt b/datafusion/sqllogictest/test_files/spark/string/format_string.slt
index 66b167a39a..07c8cd10d1 100644
--- a/datafusion/sqllogictest/test_files/spark/string/format_string.slt
+++ b/datafusion/sqllogictest/test_files/spark/string/format_string.slt
@@ -21,7 +21,2295 @@
# For more information, please see:
# https://github.com/apache/datafusion/issues/15914
-## Original Query: SELECT format_string("Hello World %d %s", 100, "days");
-## PySpark 3.5.5 Result: {'format_string(Hello World %d %s, 100, days)': 'Hello World 100 days', 'typeof(format_string(Hello World %d %s, 100, days))': 'string', 'typeof(Hello World %d %s)': 'string', 'typeof(100)': 'int', 'typeof(days)': 'string'}
-#query
-#SELECT format_string('Hello World %d %s'::string, 100::int, 'days'::string);
+# ================================
+# Basic format_string tests
+# ================================
+
+## Basic string formatting
+query T
+SELECT format_string('Hello World %s', 'DataFusion');
+----
+Hello World DataFusion
+
+query T
+SELECT format_string(arrow_cast('Hello World %s', 'LargeUtf8'), 'DataFusion');
+----
+Hello World DataFusion
+
+query T
+SELECT format_string(arrow_cast('Hello World %s', 'Utf8View'), 'DataFusion');
+----
+Hello World DataFusion
+
+## Basic integer formatting
+query T
+SELECT format_string('Hello World %d %s', 100, 'days');
+----
+Hello World 100 days
+
+## Multiple string arguments
+query T
+SELECT format_string('%s %s %s', 'Hello', 'World', 'Test');
+----
+Hello World Test
+
+## Format without arguments (just return the format string)
+query T
+SELECT format_string('Hello World');
+----
+Hello World
+
+# ================================
+# Integer formatting tests
+# ================================
+
+## Decimal integer formatting
+query T
+SELECT format_string('Value: %d', 42);
+----
+Value: 42
+
+## Hexadecimal integer formatting (lowercase)
+query T
+SELECT format_string('Hex: %x', 255);
+----
+Hex: ff
+
+## Hexadecimal integer formatting (uppercase)
+query T
+SELECT format_string('Hex: %X', 255);
+----
+Hex: FF
+
+## Octal integer formatting
+query T
+SELECT format_string('Octal: %o', 64);
+----
+Octal: 100
+
+## Integer with width padding
+query T
+SELECT format_string('Padded: %5d', 42);
+----
+Padded: 42
+
+## Integer with zero padding
+query T
+SELECT format_string('Zero padded: %05d', 42);
+----
+Zero padded: 00042
+
+## Left-aligned integer
+query T
+SELECT format_string('Left: %-5d|', 42);
+----
+Left: 42 |
+
+## Integer with force sign
+query T
+SELECT format_string('Signed: %+d', 42);
+----
+Signed: +42
+
+## Negative integer
+query T
+SELECT format_string('Negative: %d', -42);
+----
+Negative: -42
+
+# ================================
+# Float formatting tests
+# ================================
+
+## Basic float formatting
+query T
+SELECT format_string('Float: %f', 3.14159);
+----
+Float: 3.141590
+
+query T
+SELECT format_string('Float: %f', 30.0);
+----
+Float: 30.000000
+
+## Float with precision
+query T
+SELECT format_string('Precision: %.2f', 3.14159);
+----
+Precision: 3.14
+
+## Scientific notation (lowercase)
+query T
+SELECT format_string('Scientific: %e', 1234.5);
+----
+Scientific: 1.234500e+03
+
+## Scientific notation (uppercase)
+query T
+SELECT format_string('Scientific: %E', 1234.5);
+----
+Scientific: 1.234500E+03
+
+## Compact float (lowercase)
+query T
+SELECT format_string('Compact: %g', 1234.5);
+----
+Compact: 1234.5
+
+query T
+SELECT format_string('Compact: %g', CAST(123456789.1 AS DOUBLE));
+----
+Compact: 1.23457e+08
+
+## Compact float (uppercase)
+query T
+SELECT format_string('Compact: %G', 1234.5);
+----
+Compact: 1234.5
+
+query T
+SELECT format_string('Compact: %G', CAST(123456789.1 AS DOUBLE));
+----
+Compact: 1.23457E+08
+
+## Float with width and precision
+query T
+SELECT format_string('Formatted: %10.2f', 3.14159);
+----
+Formatted: 3.14
+
+## Float zero padding
+query T
+SELECT format_string('Zero: %08.2f', 3.14);
+----
+Zero: 00003.14
+
+## Float with left alignment
+query T
+SELECT format_string('Left: %-10.2f|', 3.14);
+----
+Left: 3.14 |
+
+## Float with space sign (positive)
+query T
+SELECT format_string('Space: % .2f', 3.14);
+----
+Space: 3.14
+
+## Float with space sign (negative)
+query T
+SELECT format_string('Space: % .2f', -3.14);
+----
+Space: -3.14
+
+## Float with force sign (positive)
+query T
+SELECT format_string('Force: %+.2f', 3.14);
+----
+Force: +3.14
+
+## Float with force sign (negative)
+query T
+SELECT format_string('Force: %+.2f', -3.14);
+----
+Force: -3.14
+
+## Float with precision 0
+query T
+SELECT format_string('Precision 0: %.0f', 3.14);
+----
+Precision 0: 3
+
+## Float with precision 0 (rounds up)
+query T
+SELECT format_string('Precision 0: %.0f', 3.6);
+----
+Precision 0: 4
+
+## Float with precision 0 and alternate form
+query T
+SELECT format_string('Alt form: %#.0f', 3.14);
+----
+Alt form: 3.
+
+## Scientific notation with precision 0
+query T
+SELECT format_string('Sci: %.0e', 1234.5);
+----
+Sci: 1e+03
+
+## Compact format with precision 0
+query T
+SELECT format_string('Compact: %.0g', 1234.5);
+----
+Compact: 1e+03
+
+# ================================
+# Boolean formatting tests
+# ================================
+
+## Boolean lowercase
+query T
+SELECT format_string('Bool: %b', true);
+----
+Bool: true
+
+## Boolean uppercase
+query T
+SELECT format_string('Bool: %B', false);
+----
+Bool: FALSE
+
+## Boolean with width
+query T
+SELECT format_string('Bool: %6b', true);
+----
+Bool: true
+
+## Boolean with invalid ARGUMENT
+statement error
+SELECT format_string('Bool: %6b', 1)
+
+# ================================
+# String formatting tests
+# ================================
+
+## String formatting
+query T
+SELECT format_string('String: %s', 'DataFusion');
+----
+String: DataFusion
+
+## String with width
+query T
+SELECT format_string('Padded: %10s|', 'test');
+----
+Padded: test|
+
+## String left-aligned
+query T
+SELECT format_string('Left: %-10s|', 'test');
+----
+Left: test |
+
+## String with precision (truncation)
+query T
+SELECT format_string('Truncated: %.3s', 'DataFusion');
+----
+Truncated: Dat
+
+## String uppercase conversion
+query T
+SELECT format_string('Upper: %S', 'datafusion');
+----
+Upper: DATAFUSION
+
+# ================================
+# Character formatting tests
+# ================================
+
+## Character formatting from integer
+query T
+SELECT format_string('Char: %c', 97);
+----
+Char: a
+
+## Character uppercase
+query T
+SELECT format_string('Char: %C', 97);
+----
+Char: A
+
+## Character with width padding
+query T
+SELECT format_string('Char: %5c', 65);
+----
+Char: A
+
+## Character with left alignment
+query T
+SELECT format_string('Char: %-5c|', 65);
+----
+Char: A |
+
+## Character uppercase with width
+query T
+SELECT format_string('Char: %5C', 97);
+----
+Char: A
+
+## Character uppercase with left alignment
+query T
+SELECT format_string('Char: %-5C|', 97);
+----
+Char: A |
+
+## Character with invalid ARGUMENT
+statement error
+SELECT format_string('Char: %5c', true);
+
+# ================================
+# Time formatting tests
+# ================================
+
+## Hour formatting (24-hour)
+query T
+SELECT format_string('Hour: %tH', TIMESTAMP '2023-12-25 14:30:45');
+----
+Hour: 14
+
+## Hour formatting (12-hour)
+query T
+SELECT format_string('Hour: %tI', TIMESTAMP '2023-12-25 14:30:45');
+----
+Hour: 02
+
+## Minute formatting
+query T
+SELECT format_string('Minute: %tM', TIMESTAMP '2023-12-25 14:30:45');
+----
+Minute: 30
+
+## Second formatting
+query T
+SELECT format_string('Second: %tS', TIMESTAMP '2023-12-25 14:30:45');
+----
+Second: 45
+
+## AM/PM marker
+query T
+SELECT format_string('AM/PM: %tp', TIMESTAMP '2023-12-25 14:30:45');
+----
+AM/PM: pm
+
+## AM/PM marker uppercase
+query T
+SELECT format_string('AM/PM: %Tp', TIMESTAMP '2023-12-25 14:30:45');
+----
+AM/PM: PM
+
+## AM/PM marker uppercase (morning)
+query T
+SELECT format_string('AM/PM: %Tp', TIMESTAMP '2023-12-25 09:30:45');
+----
+AM/PM: AM
+
+## Year formatting
+query T
+SELECT format_string('Year: %tY', TIMESTAMP '2023-12-25 14:30:45');
+----
+Year: 2023
+
+## Year formatting uppercase
+query T
+SELECT format_string('Year: %TY', TIMESTAMP '2023-12-25 14:30:45');
+----
+Year: 2023
+
+## Month formatting
+query T
+SELECT format_string('Month: %tm', TIMESTAMP '2023-12-25 14:30:45');
+----
+Month: 12
+
+## Day formatting
+query T
+SELECT format_string('Day: %td', TIMESTAMP '2023-12-25 14:30:45');
+----
+Day: 25
+
+## Time formatting (HH:MM)
+query T
+SELECT format_string('Time: %tR', TIMESTAMP '2023-12-25 14:30:45');
+----
+Time: 14:30
+
+## Time formatting (HH:MM:SS)
+query T
+SELECT format_string('Time: %tT', TIMESTAMP '2023-12-25 14:30:45');
+----
+Time: 14:30:45
+
+## Date formatting (MM/DD/YY)
+query T
+SELECT format_string('Date: %tD', TIMESTAMP '2023-12-25 14:30:45');
+----
+Date: 12/25/23
+
+## ISO date formatting (YYYY-MM-DD)
+query T
+SELECT format_string('ISO Date: %tF', TIMESTAMP '2023-12-25 14:30:45');
+----
+ISO Date: 2023-12-25
+
+## Complex date formatting (Sun Jul 20 16:17:00 EDT 1969)
+query B
+SELECT format_string('Date: %tc', TIMESTAMP '1969-07-20 16:17:00') LIKE 'Date: Sun Jul 20 16:17:00 % 1969';
+----
+true
+
+
+## Hour formatting (24-hour no padding)
+query T
+SELECT format_string('Hour: %tk', TIMESTAMP '2023-12-25 04:30:45');
+----
+Hour: 4
+
+## Hour formatting (12-hour no padding)
+query T
+SELECT format_string('Hour: %tl', TIMESTAMP '2023-12-25 14:30:45');
+----
+Hour: 2
+
+## Milliseconds formatting
+query T
+SELECT format_string('Milliseconds: %tL', TIMESTAMP '2023-12-25 14:30:45.123');
+----
+Milliseconds: 123
+
+## Nanoseconds formatting
+query T
+SELECT format_string('Nanoseconds: %tN', TIMESTAMP '2023-12-25 14:30:45.123456789');
+----
+Nanoseconds: 123456789
+
+## Timezone offset (RFC 822)
+query T
+SELECT format_string('Timezone: %tz', TIMESTAMP '2023-12-25 14:30:45');
+----
+Timezone: +0000
+
+## Timezone abbreviation
+query T
+SELECT format_string('Timezone: %tZ', from_unixtime(1599572549, 'America/New_York'));
+----
+Timezone: UTC
+
+## Seconds since epoch
+query T
+SELECT format_string('Epoch seconds: %ts', TIMESTAMP '1970-01-01 00:00:01');
+----
+Epoch seconds: 1
+
+## Milliseconds since epoch
+query T
+SELECT format_string('Epoch millis: %tQ', TIMESTAMP '1970-01-01 00:00:01');
+----
+Epoch millis: 1000
+
+## Full month name
+query T
+SELECT format_string('Month: %tB', TIMESTAMP '2023-12-25 14:30:45');
+----
+Month: December
+
+## Full month name uppercase
+query T
+SELECT format_string('Month: %TB', TIMESTAMP '2023-12-25 14:30:45');
+----
+Month: DECEMBER
+
+## Abbreviated month name
+query T
+SELECT format_string('Month: %tb', TIMESTAMP '2023-12-25 14:30:45');
+----
+Month: Dec
+
+## Abbreviated month name uppercase
+query T
+SELECT format_string('Month: %Tb', TIMESTAMP '2023-12-25 14:30:45');
+----
+Month: DEC
+
+## Same as %tb
+query T
+SELECT format_string('Month: %th', TIMESTAMP '2023-12-25 14:30:45');
+----
+Month: Dec
+
+## Full day of week
+query T
+SELECT format_string('Day: %tA', TIMESTAMP '2023-12-25 14:30:45');
+----
+Day: Monday
+
+## Full day of week uppercase
+query T
+SELECT format_string('Day: %TA', TIMESTAMP '2023-12-25 14:30:45');
+----
+Day: MONDAY
+
+## Abbreviated day of week
+query T
+SELECT format_string('Day: %ta', TIMESTAMP '2023-12-25 14:30:45');
+----
+Day: Mon
+
+## Abbreviated day of week uppercase
+query T
+SELECT format_string('Day: %Ta', TIMESTAMP '2023-12-25 14:30:45');
+----
+Day: MON
+
+## Century (year/100)
+query T
+SELECT format_string('Century: %tC', TIMESTAMP '2023-12-25 14:30:45');
+----
+Century: 20
+
+## Two-digit year
+query T
+SELECT format_string('Year: %ty', TIMESTAMP '2023-12-25 14:30:45');
+----
+Year: 23
+
+## Day of year
+query T
+SELECT format_string('Day of year: %tj', TIMESTAMP '2023-12-25 14:30:45');
+----
+Day of year: 359
+
+## Day of month (no padding)
+query T
+SELECT format_string('Day: %te', TIMESTAMP '2023-12-05 14:30:45');
+----
+Day: 5
+
+## 12-hour time with AM/PM
+query T
+SELECT format_string('Time: %tr', TIMESTAMP '2023-12-25 14:30:45');
+----
+Time: 02:30:45 PM
+
+statement error
+SELECT format_string('Time: %t', TIMESTAMP '2023-12-25 14:30:45');
+
+statement error
+SELECT format_string('Time: %T', TIMESTAMP '2023-12-25 14:30:45');
+
+
+statement error
+SELECT format_string('Time: %tx', TIMESTAMP '2023-12-25 14:30:45');
+
+statement error
+SELECT format_string('Time: %Tx', TIMESTAMP '2023-12-25 14:30:45');
+
+
+
+# ================================
+# Decimal formatting tests
+# ================================
+
+## Decimal formatting
+query T
+SELECT format_string('Decimal: %f', CAST(123.456 AS DECIMAL(10,3)));
+----
+Decimal: 123.456000
+
+## Decimal with precision
+query T
+SELECT format_string('Decimal: %.2f', CAST(123.456 AS DECIMAL(10,3)));
+----
+Decimal: 123.46
+
+## Decimal scientific notation
+query T
+SELECT format_string('Scientific: %e', CAST(1234.5 AS DECIMAL(10,2)));
+----
+Scientific: 1.234500e+03
+
+## Decimal with width padding
+query T
+SELECT format_string('Padded: %10.2f', CAST(123.456 AS DECIMAL(10,3)));
+----
+Padded: 123.46
+
+## Decimal with zero padding
+query T
+SELECT format_string('Zero padded: %010.2f', CAST(123.456 AS DECIMAL(10,3)));
+----
+Zero padded: 0000123.46
+
+## Decimal with left adjustment
+query T
+SELECT format_string('Left: %-10.2f', CAST(123.456 AS DECIMAL(10,3)));
+----
+Left: 123.46
+
+## Decimal with plus sign
+query T
+SELECT format_string('Plus: %+.2f', CAST(123.456 AS DECIMAL(10,3)));
+----
+Plus: +123.46
+
+## Decimal with space sign
+query T
+SELECT format_string('Space: % .2f', CAST(123.456 AS DECIMAL(10,3)));
+----
+Space: 123.46
+
+## Negative decimal with plus sign
+query T
+SELECT format_string('Negative: %+.2f', CAST(-123.456 AS DECIMAL(10,3)));
+----
+Negative: -123.46
+
+## Negative decimal with space sign
+query T
+SELECT format_string('Negative: % .2f', CAST(-123.456 AS DECIMAL(10,3)));
+----
+Negative: -123.46
+
+## Decimal with width and plus sign
+query T
+SELECT format_string('Width+Plus: %+10.2f', CAST(123.456 AS DECIMAL(10,3)));
+----
+Width+Plus: +123.46
+
+## Decimal with zero padding and plus sign
+query T
+SELECT format_string('Zero+Plus: %+010.2f', CAST(123.456 AS DECIMAL(10,3)));
+----
+Zero+Plus: +000123.46
+
+## Decimal with left adjustment and plus sign
+query T
+SELECT format_string('Left+Plus: %-+10.2f', CAST(123.456 AS DECIMAL(10,3)));
+----
+Left+Plus: +123.46
+
+## Decimal scientific notation with width
+query T
+SELECT format_string('Sci Width: %15.2e', CAST(1234.5 AS DECIMAL(10,2)));
+----
+Sci Width: 1.23e+03
+
+## Decimal scientific notation with zero padding
+query T
+SELECT format_string('Sci Zero: %015.2e', CAST(1234.5 AS DECIMAL(10,2)));
+----
+Sci Zero: 00000001.23e+03
+
+## Decimal scientific notation with plus sign
+query T
+SELECT format_string('Sci Plus: %+.2e', CAST(1234.5 AS DECIMAL(10,2)));
+----
+Sci Plus: +1.23e+03
+
+## Decimal compact format with width
+query T
+SELECT format_string('Compact: %10.2g', CAST(123.456 AS DECIMAL(10,3)));
+----
+Compact: 1.2e+02
+
+## Decimal compact format with plus sign
+query T
+SELECT format_string('Compact+: %+.2g', CAST(123.456 AS DECIMAL(10,3)));
+----
+Compact+: +1.2e+02
+
+statement error
+SELECT format_string('Compact+: %+.2g', 1);
+
+# ================================
+# Special cases and edge cases
+# ================================
+
+## Literal percent sign
+query T
+SELECT format_string('Percent: %%');
+----
+Percent: %
+
+## Newline character
+query T
+SELECT format_string('Line1%nLine2');
+----
+
+01)Line1
+02)Line2
+
+## Multiple format specifiers
+query T
+SELECT format_string('String: %s, Integer: %d, Float: %.2f', 'test', 42, 3.14159);
+----
+String: test, Integer: 42, Float: 3.14
+
+## Mixed width and precision
+query T
+SELECT format_string('Mixed: %10s %5d %.2f', 'hello', 123, 45.678);
+----
+Mixed: hello 123 45.68
+
+# ================================
+# NULL handling tests
+# ================================
+
+## NULL format string
+query T
+SELECT format_string(NULL, 'test');
+----
+NULL
+
+query T
+SELECT format_string(arrow_cast(NULL, 'Utf8'), 'test');
+----
+NULL
+
+query T
+SELECT format_string(arrow_cast(NULL, 'LargeUtf8'), 'test');
+----
+NULL
+
+query T
+SELECT format_string(arrow_cast(NULL, 'Utf8View'), 'test');
+----
+NULL
+
+## NULL argument with string format
+query T
+SELECT format_string('Value: %s', NULL);
+----
+Value: null
+
+## NULL with string format (uppercase)
+query T
+SELECT format_string('Upper: %S', NULL);
+----
+Upper: NULL
+
+
+## NULL argument with string format
+query T
+SELECT format_string('Value: %s', arrow_cast(NULL, 'Utf8'));
+----
+Value: null
+
+## NULL with string format (uppercase)
+query T
+SELECT format_string('Upper: %S', arrow_cast(NULL, 'Utf8'));
+----
+Upper: NULL
+
+## NULL argument with string format
+query T
+SELECT format_string('Value: %s', arrow_cast(NULL, 'LargeUtf8'));
+----
+Value: null
+
+## NULL with string format (uppercase)
+query T
+SELECT format_string('Upper: %S', arrow_cast(NULL, 'LargeUtf8'));
+----
+Upper: NULL
+
+## NULL argument with string format
+query T
+SELECT format_string('Value: %s', arrow_cast(NULL, 'Utf8View'));
+----
+Value: null
+
+## NULL with string format (uppercase)
+query T
+SELECT format_string('Upper: %S', arrow_cast(NULL, 'Utf8View'));
+----
+Upper: NULL
+
+## NULL with integer format using arrow_cast
+query T
+SELECT format_string('Integer: %d', arrow_cast(NULL, 'Int32'));
+----
+Integer: null
+
+## NULL with hex format (lowercase) using arrow_cast
+query T
+SELECT format_string('Hex: %x', arrow_cast(NULL, 'Int32'));
+----
+Hex: null
+
+## NULL with hex format (uppercase) using arrow_cast
+query T
+SELECT format_string('Hex: %X', arrow_cast(NULL, 'Int32'));
+----
+Hex: NULL
+
+## NULL with octal format using arrow_cast
+query T
+SELECT format_string('Octal: %o', arrow_cast(NULL, 'Int32'));
+----
+Octal: null
+
+## NULL with float format using arrow_cast
+query T
+SELECT format_string('Float: %f', arrow_cast(NULL, 'Float64'));
+----
+Float: null
+
+## NULL with float and precision using arrow_cast
+query T
+SELECT format_string('Float: %.2f', arrow_cast(NULL, 'Float64'));
+----
+Float: nu
+
+## NULL with scientific notation (lowercase) using arrow_cast
+query T
+SELECT format_string('Scientific: %e', arrow_cast(NULL, 'Float64'));
+----
+Scientific: null
+
+## NULL with scientific notation (uppercase) using arrow_cast
+query T
+SELECT format_string('Scientific: %E', arrow_cast(NULL, 'Float64'));
+----
+Scientific: NULL
+
+## NULL with compact float (lowercase) using arrow_cast
+query T
+SELECT format_string('Compact: %g', arrow_cast(NULL, 'Float64'));
+----
+Compact: null
+
+## NULL with compact float and precision (lowercase) using arrow_cast
+query T
+SELECT format_string('Float: %.3g', arrow_cast(NULL, 'Float64'));
+----
+Float: nul
+
+## NULL with compact float (uppercase) using arrow_cast
+query T
+SELECT format_string('Compact: %G', arrow_cast(NULL, 'Float64'));
+----
+Compact: NULL
+
+## NULL with compact float and precision (uppercase) using arrow_cast
+query T
+SELECT format_string('Float: %.3G', arrow_cast(NULL, 'Float64'));
+----
+Float: NUL
+
+## NULL with hex float (lowercase) using arrow_cast
+query T
+SELECT format_string('Hex float: %a', arrow_cast(NULL, 'Float64'));
+----
+Hex float: null
+
+## NULL with hex float (uppercase) using arrow_cast
+query T
+SELECT format_string('Hex float: %A', arrow_cast(NULL, 'Float64'));
+----
+Hex float: NULL
+
+# ## NULL with float and precision using arrow_cast
+# query T
+# SELECT format_string('Float: %.2f', arrow_cast(NULL, 'Float16'));
+# ----
+# Float: nu
+
+## NULL with boolean format (lowercase) using arrow_cast
+query T
+SELECT format_string('Bool: %b', arrow_cast(NULL, 'Boolean'));
+----
+Bool: false
+
+## NULL with boolean format (uppercase) using arrow_cast
+query T
+SELECT format_string('Bool: %B', arrow_cast(NULL, 'Boolean'));
+----
+Bool: FALSE
+
+## NULL with character format (lowercase) using arrow_cast
+query T
+SELECT format_string('Char: %c', arrow_cast(NULL, 'Int32'));
+----
+Char: null
+
+## NULL with character format (uppercase) using arrow_cast
+query T
+SELECT format_string('Char: %C', arrow_cast(NULL, 'Int32'));
+----
+Char: NULL
+
+## NULL with timestamp format using arrow_cast
+query T
+SELECT format_string('Hour: %tH', arrow_cast(NULL, 'Timestamp(Nanosecond, None)'));
+----
+Hour: null
+
+## NULL with timestamp format using arrow_cast
+query T
+SELECT format_string('Month: %tB', arrow_cast(NULL, 'Timestamp(Nanosecond, None)'));
+----
+Month: null
+
+## NULL with timestamp format using arrow_cast
+query T
+SELECT format_string('Month: %tB', arrow_cast(NULL, 'Time32(Second)'));
+----
+Month: null
+
+## NULL with timestamp format using arrow_cast
+query T
+SELECT format_string('Month: %tB', arrow_cast(NULL, 'Time32(Millisecond)'));
+----
+Month: null
+
+## NULL with timestamp format using arrow_cast
+query T
+SELECT format_string('Month: %tB', arrow_cast(NULL, 'Time64(Microsecond)'));
+----
+Month: null
+
+## NULL with timestamp format using arrow_cast
+query T
+SELECT format_string('Month: %tB', arrow_cast(NULL, 'Time64(Nanosecond)'));
+----
+Month: null
+
+## NULL with timestamp format using arrow_cast
+query T
+SELECT format_string('Month: %tB', arrow_cast(NULL, 'Timestamp(Second, None)'));
+----
+Month: null
+
+## NULL with timestamp format using arrow_cast
+query T
+SELECT format_string('Month: %tB', arrow_cast(NULL, 'Timestamp(Millisecond, None)'));
+----
+Month: null
+
+## NULL with timestamp format using arrow_cast
+query T
+SELECT format_string('Month: %tB', arrow_cast(NULL, 'Timestamp(Microsecond, None)'));
+----
+Month: null
+
+## NULL with timestamp format using arrow_cast
+query T
+SELECT format_string('Month: %tB', arrow_cast(NULL, 'Timestamp(Nanosecond, None)'));
+----
+Month: null
+
+## NULL with decimal format using arrow_cast
+query T
+SELECT format_string('Decimal: %f', arrow_cast(NULL, 'Decimal128(10, 2)'));
+----
+Decimal: null
+
+## NULL Int8 with string format using arrow_cast
+query T
+SELECT format_string('Value: %s', arrow_cast(NULL, 'Int8'));
+----
+Value: null
+
+## NULL Int16 with string format using arrow_cast
+query T
+SELECT format_string('Value: %s', arrow_cast(NULL, 'Int16'));
+----
+Value: null
+
+## NULL Int64 with string format using arrow_cast
+query T
+SELECT format_string('Value: %s', arrow_cast(NULL, 'Int64'));
+----
+Value: null
+
+## NULL UInt8 with string format using arrow_cast
+query T
+SELECT format_string('Value: %s', arrow_cast(NULL, 'UInt8'));
+----
+Value: null
+
+## NULL UInt16 with string format using arrow_cast
+query T
+SELECT format_string('Value: %s', arrow_cast(NULL, 'UInt16'));
+----
+Value: null
+
+## NULL UInt32 with string format using arrow_cast
+query T
+SELECT format_string('Value: %s', arrow_cast(NULL, 'UInt32'));
+----
+Value: null
+
+## NULL UInt64 with string format using arrow_cast
+query T
+SELECT format_string('Value: %s', arrow_cast(NULL, 'UInt64'));
+----
+Value: null
+
+## NULL Float32 with string format using arrow_cast
+query T
+SELECT format_string('Value: %s', arrow_cast(NULL, 'Float32'));
+----
+Value: null
+
+## NULL Float64 with string format using arrow_cast
+query T
+SELECT format_string('Value: %s', arrow_cast(NULL, 'Float64'));
+----
+Value: null
+
+## NULL Timestamp with string format using arrow_cast
+query T
+SELECT format_string('Value: %s', arrow_cast(NULL, 'Timestamp(Nanosecond, None)'));
+----
+Value: null
+
+## NULL Date32 with string format using arrow_cast
+query T
+SELECT format_string('Value: %s', arrow_cast(NULL, 'Date32'));
+----
+Value: null
+
+## NULL Date64 with string format using arrow_cast
+query T
+SELECT format_string('Value: %s', arrow_cast(NULL, 'Date64'));
+----
+Value: null
+
+## NULL Decimal128 with string format using arrow_cast
+query T
+SELECT format_string('Value: %s', arrow_cast(NULL, 'Decimal128(10, 2)'));
+----
+Value: null
+
+## NULL Decimal256 with string format using arrow_cast
+query T
+SELECT format_string('Value: %s', arrow_cast(NULL, 'Decimal256(20, 3)'));
+----
+Value: null
+
+
+# ================================
+# Error cases (should fail)
+# ================================
+
+## Format string expects arguments but none provided
+statement error
+SELECT format_string('Value: %d');
+
+statement error
+SELECT format_string(1);
+
+## Too few arguments for format specifiers
+statement error
+SELECT format_string('Values: %d %s', 42);
+
+## Invalid conversion for data type
+statement error
+SELECT format_string('Value: %d', 'not_a_number');
+
+statement error
+SELECT format_string('Value: %k', 'string');
+
+# ================================
+# Positional argument tests
+# ================================
+
+## Positional arguments
+query T
+SELECT format_string('%2$s %1$d', 42, 'test');
+----
+test 42
+
+## Reuse positional arguments
+query T
+SELECT format_string('%1$s %1$s', 'repeat');
+----
+repeat repeat
+
+## Mixed positional and sequential
+query T
+SELECT format_string('%2$s %s %1$d', 42, 'middle', 'end');
+----
+middle 42 42
+
+statement error
+SELECT format_string('%$s', 'test');
+
+# ================================
+# Flag combination tests
+# ================================
+
+## Alternate form with hex
+query T
+SELECT format_string('Hex: %#x', 255);
+----
+Hex: 0xff
+
+## Alternate form with octal
+query T
+SELECT format_string('Octal: %#o', 64);
+----
+Octal: 0100
+
+## Space sign with positive number
+query T
+SELECT format_string('Space: % d', 42);
+----
+Space: 42
+
+## Grouping separator (if supported)
+query T
+SELECT format_string('Grouped: %,d', 1234567);
+----
+Grouped: 1,234,567
+
+## Parentheses for negative numbers
+query T
+SELECT format_string('Negative: %(d', -42);
+----
+Negative: (42)
+
+# ================================
+# Array/Column tests
+# ================================
+
+## Test with array values
+statement ok
+CREATE TABLE test_format(fmt STRING, val1 STRING, val2 INT) AS VALUES
+ ('Hello %s %d', 'World', 1),
+ ('Float: %2$d %1$s', '3.14159', 2),
+ (NULL, '3.14159', 3);
+
+query T
+SELECT format_string(arrow_cast(fmt, 'Utf8'), val1, val2) FROM test_format;
+----
+Hello World 1
+Float: 2 3.14159
+NULL
+
+query T
+SELECT format_string(arrow_cast(fmt, 'LargeUtf8'), val1, val2) FROM test_format;
+----
+Hello World 1
+Float: 2 3.14159
+NULL
+
+query T
+SELECT format_string(arrow_cast(fmt, 'Utf8View'), val1, val2) FROM test_format;
+----
+Hello World 1
+Float: 2 3.14159
+NULL
+
+query T
+SELECT format_string(fmt, arrow_cast(val1, 'LargeUtf8'), val2) FROM test_format;
+----
+Hello World 1
+Float: 2 3.14159
+NULL
+
+query T
+SELECT format_string(fmt, arrow_cast(val1, 'Utf8'), val2) FROM test_format;
+----
+Hello World 1
+Float: 2 3.14159
+NULL
+
+query T
+SELECT format_string(fmt, arrow_cast(val1, 'Utf8View'), val2) FROM test_format;
+----
+Hello World 1
+Float: 2 3.14159
+NULL
+
+query T
+SELECT format_string(arrow_cast('Hello %s %d', 'Utf8'), val1, val2) FROM test_format;
+----
+Hello World 1
+Hello 3.14159 2
+Hello 3.14159 3
+
+query T
+SELECT format_string(arrow_cast('Hello %s %d', 'LargeUtf8'), val1, val2) FROM test_format;
+----
+Hello World 1
+Hello 3.14159 2
+Hello 3.14159 3
+
+query T
+SELECT format_string(arrow_cast('Hello %s %d', 'Utf8View'), val1, val2) FROM test_format;
+----
+Hello World 1
+Hello 3.14159 2
+Hello 3.14159 3
+
+statement ok
+DROP TABLE test_format;
+
+# ================================
+# Type-specific conversion tests
+# ================================
+
+## Boolean with string formats
+query T
+SELECT format_string('Value: %s', arrow_cast(true, 'Boolean'));
+----
+Value: true
+
+query T
+SELECT format_string('Value: %S', arrow_cast(false, 'Boolean'));
+----
+Value: FALSE
+
+## Int8 with various formats
+query T
+SELECT format_string('Decimal: %d', arrow_cast(127, 'Int8'));
+----
+Decimal: 127
+
+query T
+SELECT format_string('Hex: %x', arrow_cast(127, 'Int8'));
+----
+Hex: 7f
+
+query T
+SELECT format_string('Hex: %X', arrow_cast(127, 'Int8'));
+----
+Hex: 7F
+
+query T
+SELECT format_string('Octal: %o', arrow_cast(127, 'Int8'));
+----
+Octal: 177
+
+query T
+SELECT format_string('Char: %c', arrow_cast(65, 'Int8'));
+----
+Char: A
+
+query T
+SELECT format_string('Char: %C', arrow_cast(97, 'Int8'));
+----
+Char: A
+
+query T
+SELECT format_string('Char: %c', arrow_cast(65, 'UInt32'));
+----
+Char: A
+
+query T
+SELECT format_string('Char: %C', arrow_cast(97, 'UInt32'));
+----
+Char: A
+
+query T
+SELECT format_string('Char: %c', arrow_cast(65, 'UInt64'));
+----
+Char: A
+
+query T
+SELECT format_string('Char: %C', arrow_cast(97, 'UInt64'));
+----
+Char: A
+
+query T
+SELECT format_string('String: %s', arrow_cast(127, 'Int8'));
+----
+String: 127
+
+query T
+SELECT format_string('String: %S', arrow_cast(127, 'Int8'));
+----
+String: 127
+
+query T
+SELECT format_string('String: %s', arrow_cast(127, 'UInt8'));
+----
+String: 127
+
+query T
+SELECT format_string('String: %S', arrow_cast(127, 'UInt8'));
+----
+String: 127
+
+query T
+SELECT format_string('String: %s', arrow_cast(127, 'UInt16'));
+----
+String: 127
+
+query T
+SELECT format_string('String: %S', arrow_cast(127, 'UInt16'));
+----
+String: 127
+
+query T
+SELECT format_string('String: %s', arrow_cast(127, 'Int32'));
+----
+String: 127
+
+query T
+SELECT format_string('String: %S', arrow_cast(127, 'Int32'));
+----
+String: 127
+
+query T
+SELECT format_string('String: %s', arrow_cast(127, 'UInt64'));
+----
+String: 127
+
+query T
+SELECT format_string('String: %S', arrow_cast(127, 'UInt64'));
+----
+String: 127
+
+## Int16 with various formats
+query T
+SELECT format_string('Decimal: %d', arrow_cast(32767, 'Int16'));
+----
+Decimal: 32767
+
+query T
+SELECT format_string('Hex: %x', arrow_cast(32767, 'Int16'));
+----
+Hex: 7fff
+
+query T
+SELECT format_string('Hex: %X', arrow_cast(32767, 'Int16'));
+----
+Hex: 7FFF
+
+query T
+SELECT format_string('Octal: %o', arrow_cast(32767, 'Int16'));
+----
+Octal: 77777
+
+query T
+SELECT format_string('Char: %c', arrow_cast(8364, 'Int16'));
+----
+Char: €
+
+query T
+SELECT format_string('String: %s', arrow_cast(32767, 'Int16'));
+----
+String: 32767
+
+query T
+SELECT format_string('NaN: %s', CAST('NaN' AS DOUBLE));
+----
+NaN: NaN
+
+query T
+SELECT format_string('Infinity: %s', CAST('+Inf' AS DOUBLE));
+----
+Infinity: Infinity
+
+query T
+SELECT format_string('Infinity: %s', CAST('-Inf' AS DOUBLE));
+----
+Infinity: -Infinity
+
+query T
+SELECT format_string('NaN: %S', CAST('NaN' AS DOUBLE));
+----
+NaN: NAN
+
+query T
+SELECT format_string('Infinity: %S', CAST('+Inf' AS DOUBLE));
+----
+Infinity: INFINITY
+
+query T
+SELECT format_string('Infinity: %S', CAST('-Inf' AS DOUBLE));
+----
+Infinity: -INFINITY
+
+## Int32 with various formats
+query T
+SELECT format_string('Decimal: %d', arrow_cast(2147483647, 'Int32'));
+----
+Decimal: 2147483647
+
+query T
+SELECT format_string('Hex: %x', arrow_cast(255, 'Int32'));
+----
+Hex: ff
+
+query T
+SELECT format_string('Octal: %o', arrow_cast(511, 'Int32'));
+----
+Octal: 777
+
+query T
+SELECT format_string('Char: %c', arrow_cast(128512, 'Int32'));
+----
+Char: πŸ˜€
+
+## UInt8 with various formats
+query T
+SELECT format_string('Decimal: %d', arrow_cast(255, 'UInt8'));
+----
+Decimal: 255
+
+query T
+SELECT format_string('Hex: %x', arrow_cast(255, 'UInt8'));
+----
+Hex: ff
+
+query T
+SELECT format_string('Octal: %o', arrow_cast(255, 'UInt8'));
+----
+Octal: 377
+
+query T
+SELECT format_string('Char: %c', arrow_cast(65, 'UInt8'));
+----
+Char: A
+
+## UInt16 with various formats
+query T
+SELECT format_string('Decimal: %d', arrow_cast(65535, 'UInt16'));
+----
+Decimal: 65535
+
+query T
+SELECT format_string('Hex: %X', arrow_cast(65535, 'UInt16'));
+----
+Hex: FFFF
+
+query T
+SELECT format_string('Char: %c', arrow_cast(9733, 'UInt16'));
+----
+Char: β˜…
+
+## UInt32 with various formats
+query T
+SELECT format_string('Decimal: %d', arrow_cast(4294967295, 'UInt32'));
+----
+Decimal: 4294967295
+
+query T
+SELECT format_string('Hex: %x', arrow_cast(4294967295, 'UInt32'));
+----
+Hex: ffffffff
+
+query T
+SELECT format_string('String: %s', arrow_cast(4294967295, 'UInt32'));
+----
+String: 4294967295
+
+## UInt64 with various formats
+query T
+SELECT format_string('Decimal: %d', arrow_cast(18446744073709551615, 'UInt64'));
+----
+Decimal: 18446744073709551615
+
+query T
+SELECT format_string('Hex: %X', arrow_cast(18446744073709551615, 'UInt64'));
+----
+Hex: FFFFFFFFFFFFFFFF
+
+## Float16 with various formats
+query T
+SELECT format_string('Float: %f', arrow_cast(3.14, 'Float16'));
+----
+Float: 3.140625
+
+query T
+SELECT format_string('Scientific: %e', arrow_cast(3.14, 'Float16'));
+----
+Scientific: 3.140625e+00
+
+query T
+SELECT format_string('Scientific: %E', arrow_cast(3.14, 'Float16'));
+----
+Scientific: 3.140625E+00
+
+query T
+SELECT format_string('Compact: %g', arrow_cast(3.14, 'Float16'));
+----
+Compact: 3.14063
+
+query T
+SELECT format_string('Compact: %G', arrow_cast(3.14, 'Float16'));
+----
+Compact: 3.14063
+
+query T
+SELECT format_string('String: %s', arrow_cast(3.14, 'Float16'));
+----
+String: 3.140625
+
+query T
+SELECT format_string('String: %S', arrow_cast(3.14, 'Float16'));
+----
+String: 3.140625
+
+query T
+SELECT format_string('Hex float: %a', arrow_cast(3.14, 'Float16'));
+----
+Hex float: 0x1.92p1
+
+query T
+SELECT format_string('Hex float: %A', arrow_cast(3.14, 'Float16'));
+----
+Hex float: 0X1.92P1
+
+## Float32 with various formats
+query T
+SELECT format_string('Float: %f', arrow_cast(3.14159, 'Float32'));
+----
+Float: 3.141590
+
+query T
+SELECT format_string('Scientific: %e', arrow_cast(1234.5, 'Float32'));
+----
+Scientific: 1.234500e+03
+
+query T
+SELECT format_string('Compact: %g', arrow_cast(1234.5, 'Float32'));
+----
+Compact: 1234.5
+
+query T
+SELECT format_string('String: %s', arrow_cast(3.14159, 'Float32'));
+----
+String: 3.14159
+
+query T
+SELECT format_string('Hex float: %a', arrow_cast(3.14, 'Float32'));
+----
+Hex float: 0x1.91eb86p1
+
+query T
+SELECT format_string('Hex float: %A', arrow_cast(3.14, 'Float32'));
+----
+Hex float: 0X1.91EB86P1
+
+## Float64 with various formats
+
+query T
+SELECT format_string('String: %s', arrow_cast(3.14159, 'Float64'));
+----
+String: 3.14159
+
+query T
+SELECT format_string('String: %S', arrow_cast(3.14159, 'Float64'));
+----
+String: 3.14159
+
+## Decimal128 with various formats
+query T
+SELECT format_string('Float: %f', arrow_cast(123.456, 'Decimal128(10, 3)'));
+----
+Float: 123.456000
+
+query T
+SELECT format_string('Scientific: %e', arrow_cast(1234.5, 'Decimal128(10, 2)'));
+----
+Scientific: 1.234500e+03
+
+query T
+SELECT format_string('Scientific: %E', arrow_cast(1234.5, 'Decimal128(10, 2)'));
+----
+Scientific: 1.234500E+03
+
+query T
+SELECT format_string('Compact: %g', arrow_cast(1234.5, 'Decimal128(10, 2)'));
+----
+Compact: 1234.5
+
+query T
+SELECT format_string('Compact: %G', arrow_cast(1234.5, 'Decimal128(10, 2)'));
+----
+Compact: 1234.5
+
+query T
+SELECT format_string('String: %s', arrow_cast(123.456, 'Decimal128(10, 3)'));
+----
+String: 123456
+
+query T
+SELECT format_string('String: %S', arrow_cast(123.456, 'Decimal128(10, 3)'));
+----
+String: 123456
+
+## Decimal256 with various formats
+query T
+SELECT format_string('Float: %f', arrow_cast(123.456, 'Decimal256(20, 3)'));
+----
+Float: 123.456000
+
+query T
+SELECT format_string('Scientific: %e', arrow_cast(1234.5, 'Decimal256(20, 2)'));
+----
+Scientific: 1.234500e+03
+
+query T
+SELECT format_string('Compact: %g', arrow_cast(1234.5, 'Decimal256(20, 2)'));
+----
+Compact: 1234.5
+
+query T
+SELECT format_string('String: %s', arrow_cast(123.456, 'Decimal256(20, 3)'));
+----
+String: 123456
+
+## Time32Second with time formats
+query T
+SELECT format_string('Hour: %tH', arrow_cast(52245::int, 'Time32(Second)'));
+----
+Hour: 14
+
+query T
+SELECT format_string('Minute: %tM', arrow_cast(52245::int, 'Time32(Second)'));
+----
+Minute: 30
+
+query T
+SELECT format_string('String: %s', arrow_cast(52245::int, 'Time32(Second)'));
+----
+String: 52245
+
+query T
+SELECT format_string('String: %S', arrow_cast(52245::int, 'Time32(Second)'));
+----
+String: 52245
+
+## Time32Millisecond with time formats
+query T
+SELECT format_string('Hour: %tH', arrow_cast(52245000::int, 'Time32(Millisecond)'));
+----
+Hour: 14
+
+query T
+SELECT format_string('Second: %tS', arrow_cast(52245000::int, 'Time32(Millisecond)'));
+----
+Second: 45
+
+query T
+SELECT format_string('String: %s', arrow_cast(52245000::int, 'Time32(Millisecond)'));
+----
+String: 52245000
+
+## Time64Microsecond with time formats
+query T
+SELECT format_string('Hour: %tH', arrow_cast(52245000000, 'Time64(Microsecond)'));
+----
+Hour: 14
+
+query T
+SELECT format_string('Time: %tT', arrow_cast(52245000000, 'Time64(Microsecond)'));
+----
+Time: 14:30:45
+
+query T
+SELECT format_string('String: %s', arrow_cast(52245000000, 'Time64(Microsecond)'));
+----
+String: 52245000000
+
+## Time64Nanosecond with time formats
+query T
+SELECT format_string('Hour: %tH', arrow_cast(52245000000000, 'Time64(Nanosecond)'));
+----
+Hour: 14
+
+query T
+SELECT format_string('AM/PM: %tp', arrow_cast(52245000000000, 'Time64(Nanosecond)'));
+----
+AM/PM: pm
+
+query T
+SELECT format_string('String: %s', arrow_cast(52245000000000, 'Time64(Nanosecond)'));
+----
+String: 52245000000000
+
+## TimestampSecond with time formats
+query T
+SELECT format_string('Year: %tY', arrow_cast(1703512245, 'Timestamp(Second, None)'));
+----
+Year: 2023
+
+query T
+SELECT format_string('Month: %tm', arrow_cast(1703512245, 'Timestamp(Second, None)'));
+----
+Month: 12
+
+query T
+SELECT format_string('String: %s', arrow_cast(1703512245, 'Timestamp(Second, None)'));
+----
+String: 1703512245
+
+query T
+SELECT format_string('String: %S', arrow_cast(1703512245, 'Timestamp(Second, None)'));
+----
+String: 1703512245
+
+## TimestampMillisecond with time formats
+query T
+SELECT format_string('ISO Date: %tF', arrow_cast(1703512245000, 'Timestamp(Millisecond, None)'));
+----
+ISO Date: 2023-12-25
+
+query T
+SELECT format_string('String: %s', arrow_cast(1703512245000, 'Timestamp(Millisecond, None)'));
+----
+String: 1703512245000
+
+## TimestampMicrosecond with time formats
+query T
+SELECT format_string('Date: %tD', arrow_cast(1703512245000000, 'Timestamp(Microsecond, None)'));
+----
+Date: 12/25/23
+
+query T
+SELECT format_string('String: %s', arrow_cast(1703512245000000, 'Timestamp(Microsecond, None)'));
+----
+String: 1703512245000000
+
+query T
+SELECT format_string('String: %s', arrow_cast('2020-01-02 01:01:11.1234567890Z', 'Timestamp(Nanosecond, None)'));
+----
+String: 1577926871123456789
+
+## Date32 with time formats
+query T
+SELECT format_string('Year: %tY', arrow_cast(19716, 'Date32'));
+----
+Year: 2023
+
+query T
+SELECT format_string('Month: %tB', arrow_cast(19716, 'Date32'));
+----
+Month: December
+
+query T
+SELECT format_string('String: %s', arrow_cast(19716, 'Date32'));
+----
+String: 19716
+
+query T
+SELECT format_string('String: %S', arrow_cast(19716, 'Date32'));
+----
+String: 19716
+
+## Date64 with time formats
+query T
+SELECT format_string('Year: %tY', arrow_cast(19716, 'Date64'));
+----
+Year: 2023
+
+query T
+SELECT format_string('Month: %tB', arrow_cast(19716, 'Date64'));
+----
+Month: December
+
+query T
+SELECT format_string('String: %s', arrow_cast(19716, 'Date64'));
+----
+String: 19716
+
+query T
+SELECT format_string('String: %S', arrow_cast(19716, 'Date64'));
+----
+String: 19716
+
+## Date64 with invalid ARGUMENT
+statement error
+SELECT format_string('String: %tY', true);
+
+# ================================
+# General formatting tests (%h, %H)
+# ================================
+
+# Not implemented yet. Can be implemented after https://github.com/apache/datafusion/pull/17093 is merged
+## Hash value formatting (lowercase)
+statement error
+SELECT format_string('Hash: %h', 'test');
+# ----
+# Hash: ec06e15a
+
+## Hash value formatting (uppercase)
+statement error
+SELECT format_string('Hash: %H', 'test');
+# ----
+# Hash: EC06E15A
+
+## Hash with width
+statement error
+SELECT format_string('Hash: %10h', 'test');
+# ----
+# Hash: ec06e15a
+
+# ================================
+# Hexadecimal floating point tests
+# ================================
+
+## Hexadecimal float (lowercase)
+query T
+SELECT format_string('Hex float: %a', 15.9375);
+----
+Hex float: 0x1.fep3
+
+## Hexadecimal float (uppercase)
+query T
+SELECT format_string('Hex float: %A', 15.9375);
+----
+Hex float: 0X1.FEP3
+
+## Hexadecimal float with precision
+query T
+SELECT format_string('Hex float: %.10a', 15.9375);
+----
+Hex float: 0x1.fe00000000p3
+
+query T
+SELECT format_string('%a', 12.3456);
+----
+0x1.8b0f27bb2fec5p3
+
+## Hexadecimal float with zero
+query T
+SELECT format_string('Hex float: %a', 0.0);
+----
+Hex float: 0x0.0p0
+
+## Hexadecimal float with negative value
+query T
+SELECT format_string('Hex float: %a', -15.9375);
+----
+Hex float: -0x1.fep3
+
+## Hexadecimal float with very small value
+query T
+SELECT format_string('Hex float: %a', 0.0000152587890625);
+----
+Hex float: 0x1.0p-16
+
+## Hexadecimal float with force sign
+query T
+SELECT format_string('Hex float: %+a', 15.9375);
+----
+Hex float: +0x1.fep3
+
+## Hexadecimal float with space sign (positive)
+query T
+SELECT format_string('Hex float: % a', 15.9375);
+----
+Hex float: 0x1.fep3
+
+## Hexadecimal float with space sign (negative)
+query T
+SELECT format_string('Hex float: % a', -15.9375);
+----
+Hex float: -0x1.fep3
+
+## Hexadecimal float uppercase with space sign
+query T
+SELECT format_string('Hex float: % A', 15.9375);
+----
+Hex float: 0X1.FEP3
+
+## Hexadecimal float with width
+query T
+SELECT format_string('Hex float: %20a', 15.9375);
+----
+Hex float: 0x1.fep3
+
+## Hexadecimal float with zero padding
+query T
+SELECT format_string('Hex float: %020a', 15.9375);
+----
+Hex float: 0x0000000000001.fep3
+
+## Hexadecimal float with alternate form and precision
+query T
+SELECT format_string('Hex float: %#.5a', 1.0);
+----
+Hex float: 0x1.00000p0
+
+## Hexadecimal float uppercase with force sign
+query T
+SELECT format_string('Hex float: %+A', -15.9375);
+----
+Hex float: -0X1.FEP3
+
+## Hexadecimal float with left alignment
+query T
+SELECT format_string('Hex float: %-20a', 15.9375);
+----
+Hex float: 0x1.fep3
+
+## Hexadecimal float with subnormal number (Float64)
+query T
+SELECT format_string('Hex float: %a', 2.2250738585072014e-308);
+----
+Hex float: 0x1.0p-1022
+
+## Hexadecimal float with smallest subnormal (Float64)
+query T
+SELECT format_string('Hex float: %a', 5.0e-324);
+----
+Hex float: 0x0.0000000000001p-1022
+
+## Hexadecimal float uppercase with subnormal
+query T
+SELECT format_string('Hex float: %A', 5.0e-324);
+----
+Hex float: 0X0.0000000000001P-1022
+
+## Hexadecimal float with subnormal and precision
+query T
+SELECT format_string('Hex float: %.20a', 2.2250738585072014e-308);
+----
+Hex float: 0x1.00000000000000000000p-1022
+
+## Hexadecimal float with negative subnormal
+query T
+SELECT format_string('Hex float: %a', -5.0e-324);
+----
+Hex float: -0x0.0000000000001p-1022
+
+## Hexadecimal float with subnormal and precision 5
+query T
+SELECT format_string('Hex float: %.5a', 5.0e-324);
+----
+Hex float: 0x1.00000p-1074
+
+## Hexadecimal float with subnormal and precision 10
+query T
+SELECT format_string('Hex float: %.10a', 5.0e-324);
+----
+Hex float: 0x1.0000000000p-1074
+
+## Hexadecimal float with subnormal and precision 13 (full)
+query T
+SELECT format_string('Hex float: %.13a', 5.0e-324);
+----
+Hex float: 0x0.0000000000001p-1022
+
+## Hexadecimal float with larger subnormal and precision
+query T
+SELECT format_string('Hex float: %.5a', 2.225e-308);
+----
+Hex float: 0x1.fffbap-1023
+
+## Hexadecimal float with subnormal and precision 0
+query T
+SELECT format_string('Hex float: %.0a', 5.0e-324);
+----
+Hex float: 0x1.0p-1074
+
+query T
+SELECT format_string('Hex float: %.2a', 5.0e-324);
+----
+Hex float: 0x1.00p-1074
+
+
+query T
+SELECT format_string('Hex float: %.2a', 5.0e-323);
+----
+Hex float: 0x1.40p-1071
+
+query T
+SELECT format_string('Hex float: %.0a', 5.0e-323);
+----
+Hex float: 0x1.4p-1071
+
+# ================================
+# Relative indexing tests
+# ================================
+
+## Relative indexing with <
+query T
+SELECT format_string('%s %<s %<s', 'repeat');
+----
+repeat repeat repeat
+
+## Mixed relative and positional indexing
+query T
+SELECT format_string('%2$s %<s %1$d', 42, 'test');
+----
+test test 42
+
+statement error
+SELECT format_string('%<s %<s', 'repeat');
+
+# ================================
+# Extended flag combination tests
+# ================================
+
+## Combine + and 0 flags
+query T
+SELECT format_string('Signed zero-padded: %+08d', 42);
+----
+Signed zero-padded: +0000042
+
+## Combine space and width
+query T
+SELECT format_string('Space padded: % 8d', 42);
+----
+Space padded: 42
+
+## Combine # flag with float
+query T
+SELECT format_string('Always decimal: %#.0f', 42.0);
+----
+Always decimal: 42.
+
+## Combine # flag with float
+query T
+SELECT format_string('Always decimal: %#.0f', 40.0);
+----
+Always decimal: 40.
+
+## Combine multiple flags with hex
+query T
+SELECT format_string('Hex: %#08x', 255);
+----
+Hex: 0x0000ff
+
+# ================================
+# Special numeric values
+# ================================
+
+## Float NaN
+query T
+SELECT format_string('NaN: %f', CAST('NaN' AS DOUBLE));
+----
+NaN: NaN
+
+## Float positive infinity
+query T
+SELECT format_string('Infinity: %f', CAST('+Inf' AS DOUBLE));
+----
+Infinity: Infinity
+
+## Float negative infinity
+query T
+SELECT format_string('Negative Infinity: %f', CAST('-Inf' AS DOUBLE));
+----
+Negative Infinity: -Infinity
+
+## Float negative infinity with parentheses
+query T
+SELECT format_string('Negative Infinity: %(f', CAST('-Inf' AS DOUBLE));
+----
+Negative Infinity: (Infinity)
+
+## NaN with scientific notation (lowercase)
+query T
+SELECT format_string('NaN: %e', CAST('NaN' AS DOUBLE));
+----
+NaN: NaN
+
+## NaN with scientific notation (uppercase)
+query T
+SELECT format_string('NaN: %E', CAST('NaN' AS DOUBLE));
+----
+NaN: NAN
+
+## NaN with compact format (lowercase)
+query T
+SELECT format_string('NaN: %g', CAST('NaN' AS DOUBLE));
+----
+NaN: NaN
+
+## NaN with compact format (uppercase)
+query T
+SELECT format_string('NaN: %G', CAST('NaN' AS DOUBLE));
+----
+NaN: NAN
+
+## NaN with hex float (lowercase)
+query T
+SELECT format_string('NaN: %a', CAST('NaN' AS DOUBLE));
+----
+NaN: NaN
+
+## NaN with hex float (uppercase)
+query T
+SELECT format_string('NaN: %A', CAST('NaN' AS DOUBLE));
+----
+NaN: NAN
+
+## Positive infinity with scientific notation (lowercase)
+query T
+SELECT format_string('Infinity: %e', CAST('+Inf' AS DOUBLE));
+----
+Infinity: Infinity
+
+## Positive infinity with scientific notation (uppercase)
+query T
+SELECT format_string('Infinity: %E', CAST('+Inf' AS DOUBLE));
+----
+Infinity: INFINITY
+
+## Positive infinity with compact format (lowercase)
+query T
+SELECT format_string('Infinity: %g', CAST('+Inf' AS DOUBLE));
+----
+Infinity: Infinity
+
+## Positive infinity with compact format (uppercase)
+query T
+SELECT format_string('Infinity: %G', CAST('+Inf' AS DOUBLE));
+----
+Infinity: INFINITY
+
+## Positive infinity with hex float (lowercase)
+query T
+SELECT format_string('Infinity: %a', CAST('+Inf' AS DOUBLE));
+----
+Infinity: Infinity
+
+## Positive infinity with hex float (uppercase)
+query T
+SELECT format_string('Infinity: %A', CAST('+Inf' AS DOUBLE));
+----
+Infinity: INFINITY
+
+## Negative infinity with scientific notation (lowercase)
+query T
+SELECT format_string('Negative Infinity: %e', CAST('-Inf' AS DOUBLE));
+----
+Negative Infinity: -Infinity
+
+## Negative infinity with scientific notation (uppercase)
+query T
+SELECT format_string('Negative Infinity: %E', CAST('-Inf' AS DOUBLE));
+----
+Negative Infinity: -INFINITY
+
+## Negative infinity with compact format (lowercase)
+query T
+SELECT format_string('Negative Infinity: %g', CAST('-Inf' AS DOUBLE));
+----
+Negative Infinity: -Infinity
+
+## Negative infinity with compact format (uppercase)
+query T
+SELECT format_string('Negative Infinity: %G', CAST('-Inf' AS DOUBLE));
+----
+Negative Infinity: -INFINITY
+
+## Negative infinity with hex float (lowercase)
+query T
+SELECT format_string('Negative Infinity: %a', CAST('-Inf' AS DOUBLE));
+----
+Negative Infinity: -Infinity
+
+## Negative infinity with hex float (uppercase)
+query T
+SELECT format_string('Negative Infinity: %A', CAST('-Inf' AS DOUBLE));
+----
+Negative Infinity: -INFINITY
+
+## Positive infinity with force sign
+query T
+SELECT format_string('Infinity: %+f', CAST('+Inf' AS DOUBLE));
+----
+Infinity: +Infinity
+
+## Negative infinity with scientific notation and parentheses
+query T
+SELECT format_string('Negative Infinity: %(e', CAST('-Inf' AS DOUBLE));
+----
+Negative Infinity: (Infinity)
+
+# ================================
+# Large number tests
+# ================================
+
+## Large integer
+query T
+SELECT format_string('Large: %d', 9223372036854775807);
+----
+Large: 9223372036854775807
+
+## Very large integer with grouping
+query T
+SELECT format_string('Grouped large: %,d', 9223372036854775807);
+----
+Grouped large: 9,223,372,036,854,775,807
+
+# ================================
+# Precision edge cases
+# ================================
+
+## Zero precision with decimal
+query T
+SELECT format_string('Zero precision: %.0f', 3.14159);
+----
+Zero precision: 3
+
+## High precision float
+query T
+SELECT format_string('High precision: %.10f', 3.14159);
+----
+High precision: 3.1415900000
+
+## Scientific notation with precision
+query T
+SELECT format_string('Scientific: %.3e', 1234.56789);
+----
+Scientific: 1.235e+03
+
+# ================================
+# Width edge cases
+# ================================
+
+## Very wide formatting
+query T
+SELECT format_string('Wide: %20s|', 'test');
+----
+Wide: test|
+
+## Wide with left alignment
+query T
+SELECT format_string('Wide left: %-20s|', 'test');
+----
+Wide left: test |
+
+# ================================
+# Character encoding tests
+# ================================
+
+## Unicode character
+query T
+SELECT format_string('Unicode: %c', 8364);
+----
+Unicode: €
+
+## High Unicode codepoint
+query T
+SELECT format_string('Emoji: %c', 128512);
+----
+Emoji: πŸ˜€
+
+# ================================
+# Advanced error cases
+# ================================
+
+## Invalid flag combination (+ and space)
+statement error
+SELECT format_string('%+ d', 42);
+
+## Invalid flag combination (+ and space)
+statement error
+SELECT format_string('% +d', 42);
+
+## Invalid flag combination (- and 0)
+statement error
+SELECT format_string('%-0d', 42);
+
+## Width without value for line separator
+statement error
+SELECT format_string('%5n');
+
+# ================================
+# BigInteger-like tests
+# ================================
+
+## Very large number in different bases
+query T
+SELECT format_string('Large hex: %x', 9223372036854775807::BIGINT);
+----
+Large hex: 7fffffffffffffff
+
+## Large octal
+query T
+SELECT format_string('Large octal: %o', 9223372036854775807::BIGINT);
+----
+Large octal: 777777777777777777777
diff --git a/datafusion/sqllogictest/test_files/spark/string/printf.slt b/datafusion/sqllogictest/test_files/spark/string/printf.slt
index dd25dbcbfe..f248c4434b 100644
--- a/datafusion/sqllogictest/test_files/spark/string/printf.slt
+++ b/datafusion/sqllogictest/test_files/spark/string/printf.slt
@@ -23,5 +23,8 @@
## Original Query: SELECT printf("Hello World %d %s", 100, "days");
## PySpark 3.5.5 Result: {'printf(Hello World %d %s, 100, days)': 'Hello World 100 days', 'typeof(printf(Hello World %d %s, 100, days))': 'string', 'typeof(Hello World %d %s)': 'string', 'typeof(100)': 'int', 'typeof(days)': 'string'}
-#query
-#SELECT printf('Hello World %d %s'::string, 100::int, 'days'::string);
+
+query T
+SELECT printf('Hello World %d %s'::string, 100::int, 'days'::string);
+----
+Hello World 100 days