Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for time type in Cassandra #15802

Merged
merged 1 commit into from
Mar 3, 2023
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
3 changes: 3 additions & 0 deletions docs/src/main/sphinx/connector/cassandra.rst
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,9 @@ the following table:
* - ``DATE``
- ``DATE``
-
* - ``TIME``
- ``TIME(9)``
-
* - ``TIMESTAMP``
- ``TIMESTAMP(3) WITH TIME ZONE``
-
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@

import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collection;
Expand All @@ -60,7 +61,11 @@
import static io.trino.spi.type.IntegerType.INTEGER;
import static io.trino.spi.type.RealType.REAL;
import static io.trino.spi.type.SmallintType.SMALLINT;
import static io.trino.spi.type.TimeType.TIME_NANOS;
import static io.trino.spi.type.TimestampWithTimeZoneType.TIMESTAMP_TZ_MILLIS;
import static io.trino.spi.type.Timestamps.NANOSECONDS_PER_DAY;
import static io.trino.spi.type.Timestamps.PICOSECONDS_PER_NANOSECOND;
import static io.trino.spi.type.Timestamps.roundDiv;
import static io.trino.spi.type.TinyintType.TINYINT;
import static io.trino.spi.type.UuidType.trinoUuidToJavaUuid;
import static io.trino.spi.type.VarbinaryType.VARBINARY;
Expand Down Expand Up @@ -177,6 +182,10 @@ else if (REAL.equals(type)) {
else if (DATE.equals(type)) {
values.add(toCassandraDate.apply(type.getLong(block, position)));
}
else if (TIME_NANOS.equals(type)) {
long value = type.getLong(block, position);
values.add(LocalTime.ofNanoOfDay(roundDiv(value, PICOSECONDS_PER_NANOSECOND) % NANOSECONDS_PER_DAY));
}
else if (TIMESTAMP_TZ_MILLIS.equals(type)) {
values.add(Instant.ofEpochMilli(unpackMillisUtc(type.getLong(block, position))));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
import static io.airlift.slice.Slices.utf8Slice;
import static io.trino.plugin.cassandra.util.CassandraCqlUtils.validColumnName;
import static io.trino.spi.type.DateTimeEncoding.packDateTimeWithZone;
import static io.trino.spi.type.Timestamps.PICOSECONDS_PER_NANOSECOND;
import static java.lang.Float.floatToRawIntBits;
import static java.util.Objects.requireNonNull;

Expand Down Expand Up @@ -115,6 +116,8 @@ public long getLong(int i)
case BIGINT:
case COUNTER:
return currentRow.getLong(columnName);
case TIME:
return currentRow.getLocalTime(columnName).toNanoOfDay() * PICOSECONDS_PER_NANOSECOND;
case TIMESTAMP:
return packDateTimeWithZone(currentRow.getInstant(columnName).toEpochMilli(), TimeZoneKey.UTC_KEY);
case DATE:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ public enum Kind
DOUBLE,
DECIMAL,
DATE,
TIME,
TIMESTAMP,
ASCII,
TEXT,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
import io.trino.spi.type.RowType;
import io.trino.spi.type.SmallintType;
import io.trino.spi.type.StandardTypes;
import io.trino.spi.type.TimeType;
import io.trino.spi.type.TimeZoneKey;
import io.trino.spi.type.TimestampWithTimeZoneType;
import io.trino.spi.type.TinyintType;
Expand All @@ -64,6 +65,7 @@
import java.nio.ByteBuffer;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
Expand All @@ -78,6 +80,7 @@
import static io.airlift.slice.Slices.utf8Slice;
import static io.airlift.slice.Slices.wrappedBuffer;
import static io.trino.plugin.cassandra.CassandraType.Kind.DATE;
import static io.trino.plugin.cassandra.CassandraType.Kind.TIME;
import static io.trino.plugin.cassandra.CassandraType.Kind.TIMESTAMP;
import static io.trino.plugin.cassandra.CassandraType.Kind.TUPLE;
import static io.trino.plugin.cassandra.CassandraType.Kind.UDT;
Expand All @@ -88,6 +91,8 @@
import static io.trino.spi.StandardErrorCode.NOT_SUPPORTED;
import static io.trino.spi.type.DateTimeEncoding.packDateTimeWithZone;
import static io.trino.spi.type.DateTimeEncoding.unpackMillisUtc;
import static io.trino.spi.type.Timestamps.PICOSECONDS_PER_NANOSECOND;
import static io.trino.spi.type.Timestamps.roundDiv;
import static io.trino.spi.type.TypeUtils.writeNativeValue;
import static io.trino.spi.type.UuidType.javaUuidToTrinoUuid;
import static io.trino.spi.type.UuidType.trinoUuidToJavaUuid;
Expand Down Expand Up @@ -146,6 +151,8 @@ public Optional<CassandraType> toCassandraType(DataType dataType)
return Optional.of(CassandraTypes.SET);
case ProtocolConstants.DataType.SMALLINT:
return Optional.of(CassandraTypes.SMALLINT);
case ProtocolConstants.DataType.TIME:
return Optional.of(CassandraTypes.TIME);
case ProtocolConstants.DataType.TIMESTAMP:
return Optional.of(CassandraTypes.TIMESTAMP);
case ProtocolConstants.DataType.TIMEUUID:
Expand Down Expand Up @@ -254,6 +261,8 @@ public NullableValue getColumnValue(CassandraType cassandraType, GettableByIndex
case UUID:
case TIMEUUID:
return NullableValue.of(trinoType, javaUuidToTrinoUuid(row.getUuid(position)));
case TIME:
return NullableValue.of(trinoType, row.getLocalTime(position).toNanoOfDay() * PICOSECONDS_PER_NANOSECOND);
case TIMESTAMP:
return NullableValue.of(trinoType, packDateTimeWithZone(row.getInstant(position).toEpochMilli(), TimeZoneKey.UTC_KEY));
case DATE:
Expand Down Expand Up @@ -400,6 +409,8 @@ public String getColumnValueForCql(CassandraType type, Row row, int position)
case UUID:
case TIMEUUID:
return row.getUuid(position).toString();
case TIME:
return quoteStringLiteral(row.getLocalTime(position).toString());
case TIMESTAMP:
return Long.toString(row.getInstant(position).toEpochMilli());
case DATE:
Expand Down Expand Up @@ -431,6 +442,10 @@ public String toCqlLiteral(CassandraType type, Object trinoNativeValue)
LocalDate date = LocalDate.ofEpochDay(toIntExact((long) trinoNativeValue));
return quoteStringLiteral(date.toString());
}
if (kind == TIME) {
LocalTime time = LocalTime.ofNanoOfDay(roundDiv((long) trinoNativeValue, PICOSECONDS_PER_NANOSECOND));
return quoteStringLiteral(time.toString());
}
if (kind == TIMESTAMP) {
return String.valueOf(unpackMillisUtc((Long) trinoNativeValue));
}
Expand Down Expand Up @@ -467,6 +482,7 @@ private String objectToJson(Object cassandraValue, DataType dataType)
case VARCHAR:
case UUID:
case TIMEUUID:
case TIME:
case TIMESTAMP:
case DATE:
case INET:
Expand Down Expand Up @@ -537,6 +553,8 @@ public Object getJavaValue(CassandraType.Kind kind, Object trinoNativeValue)
// Trino uses double for decimal, so to keep the floating point precision, convert it to string.
// Otherwise partition id doesn't match
return new BigDecimal(trinoNativeValue.toString());
case TIME:
return LocalTime.ofNanoOfDay(roundDiv((long) trinoNativeValue, PICOSECONDS_PER_NANOSECOND));
case TIMESTAMP:
return Instant.ofEpochMilli(unpackMillisUtc((Long) trinoNativeValue));
case DATE:
Expand Down Expand Up @@ -574,6 +592,7 @@ public boolean isSupportedPartitionKey(CassandraType.Kind kind)
case FLOAT:
case DECIMAL:
case DATE:
case TIME:
case TIMESTAMP:
case UUID:
case TIMEUUID:
Expand Down Expand Up @@ -658,6 +677,9 @@ public CassandraType toCassandraType(Type type, ProtocolVersion protocolVersion)
if (type.equals(VarbinaryType.VARBINARY)) {
return CassandraTypes.BLOB;
}
if (type.equals(TimeType.TIME_NANOS)) {
return CassandraTypes.TIME;
}
if (type.equals(TimestampWithTimeZoneType.TIMESTAMP_TZ_MILLIS)) {
return CassandraTypes.TIMESTAMP;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import io.trino.spi.type.IntegerType;
import io.trino.spi.type.RealType;
import io.trino.spi.type.SmallintType;
import io.trino.spi.type.TimeType;
import io.trino.spi.type.TimestampWithTimeZoneType;
import io.trino.spi.type.TinyintType;
import io.trino.spi.type.UuidType;
Expand Down Expand Up @@ -48,6 +49,7 @@ private CassandraTypes() {}
public static final CassandraType SET = new CassandraType(Kind.SET, createUnboundedVarcharType());
public static final CassandraType SMALLINT = new CassandraType(Kind.SMALLINT, SmallintType.SMALLINT);
public static final CassandraType TEXT = new CassandraType(Kind.TEXT, createUnboundedVarcharType());
public static final CassandraType TIME = new CassandraType(Kind.TIME, TimeType.TIME_NANOS);
public static final CassandraType TIMESTAMP = new CassandraType(Kind.TIMESTAMP, TimestampWithTimeZoneType.TIMESTAMP_TZ_MILLIS);
public static final CassandraType TIMEUUID = new CassandraType(Kind.TIMEUUID, UuidType.UUID);
public static final CassandraType TINYINT = new CassandraType(Kind.TINYINT, TinyintType.TINYINT);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -283,6 +283,7 @@ public void testPushdownAllTypesPartitionKeyPredicate()
partitionColumn("typelong", "bigint"),
generalColumn("typebytes", "blob"),
partitionColumn("typedate", "date"),
partitionColumn("typetime", "time"),
partitionColumn("typetimestamp", "timestamp"),
partitionColumn("typeansi", "ascii"),
partitionColumn("typeboolean", "boolean"),
Expand All @@ -305,6 +306,7 @@ public void testPushdownAllTypesPartitionKeyPredicate()
"1007, " +
"0x00000007, " +
"'1970-01-01', " +
"'03:04:05.123456789', " +
"'1970-01-01 03:04:05.000+0000', " +
"'ansi 7', " +
"false, " +
Expand All @@ -327,6 +329,7 @@ public void testPushdownAllTypesPartitionKeyPredicate()
" AND typeinteger = 7" +
" AND typelong = 1007" +
" AND typedate = DATE '1970-01-01'" +
" AND typetime = TIME '03:04:05.123456789'" +
" AND typetimestamp = TIMESTAMP '1970-01-01 03:04:05Z'" +
" AND typeansi = 'ansi 7'" +
" AND typeboolean = false" +
Expand Down Expand Up @@ -1469,18 +1472,6 @@ public void testNativeQueryUnsupportedStatement()
onCassandra("DROP TABLE IF EXISTS tpch." + tableName);
}

@Test
public void testNativeQueryUnsupportedType()
{
String tableName = "test_unsupported_type" + randomNameSuffix();
onCassandra("CREATE TABLE tpch." + tableName + "(col TIME PRIMARY KEY)");

assertThatThrownBy(() -> query("SELECT * FROM TABLE(cassandra.system.query(query => 'SELECT * FROM tpch." + tableName + "'))"))
.hasMessage("Unsupported type: TIME");

onCassandra("DROP TABLE IF EXISTS tpch." + tableName);
}

@Test
public void testNativeQueryIncorrectSyntax()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
Expand All @@ -57,6 +58,7 @@
import static io.trino.spi.type.RowType.anonymousRow;
import static io.trino.spi.type.RowType.rowType;
import static io.trino.spi.type.SmallintType.SMALLINT;
import static io.trino.spi.type.TimeType.createTimeType;
import static io.trino.spi.type.TimestampWithTimeZoneType.TIMESTAMP_TZ_MILLIS;
import static io.trino.spi.type.TinyintType.TINYINT;
import static io.trino.spi.type.UuidType.UUID;
Expand Down Expand Up @@ -507,6 +509,40 @@ private SqlDataTypeTest dateTest(Function<String, String> inputLiteralFactory)
.addRoundTrip("date", inputLiteralFactory.apply("'5881580-07-11'"), DATE, "DATE '5881580-07-11'"); // max value in Cassandra and Trino
}

@Test(dataProvider = "sessionZonesDataProvider")
public void testTime(ZoneId sessionZone)
{
LocalTime timeGapInJvmZone = LocalTime.of(0, 12, 34, 567_000_000);
checkIsGap(jvmZone, timeGapInJvmZone.atDate(LocalDate.ofEpochDay(0)));

Session session = Session.builder(getSession())
.setTimeZoneKey(TimeZoneKey.getTimeZoneKey(sessionZone.getId()))
.build();

timeTypeTest("time(9)", trinoTimeInputLiteralFactory())
.execute(getQueryRunner(), session, trinoCreateAsSelect(session, "test_time"))
.execute(getQueryRunner(), session, trinoCreateAsSelect("test_time"))
.execute(getQueryRunner(), session, trinoCreateAndInsert(session, "test_time"))
.execute(getQueryRunner(), session, trinoCreateAndInsert("test_time"));

timeTypeTest("time", cassandraTimeInputLiteralFactory())
.execute(getQueryRunner(), session, cassandraCreateAndInsert("tpch.test_time"));
}

private static SqlDataTypeTest timeTypeTest(String inputType, Function<String, String> inputLiteralFactory)
{
return SqlDataTypeTest.create()
ebyhr marked this conversation as resolved.
Show resolved Hide resolved
.addRoundTrip(inputType, inputLiteralFactory.apply("'09:12:34'"), createTimeType(9), "TIME '09:12:34.000000000'")
.addRoundTrip(inputType, inputLiteralFactory.apply("'10:12:34.000000000'"), createTimeType(9), "TIME '10:12:34.000000000'")
.addRoundTrip(inputType, inputLiteralFactory.apply("'15:12:34.567000000'"), createTimeType(9), "TIME '15:12:34.567000000'")
.addRoundTrip(inputType, inputLiteralFactory.apply("'23:59:59.000000000'"), createTimeType(9), "TIME '23:59:59.000000000'")
.addRoundTrip(inputType, inputLiteralFactory.apply("'23:59:59.999000000'"), createTimeType(9), "TIME '23:59:59.999000000'")
.addRoundTrip(inputType, inputLiteralFactory.apply("'23:59:59.999900000'"), createTimeType(9), "TIME '23:59:59.999900000'")
.addRoundTrip(inputType, inputLiteralFactory.apply("'23:59:59.999990000'"), createTimeType(9), "TIME '23:59:59.999990000'")
.addRoundTrip(inputType, inputLiteralFactory.apply("'23:59:59.999999999'"), createTimeType(9), "TIME '23:59:59.999999999'")
.addRoundTrip(inputType, inputLiteralFactory.apply("NULL"), createTimeType(9), "CAST(NULL AS TIME(9))");
}

@Test(dataProvider = "sessionZonesDataProvider")
public void testCassandraTimestamp(ZoneId sessionZone)
{
Expand Down Expand Up @@ -663,6 +699,16 @@ private void assertCassandraQueryFails(@Language("SQL") String sql, String expec
assertThatThrownBy(() -> session.execute(sql)).hasMessageContaining(expectedMessage);
}

private static Function<String, String> trinoTimeInputLiteralFactory()
{
return "CAST(%s AS TIME(9))"::formatted;
}

private static Function<String, String> cassandraTimeInputLiteralFactory()
{
return literal -> literal;
}

private static BiFunction<LocalDateTime, ZoneId, String> cassandraTimestampInputLiteralFactory()
{
return timestampInputLiteralFactory(Optional.empty());
Expand Down