Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[DRAFT] Resolve default string producing expressions in analyzer #49607

Draft
wants to merge 5 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,10 @@

package org.apache.spark.sql.catalyst.analysis

import org.apache.spark.sql.catalyst.expressions.{Cast, Expression, Literal}
import org.apache.spark.sql.catalyst.expressions.{Cast, DefaultStringProducingExpression, Expression, Literal}
import org.apache.spark.sql.catalyst.plans.logical.{AddColumns, AlterColumns, AlterColumnSpec, AlterViewAs, ColumnDefinition, CreateView, LogicalPlan, QualifiedColType, ReplaceColumns, V1CreateTablePlan, V2CreateTablePlan}
import org.apache.spark.sql.catalyst.rules.{Rule, RuleExecutor}
import org.apache.spark.sql.catalyst.trees.TreeNodeTag
import org.apache.spark.sql.types.{DataType, StringType}

/**
Expand All @@ -29,6 +30,8 @@ import org.apache.spark.sql.types.{DataType, StringType}
* So, we will just use UTF8_BINARY for now.
*/
object ResolveDefaultStringTypes extends Rule[LogicalPlan] {
private val CAST_ADDED_TAG = new TreeNodeTag[Unit]("castAddedTag")

def apply(plan: LogicalPlan): LogicalPlan = {
val newPlan = apply0(plan)
if (plan.ne(newPlan)) {
Expand Down Expand Up @@ -149,6 +152,21 @@ object ResolveDefaultStringTypes extends Rule[LogicalPlan] {

case Literal(value, dt) if hasDefaultStringType(dt) =>
newType => Literal(value, replaceDefaultStringType(dt, newType))

case expression if needsCast(expression) =>
expression.setTagValue(CAST_ADDED_TAG, ())
newType => {
if (newType == StringType) {
expression
} else {
Cast(expression, replaceDefaultStringType(expression.dataType, newType))
}
}
}

private def needsCast(expression: Expression): Boolean = expression match {
case ex: DefaultStringProducingExpression => ex.getTagValue(CAST_ADDED_TAG).isEmpty
Copy link
Contributor Author

Choose a reason for hiding this comment

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

@cloud-fan Is there an easier way to do this that won't result in the infinite loop of always adding a cast on top of DefaultStringProducingExpression?

case _ => false
}

private def hasDefaultStringType(dataType: DataType): Boolean =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1467,5 +1467,5 @@ case class MultiCommutativeOp(
* Trait for expressions whose data type should be a default string type.
*/
trait DefaultStringProducingExpression extends Expression {
override def dataType: DataType = SQLConf.get.defaultStringType
override def dataType: DataType = StringType
}
Original file line number Diff line number Diff line change
Expand Up @@ -858,12 +858,13 @@ case class SchemaOfVariantAgg(
extends TypedImperativeAggregate[DataType]
with ExpectsInputTypes
with QueryErrorsBase
with DefaultStringProducingExpression
with UnaryLike[Expression] {
def this(child: Expression) = this(child, 0, 0)

override def inputTypes: Seq[AbstractDataType] = Seq(VariantType)

override def dataType: DataType = SQLConf.get.defaultStringType

override def nullable: Boolean = false

override def createAggregationBuffer(): DataType = NullType
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@ import org.apache.spark.sql.catalyst.util.DateTimeUtils
import org.apache.spark.sql.catalyst.util.DateTimeUtils.{convertSpecialDate, convertSpecialTimestamp, convertSpecialTimestampNTZ, instantToMicros, localDateTimeToMicros}
import org.apache.spark.sql.catalyst.util.TypeUtils.toSQLExpr
import org.apache.spark.sql.connector.catalog.CatalogManager
import org.apache.spark.sql.internal.SQLConf
import org.apache.spark.sql.types._


Expand Down Expand Up @@ -153,14 +152,15 @@ case class ReplaceCurrentLike(catalogManager: CatalogManager) extends Rule[Logic
val currentCatalog = catalogManager.currentCatalog.name()
val currentUser = CurrentUserContext.getCurrentUser

plan.transformAllExpressionsWithPruning(_.containsPattern(CURRENT_LIKE)) {
val res = plan.transformAllExpressionsWithPruning(_.containsPattern(CURRENT_LIKE)) {
case CurrentDatabase() =>
Literal.create(currentNamespace, SQLConf.get.defaultStringType)
Literal.create(currentNamespace)
case CurrentCatalog() =>
Literal.create(currentCatalog, SQLConf.get.defaultStringType)
Literal.create(currentCatalog)
case CurrentUser() =>
Literal.create(currentUser, SQLConf.get.defaultStringType)
Literal.create(currentUser)
}
res
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,13 @@ abstract class DefaultCollationTestSuite extends QueryTest with SharedSparkSessi
def testView: String = "test_view"
protected val fullyQualifiedPrefix = s"${CollationFactory.CATALOG}.${CollationFactory.SCHEMA}."

val defaultStringProducingExpressions: Seq[String] = Seq(
"current_timezone()", "current_database()", "md5('Spark' collate unicode)",
"soundex('Spark' collate unicode)", "url_encode('https://spark.apache.org' collate unicode)",
"url_decode('https%3A%2F%2Fspark.apache.org')", "uuid()", "chr(65)", "collation('UNICODE')",
"version()", "space(5)", "randstr(5, 123)"
)

def withSessionCollationAndTable(collation: String, testTables: String*)(f: => Unit): Unit = {
withTable(testTables: _*) {
withSessionCollation(collation) {
Expand Down Expand Up @@ -233,6 +240,25 @@ abstract class DefaultCollationTestSuite extends QueryTest with SharedSparkSessi
}
}

test("expressions that have default string result in DDL should have object collation") {
withSessionCollationAndTable("UTF8_LCASE", testTable) {

val columns = defaultStringProducingExpressions.zipWithIndex.map {
case (expr, index) => s"$expr AS c${index + 1}"
}.mkString(", ")

sql(s"""
|CREATE TABLE $testTable
|USING $dataSource AS
|SELECT $columns
|""".stripMargin)

(1 to defaultStringProducingExpressions.length).foreach { index =>
assertTableColumnCollation(testTable, s"c$index", "UTF8_BINARY")
}
}
}

// endregion

// region DML tests
Expand Down Expand Up @@ -389,6 +415,17 @@ abstract class DefaultCollationTestSuite extends QueryTest with SharedSparkSessi
}
}

test("expressions that have default string result in DML should have session collation") {
withSessionCollation("UTF8_LCASE") {
defaultStringProducingExpressions.foreach { expr =>
checkAnswer(
sql(s"SELECT COLLATION($expr)"),
Seq(Row(fullyQualifiedPrefix + "UTF8_LCASE"))
)
}
}
}

// endregion
}

Expand Down
Loading