comphead commented on code in PR #26377:
URL: https://github.com/apache/datafusion/pull/26377#discussion_r4285410471


##########
datafusion/sqllogictest/test_files/functions.slt:
##########
@@ -486,6 +486,72 @@ BAR Dictionary(Int32, Utf8)
 statement ok
 DROP TABLE upper_dictionary_test
 
+# The array is not all ASCII, so each row is converted on its own: ASCII rows,
+# and rows with non-ASCII characters at the start, middle and end, including
+# values longer than the 12 bytes a Utf8View can store inline.
+statement ok
+CREATE TABLE upper_mixed_test AS
+SELECT column1 AS id,
+  arrow_cast(column2, 'Utf8') AS utf8,
+  arrow_cast(column2, 'LargeUtf8') AS large_utf8,
+  arrow_cast(column2, 'Utf8View') AS utf8view
+FROM (VALUES
+(1, 'datafusion'),
+(2, 'a long ascii-only value'),
+(3, ''),
+(4, NULL),
+(5, 'éa'),
+(6, 'über alles, then ascii'),
+(7, 'straße'),
+(8, 'a long value ending in ß'),
+(9, 'ⱦx'),
+(10, '农历新年 new year'));
+
+query T
+SELECT upper(utf8) FROM upper_mixed_test ORDER BY id

Review Comment:
   The three queries per function repeat the same ten expected rows, and 
`lower_mixed_test` does the same. One `query TTT` selecting `upper(utf8), 
upper(large_utf8), upper(utf8view)` keeps the coverage with a third of the 
expected output, and adding a row such as the mid-word sigma case becomes one 
edit instead of three.



