This is an automated email from the ASF dual-hosted git repository.

JackieTien97 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/iotdb.git


The following commit(s) were added to refs/heads/master by this push:
     new c29d58e040a Fix natural-month subtraction in date expressions
c29d58e040a is described below

commit c29d58e040a5ef0c6747d57315169be293b731f1
Author: KARMAN SINGH TALWAR <[email protected]>
AuthorDate: Mon Nov 23 13:18:49 2026 +0530

    Fix natural-month subtraction in date expressions
---
 .../db/queryengine/plan/parser/ASTVisitor.java     |  27 +++--
 .../plan/relational/sql/parser/AstBuilder.java     |  12 +-
 .../iotdb/db/utils/DataNodeDateTimeUtils.java      |  78 +++++++++++--
 .../apache/iotdb/db/utils/DateTimeUtilsTest.java   | 124 +++++++++++++++++++++
 4 files changed, 212 insertions(+), 29 deletions(-)

diff --git 
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/parser/ASTVisitor.java
 
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/parser/ASTVisitor.java
index c0be20613b9..f6739938942 100644
--- 
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/parser/ASTVisitor.java
+++ 
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/parser/ASTVisitor.java
@@ -3678,13 +3678,14 @@ public class ASTVisitor extends 
IoTDBSqlParserBaseVisitor<Statement> {
     time = parseDateTimeFormat(ctx.getChild(0).getText());
     for (int i = 1; i < ctx.getChildCount(); i = i + 2) {
       try {
-        long duration =
-            DataNodeDateTimeUtils.convertDurationStrToLong(
-                time, ctx.getChild(i + 1).getText(), precision, false);
-        time =
-            "+".equals(ctx.getChild(i).getText())
-                ? Math.addExact(time, duration)
-                : Math.subtractExact(time, duration);
+        // apply "- duration" backwards from time, so that natural months are 
counted correctly
+        long offset =
+            DataNodeDateTimeUtils.convertDateExpressionOffset(
+                time,
+                ctx.getChild(i + 1).getText(),
+                precision,
+                "-".equals(ctx.getChild(i).getText()));
+        time = Math.addExact(time, offset);
       } catch (ArithmeticException e) {
         throw new SemanticException(
             String.format(
@@ -3700,13 +3701,11 @@ public class ASTVisitor extends 
IoTDBSqlParserBaseVisitor<Statement> {
     time = parseDateTimeFormat(ctx.getChild(0).getText(), currentTime, zoneId);
     for (int i = 1; i < ctx.getChildCount(); i = i + 2) {
       try {
-        long duration =
-            DataNodeDateTimeUtils.convertDurationStrToLong(
-                time, ctx.getChild(i + 1).getText(), false);
-        time =
-            "+".equals(ctx.getChild(i).getText())
-                ? Math.addExact(time, duration)
-                : Math.subtractExact(time, duration);
+        // apply "- duration" backwards from time, so that natural months are 
counted correctly
+        long offset =
+            DataNodeDateTimeUtils.convertDateExpressionOffset(
+                time, ctx.getChild(i + 1).getText(), 
"-".equals(ctx.getChild(i).getText()));
+        time = Math.addExact(time, offset);
       } catch (ArithmeticException e) {
         throw new SemanticException(
             String.format(
diff --git 
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/sql/parser/AstBuilder.java
 
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/sql/parser/AstBuilder.java
index 7a7e5257da9..19de1ebd886 100644
--- 
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/sql/parser/AstBuilder.java
+++ 
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/sql/parser/AstBuilder.java
@@ -3340,13 +3340,11 @@ public class AstBuilder extends 
RelationalSqlBaseVisitor<Node> {
     time = parseDateTimeFormat(ctx.getChild(0).getText(), currentTime, zoneId);
     for (int i = 1; i < ctx.getChildCount(); i = i + 2) {
       try {
-        long duration =
-            DataNodeDateTimeUtils.convertDurationStrToLong(
-                time, ctx.getChild(i + 1).getText(), false);
-        time =
-            "+".equals(ctx.getChild(i).getText())
-                ? Math.addExact(time, duration)
-                : Math.subtractExact(time, duration);
+        // apply "- duration" backwards from time, so that natural months are 
counted correctly
+        long offset =
+            DataNodeDateTimeUtils.convertDateExpressionOffset(
+                time, ctx.getChild(i + 1).getText(), 
"-".equals(ctx.getChild(i).getText()));
+        time = Math.addExact(time, offset);
       } catch (ArithmeticException e) {
         throw new SemanticException(
             String.format(
diff --git 
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/utils/DataNodeDateTimeUtils.java
 
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/utils/DataNodeDateTimeUtils.java
index 617572d0f86..f39b5bfb3f4 100644
--- 
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/utils/DataNodeDateTimeUtils.java
+++ 
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/utils/DataNodeDateTimeUtils.java
@@ -38,6 +38,7 @@ import org.apache.tsfile.utils.TimeDuration;
 
 import java.time.ZoneId;
 import java.util.Calendar;
+import java.util.concurrent.TimeUnit;
 
 public class DataNodeDateTimeUtils {
   public static Long parseDateTimeExpressionToLong(String dateExpression, 
ZoneId zoneId) {
@@ -60,11 +61,23 @@ public class DataNodeDateTimeUtils {
         parser1.dateExpression(), DateTimeUtils.getTimestampPrecision());
   }
 
-  /** convert duration string to millisecond, microsecond or nanosecond. */
+  /**
+   * convert duration string to millisecond, microsecond or nanosecond.
+   *
+   * <p>A {@code currentTime} of -1 means a context free situation, see {@link
+   * #convertDurationStrToLong(String)}.
+   */
   public static long convertDurationStrToLong(
       long currentTime, long value, String unit, String timestampPrecision) {
+    return convertDurationStrToLong(
+        currentTime, currentTime != -1, value, unit, timestampPrecision);
+  }
+
+  private static long convertDurationStrToLong(
+      long currentTime, boolean anchored, long value, String unit, String 
timestampPrecision) {
     try {
-      return convertDurationStrToLongInternal(currentTime, value, unit, 
timestampPrecision);
+      return convertDurationStrToLongInternal(
+          currentTime, anchored, value, unit, timestampPrecision);
     } catch (ArithmeticException e) {
       throw new SemanticException(
           
DataNodeQueryMessages.EXCEPTION_TIME_DURATION_IS_OUT_OF_RANGE_A56B1A29);
@@ -72,7 +85,7 @@ public class DataNodeDateTimeUtils {
   }
 
   private static long convertDurationStrToLongInternal(
-      long currentTime, long value, String unit, String timestampPrecision) {
+      long currentTime, boolean anchored, long value, String unit, String 
timestampPrecision) {
     DateTimeUtils.DurationUnit durationUnit = 
DateTimeUtils.DurationUnit.valueOf(unit);
     long res = value;
     switch (durationUnit) {
@@ -82,14 +95,19 @@ public class DataNodeDateTimeUtils {
         break;
       case mo:
       case month:
-        if (currentTime == -1) {
+        if (!anchored) {
           res = Math.multiplyExact(value, 30 * 86_400_000L);
         } else {
+          // Calendar works in milliseconds, while currentTime is in 
timestampPrecision units, so
+          // the calendar is anchored at the millisecond that currentTime 
falls in. The offset
+          // below is a whole number of milliseconds, so the sub-millisecond 
part of currentTime
+          // is left untouched by the month step and is carried over to the 
caller's result.
+          long anchorMillis = Math.floorDiv(currentTime, 
ticksPerMillisecond(timestampPrecision));
           Calendar calendar = Calendar.getInstance();
           
calendar.setTimeZone(SessionManager.getInstance().getSessionTimeZone());
-          calendar.setTimeInMillis(currentTime);
+          calendar.setTimeInMillis(anchorMillis);
           calendar.add(Calendar.MONTH, Math.toIntExact(value));
-          res = Math.subtractExact(calendar.getTimeInMillis(), currentTime);
+          res = Math.subtractExact(calendar.getTimeInMillis(), anchorMillis);
         }
         break;
       case w:
@@ -149,6 +167,11 @@ public class DataNodeDateTimeUtils {
     }
   }
 
+  private static long ticksPerMillisecond(String timestampPrecision) {
+    return DateTimeUtils.timestampPrecisionStringToTimeUnit(timestampPrecision)
+        .convert(1, TimeUnit.MILLISECONDS);
+  }
+
   @TestOnly
   public static long convertDurationStrToLongForTest(
       long value, String unit, String timestampPrecision) {
@@ -164,6 +187,44 @@ public class DataNodeDateTimeUtils {
    */
   public static long convertDurationStrToLong(
       long currentTime, String duration, String timestampPrecision, boolean 
convertYearToMonth) {
+    return convertDurationStrToLongInternal(
+        currentTime, currentTime != -1, duration, timestampPrecision, 
convertYearToMonth, false);
+  }
+
+  /**
+   * Offset to add to {@code time} for the {@code time + duration} or {@code 
time - duration} of a
+   * date expression.
+   *
+   * <p>{@code time} is always a real timestamp here, so -1 is an ordinary 
anchor and not the
+   * context free marker that {@link #convertDurationStrToLong(long, String, 
String, boolean)} takes
+   * it for.
+   *
+   * <p>If {@code negative} is true, every unit is applied backwards from 
{@code time} and the
+   * returned offset is negative. That is what {@code time - duration} means 
for natural months: for
+   * 2024-03-15 and 1mo the offset is -29 days (back to 2024-02-15), not -31 
days, which is the
+   * length of the month that follows 2024-03-15.
+   */
+  public static long convertDateExpressionOffset(
+      long time, String duration, String timestampPrecision, boolean negative) 
{
+    return convertDurationStrToLongInternal(
+        time, true, duration, timestampPrecision, false, negative);
+  }
+
+  public static long convertDateExpressionOffset(long time, String duration, 
boolean negative) {
+    return convertDateExpressionOffset(
+        time,
+        duration,
+        CommonDescriptor.getInstance().getConfig().getTimestampPrecision(),
+        negative);
+  }
+
+  private static long convertDurationStrToLongInternal(
+      long currentTime,
+      boolean anchored,
+      String duration,
+      String timestampPrecision,
+      boolean convertYearToMonth,
+      boolean negative) {
     try {
       long total = 0;
       long temp = 0;
@@ -187,8 +248,9 @@ public class DataNodeDateTimeUtils {
               Math.addExact(
                   total,
                   convertDurationStrToLong(
-                      currentTime == -1 ? -1 : Math.addExact(currentTime, 
total),
-                      temp,
+                      anchored ? Math.addExact(currentTime, total) : -1,
+                      anchored,
+                      negative ? -temp : temp,
                       unit,
                       timestampPrecision));
           temp = 0;
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 784585ab799..d196bdecef6 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
@@ -18,17 +18,21 @@
  */
 package org.apache.iotdb.db.utils;
 
+import org.apache.iotdb.commons.conf.CommonDescriptor;
 import org.apache.iotdb.commons.exception.SemanticException;
+import 
org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.LongLiteral;
 import org.apache.iotdb.commons.queryengine.utils.DateTimeUtils;
 import org.apache.iotdb.db.protocol.session.IClientSession;
 import org.apache.iotdb.db.protocol.session.InternalClientSession;
 import org.apache.iotdb.db.protocol.session.SessionManager;
+import org.apache.iotdb.db.queryengine.plan.relational.sql.parser.SqlParser;
 
 import org.apache.tsfile.utils.TimeDuration;
 import org.junit.Assert;
 import org.junit.Ignore;
 import org.junit.Test;
 
+import java.time.Instant;
 import java.time.ZoneId;
 import java.time.ZoneOffset;
 import java.time.ZonedDateTime;
@@ -321,6 +325,126 @@ public class DateTimeUtilsTest {
     }
   }
 
+  /** "- Nmo" in a date expression must go back N calendar months from the 
original time. */
+  @Test
+  public void dateExpressionSubtractNaturalMonthTest() {
+    String[][] cases = {
+      // expression, expected
+      {"2024-03-15T00:00:00+00:00 - 1mo", "2024-02-15T00:00:00Z"},
+      {"2024-02-15T00:00:00+00:00 - 1mo", "2024-01-15T00:00:00Z"},
+      {"2025-03-15T00:00:00+00:00 - 1mo", "2025-02-15T00:00:00Z"},
+      {"2024-03-15T00:00:00+00:00 - 2mo", "2024-01-15T00:00:00Z"},
+      {"2024-01-15T00:00:00+00:00 - 1mo", "2023-12-15T00:00:00Z"},
+      // month end is clamped, the same as for "+ 1mo"
+      {"2024-03-31T00:00:00+00:00 - 1mo", "2024-02-29T00:00:00Z"},
+      {"2025-03-31T00:00:00+00:00 - 1mo", "2025-02-28T00:00:00Z"},
+      {"2024-05-31T00:00:00+00:00 - 1mo", "2024-04-30T00:00:00Z"},
+      // mixed units are applied from left to right (compound durations are 
tree syntax only)
+      {"2024-03-31T00:00:00+00:00 - 1mo1d", "2024-02-28T00:00:00Z", "tree"},
+      {"2024-03-15T00:00:00+00:00 - 1w2d", "2024-03-06T00:00:00Z", "tree"},
+      {"2024-03-31T00:00:00+00:00 - 1mo - 1d", "2024-02-28T00:00:00Z"},
+      // negative timestamp
+      {"1969-03-15T00:00:00+00:00 - 1mo", "1969-02-15T00:00:00Z"},
+      // an intermediate timestamp of -1 is a real anchor, not a missing one
+      {"1970-01-01T00:00:00+00:00 - 1ms - 1mo", "1969-11-30T23:59:59.999Z"},
+      {"1970-01-01T00:00:00+00:00 - 1ms1mo", "1969-11-30T23:59:59.999Z", 
"tree"},
+      {"1970-01-01T00:00:00+00:00 - 1ms + 1mo", "1970-01-31T23:59:59.999Z"},
+      // subtraction is the inverse of addition
+      {"2024-02-15T00:00:00+00:00 + 1mo - 1mo", "2024-02-15T00:00:00Z"},
+      // addition is unchanged
+      {"2024-02-15T00:00:00+00:00 + 1mo", "2024-03-15T00:00:00Z"},
+      {"2024-01-31T00:00:00+00:00 + 1mo", "2024-02-29T00:00:00Z"},
+    };
+    assertDateExpressions("UTC", cases);
+  }
+
+  /** Natural months are counted in the session time zone, keeping the local 
time across DST. */
+  @Test
+  public void dateExpressionSubtractNaturalMonthWithTimeZoneTest() {
+    assertDateExpressions(
+        "America/New_York",
+        new String[][] {
+          {"2024-04-15T12:00:00-04:00 - 1mo", "2024-03-15T16:00:00Z"},
+          {"2024-03-15T12:00:00-04:00 - 1mo", "2024-02-15T17:00:00Z"},
+        });
+    assertDateExpressions(
+        "Asia/Kolkata",
+        new String[][] {{"2024-03-01T00:00:00+05:30 - 1mo", 
"2024-01-31T18:30:00Z"}});
+  }
+
+  /**
+   * Natural months are counted from the same calendar instant at every 
timestamp precision, and the
+   * sub-millisecond part of the timestamp survives the month step.
+   */
+  @Test
+  public void dateExpressionNaturalMonthSubMillisecondPrecisionTest() {
+    String[][] cases = {
+      {"2024-01-16T00:00:00+00:00 - 1mo", "2023-12-16T00:00:00Z"},
+      {"2024-01-16T00:00:00+00:00 + 1mo", "2024-02-16T00:00:00Z"},
+      {"2024-03-31T00:00:00+00:00 - 1mo", "2024-02-29T00:00:00Z"},
+      {"2024-01-31T00:00:00+00:00 + 1mo", "2024-02-29T00:00:00Z"},
+      {"2024-02-15T00:00:00+00:00 + 1mo - 1mo", "2024-02-15T00:00:00Z"},
+      {"2024-01-16T00:00:00.000500+00:00 - 1mo", 
"2023-12-16T00:00:00.000500Z"},
+      {"1969-03-15T00:00:00+00:00 - 1mo", "1969-02-15T00:00:00Z"},
+    };
+    assertDateExpressions("UTC", "us", cases);
+    assertDateExpressions("UTC", "ns", cases);
+    // A pre-1970 timestamp with a sub-millisecond part: the calendar is 
anchored at the
+    // millisecond the timestamp falls in, which is below it. This is ns only 
because
+    // DateTimeUtils.getInstantWithPrecision reads such a literal 999999us too 
high at us
+    // precision, which is a separate problem on master.
+    assertDateExpressions(
+        "UTC",
+        "ns",
+        new String[][] {{"1969-03-15T00:00:00.000500+00:00 - 1mo", 
"1969-02-15T00:00:00.000500Z"}});
+  }
+
+  private void assertDateExpressions(String sessionZone, String[][] cases) {
+    assertDateExpressions(sessionZone, "ms", cases);
+  }
+
+  private void assertDateExpressions(String sessionZone, String precision, 
String[][] cases) {
+    ZoneId zoneId = ZoneId.of(sessionZone);
+    IClientSession session = new 
InternalClientSession("dateExpressionNaturalMonthTest");
+    session.setZoneId(zoneId);
+    String previousPrecision = 
CommonDescriptor.getInstance().getConfig().getTimestampPrecision();
+    
CommonDescriptor.getInstance().getConfig().setTimestampPrecision(precision);
+    DateTimeUtils.initTimestampPrecision();
+    SqlParser tableParser = new SqlParser();
+    try {
+      SessionManager.getInstance().registerSession(session);
+      for (String[] c : cases) {
+        long expected = toPrecision(Instant.parse(c[1]), precision);
+        Assert.assertEquals(
+            precision + " tree: " + c[0],
+            expected,
+            (long) DataNodeDateTimeUtils.parseDateTimeExpressionToLong(c[0], 
zoneId));
+        if (c.length > 2) {
+          continue;
+        }
+        Assert.assertEquals(
+            precision + " table: " + c[0],
+            expected,
+            ((LongLiteral) tableParser.createExpression(c[0], 
zoneId)).getParsedValue());
+      }
+    } finally {
+      SessionManager.getInstance().removeCurrSession();
+      
CommonDescriptor.getInstance().getConfig().setTimestampPrecision(previousPrecision);
+      DateTimeUtils.initTimestampPrecision();
+    }
+  }
+
+  private static long toPrecision(Instant instant, String precision) {
+    switch (precision) {
+      case "us":
+        return instant.getEpochSecond() * 1000_000L + instant.getNano() / 1000;
+      case "ns":
+        return instant.getEpochSecond() * 1000_000_000L + instant.getNano();
+      default:
+        return instant.toEpochMilli();
+    }
+  }
+
   public void testConvertDatetimeStrToLongWithoutMS(
       ZoneOffset zoneOffset, ZoneId zoneId, long res) {
     String[] timeFormatWithoutMs =

Reply via email to