Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix: SQLite/PostgreSQL parity for stats timestamps, uuid defaults, and id column types (#533)

Yudhi Armyndharisd594f3e89af7
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e1eaab036..eb83be240 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,6 +11,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- **Bulk batch ids are unique per session, not globally.** A batch id claimed by one session no longer prevents another session from using the same id — the uniqueness constraint is now scoped to `(session, batchId)`, matching the per-session lookup, so an explicit cross-session reuse no longer fails with a `500`. Reusing an id within the same session is still rejected with a clear `400`. Existing databases are migrated in place. (#531)
- **A message arriving while a session is being deleted is no longer persisted as an orphan.** The inbound-message handler re-checks that the session is still live after its asynchronous processing, so a message that races a session deletion can't leave behind a `messages` row (which has no cascade) for a session that no longer exists. (#531)
+- **Per-session stats return a consistent `lastActive` timestamp on SQLite and PostgreSQL.** `GET /stats/sessions/:id` previously emitted a different `topChats[].lastActive` format depending on the database (an ISO date-time on PostgreSQL versus the stored text on SQLite); it is now formatted to a stable `YYYY-MM-DD HH:MM:SS` on both. (#533)
+- **The uuid id default now works on PostgreSQL 12 and older.** Id generation relies on a `gen_random_uuid()` column default, which is a core built-in only from PostgreSQL 13; on older servers it lives in the `pgcrypto` extension. The migration now enables `pgcrypto` first, so a fresh deploy against PostgreSQL ≤ 12 no longer fails on startup or first insert. (#533)
### Security
diff --git a/src/database/add-uuid-defaults-migration.spec.ts b/src/database/add-uuid-defaults-migration.spec.ts
index 4ed9ca23c..ee16b6334 100644
--- a/src/database/add-uuid-defaults-migration.spec.ts
+++ b/src/database/add-uuid-defaults-migration.spec.ts
@@ -25,20 +25,28 @@ describe('AddUuidDefaultsForPostgres migration', () => {
expect(qr.hasTable).not.toHaveBeenCalled();
});
- it('on Postgres up() sets a uuid DEFAULT on every existing table', async () => {
+ it('on Postgres up() creates pgcrypto, then sets a uuid DEFAULT on every existing table', async () => {
const qr = makeQueryRunner('postgres', new Set(ALL_TABLES));
await migration.up(qr as unknown as QueryRunner);
- expect(qr.query).toHaveBeenCalledTimes(ALL_TABLES.length);
+ // 1 CREATE EXTENSION + one ALTER per table.
+ expect(qr.query).toHaveBeenCalledTimes(ALL_TABLES.length + 1);
+ const calls = qr.query.mock.calls.map(call => String((call as unknown[])[0]));
+ // pgcrypto must be ensured before any gen_random_uuid() default that depends on it (PG <= 12).
+ const extIdx = calls.findIndex(q => /CREATE EXTENSION IF NOT EXISTS pgcrypto/i.test(q));
+ const firstAlterIdx = calls.findIndex(q => /gen_random_uuid\(\)/i.test(q));
+ expect(extIdx).toBe(0);
+ expect(extIdx).toBeLessThan(firstAlterIdx);
expect(qr.query).toHaveBeenCalledWith(
'ALTER TABLE "sessions" ALTER COLUMN "id" SET DEFAULT gen_random_uuid()::varchar',
);
});
- it('skips tables that do not exist', async () => {
+ it('skips tables that do not exist (still creates pgcrypto)', async () => {
const qr = makeQueryRunner('postgres', new Set(['sessions', 'messages']));
await migration.up(qr as unknown as QueryRunner);
- expect(qr.query).toHaveBeenCalledTimes(2);
+ // 1 CREATE EXTENSION + 2 ALTERs (only the two existing tables).
+ expect(qr.query).toHaveBeenCalledTimes(3);
});
it('on Postgres down() drops the DEFAULT on every existing table', async () => {
diff --git a/src/database/migrations/1779235200000-AddUuidDefaultsForPostgres.ts b/src/database/migrations/1779235200000-AddUuidDefaultsForPostgres.ts
index c55c3d1d7..aca2743bc 100644
--- a/src/database/migrations/1779235200000-AddUuidDefaultsForPostgres.ts
+++ b/src/database/migrations/1779235200000-AddUuidDefaultsForPostgres.ts
@@ -14,7 +14,10 @@ import { MigrationInterface, QueryRunner } from 'typeorm';
* This migration is a no-op on SQLite (TypeORM generates the UUID in the
* driver layer there, so no DB default is needed).
*
- * `gen_random_uuid()` is built into PostgreSQL 13+ — no extension required.
+ * `gen_random_uuid()` is a core built-in only from PostgreSQL 13; on PG <= 12
+ * it lives in the pgcrypto extension. We `CREATE EXTENSION IF NOT EXISTS
+ * pgcrypto` first so the default (and every insert that relies on it) works on
+ * older servers too. On PG 13+ the extension is harmless/redundant.
*/
export class AddUuidDefaultsForPostgres1779235200000 implements MigrationInterface {
name = 'AddUuidDefaultsForPostgres1779235200000';
@@ -25,6 +28,9 @@ export class AddUuidDefaultsForPostgres1779235200000 implements MigrationInterfa
public async up(queryRunner: QueryRunner): Promise<void> {
if (queryRunner.connection.options.type !== 'postgres') return;
+ // gen_random_uuid() is core only on PG 13+; ensure pgcrypto is present so PG <= 12 resolves it too.
+ await queryRunner.query(`CREATE EXTENSION IF NOT EXISTS pgcrypto`);
+
for (const table of this.tables) {
const exists = await queryRunner.hasTable(table);
if (!exists) continue;
diff --git a/src/modules/stats/stats.service.spec.ts b/src/modules/stats/stats.service.spec.ts
index 09acc9dc6..5347b1d02 100644
--- a/src/modules/stats/stats.service.spec.ts
+++ b/src/modules/stats/stats.service.spec.ts
@@ -1,5 +1,5 @@
import { DataSource } from 'typeorm';
-import { StatsService, timeSeriesTimestampSql, hourBucketSql } from './stats.service';
+import { StatsService, timeSeriesTimestampSql, hourBucketSql, maxCreatedAtSql } from './stats.service';
import { Session, SessionStatus } from '../session/entities/session.entity';
import { Message, MessageDirection, MessageStatus } from '../message/entities/message.entity';
@@ -19,6 +19,14 @@ describe('stats SQL dialect helpers', () => {
expect(timeSeriesTimestampSql('postgres', 'day')).toBe(`to_char(m."createdAt", 'YYYY-MM-DD')`);
expect(hourBucketSql('postgres')).toBe(`CAST(EXTRACT(HOUR FROM m."createdAt") AS INTEGER)`);
});
+
+ it('formats MAX(createdAt) to an identical text timestamp on both engines (lastActive parity)', () => {
+ // Postgres returns a timestamp the driver hydrates to a JS Date (serialized to a different ISO
+ // string than SQLite's stored text); pinning both to the same to_char/strftime format keeps the
+ // lastActive field stable regardless of the backing database.
+ expect(maxCreatedAtSql('sqlite')).toBe(`strftime('%Y-%m-%d %H:%M:%S', MAX(m.createdAt))`);
+ expect(maxCreatedAtSql('postgres')).toBe(`to_char(MAX(m."createdAt"), 'YYYY-MM-DD HH24:MI:SS')`);
+ });
});
describe('StatsService time-series + hourly activity on SQLite (end-to-end regression)', () => {
diff --git a/src/modules/stats/stats.service.ts b/src/modules/stats/stats.service.ts
index bbeba5805..ea7f12e42 100644
--- a/src/modules/stats/stats.service.ts
+++ b/src/modules/stats/stats.service.ts
@@ -28,6 +28,19 @@ export function hourBucketSql(dbType: string): string {
: `CAST(strftime('%H', m.createdAt) AS INTEGER)`;
}
+/**
+ * SQL for the most-recent-activity timestamp (MAX of createdAt) as an identical text format on both
+ * engines. SQLite's MAX over a `datetime` column returns the stored text; Postgres returns a timestamp
+ * the driver hydrates to a JS Date (serialized to a different ISO string). to_char/strftime pin both
+ * to `YYYY-MM-DD HH:MM:SS`, matching the format the time-series buckets already use, so the lastActive
+ * field is stable regardless of the backing database.
+ */
+export function maxCreatedAtSql(dbType: string): string {
+ return dbType === 'postgres'
+ ? `to_char(MAX(m."createdAt"), 'YYYY-MM-DD HH24:MI:SS')`
+ : `strftime('%Y-%m-%d %H:%M:%S', MAX(m.createdAt))`;
+}
+
export interface OverviewStats {
sessions: {
active: number;
@@ -251,7 +264,7 @@ export class StatsService {
.createQueryBuilder('m')
.select('m.chatId', 'chatId')
.addSelect('COUNT(*)', 'count')
- .addSelect('MAX(m.createdAt)', 'lastActive')
+ .addSelect(maxCreatedAtSql(this.dataDbType), 'lastActive')
.where('m.sessionId = :sessionId', { sessionId })
.groupBy('m.chatId')
.orderBy('count', 'DESC')
diff --git a/src/modules/template/entities/template.entity.ts b/src/modules/template/entities/template.entity.ts
index 9fdcb470f..96adc6bf3 100644
--- a/src/modules/template/entities/template.entity.ts
+++ b/src/modules/template/entities/template.entity.ts
@@ -18,7 +18,9 @@ export class Template {
@PrimaryGeneratedColumn('uuid')
id: string;
- @Column({ type: 'uuid' })
+ // varchar (not uuid) to match the authoritative migration DDL and sessions.id; the data connection
+ // runs synchronize:false, so a 'uuid' decorator here would only mislead schema diffs / a stray sync.
+ @Column({ type: 'varchar' })
sessionId: string;
@ManyToOne(() => Session, { onDelete: 'CASCADE' })
diff --git a/src/modules/webhook/entities/webhook.entity.ts b/src/modules/webhook/entities/webhook.entity.ts
index ca8fd94a0..4207cf00a 100644
--- a/src/modules/webhook/entities/webhook.entity.ts
+++ b/src/modules/webhook/entities/webhook.entity.ts
@@ -17,7 +17,9 @@ export class Webhook {
@PrimaryGeneratedColumn('uuid')
id: string;
- @Column({ type: 'uuid' })
+ // varchar (not uuid) to match the authoritative migration DDL and sessions.id; the data connection
+ // runs synchronize:false, so a 'uuid' decorator here would only mislead schema diffs / a stray sync.
+ @Column({ type: 'varchar' })
sessionId: string;
@ManyToOne(() => Session, { onDelete: 'CASCADE' })