Skip to content

Instantly share code, notes, and snippets.

@null-dev
Last active March 29, 2022 05:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save null-dev/0662d7c6fc322542adca7891234691bd to your computer and use it in GitHub Desktop.
Save null-dev/0662d7c6fc322542adca7891234691bd to your computer and use it in GitHub Desktop.
QuestDB Test
@Test
public void testTimestamp() throws Exception {
TestUtils.assertMemoryLeak(() -> {
try (final PGWireServer ignored = createPGServer(1)) {
try (final Connection connection = getConnection(false, true)) {
connection.setAutoCommit(false);
connection.prepareStatement("create table ts (ts timestamp) timestamp(ts) partition by month").execute();
connection.prepareStatement("insert into ts (ts) values ('2021-09-27T16:45:03.202345Z')").execute();
connection.commit();
connection.setAutoCommit(true);
Timestamp ts;
try (PreparedStatement statement = connection.prepareStatement("ts")) {
try (ResultSet rs = statement.executeQuery()) {
assertTrue(rs.next());
ts = rs.getTimestamp("ts");
}
}
assertEquals("2021-09-27 16:45:03.202345", ts.toString());
assertEquals(1632761103202L, ts.getTime());
assertEquals(202345000, ts.getNanos());
sink.clear();
try (PreparedStatement ps = connection.prepareStatement("INSERT INTO ts VALUES (?);")) {
// insert the timestamp as we got it from a select ^ ^
ps.setTimestamp(1, ts);
ps.execute();
// insert a timestamp spelling out its construction
assertEquals(1632761103202L, ts.getTime());
assertEquals(202345000, ts.getNanos());
Timestamp newTs = new Timestamp(ts.getTime());
newTs.setNanos(0);
ps.setTimestamp(1, newTs);
ps.execute();
// a more convoluted approach
long questdbTs = TimestampFormatUtils.parseTimestamp("2021-09-27T16:45:03.202345Z");
assertEquals(1632761103202345L, questdbTs);
long time = questdbTs / 1000;
assertEquals(1632761103202L, time);
int nanos = (int)(questdbTs - (int)(questdbTs / 1e6) * 1e6) * 1000;
assertEquals(202345000, nanos);
Timestamp anotherTs = new Timestamp(time);
anotherTs.setNanos(nanos);
ps.setTimestamp(1, anotherTs);
ps.execute();
}
try (PreparedStatement statement = connection.prepareStatement("ts")) {
sink.clear();
try (ResultSet rs = statement.executeQuery()) {
assertResultSet(
"ts[TIMESTAMP]\n" +
"2021-09-27 16:45:03.0\n" +
"2021-09-27 16:45:03.202345\n" +
"2021-09-27 16:45:03.202345\n" +
"2021-09-27 16:45:03.202345\n",
sink,
rs
);
}
}
connection.prepareStatement("drop table ts").execute();
}
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment