Skip to content

Commit 9f040d4

Browse files
[Spark] Current Date/Time resolution in constraints (delta-io#2766)
<!-- Thanks for sending a pull request! Here are some tips for you: 1. If this is your first time, please read our contributor guidelines: https://github.com/delta-io/delta/blob/master/CONTRIBUTING.md 2. If the PR is unfinished, add '[WIP]' in your PR title, e.g., '[WIP] Your PR title ...'. 3. Be sure to keep the PR description updated to reflect all changes. 4. Please write your PR title to summarize what this PR proposes. 5. If possible, provide a concise example to reproduce the issue for a faster review. 6. If applicable, include the corresponding issue number in the PR title and link it in the body. --> #### Which Delta project/connector is this regarding? <!-- Please add the component selected below to the beginning of the pull request title For example: [Spark] Title of my pull request --> - [x] Spark - [ ] Standalone - [ ] Flink - [ ] Kernel - [ ] Other (fill in here) ## Description <!-- - Describe what this PR changes. - Describe why we need the change. If this PR resolves an issue be sure to include "Resolves #XXX" to correctly link and close the issue upon merge. --> Heading towards the removal of codegenFallback from Date/Time expressions (apache/spark#44261), delta constraints need to resolve current_datetime expressions during the analysis of the invariants. The proposed changes work for both Spark 3.5 and Spark master. ## How was this patch tested? <!-- If tests were added, say they were added here. Please make sure to test the changes thoroughly including negative and positive cases if possible. If the changes were tested in any way other than unit tests, please clarify how you tested step by step (ideally copy and paste-able, so that other reviewers can test and check, and descendants can verify in the future). If the changes were not tested, please explain why. --> Existing tests. In particular, `CheckConstaintsSuite` covers constraints with `current_timestamp()` expressions. Added an extra test to cover `current_date()`. ## Does this PR introduce _any_ user-facing changes? <!-- If yes, please clarify the previous behavior and the change this PR proposes - provide the console output, description and/or an example to show the behavior difference if possible. If possible, please also clarify if this is a user-facing change compared to the released Delta Lake versions or within the unreleased branches such as master. If no, write 'No'. --> No.
1 parent 8cd0f94 commit 9f040d4

File tree

2 files changed

+18
-6
lines changed

2 files changed

+18
-6
lines changed

spark/src/main/scala/org/apache/spark/sql/delta/constraints/DeltaInvariantCheckerExec.scala

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,10 +27,12 @@ import org.apache.spark.sql.SparkSession
2727
import org.apache.spark.sql.catalyst.InternalRow
2828
import org.apache.spark.sql.catalyst.analysis._
2929
import org.apache.spark.sql.catalyst.expressions._
30+
import org.apache.spark.sql.catalyst.optimizer
3031
import org.apache.spark.sql.catalyst.optimizer.ReplaceExpressions
3132
import org.apache.spark.sql.catalyst.plans.logical.{LogicalPlan, UnaryNode}
3233
import org.apache.spark.sql.catalyst.plans.physical.Partitioning
3334
import org.apache.spark.sql.catalyst.rules.RuleExecutor
35+
import org.apache.spark.sql.delta.util.AnalysisHelper
3436
import org.apache.spark.sql.execution.{SparkPlan, SparkStrategy, UnaryExecNode}
3537
import org.apache.spark.sql.types.StructType
3638

@@ -71,9 +73,17 @@ case class DeltaInvariantCheckerExec(
7173
if (constraints.isEmpty) return child.execute()
7274
val invariantChecks =
7375
DeltaInvariantCheckerExec.buildInvariantChecks(child.output, constraints, session)
74-
val boundRefs = invariantChecks.map(_.withBoundReferences(child.output))
76+
77+
// Resolve current_date()/current_time() expressions.
78+
// We resolve currentTime for all invariants together to make sure we use the same timestamp.
79+
val invariantsFakePlan = AnalysisHelper.FakeLogicalPlan(invariantChecks, Nil)
80+
val newInvariantsPlan = optimizer.ComputeCurrentTime(invariantsFakePlan)
81+
val localOutput = child.output
7582

7683
child.execute().mapPartitionsInternal { rows =>
84+
val boundRefs = newInvariantsPlan.expressions
85+
.asInstanceOf[Seq[CheckDeltaInvariant]]
86+
.map(_.withBoundReferences(localOutput))
7787
val assertions = UnsafeProjection.create(boundRefs)
7888
rows.map { row =>
7989
assertions(row)

spark/src/test/scala/org/apache/spark/sql/delta/schema/CheckConstraintsSuite.scala

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -277,18 +277,20 @@ class CheckConstraintsSuite extends QueryTest
277277
}
278278
}
279279

280-
testQuietly("constraint with analyzer-evaluated expressions") {
280+
for (expression <- Seq("year(current_date())", "unix_timestamp()"))
281+
testQuietly(s"constraint with analyzer-evaluated expressions. Expression: $expression") {
281282
withTestTable { table =>
282-
// We use current_timestamp() as the most convenient analyzer-evaluated expression - of course
283-
// in a realistic use case it'd probably not be right to add a constraint on a
283+
// We use current_timestamp()/current_date() as the most convenient
284+
// analyzer-evaluated expressions - of course in a realistic use case
285+
// it'd probably not be right to add a constraint on a
284286
// nondeterministic expression.
285287
sql(s"ALTER TABLE $table ADD CONSTRAINT maxWithAnalyzerEval " +
286-
s"CHECK (num < unix_timestamp())")
288+
s"CHECK (num < $expression)")
287289
val e = intercept[InvariantViolationException] {
288290
sql(s"INSERT INTO $table VALUES (${Int.MaxValue}, 'data')")
289291
}
290292
errorContains(e.getMessage,
291-
"maxwithanalyzereval (num < unix_timestamp()) violated by row")
293+
s"maxwithanalyzereval (num < $expression) violated by row")
292294
}
293295
}
294296

0 commit comments

Comments
 (0)