cloud-fan commented on code in PR #59820:
URL: https://github.com/apache/spark/pull/59820#discussion_r4560761338
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/literals.scala:
##########
@@ -358,7 +358,26 @@ object Literal {
* Inverse of [[Literal.sql]]
*/
def fromSQL(sql: String): Expression = {
- CatalystSqlParser.parseExpression(sql).transformUp {
+ fromSQL(sql, CatalystSqlParser)
Review Comment:
**Nit (P3):** The Scaladoc above still calls `fromSQL` the inverse of
`Literal.sql`, but it parses with the session's string-escaping policy, and the
decoder now relies on that to keep session parsing for text that is not
`Literal.sql` output. With `spark.sql.parser.escapedStringLiterals=true` it is
not that inverse: decoding `Literal("Dianne's horse").sql` with it gives
`Dianne\'s horse`. Suggest saying that it follows the session's escaping, so it
inverts `Literal.sql` only when that config is false, and pointing to
`fromSQLWithCanonicalEscaping` for `Literal.sql` output.
**Verification:**
- **Inspection:** Literal.fromSQL's documentation no longer claims to be the
inverse of Literal.sql unconditionally, and it directs Literal.sql decoding to
fromSQLWithCanonicalEscaping.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/ResolveDefaultColumnsUtil.scala:
##########
@@ -324,15 +324,46 @@ object ResolveDefaultColumns extends QueryErrorsBase
coerceDefaultValue(analyzed, dataType, statementType, colName, defaultSQL)
}
+ // Recognize the constructors emitted by Literal.sql, without accepting
arbitrary functions
+ // whose string literals must still be interpreted using the session's
parser configuration.
+ private def isSerializedLiteral(expr: Expression): Boolean = expr match {
+ case _: ExprLiteral => true
+ case c: Cast => c.child.isInstanceOf[ExprLiteral]
Review Comment:
**Non-blocking (P2):** This arm accepts a cast only when its child is a bare
literal. In Spark 4.1 and earlier, `ALTER TABLE t ADD COLUMNS (c STRING DEFAULT
'C:\temp' COLLATE UTF8_LCASE)` stored `analyze(field).sql`: the collated
literal is constant-folded, `coerceDefaultValue` wraps it in a cast to `STRING`
because the string upcast rule compares only length constraints, not
collations, and 4.1's `Literal.sql` appends ` collate UTF8_LCASE`. The stored
text is `CAST('C:\\temp' collate UTF8_LCASE AS STRING)`.
Reading the code, after upgrading and with `escapedStringLiterals=true`, the
canonical tree `Cast(Collate(Literal, UnresolvedCollation))` fails this check,
the session reparse keeps both backslashes, and the old row reads `C:\\temp`
while a row inserted with `DEFAULT` gets `C:\temp`. `CREATE TABLE ... LIKE`
passes the doubled value to a V2 catalog the same way. Accepting a cast whose
child is itself a serialized-literal shape covers it, with a decoder test for
this shape in both parser modes. Default mode and defaults written by 4.2 and
later, which store a folded literal, are unaffected.
See **Shared repair plan 1** in the review body.
##########
sql/catalyst/src/test/scala/org/apache/spark/sql/types/StructTypeSuite.scala:
##########
@@ -1214,6 +1216,172 @@ class StructTypeSuite extends SparkFunSuite with
SQLHelper {
validateConvertedDefaults("c5", IntegerType, "1 + 1", "2")
}
+ for (escapedStringLiterals <- Seq(false, true)) {
+ test(s"existence default strings preserve escaped literals
($escapedStringLiterals)") {
+ withSQLConf(SQLConf.ESCAPED_STRING_LITERALS.key ->
escapedStringLiterals.toString) {
+ for {
+ dataType <- Seq(StringType, StringType("UTF8_LCASE"))
+ value <- Seq("a\\b", "a'b", "a\\nb", "a\nb", "", "plain", null)
+ } {
+ withClue(s"dataType=$dataType, value=$value: ") {
+ val literal = Literal.create(value, dataType)
+ val column = ColumnDefinition("s", dataType, true, None,
+ Some(DefaultValueExpression(literal, literal.sql)))
+ val schema =
DataType.fromJson(StructType(Seq(column.toV1Column)).json)
+ .asInstanceOf[StructType]
+ assert(ResolveDefaultColumns.existenceDefaultValues(schema).toSeq
==
+ Seq(literal.value))
+ assert(SQLConf.get.escapedStringLiterals == escapedStringLiterals)
+ }
+ }
+ }
+ }
+
+ test(s"complex existence defaults preserve escaped literals
($escapedStringLiterals)") {
+ withSQLConf(SQLConf.ESCAPED_STRING_LITERALS.key ->
escapedStringLiterals.toString) {
+ val logAppender = new LogAppender("complex existence defaults")
+ withLogAppender(logAppender, level = Some(Level.WARN)) {
+ for (stringType <- Seq(StringType, StringType("UTF8_LCASE"))) {
+ val structType = StructType(Seq(StructField("s", stringType)))
+ val cases: Seq[(DataType, Any)] = Seq(
+ ArrayType(stringType) -> Seq("a\\b'c", "\\n", "\n", "plain", "",
null),
+ MapType(StringType, stringType) ->
+ Map("k\\'ey" -> "a\\b'c", "empty" -> "", "null" -> null),
+ structType -> Row("a\\b'c"),
+ ArrayType(structType) -> Seq(Row("a\\b'c"), Row(""), Row(null),
null),
+ MapType(StringType, ArrayType(stringType)) ->
+ Map("k\\'ey" -> Seq("a\\b'c", "", null)),
+ ArrayType(stringType) -> Seq.empty[String],
+ MapType(StringType, stringType) -> Map.empty[String, String],
+ structType -> null)
+ for ((dataType, expected) <- cases) {
+ val literal = Literal.create(expected, dataType)
+ withClue(s"dataType=$dataType, default=${literal.sql}: ") {
+ val field = StructField("c",
dataType).withExistenceDefaultValue(literal.sql)
+ val schema = DataType.fromJson(StructType(Seq(field)).json)
+ .asInstanceOf[StructType]
+ val actual =
ResolveDefaultColumns.existenceDefaultValues(schema).head
+
assert(CatalystTypeConverters.createToScalaConverter(dataType)(actual) ==
expected)
+ }
+ }
+ }
+ }
+ val fallbackWarnings = logAppender.loggingEvents.filter { event =>
+ event.getLevel == Level.WARN && event.getMessage.getFormattedMessage
+ .contains("Encountered unresolved exists default value")
+ }
+ assert(fallbackWarnings.isEmpty,
+
fallbackWarnings.map(_.getMessage.getFormattedMessage).mkString("\n"))
+ }
+ }
+ }
+
+ test("existence default decoding does not repeat deprecated configuration
warnings") {
+ withSQLConf(SQLConf.ESCAPED_STRING_LITERALS.key -> "true") {
+ val schema = StructType(Seq(
+ StructField("s",
StringType).withExistenceDefaultValue(Literal("plain").sql),
+ StructField("i",
IntegerType).withExistenceDefaultValue(Literal(42).sql)))
+ val logAppender = new LogAppender("existence default decoding")
+ withLogAppender(logAppender, level = Some(Level.WARN)) {
+ for (_ <- 1 to 5) {
+ assert(ResolveDefaultColumns.existenceDefaultValues(schema).toSeq ==
+ Seq(UTF8String.fromString("plain"), 42))
+ }
+ }
+ val warnings = logAppender.loggingEvents.filter { event =>
+ event.getLevel == Level.WARN &&
+ event.getMessage.getFormattedMessage.contains("has been deprecated")
+ }
+ assert(warnings.isEmpty,
+ warnings.map(_.getMessage.getFormattedMessage).mkString("\n"))
+ }
+ }
+
+ test("existence default timestamps retain the session time zone in legacy
string mode") {
+ val callerConf = SQLConf.get
+ val originalSettings = callerConf.getAllConfs
+ withSQLConf(
+ SQLConf.ESCAPED_STRING_LITERALS.key -> "true",
+ SQLConf.SESSION_LOCAL_TIMEZONE.key -> "Asia/Kathmandu") {
+ val activeSettings = callerConf.getAllConfs
+ val literal = Literal(1577836800123456L, TimestampType)
+ assert(literal.sql == "TIMESTAMP '2020-01-01 05:45:00.123456'")
+ val field = StructField("t",
TimestampType).withExistenceDefaultValue(literal.sql)
+ val schema =
DataType.fromJson(StructType(Seq(field)).json).asInstanceOf[StructType]
+ assert(ResolveDefaultColumns.existenceDefaultValues(schema).toSeq ==
Seq(literal.value))
+ assert(SQLConf.get eq callerConf)
+ assert(callerConf.getAllConfs == activeSettings)
+ }
+ assert(SQLConf.get eq callerConf)
+ assert(callerConf.getAllConfs == originalSettings)
+ }
+
+ test("ordinary shared parsers retain dynamic string literal settings") {
+ val parser = CatalystSqlParser
+ for (escaped <- Seq(false, true, false)) {
+ withSQLConf(
+ SQLConf.ESCAPED_STRING_LITERALS.key -> escaped.toString,
+ SQLConf.LEGACY_CONSECUTIVE_STRING_LITERALS.key -> "false") {
+ val expected = if (escaped) "\\n" else "\n"
+ assert(parser.parseExpression("""'\n'""").eval() ==
UTF8String.fromString(expected))
+ assert(Literal.fromSQL("""'\n'""").eval() ==
UTF8String.fromString(expected))
+ }
+ }
+ for (legacyConsecutive <- Seq(false, true, false)) {
+ withSQLConf(
+ SQLConf.ESCAPED_STRING_LITERALS.key -> "false",
+ SQLConf.LEGACY_CONSECUTIVE_STRING_LITERALS.key ->
legacyConsecutive.toString) {
+ val expected = if (legacyConsecutive) "ab" else "a'b"
+ assert(parser.parseExpression("'a''b'").eval() ==
UTF8String.fromString(expected))
+ }
+ }
+ }
+
+ for (escapedStringLiterals <- Seq(false, true)) {
+ test(s"function existence defaults retain session parsing
($escapedStringLiterals)") {
+ withSQLConf(SQLConf.ESCAPED_STRING_LITERALS.key ->
escapedStringLiterals.toString) {
+ val expected = if (escapedStringLiterals) "a\\n" else "a\n"
+ val structType = StructType(Seq(StructField("s", StringType)))
+ val cases: Seq[(DataType, String, Any)] = Seq(
Review Comment:
**Nit (P3):** These cases check that function text keeps session parsing
under `CAST` and inside `array`, `map` and `named_struct`, but not under
`COLLATE`, and the collated cases in the other changed suites use `Literal.sql`
text or folded defaults. If the `Collate` arm of `isSerializedLiteral` were
widened to any child, `concat('a', '\n') COLLATE UTF8_LCASE` would decode in
escaped mode to `a` and a newline instead of `a\n`, and no test would fail.
Adding that case, alone, inside an `array` and under a `CAST`, in both modes,
would pin the boundary, which any later change to the cast arm also relies on.
See **Shared repair plan 1** in the review body.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/connector/catalog/CatalogV2Util.scala:
##########
@@ -891,10 +891,7 @@ private[sql] object CatalogV2Util {
checkDefaultColumnConflicts(f)
val existsDefault = if (f.getExistenceDefaultValue().isDefined) {
- val e = analyze(
- f,
- statementType = "Column analysis",
- metadataKey = EXISTS_DEFAULT_COLUMN_METADATA_KEY)
+ val e = analyzeExistenceDefaultValue(f, statementType = "Column
analysis")
Review Comment:
**Nit (P3):** This call now goes through the reader decoder. For text that
`Literal.fromSQL` rejects but default-column analysis accepts, such as a
qualified builtin call like `system.builtin.upper('a')` (`fromSQL` asserts
one-part function names), the decode fails, and
`fallbackResolveExistenceDefaultValue` logs `Encountered unresolved exists
default value ... falling back to full analysis` and parses the text again. The
base branch's `analyze(f, "Column analysis", ...)` parsed it once and logged
nothing. A pipeline dataset declared with such a default takes this path when
its table is created. Values and error classes are unchanged. On the
full-analysis path, a failed builtin lookup could lead straight to analysis of
the session-parsed text with the threaded statement type, leaving the fallback
and its warning to the readers.
See **Shared repair plan 2** in the review body.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/ResolveDefaultColumnsUtil.scala:
##########
@@ -324,15 +324,46 @@ object ResolveDefaultColumns extends QueryErrorsBase
coerceDefaultValue(analyzed, dataType, statementType, colName, defaultSQL)
}
+ // Recognize the constructors emitted by Literal.sql, without accepting
arbitrary functions
+ // whose string literals must still be interpreted using the session's
parser configuration.
+ private def isSerializedLiteral(expr: Expression): Boolean = expr match {
+ case _: ExprLiteral => true
+ case c: Cast => c.child.isInstanceOf[ExprLiteral]
+ case Collate(_: ExprLiteral, _: UnresolvedCollation) => true
+ case _: CreateArray | _: CreateMap | _: CreateNamedStruct =>
+ expr.children.forall(isSerializedLiteral)
+ case _ => false
+ }
+
/**
- * Analyze EXISTS_DEFAULT value. EXISTS_DEFAULT value was created from
CURRENT_DEFAQULT
- * via [[analyze]] and thus this can skip most of those steps.
+ * Decodes an existence default and applies full default-column analysis for
catalog conversion.
*/
- private def analyzeExistenceDefaultValue(field: StructField): Expression = {
+ def analyzeExistenceDefaultValue(field: StructField, statementType: String):
Expression = {
+ decodeExistenceDefaultValue(field, statementType, useFullAnalysis = true)
+ }
+
+ // Existence defaults are normally constant-folded already, so readers can
skip full analysis
+ // for resolved literals and casts. Catalog conversion still requires full
analysis above.
+ private def decodeExistenceDefaultValue(
+ field: StructField,
+ statementType: String,
+ useFullAnalysis: Boolean = false): Expression = {
val defaultSQL =
field.metadata.getString(EXISTS_DEFAULT_COLUMN_METADATA_KEY)
- // Parse the expression.
- val resolvedExpr = Try(Literal.fromSQL(defaultSQL)) match {
+ val parsedExpr = Try {
+ if (!SQLConf.get.escapedStringLiterals) {
+ // The session parser already uses canonical escaping in this mode.
+ Literal.fromSQL(defaultSQL)
+ } else {
+ val parsed = Literal.fromSQLWithCanonicalEscaping(defaultSQL)
+ // External expressions, including resolved casts containing
functions, retain session
+ // parsing. Recognizing a resolved cast alone does not establish
literal serialization.
+ if (isSerializedLiteral(parsed)) parsed else
Literal.fromSQL(defaultSQL)
Review Comment:
**Blocking (P1):** In escaped mode this line keeps the canonical parse for
any text whose tree has a literal-only shape, but the shape does not show that
`Literal.sql` wrote the text. `ColumnDefinition.toV1Column` stores the user's
original DEFAULT text as `EXISTS_DEFAULT` whenever the parsed default is not a
bare `Literal`, and `CREATE TEMPORARY TABLE ... USING` (through
`AstBuilder.createSchema`) and pipeline streaming tables and materialized views
keep that text without constant folding.
Reading the code, with `spark.sql.parser.escapedStringLiterals=true`:
```sql
CREATE TEMPORARY TABLE t (i INT, s STRING DEFAULT CAST('a\nb' AS STRING))
USING parquet OPTIONS (path '/d'); -- the files under /d have only column i
SELECT s FROM t;
```
The declared default is the four characters `a`, `\`, `n`, `b`, and
`EXISTS_DEFAULT` holds the original text. The base branch decoded it with the
session parser and returned those four characters. Now
`fromSQLWithCanonicalEscaping` turns `\n` into a newline, `isSerializedLiteral`
accepts the `Cast(Literal)`, and every row read from those files gets `a`,
newline, `b`, with no error or warning. `array('C:\temp')` (backslash-t becomes
a tab) and `'a\nb' COLLATE UTF8_LCASE` behave the same way. For a pipeline
dataset, `structTypeToV2Columns` hands the V2 catalog a default literal holding
a newline while its SQL, evaluated by the session for new rows, yields
backslash-n. Default mode is unaffected.
This extends existing discussions
[1](https://github.com/apache/spark/pull/59820#issuecomment-6838505939),
[2](https://github.com/apache/spark/pull/59820#discussion_r4400926113).
**Recommended change:** When ColumnDefinition.toV1Column records a default
whose parsed form is not a bare literal, it should first check whether that
default has a literal-only shape by the same rule the existence-default decoder
uses: a literal, a cast or collation of one, or ARRAY, MAP or NAMED_STRUCT of
such values. Apply the rule to the tree that Literal.fromSQL builds from the
default's original text under the session's escaping policy, not to the
default's parsed child: the plain parse leaves array, map and named_struct as
unresolved function calls, which the rule does not recognize. If the shape
matches and default-column analysis folds that tree to a constant, store the
constant's Literal.sql text as EXISTS_DEFAULT instead of the user's original
text, so every stored literal-shaped existence default is Literal.sql output.
Keep the original text for any other default and whenever that parse, its
function lookup, or the analysis fails. Add existence-default tests for CREATE
TEMPORARY TABLE ... USING over existing Parquet files and for converting such
a schema to V2 columns, in escaped mode.
**Why this works:** The decoder treats literal-shaped text as Literal.sql
output, and this makes that true for every in-repo writer. The writer reads the
default's text with Literal.fromSQL, the same session-policy parse and function
lookup the decoder falls back to, so its strings carry the values the user
declared, folding yields that value, and Literal.sql then encodes it
canonically. The decoder needs no change, and both sides apply one shape rule
to the same kind of tree, so a shape the decoder starts to accept is folded by
the writer as well.
**Compatibility:** CURRENT_DEFAULT text, function-shaped existence defaults,
and the EXISTS_DEFAULT text that V1 CREATE TABLE and ALTER TABLE ADD COLUMNS
store stay as they are.
**Risks:** Literal-only defaults whose value depends on session settings,
such as a cast of a string to TIMESTAMP, are fixed at definition time on
temporary tables instead of when they are read; this differs only if the
session changes such a setting between creating and reading the table, and the
change can be rolled back by reverting the writer step. Each non-literal
default recorded by toV1Column pays one extra parse and, for literal-only
shapes, one analysis at DDL time; CREATE TABLE then replaces the result with
its own folded text.
**Constraints:** Use exactly the decoder's serialized-literal rule,
including any shape it is extended to accept, so the writer and decoder cannot
drift apart again. Leave CURRENT_DEFAULT text and its attached expression
unchanged. Keep the original text when parsing, function lookup or analysis
fails, so an invalid default fails where it does on the base branch.
**Exclusions:**
- Literal-shaped existence-default text set through
StructField.withExistenceDefaultValue or written by an external catalog keeps
the shape-based decoding, because nothing in the text shows which escaping
policy produced it.
**Verification:**
- **Regression:** With escapedStringLiterals=true, a temporary table over
existing Parquet files that lack a column whose default is a cast of a string
literal, an array of one, or a collated one, each holding a backslash escape,
returns the declared string for that column with the vectorized reader on and
off.
- **Regression:** With escapedStringLiterals=true, the schema toV1Column
records for those defaults, converted to V2 columns, gives each column a
default literal that equals its CURRENT_DEFAULT evaluated in the session.
- **Compatibility:** A function-shaped default keeps its original
EXISTS_DEFAULT text and session decoding, an invalid literal-shaped default
keeps its original text and fails as on the base branch, and default-mode
values stay unchanged for every shape.
##########
sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/util/ResolveDefaultColumnsUtil.scala:
##########
@@ -345,29 +376,37 @@ object ResolveDefaultColumns extends QueryErrorsBase
// Check invariants
if (expr.containsPattern(PLAN_EXPRESSION)) {
throw
QueryCompilationErrors.defaultValuesMayNotContainSubQueryExpressions(
- "", field.name, defaultSQL)
+ statementType, field.name, defaultSQL)
}
expr match {
case _: ExprLiteral => expr
case c: Cast if c.resolved => expr
+ case e if isSerializedLiteral(e) =>
+ // Resolve nested constructors and collations from the decoded
expression.
+ analyze(field.name, field.dataType, e, defaultSQL, statementType)
case _ =>
- fallbackResolveExistenceDefaultValue(field)
+ fallbackResolveExistenceDefaultValue(field, statementType)
}
case Failure(_) =>
// If Literal.fromSQL fails, use fallback resolution
- fallbackResolveExistenceDefaultValue(field)
+ fallbackResolveExistenceDefaultValue(field, statementType)
Review Comment:
**Nit (P3):** `CatalogV2Util.structFieldToV2Column` now reaches this branch
whenever `Literal.fromSQL` rejects the text, and `statementType` is threaded
through it so V2 conversion keeps its `COLUMN ANALYSIS` context. Every new
`CatalogV2UtilSuite` case uses text that `fromSQL` decodes, so all of them take
the `Success` branch, and the SPARK-51119 fallback test goes through the reader
with an empty statement. Passing `""` here, or in the fallback's `analyze`
call, would go unnoticed. A V2 conversion case with unparseable text, asserting
the `COLUMN ANALYSIS` statement, and one with a qualified builtin call such as
`system.builtin.upper('a')`, asserting the value, would cover the route.
See **Shared repair plan 2** in the review body.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]