Fix: corriger les statistiques PostgreSQL (#9659)

Closes #9658

Changes proposed in this pull request:

- Use PostgreSQL `dow` instead of `day` for the day-of-week chart.
- Normalize month repartitions to exactly 12 entries, from January to December.
- Include today in the 30-day chart, anchor the day calculation on the oldest timestamp so integer division is always positive, and return a JSON list.
- Set chart labels and build the average line as an array matching the bar data.

* Fix: corriger les statistiques PostgreSQL

* Remove dead code

---------

Co-authored-by: upskaling <upskaling@users.noreply.github.com>
Co-authored-by: Alexandre Alapetite <alexandre@alapetite.fr>
This commit is contained in:
authored and GitHub committed 2026-11-30 20:35:11 +01:00
1 parent f6954526d4
commit 0abfe20385
4 files changed
+108 -17

No files matched your search

+24 -8
View File
@@ -89,14 +89,16 @@ class FreshRSS_StatsDAO extends Minz_ModelPdo {
$count = $this->initEntryCountArray();
$midnight = mktime(0, 0, 0) ?: 0;
$oldest = $midnight - (self::ENTRY_COUNT_PERIOD * 86400);
$endOfDay = $midnight + 86400;
// Get stats per day for the last 30 days
$sqlDay = $this->sqlFloor("(date - $midnight) / 86400");
// Get stats per day for the last 30 days, including today.
// The reference is the oldest timestamp so that the division is always positive (and thus floors correctly with integer division).
$sqlDay = $this->sqlFloor("(date - $oldest) / 86400");
$sql = <<<SQL
SELECT {$sqlDay} AS day,
COUNT(*) as count
FROM `_entry`
WHERE date >= {$oldest} AND date < {$midnight}
WHERE date >= {$oldest} AND date < {$endOfDay}
GROUP BY day
ORDER BY day ASC
SQL;
@@ -108,7 +110,8 @@ class FreshRSS_StatsDAO extends Minz_ModelPdo {
foreach ($res as $value) {
$count[(int)($value['day'])] = (int)($value['count']);
}
return $count;
// Return a list so that JSON encoding produces an array and not an object.
return array_values($count);
}
/**
@@ -116,7 +119,7 @@ class FreshRSS_StatsDAO extends Minz_ModelPdo {
* @return array<int,int>
*/
protected function initEntryCountArray(): array {
return $this->initStatsArray(-self::ENTRY_COUNT_PERIOD, -1);
return $this->initStatsArray(0, self::ENTRY_COUNT_PERIOD);
}
/**
@@ -141,9 +144,22 @@ class FreshRSS_StatsDAO extends Minz_ModelPdo {
*/
public function calculateEntryRepartitionPerFeedPerMonth(?int $feed = null): array {
$monthRepartition = $this->calculateEntryRepartitionPerFeedPerPeriod('%m', $feed);
// cut out the 0th month (Jan=1, Dec=12)
\array_splice($monthRepartition, 0, 1);
return $monthRepartition;
return $this->normalizeMonthRepartition($monthRepartition);
}
/**
* Normalize a month repartition so that it always contains 12 entries indexed from 0 (January) to 11 (December).
* @param array<int,int> $repartition
* @return array<int,int>
*/
protected function normalizeMonthRepartition(array $repartition): array {
$months = array_fill(0, 12, 0);
foreach ($repartition as $month => $count) {
if ($month >= 1 && $month <= 12) {
$months[$month - 1] = $count;
}
}
return $months;
}
/**
+6 -3
View File
@@ -34,7 +34,9 @@ class FreshRSS_StatsDAOPGSQL extends FreshRSS_StatsDAO {
*/
#[\Override]
public function calculateEntryRepartitionPerFeedPerDayOfWeek(?int $feed = null): array {
return $this->calculateEntryRepartitionPerFeedPerPeriod('day', $feed);
// PostgreSQL uses `dow` (0 = Sunday .. 6 = Saturday) for the day of week,
// whereas `day` would extract the day of the month.
return $this->calculateEntryRepartitionPerFeedPerPeriod('dow', $feed);
}
/**
@@ -43,7 +45,8 @@ class FreshRSS_StatsDAOPGSQL extends FreshRSS_StatsDAO {
*/
#[\Override]
public function calculateEntryRepartitionPerFeedPerMonth(?int $feed = null): array {
return $this->calculateEntryRepartitionPerFeedPerPeriod('month', $feed);
$monthRepartition = $this->calculateEntryRepartitionPerFeedPerPeriod('month', $feed);
return $this->normalizeMonthRepartition($monthRepartition);
}
/**
@@ -73,7 +76,7 @@ class FreshRSS_StatsDAOPGSQL extends FreshRSS_StatsDAO {
$periodMax = match ($period) {
'hour' => 24,
'day' => 7,
'dow' => 7,
'month' => 12,
default => 30,
};
+4 -6
View File
@@ -148,6 +148,7 @@ function jsonChartBarWithAverage(labelBarChart, dataBarChart, labelAverage, data
return {
type: 'bar',
data: {
labels: xAxisLabels,
datasets: [
{
// bar chart layout
@@ -164,10 +165,7 @@ function jsonChartBarWithAverage(labelBarChart, dataBarChart, labelAverage, data
type: 'line',
label: labelAverage, // Todo: i18n
borderColor: 'rgb(192,216,0)',
data: {
'-30': dataAverage,
'-1': dataAverage,
},
data: dataBarChart.map(() => dataAverage),
order: 1,
},
],
@@ -180,9 +178,9 @@ function jsonChartBarWithAverage(labelBarChart, dataBarChart, labelAverage, data
},
x: {
ticks: {
callback: function (val) {
callback: function (val, index) {
if (xAxisLabels.length > 0) {
return xAxisLabels[val];
return xAxisLabels[index] ?? val;
} else {
return val;
}
+74
View File
@@ -4,6 +4,80 @@ use PHPUnit\Framework\TestCase;
final class StatsDAOTest extends TestCase {
/**
* @return array{0:FreshRSS_StatsDAOSQLite,1:Minz_PdoSqlite}
*/
private static function createSQLiteDao(): array {
$pdo = new Minz_PdoSqlite('sqlite::memory:');
$pdo->setPrefix('');
$pdo->exec('CREATE TABLE entry (id INTEGER PRIMARY KEY, date INTEGER)');
$dao = new FreshRSS_StatsDAOSQLite('test', $pdo);
return [$dao, $pdo];
}
public static function testCalculateEntryCountIncludesTodayWithSQLite(): void {
[$dao, $pdo] = self::createSQLiteDao();
$midnight = mktime(0, 0, 0) ?: 0;
for ($day = 0; $day <= 30; $day++) {
$pdo->exec('INSERT INTO entry(date) VALUES (' . ($midnight - $day * 86400 + 12 * 3600) . ')');
}
self::assertSame(array_fill(0, 31, 1), $dao->calculateEntryCount());
}
public static function testCalculateDayOfWeekRepartitionWithSQLite(): void {
[$dao, $pdo] = self::createSQLiteDao();
$pdo->exec('INSERT INTO entry(date) VALUES (' . mktime(12, 0, 0, 1, 7, 2024) . ')'); // 2024-01-07 is a Sunday
$dayOfWeek = $dao->calculateEntryRepartitionPerFeedPerDayOfWeek();
self::assertCount(7, $dayOfWeek);
self::assertSame(1, $dayOfWeek[0]);
self::assertSame(1, array_sum($dayOfWeek));
}
public static function testCalculateMonthRepartitionWithSQLite(): void {
[$dao, $pdo] = self::createSQLiteDao();
$pdo->exec('INSERT INTO entry(date) VALUES (' . mktime(12, 0, 0, 1, 15, 2024) . ')');
$pdo->exec('INSERT INTO entry(date) VALUES (' . mktime(12, 0, 0, 12, 15, 2024) . ')');
$months = $dao->calculateEntryRepartitionPerFeedPerMonth();
self::assertCount(12, $months);
self::assertSame(1, $months[0]); // January
self::assertSame(1, $months[11]); // December
self::assertSame(2, array_sum($months));
}
public static function testPostgreSQLRepartitions(): void {
$dsn = getenv('FRESHRSS_TEST_PGSQL_DSN');
if ($dsn === false || $dsn === '') {
self::markTestSkipped('FRESHRSS_TEST_PGSQL_DSN is not configured.');
}
$pdo = new Minz_PdoPgsql($dsn, null, null, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$prefix = 'stats_test_' . getmypid() . '_';
$pdo->setPrefix($prefix);
$pdo->exec("CREATE TABLE {$prefix}entry (id BIGSERIAL PRIMARY KEY, date BIGINT)");
try {
$dao = new FreshRSS_StatsDAOPGSQL('test', $pdo);
$pdo->exec("INSERT INTO {$prefix}entry(date) VALUES (" . mktime(12, 0, 0, 1, 7, 2024) . ')'); // 2024-01-07 is a Sunday
$pdo->exec("INSERT INTO {$prefix}entry(date) VALUES (" . mktime(12, 0, 0, 12, 15, 2024) . ')');
$dayOfWeek = $dao->calculateEntryRepartitionPerFeedPerDayOfWeek();
self::assertCount(7, $dayOfWeek);
self::assertSame(2, $dayOfWeek[0]); // Both 2024-01-07 and 2024-12-15 are Sundays
self::assertSame(2, array_sum($dayOfWeek));
$months = $dao->calculateEntryRepartitionPerFeedPerMonth();
self::assertCount(12, $months);
self::assertSame(1, $months[0]); // January
self::assertSame(1, $months[11]); // December
$midnight = mktime(0, 0, 0) ?: 0;
for ($day = 0; $day <= 30; $day++) {
$pdo->exec("INSERT INTO {$prefix}entry(date) VALUES (" . ($midnight - $day * 86400 + 12 * 3600) . ')');
}
self::assertSame(array_fill(0, 31, 1), $dao->calculateEntryCount());
} finally {
$pdo->exec("DROP TABLE {$prefix}entry");
}
}
public static function testCalculateEntryAverageFromRepartition(): void {
self::assertSame(2.0, FreshRSS_StatsDAO::calculateEntryAverageFromRepartition([0, 2, 4]));
}