Skip to content

Commit

Permalink
Fixed timestamp creation
Browse files Browse the repository at this point in the history
  • Loading branch information
alex268 committed Dec 21, 2024
1 parent c50dde5 commit b3f3df6
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
10 changes: 7 additions & 3 deletions table/src/main/java/tech/ydb/table/values/PrimitiveValue.java
Original file line number Diff line number Diff line change
Expand Up @@ -291,14 +291,18 @@ public static PrimitiveValue newDatetime(LocalDateTime value) {

public static PrimitiveValue newTimestamp(long microsSinceEpoch) {
if (microsSinceEpoch < 0) {
throw new IllegalArgumentException("negative microsSinceEpoch: " + microsSinceEpoch);
throw new IllegalArgumentException("Negative microsSinceEpoch: " + microsSinceEpoch);
}
return new InstantValue(PrimitiveType.Timestamp, microsSinceEpoch);
}

public static PrimitiveValue newTimestamp(Instant value) {
long micros = TimeUnit.SECONDS.toMicros(value.getEpochSecond()) +
TimeUnit.NANOSECONDS.toMicros(value.getNano());
long seconds = value.getEpochSecond();
if (seconds < 0) {
throw new IllegalArgumentException("Instant before epoch: " + value);
}
int nanos = value.getNano();
long micros = seconds * 1000000L + nanos / 1000;
return new InstantValue(PrimitiveType.Timestamp, micros);
}

Expand Down
12 changes: 12 additions & 0 deletions table/src/test/java/tech/ydb/table/types/PrimitiveTypeTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ public class PrimitiveTypeTest {
@Test
public void timestampTest() {
PrimitiveValue min = PrimitiveValue.newTimestamp(Instant.EPOCH);
Assert.assertEquals(min, PrimitiveValue.newTimestamp(0));
Value minValue = min.toPb();

Assert.assertEquals(0, minValue.getUint32Value());
Expand All @@ -27,6 +28,7 @@ public void timestampTest() {
Assert.assertEquals(0, minValue.getHigh128());

PrimitiveValue max = PrimitiveValue.newTimestamp(Instant.parse("2105-12-31T23:59:59.999999Z"));
Assert.assertEquals(max, PrimitiveValue.newTimestamp(4291747199999999l));
Value maxValue = max.toPb();

Assert.assertEquals(0, maxValue.getUint32Value());
Expand All @@ -35,5 +37,15 @@ public void timestampTest() {
Assert.assertEquals(0, maxValue.getInt64Value());
Assert.assertEquals(0, maxValue.getLow128());
Assert.assertEquals(0, maxValue.getHigh128());

IllegalArgumentException err1 = Assert.assertThrows(
IllegalArgumentException.class, () -> PrimitiveValue.newTimestamp(-1)
);
Assert.assertEquals("Negative microsSinceEpoch: -1", err1.getMessage());

IllegalArgumentException err2 = Assert.assertThrows(
IllegalArgumentException.class, () -> PrimitiveValue.newTimestamp(Instant.EPOCH.minusNanos(1))
);
Assert.assertEquals("Instant before epoch: 1969-12-31T23:59:59.999999999Z", err2.getMessage());
}
}

0 comments on commit b3f3df6

Please sign in to comment.