You are viewing a plain text version of this content. The canonical link for it is here.
Posted to reviews@spark.apache.org by wajda <gi...@git.apache.org> on 2018/04/25 13:28:18 UTC
[GitHub] spark pull request #21155: SPARK-23927: Add "sequence" expression
GitHub user wajda opened a pull request:
https://github.com/apache/spark/pull/21155
SPARK-23927: Add "sequence" expression
## What changes were proposed in this pull request?
The PR adds the SQL function ```sequence```.
https://issues.apache.org/jira/browse/SPARK-23927
The behavior of the function is based on Presto's one.
Ref: https://prestodb.io/docs/current/functions/array.html
- ```sequence(start, stop) → array<bigint>```
Generate a sequence of integers from ```start``` to ```stop```, incrementing by ```1``` if ```start``` is less than or equal to ```stop```, otherwise ```-1```.
- ```sequence(start, stop, step) → array<bigint>```
Generate a sequence of integers from ```start``` to ```stop```, incrementing by ```step```.
- ```sequence(start_date, stop_date) → array<date>```
Generate a sequence of dates from ```start_date``` to ```stop_date```, incrementing by ```interval 1 day``` if ```start_date``` is less than or equal to ```stop_date```, otherwise ```- interval 1 day```.
- ```sequence(start_date, stop_date, step_interval) → array<date>```
Generate a sequence of dates from ```start_date``` to ```stop_date```, incrementing by ```step_interval```. The type of ```step_interval``` is ```CalendarInterval```.
- ```sequence(start, stop) → array<timestamp>```
Generate a sequence of timestamps from start timestamps to stop timestamps, incrementing by 1 day if start date is less than or equal to stop date, otherwise -1 day.
- ```sequence(start_timestamp, stop_timestamp, step_interval) → array<timestamp>```
Generate a sequence of timestamps from ```start_timestamps``` to ```stop_timestamps```, incrementing by ```interval 1 day``` if ```start_timestamp``` is less than or equal to ```stop_timestamp```, otherwise ```- interval 1 day```.
## How was this patch tested?
Added unit tests.
You can merge this pull request into a Git repository by running:
$ git pull https://github.com/AbsaOSS/spark feature/array-api-sequence
Alternatively you can review and apply these changes as the patch at:
https://github.com/apache/spark/pull/21155.patch
To close this pull request, make a commit to your master/trunk branch
with (at least) the following in the commit message:
This closes #21155
----
commit 5cc7d875ef98556ebda8fd91e4e94b898e39e18a
Author: Vayda, Oleksandr: IT (PRG) <ol...@...>
Date: 2018-04-12T14:57:11Z
SPARK-23927: Add "sequence" expression
----
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:
https://github.com/apache/spark/pull/21155
**[Test build #90330 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/90330/testReport)** for PR 21155 at commit [`383f180`](https://github.com/apache/spark/commit/383f1800470dbd7d54516e8f5609ee17dabb37ae).
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:
https://github.com/apache/spark/pull/21155
**[Test build #92334 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/92334/testReport)** for PR 21155 at commit [`d6de8cb`](https://github.com/apache/spark/commit/d6de8cb9b571f23dc357caf818295d359e19ff3d).
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:
https://github.com/apache/spark/pull/21155
**[Test build #90899 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/90899/testReport)** for PR 21155 at commit [`4b8af57`](https://github.com/apache/spark/commit/4b8af571d625d4c7c029757896f050001ab1e4f3).
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:
https://github.com/apache/spark/pull/21155
Merged build finished. Test FAILed.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by ueshin <gi...@git.apache.org>.
Github user ueshin commented on the issue:
https://github.com/apache/spark/pull/21155
Thanks! merging to master.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by ueshin <gi...@git.apache.org>.
Github user ueshin commented on a diff in the pull request:
https://github.com/apache/spark/pull/21155#discussion_r193927174
--- Diff: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/collectionOperations.scala ---
@@ -1887,6 +1889,402 @@ case class Flatten(child: Expression) extends UnaryExpression {
override def prettyName: String = "flatten"
}
+@ExpressionDescription(
+ usage = """
+ _FUNC_(start, stop, step) - Generates an array of elements from start to stop (inclusive),
+ incrementing by step. The type of the returned elements is the same as the type of argument
+ expressions.
+
+ Supported types are: byte, short, integer, long, date, timestamp.
+
+ The start and stop expressions must resolve to the same type.
+ If start and stop expressions resolve to the 'date' or 'timestamp' type
+ then the step expression must resolve to the 'interval' type, otherwise to the same type
+ as the start and stop expressions.
+ """,
+ arguments = """
+ Arguments:
+ * start - an expression. The start of the range.
+ * stop - an expression. The end the range (inclusive).
+ * step - an optional expression. The step of the range.
+ By default step is 1 if start is less than or equal to stop, otherwise -1.
+ For the temporal sequences it's 1 day and -1 day respectively.
+ If start is greater than stop then the step must be negative, and vice versa.
+ """,
+ examples = """
+ Examples:
+ > SELECT _FUNC_(1, 5);
+ [1, 2, 3, 4, 5]
+ > SELECT _FUNC_(5, 1);
+ [5, 4, 3, 2, 1]
+ > SELECT _FUNC_(to_date('2018-01-01'), to_date('2018-03-01'), interval 1 month);
+ [2018-01-01, 2018-02-01, 2018-03-01]
+ """,
+ since = "2.4.0"
+)
+case class Sequence(
+ start: Expression,
+ stop: Expression,
+ stepOpt: Option[Expression],
+ timeZoneId: Option[String] = None)
+ extends Expression
+ with TimeZoneAwareExpression {
+
+ import Sequence._
+
+ def this(start: Expression, stop: Expression) =
+ this(start, stop, None, None)
+
+ def this(start: Expression, stop: Expression, step: Expression) =
+ this(start, stop, Some(step), None)
+
+ override def withTimeZone(timeZoneId: String): TimeZoneAwareExpression =
+ copy(timeZoneId = Some(timeZoneId))
+
+ override def children: Seq[Expression] = Seq(start, stop) ++ stepOpt
+
+ override def foldable: Boolean = children.forall(_.foldable)
+
+ override def nullable: Boolean = children.exists(_.nullable)
+
+ override lazy val dataType: ArrayType = ArrayType(start.dataType, containsNull = false)
+
+ override def checkInputDataTypes(): TypeCheckResult = {
+ val startType = start.dataType
+ def stepType = stepOpt.get.dataType
+ val typesCorrect =
+ startType.sameType(stop.dataType) &&
+ (startType match {
+ case TimestampType | DateType =>
+ stepOpt.isEmpty || CalendarIntervalType.acceptsType(stepType)
+ case _: IntegralType =>
+ stepOpt.isEmpty || stepType.sameType(startType)
+ case _ => false
+ })
+
+ if (typesCorrect) {
+ TypeCheckResult.TypeCheckSuccess
+ } else {
+ TypeCheckResult.TypeCheckFailure(
+ s"$prettyName only supports integral, timestamp or date types")
+ }
+ }
+
+ def coercibleChildren: Seq[Expression] = children.filter(_.dataType != CalendarIntervalType)
+
+ def castChildrenTo(widerType: DataType): Expression = Sequence(
+ Cast(start, widerType),
+ Cast(stop, widerType),
+ stepOpt.map(step => if (step.dataType != CalendarIntervalType) Cast(step, widerType) else step),
+ timeZoneId)
+
+ private lazy val impl: SequenceImpl = dataType.elementType match {
+ case iType: IntegralType =>
+ type T = iType.InternalType
+ val ct = ClassTag[T](iType.tag.mirror.runtimeClass(iType.tag.tpe))
+ new IntegralSequenceImpl(iType)(ct, iType.integral)
+
+ case TimestampType =>
+ new TemporalSequenceImpl[Long](LongType, 1, identity, timeZone)
+
+ case DateType =>
+ new TemporalSequenceImpl[Int](IntegerType, MICROS_PER_DAY, _.toInt, timeZone)
+ }
+
+ override def eval(input: InternalRow): Any = {
+ val startVal = start.eval(input)
+ if (startVal == null) return null
+ val stopVal = stop.eval(input)
+ if (stopVal == null) return null
+ val stepVal = stepOpt.map(_.eval(input)).getOrElse(impl.defaultStep(startVal, stopVal))
+ if (stepVal == null) return null
+
+ ArrayData.toArrayData(impl.eval(startVal, stopVal, stepVal))
+ }
+
+ override protected def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = {
+ val startGen = start.genCode(ctx)
+ val stopGen = stop.genCode(ctx)
+ val stepGen = stepOpt.map(_.genCode(ctx)).getOrElse(
+ impl.defaultStep.genCode(ctx, startGen, stopGen))
+
+ val resultType = CodeGenerator.javaType(dataType)
+ val resultCode = {
+ val arr = ctx.freshName("arr")
+ val arrElemType = CodeGenerator.javaType(dataType.elementType)
+ s"""
+ |final $arrElemType[] $arr = null;
+ |${impl.genCode(ctx, startGen.value, stopGen.value, stepGen.value, arr, arrElemType)}
+ |${ev.value} = UnsafeArrayData.fromPrimitiveArray($arr);
+ """.stripMargin
+ }
+
+ if (nullable) {
+ val nullSafeEval =
+ startGen.code + ctx.nullSafeExec(start.nullable, startGen.isNull) {
+ stopGen.code + ctx.nullSafeExec(stop.nullable, stopGen.isNull) {
+ stepGen.code + ctx.nullSafeExec(stepOpt.exists(_.nullable), stepGen.isNull) {
+ s"""
+ |${ev.isNull} = false;
+ |$resultCode
+ """.stripMargin
+ }
+ }
+ }
+ ev.copy(code =
+ s"""
+ |boolean ${ev.isNull} = true;
+ |$resultType ${ev.value} = null;
+ |$nullSafeEval
+ """.stripMargin)
+
+ } else {
+ ev.copy(code =
+ s"""
+ |boolean ${ev.isNull} = false;
+ |${startGen.code}
+ |${stopGen.code}
+ |${stepGen.code}
+ |$resultType ${ev.value} = null;
+ |$resultCode
+ """.stripMargin,
+ isNull = FalseLiteral)
+ }
+ }
+}
+
+object Sequence {
+
+ private type LessThanOrEqualFn = (Any, Any) => Boolean
+
+ private class DefaultStep(lteq: LessThanOrEqualFn, stepType: DataType, one: Any) {
+ private val negativeOne = UnaryMinus(Literal(one)).eval()
+
+ def apply(start: Any, stop: Any): Any = {
+ if (lteq(start, stop)) one else negativeOne
+ }
+
+ def genCode(ctx: CodegenContext, startGen: ExprCode, stopGen: ExprCode): ExprCode = {
+ val Seq(oneVal, negativeOneVal) = Seq(one, negativeOne).map(Literal(_).genCode(ctx).value)
+ ExprCode.forNonNullValue(JavaCode.expression(
+ s"${startGen.value} <= ${stopGen.value} ? $oneVal : $negativeOneVal",
+ stepType))
+ }
+ }
+
+ private trait SequenceImpl {
+ def eval(start: Any, stop: Any, step: Any): Any
+
+ def genCode(
+ ctx: CodegenContext,
+ start: String,
+ stop: String,
+ step: String,
+ arr: String,
+ elemType: String): String
+
+ val defaultStep: DefaultStep
+ }
+
+ private class IntegralSequenceImpl[T: ClassTag]
+ (elemType: IntegralType)(implicit num: Integral[T]) extends SequenceImpl {
+
+ override val defaultStep: DefaultStep = new DefaultStep(
+ (elemType.ordering.lteq _).asInstanceOf[LessThanOrEqualFn],
+ elemType,
+ num.one)
+
+ override def eval(input1: Any, input2: Any, input3: Any): Array[T] = {
+ import num._
+
+ val start = input1.asInstanceOf[T]
+ val stop = input2.asInstanceOf[T]
+ val step = input3.asInstanceOf[T]
+
+ var i: Int = getSequenceLength(start, stop, step)
+ val arr = new Array[T](i)
+ while (i > 0) {
+ i -= 1
+ arr(i) = start + step * num.fromInt(i)
+ }
+ arr
+ }
+
+ override def genCode(
+ ctx: CodegenContext,
+ start: String,
+ stop: String,
+ step: String,
+ arr: String,
+ elemType: String): String = {
+ val i = ctx.freshName("i")
+ s"""
+ |${genSequenceLengthCode(ctx, start, stop, step, i)}
+ |$arr = new $elemType[$i];
+ |while ($i > 0) {
+ | $i--;
+ | $arr[$i] = ($elemType) ($start + $step * $i);
+ |}
+ """.stripMargin
+ }
+ }
+
+ private class TemporalSequenceImpl[T: ClassTag]
+ (dt: IntegralType, scale: Long, fromLong: Long => T, timeZone: TimeZone)
+ (implicit num: Integral[T]) extends SequenceImpl {
+
+ override val defaultStep: DefaultStep = new DefaultStep(
+ (dt.ordering.lteq _).asInstanceOf[LessThanOrEqualFn],
+ CalendarIntervalType,
+ new CalendarInterval(0, MICROS_PER_DAY))
+
+ private val backedSequenceImpl = new IntegralSequenceImpl[T](dt)
+ private val microsPerMonth = 28 * CalendarInterval.MICROS_PER_DAY
+
+ override def eval(input1: Any, input2: Any, input3: Any): Array[T] = {
+ val start = input1.asInstanceOf[T]
+ val stop = input2.asInstanceOf[T]
+ val step = input3.asInstanceOf[CalendarInterval]
+ val stepMonths = step.months
+ val stepMicros = step.microseconds
+
+ if (stepMonths == 0) {
+ backedSequenceImpl.eval(start, stop, fromLong(stepMicros / scale))
+
+ } else {
+ // To estimate the resulted array length we need to make assumptions
+ // about a month length in microseconds
+ val intervalStepInMicros = stepMicros + stepMonths * microsPerMonth
+ val startMicros: Long = num.toLong(start) * scale
+ val stopMicros: Long = num.toLong(stop) * scale
+ val maxEstimatedArrayLength =
+ getSequenceLength(startMicros, stopMicros, intervalStepInMicros)
+
+ val stepSign = if (stopMicros > startMicros) +1 else -1
+ val exclusiveItem = stopMicros + stepSign
+ val arr = new Array[T](maxEstimatedArrayLength)
+ var t = startMicros
+ var i = 0
+
+ while (t < exclusiveItem ^ stepSign < 0) {
+ arr(i) = fromLong(t / scale)
+ t = timestampAddInterval(t, stepMonths, stepMicros, timeZone)
+ i += 1
+ }
+
+ // truncate array to the correct length
+ if (arr.length == i) arr else arr.slice(0, i)
+ }
+ }
+
+ override def genCode(
+ ctx: CodegenContext,
+ start: String,
+ stop: String,
+ step: String,
+ arr: String,
+ elemType: String): String = {
+ val stepMonths = ctx.freshName("stepMonths")
+ val stepMicros = ctx.freshName("stepMicros")
+ val stepScaled = ctx.freshName("stepScaled")
+ val intervalInMicros = ctx.freshName("intervalInMicros")
+ val startMicros = ctx.freshName("startMicros")
+ val stopMicros = ctx.freshName("stopMicros")
+ val arrLength = ctx.freshName("arrLength")
+ val stepSign = ctx.freshName("stepSign")
+ val exclusiveItem = ctx.freshName("exclusiveItem")
+ val t = ctx.freshName("t")
+ val i = ctx.freshName("i")
+ val genTimeZone = ctx.freshName("timeZone")
+
+ val sequenceLengthCode =
+ s"""
+ |final long $intervalInMicros = $stepMicros + $stepMonths * ${microsPerMonth}L;
+ |${genSequenceLengthCode(ctx, startMicros, stopMicros, intervalInMicros, arrLength)}
+ """.stripMargin
+
+ val timestampAddIntervalCode =
+ s"""
+ |$t = org.apache.spark.sql.catalyst.util.DateTimeUtils.timestampAddInterval(
+ | $t, $stepMonths, $stepMicros, $genTimeZone);
+ """.stripMargin
+
+ s"""
+ |final int $stepMonths = $step.months;
+ |final long $stepMicros = $step.microseconds;
+ |
+ |if ($stepMonths == 0) {
+ | final $elemType $stepScaled = ($elemType) ($stepMicros / ${scale}L);
+ | ${backedSequenceImpl.genCode(ctx, start, stop, stepScaled, arr, elemType)};
+ |
+ |} else {
+ | final long $startMicros = $start * ${scale}L;
+ | final long $stopMicros = $stop * ${scale}L;
+ |
+ | $sequenceLengthCode
+ |
+ | final int $stepSign = $stopMicros > $startMicros ? +1 : -1;
+ | final long $exclusiveItem = $stopMicros + $stepSign;
+ | final java.util.TimeZone $genTimeZone =
+ | java.util.TimeZone.getTimeZone("${timeZone.getID}");
+ |
+ | $arr = new $elemType[$arrLength];
+ | long $t = $startMicros;
+ | int $i = 0;
+ |
+ | while ($t < $exclusiveItem ^ $stepSign < 0) {
+ | $arr[$i] = ($elemType) ($t / ${scale}L);
+ | $timestampAddIntervalCode
+ | $i += 1;
+ | }
+ |
+ | if ($arr.length > $i) {
+ | $arr = java.util.Arrays.copyOf($arr, $i);
+ | }
+ |}
+ """.stripMargin
+ }
+ }
+
+ private def getSequenceLength[U](start: U, stop: U, step: U)(implicit num: Integral[U]): Int = {
+ import num._
+ require(
+ step > num.zero && start <= stop
+ || step < num.zero && start >= stop
+ || step == 0 && start == stop,
--- End diff --
ditto.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:
https://github.com/apache/spark/pull/21155
**[Test build #90456 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/90456/testReport)** for PR 21155 at commit [`0a0a1e6`](https://github.com/apache/spark/commit/0a0a1e655f5b005d337a521692bbe9e6e09e5377).
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by wajda <gi...@git.apache.org>.
Github user wajda commented on the issue:
https://github.com/apache/spark/pull/21155
Thanks you for the comments. I'll review and make changes shortly.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by kiszk <gi...@git.apache.org>.
Github user kiszk commented on a diff in the pull request:
https://github.com/apache/spark/pull/21155#discussion_r186501267
--- Diff: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/collectionOperations.scala ---
@@ -1468,3 +1472,390 @@ case class Flatten(child: Expression) extends UnaryExpression {
override def prettyName: String = "flatten"
}
+
+@ExpressionDescription(
+ usage = """
+ _FUNC_(start, stop, step) - Generates an array of elements from start to stop (inclusive),
+ incrementing by step. The type of the returned elements is the same as the type of argument
+ expressions.
+
+ Supported types are: byte, short, integer, long, date, timestamp.
+
+ The start and stop expressions must resolve to the same type.
+ If start and stop expressions resolve to the 'date' or 'timestamp' type
+ then the step expression must resolve to the 'interval' type, otherwise to the same type
+ as the start and stop expressions.
+ """,
+ arguments = """
+ Arguments:
+ * start - an expression. The start of the range.
+ * stop - an expression. The end the range (inclusive).
+ * step - an optional expression. The step of the range.
+ By default step is 1 if start is less than or equal to stop, otherwise -1.
+ For the temporal sequences it's 1 day and -1 day respectively.
+ If start is greater than stop then the step must be negative, and vice versa.
+ """,
+ examples = """
+ Examples:
+ > SELECT _FUNC_(1, 5);
+ [1, 2, 3, 4, 5]
+ > SELECT _FUNC_(5, 1);
+ [5, 4, 3, 2, 1]
+ > SELECT _FUNC_(to_date('2018-01-01'), to_date('2018-03-01'), interval 1 month);
+ [2018-01-01, 2018-02-01, 2018-03-01]
+ """,
+ since = "2.4.0"
+)
+case class Sequence(
+ start: Expression,
+ stop: Expression,
+ step: Option[Expression],
+ timeZoneId: Option[String] = None)
+ extends Expression
+ with TimeZoneAwareExpression {
+
+ import Sequence._
+
+ def this(start: Expression, stop: Expression) =
+ this(start, stop, None, None)
+
+ def this(start: Expression, stop: Expression, step: Expression) =
+ this(start, stop, Some(step), None)
+
+ override def withTimeZone(timeZoneId: String): TimeZoneAwareExpression =
+ copy(timeZoneId = Some(timeZoneId))
+
+ override def children: Seq[Expression] = Seq(start, stop) ++ step.toSeq
+
+ override def foldable: Boolean = children.forall(_.foldable)
+
+ override def nullable: Boolean = children.exists(_.nullable)
+
+ override lazy val dataType: ArrayType = ArrayType(start.dataType, containsNull = false)
+
+ override def checkInputDataTypes(): TypeCheckResult = {
+ val Seq(startType, stopType) = Seq(start, stop).map(_.dataType)
--- End diff --
How about `val StartType = start.dataType`? Then, replace `stopType` with `stop.dataType` at line 1540.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:
https://github.com/apache/spark/pull/21155
**[Test build #92295 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/92295/testReport)** for PR 21155 at commit [`def678b`](https://github.com/apache/spark/commit/def678b152b74e745b125167e55a2d999903e239).
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:
https://github.com/apache/spark/pull/21155
Can one of the admins verify this patch?
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:
https://github.com/apache/spark/pull/21155
Merged build finished. Test PASSed.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:
https://github.com/apache/spark/pull/21155
Merged build finished. Test PASSed.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:
https://github.com/apache/spark/pull/21155
**[Test build #90892 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/90892/testReport)** for PR 21155 at commit [`1b74d6f`](https://github.com/apache/spark/commit/1b74d6f734724b8e68b4f80c4e16f956cd19f92a).
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by wajda <gi...@git.apache.org>.
Github user wajda commented on the issue:
https://github.com/apache/spark/pull/21155
Regarding ```step, stop, step``` vs. ```arg1, arg2, arg3```, ```left, middle, right``` and so on. Originally I used those to avoid hiding variables from the outer scope, but after the final refactoring it doesn't seem to be an issue anymore. I'll rename those, but I would keep ones as is for the ```def eval(input1: Any, input2: Any, input3: Any)``` method implementations. The reason is to distinguish the argument of type Any from their cast references as below:
```
override def eval(input1: Any, input2: Any, input3: Any): Array[T] = {
val start = input1.asInstanceOf[T]
val stop = input2.asInstanceOf[T]
val step = input3.asInstanceOf[T]
```
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request #21155: SPARK-23927: Add "sequence" expression
Posted by ueshin <gi...@git.apache.org>.
Github user ueshin commented on a diff in the pull request:
https://github.com/apache/spark/pull/21155#discussion_r186038049
--- Diff: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/collectionOperations.scala ---
@@ -1059,3 +1063,316 @@ case class Flatten(child: Expression) extends UnaryExpression {
override def prettyName: String = "flatten"
}
+
+@ExpressionDescription(
+ usage = """
+ _FUNC_(start, stop, step) -
+ Generates an array of elements from start to stop (inclusive), incrementing by step.
+ The type of the returned elements is the same as the type of argument expressions.
+
+ Supported types are: byte, short, integer, long, date, timestamp.
+
+ The start and stop expressions must resolve to the same type.
+ If start and stop expressions resolve to the 'date' or 'timestamp' type
+ then the step expression must resolve to the 'interval' type, otherwise to the same type
+ as the start and stop expressions.
+ """,
+ arguments = """
+ Arguments:
+ * start - an expression. The start of the range.
+ * stop - an expression. The end the range (inclusive).
+ * step - an optional expression. The step of the range.
+
+ By default step is 1 if start is less than or equal to stop, otherwise -1.
+ For the temporal sequences it's 1 day and -1 day respectively.
+
+ If start is greater than stop then the step must be negative, and vice versa.
+ """,
+ examples = """
+ Examples:
+ > SELECT _FUNC_(1, 5);
+ [1, 2, 3, 4, 5]
+ > SELECT _FUNC_(5, 1);
+ [5, 4, 3, 2, 1]
+ > SELECT _FUNC_(to_date('2018-01-01'), to_date('2018-03-01'), interval 1 month);
+ [2018-01-01, 2018-02-01, 2018-03-01]
+ """,
+ since = "2.4.0"
+)
+case class Sequence(left: Expression,
+ middle: Expression,
+ right: Expression,
+ timeZoneId: Option[String] = None)
+ extends TernaryExpression with TimeZoneAwareExpression {
+
+ import Sequence._
+
+ def this(arg0: Expression, arg1: Expression) =
+ this(arg0, arg1, Sequence.defaultStepExpression(arg0, arg1), None)
+
+ def this(arg0: Expression, arg1: Expression, arg2: Expression) =
+ this(arg0, arg1, arg2, None)
+
+ override def withTimeZone(timeZoneId: String): TimeZoneAwareExpression =
+ copy(timeZoneId = Some(timeZoneId))
+
+ override def children: Seq[Expression] = Seq(left, middle, right)
+
+ override lazy val dataType: ArrayType = ArrayType(left.dataType, containsNull = false)
+
+ override def checkInputDataTypes(): TypeCheckResult = {
+ val Seq(startType, stopType, stepType) = children.map(_.dataType)
+ val typesCorrect =
+ startType.sameType(stopType) &&
+ (startType match {
+ case TimestampType | DateType => CalendarIntervalType acceptsType stepType
+ case _: IntegralType => stepType sameType startType
+ case _ => false
+ })
+
+ if (typesCorrect) {
+ TypeCheckResult.TypeCheckSuccess
+ } else {
+ TypeCheckResult.TypeCheckFailure(
+ s"$prettyName only supports integral, timestamp or date types")
+ }
+ }
+
+ private lazy val impl: SequenceImpl = dataType.elementType match {
+ case iType: IntegralType =>
+ type T = iType.InternalType
+ val ct = ClassTag[T](iType.tag.mirror.runtimeClass(iType.tag.tpe))
+ new IntegralSequenceImpl()(ct, iType.integral)
+
+ case TimestampType =>
+ new TemporalSequenceImpl[Long](LongType, 1, identity, timeZone)
+
+ case DateType =>
+ new TemporalSequenceImpl[Int](IntegerType, MICROS_PER_DAY, _.toInt, timeZone)
+ }
+
+ override protected def nullSafeEval(input1: Any, input2: Any, input3: Any): Any = {
+ ArrayData.toArrayData(impl.eval(input1, input2, input3))
+ }
+
+ override protected def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = {
+ nullSafeCodeGen(ctx, ev, (start, stop, step) => {
+ val arr = ctx.freshName("arr")
+ val arrElemType = CodeGenerator.javaType(dataType.elementType)
+ s"""
+ | final $arrElemType[] $arr = null;
+ | ${impl.genCode(start, stop, step)(arr, arrElemType)(ctx)}
+ | ${ev.value} = UnsafeArrayData.fromPrimitiveArray($arr);
+ """.stripMargin
+ })
+ }
+}
+
+object Sequence {
+
+ private trait SequenceImpl {
+ def eval(input1: Any, input2: Any, input3: Any): Any
+
+ def genCode(start: String, stop: String, step: String)
+ (arr: String, elemType: String)
+ (implicit ctx: CodegenContext): String
+ }
+
+ private class IntegralSequenceImpl[T: ClassTag]
+ (implicit num: Integral[T]) extends SequenceImpl {
+
+ override def eval(input1: Any, input2: Any, input3: Any): Array[T] = {
+ import num._
+
+ val start = input1.asInstanceOf[T]
+ val stop = input2.asInstanceOf[T]
+ val step = input3.asInstanceOf[T]
+
+ var i: Int = getSequenceLength(start, stop, step)
+ val arr = new Array[T](i)
+ while (i > 0) {
+ i -= 1
+ arr(i) = start + step * num.fromInt(i)
+ }
+ arr
+ }
+
+ override def genCode(start: String, stop: String, step: String)
+ (arr: String, elemType: String)
+ (implicit ctx: CodegenContext): String = {
+ val i = ctx.freshName("i")
+ s"""
+ | ${genSequenceLengthCode(start, stop, step)(i)}
+ | $arr = new $elemType[$i];
+ | while ($i > 0) {
+ | $i--;
+ | $arr[$i] = ($elemType) ($start + $step * $i);
+ | }
+ """.stripMargin
+ }
+ }
+
+ private class TemporalSequenceImpl[T: ClassTag]
+ (dt: IntegralType, scale: Long, fromLong: Long => T, timeZone: TimeZone)
--- End diff --
nit: indent
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by wajda <gi...@git.apache.org>.
Github user wajda commented on a diff in the pull request:
https://github.com/apache/spark/pull/21155#discussion_r187280683
--- Diff: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/collectionOperations.scala ---
@@ -1468,3 +1472,388 @@ case class Flatten(child: Expression) extends UnaryExpression {
override def prettyName: String = "flatten"
}
+
+@ExpressionDescription(
+ usage = """
+ _FUNC_(start, stop, step) - Generates an array of elements from start to stop (inclusive),
+ incrementing by step. The type of the returned elements is the same as the type of argument
+ expressions.
+
+ Supported types are: byte, short, integer, long, date, timestamp.
+
+ The start and stop expressions must resolve to the same type.
+ If start and stop expressions resolve to the 'date' or 'timestamp' type
+ then the step expression must resolve to the 'interval' type, otherwise to the same type
+ as the start and stop expressions.
+ """,
+ arguments = """
+ Arguments:
+ * start - an expression. The start of the range.
+ * stop - an expression. The end the range (inclusive).
+ * step - an optional expression. The step of the range.
+ By default step is 1 if start is less than or equal to stop, otherwise -1.
+ For the temporal sequences it's 1 day and -1 day respectively.
+ If start is greater than stop then the step must be negative, and vice versa.
+ """,
+ examples = """
+ Examples:
+ > SELECT _FUNC_(1, 5);
+ [1, 2, 3, 4, 5]
+ > SELECT _FUNC_(5, 1);
+ [5, 4, 3, 2, 1]
+ > SELECT _FUNC_(to_date('2018-01-01'), to_date('2018-03-01'), interval 1 month);
+ [2018-01-01, 2018-02-01, 2018-03-01]
+ """,
+ since = "2.4.0"
+)
+case class Sequence(
+ start: Expression,
+ stop: Expression,
+ stepOpt: Option[Expression],
+ timeZoneId: Option[String] = None)
+ extends Expression
+ with ExpectsInputTypes
+ with TimeZoneAwareExpression {
+
+ import Sequence._
+
+ def this(start: Expression, stop: Expression) =
+ this(start, stop, None, None)
+
+ def this(start: Expression, stop: Expression, step: Expression) =
+ this(start, stop, Some(step), None)
+
+ override def withTimeZone(timeZoneId: String): TimeZoneAwareExpression =
+ copy(timeZoneId = Some(timeZoneId))
+
+ override def children: Seq[Expression] = Seq(start, stop) ++ stepOpt
+
+ override def foldable: Boolean = children.forall(_.foldable)
+
+ override def nullable: Boolean = children.exists(_.nullable)
+
+ override lazy val dataType: ArrayType = ArrayType(start.dataType, containsNull = false)
+
+ override def inputTypes: Seq[AbstractDataType] = {
+ val elemType = dataType.elementType
+ Seq(elemType, elemType) ++
+ stepOpt.map(_ => elemType match {
+ case DateType | TimestampType => CalendarIntervalType
+ case _: IntegralType => elemType
--- End diff --
Both implementations basically do the same thing - check the validity of the element and step types. Unless I am missing something.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:
https://github.com/apache/spark/pull/21155
**[Test build #90207 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/90207/testReport)** for PR 21155 at commit [`d15dad8`](https://github.com/apache/spark/commit/d15dad8ed169e91b12a4243ba275d9efcd680473).
* This patch passes all tests.
* This patch merges cleanly.
* This patch adds no public classes.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:
https://github.com/apache/spark/pull/21155
Test FAILed.
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/90893/
Test FAILed.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: SPARK-23927: Add "sequence" expression
Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:
https://github.com/apache/spark/pull/21155
**[Test build #89852 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/89852/testReport)** for PR 21155 at commit [`0b4d868`](https://github.com/apache/spark/commit/0b4d868b995a58c92d294e248ee9689f50da9f1f).
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:
https://github.com/apache/spark/pull/21155
Merged build finished. Test PASSed.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:
https://github.com/apache/spark/pull/21155
**[Test build #90909 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/90909/testReport)** for PR 21155 at commit [`2ccb9bb`](https://github.com/apache/spark/commit/2ccb9bb73f729c361ee819316e9c95224797a178).
* This patch passes all tests.
* This patch merges cleanly.
* This patch adds the following public classes _(experimental)_:
* `case class Sequence(`
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:
https://github.com/apache/spark/pull/21155
**[Test build #90892 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/90892/testReport)** for PR 21155 at commit [`1b74d6f`](https://github.com/apache/spark/commit/1b74d6f734724b8e68b4f80c4e16f956cd19f92a).
* This patch **fails Scala style tests**.
* This patch merges cleanly.
* This patch adds no public classes.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:
https://github.com/apache/spark/pull/21155
**[Test build #90207 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/90207/testReport)** for PR 21155 at commit [`d15dad8`](https://github.com/apache/spark/commit/d15dad8ed169e91b12a4243ba275d9efcd680473).
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request #21155: SPARK-23927: Add "sequence" expression
Posted by kiszk <gi...@git.apache.org>.
Github user kiszk commented on a diff in the pull request:
https://github.com/apache/spark/pull/21155#discussion_r184125363
--- Diff: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/collectionOperations.scala ---
@@ -1059,3 +1063,282 @@ case class Flatten(child: Expression) extends UnaryExpression {
override def prettyName: String = "flatten"
}
+
+object Sequence {
+ private def defaultStepLiteralForType(dt: DataType) = dt match {
+ case DateType | TimestampType => Literal(new CalendarInterval(0, MICROS_PER_DAY))
+ case dt: NumericType => Literal(dt.numeric.one)
+ }
+
+ private def defaultStepExpression(start: Expression, stop: Expression): Expression = {
+ val one =
+ if (start.resolved) {
+ defaultStepLiteralForType(start.dataType)
+ } else {
+ UnresolvedLiteral(start, defaultStepLiteralForType)
+ }
+ CaseWhen(
+ Seq((LessThanOrEqual(start, stop), one)),
+ UnaryMinus(one))
+ }
+
+ def getSequenceLength[U](start: U, stop: U, step: U)(implicit num: Integral[U]): Int = {
+ import num._
+ require(
+ step > num.zero && start <= stop
+ || step < num.zero && start >= stop
+ || step == 0 && start == stop,
+ s"Illegal sequence boundaries: $start to $stop by $step")
+
+ val len = if (start == stop) 1L else 1L + (stop.toLong - start.toLong) / step.toLong
+
+ require(len <= Int.MaxValue, s"Too long sequence: $len. Should be <= ${Int.MaxValue}")
+
+ len.toInt
+ }
+
+ def genSequenceLengthCode(start: String, stop: String, step: String)
+ (len: String)
+ (implicit ctx: CodegenContext): String = {
+ val longLen = ctx.freshName("longLen")
+ s"""
+ | if (!($step > 0 && $start <= $stop ||
+ | $step < 0 && $start >= $stop ||
+ | $step == 0 && $start == $stop)) {
+ | throw new IllegalArgumentException(
+ | "Illegal sequence boundaries: " + $start + " to " + $stop + " by " + $step);
+ | }
+ | long $longLen = $stop == $start ? 1L : 1L + ((long) $stop - $start) / $step;
+ | if ($longLen > Integer.MAX_VALUE) {
+ | throw new IllegalArgumentException(
+ | "Too long sequence: " + $longLen + ". Should be <= ${Int.MaxValue}");
+ | }
+ | int $len = (int) $longLen;
+ """.stripMargin
+ }
+
+ trait SequenceImpl {
+ def eval(input1: Any, input2: Any, input3: Any): Any
+ def genCode(start: String, stop: String, step: String)
+ (arr: String, elemType: String)
+ (implicit ctx: CodegenContext): String
+ }
+}
+
+case class Sequence(left: Expression,
+ middle: Expression,
+ right: Expression,
+ timeZoneId: Option[String] = None)
+ extends TernaryExpression with TimeZoneAwareExpression {
+
+ import Sequence._
+
+ class IntegralSequenceImpl[T: ClassTag](implicit num: Integral[T]) extends SequenceImpl {
+
+ override def eval(input1: Any, input2: Any, input3: Any): Array[T] = {
+ import num._
+
+ val start = input1.asInstanceOf[T]
+ val stop = input2.asInstanceOf[T]
+ val step = input3.asInstanceOf[T]
+
+ var i: Int = getSequenceLength(start, stop, step)
+ val arr = new Array[T](i)
+ while (i > 0) {
+ i -= 1
+ arr(i) = start + step * num.fromInt(i)
+ }
+ arr
+ }
+
+ override def genCode(start: String, stop: String, step: String)
+ (arr: String, elemType: String)
+ (implicit ctx: CodegenContext): String = {
+ val i = ctx.freshName("i")
+ s"""
+ | ${genSequenceLengthCode(start, stop, step)(i)}
+ | $arr = new $elemType[$i];
+ | while ($i > 0) {
+ | $i--;
+ | $arr[$i] = ($elemType) ($start + $step * $i);
+ | }
+ """.stripMargin
+ }
+ }
+
+ abstract class TemporalSequence[T: ClassTag](dt: IntegralType, scale: Long, fromLong: Long => T)
+ (implicit num: Integral[T])
+ extends SequenceImpl {
+
+ private val backedSequenceImpl = new IntegralSequenceImpl[T]
+ private val microsPerMonth = 28 * CalendarInterval.MICROS_PER_DAY
+
+ override def eval(input1: Any, input2: Any, input3: Any): Array[T] = {
+ val start = input1.asInstanceOf[T]
+ val stop = input2.asInstanceOf[T]
+ val step = input3.asInstanceOf[CalendarInterval]
+ val stepMonths = step.months
+ val stepMicros = step.microseconds
+
+ if (stepMonths == 0) {
+ backedSequenceImpl.eval(start, stop, fromLong(stepMicros / scale))
+
+ } else {
+ // To estimate the resulted array length we need to make assumptions
+ // about a month length in microseconds
+ val minIntervalLengthInMicros = Math.abs(stepMicros) + stepMonths * microsPerMonth
+ val startMicros: Long = num.toLong(start) * scale
+ val stopMicros: Long = num.toLong(stop) * scale
+ val maxEstimatedArrayLength =
+ getSequenceLength(startMicros, stopMicros, minIntervalLengthInMicros)
+
+ val stepSign = if (stopMicros > startMicros) +1 else -1
+ val exclusiveItem = stopMicros + stepSign
+ val arr = new Array[T](maxEstimatedArrayLength)
+ var t = startMicros
+ var i = 0
+
+ while (t < exclusiveItem ^ stepSign < 0) {
+ arr(i) = fromLong(t / scale)
+ t = timestampAddInterval(t, stepMonths, stepMicros, timeZone)
+ i += 1
+ }
+
+ // truncate array to the correct length
+ if (arr.length == i) {
+ arr
+ } else {
+ arr.slice(0, i)
+ }
+ }
+ }
+
+ override def genCode(start: String, stop: String, step: String)
+ (arr: String, elemType: String)
+ (implicit ctx: CodegenContext): String = {
+ val stepMonths = ctx.freshName("stepMonths")
+ val stepMicros = ctx.freshName("stepMicros")
+
+ lazy val stepScaled = ctx.freshName("stepScaled")
--- End diff --
Is there any reason to use `lazy` here?
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:
https://github.com/apache/spark/pull/21155
**[Test build #90893 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/90893/testReport)** for PR 21155 at commit [`3ef9566`](https://github.com/apache/spark/commit/3ef9566dd85e49ecae74f888b576ba17e6e58f09).
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: SPARK-23927: Add "sequence" expression
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:
https://github.com/apache/spark/pull/21155
Merged build finished. Test FAILed.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request #21155: SPARK-23927: Add "sequence" expression
Posted by ueshin <gi...@git.apache.org>.
Github user ueshin commented on a diff in the pull request:
https://github.com/apache/spark/pull/21155#discussion_r186036063
--- Diff: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/collectionOperations.scala ---
@@ -1059,3 +1063,316 @@ case class Flatten(child: Expression) extends UnaryExpression {
override def prettyName: String = "flatten"
}
+
+@ExpressionDescription(
+ usage = """
+ _FUNC_(start, stop, step) -
+ Generates an array of elements from start to stop (inclusive), incrementing by step.
+ The type of the returned elements is the same as the type of argument expressions.
+
+ Supported types are: byte, short, integer, long, date, timestamp.
+
+ The start and stop expressions must resolve to the same type.
+ If start and stop expressions resolve to the 'date' or 'timestamp' type
+ then the step expression must resolve to the 'interval' type, otherwise to the same type
+ as the start and stop expressions.
+ """,
+ arguments = """
+ Arguments:
+ * start - an expression. The start of the range.
+ * stop - an expression. The end the range (inclusive).
+ * step - an optional expression. The step of the range.
+
+ By default step is 1 if start is less than or equal to stop, otherwise -1.
+ For the temporal sequences it's 1 day and -1 day respectively.
+
+ If start is greater than stop then the step must be negative, and vice versa.
+ """,
+ examples = """
+ Examples:
+ > SELECT _FUNC_(1, 5);
+ [1, 2, 3, 4, 5]
+ > SELECT _FUNC_(5, 1);
+ [5, 4, 3, 2, 1]
+ > SELECT _FUNC_(to_date('2018-01-01'), to_date('2018-03-01'), interval 1 month);
+ [2018-01-01, 2018-02-01, 2018-03-01]
+ """,
+ since = "2.4.0"
+)
+case class Sequence(left: Expression,
+ middle: Expression,
+ right: Expression,
+ timeZoneId: Option[String] = None)
+ extends TernaryExpression with TimeZoneAwareExpression {
+
+ import Sequence._
+
+ def this(arg0: Expression, arg1: Expression) =
+ this(arg0, arg1, Sequence.defaultStepExpression(arg0, arg1), None)
+
+ def this(arg0: Expression, arg1: Expression, arg2: Expression) =
+ this(arg0, arg1, arg2, None)
+
+ override def withTimeZone(timeZoneId: String): TimeZoneAwareExpression =
+ copy(timeZoneId = Some(timeZoneId))
+
+ override def children: Seq[Expression] = Seq(left, middle, right)
+
+ override lazy val dataType: ArrayType = ArrayType(left.dataType, containsNull = false)
+
+ override def checkInputDataTypes(): TypeCheckResult = {
+ val Seq(startType, stopType, stepType) = children.map(_.dataType)
+ val typesCorrect =
+ startType.sameType(stopType) &&
+ (startType match {
+ case TimestampType | DateType => CalendarIntervalType acceptsType stepType
+ case _: IntegralType => stepType sameType startType
+ case _ => false
+ })
+
+ if (typesCorrect) {
+ TypeCheckResult.TypeCheckSuccess
+ } else {
+ TypeCheckResult.TypeCheckFailure(
+ s"$prettyName only supports integral, timestamp or date types")
+ }
+ }
+
+ private lazy val impl: SequenceImpl = dataType.elementType match {
+ case iType: IntegralType =>
+ type T = iType.InternalType
+ val ct = ClassTag[T](iType.tag.mirror.runtimeClass(iType.tag.tpe))
+ new IntegralSequenceImpl()(ct, iType.integral)
+
+ case TimestampType =>
+ new TemporalSequenceImpl[Long](LongType, 1, identity, timeZone)
+
+ case DateType =>
+ new TemporalSequenceImpl[Int](IntegerType, MICROS_PER_DAY, _.toInt, timeZone)
+ }
+
+ override protected def nullSafeEval(input1: Any, input2: Any, input3: Any): Any = {
+ ArrayData.toArrayData(impl.eval(input1, input2, input3))
+ }
+
+ override protected def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = {
+ nullSafeCodeGen(ctx, ev, (start, stop, step) => {
+ val arr = ctx.freshName("arr")
+ val arrElemType = CodeGenerator.javaType(dataType.elementType)
+ s"""
+ | final $arrElemType[] $arr = null;
+ | ${impl.genCode(start, stop, step)(arr, arrElemType)(ctx)}
+ | ${ev.value} = UnsafeArrayData.fromPrimitiveArray($arr);
+ """.stripMargin
+ })
+ }
+}
+
+object Sequence {
+
+ private trait SequenceImpl {
+ def eval(input1: Any, input2: Any, input3: Any): Any
+
+ def genCode(start: String, stop: String, step: String)
+ (arr: String, elemType: String)
+ (implicit ctx: CodegenContext): String
+ }
+
+ private class IntegralSequenceImpl[T: ClassTag]
--- End diff --
`[T: Integral: ClassTag]`?
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by ueshin <gi...@git.apache.org>.
Github user ueshin commented on a diff in the pull request:
https://github.com/apache/spark/pull/21155#discussion_r193899743
--- Diff: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/collectionOperations.scala ---
@@ -1887,6 +1889,402 @@ case class Flatten(child: Expression) extends UnaryExpression {
override def prettyName: String = "flatten"
}
+@ExpressionDescription(
+ usage = """
+ _FUNC_(start, stop, step) - Generates an array of elements from start to stop (inclusive),
+ incrementing by step. The type of the returned elements is the same as the type of argument
+ expressions.
+
+ Supported types are: byte, short, integer, long, date, timestamp.
+
+ The start and stop expressions must resolve to the same type.
+ If start and stop expressions resolve to the 'date' or 'timestamp' type
+ then the step expression must resolve to the 'interval' type, otherwise to the same type
+ as the start and stop expressions.
+ """,
+ arguments = """
+ Arguments:
+ * start - an expression. The start of the range.
+ * stop - an expression. The end the range (inclusive).
+ * step - an optional expression. The step of the range.
+ By default step is 1 if start is less than or equal to stop, otherwise -1.
+ For the temporal sequences it's 1 day and -1 day respectively.
+ If start is greater than stop then the step must be negative, and vice versa.
+ """,
+ examples = """
+ Examples:
+ > SELECT _FUNC_(1, 5);
+ [1, 2, 3, 4, 5]
+ > SELECT _FUNC_(5, 1);
+ [5, 4, 3, 2, 1]
+ > SELECT _FUNC_(to_date('2018-01-01'), to_date('2018-03-01'), interval 1 month);
+ [2018-01-01, 2018-02-01, 2018-03-01]
+ """,
+ since = "2.4.0"
+)
+case class Sequence(
+ start: Expression,
+ stop: Expression,
+ stepOpt: Option[Expression],
+ timeZoneId: Option[String] = None)
+ extends Expression
+ with TimeZoneAwareExpression {
+
+ import Sequence._
+
+ def this(start: Expression, stop: Expression) =
+ this(start, stop, None, None)
+
+ def this(start: Expression, stop: Expression, step: Expression) =
+ this(start, stop, Some(step), None)
+
+ override def withTimeZone(timeZoneId: String): TimeZoneAwareExpression =
+ copy(timeZoneId = Some(timeZoneId))
+
+ override def children: Seq[Expression] = Seq(start, stop) ++ stepOpt
+
+ override def foldable: Boolean = children.forall(_.foldable)
+
+ override def nullable: Boolean = children.exists(_.nullable)
+
+ override lazy val dataType: ArrayType = ArrayType(start.dataType, containsNull = false)
+
+ override def checkInputDataTypes(): TypeCheckResult = {
+ val startType = start.dataType
+ def stepType = stepOpt.get.dataType
+ val typesCorrect =
+ startType.sameType(stop.dataType) &&
+ (startType match {
+ case TimestampType | DateType =>
+ stepOpt.isEmpty || CalendarIntervalType.acceptsType(stepType)
+ case _: IntegralType =>
+ stepOpt.isEmpty || stepType.sameType(startType)
+ case _ => false
+ })
+
+ if (typesCorrect) {
+ TypeCheckResult.TypeCheckSuccess
+ } else {
+ TypeCheckResult.TypeCheckFailure(
+ s"$prettyName only supports integral, timestamp or date types")
+ }
+ }
+
+ def coercibleChildren: Seq[Expression] = children.filter(_.dataType != CalendarIntervalType)
+
+ def castChildrenTo(widerType: DataType): Expression = Sequence(
--- End diff --
We can use `withNewChildren` instead?
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:
https://github.com/apache/spark/pull/21155
**[Test build #92326 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/92326/testReport)** for PR 21155 at commit [`140225d`](https://github.com/apache/spark/commit/140225d8b2326122f69e9093a071c1cdde7e489d).
* This patch **fails due to an unknown error code, -9**.
* This patch merges cleanly.
* This patch adds no public classes.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:
https://github.com/apache/spark/pull/21155
Test PASSed.
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/92334/
Test PASSed.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: SPARK-23927: Add "sequence" expression
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:
https://github.com/apache/spark/pull/21155
Can one of the admins verify this patch?
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:
https://github.com/apache/spark/pull/21155
**[Test build #90330 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/90330/testReport)** for PR 21155 at commit [`383f180`](https://github.com/apache/spark/commit/383f1800470dbd7d54516e8f5609ee17dabb37ae).
* This patch **fails Spark unit tests**.
* This patch merges cleanly.
* This patch adds no public classes.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by wajda <gi...@git.apache.org>.
Github user wajda commented on a diff in the pull request:
https://github.com/apache/spark/pull/21155#discussion_r187277937
--- Diff: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/collectionOperations.scala ---
@@ -1468,3 +1472,388 @@ case class Flatten(child: Expression) extends UnaryExpression {
override def prettyName: String = "flatten"
}
+
+@ExpressionDescription(
+ usage = """
+ _FUNC_(start, stop, step) - Generates an array of elements from start to stop (inclusive),
+ incrementing by step. The type of the returned elements is the same as the type of argument
+ expressions.
+
+ Supported types are: byte, short, integer, long, date, timestamp.
+
+ The start and stop expressions must resolve to the same type.
+ If start and stop expressions resolve to the 'date' or 'timestamp' type
+ then the step expression must resolve to the 'interval' type, otherwise to the same type
+ as the start and stop expressions.
+ """,
+ arguments = """
+ Arguments:
+ * start - an expression. The start of the range.
+ * stop - an expression. The end the range (inclusive).
+ * step - an optional expression. The step of the range.
+ By default step is 1 if start is less than or equal to stop, otherwise -1.
+ For the temporal sequences it's 1 day and -1 day respectively.
+ If start is greater than stop then the step must be negative, and vice versa.
+ """,
+ examples = """
+ Examples:
+ > SELECT _FUNC_(1, 5);
+ [1, 2, 3, 4, 5]
+ > SELECT _FUNC_(5, 1);
+ [5, 4, 3, 2, 1]
+ > SELECT _FUNC_(to_date('2018-01-01'), to_date('2018-03-01'), interval 1 month);
+ [2018-01-01, 2018-02-01, 2018-03-01]
+ """,
+ since = "2.4.0"
+)
+case class Sequence(
+ start: Expression,
+ stop: Expression,
+ stepOpt: Option[Expression],
+ timeZoneId: Option[String] = None)
+ extends Expression
+ with ExpectsInputTypes
+ with TimeZoneAwareExpression {
+
+ import Sequence._
+
+ def this(start: Expression, stop: Expression) =
+ this(start, stop, None, None)
+
+ def this(start: Expression, stop: Expression, step: Expression) =
+ this(start, stop, Some(step), None)
+
+ override def withTimeZone(timeZoneId: String): TimeZoneAwareExpression =
+ copy(timeZoneId = Some(timeZoneId))
+
+ override def children: Seq[Expression] = Seq(start, stop) ++ stepOpt
+
+ override def foldable: Boolean = children.forall(_.foldable)
+
+ override def nullable: Boolean = children.exists(_.nullable)
+
+ override lazy val dataType: ArrayType = ArrayType(start.dataType, containsNull = false)
+
+ override def inputTypes: Seq[AbstractDataType] = {
+ val elemType = dataType.elementType
+ Seq(elemType, elemType) ++
+ stepOpt.map(_ => elemType match {
+ case DateType | TimestampType => CalendarIntervalType
+ case _: IntegralType => elemType
--- End diff --
Hm, isn't it exactly what I had before? Just yesterday I followed @ueshin suggestion and replaced ```checkInputDataTypes``` with ```ExpectsInputTypes``` trait + ```inputTypes```
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request #21155: SPARK-23927: Add "sequence" expression
Posted by ueshin <gi...@git.apache.org>.
Github user ueshin commented on a diff in the pull request:
https://github.com/apache/spark/pull/21155#discussion_r186028360
--- Diff: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/TypeCoercion.scala ---
@@ -536,6 +536,15 @@ object TypeCoercion {
case None => c
}
+ case s @ Sequence(_, _, _, timeZoneId) if !haveSameType(s.children) =>
+ val types = s.children.map(_.dataType)
+ findWiderCommonType(types) match {
--- End diff --
What if step is interval?
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:
https://github.com/apache/spark/pull/21155
Test PASSed.
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/90329/
Test PASSed.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:
https://github.com/apache/spark/pull/21155
Merged build finished. Test PASSed.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:
https://github.com/apache/spark/pull/21155
Merged build finished. Test FAILed.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:
https://github.com/apache/spark/pull/21155
Merged build finished. Test FAILed.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by wajda <gi...@git.apache.org>.
Github user wajda commented on a diff in the pull request:
https://github.com/apache/spark/pull/21155#discussion_r197496245
--- Diff: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/collectionOperations.scala ---
@@ -1887,6 +1889,402 @@ case class Flatten(child: Expression) extends UnaryExpression {
override def prettyName: String = "flatten"
}
+@ExpressionDescription(
+ usage = """
+ _FUNC_(start, stop, step) - Generates an array of elements from start to stop (inclusive),
+ incrementing by step. The type of the returned elements is the same as the type of argument
+ expressions.
+
+ Supported types are: byte, short, integer, long, date, timestamp.
+
+ The start and stop expressions must resolve to the same type.
+ If start and stop expressions resolve to the 'date' or 'timestamp' type
+ then the step expression must resolve to the 'interval' type, otherwise to the same type
+ as the start and stop expressions.
+ """,
+ arguments = """
+ Arguments:
+ * start - an expression. The start of the range.
+ * stop - an expression. The end the range (inclusive).
+ * step - an optional expression. The step of the range.
+ By default step is 1 if start is less than or equal to stop, otherwise -1.
+ For the temporal sequences it's 1 day and -1 day respectively.
+ If start is greater than stop then the step must be negative, and vice versa.
+ """,
+ examples = """
+ Examples:
+ > SELECT _FUNC_(1, 5);
+ [1, 2, 3, 4, 5]
+ > SELECT _FUNC_(5, 1);
+ [5, 4, 3, 2, 1]
+ > SELECT _FUNC_(to_date('2018-01-01'), to_date('2018-03-01'), interval 1 month);
+ [2018-01-01, 2018-02-01, 2018-03-01]
+ """,
+ since = "2.4.0"
+)
+case class Sequence(
+ start: Expression,
+ stop: Expression,
+ stepOpt: Option[Expression],
+ timeZoneId: Option[String] = None)
+ extends Expression
+ with TimeZoneAwareExpression {
+
+ import Sequence._
+
+ def this(start: Expression, stop: Expression) =
+ this(start, stop, None, None)
+
+ def this(start: Expression, stop: Expression, step: Expression) =
+ this(start, stop, Some(step), None)
+
+ override def withTimeZone(timeZoneId: String): TimeZoneAwareExpression =
+ copy(timeZoneId = Some(timeZoneId))
+
+ override def children: Seq[Expression] = Seq(start, stop) ++ stepOpt
+
+ override def foldable: Boolean = children.forall(_.foldable)
+
+ override def nullable: Boolean = children.exists(_.nullable)
+
+ override lazy val dataType: ArrayType = ArrayType(start.dataType, containsNull = false)
+
+ override def checkInputDataTypes(): TypeCheckResult = {
+ val startType = start.dataType
+ def stepType = stepOpt.get.dataType
+ val typesCorrect =
+ startType.sameType(stop.dataType) &&
+ (startType match {
+ case TimestampType | DateType =>
+ stepOpt.isEmpty || CalendarIntervalType.acceptsType(stepType)
+ case _: IntegralType =>
+ stepOpt.isEmpty || stepType.sameType(startType)
+ case _ => false
+ })
+
+ if (typesCorrect) {
+ TypeCheckResult.TypeCheckSuccess
+ } else {
+ TypeCheckResult.TypeCheckFailure(
+ s"$prettyName only supports integral, timestamp or date types")
+ }
+ }
+
+ def coercibleChildren: Seq[Expression] = children.filter(_.dataType != CalendarIntervalType)
+
+ def castChildrenTo(widerType: DataType): Expression = Sequence(
+ Cast(start, widerType),
+ Cast(stop, widerType),
+ stepOpt.map(step => if (step.dataType != CalendarIntervalType) Cast(step, widerType) else step),
+ timeZoneId)
+
+ private lazy val impl: SequenceImpl = dataType.elementType match {
+ case iType: IntegralType =>
+ type T = iType.InternalType
+ val ct = ClassTag[T](iType.tag.mirror.runtimeClass(iType.tag.tpe))
+ new IntegralSequenceImpl(iType)(ct, iType.integral)
+
+ case TimestampType =>
+ new TemporalSequenceImpl[Long](LongType, 1, identity, timeZone)
+
+ case DateType =>
+ new TemporalSequenceImpl[Int](IntegerType, MICROS_PER_DAY, _.toInt, timeZone)
+ }
+
+ override def eval(input: InternalRow): Any = {
+ val startVal = start.eval(input)
+ if (startVal == null) return null
+ val stopVal = stop.eval(input)
+ if (stopVal == null) return null
+ val stepVal = stepOpt.map(_.eval(input)).getOrElse(impl.defaultStep(startVal, stopVal))
+ if (stepVal == null) return null
+
+ ArrayData.toArrayData(impl.eval(startVal, stopVal, stepVal))
+ }
+
+ override protected def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = {
+ val startGen = start.genCode(ctx)
+ val stopGen = stop.genCode(ctx)
+ val stepGen = stepOpt.map(_.genCode(ctx)).getOrElse(
+ impl.defaultStep.genCode(ctx, startGen, stopGen))
+
+ val resultType = CodeGenerator.javaType(dataType)
+ val resultCode = {
+ val arr = ctx.freshName("arr")
+ val arrElemType = CodeGenerator.javaType(dataType.elementType)
+ s"""
+ |final $arrElemType[] $arr = null;
+ |${impl.genCode(ctx, startGen.value, stopGen.value, stepGen.value, arr, arrElemType)}
+ |${ev.value} = UnsafeArrayData.fromPrimitiveArray($arr);
+ """.stripMargin
+ }
+
+ if (nullable) {
+ val nullSafeEval =
+ startGen.code + ctx.nullSafeExec(start.nullable, startGen.isNull) {
+ stopGen.code + ctx.nullSafeExec(stop.nullable, stopGen.isNull) {
+ stepGen.code + ctx.nullSafeExec(stepOpt.exists(_.nullable), stepGen.isNull) {
+ s"""
+ |${ev.isNull} = false;
+ |$resultCode
+ """.stripMargin
+ }
+ }
+ }
+ ev.copy(code =
+ s"""
+ |boolean ${ev.isNull} = true;
+ |$resultType ${ev.value} = null;
+ |$nullSafeEval
+ """.stripMargin)
+
+ } else {
+ ev.copy(code =
+ s"""
+ |boolean ${ev.isNull} = false;
--- End diff --
removed
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by wajda <gi...@git.apache.org>.
Github user wajda commented on a diff in the pull request:
https://github.com/apache/spark/pull/21155#discussion_r197465469
--- Diff: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/collectionOperations.scala ---
@@ -1887,6 +1889,402 @@ case class Flatten(child: Expression) extends UnaryExpression {
override def prettyName: String = "flatten"
}
+@ExpressionDescription(
+ usage = """
+ _FUNC_(start, stop, step) - Generates an array of elements from start to stop (inclusive),
+ incrementing by step. The type of the returned elements is the same as the type of argument
+ expressions.
+
+ Supported types are: byte, short, integer, long, date, timestamp.
+
+ The start and stop expressions must resolve to the same type.
+ If start and stop expressions resolve to the 'date' or 'timestamp' type
+ then the step expression must resolve to the 'interval' type, otherwise to the same type
+ as the start and stop expressions.
+ """,
+ arguments = """
+ Arguments:
+ * start - an expression. The start of the range.
+ * stop - an expression. The end the range (inclusive).
+ * step - an optional expression. The step of the range.
+ By default step is 1 if start is less than or equal to stop, otherwise -1.
+ For the temporal sequences it's 1 day and -1 day respectively.
+ If start is greater than stop then the step must be negative, and vice versa.
+ """,
+ examples = """
+ Examples:
+ > SELECT _FUNC_(1, 5);
+ [1, 2, 3, 4, 5]
+ > SELECT _FUNC_(5, 1);
+ [5, 4, 3, 2, 1]
+ > SELECT _FUNC_(to_date('2018-01-01'), to_date('2018-03-01'), interval 1 month);
+ [2018-01-01, 2018-02-01, 2018-03-01]
+ """,
+ since = "2.4.0"
+)
+case class Sequence(
+ start: Expression,
+ stop: Expression,
+ stepOpt: Option[Expression],
+ timeZoneId: Option[String] = None)
+ extends Expression
+ with TimeZoneAwareExpression {
+
+ import Sequence._
+
+ def this(start: Expression, stop: Expression) =
+ this(start, stop, None, None)
+
+ def this(start: Expression, stop: Expression, step: Expression) =
+ this(start, stop, Some(step), None)
+
+ override def withTimeZone(timeZoneId: String): TimeZoneAwareExpression =
+ copy(timeZoneId = Some(timeZoneId))
+
+ override def children: Seq[Expression] = Seq(start, stop) ++ stepOpt
+
+ override def foldable: Boolean = children.forall(_.foldable)
+
+ override def nullable: Boolean = children.exists(_.nullable)
+
+ override lazy val dataType: ArrayType = ArrayType(start.dataType, containsNull = false)
+
+ override def checkInputDataTypes(): TypeCheckResult = {
+ val startType = start.dataType
+ def stepType = stepOpt.get.dataType
+ val typesCorrect =
+ startType.sameType(stop.dataType) &&
+ (startType match {
+ case TimestampType | DateType =>
+ stepOpt.isEmpty || CalendarIntervalType.acceptsType(stepType)
+ case _: IntegralType =>
+ stepOpt.isEmpty || stepType.sameType(startType)
+ case _ => false
+ })
+
+ if (typesCorrect) {
+ TypeCheckResult.TypeCheckSuccess
+ } else {
+ TypeCheckResult.TypeCheckFailure(
+ s"$prettyName only supports integral, timestamp or date types")
+ }
+ }
+
+ def coercibleChildren: Seq[Expression] = children.filter(_.dataType != CalendarIntervalType)
+
+ def castChildrenTo(widerType: DataType): Expression = Sequence(
--- End diff --
what is the purpose? Copy constructor works the best in this case as it's type safe and does exactly what I need to do.
I tried to use `withNewChildren` like this:
```
def castChildrenTo(widerType: DataType): Expression = withNewChildren(Seq(
Cast(start, widerType),
Cast(stop, widerType)) ++
stepOpt.map(step => if (step.dataType != CalendarIntervalType) Cast(step, widerType) else step))
```
but it doesn't work as expected for some reason. I didn't grasp all the magic it does yet, but do we really need to complicate things? Why a copy constructor is a bad choice in this case?
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:
https://github.com/apache/spark/pull/21155
Test PASSed.
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/90456/
Test PASSed.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:
https://github.com/apache/spark/pull/21155
Test PASSed.
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/90899/
Test PASSed.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request #21155: SPARK-23927: Add "sequence" expression
Posted by ueshin <gi...@git.apache.org>.
Github user ueshin commented on a diff in the pull request:
https://github.com/apache/spark/pull/21155#discussion_r186030182
--- Diff: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/TypeCoercion.scala ---
@@ -536,6 +536,15 @@ object TypeCoercion {
case None => c
}
+ case s @ Sequence(_, _, _, timeZoneId) if !haveSameType(s.children) =>
+ val types = s.children.map(_.dataType)
+ findWiderCommonType(types) match {
--- End diff --
Maybe we should use `ExpectsInputTypes` or `ImplicitCastInputTypes` instead of `TypeCoercion`.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:
https://github.com/apache/spark/pull/21155
**[Test build #90899 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/90899/testReport)** for PR 21155 at commit [`4b8af57`](https://github.com/apache/spark/commit/4b8af571d625d4c7c029757896f050001ab1e4f3).
* This patch passes all tests.
* This patch merges cleanly.
* This patch adds the following public classes _(experimental)_:
* `case class Sequence(`
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: SPARK-23927: Add "sequence" expression
Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:
https://github.com/apache/spark/pull/21155
**[Test build #89860 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/89860/testReport)** for PR 21155 at commit [`a7c0ccd`](https://github.com/apache/spark/commit/a7c0ccdfa7b2f78ab3ae29aa6b5b1c16dfc38f9c).
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request #21155: SPARK-23927: Add "sequence" expression
Posted by ueshin <gi...@git.apache.org>.
Github user ueshin commented on a diff in the pull request:
https://github.com/apache/spark/pull/21155#discussion_r186030720
--- Diff: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/collectionOperations.scala ---
@@ -1059,3 +1063,316 @@ case class Flatten(child: Expression) extends UnaryExpression {
override def prettyName: String = "flatten"
}
+
+@ExpressionDescription(
+ usage = """
+ _FUNC_(start, stop, step) -
+ Generates an array of elements from start to stop (inclusive), incrementing by step.
+ The type of the returned elements is the same as the type of argument expressions.
+
+ Supported types are: byte, short, integer, long, date, timestamp.
+
+ The start and stop expressions must resolve to the same type.
+ If start and stop expressions resolve to the 'date' or 'timestamp' type
+ then the step expression must resolve to the 'interval' type, otherwise to the same type
+ as the start and stop expressions.
+ """,
+ arguments = """
+ Arguments:
+ * start - an expression. The start of the range.
+ * stop - an expression. The end the range (inclusive).
+ * step - an optional expression. The step of the range.
+
+ By default step is 1 if start is less than or equal to stop, otherwise -1.
+ For the temporal sequences it's 1 day and -1 day respectively.
+
+ If start is greater than stop then the step must be negative, and vice versa.
+ """,
+ examples = """
+ Examples:
+ > SELECT _FUNC_(1, 5);
+ [1, 2, 3, 4, 5]
+ > SELECT _FUNC_(5, 1);
+ [5, 4, 3, 2, 1]
+ > SELECT _FUNC_(to_date('2018-01-01'), to_date('2018-03-01'), interval 1 month);
+ [2018-01-01, 2018-02-01, 2018-03-01]
+ """,
+ since = "2.4.0"
+)
+case class Sequence(left: Expression,
+ middle: Expression,
+ right: Expression,
+ timeZoneId: Option[String] = None)
+ extends TernaryExpression with TimeZoneAwareExpression {
--- End diff --
How about making `step: Option[Expression]` so we don't need `UnresolvedLiteral`, I guess. Similar usage is in `ArrayJoin` expression.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request #21155: SPARK-23927: Add "sequence" expression
Posted by ueshin <gi...@git.apache.org>.
Github user ueshin commented on a diff in the pull request:
https://github.com/apache/spark/pull/21155#discussion_r186029528
--- Diff: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/collectionOperations.scala ---
@@ -1059,3 +1063,316 @@ case class Flatten(child: Expression) extends UnaryExpression {
override def prettyName: String = "flatten"
}
+
+@ExpressionDescription(
+ usage = """
+ _FUNC_(start, stop, step) -
+ Generates an array of elements from start to stop (inclusive), incrementing by step.
+ The type of the returned elements is the same as the type of argument expressions.
+
+ Supported types are: byte, short, integer, long, date, timestamp.
+
+ The start and stop expressions must resolve to the same type.
+ If start and stop expressions resolve to the 'date' or 'timestamp' type
+ then the step expression must resolve to the 'interval' type, otherwise to the same type
+ as the start and stop expressions.
+ """,
+ arguments = """
+ Arguments:
+ * start - an expression. The start of the range.
+ * stop - an expression. The end the range (inclusive).
+ * step - an optional expression. The step of the range.
+
+ By default step is 1 if start is less than or equal to stop, otherwise -1.
+ For the temporal sequences it's 1 day and -1 day respectively.
+
+ If start is greater than stop then the step must be negative, and vice versa.
+ """,
+ examples = """
+ Examples:
+ > SELECT _FUNC_(1, 5);
+ [1, 2, 3, 4, 5]
+ > SELECT _FUNC_(5, 1);
+ [5, 4, 3, 2, 1]
+ > SELECT _FUNC_(to_date('2018-01-01'), to_date('2018-03-01'), interval 1 month);
+ [2018-01-01, 2018-02-01, 2018-03-01]
+ """,
+ since = "2.4.0"
+)
+case class Sequence(left: Expression,
+ middle: Expression,
+ right: Expression,
+ timeZoneId: Option[String] = None)
+ extends TernaryExpression with TimeZoneAwareExpression {
+
+ import Sequence._
+
+ def this(arg0: Expression, arg1: Expression) =
--- End diff --
`start`, `stop`?
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: SPARK-23927: Add "sequence" expression
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:
https://github.com/apache/spark/pull/21155
Can one of the admins verify this patch?
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: SPARK-23927: Add "sequence" expression
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:
https://github.com/apache/spark/pull/21155
Merged build finished. Test FAILed.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by wajda <gi...@git.apache.org>.
Github user wajda commented on a diff in the pull request:
https://github.com/apache/spark/pull/21155#discussion_r187309647
--- Diff: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/collectionOperations.scala ---
@@ -1468,3 +1472,388 @@ case class Flatten(child: Expression) extends UnaryExpression {
override def prettyName: String = "flatten"
}
+
+@ExpressionDescription(
+ usage = """
+ _FUNC_(start, stop, step) - Generates an array of elements from start to stop (inclusive),
+ incrementing by step. The type of the returned elements is the same as the type of argument
+ expressions.
+
+ Supported types are: byte, short, integer, long, date, timestamp.
+
+ The start and stop expressions must resolve to the same type.
+ If start and stop expressions resolve to the 'date' or 'timestamp' type
+ then the step expression must resolve to the 'interval' type, otherwise to the same type
+ as the start and stop expressions.
+ """,
+ arguments = """
+ Arguments:
+ * start - an expression. The start of the range.
+ * stop - an expression. The end the range (inclusive).
+ * step - an optional expression. The step of the range.
+ By default step is 1 if start is less than or equal to stop, otherwise -1.
+ For the temporal sequences it's 1 day and -1 day respectively.
+ If start is greater than stop then the step must be negative, and vice versa.
+ """,
+ examples = """
+ Examples:
+ > SELECT _FUNC_(1, 5);
+ [1, 2, 3, 4, 5]
+ > SELECT _FUNC_(5, 1);
+ [5, 4, 3, 2, 1]
+ > SELECT _FUNC_(to_date('2018-01-01'), to_date('2018-03-01'), interval 1 month);
+ [2018-01-01, 2018-02-01, 2018-03-01]
+ """,
+ since = "2.4.0"
+)
+case class Sequence(
+ start: Expression,
+ stop: Expression,
+ stepOpt: Option[Expression],
+ timeZoneId: Option[String] = None)
+ extends Expression
+ with ExpectsInputTypes
+ with TimeZoneAwareExpression {
+
+ import Sequence._
+
+ def this(start: Expression, stop: Expression) =
+ this(start, stop, None, None)
+
+ def this(start: Expression, stop: Expression, step: Expression) =
+ this(start, stop, Some(step), None)
+
+ override def withTimeZone(timeZoneId: String): TimeZoneAwareExpression =
+ copy(timeZoneId = Some(timeZoneId))
+
+ override def children: Seq[Expression] = Seq(start, stop) ++ stepOpt
+
+ override def foldable: Boolean = children.forall(_.foldable)
+
+ override def nullable: Boolean = children.exists(_.nullable)
+
+ override lazy val dataType: ArrayType = ArrayType(start.dataType, containsNull = false)
+
+ override def inputTypes: Seq[AbstractDataType] = {
+ val elemType = dataType.elementType
+ Seq(elemType, elemType) ++
+ stepOpt.map(_ => elemType match {
+ case DateType | TimestampType => CalendarIntervalType
+ case _: IntegralType => elemType
--- End diff --
It would fail with match error, but I see your point.
Reverted to ```checkInputDataTypes```, improved type check conditions, added tests for invalid data types.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request #21155: SPARK-23927: Add "sequence" expression
Posted by ueshin <gi...@git.apache.org>.
Github user ueshin commented on a diff in the pull request:
https://github.com/apache/spark/pull/21155#discussion_r186031064
--- Diff: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/collectionOperations.scala ---
@@ -1059,3 +1063,316 @@ case class Flatten(child: Expression) extends UnaryExpression {
override def prettyName: String = "flatten"
}
+
+@ExpressionDescription(
+ usage = """
--- End diff --
Maybe we need to fix indent in the usage, arguments, examples.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: SPARK-23927: Add "sequence" expression
Posted by gatorsmile <gi...@git.apache.org>.
Github user gatorsmile commented on the issue:
https://github.com/apache/spark/pull/21155
cc @ueshin
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: SPARK-23927: Add "sequence" expression
Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:
https://github.com/apache/spark/pull/21155
**[Test build #89854 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/89854/testReport)** for PR 21155 at commit [`88fde1c`](https://github.com/apache/spark/commit/88fde1c3a3d009a9a138df3cf2825e22248afa2a).
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by ueshin <gi...@git.apache.org>.
Github user ueshin commented on a diff in the pull request:
https://github.com/apache/spark/pull/21155#discussion_r197674957
--- Diff: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/collectionOperations.scala ---
@@ -2288,6 +2288,401 @@ case class Flatten(child: Expression) extends UnaryExpression {
override def prettyName: String = "flatten"
}
+@ExpressionDescription(
+ usage = """
+ _FUNC_(start, stop, step) - Generates an array of elements from start to stop (inclusive),
+ incrementing by step. The type of the returned elements is the same as the type of argument
+ expressions.
+
+ Supported types are: byte, short, integer, long, date, timestamp.
+
+ The start and stop expressions must resolve to the same type.
+ If start and stop expressions resolve to the 'date' or 'timestamp' type
+ then the step expression must resolve to the 'interval' type, otherwise to the same type
+ as the start and stop expressions.
+ """,
+ arguments = """
+ Arguments:
+ * start - an expression. The start of the range.
+ * stop - an expression. The end the range (inclusive).
+ * step - an optional expression. The step of the range.
+ By default step is 1 if start is less than or equal to stop, otherwise -1.
+ For the temporal sequences it's 1 day and -1 day respectively.
+ If start is greater than stop then the step must be negative, and vice versa.
+ """,
+ examples = """
+ Examples:
+ > SELECT _FUNC_(1, 5);
+ [1, 2, 3, 4, 5]
+ > SELECT _FUNC_(5, 1);
+ [5, 4, 3, 2, 1]
+ > SELECT _FUNC_(to_date('2018-01-01'), to_date('2018-03-01'), interval 1 month);
+ [2018-01-01, 2018-02-01, 2018-03-01]
+ """,
+ since = "2.4.0"
+)
+case class Sequence(
+ start: Expression,
+ stop: Expression,
+ stepOpt: Option[Expression],
+ timeZoneId: Option[String] = None)
+ extends Expression
+ with TimeZoneAwareExpression {
+
+ import Sequence._
+
+ def this(start: Expression, stop: Expression) =
+ this(start, stop, None, None)
+
+ def this(start: Expression, stop: Expression, step: Expression) =
+ this(start, stop, Some(step), None)
+
+ override def withTimeZone(timeZoneId: String): TimeZoneAwareExpression =
+ copy(timeZoneId = Some(timeZoneId))
+
+ override def children: Seq[Expression] = Seq(start, stop) ++ stepOpt
+
+ override def foldable: Boolean = children.forall(_.foldable)
+
+ override def nullable: Boolean = children.exists(_.nullable)
+
+ override lazy val dataType: ArrayType = ArrayType(start.dataType, containsNull = false)
+
+ override def checkInputDataTypes(): TypeCheckResult = {
+ val startType = start.dataType
+ def stepType = stepOpt.get.dataType
+ val typesCorrect =
+ startType.sameType(stop.dataType) &&
+ (startType match {
+ case TimestampType | DateType =>
+ stepOpt.isEmpty || CalendarIntervalType.acceptsType(stepType)
+ case _: IntegralType =>
+ stepOpt.isEmpty || stepType.sameType(startType)
+ case _ => false
+ })
+
+ if (typesCorrect) {
+ TypeCheckResult.TypeCheckSuccess
+ } else {
+ TypeCheckResult.TypeCheckFailure(
+ s"$prettyName only supports integral, timestamp or date types")
+ }
+ }
+
+ def coercibleChildren: Seq[Expression] = children.filter(_.dataType != CalendarIntervalType)
+
+ def castChildrenTo(widerType: DataType): Expression = Sequence(
+ Cast(start, widerType),
+ Cast(stop, widerType),
+ stepOpt.map(step => if (step.dataType != CalendarIntervalType) Cast(step, widerType) else step),
--- End diff --
We can try to cast to `CalendarIntervalType` if `widerType` is `DateType` or `TimestampType` and `step.dataType` is `StringType`? We might want to use `StringType` for the interval.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:
https://github.com/apache/spark/pull/21155
Merged build finished. Test PASSed.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:
https://github.com/apache/spark/pull/21155
Merged build finished. Test PASSed.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by ueshin <gi...@git.apache.org>.
Github user ueshin commented on a diff in the pull request:
https://github.com/apache/spark/pull/21155#discussion_r193927263
--- Diff: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/collectionOperations.scala ---
@@ -1887,6 +1889,402 @@ case class Flatten(child: Expression) extends UnaryExpression {
override def prettyName: String = "flatten"
}
+@ExpressionDescription(
+ usage = """
+ _FUNC_(start, stop, step) - Generates an array of elements from start to stop (inclusive),
+ incrementing by step. The type of the returned elements is the same as the type of argument
+ expressions.
+
+ Supported types are: byte, short, integer, long, date, timestamp.
+
+ The start and stop expressions must resolve to the same type.
+ If start and stop expressions resolve to the 'date' or 'timestamp' type
+ then the step expression must resolve to the 'interval' type, otherwise to the same type
+ as the start and stop expressions.
+ """,
+ arguments = """
+ Arguments:
+ * start - an expression. The start of the range.
+ * stop - an expression. The end the range (inclusive).
+ * step - an optional expression. The step of the range.
+ By default step is 1 if start is less than or equal to stop, otherwise -1.
+ For the temporal sequences it's 1 day and -1 day respectively.
+ If start is greater than stop then the step must be negative, and vice versa.
+ """,
+ examples = """
+ Examples:
+ > SELECT _FUNC_(1, 5);
+ [1, 2, 3, 4, 5]
+ > SELECT _FUNC_(5, 1);
+ [5, 4, 3, 2, 1]
+ > SELECT _FUNC_(to_date('2018-01-01'), to_date('2018-03-01'), interval 1 month);
+ [2018-01-01, 2018-02-01, 2018-03-01]
+ """,
+ since = "2.4.0"
+)
+case class Sequence(
+ start: Expression,
+ stop: Expression,
+ stepOpt: Option[Expression],
+ timeZoneId: Option[String] = None)
+ extends Expression
+ with TimeZoneAwareExpression {
+
+ import Sequence._
+
+ def this(start: Expression, stop: Expression) =
+ this(start, stop, None, None)
+
+ def this(start: Expression, stop: Expression, step: Expression) =
+ this(start, stop, Some(step), None)
+
+ override def withTimeZone(timeZoneId: String): TimeZoneAwareExpression =
+ copy(timeZoneId = Some(timeZoneId))
+
+ override def children: Seq[Expression] = Seq(start, stop) ++ stepOpt
+
+ override def foldable: Boolean = children.forall(_.foldable)
+
+ override def nullable: Boolean = children.exists(_.nullable)
+
+ override lazy val dataType: ArrayType = ArrayType(start.dataType, containsNull = false)
+
+ override def checkInputDataTypes(): TypeCheckResult = {
+ val startType = start.dataType
+ def stepType = stepOpt.get.dataType
+ val typesCorrect =
+ startType.sameType(stop.dataType) &&
+ (startType match {
+ case TimestampType | DateType =>
+ stepOpt.isEmpty || CalendarIntervalType.acceptsType(stepType)
+ case _: IntegralType =>
+ stepOpt.isEmpty || stepType.sameType(startType)
+ case _ => false
+ })
+
+ if (typesCorrect) {
+ TypeCheckResult.TypeCheckSuccess
+ } else {
+ TypeCheckResult.TypeCheckFailure(
+ s"$prettyName only supports integral, timestamp or date types")
+ }
+ }
+
+ def coercibleChildren: Seq[Expression] = children.filter(_.dataType != CalendarIntervalType)
+
+ def castChildrenTo(widerType: DataType): Expression = Sequence(
+ Cast(start, widerType),
+ Cast(stop, widerType),
+ stepOpt.map(step => if (step.dataType != CalendarIntervalType) Cast(step, widerType) else step),
+ timeZoneId)
+
+ private lazy val impl: SequenceImpl = dataType.elementType match {
+ case iType: IntegralType =>
+ type T = iType.InternalType
+ val ct = ClassTag[T](iType.tag.mirror.runtimeClass(iType.tag.tpe))
+ new IntegralSequenceImpl(iType)(ct, iType.integral)
+
+ case TimestampType =>
+ new TemporalSequenceImpl[Long](LongType, 1, identity, timeZone)
+
+ case DateType =>
+ new TemporalSequenceImpl[Int](IntegerType, MICROS_PER_DAY, _.toInt, timeZone)
+ }
+
+ override def eval(input: InternalRow): Any = {
+ val startVal = start.eval(input)
+ if (startVal == null) return null
+ val stopVal = stop.eval(input)
+ if (stopVal == null) return null
+ val stepVal = stepOpt.map(_.eval(input)).getOrElse(impl.defaultStep(startVal, stopVal))
+ if (stepVal == null) return null
+
+ ArrayData.toArrayData(impl.eval(startVal, stopVal, stepVal))
+ }
+
+ override protected def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = {
+ val startGen = start.genCode(ctx)
+ val stopGen = stop.genCode(ctx)
+ val stepGen = stepOpt.map(_.genCode(ctx)).getOrElse(
+ impl.defaultStep.genCode(ctx, startGen, stopGen))
+
+ val resultType = CodeGenerator.javaType(dataType)
+ val resultCode = {
+ val arr = ctx.freshName("arr")
+ val arrElemType = CodeGenerator.javaType(dataType.elementType)
+ s"""
+ |final $arrElemType[] $arr = null;
+ |${impl.genCode(ctx, startGen.value, stopGen.value, stepGen.value, arr, arrElemType)}
+ |${ev.value} = UnsafeArrayData.fromPrimitiveArray($arr);
+ """.stripMargin
+ }
+
+ if (nullable) {
+ val nullSafeEval =
+ startGen.code + ctx.nullSafeExec(start.nullable, startGen.isNull) {
+ stopGen.code + ctx.nullSafeExec(stop.nullable, stopGen.isNull) {
+ stepGen.code + ctx.nullSafeExec(stepOpt.exists(_.nullable), stepGen.isNull) {
+ s"""
+ |${ev.isNull} = false;
+ |$resultCode
+ """.stripMargin
+ }
+ }
+ }
+ ev.copy(code =
+ s"""
+ |boolean ${ev.isNull} = true;
+ |$resultType ${ev.value} = null;
+ |$nullSafeEval
+ """.stripMargin)
+
+ } else {
+ ev.copy(code =
+ s"""
+ |boolean ${ev.isNull} = false;
--- End diff --
Maybe we don't need this?
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by wajda <gi...@git.apache.org>.
Github user wajda commented on the issue:
https://github.com/apache/spark/pull/21155
Any other comments on this one?
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:
https://github.com/apache/spark/pull/21155
Test PASSed.
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/92295/
Test PASSed.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request #21155: SPARK-23927: Add "sequence" expression
Posted by ueshin <gi...@git.apache.org>.
Github user ueshin commented on a diff in the pull request:
https://github.com/apache/spark/pull/21155#discussion_r186037814
--- Diff: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/collectionOperations.scala ---
@@ -1059,3 +1063,316 @@ case class Flatten(child: Expression) extends UnaryExpression {
override def prettyName: String = "flatten"
}
+
+@ExpressionDescription(
+ usage = """
+ _FUNC_(start, stop, step) -
+ Generates an array of elements from start to stop (inclusive), incrementing by step.
+ The type of the returned elements is the same as the type of argument expressions.
+
+ Supported types are: byte, short, integer, long, date, timestamp.
+
+ The start and stop expressions must resolve to the same type.
+ If start and stop expressions resolve to the 'date' or 'timestamp' type
+ then the step expression must resolve to the 'interval' type, otherwise to the same type
+ as the start and stop expressions.
+ """,
+ arguments = """
+ Arguments:
+ * start - an expression. The start of the range.
+ * stop - an expression. The end the range (inclusive).
+ * step - an optional expression. The step of the range.
+
+ By default step is 1 if start is less than or equal to stop, otherwise -1.
+ For the temporal sequences it's 1 day and -1 day respectively.
+
+ If start is greater than stop then the step must be negative, and vice versa.
+ """,
+ examples = """
+ Examples:
+ > SELECT _FUNC_(1, 5);
+ [1, 2, 3, 4, 5]
+ > SELECT _FUNC_(5, 1);
+ [5, 4, 3, 2, 1]
+ > SELECT _FUNC_(to_date('2018-01-01'), to_date('2018-03-01'), interval 1 month);
+ [2018-01-01, 2018-02-01, 2018-03-01]
+ """,
+ since = "2.4.0"
+)
+case class Sequence(left: Expression,
+ middle: Expression,
+ right: Expression,
+ timeZoneId: Option[String] = None)
+ extends TernaryExpression with TimeZoneAwareExpression {
+
+ import Sequence._
+
+ def this(arg0: Expression, arg1: Expression) =
+ this(arg0, arg1, Sequence.defaultStepExpression(arg0, arg1), None)
+
+ def this(arg0: Expression, arg1: Expression, arg2: Expression) =
+ this(arg0, arg1, arg2, None)
+
+ override def withTimeZone(timeZoneId: String): TimeZoneAwareExpression =
+ copy(timeZoneId = Some(timeZoneId))
+
+ override def children: Seq[Expression] = Seq(left, middle, right)
+
+ override lazy val dataType: ArrayType = ArrayType(left.dataType, containsNull = false)
+
+ override def checkInputDataTypes(): TypeCheckResult = {
+ val Seq(startType, stopType, stepType) = children.map(_.dataType)
+ val typesCorrect =
+ startType.sameType(stopType) &&
+ (startType match {
+ case TimestampType | DateType => CalendarIntervalType acceptsType stepType
+ case _: IntegralType => stepType sameType startType
+ case _ => false
+ })
+
+ if (typesCorrect) {
+ TypeCheckResult.TypeCheckSuccess
+ } else {
+ TypeCheckResult.TypeCheckFailure(
+ s"$prettyName only supports integral, timestamp or date types")
+ }
+ }
+
+ private lazy val impl: SequenceImpl = dataType.elementType match {
+ case iType: IntegralType =>
+ type T = iType.InternalType
+ val ct = ClassTag[T](iType.tag.mirror.runtimeClass(iType.tag.tpe))
+ new IntegralSequenceImpl()(ct, iType.integral)
+
+ case TimestampType =>
+ new TemporalSequenceImpl[Long](LongType, 1, identity, timeZone)
+
+ case DateType =>
+ new TemporalSequenceImpl[Int](IntegerType, MICROS_PER_DAY, _.toInt, timeZone)
+ }
+
+ override protected def nullSafeEval(input1: Any, input2: Any, input3: Any): Any = {
+ ArrayData.toArrayData(impl.eval(input1, input2, input3))
+ }
+
+ override protected def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = {
+ nullSafeCodeGen(ctx, ev, (start, stop, step) => {
+ val arr = ctx.freshName("arr")
+ val arrElemType = CodeGenerator.javaType(dataType.elementType)
+ s"""
+ | final $arrElemType[] $arr = null;
+ | ${impl.genCode(start, stop, step)(arr, arrElemType)(ctx)}
+ | ${ev.value} = UnsafeArrayData.fromPrimitiveArray($arr);
+ """.stripMargin
+ })
+ }
+}
+
+object Sequence {
+
+ private trait SequenceImpl {
+ def eval(input1: Any, input2: Any, input3: Any): Any
+
+ def genCode(start: String, stop: String, step: String)
+ (arr: String, elemType: String)
+ (implicit ctx: CodegenContext): String
+ }
+
+ private class IntegralSequenceImpl[T: ClassTag]
+ (implicit num: Integral[T]) extends SequenceImpl {
+
+ override def eval(input1: Any, input2: Any, input3: Any): Array[T] = {
+ import num._
+
+ val start = input1.asInstanceOf[T]
+ val stop = input2.asInstanceOf[T]
+ val step = input3.asInstanceOf[T]
+
+ var i: Int = getSequenceLength(start, stop, step)
+ val arr = new Array[T](i)
+ while (i > 0) {
+ i -= 1
+ arr(i) = start + step * num.fromInt(i)
+ }
+ arr
+ }
+
+ override def genCode(start: String, stop: String, step: String)
+ (arr: String, elemType: String)
+ (implicit ctx: CodegenContext): String = {
--- End diff --
ditto.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by ueshin <gi...@git.apache.org>.
Github user ueshin commented on a diff in the pull request:
https://github.com/apache/spark/pull/21155#discussion_r193926575
--- Diff: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/collectionOperations.scala ---
@@ -1887,6 +1889,402 @@ case class Flatten(child: Expression) extends UnaryExpression {
override def prettyName: String = "flatten"
}
+@ExpressionDescription(
+ usage = """
+ _FUNC_(start, stop, step) - Generates an array of elements from start to stop (inclusive),
+ incrementing by step. The type of the returned elements is the same as the type of argument
+ expressions.
+
+ Supported types are: byte, short, integer, long, date, timestamp.
+
+ The start and stop expressions must resolve to the same type.
+ If start and stop expressions resolve to the 'date' or 'timestamp' type
+ then the step expression must resolve to the 'interval' type, otherwise to the same type
+ as the start and stop expressions.
+ """,
+ arguments = """
+ Arguments:
+ * start - an expression. The start of the range.
+ * stop - an expression. The end the range (inclusive).
+ * step - an optional expression. The step of the range.
+ By default step is 1 if start is less than or equal to stop, otherwise -1.
+ For the temporal sequences it's 1 day and -1 day respectively.
+ If start is greater than stop then the step must be negative, and vice versa.
+ """,
+ examples = """
+ Examples:
+ > SELECT _FUNC_(1, 5);
+ [1, 2, 3, 4, 5]
+ > SELECT _FUNC_(5, 1);
+ [5, 4, 3, 2, 1]
+ > SELECT _FUNC_(to_date('2018-01-01'), to_date('2018-03-01'), interval 1 month);
+ [2018-01-01, 2018-02-01, 2018-03-01]
+ """,
+ since = "2.4.0"
+)
+case class Sequence(
+ start: Expression,
+ stop: Expression,
+ stepOpt: Option[Expression],
+ timeZoneId: Option[String] = None)
+ extends Expression
+ with TimeZoneAwareExpression {
+
+ import Sequence._
+
+ def this(start: Expression, stop: Expression) =
+ this(start, stop, None, None)
+
+ def this(start: Expression, stop: Expression, step: Expression) =
+ this(start, stop, Some(step), None)
+
+ override def withTimeZone(timeZoneId: String): TimeZoneAwareExpression =
+ copy(timeZoneId = Some(timeZoneId))
+
+ override def children: Seq[Expression] = Seq(start, stop) ++ stepOpt
+
+ override def foldable: Boolean = children.forall(_.foldable)
+
+ override def nullable: Boolean = children.exists(_.nullable)
+
+ override lazy val dataType: ArrayType = ArrayType(start.dataType, containsNull = false)
+
+ override def checkInputDataTypes(): TypeCheckResult = {
+ val startType = start.dataType
+ def stepType = stepOpt.get.dataType
+ val typesCorrect =
+ startType.sameType(stop.dataType) &&
+ (startType match {
+ case TimestampType | DateType =>
+ stepOpt.isEmpty || CalendarIntervalType.acceptsType(stepType)
+ case _: IntegralType =>
+ stepOpt.isEmpty || stepType.sameType(startType)
+ case _ => false
+ })
+
+ if (typesCorrect) {
+ TypeCheckResult.TypeCheckSuccess
+ } else {
+ TypeCheckResult.TypeCheckFailure(
+ s"$prettyName only supports integral, timestamp or date types")
+ }
+ }
+
+ def coercibleChildren: Seq[Expression] = children.filter(_.dataType != CalendarIntervalType)
+
+ def castChildrenTo(widerType: DataType): Expression = Sequence(
+ Cast(start, widerType),
+ Cast(stop, widerType),
+ stepOpt.map(step => if (step.dataType != CalendarIntervalType) Cast(step, widerType) else step),
+ timeZoneId)
+
+ private lazy val impl: SequenceImpl = dataType.elementType match {
+ case iType: IntegralType =>
+ type T = iType.InternalType
+ val ct = ClassTag[T](iType.tag.mirror.runtimeClass(iType.tag.tpe))
+ new IntegralSequenceImpl(iType)(ct, iType.integral)
+
+ case TimestampType =>
+ new TemporalSequenceImpl[Long](LongType, 1, identity, timeZone)
+
+ case DateType =>
+ new TemporalSequenceImpl[Int](IntegerType, MICROS_PER_DAY, _.toInt, timeZone)
+ }
+
+ override def eval(input: InternalRow): Any = {
+ val startVal = start.eval(input)
+ if (startVal == null) return null
+ val stopVal = stop.eval(input)
+ if (stopVal == null) return null
+ val stepVal = stepOpt.map(_.eval(input)).getOrElse(impl.defaultStep(startVal, stopVal))
+ if (stepVal == null) return null
+
+ ArrayData.toArrayData(impl.eval(startVal, stopVal, stepVal))
+ }
+
+ override protected def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = {
+ val startGen = start.genCode(ctx)
+ val stopGen = stop.genCode(ctx)
+ val stepGen = stepOpt.map(_.genCode(ctx)).getOrElse(
+ impl.defaultStep.genCode(ctx, startGen, stopGen))
+
+ val resultType = CodeGenerator.javaType(dataType)
+ val resultCode = {
+ val arr = ctx.freshName("arr")
+ val arrElemType = CodeGenerator.javaType(dataType.elementType)
+ s"""
+ |final $arrElemType[] $arr = null;
+ |${impl.genCode(ctx, startGen.value, stopGen.value, stepGen.value, arr, arrElemType)}
+ |${ev.value} = UnsafeArrayData.fromPrimitiveArray($arr);
+ """.stripMargin
+ }
+
+ if (nullable) {
+ val nullSafeEval =
+ startGen.code + ctx.nullSafeExec(start.nullable, startGen.isNull) {
+ stopGen.code + ctx.nullSafeExec(stop.nullable, stopGen.isNull) {
+ stepGen.code + ctx.nullSafeExec(stepOpt.exists(_.nullable), stepGen.isNull) {
+ s"""
+ |${ev.isNull} = false;
+ |$resultCode
+ """.stripMargin
+ }
+ }
+ }
+ ev.copy(code =
+ s"""
+ |boolean ${ev.isNull} = true;
+ |$resultType ${ev.value} = null;
+ |$nullSafeEval
+ """.stripMargin)
+
+ } else {
+ ev.copy(code =
+ s"""
+ |boolean ${ev.isNull} = false;
+ |${startGen.code}
+ |${stopGen.code}
+ |${stepGen.code}
+ |$resultType ${ev.value} = null;
+ |$resultCode
+ """.stripMargin,
+ isNull = FalseLiteral)
+ }
+ }
+}
+
+object Sequence {
+
+ private type LessThanOrEqualFn = (Any, Any) => Boolean
+
+ private class DefaultStep(lteq: LessThanOrEqualFn, stepType: DataType, one: Any) {
+ private val negativeOne = UnaryMinus(Literal(one)).eval()
+
+ def apply(start: Any, stop: Any): Any = {
+ if (lteq(start, stop)) one else negativeOne
+ }
+
+ def genCode(ctx: CodegenContext, startGen: ExprCode, stopGen: ExprCode): ExprCode = {
+ val Seq(oneVal, negativeOneVal) = Seq(one, negativeOne).map(Literal(_).genCode(ctx).value)
+ ExprCode.forNonNullValue(JavaCode.expression(
+ s"${startGen.value} <= ${stopGen.value} ? $oneVal : $negativeOneVal",
+ stepType))
+ }
+ }
+
+ private trait SequenceImpl {
+ def eval(start: Any, stop: Any, step: Any): Any
+
+ def genCode(
+ ctx: CodegenContext,
+ start: String,
+ stop: String,
+ step: String,
+ arr: String,
+ elemType: String): String
+
+ val defaultStep: DefaultStep
+ }
+
+ private class IntegralSequenceImpl[T: ClassTag]
+ (elemType: IntegralType)(implicit num: Integral[T]) extends SequenceImpl {
+
+ override val defaultStep: DefaultStep = new DefaultStep(
+ (elemType.ordering.lteq _).asInstanceOf[LessThanOrEqualFn],
+ elemType,
+ num.one)
+
+ override def eval(input1: Any, input2: Any, input3: Any): Array[T] = {
+ import num._
+
+ val start = input1.asInstanceOf[T]
+ val stop = input2.asInstanceOf[T]
+ val step = input3.asInstanceOf[T]
+
+ var i: Int = getSequenceLength(start, stop, step)
+ val arr = new Array[T](i)
+ while (i > 0) {
+ i -= 1
+ arr(i) = start + step * num.fromInt(i)
+ }
+ arr
+ }
+
+ override def genCode(
+ ctx: CodegenContext,
+ start: String,
+ stop: String,
+ step: String,
+ arr: String,
+ elemType: String): String = {
+ val i = ctx.freshName("i")
+ s"""
+ |${genSequenceLengthCode(ctx, start, stop, step, i)}
+ |$arr = new $elemType[$i];
+ |while ($i > 0) {
+ | $i--;
+ | $arr[$i] = ($elemType) ($start + $step * $i);
+ |}
+ """.stripMargin
+ }
+ }
+
+ private class TemporalSequenceImpl[T: ClassTag]
+ (dt: IntegralType, scale: Long, fromLong: Long => T, timeZone: TimeZone)
+ (implicit num: Integral[T]) extends SequenceImpl {
+
+ override val defaultStep: DefaultStep = new DefaultStep(
+ (dt.ordering.lteq _).asInstanceOf[LessThanOrEqualFn],
+ CalendarIntervalType,
+ new CalendarInterval(0, MICROS_PER_DAY))
+
+ private val backedSequenceImpl = new IntegralSequenceImpl[T](dt)
+ private val microsPerMonth = 28 * CalendarInterval.MICROS_PER_DAY
+
+ override def eval(input1: Any, input2: Any, input3: Any): Array[T] = {
+ val start = input1.asInstanceOf[T]
+ val stop = input2.asInstanceOf[T]
+ val step = input3.asInstanceOf[CalendarInterval]
+ val stepMonths = step.months
+ val stepMicros = step.microseconds
+
+ if (stepMonths == 0) {
+ backedSequenceImpl.eval(start, stop, fromLong(stepMicros / scale))
+
+ } else {
+ // To estimate the resulted array length we need to make assumptions
+ // about a month length in microseconds
+ val intervalStepInMicros = stepMicros + stepMonths * microsPerMonth
+ val startMicros: Long = num.toLong(start) * scale
+ val stopMicros: Long = num.toLong(stop) * scale
+ val maxEstimatedArrayLength =
+ getSequenceLength(startMicros, stopMicros, intervalStepInMicros)
+
+ val stepSign = if (stopMicros > startMicros) +1 else -1
+ val exclusiveItem = stopMicros + stepSign
+ val arr = new Array[T](maxEstimatedArrayLength)
+ var t = startMicros
+ var i = 0
+
+ while (t < exclusiveItem ^ stepSign < 0) {
+ arr(i) = fromLong(t / scale)
+ t = timestampAddInterval(t, stepMonths, stepMicros, timeZone)
+ i += 1
+ }
+
+ // truncate array to the correct length
+ if (arr.length == i) arr else arr.slice(0, i)
+ }
+ }
+
+ override def genCode(
+ ctx: CodegenContext,
+ start: String,
+ stop: String,
+ step: String,
+ arr: String,
+ elemType: String): String = {
+ val stepMonths = ctx.freshName("stepMonths")
+ val stepMicros = ctx.freshName("stepMicros")
+ val stepScaled = ctx.freshName("stepScaled")
+ val intervalInMicros = ctx.freshName("intervalInMicros")
+ val startMicros = ctx.freshName("startMicros")
+ val stopMicros = ctx.freshName("stopMicros")
+ val arrLength = ctx.freshName("arrLength")
+ val stepSign = ctx.freshName("stepSign")
+ val exclusiveItem = ctx.freshName("exclusiveItem")
+ val t = ctx.freshName("t")
+ val i = ctx.freshName("i")
+ val genTimeZone = ctx.freshName("timeZone")
+
+ val sequenceLengthCode =
+ s"""
+ |final long $intervalInMicros = $stepMicros + $stepMonths * ${microsPerMonth}L;
+ |${genSequenceLengthCode(ctx, startMicros, stopMicros, intervalInMicros, arrLength)}
+ """.stripMargin
+
+ val timestampAddIntervalCode =
+ s"""
+ |$t = org.apache.spark.sql.catalyst.util.DateTimeUtils.timestampAddInterval(
+ | $t, $stepMonths, $stepMicros, $genTimeZone);
+ """.stripMargin
+
+ s"""
+ |final int $stepMonths = $step.months;
+ |final long $stepMicros = $step.microseconds;
+ |
+ |if ($stepMonths == 0) {
+ | final $elemType $stepScaled = ($elemType) ($stepMicros / ${scale}L);
+ | ${backedSequenceImpl.genCode(ctx, start, stop, stepScaled, arr, elemType)};
+ |
+ |} else {
+ | final long $startMicros = $start * ${scale}L;
+ | final long $stopMicros = $stop * ${scale}L;
+ |
+ | $sequenceLengthCode
+ |
+ | final int $stepSign = $stopMicros > $startMicros ? +1 : -1;
+ | final long $exclusiveItem = $stopMicros + $stepSign;
+ | final java.util.TimeZone $genTimeZone =
+ | java.util.TimeZone.getTimeZone("${timeZone.getID}");
+ |
+ | $arr = new $elemType[$arrLength];
+ | long $t = $startMicros;
+ | int $i = 0;
+ |
+ | while ($t < $exclusiveItem ^ $stepSign < 0) {
+ | $arr[$i] = ($elemType) ($t / ${scale}L);
+ | $timestampAddIntervalCode
+ | $i += 1;
+ | }
+ |
+ | if ($arr.length > $i) {
+ | $arr = java.util.Arrays.copyOf($arr, $i);
+ | }
+ |}
+ """.stripMargin
+ }
+ }
+
+ private def getSequenceLength[U](start: U, stop: U, step: U)(implicit num: Integral[U]): Int = {
+ import num._
+ require(
+ step > num.zero && start <= stop
+ || step < num.zero && start >= stop
+ || step == 0 && start == stop,
+ s"Illegal sequence boundaries: $start to $stop by $step")
+
+ val len = if (start == stop) 1L else 1L + (stop.toLong - start.toLong) / step.toLong
+
+ require(len <= Int.MaxValue, s"Too long sequence: $len. Should be <= ${Int.MaxValue}")
+
+ len.toInt
+ }
+
+ private def genSequenceLengthCode(
+ ctx: CodegenContext,
+ start: String,
+ stop: String,
+ step: String,
+ len: String): String = {
+ val longLen = ctx.freshName("longLen")
+ s"""
+ |if (!($step > 0 && $start <= $stop||
+ | $step < 0 && $start >= $stop||
+ | $step == 0 && $start == $stop)) {
--- End diff --
Could you add more parenthesis to be clear the boundaries between `&&` and `||`? The combinations of `&&` and `||` without parenthesis may cause an unexpected behavior.
```
( ... && ... ) || ( ... && ... ) || ...
```
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:
https://github.com/apache/spark/pull/21155
**[Test build #92326 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/92326/testReport)** for PR 21155 at commit [`140225d`](https://github.com/apache/spark/commit/140225d8b2326122f69e9093a071c1cdde7e489d).
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:
https://github.com/apache/spark/pull/21155
Merged build finished. Test PASSed.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by wajda <gi...@git.apache.org>.
Github user wajda commented on the issue:
https://github.com/apache/spark/pull/21155
please retest
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by wajda <gi...@git.apache.org>.
Github user wajda commented on a diff in the pull request:
https://github.com/apache/spark/pull/21155#discussion_r198079703
--- Diff: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/collectionOperations.scala ---
@@ -2289,6 +2292,401 @@ case class Flatten(child: Expression) extends UnaryExpression {
override def prettyName: String = "flatten"
}
+@ExpressionDescription(
+ usage = """
+ _FUNC_(start, stop, step) - Generates an array of elements from start to stop (inclusive),
+ incrementing by step. The type of the returned elements is the same as the type of argument
+ expressions.
+
+ Supported types are: byte, short, integer, long, date, timestamp.
+
+ The start and stop expressions must resolve to the same type.
+ If start and stop expressions resolve to the 'date' or 'timestamp' type
+ then the step expression must resolve to the 'interval' type, otherwise to the same type
+ as the start and stop expressions.
+ """,
+ arguments = """
+ Arguments:
+ * start - an expression. The start of the range.
+ * stop - an expression. The end the range (inclusive).
+ * step - an optional expression. The step of the range.
+ By default step is 1 if start is less than or equal to stop, otherwise -1.
+ For the temporal sequences it's 1 day and -1 day respectively.
+ If start is greater than stop then the step must be negative, and vice versa.
+ """,
+ examples = """
+ Examples:
+ > SELECT _FUNC_(1, 5);
+ [1, 2, 3, 4, 5]
+ > SELECT _FUNC_(5, 1);
+ [5, 4, 3, 2, 1]
+ > SELECT _FUNC_(to_date('2018-01-01'), to_date('2018-03-01'), interval 1 month);
+ [2018-01-01, 2018-02-01, 2018-03-01]
+ """,
+ since = "2.4.0"
+)
+case class Sequence(
+ start: Expression,
+ stop: Expression,
+ stepOpt: Option[Expression],
+ timeZoneId: Option[String] = None)
+ extends Expression
+ with TimeZoneAwareExpression {
+
+ import Sequence._
+
+ def this(start: Expression, stop: Expression) =
+ this(start, stop, None, None)
+
+ def this(start: Expression, stop: Expression, step: Expression) =
+ this(start, stop, Some(step), None)
+
+ override def withTimeZone(timeZoneId: String): TimeZoneAwareExpression =
+ copy(timeZoneId = Some(timeZoneId))
+
+ override def children: Seq[Expression] = Seq(start, stop) ++ stepOpt
+
+ override def foldable: Boolean = children.forall(_.foldable)
+
+ override def nullable: Boolean = children.exists(_.nullable)
+
+ override lazy val dataType: ArrayType = ArrayType(start.dataType, containsNull = false)
+
+ override def checkInputDataTypes(): TypeCheckResult = {
+ val startType = start.dataType
+ def stepType = stepOpt.get.dataType
+ val typesCorrect =
+ startType.sameType(stop.dataType) &&
+ (startType match {
+ case TimestampType | DateType =>
+ stepOpt.isEmpty || CalendarIntervalType.acceptsType(stepType)
+ case _: IntegralType =>
+ stepOpt.isEmpty || stepType.sameType(startType)
+ case _ => false
+ })
+
+ if (typesCorrect) {
+ TypeCheckResult.TypeCheckSuccess
+ } else {
+ TypeCheckResult.TypeCheckFailure(
+ s"$prettyName only supports integral, timestamp or date types")
+ }
+ }
+
+ def coercibleChildren: Seq[Expression] = children.filter(_.dataType != CalendarIntervalType)
+
+ def castChildrenTo(widerType: DataType): Expression = Sequence(
+ Cast(start, widerType),
+ Cast(stop, widerType),
+ stepOpt.map(step => if (step.dataType != CalendarIntervalType) Cast(step, widerType) else step),
+ timeZoneId)
+
+ private lazy val impl: SequenceImpl = dataType.elementType match {
+ case iType: IntegralType =>
+ type T = iType.InternalType
+ val ct = ClassTag[T](iType.tag.mirror.runtimeClass(iType.tag.tpe))
+ new IntegralSequenceImpl(iType)(ct, iType.integral)
+
+ case TimestampType =>
+ new TemporalSequenceImpl[Long](LongType, 1, identity, timeZone)
+
+ case DateType =>
+ new TemporalSequenceImpl[Int](IntegerType, MICROS_PER_DAY, _.toInt, timeZone)
+ }
+
+ override def eval(input: InternalRow): Any = {
+ val startVal = start.eval(input)
+ if (startVal == null) return null
+ val stopVal = stop.eval(input)
+ if (stopVal == null) return null
+ val stepVal = stepOpt.map(_.eval(input)).getOrElse(impl.defaultStep(startVal, stopVal))
+ if (stepVal == null) return null
+
+ ArrayData.toArrayData(impl.eval(startVal, stopVal, stepVal))
+ }
+
+ override protected def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = {
+ val startGen = start.genCode(ctx)
+ val stopGen = stop.genCode(ctx)
+ val stepGen = stepOpt.map(_.genCode(ctx)).getOrElse(
+ impl.defaultStep.genCode(ctx, startGen, stopGen))
+
+ val resultType = CodeGenerator.javaType(dataType)
+ val resultCode = {
+ val arr = ctx.freshName("arr")
+ val arrElemType = CodeGenerator.javaType(dataType.elementType)
+ s"""
+ |final $arrElemType[] $arr = null;
+ |${impl.genCode(ctx, startGen.value, stopGen.value, stepGen.value, arr, arrElemType)}
+ |${ev.value} = UnsafeArrayData.fromPrimitiveArray($arr);
+ """.stripMargin
+ }
+
+ if (nullable) {
+ val nullSafeEval =
+ startGen.code + ctx.nullSafeExec(start.nullable, startGen.isNull) {
+ stopGen.code + ctx.nullSafeExec(stop.nullable, stopGen.isNull) {
+ stepGen.code + ctx.nullSafeExec(stepOpt.exists(_.nullable), stepGen.isNull) {
+ s"""
+ |${ev.isNull} = false;
+ |$resultCode
+ """.stripMargin
+ }
+ }
+ }
+ ev.copy(code =
+ code"""
+ |boolean ${ev.isNull} = true;
+ |$resultType ${ev.value} = null;
+ |$nullSafeEval
+ """.stripMargin)
+
+ } else {
+ ev.copy(code =
+ code"""
+ |${startGen.code}
+ |${stopGen.code}
+ |${stepGen.code}
+ |$resultType ${ev.value} = null;
+ |$resultCode
+ """.stripMargin,
+ isNull = FalseLiteral)
+ }
+ }
+}
+
+object Sequence {
+
+ private type LessThanOrEqualFn = (Any, Any) => Boolean
+
+ private class DefaultStep(lteq: LessThanOrEqualFn, stepType: DataType, one: Any) {
+ private val negativeOne = UnaryMinus(Literal(one)).eval()
+
+ def apply(start: Any, stop: Any): Any = {
+ if (lteq(start, stop)) one else negativeOne
+ }
+
+ def genCode(ctx: CodegenContext, startGen: ExprCode, stopGen: ExprCode): ExprCode = {
+ val Seq(oneVal, negativeOneVal) = Seq(one, negativeOne).map(Literal(_).genCode(ctx).value)
+ ExprCode.forNonNullValue(JavaCode.expression(
+ s"${startGen.value} <= ${stopGen.value} ? $oneVal : $negativeOneVal",
+ stepType))
+ }
+ }
+
+ private trait SequenceImpl {
+ def eval(start: Any, stop: Any, step: Any): Any
+
+ def genCode(
+ ctx: CodegenContext,
+ start: String,
+ stop: String,
+ step: String,
+ arr: String,
+ elemType: String): String
+
+ val defaultStep: DefaultStep
+ }
+
+ private class IntegralSequenceImpl[T: ClassTag]
+ (elemType: IntegralType)(implicit num: Integral[T]) extends SequenceImpl {
+
+ override val defaultStep: DefaultStep = new DefaultStep(
+ (elemType.ordering.lteq _).asInstanceOf[LessThanOrEqualFn],
+ elemType,
+ num.one)
+
+ override def eval(input1: Any, input2: Any, input3: Any): Array[T] = {
+ import num._
+
+ val start = input1.asInstanceOf[T]
+ val stop = input2.asInstanceOf[T]
+ val step = input3.asInstanceOf[T]
+
+ var i: Int = getSequenceLength(start, stop, step)
+ val arr = new Array[T](i)
+ while (i > 0) {
+ i -= 1
+ arr(i) = start + step * num.fromInt(i)
+ }
+ arr
+ }
+
+ override def genCode(
+ ctx: CodegenContext,
+ start: String,
+ stop: String,
+ step: String,
+ arr: String,
+ elemType: String): String = {
+ val i = ctx.freshName("i")
+ s"""
+ |${genSequenceLengthCode(ctx, start, stop, step, i)}
+ |$arr = new $elemType[$i];
+ |while ($i > 0) {
+ | $i--;
+ | $arr[$i] = ($elemType) ($start + $step * $i);
+ |}
+ """.stripMargin
+ }
+ }
+
+ private class TemporalSequenceImpl[T: ClassTag]
+ (dt: IntegralType, scale: Long, fromLong: Long => T, timeZone: TimeZone)
+ (implicit num: Integral[T]) extends SequenceImpl {
+
+ override val defaultStep: DefaultStep = new DefaultStep(
+ (dt.ordering.lteq _).asInstanceOf[LessThanOrEqualFn],
+ CalendarIntervalType,
+ new CalendarInterval(0, MICROS_PER_DAY))
+
+ private val backedSequenceImpl = new IntegralSequenceImpl[T](dt)
+ private val microsPerMonth = 28 * CalendarInterval.MICROS_PER_DAY
+
+ override def eval(input1: Any, input2: Any, input3: Any): Array[T] = {
+ val start = input1.asInstanceOf[T]
+ val stop = input2.asInstanceOf[T]
+ val step = input3.asInstanceOf[CalendarInterval]
+ val stepMonths = step.months
+ val stepMicros = step.microseconds
+
+ if (stepMonths == 0) {
+ backedSequenceImpl.eval(start, stop, fromLong(stepMicros / scale))
+
+ } else {
+ // To estimate the resulted array length we need to make assumptions
+ // about a month length in microseconds
+ val intervalStepInMicros = stepMicros + stepMonths * microsPerMonth
+ val startMicros: Long = num.toLong(start) * scale
+ val stopMicros: Long = num.toLong(stop) * scale
+ val maxEstimatedArrayLength =
+ getSequenceLength(startMicros, stopMicros, intervalStepInMicros)
+
+ val stepSign = if (stopMicros > startMicros) +1 else -1
+ val exclusiveItem = stopMicros + stepSign
+ val arr = new Array[T](maxEstimatedArrayLength)
+ var t = startMicros
+ var i = 0
+
+ while (t < exclusiveItem ^ stepSign < 0) {
+ arr(i) = fromLong(t / scale)
+ t = timestampAddInterval(t, stepMonths, stepMicros, timeZone)
+ i += 1
+ }
+
+ // truncate array to the correct length
+ if (arr.length == i) arr else arr.slice(0, i)
+ }
+ }
+
+ override def genCode(
+ ctx: CodegenContext,
+ start: String,
+ stop: String,
+ step: String,
+ arr: String,
+ elemType: String): String = {
+ val stepMonths = ctx.freshName("stepMonths")
+ val stepMicros = ctx.freshName("stepMicros")
+ val stepScaled = ctx.freshName("stepScaled")
+ val intervalInMicros = ctx.freshName("intervalInMicros")
+ val startMicros = ctx.freshName("startMicros")
+ val stopMicros = ctx.freshName("stopMicros")
+ val arrLength = ctx.freshName("arrLength")
+ val stepSign = ctx.freshName("stepSign")
+ val exclusiveItem = ctx.freshName("exclusiveItem")
+ val t = ctx.freshName("t")
+ val i = ctx.freshName("i")
+ val genTimeZone = ctx.addReferenceObj("timeZone", timeZone, classOf[TimeZone].getName)
+
+ val sequenceLengthCode =
+ s"""
+ |final long $intervalInMicros = $stepMicros + $stepMonths * ${microsPerMonth}L;
+ |${genSequenceLengthCode(ctx, startMicros, stopMicros, intervalInMicros, arrLength)}
+ """.stripMargin
+
+ val timestampAddIntervalCode =
+ s"""
+ |$t = org.apache.spark.sql.catalyst.util.DateTimeUtils.timestampAddInterval(
+ | $t, $stepMonths, $stepMicros, $genTimeZone);
+ """.stripMargin
+
+ s"""
+ |final int $stepMonths = $step.months;
+ |final long $stepMicros = $step.microseconds;
+ |
+ |if ($stepMonths == 0) {
+ | final $elemType $stepScaled = ($elemType) ($stepMicros / ${scale}L);
+ | ${backedSequenceImpl.genCode(ctx, start, stop, stepScaled, arr, elemType)};
+ |
+ |} else {
+ | final long $startMicros = $start * ${scale}L;
+ | final long $stopMicros = $stop * ${scale}L;
+ |
+ | $sequenceLengthCode
+ |
+ | final int $stepSign = $stopMicros > $startMicros ? +1 : -1;
+ | final long $exclusiveItem = $stopMicros + $stepSign;
+ |
+ | $arr = new $elemType[$arrLength];
+ | long $t = $startMicros;
+ | int $i = 0;
+ |
+ | while ($t < $exclusiveItem ^ $stepSign < 0) {
+ | $arr[$i] = ($elemType) ($t / ${scale}L);
+ | $timestampAddIntervalCode
+ | $i += 1;
+ | }
+ |
+ | if ($arr.length > $i) {
+ | $arr = java.util.Arrays.copyOf($arr, $i);
+ | }
+ |}
+ """.stripMargin
+ }
+ }
+
+ private def getSequenceLength[U](start: U, stop: U, step: U)(implicit num: Integral[U]): Int = {
+ import num._
+ require(
+ (step > num.zero && start <= stop)
+ || (step < num.zero && start >= stop)
+ || (step == 0 && start == stop),
--- End diff --
Fixed. Although I wonder what difference it makes besides the readability? Doesn't `equals(0)` work consistently on every numeric types in Scala? Or is it related to autoboxing somehow? It's not very clear to me in this context. Thanks.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by viirya <gi...@git.apache.org>.
Github user viirya commented on a diff in the pull request:
https://github.com/apache/spark/pull/21155#discussion_r187288741
--- Diff: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/collectionOperations.scala ---
@@ -1468,3 +1472,388 @@ case class Flatten(child: Expression) extends UnaryExpression {
override def prettyName: String = "flatten"
}
+
+@ExpressionDescription(
+ usage = """
+ _FUNC_(start, stop, step) - Generates an array of elements from start to stop (inclusive),
+ incrementing by step. The type of the returned elements is the same as the type of argument
+ expressions.
+
+ Supported types are: byte, short, integer, long, date, timestamp.
+
+ The start and stop expressions must resolve to the same type.
+ If start and stop expressions resolve to the 'date' or 'timestamp' type
+ then the step expression must resolve to the 'interval' type, otherwise to the same type
+ as the start and stop expressions.
+ """,
+ arguments = """
+ Arguments:
+ * start - an expression. The start of the range.
+ * stop - an expression. The end the range (inclusive).
+ * step - an optional expression. The step of the range.
+ By default step is 1 if start is less than or equal to stop, otherwise -1.
+ For the temporal sequences it's 1 day and -1 day respectively.
+ If start is greater than stop then the step must be negative, and vice versa.
+ """,
+ examples = """
+ Examples:
+ > SELECT _FUNC_(1, 5);
+ [1, 2, 3, 4, 5]
+ > SELECT _FUNC_(5, 1);
+ [5, 4, 3, 2, 1]
+ > SELECT _FUNC_(to_date('2018-01-01'), to_date('2018-03-01'), interval 1 month);
+ [2018-01-01, 2018-02-01, 2018-03-01]
+ """,
+ since = "2.4.0"
+)
+case class Sequence(
+ start: Expression,
+ stop: Expression,
+ stepOpt: Option[Expression],
+ timeZoneId: Option[String] = None)
+ extends Expression
+ with ExpectsInputTypes
+ with TimeZoneAwareExpression {
+
+ import Sequence._
+
+ def this(start: Expression, stop: Expression) =
+ this(start, stop, None, None)
+
+ def this(start: Expression, stop: Expression, step: Expression) =
+ this(start, stop, Some(step), None)
+
+ override def withTimeZone(timeZoneId: String): TimeZoneAwareExpression =
+ copy(timeZoneId = Some(timeZoneId))
+
+ override def children: Seq[Expression] = Seq(start, stop) ++ stepOpt
+
+ override def foldable: Boolean = children.forall(_.foldable)
+
+ override def nullable: Boolean = children.exists(_.nullable)
+
+ override lazy val dataType: ArrayType = ArrayType(start.dataType, containsNull = false)
+
+ override def inputTypes: Seq[AbstractDataType] = {
+ val elemType = dataType.elementType
+ Seq(elemType, elemType) ++
+ stepOpt.map(_ => elemType match {
+ case DateType | TimestampType => CalendarIntervalType
+ case _: IntegralType => elemType
--- End diff --
Default `checkInputDataTypes` just checks if data types of children matches `inputTypes`. Looks like for now here we don't have any limit. So even an invalid data type is given, `checkInputDataTypes` won't complain.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by ueshin <gi...@git.apache.org>.
Github user ueshin commented on a diff in the pull request:
https://github.com/apache/spark/pull/21155#discussion_r198051469
--- Diff: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/collectionOperations.scala ---
@@ -2289,6 +2292,401 @@ case class Flatten(child: Expression) extends UnaryExpression {
override def prettyName: String = "flatten"
}
+@ExpressionDescription(
+ usage = """
+ _FUNC_(start, stop, step) - Generates an array of elements from start to stop (inclusive),
+ incrementing by step. The type of the returned elements is the same as the type of argument
+ expressions.
+
+ Supported types are: byte, short, integer, long, date, timestamp.
+
+ The start and stop expressions must resolve to the same type.
+ If start and stop expressions resolve to the 'date' or 'timestamp' type
+ then the step expression must resolve to the 'interval' type, otherwise to the same type
+ as the start and stop expressions.
+ """,
+ arguments = """
+ Arguments:
+ * start - an expression. The start of the range.
+ * stop - an expression. The end the range (inclusive).
+ * step - an optional expression. The step of the range.
+ By default step is 1 if start is less than or equal to stop, otherwise -1.
+ For the temporal sequences it's 1 day and -1 day respectively.
+ If start is greater than stop then the step must be negative, and vice versa.
+ """,
+ examples = """
+ Examples:
+ > SELECT _FUNC_(1, 5);
+ [1, 2, 3, 4, 5]
+ > SELECT _FUNC_(5, 1);
+ [5, 4, 3, 2, 1]
+ > SELECT _FUNC_(to_date('2018-01-01'), to_date('2018-03-01'), interval 1 month);
+ [2018-01-01, 2018-02-01, 2018-03-01]
+ """,
+ since = "2.4.0"
+)
+case class Sequence(
+ start: Expression,
+ stop: Expression,
+ stepOpt: Option[Expression],
+ timeZoneId: Option[String] = None)
+ extends Expression
+ with TimeZoneAwareExpression {
+
+ import Sequence._
+
+ def this(start: Expression, stop: Expression) =
+ this(start, stop, None, None)
+
+ def this(start: Expression, stop: Expression, step: Expression) =
+ this(start, stop, Some(step), None)
+
+ override def withTimeZone(timeZoneId: String): TimeZoneAwareExpression =
+ copy(timeZoneId = Some(timeZoneId))
+
+ override def children: Seq[Expression] = Seq(start, stop) ++ stepOpt
+
+ override def foldable: Boolean = children.forall(_.foldable)
+
+ override def nullable: Boolean = children.exists(_.nullable)
+
+ override lazy val dataType: ArrayType = ArrayType(start.dataType, containsNull = false)
+
+ override def checkInputDataTypes(): TypeCheckResult = {
+ val startType = start.dataType
+ def stepType = stepOpt.get.dataType
+ val typesCorrect =
+ startType.sameType(stop.dataType) &&
+ (startType match {
+ case TimestampType | DateType =>
+ stepOpt.isEmpty || CalendarIntervalType.acceptsType(stepType)
+ case _: IntegralType =>
+ stepOpt.isEmpty || stepType.sameType(startType)
+ case _ => false
+ })
+
+ if (typesCorrect) {
+ TypeCheckResult.TypeCheckSuccess
+ } else {
+ TypeCheckResult.TypeCheckFailure(
+ s"$prettyName only supports integral, timestamp or date types")
+ }
+ }
+
+ def coercibleChildren: Seq[Expression] = children.filter(_.dataType != CalendarIntervalType)
+
+ def castChildrenTo(widerType: DataType): Expression = Sequence(
+ Cast(start, widerType),
+ Cast(stop, widerType),
+ stepOpt.map(step => if (step.dataType != CalendarIntervalType) Cast(step, widerType) else step),
+ timeZoneId)
+
+ private lazy val impl: SequenceImpl = dataType.elementType match {
+ case iType: IntegralType =>
+ type T = iType.InternalType
+ val ct = ClassTag[T](iType.tag.mirror.runtimeClass(iType.tag.tpe))
+ new IntegralSequenceImpl(iType)(ct, iType.integral)
+
+ case TimestampType =>
+ new TemporalSequenceImpl[Long](LongType, 1, identity, timeZone)
+
+ case DateType =>
+ new TemporalSequenceImpl[Int](IntegerType, MICROS_PER_DAY, _.toInt, timeZone)
+ }
+
+ override def eval(input: InternalRow): Any = {
+ val startVal = start.eval(input)
+ if (startVal == null) return null
+ val stopVal = stop.eval(input)
+ if (stopVal == null) return null
+ val stepVal = stepOpt.map(_.eval(input)).getOrElse(impl.defaultStep(startVal, stopVal))
+ if (stepVal == null) return null
+
+ ArrayData.toArrayData(impl.eval(startVal, stopVal, stepVal))
+ }
+
+ override protected def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = {
+ val startGen = start.genCode(ctx)
+ val stopGen = stop.genCode(ctx)
+ val stepGen = stepOpt.map(_.genCode(ctx)).getOrElse(
+ impl.defaultStep.genCode(ctx, startGen, stopGen))
+
+ val resultType = CodeGenerator.javaType(dataType)
+ val resultCode = {
+ val arr = ctx.freshName("arr")
+ val arrElemType = CodeGenerator.javaType(dataType.elementType)
+ s"""
+ |final $arrElemType[] $arr = null;
+ |${impl.genCode(ctx, startGen.value, stopGen.value, stepGen.value, arr, arrElemType)}
+ |${ev.value} = UnsafeArrayData.fromPrimitiveArray($arr);
+ """.stripMargin
+ }
+
+ if (nullable) {
+ val nullSafeEval =
+ startGen.code + ctx.nullSafeExec(start.nullable, startGen.isNull) {
+ stopGen.code + ctx.nullSafeExec(stop.nullable, stopGen.isNull) {
+ stepGen.code + ctx.nullSafeExec(stepOpt.exists(_.nullable), stepGen.isNull) {
+ s"""
+ |${ev.isNull} = false;
+ |$resultCode
+ """.stripMargin
+ }
+ }
+ }
+ ev.copy(code =
+ code"""
+ |boolean ${ev.isNull} = true;
+ |$resultType ${ev.value} = null;
+ |$nullSafeEval
+ """.stripMargin)
+
+ } else {
+ ev.copy(code =
+ code"""
+ |${startGen.code}
+ |${stopGen.code}
+ |${stepGen.code}
+ |$resultType ${ev.value} = null;
+ |$resultCode
+ """.stripMargin,
+ isNull = FalseLiteral)
+ }
+ }
+}
+
+object Sequence {
+
+ private type LessThanOrEqualFn = (Any, Any) => Boolean
+
+ private class DefaultStep(lteq: LessThanOrEqualFn, stepType: DataType, one: Any) {
+ private val negativeOne = UnaryMinus(Literal(one)).eval()
+
+ def apply(start: Any, stop: Any): Any = {
+ if (lteq(start, stop)) one else negativeOne
+ }
+
+ def genCode(ctx: CodegenContext, startGen: ExprCode, stopGen: ExprCode): ExprCode = {
+ val Seq(oneVal, negativeOneVal) = Seq(one, negativeOne).map(Literal(_).genCode(ctx).value)
+ ExprCode.forNonNullValue(JavaCode.expression(
+ s"${startGen.value} <= ${stopGen.value} ? $oneVal : $negativeOneVal",
+ stepType))
+ }
+ }
+
+ private trait SequenceImpl {
+ def eval(start: Any, stop: Any, step: Any): Any
+
+ def genCode(
+ ctx: CodegenContext,
+ start: String,
+ stop: String,
+ step: String,
+ arr: String,
+ elemType: String): String
+
+ val defaultStep: DefaultStep
+ }
+
+ private class IntegralSequenceImpl[T: ClassTag]
+ (elemType: IntegralType)(implicit num: Integral[T]) extends SequenceImpl {
+
+ override val defaultStep: DefaultStep = new DefaultStep(
+ (elemType.ordering.lteq _).asInstanceOf[LessThanOrEqualFn],
+ elemType,
+ num.one)
+
+ override def eval(input1: Any, input2: Any, input3: Any): Array[T] = {
+ import num._
+
+ val start = input1.asInstanceOf[T]
+ val stop = input2.asInstanceOf[T]
+ val step = input3.asInstanceOf[T]
+
+ var i: Int = getSequenceLength(start, stop, step)
+ val arr = new Array[T](i)
+ while (i > 0) {
+ i -= 1
+ arr(i) = start + step * num.fromInt(i)
+ }
+ arr
+ }
+
+ override def genCode(
+ ctx: CodegenContext,
+ start: String,
+ stop: String,
+ step: String,
+ arr: String,
+ elemType: String): String = {
+ val i = ctx.freshName("i")
+ s"""
+ |${genSequenceLengthCode(ctx, start, stop, step, i)}
+ |$arr = new $elemType[$i];
+ |while ($i > 0) {
+ | $i--;
+ | $arr[$i] = ($elemType) ($start + $step * $i);
+ |}
+ """.stripMargin
+ }
+ }
+
+ private class TemporalSequenceImpl[T: ClassTag]
+ (dt: IntegralType, scale: Long, fromLong: Long => T, timeZone: TimeZone)
+ (implicit num: Integral[T]) extends SequenceImpl {
+
+ override val defaultStep: DefaultStep = new DefaultStep(
+ (dt.ordering.lteq _).asInstanceOf[LessThanOrEqualFn],
+ CalendarIntervalType,
+ new CalendarInterval(0, MICROS_PER_DAY))
+
+ private val backedSequenceImpl = new IntegralSequenceImpl[T](dt)
+ private val microsPerMonth = 28 * CalendarInterval.MICROS_PER_DAY
+
+ override def eval(input1: Any, input2: Any, input3: Any): Array[T] = {
+ val start = input1.asInstanceOf[T]
+ val stop = input2.asInstanceOf[T]
+ val step = input3.asInstanceOf[CalendarInterval]
+ val stepMonths = step.months
+ val stepMicros = step.microseconds
+
+ if (stepMonths == 0) {
+ backedSequenceImpl.eval(start, stop, fromLong(stepMicros / scale))
+
+ } else {
+ // To estimate the resulted array length we need to make assumptions
+ // about a month length in microseconds
+ val intervalStepInMicros = stepMicros + stepMonths * microsPerMonth
+ val startMicros: Long = num.toLong(start) * scale
+ val stopMicros: Long = num.toLong(stop) * scale
+ val maxEstimatedArrayLength =
+ getSequenceLength(startMicros, stopMicros, intervalStepInMicros)
+
+ val stepSign = if (stopMicros > startMicros) +1 else -1
+ val exclusiveItem = stopMicros + stepSign
+ val arr = new Array[T](maxEstimatedArrayLength)
+ var t = startMicros
+ var i = 0
+
+ while (t < exclusiveItem ^ stepSign < 0) {
+ arr(i) = fromLong(t / scale)
+ t = timestampAddInterval(t, stepMonths, stepMicros, timeZone)
+ i += 1
+ }
+
+ // truncate array to the correct length
+ if (arr.length == i) arr else arr.slice(0, i)
+ }
+ }
+
+ override def genCode(
+ ctx: CodegenContext,
+ start: String,
+ stop: String,
+ step: String,
+ arr: String,
+ elemType: String): String = {
+ val stepMonths = ctx.freshName("stepMonths")
+ val stepMicros = ctx.freshName("stepMicros")
+ val stepScaled = ctx.freshName("stepScaled")
+ val intervalInMicros = ctx.freshName("intervalInMicros")
+ val startMicros = ctx.freshName("startMicros")
+ val stopMicros = ctx.freshName("stopMicros")
+ val arrLength = ctx.freshName("arrLength")
+ val stepSign = ctx.freshName("stepSign")
+ val exclusiveItem = ctx.freshName("exclusiveItem")
+ val t = ctx.freshName("t")
+ val i = ctx.freshName("i")
+ val genTimeZone = ctx.addReferenceObj("timeZone", timeZone, classOf[TimeZone].getName)
+
+ val sequenceLengthCode =
+ s"""
+ |final long $intervalInMicros = $stepMicros + $stepMonths * ${microsPerMonth}L;
+ |${genSequenceLengthCode(ctx, startMicros, stopMicros, intervalInMicros, arrLength)}
+ """.stripMargin
+
+ val timestampAddIntervalCode =
+ s"""
+ |$t = org.apache.spark.sql.catalyst.util.DateTimeUtils.timestampAddInterval(
+ | $t, $stepMonths, $stepMicros, $genTimeZone);
+ """.stripMargin
+
+ s"""
+ |final int $stepMonths = $step.months;
+ |final long $stepMicros = $step.microseconds;
+ |
+ |if ($stepMonths == 0) {
+ | final $elemType $stepScaled = ($elemType) ($stepMicros / ${scale}L);
+ | ${backedSequenceImpl.genCode(ctx, start, stop, stepScaled, arr, elemType)};
+ |
+ |} else {
+ | final long $startMicros = $start * ${scale}L;
+ | final long $stopMicros = $stop * ${scale}L;
+ |
+ | $sequenceLengthCode
+ |
+ | final int $stepSign = $stopMicros > $startMicros ? +1 : -1;
+ | final long $exclusiveItem = $stopMicros + $stepSign;
+ |
+ | $arr = new $elemType[$arrLength];
+ | long $t = $startMicros;
+ | int $i = 0;
+ |
+ | while ($t < $exclusiveItem ^ $stepSign < 0) {
+ | $arr[$i] = ($elemType) ($t / ${scale}L);
+ | $timestampAddIntervalCode
+ | $i += 1;
+ | }
+ |
+ | if ($arr.length > $i) {
+ | $arr = java.util.Arrays.copyOf($arr, $i);
+ | }
+ |}
+ """.stripMargin
+ }
+ }
+
+ private def getSequenceLength[U](start: U, stop: U, step: U)(implicit num: Integral[U]): Int = {
+ import num._
+ require(
+ (step > num.zero && start <= stop)
+ || (step < num.zero && start >= stop)
+ || (step == 0 && start == stop),
--- End diff --
`num.zero` instead of `0`?
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by ueshin <gi...@git.apache.org>.
Github user ueshin commented on a diff in the pull request:
https://github.com/apache/spark/pull/21155#discussion_r193928034
--- Diff: sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/CollectionExpressionsSuite.scala ---
@@ -308,6 +313,292 @@ class CollectionExpressionsSuite extends SparkFunSuite with ExpressionEvalHelper
ArrayMax(Literal.create(Seq(1.123, 0.1234, 1.121), ArrayType(DoubleType))), 1.123)
}
+ test("Sequence") {
--- End diff --
Maybe we need additional words in the test title?
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: SPARK-23927: Add "sequence" expression
Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:
https://github.com/apache/spark/pull/21155
**[Test build #89851 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/89851/testReport)** for PR 21155 at commit [`8fb427c`](https://github.com/apache/spark/commit/8fb427c72d719b37a2c36caccd9309bc200cd29c).
* This patch **fails Scala style tests**.
* This patch merges cleanly.
* This patch adds the following public classes _(experimental)_:
* `case class UnresolvedLiteral(child: Expression, literalResolver: DataType => Literal)`
* ` trait SequenceImpl `
* `case class Sequence(left: Expression,`
* ` class IntegralSequenceImpl[T: ClassTag](implicit num: Integral[T]) extends SequenceImpl `
* ` abstract class TemporalSequence[T: ClassTag](dt: IntegralType, scale: Long, fromLong: Long => T)`
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request #21155: SPARK-23927: Add "sequence" expression
Posted by ueshin <gi...@git.apache.org>.
Github user ueshin commented on a diff in the pull request:
https://github.com/apache/spark/pull/21155#discussion_r186036247
--- Diff: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/collectionOperations.scala ---
@@ -1059,3 +1063,316 @@ case class Flatten(child: Expression) extends UnaryExpression {
override def prettyName: String = "flatten"
}
+
+@ExpressionDescription(
+ usage = """
+ _FUNC_(start, stop, step) -
+ Generates an array of elements from start to stop (inclusive), incrementing by step.
+ The type of the returned elements is the same as the type of argument expressions.
+
+ Supported types are: byte, short, integer, long, date, timestamp.
+
+ The start and stop expressions must resolve to the same type.
+ If start and stop expressions resolve to the 'date' or 'timestamp' type
+ then the step expression must resolve to the 'interval' type, otherwise to the same type
+ as the start and stop expressions.
+ """,
+ arguments = """
+ Arguments:
+ * start - an expression. The start of the range.
+ * stop - an expression. The end the range (inclusive).
+ * step - an optional expression. The step of the range.
+
+ By default step is 1 if start is less than or equal to stop, otherwise -1.
+ For the temporal sequences it's 1 day and -1 day respectively.
+
+ If start is greater than stop then the step must be negative, and vice versa.
+ """,
+ examples = """
+ Examples:
+ > SELECT _FUNC_(1, 5);
+ [1, 2, 3, 4, 5]
+ > SELECT _FUNC_(5, 1);
+ [5, 4, 3, 2, 1]
+ > SELECT _FUNC_(to_date('2018-01-01'), to_date('2018-03-01'), interval 1 month);
+ [2018-01-01, 2018-02-01, 2018-03-01]
+ """,
+ since = "2.4.0"
+)
+case class Sequence(left: Expression,
+ middle: Expression,
+ right: Expression,
+ timeZoneId: Option[String] = None)
+ extends TernaryExpression with TimeZoneAwareExpression {
+
+ import Sequence._
+
+ def this(arg0: Expression, arg1: Expression) =
+ this(arg0, arg1, Sequence.defaultStepExpression(arg0, arg1), None)
+
+ def this(arg0: Expression, arg1: Expression, arg2: Expression) =
+ this(arg0, arg1, arg2, None)
+
+ override def withTimeZone(timeZoneId: String): TimeZoneAwareExpression =
+ copy(timeZoneId = Some(timeZoneId))
+
+ override def children: Seq[Expression] = Seq(left, middle, right)
+
+ override lazy val dataType: ArrayType = ArrayType(left.dataType, containsNull = false)
+
+ override def checkInputDataTypes(): TypeCheckResult = {
+ val Seq(startType, stopType, stepType) = children.map(_.dataType)
+ val typesCorrect =
+ startType.sameType(stopType) &&
+ (startType match {
+ case TimestampType | DateType => CalendarIntervalType acceptsType stepType
+ case _: IntegralType => stepType sameType startType
+ case _ => false
+ })
+
+ if (typesCorrect) {
+ TypeCheckResult.TypeCheckSuccess
+ } else {
+ TypeCheckResult.TypeCheckFailure(
+ s"$prettyName only supports integral, timestamp or date types")
+ }
+ }
+
+ private lazy val impl: SequenceImpl = dataType.elementType match {
+ case iType: IntegralType =>
+ type T = iType.InternalType
+ val ct = ClassTag[T](iType.tag.mirror.runtimeClass(iType.tag.tpe))
+ new IntegralSequenceImpl()(ct, iType.integral)
+
+ case TimestampType =>
+ new TemporalSequenceImpl[Long](LongType, 1, identity, timeZone)
+
+ case DateType =>
+ new TemporalSequenceImpl[Int](IntegerType, MICROS_PER_DAY, _.toInt, timeZone)
+ }
+
+ override protected def nullSafeEval(input1: Any, input2: Any, input3: Any): Any = {
+ ArrayData.toArrayData(impl.eval(input1, input2, input3))
+ }
+
+ override protected def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = {
+ nullSafeCodeGen(ctx, ev, (start, stop, step) => {
+ val arr = ctx.freshName("arr")
+ val arrElemType = CodeGenerator.javaType(dataType.elementType)
+ s"""
+ | final $arrElemType[] $arr = null;
--- End diff --
nit: we usually don't add a space between | and the following sentence if the indent is not needed.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:
https://github.com/apache/spark/pull/21155
Test FAILed.
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/91617/
Test FAILed.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request #21155: SPARK-23927: Add "sequence" expression
Posted by ueshin <gi...@git.apache.org>.
Github user ueshin commented on a diff in the pull request:
https://github.com/apache/spark/pull/21155#discussion_r186036365
--- Diff: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/collectionOperations.scala ---
@@ -1059,3 +1063,316 @@ case class Flatten(child: Expression) extends UnaryExpression {
override def prettyName: String = "flatten"
}
+
+@ExpressionDescription(
+ usage = """
+ _FUNC_(start, stop, step) -
+ Generates an array of elements from start to stop (inclusive), incrementing by step.
+ The type of the returned elements is the same as the type of argument expressions.
+
+ Supported types are: byte, short, integer, long, date, timestamp.
+
+ The start and stop expressions must resolve to the same type.
+ If start and stop expressions resolve to the 'date' or 'timestamp' type
+ then the step expression must resolve to the 'interval' type, otherwise to the same type
+ as the start and stop expressions.
+ """,
+ arguments = """
+ Arguments:
+ * start - an expression. The start of the range.
+ * stop - an expression. The end the range (inclusive).
+ * step - an optional expression. The step of the range.
+
+ By default step is 1 if start is less than or equal to stop, otherwise -1.
+ For the temporal sequences it's 1 day and -1 day respectively.
+
+ If start is greater than stop then the step must be negative, and vice versa.
+ """,
+ examples = """
+ Examples:
+ > SELECT _FUNC_(1, 5);
+ [1, 2, 3, 4, 5]
+ > SELECT _FUNC_(5, 1);
+ [5, 4, 3, 2, 1]
+ > SELECT _FUNC_(to_date('2018-01-01'), to_date('2018-03-01'), interval 1 month);
+ [2018-01-01, 2018-02-01, 2018-03-01]
+ """,
+ since = "2.4.0"
+)
+case class Sequence(left: Expression,
+ middle: Expression,
+ right: Expression,
+ timeZoneId: Option[String] = None)
+ extends TernaryExpression with TimeZoneAwareExpression {
+
+ import Sequence._
+
+ def this(arg0: Expression, arg1: Expression) =
+ this(arg0, arg1, Sequence.defaultStepExpression(arg0, arg1), None)
+
+ def this(arg0: Expression, arg1: Expression, arg2: Expression) =
+ this(arg0, arg1, arg2, None)
+
+ override def withTimeZone(timeZoneId: String): TimeZoneAwareExpression =
+ copy(timeZoneId = Some(timeZoneId))
+
+ override def children: Seq[Expression] = Seq(left, middle, right)
+
+ override lazy val dataType: ArrayType = ArrayType(left.dataType, containsNull = false)
+
+ override def checkInputDataTypes(): TypeCheckResult = {
+ val Seq(startType, stopType, stepType) = children.map(_.dataType)
+ val typesCorrect =
+ startType.sameType(stopType) &&
+ (startType match {
+ case TimestampType | DateType => CalendarIntervalType acceptsType stepType
+ case _: IntegralType => stepType sameType startType
+ case _ => false
+ })
+
+ if (typesCorrect) {
+ TypeCheckResult.TypeCheckSuccess
+ } else {
+ TypeCheckResult.TypeCheckFailure(
+ s"$prettyName only supports integral, timestamp or date types")
+ }
+ }
+
+ private lazy val impl: SequenceImpl = dataType.elementType match {
+ case iType: IntegralType =>
+ type T = iType.InternalType
+ val ct = ClassTag[T](iType.tag.mirror.runtimeClass(iType.tag.tpe))
+ new IntegralSequenceImpl()(ct, iType.integral)
+
+ case TimestampType =>
+ new TemporalSequenceImpl[Long](LongType, 1, identity, timeZone)
+
+ case DateType =>
+ new TemporalSequenceImpl[Int](IntegerType, MICROS_PER_DAY, _.toInt, timeZone)
+ }
+
+ override protected def nullSafeEval(input1: Any, input2: Any, input3: Any): Any = {
+ ArrayData.toArrayData(impl.eval(input1, input2, input3))
+ }
+
+ override protected def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = {
+ nullSafeCodeGen(ctx, ev, (start, stop, step) => {
+ val arr = ctx.freshName("arr")
+ val arrElemType = CodeGenerator.javaType(dataType.elementType)
+ s"""
+ | final $arrElemType[] $arr = null;
+ | ${impl.genCode(start, stop, step)(arr, arrElemType)(ctx)}
+ | ${ev.value} = UnsafeArrayData.fromPrimitiveArray($arr);
+ """.stripMargin
+ })
+ }
+}
+
+object Sequence {
+
+ private trait SequenceImpl {
+ def eval(input1: Any, input2: Any, input3: Any): Any
--- End diff --
`start`, `stop`, `step`?
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:
https://github.com/apache/spark/pull/21155
Merged build finished. Test PASSed.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:
https://github.com/apache/spark/pull/21155
**[Test build #92217 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/92217/testReport)** for PR 21155 at commit [`c54857a`](https://github.com/apache/spark/commit/c54857a9cc9cdb64639913bc539975e2b507af28).
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request #21155: SPARK-23927: Add "sequence" expression
Posted by ueshin <gi...@git.apache.org>.
Github user ueshin commented on a diff in the pull request:
https://github.com/apache/spark/pull/21155#discussion_r186037997
--- Diff: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/collectionOperations.scala ---
@@ -1059,3 +1063,316 @@ case class Flatten(child: Expression) extends UnaryExpression {
override def prettyName: String = "flatten"
}
+
+@ExpressionDescription(
+ usage = """
+ _FUNC_(start, stop, step) -
+ Generates an array of elements from start to stop (inclusive), incrementing by step.
+ The type of the returned elements is the same as the type of argument expressions.
+
+ Supported types are: byte, short, integer, long, date, timestamp.
+
+ The start and stop expressions must resolve to the same type.
+ If start and stop expressions resolve to the 'date' or 'timestamp' type
+ then the step expression must resolve to the 'interval' type, otherwise to the same type
+ as the start and stop expressions.
+ """,
+ arguments = """
+ Arguments:
+ * start - an expression. The start of the range.
+ * stop - an expression. The end the range (inclusive).
+ * step - an optional expression. The step of the range.
+
+ By default step is 1 if start is less than or equal to stop, otherwise -1.
+ For the temporal sequences it's 1 day and -1 day respectively.
+
+ If start is greater than stop then the step must be negative, and vice versa.
+ """,
+ examples = """
+ Examples:
+ > SELECT _FUNC_(1, 5);
+ [1, 2, 3, 4, 5]
+ > SELECT _FUNC_(5, 1);
+ [5, 4, 3, 2, 1]
+ > SELECT _FUNC_(to_date('2018-01-01'), to_date('2018-03-01'), interval 1 month);
+ [2018-01-01, 2018-02-01, 2018-03-01]
+ """,
+ since = "2.4.0"
+)
+case class Sequence(left: Expression,
+ middle: Expression,
+ right: Expression,
+ timeZoneId: Option[String] = None)
+ extends TernaryExpression with TimeZoneAwareExpression {
+
+ import Sequence._
+
+ def this(arg0: Expression, arg1: Expression) =
+ this(arg0, arg1, Sequence.defaultStepExpression(arg0, arg1), None)
+
+ def this(arg0: Expression, arg1: Expression, arg2: Expression) =
+ this(arg0, arg1, arg2, None)
+
+ override def withTimeZone(timeZoneId: String): TimeZoneAwareExpression =
+ copy(timeZoneId = Some(timeZoneId))
+
+ override def children: Seq[Expression] = Seq(left, middle, right)
+
+ override lazy val dataType: ArrayType = ArrayType(left.dataType, containsNull = false)
+
+ override def checkInputDataTypes(): TypeCheckResult = {
+ val Seq(startType, stopType, stepType) = children.map(_.dataType)
+ val typesCorrect =
+ startType.sameType(stopType) &&
+ (startType match {
+ case TimestampType | DateType => CalendarIntervalType acceptsType stepType
+ case _: IntegralType => stepType sameType startType
+ case _ => false
+ })
+
+ if (typesCorrect) {
+ TypeCheckResult.TypeCheckSuccess
+ } else {
+ TypeCheckResult.TypeCheckFailure(
+ s"$prettyName only supports integral, timestamp or date types")
+ }
+ }
+
+ private lazy val impl: SequenceImpl = dataType.elementType match {
+ case iType: IntegralType =>
+ type T = iType.InternalType
+ val ct = ClassTag[T](iType.tag.mirror.runtimeClass(iType.tag.tpe))
+ new IntegralSequenceImpl()(ct, iType.integral)
+
+ case TimestampType =>
+ new TemporalSequenceImpl[Long](LongType, 1, identity, timeZone)
+
+ case DateType =>
+ new TemporalSequenceImpl[Int](IntegerType, MICROS_PER_DAY, _.toInt, timeZone)
+ }
+
+ override protected def nullSafeEval(input1: Any, input2: Any, input3: Any): Any = {
+ ArrayData.toArrayData(impl.eval(input1, input2, input3))
+ }
+
+ override protected def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = {
+ nullSafeCodeGen(ctx, ev, (start, stop, step) => {
+ val arr = ctx.freshName("arr")
+ val arrElemType = CodeGenerator.javaType(dataType.elementType)
+ s"""
+ | final $arrElemType[] $arr = null;
+ | ${impl.genCode(start, stop, step)(arr, arrElemType)(ctx)}
+ | ${ev.value} = UnsafeArrayData.fromPrimitiveArray($arr);
+ """.stripMargin
+ })
+ }
+}
+
+object Sequence {
+
+ private trait SequenceImpl {
+ def eval(input1: Any, input2: Any, input3: Any): Any
+
+ def genCode(start: String, stop: String, step: String)
+ (arr: String, elemType: String)
+ (implicit ctx: CodegenContext): String
+ }
+
+ private class IntegralSequenceImpl[T: ClassTag]
+ (implicit num: Integral[T]) extends SequenceImpl {
+
+ override def eval(input1: Any, input2: Any, input3: Any): Array[T] = {
+ import num._
+
+ val start = input1.asInstanceOf[T]
+ val stop = input2.asInstanceOf[T]
+ val step = input3.asInstanceOf[T]
+
+ var i: Int = getSequenceLength(start, stop, step)
+ val arr = new Array[T](i)
+ while (i > 0) {
+ i -= 1
+ arr(i) = start + step * num.fromInt(i)
+ }
+ arr
+ }
+
+ override def genCode(start: String, stop: String, step: String)
+ (arr: String, elemType: String)
+ (implicit ctx: CodegenContext): String = {
+ val i = ctx.freshName("i")
+ s"""
+ | ${genSequenceLengthCode(start, stop, step)(i)}
+ | $arr = new $elemType[$i];
+ | while ($i > 0) {
+ | $i--;
+ | $arr[$i] = ($elemType) ($start + $step * $i);
+ | }
+ """.stripMargin
--- End diff --
nit: indent
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request #21155: SPARK-23927: Add "sequence" expression
Posted by ueshin <gi...@git.apache.org>.
Github user ueshin commented on a diff in the pull request:
https://github.com/apache/spark/pull/21155#discussion_r186029578
--- Diff: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/collectionOperations.scala ---
@@ -1059,3 +1063,316 @@ case class Flatten(child: Expression) extends UnaryExpression {
override def prettyName: String = "flatten"
}
+
+@ExpressionDescription(
+ usage = """
+ _FUNC_(start, stop, step) -
+ Generates an array of elements from start to stop (inclusive), incrementing by step.
+ The type of the returned elements is the same as the type of argument expressions.
+
+ Supported types are: byte, short, integer, long, date, timestamp.
+
+ The start and stop expressions must resolve to the same type.
+ If start and stop expressions resolve to the 'date' or 'timestamp' type
+ then the step expression must resolve to the 'interval' type, otherwise to the same type
+ as the start and stop expressions.
+ """,
+ arguments = """
+ Arguments:
+ * start - an expression. The start of the range.
+ * stop - an expression. The end the range (inclusive).
+ * step - an optional expression. The step of the range.
+
+ By default step is 1 if start is less than or equal to stop, otherwise -1.
+ For the temporal sequences it's 1 day and -1 day respectively.
+
+ If start is greater than stop then the step must be negative, and vice versa.
+ """,
+ examples = """
+ Examples:
+ > SELECT _FUNC_(1, 5);
+ [1, 2, 3, 4, 5]
+ > SELECT _FUNC_(5, 1);
+ [5, 4, 3, 2, 1]
+ > SELECT _FUNC_(to_date('2018-01-01'), to_date('2018-03-01'), interval 1 month);
+ [2018-01-01, 2018-02-01, 2018-03-01]
+ """,
+ since = "2.4.0"
+)
+case class Sequence(left: Expression,
+ middle: Expression,
+ right: Expression,
+ timeZoneId: Option[String] = None)
+ extends TernaryExpression with TimeZoneAwareExpression {
+
+ import Sequence._
+
+ def this(arg0: Expression, arg1: Expression) =
+ this(arg0, arg1, Sequence.defaultStepExpression(arg0, arg1), None)
+
+ def this(arg0: Expression, arg1: Expression, arg2: Expression) =
--- End diff --
`start`, `stop`, `step`?
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request #21155: SPARK-23927: Add "sequence" expression
Posted by wajda <gi...@git.apache.org>.
Github user wajda commented on a diff in the pull request:
https://github.com/apache/spark/pull/21155#discussion_r184130293
--- Diff: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/collectionOperations.scala ---
@@ -1059,3 +1063,282 @@ case class Flatten(child: Expression) extends UnaryExpression {
override def prettyName: String = "flatten"
}
+
+object Sequence {
+ private def defaultStepLiteralForType(dt: DataType) = dt match {
+ case DateType | TimestampType => Literal(new CalendarInterval(0, MICROS_PER_DAY))
+ case dt: NumericType => Literal(dt.numeric.one)
+ }
+
+ private def defaultStepExpression(start: Expression, stop: Expression): Expression = {
+ val one =
+ if (start.resolved) {
+ defaultStepLiteralForType(start.dataType)
+ } else {
+ UnresolvedLiteral(start, defaultStepLiteralForType)
+ }
+ CaseWhen(
+ Seq((LessThanOrEqual(start, stop), one)),
+ UnaryMinus(one))
+ }
+
+ def getSequenceLength[U](start: U, stop: U, step: U)(implicit num: Integral[U]): Int = {
+ import num._
+ require(
+ step > num.zero && start <= stop
+ || step < num.zero && start >= stop
+ || step == 0 && start == stop,
+ s"Illegal sequence boundaries: $start to $stop by $step")
+
+ val len = if (start == stop) 1L else 1L + (stop.toLong - start.toLong) / step.toLong
+
+ require(len <= Int.MaxValue, s"Too long sequence: $len. Should be <= ${Int.MaxValue}")
+
+ len.toInt
+ }
+
+ def genSequenceLengthCode(start: String, stop: String, step: String)
+ (len: String)
+ (implicit ctx: CodegenContext): String = {
+ val longLen = ctx.freshName("longLen")
+ s"""
+ | if (!($step > 0 && $start <= $stop ||
+ | $step < 0 && $start >= $stop ||
+ | $step == 0 && $start == $stop)) {
+ | throw new IllegalArgumentException(
+ | "Illegal sequence boundaries: " + $start + " to " + $stop + " by " + $step);
+ | }
+ | long $longLen = $stop == $start ? 1L : 1L + ((long) $stop - $start) / $step;
+ | if ($longLen > Integer.MAX_VALUE) {
+ | throw new IllegalArgumentException(
+ | "Too long sequence: " + $longLen + ". Should be <= ${Int.MaxValue}");
+ | }
+ | int $len = (int) $longLen;
+ """.stripMargin
+ }
+
+ trait SequenceImpl {
+ def eval(input1: Any, input2: Any, input3: Any): Any
+ def genCode(start: String, stop: String, step: String)
+ (arr: String, elemType: String)
+ (implicit ctx: CodegenContext): String
+ }
+}
+
+case class Sequence(left: Expression,
+ middle: Expression,
+ right: Expression,
+ timeZoneId: Option[String] = None)
+ extends TernaryExpression with TimeZoneAwareExpression {
+
+ import Sequence._
+
+ class IntegralSequenceImpl[T: ClassTag](implicit num: Integral[T]) extends SequenceImpl {
+
+ override def eval(input1: Any, input2: Any, input3: Any): Array[T] = {
+ import num._
+
+ val start = input1.asInstanceOf[T]
+ val stop = input2.asInstanceOf[T]
+ val step = input3.asInstanceOf[T]
+
+ var i: Int = getSequenceLength(start, stop, step)
+ val arr = new Array[T](i)
+ while (i > 0) {
+ i -= 1
+ arr(i) = start + step * num.fromInt(i)
+ }
+ arr
+ }
+
+ override def genCode(start: String, stop: String, step: String)
+ (arr: String, elemType: String)
+ (implicit ctx: CodegenContext): String = {
+ val i = ctx.freshName("i")
+ s"""
+ | ${genSequenceLengthCode(start, stop, step)(i)}
+ | $arr = new $elemType[$i];
+ | while ($i > 0) {
+ | $i--;
+ | $arr[$i] = ($elemType) ($start + $step * $i);
+ | }
+ """.stripMargin
+ }
+ }
+
+ abstract class TemporalSequence[T: ClassTag](dt: IntegralType, scale: Long, fromLong: Long => T)
+ (implicit num: Integral[T])
+ extends SequenceImpl {
+
+ private val backedSequenceImpl = new IntegralSequenceImpl[T]
+ private val microsPerMonth = 28 * CalendarInterval.MICROS_PER_DAY
+
+ override def eval(input1: Any, input2: Any, input3: Any): Array[T] = {
+ val start = input1.asInstanceOf[T]
+ val stop = input2.asInstanceOf[T]
+ val step = input3.asInstanceOf[CalendarInterval]
+ val stepMonths = step.months
+ val stepMicros = step.microseconds
+
+ if (stepMonths == 0) {
+ backedSequenceImpl.eval(start, stop, fromLong(stepMicros / scale))
+
+ } else {
+ // To estimate the resulted array length we need to make assumptions
+ // about a month length in microseconds
+ val minIntervalLengthInMicros = Math.abs(stepMicros) + stepMonths * microsPerMonth
+ val startMicros: Long = num.toLong(start) * scale
+ val stopMicros: Long = num.toLong(stop) * scale
+ val maxEstimatedArrayLength =
+ getSequenceLength(startMicros, stopMicros, minIntervalLengthInMicros)
+
+ val stepSign = if (stopMicros > startMicros) +1 else -1
+ val exclusiveItem = stopMicros + stepSign
+ val arr = new Array[T](maxEstimatedArrayLength)
+ var t = startMicros
+ var i = 0
+
+ while (t < exclusiveItem ^ stepSign < 0) {
+ arr(i) = fromLong(t / scale)
+ t = timestampAddInterval(t, stepMonths, stepMicros, timeZone)
+ i += 1
+ }
+
+ // truncate array to the correct length
+ if (arr.length == i) {
+ arr
+ } else {
+ arr.slice(0, i)
+ }
+ }
+ }
+
+ override def genCode(start: String, stop: String, step: String)
+ (arr: String, elemType: String)
+ (implicit ctx: CodegenContext): String = {
+ val stepMonths = ctx.freshName("stepMonths")
+ val stepMicros = ctx.freshName("stepMicros")
+
+ lazy val stepScaled = ctx.freshName("stepScaled")
--- End diff --
No reason. It's a left over, sorry.
Fixed.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by viirya <gi...@git.apache.org>.
Github user viirya commented on a diff in the pull request:
https://github.com/apache/spark/pull/21155#discussion_r187289346
--- Diff: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/collectionOperations.scala ---
@@ -1468,3 +1472,388 @@ case class Flatten(child: Expression) extends UnaryExpression {
override def prettyName: String = "flatten"
}
+
+@ExpressionDescription(
+ usage = """
+ _FUNC_(start, stop, step) - Generates an array of elements from start to stop (inclusive),
+ incrementing by step. The type of the returned elements is the same as the type of argument
+ expressions.
+
+ Supported types are: byte, short, integer, long, date, timestamp.
+
+ The start and stop expressions must resolve to the same type.
+ If start and stop expressions resolve to the 'date' or 'timestamp' type
+ then the step expression must resolve to the 'interval' type, otherwise to the same type
+ as the start and stop expressions.
+ """,
+ arguments = """
+ Arguments:
+ * start - an expression. The start of the range.
+ * stop - an expression. The end the range (inclusive).
+ * step - an optional expression. The step of the range.
+ By default step is 1 if start is less than or equal to stop, otherwise -1.
+ For the temporal sequences it's 1 day and -1 day respectively.
+ If start is greater than stop then the step must be negative, and vice versa.
+ """,
+ examples = """
+ Examples:
+ > SELECT _FUNC_(1, 5);
+ [1, 2, 3, 4, 5]
+ > SELECT _FUNC_(5, 1);
+ [5, 4, 3, 2, 1]
+ > SELECT _FUNC_(to_date('2018-01-01'), to_date('2018-03-01'), interval 1 month);
+ [2018-01-01, 2018-02-01, 2018-03-01]
+ """,
+ since = "2.4.0"
+)
+case class Sequence(
+ start: Expression,
+ stop: Expression,
+ stepOpt: Option[Expression],
+ timeZoneId: Option[String] = None)
+ extends Expression
+ with ExpectsInputTypes
+ with TimeZoneAwareExpression {
+
+ import Sequence._
+
+ def this(start: Expression, stop: Expression) =
+ this(start, stop, None, None)
+
+ def this(start: Expression, stop: Expression, step: Expression) =
+ this(start, stop, Some(step), None)
+
+ override def withTimeZone(timeZoneId: String): TimeZoneAwareExpression =
+ copy(timeZoneId = Some(timeZoneId))
+
+ override def children: Seq[Expression] = Seq(start, stop) ++ stepOpt
+
+ override def foldable: Boolean = children.forall(_.foldable)
+
+ override def nullable: Boolean = children.exists(_.nullable)
+
+ override lazy val dataType: ArrayType = ArrayType(start.dataType, containsNull = false)
+
+ override def inputTypes: Seq[AbstractDataType] = {
+ val elemType = dataType.elementType
+ Seq(elemType, elemType) ++
+ stepOpt.map(_ => elemType match {
+ case DateType | TimestampType => CalendarIntervalType
+ case _: IntegralType => elemType
--- End diff --
Seems there are no test cases with invalid data types.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:
https://github.com/apache/spark/pull/21155
**[Test build #90909 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/90909/testReport)** for PR 21155 at commit [`2ccb9bb`](https://github.com/apache/spark/commit/2ccb9bb73f729c361ee819316e9c95224797a178).
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by asfgit <gi...@git.apache.org>.
Github user asfgit closed the pull request at:
https://github.com/apache/spark/pull/21155
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by wajda <gi...@git.apache.org>.
Github user wajda commented on a diff in the pull request:
https://github.com/apache/spark/pull/21155#discussion_r197496187
--- Diff: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/collectionOperations.scala ---
@@ -1887,6 +1889,402 @@ case class Flatten(child: Expression) extends UnaryExpression {
override def prettyName: String = "flatten"
}
+@ExpressionDescription(
+ usage = """
+ _FUNC_(start, stop, step) - Generates an array of elements from start to stop (inclusive),
+ incrementing by step. The type of the returned elements is the same as the type of argument
+ expressions.
+
+ Supported types are: byte, short, integer, long, date, timestamp.
+
+ The start and stop expressions must resolve to the same type.
+ If start and stop expressions resolve to the 'date' or 'timestamp' type
+ then the step expression must resolve to the 'interval' type, otherwise to the same type
+ as the start and stop expressions.
+ """,
+ arguments = """
+ Arguments:
+ * start - an expression. The start of the range.
+ * stop - an expression. The end the range (inclusive).
+ * step - an optional expression. The step of the range.
+ By default step is 1 if start is less than or equal to stop, otherwise -1.
+ For the temporal sequences it's 1 day and -1 day respectively.
+ If start is greater than stop then the step must be negative, and vice versa.
+ """,
+ examples = """
+ Examples:
+ > SELECT _FUNC_(1, 5);
+ [1, 2, 3, 4, 5]
+ > SELECT _FUNC_(5, 1);
+ [5, 4, 3, 2, 1]
+ > SELECT _FUNC_(to_date('2018-01-01'), to_date('2018-03-01'), interval 1 month);
+ [2018-01-01, 2018-02-01, 2018-03-01]
+ """,
+ since = "2.4.0"
+)
+case class Sequence(
+ start: Expression,
+ stop: Expression,
+ stepOpt: Option[Expression],
+ timeZoneId: Option[String] = None)
+ extends Expression
+ with TimeZoneAwareExpression {
+
+ import Sequence._
+
+ def this(start: Expression, stop: Expression) =
+ this(start, stop, None, None)
+
+ def this(start: Expression, stop: Expression, step: Expression) =
+ this(start, stop, Some(step), None)
+
+ override def withTimeZone(timeZoneId: String): TimeZoneAwareExpression =
+ copy(timeZoneId = Some(timeZoneId))
+
+ override def children: Seq[Expression] = Seq(start, stop) ++ stepOpt
+
+ override def foldable: Boolean = children.forall(_.foldable)
+
+ override def nullable: Boolean = children.exists(_.nullable)
+
+ override lazy val dataType: ArrayType = ArrayType(start.dataType, containsNull = false)
+
+ override def checkInputDataTypes(): TypeCheckResult = {
+ val startType = start.dataType
+ def stepType = stepOpt.get.dataType
+ val typesCorrect =
+ startType.sameType(stop.dataType) &&
+ (startType match {
+ case TimestampType | DateType =>
+ stepOpt.isEmpty || CalendarIntervalType.acceptsType(stepType)
+ case _: IntegralType =>
+ stepOpt.isEmpty || stepType.sameType(startType)
+ case _ => false
+ })
+
+ if (typesCorrect) {
+ TypeCheckResult.TypeCheckSuccess
+ } else {
+ TypeCheckResult.TypeCheckFailure(
+ s"$prettyName only supports integral, timestamp or date types")
+ }
+ }
+
+ def coercibleChildren: Seq[Expression] = children.filter(_.dataType != CalendarIntervalType)
+
+ def castChildrenTo(widerType: DataType): Expression = Sequence(
+ Cast(start, widerType),
+ Cast(stop, widerType),
+ stepOpt.map(step => if (step.dataType != CalendarIntervalType) Cast(step, widerType) else step),
+ timeZoneId)
+
+ private lazy val impl: SequenceImpl = dataType.elementType match {
+ case iType: IntegralType =>
+ type T = iType.InternalType
+ val ct = ClassTag[T](iType.tag.mirror.runtimeClass(iType.tag.tpe))
+ new IntegralSequenceImpl(iType)(ct, iType.integral)
+
+ case TimestampType =>
+ new TemporalSequenceImpl[Long](LongType, 1, identity, timeZone)
+
+ case DateType =>
+ new TemporalSequenceImpl[Int](IntegerType, MICROS_PER_DAY, _.toInt, timeZone)
+ }
+
+ override def eval(input: InternalRow): Any = {
+ val startVal = start.eval(input)
+ if (startVal == null) return null
+ val stopVal = stop.eval(input)
+ if (stopVal == null) return null
+ val stepVal = stepOpt.map(_.eval(input)).getOrElse(impl.defaultStep(startVal, stopVal))
+ if (stepVal == null) return null
+
+ ArrayData.toArrayData(impl.eval(startVal, stopVal, stepVal))
+ }
+
+ override protected def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = {
+ val startGen = start.genCode(ctx)
+ val stopGen = stop.genCode(ctx)
+ val stepGen = stepOpt.map(_.genCode(ctx)).getOrElse(
+ impl.defaultStep.genCode(ctx, startGen, stopGen))
+
+ val resultType = CodeGenerator.javaType(dataType)
+ val resultCode = {
+ val arr = ctx.freshName("arr")
+ val arrElemType = CodeGenerator.javaType(dataType.elementType)
+ s"""
+ |final $arrElemType[] $arr = null;
+ |${impl.genCode(ctx, startGen.value, stopGen.value, stepGen.value, arr, arrElemType)}
+ |${ev.value} = UnsafeArrayData.fromPrimitiveArray($arr);
+ """.stripMargin
+ }
+
+ if (nullable) {
+ val nullSafeEval =
+ startGen.code + ctx.nullSafeExec(start.nullable, startGen.isNull) {
+ stopGen.code + ctx.nullSafeExec(stop.nullable, stopGen.isNull) {
+ stepGen.code + ctx.nullSafeExec(stepOpt.exists(_.nullable), stepGen.isNull) {
+ s"""
+ |${ev.isNull} = false;
+ |$resultCode
+ """.stripMargin
+ }
+ }
+ }
+ ev.copy(code =
+ s"""
+ |boolean ${ev.isNull} = true;
+ |$resultType ${ev.value} = null;
+ |$nullSafeEval
+ """.stripMargin)
+
+ } else {
+ ev.copy(code =
+ s"""
+ |boolean ${ev.isNull} = false;
+ |${startGen.code}
+ |${stopGen.code}
+ |${stepGen.code}
+ |$resultType ${ev.value} = null;
+ |$resultCode
+ """.stripMargin,
+ isNull = FalseLiteral)
+ }
+ }
+}
+
+object Sequence {
+
+ private type LessThanOrEqualFn = (Any, Any) => Boolean
+
+ private class DefaultStep(lteq: LessThanOrEqualFn, stepType: DataType, one: Any) {
+ private val negativeOne = UnaryMinus(Literal(one)).eval()
+
+ def apply(start: Any, stop: Any): Any = {
+ if (lteq(start, stop)) one else negativeOne
+ }
+
+ def genCode(ctx: CodegenContext, startGen: ExprCode, stopGen: ExprCode): ExprCode = {
+ val Seq(oneVal, negativeOneVal) = Seq(one, negativeOne).map(Literal(_).genCode(ctx).value)
+ ExprCode.forNonNullValue(JavaCode.expression(
+ s"${startGen.value} <= ${stopGen.value} ? $oneVal : $negativeOneVal",
+ stepType))
+ }
+ }
+
+ private trait SequenceImpl {
+ def eval(start: Any, stop: Any, step: Any): Any
+
+ def genCode(
+ ctx: CodegenContext,
+ start: String,
+ stop: String,
+ step: String,
+ arr: String,
+ elemType: String): String
+
+ val defaultStep: DefaultStep
+ }
+
+ private class IntegralSequenceImpl[T: ClassTag]
+ (elemType: IntegralType)(implicit num: Integral[T]) extends SequenceImpl {
+
+ override val defaultStep: DefaultStep = new DefaultStep(
+ (elemType.ordering.lteq _).asInstanceOf[LessThanOrEqualFn],
+ elemType,
+ num.one)
+
+ override def eval(input1: Any, input2: Any, input3: Any): Array[T] = {
+ import num._
+
+ val start = input1.asInstanceOf[T]
+ val stop = input2.asInstanceOf[T]
+ val step = input3.asInstanceOf[T]
+
+ var i: Int = getSequenceLength(start, stop, step)
+ val arr = new Array[T](i)
+ while (i > 0) {
+ i -= 1
+ arr(i) = start + step * num.fromInt(i)
+ }
+ arr
+ }
+
+ override def genCode(
+ ctx: CodegenContext,
+ start: String,
+ stop: String,
+ step: String,
+ arr: String,
+ elemType: String): String = {
+ val i = ctx.freshName("i")
+ s"""
+ |${genSequenceLengthCode(ctx, start, stop, step, i)}
+ |$arr = new $elemType[$i];
+ |while ($i > 0) {
+ | $i--;
+ | $arr[$i] = ($elemType) ($start + $step * $i);
+ |}
+ """.stripMargin
+ }
+ }
+
+ private class TemporalSequenceImpl[T: ClassTag]
+ (dt: IntegralType, scale: Long, fromLong: Long => T, timeZone: TimeZone)
+ (implicit num: Integral[T]) extends SequenceImpl {
+
+ override val defaultStep: DefaultStep = new DefaultStep(
+ (dt.ordering.lteq _).asInstanceOf[LessThanOrEqualFn],
+ CalendarIntervalType,
+ new CalendarInterval(0, MICROS_PER_DAY))
+
+ private val backedSequenceImpl = new IntegralSequenceImpl[T](dt)
+ private val microsPerMonth = 28 * CalendarInterval.MICROS_PER_DAY
+
+ override def eval(input1: Any, input2: Any, input3: Any): Array[T] = {
+ val start = input1.asInstanceOf[T]
+ val stop = input2.asInstanceOf[T]
+ val step = input3.asInstanceOf[CalendarInterval]
+ val stepMonths = step.months
+ val stepMicros = step.microseconds
+
+ if (stepMonths == 0) {
+ backedSequenceImpl.eval(start, stop, fromLong(stepMicros / scale))
+
+ } else {
+ // To estimate the resulted array length we need to make assumptions
+ // about a month length in microseconds
+ val intervalStepInMicros = stepMicros + stepMonths * microsPerMonth
+ val startMicros: Long = num.toLong(start) * scale
+ val stopMicros: Long = num.toLong(stop) * scale
+ val maxEstimatedArrayLength =
+ getSequenceLength(startMicros, stopMicros, intervalStepInMicros)
+
+ val stepSign = if (stopMicros > startMicros) +1 else -1
+ val exclusiveItem = stopMicros + stepSign
+ val arr = new Array[T](maxEstimatedArrayLength)
+ var t = startMicros
+ var i = 0
+
+ while (t < exclusiveItem ^ stepSign < 0) {
+ arr(i) = fromLong(t / scale)
+ t = timestampAddInterval(t, stepMonths, stepMicros, timeZone)
+ i += 1
+ }
+
+ // truncate array to the correct length
+ if (arr.length == i) arr else arr.slice(0, i)
+ }
+ }
+
+ override def genCode(
+ ctx: CodegenContext,
+ start: String,
+ stop: String,
+ step: String,
+ arr: String,
+ elemType: String): String = {
+ val stepMonths = ctx.freshName("stepMonths")
+ val stepMicros = ctx.freshName("stepMicros")
+ val stepScaled = ctx.freshName("stepScaled")
+ val intervalInMicros = ctx.freshName("intervalInMicros")
+ val startMicros = ctx.freshName("startMicros")
+ val stopMicros = ctx.freshName("stopMicros")
+ val arrLength = ctx.freshName("arrLength")
+ val stepSign = ctx.freshName("stepSign")
+ val exclusiveItem = ctx.freshName("exclusiveItem")
+ val t = ctx.freshName("t")
+ val i = ctx.freshName("i")
+ val genTimeZone = ctx.freshName("timeZone")
+
+ val sequenceLengthCode =
+ s"""
+ |final long $intervalInMicros = $stepMicros + $stepMonths * ${microsPerMonth}L;
+ |${genSequenceLengthCode(ctx, startMicros, stopMicros, intervalInMicros, arrLength)}
+ """.stripMargin
+
+ val timestampAddIntervalCode =
+ s"""
+ |$t = org.apache.spark.sql.catalyst.util.DateTimeUtils.timestampAddInterval(
+ | $t, $stepMonths, $stepMicros, $genTimeZone);
+ """.stripMargin
+
+ s"""
+ |final int $stepMonths = $step.months;
+ |final long $stepMicros = $step.microseconds;
+ |
+ |if ($stepMonths == 0) {
+ | final $elemType $stepScaled = ($elemType) ($stepMicros / ${scale}L);
+ | ${backedSequenceImpl.genCode(ctx, start, stop, stepScaled, arr, elemType)};
+ |
+ |} else {
+ | final long $startMicros = $start * ${scale}L;
+ | final long $stopMicros = $stop * ${scale}L;
+ |
+ | $sequenceLengthCode
+ |
+ | final int $stepSign = $stopMicros > $startMicros ? +1 : -1;
+ | final long $exclusiveItem = $stopMicros + $stepSign;
+ | final java.util.TimeZone $genTimeZone =
+ | java.util.TimeZone.getTimeZone("${timeZone.getID}");
+ |
+ | $arr = new $elemType[$arrLength];
+ | long $t = $startMicros;
+ | int $i = 0;
+ |
+ | while ($t < $exclusiveItem ^ $stepSign < 0) {
+ | $arr[$i] = ($elemType) ($t / ${scale}L);
+ | $timestampAddIntervalCode
+ | $i += 1;
+ | }
+ |
+ | if ($arr.length > $i) {
+ | $arr = java.util.Arrays.copyOf($arr, $i);
+ | }
+ |}
+ """.stripMargin
+ }
+ }
+
+ private def getSequenceLength[U](start: U, stop: U, step: U)(implicit num: Integral[U]): Int = {
+ import num._
+ require(
+ step > num.zero && start <= stop
+ || step < num.zero && start >= stop
+ || step == 0 && start == stop,
+ s"Illegal sequence boundaries: $start to $stop by $step")
+
+ val len = if (start == stop) 1L else 1L + (stop.toLong - start.toLong) / step.toLong
+
+ require(len <= Int.MaxValue, s"Too long sequence: $len. Should be <= ${Int.MaxValue}")
+
+ len.toInt
+ }
+
+ private def genSequenceLengthCode(
+ ctx: CodegenContext,
+ start: String,
+ stop: String,
+ step: String,
+ len: String): String = {
+ val longLen = ctx.freshName("longLen")
+ s"""
+ |if (!($step > 0 && $start <= $stop||
+ | $step < 0 && $start >= $stop||
+ | $step == 0 && $start == $stop)) {
--- End diff --
done
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by ueshin <gi...@git.apache.org>.
Github user ueshin commented on a diff in the pull request:
https://github.com/apache/spark/pull/21155#discussion_r193895158
--- Diff: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/collectionOperations.scala ---
@@ -1468,3 +1472,388 @@ case class Flatten(child: Expression) extends UnaryExpression {
override def prettyName: String = "flatten"
}
+
+@ExpressionDescription(
+ usage = """
+ _FUNC_(start, stop, step) - Generates an array of elements from start to stop (inclusive),
+ incrementing by step. The type of the returned elements is the same as the type of argument
+ expressions.
+
+ Supported types are: byte, short, integer, long, date, timestamp.
+
+ The start and stop expressions must resolve to the same type.
+ If start and stop expressions resolve to the 'date' or 'timestamp' type
+ then the step expression must resolve to the 'interval' type, otherwise to the same type
+ as the start and stop expressions.
+ """,
+ arguments = """
+ Arguments:
+ * start - an expression. The start of the range.
+ * stop - an expression. The end the range (inclusive).
+ * step - an optional expression. The step of the range.
+ By default step is 1 if start is less than or equal to stop, otherwise -1.
+ For the temporal sequences it's 1 day and -1 day respectively.
+ If start is greater than stop then the step must be negative, and vice versa.
+ """,
+ examples = """
+ Examples:
+ > SELECT _FUNC_(1, 5);
+ [1, 2, 3, 4, 5]
+ > SELECT _FUNC_(5, 1);
+ [5, 4, 3, 2, 1]
+ > SELECT _FUNC_(to_date('2018-01-01'), to_date('2018-03-01'), interval 1 month);
+ [2018-01-01, 2018-02-01, 2018-03-01]
+ """,
+ since = "2.4.0"
+)
+case class Sequence(
+ start: Expression,
+ stop: Expression,
+ stepOpt: Option[Expression],
+ timeZoneId: Option[String] = None)
+ extends Expression
+ with ExpectsInputTypes
+ with TimeZoneAwareExpression {
+
+ import Sequence._
+
+ def this(start: Expression, stop: Expression) =
+ this(start, stop, None, None)
+
+ def this(start: Expression, stop: Expression, step: Expression) =
+ this(start, stop, Some(step), None)
+
+ override def withTimeZone(timeZoneId: String): TimeZoneAwareExpression =
+ copy(timeZoneId = Some(timeZoneId))
+
+ override def children: Seq[Expression] = Seq(start, stop) ++ stepOpt
+
+ override def foldable: Boolean = children.forall(_.foldable)
+
+ override def nullable: Boolean = children.exists(_.nullable)
+
+ override lazy val dataType: ArrayType = ArrayType(start.dataType, containsNull = false)
+
+ override def inputTypes: Seq[AbstractDataType] = {
+ val elemType = dataType.elementType
+ Seq(elemType, elemType) ++
+ stepOpt.map(_ => elemType match {
+ case DateType | TimestampType => CalendarIntervalType
+ case _: IntegralType => elemType
--- End diff --
I'm wondering what was wrong with `checkInputDataTypes`, but I can't see the difference because the commit was just overwritten.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by wajda <gi...@git.apache.org>.
Github user wajda commented on a diff in the pull request:
https://github.com/apache/spark/pull/21155#discussion_r197477593
--- Diff: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/collectionOperations.scala ---
@@ -1887,6 +1889,402 @@ case class Flatten(child: Expression) extends UnaryExpression {
override def prettyName: String = "flatten"
}
+@ExpressionDescription(
+ usage = """
+ _FUNC_(start, stop, step) - Generates an array of elements from start to stop (inclusive),
+ incrementing by step. The type of the returned elements is the same as the type of argument
+ expressions.
+
+ Supported types are: byte, short, integer, long, date, timestamp.
+
+ The start and stop expressions must resolve to the same type.
+ If start and stop expressions resolve to the 'date' or 'timestamp' type
+ then the step expression must resolve to the 'interval' type, otherwise to the same type
+ as the start and stop expressions.
+ """,
+ arguments = """
+ Arguments:
+ * start - an expression. The start of the range.
+ * stop - an expression. The end the range (inclusive).
+ * step - an optional expression. The step of the range.
+ By default step is 1 if start is less than or equal to stop, otherwise -1.
+ For the temporal sequences it's 1 day and -1 day respectively.
+ If start is greater than stop then the step must be negative, and vice versa.
+ """,
+ examples = """
+ Examples:
+ > SELECT _FUNC_(1, 5);
+ [1, 2, 3, 4, 5]
+ > SELECT _FUNC_(5, 1);
+ [5, 4, 3, 2, 1]
+ > SELECT _FUNC_(to_date('2018-01-01'), to_date('2018-03-01'), interval 1 month);
+ [2018-01-01, 2018-02-01, 2018-03-01]
+ """,
+ since = "2.4.0"
+)
+case class Sequence(
+ start: Expression,
+ stop: Expression,
+ stepOpt: Option[Expression],
+ timeZoneId: Option[String] = None)
+ extends Expression
+ with TimeZoneAwareExpression {
+
+ import Sequence._
+
+ def this(start: Expression, stop: Expression) =
+ this(start, stop, None, None)
+
+ def this(start: Expression, stop: Expression, step: Expression) =
+ this(start, stop, Some(step), None)
+
+ override def withTimeZone(timeZoneId: String): TimeZoneAwareExpression =
+ copy(timeZoneId = Some(timeZoneId))
+
+ override def children: Seq[Expression] = Seq(start, stop) ++ stepOpt
+
+ override def foldable: Boolean = children.forall(_.foldable)
+
+ override def nullable: Boolean = children.exists(_.nullable)
+
+ override lazy val dataType: ArrayType = ArrayType(start.dataType, containsNull = false)
+
+ override def checkInputDataTypes(): TypeCheckResult = {
+ val startType = start.dataType
+ def stepType = stepOpt.get.dataType
+ val typesCorrect =
+ startType.sameType(stop.dataType) &&
+ (startType match {
+ case TimestampType | DateType =>
+ stepOpt.isEmpty || CalendarIntervalType.acceptsType(stepType)
+ case _: IntegralType =>
+ stepOpt.isEmpty || stepType.sameType(startType)
+ case _ => false
+ })
+
+ if (typesCorrect) {
+ TypeCheckResult.TypeCheckSuccess
+ } else {
+ TypeCheckResult.TypeCheckFailure(
+ s"$prettyName only supports integral, timestamp or date types")
+ }
+ }
+
+ def coercibleChildren: Seq[Expression] = children.filter(_.dataType != CalendarIntervalType)
+
+ def castChildrenTo(widerType: DataType): Expression = Sequence(
+ Cast(start, widerType),
+ Cast(stop, widerType),
+ stepOpt.map(step => if (step.dataType != CalendarIntervalType) Cast(step, widerType) else step),
+ timeZoneId)
+
+ private lazy val impl: SequenceImpl = dataType.elementType match {
+ case iType: IntegralType =>
+ type T = iType.InternalType
+ val ct = ClassTag[T](iType.tag.mirror.runtimeClass(iType.tag.tpe))
+ new IntegralSequenceImpl(iType)(ct, iType.integral)
+
+ case TimestampType =>
+ new TemporalSequenceImpl[Long](LongType, 1, identity, timeZone)
+
+ case DateType =>
+ new TemporalSequenceImpl[Int](IntegerType, MICROS_PER_DAY, _.toInt, timeZone)
+ }
+
+ override def eval(input: InternalRow): Any = {
+ val startVal = start.eval(input)
+ if (startVal == null) return null
+ val stopVal = stop.eval(input)
+ if (stopVal == null) return null
+ val stepVal = stepOpt.map(_.eval(input)).getOrElse(impl.defaultStep(startVal, stopVal))
+ if (stepVal == null) return null
+
+ ArrayData.toArrayData(impl.eval(startVal, stopVal, stepVal))
+ }
+
+ override protected def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = {
+ val startGen = start.genCode(ctx)
+ val stopGen = stop.genCode(ctx)
+ val stepGen = stepOpt.map(_.genCode(ctx)).getOrElse(
+ impl.defaultStep.genCode(ctx, startGen, stopGen))
+
+ val resultType = CodeGenerator.javaType(dataType)
+ val resultCode = {
+ val arr = ctx.freshName("arr")
+ val arrElemType = CodeGenerator.javaType(dataType.elementType)
+ s"""
+ |final $arrElemType[] $arr = null;
+ |${impl.genCode(ctx, startGen.value, stopGen.value, stepGen.value, arr, arrElemType)}
+ |${ev.value} = UnsafeArrayData.fromPrimitiveArray($arr);
+ """.stripMargin
+ }
+
+ if (nullable) {
+ val nullSafeEval =
+ startGen.code + ctx.nullSafeExec(start.nullable, startGen.isNull) {
+ stopGen.code + ctx.nullSafeExec(stop.nullable, stopGen.isNull) {
+ stepGen.code + ctx.nullSafeExec(stepOpt.exists(_.nullable), stepGen.isNull) {
+ s"""
+ |${ev.isNull} = false;
+ |$resultCode
+ """.stripMargin
+ }
+ }
+ }
+ ev.copy(code =
+ s"""
+ |boolean ${ev.isNull} = true;
+ |$resultType ${ev.value} = null;
+ |$nullSafeEval
+ """.stripMargin)
+
+ } else {
+ ev.copy(code =
+ s"""
+ |boolean ${ev.isNull} = false;
+ |${startGen.code}
+ |${stopGen.code}
+ |${stepGen.code}
+ |$resultType ${ev.value} = null;
+ |$resultCode
+ """.stripMargin,
+ isNull = FalseLiteral)
+ }
+ }
+}
+
+object Sequence {
+
+ private type LessThanOrEqualFn = (Any, Any) => Boolean
+
+ private class DefaultStep(lteq: LessThanOrEqualFn, stepType: DataType, one: Any) {
+ private val negativeOne = UnaryMinus(Literal(one)).eval()
+
+ def apply(start: Any, stop: Any): Any = {
+ if (lteq(start, stop)) one else negativeOne
+ }
+
+ def genCode(ctx: CodegenContext, startGen: ExprCode, stopGen: ExprCode): ExprCode = {
+ val Seq(oneVal, negativeOneVal) = Seq(one, negativeOne).map(Literal(_).genCode(ctx).value)
+ ExprCode.forNonNullValue(JavaCode.expression(
+ s"${startGen.value} <= ${stopGen.value} ? $oneVal : $negativeOneVal",
+ stepType))
+ }
+ }
+
+ private trait SequenceImpl {
+ def eval(start: Any, stop: Any, step: Any): Any
+
+ def genCode(
+ ctx: CodegenContext,
+ start: String,
+ stop: String,
+ step: String,
+ arr: String,
+ elemType: String): String
+
+ val defaultStep: DefaultStep
+ }
+
+ private class IntegralSequenceImpl[T: ClassTag]
+ (elemType: IntegralType)(implicit num: Integral[T]) extends SequenceImpl {
+
+ override val defaultStep: DefaultStep = new DefaultStep(
+ (elemType.ordering.lteq _).asInstanceOf[LessThanOrEqualFn],
+ elemType,
+ num.one)
+
+ override def eval(input1: Any, input2: Any, input3: Any): Array[T] = {
+ import num._
+
+ val start = input1.asInstanceOf[T]
+ val stop = input2.asInstanceOf[T]
+ val step = input3.asInstanceOf[T]
+
+ var i: Int = getSequenceLength(start, stop, step)
+ val arr = new Array[T](i)
+ while (i > 0) {
+ i -= 1
+ arr(i) = start + step * num.fromInt(i)
+ }
+ arr
+ }
+
+ override def genCode(
+ ctx: CodegenContext,
+ start: String,
+ stop: String,
+ step: String,
+ arr: String,
+ elemType: String): String = {
+ val i = ctx.freshName("i")
+ s"""
+ |${genSequenceLengthCode(ctx, start, stop, step, i)}
+ |$arr = new $elemType[$i];
+ |while ($i > 0) {
+ | $i--;
+ | $arr[$i] = ($elemType) ($start + $step * $i);
+ |}
+ """.stripMargin
+ }
+ }
+
+ private class TemporalSequenceImpl[T: ClassTag]
+ (dt: IntegralType, scale: Long, fromLong: Long => T, timeZone: TimeZone)
+ (implicit num: Integral[T]) extends SequenceImpl {
+
+ override val defaultStep: DefaultStep = new DefaultStep(
+ (dt.ordering.lteq _).asInstanceOf[LessThanOrEqualFn],
+ CalendarIntervalType,
+ new CalendarInterval(0, MICROS_PER_DAY))
+
+ private val backedSequenceImpl = new IntegralSequenceImpl[T](dt)
+ private val microsPerMonth = 28 * CalendarInterval.MICROS_PER_DAY
+
+ override def eval(input1: Any, input2: Any, input3: Any): Array[T] = {
+ val start = input1.asInstanceOf[T]
+ val stop = input2.asInstanceOf[T]
+ val step = input3.asInstanceOf[CalendarInterval]
+ val stepMonths = step.months
+ val stepMicros = step.microseconds
+
+ if (stepMonths == 0) {
+ backedSequenceImpl.eval(start, stop, fromLong(stepMicros / scale))
+
+ } else {
+ // To estimate the resulted array length we need to make assumptions
+ // about a month length in microseconds
+ val intervalStepInMicros = stepMicros + stepMonths * microsPerMonth
+ val startMicros: Long = num.toLong(start) * scale
+ val stopMicros: Long = num.toLong(stop) * scale
+ val maxEstimatedArrayLength =
+ getSequenceLength(startMicros, stopMicros, intervalStepInMicros)
+
+ val stepSign = if (stopMicros > startMicros) +1 else -1
+ val exclusiveItem = stopMicros + stepSign
+ val arr = new Array[T](maxEstimatedArrayLength)
+ var t = startMicros
+ var i = 0
+
+ while (t < exclusiveItem ^ stepSign < 0) {
+ arr(i) = fromLong(t / scale)
+ t = timestampAddInterval(t, stepMonths, stepMicros, timeZone)
+ i += 1
+ }
+
+ // truncate array to the correct length
+ if (arr.length == i) arr else arr.slice(0, i)
+ }
+ }
+
+ override def genCode(
+ ctx: CodegenContext,
+ start: String,
+ stop: String,
+ step: String,
+ arr: String,
+ elemType: String): String = {
+ val stepMonths = ctx.freshName("stepMonths")
+ val stepMicros = ctx.freshName("stepMicros")
+ val stepScaled = ctx.freshName("stepScaled")
+ val intervalInMicros = ctx.freshName("intervalInMicros")
+ val startMicros = ctx.freshName("startMicros")
+ val stopMicros = ctx.freshName("stopMicros")
+ val arrLength = ctx.freshName("arrLength")
+ val stepSign = ctx.freshName("stepSign")
+ val exclusiveItem = ctx.freshName("exclusiveItem")
+ val t = ctx.freshName("t")
+ val i = ctx.freshName("i")
+ val genTimeZone = ctx.freshName("timeZone")
+
+ val sequenceLengthCode =
+ s"""
+ |final long $intervalInMicros = $stepMicros + $stepMonths * ${microsPerMonth}L;
+ |${genSequenceLengthCode(ctx, startMicros, stopMicros, intervalInMicros, arrLength)}
+ """.stripMargin
+
+ val timestampAddIntervalCode =
+ s"""
+ |$t = org.apache.spark.sql.catalyst.util.DateTimeUtils.timestampAddInterval(
+ | $t, $stepMonths, $stepMicros, $genTimeZone);
+ """.stripMargin
+
+ s"""
+ |final int $stepMonths = $step.months;
+ |final long $stepMicros = $step.microseconds;
+ |
+ |if ($stepMonths == 0) {
+ | final $elemType $stepScaled = ($elemType) ($stepMicros / ${scale}L);
+ | ${backedSequenceImpl.genCode(ctx, start, stop, stepScaled, arr, elemType)};
+ |
+ |} else {
+ | final long $startMicros = $start * ${scale}L;
+ | final long $stopMicros = $stop * ${scale}L;
+ |
+ | $sequenceLengthCode
+ |
+ | final int $stepSign = $stopMicros > $startMicros ? +1 : -1;
+ | final long $exclusiveItem = $stopMicros + $stepSign;
+ | final java.util.TimeZone $genTimeZone =
+ | java.util.TimeZone.getTimeZone("${timeZone.getID}");
--- End diff --
Good catch. Done.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: SPARK-23927: Add "sequence" expression
Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:
https://github.com/apache/spark/pull/21155
**[Test build #89860 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/89860/testReport)** for PR 21155 at commit [`a7c0ccd`](https://github.com/apache/spark/commit/a7c0ccdfa7b2f78ab3ae29aa6b5b1c16dfc38f9c).
* This patch passes all tests.
* This patch merges cleanly.
* This patch adds no public classes.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: SPARK-23927: Add "sequence" expression
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:
https://github.com/apache/spark/pull/21155
Merged build finished. Test FAILed.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:
https://github.com/apache/spark/pull/21155
**[Test build #90456 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/90456/testReport)** for PR 21155 at commit [`0a0a1e6`](https://github.com/apache/spark/commit/0a0a1e655f5b005d337a521692bbe9e6e09e5377).
* This patch passes all tests.
* This patch merges cleanly.
* This patch adds no public classes.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by ueshin <gi...@git.apache.org>.
Github user ueshin commented on a diff in the pull request:
https://github.com/apache/spark/pull/21155#discussion_r197723939
--- Diff: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/collectionOperations.scala ---
@@ -2288,6 +2288,401 @@ case class Flatten(child: Expression) extends UnaryExpression {
override def prettyName: String = "flatten"
}
+@ExpressionDescription(
+ usage = """
+ _FUNC_(start, stop, step) - Generates an array of elements from start to stop (inclusive),
+ incrementing by step. The type of the returned elements is the same as the type of argument
+ expressions.
+
+ Supported types are: byte, short, integer, long, date, timestamp.
+
+ The start and stop expressions must resolve to the same type.
+ If start and stop expressions resolve to the 'date' or 'timestamp' type
+ then the step expression must resolve to the 'interval' type, otherwise to the same type
+ as the start and stop expressions.
+ """,
+ arguments = """
+ Arguments:
+ * start - an expression. The start of the range.
+ * stop - an expression. The end the range (inclusive).
+ * step - an optional expression. The step of the range.
+ By default step is 1 if start is less than or equal to stop, otherwise -1.
+ For the temporal sequences it's 1 day and -1 day respectively.
+ If start is greater than stop then the step must be negative, and vice versa.
+ """,
+ examples = """
+ Examples:
+ > SELECT _FUNC_(1, 5);
+ [1, 2, 3, 4, 5]
+ > SELECT _FUNC_(5, 1);
+ [5, 4, 3, 2, 1]
+ > SELECT _FUNC_(to_date('2018-01-01'), to_date('2018-03-01'), interval 1 month);
+ [2018-01-01, 2018-02-01, 2018-03-01]
+ """,
+ since = "2.4.0"
+)
+case class Sequence(
+ start: Expression,
+ stop: Expression,
+ stepOpt: Option[Expression],
+ timeZoneId: Option[String] = None)
+ extends Expression
+ with TimeZoneAwareExpression {
+
+ import Sequence._
+
+ def this(start: Expression, stop: Expression) =
+ this(start, stop, None, None)
+
+ def this(start: Expression, stop: Expression, step: Expression) =
+ this(start, stop, Some(step), None)
+
+ override def withTimeZone(timeZoneId: String): TimeZoneAwareExpression =
+ copy(timeZoneId = Some(timeZoneId))
+
+ override def children: Seq[Expression] = Seq(start, stop) ++ stepOpt
+
+ override def foldable: Boolean = children.forall(_.foldable)
+
+ override def nullable: Boolean = children.exists(_.nullable)
+
+ override lazy val dataType: ArrayType = ArrayType(start.dataType, containsNull = false)
+
+ override def checkInputDataTypes(): TypeCheckResult = {
+ val startType = start.dataType
+ def stepType = stepOpt.get.dataType
+ val typesCorrect =
+ startType.sameType(stop.dataType) &&
+ (startType match {
+ case TimestampType | DateType =>
+ stepOpt.isEmpty || CalendarIntervalType.acceptsType(stepType)
+ case _: IntegralType =>
+ stepOpt.isEmpty || stepType.sameType(startType)
+ case _ => false
+ })
+
+ if (typesCorrect) {
+ TypeCheckResult.TypeCheckSuccess
+ } else {
+ TypeCheckResult.TypeCheckFailure(
+ s"$prettyName only supports integral, timestamp or date types")
+ }
+ }
+
+ def coercibleChildren: Seq[Expression] = children.filter(_.dataType != CalendarIntervalType)
+
+ def castChildrenTo(widerType: DataType): Expression = Sequence(
+ Cast(start, widerType),
+ Cast(stop, widerType),
+ stepOpt.map(step => if (step.dataType != CalendarIntervalType) Cast(step, widerType) else step),
--- End diff --
Makes sense. Thanks!
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:
https://github.com/apache/spark/pull/21155
**[Test build #90428 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/90428/testReport)** for PR 21155 at commit [`22bde31`](https://github.com/apache/spark/commit/22bde31feab95e548351a6057f5286c6faf75695).
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:
https://github.com/apache/spark/pull/21155
Test FAILed.
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/92326/
Test FAILed.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by HyukjinKwon <gi...@git.apache.org>.
Github user HyukjinKwon commented on the issue:
https://github.com/apache/spark/pull/21155
ok to test
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:
https://github.com/apache/spark/pull/21155
Test FAILed.
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/90330/
Test FAILed.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:
https://github.com/apache/spark/pull/21155
**[Test build #90329 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/90329/testReport)** for PR 21155 at commit [`8786192`](https://github.com/apache/spark/commit/878619276592d189d69d9c6ed259f3d7d1f6fa48).
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by ueshin <gi...@git.apache.org>.
Github user ueshin commented on a diff in the pull request:
https://github.com/apache/spark/pull/21155#discussion_r193928619
--- Diff: sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/CollectionExpressionsSuite.scala ---
@@ -308,6 +313,292 @@ class CollectionExpressionsSuite extends SparkFunSuite with ExpressionEvalHelper
ArrayMax(Literal.create(Seq(1.123, 0.1234, 1.121), ArrayType(DoubleType))), 1.123)
}
+ test("Sequence") {
+ // test null handling
+
+ checkEvaluation(new Sequence(Literal(null, LongType), Literal(1L)), null)
+ checkEvaluation(new Sequence(Literal(1L), Literal(null, LongType)), null)
+ checkEvaluation(new Sequence(Literal(null, LongType), Literal(1L), Literal(1L)), null)
+ checkEvaluation(new Sequence(Literal(1L), Literal(null, LongType), Literal(1L)), null)
+ checkEvaluation(new Sequence(Literal(1L), Literal(1L), Literal(null, LongType)), null)
+
+ // test sequence boundaries checking
+
+ checkExceptionInExpression[IllegalArgumentException](
+ new Sequence(Literal(Int.MinValue), Literal(Int.MaxValue), Literal(1)),
+ EmptyRow, s"Too long sequence: 4294967296. Should be <= ${Int.MaxValue}")
+
+ checkExceptionInExpression[IllegalArgumentException](
+ new Sequence(Literal(1), Literal(2), Literal(0)), EmptyRow, "boundaries: 1 to 2 by 0")
+ checkExceptionInExpression[IllegalArgumentException](
+ new Sequence(Literal(2), Literal(1), Literal(0)), EmptyRow, "boundaries: 2 to 1 by 0")
+ checkExceptionInExpression[IllegalArgumentException](
+ new Sequence(Literal(2), Literal(1), Literal(1)), EmptyRow, "boundaries: 2 to 1 by 1")
+ checkExceptionInExpression[IllegalArgumentException](
+ new Sequence(Literal(1), Literal(2), Literal(-1)), EmptyRow, "boundaries: 1 to 2 by -1")
+
+ checkExceptionInExpression[IllegalArgumentException](
+ new Sequence(
+ Literal(Date.valueOf("1970-01-02")),
+ Literal(Date.valueOf("1970-01-01")),
+ Literal(CalendarInterval.fromString("interval 1 day"))),
+ EmptyRow, "sequence boundaries: 1 to 0 by 1")
+
+ checkExceptionInExpression[IllegalArgumentException](
+ new Sequence(
+ Literal(Date.valueOf("1970-01-01")),
+ Literal(Date.valueOf("1970-02-01")),
+ Literal(CalendarInterval.fromString("interval 1 month").negate())),
+ EmptyRow,
+ s"sequence boundaries: 0 to 2678400000000 by -${28 * CalendarInterval.MICROS_PER_DAY}")
+
+ // test sequence with one element (zero step or equal start and stop)
+
+ checkEvaluation(new Sequence(Literal(1), Literal(1), Literal(-1)), Seq(1))
+ checkEvaluation(new Sequence(Literal(1), Literal(1), Literal(0)), Seq(1))
+ checkEvaluation(new Sequence(Literal(1), Literal(1), Literal(1)), Seq(1))
+ checkEvaluation(new Sequence(Literal(1), Literal(2), Literal(2)), Seq(1))
+ checkEvaluation(new Sequence(Literal(1), Literal(0), Literal(-2)), Seq(1))
+
+ // test sequence of different integral types (ascending and descending)
+
+ checkEvaluation(new Sequence(Literal(1L), Literal(3L), Literal(1L)), Seq(1L, 2L, 3L))
+ checkEvaluation(new Sequence(Literal(-3), Literal(3), Literal(3)), Seq(-3, 0, 3))
+ checkEvaluation(
+ new Sequence(Literal(3.toShort), Literal(-3.toShort), Literal(-3.toShort)),
+ Seq(3.toShort, 0.toShort, -3.toShort))
+ checkEvaluation(
+ new Sequence(Literal(-1.toByte), Literal(-3.toByte), Literal(-1.toByte)),
+ Seq(-1.toByte, -2.toByte, -3.toByte))
+ }
+
+ test("Sequence of timestamps") {
+ checkEvaluation(new Sequence(
+ Literal(Timestamp.valueOf("2018-01-01 00:00:00")),
+ Literal(Timestamp.valueOf("2018-01-02 00:00:00")),
+ Literal(CalendarInterval.fromString("interval 12 hours"))),
+ Seq(
+ Timestamp.valueOf("2018-01-01 00:00:00"),
+ Timestamp.valueOf("2018-01-01 12:00:00"),
+ Timestamp.valueOf("2018-01-02 00:00:00")))
+
+ checkEvaluation(new Sequence(
+ Literal(Timestamp.valueOf("2018-01-01 00:00:00")),
+ Literal(Timestamp.valueOf("2018-01-02 00:00:01")),
+ Literal(CalendarInterval.fromString("interval 12 hours"))),
+ Seq(
+ Timestamp.valueOf("2018-01-01 00:00:00"),
+ Timestamp.valueOf("2018-01-01 12:00:00"),
+ Timestamp.valueOf("2018-01-02 00:00:00")))
+
+ checkEvaluation(new Sequence(
+ Literal(Timestamp.valueOf("2018-01-02 00:00:00")),
+ Literal(Timestamp.valueOf("2018-01-01 00:00:00")),
+ Literal(CalendarInterval.fromString("interval 12 hours").negate())),
+ Seq(
+ Timestamp.valueOf("2018-01-02 00:00:00"),
+ Timestamp.valueOf("2018-01-01 12:00:00"),
+ Timestamp.valueOf("2018-01-01 00:00:00")))
+
+ checkEvaluation(new Sequence(
+ Literal(Timestamp.valueOf("2018-01-02 00:00:00")),
+ Literal(Timestamp.valueOf("2017-12-31 23:59:59")),
+ Literal(CalendarInterval.fromString("interval 12 hours").negate())),
+ Seq(
+ Timestamp.valueOf("2018-01-02 00:00:00"),
+ Timestamp.valueOf("2018-01-01 12:00:00"),
+ Timestamp.valueOf("2018-01-01 00:00:00")))
+
+ checkEvaluation(new Sequence(
+ Literal(Timestamp.valueOf("2018-01-01 00:00:00")),
+ Literal(Timestamp.valueOf("2018-03-01 00:00:00")),
+ Literal(CalendarInterval.fromString("interval 1 month"))),
+ Seq(
+ Timestamp.valueOf("2018-01-01 00:00:00"),
+ Timestamp.valueOf("2018-02-01 00:00:00"),
+ Timestamp.valueOf("2018-03-01 00:00:00")))
+
+ checkEvaluation(new Sequence(
+ Literal(Timestamp.valueOf("2018-03-01 00:00:00")),
+ Literal(Timestamp.valueOf("2018-01-01 00:00:00")),
+ Literal(CalendarInterval.fromString("interval 1 month").negate())),
+ Seq(
+ Timestamp.valueOf("2018-03-01 00:00:00"),
+ Timestamp.valueOf("2018-02-01 00:00:00"),
+ Timestamp.valueOf("2018-01-01 00:00:00")))
+
+ checkEvaluation(new Sequence(
+ Literal(Timestamp.valueOf("2018-03-03 00:00:00")),
+ Literal(Timestamp.valueOf("2018-01-01 00:00:00")),
+ Literal(CalendarInterval.fromString("interval 1 month 1 day").negate())),
+ Seq(
+ Timestamp.valueOf("2018-03-03 00:00:00"),
+ Timestamp.valueOf("2018-02-02 00:00:00"),
+ Timestamp.valueOf("2018-01-01 00:00:00")))
+
+ checkEvaluation(new Sequence(
+ Literal(Timestamp.valueOf("2018-01-31 00:00:00")),
+ Literal(Timestamp.valueOf("2018-04-30 00:00:00")),
+ Literal(CalendarInterval.fromString("interval 1 month"))),
+ Seq(
+ Timestamp.valueOf("2018-01-31 00:00:00"),
+ Timestamp.valueOf("2018-02-28 00:00:00"),
+ Timestamp.valueOf("2018-03-31 00:00:00"),
+ Timestamp.valueOf("2018-04-30 00:00:00")))
+
+ checkEvaluation(new Sequence(
+ Literal(Timestamp.valueOf("2018-01-01 00:00:00")),
+ Literal(Timestamp.valueOf("2018-03-01 00:00:00")),
+ Literal(CalendarInterval.fromString("interval 1 month 1 second"))),
+ Seq(
+ Timestamp.valueOf("2018-01-01 00:00:00"),
+ Timestamp.valueOf("2018-02-01 00:00:01")))
+
+ checkEvaluation(new Sequence(
+ Literal(Timestamp.valueOf("2018-01-01 00:00:00")),
+ Literal(Timestamp.valueOf("2018-03-01 00:04:06")),
+ Literal(CalendarInterval.fromString("interval 1 month 2 minutes 3 seconds"))),
+ Seq(
+ Timestamp.valueOf("2018-01-01 00:00:00"),
+ Timestamp.valueOf("2018-02-01 00:02:03"),
+ Timestamp.valueOf("2018-03-01 00:04:06")))
+
+ checkEvaluation(new Sequence(
+ Literal(Timestamp.valueOf("2018-01-01 00:00:00")),
+ Literal(Timestamp.valueOf("2023-01-01 00:00:00")),
+ Literal(CalendarInterval.fromYearMonthString("1-5"))),
+ Seq(
+ Timestamp.valueOf("2018-01-01 00:00:00.000"),
+ Timestamp.valueOf("2019-06-01 00:00:00.000"),
+ Timestamp.valueOf("2020-11-01 00:00:00.000"),
+ Timestamp.valueOf("2022-04-01 00:00:00.000")))
+
+ checkEvaluation(new Sequence(
+ Literal(Timestamp.valueOf("2022-04-01 00:00:00")),
+ Literal(Timestamp.valueOf("2017-01-01 00:00:00")),
+ Literal(CalendarInterval.fromYearMonthString("1-5").negate())),
+ Seq(
+ Timestamp.valueOf("2022-04-01 00:00:00.000"),
+ Timestamp.valueOf("2020-11-01 00:00:00.000"),
+ Timestamp.valueOf("2019-06-01 00:00:00.000"),
+ Timestamp.valueOf("2018-01-01 00:00:00.000")))
+ }
+
+ test("Sequence on DST boundaries") {
+ val timeZone = TimeZone.getTimeZone("CET")
--- End diff --
Could you use a long name? 3-letter name might not work in some environment.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request #21155: SPARK-23927: Add "sequence" expression
Posted by ueshin <gi...@git.apache.org>.
Github user ueshin commented on a diff in the pull request:
https://github.com/apache/spark/pull/21155#discussion_r186036116
--- Diff: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/collectionOperations.scala ---
@@ -1059,3 +1063,316 @@ case class Flatten(child: Expression) extends UnaryExpression {
override def prettyName: String = "flatten"
}
+
+@ExpressionDescription(
+ usage = """
+ _FUNC_(start, stop, step) -
+ Generates an array of elements from start to stop (inclusive), incrementing by step.
+ The type of the returned elements is the same as the type of argument expressions.
+
+ Supported types are: byte, short, integer, long, date, timestamp.
+
+ The start and stop expressions must resolve to the same type.
+ If start and stop expressions resolve to the 'date' or 'timestamp' type
+ then the step expression must resolve to the 'interval' type, otherwise to the same type
+ as the start and stop expressions.
+ """,
+ arguments = """
+ Arguments:
+ * start - an expression. The start of the range.
+ * stop - an expression. The end the range (inclusive).
+ * step - an optional expression. The step of the range.
+
+ By default step is 1 if start is less than or equal to stop, otherwise -1.
+ For the temporal sequences it's 1 day and -1 day respectively.
+
+ If start is greater than stop then the step must be negative, and vice versa.
+ """,
+ examples = """
+ Examples:
+ > SELECT _FUNC_(1, 5);
+ [1, 2, 3, 4, 5]
+ > SELECT _FUNC_(5, 1);
+ [5, 4, 3, 2, 1]
+ > SELECT _FUNC_(to_date('2018-01-01'), to_date('2018-03-01'), interval 1 month);
+ [2018-01-01, 2018-02-01, 2018-03-01]
+ """,
+ since = "2.4.0"
+)
+case class Sequence(left: Expression,
+ middle: Expression,
+ right: Expression,
+ timeZoneId: Option[String] = None)
+ extends TernaryExpression with TimeZoneAwareExpression {
+
+ import Sequence._
+
+ def this(arg0: Expression, arg1: Expression) =
+ this(arg0, arg1, Sequence.defaultStepExpression(arg0, arg1), None)
+
+ def this(arg0: Expression, arg1: Expression, arg2: Expression) =
+ this(arg0, arg1, arg2, None)
+
+ override def withTimeZone(timeZoneId: String): TimeZoneAwareExpression =
+ copy(timeZoneId = Some(timeZoneId))
+
+ override def children: Seq[Expression] = Seq(left, middle, right)
+
+ override lazy val dataType: ArrayType = ArrayType(left.dataType, containsNull = false)
+
+ override def checkInputDataTypes(): TypeCheckResult = {
+ val Seq(startType, stopType, stepType) = children.map(_.dataType)
+ val typesCorrect =
+ startType.sameType(stopType) &&
+ (startType match {
+ case TimestampType | DateType => CalendarIntervalType acceptsType stepType
+ case _: IntegralType => stepType sameType startType
+ case _ => false
+ })
+
+ if (typesCorrect) {
+ TypeCheckResult.TypeCheckSuccess
+ } else {
+ TypeCheckResult.TypeCheckFailure(
+ s"$prettyName only supports integral, timestamp or date types")
+ }
+ }
+
+ private lazy val impl: SequenceImpl = dataType.elementType match {
+ case iType: IntegralType =>
+ type T = iType.InternalType
+ val ct = ClassTag[T](iType.tag.mirror.runtimeClass(iType.tag.tpe))
+ new IntegralSequenceImpl()(ct, iType.integral)
+
+ case TimestampType =>
+ new TemporalSequenceImpl[Long](LongType, 1, identity, timeZone)
+
+ case DateType =>
+ new TemporalSequenceImpl[Int](IntegerType, MICROS_PER_DAY, _.toInt, timeZone)
+ }
+
+ override protected def nullSafeEval(input1: Any, input2: Any, input3: Any): Any = {
+ ArrayData.toArrayData(impl.eval(input1, input2, input3))
+ }
+
+ override protected def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = {
+ nullSafeCodeGen(ctx, ev, (start, stop, step) => {
+ val arr = ctx.freshName("arr")
+ val arrElemType = CodeGenerator.javaType(dataType.elementType)
+ s"""
+ | final $arrElemType[] $arr = null;
+ | ${impl.genCode(start, stop, step)(arr, arrElemType)(ctx)}
+ | ${ev.value} = UnsafeArrayData.fromPrimitiveArray($arr);
+ """.stripMargin
+ })
+ }
+}
+
+object Sequence {
+
+ private trait SequenceImpl {
+ def eval(input1: Any, input2: Any, input3: Any): Any
+
+ def genCode(start: String, stop: String, step: String)
+ (arr: String, elemType: String)
+ (implicit ctx: CodegenContext): String
+ }
+
+ private class IntegralSequenceImpl[T: ClassTag]
+ (implicit num: Integral[T]) extends SequenceImpl {
+
+ override def eval(input1: Any, input2: Any, input3: Any): Array[T] = {
+ import num._
+
+ val start = input1.asInstanceOf[T]
+ val stop = input2.asInstanceOf[T]
+ val step = input3.asInstanceOf[T]
+
+ var i: Int = getSequenceLength(start, stop, step)
+ val arr = new Array[T](i)
+ while (i > 0) {
+ i -= 1
+ arr(i) = start + step * num.fromInt(i)
+ }
+ arr
+ }
+
+ override def genCode(start: String, stop: String, step: String)
+ (arr: String, elemType: String)
+ (implicit ctx: CodegenContext): String = {
+ val i = ctx.freshName("i")
+ s"""
+ | ${genSequenceLengthCode(start, stop, step)(i)}
+ | $arr = new $elemType[$i];
+ | while ($i > 0) {
+ | $i--;
+ | $arr[$i] = ($elemType) ($start + $step * $i);
+ | }
+ """.stripMargin
+ }
+ }
+
+ private class TemporalSequenceImpl[T: ClassTag]
--- End diff --
ditto.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:
https://github.com/apache/spark/pull/21155
Test PASSed.
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/90207/
Test PASSed.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:
https://github.com/apache/spark/pull/21155
Test PASSed.
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/92217/
Test PASSed.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by wajda <gi...@git.apache.org>.
Github user wajda commented on a diff in the pull request:
https://github.com/apache/spark/pull/21155#discussion_r197714164
--- Diff: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/collectionOperations.scala ---
@@ -2288,6 +2288,401 @@ case class Flatten(child: Expression) extends UnaryExpression {
override def prettyName: String = "flatten"
}
+@ExpressionDescription(
+ usage = """
+ _FUNC_(start, stop, step) - Generates an array of elements from start to stop (inclusive),
+ incrementing by step. The type of the returned elements is the same as the type of argument
+ expressions.
+
+ Supported types are: byte, short, integer, long, date, timestamp.
+
+ The start and stop expressions must resolve to the same type.
+ If start and stop expressions resolve to the 'date' or 'timestamp' type
+ then the step expression must resolve to the 'interval' type, otherwise to the same type
+ as the start and stop expressions.
+ """,
+ arguments = """
+ Arguments:
+ * start - an expression. The start of the range.
+ * stop - an expression. The end the range (inclusive).
+ * step - an optional expression. The step of the range.
+ By default step is 1 if start is less than or equal to stop, otherwise -1.
+ For the temporal sequences it's 1 day and -1 day respectively.
+ If start is greater than stop then the step must be negative, and vice versa.
+ """,
+ examples = """
+ Examples:
+ > SELECT _FUNC_(1, 5);
+ [1, 2, 3, 4, 5]
+ > SELECT _FUNC_(5, 1);
+ [5, 4, 3, 2, 1]
+ > SELECT _FUNC_(to_date('2018-01-01'), to_date('2018-03-01'), interval 1 month);
+ [2018-01-01, 2018-02-01, 2018-03-01]
+ """,
+ since = "2.4.0"
+)
+case class Sequence(
+ start: Expression,
+ stop: Expression,
+ stepOpt: Option[Expression],
+ timeZoneId: Option[String] = None)
+ extends Expression
+ with TimeZoneAwareExpression {
+
+ import Sequence._
+
+ def this(start: Expression, stop: Expression) =
+ this(start, stop, None, None)
+
+ def this(start: Expression, stop: Expression, step: Expression) =
+ this(start, stop, Some(step), None)
+
+ override def withTimeZone(timeZoneId: String): TimeZoneAwareExpression =
+ copy(timeZoneId = Some(timeZoneId))
+
+ override def children: Seq[Expression] = Seq(start, stop) ++ stepOpt
+
+ override def foldable: Boolean = children.forall(_.foldable)
+
+ override def nullable: Boolean = children.exists(_.nullable)
+
+ override lazy val dataType: ArrayType = ArrayType(start.dataType, containsNull = false)
+
+ override def checkInputDataTypes(): TypeCheckResult = {
+ val startType = start.dataType
+ def stepType = stepOpt.get.dataType
+ val typesCorrect =
+ startType.sameType(stop.dataType) &&
+ (startType match {
+ case TimestampType | DateType =>
+ stepOpt.isEmpty || CalendarIntervalType.acceptsType(stepType)
+ case _: IntegralType =>
+ stepOpt.isEmpty || stepType.sameType(startType)
+ case _ => false
+ })
+
+ if (typesCorrect) {
+ TypeCheckResult.TypeCheckSuccess
+ } else {
+ TypeCheckResult.TypeCheckFailure(
+ s"$prettyName only supports integral, timestamp or date types")
+ }
+ }
+
+ def coercibleChildren: Seq[Expression] = children.filter(_.dataType != CalendarIntervalType)
+
+ def castChildrenTo(widerType: DataType): Expression = Sequence(
+ Cast(start, widerType),
+ Cast(stop, widerType),
+ stepOpt.map(step => if (step.dataType != CalendarIntervalType) Cast(step, widerType) else step),
--- End diff --
How can it be useful? Do you have a use case example?
When using SQL notation an interval step is automatically parsed as a correct type, so I never get it as `String` in this method. Unless I am mistaken the only way for 'step' to be of 'String' type is if `Sequence` expression is created programmatically with a string type expression passed as 3rd argument. But in this case having strong typing is rather a good thing, isn't it?
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: SPARK-23927: Add "sequence" expression
Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:
https://github.com/apache/spark/pull/21155
**[Test build #89851 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/89851/testReport)** for PR 21155 at commit [`8fb427c`](https://github.com/apache/spark/commit/8fb427c72d719b37a2c36caccd9309bc200cd29c).
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by ueshin <gi...@git.apache.org>.
Github user ueshin commented on a diff in the pull request:
https://github.com/apache/spark/pull/21155#discussion_r193926035
--- Diff: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/collectionOperations.scala ---
@@ -1887,6 +1889,402 @@ case class Flatten(child: Expression) extends UnaryExpression {
override def prettyName: String = "flatten"
}
+@ExpressionDescription(
+ usage = """
+ _FUNC_(start, stop, step) - Generates an array of elements from start to stop (inclusive),
+ incrementing by step. The type of the returned elements is the same as the type of argument
+ expressions.
+
+ Supported types are: byte, short, integer, long, date, timestamp.
+
+ The start and stop expressions must resolve to the same type.
+ If start and stop expressions resolve to the 'date' or 'timestamp' type
+ then the step expression must resolve to the 'interval' type, otherwise to the same type
+ as the start and stop expressions.
+ """,
+ arguments = """
+ Arguments:
+ * start - an expression. The start of the range.
+ * stop - an expression. The end the range (inclusive).
+ * step - an optional expression. The step of the range.
+ By default step is 1 if start is less than or equal to stop, otherwise -1.
+ For the temporal sequences it's 1 day and -1 day respectively.
+ If start is greater than stop then the step must be negative, and vice versa.
+ """,
+ examples = """
+ Examples:
+ > SELECT _FUNC_(1, 5);
+ [1, 2, 3, 4, 5]
+ > SELECT _FUNC_(5, 1);
+ [5, 4, 3, 2, 1]
+ > SELECT _FUNC_(to_date('2018-01-01'), to_date('2018-03-01'), interval 1 month);
+ [2018-01-01, 2018-02-01, 2018-03-01]
+ """,
+ since = "2.4.0"
+)
+case class Sequence(
+ start: Expression,
+ stop: Expression,
+ stepOpt: Option[Expression],
+ timeZoneId: Option[String] = None)
+ extends Expression
+ with TimeZoneAwareExpression {
+
+ import Sequence._
+
+ def this(start: Expression, stop: Expression) =
+ this(start, stop, None, None)
+
+ def this(start: Expression, stop: Expression, step: Expression) =
+ this(start, stop, Some(step), None)
+
+ override def withTimeZone(timeZoneId: String): TimeZoneAwareExpression =
+ copy(timeZoneId = Some(timeZoneId))
+
+ override def children: Seq[Expression] = Seq(start, stop) ++ stepOpt
+
+ override def foldable: Boolean = children.forall(_.foldable)
+
+ override def nullable: Boolean = children.exists(_.nullable)
+
+ override lazy val dataType: ArrayType = ArrayType(start.dataType, containsNull = false)
+
+ override def checkInputDataTypes(): TypeCheckResult = {
+ val startType = start.dataType
+ def stepType = stepOpt.get.dataType
+ val typesCorrect =
+ startType.sameType(stop.dataType) &&
+ (startType match {
+ case TimestampType | DateType =>
+ stepOpt.isEmpty || CalendarIntervalType.acceptsType(stepType)
+ case _: IntegralType =>
+ stepOpt.isEmpty || stepType.sameType(startType)
+ case _ => false
+ })
+
+ if (typesCorrect) {
+ TypeCheckResult.TypeCheckSuccess
+ } else {
+ TypeCheckResult.TypeCheckFailure(
+ s"$prettyName only supports integral, timestamp or date types")
+ }
+ }
+
+ def coercibleChildren: Seq[Expression] = children.filter(_.dataType != CalendarIntervalType)
+
+ def castChildrenTo(widerType: DataType): Expression = Sequence(
+ Cast(start, widerType),
+ Cast(stop, widerType),
+ stepOpt.map(step => if (step.dataType != CalendarIntervalType) Cast(step, widerType) else step),
+ timeZoneId)
+
+ private lazy val impl: SequenceImpl = dataType.elementType match {
+ case iType: IntegralType =>
+ type T = iType.InternalType
+ val ct = ClassTag[T](iType.tag.mirror.runtimeClass(iType.tag.tpe))
+ new IntegralSequenceImpl(iType)(ct, iType.integral)
+
+ case TimestampType =>
+ new TemporalSequenceImpl[Long](LongType, 1, identity, timeZone)
+
+ case DateType =>
+ new TemporalSequenceImpl[Int](IntegerType, MICROS_PER_DAY, _.toInt, timeZone)
+ }
+
+ override def eval(input: InternalRow): Any = {
+ val startVal = start.eval(input)
+ if (startVal == null) return null
+ val stopVal = stop.eval(input)
+ if (stopVal == null) return null
+ val stepVal = stepOpt.map(_.eval(input)).getOrElse(impl.defaultStep(startVal, stopVal))
+ if (stepVal == null) return null
+
+ ArrayData.toArrayData(impl.eval(startVal, stopVal, stepVal))
+ }
+
+ override protected def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = {
+ val startGen = start.genCode(ctx)
+ val stopGen = stop.genCode(ctx)
+ val stepGen = stepOpt.map(_.genCode(ctx)).getOrElse(
+ impl.defaultStep.genCode(ctx, startGen, stopGen))
+
+ val resultType = CodeGenerator.javaType(dataType)
+ val resultCode = {
+ val arr = ctx.freshName("arr")
+ val arrElemType = CodeGenerator.javaType(dataType.elementType)
+ s"""
+ |final $arrElemType[] $arr = null;
+ |${impl.genCode(ctx, startGen.value, stopGen.value, stepGen.value, arr, arrElemType)}
+ |${ev.value} = UnsafeArrayData.fromPrimitiveArray($arr);
+ """.stripMargin
+ }
+
+ if (nullable) {
+ val nullSafeEval =
+ startGen.code + ctx.nullSafeExec(start.nullable, startGen.isNull) {
+ stopGen.code + ctx.nullSafeExec(stop.nullable, stopGen.isNull) {
+ stepGen.code + ctx.nullSafeExec(stepOpt.exists(_.nullable), stepGen.isNull) {
+ s"""
+ |${ev.isNull} = false;
+ |$resultCode
+ """.stripMargin
+ }
+ }
+ }
+ ev.copy(code =
+ s"""
+ |boolean ${ev.isNull} = true;
+ |$resultType ${ev.value} = null;
+ |$nullSafeEval
+ """.stripMargin)
+
+ } else {
+ ev.copy(code =
+ s"""
+ |boolean ${ev.isNull} = false;
+ |${startGen.code}
+ |${stopGen.code}
+ |${stepGen.code}
+ |$resultType ${ev.value} = null;
+ |$resultCode
+ """.stripMargin,
+ isNull = FalseLiteral)
+ }
+ }
+}
+
+object Sequence {
+
+ private type LessThanOrEqualFn = (Any, Any) => Boolean
+
+ private class DefaultStep(lteq: LessThanOrEqualFn, stepType: DataType, one: Any) {
+ private val negativeOne = UnaryMinus(Literal(one)).eval()
+
+ def apply(start: Any, stop: Any): Any = {
+ if (lteq(start, stop)) one else negativeOne
+ }
+
+ def genCode(ctx: CodegenContext, startGen: ExprCode, stopGen: ExprCode): ExprCode = {
+ val Seq(oneVal, negativeOneVal) = Seq(one, negativeOne).map(Literal(_).genCode(ctx).value)
+ ExprCode.forNonNullValue(JavaCode.expression(
+ s"${startGen.value} <= ${stopGen.value} ? $oneVal : $negativeOneVal",
+ stepType))
+ }
+ }
+
+ private trait SequenceImpl {
+ def eval(start: Any, stop: Any, step: Any): Any
+
+ def genCode(
+ ctx: CodegenContext,
+ start: String,
+ stop: String,
+ step: String,
+ arr: String,
+ elemType: String): String
+
+ val defaultStep: DefaultStep
+ }
+
+ private class IntegralSequenceImpl[T: ClassTag]
+ (elemType: IntegralType)(implicit num: Integral[T]) extends SequenceImpl {
+
+ override val defaultStep: DefaultStep = new DefaultStep(
+ (elemType.ordering.lteq _).asInstanceOf[LessThanOrEqualFn],
+ elemType,
+ num.one)
+
+ override def eval(input1: Any, input2: Any, input3: Any): Array[T] = {
+ import num._
+
+ val start = input1.asInstanceOf[T]
+ val stop = input2.asInstanceOf[T]
+ val step = input3.asInstanceOf[T]
+
+ var i: Int = getSequenceLength(start, stop, step)
+ val arr = new Array[T](i)
+ while (i > 0) {
+ i -= 1
+ arr(i) = start + step * num.fromInt(i)
+ }
+ arr
+ }
+
+ override def genCode(
+ ctx: CodegenContext,
+ start: String,
+ stop: String,
+ step: String,
+ arr: String,
+ elemType: String): String = {
+ val i = ctx.freshName("i")
+ s"""
+ |${genSequenceLengthCode(ctx, start, stop, step, i)}
+ |$arr = new $elemType[$i];
+ |while ($i > 0) {
+ | $i--;
+ | $arr[$i] = ($elemType) ($start + $step * $i);
+ |}
+ """.stripMargin
+ }
+ }
+
+ private class TemporalSequenceImpl[T: ClassTag]
+ (dt: IntegralType, scale: Long, fromLong: Long => T, timeZone: TimeZone)
+ (implicit num: Integral[T]) extends SequenceImpl {
+
+ override val defaultStep: DefaultStep = new DefaultStep(
+ (dt.ordering.lteq _).asInstanceOf[LessThanOrEqualFn],
+ CalendarIntervalType,
+ new CalendarInterval(0, MICROS_PER_DAY))
+
+ private val backedSequenceImpl = new IntegralSequenceImpl[T](dt)
+ private val microsPerMonth = 28 * CalendarInterval.MICROS_PER_DAY
+
+ override def eval(input1: Any, input2: Any, input3: Any): Array[T] = {
+ val start = input1.asInstanceOf[T]
+ val stop = input2.asInstanceOf[T]
+ val step = input3.asInstanceOf[CalendarInterval]
+ val stepMonths = step.months
+ val stepMicros = step.microseconds
+
+ if (stepMonths == 0) {
+ backedSequenceImpl.eval(start, stop, fromLong(stepMicros / scale))
+
+ } else {
+ // To estimate the resulted array length we need to make assumptions
+ // about a month length in microseconds
+ val intervalStepInMicros = stepMicros + stepMonths * microsPerMonth
+ val startMicros: Long = num.toLong(start) * scale
+ val stopMicros: Long = num.toLong(stop) * scale
+ val maxEstimatedArrayLength =
+ getSequenceLength(startMicros, stopMicros, intervalStepInMicros)
+
+ val stepSign = if (stopMicros > startMicros) +1 else -1
+ val exclusiveItem = stopMicros + stepSign
+ val arr = new Array[T](maxEstimatedArrayLength)
+ var t = startMicros
+ var i = 0
+
+ while (t < exclusiveItem ^ stepSign < 0) {
+ arr(i) = fromLong(t / scale)
+ t = timestampAddInterval(t, stepMonths, stepMicros, timeZone)
+ i += 1
+ }
+
+ // truncate array to the correct length
+ if (arr.length == i) arr else arr.slice(0, i)
+ }
+ }
+
+ override def genCode(
+ ctx: CodegenContext,
+ start: String,
+ stop: String,
+ step: String,
+ arr: String,
+ elemType: String): String = {
+ val stepMonths = ctx.freshName("stepMonths")
+ val stepMicros = ctx.freshName("stepMicros")
+ val stepScaled = ctx.freshName("stepScaled")
+ val intervalInMicros = ctx.freshName("intervalInMicros")
+ val startMicros = ctx.freshName("startMicros")
+ val stopMicros = ctx.freshName("stopMicros")
+ val arrLength = ctx.freshName("arrLength")
+ val stepSign = ctx.freshName("stepSign")
+ val exclusiveItem = ctx.freshName("exclusiveItem")
+ val t = ctx.freshName("t")
+ val i = ctx.freshName("i")
+ val genTimeZone = ctx.freshName("timeZone")
+
+ val sequenceLengthCode =
+ s"""
+ |final long $intervalInMicros = $stepMicros + $stepMonths * ${microsPerMonth}L;
+ |${genSequenceLengthCode(ctx, startMicros, stopMicros, intervalInMicros, arrLength)}
+ """.stripMargin
+
+ val timestampAddIntervalCode =
+ s"""
+ |$t = org.apache.spark.sql.catalyst.util.DateTimeUtils.timestampAddInterval(
+ | $t, $stepMonths, $stepMicros, $genTimeZone);
+ """.stripMargin
+
+ s"""
+ |final int $stepMonths = $step.months;
+ |final long $stepMicros = $step.microseconds;
+ |
+ |if ($stepMonths == 0) {
+ | final $elemType $stepScaled = ($elemType) ($stepMicros / ${scale}L);
+ | ${backedSequenceImpl.genCode(ctx, start, stop, stepScaled, arr, elemType)};
+ |
+ |} else {
+ | final long $startMicros = $start * ${scale}L;
+ | final long $stopMicros = $stop * ${scale}L;
+ |
+ | $sequenceLengthCode
+ |
+ | final int $stepSign = $stopMicros > $startMicros ? +1 : -1;
+ | final long $exclusiveItem = $stopMicros + $stepSign;
+ | final java.util.TimeZone $genTimeZone =
+ | java.util.TimeZone.getTimeZone("${timeZone.getID}");
--- End diff --
We should use `ctx.addReferenctObj("timeZone", timeZone)` instead to follow the implementations of datetime expressions? Doing `TimeZone.getTimeZone()` for every row should be slow.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: SPARK-23927: Add "sequence" expression
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:
https://github.com/apache/spark/pull/21155
Test FAILed.
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/89852/
Test FAILed.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:
https://github.com/apache/spark/pull/21155
Merged build finished. Test FAILed.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:
https://github.com/apache/spark/pull/21155
Test PASSed.
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/90909/
Test PASSed.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:
https://github.com/apache/spark/pull/21155
**[Test build #90329 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/90329/testReport)** for PR 21155 at commit [`8786192`](https://github.com/apache/spark/commit/878619276592d189d69d9c6ed259f3d7d1f6fa48).
* This patch passes all tests.
* This patch merges cleanly.
* This patch adds no public classes.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: SPARK-23927: Add "sequence" expression
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:
https://github.com/apache/spark/pull/21155
Test FAILed.
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/89851/
Test FAILed.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:
https://github.com/apache/spark/pull/21155
Test FAILed.
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/90892/
Test FAILed.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by ueshin <gi...@git.apache.org>.
Github user ueshin commented on a diff in the pull request:
https://github.com/apache/spark/pull/21155#discussion_r197672902
--- Diff: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/collectionOperations.scala ---
@@ -1887,6 +1889,402 @@ case class Flatten(child: Expression) extends UnaryExpression {
override def prettyName: String = "flatten"
}
+@ExpressionDescription(
+ usage = """
+ _FUNC_(start, stop, step) - Generates an array of elements from start to stop (inclusive),
+ incrementing by step. The type of the returned elements is the same as the type of argument
+ expressions.
+
+ Supported types are: byte, short, integer, long, date, timestamp.
+
+ The start and stop expressions must resolve to the same type.
+ If start and stop expressions resolve to the 'date' or 'timestamp' type
+ then the step expression must resolve to the 'interval' type, otherwise to the same type
+ as the start and stop expressions.
+ """,
+ arguments = """
+ Arguments:
+ * start - an expression. The start of the range.
+ * stop - an expression. The end the range (inclusive).
+ * step - an optional expression. The step of the range.
+ By default step is 1 if start is less than or equal to stop, otherwise -1.
+ For the temporal sequences it's 1 day and -1 day respectively.
+ If start is greater than stop then the step must be negative, and vice versa.
+ """,
+ examples = """
+ Examples:
+ > SELECT _FUNC_(1, 5);
+ [1, 2, 3, 4, 5]
+ > SELECT _FUNC_(5, 1);
+ [5, 4, 3, 2, 1]
+ > SELECT _FUNC_(to_date('2018-01-01'), to_date('2018-03-01'), interval 1 month);
+ [2018-01-01, 2018-02-01, 2018-03-01]
+ """,
+ since = "2.4.0"
+)
+case class Sequence(
+ start: Expression,
+ stop: Expression,
+ stepOpt: Option[Expression],
+ timeZoneId: Option[String] = None)
+ extends Expression
+ with TimeZoneAwareExpression {
+
+ import Sequence._
+
+ def this(start: Expression, stop: Expression) =
+ this(start, stop, None, None)
+
+ def this(start: Expression, stop: Expression, step: Expression) =
+ this(start, stop, Some(step), None)
+
+ override def withTimeZone(timeZoneId: String): TimeZoneAwareExpression =
+ copy(timeZoneId = Some(timeZoneId))
+
+ override def children: Seq[Expression] = Seq(start, stop) ++ stepOpt
+
+ override def foldable: Boolean = children.forall(_.foldable)
+
+ override def nullable: Boolean = children.exists(_.nullable)
+
+ override lazy val dataType: ArrayType = ArrayType(start.dataType, containsNull = false)
+
+ override def checkInputDataTypes(): TypeCheckResult = {
+ val startType = start.dataType
+ def stepType = stepOpt.get.dataType
+ val typesCorrect =
+ startType.sameType(stop.dataType) &&
+ (startType match {
+ case TimestampType | DateType =>
+ stepOpt.isEmpty || CalendarIntervalType.acceptsType(stepType)
+ case _: IntegralType =>
+ stepOpt.isEmpty || stepType.sameType(startType)
+ case _ => false
+ })
+
+ if (typesCorrect) {
+ TypeCheckResult.TypeCheckSuccess
+ } else {
+ TypeCheckResult.TypeCheckFailure(
+ s"$prettyName only supports integral, timestamp or date types")
+ }
+ }
+
+ def coercibleChildren: Seq[Expression] = children.filter(_.dataType != CalendarIntervalType)
+
+ def castChildrenTo(widerType: DataType): Expression = Sequence(
--- End diff --
I just wanted to confirm if we can use `withNewChildren` or not, and it's okay to use the copy constructor if it's hard to use the method.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:
https://github.com/apache/spark/pull/21155
Build finished. Test FAILed.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: SPARK-23927: Add "sequence" expression
Posted by gatorsmile <gi...@git.apache.org>.
Github user gatorsmile commented on the issue:
https://github.com/apache/spark/pull/21155
ok to test
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: SPARK-23927: Add "sequence" expression
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:
https://github.com/apache/spark/pull/21155
Test PASSed.
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/89860/
Test PASSed.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:
https://github.com/apache/spark/pull/21155
**[Test build #90428 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/90428/testReport)** for PR 21155 at commit [`22bde31`](https://github.com/apache/spark/commit/22bde31feab95e548351a6057f5286c6faf75695).
* This patch passes all tests.
* This patch merges cleanly.
* This patch adds no public classes.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by ueshin <gi...@git.apache.org>.
Github user ueshin commented on the issue:
https://github.com/apache/spark/pull/21155
Jenkins, retest this please.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by wajda <gi...@git.apache.org>.
Github user wajda commented on a diff in the pull request:
https://github.com/apache/spark/pull/21155#discussion_r186479450
--- Diff: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/collectionOperations.scala ---
@@ -1059,3 +1063,316 @@ case class Flatten(child: Expression) extends UnaryExpression {
override def prettyName: String = "flatten"
}
+
+@ExpressionDescription(
+ usage = """
+ _FUNC_(start, stop, step) -
+ Generates an array of elements from start to stop (inclusive), incrementing by step.
+ The type of the returned elements is the same as the type of argument expressions.
+
+ Supported types are: byte, short, integer, long, date, timestamp.
+
+ The start and stop expressions must resolve to the same type.
+ If start and stop expressions resolve to the 'date' or 'timestamp' type
+ then the step expression must resolve to the 'interval' type, otherwise to the same type
+ as the start and stop expressions.
+ """,
+ arguments = """
+ Arguments:
+ * start - an expression. The start of the range.
+ * stop - an expression. The end the range (inclusive).
+ * step - an optional expression. The step of the range.
+
+ By default step is 1 if start is less than or equal to stop, otherwise -1.
+ For the temporal sequences it's 1 day and -1 day respectively.
+
+ If start is greater than stop then the step must be negative, and vice versa.
+ """,
+ examples = """
+ Examples:
+ > SELECT _FUNC_(1, 5);
+ [1, 2, 3, 4, 5]
+ > SELECT _FUNC_(5, 1);
+ [5, 4, 3, 2, 1]
+ > SELECT _FUNC_(to_date('2018-01-01'), to_date('2018-03-01'), interval 1 month);
+ [2018-01-01, 2018-02-01, 2018-03-01]
+ """,
+ since = "2.4.0"
+)
+case class Sequence(left: Expression,
+ middle: Expression,
+ right: Expression,
+ timeZoneId: Option[String] = None)
+ extends TernaryExpression with TimeZoneAwareExpression {
--- End diff --
Changed to ```Option[Expression]```, removed ```UnresolvedLiteral```. Thanks for suggestion.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: SPARK-23927: Add "sequence" expression
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:
https://github.com/apache/spark/pull/21155
Merged build finished. Test PASSed.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by ueshin <gi...@git.apache.org>.
Github user ueshin commented on a diff in the pull request:
https://github.com/apache/spark/pull/21155#discussion_r197676498
--- Diff: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/collectionOperations.scala ---
@@ -2288,6 +2288,401 @@ case class Flatten(child: Expression) extends UnaryExpression {
override def prettyName: String = "flatten"
}
+@ExpressionDescription(
+ usage = """
+ _FUNC_(start, stop, step) - Generates an array of elements from start to stop (inclusive),
+ incrementing by step. The type of the returned elements is the same as the type of argument
+ expressions.
+
+ Supported types are: byte, short, integer, long, date, timestamp.
+
+ The start and stop expressions must resolve to the same type.
+ If start and stop expressions resolve to the 'date' or 'timestamp' type
+ then the step expression must resolve to the 'interval' type, otherwise to the same type
+ as the start and stop expressions.
+ """,
+ arguments = """
+ Arguments:
+ * start - an expression. The start of the range.
+ * stop - an expression. The end the range (inclusive).
+ * step - an optional expression. The step of the range.
+ By default step is 1 if start is less than or equal to stop, otherwise -1.
+ For the temporal sequences it's 1 day and -1 day respectively.
+ If start is greater than stop then the step must be negative, and vice versa.
+ """,
+ examples = """
+ Examples:
+ > SELECT _FUNC_(1, 5);
+ [1, 2, 3, 4, 5]
+ > SELECT _FUNC_(5, 1);
+ [5, 4, 3, 2, 1]
+ > SELECT _FUNC_(to_date('2018-01-01'), to_date('2018-03-01'), interval 1 month);
+ [2018-01-01, 2018-02-01, 2018-03-01]
+ """,
+ since = "2.4.0"
+)
+case class Sequence(
+ start: Expression,
+ stop: Expression,
+ stepOpt: Option[Expression],
+ timeZoneId: Option[String] = None)
+ extends Expression
+ with TimeZoneAwareExpression {
+
+ import Sequence._
+
+ def this(start: Expression, stop: Expression) =
+ this(start, stop, None, None)
+
+ def this(start: Expression, stop: Expression, step: Expression) =
+ this(start, stop, Some(step), None)
+
+ override def withTimeZone(timeZoneId: String): TimeZoneAwareExpression =
+ copy(timeZoneId = Some(timeZoneId))
+
+ override def children: Seq[Expression] = Seq(start, stop) ++ stepOpt
+
+ override def foldable: Boolean = children.forall(_.foldable)
+
+ override def nullable: Boolean = children.exists(_.nullable)
+
+ override lazy val dataType: ArrayType = ArrayType(start.dataType, containsNull = false)
+
+ override def checkInputDataTypes(): TypeCheckResult = {
+ val startType = start.dataType
+ def stepType = stepOpt.get.dataType
+ val typesCorrect =
+ startType.sameType(stop.dataType) &&
+ (startType match {
+ case TimestampType | DateType =>
+ stepOpt.isEmpty || CalendarIntervalType.acceptsType(stepType)
+ case _: IntegralType =>
+ stepOpt.isEmpty || stepType.sameType(startType)
+ case _ => false
+ })
+
+ if (typesCorrect) {
+ TypeCheckResult.TypeCheckSuccess
+ } else {
+ TypeCheckResult.TypeCheckFailure(
+ s"$prettyName only supports integral, timestamp or date types")
+ }
+ }
+
+ def coercibleChildren: Seq[Expression] = children.filter(_.dataType != CalendarIntervalType)
+
+ def castChildrenTo(widerType: DataType): Expression = Sequence(
+ Cast(start, widerType),
+ Cast(stop, widerType),
+ stepOpt.map(step => if (step.dataType != CalendarIntervalType) Cast(step, widerType) else step),
+ timeZoneId)
+
+ private lazy val impl: SequenceImpl = dataType.elementType match {
+ case iType: IntegralType =>
+ type T = iType.InternalType
+ val ct = ClassTag[T](iType.tag.mirror.runtimeClass(iType.tag.tpe))
+ new IntegralSequenceImpl(iType)(ct, iType.integral)
+
+ case TimestampType =>
+ new TemporalSequenceImpl[Long](LongType, 1, identity, timeZone)
+
+ case DateType =>
+ new TemporalSequenceImpl[Int](IntegerType, MICROS_PER_DAY, _.toInt, timeZone)
+ }
+
+ override def eval(input: InternalRow): Any = {
+ val startVal = start.eval(input)
+ if (startVal == null) return null
+ val stopVal = stop.eval(input)
+ if (stopVal == null) return null
+ val stepVal = stepOpt.map(_.eval(input)).getOrElse(impl.defaultStep(startVal, stopVal))
+ if (stepVal == null) return null
+
+ ArrayData.toArrayData(impl.eval(startVal, stopVal, stepVal))
+ }
+
+ override protected def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = {
+ val startGen = start.genCode(ctx)
+ val stopGen = stop.genCode(ctx)
+ val stepGen = stepOpt.map(_.genCode(ctx)).getOrElse(
+ impl.defaultStep.genCode(ctx, startGen, stopGen))
+
+ val resultType = CodeGenerator.javaType(dataType)
+ val resultCode = {
+ val arr = ctx.freshName("arr")
+ val arrElemType = CodeGenerator.javaType(dataType.elementType)
+ s"""
+ |final $arrElemType[] $arr = null;
+ |${impl.genCode(ctx, startGen.value, stopGen.value, stepGen.value, arr, arrElemType)}
+ |${ev.value} = UnsafeArrayData.fromPrimitiveArray($arr);
+ """.stripMargin
+ }
+
+ if (nullable) {
+ val nullSafeEval =
+ startGen.code + ctx.nullSafeExec(start.nullable, startGen.isNull) {
+ stopGen.code + ctx.nullSafeExec(stop.nullable, stopGen.isNull) {
+ stepGen.code + ctx.nullSafeExec(stepOpt.exists(_.nullable), stepGen.isNull) {
+ s"""
+ |${ev.isNull} = false;
+ |$resultCode
+ """.stripMargin
+ }
+ }
+ }
+ ev.copy(code =
+ code"""
+ |boolean ${ev.isNull} = true;
+ |$resultType ${ev.value} = null;
+ |$nullSafeEval
+ """.stripMargin)
+
+ } else {
+ ev.copy(code =
+ code"""
+ |${startGen.code}
+ |${stopGen.code}
+ |${stepGen.code}
+ |$resultType ${ev.value} = null;
+ |$resultCode
+ """.stripMargin,
+ isNull = FalseLiteral)
+ }
+ }
+}
+
+object Sequence {
+
+ private type LessThanOrEqualFn = (Any, Any) => Boolean
+
+ private class DefaultStep(lteq: LessThanOrEqualFn, stepType: DataType, one: Any) {
+ private val negativeOne = UnaryMinus(Literal(one)).eval()
+
+ def apply(start: Any, stop: Any): Any = {
+ if (lteq(start, stop)) one else negativeOne
+ }
+
+ def genCode(ctx: CodegenContext, startGen: ExprCode, stopGen: ExprCode): ExprCode = {
+ val Seq(oneVal, negativeOneVal) = Seq(one, negativeOne).map(Literal(_).genCode(ctx).value)
+ ExprCode.forNonNullValue(JavaCode.expression(
+ s"${startGen.value} <= ${stopGen.value} ? $oneVal : $negativeOneVal",
+ stepType))
+ }
+ }
+
+ private trait SequenceImpl {
+ def eval(start: Any, stop: Any, step: Any): Any
+
+ def genCode(
+ ctx: CodegenContext,
+ start: String,
+ stop: String,
+ step: String,
+ arr: String,
+ elemType: String): String
+
+ val defaultStep: DefaultStep
+ }
+
+ private class IntegralSequenceImpl[T: ClassTag]
+ (elemType: IntegralType)(implicit num: Integral[T]) extends SequenceImpl {
+
+ override val defaultStep: DefaultStep = new DefaultStep(
+ (elemType.ordering.lteq _).asInstanceOf[LessThanOrEqualFn],
+ elemType,
+ num.one)
+
+ override def eval(input1: Any, input2: Any, input3: Any): Array[T] = {
+ import num._
+
+ val start = input1.asInstanceOf[T]
+ val stop = input2.asInstanceOf[T]
+ val step = input3.asInstanceOf[T]
+
+ var i: Int = getSequenceLength(start, stop, step)
+ val arr = new Array[T](i)
+ while (i > 0) {
+ i -= 1
+ arr(i) = start + step * num.fromInt(i)
+ }
+ arr
+ }
+
+ override def genCode(
+ ctx: CodegenContext,
+ start: String,
+ stop: String,
+ step: String,
+ arr: String,
+ elemType: String): String = {
+ val i = ctx.freshName("i")
+ s"""
+ |${genSequenceLengthCode(ctx, start, stop, step, i)}
+ |$arr = new $elemType[$i];
+ |while ($i > 0) {
+ | $i--;
+ | $arr[$i] = ($elemType) ($start + $step * $i);
+ |}
+ """.stripMargin
+ }
+ }
+
+ private class TemporalSequenceImpl[T: ClassTag]
+ (dt: IntegralType, scale: Long, fromLong: Long => T, timeZone: TimeZone)
+ (implicit num: Integral[T]) extends SequenceImpl {
+
+ override val defaultStep: DefaultStep = new DefaultStep(
+ (dt.ordering.lteq _).asInstanceOf[LessThanOrEqualFn],
+ CalendarIntervalType,
+ new CalendarInterval(0, MICROS_PER_DAY))
+
+ private val backedSequenceImpl = new IntegralSequenceImpl[T](dt)
+ private val microsPerMonth = 28 * CalendarInterval.MICROS_PER_DAY
+
+ override def eval(input1: Any, input2: Any, input3: Any): Array[T] = {
+ val start = input1.asInstanceOf[T]
+ val stop = input2.asInstanceOf[T]
+ val step = input3.asInstanceOf[CalendarInterval]
+ val stepMonths = step.months
+ val stepMicros = step.microseconds
+
+ if (stepMonths == 0) {
+ backedSequenceImpl.eval(start, stop, fromLong(stepMicros / scale))
+
+ } else {
+ // To estimate the resulted array length we need to make assumptions
+ // about a month length in microseconds
+ val intervalStepInMicros = stepMicros + stepMonths * microsPerMonth
+ val startMicros: Long = num.toLong(start) * scale
+ val stopMicros: Long = num.toLong(stop) * scale
+ val maxEstimatedArrayLength =
+ getSequenceLength(startMicros, stopMicros, intervalStepInMicros)
+
+ val stepSign = if (stopMicros > startMicros) +1 else -1
+ val exclusiveItem = stopMicros + stepSign
+ val arr = new Array[T](maxEstimatedArrayLength)
+ var t = startMicros
+ var i = 0
+
+ while (t < exclusiveItem ^ stepSign < 0) {
+ arr(i) = fromLong(t / scale)
+ t = timestampAddInterval(t, stepMonths, stepMicros, timeZone)
+ i += 1
+ }
+
+ // truncate array to the correct length
+ if (arr.length == i) arr else arr.slice(0, i)
+ }
+ }
+
+ override def genCode(
+ ctx: CodegenContext,
+ start: String,
+ stop: String,
+ step: String,
+ arr: String,
+ elemType: String): String = {
+ val stepMonths = ctx.freshName("stepMonths")
+ val stepMicros = ctx.freshName("stepMicros")
+ val stepScaled = ctx.freshName("stepScaled")
+ val intervalInMicros = ctx.freshName("intervalInMicros")
+ val startMicros = ctx.freshName("startMicros")
+ val stopMicros = ctx.freshName("stopMicros")
+ val arrLength = ctx.freshName("arrLength")
+ val stepSign = ctx.freshName("stepSign")
+ val exclusiveItem = ctx.freshName("exclusiveItem")
+ val t = ctx.freshName("t")
+ val i = ctx.freshName("i")
+ val genTimeZone = ctx.addReferenceObj("timeZone", timeZone, classOf[TimeZone].getName)
+
+ val sequenceLengthCode =
+ s"""
+ |final long $intervalInMicros = $stepMicros + $stepMonths * ${microsPerMonth}L;
+ |${genSequenceLengthCode(ctx, startMicros, stopMicros, intervalInMicros, arrLength)}
+ """.stripMargin
+
+ val timestampAddIntervalCode =
+ s"""
+ |$t = org.apache.spark.sql.catalyst.util.DateTimeUtils.timestampAddInterval(
+ | $t, $stepMonths, $stepMicros, $genTimeZone);
+ """.stripMargin
+
+ s"""
+ |final int $stepMonths = $step.months;
+ |final long $stepMicros = $step.microseconds;
+ |
+ |if ($stepMonths == 0) {
+ | final $elemType $stepScaled = ($elemType) ($stepMicros / ${scale}L);
+ | ${backedSequenceImpl.genCode(ctx, start, stop, stepScaled, arr, elemType)};
+ |
+ |} else {
+ | final long $startMicros = $start * ${scale}L;
+ | final long $stopMicros = $stop * ${scale}L;
+ |
+ | $sequenceLengthCode
+ |
+ | final int $stepSign = $stopMicros > $startMicros ? +1 : -1;
+ | final long $exclusiveItem = $stopMicros + $stepSign;
+ |
+ | $arr = new $elemType[$arrLength];
+ | long $t = $startMicros;
+ | int $i = 0;
+ |
+ | while ($t < $exclusiveItem ^ $stepSign < 0) {
+ | $arr[$i] = ($elemType) ($t / ${scale}L);
+ | $timestampAddIntervalCode
+ | $i += 1;
+ | }
+ |
+ | if ($arr.length > $i) {
+ | $arr = java.util.Arrays.copyOf($arr, $i);
+ | }
+ |}
+ """.stripMargin
+ }
+ }
+
+ private def getSequenceLength[U](start: U, stop: U, step: U)(implicit num: Integral[U]): Int = {
+ import num._
+ require(
+ (step > num.zero && start <= stop)
+ || (step < num.zero && start >= stop)
+ || (step == 0 && start == stop),
+ s"Illegal sequence boundaries: $start to $stop by $step")
+
+ val len = if (start == stop) 1L else 1L + (stop.toLong - start.toLong) / step.toLong
+
+ require(
+ len <= MAX_ROUNDED_ARRAY_LENGTH,
+ s"Too long sequence: $len. Should be <= $MAX_ROUNDED_ARRAY_LENGTH")
+
+ len.toInt
+ }
+
+ private def genSequenceLengthCode(
+ ctx: CodegenContext,
+ start: String,
+ stop: String,
+ step: String,
+ len: String): String = {
+ val longLen = ctx.freshName("longLen")
+ s"""
+ |if (!(($step > 0 && $start <= $stop) ||
+ | ($step < 0 && $start >= $stop) ||
+ | ($step == 0 && $start == $stop))) {
+ | throw new IllegalArgumentException(
+ | "Illegal sequence boundaries: " + $start + " to " + $stop + " by " + $step);
+ |}
+ |long $longLen = $stop == $start ? 1L : 1L + ((long) $stop - $start) / $step;
+ |if ($longLen > Integer.MAX_VALUE) {
--- End diff --
`MAX_ROUNDED_ARRAY_LENGTH` instead of `Integer.MAX_VALUE`?
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by wajda <gi...@git.apache.org>.
Github user wajda commented on a diff in the pull request:
https://github.com/apache/spark/pull/21155#discussion_r186134394
--- Diff: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/collectionOperations.scala ---
@@ -1059,3 +1063,316 @@ case class Flatten(child: Expression) extends UnaryExpression {
override def prettyName: String = "flatten"
}
+
+@ExpressionDescription(
+ usage = """
+ _FUNC_(start, stop, step) -
+ Generates an array of elements from start to stop (inclusive), incrementing by step.
+ The type of the returned elements is the same as the type of argument expressions.
+
+ Supported types are: byte, short, integer, long, date, timestamp.
+
+ The start and stop expressions must resolve to the same type.
+ If start and stop expressions resolve to the 'date' or 'timestamp' type
+ then the step expression must resolve to the 'interval' type, otherwise to the same type
+ as the start and stop expressions.
+ """,
+ arguments = """
+ Arguments:
+ * start - an expression. The start of the range.
+ * stop - an expression. The end the range (inclusive).
+ * step - an optional expression. The step of the range.
+
+ By default step is 1 if start is less than or equal to stop, otherwise -1.
+ For the temporal sequences it's 1 day and -1 day respectively.
+
+ If start is greater than stop then the step must be negative, and vice versa.
+ """,
+ examples = """
+ Examples:
+ > SELECT _FUNC_(1, 5);
+ [1, 2, 3, 4, 5]
+ > SELECT _FUNC_(5, 1);
+ [5, 4, 3, 2, 1]
+ > SELECT _FUNC_(to_date('2018-01-01'), to_date('2018-03-01'), interval 1 month);
+ [2018-01-01, 2018-02-01, 2018-03-01]
+ """,
+ since = "2.4.0"
+)
+case class Sequence(left: Expression,
+ middle: Expression,
+ right: Expression,
+ timeZoneId: Option[String] = None)
+ extends TernaryExpression with TimeZoneAwareExpression {
+
+ import Sequence._
+
+ def this(arg0: Expression, arg1: Expression) =
+ this(arg0, arg1, Sequence.defaultStepExpression(arg0, arg1), None)
+
+ def this(arg0: Expression, arg1: Expression, arg2: Expression) =
+ this(arg0, arg1, arg2, None)
+
+ override def withTimeZone(timeZoneId: String): TimeZoneAwareExpression =
+ copy(timeZoneId = Some(timeZoneId))
+
+ override def children: Seq[Expression] = Seq(left, middle, right)
+
+ override lazy val dataType: ArrayType = ArrayType(left.dataType, containsNull = false)
+
+ override def checkInputDataTypes(): TypeCheckResult = {
+ val Seq(startType, stopType, stepType) = children.map(_.dataType)
+ val typesCorrect =
+ startType.sameType(stopType) &&
+ (startType match {
+ case TimestampType | DateType => CalendarIntervalType acceptsType stepType
+ case _: IntegralType => stepType sameType startType
+ case _ => false
+ })
+
+ if (typesCorrect) {
+ TypeCheckResult.TypeCheckSuccess
+ } else {
+ TypeCheckResult.TypeCheckFailure(
+ s"$prettyName only supports integral, timestamp or date types")
+ }
+ }
+
+ private lazy val impl: SequenceImpl = dataType.elementType match {
+ case iType: IntegralType =>
+ type T = iType.InternalType
+ val ct = ClassTag[T](iType.tag.mirror.runtimeClass(iType.tag.tpe))
+ new IntegralSequenceImpl()(ct, iType.integral)
+
+ case TimestampType =>
+ new TemporalSequenceImpl[Long](LongType, 1, identity, timeZone)
+
+ case DateType =>
+ new TemporalSequenceImpl[Int](IntegerType, MICROS_PER_DAY, _.toInt, timeZone)
+ }
+
+ override protected def nullSafeEval(input1: Any, input2: Any, input3: Any): Any = {
+ ArrayData.toArrayData(impl.eval(input1, input2, input3))
+ }
+
+ override protected def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = {
+ nullSafeCodeGen(ctx, ev, (start, stop, step) => {
+ val arr = ctx.freshName("arr")
+ val arrElemType = CodeGenerator.javaType(dataType.elementType)
+ s"""
+ | final $arrElemType[] $arr = null;
+ | ${impl.genCode(start, stop, step)(arr, arrElemType)(ctx)}
+ | ${ev.value} = UnsafeArrayData.fromPrimitiveArray($arr);
+ """.stripMargin
+ })
+ }
+}
+
+object Sequence {
+
+ private trait SequenceImpl {
+ def eval(input1: Any, input2: Any, input3: Any): Any
+
+ def genCode(start: String, stop: String, step: String)
+ (arr: String, elemType: String)
+ (implicit ctx: CodegenContext): String
+ }
+
+ private class IntegralSequenceImpl[T: ClassTag]
--- End diff --
If using that syntax where would I take ```Integral[T]``` instance to call methods ```fromInt(), toLong(), zero, one``` on?
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by ueshin <gi...@git.apache.org>.
Github user ueshin commented on a diff in the pull request:
https://github.com/apache/spark/pull/21155#discussion_r193926459
--- Diff: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/collectionOperations.scala ---
@@ -1887,6 +1889,402 @@ case class Flatten(child: Expression) extends UnaryExpression {
override def prettyName: String = "flatten"
}
+@ExpressionDescription(
+ usage = """
+ _FUNC_(start, stop, step) - Generates an array of elements from start to stop (inclusive),
+ incrementing by step. The type of the returned elements is the same as the type of argument
+ expressions.
+
+ Supported types are: byte, short, integer, long, date, timestamp.
+
+ The start and stop expressions must resolve to the same type.
+ If start and stop expressions resolve to the 'date' or 'timestamp' type
+ then the step expression must resolve to the 'interval' type, otherwise to the same type
+ as the start and stop expressions.
+ """,
+ arguments = """
+ Arguments:
+ * start - an expression. The start of the range.
+ * stop - an expression. The end the range (inclusive).
+ * step - an optional expression. The step of the range.
+ By default step is 1 if start is less than or equal to stop, otherwise -1.
+ For the temporal sequences it's 1 day and -1 day respectively.
+ If start is greater than stop then the step must be negative, and vice versa.
+ """,
+ examples = """
+ Examples:
+ > SELECT _FUNC_(1, 5);
+ [1, 2, 3, 4, 5]
+ > SELECT _FUNC_(5, 1);
+ [5, 4, 3, 2, 1]
+ > SELECT _FUNC_(to_date('2018-01-01'), to_date('2018-03-01'), interval 1 month);
+ [2018-01-01, 2018-02-01, 2018-03-01]
+ """,
+ since = "2.4.0"
+)
+case class Sequence(
+ start: Expression,
+ stop: Expression,
+ stepOpt: Option[Expression],
+ timeZoneId: Option[String] = None)
+ extends Expression
+ with TimeZoneAwareExpression {
+
+ import Sequence._
+
+ def this(start: Expression, stop: Expression) =
+ this(start, stop, None, None)
+
+ def this(start: Expression, stop: Expression, step: Expression) =
+ this(start, stop, Some(step), None)
+
+ override def withTimeZone(timeZoneId: String): TimeZoneAwareExpression =
+ copy(timeZoneId = Some(timeZoneId))
+
+ override def children: Seq[Expression] = Seq(start, stop) ++ stepOpt
+
+ override def foldable: Boolean = children.forall(_.foldable)
+
+ override def nullable: Boolean = children.exists(_.nullable)
+
+ override lazy val dataType: ArrayType = ArrayType(start.dataType, containsNull = false)
+
+ override def checkInputDataTypes(): TypeCheckResult = {
+ val startType = start.dataType
+ def stepType = stepOpt.get.dataType
+ val typesCorrect =
+ startType.sameType(stop.dataType) &&
+ (startType match {
+ case TimestampType | DateType =>
+ stepOpt.isEmpty || CalendarIntervalType.acceptsType(stepType)
+ case _: IntegralType =>
+ stepOpt.isEmpty || stepType.sameType(startType)
+ case _ => false
+ })
+
+ if (typesCorrect) {
+ TypeCheckResult.TypeCheckSuccess
+ } else {
+ TypeCheckResult.TypeCheckFailure(
+ s"$prettyName only supports integral, timestamp or date types")
+ }
+ }
+
+ def coercibleChildren: Seq[Expression] = children.filter(_.dataType != CalendarIntervalType)
+
+ def castChildrenTo(widerType: DataType): Expression = Sequence(
+ Cast(start, widerType),
+ Cast(stop, widerType),
+ stepOpt.map(step => if (step.dataType != CalendarIntervalType) Cast(step, widerType) else step),
+ timeZoneId)
+
+ private lazy val impl: SequenceImpl = dataType.elementType match {
+ case iType: IntegralType =>
+ type T = iType.InternalType
+ val ct = ClassTag[T](iType.tag.mirror.runtimeClass(iType.tag.tpe))
+ new IntegralSequenceImpl(iType)(ct, iType.integral)
+
+ case TimestampType =>
+ new TemporalSequenceImpl[Long](LongType, 1, identity, timeZone)
+
+ case DateType =>
+ new TemporalSequenceImpl[Int](IntegerType, MICROS_PER_DAY, _.toInt, timeZone)
+ }
+
+ override def eval(input: InternalRow): Any = {
+ val startVal = start.eval(input)
+ if (startVal == null) return null
+ val stopVal = stop.eval(input)
+ if (stopVal == null) return null
+ val stepVal = stepOpt.map(_.eval(input)).getOrElse(impl.defaultStep(startVal, stopVal))
+ if (stepVal == null) return null
+
+ ArrayData.toArrayData(impl.eval(startVal, stopVal, stepVal))
+ }
+
+ override protected def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = {
+ val startGen = start.genCode(ctx)
+ val stopGen = stop.genCode(ctx)
+ val stepGen = stepOpt.map(_.genCode(ctx)).getOrElse(
+ impl.defaultStep.genCode(ctx, startGen, stopGen))
+
+ val resultType = CodeGenerator.javaType(dataType)
+ val resultCode = {
+ val arr = ctx.freshName("arr")
+ val arrElemType = CodeGenerator.javaType(dataType.elementType)
+ s"""
+ |final $arrElemType[] $arr = null;
+ |${impl.genCode(ctx, startGen.value, stopGen.value, stepGen.value, arr, arrElemType)}
+ |${ev.value} = UnsafeArrayData.fromPrimitiveArray($arr);
+ """.stripMargin
+ }
+
+ if (nullable) {
+ val nullSafeEval =
+ startGen.code + ctx.nullSafeExec(start.nullable, startGen.isNull) {
+ stopGen.code + ctx.nullSafeExec(stop.nullable, stopGen.isNull) {
+ stepGen.code + ctx.nullSafeExec(stepOpt.exists(_.nullable), stepGen.isNull) {
+ s"""
+ |${ev.isNull} = false;
+ |$resultCode
+ """.stripMargin
+ }
+ }
+ }
+ ev.copy(code =
+ s"""
+ |boolean ${ev.isNull} = true;
+ |$resultType ${ev.value} = null;
+ |$nullSafeEval
+ """.stripMargin)
+
+ } else {
+ ev.copy(code =
+ s"""
+ |boolean ${ev.isNull} = false;
+ |${startGen.code}
+ |${stopGen.code}
+ |${stepGen.code}
+ |$resultType ${ev.value} = null;
+ |$resultCode
+ """.stripMargin,
+ isNull = FalseLiteral)
+ }
+ }
+}
+
+object Sequence {
+
+ private type LessThanOrEqualFn = (Any, Any) => Boolean
+
+ private class DefaultStep(lteq: LessThanOrEqualFn, stepType: DataType, one: Any) {
+ private val negativeOne = UnaryMinus(Literal(one)).eval()
+
+ def apply(start: Any, stop: Any): Any = {
+ if (lteq(start, stop)) one else negativeOne
+ }
+
+ def genCode(ctx: CodegenContext, startGen: ExprCode, stopGen: ExprCode): ExprCode = {
+ val Seq(oneVal, negativeOneVal) = Seq(one, negativeOne).map(Literal(_).genCode(ctx).value)
+ ExprCode.forNonNullValue(JavaCode.expression(
+ s"${startGen.value} <= ${stopGen.value} ? $oneVal : $negativeOneVal",
+ stepType))
+ }
+ }
+
+ private trait SequenceImpl {
+ def eval(start: Any, stop: Any, step: Any): Any
+
+ def genCode(
+ ctx: CodegenContext,
+ start: String,
+ stop: String,
+ step: String,
+ arr: String,
+ elemType: String): String
+
+ val defaultStep: DefaultStep
+ }
+
+ private class IntegralSequenceImpl[T: ClassTag]
+ (elemType: IntegralType)(implicit num: Integral[T]) extends SequenceImpl {
+
+ override val defaultStep: DefaultStep = new DefaultStep(
+ (elemType.ordering.lteq _).asInstanceOf[LessThanOrEqualFn],
+ elemType,
+ num.one)
+
+ override def eval(input1: Any, input2: Any, input3: Any): Array[T] = {
+ import num._
+
+ val start = input1.asInstanceOf[T]
+ val stop = input2.asInstanceOf[T]
+ val step = input3.asInstanceOf[T]
+
+ var i: Int = getSequenceLength(start, stop, step)
+ val arr = new Array[T](i)
+ while (i > 0) {
+ i -= 1
+ arr(i) = start + step * num.fromInt(i)
+ }
+ arr
+ }
+
+ override def genCode(
+ ctx: CodegenContext,
+ start: String,
+ stop: String,
+ step: String,
+ arr: String,
+ elemType: String): String = {
+ val i = ctx.freshName("i")
+ s"""
+ |${genSequenceLengthCode(ctx, start, stop, step, i)}
+ |$arr = new $elemType[$i];
+ |while ($i > 0) {
+ | $i--;
+ | $arr[$i] = ($elemType) ($start + $step * $i);
+ |}
+ """.stripMargin
+ }
+ }
+
+ private class TemporalSequenceImpl[T: ClassTag]
+ (dt: IntegralType, scale: Long, fromLong: Long => T, timeZone: TimeZone)
+ (implicit num: Integral[T]) extends SequenceImpl {
+
+ override val defaultStep: DefaultStep = new DefaultStep(
+ (dt.ordering.lteq _).asInstanceOf[LessThanOrEqualFn],
+ CalendarIntervalType,
+ new CalendarInterval(0, MICROS_PER_DAY))
+
+ private val backedSequenceImpl = new IntegralSequenceImpl[T](dt)
+ private val microsPerMonth = 28 * CalendarInterval.MICROS_PER_DAY
+
+ override def eval(input1: Any, input2: Any, input3: Any): Array[T] = {
+ val start = input1.asInstanceOf[T]
+ val stop = input2.asInstanceOf[T]
+ val step = input3.asInstanceOf[CalendarInterval]
+ val stepMonths = step.months
+ val stepMicros = step.microseconds
+
+ if (stepMonths == 0) {
+ backedSequenceImpl.eval(start, stop, fromLong(stepMicros / scale))
+
+ } else {
+ // To estimate the resulted array length we need to make assumptions
+ // about a month length in microseconds
+ val intervalStepInMicros = stepMicros + stepMonths * microsPerMonth
+ val startMicros: Long = num.toLong(start) * scale
+ val stopMicros: Long = num.toLong(stop) * scale
+ val maxEstimatedArrayLength =
+ getSequenceLength(startMicros, stopMicros, intervalStepInMicros)
+
+ val stepSign = if (stopMicros > startMicros) +1 else -1
+ val exclusiveItem = stopMicros + stepSign
+ val arr = new Array[T](maxEstimatedArrayLength)
+ var t = startMicros
+ var i = 0
+
+ while (t < exclusiveItem ^ stepSign < 0) {
+ arr(i) = fromLong(t / scale)
+ t = timestampAddInterval(t, stepMonths, stepMicros, timeZone)
+ i += 1
+ }
+
+ // truncate array to the correct length
+ if (arr.length == i) arr else arr.slice(0, i)
+ }
+ }
+
+ override def genCode(
+ ctx: CodegenContext,
+ start: String,
+ stop: String,
+ step: String,
+ arr: String,
+ elemType: String): String = {
+ val stepMonths = ctx.freshName("stepMonths")
+ val stepMicros = ctx.freshName("stepMicros")
+ val stepScaled = ctx.freshName("stepScaled")
+ val intervalInMicros = ctx.freshName("intervalInMicros")
+ val startMicros = ctx.freshName("startMicros")
+ val stopMicros = ctx.freshName("stopMicros")
+ val arrLength = ctx.freshName("arrLength")
+ val stepSign = ctx.freshName("stepSign")
+ val exclusiveItem = ctx.freshName("exclusiveItem")
+ val t = ctx.freshName("t")
+ val i = ctx.freshName("i")
+ val genTimeZone = ctx.freshName("timeZone")
+
+ val sequenceLengthCode =
+ s"""
+ |final long $intervalInMicros = $stepMicros + $stepMonths * ${microsPerMonth}L;
+ |${genSequenceLengthCode(ctx, startMicros, stopMicros, intervalInMicros, arrLength)}
+ """.stripMargin
+
+ val timestampAddIntervalCode =
+ s"""
+ |$t = org.apache.spark.sql.catalyst.util.DateTimeUtils.timestampAddInterval(
+ | $t, $stepMonths, $stepMicros, $genTimeZone);
+ """.stripMargin
+
+ s"""
+ |final int $stepMonths = $step.months;
+ |final long $stepMicros = $step.microseconds;
+ |
+ |if ($stepMonths == 0) {
+ | final $elemType $stepScaled = ($elemType) ($stepMicros / ${scale}L);
+ | ${backedSequenceImpl.genCode(ctx, start, stop, stepScaled, arr, elemType)};
+ |
+ |} else {
+ | final long $startMicros = $start * ${scale}L;
+ | final long $stopMicros = $stop * ${scale}L;
+ |
+ | $sequenceLengthCode
+ |
+ | final int $stepSign = $stopMicros > $startMicros ? +1 : -1;
+ | final long $exclusiveItem = $stopMicros + $stepSign;
+ | final java.util.TimeZone $genTimeZone =
+ | java.util.TimeZone.getTimeZone("${timeZone.getID}");
+ |
+ | $arr = new $elemType[$arrLength];
+ | long $t = $startMicros;
+ | int $i = 0;
+ |
+ | while ($t < $exclusiveItem ^ $stepSign < 0) {
+ | $arr[$i] = ($elemType) ($t / ${scale}L);
+ | $timestampAddIntervalCode
+ | $i += 1;
+ | }
+ |
+ | if ($arr.length > $i) {
+ | $arr = java.util.Arrays.copyOf($arr, $i);
+ | }
+ |}
+ """.stripMargin
+ }
+ }
+
+ private def getSequenceLength[U](start: U, stop: U, step: U)(implicit num: Integral[U]): Int = {
+ import num._
+ require(
+ step > num.zero && start <= stop
+ || step < num.zero && start >= stop
+ || step == 0 && start == stop,
+ s"Illegal sequence boundaries: $start to $stop by $step")
+
+ val len = if (start == stop) 1L else 1L + (stop.toLong - start.toLong) / step.toLong
+
+ require(len <= Int.MaxValue, s"Too long sequence: $len. Should be <= ${Int.MaxValue}")
--- End diff --
`ByteArrayMethods.MAX_ROUNDED_ARRAY_LENGTH` instead of `Int.MaxValue`?
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by wajda <gi...@git.apache.org>.
Github user wajda commented on a diff in the pull request:
https://github.com/apache/spark/pull/21155#discussion_r197496293
--- Diff: sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/CollectionExpressionsSuite.scala ---
@@ -308,6 +313,292 @@ class CollectionExpressionsSuite extends SparkFunSuite with ExpressionEvalHelper
ArrayMax(Literal.create(Seq(1.123, 0.1234, 1.121), ArrayType(DoubleType))), 1.123)
}
+ test("Sequence") {
--- End diff --
renamed
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:
https://github.com/apache/spark/pull/21155
**[Test build #90893 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/90893/testReport)** for PR 21155 at commit [`3ef9566`](https://github.com/apache/spark/commit/3ef9566dd85e49ecae74f888b576ba17e6e58f09).
* This patch **fails SparkR unit tests**.
* This patch **does not merge cleanly**.
* This patch adds the following public classes _(experimental)_:
* `case class Sequence(`
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by wajda <gi...@git.apache.org>.
Github user wajda commented on a diff in the pull request:
https://github.com/apache/spark/pull/21155#discussion_r197496354
--- Diff: sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/expressions/CollectionExpressionsSuite.scala ---
@@ -308,6 +313,292 @@ class CollectionExpressionsSuite extends SparkFunSuite with ExpressionEvalHelper
ArrayMax(Literal.create(Seq(1.123, 0.1234, 1.121), ArrayType(DoubleType))), 1.123)
}
+ test("Sequence") {
+ // test null handling
+
+ checkEvaluation(new Sequence(Literal(null, LongType), Literal(1L)), null)
+ checkEvaluation(new Sequence(Literal(1L), Literal(null, LongType)), null)
+ checkEvaluation(new Sequence(Literal(null, LongType), Literal(1L), Literal(1L)), null)
+ checkEvaluation(new Sequence(Literal(1L), Literal(null, LongType), Literal(1L)), null)
+ checkEvaluation(new Sequence(Literal(1L), Literal(1L), Literal(null, LongType)), null)
+
+ // test sequence boundaries checking
+
+ checkExceptionInExpression[IllegalArgumentException](
+ new Sequence(Literal(Int.MinValue), Literal(Int.MaxValue), Literal(1)),
+ EmptyRow, s"Too long sequence: 4294967296. Should be <= ${Int.MaxValue}")
+
+ checkExceptionInExpression[IllegalArgumentException](
+ new Sequence(Literal(1), Literal(2), Literal(0)), EmptyRow, "boundaries: 1 to 2 by 0")
+ checkExceptionInExpression[IllegalArgumentException](
+ new Sequence(Literal(2), Literal(1), Literal(0)), EmptyRow, "boundaries: 2 to 1 by 0")
+ checkExceptionInExpression[IllegalArgumentException](
+ new Sequence(Literal(2), Literal(1), Literal(1)), EmptyRow, "boundaries: 2 to 1 by 1")
+ checkExceptionInExpression[IllegalArgumentException](
+ new Sequence(Literal(1), Literal(2), Literal(-1)), EmptyRow, "boundaries: 1 to 2 by -1")
+
+ checkExceptionInExpression[IllegalArgumentException](
+ new Sequence(
+ Literal(Date.valueOf("1970-01-02")),
+ Literal(Date.valueOf("1970-01-01")),
+ Literal(CalendarInterval.fromString("interval 1 day"))),
+ EmptyRow, "sequence boundaries: 1 to 0 by 1")
+
+ checkExceptionInExpression[IllegalArgumentException](
+ new Sequence(
+ Literal(Date.valueOf("1970-01-01")),
+ Literal(Date.valueOf("1970-02-01")),
+ Literal(CalendarInterval.fromString("interval 1 month").negate())),
+ EmptyRow,
+ s"sequence boundaries: 0 to 2678400000000 by -${28 * CalendarInterval.MICROS_PER_DAY}")
+
+ // test sequence with one element (zero step or equal start and stop)
+
+ checkEvaluation(new Sequence(Literal(1), Literal(1), Literal(-1)), Seq(1))
+ checkEvaluation(new Sequence(Literal(1), Literal(1), Literal(0)), Seq(1))
+ checkEvaluation(new Sequence(Literal(1), Literal(1), Literal(1)), Seq(1))
+ checkEvaluation(new Sequence(Literal(1), Literal(2), Literal(2)), Seq(1))
+ checkEvaluation(new Sequence(Literal(1), Literal(0), Literal(-2)), Seq(1))
+
+ // test sequence of different integral types (ascending and descending)
+
+ checkEvaluation(new Sequence(Literal(1L), Literal(3L), Literal(1L)), Seq(1L, 2L, 3L))
+ checkEvaluation(new Sequence(Literal(-3), Literal(3), Literal(3)), Seq(-3, 0, 3))
+ checkEvaluation(
+ new Sequence(Literal(3.toShort), Literal(-3.toShort), Literal(-3.toShort)),
+ Seq(3.toShort, 0.toShort, -3.toShort))
+ checkEvaluation(
+ new Sequence(Literal(-1.toByte), Literal(-3.toByte), Literal(-1.toByte)),
+ Seq(-1.toByte, -2.toByte, -3.toByte))
+ }
+
+ test("Sequence of timestamps") {
+ checkEvaluation(new Sequence(
+ Literal(Timestamp.valueOf("2018-01-01 00:00:00")),
+ Literal(Timestamp.valueOf("2018-01-02 00:00:00")),
+ Literal(CalendarInterval.fromString("interval 12 hours"))),
+ Seq(
+ Timestamp.valueOf("2018-01-01 00:00:00"),
+ Timestamp.valueOf("2018-01-01 12:00:00"),
+ Timestamp.valueOf("2018-01-02 00:00:00")))
+
+ checkEvaluation(new Sequence(
+ Literal(Timestamp.valueOf("2018-01-01 00:00:00")),
+ Literal(Timestamp.valueOf("2018-01-02 00:00:01")),
+ Literal(CalendarInterval.fromString("interval 12 hours"))),
+ Seq(
+ Timestamp.valueOf("2018-01-01 00:00:00"),
+ Timestamp.valueOf("2018-01-01 12:00:00"),
+ Timestamp.valueOf("2018-01-02 00:00:00")))
+
+ checkEvaluation(new Sequence(
+ Literal(Timestamp.valueOf("2018-01-02 00:00:00")),
+ Literal(Timestamp.valueOf("2018-01-01 00:00:00")),
+ Literal(CalendarInterval.fromString("interval 12 hours").negate())),
+ Seq(
+ Timestamp.valueOf("2018-01-02 00:00:00"),
+ Timestamp.valueOf("2018-01-01 12:00:00"),
+ Timestamp.valueOf("2018-01-01 00:00:00")))
+
+ checkEvaluation(new Sequence(
+ Literal(Timestamp.valueOf("2018-01-02 00:00:00")),
+ Literal(Timestamp.valueOf("2017-12-31 23:59:59")),
+ Literal(CalendarInterval.fromString("interval 12 hours").negate())),
+ Seq(
+ Timestamp.valueOf("2018-01-02 00:00:00"),
+ Timestamp.valueOf("2018-01-01 12:00:00"),
+ Timestamp.valueOf("2018-01-01 00:00:00")))
+
+ checkEvaluation(new Sequence(
+ Literal(Timestamp.valueOf("2018-01-01 00:00:00")),
+ Literal(Timestamp.valueOf("2018-03-01 00:00:00")),
+ Literal(CalendarInterval.fromString("interval 1 month"))),
+ Seq(
+ Timestamp.valueOf("2018-01-01 00:00:00"),
+ Timestamp.valueOf("2018-02-01 00:00:00"),
+ Timestamp.valueOf("2018-03-01 00:00:00")))
+
+ checkEvaluation(new Sequence(
+ Literal(Timestamp.valueOf("2018-03-01 00:00:00")),
+ Literal(Timestamp.valueOf("2018-01-01 00:00:00")),
+ Literal(CalendarInterval.fromString("interval 1 month").negate())),
+ Seq(
+ Timestamp.valueOf("2018-03-01 00:00:00"),
+ Timestamp.valueOf("2018-02-01 00:00:00"),
+ Timestamp.valueOf("2018-01-01 00:00:00")))
+
+ checkEvaluation(new Sequence(
+ Literal(Timestamp.valueOf("2018-03-03 00:00:00")),
+ Literal(Timestamp.valueOf("2018-01-01 00:00:00")),
+ Literal(CalendarInterval.fromString("interval 1 month 1 day").negate())),
+ Seq(
+ Timestamp.valueOf("2018-03-03 00:00:00"),
+ Timestamp.valueOf("2018-02-02 00:00:00"),
+ Timestamp.valueOf("2018-01-01 00:00:00")))
+
+ checkEvaluation(new Sequence(
+ Literal(Timestamp.valueOf("2018-01-31 00:00:00")),
+ Literal(Timestamp.valueOf("2018-04-30 00:00:00")),
+ Literal(CalendarInterval.fromString("interval 1 month"))),
+ Seq(
+ Timestamp.valueOf("2018-01-31 00:00:00"),
+ Timestamp.valueOf("2018-02-28 00:00:00"),
+ Timestamp.valueOf("2018-03-31 00:00:00"),
+ Timestamp.valueOf("2018-04-30 00:00:00")))
+
+ checkEvaluation(new Sequence(
+ Literal(Timestamp.valueOf("2018-01-01 00:00:00")),
+ Literal(Timestamp.valueOf("2018-03-01 00:00:00")),
+ Literal(CalendarInterval.fromString("interval 1 month 1 second"))),
+ Seq(
+ Timestamp.valueOf("2018-01-01 00:00:00"),
+ Timestamp.valueOf("2018-02-01 00:00:01")))
+
+ checkEvaluation(new Sequence(
+ Literal(Timestamp.valueOf("2018-01-01 00:00:00")),
+ Literal(Timestamp.valueOf("2018-03-01 00:04:06")),
+ Literal(CalendarInterval.fromString("interval 1 month 2 minutes 3 seconds"))),
+ Seq(
+ Timestamp.valueOf("2018-01-01 00:00:00"),
+ Timestamp.valueOf("2018-02-01 00:02:03"),
+ Timestamp.valueOf("2018-03-01 00:04:06")))
+
+ checkEvaluation(new Sequence(
+ Literal(Timestamp.valueOf("2018-01-01 00:00:00")),
+ Literal(Timestamp.valueOf("2023-01-01 00:00:00")),
+ Literal(CalendarInterval.fromYearMonthString("1-5"))),
+ Seq(
+ Timestamp.valueOf("2018-01-01 00:00:00.000"),
+ Timestamp.valueOf("2019-06-01 00:00:00.000"),
+ Timestamp.valueOf("2020-11-01 00:00:00.000"),
+ Timestamp.valueOf("2022-04-01 00:00:00.000")))
+
+ checkEvaluation(new Sequence(
+ Literal(Timestamp.valueOf("2022-04-01 00:00:00")),
+ Literal(Timestamp.valueOf("2017-01-01 00:00:00")),
+ Literal(CalendarInterval.fromYearMonthString("1-5").negate())),
+ Seq(
+ Timestamp.valueOf("2022-04-01 00:00:00.000"),
+ Timestamp.valueOf("2020-11-01 00:00:00.000"),
+ Timestamp.valueOf("2019-06-01 00:00:00.000"),
+ Timestamp.valueOf("2018-01-01 00:00:00.000")))
+ }
+
+ test("Sequence on DST boundaries") {
+ val timeZone = TimeZone.getTimeZone("CET")
--- End diff --
renamed
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: SPARK-23927: Add "sequence" expression
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:
https://github.com/apache/spark/pull/21155
Test FAILed.
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/89854/
Test FAILed.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: SPARK-23927: Add "sequence" expression
Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:
https://github.com/apache/spark/pull/21155
**[Test build #89852 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/89852/testReport)** for PR 21155 at commit [`0b4d868`](https://github.com/apache/spark/commit/0b4d868b995a58c92d294e248ee9689f50da9f1f).
* This patch **fails Spark unit tests**.
* This patch merges cleanly.
* This patch adds no public classes.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by viirya <gi...@git.apache.org>.
Github user viirya commented on a diff in the pull request:
https://github.com/apache/spark/pull/21155#discussion_r187213977
--- Diff: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/collectionOperations.scala ---
@@ -1468,3 +1472,388 @@ case class Flatten(child: Expression) extends UnaryExpression {
override def prettyName: String = "flatten"
}
+
+@ExpressionDescription(
+ usage = """
+ _FUNC_(start, stop, step) - Generates an array of elements from start to stop (inclusive),
+ incrementing by step. The type of the returned elements is the same as the type of argument
+ expressions.
+
+ Supported types are: byte, short, integer, long, date, timestamp.
+
+ The start and stop expressions must resolve to the same type.
+ If start and stop expressions resolve to the 'date' or 'timestamp' type
+ then the step expression must resolve to the 'interval' type, otherwise to the same type
+ as the start and stop expressions.
+ """,
+ arguments = """
+ Arguments:
+ * start - an expression. The start of the range.
+ * stop - an expression. The end the range (inclusive).
+ * step - an optional expression. The step of the range.
+ By default step is 1 if start is less than or equal to stop, otherwise -1.
+ For the temporal sequences it's 1 day and -1 day respectively.
+ If start is greater than stop then the step must be negative, and vice versa.
+ """,
+ examples = """
+ Examples:
+ > SELECT _FUNC_(1, 5);
+ [1, 2, 3, 4, 5]
+ > SELECT _FUNC_(5, 1);
+ [5, 4, 3, 2, 1]
+ > SELECT _FUNC_(to_date('2018-01-01'), to_date('2018-03-01'), interval 1 month);
+ [2018-01-01, 2018-02-01, 2018-03-01]
+ """,
+ since = "2.4.0"
+)
+case class Sequence(
+ start: Expression,
+ stop: Expression,
+ stepOpt: Option[Expression],
+ timeZoneId: Option[String] = None)
+ extends Expression
+ with ExpectsInputTypes
+ with TimeZoneAwareExpression {
+
+ import Sequence._
+
+ def this(start: Expression, stop: Expression) =
+ this(start, stop, None, None)
+
+ def this(start: Expression, stop: Expression, step: Expression) =
+ this(start, stop, Some(step), None)
+
+ override def withTimeZone(timeZoneId: String): TimeZoneAwareExpression =
+ copy(timeZoneId = Some(timeZoneId))
+
+ override def children: Seq[Expression] = Seq(start, stop) ++ stepOpt
+
+ override def foldable: Boolean = children.forall(_.foldable)
+
+ override def nullable: Boolean = children.exists(_.nullable)
+
+ override lazy val dataType: ArrayType = ArrayType(start.dataType, containsNull = false)
+
+ override def inputTypes: Seq[AbstractDataType] = {
+ val elemType = dataType.elementType
+ Seq(elemType, elemType) ++
+ stepOpt.map(_ => elemType match {
+ case DateType | TimestampType => CalendarIntervalType
+ case _: IntegralType => elemType
--- End diff --
We might need to override `checkInputDataTypes` here to check if `elemType` is one of `DateType`, `TimestampType` or `IntegralType`. And also the validity of type of step expression.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:
https://github.com/apache/spark/pull/21155
**[Test build #92331 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/92331/testReport)** for PR 21155 at commit [`140225d`](https://github.com/apache/spark/commit/140225d8b2326122f69e9093a071c1cdde7e489d).
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:
https://github.com/apache/spark/pull/21155
**[Test build #92331 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/92331/testReport)** for PR 21155 at commit [`140225d`](https://github.com/apache/spark/commit/140225d8b2326122f69e9093a071c1cdde7e489d).
* This patch passes all tests.
* This patch merges cleanly.
* This patch adds no public classes.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by wajda <gi...@git.apache.org>.
Github user wajda commented on a diff in the pull request:
https://github.com/apache/spark/pull/21155#discussion_r187195445
--- Diff: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/TypeCoercion.scala ---
@@ -536,6 +536,15 @@ object TypeCoercion {
case None => c
}
+ case s @ Sequence(_, _, _, timeZoneId) if !haveSameType(s.children) =>
+ val types = s.children.map(_.dataType)
+ findWiderCommonType(types) match {
--- End diff --
Good catch, thank you. I've added a unit test and fixed coercion when the step is interval.
Regarding ```ImplicitCastInputTypes ``` I tried it, but it isn't flexible enough for my case. To support actual type coercion for both integral and temporal sequences I had to resort to ```TypeCoercion```. Please check the fixed version. Is there any better way how to do it?
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:
https://github.com/apache/spark/pull/21155
**[Test build #91617 has started](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/91617/testReport)** for PR 21155 at commit [`2ccb9bb`](https://github.com/apache/spark/commit/2ccb9bb73f729c361ee819316e9c95224797a178).
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request #21155: SPARK-23927: Add "sequence" expression
Posted by ueshin <gi...@git.apache.org>.
Github user ueshin commented on a diff in the pull request:
https://github.com/apache/spark/pull/21155#discussion_r186037505
--- Diff: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/collectionOperations.scala ---
@@ -1059,3 +1063,316 @@ case class Flatten(child: Expression) extends UnaryExpression {
override def prettyName: String = "flatten"
}
+
+@ExpressionDescription(
+ usage = """
+ _FUNC_(start, stop, step) -
+ Generates an array of elements from start to stop (inclusive), incrementing by step.
+ The type of the returned elements is the same as the type of argument expressions.
+
+ Supported types are: byte, short, integer, long, date, timestamp.
+
+ The start and stop expressions must resolve to the same type.
+ If start and stop expressions resolve to the 'date' or 'timestamp' type
+ then the step expression must resolve to the 'interval' type, otherwise to the same type
+ as the start and stop expressions.
+ """,
+ arguments = """
+ Arguments:
+ * start - an expression. The start of the range.
+ * stop - an expression. The end the range (inclusive).
+ * step - an optional expression. The step of the range.
+
+ By default step is 1 if start is less than or equal to stop, otherwise -1.
+ For the temporal sequences it's 1 day and -1 day respectively.
+
+ If start is greater than stop then the step must be negative, and vice versa.
+ """,
+ examples = """
+ Examples:
+ > SELECT _FUNC_(1, 5);
+ [1, 2, 3, 4, 5]
+ > SELECT _FUNC_(5, 1);
+ [5, 4, 3, 2, 1]
+ > SELECT _FUNC_(to_date('2018-01-01'), to_date('2018-03-01'), interval 1 month);
+ [2018-01-01, 2018-02-01, 2018-03-01]
+ """,
+ since = "2.4.0"
+)
+case class Sequence(left: Expression,
+ middle: Expression,
+ right: Expression,
+ timeZoneId: Option[String] = None)
+ extends TernaryExpression with TimeZoneAwareExpression {
+
+ import Sequence._
+
+ def this(arg0: Expression, arg1: Expression) =
+ this(arg0, arg1, Sequence.defaultStepExpression(arg0, arg1), None)
+
+ def this(arg0: Expression, arg1: Expression, arg2: Expression) =
+ this(arg0, arg1, arg2, None)
+
+ override def withTimeZone(timeZoneId: String): TimeZoneAwareExpression =
+ copy(timeZoneId = Some(timeZoneId))
+
+ override def children: Seq[Expression] = Seq(left, middle, right)
+
+ override lazy val dataType: ArrayType = ArrayType(left.dataType, containsNull = false)
+
+ override def checkInputDataTypes(): TypeCheckResult = {
+ val Seq(startType, stopType, stepType) = children.map(_.dataType)
+ val typesCorrect =
+ startType.sameType(stopType) &&
+ (startType match {
+ case TimestampType | DateType => CalendarIntervalType acceptsType stepType
+ case _: IntegralType => stepType sameType startType
+ case _ => false
+ })
+
+ if (typesCorrect) {
+ TypeCheckResult.TypeCheckSuccess
+ } else {
+ TypeCheckResult.TypeCheckFailure(
+ s"$prettyName only supports integral, timestamp or date types")
+ }
+ }
+
+ private lazy val impl: SequenceImpl = dataType.elementType match {
+ case iType: IntegralType =>
+ type T = iType.InternalType
+ val ct = ClassTag[T](iType.tag.mirror.runtimeClass(iType.tag.tpe))
+ new IntegralSequenceImpl()(ct, iType.integral)
+
+ case TimestampType =>
+ new TemporalSequenceImpl[Long](LongType, 1, identity, timeZone)
+
+ case DateType =>
+ new TemporalSequenceImpl[Int](IntegerType, MICROS_PER_DAY, _.toInt, timeZone)
+ }
+
+ override protected def nullSafeEval(input1: Any, input2: Any, input3: Any): Any = {
+ ArrayData.toArrayData(impl.eval(input1, input2, input3))
+ }
+
+ override protected def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = {
+ nullSafeCodeGen(ctx, ev, (start, stop, step) => {
+ val arr = ctx.freshName("arr")
+ val arrElemType = CodeGenerator.javaType(dataType.elementType)
+ s"""
+ | final $arrElemType[] $arr = null;
+ | ${impl.genCode(start, stop, step)(arr, arrElemType)(ctx)}
+ | ${ev.value} = UnsafeArrayData.fromPrimitiveArray($arr);
+ """.stripMargin
+ })
+ }
+}
+
+object Sequence {
+
+ private trait SequenceImpl {
+ def eval(input1: Any, input2: Any, input3: Any): Any
+
+ def genCode(start: String, stop: String, step: String)
+ (arr: String, elemType: String)
+ (implicit ctx: CodegenContext): String
--- End diff --
nit: style
```scala
def genCode
(start: String, stop: String, step: String)
(arr: String, elemType: String)
(implicit ctx: CodegenContext): String
```
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:
https://github.com/apache/spark/pull/21155
**[Test build #91617 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/91617/testReport)** for PR 21155 at commit [`2ccb9bb`](https://github.com/apache/spark/commit/2ccb9bb73f729c361ee819316e9c95224797a178).
* This patch **fails to build**.
* This patch merges cleanly.
* This patch adds the following public classes _(experimental)_:
* `case class Sequence(`
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by wajda <gi...@git.apache.org>.
Github user wajda commented on a diff in the pull request:
https://github.com/apache/spark/pull/21155#discussion_r197485470
--- Diff: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/collectionOperations.scala ---
@@ -1887,6 +1889,402 @@ case class Flatten(child: Expression) extends UnaryExpression {
override def prettyName: String = "flatten"
}
+@ExpressionDescription(
+ usage = """
+ _FUNC_(start, stop, step) - Generates an array of elements from start to stop (inclusive),
+ incrementing by step. The type of the returned elements is the same as the type of argument
+ expressions.
+
+ Supported types are: byte, short, integer, long, date, timestamp.
+
+ The start and stop expressions must resolve to the same type.
+ If start and stop expressions resolve to the 'date' or 'timestamp' type
+ then the step expression must resolve to the 'interval' type, otherwise to the same type
+ as the start and stop expressions.
+ """,
+ arguments = """
+ Arguments:
+ * start - an expression. The start of the range.
+ * stop - an expression. The end the range (inclusive).
+ * step - an optional expression. The step of the range.
+ By default step is 1 if start is less than or equal to stop, otherwise -1.
+ For the temporal sequences it's 1 day and -1 day respectively.
+ If start is greater than stop then the step must be negative, and vice versa.
+ """,
+ examples = """
+ Examples:
+ > SELECT _FUNC_(1, 5);
+ [1, 2, 3, 4, 5]
+ > SELECT _FUNC_(5, 1);
+ [5, 4, 3, 2, 1]
+ > SELECT _FUNC_(to_date('2018-01-01'), to_date('2018-03-01'), interval 1 month);
+ [2018-01-01, 2018-02-01, 2018-03-01]
+ """,
+ since = "2.4.0"
+)
+case class Sequence(
+ start: Expression,
+ stop: Expression,
+ stepOpt: Option[Expression],
+ timeZoneId: Option[String] = None)
+ extends Expression
+ with TimeZoneAwareExpression {
+
+ import Sequence._
+
+ def this(start: Expression, stop: Expression) =
+ this(start, stop, None, None)
+
+ def this(start: Expression, stop: Expression, step: Expression) =
+ this(start, stop, Some(step), None)
+
+ override def withTimeZone(timeZoneId: String): TimeZoneAwareExpression =
+ copy(timeZoneId = Some(timeZoneId))
+
+ override def children: Seq[Expression] = Seq(start, stop) ++ stepOpt
+
+ override def foldable: Boolean = children.forall(_.foldable)
+
+ override def nullable: Boolean = children.exists(_.nullable)
+
+ override lazy val dataType: ArrayType = ArrayType(start.dataType, containsNull = false)
+
+ override def checkInputDataTypes(): TypeCheckResult = {
+ val startType = start.dataType
+ def stepType = stepOpt.get.dataType
+ val typesCorrect =
+ startType.sameType(stop.dataType) &&
+ (startType match {
+ case TimestampType | DateType =>
+ stepOpt.isEmpty || CalendarIntervalType.acceptsType(stepType)
+ case _: IntegralType =>
+ stepOpt.isEmpty || stepType.sameType(startType)
+ case _ => false
+ })
+
+ if (typesCorrect) {
+ TypeCheckResult.TypeCheckSuccess
+ } else {
+ TypeCheckResult.TypeCheckFailure(
+ s"$prettyName only supports integral, timestamp or date types")
+ }
+ }
+
+ def coercibleChildren: Seq[Expression] = children.filter(_.dataType != CalendarIntervalType)
+
+ def castChildrenTo(widerType: DataType): Expression = Sequence(
+ Cast(start, widerType),
+ Cast(stop, widerType),
+ stepOpt.map(step => if (step.dataType != CalendarIntervalType) Cast(step, widerType) else step),
+ timeZoneId)
+
+ private lazy val impl: SequenceImpl = dataType.elementType match {
+ case iType: IntegralType =>
+ type T = iType.InternalType
+ val ct = ClassTag[T](iType.tag.mirror.runtimeClass(iType.tag.tpe))
+ new IntegralSequenceImpl(iType)(ct, iType.integral)
+
+ case TimestampType =>
+ new TemporalSequenceImpl[Long](LongType, 1, identity, timeZone)
+
+ case DateType =>
+ new TemporalSequenceImpl[Int](IntegerType, MICROS_PER_DAY, _.toInt, timeZone)
+ }
+
+ override def eval(input: InternalRow): Any = {
+ val startVal = start.eval(input)
+ if (startVal == null) return null
+ val stopVal = stop.eval(input)
+ if (stopVal == null) return null
+ val stepVal = stepOpt.map(_.eval(input)).getOrElse(impl.defaultStep(startVal, stopVal))
+ if (stepVal == null) return null
+
+ ArrayData.toArrayData(impl.eval(startVal, stopVal, stepVal))
+ }
+
+ override protected def doGenCode(ctx: CodegenContext, ev: ExprCode): ExprCode = {
+ val startGen = start.genCode(ctx)
+ val stopGen = stop.genCode(ctx)
+ val stepGen = stepOpt.map(_.genCode(ctx)).getOrElse(
+ impl.defaultStep.genCode(ctx, startGen, stopGen))
+
+ val resultType = CodeGenerator.javaType(dataType)
+ val resultCode = {
+ val arr = ctx.freshName("arr")
+ val arrElemType = CodeGenerator.javaType(dataType.elementType)
+ s"""
+ |final $arrElemType[] $arr = null;
+ |${impl.genCode(ctx, startGen.value, stopGen.value, stepGen.value, arr, arrElemType)}
+ |${ev.value} = UnsafeArrayData.fromPrimitiveArray($arr);
+ """.stripMargin
+ }
+
+ if (nullable) {
+ val nullSafeEval =
+ startGen.code + ctx.nullSafeExec(start.nullable, startGen.isNull) {
+ stopGen.code + ctx.nullSafeExec(stop.nullable, stopGen.isNull) {
+ stepGen.code + ctx.nullSafeExec(stepOpt.exists(_.nullable), stepGen.isNull) {
+ s"""
+ |${ev.isNull} = false;
+ |$resultCode
+ """.stripMargin
+ }
+ }
+ }
+ ev.copy(code =
+ s"""
+ |boolean ${ev.isNull} = true;
+ |$resultType ${ev.value} = null;
+ |$nullSafeEval
+ """.stripMargin)
+
+ } else {
+ ev.copy(code =
+ s"""
+ |boolean ${ev.isNull} = false;
+ |${startGen.code}
+ |${stopGen.code}
+ |${stepGen.code}
+ |$resultType ${ev.value} = null;
+ |$resultCode
+ """.stripMargin,
+ isNull = FalseLiteral)
+ }
+ }
+}
+
+object Sequence {
+
+ private type LessThanOrEqualFn = (Any, Any) => Boolean
+
+ private class DefaultStep(lteq: LessThanOrEqualFn, stepType: DataType, one: Any) {
+ private val negativeOne = UnaryMinus(Literal(one)).eval()
+
+ def apply(start: Any, stop: Any): Any = {
+ if (lteq(start, stop)) one else negativeOne
+ }
+
+ def genCode(ctx: CodegenContext, startGen: ExprCode, stopGen: ExprCode): ExprCode = {
+ val Seq(oneVal, negativeOneVal) = Seq(one, negativeOne).map(Literal(_).genCode(ctx).value)
+ ExprCode.forNonNullValue(JavaCode.expression(
+ s"${startGen.value} <= ${stopGen.value} ? $oneVal : $negativeOneVal",
+ stepType))
+ }
+ }
+
+ private trait SequenceImpl {
+ def eval(start: Any, stop: Any, step: Any): Any
+
+ def genCode(
+ ctx: CodegenContext,
+ start: String,
+ stop: String,
+ step: String,
+ arr: String,
+ elemType: String): String
+
+ val defaultStep: DefaultStep
+ }
+
+ private class IntegralSequenceImpl[T: ClassTag]
+ (elemType: IntegralType)(implicit num: Integral[T]) extends SequenceImpl {
+
+ override val defaultStep: DefaultStep = new DefaultStep(
+ (elemType.ordering.lteq _).asInstanceOf[LessThanOrEqualFn],
+ elemType,
+ num.one)
+
+ override def eval(input1: Any, input2: Any, input3: Any): Array[T] = {
+ import num._
+
+ val start = input1.asInstanceOf[T]
+ val stop = input2.asInstanceOf[T]
+ val step = input3.asInstanceOf[T]
+
+ var i: Int = getSequenceLength(start, stop, step)
+ val arr = new Array[T](i)
+ while (i > 0) {
+ i -= 1
+ arr(i) = start + step * num.fromInt(i)
+ }
+ arr
+ }
+
+ override def genCode(
+ ctx: CodegenContext,
+ start: String,
+ stop: String,
+ step: String,
+ arr: String,
+ elemType: String): String = {
+ val i = ctx.freshName("i")
+ s"""
+ |${genSequenceLengthCode(ctx, start, stop, step, i)}
+ |$arr = new $elemType[$i];
+ |while ($i > 0) {
+ | $i--;
+ | $arr[$i] = ($elemType) ($start + $step * $i);
+ |}
+ """.stripMargin
+ }
+ }
+
+ private class TemporalSequenceImpl[T: ClassTag]
+ (dt: IntegralType, scale: Long, fromLong: Long => T, timeZone: TimeZone)
+ (implicit num: Integral[T]) extends SequenceImpl {
+
+ override val defaultStep: DefaultStep = new DefaultStep(
+ (dt.ordering.lteq _).asInstanceOf[LessThanOrEqualFn],
+ CalendarIntervalType,
+ new CalendarInterval(0, MICROS_PER_DAY))
+
+ private val backedSequenceImpl = new IntegralSequenceImpl[T](dt)
+ private val microsPerMonth = 28 * CalendarInterval.MICROS_PER_DAY
+
+ override def eval(input1: Any, input2: Any, input3: Any): Array[T] = {
+ val start = input1.asInstanceOf[T]
+ val stop = input2.asInstanceOf[T]
+ val step = input3.asInstanceOf[CalendarInterval]
+ val stepMonths = step.months
+ val stepMicros = step.microseconds
+
+ if (stepMonths == 0) {
+ backedSequenceImpl.eval(start, stop, fromLong(stepMicros / scale))
+
+ } else {
+ // To estimate the resulted array length we need to make assumptions
+ // about a month length in microseconds
+ val intervalStepInMicros = stepMicros + stepMonths * microsPerMonth
+ val startMicros: Long = num.toLong(start) * scale
+ val stopMicros: Long = num.toLong(stop) * scale
+ val maxEstimatedArrayLength =
+ getSequenceLength(startMicros, stopMicros, intervalStepInMicros)
+
+ val stepSign = if (stopMicros > startMicros) +1 else -1
+ val exclusiveItem = stopMicros + stepSign
+ val arr = new Array[T](maxEstimatedArrayLength)
+ var t = startMicros
+ var i = 0
+
+ while (t < exclusiveItem ^ stepSign < 0) {
+ arr(i) = fromLong(t / scale)
+ t = timestampAddInterval(t, stepMonths, stepMicros, timeZone)
+ i += 1
+ }
+
+ // truncate array to the correct length
+ if (arr.length == i) arr else arr.slice(0, i)
+ }
+ }
+
+ override def genCode(
+ ctx: CodegenContext,
+ start: String,
+ stop: String,
+ step: String,
+ arr: String,
+ elemType: String): String = {
+ val stepMonths = ctx.freshName("stepMonths")
+ val stepMicros = ctx.freshName("stepMicros")
+ val stepScaled = ctx.freshName("stepScaled")
+ val intervalInMicros = ctx.freshName("intervalInMicros")
+ val startMicros = ctx.freshName("startMicros")
+ val stopMicros = ctx.freshName("stopMicros")
+ val arrLength = ctx.freshName("arrLength")
+ val stepSign = ctx.freshName("stepSign")
+ val exclusiveItem = ctx.freshName("exclusiveItem")
+ val t = ctx.freshName("t")
+ val i = ctx.freshName("i")
+ val genTimeZone = ctx.freshName("timeZone")
+
+ val sequenceLengthCode =
+ s"""
+ |final long $intervalInMicros = $stepMicros + $stepMonths * ${microsPerMonth}L;
+ |${genSequenceLengthCode(ctx, startMicros, stopMicros, intervalInMicros, arrLength)}
+ """.stripMargin
+
+ val timestampAddIntervalCode =
+ s"""
+ |$t = org.apache.spark.sql.catalyst.util.DateTimeUtils.timestampAddInterval(
+ | $t, $stepMonths, $stepMicros, $genTimeZone);
+ """.stripMargin
+
+ s"""
+ |final int $stepMonths = $step.months;
+ |final long $stepMicros = $step.microseconds;
+ |
+ |if ($stepMonths == 0) {
+ | final $elemType $stepScaled = ($elemType) ($stepMicros / ${scale}L);
+ | ${backedSequenceImpl.genCode(ctx, start, stop, stepScaled, arr, elemType)};
+ |
+ |} else {
+ | final long $startMicros = $start * ${scale}L;
+ | final long $stopMicros = $stop * ${scale}L;
+ |
+ | $sequenceLengthCode
+ |
+ | final int $stepSign = $stopMicros > $startMicros ? +1 : -1;
+ | final long $exclusiveItem = $stopMicros + $stepSign;
+ | final java.util.TimeZone $genTimeZone =
+ | java.util.TimeZone.getTimeZone("${timeZone.getID}");
+ |
+ | $arr = new $elemType[$arrLength];
+ | long $t = $startMicros;
+ | int $i = 0;
+ |
+ | while ($t < $exclusiveItem ^ $stepSign < 0) {
+ | $arr[$i] = ($elemType) ($t / ${scale}L);
+ | $timestampAddIntervalCode
+ | $i += 1;
+ | }
+ |
+ | if ($arr.length > $i) {
+ | $arr = java.util.Arrays.copyOf($arr, $i);
+ | }
+ |}
+ """.stripMargin
+ }
+ }
+
+ private def getSequenceLength[U](start: U, stop: U, step: U)(implicit num: Integral[U]): Int = {
+ import num._
+ require(
+ step > num.zero && start <= stop
+ || step < num.zero && start >= stop
+ || step == 0 && start == stop,
+ s"Illegal sequence boundaries: $start to $stop by $step")
+
+ val len = if (start == stop) 1L else 1L + (stop.toLong - start.toLong) / step.toLong
+
+ require(len <= Int.MaxValue, s"Too long sequence: $len. Should be <= ${Int.MaxValue}")
--- End diff --
done
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:
https://github.com/apache/spark/pull/21155
Merged build finished. Test PASSed.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:
https://github.com/apache/spark/pull/21155
**[Test build #92295 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/92295/testReport)** for PR 21155 at commit [`def678b`](https://github.com/apache/spark/commit/def678b152b74e745b125167e55a2d999903e239).
* This patch passes all tests.
* This patch merges cleanly.
* This patch adds no public classes.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:
https://github.com/apache/spark/pull/21155
**[Test build #92217 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/92217/testReport)** for PR 21155 at commit [`c54857a`](https://github.com/apache/spark/commit/c54857a9cc9cdb64639913bc539975e2b507af28).
* This patch passes all tests.
* This patch merges cleanly.
* This patch adds no public classes.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:
https://github.com/apache/spark/pull/21155
**[Test build #92334 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/92334/testReport)** for PR 21155 at commit [`d6de8cb`](https://github.com/apache/spark/commit/d6de8cb9b571f23dc357caf818295d359e19ff3d).
* This patch passes all tests.
* This patch merges cleanly.
* This patch adds no public classes.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:
https://github.com/apache/spark/pull/21155
Test PASSed.
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/90428/
Test PASSed.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:
https://github.com/apache/spark/pull/21155
Merged build finished. Test PASSed.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark pull request #21155: SPARK-23927: Add "sequence" expression
Posted by ueshin <gi...@git.apache.org>.
Github user ueshin commented on a diff in the pull request:
https://github.com/apache/spark/pull/21155#discussion_r186028756
--- Diff: sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/collectionOperations.scala ---
@@ -1059,3 +1063,316 @@ case class Flatten(child: Expression) extends UnaryExpression {
override def prettyName: String = "flatten"
}
+
+@ExpressionDescription(
+ usage = """
+ _FUNC_(start, stop, step) -
+ Generates an array of elements from start to stop (inclusive), incrementing by step.
+ The type of the returned elements is the same as the type of argument expressions.
+
+ Supported types are: byte, short, integer, long, date, timestamp.
+
+ The start and stop expressions must resolve to the same type.
+ If start and stop expressions resolve to the 'date' or 'timestamp' type
+ then the step expression must resolve to the 'interval' type, otherwise to the same type
+ as the start and stop expressions.
+ """,
+ arguments = """
+ Arguments:
+ * start - an expression. The start of the range.
+ * stop - an expression. The end the range (inclusive).
+ * step - an optional expression. The step of the range.
+
+ By default step is 1 if start is less than or equal to stop, otherwise -1.
+ For the temporal sequences it's 1 day and -1 day respectively.
+
+ If start is greater than stop then the step must be negative, and vice versa.
+ """,
+ examples = """
+ Examples:
+ > SELECT _FUNC_(1, 5);
+ [1, 2, 3, 4, 5]
+ > SELECT _FUNC_(5, 1);
+ [5, 4, 3, 2, 1]
+ > SELECT _FUNC_(to_date('2018-01-01'), to_date('2018-03-01'), interval 1 month);
+ [2018-01-01, 2018-02-01, 2018-03-01]
+ """,
+ since = "2.4.0"
+)
+case class Sequence(left: Expression,
+ middle: Expression,
+ right: Expression,
+ timeZoneId: Option[String] = None)
+ extends TernaryExpression with TimeZoneAwareExpression {
--- End diff --
nit: style
```scala
case class Sequence(
left: Expression,
middle: Expression,
right: Expression,
timeZoneId: Option[String] = None)
extends TernaryExpression with TimeZoneAwareExpression {
...
```
And should we use `start`, `stop`, `step` instead of `left`, `middle`, `right` respectively for readability?
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: SPARK-23927: Add "sequence" expression
Posted by SparkQA <gi...@git.apache.org>.
Github user SparkQA commented on the issue:
https://github.com/apache/spark/pull/21155
**[Test build #89854 has finished](https://amplab.cs.berkeley.edu/jenkins/job/SparkPullRequestBuilder/89854/testReport)** for PR 21155 at commit [`88fde1c`](https://github.com/apache/spark/commit/88fde1c3a3d009a9a138df3cf2825e22248afa2a).
* This patch **fails Spark unit tests**.
* This patch merges cleanly.
* This patch adds no public classes.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org
[GitHub] spark issue #21155: [SPARK-23927][SQL] Add "sequence" expression
Posted by AmplabJenkins <gi...@git.apache.org>.
Github user AmplabJenkins commented on the issue:
https://github.com/apache/spark/pull/21155
Test PASSed.
Refer to this link for build results (access rights to CI server needed):
https://amplab.cs.berkeley.edu/jenkins//job/SparkPullRequestBuilder/92331/
Test PASSed.
---
---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org