|
| 1 | +// Licensed to the Apache Software Foundation (ASF) under one |
| 2 | +// or more contributor license agreements. See the NOTICE file |
| 3 | +// distributed with this work for additional information |
| 4 | +// regarding copyright ownership. The ASF licenses this file |
| 5 | +// to you under the Apache License, Version 2.0 (the |
| 6 | +// "License"); you may not use this file except in compliance |
| 7 | +// with the License. You may obtain a copy of the License at |
| 8 | +// |
| 9 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 10 | +// |
| 11 | +// Unless required by applicable law or agreed to in writing, |
| 12 | +// software distributed under the License is distributed on an |
| 13 | +// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY |
| 14 | +// KIND, either express or implied. See the License for the |
| 15 | +// specific language governing permissions and limitations |
| 16 | +// under the License. |
| 17 | + |
| 18 | +use std::any::Any; |
| 19 | +use std::sync::Arc; |
| 20 | + |
| 21 | +use arrow::compute::cast; |
| 22 | +use arrow::{ |
| 23 | + array::{Array, ArrayRef, Float64Array, PrimitiveArray}, |
| 24 | + datatypes::{ArrowNumericType, ArrowTemporalType, DataType}, |
| 25 | +}; |
| 26 | +use arrow::{compute::kernels::temporal, datatypes::TimeUnit}; |
| 27 | +use datafusion_common::cast::{ |
| 28 | + as_date32_array, as_date64_array, as_timestamp_microsecond_array, |
| 29 | + as_timestamp_millisecond_array, as_timestamp_nanosecond_array, |
| 30 | + as_timestamp_second_array, |
| 31 | +}; |
| 32 | +use datafusion_common::{exec_err, Result, ScalarValue}; |
| 33 | +use datafusion_expr::{ |
| 34 | + ColumnarValue, ScalarUDFImpl, Signature, TypeSignature::Exact, Volatility, |
| 35 | + TIMEZONE_WILDCARD, |
| 36 | +}; |
| 37 | +use DataType::{Date32, Date64, Timestamp, Utf8}; |
| 38 | +use TimeUnit::{Microsecond, Millisecond, Nanosecond, Second}; |
| 39 | + |
| 40 | +fn to_ticks<T>(array: &PrimitiveArray<T>, frac: i32) -> Result<Float64Array> |
| 41 | +where |
| 42 | + T: ArrowTemporalType + ArrowNumericType, |
| 43 | + i64: From<T::Native>, |
| 44 | +{ |
| 45 | + let zipped = temporal::second(array)? |
| 46 | + .values() |
| 47 | + .iter() |
| 48 | + .zip(temporal::nanosecond(array)?.values().iter()) |
| 49 | + .map(|o| ((*o.0 as f64 + (*o.1 as f64) / 1_000_000_000.0) * (frac as f64))) |
| 50 | + .collect::<Vec<f64>>(); |
| 51 | + |
| 52 | + Ok(Float64Array::from(zipped)) |
| 53 | +} |
| 54 | + |
| 55 | +fn seconds<T>(array: &PrimitiveArray<T>) -> Result<Float64Array> |
| 56 | +where |
| 57 | + T: ArrowTemporalType + ArrowNumericType, |
| 58 | + i64: From<T::Native>, |
| 59 | +{ |
| 60 | + to_ticks(array, 1) |
| 61 | +} |
| 62 | + |
| 63 | +fn millis<T>(array: &PrimitiveArray<T>) -> Result<Float64Array> |
| 64 | +where |
| 65 | + T: ArrowTemporalType + ArrowNumericType, |
| 66 | + i64: From<T::Native>, |
| 67 | +{ |
| 68 | + to_ticks(array, 1_000) |
| 69 | +} |
| 70 | + |
| 71 | +fn micros<T>(array: &PrimitiveArray<T>) -> Result<Float64Array> |
| 72 | +where |
| 73 | + T: ArrowTemporalType + ArrowNumericType, |
| 74 | + i64: From<T::Native>, |
| 75 | +{ |
| 76 | + to_ticks(array, 1_000_000) |
| 77 | +} |
| 78 | + |
| 79 | +fn nanos<T>(array: &PrimitiveArray<T>) -> Result<Float64Array> |
| 80 | +where |
| 81 | + T: ArrowTemporalType + ArrowNumericType, |
| 82 | + i64: From<T::Native>, |
| 83 | +{ |
| 84 | + to_ticks(array, 1_000_000_000) |
| 85 | +} |
| 86 | + |
| 87 | +fn epoch<T>(array: &PrimitiveArray<T>) -> Result<Float64Array> |
| 88 | +where |
| 89 | + T: ArrowTemporalType + ArrowNumericType, |
| 90 | + i64: From<T::Native>, |
| 91 | +{ |
| 92 | + let b = match array.data_type() { |
| 93 | + DataType::Timestamp(tu, _) => { |
| 94 | + let scale = match tu { |
| 95 | + TimeUnit::Second => 1, |
| 96 | + TimeUnit::Millisecond => 1_000, |
| 97 | + TimeUnit::Microsecond => 1_000_000, |
| 98 | + TimeUnit::Nanosecond => 1_000_000_000, |
| 99 | + } as f64; |
| 100 | + array.unary(|n| { |
| 101 | + let n: i64 = n.into(); |
| 102 | + n as f64 / scale |
| 103 | + }) |
| 104 | + } |
| 105 | + DataType::Date32 => { |
| 106 | + let seconds_in_a_day = 86400_f64; |
| 107 | + array.unary(|n| { |
| 108 | + let n: i64 = n.into(); |
| 109 | + n as f64 * seconds_in_a_day |
| 110 | + }) |
| 111 | + } |
| 112 | + DataType::Date64 => array.unary(|n| { |
| 113 | + let n: i64 = n.into(); |
| 114 | + n as f64 / 1_000_f64 |
| 115 | + }), |
| 116 | + _ => return exec_err!("Can not convert {:?} to epoch", array.data_type()), |
| 117 | + }; |
| 118 | + Ok(b) |
| 119 | +} |
| 120 | + |
| 121 | +macro_rules! extract_date_part { |
| 122 | + ($ARRAY: expr, $FN:expr) => { |
| 123 | + match $ARRAY.data_type() { |
| 124 | + DataType::Date32 => { |
| 125 | + let array = as_date32_array($ARRAY)?; |
| 126 | + Ok($FN(array) |
| 127 | + .map(|v| cast(&(Arc::new(v) as ArrayRef), &DataType::Float64))?) |
| 128 | + } |
| 129 | + DataType::Date64 => { |
| 130 | + let array = as_date64_array($ARRAY)?; |
| 131 | + Ok($FN(array) |
| 132 | + .map(|v| cast(&(Arc::new(v) as ArrayRef), &DataType::Float64))?) |
| 133 | + } |
| 134 | + DataType::Timestamp(time_unit, _) => match time_unit { |
| 135 | + TimeUnit::Second => { |
| 136 | + let array = as_timestamp_second_array($ARRAY)?; |
| 137 | + Ok($FN(array) |
| 138 | + .map(|v| cast(&(Arc::new(v) as ArrayRef), &DataType::Float64))?) |
| 139 | + } |
| 140 | + TimeUnit::Millisecond => { |
| 141 | + let array = as_timestamp_millisecond_array($ARRAY)?; |
| 142 | + Ok($FN(array) |
| 143 | + .map(|v| cast(&(Arc::new(v) as ArrayRef), &DataType::Float64))?) |
| 144 | + } |
| 145 | + TimeUnit::Microsecond => { |
| 146 | + let array = as_timestamp_microsecond_array($ARRAY)?; |
| 147 | + Ok($FN(array) |
| 148 | + .map(|v| cast(&(Arc::new(v) as ArrayRef), &DataType::Float64))?) |
| 149 | + } |
| 150 | + TimeUnit::Nanosecond => { |
| 151 | + let array = as_timestamp_nanosecond_array($ARRAY)?; |
| 152 | + Ok($FN(array) |
| 153 | + .map(|v| cast(&(Arc::new(v) as ArrayRef), &DataType::Float64))?) |
| 154 | + } |
| 155 | + }, |
| 156 | + datatype => exec_err!("Extract does not support datatype {:?}", datatype), |
| 157 | + } |
| 158 | + }; |
| 159 | +} |
| 160 | + |
| 161 | +#[derive(Debug)] |
| 162 | +pub struct DatePartFunc { |
| 163 | + signature: Signature, |
| 164 | + aliases: Vec<String>, |
| 165 | +} |
| 166 | + |
| 167 | +impl DatePartFunc { |
| 168 | + pub fn new() -> Self { |
| 169 | + Self { |
| 170 | + signature: Signature::one_of( |
| 171 | + vec![ |
| 172 | + Exact(vec![Utf8, Timestamp(Nanosecond, None)]), |
| 173 | + Exact(vec![ |
| 174 | + Utf8, |
| 175 | + Timestamp(Nanosecond, Some(TIMEZONE_WILDCARD.into())), |
| 176 | + ]), |
| 177 | + Exact(vec![Utf8, Timestamp(Millisecond, None)]), |
| 178 | + Exact(vec![ |
| 179 | + Utf8, |
| 180 | + Timestamp(Millisecond, Some(TIMEZONE_WILDCARD.into())), |
| 181 | + ]), |
| 182 | + Exact(vec![Utf8, Timestamp(Microsecond, None)]), |
| 183 | + Exact(vec![ |
| 184 | + Utf8, |
| 185 | + Timestamp(Microsecond, Some(TIMEZONE_WILDCARD.into())), |
| 186 | + ]), |
| 187 | + Exact(vec![Utf8, Timestamp(Second, None)]), |
| 188 | + Exact(vec![ |
| 189 | + Utf8, |
| 190 | + Timestamp(Second, Some(TIMEZONE_WILDCARD.into())), |
| 191 | + ]), |
| 192 | + Exact(vec![Utf8, Date64]), |
| 193 | + Exact(vec![Utf8, Date32]), |
| 194 | + ], |
| 195 | + Volatility::Immutable, |
| 196 | + ), |
| 197 | + aliases: vec![String::from("date_part"), String::from("datepart")], |
| 198 | + } |
| 199 | + } |
| 200 | +} |
| 201 | + |
| 202 | +impl ScalarUDFImpl for DatePartFunc { |
| 203 | + fn as_any(&self) -> &dyn Any { |
| 204 | + self |
| 205 | + } |
| 206 | + |
| 207 | + fn name(&self) -> &str { |
| 208 | + "date_part" |
| 209 | + } |
| 210 | + |
| 211 | + fn aliases(&self) -> &[String] { |
| 212 | + &self.aliases |
| 213 | + } |
| 214 | + |
| 215 | + fn signature(&self) -> &Signature { |
| 216 | + &self.signature |
| 217 | + } |
| 218 | + |
| 219 | + fn return_type(&self, _arg_types: &[DataType]) -> Result<DataType> { |
| 220 | + Ok(DataType::Float64) |
| 221 | + } |
| 222 | + |
| 223 | + fn invoke(&self, args: &[ColumnarValue]) -> Result<ColumnarValue> { |
| 224 | + if args.len() != 2 { |
| 225 | + return exec_err!("Expected two arguments in DATE_PART"); |
| 226 | + } |
| 227 | + let (date_part, array) = (&args[0], &args[1]); |
| 228 | + |
| 229 | + let date_part = |
| 230 | + if let ColumnarValue::Scalar(ScalarValue::Utf8(Some(v))) = date_part { |
| 231 | + v |
| 232 | + } else { |
| 233 | + return exec_err!( |
| 234 | + "First argument of `DATE_PART` must be non-null scalar Utf8" |
| 235 | + ); |
| 236 | + }; |
| 237 | + |
| 238 | + let is_scalar = matches!(array, ColumnarValue::Scalar(_)); |
| 239 | + |
| 240 | + let array = match array { |
| 241 | + ColumnarValue::Array(array) => array.clone(), |
| 242 | + ColumnarValue::Scalar(scalar) => scalar.to_array()?, |
| 243 | + }; |
| 244 | + |
| 245 | + let arr = match date_part.to_lowercase().as_str() { |
| 246 | + "year" => extract_date_part!(&array, temporal::year), |
| 247 | + "quarter" => extract_date_part!(&array, temporal::quarter), |
| 248 | + "month" => extract_date_part!(&array, temporal::month), |
| 249 | + "week" => extract_date_part!(&array, temporal::week), |
| 250 | + "day" => extract_date_part!(&array, temporal::day), |
| 251 | + "doy" => extract_date_part!(&array, temporal::doy), |
| 252 | + "dow" => extract_date_part!(&array, temporal::num_days_from_sunday), |
| 253 | + "hour" => extract_date_part!(&array, temporal::hour), |
| 254 | + "minute" => extract_date_part!(&array, temporal::minute), |
| 255 | + "second" => extract_date_part!(&array, seconds), |
| 256 | + "millisecond" => extract_date_part!(&array, millis), |
| 257 | + "microsecond" => extract_date_part!(&array, micros), |
| 258 | + "nanosecond" => extract_date_part!(&array, nanos), |
| 259 | + "epoch" => extract_date_part!(&array, epoch), |
| 260 | + _ => exec_err!("Date part '{date_part}' not supported"), |
| 261 | + }?; |
| 262 | + |
| 263 | + Ok(if is_scalar { |
| 264 | + ColumnarValue::Scalar(ScalarValue::try_from_array(&arr?, 0)?) |
| 265 | + } else { |
| 266 | + ColumnarValue::Array(arr?) |
| 267 | + }) |
| 268 | + } |
| 269 | +} |
0 commit comments