Skip to content

Commit

Permalink
Chart: Fix binary query, return first value (#2153)
Browse files Browse the repository at this point in the history
  • Loading branch information
Pierre-Gilles authored Nov 1, 2024
1 parent df91742 commit 38a2613
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 47 deletions.
77 changes: 30 additions & 47 deletions server/lib/device/device.getDeviceFeaturesAggregates.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 ?
`;

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down

0 comments on commit 38a2613

Please sign in to comment.