You are viewing a plain text version of this content. The canonical link for it is here.
Posted to reviews@spark.apache.org by "nikolamand-db (via GitHub)" <gi...@apache.org> on 2024/03/27 15:59:29 UTC

[PR] [SPARK-47617] Add TPC-DS testing infrastructure for collations [spark]

nikolamand-db opened a new pull request, #45739:
URL: https://github.com/apache/spark/pull/45739

   <!--
   Thanks for sending a pull request!  Here are some tips for you:
     1. If this is your first time, please read our contributor guidelines: https://spark.apache.org/contributing.html
     2. Ensure you have added or run the appropriate tests for your PR: https://spark.apache.org/developer-tools.html
     3. If the PR is unfinished, add '[WIP]' in your PR title, e.g., '[WIP][SPARK-XXXX] Your PR title ...'.
     4. Be sure to keep the PR description updated to reflect all changes.
     5. Please write your PR title to summarize what this PR proposes.
     6. If possible, provide a concise example to reproduce the issue for a faster review.
     7. If you want to add a new configuration, please read the guideline first for naming configurations in
        'core/src/main/scala/org/apache/spark/internal/config/ConfigEntry.scala'.
     8. If you want to add or modify an error type or message, please read the guideline first in
        'common/utils/src/main/resources/error/README.md'.
   -->
   
   ### What changes were proposed in this pull request?
   <!--
   Please clarify what changes you are proposing. The purpose of this section is to outline the changes and how this PR fixes the issue. 
   If possible, please consider writing useful notes for better and faster reviews in your PR. See the examples below.
     1. If you refactor some codes with changing classes, showing the class hierarchy will help reviewers.
     2. If you fix some SQL features, you can provide some references of other DBMSes.
     3. If there is design documentation, please add the link.
     4. If there is a discussion in the mailing list, please add the link.
   -->
   
   **PR branch is currently based off of https://github.com/apache/spark/pull/45383 because implicit casting is required for the checks to work. Will resolve with master once the dependency PR is merged.**
   
   We can utilize TPC-DS testing infrastructure already present in Spark. The idea is to vary TPC-DS table string columns by adding multiple collations with different ordering rules and case sensitivity, producing new tables. These tables should yield the same results against predefined TPC-DS queries for certain batches of collations. For example, when comparing query runs on table where columns are first collated as `UTF8_BINARY` and then as `UTF8_BINARY_LCASE`, we should be getting same results after converting to lowercase.
   
   Introduce new query suite which tests the described behavior with available collations (utf8_binary and unicode) combined with case conversions (lowercase, uppercase, randomized case for fuzzy testing).
   
   ### Why are the changes needed?
   <!--
   Please clarify why the changes are needed. For instance,
     1. If you propose a new API, clarify the use case for a new API.
     2. If you fix a bug, you can clarify why it is a bug.
   -->
   
   Improve collations testing coverage.
   
   ### Does this PR introduce _any_ user-facing change?
   <!--
   Note that it means *any* user-facing change including all aspects such as the documentation fix.
   If yes, please clarify the previous behavior and the change this PR proposes - provide the console output, description and/or an example to show the behavior difference if possible.
   If possible, please also clarify if this is a user-facing change compared to the released Spark versions or within the unreleased branches such as master.
   If no, write 'No'.
   -->
   
   No.
   
   ### How was this patch tested?
   <!--
   If tests were added, say they were added here. Please make sure to add some test cases that check the changes thoroughly including negative and positive cases if possible.
   If it was tested in a way different from regular unit tests, please clarify how you tested step by step, ideally copy and paste-able, so that other reviewers can test and check, and descendants can verify in the future.
   If tests were not added, please describe why they were not added and/or why it was difficult to add.
   If benchmark tests were added, please run the benchmarks in GitHub Actions for the consistent environment, and the instructions could accord to: https://spark.apache.org/developer-tools.html#github-workflow-benchmarks.
   -->
   
   Added TPC-DS collations query suite.
   
   ### Was this patch authored or co-authored using generative AI tooling?
   <!--
   If generative AI tooling has been used in the process of authoring this patch, please include the
   phrase: 'Generated-by: ' followed by the name of the tool and its version.
   If no, write 'No'.
   Please refer to the [ASF Generative Tooling Guidance](https://www.apache.org/legal/generative-tooling.html) for details.
   -->
   
   No.
   


-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-47617][SQL] Add TPC-DS testing infrastructure for collations [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on PR #45739:
URL: https://github.com/apache/spark/pull/45739#issuecomment-2049655914

   thanks, merging to master!


-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-47617][SQL] Add TPC-DS testing infrastructure for collations [spark]

Posted by "stefankandic (via GitHub)" <gi...@apache.org>.
stefankandic commented on PR #45739:
URL: https://github.com/apache/spark/pull/45739#issuecomment-2046858666

   @nikolamand-db could we also run this test on delta in runtime?


