Skip to content

Commit

Permalink
Fail parsing dates beyond a representable range
Browse files Browse the repository at this point in the history
  • Loading branch information
Praveen2112 authored and findepi committed Feb 28, 2020
1 parent b184eb1 commit c6c7cb7
Show file tree
Hide file tree
Showing 3 changed files with 12 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,7 @@ public static long castFromSlice(@SqlType("varchar(x)") Slice value)
try {
return parseDate(trim(value).toStringUtf8());
}
catch (IllegalArgumentException e) {
catch (IllegalArgumentException | ArithmeticException e) {
throw new PrestoException(INVALID_CAST_ARGUMENT, "Value cannot be cast to date: " + value.toStringUtf8(), e);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@
import static io.prestosql.util.DateTimeZoneIndex.packDateTimeWithZone;
import static io.prestosql.util.DateTimeZoneIndex.unpackChronology;
import static io.prestosql.util.DateTimeZoneIndex.unpackDateTimeZone;
import static java.lang.Math.toIntExact;
import static java.lang.String.format;

public final class DateTimeUtils
Expand All @@ -64,7 +65,7 @@ private DateTimeUtils() {}

public static int parseDate(String value)
{
return (int) TimeUnit.MILLISECONDS.toDays(DATE_FORMATTER.parseMillis(value));
return toIntExact(TimeUnit.MILLISECONDS.toDays(DATE_FORMATTER.parseMillis(value)));
}

public static String printDate(int days)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@

import java.util.concurrent.TimeUnit;

import static io.prestosql.spi.StandardErrorCode.INVALID_CAST_ARGUMENT;
import static io.prestosql.spi.type.BooleanType.BOOLEAN;
import static io.prestosql.spi.type.DateType.DATE;
import static io.prestosql.spi.type.TimeType.TIME;
Expand Down Expand Up @@ -251,6 +252,14 @@ public void testIsDistinctFrom()
assertFunction("DATE '2013-10-27' IS DISTINCT FROM NULL", BOOLEAN, true);
}

@Test
public void testDateCastFromVarchar()
{
assertFunction("DATE '2013-02-02'", DATE, toDate(new DateTime(2013, 2, 2, 0, 0, 0, 0, UTC)));
assertInvalidFunction("DATE '5881580-07-12'", INVALID_CAST_ARGUMENT, "Value cannot be cast to date: 5881580-07-12");
assertInvalidFunction("DATE '392251590-07-12'", INVALID_CAST_ARGUMENT, "Value cannot be cast to date: 392251590-07-12");
}

private static SqlDate toDate(DateTime dateTime)
{
return new SqlDate((int) TimeUnit.MILLISECONDS.toDays(dateTime.getMillis()));
Expand Down

0 comments on commit c6c7cb7

Please sign in to comment.