diff --git a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcTime.java b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcTime.java index f87d7f9004..b859e9f58d 100644 --- a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcTime.java +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcTime.java @@ -16,14 +16,9 @@ */ package org.apache.arrow.driver.jdbc; -import static org.apache.calcite.avatica.util.DateTimeUtils.MILLIS_PER_DAY; - -import com.google.common.collect.ImmutableList; import java.sql.Time; import java.time.LocalTime; -import java.time.temporal.ChronoField; -import java.util.List; -import java.util.Objects; +import java.util.Locale; import java.util.concurrent.TimeUnit; import org.apache.arrow.util.VisibleForTesting; @@ -32,13 +27,11 @@ * this#toString. */ public class ArrowFlightJdbcTime extends Time { - private static final List LEADING_ZEROES = ImmutableList.of("", "0", "00"); - - // Desired length of the millisecond portion should be 3 - private static final int DESIRED_MILLIS_LENGTH = 3; + private static final int NANOS_PER_SECOND = 1_000_000_000; + private static final int NANOS_PER_MILLI = 1_000_000; - // Millis of the date time object. - private final int millisReprValue; + // Fraction of the second in nanoseconds. java.sql.Time itself only holds milliseconds. + private final int nanos; /** * Constructs this object based on epoch millis. @@ -46,53 +39,64 @@ public class ArrowFlightJdbcTime extends Time { * @param milliseconds milliseconds representing Time. */ public ArrowFlightJdbcTime(final long milliseconds) { + this(milliseconds, (int) TimeUnit.MILLISECONDS.toNanos(Math.floorMod(milliseconds, 1000L))); + } + + /** + * Constructs this object based on epoch millis and the full fraction of the second. + * + * @param milliseconds milliseconds representing Time. + * @param nanos fraction of the second in nanoseconds, including the millisecond part. Its + * millisecond part must be the same as the one of {@code milliseconds}. + * @throws IllegalArgumentException if {@code nanos} is out of range, or if its millisecond part + * differs from the one of {@code milliseconds}. + */ + public ArrowFlightJdbcTime(final long milliseconds, final int nanos) { super(milliseconds); - millisReprValue = getMillisReprValue(milliseconds); + if (nanos < 0 || nanos >= NANOS_PER_SECOND) { + throw new IllegalArgumentException("nanos must be between 0 and 999999999: " + nanos); + } + if (Math.floorMod(milliseconds, 1000L) != nanos / NANOS_PER_MILLI) { + throw new IllegalArgumentException( + "nanos (" + + nanos + + ") must have the same millisecond part as milliseconds (" + + milliseconds + + ")"); + } + this.nanos = nanos; } @VisibleForTesting ArrowFlightJdbcTime(final LocalTime time) { - // Although the constructor is deprecated, this is the exact same code as - // Time#valueOf(LocalTime) - super(time.getHour(), time.getMinute(), time.getSecond()); - millisReprValue = time.get(ChronoField.MILLI_OF_SECOND); + // Time#valueOf(LocalTime) drops the fraction of the second, so the milliseconds are added back + this(Time.valueOf(time).getTime() + time.getNano() / NANOS_PER_MILLI, time.getNano()); } - private int getMillisReprValue(long milliseconds) { - // Extract the millisecond part from epoch nano day - if (milliseconds >= MILLIS_PER_DAY) { - // Convert to Epoch Day - milliseconds %= MILLIS_PER_DAY; - } else if (milliseconds < 0) { - // LocalTime#ofNanoDay only accepts positive values - milliseconds -= ((milliseconds / MILLIS_PER_DAY) - 1) * MILLIS_PER_DAY; - } - return LocalTime.ofNanoOfDay(TimeUnit.MILLISECONDS.toNanos(milliseconds)) - .get(ChronoField.MILLI_OF_SECOND); + /** Returns the time with the full fraction of the second, not only whole seconds. */ + @Override + public LocalTime toLocalTime() { + return super.toLocalTime().withNano(nanos); } + /** + * Formats the time as {@code hh:mm:ss}, followed by 3, 6 or 9 fractional digits if the fraction + * of the second is not zero. + */ @Override public String toString() { final StringBuilder time = new StringBuilder().append(super.toString()); - if (millisReprValue > 0) { - final String millisString = Integer.toString(millisReprValue); - - // dot to separate the fractional seconds - time.append("."); - - final int millisLength = millisString.length(); - if (millisLength < DESIRED_MILLIS_LENGTH) { - // add necessary leading zeroes - time.append(LEADING_ZEROES.get(DESIRED_MILLIS_LENGTH - millisLength)); - } - time.append(millisString); + if (nanos > 0) { + final int digits = nanos % 1_000_000 == 0 ? 3 : nanos % 1_000 == 0 ? 6 : 9; + time.append('.').append(String.format(Locale.ROOT, "%09d", nanos), 0, digits); } return time.toString(); } - // Spotbugs requires these methods to be overridden + // Spotbugs requires these methods to be overridden. Like java.sql.Time, equality is based on the + // millisecond value only, so that this class stays interchangeable with java.sql.Time. @Override public boolean equals(Object obj) { return super.equals(obj); @@ -100,6 +104,6 @@ public boolean equals(Object obj) { @Override public int hashCode() { - return Objects.hash(super.hashCode(), this.millisReprValue); + return super.hashCode(); } } diff --git a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/accessor/impl/calendar/ArrowFlightJdbcTimeVectorAccessor.java b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/accessor/impl/calendar/ArrowFlightJdbcTimeVectorAccessor.java index d525c2fdd2..b3d2c5ee63 100644 --- a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/accessor/impl/calendar/ArrowFlightJdbcTimeVectorAccessor.java +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/accessor/impl/calendar/ArrowFlightJdbcTimeVectorAccessor.java @@ -23,14 +23,15 @@ import java.sql.SQLException; import java.sql.Time; import java.sql.Timestamp; +import java.time.LocalDate; import java.time.LocalTime; +import java.time.ZoneId; import java.util.Calendar; import java.util.concurrent.TimeUnit; import java.util.function.IntSupplier; import org.apache.arrow.driver.jdbc.ArrowFlightJdbcTime; import org.apache.arrow.driver.jdbc.accessor.ArrowFlightJdbcAccessor; import org.apache.arrow.driver.jdbc.accessor.ArrowFlightJdbcAccessorFactory; -import org.apache.arrow.driver.jdbc.utils.DateTimeUtils; import org.apache.arrow.vector.TimeMicroVector; import org.apache.arrow.vector.TimeMilliVector; import org.apache.arrow.vector.TimeNanoVector; @@ -47,6 +48,8 @@ public class ArrowFlightJdbcTimeVectorAccessor extends ArrowFlightJdbcAccessor { private final TimeUnit timeUnit; private final Holder holder; + private static final long NANOS_PER_DAY = TimeUnit.DAYS.toNanos(1); + /** * Instantiate an accessor for a {@link TimeNanoVector}. * @@ -136,21 +139,35 @@ public T getObject(final Class type) throws SQLException { return !type.isPrimitive() && wasNull ? null : type.cast(value); } + /** + * Returns the value as a {@link Time} holding the wall-clock time of the column in the time zone + * of the given calendar, or in the JVM default time zone if no calendar is given. TIME has no + * time zone, so the value read with the default calendar prints the same in any client zone. + * + *

