Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -13,19 +13,13 @@
*/
package io.trino.type;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.google.common.primitives.Ints;
import io.airlift.json.JsonMapperProvider;
import io.airlift.slice.DynamicSliceOutput;
import io.airlift.slice.Slice;
import io.airlift.slice.SliceOutput;
import io.trino.metadata.InternalFunctionBundle;
import io.trino.plugin.base.util.JsonTypeUtil;
import io.trino.spi.TrinoException;
import io.trino.spi.block.ArrayBlockBuilder;
import io.trino.spi.block.Block;
import io.trino.spi.function.LiteralParameters;
Expand All @@ -42,14 +36,8 @@
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.parallel.Execution;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Collections;

import static com.fasterxml.jackson.databind.DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS;
import static com.fasterxml.jackson.databind.SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS;
import static com.google.common.base.Preconditions.checkState;
import static io.trino.block.BlockSerdeUtil.writeBlock;
import static io.trino.operator.scalar.BlockSet.MAX_FUNCTION_MEMORY;
import static io.trino.spi.StandardErrorCode.AMBIGUOUS_FUNCTION_CALL;
Expand Down Expand Up @@ -90,7 +78,6 @@
import static java.lang.Double.POSITIVE_INFINITY;
import static java.lang.Math.toIntExact;
import static java.lang.String.format;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Arrays.asList;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
Expand Down Expand Up @@ -129,35 +116,6 @@ public static Slice uncheckedToJson(@SqlType("varchar(x)") Slice slice)
return slice;
}

// TODO (https://github.com/trinodb/trino/issues/28867) remove when json_parse and JSON literals are no longer lossy.
@ScalarFunction("json_literal_fixed")
@LiteralParameters("x")
@SqlType(StandardTypes.JSON)
public static Slice workaroundBrokenJsonLiteralParsing(@SqlType("varchar(x)") Slice slice)
{
// This is copy of JsonTypeUtil.jsonParse with addition of USE_BIG_DECIMAL_FOR_FLOATS to prevent numeric precision loss during JSON parsing.
JsonMapper sortingMapper = new JsonMapperProvider().get()
.rebuild()
.configure(ORDER_MAP_ENTRIES_BY_KEYS, true)
.configure(USE_BIG_DECIMAL_FOR_FLOATS, true)
.build();

Slice json;
try (JsonParser parser = sortingMapper.createParser(new InputStreamReader(slice.getInput(), UTF_8))) {
SliceOutput output = new DynamicSliceOutput(slice.length());
sortingMapper.writeValue((OutputStream) output, sortingMapper.readValue(parser, Object.class));
checkState(parser.nextToken() == null, "Found characters after the expected end of input");
json = output.slice();
}
catch (IOException | RuntimeException e) {
throw new TrinoException(INVALID_FUNCTION_ARGUMENT, format("Cannot convert value to JSON: '%s'", slice.toStringUtf8()), e);
}

Slice lossyJson = JsonTypeUtil.jsonParse(slice);
checkState(!json.equals(lossyJson), "json_literal_fixed is used unnecessarily here, or jsonParse has been fixed");
return json;
}

