1use vortex_array::AnyColumnar;
5use vortex_array::ArrayRef;
6use vortex_array::ExecutionCtx;
7use vortex_array::IntoArray;
8use vortex_array::arrays::ConstantArray;
9use vortex_array::arrays::VarBinViewArray;
10use vortex_array::builders::ArrayBuilder;
11use vortex_array::builders::VarBinViewBuilder;
12use vortex_array::dtype::DType;
13use vortex_array::require_input;
14use vortex_array::scalar::Scalar;
15use vortex_array::scalar_fn::Arity;
16use vortex_array::scalar_fn::ChildName;
17use vortex_array::scalar_fn::EmptyOptions;
18use vortex_array::scalar_fn::ExecutionArgs;
19use vortex_array::scalar_fn::ScalarFnExecutionResult;
20use vortex_array::scalar_fn::ScalarFnId;
21use vortex_array::scalar_fn::ScalarFnVTable;
22use vortex_error::VortexResult;
23use vortex_error::vortex_bail;
24use vortex_error::vortex_err;
25use vortex_session::VortexSession;
26use vortex_session::registry::CachedId;
27#[derive(Clone)]
32pub struct Lower;
33
34impl ScalarFnVTable for Lower {
35 type Options = EmptyOptions;
36
37 fn id(&self) -> ScalarFnId {
38 static ID: CachedId = CachedId::new("vortex.lower");
39 *ID
40 }
41
42 fn serialize(&self, _options: &Self::Options) -> VortexResult<Option<Vec<u8>>> {
43 Ok(Some(vec![]))
44 }
45
46 fn deserialize(
47 &self,
48 _metadata: &[u8],
49 _session: &VortexSession,
50 ) -> VortexResult<Self::Options> {
51 Ok(EmptyOptions)
52 }
53
54 fn arity(&self, _options: &Self::Options) -> Arity {
55 Arity::Exact(1)
56 }
57
58 fn child_name(&self, _options: &Self::Options, child_idx: usize) -> ChildName {
59 match child_idx {
60 0 => ChildName::from("input"),
61 _ => unreachable!("Invalid child index {child_idx} for lower()"),
62 }
63 }
64
65 fn return_dtype(&self, _options: &Self::Options, arg_dtypes: &[DType]) -> VortexResult<DType> {
66 match &arg_dtypes[0] {
67 dtype @ DType::Utf8(_) => Ok(dtype.clone()),
68 other => vortex_bail!("lower() requires Utf8, got {other}"),
69 }
70 }
71
72 fn execute(
73 &self,
74 _options: &Self::Options,
75 args: &dyn ExecutionArgs,
76 ctx: &mut ExecutionCtx,
77 ) -> VortexResult<ArrayRef> {
78 let input = args.get(0)?;
79 if let Some(scalar) = input.as_constant() {
80 let lowered = match scalar.as_utf8().value() {
81 Some(value) => Scalar::utf8(value.to_lowercase(), input.dtype().nullability()),
82 None => Scalar::null(input.dtype().clone()),
83 };
84 return Ok(ConstantArray::new(lowered, args.row_count()).into_array());
85 }
86 lower(input.execute::<VarBinViewArray>(ctx)?, ctx)
87 }
88
89 fn execute_step(
90 &self,
91 options: &Self::Options,
92 args: &dyn ExecutionArgs,
93 ctx: &mut ExecutionCtx,
94 ) -> VortexResult<ScalarFnExecutionResult> {
95 require_input!(args, 0 => AnyColumnar);
96 self.execute(options, args, ctx)
97 .map(ScalarFnExecutionResult::done)
98 }
99
100 fn is_strict(&self, _options: &Self::Options) -> bool {
101 true
102 }
103
104 fn is_infallible(&self, _options: &Self::Options) -> bool {
105 true
106 }
107}
108
109fn lower(input: VarBinViewArray, ctx: &mut ExecutionCtx) -> VortexResult<ArrayRef> {
110 let views = input.resolved_views();
111 let validity = input.validity()?.execute_mask(input.len(), ctx)?;
112 if (0..input.len()).all(|i| !validity.value(i) || is_lowercase_ascii(views.bytes(i))) {
114 return Ok(input.into_array());
115 }
116
117 let mut builder = VarBinViewBuilder::with_capacity_in(
118 input.dtype().clone(),
119 input.len(),
120 ctx.allocator().clone(),
121 );
122 let mut ascii = Vec::new();
123 for i in 0..input.len() {
124 if !validity.value(i) {
125 builder.append_null();
126 continue;
127 }
128 let bytes = views.bytes(i);
129 if bytes.is_ascii() {
130 ascii.clear();
131 ascii.extend(bytes.iter().map(u8::to_ascii_lowercase));
132 builder.append_value(&ascii);
133 } else {
134 let value = std::str::from_utf8(bytes)
135 .map_err(|e| vortex_err!("lower() input is not valid UTF-8: {e}"))?;
136 builder.append_value(value.to_lowercase());
137 }
138 }
139 Ok(builder.finish_into_varbinview().into_array())
140}
141
142pub(crate) fn is_lowercase_ascii(bytes: &[u8]) -> bool {
144 bytes
145 .iter()
146 .all(|byte| byte.is_ascii() && !byte.is_ascii_uppercase())
147}
148
149#[cfg(test)]
150mod tests {
151 use std::ops::Range;
152 use std::sync::LazyLock;
153
154 use rstest::rstest;
155 use vortex_array::ArrayRef;
156 use vortex_array::IntoArray;
157 use vortex_array::VortexSessionExecute;
158 use vortex_array::arrays::Constant;
159 use vortex_array::arrays::ConstantArray;
160 use vortex_array::arrays::DictArray;
161 use vortex_array::arrays::PrimitiveArray;
162 use vortex_array::arrays::RunEnd;
163 use vortex_array::arrays::VarBinViewArray;
164 use vortex_array::assert_arrays_eq;
165 use vortex_array::scalar::Scalar;
166 use vortex_error::VortexResult;
167 use vortex_expr::ArrayExprExt;
168 use vortex_expr::Expression;
169 use vortex_expr::proto::ExprSerializeProtoExt;
170 use vortex_expr::root;
171 use vortex_session::VortexSession;
172
173 use crate::expr::lower;
174
175 static SESSION: LazyLock<VortexSession> = LazyLock::new(|| {
176 let session = VortexSession::empty();
177 vortex_array::initialize(&session);
178 crate::initialize(&session);
179 session
180 });
181
182 fn strings(values: &[Option<&str>]) -> ArrayRef {
183 VarBinViewArray::from_iter_nullable_str(values.iter().copied()).into_array()
184 }
185
186 #[rstest]
187 #[case::ascii(&[Some("GrEaT-LaKeS"), None, Some("")], &[Some("great-lakes"), None, Some("")])]
188 #[case::final_sigma(&[Some("ΟΣ"), Some("ΟΣΑ")], &[Some("ος"), Some("οσα")])]
189 #[case::expanding(&[Some("İȾ")], &[Some("i\u{307}ⱦ")])]
190 #[case::already_lowercase(&[Some("great-lakes"), None], &[Some("great-lakes"), None])]
191 fn lowercases(
192 #[case] input: &[Option<&str>],
193 #[case] expected: &[Option<&str>],
194 ) -> VortexResult<()> {
195 let mut ctx = SESSION.create_execution_ctx();
196 assert_arrays_eq!(
197 strings(input).apply(&lower(root()))?,
198 strings(expected),
199 &mut ctx
200 );
201 Ok(())
202 }
203
204 #[test]
205 fn roundtrips_through_proto() -> VortexResult<()> {
206 let expr = lower(root());
207 assert_eq!(
208 Expression::from_proto(&expr.serialize_proto()?, &SESSION)?,
209 expr
210 );
211 Ok(())
212 }
213
214 #[rstest]
215 #[case::whole(0..8)]
216 #[case::sliced(1..7)]
217 fn preserves_runs_and_dictionary(#[case] rows: Range<usize>) -> VortexResult<()> {
218 let mut ctx = SESSION.create_execution_ctx();
219 let values = DictArray::try_new(
220 PrimitiveArray::from_iter([0u8, 1, 2, 0]).into_array(),
221 strings(&[Some("ΟΣ"), None, Some("İȾ")]),
222 )?
223 .into_array();
224 let input = RunEnd::try_new_offset_length(
225 PrimitiveArray::from_iter([3u32, 5, 7, 10]).into_array(),
226 values,
227 1,
228 8,
229 &mut ctx,
230 )?
231 .into_array()
232 .slice(rows.clone())?;
233 let result = input
234 .apply(&lower(root()))?
235 .execute_until::<RunEnd>(&mut ctx)?;
236 assert!(result.is::<RunEnd>());
237 assert_arrays_eq!(
238 result,
239 strings(
240 &[
241 Some("ος"),
242 Some("ος"),
243 None,
244 None,
245 Some("i\u{307}ⱦ"),
246 Some("i\u{307}ⱦ"),
247 Some("ος"),
248 Some("ος"),
249 ][rows]
250 ),
251 &mut ctx
252 );
253 Ok(())
254 }
255
256 #[rstest]
257 #[case(Some("ΟΣ"), Some("ος"))]
258 #[case(None, None)]
259 fn preserves_constants(
260 #[case] input: Option<&str>,
261 #[case] expected: Option<&str>,
262 ) -> VortexResult<()> {
263 let mut ctx = SESSION.create_execution_ctx();
264 let result = ConstantArray::new(Scalar::from(input), 1024)
265 .into_array()
266 .apply(&lower(root()))?
267 .execute_until::<Constant>(&mut ctx)?;
268 assert!(result.is::<Constant>());
269 assert_arrays_eq!(
270 result,
271 ConstantArray::new(Scalar::from(expected), 1024),
272 &mut ctx
273 );
274 Ok(())
275 }
276}