diff --git a/integration-test/src/test/java/org/apache/iotdb/db/it/IoTDBDatetimeFormatIT.java b/integration-test/src/test/java/org/apache/iotdb/db/it/IoTDBDatetimeFormatIT.java index 1a7c985635304..bb78e81d4e741 100644 --- a/integration-test/src/test/java/org/apache/iotdb/db/it/IoTDBDatetimeFormatIT.java +++ b/integration-test/src/test/java/org/apache/iotdb/db/it/IoTDBDatetimeFormatIT.java @@ -35,6 +35,7 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; +import java.time.Instant; import static org.junit.Assert.fail; @@ -123,6 +124,23 @@ public void testDatetimeInputFormat() { } } + @Test + public void testDatetimeLiteralsInDstZone() throws SQLException { + try (Connection connection = EnvFactory.getEnv().getConnection(); + Statement statement = connection.createStatement()) { + connection.setClientInfo("time_zone", "America/New_York"); + statement.execute( + "INSERT INTO root.dst.d1(time, s1) VALUES (2026-01-01T12:00:00, 1), (2026-07-01T12:00:00, 2)"); + try (ResultSet rows = statement.executeQuery("SELECT s1 FROM root.dst.d1 ORDER BY TIME")) { + Assert.assertTrue(rows.next()); + Assert.assertEquals(Instant.parse("2026-01-01T17:00:00Z").toEpochMilli(), rows.getLong(1)); + Assert.assertTrue(rows.next()); + Assert.assertEquals(Instant.parse("2026-07-01T16:00:00Z").toEpochMilli(), rows.getLong(1)); + Assert.assertFalse(rows.next()); + } + } + } + @Test public void testBigDateTime() { try (Connection connection = EnvFactory.getEnv().getConnection(); diff --git a/integration-test/src/test/java/org/apache/iotdb/relational/it/query/old/IoTDBDatetimeFormatTableIT.java b/integration-test/src/test/java/org/apache/iotdb/relational/it/query/old/IoTDBDatetimeFormatTableIT.java index 08e9ccc8635ad..f9fd3f80c0100 100644 --- a/integration-test/src/test/java/org/apache/iotdb/relational/it/query/old/IoTDBDatetimeFormatTableIT.java +++ b/integration-test/src/test/java/org/apache/iotdb/relational/it/query/old/IoTDBDatetimeFormatTableIT.java @@ -36,7 +36,9 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; +import java.time.Instant; +import static org.apache.iotdb.db.it.utils.TestUtils.tableAssertTestFail; import static org.junit.Assert.fail; @RunWith(IoTDBTestRunner.class) @@ -127,6 +129,39 @@ public void testDatetimeInputFormat() { } } + @Test + public void testDatetimeLiteralsAndCastInDstZone() throws SQLException { + try (Connection connection = EnvFactory.getEnv().getConnection(BaseEnv.TABLE_SQL_DIALECT); + Statement statement = connection.createStatement()) { + connection.setClientInfo("time_zone", "America/New_York"); + statement.execute("USE " + DATABASE_NAME); + statement.execute("CREATE TABLE dst (local_time STRING FIELD)"); + statement.execute( + "INSERT INTO dst(time, local_time) VALUES" + + " (2026-01-01T12:00:00, '2026-01-01T12:00:00')," + + " (2026-07-01T12:00:00, '2026-07-01T12:00:00')"); + try (ResultSet rows = + statement.executeQuery( + "SELECT time, CAST(local_time AS TIMESTAMP) FROM dst ORDER BY time")) { + for (String instant : new String[] {"2026-01-01T17:00:00Z", "2026-07-01T16:00:00Z"}) { + Assert.assertTrue(rows.next()); + long expected = Instant.parse(instant).toEpochMilli(); + Assert.assertEquals(expected, rows.getLong(1)); + Assert.assertEquals(expected, rows.getLong(2)); + } + Assert.assertFalse(rows.next()); + } + } + } + + @Test + public void testCastRejectsTrailingTextAfterOffset() { + tableAssertTestFail( + "SELECT CAST('2026-12-04T03:33:17.083Zjunk' AS TIMESTAMP)", + "Cannot cast 2026-12-04T03:33:17.083Zjunk to TIMESTAMP type", + DATABASE_NAME); + } + @Test public void testBigDateTime() { diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/utils/DateTimeUtilsTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/utils/DateTimeUtilsTest.java index d196bdecef6b4..fdac6cf6e2960 100644 --- a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/utils/DateTimeUtilsTest.java +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/utils/DateTimeUtilsTest.java @@ -33,9 +33,9 @@ import org.junit.Test; import java.time.Instant; +import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZoneOffset; -import java.time.ZonedDateTime; import java.util.TimeZone; import static org.junit.Assert.assertEquals; @@ -53,13 +53,9 @@ public class DateTimeUtilsTest { /** Test convertDatetimeStrToLong() method with different time precision. */ @Test public void convertDatetimeStrToLongTest1() { - zoneOffset = ZonedDateTime.now().getOffset(); zoneId = ZoneId.systemDefault(); - if (zoneOffset.toString().equals("Z")) { - delta = 8 * 3600000; - } else { - delta = (8 - Long.parseLong(zoneOffset.toString().split(":")[0])) * 3600000; - } + zoneOffset = zoneId.getRules().getOffset(LocalDateTime.of(2019, 1, 2, 15, 13, 27)); + delta = (ZoneOffset.ofHours(8).getTotalSeconds() - zoneOffset.getTotalSeconds()) * 1000L; testConvertDatetimeStrToLongWithoutMS(zoneOffset, zoneId, timestamp - 689 + delta); testConvertDatetimeStrToLongWithMS(zoneOffset, zoneId, timestamp + delta); testConvertDatetimeStrToLongWithMS2(zoneOffset, zoneId, timestamp - 9 + delta); @@ -93,11 +89,23 @@ public void convertDatetimeStrToLongTest4() { fail(); } catch (Exception e) { assertEquals( - "Text '1999-02-29T00:00:00.000+00:00' could not be parsed: Invalid date 'February 29' as '1999' is not a leap year", + "Text '1999-02-29T00:00:00.000' could not be parsed: Invalid date 'February 29' as '1999' is not a leap year", e.getMessage()); } } + @Test + public void testExplicitTimestampOffsets() { + assertEquals( + 0L, + DateTimeUtils.convertDatetimeStrToLong( + "1970-01-01T00:00:00z", ZoneOffset.ofHours(8), "ms")); + assertEquals( + 0L, + DateTimeUtils.convertDatetimeStrToLong( + "1970-01-01T08:00:15+08:00:15", ZoneOffset.UTC, "ms")); + } + /** Test time precision is ms. */ @Test public void convertDurationStrToLongTest1() { @@ -224,6 +232,12 @@ public void getInstantWithPrecisionTest() { Assert.assertThrows( ArithmeticException.class, () -> DateTimeUtils.getInstantWithPrecision("294247-01-10T04:00:54.775808+00:00", "us")); + assertEquals( + Long.MIN_VALUE, + DateTimeUtils.getInstantWithPrecision("1677-09-21T00:12:43.145224192Z", "ns")); + Assert.assertThrows( + ArithmeticException.class, + () -> DateTimeUtils.getInstantWithPrecision("1677-09-21T00:12:43.145224191Z", "ns")); } @Test diff --git a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/utils/DateTimeUtils.java b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/utils/DateTimeUtils.java index 5102738df70d9..ca273f5c8ea29 100644 --- a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/utils/DateTimeUtils.java +++ b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/utils/DateTimeUtils.java @@ -539,6 +539,28 @@ public static void initTimestampPrecision() { .toFormatter() .withResolverStyle(ResolverStyle.STRICT); + private static final DateTimeFormatter DASHED_TIMESTAMP = + timestampParser(ISO_LOCAL_DATE_WIDTH_1_2); + private static final DateTimeFormatter ISO_TIMESTAMP = + timestampParser(DateTimeFormatter.ISO_LOCAL_DATE); + private static final DateTimeFormatter SLASHED_TIMESTAMP = + timestampParser(ISO_LOCAL_DATE_WITH_SLASH); + private static final DateTimeFormatter DOTTED_TIMESTAMP = + timestampParser(ISO_LOCAL_DATE_WITH_DOT); + + private static DateTimeFormatter timestampParser(DateTimeFormatter date) { + return new DateTimeFormatterBuilder() + .parseCaseInsensitive() + .append(date) + .appendLiteral('T') + .append(ISO_LOCAL_TIME_WITH_NS) + .optionalStart() + .appendOffsetId() + .optionalEnd() + .toFormatter() + .withResolverStyle(ResolverStyle.STRICT); + } + public static long convertTimestampOrDatetimeStrToLongWithDefaultZone(String timeStr) { try { return Long.parseLong(timeStr); @@ -549,38 +571,58 @@ public static long convertTimestampOrDatetimeStrToLongWithDefaultZone(String tim public static long convertDatetimeStrToLong(String str, ZoneId zoneId) { return convertDatetimeStrToLong( - str, - toZoneOffset(zoneId), - 0, - CommonDescriptor.getInstance().getConfig().getTimestampPrecision()); + str, zoneId, CommonDescriptor.getInstance().getConfig().getTimestampPrecision()); } public static long convertDatetimeStrToLong( String str, ZoneId zoneId, String timestampPrecision) { - return convertDatetimeStrToLong(str, toZoneOffset(zoneId), 0, timestampPrecision); + if (str.contains("[") || str.contains("]")) { + throw new DateTimeException( + String.format(QueryMessages.DATETIME_TIME_REGION_NOT_SUPPORTED, str)); + } + if (str.length() == 10) { + str += "T00:00:00"; + } + return getInstantWithPrecision(parseDateTime(str, zoneId), timestampPrecision); } public static long getInstantWithPrecision(String str, String timestampPrecision) { - ZonedDateTime zonedDateTime = ZonedDateTime.parse(str, formatter); - Instant instant = zonedDateTime.toInstant(); + return getInstantWithPrecision(parseDateTime(str, null), timestampPrecision); + } + + private static Instant parseDateTime(String str, ZoneId defaultZone) { + DateTimeFormatter parser; + int dot = str.indexOf('.'); + if (str.indexOf('/') >= 0) { + parser = SLASHED_TIMESTAMP; + } else if (dot >= 0 && dot < str.indexOf(':')) { + parser = DOTTED_TIMESTAMP; + } else { + // The space-separated ISO form also supports signed years. + parser = str.indexOf(' ') >= 0 ? ISO_TIMESTAMP : DASHED_TIMESTAMP; + } + return parser.withZone(defaultZone).parse(str.replace(' ', 'T'), Instant::from); + } + + private static long getInstantWithPrecision(Instant instant, String timestampPrecision) { if ("us".equals(timestampPrecision) || "microsecond".equals(timestampPrecision)) { - if (instant.getEpochSecond() < 0 && instant.getNano() > 0) { - // Same as Instant#toEpochMilli: multiply (epochSecond + 1) so that the product cannot - // overflow near Long.MIN_VALUE, then subtract that extra second (1_000_000 us). - long millis = Math.multiplyExact(instant.getEpochSecond() + 1, 1000_000L); - long adjustment = instant.getNano() / 1000 - 1_000_000L; - return Math.addExact(millis, adjustment); - } else { - long millis = Math.multiplyExact(instant.getEpochSecond(), 1000_000L); - return Math.addExact(millis, instant.getNano() / 1000); - } + return scaleEpochSecond(instant, 1_000_000L, instant.getNano() / 1000); } else if ("ns".equals(timestampPrecision) || "nanosecond".equals(timestampPrecision)) { - long millis = Math.multiplyExact(instant.getEpochSecond(), 1000_000_000L); - return Math.addExact(millis, instant.getNano()); + return scaleEpochSecond(instant, 1_000_000_000L, instant.getNano()); } return instant.toEpochMilli(); } + private static long scaleEpochSecond(Instant instant, long unitsPerSecond, long fraction) { + long seconds = instant.getEpochSecond(); + if (seconds < 0 && fraction > 0) { + // As in Instant.toEpochMilli(), avoid intermediate overflow near Long.MIN_VALUE. + seconds++; + fraction -= unitsPerSecond; + } + return Math.addExact(Math.multiplyExact(seconds, unitsPerSecond), fraction); + } + /** convert date time string to millisecond, microsecond or nanosecond. */ public static long convertDatetimeStrToLong( String str, ZoneOffset offset, int depth, String timestampPrecision) { @@ -588,19 +630,7 @@ public static long convertDatetimeStrToLong( throw new DateTimeException( String.format(QueryMessages.DATETIME_CONVERT_FAILED, str, offset)); } - if (str.contains("Z")) { - return convertDatetimeStrToLong( - str.substring(0, str.indexOf('Z')) + "+00:00", offset, depth, timestampPrecision); - } else if (str.length() == 10) { - return convertDatetimeStrToLong(str + "T00:00:00", offset, depth, timestampPrecision); - } else if (str.length() - str.lastIndexOf('+') != 6 - && str.length() - str.lastIndexOf('-') != 6) { - return convertDatetimeStrToLong(str + offset, offset, depth + 1, timestampPrecision); - } else if (str.contains("[") || str.contains("]")) { - throw new DateTimeException( - String.format(QueryMessages.DATETIME_TIME_REGION_NOT_SUPPORTED, str)); - } - return getInstantWithPrecision(str, timestampPrecision); + return convertDatetimeStrToLong(str, offset, timestampPrecision); } public static TimeUnit timestampPrecisionStringToTimeUnit(String timestampPrecision) {