Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,13 @@ public Object execute(final Object self, final Identifiable currentRecord, final
// reach. intervalMs is positive here (guarded above), so floorDiv differs from '/' only on negative inputs.
final long bucketStart = Math.floorDiv(timestampMs, intervalMs) * intervalMs;

return new Date(bucketStart);
// Issue #7610: expose the bucket as a LocalDateTime, not a java.util.Date. This is the same
// representation AggregateFromTimeSeriesStep's own bucket pushdown already uses for a single
// grouping key (issue #4385), and it keeps the value out of JSONObject's ambiguous
// Date-vs-DATE-column dispatch - a java.util.Date here silently lost its time of day over HTTP
// query results, because the JSON serializer cannot tell a computed instant from a genuine DATE
// column by Java class alone.
return LocalDateTime.ofInstant(Instant.ofEpochMilli(bucketStart), ZoneOffset.UTC);
}

public static long parseInterval(final String interval) {
Expand Down
21 changes: 21 additions & 0 deletions engine/src/main/java/com/arcadedb/serializer/JsonSerializer.java
Original file line number Diff line number Diff line change
Expand Up @@ -603,8 +603,29 @@ else if (elementType != t)
* </ol>
* Returns {@code value} unchanged when it is not a temporal we can handle, so {@link
* JSONObject#put(String, Object)}'s existing temporal branch covers any leftover cases.
* <p>
* Issue #7610: a {@code java.util.Date} backs both a genuine DATE column and any computed or
* aggregate expression that yields an instant (e.g. {@code ts.timeBucket()}), or a DATETIME column
* configured with {@code arcadedb.dateTimeImplementation} = java.util.Date. {@link
* JSONObject#put(String, Object)} dispatches on Java class alone and can't tell those apart, so it
* would format every one of them with the schema's date-only pattern and silently drop the time of
* day. Only a value actually backed by a DATE-typed property is left for that dispatch (unchanged
* below); everything else is formatted here with the full date-time pattern, anchored to UTC to
* match {@code Type#convertToDate}'s own UTC-anchored LocalDateTime-to-Date conversion (the write
* side of the same round trip), and precision-expanded the same way the {@code Temporal} branch
* below is, so a {@code Date} with a non-zero millisecond component doesn't get silently truncated
* by a seconds-only schema pattern. {@code Date} can never hold finer than millisecond precision, so
* the data-driven fallback below caps at {@link ChronoUnit#MILLIS}, not the nanos field.
*/
private static Object formatTemporalForPrecision(final Object value, final Type propertyType, final String baseDateTimeFormat) {
if (value instanceof Date date) {
if (propertyType == Type.DATE)
return value;
final ChronoUnit precision = propertyType != null
? DateUtils.getPrecisionFromType(propertyType)
: DateUtils.getPrecision((int) (Math.floorMod(date.getTime(), 1000L) * 1_000_000L));
return DateUtils.format(date, expandFormatToPrecision(baseDateTimeFormat, precision), "UTC");
}
if (!(value instanceof Temporal))
return value;
final ChronoUnit precision;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@
import com.arcadedb.function.sql.time.SQLFunctionTimeBucket;
import org.junit.jupiter.api.Test;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Date;

import static org.assertj.core.api.Assertions.assertThat;
Expand All @@ -35,70 +37,78 @@ class SQLFunctionTimeBucketTest {

private final SQLFunctionTimeBucket fn = new SQLFunctionTimeBucket();

/**
* Issue #7610: the function returns a UTC-anchored LocalDateTime, not a java.util.Date (see
* SQLFunctionTimeBucket for why), so tests compare bucket boundaries as epoch millis.
*/
private static long bucketMs(final Object result) {
return ((LocalDateTime) result).toInstant(ZoneOffset.UTC).toEpochMilli();
}

@Test
void hourBucket() {
// 2026-02-20T10:35:00Z -> should truncate to 2026-02-20T10:00:00Z
final long ts = 1771580100000L; // ~2026-02-20T10:35:00Z
final Date result = (Date) fn.execute(null, null, null, new Object[] { "1h", ts }, null);
final Object result = fn.execute(null, null, null, new Object[] { "1h", ts }, null);

// Should be truncated to nearest hour
assertThat(result.getTime() % 3600000L).isEqualTo(0L);
assertThat(result.getTime()).isLessThanOrEqualTo(ts);
assertThat(result.getTime()).isGreaterThan(ts - 3600000L);
assertThat(bucketMs(result) % 3600000L).isEqualTo(0L);
assertThat(bucketMs(result)).isLessThanOrEqualTo(ts);
assertThat(bucketMs(result)).isGreaterThan(ts - 3600000L);
}

@Test
void minuteBucket() {
final long ts = 1771580100000L; // some timestamp
final Date result = (Date) fn.execute(null, null, null, new Object[] { "5m", ts }, null);
final Object result = fn.execute(null, null, null, new Object[] { "5m", ts }, null);

// Should be truncated to 5-minute boundary
assertThat(result.getTime() % (5 * 60000L)).isEqualTo(0L);
assertThat(result.getTime()).isLessThanOrEqualTo(ts);
assertThat(bucketMs(result) % (5 * 60000L)).isEqualTo(0L);
assertThat(bucketMs(result)).isLessThanOrEqualTo(ts);
}

@Test
void secondBucket() {
final long ts = 1771580123456L;
final Date result = (Date) fn.execute(null, null, null, new Object[] { "1s", ts }, null);
final Object result = fn.execute(null, null, null, new Object[] { "1s", ts }, null);

assertThat(result.getTime() % 1000L).isEqualTo(0L);
assertThat(result.getTime()).isLessThanOrEqualTo(ts);
assertThat(bucketMs(result) % 1000L).isEqualTo(0L);
assertThat(bucketMs(result)).isLessThanOrEqualTo(ts);
}

@Test
void dayBucket() {
final long ts = 1771580100000L;
final Date result = (Date) fn.execute(null, null, null, new Object[] { "1d", ts }, null);
final Object result = fn.execute(null, null, null, new Object[] { "1d", ts }, null);

assertThat(result.getTime() % 86400000L).isEqualTo(0L);
assertThat(result.getTime()).isLessThanOrEqualTo(ts);
assertThat(bucketMs(result) % 86400000L).isEqualTo(0L);
assertThat(bucketMs(result)).isLessThanOrEqualTo(ts);
}

@Test
void weekBucket() {
final long ts = 1771580100000L;
final Date result = (Date) fn.execute(null, null, null, new Object[] { "1w", ts }, null);
final Object result = fn.execute(null, null, null, new Object[] { "1w", ts }, null);

assertThat(result.getTime() % (7 * 86400000L)).isEqualTo(0L);
assertThat(result.getTime()).isLessThanOrEqualTo(ts);
assertThat(bucketMs(result) % (7 * 86400000L)).isEqualTo(0L);
assertThat(bucketMs(result)).isLessThanOrEqualTo(ts);
}

@Test
void withDateObject() {
final Date input = new Date(1771580100000L);
final Date result = (Date) fn.execute(null, null, null, new Object[] { "1h", input }, null);
final Object result = fn.execute(null, null, null, new Object[] { "1h", input }, null);

assertThat(result.getTime() % 3600000L).isEqualTo(0L);
assertThat(bucketMs(result) % 3600000L).isEqualTo(0L);
}

@Test
void exactBoundary() {
// Timestamp already on an hour boundary
final long ts = 3600000L * 5; // exactly 05:00:00 UTC epoch
final Date result = (Date) fn.execute(null, null, null, new Object[] { "1h", ts }, null);
final Object result = fn.execute(null, null, null, new Object[] { "1h", ts }, null);

assertThat(result.getTime()).isEqualTo(ts);
assertThat(bucketMs(result)).isEqualTo(ts);
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,9 @@
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import static org.assertj.core.api.Assertions.assertThat;

Expand Down Expand Up @@ -245,4 +247,51 @@ void selectTimestampKeepsTimeComponent() {
final String tsAsString = json.get("ts").toString();
assertThat(tsAsString).contains("2026-05-28").contains("06:46:06");
}

/**
* Regression test for issue #7610: {@code SELECT host, ts.timeBucket('1h', ts) AS h, avg(value) FROM
* ... GROUP BY host, h} - two grouping keys - does not qualify for the single-key TS aggregate
* pushdown (#4385), which already exposes the bucket as a {@code LocalDateTime}. It falls back to
* the generic {@code ts.timeBucket()} SQL function, which returned a raw {@code java.util.Date}.
* {@code serializeResult()} formats a {@code java.util.Date} with the schema's DATE-only pattern
* (it cannot tell a genuine DATE column from a computed instant), so every bucket inside one
* calendar day collapsed onto the same string over HTTP/JSON even though the engine grouped the
* rows correctly. Fixed by making {@code ts.timeBucket()} return a {@code LocalDateTime}, like the
* pushdown path already does.
*/
@Test
void timeBucketTwoGroupingKeysKeepsTimeComponent() {
database.command("sql",
"CREATE TIMESERIES TYPE MultiHostMetrics TIMESTAMP ts TAGS (host STRING) FIELDS (value DOUBLE)");

final long baseMs = 1767225600000L; // 2026-01-01T00:00:00Z
database.transaction(() -> {
for (int hour = 0; hour < 5; hour++)
for (final String host : new String[] { "h1", "h2" })
database.command("sql", "INSERT INTO MultiHostMetrics SET ts = " + (baseMs + hour * 3_600_000L)
+ ", host = '" + host + "', value = " + hour + ".0");
});

try (final ResultSet rs = database.query("sql",
"SELECT host, ts.timeBucket('1h', ts) AS h, avg(value) AS v FROM MultiHostMetrics "
+ "GROUP BY host, h ORDER BY host, h")) {
final List<Result> results = new ArrayList<>();
while (rs.hasNext())
results.add(rs.next());

assertThat(results).hasSize(10); // 2 hosts x 5 hourly buckets

// The bucket value must be a temporal, not a raw java.util.Date: matches the single-key
// pushdown path's type (#4385) and keeps it out of JSONObject's ambiguous Date branch.
final Object h = results.get(0).getProperty("h");
assertThat(h).isInstanceOf(LocalDateTime.class);

final JsonSerializer serializer = new JsonSerializer(database);
final Set<String> distinctBuckets = new HashSet<>();
for (final Result row : results)
distinctBuckets.add(serializer.serializeResult(database, row).getString("h"));

assertThat(distinctBuckets).hasSize(5); // one string per hourly bucket, not one per day
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,9 @@
import org.junit.jupiter.api.Test;

import java.time.Duration;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.util.Date;
import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;
Expand Down Expand Up @@ -132,8 +133,10 @@ void timeBucketWithANullArgumentIsNullNotAnNpe() {

@Test
void timeBucketStillTruncatesToTheBucketStart() {
// Issue #7610: the bucket is a UTC-anchored LocalDateTime, not a java.util.Date.
try (final ResultSet rs = database.query("sql", "SELECT ts.timeBucket('1h', 3900000) AS b")) {
assertThat(rs.next().<Date>getProperty("b")).isEqualTo(new Date(3_600_000L));
assertThat(rs.next().<LocalDateTime>getProperty("b"))
.isEqualTo(LocalDateTime.ofEpochSecond(3_600L, 0, ZoneOffset.UTC));
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
import org.junit.jupiter.api.Test;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
Expand Down Expand Up @@ -53,7 +55,8 @@ class Issue6824TimeBucketPreEpochTest extends TestHelper {
private long bucket(final String interval, final long timestampMs) {
try (final ResultSet resultSet = database.query("sql",
"SELECT ts.timeBucket('" + interval + "', " + timestampMs + ") AS b")) {
return resultSet.next().<Date>getProperty("b").getTime();
// Issue #7610: the bucket is a UTC-anchored LocalDateTime, not a java.util.Date.
return resultSet.next().<LocalDateTime>getProperty("b").toInstant(ZoneOffset.UTC).toEpochMilli();
}
}

Expand Down Expand Up @@ -111,11 +114,13 @@ void positiveTimestampsBucketExactlyAsBefore() {
void theTypedPreEpochOverloadsFloorAsWell() {
try (final ResultSet resultSet = database.query("sql", "SELECT ts.timeBucket('1h', ?) AS b",
new Date(-1_800_000L))) {
assertThat(resultSet.next().<Date>getProperty("b").getTime()).isEqualTo(-HOUR_MS);
assertThat(resultSet.next().<LocalDateTime>getProperty("b").toInstant(ZoneOffset.UTC).toEpochMilli())
.isEqualTo(-HOUR_MS);
}
try (final ResultSet resultSet = database.query("sql", "SELECT ts.timeBucket('1h', ?) AS b",
Instant.ofEpochMilli(-1_800_000L))) {
assertThat(resultSet.next().<Date>getProperty("b").getTime()).isEqualTo(-HOUR_MS);
assertThat(resultSet.next().<LocalDateTime>getProperty("b").toInstant(ZoneOffset.UTC).toEpochMilli())
.isEqualTo(-HOUR_MS);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -350,4 +350,65 @@ void datetimeSerializedWithInstantImplementation() throws Exception {
serializer.setDateTimeImplementation(previous);
}
}

/**
* Issue #7610: {@code serializeResult()} formatted every {@code java.util.Date} value with the
* schema's DATE-only pattern, because {@code JSONObject} dispatches on Java class alone and
* {@code java.util.Date} backs both a genuine DATE column and a DATETIME column configured with
* {@code arcadedb.dateTimeImplementation} = java.util.Date - a real, supported configuration, not a
* hypothetical one. A DATETIME column in that configuration lost its time of day over HTTP query
* results before this fix.
*/
@Test
void dateTimeImplementationAsJavaUtilDateKeepsTimeComponent() {
final BinarySerializer serializer = ((DatabaseInternal) database).getSerializer();
final Object previous = serializer.getDateTimeImplementation();
try {
serializer.setDateTimeImplementation(Date.class);

database.transaction(() -> {
final DocumentType type = database.getSchema().createDocumentType("DateTimeAsDateType");
type.createProperty("dt", Type.DATETIME);
// A non-zero millisecond component: Type.DATETIME's declared precision is MILLIS, and a
// java.util.Date can carry exactly that - this must survive, not be truncated by a
// seconds-only schema pattern (issue #7610 code-review follow-up).
database.newDocument("DateTimeAsDateType").set("dt", LocalDateTime.of(2026, 6, 12, 15, 30, 0, 250_000_000)).save();
});

// SELECT FROM (not a column list) keeps the result an element, so serializeResult() resolves
// the property's schema type - the case the fix's DATE-vs-DATETIME distinction depends on.
try (final ResultSet rs = database.query("sql", "SELECT FROM DateTimeAsDateType")) {
assertThat(rs.hasNext()).isTrue();
final Result row = rs.next();
final Object dt = row.getProperty("dt");
assertThat(dt).isInstanceOf(Date.class);

final JSONObject json = new JsonSerializer(database).serializeResult(database, row);
assertThat(json.getString("dt")).isEqualTo("2026-06-12 15:30:00.250");
}
} finally {
serializer.setDateTimeImplementation(previous);
}
}

/**
* Companion to {@link #dateTimeImplementationAsJavaUtilDateKeepsTimeComponent()}: a genuine DATE
* column (default {@code arcadedb.dateImplementation} = java.time.LocalDate) must keep its
* date-only formatting through {@code serializeResult()} - only a {@code java.util.Date} that does
* NOT back a DATE-typed property gained the time component in the fix above.
*/
@Test
void plainDateColumnStaysDateOnlyInSerializeResult() {
database.transaction(() -> {
final DocumentType type = database.getSchema().createDocumentType("PlainDateType");
type.createProperty("d", Type.DATE);
database.newDocument("PlainDateType").set("d", LocalDate.of(2026, 6, 12)).save();
});

try (final ResultSet rs = database.query("sql", "SELECT FROM PlainDateType")) {
assertThat(rs.hasNext()).isTrue();
final JSONObject json = new JsonSerializer(database).serializeResult(database, rs.next());
assertThat(json.getString("d")).isEqualTo("2026-06-12");
}
}
}
Loading