diff --git a/backend/data.go b/backend/data.go index 5712115ac..bc005f141 100644 --- a/backend/data.go +++ b/backend/data.go @@ -110,6 +110,21 @@ type DataQuery struct { JSON json.RawMessage } +func BatchDataQueriesByTimeRange(queries []DataQuery) [][]DataQuery { + timeToBatch := make(map[TimeRange][]DataQuery) + + for _, query := range queries { + key := TimeRange{From: query.TimeRange.From.UTC(), To: query.TimeRange.To.UTC()} + timeToBatch[key] = append(timeToBatch[key], query) + } + + finalBatches := [][]DataQuery{} + for _, batch := range timeToBatch { + finalBatches = append(finalBatches, batch) + } + return finalBatches +} + // QueryDataResponse contains the results from a QueryDataRequest. // It is the return type of a QueryData call. type QueryDataResponse struct { diff --git a/backend/data_test.go b/backend/data_test.go index 140b26c19..9882f70a5 100644 --- a/backend/data_test.go +++ b/backend/data_test.go @@ -3,6 +3,7 @@ package backend import ( "strings" "testing" + "time" "github.com/stretchr/testify/require" ) @@ -103,3 +104,40 @@ func TestQueryDataRequest(t *testing.T) { }) }) } + +func TestBatchDataQueriesByTimeRange(t *testing.T) { + start := time.Date(2024, time.November, 29, 0, 42, 34, 0, time.UTC) + FiveMin := time.Date(2024, time.November, 29, 0, 47, 34, 0, time.UTC) + TenMin := time.Date(2024, time.November, 29, 0, 52, 34, 0, time.UTC) + loc := time.FixedZone("UTC+1", 1*60*60) + FiveMinDifferentZone := time.Date(2024, time.November, 29, 1, 47, 34, 0, loc) + testQueries := []DataQuery{ + { + RefID: "A", + TimeRange: TimeRange{From: start, To: FiveMin}, + }, + { + RefID: "B", + TimeRange: TimeRange{From: start, To: TenMin}, + }, + { + RefID: "C", + TimeRange: TimeRange{From: start, To: FiveMinDifferentZone}, + }, + } + result := BatchDataQueriesByTimeRange(testQueries) + require.Equal(t, 2, len(result)) + var FiveMinQueries = result[0] + var TenMinQueries = result[1] + if len(result[0]) == 1 { + TenMinQueries = result[0] + FiveMinQueries = result[1] + } + + require.Equal(t, 2, len(FiveMinQueries)) + require.Equal(t, "A", FiveMinQueries[0].RefID) + require.Equal(t, "C", FiveMinQueries[1].RefID) + + require.Equal(t, 1, len(TenMinQueries)) + require.Equal(t, "B", TenMinQueries[0].RefID) +}