diff --git a/server/lib/device/device.getDeviceFeaturesAggregates.js b/server/lib/device/device.getDeviceFeaturesAggregates.js index d5cd468869..7a678f7fc1 100644 --- a/server/lib/device/device.getDeviceFeaturesAggregates.js +++ b/server/lib/device/device.getDeviceFeaturesAggregates.js @@ -24,53 +24,36 @@ const NON_BINARY_QUERY = ` `; const BINARY_QUERY = ` - WITH value_changes AS ( - SELECT - created_at, - value, - LAG(value) OVER (ORDER BY created_at) AS prev_value - FROM - t_device_feature_state - WHERE - device_feature_id = ? - AND created_at > ? - ORDER BY - created_at DESC - ), - grouped_changes AS ( - SELECT - created_at, - value, - CASE - WHEN value != LAG(value) OVER (ORDER BY created_at) THEN created_at - ELSE NULL - END AS change_marker - FROM - value_changes - ORDER BY - created_at DESC - ), - final_grouping AS ( - SELECT - created_at AS start_time, - LEAD(created_at) OVER (ORDER BY created_at) AS end_time, - value - FROM - grouped_changes - WHERE - change_marker IS NOT NULL - ORDER BY - created_at DESC - LIMIT ? - ) - SELECT - value, - start_time AS created_at, - end_time - FROM - final_grouping - ORDER BY - created_at ASC +WITH value_changes AS ( + SELECT + created_at, + value, + LAG(value) OVER (ORDER BY created_at) AS prev_value + FROM + t_device_feature_state + WHERE + device_feature_id = ? + AND created_at > ? +), +state_transitions AS ( + SELECT + created_at, + value, + LEAD(created_at) OVER (ORDER BY created_at) AS end_time + FROM + value_changes + WHERE + prev_value IS NULL OR value != prev_value +) +SELECT + value, + created_at, + end_time +FROM + state_transitions +ORDER BY + created_at ASC +LIMIT ? `; /** diff --git a/server/test/lib/device/device.getDeviceFeaturesAggregates.test.js b/server/test/lib/device/device.getDeviceFeaturesAggregates.test.js index 917167d872..a68fdf9a76 100644 --- a/server/test/lib/device/device.getDeviceFeaturesAggregates.test.js +++ b/server/test/lib/device/device.getDeviceFeaturesAggregates.test.js @@ -244,6 +244,14 @@ describe('Device.getDeviceFeaturesAggregates binary feature', function Describe( expect(values).to.have.lengthOf(300); expect(device).to.have.property('name'); expect(deviceFeature).to.have.property('name'); + + values.forEach((value) => { + expect(value).to.have.property('value'); + // Check that both created_at and end_time are present + expect(value).to.have.property('created_at'); + expect(value).to.have.property('end_time'); + }); + // Check that the values are state changes for (let i = 1; i < values.length; i += 1) { expect(values[i].value).to.not.equal(values[i - 1].value);