You are viewing a plain text version of this content. The canonical link for it is here.
Posted to issues@flink.apache.org by "raminqaf (via GitHub)" <gi...@apache.org> on 2026/10/02 14:20:34 UTC
[PR] [FLINK-40826][table] Support casting ARRAY, MAP, ROW and STRUCTURED to VARIANT [flink]
raminqaf opened a new pull request, #29369:
URL: https://github.com/apache/flink/pull/29369
## What is the purpose of the change
FLINK-40825 added `CAST` from primitive types to VARIANT. This PR casts a whole ARRAY, MAP, ROW or STRUCTURED value into one VARIANT. An ARRAY becomes a variant array, and a MAP, ROW or STRUCTURED value a variant object. Every leaf is stored the same way the cast stores it on its own.
| Expression | Result |
|-------------------------------------------------------------------|--------------------------------------------------------------|
| `CAST(ARRAY[1, NULL] AS VARIANT)` | `[1, null]`, the `NULL` becomes a variant null |
| `CAST(MAP['a', 1, 'b', 2] AS VARIANT)` | `{"a": 1, "b": 2}` |
| `CAST(r AS VARIANT)` for `r ROW<name STRING, id BIGINT>` | `{"id": 7, "name": "ada"}`, keys sorted, `id` a BIGINT |
| `CAST(ROW(1, 'a') AS VARIANT)` | `{"EXPR$0": 1, "EXPR$1": "a"}` |
| `CAST(CAST(ROW(1, 'a') AS ROW<id INT, name STRING>) AS VARIANT)` | `{"id": 1, "name": "a"}` |
| `CAST(ARRAY[PARSE_JSON(s)['a'], PARSE_JSON(s)['b']] AS VARIANT)` | the nested VARIANTs embedded as is |
| `CAST(MAP[NULLIF(s, 'x'), 1] AS VARIANT)` with a `NULL` key | fails, and `TRY_CAST` returns `NULL` |
| `CAST(MAP[1, 'a'] AS VARIANT)` | fails at validation, a key must be a character string |
## Brief change log
- Commit 1, `[core]`: `BinaryVariantInternalBuilder#appendVariant` read a nested variant, such as the result of `getField` or `getElement`, at its old position inside a copy that starts at 0. Embedding such a value failed with `MALFORMED_VARIANT` or silently wrote a wrong value. This also affected the public `VariantBuilder`. It now reads the shared buffer at the variant's own position.
- Commit 2: `VariantCastUtils` gets `appendTimestamp` and `appendTimestampLtz`, which write a timestamp into a shared builder. No behavior change.
- Commit 3:
- `LogicalTypeCasts` allows ARRAY, MAP, ROW and STRUCTURED to VARIANT when every leaf casts. A MAP key must be a character string and is never converted. MULTISET stays rejected.
- New `ToVariantConverter` in flink-table-runtime. It is built once per type and writes the whole value into one builder, so a nested value is encoded in a single pass. It lives next to `VariantCastUtils` so that formats can reuse it.
- New `ConstructedToVariantCastRule`. The generated code is one `converter.convert(input)` call.
- New `CodeGeneratorCastRule.Context#declareReusableObject`, so a rule can hand an object to the generated code. The standalone `CastExecutor` passes it to its constructor, like the type serializers.
- Docs: a section on casting a whole value, and the VARIANT column of the cast matrix.
Notes for reviewers:
- A ROW is keyed by the field names of its type. The SQL `ROW` constructor names them `EXPR$0`, `EXPR$1`, and the Table API `row()` names them `f0`, `f1`. A ROW type always carries names, so generated names cannot be told apart from chosen ones. `JSON_STRING` uses the names of the type the same way, and a cast back to ROW matches by name, so the round trip holds. The docs show how to name the fields with `CAST(... AS ROW<...>)` or `as()` in the Table API.
- A variant object sorts its keys, so the field order of a ROW is not kept.
- Building each node as its own VARIANT and copying it into its parent re-encodes every subtree once per level. In a micro benchmark that was 5 times slower on a typical nested row, and up to 30 times on deep nesting. The converter writes the leaves straight into one builder. As a tree of writers it costs about 12% over fully inlined code, but it keeps the generated code to one call for wide schemas, and formats can reuse it.
- A `MapData` can hold the same key twice at runtime. The last value wins, like in the MAP constructor.
- `canFail` is always true for ARRAY and MAP, since their size has no bound. For a ROW it is true when a leaf can fail, or when the declared sizes of its fields can exceed 16 MiB.
- A SQL `NULL` in a `VARIANT` field becomes a variant null, so the cast back to ROW returns a variant null for it, not SQL `NULL`. The docs say so.
- Not new: walking a VARIANT recurses once per nesting level, so embedding a VARIANT nested about 2,000 levels deep overflows a 1 MiB stack, as `toJson()` already does. `TRY_CAST` returns `NULL` in that case. I will track this in a separate ticket.
## Verifying this change
This change added tests and can be verified as follows:
- `BinaryVariantInternalBuilderTest` embeds a field and an element of another variant through `VariantBuilder`. It failed before the fix.
- `ToVariantConverterTest` covers the kind of every leaf, `NULL` values and `NULL` element types, empty values, duplicate and `NULL` map keys, an embedded VARIANT that does not start at position 0, STRUCTURED and DISTINCT types, the size limit, the nanosecond range of timestamps, and Java serialization of the converter.
- `LogicalTypeCastsTest` covers the allowed and rejected shapes.
- `CastRuleProviderTest` covers rule resolution and `canFail`, including the 16 MiB boundary for a ROW.
- `CastRulesTest` covers the standalone `CastExecutor` path, with byte-exact results.
- `CastFunctionITCase` covers SQL and Table API round trips, the field names of a ROW constructor and how to choose them, embedded VARIANTs, a `NULL` map key, the size limit with `TRY_CAST`, and the validation errors.
## Does this pull request potentially affect one of the following parts:
- Dependencies (does it add or upgrade a dependency): no
- The public API, i.e., is any changed class annotated with `@Public(Evolving)`: no. The `appendVariant` fix changes the behavior of `VariantBuilder`, which is `@PublicEvolving`, but not its API.
- The serializers: no
- The runtime per-record code paths (performance sensitive): yes. The new cast runs per record and builds one VARIANT per value.
- Anything that affects deployment or recovery: JobManager (and its components), Checkpointing, Kubernetes/Yarn, ZooKeeper: no
- The S3 file system connector: no
## Documentation
- Does this pull request introduce a new feature? yes
- If yes, how is the feature documented? docs, in `data-types.md` (English and Chinese)
---
##### Was generative AI tooling used to co-author this PR?
- [X] Yes (please specify the tool below)
Generated-by: Opus 5.5
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-40826][table] Support casting ARRAY, MAP, ROW and STRUCTURED to VARIANT [flink]
Posted by "AHeise (via GitHub)" <gi...@apache.org>.
AHeise commented on code in PR #29369:
URL: https://github.com/apache/flink/pull/29369#discussion_r4181315118
##########
flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/logical/utils/LogicalTypeCasts.java:
##########
@@ -730,6 +730,23 @@ private static boolean supportsCasting(
return allowExplicit
&& mapChildren.get(0).is(CHARACTER_STRING)
&& supportsCasting(sourceType, mapChildren.get(1), true);
+ } else if (targetRoot == VARIANT
Review Comment:
Keying a ROW by its type's field names means `CAST(ROW(id, name) AS VARIANT)` produces `{"EXPR$0": ..., "EXPR$1": ...}`, even though both operands are column references. I'd expect that to be the most common way to write it. The same query in the Table API gives `f0`/`f1`, and `EXPR$N` is a Calcite naming detail we don't control. Once released, these keys become a data contract that ends up in sinks.
FLIP-521 does list ROW and STRUCTURED as castable to VARIANT, so CAST itself is fine. For comparison, Spark rejects `CAST(struct AS VARIANT)` and offers `to_variant_object`, documented as "maps and structs are converted to variant objects which are unordered unlike SQL structs".
I'm not asking to change the approach in this PR, but I'd like the `EXPR$N` keys to be a conscious decision on the ML rather than an emergent one. Options: reject a ROW constructor without explicit names, document it more prominently, or add a dedicated object-building function later. WDYT?
##########
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/functions/ToVariantConverter.java:
##########
@@ -0,0 +1,260 @@
+/*
+ * 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.api.TableRuntimeException;
+import org.apache.flink.table.data.ArrayData;
+import org.apache.flink.table.data.DecimalData;
+import org.apache.flink.table.data.MapData;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.data.TimestampData;
+import org.apache.flink.table.types.logical.ArrayType;
+import org.apache.flink.table.types.logical.DistinctType;
+import org.apache.flink.table.types.logical.LogicalType;
+import org.apache.flink.table.types.logical.LogicalTypeRoot;
+import org.apache.flink.table.types.logical.MapType;
+import org.apache.flink.table.types.logical.utils.LogicalTypeChecks;
+import org.apache.flink.table.types.logical.utils.UuidUtils;
+import org.apache.flink.types.variant.BinaryVariant;
+import org.apache.flink.types.variant.BinaryVariantInternalBuilder;
+import org.apache.flink.types.variant.BinaryVariantInternalBuilder.FieldEntry;
+import org.apache.flink.types.variant.Variant;
+import org.apache.flink.types.variant.VariantTypeException;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Converts internal data of a SQL type into a {@link Variant}, like {@code CAST(x AS VARIANT)}.
+ *
+ * <p>An {@code ARRAY} becomes a variant array. A {@code ROW} or {@code STRUCTURED} value becomes a
+ * variant object keyed by its field names, and a {@code MAP} one keyed by its character string
+ * keys. A {@code NULL} element, field or map value becomes a variant null. A leaf is stored like
+ * the cast stores it on its own, see {@link VariantCastUtils}, and a nested {@code VARIANT} is
+ * embedded as is.
+ *
+ * <p>The converter is created once per type and writes a whole value into one builder, so a nested
+ * value is encoded in a single pass. It keeps no state between calls.
+ */
+@Internal
+public final class ToVariantConverter implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ private final String sourceType;
+ private final ValueWriter writer;
+
+ private ToVariantConverter(String sourceType, ValueWriter writer) {
+ this.sourceType = sourceType;
+ this.writer = writer;
+ }
+
+ /** Creates a converter for a type that {@code LogicalTypeCasts} allows to cast to VARIANT. */
+ public static ToVariantConverter create(LogicalType type) {
+ return new ToVariantConverter(type.asSummaryString(), createWriter(type));
+ }
+
+ /**
+ * Converts a value that is not {@code NULL}.
+ *
+ * @throws TableRuntimeException if the value has a {@code NULL} map key, a timestamp outside
+ * the range of its variant kind, or does not fit into the 16 MiB of a {@code VARIANT}
+ */
+ public Variant convert(Object value) {
+ // A MAP can hold the same key twice at runtime. The builder keeps the last one, like the
+ // MAP constructor does.
+ final BinaryVariantInternalBuilder builder = new BinaryVariantInternalBuilder(true);
+ try {
+ writer.write(builder, value);
+ return builder.build();
+ } catch (VariantTypeException e) {
+ if (e != BinaryVariantInternalBuilder.VARIANT_SIZE_LIMIT_EXCEPTION) {
+ throw e;
+ }
+ throw new TableRuntimeException(
+ String.format(
+ "Cannot cast a value of type %s to VARIANT. A VARIANT is limited to "
+ + "16 MiB.",
+ sourceType));
+ }
+ }
+
+ @FunctionalInterface
+ private interface ValueWriter extends Serializable {
+ void write(BinaryVariantInternalBuilder builder, Object value);
+ }
+
+ private static ValueWriter createNullableWriter(LogicalType type) {
+ final ValueWriter writer = createWriter(type);
+ return (builder, value) -> {
+ if (value == null) {
+ builder.appendNull();
+ } else {
+ writer.write(builder, value);
+ }
+ };
+ }
+
+ private static ValueWriter createWriter(LogicalType type) {
Review Comment:
This switch encodes every leaf a second time, next to `VariantCastUtils.fromXxx`, which `PrimitiveToVariantCastRule` uses. The two match today; I compared the bytes for TIMESTAMP(3), TIMESTAMP(9), TIME, CHAR(4), DECIMAL(38, 0) and DECIMAL(10, 4). But any change, such as the deferred UTF-8 byte path for strings from #29311, now has to happen in two places, and drift would make `CAST(x AS VARIANT)` differ from `x` inside `CAST(ARRAY[x] AS VARIANT)`.
Could we keep one source of truth? Either `fromXxx` delegates to append helpers as commit 2 does for timestamps, or `PrimitiveToVariantCastRule` uses `ToVariantConverter.create(type)` for primitives too.
##########
docs/content/docs/sql/reference/data-types.md:
##########
@@ -1725,7 +1725,38 @@ CAST(NULL AS VARIANT) -- NULL
CAST(CAST('NaN' AS DOUBLE) AS VARIANT) -- NaN, stored as a DOUBLE
CAST(INTERVAL '2' DAY AS VARIANT) -- fails at validation
CAST(ARRAY[1, NULL] AS ARRAY<VARIANT>) -- [1, NULL], each element a VARIANT, the NULL stays SQL NULL
-CAST(ARRAY[1, 2] AS VARIANT) -- fails at validation, not supported yet
+```
+
+A whole `ARRAY`, `MAP`, `ROW`, or `STRUCTURED` value can also be cast into a single `VARIANT`. An
Review Comment:
nit: FLIP-521 lists ARRAY, ROW and STRUCTURED as castable to and from VARIANT, but not MAP. VARIANT to MAP already exists, so this is symmetric and I'm fine with it. It may be worth a line on the ML or a FLIP update so the doc stays the reference.
##########
flink-core/src/main/java/org/apache/flink/types/variant/BinaryVariantInternalBuilder.java:
##########
@@ -537,7 +537,9 @@ public void finishWritingArray(int start, ArrayList<Integer> offsets) {
// the
// input variant, we can directly copy the binary slice.
public void appendVariant(BinaryVariant v) {
- appendVariantImpl(v.getValue(), v.getMetadata(), v.getPos());
+ // A nested variant, such as a field or an element of another variant, starts at its own
+ // position in the shared buffer. getValue() would copy it to position 0 instead.
+ appendVariantImpl(v.rawValue(), v.getMetadata(), v.getPos());
Review Comment:
This fix is independent of the cast, and `VariantBuilder` is `@PublicEvolving`. Every released version with VARIANT ships the bug. Could you give it its own JIRA so it can be backported?
Related but pre-existing, so a separate ticket: `BinaryVariant#hashCode` hashes the whole underlying buffer, while `equals` compares the slice and `pos`. Two equal nested variants can therefore have different hash codes. Embedding nested values makes such variants more common.
##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/casting/AbstractCodeGeneratorCastRule.java:
##########
@@ -95,7 +96,7 @@ public CastExecutor<IN, OUT> create(
"public "
+ castExecutorClassName
+ "("
- + ctx.typeSerializers.values().stream()
+ + constructorFields.entrySet().stream()
.map(
entry ->
className(entry.getValue().getClass())
Review Comment:
nit: The constructor parameter type comes from `entry.getValue().getClass()`, and `ScalarOperatorGens` uses `getCanonicalName()` through `addReusableObject`. Both break for a lambda, an anonymous class or a non-public class. This only works because `ToVariantConverter` is public and final. Maybe let `declareReusableObject` take the declared type, or state the restriction in its Javadoc.
##########
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/functions/ToVariantConverter.java:
##########
@@ -0,0 +1,260 @@
+/*
+ * 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.api.TableRuntimeException;
+import org.apache.flink.table.data.ArrayData;
+import org.apache.flink.table.data.DecimalData;
+import org.apache.flink.table.data.MapData;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.data.TimestampData;
+import org.apache.flink.table.types.logical.ArrayType;
+import org.apache.flink.table.types.logical.DistinctType;
+import org.apache.flink.table.types.logical.LogicalType;
+import org.apache.flink.table.types.logical.LogicalTypeRoot;
+import org.apache.flink.table.types.logical.MapType;
+import org.apache.flink.table.types.logical.utils.LogicalTypeChecks;
+import org.apache.flink.table.types.logical.utils.UuidUtils;
+import org.apache.flink.types.variant.BinaryVariant;
+import org.apache.flink.types.variant.BinaryVariantInternalBuilder;
+import org.apache.flink.types.variant.BinaryVariantInternalBuilder.FieldEntry;
+import org.apache.flink.types.variant.Variant;
+import org.apache.flink.types.variant.VariantTypeException;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Converts internal data of a SQL type into a {@link Variant}, like {@code CAST(x AS VARIANT)}.
+ *
+ * <p>An {@code ARRAY} becomes a variant array. A {@code ROW} or {@code STRUCTURED} value becomes a
+ * variant object keyed by its field names, and a {@code MAP} one keyed by its character string
+ * keys. A {@code NULL} element, field or map value becomes a variant null. A leaf is stored like
+ * the cast stores it on its own, see {@link VariantCastUtils}, and a nested {@code VARIANT} is
+ * embedded as is.
+ *
+ * <p>The converter is created once per type and writes a whole value into one builder, so a nested
Review Comment:
nit: "encoded in a single pass" isn't quite exact. Each `finishWritingObject`/`finishWritingArray` shifts its data to make room for the header, so the bytes move once per nesting level. That's still far cheaper than re-encoding every subtree. Maybe "without re-encoding nested values"?
##########
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/functions/ToVariantConverter.java:
##########
@@ -0,0 +1,260 @@
+/*
+ * 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.api.TableRuntimeException;
+import org.apache.flink.table.data.ArrayData;
+import org.apache.flink.table.data.DecimalData;
+import org.apache.flink.table.data.MapData;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.data.TimestampData;
+import org.apache.flink.table.types.logical.ArrayType;
+import org.apache.flink.table.types.logical.DistinctType;
+import org.apache.flink.table.types.logical.LogicalType;
+import org.apache.flink.table.types.logical.LogicalTypeRoot;
+import org.apache.flink.table.types.logical.MapType;
+import org.apache.flink.table.types.logical.utils.LogicalTypeChecks;
+import org.apache.flink.table.types.logical.utils.UuidUtils;
+import org.apache.flink.types.variant.BinaryVariant;
+import org.apache.flink.types.variant.BinaryVariantInternalBuilder;
+import org.apache.flink.types.variant.BinaryVariantInternalBuilder.FieldEntry;
+import org.apache.flink.types.variant.Variant;
+import org.apache.flink.types.variant.VariantTypeException;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Converts internal data of a SQL type into a {@link Variant}, like {@code CAST(x AS VARIANT)}.
+ *
+ * <p>An {@code ARRAY} becomes a variant array. A {@code ROW} or {@code STRUCTURED} value becomes a
+ * variant object keyed by its field names, and a {@code MAP} one keyed by its character string
+ * keys. A {@code NULL} element, field or map value becomes a variant null. A leaf is stored like
+ * the cast stores it on its own, see {@link VariantCastUtils}, and a nested {@code VARIANT} is
+ * embedded as is.
+ *
+ * <p>The converter is created once per type and writes a whole value into one builder, so a nested
+ * value is encoded in a single pass. It keeps no state between calls.
+ */
+@Internal
+public final class ToVariantConverter implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ private final String sourceType;
+ private final ValueWriter writer;
+
+ private ToVariantConverter(String sourceType, ValueWriter writer) {
+ this.sourceType = sourceType;
+ this.writer = writer;
+ }
+
+ /** Creates a converter for a type that {@code LogicalTypeCasts} allows to cast to VARIANT. */
+ public static ToVariantConverter create(LogicalType type) {
+ return new ToVariantConverter(type.asSummaryString(), createWriter(type));
+ }
+
+ /**
+ * Converts a value that is not {@code NULL}.
+ *
+ * @throws TableRuntimeException if the value has a {@code NULL} map key, a timestamp outside
+ * the range of its variant kind, or does not fit into the 16 MiB of a {@code VARIANT}
+ */
+ public Variant convert(Object value) {
+ // A MAP can hold the same key twice at runtime. The builder keeps the last one, like the
+ // MAP constructor does.
+ final BinaryVariantInternalBuilder builder = new BinaryVariantInternalBuilder(true);
+ try {
+ writer.write(builder, value);
+ return builder.build();
+ } catch (VariantTypeException e) {
+ if (e != BinaryVariantInternalBuilder.VARIANT_SIZE_LIMIT_EXCEPTION) {
+ throw e;
+ }
+ throw new TableRuntimeException(
+ String.format(
+ "Cannot cast a value of type %s to VARIANT. A VARIANT is limited to "
+ + "16 MiB.",
+ sourceType));
+ }
+ }
+
+ @FunctionalInterface
+ private interface ValueWriter extends Serializable {
+ void write(BinaryVariantInternalBuilder builder, Object value);
+ }
+
+ private static ValueWriter createNullableWriter(LogicalType type) {
+ final ValueWriter writer = createWriter(type);
+ return (builder, value) -> {
+ if (value == null) {
+ builder.appendNull();
+ } else {
+ writer.write(builder, value);
+ }
+ };
+ }
+
+ private static ValueWriter createWriter(LogicalType type) {
+ switch (type.getTypeRoot()) {
+ case NULL:
+ return (builder, value) -> builder.appendNull();
+ case BOOLEAN:
+ return (builder, value) -> builder.appendBoolean((Boolean) value);
+ case TINYINT:
+ return (builder, value) -> builder.appendByte((Byte) value);
+ case SMALLINT:
+ return (builder, value) -> builder.appendShort((Short) value);
+ case INTEGER:
+ return (builder, value) -> builder.appendInt((Integer) value);
+ case BIGINT:
+ return (builder, value) -> builder.appendLong((Long) value);
+ case FLOAT:
+ return (builder, value) -> builder.appendFloat((Float) value);
+ case DOUBLE:
+ return (builder, value) -> builder.appendDouble((Double) value);
+ case DECIMAL:
+ return (builder, value) ->
+ builder.appendDecimal(((DecimalData) value).toBigDecimal());
+ case CHAR:
+ case VARCHAR:
+ return (builder, value) -> builder.appendString(value.toString());
+ case BINARY:
+ case VARBINARY:
+ return (builder, value) -> builder.appendBinary((byte[]) value);
+ case DATE:
+ return (builder, value) -> builder.appendDate((Integer) value);
+ case TIME_WITHOUT_TIME_ZONE:
+ // TIME is millisecond-of-day at runtime, the variant kind holds microseconds.
+ return (builder, value) -> builder.appendTime((Integer) value * 1_000L);
+ case TIMESTAMP_WITHOUT_TIME_ZONE:
+ {
+ final int precision = LogicalTypeChecks.getPrecision(type);
+ return (builder, value) ->
+ VariantCastUtils.appendTimestamp(
+ builder, (TimestampData) value, precision);
+ }
+ case TIMESTAMP_WITH_LOCAL_TIME_ZONE:
+ {
+ final int precision = LogicalTypeChecks.getPrecision(type);
+ return (builder, value) ->
+ VariantCastUtils.appendTimestampLtz(
+ builder, (TimestampData) value, precision);
+ }
+ case UUID:
+ return (builder, value) -> builder.appendUuid(UuidUtils.fromBytes((byte[]) value));
+ case VARIANT:
Review Comment:
Embedding a deeply nested VARIANT recurses once per level in `appendVariantImpl`, so around 2,000 levels overflow the stack. `TRY_CAST` catches it because the generated try/catch takes `Throwable`, but plain `CAST` throws a `StackOverflowError`. `ExceptionUtils.isJvmFatalError` doesn't treat it as fatal, so the task fails over and restarts on the same record forever. That's a poison pill with no useful error message. `PARSE_JSON` is bounded by Jackson's nesting limit, but a VARIANT from a UDF using `VariantBuilder`, a format converter, or a view that wraps a VARIANT per level is not.
I agree `toJson()` has the same problem, but this PR adds a new per-record path that can hit it. Could we at least catch `StackOverflowError` in `convert` and rethrow it as a `TableRuntimeException` naming the nesting depth? A depth limit or an iterative `appendVariantImpl` can be the separate ticket; please link it here.
##########
docs/content/docs/sql/reference/data-types.md:
##########
@@ -1725,7 +1725,38 @@ CAST(NULL AS VARIANT) -- NULL
CAST(CAST('NaN' AS DOUBLE) AS VARIANT) -- NaN, stored as a DOUBLE
CAST(INTERVAL '2' DAY AS VARIANT) -- fails at validation
CAST(ARRAY[1, NULL] AS ARRAY<VARIANT>) -- [1, NULL], each element a VARIANT, the NULL stays SQL NULL
-CAST(ARRAY[1, 2] AS VARIANT) -- fails at validation, not supported yet
+```
+
+A whole `ARRAY`, `MAP`, `ROW`, or `STRUCTURED` value can also be cast into a single `VARIANT`. An
+`ARRAY` becomes a variant array, and a `MAP`, `ROW`, or `STRUCTURED` value a variant object. Each
+leaf is stored by the rules above, so the cast is supported only when every leaf type casts to
+`VARIANT`.
+
+- A `ROW` or `STRUCTURED` value is keyed by its field names. The SQL `ROW` constructor names its
+ fields `EXPR$0`, `EXPR$1`, and so on, and the Table API `row()` names them `f0`, `f1`, and so on.
+ To choose the keys, cast to a `ROW` with named fields first, or name each field with `as()` in the
+ Table API.
+- A `MAP` needs a character string key, which becomes the object key. A `NULL` key fails the cast.
+ If a key appears twice, the last value is kept.
+- A variant object sorts its keys, so the field order of a `ROW` is not kept.
+- A `NULL` element, field, or map value becomes a variant null, so an array keeps its length and an
+ object keeps its keys.
+- A nested `VARIANT` is embedded as is.
+- The whole value must fit into the 16 MiB of a `VARIANT`. Any `ARRAY` or `MAP` can exceed it, and so
+ can a `ROW` with a nested `VARIANT` or with fields whose declared sizes add up to more. The cast
+ then fails, and `TRY_CAST` returns `NULL` for the whole value.
+- Casting the `VARIANT` back to the original type returns the original value, since a cast to `ROW`
Review Comment:
The round trip has a few more exceptions than the SQL `NULL` in a `VARIANT` field:
- The same happens for a SQL `NULL` element of `ARRAY<VARIANT>` and a SQL `NULL` value of `MAP<STRING, VARIANT>`.
- A MAP with a duplicate key loses the earlier value.
It's also worth one sentence contrasting the two NULL behaviors: `ARRAY<INT>` to `ARRAY<VARIANT>` keeps a SQL `NULL`, while `ARRAY<INT>` to `VARIANT` turns it into a variant null. Otherwise users will hit that difference by surprise.
##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/casting/ConstructedToVariantCastRule.java:
##########
@@ -0,0 +1,155 @@
+/*
+ * 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.functions.casting;
+
+import org.apache.flink.table.runtime.functions.ToVariantConverter;
+import org.apache.flink.table.types.logical.DistinctType;
+import org.apache.flink.table.types.logical.LogicalType;
+import org.apache.flink.table.types.logical.LogicalTypeRoot;
+import org.apache.flink.table.types.logical.utils.LogicalTypeCasts;
+import org.apache.flink.table.types.logical.utils.LogicalTypeChecks;
+import org.apache.flink.types.variant.BinaryVariantUtil;
+import org.apache.flink.types.variant.Variant;
+
+import java.util.ArrayDeque;
+import java.util.Deque;
+
+import static org.apache.flink.table.planner.functions.casting.CastRuleUtils.methodCall;
+
+/**
+ * Cast rule from {@link LogicalTypeRoot#ARRAY}, {@link LogicalTypeRoot#MAP}, {@link
+ * LogicalTypeRoot#ROW} and {@link LogicalTypeRoot#STRUCTURED_TYPE} to {@link
+ * LogicalTypeRoot#VARIANT}.
+ *
+ * <p>The generated code calls a {@link ToVariantConverter} created once for the input type, which
+ * describes how a value is stored. A failure anywhere in the value fails the whole cast, so {@code
+ * TRY_CAST} returns {@code NULL} rather than a partial result. See {@link #canFail} for when a cast
+ * can fail.
+ */
+class ConstructedToVariantCastRule extends AbstractNullAwareCodeGeneratorCastRule<Object, Variant> {
+
+ static final ConstructedToVariantCastRule INSTANCE = new ConstructedToVariantCastRule();
+
+ /** The largest fixed-size value: a 16-byte decimal with its header and scale. */
+ private static final long MAX_FIXED_SIZE = 18;
+
+ /** A header byte and a 4-byte size or length, the largest header a value has. */
+ private static final long MAX_HEADER_SIZE = 1 + BinaryVariantUtil.U32_SIZE;
+
+ private ConstructedToVariantCastRule() {
+ super(CastRulePredicate.builder().predicate(ConstructedToVariantCastRule::matches).build());
+ }
+
+ private static boolean matches(LogicalType input, LogicalType target) {
+ return target.is(LogicalTypeRoot.VARIANT)
+ && (input.is(LogicalTypeRoot.ARRAY)
+ || input.is(LogicalTypeRoot.MAP)
+ || input.is(LogicalTypeRoot.ROW)
+ || input.is(LogicalTypeRoot.STRUCTURED_TYPE))
+ && LogicalTypeCasts.supportsExplicitCast(input, target);
+ }
+
+ /**
+ * Returns whether a value of the input type can fail the cast, so that {@code TRY_CAST} returns
+ * {@code NULL} for it instead of failing. A value can fail in two ways:
+ *
+ * <ul>
+ * <li>A leaf fails like it does on its own, see {@link PrimitiveToVariantCastRule#canFail}.
+ * <li>The whole value does not fit into the 16 MiB of a {@code VARIANT}. Any {@code ARRAY},
+ * {@code MAP} or nested {@code VARIANT} can reach that size. A {@code ROW} can when the
+ * declared sizes of its fields add up to more.
+ * </ul>
+ *
+ * <p>A {@code MAP} also fails on a {@code NULL} key, but every {@code MAP} can fail anyway.
+ */
+ @Override
+ public boolean canFail(LogicalType inputLogicalType, LogicalType targetLogicalType) {
+ // Without an ARRAY, MAP or VARIANT, the size of a value is bounded by the sum of its
+ // leaves and object headers.
+ long maxSize = 0;
+ final Deque<LogicalType> pending = new ArrayDeque<>();
+ pending.push(inputLogicalType);
+ while (!pending.isEmpty()) {
+ final LogicalType type = pending.pop();
+ if (type.is(LogicalTypeRoot.DISTINCT_TYPE)) {
+ pending.push(((DistinctType) type).getSourceType());
+ continue;
+ }
+ switch (type.getTypeRoot()) {
+ case ARRAY:
+ case MAP:
+ case VARIANT:
+ return true;
+ case ROW:
+ case STRUCTURED_TYPE:
+ LogicalTypeChecks.getFieldTypes(type).forEach(pending::push);
+ break;
+ default:
+ if (PrimitiveToVariantCastRule.INSTANCE.canFail(type, targetLogicalType)) {
+ return true;
+ }
+ }
+ maxSize += maxOwnSize(type);
+ }
+ return maxSize > BinaryVariantUtil.SIZE_LIMIT;
+ }
+
+ private static long maxOwnSize(LogicalType type) {
+ switch (type.getTypeRoot()) {
+ case ROW:
+ case STRUCTURED_TYPE:
+ // Only the object header. Its fields are counted on their own. A 4-byte id per
+ // field, and a 4-byte offset per field plus one for the end.
+ return MAX_HEADER_SIZE
+ + BinaryVariantUtil.U32_SIZE
+ * (2L * LogicalTypeChecks.getFieldCount(type) + 1);
+ case CHAR:
+ case VARCHAR:
+ return MAX_HEADER_SIZE
+ + (long) PrimitiveToVariantCastRule.MAX_UTF8_BYTES_PER_CHAR
+ * LogicalTypeChecks.getLength(type);
+ case BINARY:
+ case VARBINARY:
+ return MAX_HEADER_SIZE + LogicalTypeChecks.getLength(type);
+ default:
+ return MAX_FIXED_SIZE;
+ }
+ }
+
+ /* Example generated code for ARRAY<INT>, inside the null check of the base class. The
+ converter is a field, created once when the code is generated:
+
+ result$1 = toVariantConverter$2.convert(array$0);
+
+ */
+ @Override
+ protected String generateCodeBlockInternal(
Review Comment:
Together with the element-wise casts from #29311, `CAST(arr AS ARRAY<VARIANT>)` for `arr ARRAY<ROW<...>>` becomes valid: each element turns into a variant object. That path runs `declareReusableObject` inside the nested code generation of `ArrayToArrayCastRule`, both through `ScalarOperatorGens` and through the standalone `CastExecutor`, which is the trickier one. The tests only cover `ARRAY<VARIANT>` to VARIANT. Could you add `ARRAY<ROW<...>>` to `ARRAY<VARIANT>` and `MAP<STRING, ROW<...>>` to `MAP<STRING, VARIANT>` rows to `CastRulesTest` and `CastFunctionITCase`?
##########
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/functions/ToVariantConverter.java:
##########
@@ -0,0 +1,260 @@
+/*
+ * 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.api.TableRuntimeException;
+import org.apache.flink.table.data.ArrayData;
+import org.apache.flink.table.data.DecimalData;
+import org.apache.flink.table.data.MapData;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.data.TimestampData;
+import org.apache.flink.table.types.logical.ArrayType;
+import org.apache.flink.table.types.logical.DistinctType;
+import org.apache.flink.table.types.logical.LogicalType;
+import org.apache.flink.table.types.logical.LogicalTypeRoot;
+import org.apache.flink.table.types.logical.MapType;
+import org.apache.flink.table.types.logical.utils.LogicalTypeChecks;
+import org.apache.flink.table.types.logical.utils.UuidUtils;
+import org.apache.flink.types.variant.BinaryVariant;
+import org.apache.flink.types.variant.BinaryVariantInternalBuilder;
+import org.apache.flink.types.variant.BinaryVariantInternalBuilder.FieldEntry;
+import org.apache.flink.types.variant.Variant;
+import org.apache.flink.types.variant.VariantTypeException;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Converts internal data of a SQL type into a {@link Variant}, like {@code CAST(x AS VARIANT)}.
+ *
+ * <p>An {@code ARRAY} becomes a variant array. A {@code ROW} or {@code STRUCTURED} value becomes a
+ * variant object keyed by its field names, and a {@code MAP} one keyed by its character string
+ * keys. A {@code NULL} element, field or map value becomes a variant null. A leaf is stored like
+ * the cast stores it on its own, see {@link VariantCastUtils}, and a nested {@code VARIANT} is
+ * embedded as is.
+ *
+ * <p>The converter is created once per type and writes a whole value into one builder, so a nested
+ * value is encoded in a single pass. It keeps no state between calls.
+ */
+@Internal
+public final class ToVariantConverter implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ private final String sourceType;
+ private final ValueWriter writer;
+
+ private ToVariantConverter(String sourceType, ValueWriter writer) {
+ this.sourceType = sourceType;
+ this.writer = writer;
+ }
+
+ /** Creates a converter for a type that {@code LogicalTypeCasts} allows to cast to VARIANT. */
+ public static ToVariantConverter create(LogicalType type) {
+ return new ToVariantConverter(type.asSummaryString(), createWriter(type));
+ }
+
+ /**
+ * Converts a value that is not {@code NULL}.
+ *
+ * @throws TableRuntimeException if the value has a {@code NULL} map key, a timestamp outside
+ * the range of its variant kind, or does not fit into the 16 MiB of a {@code VARIANT}
+ */
+ public Variant convert(Object value) {
+ // A MAP can hold the same key twice at runtime. The builder keeps the last one, like the
+ // MAP constructor does.
+ final BinaryVariantInternalBuilder builder = new BinaryVariantInternalBuilder(true);
Review Comment:
nit: Every value allocates a new builder (128 bytes, growing by doubling), a boxed `ArrayList<Integer>` per array, and one `FieldEntry` per field. That's fine for now; just noting it as the obvious target if the micro benchmark matters.
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-40826][table] Support casting ARRAY, MAP, ROW and STRUCTURED to VARIANT [flink]
Posted by "AHeise (via GitHub)" <gi...@apache.org>.
AHeise commented on code in PR #29369:
URL: https://github.com/apache/flink/pull/29369#discussion_r4184730375
##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/casting/ToVariantCastRule.java:
##########
@@ -0,0 +1,155 @@
+/*
+ * 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.functions.casting;
+
+import org.apache.flink.table.runtime.functions.ToVariantConverter;
+import org.apache.flink.table.types.logical.DistinctType;
+import org.apache.flink.table.types.logical.LogicalType;
+import org.apache.flink.table.types.logical.LogicalTypeRoot;
+import org.apache.flink.table.types.logical.utils.LogicalTypeCasts;
+import org.apache.flink.table.types.logical.utils.LogicalTypeChecks;
+import org.apache.flink.types.variant.BinaryVariantUtil;
+import org.apache.flink.types.variant.Variant;
+
+import java.util.ArrayDeque;
+import java.util.Deque;
+
+import static org.apache.flink.table.planner.functions.casting.CastRuleUtils.methodCall;
+
+/**
+ * Cast rule from {@link LogicalTypeRoot#ARRAY}, {@link LogicalTypeRoot#MAP}, {@link
+ * LogicalTypeRoot#ROW} and {@link LogicalTypeRoot#STRUCTURED_TYPE} to {@link
+ * LogicalTypeRoot#VARIANT}.
+ *
+ * <p>The generated code calls a {@link ToVariantConverter} created once for the input type, which
+ * describes how a value is stored. A failure anywhere in the value fails the whole cast, so {@code
+ * TRY_CAST} returns {@code NULL} rather than a partial result. See {@link #canFail} for when a cast
+ * can fail.
+ */
+class ConstructedToVariantCastRule extends AbstractNullAwareCodeGeneratorCastRule<Object, Variant> {
+
+ static final ConstructedToVariantCastRule INSTANCE = new ConstructedToVariantCastRule();
+
+ /** The largest fixed-size value: a 16-byte decimal with its header and scale. */
+ private static final long MAX_FIXED_SIZE = 18;
+
+ /** A header byte and a 4-byte size or length, the largest header a value has. */
+ private static final long MAX_HEADER_SIZE = 1 + BinaryVariantUtil.U32_SIZE;
+
+ private ConstructedToVariantCastRule() {
+ super(CastRulePredicate.builder().predicate(ConstructedToVariantCastRule::matches).build());
+ }
+
+ private static boolean matches(LogicalType input, LogicalType target) {
+ return target.is(LogicalTypeRoot.VARIANT)
+ && (input.is(LogicalTypeRoot.ARRAY)
+ || input.is(LogicalTypeRoot.MAP)
+ || input.is(LogicalTypeRoot.ROW)
+ || input.is(LogicalTypeRoot.STRUCTURED_TYPE))
+ && LogicalTypeCasts.supportsExplicitCast(input, target);
+ }
+
+ /**
+ * Returns whether a value of the input type can fail the cast, so that {@code TRY_CAST} returns
+ * {@code NULL} for it instead of failing. A value can fail in two ways:
+ *
+ * <ul>
+ * <li>A leaf fails like it does on its own, see {@link PrimitiveToVariantCastRule#canFail}.
+ * <li>The whole value does not fit into the 16 MiB of a {@code VARIANT}. Any {@code ARRAY},
+ * {@code MAP} or nested {@code VARIANT} can reach that size. A {@code ROW} can when the
+ * declared sizes of its fields add up to more.
+ * </ul>
+ *
+ * <p>A {@code MAP} also fails on a {@code NULL} key, but every {@code MAP} can fail anyway.
+ */
+ @Override
+ public boolean canFail(LogicalType inputLogicalType, LogicalType targetLogicalType) {
+ // Without an ARRAY, MAP or VARIANT, the size of a value is bounded by the sum of its
+ // leaves and object headers.
+ long maxSize = 0;
+ final Deque<LogicalType> pending = new ArrayDeque<>();
+ pending.push(inputLogicalType);
+ while (!pending.isEmpty()) {
+ final LogicalType type = pending.pop();
+ if (type.is(LogicalTypeRoot.DISTINCT_TYPE)) {
+ pending.push(((DistinctType) type).getSourceType());
+ continue;
+ }
+ switch (type.getTypeRoot()) {
+ case ARRAY:
+ case MAP:
+ case VARIANT:
+ return true;
+ case ROW:
+ case STRUCTURED_TYPE:
+ LogicalTypeChecks.getFieldTypes(type).forEach(pending::push);
+ break;
+ default:
+ if (PrimitiveToVariantCastRule.INSTANCE.canFail(type, targetLogicalType)) {
+ return true;
+ }
+ }
+ maxSize += maxOwnSize(type);
+ }
+ return maxSize > BinaryVariantUtil.SIZE_LIMIT;
+ }
+
+ private static long maxOwnSize(LogicalType type) {
+ switch (type.getTypeRoot()) {
+ case ROW:
+ case STRUCTURED_TYPE:
+ // Only the object header. Its fields are counted on their own. A 4-byte id per
+ // field, and a 4-byte offset per field plus one for the end.
+ return MAX_HEADER_SIZE
+ + BinaryVariantUtil.U32_SIZE
+ * (2L * LogicalTypeChecks.getFieldCount(type) + 1);
+ case CHAR:
+ case VARCHAR:
+ return MAX_HEADER_SIZE
+ + (long) PrimitiveToVariantCastRule.MAX_UTF8_BYTES_PER_CHAR
+ * LogicalTypeChecks.getLength(type);
+ case BINARY:
+ case VARBINARY:
+ return MAX_HEADER_SIZE + LogicalTypeChecks.getLength(type);
+ default:
+ return MAX_FIXED_SIZE;
+ }
+ }
+
+ /* Example generated code for ARRAY<INT>, inside the null check of the base class. The
+ converter is a field, created once when the code is generated:
+
+ result$1 = toVariantConverter$2.convert(array$0);
+
+ */
+ @Override
+ protected String generateCodeBlockInternal(
Review Comment:
Covered. The test comment says Calcite turns a plain SQL `CAST(ARRAY<ROW> AS ARRAY<VARIANT>)` into a MULTISET. What does a user get there, a validation error? If that applies to any `ARRAY<ROW>` target, is there a ticket?
##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/casting/ToVariantCastRule.java:
##########
@@ -0,0 +1,178 @@
+/*
+ * 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.functions.casting;
+
+import org.apache.flink.table.runtime.functions.ToVariantConverter;
+import org.apache.flink.table.runtime.functions.VariantCastUtils;
+import org.apache.flink.table.types.logical.DistinctType;
+import org.apache.flink.table.types.logical.LogicalType;
+import org.apache.flink.table.types.logical.LogicalTypeRoot;
+import org.apache.flink.table.types.logical.utils.LogicalTypeCasts;
+import org.apache.flink.table.types.logical.utils.LogicalTypeChecks;
+import org.apache.flink.types.variant.BinaryVariantUtil;
+import org.apache.flink.types.variant.Variant;
+
+import java.util.ArrayDeque;
+import java.util.Deque;
+
+import static org.apache.flink.table.planner.functions.casting.CastRuleUtils.box;
+import static org.apache.flink.table.planner.functions.casting.CastRuleUtils.methodCall;
+
+/**
+ * Cast rule to {@link LogicalTypeRoot#VARIANT} from every type that {@link LogicalTypeCasts}
+ * allows: a primitive type, or an {@link LogicalTypeRoot#ARRAY}, {@link LogicalTypeRoot#MAP},
+ * {@link LogicalTypeRoot#ROW} or {@link LogicalTypeRoot#STRUCTURED_TYPE} whose leaves all cast to
+ * {@code VARIANT} and whose {@code MAP} keys are character strings.
+ *
+ * <p>The generated code calls a {@link ToVariantConverter} created once for the input type, which
+ * describes how a value is stored. A failure anywhere in the value fails the whole cast, so {@code
+ * TRY_CAST} returns {@code NULL} rather than a partial result. See {@link #canFail} for when a cast
+ * can fail.
+ */
+class ToVariantCastRule extends AbstractNullAwareCodeGeneratorCastRule<Object, Variant> {
+
+ static final ToVariantCastRule INSTANCE = new ToVariantCastRule();
+
+ /** A character takes up to 4 bytes in UTF-8, which a declared length counts as one. */
+ private static final int MAX_UTF8_BYTES_PER_CHAR = 4;
+
+ /** The largest fixed-size value: a 16-byte decimal with its header and scale. */
+ private static final long MAX_FIXED_SIZE = 18;
+
+ /** A header byte and a 4-byte size or length, the largest header a value has. */
+ private static final long MAX_HEADER_SIZE = 1 + BinaryVariantUtil.U32_SIZE;
+
+ private ToVariantCastRule() {
+ super(CastRulePredicate.builder().predicate(ToVariantCastRule::matches).build());
+ }
+
+ private static boolean matches(LogicalType input, LogicalType target) {
+ // No cast rule takes the NULL type, although LogicalTypeCasts allows it to cast to any
+ // type.
+ return target.is(LogicalTypeRoot.VARIANT)
+ && !input.is(LogicalTypeRoot.NULL)
+ && LogicalTypeCasts.supportsExplicitCast(input, target);
+ }
+
+ /**
+ * Returns whether a value of the input type can fail the cast, so that {@code TRY_CAST} returns
+ * {@code NULL} for it instead of failing. A value can fail in three ways:
+ *
+ * <ul>
+ * <li>A {@code TIMESTAMP(p)} or {@code TIMESTAMP_LTZ(p)} with {@code p > 6} is stored with
+ * nanoseconds, which only cover 1677-09-21 to 2262-04-11.
+ * <li>The value does not fit into the 16 MiB of a {@code VARIANT}. Any {@code ARRAY}, {@code
+ * MAP} or nested {@code VARIANT} can reach that size. A string or binary type can when
+ * its declared length allows more, and a {@code ROW} when the declared sizes of its
+ * fields add up to more.
+ * <li>A {@code MAP} with a {@code NULL} key fails. Every {@code MAP} can already fail on its
+ * size, so this makes no other type fallible.
+ * </ul>
+ *
+ * <p>Every other type never fails.
+ *
+ * <p>The size check trusts the declared length. Flink does not enforce that length on values
+ * from a source, so a longer value can still reach the cast. {@code TRY_CAST} then fails for it
+ * instead of returning {@code NULL}.
+ */
+ @Override
+ public boolean canFail(LogicalType inputLogicalType, LogicalType targetLogicalType) {
+ // Without an ARRAY, MAP or VARIANT, the size of a value is bounded by the sum of its
+ // leaves and object headers.
+ long maxSize = 0;
+ final Deque<LogicalType> pending = new ArrayDeque<>();
+ pending.push(inputLogicalType);
+ while (!pending.isEmpty()) {
+ final LogicalType type = pending.pop();
+ if (type.is(LogicalTypeRoot.DISTINCT_TYPE)) {
+ pending.push(((DistinctType) type).getSourceType());
+ continue;
+ }
+ switch (type.getTypeRoot()) {
+ case ARRAY:
+ case MAP:
+ case VARIANT:
+ return true;
+ case ROW:
+ case STRUCTURED_TYPE:
+ LogicalTypeChecks.getFieldTypes(type).forEach(pending::push);
+ break;
+ case TIMESTAMP_WITHOUT_TIME_ZONE:
Review Comment:
`timeMicros` throws a `TableRuntimeException` for a TIME outside one day, but `canFail` treats TIME as infallible, so `TRY_CAST(t AS VARIANT)` fails for such a value instead of returning `NULL`. The Javadoc above ("Every other type never fails") and footnote 8 in the docs say the same. Such a value only comes from a source or a UDF, but FLINK-40845 shows it happens. Could TIME count as fallible here, like TIMESTAMP(7..9)? The try/catch it adds costs next to nothing.
##########
flink-core/src/main/java/org/apache/flink/types/variant/BinaryVariantInternalBuilder.java:
##########
@@ -537,7 +537,9 @@ public void finishWritingArray(int start, ArrayList<Integer> offsets) {
// the
// input variant, we can directly copy the binary slice.
public void appendVariant(BinaryVariant v) {
- appendVariantImpl(v.getValue(), v.getMetadata(), v.getPos());
+ // A nested variant, such as a field or an element of another variant, starts at its own
+ // position in the shared buffer. getValue() would copy it to position 0 instead.
+ appendVariantImpl(v.rawValue(), v.getMetadata(), v.getPos());
Review Comment:
FLINK-40911 has no affects or fix versions yet. Please set them so it can be picked for the release branches. The `BinaryVariant#hashCode` vs `equals` ticket is still missing.
##########
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/functions/ToVariantConverter.java:
##########
@@ -0,0 +1,260 @@
+/*
+ * 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.api.TableRuntimeException;
+import org.apache.flink.table.data.ArrayData;
+import org.apache.flink.table.data.DecimalData;
+import org.apache.flink.table.data.MapData;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.data.TimestampData;
+import org.apache.flink.table.types.logical.ArrayType;
+import org.apache.flink.table.types.logical.DistinctType;
+import org.apache.flink.table.types.logical.LogicalType;
+import org.apache.flink.table.types.logical.LogicalTypeRoot;
+import org.apache.flink.table.types.logical.MapType;
+import org.apache.flink.table.types.logical.utils.LogicalTypeChecks;
+import org.apache.flink.table.types.logical.utils.UuidUtils;
+import org.apache.flink.types.variant.BinaryVariant;
+import org.apache.flink.types.variant.BinaryVariantInternalBuilder;
+import org.apache.flink.types.variant.BinaryVariantInternalBuilder.FieldEntry;
+import org.apache.flink.types.variant.Variant;
+import org.apache.flink.types.variant.VariantTypeException;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Converts internal data of a SQL type into a {@link Variant}, like {@code CAST(x AS VARIANT)}.
+ *
+ * <p>An {@code ARRAY} becomes a variant array. A {@code ROW} or {@code STRUCTURED} value becomes a
+ * variant object keyed by its field names, and a {@code MAP} one keyed by its character string
+ * keys. A {@code NULL} element, field or map value becomes a variant null. A leaf is stored like
+ * the cast stores it on its own, see {@link VariantCastUtils}, and a nested {@code VARIANT} is
+ * embedded as is.
+ *
+ * <p>The converter is created once per type and writes a whole value into one builder, so a nested
+ * value is encoded in a single pass. It keeps no state between calls.
+ */
+@Internal
+public final class ToVariantConverter implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ private final String sourceType;
+ private final ValueWriter writer;
+
+ private ToVariantConverter(String sourceType, ValueWriter writer) {
+ this.sourceType = sourceType;
+ this.writer = writer;
+ }
+
+ /** Creates a converter for a type that {@code LogicalTypeCasts} allows to cast to VARIANT. */
+ public static ToVariantConverter create(LogicalType type) {
+ return new ToVariantConverter(type.asSummaryString(), createWriter(type));
+ }
+
+ /**
+ * Converts a value that is not {@code NULL}.
+ *
+ * @throws TableRuntimeException if the value has a {@code NULL} map key, a timestamp outside
+ * the range of its variant kind, or does not fit into the 16 MiB of a {@code VARIANT}
+ */
+ public Variant convert(Object value) {
+ // A MAP can hold the same key twice at runtime. The builder keeps the last one, like the
+ // MAP constructor does.
+ final BinaryVariantInternalBuilder builder = new BinaryVariantInternalBuilder(true);
+ try {
+ writer.write(builder, value);
+ return builder.build();
+ } catch (VariantTypeException e) {
+ if (e != BinaryVariantInternalBuilder.VARIANT_SIZE_LIMIT_EXCEPTION) {
+ throw e;
+ }
+ throw new TableRuntimeException(
+ String.format(
+ "Cannot cast a value of type %s to VARIANT. A VARIANT is limited to "
+ + "16 MiB.",
+ sourceType));
+ }
+ }
+
+ @FunctionalInterface
+ private interface ValueWriter extends Serializable {
+ void write(BinaryVariantInternalBuilder builder, Object value);
+ }
+
+ private static ValueWriter createNullableWriter(LogicalType type) {
+ final ValueWriter writer = createWriter(type);
+ return (builder, value) -> {
+ if (value == null) {
+ builder.appendNull();
+ } else {
+ writer.write(builder, value);
+ }
+ };
+ }
+
+ private static ValueWriter createWriter(LogicalType type) {
+ switch (type.getTypeRoot()) {
+ case NULL:
+ return (builder, value) -> builder.appendNull();
+ case BOOLEAN:
+ return (builder, value) -> builder.appendBoolean((Boolean) value);
+ case TINYINT:
+ return (builder, value) -> builder.appendByte((Byte) value);
+ case SMALLINT:
+ return (builder, value) -> builder.appendShort((Short) value);
+ case INTEGER:
+ return (builder, value) -> builder.appendInt((Integer) value);
+ case BIGINT:
+ return (builder, value) -> builder.appendLong((Long) value);
+ case FLOAT:
+ return (builder, value) -> builder.appendFloat((Float) value);
+ case DOUBLE:
+ return (builder, value) -> builder.appendDouble((Double) value);
+ case DECIMAL:
+ return (builder, value) ->
+ builder.appendDecimal(((DecimalData) value).toBigDecimal());
+ case CHAR:
+ case VARCHAR:
+ return (builder, value) -> builder.appendString(value.toString());
+ case BINARY:
+ case VARBINARY:
+ return (builder, value) -> builder.appendBinary((byte[]) value);
+ case DATE:
+ return (builder, value) -> builder.appendDate((Integer) value);
+ case TIME_WITHOUT_TIME_ZONE:
+ // TIME is millisecond-of-day at runtime, the variant kind holds microseconds.
+ return (builder, value) -> builder.appendTime((Integer) value * 1_000L);
+ case TIMESTAMP_WITHOUT_TIME_ZONE:
+ {
+ final int precision = LogicalTypeChecks.getPrecision(type);
+ return (builder, value) ->
+ VariantCastUtils.appendTimestamp(
+ builder, (TimestampData) value, precision);
+ }
+ case TIMESTAMP_WITH_LOCAL_TIME_ZONE:
+ {
+ final int precision = LogicalTypeChecks.getPrecision(type);
+ return (builder, value) ->
+ VariantCastUtils.appendTimestampLtz(
+ builder, (TimestampData) value, precision);
+ }
+ case UUID:
+ return (builder, value) -> builder.appendUuid(UuidUtils.fromBytes((byte[]) value));
+ case VARIANT:
Review Comment:
Verified with a 20,000-level VARIANT. Please link the follow-up ticket here once it is filed.
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-40826][table] Support casting ARRAY, MAP, ROW and STRUCTURED to VARIANT [flink]
Posted by "AHeise (via GitHub)" <gi...@apache.org>.
AHeise commented on code in PR #29369:
URL: https://github.com/apache/flink/pull/29369#discussion_r4184726670
##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/casting/ToVariantCastRule.java:
##########
@@ -0,0 +1,155 @@
+/*
+ * 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.functions.casting;
+
+import org.apache.flink.table.runtime.functions.ToVariantConverter;
+import org.apache.flink.table.types.logical.DistinctType;
+import org.apache.flink.table.types.logical.LogicalType;
+import org.apache.flink.table.types.logical.LogicalTypeRoot;
+import org.apache.flink.table.types.logical.utils.LogicalTypeCasts;
+import org.apache.flink.table.types.logical.utils.LogicalTypeChecks;
+import org.apache.flink.types.variant.BinaryVariantUtil;
+import org.apache.flink.types.variant.Variant;
+
+import java.util.ArrayDeque;
+import java.util.Deque;
+
+import static org.apache.flink.table.planner.functions.casting.CastRuleUtils.methodCall;
+
+/**
+ * Cast rule from {@link LogicalTypeRoot#ARRAY}, {@link LogicalTypeRoot#MAP}, {@link
+ * LogicalTypeRoot#ROW} and {@link LogicalTypeRoot#STRUCTURED_TYPE} to {@link
+ * LogicalTypeRoot#VARIANT}.
+ *
+ * <p>The generated code calls a {@link ToVariantConverter} created once for the input type, which
+ * describes how a value is stored. A failure anywhere in the value fails the whole cast, so {@code
+ * TRY_CAST} returns {@code NULL} rather than a partial result. See {@link #canFail} for when a cast
+ * can fail.
+ */
+class ConstructedToVariantCastRule extends AbstractNullAwareCodeGeneratorCastRule<Object, Variant> {
+
+ static final ConstructedToVariantCastRule INSTANCE = new ConstructedToVariantCastRule();
+
+ /** The largest fixed-size value: a 16-byte decimal with its header and scale. */
+ private static final long MAX_FIXED_SIZE = 18;
+
+ /** A header byte and a 4-byte size or length, the largest header a value has. */
+ private static final long MAX_HEADER_SIZE = 1 + BinaryVariantUtil.U32_SIZE;
+
+ private ConstructedToVariantCastRule() {
+ super(CastRulePredicate.builder().predicate(ConstructedToVariantCastRule::matches).build());
+ }
+
+ private static boolean matches(LogicalType input, LogicalType target) {
+ return target.is(LogicalTypeRoot.VARIANT)
+ && (input.is(LogicalTypeRoot.ARRAY)
+ || input.is(LogicalTypeRoot.MAP)
+ || input.is(LogicalTypeRoot.ROW)
+ || input.is(LogicalTypeRoot.STRUCTURED_TYPE))
+ && LogicalTypeCasts.supportsExplicitCast(input, target);
+ }
+
+ /**
+ * Returns whether a value of the input type can fail the cast, so that {@code TRY_CAST} returns
+ * {@code NULL} for it instead of failing. A value can fail in two ways:
+ *
+ * <ul>
+ * <li>A leaf fails like it does on its own, see {@link PrimitiveToVariantCastRule#canFail}.
+ * <li>The whole value does not fit into the 16 MiB of a {@code VARIANT}. Any {@code ARRAY},
+ * {@code MAP} or nested {@code VARIANT} can reach that size. A {@code ROW} can when the
+ * declared sizes of its fields add up to more.
+ * </ul>
+ *
+ * <p>A {@code MAP} also fails on a {@code NULL} key, but every {@code MAP} can fail anyway.
+ */
+ @Override
+ public boolean canFail(LogicalType inputLogicalType, LogicalType targetLogicalType) {
+ // Without an ARRAY, MAP or VARIANT, the size of a value is bounded by the sum of its
+ // leaves and object headers.
+ long maxSize = 0;
+ final Deque<LogicalType> pending = new ArrayDeque<>();
+ pending.push(inputLogicalType);
+ while (!pending.isEmpty()) {
+ final LogicalType type = pending.pop();
+ if (type.is(LogicalTypeRoot.DISTINCT_TYPE)) {
+ pending.push(((DistinctType) type).getSourceType());
+ continue;
+ }
+ switch (type.getTypeRoot()) {
+ case ARRAY:
+ case MAP:
+ case VARIANT:
+ return true;
+ case ROW:
+ case STRUCTURED_TYPE:
+ LogicalTypeChecks.getFieldTypes(type).forEach(pending::push);
+ break;
+ default:
+ if (PrimitiveToVariantCastRule.INSTANCE.canFail(type, targetLogicalType)) {
+ return true;
+ }
+ }
+ maxSize += maxOwnSize(type);
+ }
+ return maxSize > BinaryVariantUtil.SIZE_LIMIT;
+ }
+
+ private static long maxOwnSize(LogicalType type) {
+ switch (type.getTypeRoot()) {
+ case ROW:
+ case STRUCTURED_TYPE:
+ // Only the object header. Its fields are counted on their own. A 4-byte id per
+ // field, and a 4-byte offset per field plus one for the end.
+ return MAX_HEADER_SIZE
+ + BinaryVariantUtil.U32_SIZE
+ * (2L * LogicalTypeChecks.getFieldCount(type) + 1);
+ case CHAR:
+ case VARCHAR:
+ return MAX_HEADER_SIZE
+ + (long) PrimitiveToVariantCastRule.MAX_UTF8_BYTES_PER_CHAR
+ * LogicalTypeChecks.getLength(type);
+ case BINARY:
+ case VARBINARY:
+ return MAX_HEADER_SIZE + LogicalTypeChecks.getLength(type);
+ default:
+ return MAX_FIXED_SIZE;
+ }
+ }
+
+ /* Example generated code for ARRAY<INT>, inside the null check of the base class. The
+ converter is a field, created once when the code is generated:
+
+ result$1 = toVariantConverter$2.convert(array$0);
+
+ */
+ @Override
+ protected String generateCodeBlockInternal(
Review Comment:
Covered. The test comment says Calcite turns a plain SQL `CAST(ARRAY<ROW> AS ARRAY<VARIANT>)` into a MULTISET. What does a user get there, a validation error? If that applies to any `ARRAY<ROW>` target, is there a ticket?
##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/casting/ToVariantCastRule.java:
##########
@@ -0,0 +1,178 @@
+/*
+ * 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.functions.casting;
+
+import org.apache.flink.table.runtime.functions.ToVariantConverter;
+import org.apache.flink.table.runtime.functions.VariantCastUtils;
+import org.apache.flink.table.types.logical.DistinctType;
+import org.apache.flink.table.types.logical.LogicalType;
+import org.apache.flink.table.types.logical.LogicalTypeRoot;
+import org.apache.flink.table.types.logical.utils.LogicalTypeCasts;
+import org.apache.flink.table.types.logical.utils.LogicalTypeChecks;
+import org.apache.flink.types.variant.BinaryVariantUtil;
+import org.apache.flink.types.variant.Variant;
+
+import java.util.ArrayDeque;
+import java.util.Deque;
+
+import static org.apache.flink.table.planner.functions.casting.CastRuleUtils.box;
+import static org.apache.flink.table.planner.functions.casting.CastRuleUtils.methodCall;
+
+/**
+ * Cast rule to {@link LogicalTypeRoot#VARIANT} from every type that {@link LogicalTypeCasts}
+ * allows: a primitive type, or an {@link LogicalTypeRoot#ARRAY}, {@link LogicalTypeRoot#MAP},
+ * {@link LogicalTypeRoot#ROW} or {@link LogicalTypeRoot#STRUCTURED_TYPE} whose leaves all cast to
+ * {@code VARIANT} and whose {@code MAP} keys are character strings.
+ *
+ * <p>The generated code calls a {@link ToVariantConverter} created once for the input type, which
+ * describes how a value is stored. A failure anywhere in the value fails the whole cast, so {@code
+ * TRY_CAST} returns {@code NULL} rather than a partial result. See {@link #canFail} for when a cast
+ * can fail.
+ */
+class ToVariantCastRule extends AbstractNullAwareCodeGeneratorCastRule<Object, Variant> {
+
+ static final ToVariantCastRule INSTANCE = new ToVariantCastRule();
+
+ /** A character takes up to 4 bytes in UTF-8, which a declared length counts as one. */
+ private static final int MAX_UTF8_BYTES_PER_CHAR = 4;
+
+ /** The largest fixed-size value: a 16-byte decimal with its header and scale. */
+ private static final long MAX_FIXED_SIZE = 18;
+
+ /** A header byte and a 4-byte size or length, the largest header a value has. */
+ private static final long MAX_HEADER_SIZE = 1 + BinaryVariantUtil.U32_SIZE;
+
+ private ToVariantCastRule() {
+ super(CastRulePredicate.builder().predicate(ToVariantCastRule::matches).build());
+ }
+
+ private static boolean matches(LogicalType input, LogicalType target) {
+ // No cast rule takes the NULL type, although LogicalTypeCasts allows it to cast to any
+ // type.
+ return target.is(LogicalTypeRoot.VARIANT)
+ && !input.is(LogicalTypeRoot.NULL)
+ && LogicalTypeCasts.supportsExplicitCast(input, target);
+ }
+
+ /**
+ * Returns whether a value of the input type can fail the cast, so that {@code TRY_CAST} returns
+ * {@code NULL} for it instead of failing. A value can fail in three ways:
+ *
+ * <ul>
+ * <li>A {@code TIMESTAMP(p)} or {@code TIMESTAMP_LTZ(p)} with {@code p > 6} is stored with
+ * nanoseconds, which only cover 1677-09-21 to 2262-04-11.
+ * <li>The value does not fit into the 16 MiB of a {@code VARIANT}. Any {@code ARRAY}, {@code
+ * MAP} or nested {@code VARIANT} can reach that size. A string or binary type can when
+ * its declared length allows more, and a {@code ROW} when the declared sizes of its
+ * fields add up to more.
+ * <li>A {@code MAP} with a {@code NULL} key fails. Every {@code MAP} can already fail on its
+ * size, so this makes no other type fallible.
+ * </ul>
+ *
+ * <p>Every other type never fails.
+ *
+ * <p>The size check trusts the declared length. Flink does not enforce that length on values
+ * from a source, so a longer value can still reach the cast. {@code TRY_CAST} then fails for it
+ * instead of returning {@code NULL}.
+ */
+ @Override
+ public boolean canFail(LogicalType inputLogicalType, LogicalType targetLogicalType) {
+ // Without an ARRAY, MAP or VARIANT, the size of a value is bounded by the sum of its
+ // leaves and object headers.
+ long maxSize = 0;
+ final Deque<LogicalType> pending = new ArrayDeque<>();
+ pending.push(inputLogicalType);
+ while (!pending.isEmpty()) {
+ final LogicalType type = pending.pop();
+ if (type.is(LogicalTypeRoot.DISTINCT_TYPE)) {
+ pending.push(((DistinctType) type).getSourceType());
+ continue;
+ }
+ switch (type.getTypeRoot()) {
+ case ARRAY:
+ case MAP:
+ case VARIANT:
+ return true;
+ case ROW:
+ case STRUCTURED_TYPE:
+ LogicalTypeChecks.getFieldTypes(type).forEach(pending::push);
+ break;
+ case TIMESTAMP_WITHOUT_TIME_ZONE:
Review Comment:
`timeMicros` throws a `TableRuntimeException` for a TIME outside one day, but `canFail` treats TIME as infallible, so `TRY_CAST(t AS VARIANT)` fails for such a value instead of returning `NULL`. The Javadoc above ("Every other type never fails") and footnote 8 in the docs say the same. Such a value only comes from a source or a UDF, but FLINK-40845 shows it happens. Could TIME count as fallible here, like TIMESTAMP(7..9)? The try/catch it adds costs next to nothing.
##########
flink-core/src/main/java/org/apache/flink/types/variant/BinaryVariantInternalBuilder.java:
##########
@@ -537,7 +537,9 @@ public void finishWritingArray(int start, ArrayList<Integer> offsets) {
// the
// input variant, we can directly copy the binary slice.
public void appendVariant(BinaryVariant v) {
- appendVariantImpl(v.getValue(), v.getMetadata(), v.getPos());
+ // A nested variant, such as a field or an element of another variant, starts at its own
+ // position in the shared buffer. getValue() would copy it to position 0 instead.
+ appendVariantImpl(v.rawValue(), v.getMetadata(), v.getPos());
Review Comment:
FLINK-40911 has no affects or fix versions yet. Please set them so it can be picked for the release branches. The `BinaryVariant#hashCode` vs `equals` ticket is still missing.
##########
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/functions/ToVariantConverter.java:
##########
@@ -0,0 +1,260 @@
+/*
+ * 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.api.TableRuntimeException;
+import org.apache.flink.table.data.ArrayData;
+import org.apache.flink.table.data.DecimalData;
+import org.apache.flink.table.data.MapData;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.data.TimestampData;
+import org.apache.flink.table.types.logical.ArrayType;
+import org.apache.flink.table.types.logical.DistinctType;
+import org.apache.flink.table.types.logical.LogicalType;
+import org.apache.flink.table.types.logical.LogicalTypeRoot;
+import org.apache.flink.table.types.logical.MapType;
+import org.apache.flink.table.types.logical.utils.LogicalTypeChecks;
+import org.apache.flink.table.types.logical.utils.UuidUtils;
+import org.apache.flink.types.variant.BinaryVariant;
+import org.apache.flink.types.variant.BinaryVariantInternalBuilder;
+import org.apache.flink.types.variant.BinaryVariantInternalBuilder.FieldEntry;
+import org.apache.flink.types.variant.Variant;
+import org.apache.flink.types.variant.VariantTypeException;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Converts internal data of a SQL type into a {@link Variant}, like {@code CAST(x AS VARIANT)}.
+ *
+ * <p>An {@code ARRAY} becomes a variant array. A {@code ROW} or {@code STRUCTURED} value becomes a
+ * variant object keyed by its field names, and a {@code MAP} one keyed by its character string
+ * keys. A {@code NULL} element, field or map value becomes a variant null. A leaf is stored like
+ * the cast stores it on its own, see {@link VariantCastUtils}, and a nested {@code VARIANT} is
+ * embedded as is.
+ *
+ * <p>The converter is created once per type and writes a whole value into one builder, so a nested
+ * value is encoded in a single pass. It keeps no state between calls.
+ */
+@Internal
+public final class ToVariantConverter implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ private final String sourceType;
+ private final ValueWriter writer;
+
+ private ToVariantConverter(String sourceType, ValueWriter writer) {
+ this.sourceType = sourceType;
+ this.writer = writer;
+ }
+
+ /** Creates a converter for a type that {@code LogicalTypeCasts} allows to cast to VARIANT. */
+ public static ToVariantConverter create(LogicalType type) {
+ return new ToVariantConverter(type.asSummaryString(), createWriter(type));
+ }
+
+ /**
+ * Converts a value that is not {@code NULL}.
+ *
+ * @throws TableRuntimeException if the value has a {@code NULL} map key, a timestamp outside
+ * the range of its variant kind, or does not fit into the 16 MiB of a {@code VARIANT}
+ */
+ public Variant convert(Object value) {
+ // A MAP can hold the same key twice at runtime. The builder keeps the last one, like the
+ // MAP constructor does.
+ final BinaryVariantInternalBuilder builder = new BinaryVariantInternalBuilder(true);
+ try {
+ writer.write(builder, value);
+ return builder.build();
+ } catch (VariantTypeException e) {
+ if (e != BinaryVariantInternalBuilder.VARIANT_SIZE_LIMIT_EXCEPTION) {
+ throw e;
+ }
+ throw new TableRuntimeException(
+ String.format(
+ "Cannot cast a value of type %s to VARIANT. A VARIANT is limited to "
+ + "16 MiB.",
+ sourceType));
+ }
+ }
+
+ @FunctionalInterface
+ private interface ValueWriter extends Serializable {
+ void write(BinaryVariantInternalBuilder builder, Object value);
+ }
+
+ private static ValueWriter createNullableWriter(LogicalType type) {
+ final ValueWriter writer = createWriter(type);
+ return (builder, value) -> {
+ if (value == null) {
+ builder.appendNull();
+ } else {
+ writer.write(builder, value);
+ }
+ };
+ }
+
+ private static ValueWriter createWriter(LogicalType type) {
+ switch (type.getTypeRoot()) {
+ case NULL:
+ return (builder, value) -> builder.appendNull();
+ case BOOLEAN:
+ return (builder, value) -> builder.appendBoolean((Boolean) value);
+ case TINYINT:
+ return (builder, value) -> builder.appendByte((Byte) value);
+ case SMALLINT:
+ return (builder, value) -> builder.appendShort((Short) value);
+ case INTEGER:
+ return (builder, value) -> builder.appendInt((Integer) value);
+ case BIGINT:
+ return (builder, value) -> builder.appendLong((Long) value);
+ case FLOAT:
+ return (builder, value) -> builder.appendFloat((Float) value);
+ case DOUBLE:
+ return (builder, value) -> builder.appendDouble((Double) value);
+ case DECIMAL:
+ return (builder, value) ->
+ builder.appendDecimal(((DecimalData) value).toBigDecimal());
+ case CHAR:
+ case VARCHAR:
+ return (builder, value) -> builder.appendString(value.toString());
+ case BINARY:
+ case VARBINARY:
+ return (builder, value) -> builder.appendBinary((byte[]) value);
+ case DATE:
+ return (builder, value) -> builder.appendDate((Integer) value);
+ case TIME_WITHOUT_TIME_ZONE:
+ // TIME is millisecond-of-day at runtime, the variant kind holds microseconds.
+ return (builder, value) -> builder.appendTime((Integer) value * 1_000L);
+ case TIMESTAMP_WITHOUT_TIME_ZONE:
+ {
+ final int precision = LogicalTypeChecks.getPrecision(type);
+ return (builder, value) ->
+ VariantCastUtils.appendTimestamp(
+ builder, (TimestampData) value, precision);
+ }
+ case TIMESTAMP_WITH_LOCAL_TIME_ZONE:
+ {
+ final int precision = LogicalTypeChecks.getPrecision(type);
+ return (builder, value) ->
+ VariantCastUtils.appendTimestampLtz(
+ builder, (TimestampData) value, precision);
+ }
+ case UUID:
+ return (builder, value) -> builder.appendUuid(UuidUtils.fromBytes((byte[]) value));
+ case VARIANT:
Review Comment:
Verified with a 20,000-level VARIANT. Please link the follow-up ticket here once it is filed.
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-40826][table] Support casting ARRAY, MAP, ROW and STRUCTURED to VARIANT [flink]
Posted by "raminqaf (via GitHub)" <gi...@apache.org>.
raminqaf commented on code in PR #29369:
URL: https://github.com/apache/flink/pull/29369#discussion_r4184983198
##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/casting/ToVariantCastRule.java:
##########
@@ -0,0 +1,178 @@
+/*
+ * 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.functions.casting;
+
+import org.apache.flink.table.runtime.functions.ToVariantConverter;
+import org.apache.flink.table.runtime.functions.VariantCastUtils;
+import org.apache.flink.table.types.logical.DistinctType;
+import org.apache.flink.table.types.logical.LogicalType;
+import org.apache.flink.table.types.logical.LogicalTypeRoot;
+import org.apache.flink.table.types.logical.utils.LogicalTypeCasts;
+import org.apache.flink.table.types.logical.utils.LogicalTypeChecks;
+import org.apache.flink.types.variant.BinaryVariantUtil;
+import org.apache.flink.types.variant.Variant;
+
+import java.util.ArrayDeque;
+import java.util.Deque;
+
+import static org.apache.flink.table.planner.functions.casting.CastRuleUtils.box;
+import static org.apache.flink.table.planner.functions.casting.CastRuleUtils.methodCall;
+
+/**
+ * Cast rule to {@link LogicalTypeRoot#VARIANT} from every type that {@link LogicalTypeCasts}
+ * allows: a primitive type, or an {@link LogicalTypeRoot#ARRAY}, {@link LogicalTypeRoot#MAP},
+ * {@link LogicalTypeRoot#ROW} or {@link LogicalTypeRoot#STRUCTURED_TYPE} whose leaves all cast to
+ * {@code VARIANT} and whose {@code MAP} keys are character strings.
+ *
+ * <p>The generated code calls a {@link ToVariantConverter} created once for the input type, which
+ * describes how a value is stored. A failure anywhere in the value fails the whole cast, so {@code
+ * TRY_CAST} returns {@code NULL} rather than a partial result. See {@link #canFail} for when a cast
+ * can fail.
+ */
+class ToVariantCastRule extends AbstractNullAwareCodeGeneratorCastRule<Object, Variant> {
+
+ static final ToVariantCastRule INSTANCE = new ToVariantCastRule();
+
+ /** A character takes up to 4 bytes in UTF-8, which a declared length counts as one. */
+ private static final int MAX_UTF8_BYTES_PER_CHAR = 4;
+
+ /** The largest fixed-size value: a 16-byte decimal with its header and scale. */
+ private static final long MAX_FIXED_SIZE = 18;
+
+ /** A header byte and a 4-byte size or length, the largest header a value has. */
+ private static final long MAX_HEADER_SIZE = 1 + BinaryVariantUtil.U32_SIZE;
+
+ private ToVariantCastRule() {
+ super(CastRulePredicate.builder().predicate(ToVariantCastRule::matches).build());
+ }
+
+ private static boolean matches(LogicalType input, LogicalType target) {
+ // No cast rule takes the NULL type, although LogicalTypeCasts allows it to cast to any
+ // type.
+ return target.is(LogicalTypeRoot.VARIANT)
+ && !input.is(LogicalTypeRoot.NULL)
+ && LogicalTypeCasts.supportsExplicitCast(input, target);
+ }
+
+ /**
+ * Returns whether a value of the input type can fail the cast, so that {@code TRY_CAST} returns
+ * {@code NULL} for it instead of failing. A value can fail in three ways:
+ *
+ * <ul>
+ * <li>A {@code TIMESTAMP(p)} or {@code TIMESTAMP_LTZ(p)} with {@code p > 6} is stored with
+ * nanoseconds, which only cover 1677-09-21 to 2262-04-11.
+ * <li>The value does not fit into the 16 MiB of a {@code VARIANT}. Any {@code ARRAY}, {@code
+ * MAP} or nested {@code VARIANT} can reach that size. A string or binary type can when
+ * its declared length allows more, and a {@code ROW} when the declared sizes of its
+ * fields add up to more.
+ * <li>A {@code MAP} with a {@code NULL} key fails. Every {@code MAP} can already fail on its
+ * size, so this makes no other type fallible.
+ * </ul>
+ *
+ * <p>Every other type never fails.
+ *
+ * <p>The size check trusts the declared length. Flink does not enforce that length on values
+ * from a source, so a longer value can still reach the cast. {@code TRY_CAST} then fails for it
+ * instead of returning {@code NULL}.
+ */
+ @Override
+ public boolean canFail(LogicalType inputLogicalType, LogicalType targetLogicalType) {
+ // Without an ARRAY, MAP or VARIANT, the size of a value is bounded by the sum of its
+ // leaves and object headers.
+ long maxSize = 0;
+ final Deque<LogicalType> pending = new ArrayDeque<>();
+ pending.push(inputLogicalType);
+ while (!pending.isEmpty()) {
+ final LogicalType type = pending.pop();
+ if (type.is(LogicalTypeRoot.DISTINCT_TYPE)) {
+ pending.push(((DistinctType) type).getSourceType());
+ continue;
+ }
+ switch (type.getTypeRoot()) {
+ case ARRAY:
+ case MAP:
+ case VARIANT:
+ return true;
+ case ROW:
+ case STRUCTURED_TYPE:
+ LogicalTypeChecks.getFieldTypes(type).forEach(pending::push);
+ break;
+ case TIMESTAMP_WITHOUT_TIME_ZONE:
Review Comment:
Good catch, done. `TIME` now counts as fallible in canFail, like `TIMESTAMP(7..9)`, so `TRY_CAST` returns NULL for a `TIME` outside one day. The Javadoc, the docs bullet and the cast matrix now say so, and footnote 8 then covers a `ROW` holding a `TIME`. `CastFunctionITCase` checks it with a UDF that returns a raw millisecond value: `CAST` fails with the `TIME` message, and `TRY_CAST` returns `NULL`. The change is in the second commit.
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-40826][table] Support casting ARRAY, MAP, ROW and STRUCTURED to VARIANT [flink]
Posted by "twalthr (via GitHub)" <gi...@apache.org>.
twalthr merged PR #29369:
URL: https://github.com/apache/flink/pull/29369
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-40826][table] Support casting ARRAY, MAP, ROW and STRUCTURED to VARIANT [flink]
Posted by "raminqaf (via GitHub)" <gi...@apache.org>.
raminqaf commented on code in PR #29369:
URL: https://github.com/apache/flink/pull/29369#discussion_r4184398189
##########
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/functions/ToVariantConverter.java:
##########
@@ -0,0 +1,260 @@
+/*
+ * 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.api.TableRuntimeException;
+import org.apache.flink.table.data.ArrayData;
+import org.apache.flink.table.data.DecimalData;
+import org.apache.flink.table.data.MapData;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.data.TimestampData;
+import org.apache.flink.table.types.logical.ArrayType;
+import org.apache.flink.table.types.logical.DistinctType;
+import org.apache.flink.table.types.logical.LogicalType;
+import org.apache.flink.table.types.logical.LogicalTypeRoot;
+import org.apache.flink.table.types.logical.MapType;
+import org.apache.flink.table.types.logical.utils.LogicalTypeChecks;
+import org.apache.flink.table.types.logical.utils.UuidUtils;
+import org.apache.flink.types.variant.BinaryVariant;
+import org.apache.flink.types.variant.BinaryVariantInternalBuilder;
+import org.apache.flink.types.variant.BinaryVariantInternalBuilder.FieldEntry;
+import org.apache.flink.types.variant.Variant;
+import org.apache.flink.types.variant.VariantTypeException;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Converts internal data of a SQL type into a {@link Variant}, like {@code CAST(x AS VARIANT)}.
+ *
+ * <p>An {@code ARRAY} becomes a variant array. A {@code ROW} or {@code STRUCTURED} value becomes a
+ * variant object keyed by its field names, and a {@code MAP} one keyed by its character string
+ * keys. A {@code NULL} element, field or map value becomes a variant null. A leaf is stored like
+ * the cast stores it on its own, see {@link VariantCastUtils}, and a nested {@code VARIANT} is
+ * embedded as is.
+ *
+ * <p>The converter is created once per type and writes a whole value into one builder, so a nested
+ * value is encoded in a single pass. It keeps no state between calls.
+ */
+@Internal
+public final class ToVariantConverter implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ private final String sourceType;
+ private final ValueWriter writer;
+
+ private ToVariantConverter(String sourceType, ValueWriter writer) {
+ this.sourceType = sourceType;
+ this.writer = writer;
+ }
+
+ /** Creates a converter for a type that {@code LogicalTypeCasts} allows to cast to VARIANT. */
+ public static ToVariantConverter create(LogicalType type) {
+ return new ToVariantConverter(type.asSummaryString(), createWriter(type));
+ }
+
+ /**
+ * Converts a value that is not {@code NULL}.
+ *
+ * @throws TableRuntimeException if the value has a {@code NULL} map key, a timestamp outside
+ * the range of its variant kind, or does not fit into the 16 MiB of a {@code VARIANT}
+ */
+ public Variant convert(Object value) {
+ // A MAP can hold the same key twice at runtime. The builder keeps the last one, like the
+ // MAP constructor does.
+ final BinaryVariantInternalBuilder builder = new BinaryVariantInternalBuilder(true);
+ try {
+ writer.write(builder, value);
+ return builder.build();
+ } catch (VariantTypeException e) {
+ if (e != BinaryVariantInternalBuilder.VARIANT_SIZE_LIMIT_EXCEPTION) {
+ throw e;
+ }
+ throw new TableRuntimeException(
+ String.format(
+ "Cannot cast a value of type %s to VARIANT. A VARIANT is limited to "
+ + "16 MiB.",
+ sourceType));
+ }
+ }
+
+ @FunctionalInterface
+ private interface ValueWriter extends Serializable {
+ void write(BinaryVariantInternalBuilder builder, Object value);
+ }
+
+ private static ValueWriter createNullableWriter(LogicalType type) {
+ final ValueWriter writer = createWriter(type);
+ return (builder, value) -> {
+ if (value == null) {
+ builder.appendNull();
+ } else {
+ writer.write(builder, value);
+ }
+ };
+ }
+
+ private static ValueWriter createWriter(LogicalType type) {
+ switch (type.getTypeRoot()) {
+ case NULL:
+ return (builder, value) -> builder.appendNull();
+ case BOOLEAN:
+ return (builder, value) -> builder.appendBoolean((Boolean) value);
+ case TINYINT:
+ return (builder, value) -> builder.appendByte((Byte) value);
+ case SMALLINT:
+ return (builder, value) -> builder.appendShort((Short) value);
+ case INTEGER:
+ return (builder, value) -> builder.appendInt((Integer) value);
+ case BIGINT:
+ return (builder, value) -> builder.appendLong((Long) value);
+ case FLOAT:
+ return (builder, value) -> builder.appendFloat((Float) value);
+ case DOUBLE:
+ return (builder, value) -> builder.appendDouble((Double) value);
+ case DECIMAL:
+ return (builder, value) ->
+ builder.appendDecimal(((DecimalData) value).toBigDecimal());
+ case CHAR:
+ case VARCHAR:
+ return (builder, value) -> builder.appendString(value.toString());
+ case BINARY:
+ case VARBINARY:
+ return (builder, value) -> builder.appendBinary((byte[]) value);
+ case DATE:
+ return (builder, value) -> builder.appendDate((Integer) value);
+ case TIME_WITHOUT_TIME_ZONE:
+ // TIME is millisecond-of-day at runtime, the variant kind holds microseconds.
+ return (builder, value) -> builder.appendTime((Integer) value * 1_000L);
+ case TIMESTAMP_WITHOUT_TIME_ZONE:
+ {
+ final int precision = LogicalTypeChecks.getPrecision(type);
+ return (builder, value) ->
+ VariantCastUtils.appendTimestamp(
+ builder, (TimestampData) value, precision);
+ }
+ case TIMESTAMP_WITH_LOCAL_TIME_ZONE:
+ {
+ final int precision = LogicalTypeChecks.getPrecision(type);
+ return (builder, value) ->
+ VariantCastUtils.appendTimestampLtz(
+ builder, (TimestampData) value, precision);
+ }
+ case UUID:
+ return (builder, value) -> builder.appendUuid(UuidUtils.fromBytes((byte[]) value));
+ case VARIANT:
Review Comment:
Added StackOverflowError with proper message. I will create a follow up ticket
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-40826][table] Support casting ARRAY, MAP, ROW and STRUCTURED to VARIANT [flink]
Posted by "raminqaf (via GitHub)" <gi...@apache.org>.
raminqaf commented on code in PR #29369:
URL: https://github.com/apache/flink/pull/29369#discussion_r4184355140
##########
flink-core/src/main/java/org/apache/flink/types/variant/BinaryVariantInternalBuilder.java:
##########
@@ -537,7 +537,9 @@ public void finishWritingArray(int start, ArrayList<Integer> offsets) {
// the
// input variant, we can directly copy the binary slice.
public void appendVariant(BinaryVariant v) {
- appendVariantImpl(v.getValue(), v.getMetadata(), v.getPos());
+ // A nested variant, such as a field or an element of another variant, starts at its own
+ // position in the shared buffer. getValue() would copy it to position 0 instead.
+ appendVariantImpl(v.rawValue(), v.getMetadata(), v.getPos());
Review Comment:
Added new ticket and updated the commit: https://issues.apache.org/jira/browse/FLINK-40911
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-40826][table] Support casting ARRAY, MAP, ROW and STRUCTURED to VARIANT [flink]
Posted by "raminqaf (via GitHub)" <gi...@apache.org>.
raminqaf commented on code in PR #29369:
URL: https://github.com/apache/flink/pull/29369#discussion_r4191886227
##########
flink-table/flink-table-common/src/main/java/org/apache/flink/table/data/utils/ToVariantConverter.java:
##########
@@ -0,0 +1,260 @@
+/*
+ * 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.api.TableRuntimeException;
+import org.apache.flink.table.data.ArrayData;
+import org.apache.flink.table.data.DecimalData;
+import org.apache.flink.table.data.MapData;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.data.TimestampData;
+import org.apache.flink.table.types.logical.ArrayType;
+import org.apache.flink.table.types.logical.DistinctType;
+import org.apache.flink.table.types.logical.LogicalType;
+import org.apache.flink.table.types.logical.LogicalTypeRoot;
+import org.apache.flink.table.types.logical.MapType;
+import org.apache.flink.table.types.logical.utils.LogicalTypeChecks;
+import org.apache.flink.table.types.logical.utils.UuidUtils;
+import org.apache.flink.types.variant.BinaryVariant;
+import org.apache.flink.types.variant.BinaryVariantInternalBuilder;
+import org.apache.flink.types.variant.BinaryVariantInternalBuilder.FieldEntry;
+import org.apache.flink.types.variant.Variant;
+import org.apache.flink.types.variant.VariantTypeException;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Converts internal data of a SQL type into a {@link Variant}, like {@code CAST(x AS VARIANT)}.
+ *
+ * <p>An {@code ARRAY} becomes a variant array. A {@code ROW} or {@code STRUCTURED} value becomes a
+ * variant object keyed by its field names, and a {@code MAP} one keyed by its character string
+ * keys. A {@code NULL} element, field or map value becomes a variant null. A leaf is stored like
+ * the cast stores it on its own, see {@link VariantCastUtils}, and a nested {@code VARIANT} is
+ * embedded as is.
+ *
+ * <p>The converter is created once per type and writes a whole value into one builder, so a nested
+ * value is encoded in a single pass. It keeps no state between calls.
+ */
+@Internal
+public final class ToVariantConverter implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ private final String sourceType;
+ private final ValueWriter writer;
+
+ private ToVariantConverter(String sourceType, ValueWriter writer) {
+ this.sourceType = sourceType;
+ this.writer = writer;
+ }
+
+ /** Creates a converter for a type that {@code LogicalTypeCasts} allows to cast to VARIANT. */
+ public static ToVariantConverter create(LogicalType type) {
+ return new ToVariantConverter(type.asSummaryString(), createWriter(type));
+ }
+
+ /**
+ * Converts a value that is not {@code NULL}.
+ *
+ * @throws TableRuntimeException if the value has a {@code NULL} map key, a timestamp outside
+ * the range of its variant kind, or does not fit into the 16 MiB of a {@code VARIANT}
+ */
+ public Variant convert(Object value) {
+ // A MAP can hold the same key twice at runtime. The builder keeps the last one, like the
+ // MAP constructor does.
+ final BinaryVariantInternalBuilder builder = new BinaryVariantInternalBuilder(true);
+ try {
+ writer.write(builder, value);
+ return builder.build();
+ } catch (VariantTypeException e) {
+ if (e != BinaryVariantInternalBuilder.VARIANT_SIZE_LIMIT_EXCEPTION) {
+ throw e;
+ }
+ throw new TableRuntimeException(
+ String.format(
+ "Cannot cast a value of type %s to VARIANT. A VARIANT is limited to "
+ + "16 MiB.",
+ sourceType));
+ }
+ }
+
+ @FunctionalInterface
+ private interface ValueWriter extends Serializable {
+ void write(BinaryVariantInternalBuilder builder, Object value);
+ }
+
+ private static ValueWriter createNullableWriter(LogicalType type) {
+ final ValueWriter writer = createWriter(type);
+ return (builder, value) -> {
+ if (value == null) {
+ builder.appendNull();
+ } else {
+ writer.write(builder, value);
+ }
+ };
+ }
+
+ private static ValueWriter createWriter(LogicalType type) {
+ switch (type.getTypeRoot()) {
+ case NULL:
+ return (builder, value) -> builder.appendNull();
+ case BOOLEAN:
+ return (builder, value) -> builder.appendBoolean((Boolean) value);
+ case TINYINT:
+ return (builder, value) -> builder.appendByte((Byte) value);
+ case SMALLINT:
+ return (builder, value) -> builder.appendShort((Short) value);
+ case INTEGER:
+ return (builder, value) -> builder.appendInt((Integer) value);
+ case BIGINT:
+ return (builder, value) -> builder.appendLong((Long) value);
+ case FLOAT:
+ return (builder, value) -> builder.appendFloat((Float) value);
+ case DOUBLE:
+ return (builder, value) -> builder.appendDouble((Double) value);
+ case DECIMAL:
+ return (builder, value) ->
+ builder.appendDecimal(((DecimalData) value).toBigDecimal());
+ case CHAR:
+ case VARCHAR:
+ return (builder, value) -> builder.appendString(value.toString());
+ case BINARY:
+ case VARBINARY:
+ return (builder, value) -> builder.appendBinary((byte[]) value);
+ case DATE:
+ return (builder, value) -> builder.appendDate((Integer) value);
+ case TIME_WITHOUT_TIME_ZONE:
+ // TIME is millisecond-of-day at runtime, the variant kind holds microseconds.
+ return (builder, value) -> builder.appendTime((Integer) value * 1_000L);
+ case TIMESTAMP_WITHOUT_TIME_ZONE:
+ {
+ final int precision = LogicalTypeChecks.getPrecision(type);
+ return (builder, value) ->
+ VariantCastUtils.appendTimestamp(
+ builder, (TimestampData) value, precision);
+ }
+ case TIMESTAMP_WITH_LOCAL_TIME_ZONE:
+ {
+ final int precision = LogicalTypeChecks.getPrecision(type);
+ return (builder, value) ->
+ VariantCastUtils.appendTimestampLtz(
+ builder, (TimestampData) value, precision);
+ }
+ case UUID:
+ return (builder, value) -> builder.appendUuid(UuidUtils.fromBytes((byte[]) value));
+ case VARIANT:
Review Comment:
https://issues.apache.org/jira/browse/FLINK-40917
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-40826][table] Support casting ARRAY, MAP, ROW and STRUCTURED to VARIANT [flink]
Posted by "twalthr (via GitHub)" <gi...@apache.org>.
twalthr commented on code in PR #29369:
URL: https://github.com/apache/flink/pull/29369#discussion_r4192979851
##########
docs/content.zh/docs/sql/reference/data-types.md:
##########
@@ -1717,7 +1719,46 @@ CAST(NULL AS VARIANT) -- NULL
CAST(CAST('NaN' AS DOUBLE) AS VARIANT) -- NaN, stored as a DOUBLE
CAST(INTERVAL '2' DAY AS VARIANT) -- fails at validation
CAST(ARRAY[1, NULL] AS ARRAY<VARIANT>) -- [1, NULL], each element a VARIANT, the NULL stays SQL NULL
-CAST(ARRAY[1, 2] AS VARIANT) -- fails at validation, not supported yet
+```
+
+A whole `ARRAY`, `MAP`, `ROW`, or `STRUCTURED` value can also be cast into a single `VARIANT`. An
+`ARRAY` becomes a variant array, and a `MAP`, `ROW`, or `STRUCTURED` value a variant object. Each
+leaf is stored by the rules above, so the cast is supported only when every leaf type casts to
+`VARIANT`.
+
+- A `ROW` or `STRUCTURED` value is keyed by its field names. The SQL `ROW` constructor names its
+ fields `EXPR$0`, `EXPR$1`, and so on, and the Table API `row()` names them `f0`, `f1`, and so on.
+ To choose the keys, cast to a `ROW` with named fields first, or name each field with `as()` in the
+ Table API.
Review Comment:
```suggestion
- A `ROW` or `STRUCTURED` value is keyed by its field names.
```
Orthogonal concerns.
##########
docs/content.zh/docs/sql/reference/data-types.md:
##########
@@ -1949,6 +1990,7 @@ COALESCE(TRY_CAST('non-number' AS INT), 0) --- 结果返回数字 0 的 INT 格
5. 支持转换,当且仅当用使用 `INTERVAL` 做“月”到“年”的转换。
6. 支持转换,当且仅当用使用 `INTERVAL` 做“天”到“时间”的转换。
7. 仅支持转换到无界的 `VARBINARY`(`BYTES`),因为裁剪或填充会破坏序列化的位图数据。
+8. 支持转换,当且仅当所有叶子类型都支持转换为 `VARIANT`,并且所有 `MAP` 的键都是字符串类型。`ARRAY` 和 `MAP` 的转换总是可能会失败。`ROW` 和 `STRUCTURED` 的转换可能会失败,当且仅当某个字段可能转换失败、某个字段是 `VARIANT`,或者字段声明的总大小可能超过 `VARIANT` 的 16 MiB 上限。
Review Comment:
Don't add Chinese.
##########
flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/codegen/CodeGeneratorContext.scala:
##########
@@ -834,6 +839,31 @@ class CodeGeneratorContext(
addReusableObjectWithName(obj, newName(this, fieldNamePrefix), fieldTypeTerm)
}
+ /**
+ * Adds a reusable Object to the member area of the generated class, unless one was added for an
+ * equal key before. The factory only runs when the object is added.
+ *
+ * @param key
+ * the key that identifies the object
+ * @param factory
+ * creates the object to be added to the generated class
+ * @param fieldNamePrefix
+ * prefix field name of the generated member field term
+ * @param fieldTypeTerm
+ * field type class name
+ * @return
+ * the field term of the object for the key
+ */
+ def addReusableObjectIfAbsent(
Review Comment:
Could you double check if there available reusable methods really don't work? The context is complex enough, I would like to avoid complexity.
##########
docs/content.zh/docs/sql/reference/data-types.md:
##########
@@ -1717,7 +1719,46 @@ CAST(NULL AS VARIANT) -- NULL
CAST(CAST('NaN' AS DOUBLE) AS VARIANT) -- NaN, stored as a DOUBLE
CAST(INTERVAL '2' DAY AS VARIANT) -- fails at validation
CAST(ARRAY[1, NULL] AS ARRAY<VARIANT>) -- [1, NULL], each element a VARIANT, the NULL stays SQL NULL
-CAST(ARRAY[1, 2] AS VARIANT) -- fails at validation, not supported yet
+```
+
+A whole `ARRAY`, `MAP`, `ROW`, or `STRUCTURED` value can also be cast into a single `VARIANT`. An
+`ARRAY` becomes a variant array, and a `MAP`, `ROW`, or `STRUCTURED` value a variant object. Each
+leaf is stored by the rules above, so the cast is supported only when every leaf type casts to
+`VARIANT`.
+
+- A `ROW` or `STRUCTURED` value is keyed by its field names. The SQL `ROW` constructor names its
+ fields `EXPR$0`, `EXPR$1`, and so on, and the Table API `row()` names them `f0`, `f1`, and so on.
+ To choose the keys, cast to a `ROW` with named fields first, or name each field with `as()` in the
+ Table API.
+- A `MAP` needs a character string key, which becomes the object key. A `NULL` key fails the cast.
+ If a key appears twice, the last value is kept. The order of the entries is part of the encoding,
+ so two `MAP`s with the same entries in a different order cast to `VARIANT` values that are not
Review Comment:
I find it a bit inconsistent to sort for rows but not for maps. Rows would have been more important to keep the order tbh because they are positional.
##########
flink-table/flink-table-common/src/main/java/org/apache/flink/table/data/utils/ToVariantConverter.java:
##########
@@ -0,0 +1,437 @@
+/*
+ * 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.data.utils;
+
+import org.apache.flink.annotation.Internal;
+import org.apache.flink.core.memory.MemorySegment;
+import org.apache.flink.table.api.TableRuntimeException;
+import org.apache.flink.table.data.ArrayData;
+import org.apache.flink.table.data.DecimalData;
+import org.apache.flink.table.data.MapData;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.data.StringData;
+import org.apache.flink.table.data.TimestampData;
+import org.apache.flink.table.data.binary.BinaryStringData;
+import org.apache.flink.table.data.binary.StringUtf8Utils;
+import org.apache.flink.table.types.logical.ArrayType;
+import org.apache.flink.table.types.logical.DistinctType;
+import org.apache.flink.table.types.logical.LogicalType;
+import org.apache.flink.table.types.logical.LogicalTypeFamily;
+import org.apache.flink.table.types.logical.LogicalTypeRoot;
+import org.apache.flink.table.types.logical.MapType;
+import org.apache.flink.table.types.logical.utils.LogicalTypeChecks;
+import org.apache.flink.table.types.logical.utils.UuidUtils;
+import org.apache.flink.types.variant.BinaryVariant;
+import org.apache.flink.types.variant.BinaryVariantInternalBuilder;
+import org.apache.flink.types.variant.BinaryVariantInternalBuilder.FieldEntry;
+import org.apache.flink.types.variant.BinaryVariantUtil;
+import org.apache.flink.types.variant.Variant;
+import org.apache.flink.types.variant.VariantTypeException;
+
+import java.io.Serializable;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.List;
+
+import static org.apache.flink.table.utils.DateTimeUtils.MILLIS_PER_DAY;
+
+/**
+ * Converts internal data of a SQL type into a {@link Variant}. It implements {@code CAST(x AS
+ * VARIANT)}, and a format can use it to store a value in a {@code VARIANT} the same way.
+ *
+ * <p>A leaf keeps the kind of its SQL type. For example, a {@code BIGINT} is stored as a {@code
+ * BIGINT}, even when it would fit a smaller kind. A {@code TIMESTAMP(p)} or {@code
+ * TIMESTAMP_LTZ(p)} is stored with microseconds up to {@code p = 6} and with nanoseconds above,
+ * whatever the digits of the value. A {@code NaN} or infinite {@code FLOAT} or {@code DOUBLE} is
+ * stored as is, although {@code PARSE_JSON} rejects it.
+ *
+ * <p>An {@code ARRAY} becomes a variant array. A {@code ROW} or {@code STRUCTURED} value becomes a
+ * variant object keyed by its field names, and a {@code MAP} one keyed by its character string
+ * keys. A {@code NULL} becomes a variant null, and a nested {@code VARIANT} is copied in as is.
+ *
+ * <p>The converter is created once per type and writes a whole value into one builder. A nested
+ * {@code ARRAY}, {@code MAP} or {@code ROW} is written in place rather than built as a separate
+ * variant first. The converter keeps no state between calls.
+ */
+@Internal
+public final class ToVariantConverter implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ /** The highest timestamp precision a {@code VARIANT} stores with microseconds. */
+ public static final int TIMESTAMP_PRECISION = 6;
+
+ /**
+ * The largest string or binary value a {@code VARIANT} holds, in bytes. A {@code VARIANT} is
+ * limited to 16 MiB, and a long string or binary value spends 5 bytes of that on its header.
+ */
+ public static final int MAX_PAYLOAD_BYTES =
+ BinaryVariantUtil.SIZE_LIMIT - 1 - BinaryVariantUtil.U32_SIZE;
+
+ private final String sourceType;
+ private final ValueWriter writer;
+
+ private ToVariantConverter(String sourceType, ValueWriter writer) {
+ this.sourceType = sourceType;
+ this.writer = writer;
+ }
+
+ /**
+ * Creates a converter for a type that {@code LogicalTypeCasts} allows to cast to VARIANT.
+ *
+ * @throws IllegalArgumentException if the type cannot be cast to VARIANT
+ */
+ public static ToVariantConverter create(LogicalType type) {
+ return new ToVariantConverter(type.asSummaryString(), createNullableWriter(type));
+ }
+
+ /**
+ * Converts a value into a new {@code VARIANT}. A {@code null} value becomes a variant null.
+ *
+ * @throws TableRuntimeException if the value has a {@code NULL} map key, a time or timestamp
+ * outside the range of its variant kind, does not fit into the 16 MiB of a {@code VARIANT},
+ * or is nested too deeply
+ * @throws VariantTypeException if a nested {@code VARIANT} is malformed
+ */
+ public Variant convert(Object value) {
+ // A MAP can hold the same key twice at runtime. The builder keeps the last one, like the
+ // MAP constructor does.
+ final BinaryVariantInternalBuilder builder = new BinaryVariantInternalBuilder(true);
+ try {
+ writeTo(builder, value);
+ return builder.build();
+ } catch (VariantTypeException e) {
+ if (e != BinaryVariantInternalBuilder.VARIANT_SIZE_LIMIT_EXCEPTION) {
+ throw e;
+ }
+ throw new TableRuntimeException(
+ String.format(
+ "Cannot cast a value of type %s to VARIANT. A VARIANT is limited to "
+ + "16 MiB.",
+ sourceType));
+ } catch (StackOverflowError e) {
+ // The builder copies an embedded VARIANT with one call per nesting level, so a deeply
+ // nested one overflows the stack. A bare StackOverflowError would not say which cast
+ // failed or why.
+ throw new TableRuntimeException(
+ String.format(
+ "Cannot cast a value of type %s to VARIANT because it is nested too "
+ + "deeply.",
+ sourceType));
+ }
+ }
+
+ /**
+ * Writes a value into a builder that the caller owns, for example as a field of a larger {@code
+ * VARIANT}. A {@code null} value becomes a variant null.
+ *
+ * <p>It fails like {@link #convert} for a {@code NULL} map key, a time or timestamp out of
+ * range, and a string or binary value that can never fit. The caller builds the result, so it
+ * handles {@link BinaryVariantInternalBuilder#VARIANT_SIZE_LIMIT_EXCEPTION} and a {@link
+ * StackOverflowError} from a deeply nested {@code VARIANT} itself. A repeated {@code MAP} key
+ * keeps the last value if the caller's builder allows duplicate keys, and fails otherwise. The
+ * builder holds partial data after a failure, so the caller must not use it any further.
+ */
+ public void writeTo(BinaryVariantInternalBuilder builder, Object value) {
+ writer.write(builder, value);
+ }
+
+ @FunctionalInterface
+ private interface ValueWriter extends Serializable {
+ void write(BinaryVariantInternalBuilder builder, Object value);
+ }
+
+ private static ValueWriter createNullableWriter(LogicalType type) {
+ final ValueWriter writer = createWriter(type);
+ return (builder, value) -> {
+ if (value == null) {
+ builder.appendNull();
+ } else {
+ writer.write(builder, value);
+ }
+ };
+ }
+
+ private static ValueWriter createWriter(LogicalType type) {
+ switch (type.getTypeRoot()) {
+ case NULL:
+ return (builder, value) -> builder.appendNull();
+ case BOOLEAN:
+ return (builder, value) -> builder.appendBoolean((Boolean) value);
+ case TINYINT:
+ return (builder, value) -> builder.appendByte((Byte) value);
+ case SMALLINT:
+ return (builder, value) -> builder.appendShort((Short) value);
+ case INTEGER:
+ return (builder, value) -> builder.appendInt((Integer) value);
+ case BIGINT:
+ return (builder, value) -> builder.appendLong((Long) value);
+ case FLOAT:
+ return (builder, value) -> builder.appendFloat((Float) value);
+ case DOUBLE:
+ return (builder, value) -> builder.appendDouble((Double) value);
+ case DECIMAL:
+ return (builder, value) -> appendDecimal(builder, (DecimalData) value);
+ case CHAR:
+ case VARCHAR:
+ return (builder, value) -> appendString(builder, (StringData) value);
+ case BINARY:
+ case VARBINARY:
+ return (builder, value) -> appendBinary(builder, (byte[]) value);
+ case DATE:
+ return (builder, value) -> builder.appendDate((Integer) value);
+ case TIME_WITHOUT_TIME_ZONE:
+ return (builder, value) -> builder.appendTime(timeMicros((Integer) value));
+ case TIMESTAMP_WITHOUT_TIME_ZONE:
+ {
+ final int precision = LogicalTypeChecks.getPrecision(type);
+ if (precision <= TIMESTAMP_PRECISION) {
+ return (builder, value) ->
+ builder.appendTimestamp(timestampMicros((TimestampData) value));
+ }
+ final String timestampType = "TIMESTAMP(" + precision + ")";
+ return (builder, value) ->
+ builder.appendTimestampNanos(
+ timestampNanos((TimestampData) value, timestampType));
+ }
+ case TIMESTAMP_WITH_LOCAL_TIME_ZONE:
+ {
+ final int precision = LogicalTypeChecks.getPrecision(type);
+ if (precision <= TIMESTAMP_PRECISION) {
+ return (builder, value) ->
+ builder.appendTimestampLtz(timestampMicros((TimestampData) value));
+ }
+ final String timestampType = "TIMESTAMP_LTZ(" + precision + ")";
+ return (builder, value) ->
+ builder.appendTimestampLtzNanos(
+ timestampNanos((TimestampData) value, timestampType));
+ }
+ case UUID:
+ return (builder, value) -> builder.appendUuid(UuidUtils.fromBytes((byte[]) value));
+ case VARIANT:
+ return (builder, value) -> builder.appendVariant((BinaryVariant) value);
+ case ARRAY:
+ return createArrayWriter((ArrayType) type);
+ case MAP:
+ return createMapWriter((MapType) type);
+ case ROW:
+ case STRUCTURED_TYPE:
+ return createRowWriter(type);
+ case DISTINCT_TYPE:
+ return createWriter(((DistinctType) type).getSourceType());
+ default:
+ throw new IllegalArgumentException("Cannot cast " + type + " to VARIANT.");
+ }
+ }
+
+ // A compact decimal is written from its unscaled long, which saves building a BigDecimal.
+ private static void appendDecimal(BinaryVariantInternalBuilder builder, DecimalData value) {
+ if (value.isCompact()) {
+ builder.appendDecimal(value.toUnscaledLong(), value.scale());
+ } else {
+ builder.appendDecimal(value.toBigDecimal());
+ }
+ }
+
+ private static void appendString(BinaryVariantInternalBuilder builder, StringData value) {
+ final BinaryStringData string = (BinaryStringData) value;
+ try {
+ appendUtf8(builder, string);
+ } catch (VariantTypeException e) {
+ throw payloadTooLarge(e, "string", string.getSizeInBytes());
+ }
+ }
+
+ /**
+ * Stores the UTF-8 bytes of the string as they are. A {@link StringData} may hold invalid
+ * UTF-8, which the variant spec does not allow, so such a value is decoded first and every
+ * malformed sequence is stored as the U+FFFD replacement character.
+ */
+ private static void appendUtf8(BinaryVariantInternalBuilder builder, BinaryStringData string) {
+ if (string.getBinarySection() == null) {
Review Comment:
Don't we have utils in StringUtf8Utils that help you converting a StringData to a byte array? Ideally we have can share this logic, if not the logic should at least be in StringUtf8Utils.
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-40826][table] Support casting ARRAY, MAP, ROW and STRUCTURED to VARIANT [flink]
Posted by "raminqaf (via GitHub)" <gi...@apache.org>.
raminqaf commented on code in PR #29369:
URL: https://github.com/apache/flink/pull/29369#discussion_r4184329418
##########
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/functions/ToVariantConverter.java:
##########
@@ -0,0 +1,260 @@
+/*
+ * 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.api.TableRuntimeException;
+import org.apache.flink.table.data.ArrayData;
+import org.apache.flink.table.data.DecimalData;
+import org.apache.flink.table.data.MapData;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.data.TimestampData;
+import org.apache.flink.table.types.logical.ArrayType;
+import org.apache.flink.table.types.logical.DistinctType;
+import org.apache.flink.table.types.logical.LogicalType;
+import org.apache.flink.table.types.logical.LogicalTypeRoot;
+import org.apache.flink.table.types.logical.MapType;
+import org.apache.flink.table.types.logical.utils.LogicalTypeChecks;
+import org.apache.flink.table.types.logical.utils.UuidUtils;
+import org.apache.flink.types.variant.BinaryVariant;
+import org.apache.flink.types.variant.BinaryVariantInternalBuilder;
+import org.apache.flink.types.variant.BinaryVariantInternalBuilder.FieldEntry;
+import org.apache.flink.types.variant.Variant;
+import org.apache.flink.types.variant.VariantTypeException;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Converts internal data of a SQL type into a {@link Variant}, like {@code CAST(x AS VARIANT)}.
+ *
+ * <p>An {@code ARRAY} becomes a variant array. A {@code ROW} or {@code STRUCTURED} value becomes a
+ * variant object keyed by its field names, and a {@code MAP} one keyed by its character string
+ * keys. A {@code NULL} element, field or map value becomes a variant null. A leaf is stored like
+ * the cast stores it on its own, see {@link VariantCastUtils}, and a nested {@code VARIANT} is
+ * embedded as is.
+ *
+ * <p>The converter is created once per type and writes a whole value into one builder, so a nested
+ * value is encoded in a single pass. It keeps no state between calls.
+ */
+@Internal
+public final class ToVariantConverter implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ private final String sourceType;
+ private final ValueWriter writer;
+
+ private ToVariantConverter(String sourceType, ValueWriter writer) {
+ this.sourceType = sourceType;
+ this.writer = writer;
+ }
+
+ /** Creates a converter for a type that {@code LogicalTypeCasts} allows to cast to VARIANT. */
+ public static ToVariantConverter create(LogicalType type) {
+ return new ToVariantConverter(type.asSummaryString(), createWriter(type));
+ }
+
+ /**
+ * Converts a value that is not {@code NULL}.
+ *
+ * @throws TableRuntimeException if the value has a {@code NULL} map key, a timestamp outside
+ * the range of its variant kind, or does not fit into the 16 MiB of a {@code VARIANT}
+ */
+ public Variant convert(Object value) {
+ // A MAP can hold the same key twice at runtime. The builder keeps the last one, like the
+ // MAP constructor does.
+ final BinaryVariantInternalBuilder builder = new BinaryVariantInternalBuilder(true);
Review Comment:
Thanks, noted. I'll leave it for now and come back to it if the cast shows up in a profile.
##########
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/functions/ToVariantConverter.java:
##########
@@ -0,0 +1,260 @@
+/*
+ * 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.api.TableRuntimeException;
+import org.apache.flink.table.data.ArrayData;
+import org.apache.flink.table.data.DecimalData;
+import org.apache.flink.table.data.MapData;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.data.TimestampData;
+import org.apache.flink.table.types.logical.ArrayType;
+import org.apache.flink.table.types.logical.DistinctType;
+import org.apache.flink.table.types.logical.LogicalType;
+import org.apache.flink.table.types.logical.LogicalTypeRoot;
+import org.apache.flink.table.types.logical.MapType;
+import org.apache.flink.table.types.logical.utils.LogicalTypeChecks;
+import org.apache.flink.table.types.logical.utils.UuidUtils;
+import org.apache.flink.types.variant.BinaryVariant;
+import org.apache.flink.types.variant.BinaryVariantInternalBuilder;
+import org.apache.flink.types.variant.BinaryVariantInternalBuilder.FieldEntry;
+import org.apache.flink.types.variant.Variant;
+import org.apache.flink.types.variant.VariantTypeException;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Converts internal data of a SQL type into a {@link Variant}, like {@code CAST(x AS VARIANT)}.
+ *
+ * <p>An {@code ARRAY} becomes a variant array. A {@code ROW} or {@code STRUCTURED} value becomes a
+ * variant object keyed by its field names, and a {@code MAP} one keyed by its character string
+ * keys. A {@code NULL} element, field or map value becomes a variant null. A leaf is stored like
+ * the cast stores it on its own, see {@link VariantCastUtils}, and a nested {@code VARIANT} is
+ * embedded as is.
+ *
+ * <p>The converter is created once per type and writes a whole value into one builder, so a nested
Review Comment:
Reworded.
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-40826][table] Support casting ARRAY, MAP, ROW and STRUCTURED to VARIANT [flink]
Posted by "raminqaf (via GitHub)" <gi...@apache.org>.
raminqaf commented on code in PR #29369:
URL: https://github.com/apache/flink/pull/29369#discussion_r4184318671
##########
flink-table/flink-table-runtime/src/main/java/org/apache/flink/table/runtime/functions/ToVariantConverter.java:
##########
@@ -0,0 +1,260 @@
+/*
+ * 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.api.TableRuntimeException;
+import org.apache.flink.table.data.ArrayData;
+import org.apache.flink.table.data.DecimalData;
+import org.apache.flink.table.data.MapData;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.data.TimestampData;
+import org.apache.flink.table.types.logical.ArrayType;
+import org.apache.flink.table.types.logical.DistinctType;
+import org.apache.flink.table.types.logical.LogicalType;
+import org.apache.flink.table.types.logical.LogicalTypeRoot;
+import org.apache.flink.table.types.logical.MapType;
+import org.apache.flink.table.types.logical.utils.LogicalTypeChecks;
+import org.apache.flink.table.types.logical.utils.UuidUtils;
+import org.apache.flink.types.variant.BinaryVariant;
+import org.apache.flink.types.variant.BinaryVariantInternalBuilder;
+import org.apache.flink.types.variant.BinaryVariantInternalBuilder.FieldEntry;
+import org.apache.flink.types.variant.Variant;
+import org.apache.flink.types.variant.VariantTypeException;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Converts internal data of a SQL type into a {@link Variant}, like {@code CAST(x AS VARIANT)}.
+ *
+ * <p>An {@code ARRAY} becomes a variant array. A {@code ROW} or {@code STRUCTURED} value becomes a
+ * variant object keyed by its field names, and a {@code MAP} one keyed by its character string
+ * keys. A {@code NULL} element, field or map value becomes a variant null. A leaf is stored like
+ * the cast stores it on its own, see {@link VariantCastUtils}, and a nested {@code VARIANT} is
+ * embedded as is.
+ *
+ * <p>The converter is created once per type and writes a whole value into one builder, so a nested
+ * value is encoded in a single pass. It keeps no state between calls.
+ */
+@Internal
+public final class ToVariantConverter implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ private final String sourceType;
+ private final ValueWriter writer;
+
+ private ToVariantConverter(String sourceType, ValueWriter writer) {
+ this.sourceType = sourceType;
+ this.writer = writer;
+ }
+
+ /** Creates a converter for a type that {@code LogicalTypeCasts} allows to cast to VARIANT. */
+ public static ToVariantConverter create(LogicalType type) {
+ return new ToVariantConverter(type.asSummaryString(), createWriter(type));
+ }
+
+ /**
+ * Converts a value that is not {@code NULL}.
+ *
+ * @throws TableRuntimeException if the value has a {@code NULL} map key, a timestamp outside
+ * the range of its variant kind, or does not fit into the 16 MiB of a {@code VARIANT}
+ */
+ public Variant convert(Object value) {
+ // A MAP can hold the same key twice at runtime. The builder keeps the last one, like the
+ // MAP constructor does.
+ final BinaryVariantInternalBuilder builder = new BinaryVariantInternalBuilder(true);
+ try {
+ writer.write(builder, value);
+ return builder.build();
+ } catch (VariantTypeException e) {
+ if (e != BinaryVariantInternalBuilder.VARIANT_SIZE_LIMIT_EXCEPTION) {
+ throw e;
+ }
+ throw new TableRuntimeException(
+ String.format(
+ "Cannot cast a value of type %s to VARIANT. A VARIANT is limited to "
+ + "16 MiB.",
+ sourceType));
+ }
+ }
+
+ @FunctionalInterface
+ private interface ValueWriter extends Serializable {
+ void write(BinaryVariantInternalBuilder builder, Object value);
+ }
+
+ private static ValueWriter createNullableWriter(LogicalType type) {
+ final ValueWriter writer = createWriter(type);
+ return (builder, value) -> {
+ if (value == null) {
+ builder.appendNull();
+ } else {
+ writer.write(builder, value);
+ }
+ };
+ }
+
+ private static ValueWriter createWriter(LogicalType type) {
Review Comment:
Done, with your second option. `ToVariantCastRule` replaces `PrimitiveToVariantCastRule`, and the primitive cast now calls `ToVariantConverter` too. `createWriter` is now the only mapping from a SQL type to a variant kind, and the `VariantCastUtils.from*` methods are gone. The string and decimal fast paths from #29370 will move into the converter's writers.
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-40826][table] Support casting ARRAY, MAP, ROW and STRUCTURED to VARIANT [flink]
Posted by "raminqaf (via GitHub)" <gi...@apache.org>.
raminqaf commented on code in PR #29369:
URL: https://github.com/apache/flink/pull/29369#discussion_r4193547767
##########
docs/content.zh/docs/sql/reference/data-types.md:
##########
@@ -1717,7 +1719,46 @@ CAST(NULL AS VARIANT) -- NULL
CAST(CAST('NaN' AS DOUBLE) AS VARIANT) -- NaN, stored as a DOUBLE
CAST(INTERVAL '2' DAY AS VARIANT) -- fails at validation
CAST(ARRAY[1, NULL] AS ARRAY<VARIANT>) -- [1, NULL], each element a VARIANT, the NULL stays SQL NULL
-CAST(ARRAY[1, 2] AS VARIANT) -- fails at validation, not supported yet
+```
+
+A whole `ARRAY`, `MAP`, `ROW`, or `STRUCTURED` value can also be cast into a single `VARIANT`. An
+`ARRAY` becomes a variant array, and a `MAP`, `ROW`, or `STRUCTURED` value a variant object. Each
+leaf is stored by the rules above, so the cast is supported only when every leaf type casts to
+`VARIANT`.
+
+- A `ROW` or `STRUCTURED` value is keyed by its field names. The SQL `ROW` constructor names its
+ fields `EXPR$0`, `EXPR$1`, and so on, and the Table API `row()` names them `f0`, `f1`, and so on.
+ To choose the keys, cast to a `ROW` with named fields first, or name each field with `as()` in the
+ Table API.
Review Comment:
Done. I also removed the two `EXPR$0` examples, since they show the same thing.
##########
docs/content.zh/docs/sql/reference/data-types.md:
##########
@@ -1717,7 +1719,46 @@ CAST(NULL AS VARIANT) -- NULL
CAST(CAST('NaN' AS DOUBLE) AS VARIANT) -- NaN, stored as a DOUBLE
CAST(INTERVAL '2' DAY AS VARIANT) -- fails at validation
CAST(ARRAY[1, NULL] AS ARRAY<VARIANT>) -- [1, NULL], each element a VARIANT, the NULL stays SQL NULL
-CAST(ARRAY[1, 2] AS VARIANT) -- fails at validation, not supported yet
+```
+
+A whole `ARRAY`, `MAP`, `ROW`, or `STRUCTURED` value can also be cast into a single `VARIANT`. An
+`ARRAY` becomes a variant array, and a `MAP`, `ROW`, or `STRUCTURED` value a variant object. Each
+leaf is stored by the rules above, so the cast is supported only when every leaf type casts to
+`VARIANT`.
+
+- A `ROW` or `STRUCTURED` value is keyed by its field names. The SQL `ROW` constructor names its
+ fields `EXPR$0`, `EXPR$1`, and so on, and the Table API `row()` names them `f0`, `f1`, and so on.
+ To choose the keys, cast to a `ROW` with named fields first, or name each field with `as()` in the
+ Table API.
+- A `MAP` needs a character string key, which becomes the object key. A `NULL` key fails the cast.
+ If a key appears twice, the last value is kept. The order of the entries is part of the encoding,
+ so two `MAP`s with the same entries in a different order cast to `VARIANT` values that are not
Review Comment:
Both are sorted. A ROW and a MAP both become a variant object, and the spec orders object fields by key. The docs wrongly suggested that a MAP keeps its order. I fixed that, and the example is now `MAP['b', 2, 'a', 1]`, which comes back as `{"a": 1, "b": 2}`.
The MAP note was only about equality. The entry order still shapes the bytes, so the same entries in a different order give VARIANTs that are not equal. Sorting the entries first would fix that, at the cost of a sort per value. I would leave that for a follow-up.
##########
docs/content.zh/docs/sql/reference/data-types.md:
##########
@@ -1949,6 +1990,7 @@ COALESCE(TRY_CAST('non-number' AS INT), 0) --- 结果返回数字 0 的 INT 格
5. 支持转换,当且仅当用使用 `INTERVAL` 做“月”到“年”的转换。
6. 支持转换,当且仅当用使用 `INTERVAL` 做“天”到“时间”的转换。
7. 仅支持转换到无界的 `VARBINARY`(`BYTES`),因为裁剪或填充会破坏序列化的位图数据。
+8. 支持转换,当且仅当所有叶子类型都支持转换为 `VARIANT`,并且所有 `MAP` 的键都是字符串类型。`ARRAY` 和 `MAP` 的转换总是可能会失败。`ROW` 和 `STRUCTURED` 的转换可能会失败,当且仅当某个字段可能转换失败、某个字段是 `VARIANT`,或者字段声明的总大小可能超过 `VARIANT` 的 16 MiB 上限。
Review Comment:
Done, reverted.
##########
flink-table/flink-table-common/src/main/java/org/apache/flink/table/data/utils/ToVariantConverter.java:
##########
@@ -0,0 +1,437 @@
+/*
+ * 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.data.utils;
+
+import org.apache.flink.annotation.Internal;
+import org.apache.flink.core.memory.MemorySegment;
+import org.apache.flink.table.api.TableRuntimeException;
+import org.apache.flink.table.data.ArrayData;
+import org.apache.flink.table.data.DecimalData;
+import org.apache.flink.table.data.MapData;
+import org.apache.flink.table.data.RowData;
+import org.apache.flink.table.data.StringData;
+import org.apache.flink.table.data.TimestampData;
+import org.apache.flink.table.data.binary.BinaryStringData;
+import org.apache.flink.table.data.binary.StringUtf8Utils;
+import org.apache.flink.table.types.logical.ArrayType;
+import org.apache.flink.table.types.logical.DistinctType;
+import org.apache.flink.table.types.logical.LogicalType;
+import org.apache.flink.table.types.logical.LogicalTypeFamily;
+import org.apache.flink.table.types.logical.LogicalTypeRoot;
+import org.apache.flink.table.types.logical.MapType;
+import org.apache.flink.table.types.logical.utils.LogicalTypeChecks;
+import org.apache.flink.table.types.logical.utils.UuidUtils;
+import org.apache.flink.types.variant.BinaryVariant;
+import org.apache.flink.types.variant.BinaryVariantInternalBuilder;
+import org.apache.flink.types.variant.BinaryVariantInternalBuilder.FieldEntry;
+import org.apache.flink.types.variant.BinaryVariantUtil;
+import org.apache.flink.types.variant.Variant;
+import org.apache.flink.types.variant.VariantTypeException;
+
+import java.io.Serializable;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.List;
+
+import static org.apache.flink.table.utils.DateTimeUtils.MILLIS_PER_DAY;
+
+/**
+ * Converts internal data of a SQL type into a {@link Variant}. It implements {@code CAST(x AS
+ * VARIANT)}, and a format can use it to store a value in a {@code VARIANT} the same way.
+ *
+ * <p>A leaf keeps the kind of its SQL type. For example, a {@code BIGINT} is stored as a {@code
+ * BIGINT}, even when it would fit a smaller kind. A {@code TIMESTAMP(p)} or {@code
+ * TIMESTAMP_LTZ(p)} is stored with microseconds up to {@code p = 6} and with nanoseconds above,
+ * whatever the digits of the value. A {@code NaN} or infinite {@code FLOAT} or {@code DOUBLE} is
+ * stored as is, although {@code PARSE_JSON} rejects it.
+ *
+ * <p>An {@code ARRAY} becomes a variant array. A {@code ROW} or {@code STRUCTURED} value becomes a
+ * variant object keyed by its field names, and a {@code MAP} one keyed by its character string
+ * keys. A {@code NULL} becomes a variant null, and a nested {@code VARIANT} is copied in as is.
+ *
+ * <p>The converter is created once per type and writes a whole value into one builder. A nested
+ * {@code ARRAY}, {@code MAP} or {@code ROW} is written in place rather than built as a separate
+ * variant first. The converter keeps no state between calls.
+ */
+@Internal
+public final class ToVariantConverter implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ /** The highest timestamp precision a {@code VARIANT} stores with microseconds. */
+ public static final int TIMESTAMP_PRECISION = 6;
+
+ /**
+ * The largest string or binary value a {@code VARIANT} holds, in bytes. A {@code VARIANT} is
+ * limited to 16 MiB, and a long string or binary value spends 5 bytes of that on its header.
+ */
+ public static final int MAX_PAYLOAD_BYTES =
+ BinaryVariantUtil.SIZE_LIMIT - 1 - BinaryVariantUtil.U32_SIZE;
+
+ private final String sourceType;
+ private final ValueWriter writer;
+
+ private ToVariantConverter(String sourceType, ValueWriter writer) {
+ this.sourceType = sourceType;
+ this.writer = writer;
+ }
+
+ /**
+ * Creates a converter for a type that {@code LogicalTypeCasts} allows to cast to VARIANT.
+ *
+ * @throws IllegalArgumentException if the type cannot be cast to VARIANT
+ */
+ public static ToVariantConverter create(LogicalType type) {
+ return new ToVariantConverter(type.asSummaryString(), createNullableWriter(type));
+ }
+
+ /**
+ * Converts a value into a new {@code VARIANT}. A {@code null} value becomes a variant null.
+ *
+ * @throws TableRuntimeException if the value has a {@code NULL} map key, a time or timestamp
+ * outside the range of its variant kind, does not fit into the 16 MiB of a {@code VARIANT},
+ * or is nested too deeply
+ * @throws VariantTypeException if a nested {@code VARIANT} is malformed
+ */
+ public Variant convert(Object value) {
+ // A MAP can hold the same key twice at runtime. The builder keeps the last one, like the
+ // MAP constructor does.
+ final BinaryVariantInternalBuilder builder = new BinaryVariantInternalBuilder(true);
+ try {
+ writeTo(builder, value);
+ return builder.build();
+ } catch (VariantTypeException e) {
+ if (e != BinaryVariantInternalBuilder.VARIANT_SIZE_LIMIT_EXCEPTION) {
+ throw e;
+ }
+ throw new TableRuntimeException(
+ String.format(
+ "Cannot cast a value of type %s to VARIANT. A VARIANT is limited to "
+ + "16 MiB.",
+ sourceType));
+ } catch (StackOverflowError e) {
+ // The builder copies an embedded VARIANT with one call per nesting level, so a deeply
+ // nested one overflows the stack. A bare StackOverflowError would not say which cast
+ // failed or why.
+ throw new TableRuntimeException(
+ String.format(
+ "Cannot cast a value of type %s to VARIANT because it is nested too "
+ + "deeply.",
+ sourceType));
+ }
+ }
+
+ /**
+ * Writes a value into a builder that the caller owns, for example as a field of a larger {@code
+ * VARIANT}. A {@code null} value becomes a variant null.
+ *
+ * <p>It fails like {@link #convert} for a {@code NULL} map key, a time or timestamp out of
+ * range, and a string or binary value that can never fit. The caller builds the result, so it
+ * handles {@link BinaryVariantInternalBuilder#VARIANT_SIZE_LIMIT_EXCEPTION} and a {@link
+ * StackOverflowError} from a deeply nested {@code VARIANT} itself. A repeated {@code MAP} key
+ * keeps the last value if the caller's builder allows duplicate keys, and fails otherwise. The
+ * builder holds partial data after a failure, so the caller must not use it any further.
+ */
+ public void writeTo(BinaryVariantInternalBuilder builder, Object value) {
+ writer.write(builder, value);
+ }
+
+ @FunctionalInterface
+ private interface ValueWriter extends Serializable {
+ void write(BinaryVariantInternalBuilder builder, Object value);
+ }
+
+ private static ValueWriter createNullableWriter(LogicalType type) {
+ final ValueWriter writer = createWriter(type);
+ return (builder, value) -> {
+ if (value == null) {
+ builder.appendNull();
+ } else {
+ writer.write(builder, value);
+ }
+ };
+ }
+
+ private static ValueWriter createWriter(LogicalType type) {
+ switch (type.getTypeRoot()) {
+ case NULL:
+ return (builder, value) -> builder.appendNull();
+ case BOOLEAN:
+ return (builder, value) -> builder.appendBoolean((Boolean) value);
+ case TINYINT:
+ return (builder, value) -> builder.appendByte((Byte) value);
+ case SMALLINT:
+ return (builder, value) -> builder.appendShort((Short) value);
+ case INTEGER:
+ return (builder, value) -> builder.appendInt((Integer) value);
+ case BIGINT:
+ return (builder, value) -> builder.appendLong((Long) value);
+ case FLOAT:
+ return (builder, value) -> builder.appendFloat((Float) value);
+ case DOUBLE:
+ return (builder, value) -> builder.appendDouble((Double) value);
+ case DECIMAL:
+ return (builder, value) -> appendDecimal(builder, (DecimalData) value);
+ case CHAR:
+ case VARCHAR:
+ return (builder, value) -> appendString(builder, (StringData) value);
+ case BINARY:
+ case VARBINARY:
+ return (builder, value) -> appendBinary(builder, (byte[]) value);
+ case DATE:
+ return (builder, value) -> builder.appendDate((Integer) value);
+ case TIME_WITHOUT_TIME_ZONE:
+ return (builder, value) -> builder.appendTime(timeMicros((Integer) value));
+ case TIMESTAMP_WITHOUT_TIME_ZONE:
+ {
+ final int precision = LogicalTypeChecks.getPrecision(type);
+ if (precision <= TIMESTAMP_PRECISION) {
+ return (builder, value) ->
+ builder.appendTimestamp(timestampMicros((TimestampData) value));
+ }
+ final String timestampType = "TIMESTAMP(" + precision + ")";
+ return (builder, value) ->
+ builder.appendTimestampNanos(
+ timestampNanos((TimestampData) value, timestampType));
+ }
+ case TIMESTAMP_WITH_LOCAL_TIME_ZONE:
+ {
+ final int precision = LogicalTypeChecks.getPrecision(type);
+ if (precision <= TIMESTAMP_PRECISION) {
+ return (builder, value) ->
+ builder.appendTimestampLtz(timestampMicros((TimestampData) value));
+ }
+ final String timestampType = "TIMESTAMP_LTZ(" + precision + ")";
+ return (builder, value) ->
+ builder.appendTimestampLtzNanos(
+ timestampNanos((TimestampData) value, timestampType));
+ }
+ case UUID:
+ return (builder, value) -> builder.appendUuid(UuidUtils.fromBytes((byte[]) value));
+ case VARIANT:
+ return (builder, value) -> builder.appendVariant((BinaryVariant) value);
+ case ARRAY:
+ return createArrayWriter((ArrayType) type);
+ case MAP:
+ return createMapWriter((MapType) type);
+ case ROW:
+ case STRUCTURED_TYPE:
+ return createRowWriter(type);
+ case DISTINCT_TYPE:
+ return createWriter(((DistinctType) type).getSourceType());
+ default:
+ throw new IllegalArgumentException("Cannot cast " + type + " to VARIANT.");
+ }
+ }
+
+ // A compact decimal is written from its unscaled long, which saves building a BigDecimal.
+ private static void appendDecimal(BinaryVariantInternalBuilder builder, DecimalData value) {
+ if (value.isCompact()) {
+ builder.appendDecimal(value.toUnscaledLong(), value.scale());
+ } else {
+ builder.appendDecimal(value.toBigDecimal());
+ }
+ }
+
+ private static void appendString(BinaryVariantInternalBuilder builder, StringData value) {
+ final BinaryStringData string = (BinaryStringData) value;
+ try {
+ appendUtf8(builder, string);
+ } catch (VariantTypeException e) {
+ throw payloadTooLarge(e, "string", string.getSizeInBytes());
+ }
+ }
+
+ /**
+ * Stores the UTF-8 bytes of the string as they are. A {@link StringData} may hold invalid
+ * UTF-8, which the variant spec does not allow, so such a value is decoded first and every
+ * malformed sequence is stored as the U+FFFD replacement character.
+ */
+ private static void appendUtf8(BinaryVariantInternalBuilder builder, BinaryStringData string) {
+ if (string.getBinarySection() == null) {
Review Comment:
Moved it to `StringUtf8Utils#toValidUtf8Bytes(StringData)`, built on `StringData#toBytes()`. It keeps the shortcut for Java-object strings from #29370, but drops the in-place segment read, so a string in a binary row is copied once more.
##########
flink-table/flink-table-planner/src/main/scala/org/apache/flink/table/planner/codegen/CodeGeneratorContext.scala:
##########
@@ -834,6 +839,31 @@ class CodeGeneratorContext(
addReusableObjectWithName(obj, newName(this, fieldNamePrefix), fieldTypeTerm)
}
+ /**
+ * Adds a reusable Object to the member area of the generated class, unless one was added for an
+ * equal key before. The factory only runs when the object is added.
+ *
+ * @param key
+ * the key that identifies the object
+ * @param factory
+ * creates the object to be added to the generated class
+ * @param fieldNamePrefix
+ * prefix field name of the generated member field term
+ * @param fieldTypeTerm
+ * field type class name
+ * @return
+ * the field term of the object for the key
+ */
+ def addReusableObjectIfAbsent(
Review Comment:
You're right, `addReusableObject` works. The new method only shared one converter per type, which saves little. I removed it, so `CodeGeneratorContext` is unchanged.
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-40826][table] Support casting ARRAY, MAP, ROW and STRUCTURED to VARIANT [flink]
Posted by "flinkbot (via GitHub)" <gi...@apache.org>.
flinkbot commented on PR #29369:
URL: https://github.com/apache/flink/pull/29369#issuecomment-5954760111
<!--
Meta data
{
"version" : 1,
"metaDataEntries" : [ {
"hash" : "42495c37113683f9c268cdcbbaf85a10a6b1a35c",
"status" : "UNKNOWN",
"url" : "TBD",
"triggerID" : "42495c37113683f9c268cdcbbaf85a10a6b1a35c",
"triggerType" : "PUSH"
} ]
}-->
## CI report:
* 42495c37113683f9c268cdcbbaf85a10a6b1a35c UNKNOWN
<details>
<summary>Bot commands</summary>
The @flinkbot bot supports the following commands:
- `@flinkbot run azure` re-run the last Azure build
</details>
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-40826][table] Support casting ARRAY, MAP, ROW and STRUCTURED to VARIANT [flink]
Posted by "raminqaf (via GitHub)" <gi...@apache.org>.
raminqaf commented on code in PR #29369:
URL: https://github.com/apache/flink/pull/29369#discussion_r4184335761
##########
flink-table/flink-table-planner/src/main/java/org/apache/flink/table/planner/functions/casting/AbstractCodeGeneratorCastRule.java:
##########
@@ -95,7 +96,7 @@ public CastExecutor<IN, OUT> create(
"public "
+ castExecutorClassName
+ "("
- + ctx.typeSerializers.values().stream()
+ + constructorFields.entrySet().stream()
.map(
entry ->
className(entry.getValue().getClass())
Review Comment:
Done. `declareReusableObject` now takes the declared type, and both contexts use it for the field. The planner goes through `className(type)`, which fails with a clear error for a type without a canonical name. It also takes a key now, so casts of the same type share one converter instead of creating one per call site.
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-40826][table] Support casting ARRAY, MAP, ROW and STRUCTURED to VARIANT [flink]
Posted by "raminqaf (via GitHub)" <gi...@apache.org>.
raminqaf commented on code in PR #29369:
URL: https://github.com/apache/flink/pull/29369#discussion_r4184380862
##########
docs/content/docs/sql/reference/data-types.md:
##########
@@ -1725,7 +1725,38 @@ CAST(NULL AS VARIANT) -- NULL
CAST(CAST('NaN' AS DOUBLE) AS VARIANT) -- NaN, stored as a DOUBLE
CAST(INTERVAL '2' DAY AS VARIANT) -- fails at validation
CAST(ARRAY[1, NULL] AS ARRAY<VARIANT>) -- [1, NULL], each element a VARIANT, the NULL stays SQL NULL
-CAST(ARRAY[1, 2] AS VARIANT) -- fails at validation, not supported yet
+```
+
+A whole `ARRAY`, `MAP`, `ROW`, or `STRUCTURED` value can also be cast into a single `VARIANT`. An
+`ARRAY` becomes a variant array, and a `MAP`, `ROW`, or `STRUCTURED` value a variant object. Each
+leaf is stored by the rules above, so the cast is supported only when every leaf type casts to
+`VARIANT`.
+
+- A `ROW` or `STRUCTURED` value is keyed by its field names. The SQL `ROW` constructor names its
+ fields `EXPR$0`, `EXPR$1`, and so on, and the Table API `row()` names them `f0`, `f1`, and so on.
+ To choose the keys, cast to a `ROW` with named fields first, or name each field with `as()` in the
+ Table API.
+- A `MAP` needs a character string key, which becomes the object key. A `NULL` key fails the cast.
+ If a key appears twice, the last value is kept.
+- A variant object sorts its keys, so the field order of a `ROW` is not kept.
+- A `NULL` element, field, or map value becomes a variant null, so an array keeps its length and an
+ object keeps its keys.
+- A nested `VARIANT` is embedded as is.
+- The whole value must fit into the 16 MiB of a `VARIANT`. Any `ARRAY` or `MAP` can exceed it, and so
+ can a `ROW` with a nested `VARIANT` or with fields whose declared sizes add up to more. The cast
+ then fails, and `TRY_CAST` returns `NULL` for the whole value.
+- Casting the `VARIANT` back to the original type returns the original value, since a cast to `ROW`
Review Comment:
Added both exceptions, and the sentence that contrasts `ARRAY<INT>` to `ARRAY<VARIANT>` with `ARRAY<INT>` to `VARIANT`. I also documented that the order of `MAP` entries is part of the encoding. Two MAPs with the same entries in a different order cast to VARIANT values that are not equal, the same as `PARSE_JSON` does for the key order of JSON text.
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [PR] [FLINK-40826][table] Support casting ARRAY, MAP, ROW and STRUCTURED to VARIANT [flink]
Posted by "raminqaf (via GitHub)" <gi...@apache.org>.
raminqaf commented on code in PR #29369:
URL: https://github.com/apache/flink/pull/29369#discussion_r4184372211
##########
flink-table/flink-table-common/src/main/java/org/apache/flink/table/types/logical/utils/LogicalTypeCasts.java:
##########
@@ -730,6 +730,23 @@ private static boolean supportsCasting(
return allowExplicit
&& mapChildren.get(0).is(CHARACTER_STRING)
&& supportsCasting(sourceType, mapChildren.get(1), true);
+ } else if (targetRoot == VARIANT
Review Comment:
After discussion we will keep the Automatic naming and we will not throw
--
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: issues-unsubscribe@flink.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org