From 16c04f6ac22cd3bd940c57bb7cb8d01984e257a2 Mon Sep 17 00:00:00 2001 From: Peace Date: Thu, 17 Oct 2024 00:06:40 +0200 Subject: [PATCH] perf: less recursion for isParentActive using db query --- server/model/monitor.js | 31 ++++++++++++++++++++++++------- 1 file changed, 24 insertions(+), 7 deletions(-) diff --git a/server/model/monitor.js b/server/model/monitor.js index b51056643..593f7436b 100644 --- a/server/model/monitor.js +++ b/server/model/monitor.js @@ -1719,14 +1719,31 @@ class Monitor extends BeanModel { * @returns {Promise} Is the parent monitor active? */ static async isParentActive(monitorID) { - const parent = await Monitor.getParent(monitorID); - - if (parent === null) { - return true; - } + const result = await R.getRow(` + WITH RECURSIVE MonitorHierarchy AS ( + SELECT parent FROM monitor + WHERE id = ? + UNION ALL + SELECT m.parent FROM monitor m + JOIN MonitorHierarchy mh ON m.id = mh.parent + ) + SELECT + CASE + WHEN (SELECT parent FROM monitor WHERE id = ?) IS NULL THEN 1 + ELSE + CASE + WHEN COUNT(m.id) = SUM(m.active) THEN 1 + ELSE 0 + END + END AS all_active + FROM MonitorHierarchy mh + LEFT JOIN monitor m ON mh.parent = m.id; + `, [ + monitorID, + monitorID + ]); - const parentActive = await Monitor.isParentActive(parent.id); - return parent.active && parentActive; + return result.all_active === 1; } /**