From ec2cebc5dfa2bda5c6b207c7a5d0f51af1dbecad Mon Sep 17 00:00:00 2001 From: Peace Date: Thu, 17 Oct 2024 17:16:08 +0200 Subject: [PATCH] perf: option to only get ids of active children --- server/model/monitor.js | 22 +++++++++++++++++++++- server/server.js | 2 +- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/server/model/monitor.js b/server/model/monitor.js index 893379cbd..0149e11fb 100644 --- a/server/model/monitor.js +++ b/server/model/monitor.js @@ -1701,9 +1701,29 @@ class Monitor extends BeanModel { /** * Gets recursive all children ids * @param {number} monitorID ID of the monitor to get + * @param {boolean} onlyActive Return only monitors which are active (including all ancestors) * @returns {Promise} IDs of all children */ - static async getAllChildrenIDs(monitorID) { + static async getAllChildrenIDs(monitorID, onlyActive = false) { + if (onlyActive) { + // Gets all children monitor ids recursive but only if they and all their ancestors are active + return await R.getCol(` + WITH RECURSIVE MonitorHierarchy(id, active_chain) AS ( + SELECT id, active FROM monitor + WHERE id = ? + UNION ALL + SELECT m.id, m.active * mh.active_chain FROM monitor m + INNER JOIN MonitorHierarchy mh ON m.parent = mh.id + WHERE mh.active_chain = 1 + ) + SELECT id FROM MonitorHierarchy + WHERE id != ? AND active_chain = 1; + `, [ + monitorID, + monitorID + ]); + } + // Gets all children monitor ids recursive return await R.getCol(` WITH RECURSIVE MonitorHierarchy(id) AS ( SELECT id FROM monitor WHERE id = ? diff --git a/server/server.js b/server/server.js index 8dba73a1e..ef0fb49af 100644 --- a/server/server.js +++ b/server/server.js @@ -1752,7 +1752,7 @@ async function startMonitor(userID, monitorID) { userID, ]); - const childrenIDs = await Monitor.getAllChildrenIDs(monitorID); + const childrenIDs = await Monitor.getAllChildrenIDs(monitorID, true); const monitorIDs = [ monitorID, ...childrenIDs ]; let monitors = await R.find("monitor", ` id IN (${monitorIDs.map((_) => "?").join(",")})`, monitorIDs);