Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/source/user-guide/latest/expressions.md
Original file line number Diff line number Diff line change
Expand Up @@ -414,7 +414,7 @@ The type-name conversion functions (`bigint`, `binary`, `boolean`, `date`, `deci
| Function | Status | Implementation | Notes |
| --- | --- | --- | --- |
| `%` | ✅ | Native | |
| `*` | ✅ | Native | Interval multiplication falls back |
| `*` | ✅ | Hybrid | YearMonth and DayTime interval multiplication routes through the JVM codegen dispatcher; Calendar interval multiplication falls back |
| `+` | ✅ | Native | |
| `-` | ✅ | Native | |
| `/` | ✅ | Native | |
Expand Down
20 changes: 16 additions & 4 deletions native/core/src/execution/planner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,9 @@ use crate::execution::{
};
use crate::jvm_bridge::{jni_call, JVMClasses};
use arrow::compute::CastOptions;
use arrow::datatypes::{DataType, Field, FieldRef, Schema, TimeUnit, DECIMAL128_MAX_PRECISION};
use arrow::datatypes::{
DataType, Field, FieldRef, IntervalUnit, Schema, TimeUnit, DECIMAL128_MAX_PRECISION,
};
use arrow::ffi_stream::FFI_ArrowArrayStream;
use datafusion::functions_aggregate::bit_and_or_xor::{bit_and_udaf, bit_or_udaf, bit_xor_udaf};
use datafusion::functions_aggregate::count::count_udaf;
Expand Down Expand Up @@ -105,8 +107,8 @@ use datafusion::physical_expr::LexOrdering;
use crate::parquet::parquet_exec::init_datasource_exec;
use arrow::array::{
new_empty_array, Array, ArrayRef, BinaryBuilder, BooleanArray, Date32Array, Decimal128Array,
Float32Array, Float64Array, Int16Array, Int32Array, Int64Array, Int8Array, ListArray,
NullArray, StringBuilder, TimestampMicrosecondArray,
Float32Array, Float64Array, Int16Array, Int32Array, Int64Array, Int8Array,
IntervalYearMonthArray, ListArray, NullArray, StringBuilder, TimestampMicrosecondArray,
};
use arrow::buffer::{BooleanBuffer, NullBuffer, OffsetBuffer};
use arrow::row::{OwnedRow, RowConverter, SortField};
Expand Down Expand Up @@ -490,6 +492,9 @@ impl PhysicalPlanner {
DataType::Time64(TimeUnit::Nanosecond) => {
ScalarValue::Time64Nanosecond(None)
}
DataType::Interval(IntervalUnit::YearMonth) => {
ScalarValue::IntervalYearMonth(None)
}
DataType::Duration(TimeUnit::Microsecond) => {
ScalarValue::DurationMicrosecond(None)
}
Expand All @@ -505,9 +510,12 @@ impl PhysicalPlanner {
Value::IntVal(value) => match data_type {
DataType::Int32 => ScalarValue::Int32(Some(*value)),
DataType::Date32 => ScalarValue::Date32(Some(*value)),
DataType::Interval(IntervalUnit::YearMonth) => {
ScalarValue::IntervalYearMonth(Some(*value))
}
dt => {
return Err(GeneralError(format!(
"Expected either 'Int32' or 'Date32' for IntVal, but found {dt:?}"
"Expected either 'Int32', 'Date32', or 'Interval(YearMonth)' for IntVal, but found {dt:?}"
)))
}
},
Expand Down Expand Up @@ -4283,6 +4291,10 @@ fn literal_to_array_ref(
list_literal.int_values.into(),
Some(nulls.clone().into()),
))),
DataType::Interval(IntervalUnit::YearMonth) => Ok(Arc::new(IntervalYearMonthArray::new(
list_literal.int_values.into(),
Some(nulls.clone().into()),
))),
DataType::Timestamp(TimeUnit::Microsecond, None) => {
Ok(Arc::new(TimestampMicrosecondArray::new(
list_literal.long_values.into(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ private[codegen] object CometBatchKernelCodegenInput extends CometTypeShim {
classOf[TinyIntVector],
classOf[SmallIntVector],
classOf[IntVector],
classOf[IntervalYearVector],
classOf[BigIntVector],
classOf[Float4Vector],
classOf[Float8Vector],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,7 @@ object QueryPlanSerde extends Logging with CometExprShim with CometTypeShim {
classOf[MicrosToTimestamp] -> CometMicrosToTimestamp,
classOf[MillisToTimestamp] -> CometMillisToTimestamp,
classOf[MonthsBetween] -> CometMonthsBetween,
classOf[MultiplyYMInterval] -> CometMultiplyYMInterval,
classOf[Minute] -> CometMinute,
classOf[NextDay] -> CometNextDay,
classOf[PreciseTimestampConversion] -> CometPreciseTimestampConversion,
Expand Down Expand Up @@ -534,7 +535,7 @@ object QueryPlanSerde extends Logging with CometExprShim with CometTypeShim {
def supportedDataType(dt: DataType, allowComplex: Boolean = false): Boolean = dt match {
case _: ByteType | _: ShortType | _: IntegerType | _: LongType | _: FloatType |
_: DoubleType | _: StringType | _: BinaryType | _: TimestampType | _: TimestampNTZType |
_: DecimalType | _: DateType | _: BooleanType | _: NullType | CalendarIntervalType =>
_: DecimalType | _: DateType | _: BooleanType | _: NullType =>

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Moved CalendarIntervalType under CometLiteral#getSupportLevel

true
case dt if isTimeType(dt) =>
true
Expand Down
4 changes: 3 additions & 1 deletion spark/src/main/scala/org/apache/comet/serde/datetime.scala
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ package org.apache.comet.serde

import java.util.Locale

import org.apache.spark.sql.catalyst.expressions.{AddMonths, Attribute, Cast, ConvertTimezone, DateAdd, DateDiff, DateFormatClass, DateFromUnixDate, DateSub, DayOfMonth, DayOfWeek, DayOfYear, Days, Expression, FromUTCTimestamp, GetDateField, GetTimestamp, Hour, Hours, LastDay, Literal, MakeDate, MakeDTInterval, MakeInterval, MakeTimestamp, MakeYMInterval, MicrosToTimestamp, MillisToTimestamp, Minute, Month, MonthsBetween, MultiplyDTInterval, NextDay, PreciseTimestampConversion, Quarter, Second, SecondsToTimestamp, TimestampAdd, TimestampDiff, ToUnixTimestamp, ToUTCTimestamp, TruncDate, TruncTimestamp, UnixDate, UnixMicros, UnixMillis, UnixSeconds, UnixTimestamp, WeekDay, WeekOfYear, Year}
import org.apache.spark.sql.catalyst.expressions.{AddMonths, Attribute, Cast, ConvertTimezone, DateAdd, DateDiff, DateFormatClass, DateFromUnixDate, DateSub, DayOfMonth, DayOfWeek, DayOfYear, Days, Expression, FromUTCTimestamp, GetDateField, GetTimestamp, Hour, Hours, LastDay, Literal, MakeDate, MakeDTInterval, MakeInterval, MakeTimestamp, MakeYMInterval, MicrosToTimestamp, MillisToTimestamp, Minute, Month, MonthsBetween, MultiplyDTInterval, MultiplyYMInterval, NextDay, PreciseTimestampConversion, Quarter, Second, SecondsToTimestamp, TimestampAdd, TimestampDiff, ToUnixTimestamp, ToUTCTimestamp, TruncDate, TruncTimestamp, UnixDate, UnixMicros, UnixMillis, UnixSeconds, UnixTimestamp, WeekDay, WeekOfYear, Year}
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.types.{CalendarIntervalType, DataType, DateType, DoubleType, FloatType, IntegerType, LongType, StringType, TimestampNTZType, TimestampType}
import org.apache.spark.unsafe.types.UTF8String
Expand Down Expand Up @@ -955,6 +955,8 @@ object CometGetTimestamp extends CometCodegenDispatch[GetTimestamp]

object CometMakeYMInterval extends CometCodegenDispatch[MakeYMInterval]

object CometMultiplyYMInterval extends CometCodegenDispatch[MultiplyYMInterval]

object CometMakeDTInterval extends CometCodegenDispatch[MakeDTInterval]

object CometMakeInterval extends CometExpressionSerde[MakeInterval] with CodegenDispatchFallback {
Expand Down
24 changes: 14 additions & 10 deletions spark/src/main/scala/org/apache/comet/serde/literals.scala
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ import java.lang
import org.apache.spark.internal.Logging
import org.apache.spark.sql.catalyst.expressions.{Attribute, Literal}
import org.apache.spark.sql.catalyst.util.ArrayData
import org.apache.spark.sql.types.{ArrayType, BinaryType, BooleanType, ByteType, DateType, DayTimeIntervalType, Decimal, DecimalType, DoubleType, FloatType, IntegerType, LongType, NullType, ShortType, StringType, TimestampNTZType, TimestampType}
import org.apache.spark.sql.types.{ArrayType, BinaryType, BooleanType, ByteType, CalendarIntervalType, DateType, DayTimeIntervalType, Decimal, DecimalType, DoubleType, FloatType, IntegerType, LongType, NullType, ShortType, StringType, TimestampNTZType, TimestampType, YearMonthIntervalType}
import org.apache.spark.unsafe.types.UTF8String

import com.google.protobuf.ByteString
Expand All @@ -41,24 +41,27 @@ object CometLiteral extends CometExpressionSerde[Literal] with Logging {
"Not all data types are supported for literal values")

override def getSupportLevel(expr: Literal): SupportLevel = {

val dataType = expr.dataType
if (supportedDataType(
expr.dataType,
dataType,
allowComplex = expr.value == null ||

// Nested literal support for native reader
// can be tracked https://github.com/apache/datafusion-comet/issues/1937
(expr.dataType
(dataType
.isInstanceOf[ArrayType] && (!isComplexType(
expr.dataType.asInstanceOf[ArrayType].elementType) || expr.dataType
dataType.asInstanceOf[ArrayType].elementType) || dataType
.asInstanceOf[ArrayType]
.elementType
.isInstanceOf[ArrayType])))) {
Compatible(None)
} else {
expr.dataType match {
case _: DayTimeIntervalType => Compatible(None)
case _ => Unsupported(Some(s"Unsupported data type ${expr.dataType}"))
dataType match {
// Keep interval types out of QueryPlanSerde.supportedDataType, which gates broader native
// paths.
case _: DayTimeIntervalType | _: YearMonthIntervalType | CalendarIntervalType =>
Compatible(None)
case _ => Unsupported(Some(s"Unsupported data type $dataType"))
}
}
}
Expand All @@ -80,7 +83,8 @@ object CometLiteral extends CometExpressionSerde[Literal] with Logging {
case _: BooleanType => exprBuilder.setBoolVal(value.asInstanceOf[Boolean])
case _: ByteType => exprBuilder.setByteVal(value.asInstanceOf[Byte])
case _: ShortType => exprBuilder.setShortVal(value.asInstanceOf[Short])
case _: IntegerType | _: DateType => exprBuilder.setIntVal(value.asInstanceOf[Int])
case _: IntegerType | _: DateType | _: YearMonthIntervalType =>
exprBuilder.setIntVal(value.asInstanceOf[Int])
case _: LongType | _: TimestampType | _: TimestampNTZType | _: DayTimeIntervalType =>
exprBuilder.setLongVal(value.asInstanceOf[Long])
case dt if isTimeType(dt) =>
Expand Down Expand Up @@ -153,7 +157,7 @@ object CometLiteral extends CometExpressionSerde[Literal] with Logging {
else null.asInstanceOf[Integer])
listLiteralBuilder.addNullMask(casted != null)
})
case IntegerType | DateType =>
case IntegerType | DateType | _: YearMonthIntervalType =>
array.foreach(v => {
val casted = v.asInstanceOf[Integer]
listLiteralBuilder.addIntValues(casted)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

package org.apache.comet.serde.operator

import scala.collection.mutable.ListBuffer
import scala.jdk.CollectionConverters._

import org.apache.spark.sql.comet.{CometNativeExec, CometSinkPlaceHolder}
Expand All @@ -28,7 +29,7 @@ import org.apache.spark.sql.execution.adaptive.ShuffleQueryStageExec
import org.apache.spark.sql.execution.exchange.ReusedExchangeExec
import org.apache.spark.sql.types.{ArrayType, DataType, DayTimeIntervalType, MapType, StructType, YearMonthIntervalType}

import org.apache.comet.CometConf
import org.apache.comet.{CometConf, DataTypeSupport}
import org.apache.comet.CometSparkSessionExtensions.withFallbackReason
import org.apache.comet.ConfigEntry
import org.apache.comet.serde.{CometOperatorSerde, OperatorOuterClass}
Expand All @@ -39,7 +40,7 @@ import org.apache.comet.serde.QueryPlanSerde.{serializeDataType, supportedDataTy
* CometSink is the base class for transformations from a Spark operator to a Comet operator where
* the native plan is a ScanExec that will read data from the Comet operator running the JVM.
*/
abstract class CometSink[T <: SparkPlan] extends CometOperatorSerde[T] {
abstract class CometSink[T <: SparkPlan] extends CometOperatorSerde[T] with DataTypeSupport {

override def enabledConfig: Option[ConfigEntry[Boolean]] = None

Expand All @@ -50,7 +51,7 @@ abstract class CometSink[T <: SparkPlan] extends CometOperatorSerde[T] {
case ArrayType(elementType, _) => supportedSinkDataType(elementType)
case MapType(keyType, valueType, _) =>
supportedSinkDataType(keyType) && supportedSinkDataType(valueType)
case _ => supportedDataType(dt)
case _ => supportedDataType(dt) || isTypeSupported(dt, "", ListBuffer.empty)
}

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
-- 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.

-- Routes multiply_ym_interval through the codegen dispatcher; produces YearMonthIntervalType.
-- Config: spark.comet.exec.scalaUDF.codegen.enabled=true

statement
CREATE TABLE test_multiply_ym_interval(y int, m int, i int, l long, f float, d double, dec decimal(10,2)) USING parquet

statement
INSERT INTO test_multiply_ym_interval VALUES
(1, 2, 2, CAST(3 AS BIGINT), CAST(1.5 AS FLOAT), CAST(2.5 AS DOUBLE), CAST(2.50 AS DECIMAL(10, 2))),
(-1, 1, -2, CAST(-3 AS BIGINT), CAST(-1.5 AS FLOAT), CAST(-2.5 AS DOUBLE), CAST(-2.50 AS DECIMAL(10, 2))),
(0, 6, 0, CAST(0 AS BIGINT), CAST(0.5 AS FLOAT), CAST(0.5 AS DOUBLE), CAST(0.50 AS DECIMAL(10, 2))),
(2, -6, NULL, NULL, NULL, NULL, NULL)

query
SELECT
make_ym_interval(y, m) * i,
make_ym_interval(y, m) * l,
make_ym_interval(y, m) * f,
make_ym_interval(y, m) * d,
make_ym_interval(y, m) * dec
FROM test_multiply_ym_interval

-- literal interval input
query
SELECT INTERVAL '1-2' YEAR TO MONTH * i FROM test_multiply_ym_interval

-- numeric on the left is normalized by Spark to multiply_ym_interval.
query
SELECT i * make_ym_interval(y, m), 2 * INTERVAL '1-2' YEAR TO MONTH
FROM test_multiply_ym_interval

-- literal multipliers, including half-up rounding for fractional months.
query
SELECT
make_ym_interval(1, 2) * 2,
make_ym_interval(1, 2) * 1.5D,
make_ym_interval(1, 2) * CAST(1.50 AS DECIMAL(10, 2)),
make_ym_interval(-1, 1) * 1.5D

-- null interval input
query
SELECT make_ym_interval(NULL, m) * 2 FROM test_multiply_ym_interval

-- 178956970 years and 7 months is Int.MaxValue months. Multiplication overflows regardless of
-- ANSI mode; the lowercase pattern matches Spark 3.x and 4.x error messages.
query expect_error(overflow)
SELECT make_ym_interval(178956970, 7) * 2
Loading