From 546046b6a6fe0f6b4261a738356726d25fdd25e1 Mon Sep 17 00:00:00 2001 From: semihalev Date: Thu, 3 Dec 2026 18:02:34 +0300 Subject: [PATCH] Read and bind every TIMESTAMP the engine stores The engine now stores TIMESTAMP values from year 0000 to 9999, but the JNI layer moved a timestamp as i64 nanoseconds, which only reaches 1677 to 2262. A query that returned a far value failed as a whole, and a far parameter was refused before it reached the engine. I changed the wire format between Rust and Java to seconds (i64) plus nanoseconds (u32), the way java.time.Instant holds a time. It costs four bytes per value and drops a division when decoding; a read of 200k timestamps and a bind-and-query loop measured the same before and after. The engine now decides what it stores, so sub-microsecond digits outside 1680 to 2254 surface as its own type error. The new tests read and bind the far values and the nanosecond edges through the native API and JDBC. The 0.5.1 engine cannot store years outside 1677 to 2262, so the tests that store them skip there; the parameter round trips and the type error run on both engines. --- README.md | 10 +-- jni/src/lib.rs | 17 ++-- .../java/io/stoolap/internal/BulkDecoder.java | 6 +- .../io/stoolap/internal/ParamEncoder.java | 16 +--- .../java/io/stoolap/DriverFeaturesTest.java | 80 ++++++++++++++++++- .../java/io/stoolap/JdbcConformanceTest.java | 77 ++++++++++++++++++ 6 files changed, 171 insertions(+), 35 deletions(-) diff --git a/README.md b/README.md index 911e1cc..b99af3e 100644 --- a/README.md +++ b/README.md @@ -384,7 +384,7 @@ HikariDataSource ds = new HikariDataSource(config); | `VECTOR(n)` | `float[]` (JDBC `getString`: `"[0.1, 0.2]"`) | `float[]` | | `NULL` | `null` | `null` | -A TIMESTAMP holds 1677-09-21 to 2262-04-11 UTC; a value outside that range is refused. `java.sql.Date` and `LocalDate` bind as `yyyy-MM-dd` text and `java.sql.Time` and `LocalTime` as `HH:mm:ss` text, which a TIMESTAMP column reads as UTC; JDBC `getDate` and `getTime` read a TIMESTAMP's UTC date and time, so they round-trip in any JVM time zone. Stoolap has no BLOB type, so a `byte[]` parameter is refused and JDBC `setBytes` throws `SQLFeatureNotSupportedException`. Any other object binds as its `toString()` text. +A TIMESTAMP is read and bound over the whole range an `Instant` holds; the engine decides what it stores. Engines after 0.5.1 store years 0000 to 9999, with digits below a microsecond only from 1680-01-01 to 2254-01-01 (outside, the engine raises a type error, SQLSTATE 22000); the 0.5.1 engine stores 1677-09-21 to 2262-04-11. A `java.sql.Timestamp` before 1582-10-15 prints in the Julian calendar, as `java.sql` defines it, but holds the same instant; read such a value with `getObject(i, Instant.class)` or `LocalDateTime.class` to see its proleptic Gregorian date. `java.sql.Date` and `LocalDate` bind as `yyyy-MM-dd` text and `java.sql.Time` and `LocalTime` as `HH:mm:ss` text, which a TIMESTAMP column reads as UTC; JDBC `getDate` and `getTime` read a TIMESTAMP's UTC date and time, so they round-trip in any JVM time zone. Stoolap has no BLOB type, so a `byte[]` parameter is refused and JDBC `setBytes` throws `SQLFeatureNotSupportedException`. Any other object binds as its `toString()` text. Numeric aggregate results (`SUM`, `AVG`, `MIN`, `MAX` over integer columns) may be returned as `Double` depending on the engine's promotion rules. Use `((Number) value).longValue()` / `.doubleValue()` when reading aggregate output. @@ -441,7 +441,7 @@ type_tag: 2 FLOAT f64 LE (8 bytes) 3 TEXT len:u32 LE + UTF-8 bytes 4 BOOLEAN u8 (0/1) - 5 TIMESTAMP i64 LE (nanoseconds since the epoch) + 5 TIMESTAMP seconds:i64 LE + nanos:u32 LE (since the epoch, UTC) 6 JSON len:u32 LE + UTF-8 bytes 7 VECTOR count:u32 LE + f32 LE each ``` @@ -502,15 +502,15 @@ export STOOLAP_LIB=jni/target/release/libstoolap_jni.dylib mvn test ``` -163 tests total, plus the Rust unit tests (`cd jni && cargo test --release`): +169 tests total, plus the Rust unit tests (`cd jni && cargo test --release`): | Test file | Count | Covers | |---|---|---| | `StoolapDBTest` | 57 | Core API: open, execute, query, prepare, begin, clone, error handling, all SQL features | | `JdbcTest` | 47 | JDBC driver: Connection, Statement, PreparedStatement, ResultSet, metadata, batches | | `PersistenceTest` | 11 | File DB: write → close → reopen → verify (matches Python test_persistence.py) | -| `DriverFeaturesTest` | 21 | Named parameters, cursors, TIMESTAMP/VECTOR parameters, mid-result errors, closed handles, JDBC batches and transactions | -| `JdbcConformanceTest` | 21 | DDL with auto-commit off, `execute()` routing (Turkish locale too), batches, parameter checks, dates in a non-UTC zone, `getObject(Class)`, metadata types, streaming, generated keys, isolation, savepoints, SQLState, `DatabaseMetaData` | +| `DriverFeaturesTest` | 23 | Named parameters, cursors, TIMESTAMP/VECTOR parameters, TIMESTAMP years 0000 to 9999, mid-result errors, closed handles, JDBC batches and transactions | +| `JdbcConformanceTest` | 25 | DDL with auto-commit off, TRUNCATE, `execute()` routing (Turkish locale too), batches, parameter checks, dates in a non-UTC zone, TIMESTAMP years 0000 to 9999, `getObject(Class)`, metadata types, streaming, generated keys, isolation, savepoints, SQLState, `DatabaseMetaData` | | `ConcurrencyTest` | 6 | Close racing use, shared cursors, transactions and JDBC connections, unclosed handles | ### Benchmark diff --git a/jni/src/lib.rs b/jni/src/lib.rs index 2b8379f..d2d2078 100644 --- a/jni/src/lib.rs +++ b/jni/src/lib.rs @@ -267,7 +267,13 @@ impl<'b> Reader<'b> { 2 => Value::Float(f64::from_bits(self.i64()? as u64)), 3 => Value::text(self.str()?), 4 => Value::Boolean(self.u8()? != 0), - 5 => Value::Timestamp(DateTime::::from_timestamp_nanos(self.i64()?)), + 5 => { + let (secs, nanos) = (self.i64()?, self.u32()?); + Value::Timestamp( + DateTime::::from_timestamp(secs, nanos) + .ok_or("TIMESTAMP parameter is out of range")?, + ) + } 6 => Value::json(self.str()?), 7 => { let count = self.u32()? as usize; @@ -538,14 +544,9 @@ fn write_value(val: &Value, buf: &mut Vec) -> R<()> { buf.push(*v as u8); } Value::Timestamp(ts) => { - let nanos = ts.timestamp_nanos_opt().ok_or_else(|| { - Fail::from(format!( - "TIMESTAMP {ts} is outside the range 1677-09-21 00:12:43.145224192 to \ - 2262-04-11 23:47:16.854775807" - )) - })?; buf.push(5); - buf.extend_from_slice(&nanos.to_le_bytes()); + buf.extend_from_slice(&ts.timestamp().to_le_bytes()); + buf.extend_from_slice(&ts.timestamp_subsec_nanos().to_le_bytes()); } Value::Extension(data) => match data.first() { None => buf.push(0), diff --git a/src/main/java/io/stoolap/internal/BulkDecoder.java b/src/main/java/io/stoolap/internal/BulkDecoder.java index 59f644e..4e9fd36 100644 --- a/src/main/java/io/stoolap/internal/BulkDecoder.java +++ b/src/main/java/io/stoolap/internal/BulkDecoder.java @@ -109,11 +109,7 @@ public static Result decode(byte[] buf, int offset) { case 2 -> bb.getDouble(); // FLOAT case 3, 6 -> readUtf8(buf, bb, bb.getInt()); // TEXT, JSON (as String) case 4 -> bb.get() != 0; // BOOLEAN - case 5 -> { // TIMESTAMP - long nanos = bb.getLong(); - yield Instant.ofEpochSecond( - Math.floorDiv(nanos, 1_000_000_000L), Math.floorMod(nanos, 1_000_000_000L)); - } + case 5 -> Instant.ofEpochSecond(bb.getLong(), bb.getInt()); // TIMESTAMP case 7 -> readVector(bb); // VECTOR default -> throw new IllegalArgumentException("Unknown type tag: " + tag); }; diff --git a/src/main/java/io/stoolap/internal/ParamEncoder.java b/src/main/java/io/stoolap/internal/ParamEncoder.java index 376916c..1ecc4e9 100644 --- a/src/main/java/io/stoolap/internal/ParamEncoder.java +++ b/src/main/java/io/stoolap/internal/ParamEncoder.java @@ -92,19 +92,6 @@ public static byte[] encodeBatch(Object[][] batch) { return b.toArray(); } - /** Nanoseconds since the epoch, refusing an instant outside the range a TIMESTAMP holds. */ - static long epochNanos(Instant t) { - try { - return Math.addExact(Math.multiplyExact(t.getEpochSecond(), 1_000_000_000L), t.getNano()); - } catch (ArithmeticException e) { - throw new IllegalArgumentException( - "TIMESTAMP " - + t - + " is outside the range 1677-09-21T00:12:43.145224192Z to" - + " 2262-04-11T23:47:16.854775807Z"); - } - } - /** Mutable growing byte buffer, little-endian. */ private static final class Buf { byte[] data = new byte[256]; @@ -165,7 +152,8 @@ void writeUtf8(String s) { void writeTimestamp(Instant t) { writeByte((byte) 5); - writeLong(epochNanos(t)); + writeLong(t.getEpochSecond()); + writeInt(t.getNano()); } void writePositional(Object[] params) { diff --git a/src/test/java/io/stoolap/DriverFeaturesTest.java b/src/test/java/io/stoolap/DriverFeaturesTest.java index 8d24374..157c6b2 100644 --- a/src/test/java/io/stoolap/DriverFeaturesTest.java +++ b/src/test/java/io/stoolap/DriverFeaturesTest.java @@ -16,6 +16,7 @@ package io.stoolap; import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assumptions.assumeTrue; import io.stoolap.internal.BulkDecoder; import java.sql.BatchUpdateException; @@ -30,6 +31,7 @@ import java.time.LocalDateTime; import java.time.OffsetDateTime; import java.time.ZoneOffset; +import java.util.List; import java.util.Map; import org.junit.jupiter.api.Test; @@ -199,15 +201,87 @@ void timestampParametersBindNatively() throws Exception { } } + /** Instants at the edges of what an engine with years 0000 to 9999 stores. */ + static final List FAR_TIMESTAMPS = + List.of( + Instant.parse("1500-06-15T12:00:00.123456Z"), + Instant.parse("0001-01-01T00:00:00Z"), + Instant.parse("9999-12-31T23:59:59.999999Z"), + Instant.parse("1680-01-01T00:00:00.000000001Z"), + Instant.parse("2253-12-31T23:59:59.999999999Z")); + + /** + * Whether the engine stores years 0000 to 9999 in a table. The 0.5.1 engine keeps 1677-09-21 to + * 2262-04-11 and refuses a value outside with a type error, so tests that store such a value are + * skipped there. + */ + static boolean storesFarTimestamps() throws StoolapException { + try (StoolapDB db = StoolapDB.openInMemory()) { + db.execute("CREATE TABLE probe (ts TIMESTAMP)"); + db.execute("INSERT INTO probe VALUES ('0001-01-01 00:00:00')"); + return true; + } catch (StoolapException e) { + if (!"22000".equals(e.getSQLState())) throw e; + return false; + } + } + + @Test + void farTimestampsBindAndComeBackAsParameters() throws Exception { + try (StoolapDB db = StoolapDB.openInMemory(); + StoolapStmt echo = db.prepare("SELECT $1 AS ts")) { + for (Instant t : FAR_TIMESTAMPS) { + assertEquals(t, db.query("SELECT $1 AS ts", t).rows().get(0)[0], t.toString()); + assertEquals(t, echo.query(t).rows().get(0)[0], t.toString()); + } + } + } + + @Test + void farTimestampsAreStoredAndReadBack() throws Exception { + assumeTrue(storesFarTimestamps(), "this engine stores TIMESTAMP 1677 to 2262 only"); + try (StoolapDB db = StoolapDB.openInMemory()) { + db.execute("CREATE TABLE t (id INTEGER PRIMARY KEY, ts TIMESTAMP)"); + for (int i = 0; i < FAR_TIMESTAMPS.size(); i++) { + db.execute("INSERT INTO t VALUES ($1, $2)", i, FAR_TIMESTAMPS.get(i)); + String text = FAR_TIMESTAMPS.get(i).toString().replace('T', ' ').replace("Z", ""); + db.execute("INSERT INTO t VALUES ($1, '" + text + "')", 100 + i); + } + List rows = db.query("SELECT id, ts FROM t ORDER BY id").rows(); + try (StoolapCursor c = db.cursor("SELECT id, ts FROM t ORDER BY id")) { + for (Object[] row : rows) assertArrayEquals(row, c.next()); + } + for (Object[] row : rows) { + Instant want = FAR_TIMESTAMPS.get((int) ((long) row[0] % 100)); + assertEquals(want, row[1], "id " + row[0]); + assertEquals( + row[0], + db.query("SELECT id FROM t WHERE ts = $1 AND id = $2", want, row[0]).rows().get(0)[0]); + } + } + } + @Test - void timestampOutsideTheStoredRangeIsRefused() throws Exception { + void subMicrosecondDigitsOutsideTheirRangeRaiseTheEngineTypeError() throws Exception { try (StoolapDB db = StoolapDB.openInMemory()) { db.execute("CREATE TABLE t (ts TIMESTAMP)"); StoolapException e = assertThrows( StoolapException.class, - () -> db.execute("INSERT INTO t VALUES ($1)", Instant.parse("2300-01-01T00:00:00Z"))); - assertTrue(e.getMessage().contains("outside the range"), e.getMessage()); + () -> + db.execute( + "INSERT INTO t VALUES ($1)", + Instant.parse("1500-06-15T12:00:00.000000001Z"))); + assertEquals("22000", e.getSQLState()); + assertTrue( + e.getMessage().startsWith("type error: TIMESTAMP 1500-06-15 12:00:00.000000001 UTC "), + e.getMessage()); + if (storesFarTimestamps()) { + assertEquals( + "type error: TIMESTAMP 1500-06-15 12:00:00.000000001 UTC has digits below a" + + " microsecond, which a table stores only from 1680-01-01 to 2254-01-01", + e.getMessage()); + } } } diff --git a/src/test/java/io/stoolap/JdbcConformanceTest.java b/src/test/java/io/stoolap/JdbcConformanceTest.java index f094a38..b37eee1 100644 --- a/src/test/java/io/stoolap/JdbcConformanceTest.java +++ b/src/test/java/io/stoolap/JdbcConformanceTest.java @@ -16,6 +16,7 @@ package io.stoolap; import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assumptions.assumeTrue; import java.math.BigDecimal; import java.math.BigInteger; @@ -286,6 +287,82 @@ void datesAndTimesRoundTripInAnyZone() throws Exception { } } + @Test + void farTimestampsBindAndComeBackAsParameters() throws Exception { + try (Connection c = open(); + PreparedStatement ps = c.prepareStatement("SELECT ? AS ts")) { + for (Instant t : DriverFeaturesTest.FAR_TIMESTAMPS) { + ps.setObject(1, t); + try (ResultSet rs = ps.executeQuery()) { + assertTrue(rs.next()); + assertEquals(t, rs.getObject(1, Instant.class), t.toString()); + assertEquals(t, rs.getTimestamp(1).toInstant(), t.toString()); + } + } + } + } + + @Test + void farTimestampsAreStoredAndReadBackThroughEveryBinding() throws Exception { + assumeTrue( + DriverFeaturesTest.storesFarTimestamps(), "this engine stores TIMESTAMP 1677 to 2262 only"); + try (Connection c = open(); + Statement s = c.createStatement()) { + s.execute("CREATE TABLE t (id INTEGER PRIMARY KEY, ts TIMESTAMP)"); + List far = DriverFeaturesTest.FAR_TIMESTAMPS; + try (PreparedStatement ps = c.prepareStatement("INSERT INTO t VALUES (?, ?)")) { + for (int i = 0; i < far.size(); i++) { + Instant t = far.get(i); + Object[] bindings = { + t, + LocalDateTime.ofInstant(t, ZoneOffset.UTC), + OffsetDateTime.ofInstant(t, ZoneOffset.ofHours(3)), + Timestamp.from(t) + }; + for (int b = 0; b < bindings.length; b++) { + ps.setInt(1, i * 10 + b); + if (bindings[b] instanceof Timestamp ts) ps.setTimestamp(2, ts); + else ps.setObject(2, bindings[b]); + ps.executeUpdate(); + } + } + } + int rows = 0; + try (ResultSet rs = s.executeQuery("SELECT id, ts FROM t ORDER BY id")) { + while (rs.next()) { + rows++; + Instant want = far.get(rs.getInt(1) / 10); + String at = "id " + rs.getInt(1); + assertEquals(want, rs.getObject(2, Instant.class), at); + assertEquals( + LocalDateTime.ofInstant(want, ZoneOffset.UTC), + rs.getObject(2, LocalDateTime.class), + at); + assertEquals(want, rs.getObject(2, OffsetDateTime.class).toInstant(), at); + assertEquals(want, rs.getTimestamp(2).toInstant(), at); + assertEquals(Timestamp.from(want), rs.getObject(2), at); + } + } + assertEquals(far.size() * 4, rows); + } + } + + @Test + void subMicrosecondDigitsOutsideTheirRangeRaiseTheEngineTypeError() throws Exception { + try (Connection c = open(); + Statement s = c.createStatement()) { + s.execute("CREATE TABLE t (ts TIMESTAMP)"); + try (PreparedStatement ps = c.prepareStatement("INSERT INTO t VALUES (?)")) { + ps.setObject(1, Instant.parse("1500-06-15T12:00:00.000000001Z")); + SQLException e = assertThrows(SQLException.class, ps::executeUpdate); + assertEquals("22000", e.getSQLState()); + assertTrue( + e.getMessage().startsWith("type error: TIMESTAMP 1500-06-15 12:00:00.000000001 UTC "), + e.getMessage()); + } + } + } + // ---- ResultSet values ---- @Test