Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(stats): don't GROUP BY the reserved word `timestamp` (PostgreSQL 500) (#476)

Yudhi Armyndharisf2834f140b8e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 205b35717..cf88d40af 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
+### Fixed
+
+- The stats/analytics endpoint no longer crashes on PostgreSQL. The message time-series query grouped by an output alias named `timestamp` — a reserved type keyword in PostgreSQL — so `GROUP BY timestamp` was not read as the alias and the query failed with _"column m.createdAt must appear in the GROUP BY clause"_ (SQLite tolerated it, so unit tests on the SQLite test DB never caught it). The alias is now `bucket`; the API response field is unchanged. (#474)
+
### Documentation
- Added a Traefik / Coolify reverse-proxy guide to the troubleshooting FAQ: WebSocket forwarding, the `docker-proxy` double-hop that causes intermittent `504`s behind Coolify (held-open Socket.IO connections exhausting the pool to the single-port upstream), and idle-timeout tuning. (#467)
diff --git a/src/modules/stats/stats.service.spec.ts b/src/modules/stats/stats.service.spec.ts
index 636bd2750..e517bcd29 100644
--- a/src/modules/stats/stats.service.spec.ts
+++ b/src/modules/stats/stats.service.spec.ts
@@ -78,6 +78,36 @@ describe('StatsService time-series + hourly activity on SQLite (end-to-end regre
expect(stats.timeSeries[0].timestamp).toMatch(/^\d{4}-\d{2}-\d{2} \d{2}:00:00$/);
});
+ it('time-series query never groups by the bare reserved word `timestamp` (Postgres-safe)', async () => {
+ await ds
+ .getRepository(Session)
+ .save(ds.getRepository(Session).create({ id: 's1', name: 'n', status: SessionStatus.READY, config: {} }));
+ await seedMessage({ direction: MessageDirection.OUTGOING });
+
+ // SQLite tolerates `GROUP BY timestamp`, but `timestamp` is a reserved type keyword in Postgres
+ // and crashes there ("column m.createdAt must appear in the GROUP BY"). Assert the generated SQL,
+ // not the result, so the fix can't silently regress on the backend the test DB doesn't exercise.
+ const captured: string[] = [];
+ const repo = ds.getRepository(Message);
+ const origCreate = repo.createQueryBuilder.bind(repo);
+ jest.spyOn(repo, 'createQueryBuilder').mockImplementation((alias?: string) => {
+ const qb = origCreate(alias);
+ const origGetRawMany = qb.getRawMany.bind(qb);
+ jest.spyOn(qb, 'getRawMany').mockImplementation((async () => {
+ captured.push(qb.getQuery());
+ return origGetRawMany();
+ }) as never);
+ return qb;
+ });
+
+ await service.getMessageStats('24h');
+
+ expect(captured.some(sql => /GROUP BY/i.test(sql))).toBe(true); // sanity: a grouped query was built
+ for (const sql of captured) {
+ expect(sql).not.toMatch(/GROUP BY\s+timestamp\b/i);
+ }
+ });
+
it('getSessionStats returns 24 hourly buckets with the right counts', async () => {
await ds
.getRepository(Session)
diff --git a/src/modules/stats/stats.service.ts b/src/modules/stats/stats.service.ts
index a575865bc..2e523e47a 100644
--- a/src/modules/stats/stats.service.ts
+++ b/src/modules/stats/stats.service.ts
@@ -284,18 +284,22 @@ export class StatsService {
}
private async getTimeSeries(since: Date, interval: 'hour' | 'day'): Promise<TimeSeriesPoint[]> {
+ // Alias the bucket as `bucket`, not `timestamp`: `timestamp` is a reserved type keyword in
+ // PostgreSQL, so `GROUP BY timestamp` is not read as the output alias and the query 500s
+ // ("column m.createdAt must appear in the GROUP BY"). SQLite tolerates it, hence the dialect-only
+ // bug. The API field stays `timestamp` (mapped below).
const raw = await this.messageRepo
.createQueryBuilder('m')
- .select(timeSeriesTimestampSql(this.dataDbType, interval), 'timestamp')
+ .select(timeSeriesTimestampSql(this.dataDbType, interval), 'bucket')
.addSelect(`SUM(CASE WHEN m.direction = 'outgoing' THEN 1 ELSE 0 END)`, 'sent')
.addSelect(`SUM(CASE WHEN m.direction = 'incoming' THEN 1 ELSE 0 END)`, 'received')
.where('m.createdAt >= :since', { since })
- .groupBy('timestamp')
- .orderBy('timestamp', 'ASC')
- .getRawMany<{ timestamp: string; sent: string; received: string }>();
+ .groupBy('bucket')
+ .orderBy('bucket', 'ASC')
+ .getRawMany<{ bucket: string; sent: string; received: string }>();
return raw.map(r => ({
- timestamp: r.timestamp,
+ timestamp: r.bucket,
sent: parseInt(r.sent || '0'),
received: parseInt(r.received || '0'),
}));