This is an automated email from the ASF dual-hosted git repository.

LuciferYang pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/spark.git


The following commit(s) were added to refs/heads/master by this push:
     new 183ccbe75d45 [SPARK-60032][SQL] Do not freeze the current time and the 
like in a CHECK constraint added by ALTER TABLE
183ccbe75d45 is described below

commit 183ccbe75d45eb70ea1db0c09f5f49ba2eb35a7e
Author: YangJie <[email protected]>
AuthorDate: Wed Nov 11 22:06:39 2026 +0800

    [SPARK-60032][SQL] Do not freeze the current time and the like in a CHECK 
constraint added by ALTER TABLE
    
    ### What changes were proposed in this pull request?
    
    `ALTER TABLE ... ADD CONSTRAINT ... CHECK` builds the V2 predicate it 
stores from the optimized condition, where the optimizer has already replaced 
`current_timestamp()`, `current_date()`, `current_database()`, `current_user()` 
and the like with their values at the time of the ALTER TABLE. A later write 
that reads the predicate back compares with those values.
    
    This PR stores such a constraint without a predicate, so each write parses 
`predicateSql` and computes the values itself. `CheckConstraint` decides this 
from the analyzed condition when `AddCheckConstraint` stores its analyzed 
query. A condition reads the current context if it calls a function that the 
optimizer replaces with the current time, date, catalog, user and the like, 
casts TIME to a timestamp, or casts a constant string that reads the current 
date: 'now', 'today', 'tomorrow' [...]
    
    A condition that a write could read differently keeps the predicate built 
from the optimized condition, as before:
    - a variable or an `IDENTIFIER` clause, which a write looks up in its own 
session;
    - a name such as `current_date` or `user` without parentheses, or a column 
with such a name, which a write resolves to the function or to a column 
depending on its case sensitivity, its reserved keywords and the columns of the 
table at that time;
    - a name with more than one part, since the parser cannot tell a table 
qualifier, which a write resolves differently (SPARK-60286), from a struct 
column;
    - a CHAR column, whose comparison with a shorter literal is padded only at 
the ALTER TABLE;
    - a parameter marker that 
`spark.sql.legacy.parameterSubstitution.constantsOnly` leaves in 
`predicateSql`, which a write cannot bind (CREATE TABLE has the same problem, 
SPARK-60457);
    - a constant that reads no current value and may depend on the session time 
zone, such as a typed `TIMESTAMP` literal, `'2024-01-01 00:00:00'` cast to a 
timestamp or `make_timestamp(DATE'2024-01-01', TIME'00:00')`;
    - a text that the parser settings of the ALTER TABLE session, such as 
`spark.sql.ansi.doubleQuotedIdentifiers` or 
`spark.sql.parser.escapedStringLiterals`, read differently from their default 
values (ANSI mode, the timestamp type and the time zone are taken from the 
session), as `StoredExpressionText.readsAsInSession` checks for a generation 
expression, or that has a `${...}` placeholder, which a write may substitute.
    
    The parser marks the cases that the analyzed condition no longer shows, for 
ALTER TABLE only. A condition that calls a user-defined function is rejected as 
before, without being evaluated first. With 
`spark.sql.legacy.freezeCurrentValuesInCheckConstraint`, ALTER TABLE stores the 
predicate as before. The Javadoc of `Check.predicate()` now says that it can be 
null for such a condition, and that a connector that validates or enforces the 
constraint itself has to evaluate `predicateSql()`.
    
    The predicate is not built from the analyzed condition instead, because 
`V2ExpressionBuilder` folds `CAST('today' AS DATE)` there as an ordinary cast 
(SPARK-60451).
    
    Not covered: typed literals such as `DATE 'today'`, which the parser folds 
(SPARK-60452); conditions folded early under 
`spark.sql.legacy.earlyEvalCurrentTime` (SPARK-60456); and casts into an array, 
map or struct of timestamps, from a VARIANT, or of a string that only the 
optimizer makes constant. On their own, these are stored as before. When 
another part of the condition gets the constraint stored without a predicate, 
each write evaluates them too. CREATE and REPLACE TABLE build th [...]
    
    ### Why are the changes needed?
    
    ```sql
    -- t is in a catalog that supports table constraints
    CREATE TABLE t (id INT, ts TIMESTAMP);
    ALTER TABLE t ADD CONSTRAINT vt CHECK (ts <= current_timestamp());
    -- the stored predicate is ts <= <the time of the ALTER TABLE>
    INSERT INTO t VALUES (1, current_timestamp());
    -- [CHECK_CONSTRAINT_VIOLATION] CHECK constraint vt ts <= 
current_timestamp() violated ...
    ```
    
    ### Does this PR introduce _any_ user-facing change?
    
    Yes, for a CHECK constraint that ALTER TABLE adds to a Data Source V2 table:
    - One that reads the current time, date, catalog, user and the like is 
checked against their values at the time of each write. One that also has a 
part listed above is stored as before, so `d <= CURRENT_DATE` still compares 
with the date of the ALTER TABLE (SPARK-61194).
    - A write reads a constraint stored without a predicate under its own 
session settings, as it reads a CREATE TABLE constraint without one. A setting 
such as `spark.sql.caseSensitive`, `spark.sql.ansi.doubleQuotedIdentifiers`, or 
`spark.sql.ansi.enforceReservedKeywords`, which reserves `TIME`, can make it 
fail to read the text or read it differently (SPARK-60453).
    - A row-level operation that copies unchanged rows, such as a DELETE or 
UPDATE on a copy-on-write table, fails on a copied row that no longer satisfies 
the condition at the time of the write (SPARK-60453).
    - `Check.predicate()` is null for a constraint stored without a predicate.
    - A constraint added before this change keeps its stored predicate until it 
is dropped and added again. Setting 
`spark.sql.legacy.freezeCurrentValuesInCheckConstraint` to `true` before adding 
a constraint stores it as before.
    
    The SQL migration guide has an entry for this.
    
    ### How was this patch tested?
    
    `CheckConstraintSuite`, for constraints added by ALTER TABLE:
    - `created <= <now>` is stored without a predicate. It accepts a row 
written with the current value and rejects a later one, with `<now>` each of 
`current_timestamp()`, `to_timestamp('now')`, 'now' cast to TIMESTAMP and 
TIMESTAMP_NTZ, a time-only string cast to TIMESTAMP and TIMESTAMP_LTZ(9), TIME 
cast to TIMESTAMP and TIMESTAMP_NTZ, `current_date()` and `CAST('today' AS 
DATE)`.
    - `db = current_database()` is checked against the namespace of each write, 
with the error and its parameters pinned, and `p = current_path` is stored 
without a predicate.
    - These keep their predicate:
      - a condition with a session variable or `IDENTIFIER(var)`. Writes still 
pass after the variable is dropped.
      - `owner = user`, `d <= current_date` and ``d <= `current_date` ``, and 
`owner = user` added under `spark.sql.ansi.enforceReservedKeywords`. They still 
reject a row after a column of that name is added.
      - a condition that reads a column named `user`, written `user` or `` 
`USER` ``, and the current time.
      - `status = 'OPEN' OR closed <= current_date()` and `status <> 'CLOSED' 
OR closed <= current_date()` on a CHAR(10) column, which accept an 'OPEN' row 
and reject a 'CLOSED' row respectively.
      - `nullif(tbl.id, 3) > 0` on a table with a struct column `tbl`, which 
writes check against the column `id`, and `tbl.id > 0 AND ts <= 
current_timestamp() + INTERVAL 1 DAY`.
      - 'epoch' and full datetime strings.
      - a parameter marker under the legacy parameter substitution. Without it, 
the same condition is stored without a predicate.
      - a text that `spark.sql.ansi.doubleQuotedIdentifiers` or 
`spark.sql.parser.escapedStringLiterals` reads differently, also with 
`spark.sql.legacy.useCurrentConfigsForGeneratedColumn`, and a `${...}` 
placeholder.
      - `ts >= <bound> AND ts <= current_timestamp()` with the bound written as 
a string, a typed `TIMESTAMP` literal, `to_timestamp` with a format or 
`make_timestamp(DATE, TIME)`, added in UTC. A write from America/Los_Angeles 
accepts a row at 2024-01-01 00:30:00 UTC.
      - `ts <= current_timestamp()` under the legacy config.
    - `d >= DATE '2024-01-01' AND d <= current_date()` and, on a TIMESTAMP_NTZ 
column, `ts >= '2024-01-01 00:00:00' AND ts <= localtimestamp()` are stored 
without a predicate.
    - Under ANSI mode, a division by zero inside a cast to `TIMESTAMP_LTZ(9)`, 
in a branch that may not run, does not fail the ALTER TABLE, and `rand() > 0 OR 
CAST(CAST(1/0 AS STRING) AS DATE) IS NOT NULL` reports 
NON_DETERMINISTIC_CHECK_CONSTRAINT rather than DIVIDE_BY_ZERO.
    - ALTER TABLE does not call a user-defined function in a condition it then 
rejects.
    - Normalizing the optimized plan keeps the decision made at the end of the 
analysis.
    
    `CheckConstraintParseSuite`: comparing a parsed ALTER TABLE that casts a 
column to TIMESTAMP does not decide its predicate. Only ALTER TABLE marks a 
name with more than one part, a keyword such as `user` or `current_date` 
without parentheses, also backquoted, in a lambda body or under 
`spark.sql.ansi.enforceReservedKeywords`, and an `IDENTIFIER` clause.
    
    `SpecialDatetimeValuesSuite` and `DateTimeUtilsSuite`: the helpers for 
special values other than 'epoch' and for time-only strings.
    
    ### Was this patch authored or co-authored using generative AI tooling?
    
    Generated-by: Claude Opus 5
    
    Closes #59545 from LuciferYang/SPARK-60032.
    
    Lead-authored-by: YangJie <[email protected]>
    Co-authored-by: reviewer <reviewer@local>
    Signed-off-by: yangjie01 <[email protected]>
    
    
    skip-checks: true
