shujingyang-db commented on code in PR #50300: URL: https://github.com/apache/spark/pull/50300#discussion_r2031680602
########## sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/xml/XmlVariantSuite.scala: ########## @@ -0,0 +1,493 @@ +/* + * 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.execution.datasources.xml + +import java.time.ZoneOffset + +import org.apache.spark.sql.{AnalysisException, DataFrame, QueryTest, Row} +import org.apache.spark.sql.catalyst.xml.{StaxXmlParser, XmlOptions} +import org.apache.spark.sql.functions.{col, variant_get} +import org.apache.spark.sql.internal.SQLConf +import org.apache.spark.sql.test.SharedSparkSession + +class XmlVariantSuite extends QueryTest with SharedSparkSession with TestXmlData { Review Comment: Is there a way to reuse existing test suite? ########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/expressions/xmlExpressions.scala: ########## @@ -54,7 +54,7 @@ import org.apache.spark.unsafe.types.UTF8String since = "4.0.0") // scalastyle:on line.size.limit case class XmlToStructs( - schema: StructType, Review Comment: Previously, we don't allow ArrayType as the top-level data type. Can we add a test to ensure that it doesn't break the semantics? ########## sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/xml/XmlVariantSuite.scala: ########## @@ -0,0 +1,493 @@ +/* + * 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.execution.datasources.xml + +import java.time.ZoneOffset + +import org.apache.spark.sql.{AnalysisException, DataFrame, QueryTest, Row} +import org.apache.spark.sql.catalyst.xml.{StaxXmlParser, XmlOptions} +import org.apache.spark.sql.functions.{col, variant_get} +import org.apache.spark.sql.internal.SQLConf +import org.apache.spark.sql.test.SharedSparkSession + +class XmlVariantSuite extends QueryTest with SharedSparkSession with TestXmlData { + + private val baseOptions = Map("rowTag" -> "ROW", "valueTag" -> "_VALUE", "attributePrefix" -> "_") + + private val resDir = "test-data/xml-resources/" + + // ========================== + // ====== Parser tests ====== + // ========================== + + private def testParser( + xml: String, + expectedJsonStr: String, + extraOptions: Map[String, String] = Map.empty): Unit = { + val parsed = StaxXmlParser.parseVariant(xml, XmlOptions(baseOptions ++ extraOptions)) + assert(parsed.toJson(ZoneOffset.UTC) == expectedJsonStr) + } + + test("Parser: parse primitive XML elements (long, decimal, double, etc.) as variants") { + // Boolean -> Boolean + testParser("<ROW><isActive>false</isActive></ROW>", """{"isActive":false}""") + testParser("<ROW><isActive>true</isActive></ROW>", """{"isActive":true}""") + + // Long -> Long + testParser("<ROW><id>2</id></ROW>", """{"id":2}""") + testParser("<ROW><id>+2</id></ROW>", """{"id":2}""") + testParser("<ROW><id>-2</id></ROW>", """{"id":-2}""") + + // Decimal -> Decimal + testParser( + xml = "<ROW><price>158,058,049.001</price></ROW>", + expectedJsonStr = """{"price":158058049.001}""" + ) + testParser( + xml = "<ROW><decimal>10.05</decimal></ROW>", + expectedJsonStr = """{"decimal":10.05}""" + ) + testParser( + xml = "<ROW><amount>5.0</amount></ROW>", + expectedJsonStr = """{"amount":5}""" + ) + + // Date -> String + testParser( + xml = "<ROW><createdAt>2023-10-01</createdAt></ROW>", + expectedJsonStr = """{"createdAt":"2023-10-01"}""" + ) + + // Timestamp -> String + testParser( + xml = "<ROW><createdAt>2023-10-01T12:00:00Z</createdAt></ROW>", + expectedJsonStr = """{"createdAt":"2023-10-01T12:00:00Z"}""" + ) + + // String -> String + testParser("<ROW><name>Sam</name></ROW>", """{"name":"Sam"}""") + // Strings with spaces + testParser( + "<ROW><note> hello world </note></ROW>", + expectedJsonStr = """{"note":" hello world "}""", + extraOptions = Map("ignoreSurroundingSpaces" -> "false") + ) + testParser( + xml = "<ROW><note> hello world </note></ROW>", + expectedJsonStr = """{"note":"hello world"}""" + ) + // Scientic numbers -> String + testParser( + xml = "<ROW><amount>4.9E-324</amount></ROW>", + expectedJsonStr = """{"amount":"4.9E-324"}""" + ) + } + + test("Parser: parse XML attributes as variants") { + // XML elements with only attributes + testParser( + xml = "<ROW id=\"2\" name=\"Sam\" amount=\"93\"></ROW>", + expectedJsonStr = """{"_amount":93,"_id":2,"_name":"Sam"}""" + ) + + // XML elements with attributes and elements + testParser( + xml = "<ROW id=\"2\" name=\"Sam\"><amount>93</amount></ROW>", + expectedJsonStr = """{"_id":2,"_name":"Sam","amount":93}""" + ) + + // XML elements with attributes and nested elements + testParser( + xml = "<ROW id=\"2\" name=\"Sam\"><info><amount>93</amount></info></ROW>", + expectedJsonStr = """{"_id":2,"_name":"Sam","info":{"amount":93}}""" + ) + + // XML elements with attributes and value tag + testParser( + xml = "<ROW id=\"2\" name=\"Sam\">93</ROW>", + expectedJsonStr = """{"_VALUE":93,"_id":2,"_name":"Sam"}""" + ) + } + + test("Parser: parse XML value tags as variants") { + // XML elements with value tags and attributes + testParser( + xml = "<ROW id=\"2\" name=\"Sam\">93</ROW>", + expectedJsonStr = """{"_VALUE":93,"_id":2,"_name":"Sam"}""" + ) + + // XML elements with value tags and nested elements + testParser( + xml = "<ROW><info>Sam<amount>93</amount></info></ROW>", + expectedJsonStr = """{"info":{"_VALUE":"Sam","amount":93}}""" + ) + } + + test("Parser: parse XML elements as variant object") { + testParser( + xml = "<ROW><info><name>Sam</name><amount>93</amount></info></ROW>", + expectedJsonStr = """{"info":{"amount":93,"name":"Sam"}}""" + ) + } + + test("Parser: parse XML elements as variant array") { + testParser( + xml = "<ROW><array>1</array><array>2</array></ROW>", + expectedJsonStr = """{"array":[1,2]}""" + ) + } + + test("Parser: null and empty XML elements are parsed as variant null") { + // XML elements with null and empty values + testParser( + xml = "<ROW><name></name><amount>93</amount></ROW>", + expectedJsonStr = """{"amount":93,"name":null}""" + ) + testParser( + xml = "<ROW><name>Sam</name><amount>n/a</amount></ROW>", + expectedJsonStr = """{"amount":null,"name":"Sam"}""", + extraOptions = Map("nullValue" -> "n/a") + ) + } + + test("Parser: Parse whitespaces with quotes") { + // XML elements with whitespaces + testParser( + xml = s""" + |<ROW> + | <a>" "</a> + | <b>" "<c>1</c></b> + | <d><e attr=" "></e></d> + |</ROW> + |""".stripMargin, + expectedJsonStr = """{"a":"\" \"","b":{"_VALUE":"\" \"","c":1},"d":{"e":{"_attr":" "}}}""", + extraOptions = Map("ignoreSurroundingSpaces" -> "false") + ) + } + + test("Parser: Comments are ignored") { + testParser( + xml = """ + |<ROW> + | <!-- comment --> + | <name><!-- before value --> Sam <!-- after value --></name> + | <!-- comment --> + | <amount>93</amount> + |</ROW> + |""".stripMargin, + expectedJsonStr = """{"amount":93,"name":"Sam"}""" + ) + } + + test("Parser: CDATA should be handled properly") { + testParser( + xml = """ + |<!-- CDATA outside row should be ignored --> + |<ROW> + | <name><![CDATA[Sam]]></name> + | <amount>93</amount> + |</ROW> + |""".stripMargin, + expectedJsonStr = """{"amount":93,"name":"Sam"}""" + ) + } + + test("Parser: parse mixed types as variants") { Review Comment: Do we have a test of a mix of variants types and other data types in a struct (e.g. `a struct<b variant, c log>`)? ########## sql/core/src/test/scala/org/apache/spark/sql/execution/datasources/xml/XmlVariantSuite.scala: ########## @@ -0,0 +1,493 @@ +/* + * 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.execution.datasources.xml + +import java.time.ZoneOffset + +import org.apache.spark.sql.{AnalysisException, DataFrame, QueryTest, Row} +import org.apache.spark.sql.catalyst.xml.{StaxXmlParser, XmlOptions} +import org.apache.spark.sql.functions.{col, variant_get} +import org.apache.spark.sql.internal.SQLConf +import org.apache.spark.sql.test.SharedSparkSession + +class XmlVariantSuite extends QueryTest with SharedSparkSession with TestXmlData { + + private val baseOptions = Map("rowTag" -> "ROW", "valueTag" -> "_VALUE", "attributePrefix" -> "_") + + private val resDir = "test-data/xml-resources/" + + // ========================== + // ====== Parser tests ====== + // ========================== + + private def testParser( + xml: String, + expectedJsonStr: String, + extraOptions: Map[String, String] = Map.empty): Unit = { + val parsed = StaxXmlParser.parseVariant(xml, XmlOptions(baseOptions ++ extraOptions)) + assert(parsed.toJson(ZoneOffset.UTC) == expectedJsonStr) + } + + test("Parser: parse primitive XML elements (long, decimal, double, etc.) as variants") { Review Comment: can we add more tests to ensure that XML options are respected (e.g. prefersDecimal etc.)? ########## sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/xml/StaxXmlParser.scala: ########## @@ -897,4 +914,220 @@ object StaxXmlParser { curRecord } } + + /** + * Parse the input XML string as a Varaint value + */ + def parseVariant(xml: String, options: XmlOptions): VariantVal = { + val parser = StaxXmlParserUtils.filteredReader(xml) + val rootEvent = + StaxXmlParserUtils.skipUntil(parser, XMLStreamConstants.START_ELEMENT) + val rootAttributes = rootEvent.asStartElement.getAttributes.asScala.toArray + val variant = convertVariant(parser, rootAttributes, options) + val v = new VariantVal(variant.getValue, variant.getMetadata) + parser.close() + v + } + + /** + * Parse an XML element from the XML event stream into a Variant. + * This method transforms the XML element along with its attributes and child elements + * into a hierarchical Variant data structure that preserves the XML structure. + * + * @param parser The XML event stream reader positioned after the start element + * @param attributes The attributes of the current XML element to be included in the Variant + * @param options Configuration options that control how XML is parsed into Variants + * @return A Variant representing the XML element with its attributes and child content + */ + def convertVariant( + parser: XMLEventReader, + attributes: Array[Attribute], + options: XmlOptions): Variant = { + // The variant builder for the root startElement + val rootBuilder = new VariantBuilder(false) + val start = rootBuilder.getWritePos + + // Map to store the variant values of all child fields + // Each field could have multiple entries, which means it's an array + val fieldToVariants = collection.mutable.TreeMap.empty[String, java.util.ArrayList[Variant]] + + // Handle attributes first + StaxXmlParserUtils.convertAttributesToValuesMap(attributes, options).foreach { + case (f, v) => + val builder = new VariantBuilder(false) + appendXMLCharacterToVariant(builder, v, options) + addOrUpdateVariantFields(fieldToVariants, f, builder.result()) + } + + var shouldStop = false + while (!shouldStop) { + parser.nextEvent() match { + case s: StartElement => + // For each child element, convert it to a variant and keep track of it in + // fieldsToVariants + val attributes = s.getAttributes.asScala.map(_.asInstanceOf[Attribute]).toArray + val field = StaxXmlParserUtils.getName(s.asStartElement.getName, options) + addOrUpdateVariantFields( + fieldToVariants = fieldToVariants, + field = field, + variant = convertVariant(parser, attributes, options) + ) + + case c: Characters if !c.isWhiteSpace => + // Treat the character as a value tag field, where we use the [[XMLOptions.valueTag]] as + // the field key + val builder = new VariantBuilder(false) + appendXMLCharacterToVariant(builder, c.getData, options) + addOrUpdateVariantFields( + fieldToVariants = fieldToVariants, + field = options.valueTag, + variant = builder.result() + ) + + case _: EndElement => + if (fieldToVariants.nonEmpty) { + val onlyValueTagField = fieldToVariants.keySet.forall(_ == options.valueTag) + if (onlyValueTagField) { + // If the element only has value tag field, parse the element as a variant primitive + rootBuilder.appendVariant(fieldToVariants(options.valueTag).get(0)) + } else { + // Otherwise, build the element as an object with all the fields in fieldToVariants + val rootFieldEntries = new java.util.ArrayList[FieldEntry]() + + fieldToVariants.foreach { + case (field, variants) => + // Add the field key to the variant metadata + val fieldId = rootBuilder.addKey(field) + rootFieldEntries.add( + new FieldEntry(field, fieldId, rootBuilder.getWritePos - start) + ) + + val fieldValue = if (variants.size() > 1) { Review Comment: can we add a test case `<a><b attr="1"></b></a>` for this? -- 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-unsubscr...@spark.apache.org For queries about this service, please contact Infrastructure at: us...@infra.apache.org --------------------------------------------------------------------- To unsubscribe, e-mail: reviews-unsubscr...@spark.apache.org For additional commands, e-mail: reviews-h...@spark.apache.org