@Test
public void testStackRepresentation()
{
Expand Down Expand Up @@ -634,7 +592,7 @@ public void testJsonToArraySmoke()

assertTrinoExceptionThrownBy(() -> assertions.expression("CAST(a AS array(INTEGER))")
.binding("a", "JSON '[1234567890123.456]'").evaluate())
.hasMessage("Cannot cast to array(integer). Out of range for integer: 1.234567890123456E12\n[1.234567890123456E12]")
.hasMessage("Cannot cast to array(integer). Out of range for integer: 1.234567890123456E12\n[1234567890123.456]")
.hasErrorCode(INVALID_CAST_ARGUMENT);

assertThat(assertions.expression("CAST(a AS array(DECIMAL(10,5)))")
Expand Down Expand Up @@ -1133,11 +1091,10 @@ public void testCastJsonToArrayDecimal()
.matches("CAST(ARRAY[DECIMAL '12345.88'] AS ARRAY(DECIMAL(7,2)))");

// array with large decimal
// TODO precision loss!
assertThat(assertions.expression("cast(a as ARRAY(DECIMAL(38,8)))")
.binding("a", "JSON '[123456789012345678901234567890.12345678]'"))
.hasType(new ArrayType(createDecimalType(38, 8)))
.matches("CAST(ARRAY[DECIMAL '123456789012345680000000000000.00000000'] AS ARRAY(DECIMAL(38,8)))");
.matches("CAST(ARRAY[DECIMAL '123456789012345678901234567890.12345678'] AS ARRAY(DECIMAL(38,8)))");

// non-array JSON should fail
assertTrinoExceptionThrownBy(() -> assertions.expression("cast(a as ARRAY(DECIMAL(10,3)))")
Expand Down Expand Up @@ -1186,7 +1143,7 @@ public void testCastJsonToArrayNumber()
.matches("ARRAY[NUMBER '1', NUMBER '2.5', NUMBER '3.14159']");

assertThat(assertions.expression("CAST(a AS ARRAY(NUMBER))")
.binding("a", "json_literal_fixed('[12345678901234567890.123456789012345678, 123456789012345678901234567890.123456789012345678901234567890]')"))
.binding("a", "JSON '[12345678901234567890.123456789012345678, 123456789012345678901234567890.123456789012345678901234567890]'"))
.hasType(new ArrayType(NUMBER))
.matches("ARRAY[NUMBER '12345678901234567890.123456789012345678', NUMBER '123456789012345678901234567890.123456789012345678901234567890']");

Expand Down
72 changes: 8 additions & 64 deletions core/trino-main/src/test/java/io/trino/type/TestJsonOperators.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,37 +13,17 @@
*/
package io.trino.type;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import io.airlift.json.JsonMapperProvider;
import io.airlift.slice.DynamicSliceOutput;
import io.airlift.slice.Slice;
import io.airlift.slice.SliceOutput;
import io.trino.metadata.InternalFunctionBundle;
import io.trino.plugin.base.util.JsonTypeUtil;
import io.trino.spi.TrinoException;
import io.trino.spi.function.LiteralParameters;
import io.trino.spi.function.ScalarFunction;
import io.trino.spi.function.SqlType;
import io.trino.spi.type.ArrayType;
import io.trino.spi.type.RowType;
import io.trino.spi.type.StandardTypes;
import io.trino.sql.query.QueryAssertions;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.junit.jupiter.api.parallel.Execution;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;

import static com.fasterxml.jackson.databind.DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS;
import static com.fasterxml.jackson.databind.SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS;
import static com.google.common.base.Preconditions.checkState;
import static io.trino.spi.StandardErrorCode.INVALID_CAST_ARGUMENT;
import static io.trino.spi.StandardErrorCode.INVALID_FUNCTION_ARGUMENT;
import static io.trino.spi.StandardErrorCode.INVALID_LITERAL;
Expand All @@ -69,7 +49,6 @@
import static java.lang.Double.NEGATIVE_INFINITY;
import static java.lang.Double.POSITIVE_INFINITY;
import static java.lang.String.format;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS;
import static org.junit.jupiter.api.parallel.ExecutionMode.CONCURRENT;
Expand All @@ -78,17 +57,12 @@
@Execution(CONCURRENT)
public class TestJsonOperators
{
// Some of the tests in this class are expected to fail when coercion between primitive Trino types changes behavior

private QueryAssertions assertions;

@BeforeAll
public void init()
{
assertions = new QueryAssertions();
assertions.addFunctions(InternalFunctionBundle.builder()
.scalars(TestJsonOperators.class)
.build());
}

@AfterAll
Expand All @@ -98,35 +72,6 @@ public void teardown()
assertions = null;
}

// TODO (https://github.com/trinodb/trino/issues/28867) remove when json_parse and JSON literals are no longer lossy.
@ScalarFunction("json_literal_fixed")
@LiteralParameters("x")
@SqlType(StandardTypes.JSON)
public static Slice workaroundBrokenJsonLiteralParsing(@SqlType("varchar(x)") Slice slice)
{
// This is copy of JsonTypeUtil.jsonParse with addition of USE_BIG_DECIMAL_FOR_FLOATS to prevent numeric precision loss during JSON parsing.
JsonMapper sortingMapper = new JsonMapperProvider().get()
.rebuild()
.configure(ORDER_MAP_ENTRIES_BY_KEYS, true)
.configure(USE_BIG_DECIMAL_FOR_FLOATS, true)
.build();

Slice json;
try (JsonParser parser = sortingMapper.createParser(new InputStreamReader(slice.getInput(), UTF_8))) {
SliceOutput output = new DynamicSliceOutput(slice.length());
sortingMapper.writeValue((OutputStream) output, sortingMapper.readValue(parser, Object.class));
checkState(parser.nextToken() == null, "Found characters after the expected end of input");
json = output.slice();
}
catch (IOException | RuntimeException e) {
throw new TrinoException(INVALID_FUNCTION_ARGUMENT, format("Cannot convert value to JSON: '%s'", slice.toStringUtf8()), e);
}

Slice lossyJson = JsonTypeUtil.jsonParse(slice);
checkState(!json.equals(lossyJson), "json_literal_fixed is used unnecessarily here, or jsonParse has been fixed");
return json;
}

@Test
public void testCastToBigint()
{
Expand Down Expand Up @@ -759,11 +704,10 @@ public void testCastToDecimal()
.hasType(createDecimalType(10, 3))
.isEqualTo(decimal("128.000", createDecimalType(10, 3)));

// TODO precision loss!
assertThat(assertions.expression("cast(a as DECIMAL(38,8))")
.binding("a", "JSON '123456789012345678901234567890.12345678'"))
.hasType(createDecimalType(38, 8))
.isEqualTo(decimal("123456789012345680000000000000.00000000", createDecimalType(38, 8)));
.isEqualTo(decimal("123456789012345678901234567890.12345678", createDecimalType(38, 8)));

assertThat(assertions.expression("cast(a as DECIMAL(38,8))")
.binding("a", "cast(DECIMAL '123456789012345678901234567890.12345678' as JSON)"))
Expand Down Expand Up @@ -850,10 +794,10 @@ public void testCastToBoolean()
.binding("a", "JSON '1e-324'"))
.isEqualTo(false);

// overflow
assertTrinoExceptionThrownBy(() -> assertions.expression("cast(a as BOOLEAN)")
.binding("a", "JSON '1e309'").evaluate())
.hasErrorCode(INVALID_CAST_ARGUMENT);
// overflow if parsed as double
assertThat(assertions.expression("cast(a as BOOLEAN)")
.binding("a", "JSON '1e309'"))
.isEqualTo(true);

assertThat(assertions.expression("cast(a as BOOLEAN)")
.binding("a", "JSON 'true'"))
Expand Down Expand Up @@ -1311,19 +1255,19 @@ public void testCastToNumber()
.matches("NUMBER '12345678901234567890123456789012345678'");

assertThat(assertions.expression("cast(a as NUMBER)")
.binding("a", "json_literal_fixed('123456789012345678901234567890.123456789012345678901234567890')"))
.binding("a", "JSON '123456789012345678901234567890.123456789012345678901234567890'"))
.matches("NUMBER '123456789012345678901234567890.123456789012345678901234567890'");

assertThat(assertions.expression("cast(a as NUMBER)")
.binding("a", "JSON '128.9'"))
.matches("NUMBER '128.9'");

assertThat(assertions.expression("cast(a as NUMBER)")
.binding("a", "json_literal_fixed('1e-324')"))
.binding("a", "JSON '1e-324'"))
.matches("NUMBER '1E-324'");

