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,54 +16,97 @@
*/
package org.apache.arrow.driver.jdbc.converter.impl;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.TimeZone;
import org.apache.arrow.vector.FieldVector;
import org.apache.arrow.vector.TimeStampMicroTZVector;
import org.apache.arrow.vector.TimeStampMicroVector;
import org.apache.arrow.vector.TimeStampMilliTZVector;
import org.apache.arrow.vector.TimeStampMilliVector;
import org.apache.arrow.vector.TimeStampNanoTZVector;
import org.apache.arrow.vector.TimeStampNanoVector;
import org.apache.arrow.vector.TimeStampSecTZVector;
import org.apache.arrow.vector.TimeStampSecVector;
import org.apache.arrow.vector.TimeStampVector;
import org.apache.arrow.vector.types.pojo.ArrowType;
import org.apache.arrow.vector.types.pojo.Field;
import org.apache.calcite.avatica.AvaticaParameter;
import org.apache.calcite.avatica.ColumnMetaData;
import org.apache.calcite.avatica.remote.TypedValue;

/** AvaticaParameterConverter for Timestamp Arrow types. */
public class TimestampAvaticaParameterConverter extends BaseAvaticaParameterConverter {

private static final long MILLIS_PER_SECOND = 1_000L;
private static final long MICROS_PER_SECOND = 1_000_000L;
private static final long NANOS_PER_SECOND = 1_000_000_000L;

public TimestampAvaticaParameterConverter(ArrowType.Timestamp type) {}

@Override
public boolean bindParameter(FieldVector vector, TypedValue typedValue, int index) {
long value = (long) typedValue.toLocal();
if (vector instanceof TimeStampSecVector) {
((TimeStampSecVector) vector).setSafe(index, value);
return true;
} else if (vector instanceof TimeStampMicroVector) {
((TimeStampMicroVector) vector).setSafe(index, value);
return true;
} else if (vector instanceof TimeStampMilliVector) {
((TimeStampMilliVector) vector).setSafe(index, value);
return true;
} else if (vector instanceof TimeStampNanoVector) {
((TimeStampNanoVector) vector).setSafe(index, value);
return true;
} else if (vector instanceof TimeStampSecTZVector) {
((TimeStampSecTZVector) vector).setSafe(index, value);
return true;
} else if (vector instanceof TimeStampMicroTZVector) {
((TimeStampMicroTZVector) vector).setSafe(index, value);
return true;
} else if (vector instanceof TimeStampMilliTZVector) {
((TimeStampMilliTZVector) vector).setSafe(index, value);
return true;
} else if (vector instanceof TimeStampNanoTZVector) {
((TimeStampNanoTZVector) vector).setSafe(index, value);
if (!(vector instanceof TimeStampVector)) {
return false;
}
if (typedValue.type == ColumnMetaData.Rep.LONG) {
// setLong / setObject(Long): the value is already in the unit of the vector
((TimeStampVector) vector).setSafe(index, (long) typedValue.toLocal());
return true;
}
return false;
final ArrowType.Timestamp type = (ArrowType.Timestamp) vector.getField().getType();
final Instant instant = toInstant(typedValue.toLocal(), type.getTimezone());
((TimeStampVector) vector).setSafe(index, toVectorValue(instant, type));
return true;
}

/**
* Converts the parameter value to the instant to store in the vector. For a vector without a time
* zone, this is the wall-clock time of the value as if it was in UTC.
*/
private static Instant toInstant(Object value, String vectorTimeZone) {
if (value instanceof LocalDateTime) {
final LocalDateTime localDateTime = (LocalDateTime) value;
return vectorTimeZone == null
? localDateTime.toInstant(ZoneOffset.UTC)
: localDateTime.atZone(TimeZone.getTimeZone(vectorTimeZone).toZoneId()).toInstant();

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.

[P2] Parse Arrow’s numeric timezone offsets. The Arrow timestamp schema permits offsets such as +03:00 and -05:30, but TimeZone.getTimeZone silently resolves both to GMT. I ran the conversion helper on JDK 21: 2024-03-15T12:00 in +03:00 binds 12:00Z instead of 09:00Z. Could this path use ZoneId.of(vectorTimeZone) and add a numeric-offset case alongside the named-zone tests?

} else if (value instanceof Instant
|| value instanceof OffsetDateTime
|| value instanceof ZonedDateTime) {
if (vectorTimeZone == null) {
throw new UnsupportedOperationException(
String.format(
"Can't bind %s to a timestamp parameter without a time zone; use LocalDateTime.",
value.getClass().getSimpleName()));
}
if (value instanceof Instant) {
return (Instant) value;
}
return value instanceof OffsetDateTime
? ((OffsetDateTime) value).toInstant()
: ((ZonedDateTime) value).toInstant();
}
// Avatica passes java.sql.Timestamp and java.util.Date as milliseconds since the epoch,
// already adjusted by the offset of the connection calendar.
return Instant.ofEpochMilli((long) value);

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.

This fallback also catches values bound with setLong and setObject(Long), not only java.sql.Timestamp and java.util.Date. Avatica passes those as Rep.LONG. On main, they were written to the vector unchanged, so setLong was the only way to bind a correct second, microsecond or nanosecond value. With this change they are read as epoch millis:

Parameter Call main This PR
Timestamp(MICROSECOND) setLong(1, 1_710_506_096_123_456L) 1710506096123456 1710506096123456000 (year 56173)
Timestamp(SECOND) setLong(1, 1_710_506_096L) 1710506096 1710506 (1970-01-20)
Timestamp(NANOSECOND) setLong(1, 1_710_506_096_123_456_789L) stored unchanged ArithmeticException: long overflow

Clients using setLong as a workaround for #1540 would silently start writing wrong values for the first two.

I would suggest keeping longs unchanged, since they are already in the vector's unit, and only converting the date/time types. In bindParameter, before toInstant:

if (typedValue.type == ColumnMetaData.Rep.LONG) {
  // setLong / setObject(Long): the value is already in the unit of the vector
  ((TimeStampVector) vector).setSafe(index, (long) typedValue.toLocal());
  return true;
}

A test that binds TypedValue.ofJdbc(ColumnMetaData.Rep.LONG, ...) to each unit would cover it. If you would rather keep the epoc-millis reading for longs, which matches Avatica's own setObject(Long, Types.TIMESTAMP), that works for me 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.

Good catch — fixed in the latest push. Rep.LONG values are now written to the vector unchanged, as on main, and only the date/time types are converted. I added a test that binds a long to each unit, with and without a timezone, and noted it in the PR description.

}

private static long toVectorValue(Instant instant, ArrowType.Timestamp type) {
final long seconds = instant.getEpochSecond();
final long nanos = instant.getNano();
switch (type.getUnit()) {
case SECOND:
return seconds;
case MILLISECOND:
return toUnit(seconds, nanos, MILLIS_PER_SECOND);
case MICROSECOND:
return toUnit(seconds, nanos, MICROS_PER_SECOND);
case NANOSECOND:
return toUnit(seconds, nanos, NANOS_PER_SECOND);
default:
throw new UnsupportedOperationException("Invalid Arrow time unit");
}
}

private static long toUnit(long seconds, long nanos, long unitsPerSecond) {
// Fails with ArithmeticException instead of binding a wrong value if it does not fit in a long
return Math.addExact(
Math.multiplyExact(seconds, unitsPerSecond), nanos / (NANOS_PER_SECOND / unitsPerSecond));

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.

[P2] Check overflow on the final timestamp value. For the nanosecond value 1677-09-21T00:12:43.145224192Z, the exact result is Long.MIN_VALUE, but the seconds multiplication underflows before the positive fractional part is added. I reproduced this on JDK 21 at the lower bound in milliseconds, microseconds, and nanoseconds. For negative seconds, computing (seconds + 1) * unitsPerSecond + (fraction - unitsPerSecond) with the exact arithmetic helpers covers this boundary. A regression at Long.MIN_VALUE and one unit below it would check both sides.

}

@Override
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,200 @@
/*
* 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.time.Instant;
import java.time.LocalDateTime;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.Calendar;
import java.util.stream.Stream;
import org.apache.arrow.memory.BufferAllocator;
import org.apache.arrow.memory.RootAllocator;
import org.apache.arrow.vector.FieldVector;
import org.apache.arrow.vector.TimeStampVector;
import org.apache.arrow.vector.types.TimeUnit;
import org.apache.arrow.vector.types.pojo.ArrowType;
import org.apache.arrow.vector.types.pojo.FieldType;
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;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

/** Tests for {@link TimestampAvaticaParameterConverter}. */
public class TimestampAvaticaParameterConverterTest {

private static final String NEW_YORK = "America/New_York";
private static final LocalDateTime LOCAL_DATE_TIME =
LocalDateTime.parse("2024-03-15T12:34:56.123456789");
// 2024-03-15T12:34:56 UTC
private static final long EPOCH_SECOND = 1_710_506_096L;
// New York is at UTC-4 on that day
private static final long NEW_YORK_EPOCH_SECOND = EPOCH_SECOND + 4 * 60 * 60;

private BufferAllocator allocator;

@BeforeEach
public void setUp() {
allocator = new RootAllocator();
}

@AfterEach
public void tearDown() {
allocator.close();
}

/** Time unit, and the expected vector value for 12:34:56.123456789 at the given epoch second. */
public static Stream<Arguments> units() {
return Stream.of(
Arguments.of(TimeUnit.SECOND, 1L, 0L),
Arguments.of(TimeUnit.MILLISECOND, 1_000L, 123L),
Arguments.of(TimeUnit.MICROSECOND, 1_000_000L, 123_456L),
Arguments.of(TimeUnit.NANOSECOND, 1_000_000_000L, 123_456_789L));
}

private long bind(TimeUnit unit, String timeZone, TypedValue value) {
ArrowType.Timestamp type = new ArrowType.Timestamp(unit, timeZone);
try (FieldVector vector = FieldType.nullable(type).createNewSingleVector("", allocator, null)) {
assertTrue(new TimestampAvaticaParameterConverter(type).bindParameter(vector, value, 0));
vector.setValueCount(1);
return ((TimeStampVector) vector).get(0);
}
}

/** The value Avatica creates for {@code PreparedStatement.setObject(i, value)}. */
private static TypedValue objectValue(Object value) {
return TypedValue.ofJdbc(value, Calendar.getInstance());
}

@ParameterizedTest
@MethodSource("units")
public void testBindSqlTimestampConvertsToVectorUnit(
TimeUnit unit, long unitsPerSecond, long fraction) {
// For PreparedStatement.setTimestamp(i, timestamp), Avatica passes the wall-clock time of the
// timestamp as milliseconds since the epoch, so nothing below milliseconds reaches the
// converter.
long millis = EPOCH_SECOND * 1_000 + 123;
TypedValue value = TypedValue.ofLocal(ColumnMetaData.Rep.JAVA_SQL_TIMESTAMP, millis);
long expected = EPOCH_SECOND * unitsPerSecond + (123L * unitsPerSecond) / 1_000;

assertEquals(expected, bind(unit, null, value));
assertEquals(expected, bind(unit, "UTC", value));
assertEquals(expected, bind(unit, NEW_YORK, value));
}

@ParameterizedTest
@MethodSource("units")
public void testBindSqlTimestampBeforeEpoch(TimeUnit unit, long unitsPerSecond, long fraction) {
// 1969-12-31T23:59:59.500 is half a second before the epoch
TypedValue value = TypedValue.ofLocal(ColumnMetaData.Rep.JAVA_SQL_TIMESTAMP, -500L);
long expected = unit == TimeUnit.SECOND ? -1L : -unitsPerSecond / 2;

assertEquals(expected, bind(unit, null, value));
}

@ParameterizedTest
@MethodSource("units")
public void testBindLongIsNotConverted(TimeUnit unit, long unitsPerSecond, long fraction) {
// For PreparedStatement.setLong(i, value) and setObject(i, Long), the value is already in the
// unit of the vector. The last value does not fit in a long if it is read as milliseconds.
long[] longs = {
0L, -1L, EPOCH_SECOND, 1_710_506_096_123L, 1_710_506_096_123_456L, 1_710_506_096_123_456_789L
};
for (long expected : longs) {
TypedValue value =
TypedValue.ofJdbc(ColumnMetaData.Rep.LONG, expected, Calendar.getInstance());

assertEquals(expected, bind(unit, null, value));
assertEquals(expected, bind(unit, "UTC", value));
assertEquals(expected, bind(unit, NEW_YORK, value));
}
}

@ParameterizedTest
@MethodSource("units")
public void testBindLocalDateTime(TimeUnit unit, long unitsPerSecond, long fraction) {
TypedValue value = objectValue(LOCAL_DATE_TIME);

assertEquals(EPOCH_SECOND * unitsPerSecond + fraction, bind(unit, null, value));
assertEquals(EPOCH_SECOND * unitsPerSecond + fraction, bind(unit, "UTC", value));
// Wall-clock time in the time zone of the vector
assertEquals(NEW_YORK_EPOCH_SECOND * unitsPerSecond + fraction, bind(unit, NEW_YORK, value));
}

@ParameterizedTest
@MethodSource("units")
public void testBindInstantTypesToVectorWithTimeZone(
TimeUnit unit, long unitsPerSecond, long fraction) {
Instant instant = LOCAL_DATE_TIME.toInstant(ZoneOffset.UTC);
long expected = EPOCH_SECOND * unitsPerSecond + fraction;

for (String timeZone : new String[] {"UTC", NEW_YORK}) {
assertEquals(expected, bind(unit, timeZone, objectValue(instant)));
assertEquals(
expected,
bind(
unit,
timeZone,
objectValue(OffsetDateTime.ofInstant(instant, ZoneOffset.ofHours(5)))));
assertEquals(
expected,
bind(unit, timeZone, objectValue(ZonedDateTime.ofInstant(instant, ZoneId.of(NEW_YORK)))));
}
}

@Test
public void testBindInstantTypesToVectorWithoutTimeZone() {
Instant instant = LOCAL_DATE_TIME.toInstant(ZoneOffset.UTC);
Object[] values = {
instant, instant.atOffset(ZoneOffset.UTC), instant.atZone(ZoneId.of(NEW_YORK))
};
for (Object value : values) {
assertThrows(
UnsupportedOperationException.class,
() -> bind(TimeUnit.MICROSECOND, null, objectValue(value)));
}
}

@Test
public void testBindValueThatDoesNotFitInVectorUnit() {
TypedValue value = objectValue(LocalDateTime.parse("2300-01-01T00:00:00"));

assertEquals(10_413_792_000L, bind(TimeUnit.SECOND, null, value));
assertThrows(ArithmeticException.class, () -> bind(TimeUnit.NANOSECOND, null, value));
}

@Test
public void testBindUnsupportedValue() {
assertThrows(
ClassCastException.class,
() ->
bind(
TimeUnit.MICROSECOND,
null,
TypedValue.ofLocal(ColumnMetaData.Rep.STRING, "2024-03-15 12:34:56")));
}
}
Loading