You are viewing a plain text version of this content. The canonical link for it is here.
Posted to reviews@spark.apache.org by "ueshin (via GitHub)" <gi...@apache.org> on 2023/03/04 03:01:55 UTC

[GitHub] [spark] ueshin opened a new pull request, #40276: [SPARK-42630][CONNECT][PYTHON] Implement data type string parser

ueshin opened a new pull request, #40276:
URL: https://github.com/apache/spark/pull/40276

   <!--
   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
        'core/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.
   -->
   
   
   ### 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.
   -->
   
   
   ### 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'.
   -->
   
   
   ### 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.
   -->
   


-- 
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


[GitHub] [spark] HyukjinKwon commented on a diff in pull request #40276: [SPARK-42630][CONNECT][PYTHON] Implement data type string parser

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


##########
python/pyspark/sql/connect/types.py:
##########
@@ -342,20 +343,325 @@ def from_arrow_schema(arrow_schema: "pa.Schema") -> StructType:
 
 
 def parse_data_type(data_type: str) -> DataType:
-    # Currently we don't have a way to have a current Spark session in Spark Connect, and
-    # pyspark.sql.SparkSession has a centralized logic to control the session creation.
-    # So uses pyspark.sql.SparkSession for now. Should replace this to using the current
-    # Spark session for Spark Connect in the future.
-    from pyspark.sql import SparkSession as PySparkSession
-
-    assert is_remote()
-    return_type_schema = (
-        PySparkSession.builder.getOrCreate().createDataFrame(data=[], schema=data_type).schema
+    """
+    Parses the given data type string to a :class:`DataType`. The data type string format equals
+    :class:`DataType.simpleString`, except that the top level struct type can omit
+    the ``struct<>``. Since Spark 2.3, this also supports a schema in a DDL-formatted
+    string and case-insensitive strings.
+
+    Examples
+    --------
+    >>> parse_data_type("int ")
+    IntegerType()
+    >>> parse_data_type("INT ")
+    IntegerType()
+    >>> parse_data_type("a: byte, b: decimal(  16 , 8   ) ")
+    StructType([StructField('a', ByteType(), True), StructField('b', DecimalType(16,8), True)])
+    >>> parse_data_type("a DOUBLE, b STRING")
+    StructType([StructField('a', DoubleType(), True), StructField('b', StringType(), True)])
+    >>> parse_data_type("a DOUBLE, b CHAR( 50 )")
+    StructType([StructField('a', DoubleType(), True), StructField('b', CharType(50), True)])
+    >>> parse_data_type("a DOUBLE, b VARCHAR( 50 )")
+    StructType([StructField('a', DoubleType(), True), StructField('b', VarcharType(50), True)])
+    >>> parse_data_type("a: array< short>")
+    StructType([StructField('a', ArrayType(ShortType(), True), True)])
+    >>> parse_data_type(" map<string , string > ")
+    MapType(StringType(), StringType(), True)
+
+    >>> # Error cases
+    >>> parse_data_type("blabla") # doctest: +IGNORE_EXCEPTION_DETAIL
+    Traceback (most recent call last):
+        ...
+    ParseException:...
+    >>> parse_data_type("a: int,") # doctest: +IGNORE_EXCEPTION_DETAIL
+    Traceback (most recent call last):
+        ...
+    ParseException:...
+    >>> parse_data_type("array<int") # doctest: +IGNORE_EXCEPTION_DETAIL
+    Traceback (most recent call last):
+        ...
+    ParseException:...
+    >>> parse_data_type("map<int, boolean>>") # doctest: +IGNORE_EXCEPTION_DETAIL
+    Traceback (most recent call last):
+        ...
+    ParseException:...
+    """
+    try:
+        # DDL format, "fieldname datatype, fieldname datatype".
+        return DDLSchemaParser(data_type).from_ddl_schema()
+    except ParseException as e:
+        try:
+            # For backwards compatibility, "integer", "struct<fieldname: datatype>" and etc.
+            return DDLDataTypeParser(data_type).from_ddl_datatype()
+        except ParseException:
+            try:
+                # For backwards compatibility, "fieldname: datatype, fieldname: datatype" case.
+                return DDLDataTypeParser(f"struct<{data_type}>").from_ddl_datatype()
+            except ParseException:
+                raise e from None
+
+
+class DataTypeParserBase:
+    REGEXP_IDENTIFIER: Final[Pattern] = re.compile("\\w+|`(?:``|[^`])*`", re.MULTILINE)
+    REGEXP_INTEGER_VALUES: Final[Pattern] = re.compile(
+        "\\(\\s*(?:[+-]?\\d+)\\s*(?:,\\s*(?:[+-]?\\d+)\\s*)*\\)", re.MULTILINE
     )
-    with_col_name = " " in data_type.strip()
-    if len(return_type_schema.fields) == 1 and not with_col_name:
-        # To match pyspark.sql.types._parse_datatype_string
-        return_type = return_type_schema.fields[0].dataType
-    else:
-        return_type = return_type_schema
-    return return_type
+    REGEXP_INTERVAL_TYPE: Final[Pattern] = re.compile(
+        "(day|hour|minute|second)(?:\\s+to\\s+(hour|minute|second))?", re.IGNORECASE | re.MULTILINE
+    )
+    REGEXP_NOT_NULL_COMMENT: Final[Pattern] = re.compile(
+        "(not\\s+null)?(?:(?(1)\\s+)comment\\s+'((?:\\\\'|[^'])*)')?", re.IGNORECASE | re.MULTILINE
+    )
+
+    def __init__(self, type_str: str):
+        self._type_str = type_str
+        self._pos = 0
+        self._lstrip()
+
+    def _lstrip(self) -> None:
+        remaining = self._type_str[self._pos :]
+        self._pos = self._pos + (len(remaining) - len(remaining.lstrip()))
+
+    def _parse_data_type(self) -> DataType:
+        type_str = self._type_str[self._pos :]
+        m = self.REGEXP_IDENTIFIER.match(type_str)
+        if m:
+            data_type_name = m.group(0).lower().strip("`").replace("``", "`")
+            self._pos = self._pos + len(m.group(0))
+            self._lstrip()
+            if data_type_name == "array":
+                return self._parse_array_type()
+            elif data_type_name == "map":
+                return self._parse_map_type()
+            elif data_type_name == "struct":
+                return self._parse_struct_type()
+            elif data_type_name == "interval":
+                return self._parse_interval_type()
+            else:
+                return self._parse_primitive_types(data_type_name)
+
+        raise ParseException(
+            error_class="PARSE_SYNTAX_ERROR",
+            message_parameters={"error": f"'{type_str}'", "hint": ""},
+        )
+
+    def _parse_array_type(self) -> ArrayType:
+        type_str = self._type_str[self._pos :]
+        if len(type_str) > 0 and type_str[0] == "<":
+            self._pos = self._pos + 1
+            self._lstrip()
+            element_type = self._parse_data_type()
+            remaining = self._type_str[self._pos :]
+            if len(remaining) and remaining[0] == ">":
+                self._pos = self._pos + 1
+                self._lstrip()
+                return ArrayType(element_type)
+        raise ParseException(error_class="INCOMPLETE_TYPE_DEFINITION.ARRAY", message_parameters={})
+
+    def _parse_map_type(self) -> MapType:
+        type_str = self._type_str[self._pos :]
+        if len(type_str) > 0 and type_str[0] == "<":
+            self._pos = self._pos + 1
+            self._lstrip()
+            key_type = self._parse_data_type()
+            remaining = self._type_str[self._pos :]
+            if len(remaining) > 0 and remaining[0] == ",":
+                self._pos = self._pos + 1
+                self._lstrip()
+                value_type = self._parse_data_type()
+                remaining = self._type_str[self._pos :]
+                if len(remaining) > 0 and remaining[0] == ">":
+                    self._pos = self._pos + 1
+                    self._lstrip()
+                    return MapType(key_type, value_type)
+        raise ParseException(error_class="INCOMPLETE_TYPE_DEFINITION.MAP", message_parameters={})
+
+    def _parse_struct_type(self) -> StructType:
+        type_str = self._type_str[self._pos :]
+        if len(type_str) > 0 and type_str[0] == "<":
+            self._pos = self._pos + 1
+            self._lstrip()
+            fields = self._parse_struct_fields()
+            remaining = self._type_str[self._pos :]
+            if len(remaining) > 0 and remaining[0] == ">":
+                self._pos = self._pos + 1
+                self._lstrip()
+                return StructType(fields)
+        raise ParseException(error_class="INCOMPLETE_TYPE_DEFINITION.STRUCT", message_parameters={})
+
+    def _parse_struct_fields(self, sep_with_colon: bool = True) -> List[StructField]:
+        type_str = self._type_str[self._pos :]
+        m = self.REGEXP_IDENTIFIER.match(type_str)
+        if m:
+            field_name = m.group(0).lower().strip("`").replace("``", "`")

Review Comment:
   Couple of concerns..
   
   I still doubt if this is something we should manually implement. I think there'd be many cases we miss ... for example, what about case sensitivity .. Also, to do this properly, we should use antlr for Python (e.g., https://github.com/antlr/antlr4/blob/master/doc/python-target.md). But I feel that's sort of overkill.
   
   We don't have new types very often but it's not very rare either. For example, in the last couple of years, we added ANSI types, date, year, month interval, timestamp without timzone, etc. We also expose the char and varchar type that was hidden before.



##########
python/pyspark/sql/connect/types.py:
##########
@@ -342,20 +343,325 @@ def from_arrow_schema(arrow_schema: "pa.Schema") -> StructType:
 
 
 def parse_data_type(data_type: str) -> DataType:
-    # Currently we don't have a way to have a current Spark session in Spark Connect, and
-    # pyspark.sql.SparkSession has a centralized logic to control the session creation.
-    # So uses pyspark.sql.SparkSession for now. Should replace this to using the current
-    # Spark session for Spark Connect in the future.
-    from pyspark.sql import SparkSession as PySparkSession
-
-    assert is_remote()
-    return_type_schema = (
-        PySparkSession.builder.getOrCreate().createDataFrame(data=[], schema=data_type).schema
+    """
+    Parses the given data type string to a :class:`DataType`. The data type string format equals
+    :class:`DataType.simpleString`, except that the top level struct type can omit
+    the ``struct<>``. Since Spark 2.3, this also supports a schema in a DDL-formatted
+    string and case-insensitive strings.
+
+    Examples
+    --------
+    >>> parse_data_type("int ")
+    IntegerType()
+    >>> parse_data_type("INT ")
+    IntegerType()
+    >>> parse_data_type("a: byte, b: decimal(  16 , 8   ) ")
+    StructType([StructField('a', ByteType(), True), StructField('b', DecimalType(16,8), True)])
+    >>> parse_data_type("a DOUBLE, b STRING")
+    StructType([StructField('a', DoubleType(), True), StructField('b', StringType(), True)])
+    >>> parse_data_type("a DOUBLE, b CHAR( 50 )")
+    StructType([StructField('a', DoubleType(), True), StructField('b', CharType(50), True)])
+    >>> parse_data_type("a DOUBLE, b VARCHAR( 50 )")
+    StructType([StructField('a', DoubleType(), True), StructField('b', VarcharType(50), True)])
+    >>> parse_data_type("a: array< short>")
+    StructType([StructField('a', ArrayType(ShortType(), True), True)])
+    >>> parse_data_type(" map<string , string > ")
+    MapType(StringType(), StringType(), True)
+
+    >>> # Error cases
+    >>> parse_data_type("blabla") # doctest: +IGNORE_EXCEPTION_DETAIL
+    Traceback (most recent call last):
+        ...
+    ParseException:...
+    >>> parse_data_type("a: int,") # doctest: +IGNORE_EXCEPTION_DETAIL
+    Traceback (most recent call last):
+        ...
+    ParseException:...
+    >>> parse_data_type("array<int") # doctest: +IGNORE_EXCEPTION_DETAIL
+    Traceback (most recent call last):
+        ...
+    ParseException:...
+    >>> parse_data_type("map<int, boolean>>") # doctest: +IGNORE_EXCEPTION_DETAIL
+    Traceback (most recent call last):
+        ...
+    ParseException:...
+    """
+    try:
+        # DDL format, "fieldname datatype, fieldname datatype".
+        return DDLSchemaParser(data_type).from_ddl_schema()
+    except ParseException as e:
+        try:
+            # For backwards compatibility, "integer", "struct<fieldname: datatype>" and etc.
+            return DDLDataTypeParser(data_type).from_ddl_datatype()
+        except ParseException:
+            try:
+                # For backwards compatibility, "fieldname: datatype, fieldname: datatype" case.
+                return DDLDataTypeParser(f"struct<{data_type}>").from_ddl_datatype()
+            except ParseException:
+                raise e from None
+
+
+class DataTypeParserBase:
+    REGEXP_IDENTIFIER: Final[Pattern] = re.compile("\\w+|`(?:``|[^`])*`", re.MULTILINE)
+    REGEXP_INTEGER_VALUES: Final[Pattern] = re.compile(
+        "\\(\\s*(?:[+-]?\\d+)\\s*(?:,\\s*(?:[+-]?\\d+)\\s*)*\\)", re.MULTILINE
     )
-    with_col_name = " " in data_type.strip()
-    if len(return_type_schema.fields) == 1 and not with_col_name:
-        # To match pyspark.sql.types._parse_datatype_string
-        return_type = return_type_schema.fields[0].dataType
-    else:
-        return_type = return_type_schema
-    return return_type
+    REGEXP_INTERVAL_TYPE: Final[Pattern] = re.compile(
+        "(day|hour|minute|second)(?:\\s+to\\s+(hour|minute|second))?", re.IGNORECASE | re.MULTILINE
+    )
+    REGEXP_NOT_NULL_COMMENT: Final[Pattern] = re.compile(
+        "(not\\s+null)?(?:(?(1)\\s+)comment\\s+'((?:\\\\'|[^'])*)')?", re.IGNORECASE | re.MULTILINE
+    )
+
+    def __init__(self, type_str: str):
+        self._type_str = type_str
+        self._pos = 0
+        self._lstrip()
+
+    def _lstrip(self) -> None:
+        remaining = self._type_str[self._pos :]
+        self._pos = self._pos + (len(remaining) - len(remaining.lstrip()))
+
+    def _parse_data_type(self) -> DataType:
+        type_str = self._type_str[self._pos :]
+        m = self.REGEXP_IDENTIFIER.match(type_str)
+        if m:
+            data_type_name = m.group(0).lower().strip("`").replace("``", "`")
+            self._pos = self._pos + len(m.group(0))
+            self._lstrip()
+            if data_type_name == "array":
+                return self._parse_array_type()
+            elif data_type_name == "map":
+                return self._parse_map_type()
+            elif data_type_name == "struct":
+                return self._parse_struct_type()
+            elif data_type_name == "interval":
+                return self._parse_interval_type()
+            else:
+                return self._parse_primitive_types(data_type_name)
+
+        raise ParseException(
+            error_class="PARSE_SYNTAX_ERROR",
+            message_parameters={"error": f"'{type_str}'", "hint": ""},
+        )
+
+    def _parse_array_type(self) -> ArrayType:
+        type_str = self._type_str[self._pos :]
+        if len(type_str) > 0 and type_str[0] == "<":
+            self._pos = self._pos + 1
+            self._lstrip()
+            element_type = self._parse_data_type()
+            remaining = self._type_str[self._pos :]
+            if len(remaining) and remaining[0] == ">":
+                self._pos = self._pos + 1
+                self._lstrip()
+                return ArrayType(element_type)
+        raise ParseException(error_class="INCOMPLETE_TYPE_DEFINITION.ARRAY", message_parameters={})
+
+    def _parse_map_type(self) -> MapType:
+        type_str = self._type_str[self._pos :]
+        if len(type_str) > 0 and type_str[0] == "<":
+            self._pos = self._pos + 1
+            self._lstrip()
+            key_type = self._parse_data_type()
+            remaining = self._type_str[self._pos :]
+            if len(remaining) > 0 and remaining[0] == ",":
+                self._pos = self._pos + 1
+                self._lstrip()
+                value_type = self._parse_data_type()
+                remaining = self._type_str[self._pos :]
+                if len(remaining) > 0 and remaining[0] == ">":
+                    self._pos = self._pos + 1
+                    self._lstrip()
+                    return MapType(key_type, value_type)
+        raise ParseException(error_class="INCOMPLETE_TYPE_DEFINITION.MAP", message_parameters={})
+
+    def _parse_struct_type(self) -> StructType:
+        type_str = self._type_str[self._pos :]
+        if len(type_str) > 0 and type_str[0] == "<":
+            self._pos = self._pos + 1
+            self._lstrip()
+            fields = self._parse_struct_fields()
+            remaining = self._type_str[self._pos :]
+            if len(remaining) > 0 and remaining[0] == ">":
+                self._pos = self._pos + 1
+                self._lstrip()
+                return StructType(fields)
+        raise ParseException(error_class="INCOMPLETE_TYPE_DEFINITION.STRUCT", message_parameters={})
+
+    def _parse_struct_fields(self, sep_with_colon: bool = True) -> List[StructField]:
+        type_str = self._type_str[self._pos :]
+        m = self.REGEXP_IDENTIFIER.match(type_str)
+        if m:
+            field_name = m.group(0).lower().strip("`").replace("``", "`")

Review Comment:
   Couple of concerns..
   
   I still doubt if this is something we should manually implement. I think there'd be many cases we miss ... for example, what about case sensitivity .. Also, to do this properly, we should use antlr for Python (e.g., https://github.com/antlr/antlr4/blob/master/doc/python-target.md). But I feel that's sort of overkill.
   
   We don't have new types very often but it's not very rare either. For example, in the last couple of years, we added ANSI types, date, year, month interval, timestamp without timzone, etc. We also exposed the char and varchar type that was hidden before.



-- 
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


[GitHub] [spark] cloud-fan commented on pull request #40276: [SPARK-42630][CONNECT][PYTHON] Implement data type string parser

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

   does it mean every spark connect client must implement a data type parser in its language? This seems a bit overkill. Can we revisit all the places that need to parse data type at client side, and see if we can delay it to the server side?


-- 
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


[GitHub] [spark] ueshin closed pull request #40276: [SPARK-42630][CONNECT][PYTHON] Implement data type string parser

Posted by "ueshin (via GitHub)" <gi...@apache.org>.
ueshin closed pull request #40276: [SPARK-42630][CONNECT][PYTHON] Implement data type string parser
URL: https://github.com/apache/spark/pull/40276


-- 
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


[GitHub] [spark] ueshin commented on pull request #40276: [SPARK-42630][CONNECT][PYTHON] Implement data type string parser

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

   Close this in favor of #40260.


-- 
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


[GitHub] [spark] HyukjinKwon commented on a diff in pull request #40276: [SPARK-42630][CONNECT][PYTHON] Implement data type string parser

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


##########
python/pyspark/sql/connect/types.py:
##########
@@ -342,20 +343,325 @@ def from_arrow_schema(arrow_schema: "pa.Schema") -> StructType:
 
 
 def parse_data_type(data_type: str) -> DataType:
-    # Currently we don't have a way to have a current Spark session in Spark Connect, and
-    # pyspark.sql.SparkSession has a centralized logic to control the session creation.
-    # So uses pyspark.sql.SparkSession for now. Should replace this to using the current
-    # Spark session for Spark Connect in the future.
-    from pyspark.sql import SparkSession as PySparkSession
-
-    assert is_remote()
-    return_type_schema = (
-        PySparkSession.builder.getOrCreate().createDataFrame(data=[], schema=data_type).schema
+    """
+    Parses the given data type string to a :class:`DataType`. The data type string format equals
+    :class:`DataType.simpleString`, except that the top level struct type can omit
+    the ``struct<>``. Since Spark 2.3, this also supports a schema in a DDL-formatted
+    string and case-insensitive strings.
+
+    Examples
+    --------
+    >>> parse_data_type("int ")
+    IntegerType()
+    >>> parse_data_type("INT ")
+    IntegerType()
+    >>> parse_data_type("a: byte, b: decimal(  16 , 8   ) ")
+    StructType([StructField('a', ByteType(), True), StructField('b', DecimalType(16,8), True)])
+    >>> parse_data_type("a DOUBLE, b STRING")
+    StructType([StructField('a', DoubleType(), True), StructField('b', StringType(), True)])
+    >>> parse_data_type("a DOUBLE, b CHAR( 50 )")
+    StructType([StructField('a', DoubleType(), True), StructField('b', CharType(50), True)])
+    >>> parse_data_type("a DOUBLE, b VARCHAR( 50 )")
+    StructType([StructField('a', DoubleType(), True), StructField('b', VarcharType(50), True)])
+    >>> parse_data_type("a: array< short>")
+    StructType([StructField('a', ArrayType(ShortType(), True), True)])
+    >>> parse_data_type(" map<string , string > ")
+    MapType(StringType(), StringType(), True)
+
+    >>> # Error cases
+    >>> parse_data_type("blabla") # doctest: +IGNORE_EXCEPTION_DETAIL
+    Traceback (most recent call last):
+        ...
+    ParseException:...
+    >>> parse_data_type("a: int,") # doctest: +IGNORE_EXCEPTION_DETAIL
+    Traceback (most recent call last):
+        ...
+    ParseException:...
+    >>> parse_data_type("array<int") # doctest: +IGNORE_EXCEPTION_DETAIL
+    Traceback (most recent call last):
+        ...
+    ParseException:...
+    >>> parse_data_type("map<int, boolean>>") # doctest: +IGNORE_EXCEPTION_DETAIL
+    Traceback (most recent call last):
+        ...
+    ParseException:...
+    """
+    try:
+        # DDL format, "fieldname datatype, fieldname datatype".
+        return DDLSchemaParser(data_type).from_ddl_schema()
+    except ParseException as e:
+        try:
+            # For backwards compatibility, "integer", "struct<fieldname: datatype>" and etc.
+            return DDLDataTypeParser(data_type).from_ddl_datatype()
+        except ParseException:
+            try:
+                # For backwards compatibility, "fieldname: datatype, fieldname: datatype" case.
+                return DDLDataTypeParser(f"struct<{data_type}>").from_ddl_datatype()
+            except ParseException:
+                raise e from None
+
+
+class DataTypeParserBase:
+    REGEXP_IDENTIFIER: Final[Pattern] = re.compile("\\w+|`(?:``|[^`])*`", re.MULTILINE)
+    REGEXP_INTEGER_VALUES: Final[Pattern] = re.compile(
+        "\\(\\s*(?:[+-]?\\d+)\\s*(?:,\\s*(?:[+-]?\\d+)\\s*)*\\)", re.MULTILINE
     )
-    with_col_name = " " in data_type.strip()
-    if len(return_type_schema.fields) == 1 and not with_col_name:
-        # To match pyspark.sql.types._parse_datatype_string
-        return_type = return_type_schema.fields[0].dataType
-    else:
-        return_type = return_type_schema
-    return return_type
+    REGEXP_INTERVAL_TYPE: Final[Pattern] = re.compile(
+        "(day|hour|minute|second)(?:\\s+to\\s+(hour|minute|second))?", re.IGNORECASE | re.MULTILINE
+    )
+    REGEXP_NOT_NULL_COMMENT: Final[Pattern] = re.compile(
+        "(not\\s+null)?(?:(?(1)\\s+)comment\\s+'((?:\\\\'|[^'])*)')?", re.IGNORECASE | re.MULTILINE
+    )
+
+    def __init__(self, type_str: str):
+        self._type_str = type_str
+        self._pos = 0
+        self._lstrip()
+
+    def _lstrip(self) -> None:
+        remaining = self._type_str[self._pos :]
+        self._pos = self._pos + (len(remaining) - len(remaining.lstrip()))
+
+    def _parse_data_type(self) -> DataType:
+        type_str = self._type_str[self._pos :]
+        m = self.REGEXP_IDENTIFIER.match(type_str)
+        if m:
+            data_type_name = m.group(0).lower().strip("`").replace("``", "`")
+            self._pos = self._pos + len(m.group(0))
+            self._lstrip()
+            if data_type_name == "array":
+                return self._parse_array_type()
+            elif data_type_name == "map":
+                return self._parse_map_type()
+            elif data_type_name == "struct":
+                return self._parse_struct_type()
+            elif data_type_name == "interval":
+                return self._parse_interval_type()
+            else:
+                return self._parse_primitive_types(data_type_name)
+
+        raise ParseException(
+            error_class="PARSE_SYNTAX_ERROR",
+            message_parameters={"error": f"'{type_str}'", "hint": ""},
+        )
+
+    def _parse_array_type(self) -> ArrayType:
+        type_str = self._type_str[self._pos :]
+        if len(type_str) > 0 and type_str[0] == "<":
+            self._pos = self._pos + 1
+            self._lstrip()
+            element_type = self._parse_data_type()
+            remaining = self._type_str[self._pos :]
+            if len(remaining) and remaining[0] == ">":
+                self._pos = self._pos + 1
+                self._lstrip()
+                return ArrayType(element_type)
+        raise ParseException(error_class="INCOMPLETE_TYPE_DEFINITION.ARRAY", message_parameters={})
+
+    def _parse_map_type(self) -> MapType:
+        type_str = self._type_str[self._pos :]
+        if len(type_str) > 0 and type_str[0] == "<":
+            self._pos = self._pos + 1
+            self._lstrip()
+            key_type = self._parse_data_type()
+            remaining = self._type_str[self._pos :]
+            if len(remaining) > 0 and remaining[0] == ",":
+                self._pos = self._pos + 1
+                self._lstrip()
+                value_type = self._parse_data_type()
+                remaining = self._type_str[self._pos :]
+                if len(remaining) > 0 and remaining[0] == ">":
+                    self._pos = self._pos + 1
+                    self._lstrip()
+                    return MapType(key_type, value_type)
+        raise ParseException(error_class="INCOMPLETE_TYPE_DEFINITION.MAP", message_parameters={})
+
+    def _parse_struct_type(self) -> StructType:
+        type_str = self._type_str[self._pos :]
+        if len(type_str) > 0 and type_str[0] == "<":
+            self._pos = self._pos + 1
+            self._lstrip()
+            fields = self._parse_struct_fields()
+            remaining = self._type_str[self._pos :]
+            if len(remaining) > 0 and remaining[0] == ">":
+                self._pos = self._pos + 1
+                self._lstrip()
+                return StructType(fields)
+        raise ParseException(error_class="INCOMPLETE_TYPE_DEFINITION.STRUCT", message_parameters={})
+
+    def _parse_struct_fields(self, sep_with_colon: bool = True) -> List[StructField]:
+        type_str = self._type_str[self._pos :]
+        m = self.REGEXP_IDENTIFIER.match(type_str)
+        if m:
+            field_name = m.group(0).lower().strip("`").replace("``", "`")

Review Comment:
   I still doubt if this is something we should manually implement ... for example, what about case sensitivity .. To do this properly, we should use antlr for Python (e.g., https://github.com/antlr/antlr4/blob/master/doc/python-target.md).
   
   We don't have new types very often but still we add. For example, in the last couple of years, we added ANSI types, date, year, month interval, timestamp without timzone, etc. We also expose the char and varchar type that was hidden before.



-- 
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


[GitHub] [spark] HyukjinKwon commented on a diff in pull request #40276: [SPARK-42630][CONNECT][PYTHON] Implement data type string parser

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


##########
python/pyspark/sql/connect/types.py:
##########
@@ -342,20 +343,325 @@ def from_arrow_schema(arrow_schema: "pa.Schema") -> StructType:
 
 
 def parse_data_type(data_type: str) -> DataType:
-    # Currently we don't have a way to have a current Spark session in Spark Connect, and
-    # pyspark.sql.SparkSession has a centralized logic to control the session creation.
-    # So uses pyspark.sql.SparkSession for now. Should replace this to using the current
-    # Spark session for Spark Connect in the future.
-    from pyspark.sql import SparkSession as PySparkSession
-
-    assert is_remote()
-    return_type_schema = (
-        PySparkSession.builder.getOrCreate().createDataFrame(data=[], schema=data_type).schema
+    """
+    Parses the given data type string to a :class:`DataType`. The data type string format equals
+    :class:`DataType.simpleString`, except that the top level struct type can omit
+    the ``struct<>``. Since Spark 2.3, this also supports a schema in a DDL-formatted
+    string and case-insensitive strings.
+
+    Examples
+    --------
+    >>> parse_data_type("int ")
+    IntegerType()
+    >>> parse_data_type("INT ")
+    IntegerType()
+    >>> parse_data_type("a: byte, b: decimal(  16 , 8   ) ")
+    StructType([StructField('a', ByteType(), True), StructField('b', DecimalType(16,8), True)])
+    >>> parse_data_type("a DOUBLE, b STRING")
+    StructType([StructField('a', DoubleType(), True), StructField('b', StringType(), True)])
+    >>> parse_data_type("a DOUBLE, b CHAR( 50 )")
+    StructType([StructField('a', DoubleType(), True), StructField('b', CharType(50), True)])
+    >>> parse_data_type("a DOUBLE, b VARCHAR( 50 )")
+    StructType([StructField('a', DoubleType(), True), StructField('b', VarcharType(50), True)])
+    >>> parse_data_type("a: array< short>")
+    StructType([StructField('a', ArrayType(ShortType(), True), True)])
+    >>> parse_data_type(" map<string , string > ")
+    MapType(StringType(), StringType(), True)
+
+    >>> # Error cases
+    >>> parse_data_type("blabla") # doctest: +IGNORE_EXCEPTION_DETAIL
+    Traceback (most recent call last):
+        ...
+    ParseException:...
+    >>> parse_data_type("a: int,") # doctest: +IGNORE_EXCEPTION_DETAIL
+    Traceback (most recent call last):
+        ...
+    ParseException:...
+    >>> parse_data_type("array<int") # doctest: +IGNORE_EXCEPTION_DETAIL
+    Traceback (most recent call last):
+        ...
+    ParseException:...
+    >>> parse_data_type("map<int, boolean>>") # doctest: +IGNORE_EXCEPTION_DETAIL
+    Traceback (most recent call last):
+        ...
+    ParseException:...
+    """
+    try:
+        # DDL format, "fieldname datatype, fieldname datatype".
+        return DDLSchemaParser(data_type).from_ddl_schema()
+    except ParseException as e:
+        try:
+            # For backwards compatibility, "integer", "struct<fieldname: datatype>" and etc.
+            return DDLDataTypeParser(data_type).from_ddl_datatype()
+        except ParseException:
+            try:
+                # For backwards compatibility, "fieldname: datatype, fieldname: datatype" case.
+                return DDLDataTypeParser(f"struct<{data_type}>").from_ddl_datatype()
+            except ParseException:
+                raise e from None
+
+
+class DataTypeParserBase:
+    REGEXP_IDENTIFIER: Final[Pattern] = re.compile("\\w+|`(?:``|[^`])*`", re.MULTILINE)
+    REGEXP_INTEGER_VALUES: Final[Pattern] = re.compile(
+        "\\(\\s*(?:[+-]?\\d+)\\s*(?:,\\s*(?:[+-]?\\d+)\\s*)*\\)", re.MULTILINE
     )
-    with_col_name = " " in data_type.strip()
-    if len(return_type_schema.fields) == 1 and not with_col_name:
-        # To match pyspark.sql.types._parse_datatype_string
-        return_type = return_type_schema.fields[0].dataType
-    else:
-        return_type = return_type_schema
-    return return_type
+    REGEXP_INTERVAL_TYPE: Final[Pattern] = re.compile(
+        "(day|hour|minute|second)(?:\\s+to\\s+(hour|minute|second))?", re.IGNORECASE | re.MULTILINE
+    )
+    REGEXP_NOT_NULL_COMMENT: Final[Pattern] = re.compile(
+        "(not\\s+null)?(?:(?(1)\\s+)comment\\s+'((?:\\\\'|[^'])*)')?", re.IGNORECASE | re.MULTILINE
+    )
+
+    def __init__(self, type_str: str):
+        self._type_str = type_str
+        self._pos = 0
+        self._lstrip()
+
+    def _lstrip(self) -> None:
+        remaining = self._type_str[self._pos :]
+        self._pos = self._pos + (len(remaining) - len(remaining.lstrip()))
+
+    def _parse_data_type(self) -> DataType:
+        type_str = self._type_str[self._pos :]
+        m = self.REGEXP_IDENTIFIER.match(type_str)
+        if m:
+            data_type_name = m.group(0).lower().strip("`").replace("``", "`")
+            self._pos = self._pos + len(m.group(0))
+            self._lstrip()
+            if data_type_name == "array":
+                return self._parse_array_type()
+            elif data_type_name == "map":
+                return self._parse_map_type()
+            elif data_type_name == "struct":
+                return self._parse_struct_type()
+            elif data_type_name == "interval":
+                return self._parse_interval_type()
+            else:
+                return self._parse_primitive_types(data_type_name)
+
+        raise ParseException(
+            error_class="PARSE_SYNTAX_ERROR",
+            message_parameters={"error": f"'{type_str}'", "hint": ""},
+        )
+
+    def _parse_array_type(self) -> ArrayType:
+        type_str = self._type_str[self._pos :]
+        if len(type_str) > 0 and type_str[0] == "<":
+            self._pos = self._pos + 1
+            self._lstrip()
+            element_type = self._parse_data_type()
+            remaining = self._type_str[self._pos :]
+            if len(remaining) and remaining[0] == ">":
+                self._pos = self._pos + 1
+                self._lstrip()
+                return ArrayType(element_type)
+        raise ParseException(error_class="INCOMPLETE_TYPE_DEFINITION.ARRAY", message_parameters={})
+
+    def _parse_map_type(self) -> MapType:
+        type_str = self._type_str[self._pos :]
+        if len(type_str) > 0 and type_str[0] == "<":
+            self._pos = self._pos + 1
+            self._lstrip()
+            key_type = self._parse_data_type()
+            remaining = self._type_str[self._pos :]
+            if len(remaining) > 0 and remaining[0] == ",":
+                self._pos = self._pos + 1
+                self._lstrip()
+                value_type = self._parse_data_type()
+                remaining = self._type_str[self._pos :]
+                if len(remaining) > 0 and remaining[0] == ">":
+                    self._pos = self._pos + 1
+                    self._lstrip()
+                    return MapType(key_type, value_type)
+        raise ParseException(error_class="INCOMPLETE_TYPE_DEFINITION.MAP", message_parameters={})
+
+    def _parse_struct_type(self) -> StructType:
+        type_str = self._type_str[self._pos :]
+        if len(type_str) > 0 and type_str[0] == "<":
+            self._pos = self._pos + 1
+            self._lstrip()
+            fields = self._parse_struct_fields()
+            remaining = self._type_str[self._pos :]
+            if len(remaining) > 0 and remaining[0] == ">":
+                self._pos = self._pos + 1
+                self._lstrip()
+                return StructType(fields)
+        raise ParseException(error_class="INCOMPLETE_TYPE_DEFINITION.STRUCT", message_parameters={})
+
+    def _parse_struct_fields(self, sep_with_colon: bool = True) -> List[StructField]:
+        type_str = self._type_str[self._pos :]
+        m = self.REGEXP_IDENTIFIER.match(type_str)
+        if m:
+            field_name = m.group(0).lower().strip("`").replace("``", "`")

Review Comment:
   Couple of concerns..
   
   I still doubt if this is something we should manually implement. I think there'd be many cases we miss ... for example, what about case sensitivity .. Also, to do this properly, we should use antlr for Python (e.g., https://github.com/antlr/antlr4/blob/master/doc/python-target.md). But I feel that's sort of overkill.
   
   We don't have new types very often but still we add. For example, in the last couple of years, we added ANSI types, date, year, month interval, timestamp without timzone, etc. We also expose the char and varchar type that was hidden before.



-- 
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


[GitHub] [spark] ueshin commented on a diff in pull request #40276: [SPARK-42630][CONNECT][PYTHON] Implement data type string parser

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


##########
python/pyspark/sql/connect/types.py:
##########
@@ -342,20 +343,325 @@ def from_arrow_schema(arrow_schema: "pa.Schema") -> StructType:
 
 
 def parse_data_type(data_type: str) -> DataType:
-    # Currently we don't have a way to have a current Spark session in Spark Connect, and
-    # pyspark.sql.SparkSession has a centralized logic to control the session creation.
-    # So uses pyspark.sql.SparkSession for now. Should replace this to using the current
-    # Spark session for Spark Connect in the future.
-    from pyspark.sql import SparkSession as PySparkSession
-
-    assert is_remote()
-    return_type_schema = (
-        PySparkSession.builder.getOrCreate().createDataFrame(data=[], schema=data_type).schema
+    """
+    Parses the given data type string to a :class:`DataType`. The data type string format equals
+    :class:`DataType.simpleString`, except that the top level struct type can omit
+    the ``struct<>``. Since Spark 2.3, this also supports a schema in a DDL-formatted
+    string and case-insensitive strings.
+
+    Examples
+    --------
+    >>> parse_data_type("int ")
+    IntegerType()
+    >>> parse_data_type("INT ")
+    IntegerType()
+    >>> parse_data_type("a: byte, b: decimal(  16 , 8   ) ")
+    StructType([StructField('a', ByteType(), True), StructField('b', DecimalType(16,8), True)])
+    >>> parse_data_type("a DOUBLE, b STRING")
+    StructType([StructField('a', DoubleType(), True), StructField('b', StringType(), True)])
+    >>> parse_data_type("a DOUBLE, b CHAR( 50 )")
+    StructType([StructField('a', DoubleType(), True), StructField('b', CharType(50), True)])
+    >>> parse_data_type("a DOUBLE, b VARCHAR( 50 )")
+    StructType([StructField('a', DoubleType(), True), StructField('b', VarcharType(50), True)])
+    >>> parse_data_type("a: array< short>")
+    StructType([StructField('a', ArrayType(ShortType(), True), True)])
+    >>> parse_data_type(" map<string , string > ")
+    MapType(StringType(), StringType(), True)
+
+    >>> # Error cases
+    >>> parse_data_type("blabla") # doctest: +IGNORE_EXCEPTION_DETAIL
+    Traceback (most recent call last):
+        ...
+    ParseException:...
+    >>> parse_data_type("a: int,") # doctest: +IGNORE_EXCEPTION_DETAIL
+    Traceback (most recent call last):
+        ...
+    ParseException:...
+    >>> parse_data_type("array<int") # doctest: +IGNORE_EXCEPTION_DETAIL
+    Traceback (most recent call last):
+        ...
+    ParseException:...
+    >>> parse_data_type("map<int, boolean>>") # doctest: +IGNORE_EXCEPTION_DETAIL
+    Traceback (most recent call last):
+        ...
+    ParseException:...
+    """
+    try:
+        # DDL format, "fieldname datatype, fieldname datatype".
+        return DDLSchemaParser(data_type).from_ddl_schema()
+    except ParseException as e:
+        try:
+            # For backwards compatibility, "integer", "struct<fieldname: datatype>" and etc.
+            return DDLDataTypeParser(data_type).from_ddl_datatype()
+        except ParseException:
+            try:
+                # For backwards compatibility, "fieldname: datatype, fieldname: datatype" case.
+                return DDLDataTypeParser(f"struct<{data_type}>").from_ddl_datatype()
+            except ParseException:
+                raise e from None
+
+
+class DataTypeParserBase:
+    REGEXP_IDENTIFIER: Final[Pattern] = re.compile("\\w+|`(?:``|[^`])*`", re.MULTILINE)
+    REGEXP_INTEGER_VALUES: Final[Pattern] = re.compile(
+        "\\(\\s*(?:[+-]?\\d+)\\s*(?:,\\s*(?:[+-]?\\d+)\\s*)*\\)", re.MULTILINE
     )
-    with_col_name = " " in data_type.strip()
-    if len(return_type_schema.fields) == 1 and not with_col_name:
-        # To match pyspark.sql.types._parse_datatype_string
-        return_type = return_type_schema.fields[0].dataType
-    else:
-        return_type = return_type_schema
-    return return_type
+    REGEXP_INTERVAL_TYPE: Final[Pattern] = re.compile(
+        "(day|hour|minute|second)(?:\\s+to\\s+(hour|minute|second))?", re.IGNORECASE | re.MULTILINE
+    )
+    REGEXP_NOT_NULL_COMMENT: Final[Pattern] = re.compile(
+        "(not\\s+null)?(?:(?(1)\\s+)comment\\s+'((?:\\\\'|[^'])*)')?", re.IGNORECASE | re.MULTILINE
+    )
+
+    def __init__(self, type_str: str):
+        self._type_str = type_str
+        self._pos = 0
+        self._lstrip()
+
+    def _lstrip(self) -> None:
+        remaining = self._type_str[self._pos :]
+        self._pos = self._pos + (len(remaining) - len(remaining.lstrip()))
+
+    def _parse_data_type(self) -> DataType:
+        type_str = self._type_str[self._pos :]
+        m = self.REGEXP_IDENTIFIER.match(type_str)
+        if m:
+            data_type_name = m.group(0).lower().strip("`").replace("``", "`")
+            self._pos = self._pos + len(m.group(0))
+            self._lstrip()
+            if data_type_name == "array":
+                return self._parse_array_type()
+            elif data_type_name == "map":
+                return self._parse_map_type()
+            elif data_type_name == "struct":
+                return self._parse_struct_type()
+            elif data_type_name == "interval":
+                return self._parse_interval_type()
+            else:
+                return self._parse_primitive_types(data_type_name)
+
+        raise ParseException(
+            error_class="PARSE_SYNTAX_ERROR",
+            message_parameters={"error": f"'{type_str}'", "hint": ""},
+        )
+
+    def _parse_array_type(self) -> ArrayType:
+        type_str = self._type_str[self._pos :]
+        if len(type_str) > 0 and type_str[0] == "<":
+            self._pos = self._pos + 1
+            self._lstrip()
+            element_type = self._parse_data_type()
+            remaining = self._type_str[self._pos :]
+            if len(remaining) and remaining[0] == ">":
+                self._pos = self._pos + 1
+                self._lstrip()
+                return ArrayType(element_type)
+        raise ParseException(error_class="INCOMPLETE_TYPE_DEFINITION.ARRAY", message_parameters={})
+
+    def _parse_map_type(self) -> MapType:
+        type_str = self._type_str[self._pos :]
+        if len(type_str) > 0 and type_str[0] == "<":
+            self._pos = self._pos + 1
+            self._lstrip()
+            key_type = self._parse_data_type()
+            remaining = self._type_str[self._pos :]
+            if len(remaining) > 0 and remaining[0] == ",":
+                self._pos = self._pos + 1
+                self._lstrip()
+                value_type = self._parse_data_type()
+                remaining = self._type_str[self._pos :]
+                if len(remaining) > 0 and remaining[0] == ">":
+                    self._pos = self._pos + 1
+                    self._lstrip()
+                    return MapType(key_type, value_type)
+        raise ParseException(error_class="INCOMPLETE_TYPE_DEFINITION.MAP", message_parameters={})
+
+    def _parse_struct_type(self) -> StructType:
+        type_str = self._type_str[self._pos :]
+        if len(type_str) > 0 and type_str[0] == "<":
+            self._pos = self._pos + 1
+            self._lstrip()
+            fields = self._parse_struct_fields()
+            remaining = self._type_str[self._pos :]
+            if len(remaining) > 0 and remaining[0] == ">":
+                self._pos = self._pos + 1
+                self._lstrip()
+                return StructType(fields)
+        raise ParseException(error_class="INCOMPLETE_TYPE_DEFINITION.STRUCT", message_parameters={})
+
+    def _parse_struct_fields(self, sep_with_colon: bool = True) -> List[StructField]:
+        type_str = self._type_str[self._pos :]
+        m = self.REGEXP_IDENTIFIER.match(type_str)
+        if m:
+            field_name = m.group(0).lower().strip("`").replace("``", "`")

Review Comment:
   Now that it supports `NOT NULL` or `COMMENT`, actually this still needs to check a config:
   
   https://github.com/apache/spark/blob/f9c8a246ecc34ef4bb93c319c7c9b6ff732c962e/python/pyspark/sql/connect/types.py#L574-L575
   
   In Scala, it checks `spark.sql.timestampType` whether is should be `TimestampType` or `TimestampNTZType`:
   
   https://github.com/apache/spark/blob/f9c8a246ecc34ef4bb93c319c7c9b6ff732c962e/sql/catalyst/src/main/scala/org/apache/spark/sql/catalyst/parser/AstBuilder.scala#L2878
   https://github.com/apache/spark/blob/f9c8a246ecc34ef4bb93c319c7c9b6ff732c962e/sql/catalyst/src/main/scala/org/apache/spark/sql/internal/SQLConf.scala#L4858-L4865



-- 
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


[GitHub] [spark] hvanhovell commented on pull request #40276: [SPARK-42630][CONNECT][PYTHON] Implement data type string parser

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

   At the end of the day it is an optimization. However I do it is a sound one to have. 


-- 
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


[GitHub] [spark] HyukjinKwon commented on a diff in pull request #40276: [SPARK-42630][CONNECT][PYTHON] Implement data type string parser

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


##########
python/pyspark/sql/connect/types.py:
##########
@@ -342,20 +343,325 @@ def from_arrow_schema(arrow_schema: "pa.Schema") -> StructType:
 
 
 def parse_data_type(data_type: str) -> DataType:
-    # Currently we don't have a way to have a current Spark session in Spark Connect, and
-    # pyspark.sql.SparkSession has a centralized logic to control the session creation.
-    # So uses pyspark.sql.SparkSession for now. Should replace this to using the current
-    # Spark session for Spark Connect in the future.
-    from pyspark.sql import SparkSession as PySparkSession
-
-    assert is_remote()
-    return_type_schema = (
-        PySparkSession.builder.getOrCreate().createDataFrame(data=[], schema=data_type).schema
+    """
+    Parses the given data type string to a :class:`DataType`. The data type string format equals
+    :class:`DataType.simpleString`, except that the top level struct type can omit
+    the ``struct<>``. Since Spark 2.3, this also supports a schema in a DDL-formatted
+    string and case-insensitive strings.
+
+    Examples
+    --------
+    >>> parse_data_type("int ")
+    IntegerType()
+    >>> parse_data_type("INT ")
+    IntegerType()
+    >>> parse_data_type("a: byte, b: decimal(  16 , 8   ) ")
+    StructType([StructField('a', ByteType(), True), StructField('b', DecimalType(16,8), True)])
+    >>> parse_data_type("a DOUBLE, b STRING")
+    StructType([StructField('a', DoubleType(), True), StructField('b', StringType(), True)])
+    >>> parse_data_type("a DOUBLE, b CHAR( 50 )")
+    StructType([StructField('a', DoubleType(), True), StructField('b', CharType(50), True)])
+    >>> parse_data_type("a DOUBLE, b VARCHAR( 50 )")
+    StructType([StructField('a', DoubleType(), True), StructField('b', VarcharType(50), True)])
+    >>> parse_data_type("a: array< short>")
+    StructType([StructField('a', ArrayType(ShortType(), True), True)])
+    >>> parse_data_type(" map<string , string > ")
+    MapType(StringType(), StringType(), True)
+
+    >>> # Error cases
+    >>> parse_data_type("blabla") # doctest: +IGNORE_EXCEPTION_DETAIL
+    Traceback (most recent call last):
+        ...
+    ParseException:...
+    >>> parse_data_type("a: int,") # doctest: +IGNORE_EXCEPTION_DETAIL
+    Traceback (most recent call last):
+        ...
+    ParseException:...
+    >>> parse_data_type("array<int") # doctest: +IGNORE_EXCEPTION_DETAIL
+    Traceback (most recent call last):
+        ...
+    ParseException:...
+    >>> parse_data_type("map<int, boolean>>") # doctest: +IGNORE_EXCEPTION_DETAIL
+    Traceback (most recent call last):
+        ...
+    ParseException:...
+    """
+    try:
+        # DDL format, "fieldname datatype, fieldname datatype".
+        return DDLSchemaParser(data_type).from_ddl_schema()
+    except ParseException as e:
+        try:
+            # For backwards compatibility, "integer", "struct<fieldname: datatype>" and etc.
+            return DDLDataTypeParser(data_type).from_ddl_datatype()
+        except ParseException:
+            try:
+                # For backwards compatibility, "fieldname: datatype, fieldname: datatype" case.
+                return DDLDataTypeParser(f"struct<{data_type}>").from_ddl_datatype()
+            except ParseException:
+                raise e from None
+
+
+class DataTypeParserBase:
+    REGEXP_IDENTIFIER: Final[Pattern] = re.compile("\\w+|`(?:``|[^`])*`", re.MULTILINE)
+    REGEXP_INTEGER_VALUES: Final[Pattern] = re.compile(
+        "\\(\\s*(?:[+-]?\\d+)\\s*(?:,\\s*(?:[+-]?\\d+)\\s*)*\\)", re.MULTILINE
     )
-    with_col_name = " " in data_type.strip()
-    if len(return_type_schema.fields) == 1 and not with_col_name:
-        # To match pyspark.sql.types._parse_datatype_string
-        return_type = return_type_schema.fields[0].dataType
-    else:
-        return_type = return_type_schema
-    return return_type
+    REGEXP_INTERVAL_TYPE: Final[Pattern] = re.compile(
+        "(day|hour|minute|second)(?:\\s+to\\s+(hour|minute|second))?", re.IGNORECASE | re.MULTILINE
+    )
+    REGEXP_NOT_NULL_COMMENT: Final[Pattern] = re.compile(
+        "(not\\s+null)?(?:(?(1)\\s+)comment\\s+'((?:\\\\'|[^'])*)')?", re.IGNORECASE | re.MULTILINE
+    )
+
+    def __init__(self, type_str: str):
+        self._type_str = type_str
+        self._pos = 0
+        self._lstrip()
+
+    def _lstrip(self) -> None:
+        remaining = self._type_str[self._pos :]
+        self._pos = self._pos + (len(remaining) - len(remaining.lstrip()))
+
+    def _parse_data_type(self) -> DataType:
+        type_str = self._type_str[self._pos :]
+        m = self.REGEXP_IDENTIFIER.match(type_str)
+        if m:
+            data_type_name = m.group(0).lower().strip("`").replace("``", "`")
+            self._pos = self._pos + len(m.group(0))
+            self._lstrip()
+            if data_type_name == "array":
+                return self._parse_array_type()
+            elif data_type_name == "map":
+                return self._parse_map_type()
+            elif data_type_name == "struct":
+                return self._parse_struct_type()
+            elif data_type_name == "interval":
+                return self._parse_interval_type()
+            else:
+                return self._parse_primitive_types(data_type_name)
+
+        raise ParseException(
+            error_class="PARSE_SYNTAX_ERROR",
+            message_parameters={"error": f"'{type_str}'", "hint": ""},
+        )
+
+    def _parse_array_type(self) -> ArrayType:
+        type_str = self._type_str[self._pos :]
+        if len(type_str) > 0 and type_str[0] == "<":
+            self._pos = self._pos + 1
+            self._lstrip()
+            element_type = self._parse_data_type()
+            remaining = self._type_str[self._pos :]
+            if len(remaining) and remaining[0] == ">":
+                self._pos = self._pos + 1
+                self._lstrip()
+                return ArrayType(element_type)
+        raise ParseException(error_class="INCOMPLETE_TYPE_DEFINITION.ARRAY", message_parameters={})
+
+    def _parse_map_type(self) -> MapType:
+        type_str = self._type_str[self._pos :]
+        if len(type_str) > 0 and type_str[0] == "<":
+            self._pos = self._pos + 1
+            self._lstrip()
+            key_type = self._parse_data_type()
+            remaining = self._type_str[self._pos :]
+            if len(remaining) > 0 and remaining[0] == ",":
+                self._pos = self._pos + 1
+                self._lstrip()
+                value_type = self._parse_data_type()
+                remaining = self._type_str[self._pos :]
+                if len(remaining) > 0 and remaining[0] == ">":
+                    self._pos = self._pos + 1
+                    self._lstrip()
+                    return MapType(key_type, value_type)
+        raise ParseException(error_class="INCOMPLETE_TYPE_DEFINITION.MAP", message_parameters={})
+
+    def _parse_struct_type(self) -> StructType:
+        type_str = self._type_str[self._pos :]
+        if len(type_str) > 0 and type_str[0] == "<":
+            self._pos = self._pos + 1
+            self._lstrip()
+            fields = self._parse_struct_fields()
+            remaining = self._type_str[self._pos :]
+            if len(remaining) > 0 and remaining[0] == ">":
+                self._pos = self._pos + 1
+                self._lstrip()
+                return StructType(fields)
+        raise ParseException(error_class="INCOMPLETE_TYPE_DEFINITION.STRUCT", message_parameters={})
+
+    def _parse_struct_fields(self, sep_with_colon: bool = True) -> List[StructField]:
+        type_str = self._type_str[self._pos :]
+        m = self.REGEXP_IDENTIFIER.match(type_str)
+        if m:
+            field_name = m.group(0).lower().strip("`").replace("``", "`")

Review Comment:
   Couple of concerns..
   
   I still doubt if this is something we should manually implement ... for example, what about case sensitivity .. To do this properly, we should use antlr for Python (e.g., https://github.com/antlr/antlr4/blob/master/doc/python-target.md). But I feel that's sort of overkill.
   
   We don't have new types very often but still we add. For example, in the last couple of years, we added ANSI types, date, year, month interval, timestamp without timzone, etc. We also expose the char and varchar type that was hidden before.



-- 
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


[GitHub] [spark] hvanhovell commented on a diff in pull request #40276: [SPARK-42630][CONNECT][PYTHON] Implement data type string parser

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


##########
python/pyspark/sql/connect/types.py:
##########
@@ -342,20 +343,325 @@ def from_arrow_schema(arrow_schema: "pa.Schema") -> StructType:
 
 
 def parse_data_type(data_type: str) -> DataType:
-    # Currently we don't have a way to have a current Spark session in Spark Connect, and
-    # pyspark.sql.SparkSession has a centralized logic to control the session creation.
-    # So uses pyspark.sql.SparkSession for now. Should replace this to using the current
-    # Spark session for Spark Connect in the future.
-    from pyspark.sql import SparkSession as PySparkSession
-
-    assert is_remote()
-    return_type_schema = (
-        PySparkSession.builder.getOrCreate().createDataFrame(data=[], schema=data_type).schema
+    """
+    Parses the given data type string to a :class:`DataType`. The data type string format equals
+    :class:`DataType.simpleString`, except that the top level struct type can omit
+    the ``struct<>``. Since Spark 2.3, this also supports a schema in a DDL-formatted
+    string and case-insensitive strings.
+
+    Examples
+    --------
+    >>> parse_data_type("int ")
+    IntegerType()
+    >>> parse_data_type("INT ")
+    IntegerType()
+    >>> parse_data_type("a: byte, b: decimal(  16 , 8   ) ")
+    StructType([StructField('a', ByteType(), True), StructField('b', DecimalType(16,8), True)])
+    >>> parse_data_type("a DOUBLE, b STRING")
+    StructType([StructField('a', DoubleType(), True), StructField('b', StringType(), True)])
+    >>> parse_data_type("a DOUBLE, b CHAR( 50 )")
+    StructType([StructField('a', DoubleType(), True), StructField('b', CharType(50), True)])
+    >>> parse_data_type("a DOUBLE, b VARCHAR( 50 )")
+    StructType([StructField('a', DoubleType(), True), StructField('b', VarcharType(50), True)])
+    >>> parse_data_type("a: array< short>")
+    StructType([StructField('a', ArrayType(ShortType(), True), True)])
+    >>> parse_data_type(" map<string , string > ")
+    MapType(StringType(), StringType(), True)
+
+    >>> # Error cases
+    >>> parse_data_type("blabla") # doctest: +IGNORE_EXCEPTION_DETAIL
+    Traceback (most recent call last):
+        ...
+    ParseException:...
+    >>> parse_data_type("a: int,") # doctest: +IGNORE_EXCEPTION_DETAIL
+    Traceback (most recent call last):
+        ...
+    ParseException:...
+    >>> parse_data_type("array<int") # doctest: +IGNORE_EXCEPTION_DETAIL
+    Traceback (most recent call last):
+        ...
+    ParseException:...
+    >>> parse_data_type("map<int, boolean>>") # doctest: +IGNORE_EXCEPTION_DETAIL
+    Traceback (most recent call last):
+        ...
+    ParseException:...
+    """
+    try:
+        # DDL format, "fieldname datatype, fieldname datatype".
+        return DDLSchemaParser(data_type).from_ddl_schema()
+    except ParseException as e:
+        try:
+            # For backwards compatibility, "integer", "struct<fieldname: datatype>" and etc.
+            return DDLDataTypeParser(data_type).from_ddl_datatype()
+        except ParseException:
+            try:
+                # For backwards compatibility, "fieldname: datatype, fieldname: datatype" case.
+                return DDLDataTypeParser(f"struct<{data_type}>").from_ddl_datatype()
+            except ParseException:
+                raise e from None
+
+
+class DataTypeParserBase:
+    REGEXP_IDENTIFIER: Final[Pattern] = re.compile("\\w+|`(?:``|[^`])*`", re.MULTILINE)
+    REGEXP_INTEGER_VALUES: Final[Pattern] = re.compile(
+        "\\(\\s*(?:[+-]?\\d+)\\s*(?:,\\s*(?:[+-]?\\d+)\\s*)*\\)", re.MULTILINE
     )
-    with_col_name = " " in data_type.strip()
-    if len(return_type_schema.fields) == 1 and not with_col_name:
-        # To match pyspark.sql.types._parse_datatype_string
-        return_type = return_type_schema.fields[0].dataType
-    else:
-        return_type = return_type_schema
-    return return_type
+    REGEXP_INTERVAL_TYPE: Final[Pattern] = re.compile(
+        "(day|hour|minute|second)(?:\\s+to\\s+(hour|minute|second))?", re.IGNORECASE | re.MULTILINE
+    )
+    REGEXP_NOT_NULL_COMMENT: Final[Pattern] = re.compile(
+        "(not\\s+null)?(?:(?(1)\\s+)comment\\s+'((?:\\\\'|[^'])*)')?", re.IGNORECASE | re.MULTILINE
+    )
+
+    def __init__(self, type_str: str):
+        self._type_str = type_str
+        self._pos = 0
+        self._lstrip()
+
+    def _lstrip(self) -> None:
+        remaining = self._type_str[self._pos :]
+        self._pos = self._pos + (len(remaining) - len(remaining.lstrip()))
+
+    def _parse_data_type(self) -> DataType:
+        type_str = self._type_str[self._pos :]
+        m = self.REGEXP_IDENTIFIER.match(type_str)
+        if m:
+            data_type_name = m.group(0).lower().strip("`").replace("``", "`")
+            self._pos = self._pos + len(m.group(0))
+            self._lstrip()
+            if data_type_name == "array":
+                return self._parse_array_type()
+            elif data_type_name == "map":
+                return self._parse_map_type()
+            elif data_type_name == "struct":
+                return self._parse_struct_type()
+            elif data_type_name == "interval":
+                return self._parse_interval_type()
+            else:
+                return self._parse_primitive_types(data_type_name)
+
+        raise ParseException(
+            error_class="PARSE_SYNTAX_ERROR",
+            message_parameters={"error": f"'{type_str}'", "hint": ""},
+        )
+
+    def _parse_array_type(self) -> ArrayType:
+        type_str = self._type_str[self._pos :]
+        if len(type_str) > 0 and type_str[0] == "<":
+            self._pos = self._pos + 1
+            self._lstrip()
+            element_type = self._parse_data_type()
+            remaining = self._type_str[self._pos :]
+            if len(remaining) and remaining[0] == ">":
+                self._pos = self._pos + 1
+                self._lstrip()
+                return ArrayType(element_type)
+        raise ParseException(error_class="INCOMPLETE_TYPE_DEFINITION.ARRAY", message_parameters={})
+
+    def _parse_map_type(self) -> MapType:
+        type_str = self._type_str[self._pos :]
+        if len(type_str) > 0 and type_str[0] == "<":
+            self._pos = self._pos + 1
+            self._lstrip()
+            key_type = self._parse_data_type()
+            remaining = self._type_str[self._pos :]
+            if len(remaining) > 0 and remaining[0] == ",":
+                self._pos = self._pos + 1
+                self._lstrip()
+                value_type = self._parse_data_type()
+                remaining = self._type_str[self._pos :]
+                if len(remaining) > 0 and remaining[0] == ">":
+                    self._pos = self._pos + 1
+                    self._lstrip()
+                    return MapType(key_type, value_type)
+        raise ParseException(error_class="INCOMPLETE_TYPE_DEFINITION.MAP", message_parameters={})
+
+    def _parse_struct_type(self) -> StructType:
+        type_str = self._type_str[self._pos :]
+        if len(type_str) > 0 and type_str[0] == "<":
+            self._pos = self._pos + 1
+            self._lstrip()
+            fields = self._parse_struct_fields()
+            remaining = self._type_str[self._pos :]
+            if len(remaining) > 0 and remaining[0] == ">":
+                self._pos = self._pos + 1
+                self._lstrip()
+                return StructType(fields)
+        raise ParseException(error_class="INCOMPLETE_TYPE_DEFINITION.STRUCT", message_parameters={})
+
+    def _parse_struct_fields(self, sep_with_colon: bool = True) -> List[StructField]:
+        type_str = self._type_str[self._pos :]
+        m = self.REGEXP_IDENTIFIER.match(type_str)
+        if m:
+            field_name = m.group(0).lower().strip("`").replace("``", "`")

Review Comment:
   @HyukjinKwon real engines write their own parsers ;)... In this case you could add a separate tokenization step to make the actual parsing a bit easier to read, and easier to maintain, and it can take care of some case sensitivity concerns. I think adding antlr for this is overkill.
   
   As for the worry of missing stuff. I guess having some language agnostic specification test would not be a bad thing to add.



-- 
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


[GitHub] [spark] zhengruifeng commented on pull request #40276: [SPARK-42630][CONNECT][PYTHON] Implement data type string parser

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

   I don't know the internal of Parser well, but I guess if we want to reach 100% compatibility, we may need to reuse the `.g4` files and implement a subset of  `AstBuilder` to support `singleDataType` and `singleTableSchema`.
   
   For example, the DDL also support `NOT NULL` and `COMMENT`:
   ```
   >>> df = spark.createDataFrame([], """a string  COMMENT 'this is just a simple string' """)
   >>> df.schema
   StructType([StructField('a', StringType(), True)])
   >>> df = spark.createDataFrame([], """a string  NOT NULL COMMENT 'this is just a simple string' """)
   >>> df.schema
   StructType([StructField('a', StringType(), False)])
   ```
   
   cc @hvanhovell @cloud-fan @HyukjinKwon  WDYT?


-- 
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


[GitHub] [spark] HyukjinKwon commented on a diff in pull request #40276: [SPARK-42630][CONNECT][PYTHON] Implement data type string parser

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


##########
python/pyspark/sql/connect/types.py:
##########
@@ -342,20 +343,325 @@ def from_arrow_schema(arrow_schema: "pa.Schema") -> StructType:
 
 
 def parse_data_type(data_type: str) -> DataType:
-    # Currently we don't have a way to have a current Spark session in Spark Connect, and
-    # pyspark.sql.SparkSession has a centralized logic to control the session creation.
-    # So uses pyspark.sql.SparkSession for now. Should replace this to using the current
-    # Spark session for Spark Connect in the future.
-    from pyspark.sql import SparkSession as PySparkSession
-
-    assert is_remote()
-    return_type_schema = (
-        PySparkSession.builder.getOrCreate().createDataFrame(data=[], schema=data_type).schema
+    """
+    Parses the given data type string to a :class:`DataType`. The data type string format equals
+    :class:`DataType.simpleString`, except that the top level struct type can omit
+    the ``struct<>``. Since Spark 2.3, this also supports a schema in a DDL-formatted
+    string and case-insensitive strings.
+
+    Examples
+    --------
+    >>> parse_data_type("int ")
+    IntegerType()
+    >>> parse_data_type("INT ")
+    IntegerType()
+    >>> parse_data_type("a: byte, b: decimal(  16 , 8   ) ")
+    StructType([StructField('a', ByteType(), True), StructField('b', DecimalType(16,8), True)])
+    >>> parse_data_type("a DOUBLE, b STRING")
+    StructType([StructField('a', DoubleType(), True), StructField('b', StringType(), True)])
+    >>> parse_data_type("a DOUBLE, b CHAR( 50 )")
+    StructType([StructField('a', DoubleType(), True), StructField('b', CharType(50), True)])
+    >>> parse_data_type("a DOUBLE, b VARCHAR( 50 )")
+    StructType([StructField('a', DoubleType(), True), StructField('b', VarcharType(50), True)])
+    >>> parse_data_type("a: array< short>")
+    StructType([StructField('a', ArrayType(ShortType(), True), True)])
+    >>> parse_data_type(" map<string , string > ")
+    MapType(StringType(), StringType(), True)
+
+    >>> # Error cases
+    >>> parse_data_type("blabla") # doctest: +IGNORE_EXCEPTION_DETAIL
+    Traceback (most recent call last):
+        ...
+    ParseException:...
+    >>> parse_data_type("a: int,") # doctest: +IGNORE_EXCEPTION_DETAIL
+    Traceback (most recent call last):
+        ...
+    ParseException:...
+    >>> parse_data_type("array<int") # doctest: +IGNORE_EXCEPTION_DETAIL
+    Traceback (most recent call last):
+        ...
+    ParseException:...
+    >>> parse_data_type("map<int, boolean>>") # doctest: +IGNORE_EXCEPTION_DETAIL
+    Traceback (most recent call last):
+        ...
+    ParseException:...
+    """
+    try:
+        # DDL format, "fieldname datatype, fieldname datatype".
+        return DDLSchemaParser(data_type).from_ddl_schema()
+    except ParseException as e:
+        try:
+            # For backwards compatibility, "integer", "struct<fieldname: datatype>" and etc.
+            return DDLDataTypeParser(data_type).from_ddl_datatype()
+        except ParseException:
+            try:
+                # For backwards compatibility, "fieldname: datatype, fieldname: datatype" case.
+                return DDLDataTypeParser(f"struct<{data_type}>").from_ddl_datatype()
+            except ParseException:
+                raise e from None
+
+
+class DataTypeParserBase:
+    REGEXP_IDENTIFIER: Final[Pattern] = re.compile("\\w+|`(?:``|[^`])*`", re.MULTILINE)
+    REGEXP_INTEGER_VALUES: Final[Pattern] = re.compile(
+        "\\(\\s*(?:[+-]?\\d+)\\s*(?:,\\s*(?:[+-]?\\d+)\\s*)*\\)", re.MULTILINE
     )
-    with_col_name = " " in data_type.strip()
-    if len(return_type_schema.fields) == 1 and not with_col_name:
-        # To match pyspark.sql.types._parse_datatype_string
-        return_type = return_type_schema.fields[0].dataType
-    else:
-        return_type = return_type_schema
-    return return_type
+    REGEXP_INTERVAL_TYPE: Final[Pattern] = re.compile(
+        "(day|hour|minute|second)(?:\\s+to\\s+(hour|minute|second))?", re.IGNORECASE | re.MULTILINE
+    )
+    REGEXP_NOT_NULL_COMMENT: Final[Pattern] = re.compile(
+        "(not\\s+null)?(?:(?(1)\\s+)comment\\s+'((?:\\\\'|[^'])*)')?", re.IGNORECASE | re.MULTILINE
+    )
+
+    def __init__(self, type_str: str):
+        self._type_str = type_str
+        self._pos = 0
+        self._lstrip()
+
+    def _lstrip(self) -> None:
+        remaining = self._type_str[self._pos :]
+        self._pos = self._pos + (len(remaining) - len(remaining.lstrip()))
+
+    def _parse_data_type(self) -> DataType:
+        type_str = self._type_str[self._pos :]
+        m = self.REGEXP_IDENTIFIER.match(type_str)
+        if m:
+            data_type_name = m.group(0).lower().strip("`").replace("``", "`")
+            self._pos = self._pos + len(m.group(0))
+            self._lstrip()
+            if data_type_name == "array":
+                return self._parse_array_type()
+            elif data_type_name == "map":
+                return self._parse_map_type()
+            elif data_type_name == "struct":
+                return self._parse_struct_type()
+            elif data_type_name == "interval":
+                return self._parse_interval_type()
+            else:
+                return self._parse_primitive_types(data_type_name)
+
+        raise ParseException(
+            error_class="PARSE_SYNTAX_ERROR",
+            message_parameters={"error": f"'{type_str}'", "hint": ""},
+        )
+
+    def _parse_array_type(self) -> ArrayType:
+        type_str = self._type_str[self._pos :]
+        if len(type_str) > 0 and type_str[0] == "<":
+            self._pos = self._pos + 1
+            self._lstrip()
+            element_type = self._parse_data_type()
+            remaining = self._type_str[self._pos :]
+            if len(remaining) and remaining[0] == ">":
+                self._pos = self._pos + 1
+                self._lstrip()
+                return ArrayType(element_type)
+        raise ParseException(error_class="INCOMPLETE_TYPE_DEFINITION.ARRAY", message_parameters={})
+
+    def _parse_map_type(self) -> MapType:
+        type_str = self._type_str[self._pos :]
+        if len(type_str) > 0 and type_str[0] == "<":
+            self._pos = self._pos + 1
+            self._lstrip()
+            key_type = self._parse_data_type()
+            remaining = self._type_str[self._pos :]
+            if len(remaining) > 0 and remaining[0] == ",":
+                self._pos = self._pos + 1
+                self._lstrip()
+                value_type = self._parse_data_type()
+                remaining = self._type_str[self._pos :]
+                if len(remaining) > 0 and remaining[0] == ">":
+                    self._pos = self._pos + 1
+                    self._lstrip()
+                    return MapType(key_type, value_type)
+        raise ParseException(error_class="INCOMPLETE_TYPE_DEFINITION.MAP", message_parameters={})
+
+    def _parse_struct_type(self) -> StructType:
+        type_str = self._type_str[self._pos :]
+        if len(type_str) > 0 and type_str[0] == "<":
+            self._pos = self._pos + 1
+            self._lstrip()
+            fields = self._parse_struct_fields()
+            remaining = self._type_str[self._pos :]
+            if len(remaining) > 0 and remaining[0] == ">":
+                self._pos = self._pos + 1
+                self._lstrip()
+                return StructType(fields)
+        raise ParseException(error_class="INCOMPLETE_TYPE_DEFINITION.STRUCT", message_parameters={})
+
+    def _parse_struct_fields(self, sep_with_colon: bool = True) -> List[StructField]:
+        type_str = self._type_str[self._pos :]
+        m = self.REGEXP_IDENTIFIER.match(type_str)
+        if m:
+            field_name = m.group(0).lower().strip("`").replace("``", "`")

Review Comment:
   Couple of concerns..
   
   I still doubt if this is something we should manually implement. I think there'd be many cases we miss ... for example, what about case sensitivity .. Also, to do this properly, we should use antlr for Python (e.g., https://github.com/antlr/antlr4/blob/master/doc/python-target.md). But I feel that's sort of overkill.
   
   We don't have new types very often but it's not very rare either. For example, in the last couple of years, we added ANSI types, date, year, month interval, timestamp without timzone, etc. We also exposed the char and varchar type that were hidden before.



-- 
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