assertThat(assertions.expression("cast(a as NUMBER)")
.binding("a", "json_literal_fixed('1e308')"))
.binding("a", "JSON '1e308'"))
.matches("NUMBER '1e308'");

assertThat(assertions.expression("cast(a as NUMBER)")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -691,7 +691,7 @@ public void testJsonToMap()

assertTrinoExceptionThrownBy(() -> assertions.expression("cast(a as MAP(VARCHAR, INTEGER))")
.binding("a", "JSON '{\"a\": 1234567890123.456}'").evaluate())
.hasMessage("Cannot cast to map(varchar, integer). Out of range for integer: 1.234567890123456E12\n{\"a\":1.234567890123456E12}")
.hasMessage("Cannot cast to map(varchar, integer). Out of range for integer: 1.234567890123456E12\n{\"a\":1234567890123.456}")
.hasErrorCode(INVALID_CAST_ARGUMENT);

assertTrinoExceptionThrownBy(() -> assertions.expression("cast(a as MAP(BIGINT, BIGINT))")
Expand Down
13 changes: 13 additions & 0 deletions lib/trino-plugin-toolkit/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,19 @@
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-core</artifactId>
<scope>test</scope>
</dependency>

<dependency>
<groupId>org.openjdk.jmh</groupId>
<artifactId>jmh-generator-annprocess</artifactId>
<scope>test</scope>
</dependency>

</dependencies>

<build>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
import java.util.StringJoiner;

import static com.fasterxml.jackson.core.JsonFactory.Feature.CANONICALIZE_FIELD_NAMES;
import static com.fasterxml.jackson.databind.DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS;
import static com.fasterxml.jackson.databind.SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS;
import static com.google.common.base.Preconditions.checkState;
import static io.trino.plugin.base.util.JsonUtils.jsonFactoryBuilder;
Expand All @@ -52,6 +53,7 @@ public final class JsonTypeUtil
private static final JsonMapper SORTED_MAPPER = new JsonMapperProvider().get()
.rebuild()
.configure(ORDER_MAP_ENTRIES_BY_KEYS, true)
.configure(USE_BIG_DECIMAL_FOR_FLOATS, true)
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this isn't backward compatible, right?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you look at the tests it is definitely a behavior change. We could call this a fix or a backwards incompatible change. I think of it as a fix, but I think it makes sense to mark this as a backwards incompatible change in the release notes so we properly warn users.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, we should call it out, but fix itself is a correct thing

.build();

private JsonTypeUtil() {}
Expand Down
Loading