##########
datafusion/functions/benches/string_expressions/case_conversion_inputs.rs:
##########
@@ -0,0 +1,198 @@
+// 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.
+
+//! Inputs shared by the `upper` and `lower` benchmarks, so both functions are
+//! measured on the same arrays.
+
+use std::hint::black_box;
+use std::sync::Arc;
+
+use crate::helper::gen_string_array;
+use arrow::array::{Array, ArrayRef, LargeStringArray, StringArray, 
StringViewArray};
+use arrow::datatypes::Field;
+use arrow::util::bench_util::{
+    create_string_array_with_len, create_string_view_array_with_len,
+};
+use criterion::Criterion;
+use datafusion_common::config::ConfigOptions;
+use datafusion_expr::{ColumnarValue, ScalarFunctionArgs, ScalarUDF};
+
+/// Rows in each array built by [`build_values`].
+const SIZE: usize = 4096;
+
+const WORDS: [&str; 8] = [
+    "café",
+    "straße",
+    "αλφα",
+    "こんにちは",
+    "münchen",
+    "naïve",
+    " órdenes",
+    "tschüß",
+];
+
+/// Builds [`SIZE`] values: every tenth is NULL and the rest come from `value`.
+fn build_values(value: impl Fn(usize) -> String) -> Vec<Option<String>> {
+    (0..SIZE).map(|i| (i % 10 != 0).then(|| value(i))).collect()
+}
+
+/// Three words from [`WORDS`], so the value is non-ASCII.
+fn word_value(row: usize) -> String {
+    let a = WORDS[row % WORDS.len()];
+    let b = WORDS[(row * 7 + 3) % WORDS.len()];
+    format!("{a} {b} {a}")
+}
+
+/// ASCII text of exactly `len` bytes that differs from row to row.
+fn ascii_value(row: usize, len: usize) -> String {
+    let base = format!("datafusion row {row} ");
+    base.repeat(len / base.len() + 1)[..len].to_string()
+}
+
+/// Returns the named input arrays.
+///
+/// Entirely ASCII, which take the all-ASCII array fast path:
+///
+/// - `all_ascii_utf8_rows*`: 32-byte values, 20% NULL.
+/// - `all_ascii_utf8_sliced`: 128 rows sliced from the middle of a larger
+///   array, so the input's buffers are much larger than the rows it uses.
+/// - `all_ascii_utf8view_*`: values of `len` bytes, or with `_mixed`, half
+///   under 12 bytes (stored inline in the view) and half of 12 to
+///   `max(30, len)` bytes.
+///
+/// Not entirely ASCII, so each row is converted on its own:
+///
+/// - `some_non_ascii_utf8view_*`: 30-character values, about 10% of them
+///   non-ASCII.
+/// - `non_ascii_words_*`: every value is three words from [`WORDS`].
+/// - `mostly_ascii_*`: ASCII values plus one non-ASCII value in the middle.
+/// - `late_non_ascii_*`: every value is ASCII text followed by one non-ASCII
+///   character.
+pub fn inputs() -> Vec<(String, ArrayRef)> {
+    let mut inputs: Vec<(String, ArrayRef)> = Vec::new();
+
+    for size in [1024, 4096, 8192] {
+        inputs.push((
+            format!("all_ascii_utf8_rows{size}"),
+            Arc::new(create_string_array_with_len::<i32>(size, 0.2, 32)),
+        ));
+    }
+
+    let parent_size = 65536;
+    let slice_len = 128;
+    let parent = create_string_array_with_len::<i32>(parent_size, 0.2, 32);
+    inputs.push((
+        "all_ascii_utf8_sliced".to_string(),
+        Arc::new(parent.slice((parent_size - slice_len) / 2, slice_len)),
+    ));
+
+    for size in [4096, 8192] {
+        for str_len in [10, 64, 128] {
+            for null_density in [0.0, 0.1] {
+                for mixed in [false, true] {
+                    let suffix = if mixed { "_mixed" } else { "" };
+                    inputs.push((
+                        format!(
+                            
"all_ascii_utf8view_rows{size}_len{str_len}_nulls{null_density}{suffix}"
+                        ),
+                        Arc::new(create_string_view_array_with_len(
+                            size,
+                            null_density,
+                            str_len,
+                            mixed,
+                        )),
+                    ));
+                }
+            }
+        }
+    }
+
+    for size in [4096, 8192] {
+        for null_density in [0.0, 0.1] {
+            let array = gen_string_array(size, 30, null_density, 0.1, true)
+                .remove(0)
+                .into_array(size)
+                .unwrap();
+            inputs.push((
+                
format!("some_non_ascii_utf8view_rows{size}_nulls{null_density}"),
+                array,
+            ));
+        }
+    }
+
+    let words = build_values(word_value);
+    inputs.push((
+        "non_ascii_words_utf8".to_string(),
+        Arc::new(StringArray::from(words.clone())),

Review Comment:
   `words.clone()` here and `values.clone()` in the `mostly_ascii` and 
`late_non_ascii` loop deep-copy 4096 `String`s for each extra array type. 
Building the `Utf8` array once and deriving `LargeUtf8` and `Utf8View` with 
`arrow::compute::cast` removes the copies and the `Vec<Option<String>>` that 
lives alongside the arrays.



##########
datafusion/functions/src/string/common.rs:
##########
@@ -390,38 +390,48 @@ fn unicode_case(s: &str, lower: bool) -> String {
     }
 }
 
-/// Like [`unicode_case`], but uppercases into `buf` so its allocation is 
reused
-/// across rows. Lowercasing still allocates, see [`write_unicode_case`].
+/// Appends `s` to `builder` with its case converted.
+///
+/// An ASCII value is converted byte by byte straight into the builder. Other
+/// values go through `str::to_lowercase` / `str::to_uppercase`, which allocate

Review Comment:
   The removed doc on `write_unicode_case` explained why lowercasing cannot be 
streamed per character (the final sigma rule needs context). That invariant is 
what stops someone from reintroducing the streaming path, so one sentence of it 
is worth keeping here.



##########
datafusion/functions/src/strings.rs:
##########
@@ -829,38 +832,78 @@ impl StringViewArrayBuilder {
         Self::make_long_view_checked(length, buffer_index, offset, 
prefix_bytes)
     }
 
-    /// See [`BulkNullStringArrayBuilder::append_byte_map`].
+    /// Fallible variant of [`Self::append_byte_map`].
     ///
     /// # Safety
     ///
     /// The bytes produced by applying `map` to each byte of `src`, in order,
     /// must form valid UTF-8.
     ///
-    /// # Panics
+    /// # Errors
     ///
-    /// Panics under the same conditions as [`Self::append_value`]: if
-    /// `src.len()`, the in-progress buffer offset, or the number of completed
-    /// buffers exceeds `i32::MAX`.
+    /// Returns an error under the same conditions as
+    /// [`Self::try_append_value`].
     #[inline]
-    pub unsafe fn append_byte_map<F: FnMut(u8) -> u8>(&mut self, src: &[u8], 
mut map: F) {
-        let length: u32 =
-            i32::try_from(src.len()).expect("value length exceeds i32::MAX") 
as u32;
-        if length <= 12 {
-            let mut bytes = [0u8; 12];
-            for (d, &b) in bytes[..src.len()].iter_mut().zip(src) {
+    pub unsafe fn try_append_byte_map<F: FnMut(u8) -> u8>(

Review Comment:
   For `Utf8` and `LargeUtf8` the error comes from `try_append_bytes`, which 
`generic_string_builder_try_append_bytes_overflow` already covers, and 
`try_append_byte_map` only delegates to it. The view branches need a source 
slice or buffer above 2 GiB to reach, and `try_append_value` has no overflow 
test either, so I would not hold the PR on this.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to