---
 docs/sql-migration-guide.md                        |   1 +
 .../sql/connector/catalog/constraints/Check.java   |  20 +-
 .../analysis/LiteralFunctionResolution.scala       |  13 +-
 .../sql/catalyst/expressions/constraints.scala     | 153 +++++++-
 .../sql/catalyst/optimizer/finishAnalysis.scala    |  32 +-
 .../spark/sql/catalyst/parser/AstBuilder.scala     |  25 +-
 .../plans/logical/v2AlterTableCommands.scala       |  14 +-
 .../sql/catalyst/plans/logical/v2Commands.scala    |   4 +-
 .../spark/sql/catalyst/util/DateTimeUtils.scala    |  28 ++
 .../org/apache/spark/sql/internal/SQLConf.scala    |  12 +
 .../optimizer/SpecialDatetimeValuesSuite.scala     |  12 +
 .../sql/catalyst/util/DateTimeUtilsSuite.scala     |  16 +
 .../command/CheckConstraintParseSuite.scala        |  46 +++
 .../command/v2/CheckConstraintSuite.scala          | 417 ++++++++++++++++++++-
 14 files changed, 770 insertions(+), 23 deletions(-)

diff --git a/docs/sql-migration-guide.md b/docs/sql-migration-guide.md
index 20a270eab43f..876cf10b8276 100644
--- a/docs/sql-migration-guide.md
+++ b/docs/sql-migration-guide.md
@@ -94,6 +94,7 @@ license: |
 - Since Spark 4.4, `ALTER TABLE ... ADD CONSTRAINT` with a CHECK constraint 
fails with `EXPECT_TABLE_NOT_VIEW.NO_ALTERNATIVE` when the target is a view, as 
it does with the other constraint types. Previously, when the view only 
projected or filtered a Data Source V2 table, the statement added the 
constraint to that table after validating only the rows of the view 
(SPARK-60822). To add the constraint, run the statement on the table.
 - Since Spark 4.4, a write to a Data Source V2 table that parses the SQL text 
