Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(database): keep boot migrations within budget on Postgres + idempotent revert (#543)

Yudhi Armyndharisf08f7add9e84
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a08bf24ff..0747b8349 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
+
+- **Boot migrations are no longer aborted by the runtime query timeout on PostgreSQL.** The `data` connection sets a `statement_timeout` to bound live queries, and that limit was inherited by the migrations that run at startup — so on a large existing deployment a backfill plus `CREATE UNIQUE INDEX` over the `messages` or `templates` table could exceed it and fail boot. The two affected migrations now lift the timeout for their own transaction (PostgreSQL-only, transaction-scoped via `SET LOCAL`, a no-op on SQLite); the runtime timeout that protects live traffic is unchanged. (#543)
+- **The templates migration revert is idempotent on a synchronize-bootstrapped database.** `AddTemplates` now drops its index and table with `IF EXISTS`, so a `down()` no longer errors when the schema was created by `synchronize` and the migration-only `IDX_templates_sessionId` index was never created. (#543)
### Added
- **Inbound @mentions are surfaced on the Baileys engine.** An incoming message that tags participants now exposes the tagged WIDs as `mentionedIds` (normalized to the neutral `@c.us` convention), reaching parity with the whatsapp-web.js engine and feeding the existing `mentions` webhook filter and command-targeting. (#542)
diff --git a/src/app.module.ts b/src/app.module.ts
index 3cee4ed07..627d47ab2 100644
--- a/src/app.module.ts
+++ b/src/app.module.ts
@@ -162,7 +162,9 @@ if (dashboardServingEnabled && dashboardBuildPresent) {
extra: {
max: configService.get<number>('dataDatabase.poolSize', 10),
// Runtime query/pool timeouts so a stuck query or saturated pool fails fast instead of
- // hanging requests. statement_timeout is safe here (no migrations on this connection).
+ // hanging requests. statement_timeout bounds live runtime queries; the boot migrations
+ // (migrationsRun above) reset it to 0 per-transaction via SET LOCAL, so a long
+ // CREATE INDEX / backfill at boot is never aborted by it.
statement_timeout: configService.get<number>('dataDatabase.statementTimeoutMs', 30000),
idleTimeoutMillis: configService.get<number>('dataDatabase.idleTimeoutMs', 30000),
connectionTimeoutMillis: configService.get<number>('dataDatabase.connectionTimeoutMs', 10000),
diff --git a/src/database/migrations/1779840000000-AddTemplates.ts b/src/database/migrations/1779840000000-AddTemplates.ts
index b464da3ce..6506243c7 100644
--- a/src/database/migrations/1779840000000-AddTemplates.ts
+++ b/src/database/migrations/1779840000000-AddTemplates.ts
@@ -31,7 +31,9 @@ export class AddTemplates1779840000000 implements MigrationInterface {
}
public async down(queryRunner: QueryRunner): Promise<void> {
- await queryRunner.query(`DROP INDEX "IDX_templates_sessionId"`);
- await queryRunner.query(`DROP TABLE "templates"`);
+ // IF EXISTS so revert is idempotent on a synchronize-bootstrapped DB, where this migration was
+ // recorded via the up() hasTable early-return and the named index was never created.
+ await queryRunner.query(`DROP INDEX IF EXISTS "IDX_templates_sessionId"`);
+ await queryRunner.query(`DROP TABLE IF EXISTS "templates"`);
}
}
diff --git a/src/database/migrations/1781100000000-AddTemplateNameUnique.ts b/src/database/migrations/1781100000000-AddTemplateNameUnique.ts
index ec589f4ae..e6a58647b 100644
--- a/src/database/migrations/1781100000000-AddTemplateNameUnique.ts
+++ b/src/database/migrations/1781100000000-AddTemplateNameUnique.ts
@@ -17,6 +17,12 @@ export class AddTemplateNameUnique1781100000000 implements MigrationInterface {
name = 'AddTemplateNameUnique1781100000000';
public async up(queryRunner: QueryRunner): Promise<void> {
+ if (queryRunner.connection.options.type === 'postgres') {
+ // See AddMessagesWaMessageIdUnique: lift the runtime statement_timeout for this migration
+ // transaction so the dedup UPDATE / CREATE UNIQUE INDEX over templates is not aborted. SET LOCAL is
+ // transaction-scoped and a no-op on SQLite (which rejects it syntactically — hence the guard).
+ await queryRunner.query('SET LOCAL statement_timeout = 0');
+ }
if (!(await queryRunner.hasTable('templates'))) return;
// Keep the earliest row per (sessionId, name) — createdAt ASC, id ASC as a stable tiebreak —
diff --git a/src/database/migrations/1781300000000-AddMessagesWaMessageIdUnique.ts b/src/database/migrations/1781300000000-AddMessagesWaMessageIdUnique.ts
index 72a7b8bb6..df490741e 100644
--- a/src/database/migrations/1781300000000-AddMessagesWaMessageIdUnique.ts
+++ b/src/database/migrations/1781300000000-AddMessagesWaMessageIdUnique.ts
@@ -14,6 +14,13 @@ export class AddMessagesWaMessageIdUnique1781300000000 implements MigrationInter
name = 'AddMessagesWaMessageIdUnique1781300000000';
public async up(queryRunner: QueryRunner): Promise<void> {
+ if (queryRunner.connection.options.type === 'postgres') {
+ // The runtime 'data' pool carries a statement_timeout (app.module.ts) and migrations run on it at
+ // boot. Lift it for THIS transaction so the dedup DELETE / CREATE UNIQUE INDEX over the hot messages
+ // table is never aborted mid-flight. SET LOCAL is transaction-scoped (auto-reverts at COMMIT) and is
+ // a no-op everywhere else — SQLite rejects it syntactically, hence the guard.
+ await queryRunner.query('SET LOCAL statement_timeout = 0');
+ }
if (!(await queryRunner.hasTable('messages'))) return;
await queryRunner.query(
diff --git a/src/database/migrations/__tests__/1779840000000-AddTemplates.spec.ts b/src/database/migrations/__tests__/1779840000000-AddTemplates.spec.ts
new file mode 100644
index 000000000..4d0e79d1b
--- /dev/null
+++ b/src/database/migrations/__tests__/1779840000000-AddTemplates.spec.ts
@@ -0,0 +1,56 @@
+import { DataSource } from 'typeorm';
+import { AddTemplates1779840000000 } from '../1779840000000-AddTemplates';
+
+describe('AddTemplates migration', () => {
+ let ds: DataSource;
+
+ beforeEach(async () => {
+ ds = new DataSource({ type: 'sqlite', database: ':memory:' });
+ await ds.initialize();
+ // up() declares a CASCADE FK to sessions; create a minimal stand-in (mirrors the sibling specs).
+ await ds.query(`CREATE TABLE "sessions" ("id" varchar PRIMARY KEY NOT NULL)`);
+ });
+
+ afterEach(async () => {
+ await ds.destroy();
+ });
+
+ const tableExists = async (): Promise<boolean> => {
+ const rows = await ds.query<unknown[]>(`SELECT name FROM sqlite_master WHERE type='table' AND name='templates'`);
+ return rows.length === 1;
+ };
+
+ it('creates the table and its index, is idempotent, and down() reverses it', async () => {
+ const runner = ds.createQueryRunner();
+ const migration = new AddTemplates1779840000000();
+
+ await migration.up(runner);
+ expect(await tableExists()).toBe(true);
+ const index = (await runner.query(
+ `SELECT name FROM sqlite_master WHERE type='index' AND name='IDX_templates_sessionId'`,
+ )) as unknown[];
+ expect(index).toHaveLength(1);
+
+ await expect(migration.up(runner)).resolves.toBeUndefined(); // re-run: hasTable early-return
+
+ await migration.down(runner);
+ expect(await tableExists()).toBe(false);
+ await runner.release();
+ });
+
+ it('down() does not throw when the migration-only index was never created (synchronize-bootstrapped DB)', async () => {
+ // Simulate a schema built by synchronize: the templates table exists with the ENTITY index, but the
+ // migration-only IDX_templates_sessionId was never created and up() was never run.
+ await ds.query(
+ `CREATE TABLE "templates" ("id" varchar PRIMARY KEY NOT NULL, "sessionId" varchar NOT NULL, ` +
+ `"name" varchar(100) NOT NULL, "body" text NOT NULL, "header" text, "footer" text, ` +
+ `"createdAt" datetime NOT NULL, "updatedAt" datetime NOT NULL)`,
+ );
+ await ds.query(`CREATE UNIQUE INDEX "IDX_templates_session_name" ON "templates" ("sessionId", "name")`);
+
+ const runner = ds.createQueryRunner();
+ await expect(new AddTemplates1779840000000().down(runner)).resolves.toBeUndefined();
+ expect(await tableExists()).toBe(false);
+ await runner.release();
+ });
+});
diff --git a/src/database/migrations/__tests__/1781100000000-AddTemplateNameUnique.spec.ts b/src/database/migrations/__tests__/1781100000000-AddTemplateNameUnique.spec.ts
index 0e72ec208..ae955bb3a 100644
--- a/src/database/migrations/__tests__/1781100000000-AddTemplateNameUnique.spec.ts
+++ b/src/database/migrations/__tests__/1781100000000-AddTemplateNameUnique.spec.ts
@@ -1,4 +1,4 @@
-import { DataSource } from 'typeorm';
+import { DataSource, QueryRunner } from 'typeorm';
import { AddTemplateNameUnique1781100000000 } from '../1781100000000-AddTemplateNameUnique';
describe('AddTemplateNameUnique migration', () => {
@@ -75,4 +75,22 @@ describe('AddTemplateNameUnique migration', () => {
await expect(new AddTemplateNameUnique1781100000000().up(runner)).resolves.toBeUndefined();
await runner.release();
});
+
+ it('lifts the runtime statement_timeout for the migration transaction on Postgres', async () => {
+ // The runtime data pool's statement_timeout is inherited by the boot-migration connection; this
+ // dedup UPDATE / CREATE UNIQUE INDEX over templates must not be aborted mid-flight.
+ const queries: string[] = [];
+ const pgRunner = {
+ connection: { options: { type: 'postgres' } },
+ hasTable: jest.fn().mockResolvedValue(true),
+ query: jest.fn((sql: string) => {
+ queries.push(sql);
+ return Promise.resolve([]);
+ }),
+ } as unknown as QueryRunner;
+
+ await new AddTemplateNameUnique1781100000000().up(pgRunner);
+
+ expect(queries[0]).toBe('SET LOCAL statement_timeout = 0');
+ });
});
diff --git a/src/database/migrations/__tests__/1781300000000-AddMessagesWaMessageIdUnique.spec.ts b/src/database/migrations/__tests__/1781300000000-AddMessagesWaMessageIdUnique.spec.ts
index 02ac67972..0408d4d98 100644
--- a/src/database/migrations/__tests__/1781300000000-AddMessagesWaMessageIdUnique.spec.ts
+++ b/src/database/migrations/__tests__/1781300000000-AddMessagesWaMessageIdUnique.spec.ts
@@ -1,4 +1,4 @@
-import { DataSource } from 'typeorm';
+import { DataSource, QueryRunner } from 'typeorm';
import { AddMessagesWaMessageIdUnique1781300000000 } from '../1781300000000-AddMessagesWaMessageIdUnique';
describe('AddMessagesWaMessageIdUnique migration', () => {
@@ -64,4 +64,22 @@ describe('AddMessagesWaMessageIdUnique migration', () => {
await expect(migration.up(runner)).resolves.toBeUndefined(); // absent table
await runner.release();
});
+
+ it('lifts the runtime statement_timeout for the migration transaction on Postgres', async () => {
+ // The runtime data pool carries a statement_timeout that is inherited by the boot-migration
+ // connection; this DELETE / CREATE UNIQUE INDEX over the hot messages table must not be aborted.
+ const queries: string[] = [];
+ const pgRunner = {
+ connection: { options: { type: 'postgres' } },
+ hasTable: jest.fn().mockResolvedValue(true),
+ query: jest.fn((sql: string) => {
+ queries.push(sql);
+ return Promise.resolve([]);
+ }),
+ } as unknown as QueryRunner;
+
+ await new AddMessagesWaMessageIdUnique1781300000000().up(pgRunner);
+
+ expect(queries[0]).toBe('SET LOCAL statement_timeout = 0');
+ });
});