Copilot commented on code in PR #6046:
URL: https://github.com/apache/paimon/pull/6046#discussion_r2275294988


##########
paimon-common/src/main/java/org/apache/paimon/casting/StringToRowCastRule.java:
##########
@@ -0,0 +1,196 @@
+/*
+ * 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.paimon.casting;
+
+import org.apache.paimon.data.BinaryString;
+import org.apache.paimon.data.GenericRow;
+import org.apache.paimon.data.InternalRow;
+import org.apache.paimon.types.DataType;
+import org.apache.paimon.types.DataTypeFamily;
+import org.apache.paimon.types.DataTypeRoot;
+import org.apache.paimon.types.RowType;
+import org.apache.paimon.types.VarCharType;
+import org.apache.paimon.utils.StringUtils;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Stack;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+/** {@link DataTypeFamily#CHARACTER_STRING} to {@link DataTypeRoot#ROW} cast 
rule. */
+class StringToRowCastRule extends AbstractCastRule<BinaryString, InternalRow> {
+
+    static final StringToRowCastRule INSTANCE = new StringToRowCastRule();
+
+    // Pattern for bracket format: {field1, field2, field3}
+    private static final Pattern BRACKET_ROW_PATTERN = 
Pattern.compile("^\\s*\\{(.*)\\}\\s*$");
+
+    // Pattern for SQL function format: STRUCT(field1, field2, field3)
+    private static final Pattern FUNCTION_ROW_PATTERN =
+            Pattern.compile("^\\s*STRUCT\\s*\\((.*)\\)\\s*$", 
Pattern.CASE_INSENSITIVE);
+
+    private StringToRowCastRule() {
+        super(
+                CastRulePredicate.builder()
+                        .input(DataTypeFamily.CHARACTER_STRING)
+                        .target(DataTypeRoot.ROW)
+                        .build());
+    }
+
+    @Override
+    public CastExecutor<BinaryString, InternalRow> create(DataType inputType, 
DataType targetType) {
+        RowType rowType = (RowType) targetType;
+        CastExecutor<BinaryString, Object>[] fieldCastExecutors = 
createFieldCastExecutors(rowType);
+        return value -> parseRow(value, fieldCastExecutors, 
rowType.getFieldCount());
+    }
+
+    private CastExecutor<BinaryString, Object>[] 
createFieldCastExecutors(RowType rowType) {
+        int fieldCount = rowType.getFieldCount();
+        @SuppressWarnings("unchecked")
+        CastExecutor<BinaryString, Object>[] fieldCastExecutors = new 
CastExecutor[fieldCount];
+
+        for (int i = 0; i < fieldCount; i++) {
+            DataType fieldType = rowType.getTypeAt(i);
+            @SuppressWarnings("unchecked")
+            CastExecutor<BinaryString, Object> executor =
+                    (CastExecutor<BinaryString, Object>)
+                            CastExecutors.resolve(VarCharType.STRING_TYPE, 
fieldType);
+            if (executor == null) {
+                throw new RuntimeException("Cannot cast string to row field 
type: " + fieldType);
+            }
+            fieldCastExecutors[i] = executor;
+        }
+        return fieldCastExecutors;
+    }
+
+    private InternalRow parseRow(
+            BinaryString value,
+            CastExecutor<BinaryString, Object>[] fieldCastExecutors,
+            int fieldCount) {
+        try {
+            String str = value.toString().trim();
+            if ("{}".equals(str) || "STRUCT()".equalsIgnoreCase(str)) {
+                return createNullRow(fieldCount);
+            }
+            String content = extractRowContent(str);
+            if (content.isEmpty()) {
+                return createNullRow(fieldCount);
+            }
+            List<String> fieldValues = splitRowFields(content);
+            if (fieldValues.size() != fieldCount) {
+                throw new RuntimeException(
+                        "Row field count mismatch. Expected: "
+                                + fieldCount
+                                + ", Actual: "
+                                + fieldValues.size());

Review Comment:
   The error message 'Row field count mismatch' should include the field name 
or more context about which row is being parsed to help with debugging.
   ```suggestion
                                   + " (fields: " + rowType.getFieldNames()
                                   + "), Actual: "
                                   + fieldValues.size()
                                   + ". Input: '" + value + "'");
   ```



##########
paimon-common/src/main/java/org/apache/paimon/casting/StringToMapCastRule.java:
##########
@@ -0,0 +1,207 @@
+/*
+ * 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.paimon.casting;
+
+import org.apache.paimon.data.BinaryString;
+import org.apache.paimon.data.GenericMap;
+import org.apache.paimon.data.InternalMap;
+import org.apache.paimon.types.DataType;
+import org.apache.paimon.types.DataTypeFamily;
+import org.apache.paimon.types.DataTypeRoot;
+import org.apache.paimon.types.MapType;
+import org.apache.paimon.types.VarCharType;
+import org.apache.paimon.utils.StringUtils;
+
+import org.apache.paimon.shade.guava30.com.google.common.collect.Maps;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Stack;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+
+/** {@link DataTypeFamily#CHARACTER_STRING} to {@link DataTypeRoot#MAP} cast 
rule. */
+class StringToMapCastRule extends AbstractCastRule<BinaryString, InternalMap> {
+
+    static final StringToMapCastRule INSTANCE = new StringToMapCastRule();
+
+    // Pattern for bracket format: {key1 -> value1, key2 -> value2}
+    private static final Pattern BRACKET_MAP_PATTERN = 
Pattern.compile("^\\s*\\{(.*)\\}\\s*$");
+
+    // Pattern for SQL function format: MAP('key1', 'value1', 'key2', 'value2')
+    private static final Pattern FUNCTION_MAP_PATTERN =
+            Pattern.compile("^\\s*MAP\\s*\\((.*)\\)\\s*$", 
Pattern.CASE_INSENSITIVE);
+
+    private static final Pattern ENTRY_PATTERN = 
Pattern.compile("(.+?)\\s*->\\s*(.+)");
+
+    private StringToMapCastRule() {
+        super(
+                CastRulePredicate.builder()
+                        .input(DataTypeFamily.CHARACTER_STRING)
+                        .target(DataTypeRoot.MAP)
+                        .build());
+    }
+
+    @Override
+    public CastExecutor<BinaryString, InternalMap> create(DataType inputType, 
DataType targetType) {
+        MapType mapType = (MapType) targetType;
+        CastExecutor<BinaryString, Object> keyCastExecutor =
+                createCastExecutor(mapType.getKeyType());
+        CastExecutor<BinaryString, Object> valueCastExecutor =
+                createCastExecutor(mapType.getValueType());
+
+        return value -> parseMap(value, keyCastExecutor, valueCastExecutor);
+    }
+
+    private InternalMap parseMap(
+            BinaryString value,
+            CastExecutor<BinaryString, Object> keyCastExecutor,
+            CastExecutor<BinaryString, Object> valueCastExecutor) {
+        try {
+            String str = value.toString().trim();
+            if ("{}".equals(str) || "MAP()".equalsIgnoreCase(str)) {
+                return new GenericMap(new HashMap<>());
+            }
+            return new GenericMap(parseDefaultMap(str, keyCastExecutor, 
valueCastExecutor));
+        } catch (Exception e) {
+            throw new RuntimeException("Cannot parse '" + value + "' as MAP: " 
+ e.getMessage(), e);
+        }
+    }
+
+    private CastExecutor<BinaryString, Object> createCastExecutor(DataType 
targetType) {
+        @SuppressWarnings("unchecked")
+        CastExecutor<BinaryString, Object> executor =
+                (CastExecutor<BinaryString, Object>)
+                        CastExecutors.resolve(VarCharType.STRING_TYPE, 
targetType);
+        if (executor == null) {
+            throw new RuntimeException("Cannot cast string to type: " + 
targetType);
+        }
+        return executor;
+    }
+
+    private Map<Object, Object> parseDefaultMap(
+            String str,
+            CastExecutor<BinaryString, Object> keyCastExecutor,
+            CastExecutor<BinaryString, Object> valueCastExecutor) {
+
+        Map<Object, Object> mapContent = Maps.newHashMap();
+        Matcher bracketMatcher = BRACKET_MAP_PATTERN.matcher(str);
+        if (bracketMatcher.matches()) {
+            // Parse bracket format (arrow-separated entries)
+            String content = bracketMatcher.group(1).trim();
+            return parseMapEntry(content, keyCastExecutor, valueCastExecutor);
+        }
+
+        Matcher functionMatcher = FUNCTION_MAP_PATTERN.matcher(str);
+        if (functionMatcher.matches()) {
+            String functionContent = functionMatcher.group(1).trim();
+            return parseFunctionDefaultMap(functionContent, keyCastExecutor, 
valueCastExecutor);
+        }
+
+        throw new RuntimeException(
+                "Invalid map format: " + str + ". Expected format: {k -> v} or 
MAP(k, v)");
+    }
+
+    private Map<Object, Object> parseFunctionDefaultMap(
+            String content,
+            CastExecutor<BinaryString, Object> keyCastExecutor,
+            CastExecutor<BinaryString, Object> valueCastExecutor) {
+
+        List<String> elements = splitMapEntries(content.trim());
+        if (elements.size() % 2 != 0) {
+            throw new RuntimeException("Invalid Function map format: odd 
number of elements");

Review Comment:
   The error message should be more descriptive and include the actual number 
of elements found to help with debugging.
   ```suggestion
               throw new RuntimeException(
                   "Invalid Function map format: odd number of elements (" + 
elements.size() + " found)");
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to