of a CHECK constraint binds an unqualified built-in function name to 
`system.builtin`, regardless of the SQL path and 
`spark.sql.functionResolution.sessionOrder` (SPARK-60777). Previously, an 
existing constraint could call another function with the same name.
 - Since Spark 4.4, `CREATE TABLE`, `REPLACE TABLE`, and `ALTER TABLE ... ADD 
CONSTRAINT` on a Data Source V2 table fail with `SUBQUERY_IN_CHECK_CONSTRAINT` 
when the condition of a CHECK constraint contains a subquery. `ALTER TABLE ... 
ADD CONSTRAINT` keeps failing with 
`UNSUPPORTED_SUBQUERY_EXPRESSION_CATEGORY.HIGHER_ORDER_FUNCTION` on a subquery 
in a lambda function. Previously, most of these statements failed with 
`INTERNAL_ERROR`, but a subquery that needed no resolution, such as `id  [...]
+- Since Spark 4.4, a CHECK constraint that `ALTER TABLE ... ADD CONSTRAINT` 
adds to a Data Source V2 table, and whose condition reads the current time, 
date, catalog, user and the like, such as `ts <= current_timestamp()` or `db = 
current_database()`, is checked against their values at the time of each write. 
Previously, it was checked against their values at the time of the `ALTER 
TABLE`, unless a write could not read back a predicate for its condition, such 
as one with a lambda functio [...]
 - Since Spark 4.4, a function created by `CREATE FUNCTION ... AS 'class'` 
whose class implements 
`org.apache.spark.sql.connector.catalog.functions.UnboundFunction` and extends 
either a Hive UDF class (such as `UDF` or `GenericUDF`) or 
`org.apache.spark.sql.expressions.UserDefinedAggregateFunction` runs as a 
DataSource V2 function instead of a Hive UDF or Spark UDAF, including functions 
created in earlier versions. Its result type, argument coercion, and null 
handling are defined by the V [...]
 
 ## Upgrading from Spark SQL 4.3.0 to 4.3.1
diff --git 
a/sql/catalyst/src/main/java/org/apache/spark/sql/connector/catalog/constraints/Check.java
 
b/sql/catalyst/src/main/java/org/apache/spark/sql/connector/catalog/constraints/Check.java
index 5addd4b09842..a28797862287 100644
--- 
a/sql/catalyst/src/main/java/org/apache/spark/sql/connector/catalog/constraints/Check.java
+++ 
b/sql/catalyst/src/main/java/org/apache/spark/sql/connector/catalog/constraints/Check.java
@@ -29,10 +29,10 @@ import 
org.apache.spark.sql.connector.expressions.filter.Predicate;
  * <p>
  * A CHECK constraint defines a condition each row in a table must satisfy. 
The condition is always
  * represented as a SQL string (Spark SQL dialect), accessible via {@link 
#predicateSql()}, and is
- * additionally exposed as a {@link Predicate predicate} via {@link 
#predicate()} whenever it can be
- * expressed using supported expressions. A CHECK constraint can reference one 
or more columns. Such
- * constraint is considered violated if its condition evaluates to {@code 
FALSE}, but not
- * {@code NULL}. The search condition must be deterministic and cannot contain 
subqueries and
+ * additionally exposed as a {@link Predicate predicate} via {@link 
#predicate()}, which is
+ * {@code null} in the cases that method lists. A CHECK constraint can 
reference one or more
+ * columns. Such constraint is considered violated if its condition evaluates 
to {@code FALSE}, but
+ * not {@code NULL}. The search condition must be deterministic and cannot 
contain subqueries and
  * certain functions like aggregates or UDFs.
  * <p>
  * Spark supports enforced and not enforced CHECK constraints, allowing 
connectors to control
@@ -66,8 +66,8 @@ public class Check extends BaseConstraint {
    * Returns the SQL representation of the search condition (Spark SQL 
dialect).
    * <p>
    * This is the canonical representation of the condition and is always 
present (never
-   * {@code null}). The optional {@link #predicate()} provides a structured 
form when the condition
-   * can be expressed using supported {@link Predicate} expressions.
+   * {@code null}). The optional {@link #predicate()} provides a structured 
form, except in the
+   * cases that method lists.
    */
   public String predicateSql() {
     return predicateSql;
@@ -75,8 +75,12 @@ public class Check extends BaseConstraint {
 
   /**
    * Returns the search condition as a {@link Predicate}, or {@code null} if 
the condition cannot be
-   * expressed using supported predicate expressions. Use {@link 
#predicateSql()} for the canonical
-   * SQL representation, which is always present.
+   * expressed using supported predicate expressions. Spark may also leave it 
{@code null} for a
+   * condition that reads the current time, date, catalog, user and the like, 
so that each write
+   * evaluates it from {@link #predicateSql()} with its own values instead of 
comparing with the
+   * values at the time the constraint was added. A connector that validates 
or enforces such a
+   * constraint itself has to evaluate {@link #predicateSql()}. Use {@link 
#predicateSql()} for the
+   * canonical SQL representation, which is always present.
    */
   public Predicate predicate() {
     return predicate;
diff --git 
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/LiteralFunctionResolution.scala
 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/LiteralFunctionResolution.scala
index 6f09aeff0bdf..4fbbdddb7844 100644
--- 
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/LiteralFunctionResolution.scala
+++ 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/analysis/LiteralFunctionResolution.scala
@@ -29,15 +29,22 @@ object LiteralFunctionResolution {
    * When an attributes is not resolvable, we try to resolve it as a literal 
function.
    */
   def resolve(nameParts: Seq[String]): Option[NamedExpression] = {
-    if (nameParts.length != 1) return None
-    val name = nameParts.head
-    literalFunctions.find(func => caseInsensitiveResolution(func._1, 
name)).map {
+    find(nameParts).map {
       case (_, getFuncExpr, getAliasName) =>
         val funcExpr = getFuncExpr()
         Alias(funcExpr, getAliasName(funcExpr))()
     }
   }
 
+  /** Whether `nameParts` is the name of a literal function, which `resolve` 
resolves. */
+  def isLiteralFunction(nameParts: Seq[String]): Boolean = 
find(nameParts).isDefined
+
+  private def find(
+      nameParts: Seq[String]): Option[(String, () => Expression, Expression => 
String)] = {
+    if (nameParts.length != 1) return None
+    literalFunctions.find(func => caseInsensitiveResolution(func._1, 
nameParts.head))
+  }
+
   // support CURRENT_DATE, CURRENT_TIMESTAMP, CURRENT_TIME,
   //  CURRENT_USER, USER, SESSION_USER and grouping__id
   private val literalFunctions: Seq[(String, () => Expression, Expression => 
String)] = Seq(
diff --git 
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/constraints.scala
 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/constraints.scala
index 8fdf886f1444..76001ba3559a 100644
--- 
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/constraints.scala
+++ 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/constraints.scala
@@ -22,13 +22,16 @@ import org.apache.spark.sql.catalyst.InternalRow
 import org.apache.spark.sql.catalyst.analysis.{AnalysisErrorAt, 
StoredExpressionFunctions, TypeCheckResult, UnresolvedException}
 import org.apache.spark.sql.catalyst.expressions.codegen.{Block, 
CodegenContext, ExprCode, FalseLiteral, TrueLiteral}
 import org.apache.spark.sql.catalyst.expressions.codegen.Block.BlockHelper
+import org.apache.spark.sql.catalyst.optimizer.{ReplaceExpressions, 
SpecialDatetimeValues}
 import org.apache.spark.sql.catalyst.parser.ParseException
 import org.apache.spark.sql.catalyst.trees.CurrentOrigin
-import org.apache.spark.sql.catalyst.util.V2ExpressionBuilder
+import org.apache.spark.sql.catalyst.trees.TreePattern.{CURRENT_LIKE, 
VARIABLE_REFERENCE}
+import org.apache.spark.sql.catalyst.util.{CharVarcharUtils, DateTimeUtils, 
StoredExpressionText, V2ExpressionBuilder}
 import org.apache.spark.sql.connector.catalog.constraints.Constraint
 import org.apache.spark.sql.connector.expressions.FieldReference
 import org.apache.spark.sql.errors.QueryExecutionErrors
-import org.apache.spark.sql.types.{AbstractDataType, BooleanType, DataType}
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.types.{AbstractDataType, BooleanType, CharType, 
DataType, TimestampFamily}
 
 trait TableConstraint extends Expression with Unevaluable {
   /** Convert to a data source v2 constraint */
@@ -120,7 +123,8 @@ case class CheckConstraint(
     condition: String,
     override val userProvidedName: String = null,
     override val tableName: String = null,
-    override val userProvidedCharacteristic: ConstraintCharacteristic = 
ConstraintCharacteristic.empty)
+    override val userProvidedCharacteristic: ConstraintCharacteristic = 
ConstraintCharacteristic.empty,
+    omitPredicate: Option[Boolean] = None)
   extends UnaryExpression
   with TableConstraint
   with ImplicitCastInputTypes {
@@ -151,8 +155,58 @@ case class CheckConstraint(
     }
   }
 
+  // The decision is printed only once made, so that the plan string of a 
constraint without one
+  // stays as it was.
+  override def stringArgs: Iterator[Any] =
+    Iterator(child, condition, userProvidedName, tableName, 
userProvidedCharacteristic) ++
+      omitPredicate.iterator.map(omit => s"omitPredicate=$omit")
+
+  /**
+   * Decides from the analyzed condition whether to store the constraint 
without a predicate
+   * (`omitPredicate`), unless the parser has already decided to keep it.
+   * `AddCheckConstraint.storeAnalyzedQuery` calls this at the end of the 
analysis of an ALTER
+   * TABLE. CREATE and REPLACE TABLE never decide, and store the predicate if 
there is one.
+   *
+   * A write parses `condition` again, with its own settings. It cannot bind a 
parameter marker
+   * that the legacy parameter substitution leaves there, resolves an 
IDENTIFIER clause in its own
+   * session, and does not resolve a column qualified by the table name the 
way ALTER TABLE does.
+   * It also resolves a name such as `current_date` or `user` to the function 
or to a column,
+   * depending on its case sensitivity, its reserved keywords and the columns 
of the table at that
+   * time. None of them can be told apart after analysis, so the parser keeps 
the predicate for
+   * them, and for any name with more than one part, since it cannot tell a 
table qualifier from a
+   * struct column. Such a condition, one that `resolvesDifferentlyOnWrite`, 
and one that a write
+   * with the default parser settings reads differently (`readsAsOnWrite`) 
keep the predicate built
+   * from the optimized plan, as before. So does one that calls a user-defined 
function, which the
+   * analysis rejects next and which is not evaluated here, and every 
condition under
+   * `spark.sql.legacy.freezeCurrentValuesInCheckConstraint`.
+   */
+  def withPredicateDecision(): CheckConstraint = if (omitPredicate.isDefined) 
this else {
+    // Computed only after the check for a user-defined function, since 
finding the reads of the
+    // current context evaluates constant strings.
+    lazy val replaced = ReplaceExpressions.replace(child)
+    lazy val readsCurrentContext = 
CheckConstraint.nodesReadingCurrentContext(replaced)
+    copy(omitPredicate = Some(
+      !SQLConf.get.getConf(SQLConf.FREEZE_CURRENT_VALUES_IN_CHECK_CONSTRAINT) 
&&
+        StoredExpressionFunctions.findUserDefinedFunctionCall(child).isEmpty &&
+        !CheckConstraint.resolvesDifferentlyOnWrite(child, replaced, 
readsCurrentContext) &&
+        readsCurrentContext(replaced) &&
+        CheckConstraint.readsAsOnWrite(condition)))
+  }
+
+  // ALTER TABLE calls this on the optimized plan, where the current time, 
date, catalog, user and
+  // the like are replaced by their values at the time of the ALTER TABLE. A 
condition that
+  // `withPredicateDecision` finds reading one is stored without a predicate, 
so that writes check
+  // `predicateSql`. ALTER TABLE does not build the predicate from the 
analyzed condition instead,
+  // because `V2ExpressionBuilder` folds `CAST('today' AS DATE)` there as an 
ordinary cast.
+  // CREATE and REPLACE TABLE call this on the analyzed condition 
(`ResolveTableSpec`), where that
+  // folding still happens (SPARK-60451). Only `AddCheckConstraint` decides, 
so they always store
+  // the predicate if there is one.
   def toV2Constraint: Constraint = {
-    val predicate = new V2ExpressionBuilder(child, 
true).buildPredicate().orNull
+    val predicate = if (omitPredicate.contains(true)) {
+      null
+    } else {
+      new V2ExpressionBuilder(child, true).buildPredicate().orNull
+    }
     val enforced = userProvidedCharacteristic.enforced.getOrElse(true)
     val rely = userProvidedCharacteristic.rely.getOrElse(false)
     Constraint
@@ -194,6 +248,97 @@ case class CheckConstraint(
   }
 }
 
+object CheckConstraint {
+  /**
+   * Which nodes of `replaced`, an expression whose `RuntimeReplaceable`s are 
replaced, read the
+   * current time, date, catalog, user and the like, which the optimizer 
replaces with their
+   * values, found in one bottom-up pass. A node reads one if a node of its 
subtree is one of:
+   *  - a node with the CURRENT_LIKE pattern, which stands in for 
`ReplaceCurrentLike`, which needs
+   *    a `CatalogManager`, and for the functions `ComputeCurrentTime` 
replaces;
+   *  - a cast from TIME to a timestamp, which `ComputeCurrentTime` rewrites 
without that pattern;
+   *  - a cast that `castReadsCurrentDate`.
+   * The result answers by identity, so only for the nodes of `replaced` 
itself.
+   */
+  private def nodesReadingCurrentContext(replaced: Expression): Expression => 
Boolean = {
+    val reading = java.util.Collections.newSetFromMap(
+      new java.util.IdentityHashMap[Expression, java.lang.Boolean]())
+    def visit(e: Expression): Boolean = {
+      // Every child is visited, so that each node that reads one is recorded.
+      val childReads = e.children.map(visit).contains(true)
+      val reads = childReads || e.containsPattern(CURRENT_LIKE) || (e match {
+        case c: Cast =>
+          Cast.isTimeToTimestampNTZ(c.child.dataType, c.dataType) ||
+            Cast.isTimeToTimestampLTZ(c.child.dataType, c.dataType) || 
castReadsCurrentDate(c)
+        case _ => false
+      })
+      if (reads) reading.add(e)
+      reads
+    }
+    visit(replaced)
+    reading.contains
+  }
+
+  /**
+   * Whether `cast` reads the current date: `SpecialDatetimeValues` replaces 
it with the value of
+   * 'now', 'today', 'tomorrow' or 'yesterday', or it casts a string with only 
a time part to a
+   * timestamp with local time zone, which completes it with the current date. 
Only a cast of a
+   * constant string at the top level counts, not one into an array, map or 
struct of timestamps,
+   * from a VARIANT, or of a string that only the optimizer makes constant.
+   */
+  private def castReadsCurrentDate(cast: Cast): Boolean = {
+    val completesTime = TimestampFamily.isLtz(cast.dataType)
+    (completesTime || SpecialDatetimeValues.rewrites(cast.dataType)) &&
+      SpecialDatetimeValues.constantString(cast).exists { s =>
+        SpecialDatetimeValues.readsCurrentDate(s, cast.dataType) ||
+          (completesTime && DateTimeUtils.isTimeOnlyTimestamp(s))
+      }
+  }
+
+  /**
+   * Whether a write with the default parser settings reads `condition` as 
this session does, which
+   * `StoredExpressionText` decides for a generation expression too, so ANSI 
mode, the timestamp
+   * type and the session time zone are those of this session. A `${...}` 
placeholder counts as
+   * read differently, since a write with `spark.sql.variable.substitute` may 
replace it.
+   */
+  private def readsAsOnWrite(condition: String): Boolean = 
!condition.contains("${") && {
+    val conf = SQLConf.get.clone()
+    // Under its legacy config, `StoredExpressionText` would compare the 
session with itself.
+    conf.setConf(SQLConf.USE_CURRENT_SQL_CONFIGS_FOR_GENERATED_COLUMN, false)
+    
SQLConf.withExistingConf(conf)(StoredExpressionText.readsAsInSession(condition))
+  }
+
+  /**
+   * Whether a write that parses the condition resolves `e` differently: `e` 
reads a variable, which
+   * the write looks up in its own session, a column whose type is or contains 
CHAR, which the
+   * write reads without the CHAR type that pads the literals compared with 
it, or a constant that
+   * may depend on the session time zone and reads no current value, such as a 
typed `TIMESTAMP`
+   * literal or `'2024-01-01 00:00:00'` cast to a timestamp, which the write 
computes in its own
+   * time zone. Apart from a cast, which counts only if it needs the time 
zone, a foldable
+   * expression of a timestamp type that reads no current value counts whether 
or not it depends on
+   * the time zone, such as `timestamp_seconds(0)`, and then keeps its 
predicate as before. A
+   * user-defined function is rejected by `failIfCallsUserDefinedFunction`.
+   */
+  private def resolvesDifferentlyOnWrite(
+      e: Expression,
+      replaced: Expression,
+      readsCurrentContext: Expression => Boolean): Boolean = {
+    e.containsPattern(VARIABLE_REFERENCE) ||
+      e.references.exists { a =>
+        val rawType = CharVarcharUtils.getRawType(a.metadata)
+        rawType.exists(_.existsRecursively(_.isInstanceOf[CharType]))
+      } ||
+      replaced.exists {
+        case c: Cast => c.foldable && c.needsTimeZone && 
!readsCurrentContext(c)
+        case t: TimeZoneAwareExpression => t.foldable && 
!readsCurrentContext(t)
+        // A typed literal, or a function such as 
`make_timestamp(DATE'2024-01-01', TIME'00:00')`
+        // that the replacement turns into a call with the session time zone 
as an argument.
+        case x if x.foldable && 
x.dataType.existsRecursively(TimestampFamily.isLtz) =>
+          !readsCurrentContext(x)
+        case _ => false
+      }
+  }
+}
+
 // scalastyle:off line.size.limit
 case class PrimaryKeyConstraint(
     columns: Seq[String],
diff --git 
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/finishAnalysis.scala
 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/finishAnalysis.scala
index c32995d973a1..44d60c74d344 100644
--- 
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/finishAnalysis.scala
+++ 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/optimizer/finishAnalysis.scala
@@ -37,6 +37,7 @@ import 
org.apache.spark.sql.catalyst.util.SparkDateTimeUtils.{instantToNanosOfDa
 import org.apache.spark.sql.catalyst.util.TypeUtils.toSQLExpr
 import org.apache.spark.sql.connector.catalog.CatalogManager
 import org.apache.spark.sql.types._
+import org.apache.spark.unsafe.types.UTF8String
 
 
 /**
@@ -316,14 +317,41 @@ object SpecialDatetimeValues extends Rule[LogicalPlan] {
     
expression.transformWithPruning(_.containsPattern(CAST))(specialDatetimeRewrite)
   }
 
+  /** Whether this rule may replace a cast to `dt`. */
+  private[sql] def rewrites(dt: DataType): Boolean = conv.contains(dt)
+
+  /**
+   * Whether this rule replaces a cast of `s` to `dt` with a value that reads 
the current date, that
+   * is, the value of a special value other than 'epoch'.
+   */
+  private[sql] def readsCurrentDate(s: UTF8String, dt: DataType): Boolean =
+    conv.get(dt).exists(_(s.toString, java.time.ZoneOffset.UTC).isDefined) &&
+      !DateTimeUtils.isEpochSpecialValue(s.toString)
+
+  /**
+   * The constant string that `cast` casts, or None if it casts something else 
or evaluating the
+   * string fails. Unlike the rule, this does not throw.
+   */
+  private[sql] def constantString(cast: Cast): Option[UTF8String] = cast.child 
match {
+    case e if isConstantString(e) =>
+      try {
+        Option(e.eval().asInstanceOf[UTF8String])
+      } catch {
+        case NonFatal(_) => None
+      }
+    case _ => None
+  }
+
   private val specialDatetimeRewrite: PartialFunction[Expression, Expression] 
= {
-    case cast @ Cast(e, dt @ (DateType | TimestampType | TimestampNTZType), _, 
_)
-      if e.foldable && e.dataType.isInstanceOf[StringType] =>
+    case cast @ Cast(e, dt, _, _) if rewrites(dt) && isConstantString(e) =>
       Option(e.eval())
         .flatMap(s => conv(dt)(s.toString, cast.zoneId))
         .map(Literal(_, dt))
         .getOrElse(cast)
   }
+
+  private def isConstantString(e: Expression): Boolean =
+    e.foldable && e.dataType.isInstanceOf[StringType]
 }
 
 object ReplaceTranspose extends Rule[LogicalPlan] {
diff --git 
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/parser/AstBuilder.scala
 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/parser/AstBuilder.scala
index c27766c16f40..a44a920aa298 100644
--- 
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/parser/AstBuilder.scala
+++ 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/parser/AstBuilder.scala
@@ -44,7 +44,7 @@ import org.apache.spark.sql.catalyst.parser.SqlBaseParser._
 import org.apache.spark.sql.catalyst.plans._
 import org.apache.spark.sql.catalyst.plans.logical._
 import org.apache.spark.sql.catalyst.trees.{CurrentOrigin, Origin}
-import org.apache.spark.sql.catalyst.trees.TreePattern.PARAMETER
+import org.apache.spark.sql.catalyst.trees.TreePattern.{PARAMETER, 
UNRESOLVED_IDENTIFIER}
 import org.apache.spark.sql.catalyst.types.DataTypeUtils
 import org.apache.spark.sql.catalyst.util.{CharVarcharUtils, CollationFactory, 
DateTimeConstants, DateTimeUtils, EvaluateUnresolvedInlineTable, IntervalUtils, 
WriteDistributionAndOrdering}
 import org.apache.spark.sql.catalyst.util.DateTimeUtils.{convertSpecialDate, 
convertSpecialTimestamp, convertSpecialTimestampNTZ, fractionalSecondsDigits, 
getZoneId, stringToDate, stringToTime, stringToTimestamp, 
stringToTimestampLTZNanos, stringToTimestampNTZNanos, 
stringToTimestampWithoutTimeZone}
@@ -7194,6 +7194,26 @@ class AstBuilder extends DataTypeAstBuilder
         condition = condition)
     }
 
+  /**
+   * Whether a write that parses the condition of a CHECK constraint again can 
resolve it
+   * differently from the ALTER TABLE, so that the constraint keeps its 
predicate; see
+   * `CheckConstraint.withPredicateDecision`. A keyword such as `current_date` 
or `user` without
+   * parentheses parses as a name, or as the function under
+   * `spark.sql.ansi.enforceReservedKeywords`, which is the only way the 
parser builds these
+   * functions.
+   */
+  private def keepsCheckPredicate(condition: Expression): Boolean = {
+    val names = condition.collect {
+      case u: UnresolvedAttribute => u.nameParts
+      case v: UnresolvedNamedLambdaVariable => v.nameParts
+    }
+    condition.containsAnyPattern(PARAMETER, UNRESOLVED_IDENTIFIER) ||
+      names.exists(n => n.length > 1 || 
LiteralFunctionResolution.isLiteralFunction(n)) ||
+      condition.exists {
+        case _: CurrentDate | _: CurrentTimestamp | _: CurrentTime | _: 
CurrentUser => true
+        case _ => false
+      }
+  }
 
   override def visitUniqueConstraint(ctx: UniqueConstraintContext): 
TableConstraint =
     withOrigin(ctx) {
@@ -7256,7 +7276,8 @@ class AstBuilder extends DataTypeAstBuilder
           case c: CheckConstraint =>
             val relation = createUnresolvedRelation(ctx.identifierReference)
             val child = Filter(Not(c.child), relation)
-            AddCheckConstraint(child, c)
+            val check = if (keepsCheckPredicate(c.child)) c.copy(omitPredicate 
= Some(false)) else c
+            AddCheckConstraint(child, check)
           case _ =>
             val child = UnresolvedTable(identifiers, "ALTER TABLE ... ADD 
CONSTRAINT")
             AddConstraint(child, namedConstraint)
diff --git 
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/v2AlterTableCommands.scala
 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/v2AlterTableCommands.scala
index d254bdf5ced1..7097eee07056 100644
--- 
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/v2AlterTableCommands.scala
+++ 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/v2AlterTableCommands.scala
@@ -386,8 +386,18 @@ case class AddCheckConstraint(
     analyzedQuery: Option[LogicalPlan] = None) extends UnaryCommand with 
KeepAnalyzedQuery {
 
   // The optimizer replaces the filtered scan with an empty relation if no row 
can violate the
-  // check, so keep the analyzed child to find the table when planning.
-  override def storeAnalyzedQuery(): Command = copy(analyzedQuery = 
Some(child))
+  // check, so keep the analyzed child to find the table when planning. The 
constraint decides
+  // here, with its condition analyzed, whether to store a predicate. 
`NormalizePlan` also calls
+  // this, on parsed and optimized plans too, so the decision is made only 
once, on a resolved
+  // constraint.
+  override def storeAnalyzedQuery(): Command = {
+    val check = if (checkConstraint.resolved) {
+      checkConstraint.withPredicateDecision()
+    } else {
+      checkConstraint
+    }
+    copy(checkConstraint = check, analyzedQuery = Some(child))
+  }
 
   override protected def withNewChildInternal(newChild: LogicalPlan): 
LogicalPlan =
     copy(child = newChild)
diff --git 
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/v2Commands.scala
 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/v2Commands.scala
index a13002687e04..5ff9448a1ec6 100644
--- 
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/v2Commands.scala
+++ 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/plans/logical/v2Commands.scala
@@ -53,7 +53,9 @@ import org.apache.spark.util.collection.BitSet
 // that DataFrame, instead of the optimized query plan, as building DataFrame 
optimizes the
 // query plan again. This trait defines a `storeAnalyzedQuery` function which 
will be called at
 // the end of analysis, and implementations should copy the input query plan 
into a non-child
-// field so that it won't be transformed by the optimizer.
+// field so that it won't be transformed by the optimizer. 
`storeAnalyzedQuery` may also take
+// from the analyzed plan what the command needs later, as 
`AddCheckConstraint` decides there
+// whether to store a predicate. `NormalizePlan` calls it too, on plans in any 
phase.
 trait KeepAnalyzedQuery extends Command {
   def storeAnalyzedQuery(): Command
 }
diff --git 
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/DateTimeUtils.scala
 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/DateTimeUtils.scala
index 47f7e3df82d5..25e2861f27e9 100644
--- 
a/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/DateTimeUtils.scala
+++ 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/DateTimeUtils.scala
@@ -877,6 +877,34 @@ object DateTimeUtils extends SparkDateTimeUtils {
     }
   }
 
+  /**
+   * Whether `input` is the special value 'epoch', the only one that 
`convertSpecialDate`,
+   * `convertSpecialTimestamp` and `convertSpecialTimestampNTZ` convert 
without reading the
+   * current date or time.
+   *
+   * @param input A string to check. It can contain trailing or leading 
whitespaces.
+   */
+  private[sql] def isEpochSpecialValue(input: String): Boolean =
+    extractSpecialValue(input.trim).contains("epoch")
+
+  /**
+   * Whether `input` is a valid timestamp string with only a time part, which 
a cast to a timestamp
+   * with local time zone completes with the current date.
+   */
+  private[sql] def isTimeOnlyTimestamp(input: UTF8String): Boolean = {
+    try {
+      val (segments, _, justTime) = parseTimestampString(input)
+      segments.nonEmpty && justTime && {
+        // Validates the time fields as `stringToTimestamp` does when it 
builds the time.
+        LocalTime.of(segments(3), segments(4), segments(5),
+          (MICROSECONDS.toNanos(segments(6)) + segments(9)).toInt)
+        true
+      }
+    } catch {
+      case NonFatal(_) => false
+    }
+  }
+
   /**
    * Subtracts two dates expressed as days since 1970-01-01.
    *
diff --git 
a/sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala 
b/sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala
index b7885038ec9e..1de4431aef9b 100644
--- a/sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala
+++ b/sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala
@@ -4649,6 +4649,18 @@ object SQLConf {
       .booleanConf
       .createWithDefault(false)
 
+  val FREEZE_CURRENT_VALUES_IN_CHECK_CONSTRAINT =
+    buildConf("spark.sql.legacy.freezeCurrentValuesInCheckConstraint")
+      .internal()
+      .doc("When true, ALTER TABLE ... ADD CONSTRAINT ... CHECK on a Data 
Source V2 table stores " +
+        "the predicate of a condition that reads the current time, date, 
catalog, user and the " +
+        "like, if Spark can build one, with their values at the time of the 
ALTER TABLE, as " +
+        "before, so that a write that can read the predicate back compares 
with those values.")
+      .version("4.4.0")
+      .withBindingPolicy(ConfigBindingPolicy.SESSION)
+      .booleanConf
+      .createWithDefault(false)
+
   val STORE_ANALYZED_PLAN_FOR_VIEW =
     buildConf("spark.sql.legacy.storeAnalyzedPlanForView")
       .internal()
diff --git 
a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/SpecialDatetimeValuesSuite.scala
 
b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/SpecialDatetimeValuesSuite.scala
index 814df8b3426e..23348e296f47 100644
--- 
a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/SpecialDatetimeValuesSuite.scala
+++ 
b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/optimizer/SpecialDatetimeValuesSuite.scala
@@ -139,4 +139,16 @@ class SpecialDatetimeValuesSuite extends PlanTest {
       testSpecialTs(TimestampNTZType, expected, zoneId)
     }
   }
+
+  test("SPARK-60032: a cast of a special value reads the current date unless 
it is 'epoch'") {
+    Seq(DateType, TimestampType, TimestampNTZType).foreach { dt =>
+      Seq("now", " Today ", "TOMORROW", "yesterday", "tomorrow CET").foreach { 
s =>
+        
assert(SpecialDatetimeValues.readsCurrentDate(UTF8String.fromString(s), dt), 
s"$s $dt")
+      }
+      Seq("epoch", "now UTC", "2020-01-01", "12:00:00", "", "abc").foreach { s 
=>
+        
assert(!SpecialDatetimeValues.readsCurrentDate(UTF8String.fromString(s), dt), 
s"$s $dt")
+      }
+    }
+    
assert(!SpecialDatetimeValues.readsCurrentDate(UTF8String.fromString("now"), 
StringType))
+  }
 }
diff --git 
a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/util/DateTimeUtilsSuite.scala
 
b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/util/DateTimeUtilsSuite.scala
index f9b0b5d13913..dc7728a367b6 100644
--- 
a/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/util/DateTimeUtilsSuite.scala
+++ 
b/sql/catalyst/src/test/scala/org/apache/spark/sql/catalyst/util/DateTimeUtilsSuite.scala
@@ -1103,6 +1103,22 @@ class DateTimeUtilsSuite extends SparkFunSuite with 
Matchers with SQLHelper {
     }
   }
 
+  test("SPARK-60032: 'epoch' and time-only strings") {
+    Seq("epoch", " Epoch ", "EPOCH UTC").foreach { s =>
+      assert(isEpochSpecialValue(s), s)
+    }
+    Seq("now", "today", "2020-01-01", "12:00:00", "", "abc").foreach { s =>
+      assert(!isEpochSpecialValue(s), s)
+    }
+    Seq("12:00:00", " 23:59:59.999999 ", "T12:00", "12:00:00 UTC").foreach { s 
=>
+      assert(isTimeOnlyTimestamp(UTF8String.fromString(s)), s)
+    }
+    Seq("2020-01-01 12:00:00", "2020-01-01", "now", "", "abc", "24:00:00", 
"23:59:60",
+      "12:60").foreach { s =>
+      assert(!isTimeOnlyTimestamp(UTF8String.fromString(s)), s)
+    }
+  }
+
   test("parsing day of week") {
     assert(getDayOfWeekFromString(UTF8String.fromString("THU")) == 0)
     assert(getDayOfWeekFromString(UTF8String.fromString("MONDAY")) == 4)
diff --git 
a/sql/core/src/test/scala/org/apache/spark/sql/execution/command/CheckConstraintParseSuite.scala
 
b/sql/core/src/test/scala/org/apache/spark/sql/execution/command/CheckConstraintParseSuite.scala
index 2971d34da0e2..d4d904f09d97 100644
--- 
a/sql/core/src/test/scala/org/apache/spark/sql/execution/command/CheckConstraintParseSuite.scala
+++ 
b/sql/core/src/test/scala/org/apache/spark/sql/execution/command/CheckConstraintParseSuite.scala
@@ -22,6 +22,7 @@ import org.apache.spark.sql.catalyst.expressions._
 import org.apache.spark.sql.catalyst.parser.CatalystSqlParser.parsePlan
 import org.apache.spark.sql.catalyst.parser.ParseException
 import org.apache.spark.sql.catalyst.plans.logical.{AddCheckConstraint, 
ColumnDefinition, CreateTable, Filter, ReplaceTable, UnresolvedTableSpec}
+import org.apache.spark.sql.internal.SQLConf
 import org.apache.spark.sql.types.StringType
 
 class CheckConstraintParseSuite extends ConstraintParseSuiteBase {
@@ -197,6 +198,51 @@ class CheckConstraintParseSuite extends 
ConstraintParseSuiteBase {
     comparePlans(parsed, expected)
   }
 
+  test("SPARK-60032: Add check constraint with a cast to TIMESTAMP") {
+    // Comparing plans calls `storeAnalyzedQuery`, which must leave the 
predicate of an unresolved
+    // constraint undecided: deciding it would read the type of `d`.
+    val condition = "CAST(d AS TIMESTAMP) > TIMESTAMP'2020-01-01 00:00:00'"
+    val parsed = parsePlan(s"ALTER TABLE a.b.t ADD CONSTRAINT c1 CHECK 
($condition)")
+    val child = parsed.asInstanceOf[AddCheckConstraint].checkConstraint.child
+    val expected = AddCheckConstraint(
+      Filter(Not(child), UnresolvedRelation(Seq("a", "b", "t"))),
+      CheckConstraint(child = child, condition = condition, userProvidedName = 
"c1",
+        tableName = "t"))
+    comparePlans(parsed, expected)
+  }
+
+  test("SPARK-60032: only ALTER TABLE marks a condition that a write can 
resolve differently") {
+    def keepsPredicate(condition: String): Boolean =
+      parsePlan(s"ALTER TABLE a.b.t ADD CONSTRAINT c1 CHECK ($condition)") 
match {
+        case a: AddCheckConstraint => 
a.checkConstraint.omitPredicate.contains(false)
+        case other => fail(s"Expected AddCheckConstraint, but got: $other")
+      }
+    Seq("a.b > 0", "a = user", "a = `current_date`", "IDENTIFIER(v) > 0",
+        "exists(s, x -> x = user)", "exists(s, x -> x = `user`)", "exists(s, x 
-> x = t.id)",
+        "exists(s, x -> x = current_user.y)").foreach { condition =>
+      assert(keepsPredicate(condition), condition)
+    }
+    Seq("a > 0", "a = current_user()", "a = current_path").foreach { condition 
=>
+      assert(!keepsPredicate(condition), condition)
+    }
+    withSQLConf(SQLConf.ANSI_ENABLED.key -> "true",
+        SQLConf.ENFORCE_RESERVED_KEYWORDS.key -> "true") {
+      Seq("a = user", "a <= current_date", "a <= current_timestamp", "a = 
localtime",
+          "exists(s, x -> x = user)").foreach { condition =>
+        assert(keepsPredicate(condition), condition)
+      }
+      assert(!keepsPredicate("a = current_path"))
+    }
+
+    // A CREATE TABLE constraint gets no decision, and always stores its 
predicate.
+    val created = parsePlan("CREATE TABLE t (a STRUCT<b: INT>, s 
ARRAY<STRING>, " +
+      "CONSTRAINT c1 CHECK (a.b > 0 AND exists(s, x -> x = user))) USING 
parquet")
+    val constraints = created.collectFirst {
+      case c: CreateTable => 
c.tableSpec.asInstanceOf[UnresolvedTableSpec].constraints
+    }.getOrElse(fail(s"Expected CreateTable, but got: $created"))
+    assert(constraints.map(_.asInstanceOf[CheckConstraint].omitPredicate) == 
Seq(None))
+  }
+
   test("Add invalid check constraint name") {
     val sql =
       """
diff --git 
a/sql/core/src/test/scala/org/apache/spark/sql/execution/command/v2/CheckConstraintSuite.scala
 
b/sql/core/src/test/scala/org/apache/spark/sql/execution/command/v2/CheckConstraintSuite.scala
index 060091e6dc2a..db2d243b4316 100644
--- 
a/sql/core/src/test/scala/org/apache/spark/sql/execution/command/v2/CheckConstraintSuite.scala
+++ 
b/sql/core/src/test/scala/org/apache/spark/sql/execution/command/v2/CheckConstraintSuite.scala
@@ -23,13 +23,15 @@ import 
test.org.apache.spark.sql.connector.catalog.functions.JavaStrLen.JavaStrL
 import org.apache.spark.SparkRuntimeException
 import org.apache.spark.sql.{AnalysisException, MapTypeBufferAgg, QueryTest, 
Row}
 import org.apache.spark.sql.catalyst.InternalRow
-import org.apache.spark.sql.catalyst.plans.logical.Filter
+import org.apache.spark.sql.catalyst.plans.NormalizePlan
+import org.apache.spark.sql.catalyst.plans.logical.{AddCheckConstraint, 
Filter, LogicalPlan}
 import org.apache.spark.sql.catalyst.util.AttributeNameParser
 import org.apache.spark.sql.catalyst.util.QuotingUtils.quoteNameParts
 import org.apache.spark.sql.connector.{ConstantStringOfAnyArity, StrLen, 
StrLenDefault, StrLenMagic}
 import org.apache.spark.sql.connector.catalog.{Identifier, InMemoryCatalog, 
Table, TableCatalog, TableChange}
 import org.apache.spark.sql.connector.catalog.constraints.{Check, Constraint}
 import org.apache.spark.sql.connector.catalog.functions.{ScalarFunction, 
UnboundFunction}
+import org.apache.spark.sql.execution.CommandExecutionMode
 import org.apache.spark.sql.execution.command.DDLCommandTestUtils
 import org.apache.spark.sql.functions.udaf
 import org.apache.spark.sql.internal.SQLConf
@@ -45,6 +47,18 @@ private object ConstantString extends 
ScalarFunction[UTF8String] {
   override def produceResult(input: InternalRow): UTF8String = 
UTF8String.fromString("OK")
 }
 
+// A V2 function that counts its calls.
+private object CountingString extends ScalarFunction[UTF8String] {
+  @volatile var calls = 0
+  override def inputTypes(): Array[DataType] = Array(StringType)
+  override def resultType(): DataType = StringType
+  override def name(): String = "counting_string"
+  override def produceResult(input: InternalRow): UTF8String = {
+    calls += 1
+    input.getUTF8String(0)
+  }
+}
+
 class CheckConstraintSuite extends QueryTest with CommandSuiteBase with 
DDLCommandTestUtils {
   override protected def command: String = "Check CONSTRAINT"
 
@@ -247,6 +261,407 @@ class CheckConstraintSuite extends QueryTest with 
CommandSuiteBase with DDLComma
     }
   }
 
+  test("SPARK-60032: Check constraint added by ALTER TABLE reading the current 
time") {
+    // The check compares with the time of the write, not the time of the 
ALTER TABLE. 'now' is
+    // read after the snapshot `current_timestamp()` takes, so only `<=` holds 
for a row written
+    // with `current_timestamp()`. A string with only a time part and 'today' 
read the date after
+    // that snapshot too, so their rows step two days ahead in case the date 
changes in between.
+    Seq(
+      ("TIMESTAMP", "current_timestamp()", "current_timestamp()", "INTERVAL 1 
DAY"),
+      ("TIMESTAMP", "CAST('now' AS TIMESTAMP)", "current_timestamp()", 
"INTERVAL 1 DAY"),
+      ("TIMESTAMP", "to_timestamp('now')", "current_timestamp()", "INTERVAL 1 
DAY"),
+      ("TIMESTAMP", "CAST('23:59:59.999999' AS TIMESTAMP)", 
"current_timestamp()",
+        "INTERVAL 2 DAYS"),
+      ("TIMESTAMP_LTZ(9)", "CAST('23:59:59.999999' AS TIMESTAMP_LTZ(9))", 
"current_timestamp()",
+        "INTERVAL 2 DAYS"),
+      ("TIMESTAMP", "CAST(TIME '23:59:59.999999' AS TIMESTAMP)", 
"current_timestamp()",
+        "INTERVAL 1 DAY"),
+      ("TIMESTAMP_NTZ", "CAST(TIME '23:59:59.999999' AS TIMESTAMP_NTZ)", 
"localtimestamp()",
+        "INTERVAL 1 DAY"),
+      ("TIMESTAMP_NTZ", "CAST('now' AS TIMESTAMP_NTZ)", "localtimestamp()", 
"INTERVAL 1 DAY"),
+      ("DATE", "current_date()", "current_date()", "1"),
+      ("DATE", "CAST('today' AS DATE)", "current_date()", "2")
+    ).foreach { case (dataType, now, current, step) =>
+      withNamespaceAndTable("ns", "tbl", nonPartitionCatalog) { t =>
+        sql(s"CREATE TABLE $t (id INT, created $dataType) $defaultUsing")
+        sql(s"ALTER TABLE $t ADD CONSTRAINT valid_time CHECK (created <= 
$now)")
+        val check = getCheckConstraint(loadTable(nonPartitionCatalog, "ns", 
"tbl"))
+        assert(check.predicateSql() == s"created <= $now")
+        assert(check.predicate() == null, now)
+
+        sql(s"INSERT INTO $t VALUES (1, $current)")
+        checkAnswer(spark.table(t).select("id"), Seq(Row(1)))
+
+        val error = intercept[SparkRuntimeException] {
+          sql(s"INSERT INTO $t VALUES (2, $current + $step)")
+        }
+        assert(error.getCondition == "CHECK_CONSTRAINT_VIOLATION")
+        assert(error.getMessageParameters.get("constraintName") == 
"valid_time")
+      }
+    }
+  }
+
+  test("SPARK-60032: Normalizing an optimized ALTER TABLE keeps the decision 
of the analysis") {
+    // `NormalizePlan` calls `storeAnalyzedQuery` again. In the optimized plan 
the condition holds
+    // the time of the ALTER TABLE, so deciding there would store the 
predicate.
+    withNamespaceAndTable("ns", "tbl", nonPartitionCatalog) { t =>
+      sql(s"CREATE TABLE $t (id INT, created TIMESTAMP) $defaultUsing")
+      val plan = spark.sessionState.sqlParser.parsePlan(
+        s"ALTER TABLE $t ADD CONSTRAINT c1 CHECK (created <= 
current_timestamp())")
+      val qe = spark.sessionState.executePlan(plan, CommandExecutionMode.SKIP)
+      def omitsPredicate(p: LogicalPlan): Boolean = p.collectFirst {
+        case a: AddCheckConstraint => 
a.checkConstraint.omitPredicate.contains(true)
+      }.getOrElse(fail(s"Expected AddCheckConstraint, but got: $p"))
+      assert(omitsPredicate(qe.analyzed))
+      assert(omitsPredicate(NormalizePlan(qe.optimizedPlan)))
+    }
+  }
+
+  test("SPARK-60032: Check constraint added by ALTER TABLE on a column 
qualified by the table") {
+    // ALTER TABLE resolves `tbl.id` as the column `id` of the table `tbl`, 
not as the field `id` of
+    // its struct column `tbl`. A write that parses `predicateSql` reads 
`tbl.id` as the field, so
+    // the test fails if this constraint is stored without a predicate. 
`nullif` has no V2 form
+    // before the optimizer replaces it, so the test also fails if the 
predicate is built from the
+    // analyzed condition.
+    withNamespaceAndTable("ns", "tbl", nonPartitionCatalog) { t =>
+      sql(s"CREATE TABLE $t (id BIGINT, tbl STRUCT<id: BIGINT>) $defaultUsing")
+      sql(s"ALTER TABLE $t ADD CONSTRAINT c1 CHECK (nullif(tbl.id, 3) > 0)")
+      sql(s"INSERT INTO $t VALUES (3, named_struct('id', -1L))")
+      val error = intercept[SparkRuntimeException] {
+        sql(s"INSERT INTO $t VALUES (-1, named_struct('id', 3L))")
+      }
+      checkError(
+        exception = error,
+        condition = "CHECK_CONSTRAINT_VIOLATION",
+        sqlState = "23001",
+        parameters = Map(
+          "constraintName" -> "c1",
+          "expression" -> "nullif(tbl.id, 3) > 0",
+          "values" -> " - id : -1"))
+      checkAnswer(spark.table(t).select("id"), Seq(Row(3)))
+    }
+    // The same holds for a condition that also reads the current time: it 
keeps the predicate.
+    withNamespaceAndTable("ns", "tbl", nonPartitionCatalog) { t =>
+      sql(s"CREATE TABLE $t (id BIGINT, ts TIMESTAMP, tbl STRUCT<id: BIGINT>) 
$defaultUsing")
+      sql(s"ALTER TABLE $t ADD CONSTRAINT c1 CHECK " +
+        "(tbl.id > 0 AND ts <= current_timestamp() + INTERVAL 1 DAY)")
+      assert(getCheckConstraint(loadTable(nonPartitionCatalog, "ns", 
"tbl")).predicate() != null)
+      sql(s"INSERT INTO $t VALUES (1, current_timestamp(), named_struct('id', 
-1L))")
+      checkAnswer(spark.table(t).select("id"), Seq(Row(1)))
+    }
+  }
+
+  test("SPARK-60032: Check constraint added by ALTER TABLE on a fixed 
datetime") {
+    // 'epoch' and a full datetime string do not read the current date, so the 
predicate is kept.
+    Seq(
+      "created >= CAST('epoch' AS TIMESTAMP)",
+      "created >= 'epoch'",
+      "created >= CAST('2020-01-01 00:00:00' AS TIMESTAMP)").foreach { cond =>
+      withNamespaceAndTable("ns", "tbl", nonPartitionCatalog) { t =>
+        sql(s"CREATE TABLE $t (id INT, created TIMESTAMP) $defaultUsing")
+        sql(s"ALTER TABLE $t ADD CONSTRAINT c1 CHECK ($cond)")
+        assert(getCheckConstraint(loadTable(nonPartitionCatalog, "ns", 
"tbl")).predicate() != null,
+          cond)
+      }
+    }
+    // A write that parses `predicateSql` fails to resolve `tbl.created`, so 
this fails if the
+    // constraint is stored without a predicate.
+    withNamespaceAndTable("ns", "tbl", nonPartitionCatalog) { t =>
+      sql(s"CREATE TABLE $t (id INT, created TIMESTAMP) $defaultUsing")
+      sql(s"ALTER TABLE $t ADD CONSTRAINT c1 CHECK (tbl.created >= 'epoch')")
+      sql(s"INSERT INTO $t VALUES (1, TIMESTAMP '2020-01-01 00:00:00')")
+      val error = intercept[SparkRuntimeException] {
+        sql(s"INSERT INTO $t VALUES (2, TIMESTAMP '1960-01-01 00:00:00')")
+      }
+      assert(error.getCondition == "CHECK_CONSTRAINT_VIOLATION")
+      checkAnswer(spark.table(t).select("id"), Seq(Row(1)))
+    }
+  }
+
+  test("SPARK-60032: Check constraint added by ALTER TABLE with a parameter 
marker") {
+    // Under the legacy parameter substitution, the marker stays in 
`predicateSql`, which a write
+    // cannot bind, so the constraint keeps the predicate built from the 
optimized plan. Otherwise
+    // the marker is substituted before parsing and the constraint is stored 
without a predicate.
+    Seq(true, false).foreach { legacy =>
+      withSQLConf(SQLConf.LEGACY_PARAMETER_SUBSTITUTION_CONSTANTS_ONLY.key -> 
legacy.toString) {
+        withNamespaceAndTable("ns", "tbl", nonPartitionCatalog) { t =>
+          sql(s"CREATE TABLE $t (id INT, ts TIMESTAMP) $defaultUsing")
+          spark.sql(s"ALTER TABLE $t ADD CONSTRAINT c1 CHECK " +
+            "(ts >= current_timestamp() - make_interval(0, 0, 0, :d))", 
Map("d" -> 1))
+          val check = getCheckConstraint(loadTable(nonPartitionCatalog, "ns", 
"tbl"))
+          assert(check.predicateSql().contains(":d") == legacy, 
check.predicateSql())
+          assert((check.predicate() != null) == legacy, check.predicateSql())
+
+          sql(s"INSERT INTO $t VALUES (1, current_timestamp())")
+          val error = intercept[SparkRuntimeException] {
+            sql(s"INSERT INTO $t VALUES (2, current_timestamp() - INTERVAL 2 
DAYS)")
+          }
+          assert(error.getCondition == "CHECK_CONSTRAINT_VIOLATION")
+          checkAnswer(spark.table(t).select("id"), Seq(Row(1)))
+        }
+      }
+    }
+  }
+
+  test("SPARK-60032: Check constraint added by ALTER TABLE reading the current 
database") {
+    withNamespace(s"$nonPartitionCatalog.ns2") {
+      sql(s"CREATE NAMESPACE $nonPartitionCatalog.ns2")
+      withNamespaceAndTable("ns", "tbl", nonPartitionCatalog) { t =>
+        withCurrentCatalogAndNamespace {
+          sql(s"CREATE TABLE $t (id INT, db STRING) $defaultUsing")
+          sql(s"USE $nonPartitionCatalog.ns")
+          sql(s"ALTER TABLE $t ADD CONSTRAINT valid_db CHECK (db = 
current_database())")
+          assert(getCheckConstraint(loadTable(nonPartitionCatalog, "ns", 
"tbl")).predicate() ==
+            null)
+
+          sql(s"USE $nonPartitionCatalog.ns2")
+          sql(s"INSERT INTO $t VALUES (1, 'ns2')")
+          checkError(
+            exception = intercept[SparkRuntimeException] {
+              sql(s"INSERT INTO $t VALUES (2, 'ns')")
+            },
+            condition = "CHECK_CONSTRAINT_VIOLATION",
+            sqlState = "23001",
+            parameters = Map(
+              "constraintName" -> "valid_db",
+              "expression" -> "db = current_database()",
+              "values" -> " - db : ns"))
+          checkAnswer(spark.table(t).select("id"), Seq(Row(1)))
+        }
+      }
+    }
+    // `current_path` without parentheses parses as the function under any 
settings, so unlike
+    // `current_user` it is stored without a predicate.
+    withNamespaceAndTable("ns", "tbl", nonPartitionCatalog) { t =>
+      sql(s"CREATE TABLE $t (id INT, p STRING) $defaultUsing")
+      sql(s"ALTER TABLE $t ADD CONSTRAINT c1 CHECK (p = current_path)")
+      assert(getCheckConstraint(loadTable(nonPartitionCatalog, "ns", 
"tbl")).predicate() == null)
+    }
+  }
+
+  test("SPARK-60032: Check constraint added by ALTER TABLE resolving names in 
the session") {
+    // A write would resolve a variable or an IDENTIFIER clause in its own 
session, so such a
+    // condition keeps the predicate built from the optimized plan. The name 
is gone by the time of
+    // the write, so the write fails if the constraint is stored without a 
predicate.
+    def checkKeepsPredicate(cond: String)(dropName: => Unit): Unit = {
+      withNamespaceAndTable("ns", "tbl", nonPartitionCatalog) { t =>
+        sql(s"CREATE TABLE $t (id INT, ts TIMESTAMP) $defaultUsing")
+        sql(s"ALTER TABLE $t ADD CONSTRAINT c1 CHECK ($cond)")
+        assert(getCheckConstraint(loadTable(nonPartitionCatalog, "ns", 
"tbl")).predicate() != null,
+          cond)
+        dropName
+        sql(s"INSERT INTO $t VALUES (1, current_timestamp())")
+        checkAnswer(spark.table(t).select("id"), Seq(Row(1)))
+      }
+    }
+    withSessionVariable("days", "c") {
+      sql("DECLARE VARIABLE days INT DEFAULT 30")
+      checkKeepsPredicate("ts >= current_timestamp() - make_interval(0, 0, 0, 
days)") {
+        sql("DROP TEMPORARY VARIABLE days")
+      }
+      sql("DECLARE VARIABLE c STRING DEFAULT 'ts'")
+      checkKeepsPredicate("IDENTIFIER(c) <= current_timestamp() + INTERVAL 1 
DAY") {
+        sql("DROP TEMPORARY VARIABLE c")
+      }
+    }
+  }
+
+  test("SPARK-60032: Check constraint added by ALTER TABLE comparing a CHAR 
column") {
+    // ALTER TABLE pads 'OPEN' to the length of `status`, but a write that 
parses `predicateSql`
+    // does not, so the constraint keeps the predicate built from the 
optimized plan.
+    Seq(
+      ("status = 'OPEN' OR closed <= current_date()", "OPEN", true),
+      ("status <> 'CLOSED' OR closed <= current_date()", "CLOSED", false)
+    ).foreach { case (cond, status, accepted) =>
+      withNamespaceAndTable("ns", "tbl", nonPartitionCatalog) { t =>
+        sql(s"CREATE TABLE $t (id INT, status CHAR(10), closed DATE) 
$defaultUsing")
+        sql(s"ALTER TABLE $t ADD CONSTRAINT c1 CHECK ($cond)")
+        assert(getCheckConstraint(loadTable(nonPartitionCatalog, "ns", 
"tbl")).predicate() != null,
+          cond)
+        val insert = s"INSERT INTO $t VALUES (1, '$status', DATE'2999-01-01')"
+        if (accepted) {
+          sql(insert)
+          checkAnswer(spark.table(t).select("id"), Seq(Row(1)))
+        } else {
+          val error = intercept[SparkRuntimeException](sql(insert))
+          assert(error.getCondition == "CHECK_CONSTRAINT_VIOLATION", cond)
+        }
+      }
+    }
+  }
+
+  test("SPARK-60032: Check constraint added by ALTER TABLE with an error in a 
branch") {
+    // The optimizer keeps an expression that fails in a branch that may not 
run, and so does the
+    // check for the current date.
+    withSQLConf(SQLConf.ANSI_ENABLED.key -> "true") {
+      // A cast to DATE, TIMESTAMP or TIMESTAMP_NTZ fails in 
`SpecialDatetimeValues`, so this one
+      // casts to TIMESTAMP_LTZ(9).
+      withNamespaceAndTable("ns", "tbl", nonPartitionCatalog) { t =>
+        sql(s"CREATE TABLE $t (id INT, ts TIMESTAMP) $defaultUsing")
+        sql(s"ALTER TABLE $t ADD CONSTRAINT c1 CHECK " +
+          "(id < IF(false, hour(CAST(CAST(1/0 AS STRING) AS 
TIMESTAMP_LTZ(9))), 100))")
+        sql(s"INSERT INTO $t VALUES (1, current_timestamp())")
+        checkAnswer(spark.table(t).select("id"), Seq(Row(1)))
+      }
+      Seq("TIMESTAMP", "DATE").foreach { to =>
+        withNamespaceAndTable("ns", "tbl", nonPartitionCatalog) { t =>
+          sql(s"CREATE TABLE $t (id INT) $defaultUsing")
+          val error = intercept[AnalysisException] {
+            sql(s"ALTER TABLE $t ADD CONSTRAINT c1 CHECK " +
+              s"(rand() > 0 OR CAST(CAST(1/0 AS STRING) AS $to) IS NOT NULL)")
+          }
+          assert(error.getCondition == "NON_DETERMINISTIC_CHECK_CONSTRAINT", 
to)
+        }
+      }
+    }
+  }
+
+  test("SPARK-60032: Check constraint added by ALTER TABLE with a function 
without parentheses") {
+    // A write that parses `predicateSql` resolves `user` or `current_date` to 
a column of that name
+    // added later, so such a condition keeps the predicate built from the 
optimized plan.
+    Seq(
+      ("owner STRING", "owner = user", "user STRING", "'', ''"),
+      ("d DATE", "d <= current_date", "current_date DATE", "DATE'2999-01-01', 
DATE'2999-12-31'"),
+      ("d DATE", "d <= `current_date`", "current_date DATE", 
"DATE'2999-01-01', DATE'2999-12-31'")
+    ).foreach { case (column, cond, added, values) =>
+      withNamespaceAndTable("ns", "tbl", nonPartitionCatalog) { t =>
+        sql(s"CREATE TABLE $t (id INT, $column) $defaultUsing")
+        sql(s"ALTER TABLE $t ADD CONSTRAINT c1 CHECK ($cond)")
+        assert(getCheckConstraint(loadTable(nonPartitionCatalog, "ns", 
"tbl")).predicate() != null,
+          cond)
+        sql(s"ALTER TABLE $t ADD COLUMN $added")
+        val error = intercept[SparkRuntimeException](sql(s"INSERT INTO $t 
VALUES (1, $values)"))
+        assert(error.getCondition == "CHECK_CONSTRAINT_VIOLATION", cond)
+      }
+    }
+    // With `spark.sql.ansi.enforceReservedKeywords`, the keyword parses as 
the function, which a
+    // write with the default settings resolves to such a column.
+    withNamespaceAndTable("ns", "tbl", nonPartitionCatalog) { t =>
+      sql(s"CREATE TABLE $t (id INT, owner STRING) $defaultUsing")
+      withSQLConf(SQLConf.ANSI_ENABLED.key -> "true",
+          SQLConf.ENFORCE_RESERVED_KEYWORDS.key -> "true") {
+        sql(s"ALTER TABLE $t ADD CONSTRAINT c1 CHECK (owner = user)")
+      }
+      assert(getCheckConstraint(loadTable(nonPartitionCatalog, "ns", 
"tbl")).predicate() != null)
+      sql(s"ALTER TABLE $t ADD COLUMN user STRING")
+      val error = intercept[SparkRuntimeException](sql(s"INSERT INTO $t VALUES 
(1, '', '')"))
+      assert(error.getCondition == "CHECK_CONSTRAINT_VIOLATION")
+    }
+    // A column with such a name keeps the predicate too. A write with
+    // `spark.sql.ansi.enforceReservedKeywords` parses `user` as the function, 
and a case-sensitive
+    // one resolves `USER` to the function, so both would accept a NULL row 
without it.
+    Seq("user", "`USER`").foreach { name =>
+      withNamespaceAndTable("ns", "tbl", nonPartitionCatalog) { t =>
+        sql(s"CREATE TABLE $t (id INT, user STRING, ts TIMESTAMP) 
$defaultUsing")
+        sql(s"ALTER TABLE $t ADD CONSTRAINT c1 CHECK ($name IS NOT NULL AND ts 
<= now())")
+        assert(getCheckConstraint(loadTable(nonPartitionCatalog, "ns", 
"tbl")).predicate() != null,
+          name)
+      }
+    }
+  }
+
+  test("SPARK-60032: Check constraint added by ALTER TABLE does not call a 
user-defined function") {
+    // `HandleSpecialCommand` runs before `CheckAnalysis` rejects such a 
condition, so it must not
+    // evaluate the function.
+    withV2Function("strlen", StrLen(CountingString)) {
+      withNamespaceAndTable("ns", "tbl", nonPartitionCatalog) { t =>
+        sql(s"CREATE TABLE $t (id INT, ts TIMESTAMP) $defaultUsing")
+        CountingString.calls = 0
+        val error = intercept[AnalysisException] {
+          sql(s"ALTER TABLE $t ADD CONSTRAINT c1 CHECK " +
+            s"(ts <= CAST(fun_$catalog.ns.strlen('12:00:00') AS TIMESTAMP))")
+        }
+        assert(error.getCondition == 
"USER_DEFINED_FUNCTION_IN_CHECK_CONSTRAINT")
+        assert(CountingString.calls == 0)
+      }
+    }
+  }
+
+  test("SPARK-60032: Check constraint added by ALTER TABLE in a session that 
reads its text " +
+      "differently") {
+    // A write with the default settings reads `"ts"` as a string and 
`'C:\temp'` with a tab, so
+    // such a condition keeps the predicate built from the optimized plan.
+    val escaped = "path <> 'C:\\temp' OR ts <= current_timestamp()"
+    Seq(
+      (Seq(SQLConf.DOUBLE_QUOTED_IDENTIFIERS.key -> "true"), "\"ts\" <= 
current_timestamp()",
+        "'a'"),
+      (Seq(SQLConf.ESCAPED_STRING_LITERALS.key -> "true"), escaped, 
"'C:\\\\temp'"),
+      // The legacy config of generated columns does not change how a write 
reads the text.
+      (Seq(SQLConf.ESCAPED_STRING_LITERALS.key -> "true",
+        SQLConf.USE_CURRENT_SQL_CONFIGS_FOR_GENERATED_COLUMN.key -> "true"), 
escaped,
+        "'C:\\\\temp'")
+    ).foreach { case (confs, cond, path) =>
+      withNamespaceAndTable("ns", "tbl", nonPartitionCatalog) { t =>
+        sql(s"CREATE TABLE $t (id INT, path STRING, ts TIMESTAMP) 
$defaultUsing")
+        withSQLConf((SQLConf.ANSI_ENABLED.key -> "true") +: confs: _*) {
+          sql(s"ALTER TABLE $t ADD CONSTRAINT c1 CHECK ($cond)")
+        }
+        assert(getCheckConstraint(loadTable(nonPartitionCatalog, "ns", 
"tbl")).predicate() != null,
+          cond)
+        val error = intercept[SparkRuntimeException] {
+          sql(s"INSERT INTO $t VALUES (1, $path, current_timestamp() + 
INTERVAL 1 DAY)")
+        }
+        assert(error.getCondition == "CHECK_CONSTRAINT_VIOLATION", cond)
+      }
+    }
+    // A write with `spark.sql.variable.substitute` replaces the placeholder.
+    withNamespaceAndTable("ns", "tbl", nonPartitionCatalog) { t =>
+      sql(s"CREATE TABLE $t (id INT, path STRING, ts TIMESTAMP) $defaultUsing")
+      withSQLConf(SQLConf.VARIABLE_SUBSTITUTE_ENABLED.key -> "false") {
+        sql(s"ALTER TABLE $t ADD CONSTRAINT c1 CHECK " +
+          "(path <> '${spark.sql.session.timeZone}' OR ts <= 
current_timestamp())")
+      }
+      assert(getCheckConstraint(loadTable(nonPartitionCatalog, "ns", 
"tbl")).predicate() != null)
+    }
+  }
+
+  test("SPARK-60032: Check constraint added by ALTER TABLE with a constant in 
the session time " +
+      "zone") {
+    // A write that parses `predicateSql` would read the bound in its own time 
zone.
+    Seq(
+      "ts >= '2024-01-01 00:00:00'",
+      "ts >= TIMESTAMP '2024-01-01 00:00:00'",
+      "ts >= to_timestamp('2024-01-01 00:00:00', 'yyyy-MM-dd HH:mm:ss')",
+      "ts >= make_timestamp(DATE'2024-01-01', TIME'00:00:00')"
+    ).foreach { bound =>
+      withNamespaceAndTable("ns", "tbl", nonPartitionCatalog) { t =>
+        sql(s"CREATE TABLE $t (id INT, ts TIMESTAMP) $defaultUsing")
+        withSQLConf(SQLConf.SESSION_LOCAL_TIMEZONE.key -> "UTC") {
+          sql(s"ALTER TABLE $t ADD CONSTRAINT c1 CHECK ($bound AND ts <= 
current_timestamp())")
+        }
+        assert(getCheckConstraint(loadTable(nonPartitionCatalog, "ns", 
"tbl")).predicate() != null,
+          bound)
+        // 2024-01-01 00:30:00 UTC is before the bound read in 
America/Los_Angeles.
+        withSQLConf(SQLConf.SESSION_LOCAL_TIMEZONE.key -> 
"America/Los_Angeles") {
+          sql(s"INSERT INTO $t VALUES (1, timestamp_seconds(1704069000))")
+        }
+        checkAnswer(spark.table(t).select("id"), Row(1))
+      }
+    }
+    // A date constant and a timestamp without time zone depend on no time 
zone.
+    Seq(
+      ("d DATE", "d >= DATE '2024-01-01' AND d <= current_date()"),
+      ("ts TIMESTAMP_NTZ", "ts >= '2024-01-01 00:00:00' AND ts <= 
localtimestamp()")
+    ).foreach { case (column, cond) =>
+      withNamespaceAndTable("ns", "tbl", nonPartitionCatalog) { t =>
+        sql(s"CREATE TABLE $t (id INT, $column) $defaultUsing")
+        sql(s"ALTER TABLE $t ADD CONSTRAINT c1 CHECK ($cond)")
+        assert(getCheckConstraint(loadTable(nonPartitionCatalog, "ns", 
"tbl")).predicate() == null,
+          cond)
+      }
+    }
+  }
+
+  test("SPARK-60032: Check constraint added by ALTER TABLE under the legacy 
config") {
+    withNamespaceAndTable("ns", "tbl", nonPartitionCatalog) { t =>
+      sql(s"CREATE TABLE $t (id INT, ts TIMESTAMP) $defaultUsing")
+      withSQLConf(SQLConf.FREEZE_CURRENT_VALUES_IN_CHECK_CONSTRAINT.key -> 
"true") {
+        sql(s"ALTER TABLE $t ADD CONSTRAINT c1 CHECK (ts <= 
current_timestamp())")
+      }
+      assert(getCheckConstraint(loadTable(nonPartitionCatalog, "ns", 
"tbl")).predicate() != null)
+    }
+  }
+
   private def withV2Function(name: String, function: UnboundFunction)(f: => 
Unit): Unit = {
     val funCatalog = spark.sessionState.catalogManager.catalog(s"fun_$catalog")
       .asInstanceOf[InMemoryCatalog]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to