Skip to content
Open
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 @@ -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;

Expand All @@ -32,74 +27,83 @@
* this#toString.
*/
public class ArrowFlightJdbcTime extends Time {
private static final List<String> 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.
*
* @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) {

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.

I think the two parameters can allow conflicting nano settings.

// 45_296_500 ms = 12:34:56.500, but nanos says .123456789
ArrowFlightJdbcTime t = new ArrowFlightJdbcTime(45_296_500L, 123_456_789);

t.getTime();      // 45_296_500             -> .500  (from milliseconds)
t.toString();     // "12:34:56.123456789"   -> .123  (hh:mm:ss from millis, fraction from nanos)
t.toLocalTime();  // 12:34:56.123456789     -> .123
new Timestamp(t.getTime()).getNanos();  // 500_000_000
t.equals(new Time(45_296_500L));        // true, because equals only compares millis

Two ideas for fixing it:

// 1. Reject values that disagree
if (Math.floorMod(milliseconds, 1000L) != nanos / 1_000_000) {
  throw new IllegalArgumentException(...);
}

// 2. Let nanos decide, and rebuild the millis from it
super(Math.floorDiv(milliseconds, 1000L) * 1000L + nanos / 1_000_000);

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Good point. I went with the first idea: the constructor now throws IllegalArgumentException when the millisecond part of nanos differs from the one of milliseconds, so a mismatch fails loudly rather than being silently rewritten. The check uses Math.floorMod, so values before the epoch work too.

While there I also fixed the test-only LocalTime constructor, which had the same problem the other way round: it kept the fraction in nanos but dropped it from getTime(). Tests cover both.

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);
}

@Override
public int hashCode() {
return Objects.hash(super.hashCode(), this.millisReprValue);
return super.hashCode();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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}.
*
Expand Down Expand Up @@ -136,21 +139,35 @@ public <T> T getObject(final Class<T> 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.
*
* <p>{@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();
Comment on lines +157 to +158

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.

On your question in #1539: I don't think we need a legacy path here. I know the timestamp accessor keeps one in getTimestampWithOffset, but for TIME the shift is the bug being fixed, and keeping it would leave getTime wrong outside UTC.

It is still a visible change: with a Europe/Berlin JVM, getTime() for 12:34:56.123 goes from epoch millis 45296123 to 41696123. We should keep this in the PR description with a before/after example. Let me add a breaking-change label too.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Agreed, no legacy path then. I added a before/after example for a Europe/Berlin JVM to the PR description and marked it as containing breaking changes. Thanks for adding the label.


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() {
Expand All @@ -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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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
Expand Down
Loading