{@link Time} is limited to milliseconds. The returned object keeps the full fraction for + * {@link Time#toString()} and {@link Time#toLocalTime()} only. + */ @Override public Time getTime(Calendar calendar) { - fillHolder(); - if (this.wasNull) { + LocalTime localTime = getLocalTime(); + if (localTime == null) { return null; } - long value = holder.value; - long milliseconds = this.timeUnit.toMillis(value); + ZoneId zone = calendar == null ? ZoneId.systemDefault() : calendar.getTimeZone().toZoneId(); + long milliseconds = localTime.atDate(LocalDate.EPOCH).atZone(zone).toInstant().toEpochMilli(); - return new ArrowFlightJdbcTime(DateTimeUtils.applyCalendarOffset(milliseconds, calendar)); + return new ArrowFlightJdbcTime(milliseconds, localTime.getNano()); } private LocalTime getLocalTime() { - return getTime(null).toLocalTime(); + fillHolder(); + if (this.wasNull) { + return null; + } + + long nanoseconds = this.timeUnit.toNanos(holder.value); + return LocalTime.ofNanoOfDay(Math.floorMod(nanoseconds, NANOS_PER_DAY)); } private void fillHolder() { @@ -165,7 +182,9 @@ public Timestamp getTimestamp(Calendar calendar) { if (time == null) { return null; } - return new Timestamp(time.getTime()); + Timestamp timestamp = new Timestamp(time.getTime()); + timestamp.setNanos(time.toLocalTime().getNano()); + return timestamp; } protected static TimeUnit getTimeUnitForVector(ValueVector vector) { diff --git a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/converter/impl/TimeAvaticaParameterConverter.java b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/converter/impl/TimeAvaticaParameterConverter.java index 0340eb6099..9e53d5d51a 100644 --- a/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/converter/impl/TimeAvaticaParameterConverter.java +++ b/flight/flight-sql-jdbc-core/src/main/java/org/apache/arrow/driver/jdbc/converter/impl/TimeAvaticaParameterConverter.java @@ -16,6 +16,8 @@ */ package org.apache.arrow.driver.jdbc.converter.impl; +import java.time.LocalTime; +import java.util.concurrent.TimeUnit; import org.apache.arrow.vector.FieldVector; import org.apache.arrow.vector.TimeMicroVector; import org.apache.arrow.vector.TimeMilliVector; @@ -33,18 +35,23 @@ public TimeAvaticaParameterConverter(ArrowType.Time type) {} @Override public boolean bindParameter(FieldVector vector, TypedValue typedValue, int index) { - int value = (int) typedValue.toLocal(); + // Avatica passes java.sql.Time as milliseconds of the day, and java.time.LocalTime as it is. + final Object value = typedValue.toLocal(); + final long nanoOfDay = + value instanceof LocalTime + ? ((LocalTime) value).toNanoOfDay() + : TimeUnit.MILLISECONDS.toNanos((int) value); if (vector instanceof TimeMicroVector) { - ((TimeMicroVector) vector).setSafe(index, value); + ((TimeMicroVector) vector).setSafe(index, TimeUnit.NANOSECONDS.toMicros(nanoOfDay)); return true; } else if (vector instanceof TimeMilliVector) { - ((TimeMilliVector) vector).setSafe(index, value); + ((TimeMilliVector) vector).setSafe(index, (int) TimeUnit.NANOSECONDS.toMillis(nanoOfDay)); return true; } else if (vector instanceof TimeNanoVector) { - ((TimeNanoVector) vector).setSafe(index, value); + ((TimeNanoVector) vector).setSafe(index, nanoOfDay); return true; } else if (vector instanceof TimeSecVector) { - ((TimeSecVector) vector).setSafe(index, value); + ((TimeSecVector) vector).setSafe(index, (int) TimeUnit.NANOSECONDS.toSeconds(nanoOfDay)); return true; } return false; diff --git a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcTimeTest.java b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcTimeTest.java index aa499d805b..52e4ef92d7 100644 --- a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcTimeTest.java +++ b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/ArrowFlightJdbcTimeTest.java @@ -19,8 +19,10 @@ import static org.hamcrest.CoreMatchers.endsWith; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.jupiter.api.Assertions.assertThrows; import java.time.LocalTime; +import java.util.Locale; import java.util.concurrent.TimeUnit; import org.junit.jupiter.api.Test; @@ -65,6 +67,77 @@ public void testPrintingMillisTwoLeadingZeroes() { assertThat(time.getSeconds(), is(second)); } + @Test + public void testPrintingMicros() { + LocalTime localTime = LocalTime.of(hour, minute, second, 123_456_000); + ArrowFlightJdbcTime time = new ArrowFlightJdbcTime(localTime); + assertThat(time.toString(), is("05:06:07.123456")); + assertThat(time.toLocalTime(), is(localTime)); + } + + @Test + public void testPrintingNanos() { + LocalTime localTime = LocalTime.of(hour, minute, second, 1); + ArrowFlightJdbcTime time = new ArrowFlightJdbcTime(localTime); + assertThat(time.toString(), is("05:06:07.000000001")); + assertThat(time.toLocalTime(), is(localTime)); + } + + @Test + public void testPrintingFractionIgnoresDefaultLocale() { + final Locale defaultLocale = Locale.getDefault(); + try { + Locale.setDefault(Locale.forLanguageTag("ar-EG")); + ArrowFlightJdbcTime time = + new ArrowFlightJdbcTime(LocalTime.of(hour, minute, second, 123_456_000)); + assertThat(time.toString(), is("05:06:07.123456")); + } finally { + Locale.setDefault(defaultLocale); + } + } + + @Test + public void testPrintingWholeSeconds() { + ArrowFlightJdbcTime time = new ArrowFlightJdbcTime(LocalTime.of(hour, minute, second)); + assertThat(time.toString(), is("05:06:07")); + } + + @Test + public void testMillisAndNanosConstructor() { + long millis = new ArrowFlightJdbcTime(LocalTime.of(hour, minute, second)).getTime() + 123; + ArrowFlightJdbcTime time = new ArrowFlightJdbcTime(millis, 123_456_789); + assertThat(time.getTime(), is(millis)); + assertThat(time.toString(), is("05:06:07.123456789")); + assertThat(new ArrowFlightJdbcTime(millis).toString(), is("05:06:07.123")); + assertThrows(IllegalArgumentException.class, () -> new ArrowFlightJdbcTime(millis, -1)); + assertThrows( + IllegalArgumentException.class, () -> new ArrowFlightJdbcTime(millis, 1_000_000_000)); + } + + @Test + public void testMillisAndNanosMustAgree() { + long millis = new ArrowFlightJdbcTime(LocalTime.of(hour, minute, second)).getTime() + 500; + // .500 in the milliseconds, but .123456789 in the nanos + assertThrows( + IllegalArgumentException.class, () -> new ArrowFlightJdbcTime(millis, 123_456_789)); + assertThrows(IllegalArgumentException.class, () -> new ArrowFlightJdbcTime(millis, 0)); + + // before the epoch, the millisecond part is still counted from the start of the second + ArrowFlightJdbcTime beforeEpoch = new ArrowFlightJdbcTime(-1L, 999_000_001); + assertThat(beforeEpoch.getTime(), is(-1L)); + assertThat(beforeEpoch.toLocalTime().getNano(), is(999_000_001)); + assertThrows(IllegalArgumentException.class, () -> new ArrowFlightJdbcTime(-1L, 1_000_000)); + } + + @Test + public void testAllViewsOfTheFractionAgree() { + LocalTime localTime = LocalTime.of(hour, minute, second, 123_456_789); + ArrowFlightJdbcTime time = new ArrowFlightJdbcTime(localTime); + assertThat(Math.floorMod(time.getTime(), 1000L), is(123L)); + assertThat(time.toString(), is("05:06:07.123456789")); + assertThat(time.toLocalTime(), is(localTime)); + } + @Test public void testEquality() { // tests #equals and #hashCode for coverage checks diff --git a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/calendar/ArrowFlightJdbcTimeVectorAccessorTest.java b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/calendar/ArrowFlightJdbcTimeVectorAccessorTest.java index 24971052db..85e5716bcd 100644 --- a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/calendar/ArrowFlightJdbcTimeVectorAccessorTest.java +++ b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/accessor/impl/calendar/ArrowFlightJdbcTimeVectorAccessorTest.java @@ -25,6 +25,9 @@ import java.sql.Time; import java.sql.Timestamp; import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.temporal.ChronoField; +import java.time.temporal.ChronoUnit; import java.util.Calendar; import java.util.TimeZone; import java.util.concurrent.TimeUnit; @@ -43,6 +46,7 @@ import org.apache.arrow.vector.util.Text; import org.hamcrest.CoreMatchers; import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.RegisterExtension; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; @@ -245,8 +249,8 @@ public void testValidateGetStringTimeZoneConsistency( (accessor, currentRow) -> { final TimeZone defaultTz = TimeZone.getDefault(); try { - final String string = - accessor.getString(); // Should always be UTC as no calendar is provided + // Wall-clock time in the default time zone, as no calendar is provided + final String string = accessor.getString(); // Validate with UTC Time time = accessor.getTime(null); @@ -265,6 +269,114 @@ public void testValidateGetStringTimeZoneConsistency( }); } + @Test + public void testGetTimeWithCalendarInNonUtcDefaultZone() throws Exception { + // 12:34:56.789 = 45_296_789 ms of the day + final int millisOfDay = (int) (LocalTime.parse("12:34:56.789").toNanoOfDay() / 1_000_000); + try (TimeMilliVector milliVector = + new TimeMilliVector("", rootAllocatorTestExtension.getRootAllocator())) { + milliVector.setSafe(0, millisOfDay); + milliVector.setValueCount(1); + this.vector = milliVector; + + final TimeZone defaultTz = TimeZone.getDefault(); + try { + TimeZone.setDefault(TimeZone.getTimeZone("Europe/Berlin")); // UTC+1 on 1970-01-01 + ArrowFlightJdbcTimeVectorAccessor accessor = accessorSupplier.supply(vector, () -> 0); + Calendar vancouver = Calendar.getInstance(TimeZone.getTimeZone(AMERICA_VANCOUVER)); // UTC-8 + + // JDBC: the calendar's zone gives the wall-clock time its instant. + // 12:34:56.789 in Vancouver = 20:34:56.789 UTC = 74_096_789 epoch ms. + // The old code also added the default zone's offset and gave 77_696_789 (21:34:56.789 + // UTC). + assertThat(accessor.getTime(vancouver).getTime(), is(74_096_789L)); + assertThat(accessor.getTimestamp(vancouver).getTime(), is(74_096_789L)); + + // With no calendar, the default zone is used: 12:34:56.789 in Berlin = 11:34:56.789 UTC. + // The old code returned the raw 45_296_789, which prints as 13:34:56.789 in Berlin. + assertThat(accessor.getTime(null).getTime(), is(41_696_789L)); + assertThat(accessor.getTime(null).toString(), is("12:34:56.789")); + } finally { + TimeZone.setDefault(defaultTz); + } + } + } + + @Test + public void testShouldKeepMicrosecondsInAnyDefaultTimeZone() throws Exception { + try (TimeMicroVector microVector = + new TimeMicroVector("", rootAllocatorTestExtension.getRootAllocator())) { + microVector.setSafe(0, LocalTime.parse("12:34:56.123456").toNanoOfDay() / 1_000); + microVector.setSafe(1, LocalTime.parse("23:59:59.999999").toNanoOfDay() / 1_000); + microVector.setValueCount(2); + this.vector = microVector; + + assertWallClockTime(0, "12:34:56.123456"); + assertWallClockTime(1, "23:59:59.999999"); + } + } + + @Test + public void testShouldKeepNanosecondsInAnyDefaultTimeZone() throws Exception { + try (TimeNanoVector nanoVector = + new TimeNanoVector("", rootAllocatorTestExtension.getRootAllocator())) { + nanoVector.setSafe(0, LocalTime.parse("12:34:56.123456789").toNanoOfDay()); + nanoVector.setSafe(1, LocalTime.parse("00:00:00.000000001").toNanoOfDay()); + nanoVector.setValueCount(2); + this.vector = nanoVector; + + assertWallClockTime(0, "12:34:56.123456789"); + assertWallClockTime(1, "00:00:00.000000001"); + } + } + + @ParameterizedTest + @MethodSource("data") + public void testShouldGetObjectWithLocalTimeClassReturnNull( + Supplier vectorSupplier) throws Exception { + setup(vectorSupplier); + vector.setNull(0); + ArrowFlightJdbcTimeVectorAccessor accessor = accessorSupplier.supply(vector, () -> 0); + assertThat(accessor.getObject(LocalTime.class), CoreMatchers.equalTo(null)); + assertThat(accessor.wasNull(), is(true)); + } + + private void assertWallClockTime(int row, String expected) throws Exception { + final LocalTime expectedLocalTime = LocalTime.parse(expected); + final TimeZone defaultTz = TimeZone.getDefault(); + try { + for (String zone : new String[] {"UTC", "Europe/Berlin", AMERICA_VANCOUVER, "Asia/Kolkata"}) { + TimeZone.setDefault(TimeZone.getTimeZone(zone)); + ArrowFlightJdbcTimeVectorAccessor accessor = accessorSupplier.supply(vector, () -> row); + + assertThat(zone, accessor.getString(), is(expected)); + assertThat(zone, accessor.getObject(LocalTime.class), is(expectedLocalTime)); + assertThat(zone, accessor.getObject().toString(), is(expected)); + + final Time time = accessor.getTime(null); + assertThat(zone, time.toString(), is(expected)); + assertThat(zone, time.toLocalTime(), is(expectedLocalTime)); + // java.sql.Time itself is limited to milliseconds + assertThat( + zone, + new Time(time.getTime()).toLocalTime(), + is(expectedLocalTime.truncatedTo(ChronoUnit.SECONDS))); + assertThat( + zone, + Math.floorMod(time.getTime(), 1000L), + is((long) expectedLocalTime.get(ChronoField.MILLI_OF_SECOND))); + + assertThat( + zone, + accessor.getTimestamp(null).toLocalDateTime().toLocalTime(), + is(expectedLocalTime)); + assertThat(accessor.wasNull(), is(false)); + } + } finally { + TimeZone.setDefault(defaultTz); + } + } + private void assertGetStringIsConsistentWithVarCharAccessor(Calendar calendar) throws Exception { try (VarCharVector varCharVector = new VarCharVector("", rootAllocatorTestExtension.getRootAllocator())) { diff --git a/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/converter/impl/TimeAvaticaParameterConverterTest.java b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/converter/impl/TimeAvaticaParameterConverterTest.java new file mode 100644 index 0000000000..1a07badc17 --- /dev/null +++ b/flight/flight-sql-jdbc-core/src/test/java/org/apache/arrow/driver/jdbc/converter/impl/TimeAvaticaParameterConverterTest.java @@ -0,0 +1,121 @@ +/* + * 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.arrow.driver.jdbc.converter.impl; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.sql.Time; +import java.time.LocalTime; +import java.util.Calendar; +import java.util.TimeZone; +import org.apache.arrow.memory.BufferAllocator; +import org.apache.arrow.memory.RootAllocator; +import org.apache.arrow.vector.TimeMicroVector; +import org.apache.arrow.vector.TimeMilliVector; +import org.apache.arrow.vector.TimeNanoVector; +import org.apache.arrow.vector.TimeSecVector; +import org.apache.arrow.vector.types.TimeUnit; +import org.apache.arrow.vector.types.pojo.ArrowType; +import org.apache.calcite.avatica.ColumnMetaData; +import org.apache.calcite.avatica.remote.TypedValue; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** Tests for {@link TimeAvaticaParameterConverter}. */ +public class TimeAvaticaParameterConverterTest { + + private static final LocalTime LOCAL_TIME = LocalTime.parse("12:34:56.123456789"); + private static final long NANO_OF_DAY = LOCAL_TIME.toNanoOfDay(); + + private final TimeAvaticaParameterConverter converter = + new TimeAvaticaParameterConverter(new ArrowType.Time(TimeUnit.MICROSECOND, 64)); + + private BufferAllocator allocator; + + @BeforeEach + public void setUp() { + allocator = new RootAllocator(); + } + + @AfterEach + public void tearDown() { + allocator.close(); + } + + /** The value Avatica creates for {@code PreparedStatement.setObject(i, LocalTime)}. */ + private static TypedValue localTimeValue() { + return TypedValue.ofJdbc(LOCAL_TIME, Calendar.getInstance()); + } + + /** The value Avatica creates for {@code PreparedStatement.setTime(i, Time)}. */ + private static TypedValue sqlTimeValue() { + Calendar utc = Calendar.getInstance(TimeZone.getTimeZone("UTC")); + long millisOfDay = NANO_OF_DAY / 1_000_000; + return TypedValue.ofJdbc(ColumnMetaData.Rep.JAVA_SQL_TIME, new Time(millisOfDay), utc); + } + + @Test + public void testBindLocalTime() { + try (TimeSecVector sec = new TimeSecVector("", allocator); + TimeMilliVector milli = new TimeMilliVector("", allocator); + TimeMicroVector micro = new TimeMicroVector("", allocator); + TimeNanoVector nano = new TimeNanoVector("", allocator)) { + assertTrue(converter.bindParameter(sec, localTimeValue(), 0)); + assertTrue(converter.bindParameter(milli, localTimeValue(), 0)); + assertTrue(converter.bindParameter(micro, localTimeValue(), 0)); + assertTrue(converter.bindParameter(nano, localTimeValue(), 0)); + + assertEquals(NANO_OF_DAY / 1_000_000_000, sec.get(0)); + assertEquals(NANO_OF_DAY / 1_000_000, milli.get(0)); + assertEquals(NANO_OF_DAY / 1_000, micro.get(0)); + assertEquals(NANO_OF_DAY, nano.get(0)); + } + } + + @Test + public void testBindSqlTimeConvertsToVectorUnit() { + long millisOfDay = NANO_OF_DAY / 1_000_000; + try (TimeSecVector sec = new TimeSecVector("", allocator); + TimeMilliVector milli = new TimeMilliVector("", allocator); + TimeMicroVector micro = new TimeMicroVector("", allocator); + TimeNanoVector nano = new TimeNanoVector("", allocator)) { + assertTrue(converter.bindParameter(sec, sqlTimeValue(), 0)); + assertTrue(converter.bindParameter(milli, sqlTimeValue(), 0)); + assertTrue(converter.bindParameter(micro, sqlTimeValue(), 0)); + assertTrue(converter.bindParameter(nano, sqlTimeValue(), 0)); + + assertEquals(millisOfDay / 1_000, sec.get(0)); + assertEquals(millisOfDay, milli.get(0)); + assertEquals(millisOfDay * 1_000, micro.get(0)); + assertEquals(millisOfDay * 1_000_000, nano.get(0)); + } + } + + @Test + public void testBindUnsupportedValue() { + try (TimeMicroVector micro = new TimeMicroVector("", allocator)) { + assertThrows( + ClassCastException.class, + () -> + converter.bindParameter( + micro, TypedValue.ofLocal(ColumnMetaData.Rep.STRING, "12:34:56"), 0)); + } + } +}