-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-47617][SQL] Add TPC-DS testing infrastructure for collations [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan closed pull request #45739: [SPARK-47617][SQL] Add TPC-DS testing infrastructure for collations
URL: https://github.com/apache/spark/pull/45739


-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-47617][SQL] Add TPC-DS testing infrastructure for collations [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #45739:
URL: https://github.com/apache/spark/pull/45739#discussion_r1557677008


##########
sql/core/src/test/scala/org/apache/spark/sql/TPCDSBase.scala:
##########
@@ -34,7 +34,7 @@ trait TPCDSBase extends TPCBase with TPCDSSchema {
     "q81", "q82", "q83", "q84", "q85", "q86", "q87", "q88", "q89", "q90",
     "q91", "q92", "q93", "q94", "q95", "q96", "q97", "q98", "q99")
 
-  protected val excludedTpcdsQueries: Set[String] = if (regenerateGoldenFiles) {
+  protected def excludedTpcdsQueries: Set[String] = if (regenerateGoldenFiles) {

Review Comment:
   It's used in a loop and shouldn't be `def`. BTW `val` can be overridden in scala.



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-47617][SQL] Add TPC-DS testing infrastructure for collations [spark]

Posted by "nikolamand-db (via GitHub)" <gi...@apache.org>.
nikolamand-db commented on code in PR #45739:
URL: https://github.com/apache/spark/pull/45739#discussion_r1557845853


##########
sql/core/src/test/scala/org/apache/spark/sql/TPCDSCollationQueryTestSuite.scala:
##########
@@ -0,0 +1,270 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql
+
+import java.nio.file.{Files, Paths}
+import java.util.Locale
+
+import org.apache.spark.{SparkConf, SparkContext}
+import org.apache.spark.sql.catalyst.util.resourceToString
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.test.TestSparkSession
+import org.apache.spark.tags.ExtendedSQLTest
+import org.apache.spark.util.Utils
+
+/**
+ * End-to-end tests to validate TPC-DS query results against collation-aware
+ * modified data and queries.
+ *
+ * For each collation, table schemas are replicated into two databases in such way that in first
+ * DB all table columns are collated with specified collation, while the second DB collates table
+ * columns with case-insensitive version of the collation. Tables from first DB are then populated
+ * with lowercase-converted data from tpc-ds kit and tables from second DB are populated with
+ * randomized-case data.
+ *
+ * When running arbitrary SQL query, we convert the query to lowercase for execution
+ * against first DB; second DB receives original query. Results should compare equal
+ * ignoring case. We use this method to validate collations are working with arbitrary standard
+ * SQL constructs.
+ *
+ * Additionally, we perform trims on string data to properly convert it from CharType
+ * to StringType and do sanity checks to verify that results are non-empty as expected.
+ *
+ * To run this test suite:
+ * {{{
+ *   SPARK_TPCDS_DATA=<path of TPCDS SF=1 data>
+ *     build/sbt "sql/testOnly *TPCDSCollationQueryTestSuite"
+ * }}}
+ *
+ * To run a single test file upon change:
+ * {{{
+ *   SPARK_TPCDS_DATA=<path of TPCDS SF=1 data>
+ *     build/sbt "sql/testOnly *TPCDSCollationQueryTestSuite -- -z q79"
+ * }}}
+ */
+@ExtendedSQLTest
+class TPCDSCollationQueryTestSuite extends QueryTest with TPCDSBase with SQLQueryTestHelper {
+
+  private val tpcdsDataPath = sys.env.get("SPARK_TPCDS_DATA")
+
+  // To make output results deterministic
+  override protected def sparkConf: SparkConf = super.sparkConf
+    .set(SQLConf.SHUFFLE_PARTITIONS.key, "1")
+
+  protected override def createSparkSession: TestSparkSession = {
+    new TestSparkSession(new SparkContext("local[1]", this.getClass.getSimpleName, sparkConf))
+  }
+
+  if (tpcdsDataPath.nonEmpty) {
+    val nonExistentTables = tableColumns.keys.filterNot { tableName =>
+      Files.exists(Paths.get(s"${tpcdsDataPath.get}/$tableName"))
+    }
+    if (nonExistentTables.nonEmpty) {
+      fail(s"Non-existent TPCDS table paths found in ${tpcdsDataPath.get}: " +
+        nonExistentTables.mkString(", "))
+    }
+  }
+
+  private def withDB[T](dbName: String)(fun: => T): T = {
+    Utils.tryWithSafeFinally({
+      spark.sql(s"USE `$dbName`")
+      fun
+    }) {
+      spark.sql("USE DEFAULT")
+    }
+  }
+
+  abstract class CollationCheck(
+      val dbName: String,
+      val collation: String,
+      val columnTransform: String) {
+
+    def queryTransform: String => String
+  }
+
+  case class CaseInsensitiveCollationCheck(
+      override val dbName: String,
+      override val collation: String,
+      override val columnTransform: String)
+    extends CollationCheck(dbName, collation, columnTransform) {
+
+    override def queryTransform: String => String = identity
+  }
+
+  case class CaseSensitiveCollationCheck(
+      override val dbName: String,
+      override val collation: String,
+      override val columnTransform: String)
+    extends CollationCheck(dbName, collation, columnTransform) {
+
+    override def queryTransform: String => String = _.toLowerCase(Locale.ROOT)
+  }
+
+  val collateNormalize = "COLLATE_NORMALIZE"
+  val randomizeCase = "RANDOMIZE_CASE"
+
+  // List of batches of runs which should yield the same result when run on a query
+  val checks: Seq[Seq[CollationCheck]] = Seq(
+    Seq(
+      CaseSensitiveCollationCheck("tpcds_utf8", "UTF8_BINARY", collateNormalize),
+      CaseInsensitiveCollationCheck("tpcds_utf8_random", "UTF8_BINARY_LCASE", randomizeCase)
+    ),
+    Seq(
+      CaseSensitiveCollationCheck("tpcds_unicode", "UNICODE", collateNormalize),
+      CaseInsensitiveCollationCheck("tpcds_unicode_random", "UNICODE_CI", randomizeCase)
+    )
+  )
+
+  override def createTables(): Unit = {
+    // trim collated strings with udf

Review Comment:
   Fixes, please check.



##########
sql/core/src/test/scala/org/apache/spark/sql/TPCDSCollationQueryTestSuite.scala:
##########
@@ -0,0 +1,270 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql
+
+import java.nio.file.{Files, Paths}
+import java.util.Locale
+
+import org.apache.spark.{SparkConf, SparkContext}
+import org.apache.spark.sql.catalyst.util.resourceToString
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.test.TestSparkSession
+import org.apache.spark.tags.ExtendedSQLTest
+import org.apache.spark.util.Utils
+
+/**
+ * End-to-end tests to validate TPC-DS query results against collation-aware
+ * modified data and queries.
+ *
+ * For each collation, table schemas are replicated into two databases in such way that in first
+ * DB all table columns are collated with specified collation, while the second DB collates table
+ * columns with case-insensitive version of the collation. Tables from first DB are then populated
+ * with lowercase-converted data from tpc-ds kit and tables from second DB are populated with
+ * randomized-case data.
+ *
+ * When running arbitrary SQL query, we convert the query to lowercase for execution
+ * against first DB; second DB receives original query. Results should compare equal
+ * ignoring case. We use this method to validate collations are working with arbitrary standard
+ * SQL constructs.
+ *
+ * Additionally, we perform trims on string data to properly convert it from CharType
+ * to StringType and do sanity checks to verify that results are non-empty as expected.
+ *
+ * To run this test suite:
+ * {{{
+ *   SPARK_TPCDS_DATA=<path of TPCDS SF=1 data>
+ *     build/sbt "sql/testOnly *TPCDSCollationQueryTestSuite"
+ * }}}
+ *
+ * To run a single test file upon change:
+ * {{{
+ *   SPARK_TPCDS_DATA=<path of TPCDS SF=1 data>
+ *     build/sbt "sql/testOnly *TPCDSCollationQueryTestSuite -- -z q79"
+ * }}}
+ */
+@ExtendedSQLTest
+class TPCDSCollationQueryTestSuite extends QueryTest with TPCDSBase with SQLQueryTestHelper {
+
+  private val tpcdsDataPath = sys.env.get("SPARK_TPCDS_DATA")
+
+  // To make output results deterministic
+  override protected def sparkConf: SparkConf = super.sparkConf
+    .set(SQLConf.SHUFFLE_PARTITIONS.key, "1")
+
+  protected override def createSparkSession: TestSparkSession = {
+    new TestSparkSession(new SparkContext("local[1]", this.getClass.getSimpleName, sparkConf))
+  }
+
+  if (tpcdsDataPath.nonEmpty) {
+    val nonExistentTables = tableColumns.keys.filterNot { tableName =>
+      Files.exists(Paths.get(s"${tpcdsDataPath.get}/$tableName"))
+    }
+    if (nonExistentTables.nonEmpty) {
+      fail(s"Non-existent TPCDS table paths found in ${tpcdsDataPath.get}: " +
+        nonExistentTables.mkString(", "))
+    }
+  }
+
+  private def withDB[T](dbName: String)(fun: => T): T = {
+    Utils.tryWithSafeFinally({
+      spark.sql(s"USE `$dbName`")
+      fun
+    }) {
+      spark.sql("USE DEFAULT")
+    }
+  }
+
+  abstract class CollationCheck(
+      val dbName: String,
+      val collation: String,
+      val columnTransform: String) {
+
+    def queryTransform: String => String
+  }
+
+  case class CaseInsensitiveCollationCheck(
+      override val dbName: String,
+      override val collation: String,
+      override val columnTransform: String)
+    extends CollationCheck(dbName, collation, columnTransform) {
+
+    override def queryTransform: String => String = identity
+  }
+
+  case class CaseSensitiveCollationCheck(
+      override val dbName: String,
+      override val collation: String,
+      override val columnTransform: String)
+    extends CollationCheck(dbName, collation, columnTransform) {
+
+    override def queryTransform: String => String = _.toLowerCase(Locale.ROOT)
+  }
+
+  val collateNormalize = "COLLATE_NORMALIZE"
+  val randomizeCase = "RANDOMIZE_CASE"
+
+  // List of batches of runs which should yield the same result when run on a query
+  val checks: Seq[Seq[CollationCheck]] = Seq(
+    Seq(
+      CaseSensitiveCollationCheck("tpcds_utf8", "UTF8_BINARY", collateNormalize),
+      CaseInsensitiveCollationCheck("tpcds_utf8_random", "UTF8_BINARY_LCASE", randomizeCase)
+    ),
+    Seq(
+      CaseSensitiveCollationCheck("tpcds_unicode", "UNICODE", collateNormalize),
+      CaseInsensitiveCollationCheck("tpcds_unicode_random", "UNICODE_CI", randomizeCase)
+    )
+  )
+
+  override def createTables(): Unit = {
+    // trim collated strings with udf

Review Comment:
   Fixed, please check.



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-47617][SQL] Add TPC-DS testing infrastructure for collations [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #45739:
URL: https://github.com/apache/spark/pull/45739#discussion_r1559852667


##########
sql/core/src/test/scala/org/apache/spark/sql/TPCDSCollationQueryTestSuite.scala:
##########
@@ -0,0 +1,270 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql
+
+import java.nio.file.{Files, Paths}
+import java.util.Locale
+
+import org.apache.spark.{SparkConf, SparkContext}
+import org.apache.spark.sql.catalyst.util.resourceToString
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.test.TestSparkSession
+import org.apache.spark.tags.ExtendedSQLTest
+import org.apache.spark.util.Utils
+
+/**
+ * End-to-end tests to validate TPC-DS query results against collation-aware
+ * modified data and queries.
+ *
+ * For each collation, table schemas are replicated into two databases in such way that in first
+ * DB all table columns are collated with specified collation, while the second DB collates table
+ * columns with case-insensitive version of the collation. Tables from first DB are then populated
+ * with lowercase-converted data from tpc-ds kit and tables from second DB are populated with
+ * randomized-case data.
+ *
+ * When running arbitrary SQL query, we convert the query to lowercase for execution

Review Comment:
   We should highlight that it's for lowercasing the string literals in the query string.



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-47617][SQL] Add TPC-DS testing infrastructure for collations [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #45739:
URL: https://github.com/apache/spark/pull/45739#discussion_r1557699328


##########
sql/core/src/test/scala/org/apache/spark/sql/TPCDSCollationQueryTestSuite.scala:
##########
@@ -0,0 +1,270 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql
+
+import java.nio.file.{Files, Paths}
+import java.util.Locale
+
+import org.apache.spark.{SparkConf, SparkContext}
+import org.apache.spark.sql.catalyst.util.resourceToString
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.test.TestSparkSession
+import org.apache.spark.tags.ExtendedSQLTest
+import org.apache.spark.util.Utils
+
+/**
+ * End-to-end tests to validate TPC-DS query results against collation-aware
+ * modified data and queries.
+ *
+ * For each collation, table schemas are replicated into two databases in such way that in first
+ * DB all table columns are collated with specified collation, while the second DB collates table
+ * columns with case-insensitive version of the collation. Tables from first DB are then populated
+ * with lowercase-converted data from tpc-ds kit and tables from second DB are populated with
+ * randomized-case data.
+ *
+ * When running arbitrary SQL query, we convert the query to lowercase for execution
+ * against first DB; second DB receives original query. Results should compare equal
+ * ignoring case. We use this method to validate collations are working with arbitrary standard
+ * SQL constructs.
+ *
+ * Additionally, we perform trims on string data to properly convert it from CharType
+ * to StringType and do sanity checks to verify that results are non-empty as expected.
+ *
+ * To run this test suite:
+ * {{{
+ *   SPARK_TPCDS_DATA=<path of TPCDS SF=1 data>
+ *     build/sbt "sql/testOnly *TPCDSCollationQueryTestSuite"
+ * }}}
+ *
+ * To run a single test file upon change:
+ * {{{
+ *   SPARK_TPCDS_DATA=<path of TPCDS SF=1 data>
+ *     build/sbt "sql/testOnly *TPCDSCollationQueryTestSuite -- -z q79"
+ * }}}
+ */
+@ExtendedSQLTest
+class TPCDSCollationQueryTestSuite extends QueryTest with TPCDSBase with SQLQueryTestHelper {
+
+  private val tpcdsDataPath = sys.env.get("SPARK_TPCDS_DATA")
+
+  // To make output results deterministic
+  override protected def sparkConf: SparkConf = super.sparkConf
+    .set(SQLConf.SHUFFLE_PARTITIONS.key, "1")
+
+  protected override def createSparkSession: TestSparkSession = {
+    new TestSparkSession(new SparkContext("local[1]", this.getClass.getSimpleName, sparkConf))
+  }
+
+  if (tpcdsDataPath.nonEmpty) {
+    val nonExistentTables = tableColumns.keys.filterNot { tableName =>
+      Files.exists(Paths.get(s"${tpcdsDataPath.get}/$tableName"))
+    }
+    if (nonExistentTables.nonEmpty) {
+      fail(s"Non-existent TPCDS table paths found in ${tpcdsDataPath.get}: " +
+        nonExistentTables.mkString(", "))
+    }
+  }
+
+  private def withDB[T](dbName: String)(fun: => T): T = {
+    Utils.tryWithSafeFinally({
+      spark.sql(s"USE `$dbName`")
+      fun
+    }) {
+      spark.sql("USE DEFAULT")
+    }
+  }
+
+  abstract class CollationCheck(
+      val dbName: String,
+      val collation: String,
+      val columnTransform: String) {
+
+    def queryTransform: String => String
+  }
+
+  case class CaseInsensitiveCollationCheck(
+      override val dbName: String,
+      override val collation: String,
+      override val columnTransform: String)
+    extends CollationCheck(dbName, collation, columnTransform) {
+
+    override def queryTransform: String => String = identity
+  }
+
+  case class CaseSensitiveCollationCheck(
+      override val dbName: String,
+      override val collation: String,
+      override val columnTransform: String)
+    extends CollationCheck(dbName, collation, columnTransform) {
+
+    override def queryTransform: String => String = _.toLowerCase(Locale.ROOT)
+  }
+
+  val collateNormalize = "COLLATE_NORMALIZE"
+  val randomizeCase = "RANDOMIZE_CASE"
+
+  // List of batches of runs which should yield the same result when run on a query
+  val checks: Seq[Seq[CollationCheck]] = Seq(
+    Seq(
+      CaseSensitiveCollationCheck("tpcds_utf8", "UTF8_BINARY", collateNormalize),
+      CaseInsensitiveCollationCheck("tpcds_utf8_random", "UTF8_BINARY_LCASE", randomizeCase)
+    ),
+    Seq(
+      CaseSensitiveCollationCheck("tpcds_unicode", "UNICODE", collateNormalize),
+      CaseInsensitiveCollationCheck("tpcds_unicode_random", "UNICODE_CI", randomizeCase)
+    )
+  )
+
+  override def createTables(): Unit = {
+    // trim collated strings with udf

Review Comment:
   there is a `rtrim` function in Spark



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-47617][SQL] Add TPC-DS testing infrastructure for collations [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #45739:
URL: https://github.com/apache/spark/pull/45739#discussion_r1557699328


##########
sql/core/src/test/scala/org/apache/spark/sql/TPCDSCollationQueryTestSuite.scala:
##########
@@ -0,0 +1,270 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql
+
+import java.nio.file.{Files, Paths}
+import java.util.Locale
+
+import org.apache.spark.{SparkConf, SparkContext}
+import org.apache.spark.sql.catalyst.util.resourceToString
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.test.TestSparkSession
+import org.apache.spark.tags.ExtendedSQLTest
+import org.apache.spark.util.Utils
+
+/**
+ * End-to-end tests to validate TPC-DS query results against collation-aware
+ * modified data and queries.
+ *
+ * For each collation, table schemas are replicated into two databases in such way that in first
+ * DB all table columns are collated with specified collation, while the second DB collates table
+ * columns with case-insensitive version of the collation. Tables from first DB are then populated
+ * with lowercase-converted data from tpc-ds kit and tables from second DB are populated with
+ * randomized-case data.
+ *
+ * When running arbitrary SQL query, we convert the query to lowercase for execution
+ * against first DB; second DB receives original query. Results should compare equal
+ * ignoring case. We use this method to validate collations are working with arbitrary standard
+ * SQL constructs.
+ *
+ * Additionally, we perform trims on string data to properly convert it from CharType
+ * to StringType and do sanity checks to verify that results are non-empty as expected.
+ *
+ * To run this test suite:
+ * {{{
+ *   SPARK_TPCDS_DATA=<path of TPCDS SF=1 data>
+ *     build/sbt "sql/testOnly *TPCDSCollationQueryTestSuite"
+ * }}}
+ *
+ * To run a single test file upon change:
+ * {{{
+ *   SPARK_TPCDS_DATA=<path of TPCDS SF=1 data>
+ *     build/sbt "sql/testOnly *TPCDSCollationQueryTestSuite -- -z q79"
+ * }}}
+ */
+@ExtendedSQLTest
+class TPCDSCollationQueryTestSuite extends QueryTest with TPCDSBase with SQLQueryTestHelper {
+
+  private val tpcdsDataPath = sys.env.get("SPARK_TPCDS_DATA")
+
+  // To make output results deterministic
+  override protected def sparkConf: SparkConf = super.sparkConf
+    .set(SQLConf.SHUFFLE_PARTITIONS.key, "1")
+
+  protected override def createSparkSession: TestSparkSession = {
+    new TestSparkSession(new SparkContext("local[1]", this.getClass.getSimpleName, sparkConf))
+  }
+
+  if (tpcdsDataPath.nonEmpty) {
+    val nonExistentTables = tableColumns.keys.filterNot { tableName =>
+      Files.exists(Paths.get(s"${tpcdsDataPath.get}/$tableName"))
+    }
+    if (nonExistentTables.nonEmpty) {
+      fail(s"Non-existent TPCDS table paths found in ${tpcdsDataPath.get}: " +
+        nonExistentTables.mkString(", "))
+    }
+  }
+
+  private def withDB[T](dbName: String)(fun: => T): T = {
+    Utils.tryWithSafeFinally({
+      spark.sql(s"USE `$dbName`")
+      fun
+    }) {
+      spark.sql("USE DEFAULT")
+    }
+  }
+
+  abstract class CollationCheck(
+      val dbName: String,
+      val collation: String,
+      val columnTransform: String) {
+
+    def queryTransform: String => String
+  }
+
+  case class CaseInsensitiveCollationCheck(
+      override val dbName: String,
+      override val collation: String,
+      override val columnTransform: String)
+    extends CollationCheck(dbName, collation, columnTransform) {
+
+    override def queryTransform: String => String = identity
+  }
+
+  case class CaseSensitiveCollationCheck(
+      override val dbName: String,
+      override val collation: String,
+      override val columnTransform: String)
+    extends CollationCheck(dbName, collation, columnTransform) {
+
+    override def queryTransform: String => String = _.toLowerCase(Locale.ROOT)
+  }
+
+  val collateNormalize = "COLLATE_NORMALIZE"
+  val randomizeCase = "RANDOMIZE_CASE"
+
+  // List of batches of runs which should yield the same result when run on a query
+  val checks: Seq[Seq[CollationCheck]] = Seq(
+    Seq(
+      CaseSensitiveCollationCheck("tpcds_utf8", "UTF8_BINARY", collateNormalize),
+      CaseInsensitiveCollationCheck("tpcds_utf8_random", "UTF8_BINARY_LCASE", randomizeCase)
+    ),
+    Seq(
+      CaseSensitiveCollationCheck("tpcds_unicode", "UNICODE", collateNormalize),
+      CaseInsensitiveCollationCheck("tpcds_unicode_random", "UNICODE_CI", randomizeCase)
+    )
+  )
+
+  override def createTables(): Unit = {
+    // trim collated strings with udf

Review Comment:
   there is a `trim/rtrim` function in Spark, and `lower`



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-47617][SQL] Add TPC-DS testing infrastructure for collations [spark]

Posted by "nikolamand-db (via GitHub)" <gi...@apache.org>.
nikolamand-db commented on PR #45739:
URL: https://github.com/apache/spark/pull/45739#issuecomment-2037548246

   Collation team, please review @dbatomic, @stefankandic, @uros-db, @mihailom-db, @stevomitric.


-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-47617][SQL] Add TPC-DS testing infrastructure for collations [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #45739:
URL: https://github.com/apache/spark/pull/45739#discussion_r1559086524


##########
sql/core/src/test/scala/org/apache/spark/sql/TPCDSCollationQueryTestSuite.scala:
##########
@@ -0,0 +1,270 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql
+
+import java.nio.file.{Files, Paths}
+import java.util.Locale
+
+import org.apache.spark.{SparkConf, SparkContext}
+import org.apache.spark.sql.catalyst.util.resourceToString
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.test.TestSparkSession
+import org.apache.spark.tags.ExtendedSQLTest
+import org.apache.spark.util.Utils
+
+/**
+ * End-to-end tests to validate TPC-DS query results against collation-aware
+ * modified data and queries.
+ *
+ * For each collation, table schemas are replicated into two databases in such way that in first
+ * DB all table columns are collated with specified collation, while the second DB collates table
+ * columns with case-insensitive version of the collation. Tables from first DB are then populated
+ * with lowercase-converted data from tpc-ds kit and tables from second DB are populated with
+ * randomized-case data.
+ *
+ * When running arbitrary SQL query, we convert the query to lowercase for execution

Review Comment:
   What does it mean to convert query to lowercase? Lowercase the full query string?



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-47617][SQL] Add TPC-DS testing infrastructure for collations [spark]

Posted by "nikolamand-db (via GitHub)" <gi...@apache.org>.
nikolamand-db commented on code in PR #45739:
URL: https://github.com/apache/spark/pull/45739#discussion_r1557841990


##########
sql/core/src/test/scala/org/apache/spark/sql/TPCDSBase.scala:
##########
@@ -34,7 +34,7 @@ trait TPCDSBase extends TPCBase with TPCDSSchema {
     "q81", "q82", "q83", "q84", "q85", "q86", "q87", "q88", "q89", "q90",
     "q91", "q92", "q93", "q94", "q95", "q96", "q97", "q98", "q99")
 
-  protected val excludedTpcdsQueries: Set[String] = if (regenerateGoldenFiles) {
+  protected def excludedTpcdsQueries: Set[String] = if (regenerateGoldenFiles) {

Review Comment:
   I've replaced `val` with `def` because in the override definition we refer to super instance (this wouldn't compile if we used `val`): https://github.com/apache/spark/blob/50f8d7957527b3f60c96db23a6ca2db019593df3/sql/core/src/test/scala/org/apache/spark/sql/TPCDSCollationQueryTestSuite.scala#L238 The loop which runs on `tpcdsAllQueries` and calls the def has ~100 iterations so this shouldn't have significant impact on the performance.



##########
sql/core/src/test/scala/org/apache/spark/sql/TPCDSCollationQueryTestSuite.scala:
##########
@@ -0,0 +1,270 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql
+
+import java.nio.file.{Files, Paths}
+import java.util.Locale
+
+import org.apache.spark.{SparkConf, SparkContext}
+import org.apache.spark.sql.catalyst.util.resourceToString
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.test.TestSparkSession
+import org.apache.spark.tags.ExtendedSQLTest
+import org.apache.spark.util.Utils
+
+/**
+ * End-to-end tests to validate TPC-DS query results against collation-aware
+ * modified data and queries.
+ *
+ * For each collation, table schemas are replicated into two databases in such way that in first
+ * DB all table columns are collated with specified collation, while the second DB collates table
+ * columns with case-insensitive version of the collation. Tables from first DB are then populated
+ * with lowercase-converted data from tpc-ds kit and tables from second DB are populated with
+ * randomized-case data.
+ *
+ * When running arbitrary SQL query, we convert the query to lowercase for execution

Review Comment:
   Added clarification to the comment, please check.



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-47617][SQL] Add TPC-DS testing infrastructure for collations [spark]

Posted by "dbatomic (via GitHub)" <gi...@apache.org>.
dbatomic commented on code in PR #45739:
URL: https://github.com/apache/spark/pull/45739#discussion_r1553454482


##########
sql/core/src/test/scala/org/apache/spark/sql/TPCDSCollationQueryTestSuite.scala:
##########
@@ -0,0 +1,220 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql
+
+import java.nio.file.{Files, Paths}
+import java.util.Locale
+
+import org.apache.spark.{SparkConf, SparkContext}
+import org.apache.spark.sql.catalyst.util.resourceToString
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.test.TestSparkSession
+import org.apache.spark.tags.ExtendedSQLTest
+import org.apache.spark.util.Utils
+
+@ExtendedSQLTest
+class TPCDSCollationQueryTestSuite extends QueryTest with TPCDSBase with SQLQueryTestHelper {
+
+  private val tpcdsDataPath = sys.env.get("SPARK_TPCDS_DATA")
+
+  // To make output results deterministic
+  override protected def sparkConf: SparkConf = super.sparkConf
+    .set(SQLConf.SHUFFLE_PARTITIONS.key, "1")
+
+  protected override def createSparkSession: TestSparkSession = {
+    new TestSparkSession(new SparkContext("local[1]", this.getClass.getSimpleName, sparkConf))
+  }
+
+  if (tpcdsDataPath.nonEmpty) {
+    val nonExistentTables = tableColumns.keys.filterNot { tableName =>
+      Files.exists(Paths.get(s"${tpcdsDataPath.get}/$tableName"))
+    }
+    if (nonExistentTables.nonEmpty) {
+      fail(s"Non-existent TPCDS table paths found in ${tpcdsDataPath.get}: " +
+        nonExistentTables.mkString(", "))
+    }
+  }
+
+  private def withDB[T](dbName: String)(fun: => T): T = {
+    Utils.tryWithSafeFinally({
+      spark.sql(s"USE `$dbName`")
+      fun
+    }) {
+      spark.sql("USE DEFAULT")
+    }
+  }
+
+  abstract class CollationCheck(
+      val dbName: String,
+      val collation: String,
+      val columnTransform: String) {
+
+    def queryTransform: String => String
+  }
+
+  case class CaseInsensitiveCollationCheck(
+      override val dbName: String,
+      override val collation: String,
+      override val columnTransform: String)
+    extends CollationCheck(dbName, collation, columnTransform) {
+
+    override def queryTransform: String => String = identity
+  }
+
+  case class CaseSensitiveCollationCheck(
+      override val dbName: String,
+      override val collation: String,
+      override val columnTransform: String)
+    extends CollationCheck(dbName, collation, columnTransform) {
+
+    override def queryTransform: String => String = _.toLowerCase(Locale.ROOT)
+  }
+
+  val randomizeCase = "RANDOMIZE_CASE"
+
+  // List of batches of runs which should yield the same result when run on a query
+  val checks: Seq[Seq[CollationCheck]] = Seq(
+    Seq(
+      CaseSensitiveCollationCheck("tpcds_utf8", "UTF8_BINARY", "LOWER"),
+      CaseInsensitiveCollationCheck("tpcds_utf8_random", "UTF8_BINARY_LCASE", randomizeCase)
+    ),
+    Seq(
+      CaseSensitiveCollationCheck("tpcds_unicode", "UNICODE", "LOWER"),
+      CaseInsensitiveCollationCheck("tpcds_unicode_random", "UNICODE_CI", randomizeCase)
+    )
+  )
+
+  override def createTables(): Unit = {
+    spark.udf.register(
+      randomizeCase,
+      functions.udf((s: String) => {
+        s match {
+          case null => null
+          case _ =>
+            val random = new scala.util.Random()
+            s.map(c => if (random.nextBoolean()) c.toUpper else c.toLower)
+        }
+      }).asNondeterministic())
+    checks.flatten.foreach(check => {
+      spark.sql(s"CREATE DATABASE `${check.dbName}`")
+      withDB(check.dbName) {
+        tableNames.foreach(tableName => {
+          val columns = tableColumns(tableName)
+            .split("\n")
+            .filter(_.trim.nonEmpty)
+            .map { column =>
+              if (column.trim.split("\\s+").length != 2) {
+                throw new IllegalArgumentException(s"Invalid column definition: $column")
+              }
+              val Array(name, colType) = column.trim.split("\\s+")
+              (name, colType.replaceAll(",$", ""))
+            }
+
+          spark.sql(
+            s"""
+               |CREATE TABLE `$tableName` (${collateStringColumns(columns, check.collation)})
+               |USING parquet
+               |""".stripMargin)
+
+          val transformedColumns = columns.map { case (name, colType) =>
+            if (isTextColumn(colType)) {
+              s"${check.columnTransform}($name) AS $name"
+            } else {
+              name
+            }
+          }.mkString(", ")
+
+          spark.sql(
+            s"""
+               |INSERT INTO TABLE `$tableName`
+               |SELECT $transformedColumns
+               |FROM parquet.`${tpcdsDataPath.get}/$tableName`
+               |""".stripMargin)
+        })
+      }
+    })
+  }
+
+  override def dropTables(): Unit =
+    checks.flatten.foreach(check => {
+      withDB(check.dbName)(super.dropTables())
+      spark.sql(s"DROP DATABASE `${check.dbName}`")
+    })
+
+  private def collateStringColumns(
+      columns: Array[(String, String)],
+      collation: String): String = {
+    columns
+      .map { case (name, colType) =>
+        if (isTextColumn(colType)) {
+          s"$name STRING COLLATE $collation"
+        } else {
+          s"$name $colType"
+        }
+      }
+      .mkString(",\n")
+  }
+
+  private def isTextColumn(columnType: String): Boolean = {
+    columnType.toUpperCase(Locale.ROOT).contains("CHAR")

Review Comment:
   can you include varchar as well?



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-47617][SQL] Add TPC-DS testing infrastructure for collations [spark]

Posted by "dbatomic (via GitHub)" <gi...@apache.org>.
dbatomic commented on code in PR #45739:
URL: https://github.com/apache/spark/pull/45739#discussion_r1553454482


##########
sql/core/src/test/scala/org/apache/spark/sql/TPCDSCollationQueryTestSuite.scala:
##########
@@ -0,0 +1,220 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql
+
+import java.nio.file.{Files, Paths}
+import java.util.Locale
+
+import org.apache.spark.{SparkConf, SparkContext}
+import org.apache.spark.sql.catalyst.util.resourceToString
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.test.TestSparkSession
+import org.apache.spark.tags.ExtendedSQLTest
+import org.apache.spark.util.Utils
+
+@ExtendedSQLTest
+class TPCDSCollationQueryTestSuite extends QueryTest with TPCDSBase with SQLQueryTestHelper {
+
+  private val tpcdsDataPath = sys.env.get("SPARK_TPCDS_DATA")
+
+  // To make output results deterministic
+  override protected def sparkConf: SparkConf = super.sparkConf
+    .set(SQLConf.SHUFFLE_PARTITIONS.key, "1")
+
+  protected override def createSparkSession: TestSparkSession = {
+    new TestSparkSession(new SparkContext("local[1]", this.getClass.getSimpleName, sparkConf))
+  }
+
+  if (tpcdsDataPath.nonEmpty) {
+    val nonExistentTables = tableColumns.keys.filterNot { tableName =>
+      Files.exists(Paths.get(s"${tpcdsDataPath.get}/$tableName"))
+    }
+    if (nonExistentTables.nonEmpty) {
+      fail(s"Non-existent TPCDS table paths found in ${tpcdsDataPath.get}: " +
+        nonExistentTables.mkString(", "))
+    }
+  }
+
+  private def withDB[T](dbName: String)(fun: => T): T = {
+    Utils.tryWithSafeFinally({
+      spark.sql(s"USE `$dbName`")
+      fun
+    }) {
+      spark.sql("USE DEFAULT")
+    }
+  }
+
+  abstract class CollationCheck(
+      val dbName: String,
+      val collation: String,
+      val columnTransform: String) {
+
+    def queryTransform: String => String
+  }
+
+  case class CaseInsensitiveCollationCheck(
+      override val dbName: String,
+      override val collation: String,
+      override val columnTransform: String)
+    extends CollationCheck(dbName, collation, columnTransform) {
+
+    override def queryTransform: String => String = identity
+  }
+
+  case class CaseSensitiveCollationCheck(
+      override val dbName: String,
+      override val collation: String,
+      override val columnTransform: String)
+    extends CollationCheck(dbName, collation, columnTransform) {
+
+    override def queryTransform: String => String = _.toLowerCase(Locale.ROOT)
+  }
+
+  val randomizeCase = "RANDOMIZE_CASE"
+
+  // List of batches of runs which should yield the same result when run on a query
+  val checks: Seq[Seq[CollationCheck]] = Seq(
+    Seq(
+      CaseSensitiveCollationCheck("tpcds_utf8", "UTF8_BINARY", "LOWER"),
+      CaseInsensitiveCollationCheck("tpcds_utf8_random", "UTF8_BINARY_LCASE", randomizeCase)
+    ),
+    Seq(
+      CaseSensitiveCollationCheck("tpcds_unicode", "UNICODE", "LOWER"),
+      CaseInsensitiveCollationCheck("tpcds_unicode_random", "UNICODE_CI", randomizeCase)
+    )
+  )
+
+  override def createTables(): Unit = {
+    spark.udf.register(
+      randomizeCase,
+      functions.udf((s: String) => {
+        s match {
+          case null => null
+          case _ =>
+            val random = new scala.util.Random()
+            s.map(c => if (random.nextBoolean()) c.toUpper else c.toLower)
+        }
+      }).asNondeterministic())
+    checks.flatten.foreach(check => {
+      spark.sql(s"CREATE DATABASE `${check.dbName}`")
+      withDB(check.dbName) {
+        tableNames.foreach(tableName => {
+          val columns = tableColumns(tableName)
+            .split("\n")
+            .filter(_.trim.nonEmpty)
+            .map { column =>
+              if (column.trim.split("\\s+").length != 2) {
+                throw new IllegalArgumentException(s"Invalid column definition: $column")
+              }
+              val Array(name, colType) = column.trim.split("\\s+")
+              (name, colType.replaceAll(",$", ""))
+            }
+
+          spark.sql(
+            s"""
+               |CREATE TABLE `$tableName` (${collateStringColumns(columns, check.collation)})
+               |USING parquet
+               |""".stripMargin)
+
+          val transformedColumns = columns.map { case (name, colType) =>
+            if (isTextColumn(colType)) {
+              s"${check.columnTransform}($name) AS $name"
+            } else {
+              name
+            }
+          }.mkString(", ")
+
+          spark.sql(
+            s"""
+               |INSERT INTO TABLE `$tableName`
+               |SELECT $transformedColumns
+               |FROM parquet.`${tpcdsDataPath.get}/$tableName`
+               |""".stripMargin)
+        })
+      }
+    })
+  }
+
+  override def dropTables(): Unit =
+    checks.flatten.foreach(check => {
+      withDB(check.dbName)(super.dropTables())
+      spark.sql(s"DROP DATABASE `${check.dbName}`")
+    })
+
+  private def collateStringColumns(
+      columns: Array[(String, String)],
+      collation: String): String = {
+    columns
+      .map { case (name, colType) =>
+        if (isTextColumn(colType)) {
+          s"$name STRING COLLATE $collation"
+        } else {
+          s"$name $colType"
+        }
+      }
+      .mkString(",\n")
+  }
+
+  private def isTextColumn(columnType: String): Boolean = {
+    columnType.toUpperCase(Locale.ROOT).contains("CHAR")

Review Comment:
   can you include varchar as well?



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-47617][SQL] Add TPC-DS testing infrastructure for collations [spark]

Posted by "nikolamand-db (via GitHub)" <gi...@apache.org>.
nikolamand-db commented on code in PR #45739:
URL: https://github.com/apache/spark/pull/45739#discussion_r1559228727


##########
sql/core/src/test/scala/org/apache/spark/sql/TPCDSCollationQueryTestSuite.scala:
##########
@@ -0,0 +1,270 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql
+
+import java.nio.file.{Files, Paths}
+import java.util.Locale
+
+import org.apache.spark.{SparkConf, SparkContext}
+import org.apache.spark.sql.catalyst.util.resourceToString
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.test.TestSparkSession
+import org.apache.spark.tags.ExtendedSQLTest
+import org.apache.spark.util.Utils
+
+/**
+ * End-to-end tests to validate TPC-DS query results against collation-aware
+ * modified data and queries.
+ *
+ * For each collation, table schemas are replicated into two databases in such way that in first
+ * DB all table columns are collated with specified collation, while the second DB collates table
+ * columns with case-insensitive version of the collation. Tables from first DB are then populated
+ * with lowercase-converted data from tpc-ds kit and tables from second DB are populated with
+ * randomized-case data.
+ *
+ * When running arbitrary SQL query, we convert the query to lowercase for execution

Review Comment:
   That's right. We lowercase the full query text contents and in this way string literals will end up being lowercase which is required to produce the same results as case-insensitive collation.
   
   For example, if the query is something like `select count(*) where s = 'A'`, when converted to lowercase, query will count number of rows where we have "a" instead of "A" to produce correct results on row data which is already in lowercase. We need this in order to be able to compare the results with the same query executed against collated table.
   
   Can add more clarification to the header comment and include this example if you think it's still unclear.



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-47617][SQL] Add TPC-DS testing infrastructure for collations [spark]

Posted by "stefankandic (via GitHub)" <gi...@apache.org>.
stefankandic commented on code in PR #45739:
URL: https://github.com/apache/spark/pull/45739#discussion_r1551959563


##########
sql/core/src/test/scala/org/apache/spark/sql/TPCDSCollationQueryTestSuite.scala:
##########
@@ -0,0 +1,214 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql
+
+import java.nio.file.{Files, Paths}
+import java.util.Locale
+
+import org.apache.spark.{SparkConf, SparkContext}
+import org.apache.spark.sql.catalyst.util.resourceToString
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.test.TestSparkSession
+import org.apache.spark.tags.ExtendedSQLTest
+import org.apache.spark.util.Utils
+
+@ExtendedSQLTest
+class TPCDSCollationQueryTestSuite extends QueryTest with TPCDSBase with SQLQueryTestHelper {
+
+  private val tpcdsDataPath = sys.env.get("SPARK_TPCDS_DATA")
+
+  // To make output results deterministic
+  override protected def sparkConf: SparkConf = super.sparkConf
+    .set(SQLConf.SHUFFLE_PARTITIONS.key, "1")
+
+  protected override def createSparkSession: TestSparkSession = {
+    new TestSparkSession(new SparkContext("local[1]", this.getClass.getSimpleName, sparkConf))
+  }
+
+  if (tpcdsDataPath.nonEmpty) {
+    val nonExistentTables = tableColumns.keys.filterNot { tableName =>
+      Files.exists(Paths.get(s"${tpcdsDataPath.get}/$tableName"))
+    }
+    if (nonExistentTables.nonEmpty) {
+      fail(s"Non-existent TPCDS table paths found in ${tpcdsDataPath.get}: " +
+        nonExistentTables.mkString(", "))
+    }
+  }
+
+  private def withDB[T](dbName: String)(fun: => T): T = {
+    Utils.tryWithSafeFinally({
+      spark.sql(s"USE `$dbName`")
+      fun
+    }) {
+      spark.sql("USE DEFAULT")
+    }
+  }
+
+  abstract class CollationCheck(val dbName: String,
+                                val collation: String,
+                                val columnTransform: String) {
+    def queryTransform: String => String
+  }
+
+  case class CaseInsensitiveCollationCheck(override val dbName: String,
+                                           override val collation: String,
+                                           override val columnTransform: String)
+    extends CollationCheck(dbName, collation, columnTransform) {
+    def queryTransform: String => String = identity
+  }
+
+  case class CaseSensitiveCollationCheck(override val dbName: String,
+                                         override val collation: String,
+                                         override val columnTransform: String)
+    extends CollationCheck(dbName, collation, columnTransform) {
+    override def queryTransform: String => String = _.toLowerCase(Locale.ROOT)
+  }
+
+  val randomizeCase = "RANDOMIZE_CASE"
+
+  // List of batches of runs which should yield the same result when run on a query
+  val checks: Seq[Seq[CollationCheck]] = Seq(
+    Seq(
+      CaseSensitiveCollationCheck("tpcds_utf8", "UTF8_BINARY", "LOWER"),
+      CaseInsensitiveCollationCheck("tpcds_utf8_random", "UTF8_BINARY_LCASE", randomizeCase)
+    ),
+    Seq(
+      CaseSensitiveCollationCheck("tpcds_unicode", "UNICODE", "LOWER"),
+      CaseInsensitiveCollationCheck("tpcds_unicode_random", "UNICODE_CI", randomizeCase)
+    )
+  )
+
+  override def createTables(): Unit = {
+    spark.udf.register(
+      randomizeCase,
+      functions.udf((s: String) => {
+        s match {
+          case null => null
+          case _ =>
+            val random = new scala.util.Random()
+            s.map(c => if (random.nextBoolean()) c.toUpper else c.toLower)
+        }
+      }).asNondeterministic())
+    checks.flatten.foreach(check => {
+      spark.sql(s"CREATE DATABASE `${check.dbName}`")
+      withDB(check.dbName) {
+        tableNames.foreach(tableName => {
+          val columns = tableColumns(tableName)
+            .split("\n")
+            .filter(_.trim.nonEmpty)
+            .map { column =>
+              if (column.trim.split("\\s+").length != 2) {
+                throw new IllegalArgumentException(s"Invalid column definition: $column")
+              }
+              val Array(name, colType) = column.trim.split("\\s+")
+              (name, colType.replaceAll(",$", ""))
+            }
+
+          spark.sql(
+            s"""
+               |CREATE TABLE `$tableName` (${collateStringColumns(columns, check.collation)})
+               |USING parquet
+               |""".stripMargin)
+
+          val transformedColumns = columns.map { case (name, colType) =>
+            if (isTextColumn(colType)) {
+              s"${check.columnTransform}($name) AS $name"
+            } else {
+              name
+            }
+          }.mkString(", ")
+
+          spark.sql(
+            s"""
+               |INSERT INTO TABLE `$tableName`
+               |SELECT $transformedColumns
+               |FROM parquet.`${tpcdsDataPath.get}/$tableName`
+               |""".stripMargin)
+        })
+      }
+    })
+  }
+
+  override def dropTables(): Unit =
+    checks.flatten.foreach(check => {
+      withDB(check.dbName)(super.dropTables())
+      spark.sql(s"DROP DATABASE `${check.dbName}`")
+    })
+
+  private def collateStringColumns(
+      columns: Array[(String, String)],
+      collation: String): String = {
+    columns
+      .map { case (name, colType) =>
+        if (isTextColumn(colType)) {
+          s"$name STRING COLLATE $collation"
+        } else {
+          s"$name $colType"
+        }
+      }
+      .mkString(",\n")
+  }
+
+  private def isTextColumn(columnType: String): Boolean = {
+    columnType.toUpperCase(Locale.ROOT).contains("CHAR")
+  }
+
+  private def runQuery(query: String, conf: Map[String, String]): Unit = {
+    withSQLConf(conf.toSeq: _*) {
+      try {
+        checks.foreach(batch => {
+          val res = batch.map(check =>
+            withDB(check.dbName)(getQueryOutput(check.queryTransform(query)).toLowerCase()))
+          if (res.nonEmpty) res.foreach(currRes => assertResult(currRes)(res.head))
+        })
+      } catch {
+        case e: Throwable =>
+          val configs = conf.map { case (k, v) =>
+            s"$k=$v"
+          }
+          throw new Exception(s"${e.getMessage}\nError using configs:\n${configs.mkString("\n")}")
+      }
+    }
+  }
+
+  private def getQueryOutput(query: String): String = {
+    val (_, output) = handleExceptions(getNormalizedQueryExecutionResult(spark, query))
+    output.mkString("\n").replaceAll("\\s+$", "")
+  }
+
+  // skip q91 due to use of like expression which is not supported with collations yet
+  override def excludedTpcdsQueries: Set[String] = super.excludedTpcdsQueries ++ Set("q91")

Review Comment:
   what do you think about writing the output to golden files like the regular tpcds test does?
   
   that way we won't have to skip this query



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-47617][SQL] Add TPC-DS testing infrastructure for collations [spark]

Posted by "stefankandic (via GitHub)" <gi...@apache.org>.
stefankandic commented on code in PR #45739:
URL: https://github.com/apache/spark/pull/45739#discussion_r1551960665


##########
sql/core/src/test/scala/org/apache/spark/sql/TPCDSCollationQueryTestSuite.scala:
##########
@@ -0,0 +1,214 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql
+
+import java.nio.file.{Files, Paths}
+import java.util.Locale
+
+import org.apache.spark.{SparkConf, SparkContext}
+import org.apache.spark.sql.catalyst.util.resourceToString
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.test.TestSparkSession
+import org.apache.spark.tags.ExtendedSQLTest
+import org.apache.spark.util.Utils
+
+@ExtendedSQLTest
+class TPCDSCollationQueryTestSuite extends QueryTest with TPCDSBase with SQLQueryTestHelper {
+
+  private val tpcdsDataPath = sys.env.get("SPARK_TPCDS_DATA")
+
+  // To make output results deterministic
+  override protected def sparkConf: SparkConf = super.sparkConf
+    .set(SQLConf.SHUFFLE_PARTITIONS.key, "1")
+
+  protected override def createSparkSession: TestSparkSession = {
+    new TestSparkSession(new SparkContext("local[1]", this.getClass.getSimpleName, sparkConf))
+  }
+
+  if (tpcdsDataPath.nonEmpty) {
+    val nonExistentTables = tableColumns.keys.filterNot { tableName =>
+      Files.exists(Paths.get(s"${tpcdsDataPath.get}/$tableName"))
+    }
+    if (nonExistentTables.nonEmpty) {
+      fail(s"Non-existent TPCDS table paths found in ${tpcdsDataPath.get}: " +
+        nonExistentTables.mkString(", "))
+    }
+  }
+
+  private def withDB[T](dbName: String)(fun: => T): T = {
+    Utils.tryWithSafeFinally({
+      spark.sql(s"USE `$dbName`")
+      fun
+    }) {
+      spark.sql("USE DEFAULT")
+    }
+  }
+
+  abstract class CollationCheck(val dbName: String,
+                                val collation: String,

Review Comment:
   fix indentation here and below for constructor parameters



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-47617][SQL] Add TPC-DS testing infrastructure for collations [spark]

Posted by "cloud-fan (via GitHub)" <gi...@apache.org>.
cloud-fan commented on code in PR #45739:
URL: https://github.com/apache/spark/pull/45739#discussion_r1557679114


##########
sql/core/src/test/scala/org/apache/spark/sql/TPCDSCollationQueryTestSuite.scala:
##########
@@ -0,0 +1,270 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql
+
+import java.nio.file.{Files, Paths}
+import java.util.Locale
+
+import org.apache.spark.{SparkConf, SparkContext}
+import org.apache.spark.sql.catalyst.util.resourceToString
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.test.TestSparkSession
+import org.apache.spark.tags.ExtendedSQLTest
+import org.apache.spark.util.Utils
+
+/**
+ * End-to-end tests to validate TPC-DS query results against collation-aware
+ * modified data and queries.
+ *
+ * For each collation, table schemas are replicated into two databases in such way that in first
+ * DB all table columns are collated with specified collation, while the second DB collates table
+ * columns with case-insensitive version of the collation. Tables from first DB are then populated
+ * with lowercase-converted data from tpc-ds kit and tables from second DB are populated with
+ * randomized-case data.
+ *
+ * When running arbitrary SQL query, we convert the query to lowercase for execution

Review Comment:
   convert the query to lowercase?



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-47617][SQL] Add TPC-DS testing infrastructure for collations [spark]

Posted by "dbatomic (via GitHub)" <gi...@apache.org>.
dbatomic commented on code in PR #45739:
URL: https://github.com/apache/spark/pull/45739#discussion_r1553446146


##########
sql/core/src/test/scala/org/apache/spark/sql/TPCDSCollationQueryTestSuite.scala:
##########
@@ -0,0 +1,220 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql
+
+import java.nio.file.{Files, Paths}
+import java.util.Locale
+
+import org.apache.spark.{SparkConf, SparkContext}
+import org.apache.spark.sql.catalyst.util.resourceToString
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.test.TestSparkSession
+import org.apache.spark.tags.ExtendedSQLTest
+import org.apache.spark.util.Utils
+
+@ExtendedSQLTest
+class TPCDSCollationQueryTestSuite extends QueryTest with TPCDSBase with SQLQueryTestHelper {

Review Comment:
   Can you add a comment header to this class and explain why do we need it?



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org


Re: [PR] [SPARK-47617][SQL] Add TPC-DS testing infrastructure for collations [spark]

Posted by "nikolamand-db (via GitHub)" <gi...@apache.org>.
nikolamand-db commented on code in PR #45739:
URL: https://github.com/apache/spark/pull/45739#discussion_r1552030717


##########
sql/core/src/test/scala/org/apache/spark/sql/TPCDSCollationQueryTestSuite.scala:
##########
@@ -0,0 +1,214 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.spark.sql
+
+import java.nio.file.{Files, Paths}
+import java.util.Locale
+
+import org.apache.spark.{SparkConf, SparkContext}
+import org.apache.spark.sql.catalyst.util.resourceToString
+import org.apache.spark.sql.internal.SQLConf
+import org.apache.spark.sql.test.TestSparkSession
+import org.apache.spark.tags.ExtendedSQLTest
+import org.apache.spark.util.Utils
+
+@ExtendedSQLTest
+class TPCDSCollationQueryTestSuite extends QueryTest with TPCDSBase with SQLQueryTestHelper {
+
+  private val tpcdsDataPath = sys.env.get("SPARK_TPCDS_DATA")
+
+  // To make output results deterministic
+  override protected def sparkConf: SparkConf = super.sparkConf
+    .set(SQLConf.SHUFFLE_PARTITIONS.key, "1")
+
+  protected override def createSparkSession: TestSparkSession = {
+    new TestSparkSession(new SparkContext("local[1]", this.getClass.getSimpleName, sparkConf))
+  }
+
+  if (tpcdsDataPath.nonEmpty) {
+    val nonExistentTables = tableColumns.keys.filterNot { tableName =>
+      Files.exists(Paths.get(s"${tpcdsDataPath.get}/$tableName"))
+    }
+    if (nonExistentTables.nonEmpty) {
+      fail(s"Non-existent TPCDS table paths found in ${tpcdsDataPath.get}: " +
+        nonExistentTables.mkString(", "))
+    }
+  }
+
+  private def withDB[T](dbName: String)(fun: => T): T = {
+    Utils.tryWithSafeFinally({
+      spark.sql(s"USE `$dbName`")
+      fun
+    }) {
+      spark.sql("USE DEFAULT")
+    }
+  }
+
+  abstract class CollationCheck(val dbName: String,
+                                val collation: String,
+                                val columnTransform: String) {
+    def queryTransform: String => String
+  }
+
+  case class CaseInsensitiveCollationCheck(override val dbName: String,
+                                           override val collation: String,
+                                           override val columnTransform: String)
+    extends CollationCheck(dbName, collation, columnTransform) {
+    def queryTransform: String => String = identity
+  }
+
+  case class CaseSensitiveCollationCheck(override val dbName: String,
+                                         override val collation: String,
+                                         override val columnTransform: String)
+    extends CollationCheck(dbName, collation, columnTransform) {
+    override def queryTransform: String => String = _.toLowerCase(Locale.ROOT)
+  }
+
+  val randomizeCase = "RANDOMIZE_CASE"
+
+  // List of batches of runs which should yield the same result when run on a query
+  val checks: Seq[Seq[CollationCheck]] = Seq(
+    Seq(
+      CaseSensitiveCollationCheck("tpcds_utf8", "UTF8_BINARY", "LOWER"),
+      CaseInsensitiveCollationCheck("tpcds_utf8_random", "UTF8_BINARY_LCASE", randomizeCase)
+    ),
+    Seq(
+      CaseSensitiveCollationCheck("tpcds_unicode", "UNICODE", "LOWER"),
+      CaseInsensitiveCollationCheck("tpcds_unicode_random", "UNICODE_CI", randomizeCase)
+    )
+  )
+
+  override def createTables(): Unit = {
+    spark.udf.register(
+      randomizeCase,
+      functions.udf((s: String) => {
+        s match {
+          case null => null
+          case _ =>
+            val random = new scala.util.Random()
+            s.map(c => if (random.nextBoolean()) c.toUpper else c.toLower)
+        }
+      }).asNondeterministic())
+    checks.flatten.foreach(check => {
+      spark.sql(s"CREATE DATABASE `${check.dbName}`")
+      withDB(check.dbName) {
+        tableNames.foreach(tableName => {
+          val columns = tableColumns(tableName)
+            .split("\n")
+            .filter(_.trim.nonEmpty)
+            .map { column =>
+              if (column.trim.split("\\s+").length != 2) {
+                throw new IllegalArgumentException(s"Invalid column definition: $column")
+              }
+              val Array(name, colType) = column.trim.split("\\s+")
+              (name, colType.replaceAll(",$", ""))
+            }
+
+          spark.sql(
+            s"""
+               |CREATE TABLE `$tableName` (${collateStringColumns(columns, check.collation)})
+               |USING parquet
+               |""".stripMargin)
+
+          val transformedColumns = columns.map { case (name, colType) =>
+            if (isTextColumn(colType)) {
+              s"${check.columnTransform}($name) AS $name"
+            } else {
+              name
+            }
+          }.mkString(", ")
+
+          spark.sql(
+            s"""
+               |INSERT INTO TABLE `$tableName`
+               |SELECT $transformedColumns
+               |FROM parquet.`${tpcdsDataPath.get}/$tableName`
+               |""".stripMargin)
+        })
+      }
+    })
+  }
+
+  override def dropTables(): Unit =
+    checks.flatten.foreach(check => {
+      withDB(check.dbName)(super.dropTables())
+      spark.sql(s"DROP DATABASE `${check.dbName}`")
+    })
+
+  private def collateStringColumns(
+      columns: Array[(String, String)],
+      collation: String): String = {
+    columns
+      .map { case (name, colType) =>
+        if (isTextColumn(colType)) {
+          s"$name STRING COLLATE $collation"
+        } else {
+          s"$name $colType"
+        }
+      }
+      .mkString(",\n")
+  }
+
+  private def isTextColumn(columnType: String): Boolean = {
+    columnType.toUpperCase(Locale.ROOT).contains("CHAR")
+  }
+
+  private def runQuery(query: String, conf: Map[String, String]): Unit = {
+    withSQLConf(conf.toSeq: _*) {
+      try {
+        checks.foreach(batch => {
+          val res = batch.map(check =>
+            withDB(check.dbName)(getQueryOutput(check.queryTransform(query)).toLowerCase()))
+          if (res.nonEmpty) res.foreach(currRes => assertResult(currRes)(res.head))
+        })
+      } catch {
+        case e: Throwable =>
+          val configs = conf.map { case (k, v) =>
+            s"$k=$v"
+          }
+          throw new Exception(s"${e.getMessage}\nError using configs:\n${configs.mkString("\n")}")
+      }
+    }
+  }
+
+  private def getQueryOutput(query: String): String = {
+    val (_, output) = handleExceptions(getNormalizedQueryExecutionResult(spark, query))
+    output.mkString("\n").replaceAll("\\s+$", "")
+  }
+
+  // skip q91 due to use of like expression which is not supported with collations yet
+  override def excludedTpcdsQueries: Set[String] = super.excludedTpcdsQueries ++ Set("q91")

Review Comment:
   The idea to omit golden files was that the output is for the most part just lowercase version of regular TPC-DS outputs which are already checked-in and would be kinda duplicate.
   
   Not sure though how adding golden files would help for this particular case as they first need to be generated but this query errors out because it contains like expression which still doesn't support collations.



-- 
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: reviews-unsubscribe@spark.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: reviews-unsubscribe@spark.apache.org
For additional commands, e-mail: reviews-help@spark.apache.org