raminqaf commented on code in PR #30102:
URL: https://github.com/apache/flink/pull/30102#discussion_r4694079601
##########
docs/data/functions/variant/parse_json.yml:
##########
@@ -47,7 +47,7 @@ notes:
- Invalid JSON fails the job. To get NULL instead, use `TRY_PARSE_JSON`.
- Only the first JSON value is read, and content after it is ignored, so
`PARSE_JSON('{"a":1} xyz')` returns `{"a":1}`.
- An object doesn't keep the order of its fields. `JSON_STRING` returns them
sorted by name.
- - A value larger than 16 MiB fails.
+ - A value larger than 16 MiB fails. If a query only reads fields, such as
`CAST(PARSE_JSON(doc)['a'] AS INT)`, the limit applies to those fields only, so
a larger document can succeed. A query that uses the whole value, such as
`JSON_STRING(PARSE_JSON(doc))`, fails on it.
Review Comment:
Should we add this to it's separate bullet? Also I am not sure how useful
this information is for the end user.
##########
flink-core/src/main/java/org/apache/flink/types/variant/BinaryVariantInternalBuilder.java:
##########
@@ -856,38 +898,32 @@ private int getIntegerSize(int value) {
return U24_SIZE;
}
- private void parseFloatingPoint(JsonParser parser) throws IOException {
- if (!tryParseDecimal(parser.getText())) {
- final double d = parser.getDoubleValue();
- // Jackson coerces out-of-range numbers like 1e400 to +/-Infinity.
Reject them instead
- // of storing a non-finite double that toJson() could not render
as valid JSON.
- if (Double.isInfinite(d) || Double.isNaN(d)) {
- throw new JsonParseException(
- parser,
- String.format(
- "Numeric value '%s' is out of the range of
double precision and cannot be stored as a Variant.",
- parser.getText()));
- }
- appendDouble(d);
+ private static double finiteDouble(JsonParser parser) throws IOException {
Review Comment:
This method is used to check Float too correct? Should we make the name more
generic to apply for float and double?
##########
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/codegen/JsonParseReuseTest.java:
##########
@@ -667,7 +759,8 @@ void testComputedInputInDifferentCaseBranchesSharesParse(
final String secondBranch,
final Object expectedRow1,
final Object expectedRow2,
- final Pattern parsePattern) {
+ final Pattern parsePattern,
+ final int parses) {
Review Comment:
`parses` is 1 in every row, so it adds a column without testing anything
new. Could we drop it and keep `.isOne()`?
##########
flink-table/flink-table-runtime/src/test/java/org/apache/flink/table/runtime/functions/VariantPathReaderTest.java:
##########
@@ -0,0 +1,272 @@
+/*
+ * 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.flink.table.runtime.functions;
+
+import org.apache.flink.table.data.binary.BinaryStringData;
+import org.apache.flink.types.variant.BinaryVariantInternalBuilder;
+import org.apache.flink.types.variant.Variant;
+
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+import java.util.stream.Stream;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.junit.jupiter.params.provider.Arguments.arguments;
+
+/** Tests that {@link VariantPathReader} reads what {@code PARSE_JSON} and
access would. */
+class VariantPathReaderTest {
+
+ // objects, arrays, a path inside another, the same path twice, and steps
of both kinds
+ private static final Object[][] PATHS = {
+ {"book", "title"},
+ {"book"},
+ {"book", "tags", 1},
+ {"book", "title"},
+ {"a", 0},
+ {"a", 0, "b"},
+ {0},
+ {0, "x"},
+ {"missing", "x"},
+ {"?"},
+ {"k" + (char) 0xD800}
+ };
+
+ private static final String BOOK =
+
"{\"store\":\"Main\",\"book\":{\"author\":\"Melville\",\"title\":\"Moby Dick\","
+ +
"\"tags\":[\"novel\",\"sea\"],\"year\":1851},\"open\":true}";
+
+ private static Stream<Arguments> documents() {
+ final String[] jsons = {
+ BOOK,
+ // values of other types at the steps
+ "{\"book\":42}",
+ "{\"book\":null}",
+ "{\"book\":\"text\"}",
+ "{\"book\":[1,2]}",
+ "{\"book\":{\"title\":{\"nested\":[1,{\"x\":2}]}}}",
+ "{\"a\":[{\"b\":1},{\"b\":2}]}",
+ "{\"a\":[]}",
+ "{\"a\":{\"0\":1}}",
+ "[{\"x\":1},2]",
+ "[]",
+ "\"scalar\"",
+ "null",
+ "1",
+ // duplicate keys, where the last one wins if they are allowed
+ "{\"book\":{\"title\":\"first\"},\"book\":{\"title\":\"second\"}}",
+ "{\"book\":{\"title\":\"first\"},\"book\":7}",
+ "{\"store\":{\"x\":1,\"x\":2},\"book\":{\"title\":\"t\"}}",
+ // keys that are stored as the same bytes
+ "{\"?\":1,\"\\ud800\":2}",
+ "{\"k\\ud800\":1}",
+ // an escaped key of a path
+ "{\"\\u0062ook\":{\"title\":\"t\"}}",
+ // many keys, with and without a duplicate after them
+ manyKeys(20, null),
+ manyKeys(20, "k17"),
+ manyKeys(20, "k3"),
+ // numbers that fail or change type in the skipped part
+ "{\"store\":1e400,\"book\":{\"title\":\"t\"}}",
+
"{\"store\":123456789012345678901234567890,\"book\":{\"title\":\"t\"}}",
+ "{\"store\":-0.0,\"book\":{\"title\":1.5e3}}",
+ // skipped arrays: scalars of each kind, nesting, duplicates,
siblings, bad numbers
+ "{\"store\":[1,\"s\",true,false,null,1.5,[2,{\"x\":1}]],"
+ + "\"book\":{\"title\":\"t\"}}",
+ "{\"store\":[{\"x\":1,\"x\":2}],\"book\":{\"title\":\"t\"}}",
+ "{\"store\":[{\"x\":1},{\"x\":1}],\"book\":{\"title\":\"t\"}}",
+ "{\"store\":[1e400],\"book\":{\"title\":\"t\"}}",
+ "{\"store\":[1",
+ // duplicate keys in skipped objects below depth 1, and key sets
of nested objects
+
"{\"store\":{\"inner\":{\"x\":1,\"x\":2}},\"book\":{\"title\":\"t\"}}",
+
"{\"store\":{\"x\":{\"x\":1},\"y\":1,\"x\":2},\"book\":{\"title\":\"t\"}}",
+ "{\"store\":{\"a\":{\"b\":1},\"b\":2},\"book\":{\"title\":\"t\"}}",
+ // a key set over 64 keys, replaced for the next object at the
same depth
+ "{\"store\":{" + keys(70) +
"},\"other\":{\"k0\":1},\"book\":{\"title\":\"t\"}}",
+ "{\"store\":{" + keys(70) + "},\"other\":{\"k0\":1,\"k0\":2}}",
+ // escapes in a skipped object, and in a value only
+ "{\"store\":{\"?\":1,\"\\ud800\":2},\"book\":{\"title\":\"t\"}}",
+ "{\"store\":{\"a\":1,\"a\":2},\"v\":\"x\\ny\"}",
+ // malformed documents
+ "",
+ "{",
+ "{\"book\":}",
+ "{\"book\":{\"title\":\"t\"},}",
+ "[1,]",
+ // content after the document, which the full parse ignores
+ "{\"book\":{\"title\":\"t\"}} trailing",
+ // a large skipped value
+ largeDocument()
+ };
+ return Stream.of(jsons)
+ .flatMap(
+ json ->
+ Stream.of(
+
arguments(json.getBytes(StandardCharsets.UTF_8), false),
+
arguments(json.getBytes(StandardCharsets.UTF_8), true)));
+ }
+
+ @ParameterizedTest(name = "[{index}] allowDuplicateKeys={1}")
+ @MethodSource("documents")
+ void testReadsWhatTheFullParseReads(byte[] json, boolean
allowDuplicateKeys) {
+ assertSame(json, allowDuplicateKeys);
+ }
+
+ @ParameterizedTest(name = "[{index}] allowDuplicateKeys={1}")
+ @MethodSource("invalidUtf8")
+ void testInvalidUtf8InSkippedString(byte[] json, boolean
allowDuplicateKeys) {
+ assertSame(json, allowDuplicateKeys);
+ }
+
+ private static Stream<Arguments> invalidUtf8() {
+ return Stream.of(
+ invalidUtf8In("{\"store\":\"",
"\",\"book\":{\"title\":\"t\"}}"),
+ // in a skipped array
+ invalidUtf8In("{\"store\":[\"",
"\"],\"book\":{\"title\":\"t\"}}"),
+ // a key with an encoded surrogate, which Jackson
rejects: a surrogate in a
+ // key without a backslash can't reach the reader
+ withBytes("{\"", ENCODED_SURROGATE, "\":1}"),
+ withBytes("{\"?\":1,\"", ENCODED_SURROGATE, "\":2}"))
+ .flatMap(json -> Stream.of(arguments(json, false),
arguments(json, true)));
+ }
+
+ // U+D800 as UTF-8 bytes
+ private static final byte[] ENCODED_SURROGATE = {(byte) 0xED, (byte) 0xA0,
(byte) 0x80};
+
+ // a truncated character between prefix and suffix
+ private static byte[] invalidUtf8In(String prefix, String suffix) {
+ return withBytes(prefix, new byte[] {(byte) 0xC3}, suffix);
+ }
+
+ private static byte[] withBytes(String prefix, byte[] middle, String
suffix) {
+ final byte[] start = prefix.getBytes(StandardCharsets.UTF_8);
+ final byte[] end = suffix.getBytes(StandardCharsets.UTF_8);
+ final byte[] json = new byte[start.length + middle.length +
end.length];
+ System.arraycopy(start, 0, json, 0, start.length);
+ System.arraycopy(middle, 0, json, start.length, middle.length);
+ System.arraycopy(end, 0, json, start.length + middle.length,
end.length);
+ return json;
+ }
+
+ @Test
+ void testOneReader() {
+ // the reader is stateless, as the instances of the generated code
share it
+ final VariantPathReader reader = new VariantPathReader(PATHS);
+ Stream.concat(documents(), invalidUtf8())
+ .forEach(
+ arguments ->
+ assertSame(
+ reader,
+ (byte[]) arguments.get()[0],
+ (Boolean) arguments.get()[1]));
+ }
Review Comment:
Nit: this test runs the whole matrix again through one shared reader. If the
two-argument `assertSame` used one static reader, the matrix itself would cover
reuse, and this test could go. Separately, `assertSame` reads like JUnit's
identity assertion. A name like `assertReadsLikeFullParse` would say what it
checks.
##########
flink-core/src/main/java/org/apache/flink/types/variant/BinaryVariantInternalBuilder.java:
##########
@@ -140,6 +140,11 @@ public static BinaryVariant parseJson(byte[] bytes,
boolean allowDuplicateKeys)
}
}
Review Comment:
Should these also use the new `createParser` method?
##########
flink-table/flink-table-planner/src/test/java/org/apache/flink/table/planner/functions/VariantFunctionsITCase.java:
##########
@@ -56,7 +56,54 @@ Configuration getConfiguration() {
@Override
Stream<TestSetSpec> getTestSetSpecs() {
- return Stream.of(variantGet(), variantGetFailure(), tryVariantGet(),
unreadableVariant());
+ return Stream.of(
+ variantGet(),
+ variantGetFailure(),
+ tryVariantGet(),
+ unreadableVariant(),
+ literalPathAccess());
+ }
+
+ // only read at literal paths, so the document is parsed without building
the rest of it
+ private static TestSetSpec literalPathAccess() {
Review Comment:
Three cases here are covered in the unit tests. Should we drop them?
```
.testSqlResult("CAST(PARSE_JSON(f0)['book']['title'] AS STRING)", "Moby
Dick", STRING()) // case A
...
// two paths of one parse
.testSqlResult("CAST(PARSE_JSON(f0)['book']['title'] AS STRING)"
+ " || CAST(PARSE_JSON(f0)['book']['year'] AS STRING)", "Moby
Dick1851", STRING()) // case B
...
.testSqlRuntimeError("CAST(PARSE_JSON(f2)['book'][1] AS STRING)", ...,
// case C
"Integer index access on variant requires an array variant, but a
non-array variant was provided.");
```
##########
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/functions/VariantPathReader.java:
##########
@@ -0,0 +1,220 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.flink.table.runtime.functions;
+
+import org.apache.flink.annotation.Internal;
+import org.apache.flink.table.data.StringData;
+import org.apache.flink.types.variant.BinaryVariantInternalBuilder;
+import org.apache.flink.types.variant.Variant;
+
+import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.core.JsonParser;
+import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.core.JsonToken;
+
+import javax.annotation.Nullable;
+
+import java.io.IOException;
+import java.io.Serializable;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * Parses JSON like {@code PARSE_JSON}, but builds only what fixed {@code
[key]} and {@code [index]}
+ * paths reach: values at path ends in full, objects on the way with the
needed keys only, and
+ * arrays on the way with nulls for unneeded elements. The rest is only
checked, so a document fails
+ * as in {@code PARSE_JSON}.
+ *
+ * <p>The result has its own field name dictionary, and the size limit applies
to it, not to the
+ * whole document.
+ */
+@Internal
+public final class VariantPathReader implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ // read-only, so the reader is stateless
+ private final Node root = new Node();
+
+ /**
+ * @param paths the steps of each path: a {@link String} for {@code
[key]}, a 0-based {@link
+ * Integer} for {@code [index]}
+ */
+ public VariantPathReader(Object[][] paths) {
+ for (Object[] path : paths) {
+ Node node = root;
+ for (Object step : path) {
+ node = node.child(step);
+ }
+ node.isEnd = true;
+ }
+ }
+
+ /**
+ * Parses {@code json} for the paths. Fails as {@link
SqlJsonUtils#parseJsonToVariant}, except
+ * for the size limit.
+ */
+ public Variant parse(StringData json, boolean allowDuplicateKeys) throws
IOException {
+ final byte[] bytes = json.toBytes();
+ final Parsing parsing = new Parsing(allowDuplicateKeys);
+ for (byte b : bytes) {
+ if (b == '\\') {
+ parsing.hasEscapes = true;
+ break;
+ }
+ }
+ try (JsonParser parser =
BinaryVariantInternalBuilder.createParser(bytes)) {
+ parser.nextToken();
+ // an empty document fails in the builder, as in the full parse
+ parsing.read(parser, root, 0);
+ return parsing.builder.build();
+ }
+ }
+
+ /** The state of one parse. */
+ private static final class Parsing {
+ private static final int MAX_CLEARED_KEYS = 64;
+
+ private final boolean allowDuplicateKeys;
+ private final BinaryVariantInternalBuilder builder;
+ // an unpaired surrogate in a key needs a \\u escape
+ private boolean hasEscapes;
+ // keys of the open objects, by depth, to find duplicates
+ private final List<Set<String>> keysByDepth = new ArrayList<>();
+
+ private Parsing(boolean allowDuplicateKeys) {
+ this.allowDuplicateKeys = allowDuplicateKeys;
+ this.builder = new
BinaryVariantInternalBuilder(allowDuplicateKeys);
+ }
+
+ // builds the value at node; without a node, only checks it
+ private void read(JsonParser parser, @Nullable Node node, int depth)
throws IOException {
+ final JsonToken token = parser.currentToken();
+ final boolean container =
+ token == JsonToken.START_OBJECT || token ==
JsonToken.START_ARRAY;
+ if (node != null && (node.isEnd || !container)) {
+ // a path end, or a scalar on the way, so a deeper step fails
as before
+ builder.appendJson(parser);
+ return;
+ }
+ if (!container) {
+ builder.checkJsonScalar(parser);
+ return;
+ }
+ final int start = builder.getWritePos();
+ if (token == JsonToken.START_OBJECT) {
+ final Set<String> keys = allowDuplicateKeys ? null :
keysAt(depth);
+ final ArrayList<BinaryVariantInternalBuilder.FieldEntry>
fields =
+ node == null ? null : new ArrayList<>();
+ boolean duplicate = false;
+ while (parser.nextToken() != JsonToken.END_OBJECT) {
+ final String name = parser.currentName();
+ final String key = keyOf(name);
Review Comment:
Jackson already rejects lone-surrogate keys in both parses, so `keyOf` and
its loop never change a key and only adds costs.
I'd drop `hasEscapes`, that loop and `keyOf`, and keep the `storedKey` call
in `Node.child`
##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/codegen/SelectiveParseJsonCodeGen.java:
##########
@@ -0,0 +1,243 @@
+/*
+ * 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.flink.table.planner.codegen;
+
+import org.apache.flink.table.functions.BuiltInFunctionDefinitions;
+import org.apache.flink.table.functions.FunctionDefinition;
+import org.apache.flink.table.planner.calcite.FlinkTypeFactory;
+import org.apache.flink.table.planner.functions.bridging.BridgingSqlFunction;
+import org.apache.flink.table.runtime.functions.VariantPathReader;
+import org.apache.flink.table.types.logical.LogicalTypeRoot;
+import org.apache.flink.table.types.logical.utils.LogicalTypeChecks;
+
+import org.apache.calcite.rex.RexCall;
+import org.apache.calcite.rex.RexLiteral;
+import org.apache.calcite.rex.RexLocalRef;
+import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.rex.RexProgram;
+import org.apache.calcite.sql.SqlKind;
+import org.apache.calcite.sql.type.SqlTypeFamily;
+
+import javax.annotation.Nullable;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * Picks a {@link VariantPathReader} for {@code PARSE_JSON} and {@code
TRY_PARSE_JSON} calls whose
+ * results are only read at literal {@code [key]} and {@code [index]} paths,
by a {@code CAST} to a
+ * type without VARIANT or by {@code JSON_STRING}. Those don't depend on the
field name dictionary,
+ * which differs from the full parse.
+ *
+ * <p>Calls of one input and {@code allowDuplicateKeys} share a parse, so all
of them qualify or
+ * none. Anything else parses in full.
+ */
+final class SelectiveParseJsonCodeGen {
+
+ private final CodeGeneratorContext ctx;
+ private final RexProgram program;
+
+ // parse call -> its group, if it qualifies
+ private final Map<RexCall, Group> readers = new HashMap<>();
Review Comment:
Nit: this map holds groups, not readers, so a name like `groupOfCall` reads
better. Also, `literalStep`, `chainOf` and `Group.term` can return or hold null
like `parseKeyOf`, so they could carry `@Nullable` too.
##########
flink-core/src/main/java/org/apache/flink/types/variant/BinaryVariantInternalBuilder.java:
##########
@@ -856,38 +898,32 @@ private int getIntegerSize(int value) {
return U24_SIZE;
}
- private void parseFloatingPoint(JsonParser parser) throws IOException {
- if (!tryParseDecimal(parser.getText())) {
- final double d = parser.getDoubleValue();
- // Jackson coerces out-of-range numbers like 1e400 to +/-Infinity.
Reject them instead
- // of storing a non-finite double that toJson() could not render
as valid JSON.
- if (Double.isInfinite(d) || Double.isNaN(d)) {
- throw new JsonParseException(
- parser,
- String.format(
- "Numeric value '%s' is out of the range of
double precision and cannot be stored as a Variant.",
- parser.getText()));
- }
- appendDouble(d);
+ private static double finiteDouble(JsonParser parser) throws IOException {
+ final double d = parser.getDoubleValue();
+ // Jackson coerces out-of-range numbers like 1e400 to +/-Infinity.
Reject them instead
+ // of storing a non-finite double that toJson() could not render as
valid JSON.
+ if (Double.isInfinite(d) || Double.isNaN(d)) {
+ throw new JsonParseException(
+ parser,
+ String.format(
+ "Numeric value '%s' is out of the range of double
precision and cannot be stored as a Variant.",
+ parser.getText()));
}
+ return d;
}
- // Try to parse a JSON number as a decimal. Return whether the parsing
succeeds. The input must
- // only use the decimal format (an integer value with an optional '.' in
it) and must not use
- // scientific notation. It also must fit into the precision limitation of
decimal types.
- private boolean tryParseDecimal(String input) {
+ // The JSON number as a decimal, or null. The input must only use the
decimal format (an integer
+ // value with an optional '.' in it) and must not use scientific notation.
It also must fit into
+ // the precision limitation of decimal types.
+ private static BigDecimal decimalOf(String input) {
Review Comment:
add `@Nullable`
##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/codegen/SelectiveParseJsonCodeGen.java:
##########
@@ -0,0 +1,243 @@
+/*
+ * 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.flink.table.planner.codegen;
+
+import org.apache.flink.table.functions.BuiltInFunctionDefinitions;
+import org.apache.flink.table.functions.FunctionDefinition;
+import org.apache.flink.table.planner.calcite.FlinkTypeFactory;
+import org.apache.flink.table.planner.functions.bridging.BridgingSqlFunction;
+import org.apache.flink.table.runtime.functions.VariantPathReader;
+import org.apache.flink.table.types.logical.LogicalTypeRoot;
+import org.apache.flink.table.types.logical.utils.LogicalTypeChecks;
+
+import org.apache.calcite.rex.RexCall;
+import org.apache.calcite.rex.RexLiteral;
+import org.apache.calcite.rex.RexLocalRef;
+import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.rex.RexProgram;
+import org.apache.calcite.sql.SqlKind;
+import org.apache.calcite.sql.type.SqlTypeFamily;
+
+import javax.annotation.Nullable;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * Picks a {@link VariantPathReader} for {@code PARSE_JSON} and {@code
TRY_PARSE_JSON} calls whose
+ * results are only read at literal {@code [key]} and {@code [index]} paths,
by a {@code CAST} to a
+ * type without VARIANT or by {@code JSON_STRING}. Those don't depend on the
field name dictionary,
+ * which differs from the full parse.
+ *
+ * <p>Calls of one input and {@code allowDuplicateKeys} share a parse, so all
of them qualify or
+ * none. Anything else parses in full.
+ */
+final class SelectiveParseJsonCodeGen {
+
+ private final CodeGeneratorContext ctx;
+ private final RexProgram program;
+
+ // parse call -> its group, if it qualifies
+ private final Map<RexCall, Group> readers = new HashMap<>();
+
+ SelectiveParseJsonCodeGen(CodeGeneratorContext ctx, RexProgram program) {
+ this.ctx = ctx;
+ this.program = program;
+ analyze();
+ }
+
+ /** The term of the reader that parses the call's input, or null for the
full parse. */
+ @Nullable
+ String readerOf(RexCall call) {
+ final Group group = readers.get(call);
+ if (group == null) {
+ return null;
+ }
+ if (group.term == null) {
+ final Object[][] paths =
+
group.steps.stream().map(List::toArray).toArray(Object[][]::new);
+ // stateless, so shared by all instances of the generated class
+ group.term =
+ ctx.addReusableObject(new VariantPathReader(paths),
"variantPathReader", null);
+ }
+ return group.term;
+ }
+
+ private void analyze() {
+ final List<RexNode> exprs = program.getExprList();
+ final int inputCount = program.getInputRowType().getFieldCount();
+ // calls by input and allowDuplicateKeys, as the full parse shares them
+ final Map<List<Object>, Group> groups = new LinkedHashMap<>();
+ // local ref -> its group and its steps
+ final Map<Integer, Chain> chains = new HashMap<>();
+
+ for (int k = inputCount; k < exprs.size(); k++) {
+ final RexNode expr = exprs.get(k);
+ if (!(expr instanceof RexCall)) {
+ continue;
+ }
+ final RexCall call = (RexCall) expr;
+ final List<Object> key = parseKeyOf(call);
+ if (key != null) {
+ final Group group = groups.computeIfAbsent(key, ignored -> new
Group());
+ group.calls.add(call);
+ chains.put(k, new Chain(group, new Object[0]));
+ continue;
+ }
+ final List<RexNode> operands = call.getOperands();
+ for (int i = 0; i < operands.size(); i++) {
+ final Chain chain = chainOf(operands.get(i), chains);
+ if (chain == null) {
+ continue;
+ }
+ if (call.getKind() == SqlKind.ITEM && i == 0) {
+ final Object step = literalStep(operands.get(1));
+ if (step == null) {
+ chain.group.full = true;
+ } else {
+ chains.put(k, chain.then(step));
+ }
+ } else if (chain.steps.length > 0 && readsValueOnly(call)) {
+ chain.group.steps.add(Arrays.asList(chain.steps));
+ } else {
+ chain.group.full = true;
+ }
+ }
+ }
+ // a parse or a path as a result
+ final List<RexNode> roots = new ArrayList<>(program.getProjectList());
+ if (program.getCondition() != null) {
+ roots.add(program.getCondition());
+ }
+ for (RexNode root : roots) {
+ final Chain chain = chainOf(root, chains);
+ if (chain != null) {
+ chain.group.full = true;
+ }
+ }
+
+ for (Group group : groups.values()) {
+ if (!group.full && !group.steps.isEmpty()) {
+ for (RexCall call : group.calls) {
+ readers.put(call, group);
+ }
+ }
+ }
+ }
+
+ // input and allowDuplicateKeys of [TRY_]PARSE_JSON(json[, <literal>]), or
null
+ @Nullable
+ private List<Object> parseKeyOf(RexCall call) {
+ if (!(call.getOperator() instanceof BridgingSqlFunction)) {
+ return null;
+ }
+ final FunctionDefinition definition =
+ ((BridgingSqlFunction) call.getOperator()).getDefinition();
Review Comment:
use `ShortcutUtils.unwrapFunctionDefinition` instead
--
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]