Skip to content

Commit 424abb6

Browse files
author
Volodymyr Panivko
committed
fix: optimize admin reports SQL queries for performance
Replace YEAR(time) with date range in userStats() to allow index usage, switch history table from MyISAM to InnoDB for row-level locking, add composite index on (time, action), fix GROUP BY to use PK.
1 parent f5802e3 commit 424abb6

2 files changed

Lines changed: 11 additions & 5 deletions

File tree

docker-data/mysql/create-database.sql

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -68,8 +68,9 @@ CREATE TABLE `history` (
6868
KEY `userId` (`userId`),
6969
KEY `action` (`action`),
7070
KEY `standId` (`standId`),
71-
KEY `pairActionId` (`pairActionId`)
72-
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
71+
KEY `pairActionId` (`pairActionId`),
72+
KEY `idx_time_action` (`time`, `action`)
73+
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
7374

7475

7576
-- THIS TABLE IS MISSED IN CODE, DO WE NEED IT?

src/Repository/HistoryRepository.php

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,9 @@ public function dailyStats(): array
6262

6363
public function userStats(int $year): array
6464
{
65+
$yearStart = sprintf('%d-01-01 00:00:00', $year);
66+
$yearEnd = sprintf('%d-01-01 00:00:00', $year + 1);
67+
6568
$result = $this->db->query(
6669
"SELECT
6770
users.userId,
@@ -72,11 +75,13 @@ public function userStats(int $year): array
7275
FROM users
7376
LEFT JOIN history ON users.userId=history.userId
7477
WHERE history.userId IS NOT NULL
75-
AND YEAR(time) = :year
76-
GROUP BY username
78+
AND time >= :yearStart
79+
AND time < :yearEnd
80+
GROUP BY users.userId, users.userName
7781
ORDER BY totalActionCount DESC",
7882
[
79-
'year' => $year,
83+
'yearStart' => $yearStart,
84+
'yearEnd' => $yearEnd,
8085
'rentActionSum' => Action::RENT->value,
8186
'returnActionSum' => Action::RETURN->value,
8287
]

0 commit comments

Comments
 (0)