Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(infra): cast session columns in the import-data chat_states re-key

Yudhi Armyndharis02f3a7a7fe7e
diff --git a/src/database/migrations/1786500000000-ReKeyChatStatesBySessionId.ts b/src/database/migrations/1786500000000-ReKeyChatStatesBySessionId.ts
index 2d1a92937..99fea815d 100644
--- a/src/database/migrations/1786500000000-ReKeyChatStatesBySessionId.ts
+++ b/src/database/migrations/1786500000000-ReKeyChatStatesBySessionId.ts
@@ -34,16 +34,21 @@ export class ReKeyChatStatesBySessionId1786500000000 implements MigrationInterfa
* Static, not a module-level export: TypeORM loads every exported function in this directory as a
* migration class. Also run by import-data, whose archive may predate this re-key; that caller sets
* `skipAlreadyKeyed` so a row already keyed by an existing session's `to` value is left alone even
- * when some other session's `from` value happens to equal it.
+ * when some other session's `from` value happens to equal it. That caller also casts the session
+ * columns to varchar: a PostgreSQL schema built by synchronize has a native uuid `sessions.id`, which
+ * has no `=` operator against the varchar `chat_states.sessionId`. The migration's own SQL is left
+ * unchanged, since the migration chain keeps `sessions.id` varchar.
*/
static rekey(from: 'name' | 'id', to: 'name' | 'id', opts: { skipAlreadyKeyed?: boolean } = {}): string {
- const target = `(SELECT s."${to}" FROM sessions s WHERE s."${from}" = chat_states."sessionId")`;
+ const col = (alias: string, name: string): string =>
+ opts.skipAlreadyKeyed ? `CAST(${alias}."${name}" AS varchar)` : `${alias}."${name}"`;
+ const target = `(SELECT ${col('s', to)} FROM sessions s WHERE ${col('s', from)} = chat_states."sessionId")`;
const alreadyKeyed = opts.skipAlreadyKeyed
? `
- AND NOT EXISTS (SELECT 1 FROM sessions s2 WHERE s2."${to}" = chat_states."sessionId")`
+ AND NOT EXISTS (SELECT 1 FROM sessions s2 WHERE ${col('s2', to)} = chat_states."sessionId")`
: '';
return `UPDATE chat_states SET "sessionId" = ${target}
- WHERE EXISTS (SELECT 1 FROM sessions s WHERE s."${from}" = chat_states."sessionId")
+ WHERE EXISTS (SELECT 1 FROM sessions s WHERE ${col('s', from)} = chat_states."sessionId")
AND NOT EXISTS (
SELECT 1 FROM chat_states c WHERE c."chatId" = chat_states."chatId" AND c."sessionId" = ${target}
)${alreadyKeyed}`;
diff --git a/src/database/postgres-utc.pg.spec.ts b/src/database/postgres-utc.pg.spec.ts
index 52d199d96..010dda31e 100644
--- a/src/database/postgres-utc.pg.spec.ts
+++ b/src/database/postgres-utc.pg.spec.ts
@@ -431,6 +431,26 @@ const SqliteSession = new EntitySchema<Record<string, unknown>>({
expect(carried.leaseExpiresAt!.getTime()).toBeGreaterThanOrEqual(leaseExpiresAt.getTime());
});
+ it('re-keys a name-keyed chat state on restore over a uuid sessions.id', async () => {
+ // synchronize gives sessions.id a native uuid type, which has no `=` against the varchar key.
+ await ds.query('DELETE FROM chat_states');
+ const session = await seedSession(SESSION_ID, new Date('2026-01-01T00:00:00.000Z'));
+ const chats = ds.getRepository(ChatState);
+ await chats.save([
+ { sessionId: session.name, chatId: '[email protected]', archived: true, pinned: false },
+ { sessionId: SESSION_ID, chatId: '[email protected]', archived: false, pinned: true },
+ ]);
+ const archive = JSON.parse(JSON.stringify(await infra.exportData())) as { tables: MigrationTables };
+
+ expect(await infra.importData({ tables: archive.tables })).toMatchObject({ imported: true, warnings: [] });
+
+ const rows = await chats.find({ order: { chatId: 'ASC' } });
+ expect(rows.map(r => [r.chatId, r.sessionId, r.archived, r.pinned])).toEqual([
+ ['[email protected]', SESSION_ID, false, true],
+ ['[email protected]', SESSION_ID, true, false],
+ ]);
+ });
+
it('rolls back a rejected row with its real error instead of an aborted-transaction failure', async () => {
await seedSession(SESSION_ID, new Date('2026-01-01T00:00:00.000Z'));
const archive = JSON.parse(JSON.stringify(await infra.exportData())) as { tables: MigrationTables };