fix: add ServerId index to Server_Stats to speed up per-server stats lookup

Server.php's ReadStats() query (SELECT ... WHERE ServerId=? ORDER BY
TimeStamp DESC LIMIT 1) had no supporting index, forcing a full table
scan on every page load that shows server stats. Add a composite
(ServerId, TimeStamp) index via zm_update-1.39.18.sql (idempotent,
checked against INFORMATION_SCHEMA.STATISTICS) and zm_create.sql.in
for fresh installs. Keep the existing TimeStamp-only index, since
zmstats.pl's prune DELETE filters by TimeStamp alone.

Also query ReadStats() with the server's actual Id() instead of
coercing Id() <= 1 to 0.

Bump version.txt and the redhat spec Version to 1.39.18.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Q7jeoG8ptXRpXxif2JqkD7
This commit is contained in:
Isaac ConnorandClaude Sonnet 5 committed 2026-07-23 14:01:24 -04:00
1 parent b486be523b
commit 06801955a8
5 files changed
+23 -3

No files matched your search

+1
View File
@@ -846,6 +846,7 @@ CREATE TABLE `Server_Stats` (
);
CREATE INDEX `Server_Stats_TimeStamp_idx` ON `Server_Stats` (`TimeStamp`);
CREATE INDEX `Server_Stats_ServerId_idx` ON `Server_Stats` (`ServerId`, `TimeStamp`);
--
-- Table structure for table `Stats`
+19
View File
@@ -0,0 +1,19 @@
--
-- Add a composite index on Server_Stats to speed up the per-server latest-stats
-- lookup (SELECT * FROM Server_Stats WHERE ServerId=? ORDER BY TimeStamp DESC LIMIT 1),
-- which was previously a full table scan.
--
SET @s = (SELECT IF(
(SELECT COUNT(*)
FROM INFORMATION_SCHEMA.STATISTICS
WHERE table_name = 'Server_Stats'
AND table_schema = DATABASE()
AND index_name = 'Server_Stats_ServerId_idx'
) > 0,
"SELECT 'Server_Stats_ServerId_idx already exists on Server_Stats table'",
"ALTER TABLE `Server_Stats` ADD INDEX `Server_Stats_ServerId_idx` (`ServerId`, `TimeStamp`)"
));
PREPARE stmt FROM @s;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
+1 -1
View File
@@ -21,7 +21,7 @@
%global zmtargetdistro %{?rhel:el%{rhel}}%{!?rhel:fc%{fedora}}
Name: zoneminder
Version: 1.39.11
Version: 1.39.18
Release: 1%{?dist}
Summary: A camera monitoring and analysis tool
Group: System Environment/Daemons
+1 -1
View File
@@ -1 +1 @@
1.39.17
1.39.18
+1 -1
View File
@@ -46,7 +46,7 @@ class Server extends ZM_Object {
public function ReadStats() {
#ToDo: Analyze the date of the last entry, because The entry may be out of date and not updated.
$dbStats = dbFetchAll('SELECT * FROM Server_Stats WHERE ServerId=? ORDER BY TimeStamp DESC LIMIT 1',NULL, [$this->Id()>1 ? $this->Id() : 0]);
$dbStats = dbFetchAll('SELECT * FROM Server_Stats WHERE ServerId=? ORDER BY TimeStamp DESC LIMIT 1',NULL, [$this->Id()]);
if (count($dbStats)) {
$this->TimeUpdateStats = $dbStats[0]['TimeStamp'];
$this->CpuLoad = $dbStats[0]['CpuLoad'];