| 1 |
<?php |
| 2 |
|
| 3 |
namespace Mgleis\DiskUsageInsights\Domain\Collect; |
| 4 |
|
| 5 |
use Mgleis\DiskUsageInsights\Domain\Jobs\BaseJob; |
| 6 |
use Mgleis\DiskUsageInsights\Domain\Jobs\PhaseCoordinatorJob; |
| 7 |
|
| 8 |
class DetermineDirRecursiveCountJob extends BaseJob { |
| 9 |
|
| 10 |
public function work() { |
| 11 |
$this->log(self::class); |
| 12 |
|
| 13 |
$db = $this->queue->db; |
| 14 |
$stmt = $db->prepare(" |
| 15 |
WITH RECURSIVE directory_counts AS ( |
| 16 |
-- Base case: Start with all directories |
| 17 |
SELECT |
| 18 |
id AS directory_id, |
| 19 |
id AS current_id, |
| 20 |
CASE WHEN type = 'file' THEN 1 ELSE 0 END AS file_count |
| 21 |
FROM fileentries |
| 22 |
|
| 23 |
UNION ALL |
| 24 |
|
| 25 |
-- Recursive step: Add files and subdirectories |
| 26 |
SELECT |
| 27 |
dc.directory_id, -- The original directory |
| 28 |
fe.id AS current_id, -- The current entry (file or directory) |
| 29 |
CASE WHEN fe.type = 'file' THEN 1 ELSE 0 END AS file_count |
| 30 |
FROM directory_counts dc |
| 31 |
JOIN fileentries fe ON fe.parent_id = dc.current_id |
| 32 |
) |
| 33 |
-- Update the table |
| 34 |
UPDATE fileentries |
| 35 |
SET dir_recursive_count = ( |
| 36 |
SELECT SUM(file_count) |
| 37 |
FROM directory_counts |
| 38 |
WHERE directory_counts.directory_id = fileentries.id |
| 39 |
) |
| 40 |
WHERE type = 'dir'; |
| 41 |
"); |
| 42 |
$stmt->execute(); |
| 43 |
|
| 44 |
if ($this->queue->size() == 0) { |
| 45 |
$this->queue->push((new PhaseCoordinatorJob())->toArray()); |
| 46 |
} |
| 47 |
} |
| 48 |
|
| 49 |
public function toArray() { |
| 50 |
return ['type' => self::class, 'args' => []]; |
| 51 |
} |
| 52 |
|
| 53 |
public function toDescription(): string { |
| 54 |
return 'Calculating recursive dir counts...'; |
| 55 |
} |
| 56 |
|
| 57 |
} |
| 58 |
|