Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(db): normalize synchronize-built uuid id columns on Postgres (#691)
Yudhi Armyndharis788cd3cda54f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex aa678e190..a7222c3e4 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+- **PostgreSQL upgrade crash-loop for deployments formerly run with `DATABASE_SYNCHRONIZE=true`.** On the PostgreSQL data connection, migrations always run at boot (`migrationsRun: true`), so a schema previously bootstrapped with `DATABASE_SYNCHRONIZE=true` — whose `@PrimaryGeneratedColumn('uuid')` columns TypeORM created as native `uuid` — collides with a migration chain that assumes `varchar` ids and crash-loops the container on boot. A new guard migration (`NormalizeSynchronizeUuidColumns`), ordered before the first colliding migration, now converts those `uuid` id and foreign-key columns to `varchar` (dropping and recreating the dependent cascade foreign keys, and re-applying the `gen_random_uuid()::varchar` defaults), so affected deployments self-heal on the next restart. It is a single-probe no-op on SQLite and on already-`varchar` (healthy) PostgreSQL. For very large `messages` tables the conversion holds an exclusive lock, so run `npm run migration:run` against the stopped app during a maintenance window if needed; `DATABASE_SYNCHRONIZE=true` on PostgreSQL remains unsupported for production. Fixes #690.+- **Dashboard Korean (ko) locale polish.** Refined several ko strings for consistency, fluency, and accuracy (follow-up to #679): "Create New Session" → `새 세션 생성` (aligns with `생성` used elsewhere in the create flow); the plugin "Configuration" tab → `설정` (matches the rest of the config UI); "Start messaging" → `대화 시작하기` (idiomatic — in Korean one starts a conversation, not a "message"); the WhatsApp Web build "current known-good" now reads `현재` instead of `최신` (latest), which had inverted the version-pinning intent; the "New" session status → `신규` (the conventional Korean status label); and the template placeholder example re-phrases the `{{orderId}}` clause so the interpolation reads naturally.- **Reliability and correctness hardening batch.** A set of fixes across the engine, session, auth, infra, dashboard, and SDK layers:diff --git a/docs/12-troubleshooting-faq.md b/docs/12-troubleshooting-faq.mdindex 989604c46..9f7818fee 100644--- a/docs/12-troubleshooting-faq.md+++ b/docs/12-troubleshooting-faq.md@@ -675,6 +675,8 @@ npm run migration:revertnpm run migration:run:main```+**PostgreSQL crash-loop on boot after upgrade** — if logs show `column "id" is of type uuid but default expression is of type character varying` or `foreign key constraint ... cannot be implemented ... incompatible types: character varying and uuid`, the deployment was previously bootstrapped with `DATABASE_SYNCHRONIZE=true` (native `uuid` columns vs the migrations' `varchar`). A guard migration converts the columns automatically on the next boot; for large `messages` tables, run the migration against the stopped app (`npm run migration:run`) during a maintenance window. See [14.5 / 14.9 — PostgreSQL crash-loop after upgrading a `DATABASE_SYNCHRONIZE=true` deployment](./14-migration-guide.md). `DATABASE_SYNCHRONIZE=true` is unsupported on PostgreSQL for production.+## 12.6 Docker Issues### Issue: Volume Permissionsdiff --git a/docs/14-migration-guide.md b/docs/14-migration-guide.mdindex 9c306ab52..7129ceec9 100644--- a/docs/14-migration-guide.md+++ b/docs/14-migration-guide.md@@ -1245,6 +1245,30 @@ async function fullImport(options: ImportOptions): Promise<void> {| Permission denied | File ownership | `chown -R 1000:1000 ./data` || Out of memory | Large export | Increase Docker memory limit |+### PostgreSQL: boot crash-loop after upgrading a `DATABASE_SYNCHRONIZE=true` deployment++**Symptom:** after upgrade, the container crash-loops on boot. `docker logs` shows one of:++- `column "id" is of type uuid but default expression is of type character varying`+- `foreign key constraint ... cannot be implemented ... incompatible types: character varying and uuid`++**Cause:** a deployment previously bootstrapped with `DATABASE_SYNCHRONIZE=true` on PostgreSQL has native `uuid` `id`/FK columns (TypeORM derives them from `@PrimaryGeneratedColumn('uuid')`), while the migration chain assumes `varchar`. The two are incompatible, and migrations run unconditionally on the Postgres data connection (`migrationsRun: true`), so boot cannot complete (issue #690).++**Fix (automatic for most deployments):** OpenWA ships a guard migration (`NormalizeSynchronizeUuidColumns`, ordered before the first collision) that converts the affected `uuid` columns to `varchar` on the next boot. For small-to-medium databases this is transparent — upgrade and restart.++**Large-database maintenance window:** the conversion rewrites `messages` and `message_batches` in full under an exclusive lock. If either table is large (millions of rows) and your orchestrator's liveness/readiness grace is tight, run the migration against the stopped app during a planned window:++```bash+docker compose down+DATABASE_TYPE=postgres DATABASE_HOST=... DATABASE_USERNAME=... \+ DATABASE_PASSWORD=... DATABASE_NAME=openwa npm run migration:run+docker compose up -d+```++(The CLI runner does not impose a statement timeout; the migration lifts it via `SET LOCAL`.)++`DATABASE_SYNCHRONIZE=true` on PostgreSQL is unsupported for production. Leave it unset (the default `false`) and let migrations manage the schema.+### Debug Commands```bashdiff --git a/src/database/migrations/1770200000000-NormalizeSynchronizeUuidColumns.ts b/src/database/migrations/1770200000000-NormalizeSynchronizeUuidColumns.tsnew file mode 100644index 000000000..9921a09dd--- /dev/null+++ b/src/database/migrations/1770200000000-NormalizeSynchronizeUuidColumns.ts@@ -0,0 +1,202 @@+import { MigrationInterface, QueryRunner } from 'typeorm';++/**+ * Normalizes a PostgreSQL schema previously bootstrapped with DATABASE_SYNCHRONIZE=true.+ *+ * Under synchronize, `@PrimaryGeneratedColumn('uuid')` creates NATIVE uuid id/FK columns, and every+ * `@ManyToOne(() => Session)` FK column is derived as uuid too. The canonical migration chain, however,+ * builds the schema with varchar ids. The two strategies are not interchangeable on Postgres:+ * `AddUuidDefaultsForPostgres` (1779235200000) is the first migration to touch a uuid column — its+ * `gen_random_uuid()::varchar` DEFAULT on a uuid column is rejected — and later CREATE TABLE migrations+ * (AddTemplates, AddBaileysStoredMessages) cannot add a varchar FK referencing the uuid sessions(id).+ * Because `migrationsRun: true` is hardcoded for the Postgres data connection, this crash-loops boot.+ *+ * Ordered immediately after the baseline (1770108659848) and before that first collision, this migration+ * converts the 9 generated-uuid PKs + 3 session-FK columns to varchar in lockstep (dropping/recreating+ * the CASCADE FKs), then sets the `gen_random_uuid()::varchar` DEFAULTs. It is a no-op on SQLite and on+ * an already-varchar (healthy) Postgres schema via a single information_schema probe.+ *+ * See issue #690. Operational note: `ALTER COLUMN ... TYPE varchar` is a full-table rewrite under an+ * ACCESS EXCLUSIVE lock; for very large `messages` tables, run via the CLI (`npm run migration:run`)+ * against the stopped app during a maintenance window.+ */+export class NormalizeSynchronizeUuidColumns1770200000000 implements MigrationInterface {+ name = 'NormalizeSynchronizeUuidColumns1770200000000';++ // The 9 generated-uuid PKs on the DATA connection. api_keys/audit_logs live on the sqlite 'main'+ // connection (immune). lid_mappings/ingress_events/plugin_instances use a varchar @PrimaryColumn by+ // design — do NOT add them here.+ private readonly uuidPkTables = [+ 'sessions',+ 'webhooks',+ 'messages',+ 'message_batches',+ 'templates',+ 'baileys_stored_messages',+ 'webhook_delivery_failures',+ 'conversation_mappings',+ 'integration_delivery_failures',+ ];++ // The 3 @ManyToOne(() => Session) FK-bearing tables. `name` is the CANONICAL re-add name matching the+ // hasTable-guarded CREATE TABLE migrations (which no-op on a sync-built DB, so they do NOT re-add the+ // FK — this migration owns it). The DROP name is DISCOVERED at runtime: synchronize names constraints+ // with a TypeORM hash, not these canonical names.+ private readonly sessionFks = [+ { table: 'webhooks', column: 'sessionId', name: 'FK_d209715bb62b12255e825580af6' },+ { table: 'templates', column: 'sessionId', name: 'FK_templates_sessionId' },+ { table: 'baileys_stored_messages', column: 'sessionId', name: 'FK_baileys_stored_messages_sessionId' },+ ];++ public async up(queryRunner: QueryRunner): Promise<void> {+ if (queryRunner.connection.options.type !== 'postgres') return;+ // Gate: synchronize builds the WHOLE schema atomically (all-uuid, or synchronize itself errors), so a+ // single representative probe on sessions.id is sufficient to detect a drifted schema. Per-column+ // guards inside the loops below add defense-in-depth for the (non-reachable) partial-drift case.+ if (!(await this.columnIsUuid(queryRunner, 'sessions', 'id'))) return;++ await queryRunner.query(`SET LOCAL statement_timeout = 0`);+ await this.ensureGenRandomUuid(queryRunner);++ // 1. Drop FKs referencing sessions(id) FIRST — a uuid FK blocks ALTER of the referenced PK.+ for (const fk of this.sessionFks) {+ if (!(await queryRunner.hasTable(fk.table))) continue;+ for (const c of await this.fkConstraintNames(queryRunner, fk.table, fk.column, 'sessions')) {+ await queryRunner.query(`ALTER TABLE "${fk.table}" DROP CONSTRAINT IF EXISTS "${c}"`);+ }+ }++ // 2. PK uuid -> varchar. DROP DEFAULT first: gen_random_uuid() (native uuid) is not assignment-coercible+ // to varchar, so Postgres rejects ALTER TYPE while the default is still attached.+ for (const t of this.uuidPkTables) {+ if (!(await queryRunner.hasTable(t))) continue;+ if (!(await this.columnIsUuid(queryRunner, t, 'id'))) continue; // per-column idempotency+ await queryRunner.query(`ALTER TABLE "${t}" ALTER COLUMN "id" DROP DEFAULT`);+ await queryRunner.query(`ALTER TABLE "${t}" ALTER COLUMN "id" TYPE varchar USING "id"::text`);+ }++ // 3. Session-FK columns uuid -> varchar.+ for (const fk of this.sessionFks) {+ if (!(await queryRunner.hasTable(fk.table))) continue;+ if (!(await this.columnIsUuid(queryRunner, fk.table, fk.column))) continue;+ await queryRunner.query(+ `ALTER TABLE "${fk.table}" ALTER COLUMN "${fk.column}" TYPE varchar USING "${fk.column}"::text`,+ );+ }++ // 4. Recreate the 3 CASCADE FKs with canonical names.+ for (const fk of this.sessionFks) {+ if (!(await queryRunner.hasTable(fk.table))) continue;+ await queryRunner.query(+ `ALTER TABLE "${fk.table}" ADD CONSTRAINT "${fk.name}" ` ++ `FOREIGN KEY ("${fk.column}") REFERENCES "sessions" ("id") ON DELETE CASCADE ON UPDATE NO ACTION`,+ );+ }++ // 5. gen_random_uuid()::varchar DEFAULT on every existing PK. Mandatory for tables whose CREATE TABLE+ // migration no-op'd on the sync-built DB; idempotent SET DEFAULT for the rest.+ for (const t of this.uuidPkTables) {+ if (!(await queryRunner.hasTable(t))) continue;+ await queryRunner.query(`ALTER TABLE "${t}" ALTER COLUMN "id" SET DEFAULT gen_random_uuid()::varchar`);+ }+ }++ public async down(queryRunner: QueryRunner): Promise<void> {+ // Best-effort inverse (varchar -> native uuid); only meaningful to re-enable synchronize. USING id::uuid+ // validates every value — Postgres aborts on non-uuid strings (no silent corruption).+ if (queryRunner.connection.options.type !== 'postgres') return;+ if (await this.columnIsUuid(queryRunner, 'sessions', 'id')) return; // already native uuid: nothing to revert++ await queryRunner.query(`SET LOCAL statement_timeout = 0`);+ await this.ensureGenRandomUuid(queryRunner);++ // Drop FKs (discovered, same as up — robust to either hash or canonical names).+ for (const fk of this.sessionFks) {+ if (!(await queryRunner.hasTable(fk.table))) continue;+ for (const c of await this.fkConstraintNames(queryRunner, fk.table, fk.column, 'sessions')) {+ await queryRunner.query(`ALTER TABLE "${fk.table}" DROP CONSTRAINT IF EXISTS "${c}"`);+ }+ }++ for (const t of this.uuidPkTables) {+ if (!(await queryRunner.hasTable(t))) continue;+ await queryRunner.query(`ALTER TABLE "${t}" ALTER COLUMN "id" DROP DEFAULT`);+ await queryRunner.query(`ALTER TABLE "${t}" ALTER COLUMN "id" TYPE uuid USING "id"::uuid`);+ }++ for (const fk of this.sessionFks) {+ if (!(await queryRunner.hasTable(fk.table))) continue;+ await queryRunner.query(+ `ALTER TABLE "${fk.table}" ALTER COLUMN "${fk.column}" TYPE uuid USING "${fk.column}"::uuid`,+ );+ }++ for (const fk of this.sessionFks) {+ if (!(await queryRunner.hasTable(fk.table))) continue;+ await queryRunner.query(+ `ALTER TABLE "${fk.table}" ADD CONSTRAINT "${fk.name}" ` ++ `FOREIGN KEY ("${fk.column}") REFERENCES "sessions" ("id") ON DELETE CASCADE ON UPDATE NO ACTION`,+ );+ }++ for (const t of this.uuidPkTables) {+ if (!(await queryRunner.hasTable(t))) continue;+ await queryRunner.query(`ALTER TABLE "${t}" ALTER COLUMN "id" SET DEFAULT gen_random_uuid()`);+ }+ }++ // --- helpers ---++ private async columnIsUuid(queryRunner: QueryRunner, table: string, column: string): Promise<boolean> {+ const rows = (await queryRunner.query(+ `SELECT udt_name FROM information_schema.columns ` ++ `WHERE table_schema = current_schema() AND table_name = $1 AND column_name = $2`,+ [table, column],+ )) as { udt_name?: string }[] | undefined;+ return rows?.[0]?.udt_name === 'uuid';+ }++ // Schema-scoped on BOTH sides so a custom POSTGRES_SCHEMA (search_path `<schema>,public`) does not match+ // a namesake table in public. current_schema() returns the first existing schema in the path.+ private async fkConstraintNames(+ queryRunner: QueryRunner,+ table: string,+ column: string,+ referenced: string,+ ): Promise<string[]> {+ const rows = (await queryRunner.query(+ `SELECT c.conname FROM pg_constraint c ` ++ `JOIN pg_class cl ON c.conrelid = cl.oid JOIN pg_namespace n ON cl.relnamespace = n.oid ` ++ `JOIN pg_attribute a ON a.attrelid = cl.oid AND a.attnum = ANY(c.conkey) ` ++ `JOIN pg_class ref ON c.confrelid = ref.oid JOIN pg_namespace rn ON ref.relnamespace = rn.oid ` ++ `WHERE c.contype = 'f' AND n.nspname = current_schema() AND cl.relname = $1 ` ++ `AND a.attname = $2 AND rn.nspname = current_schema() AND ref.relname = $3`,+ [table, column, referenced],+ )) as { conname: string }[] | undefined;+ return (rows ?? []).map(r => r.conname);+ }++ // gen_random_uuid() is core on PG13+; pgcrypto on <=12. This migration sets varchar DEFAULTs before+ // AddUuidDefaultsForPostgres/AddIntegrationUuidDefaults, so it owns the gate (mirrors their logic).+ private async ensureGenRandomUuid(queryRunner: QueryRunner): Promise<void> {+ const v = (await queryRunner.query(`SELECT current_setting('server_version_num')::int AS num`)) as+ { num?: number | string }[] | undefined;+ const num = Number(v?.[0]?.num ?? 0);+ if (num > 0 && num < 130000) {+ const installed = (await queryRunner.query(`SELECT 1 FROM pg_extension WHERE extname = 'pgcrypto'`)) as+ unknown[] | undefined;+ if (!installed?.length) {+ try {+ await queryRunner.query(`CREATE EXTENSION IF NOT EXISTS pgcrypto`);+ } catch (err) {+ throw new Error(+ `PostgreSQL ${num} (< 13) needs the pgcrypto extension for gen_random_uuid(), but it is ` ++ `not installed and this database role cannot create it. Have a superuser run ` ++ `"CREATE EXTENSION pgcrypto;" once, then restart.`,+ { cause: err },+ );+ }+ }+ }+ }+}diff --git a/src/database/migrations/__tests__/1770200000000-NormalizeSynchronizeUuidColumns.spec.ts b/src/database/migrations/__tests__/1770200000000-NormalizeSynchronizeUuidColumns.spec.tsnew file mode 100644index 000000000..62a6b6a9b--- /dev/null+++ b/src/database/migrations/__tests__/1770200000000-NormalizeSynchronizeUuidColumns.spec.ts@@ -0,0 +1,263 @@+// Colocated in migrations/__tests__/ — the TypeORM migrations glob (`migrations/*{.ts,.js}`) matches+// only direct children, so this subdir is NOT loaded as a migration by the CLI/start:dev.+//+// This migration is Postgres-only (SQLite early-returns), so a real in-memory SQLite DataSource+// cannot exercise the conversion path. We mock the QueryRunner and script its catalog-query responses+// (information_schema.columns, pg_constraint, server_version_num, pg_extension) the way a+// synchronize-built PG schema would answer, then assert the exact DDL sequence.+import { QueryRunner } from 'typeorm';+import { NormalizeSynchronizeUuidColumns1770200000000 } from '../1770200000000-NormalizeSynchronizeUuidColumns';++const PK_TABLES = [+ 'sessions',+ 'webhooks',+ 'messages',+ 'message_batches',+ 'templates',+ 'baileys_stored_messages',+ 'webhook_delivery_failures',+ 'conversation_mappings',+ 'integration_delivery_failures',+];++const SESSION_FKS = [+ { table: 'webhooks', column: 'sessionId' },+ { table: 'templates', column: 'sessionId' },+ { table: 'baileys_stored_messages', column: 'sessionId' },+];++interface SchemaOpts {+ type: string;+ existingTables?: Set<string>;+ /** "table.column" keys that are native uuid on this schema. */+ uuidColumns?: Set<string>;+ /** "table.column" -> FK constraint names currently referencing sessions(id). */+ fkConstraints?: Record<string, string[]>;+ versionNum?: number; // server_version_num (150000 = PG15, 120000 = PG12)+ extInstalled?: boolean;+}++function makeQueryRunner(opts: SchemaOpts) {+ const {+ type,+ existingTables = new Set([...PK_TABLES, ...SESSION_FKS.map(f => f.table)]),+ uuidColumns = new Set<string>(),+ fkConstraints = {},+ versionNum = 150000,+ extInstalled = true,+ } = opts;++ const query = jest.fn((sql: string, params?: unknown[]) => {+ const s = String(sql);+ if (/information_schema\.columns/i.test(s)) {+ const [table, column] = (params ?? []) as string[];+ const isUuid = uuidColumns.has(`${table}.${column}`);+ return Promise.resolve([{ udt_name: isUuid ? 'uuid' : 'varchar' }]);+ }+ if (/pg_constraint/i.test(s)) {+ const [table, column] = (params ?? []) as string[];+ return Promise.resolve((fkConstraints[`${table}.${column}`] ?? []).map(conname => ({ conname })));+ }+ if (/server_version_num/i.test(s)) return Promise.resolve([{ num: versionNum }]);+ if (/pg_extension/i.test(s)) return Promise.resolve(extInstalled ? [{ ok: 1 }] : []);+ return Promise.resolve(undefined);+ });++ return {+ connection: { options: { type } },+ hasTable: jest.fn((t: string) => Promise.resolve(existingTables.has(t))),+ query,+ };+}++const sqlOf = (qr: ReturnType<typeof makeQueryRunner>): string[] =>+ qr.query.mock.calls.map(call => String((call as unknown[])[0]));++const idxOf = (calls: string[], re: RegExp): number => calls.findIndex(q => re.test(q));++describe('NormalizeSynchronizeUuidColumns migration', () => {+ const migration = new NormalizeSynchronizeUuidColumns1770200000000();++ // ---- name convention (load-bearing for TypeORM sort + the PG-migrations CI gate) ----+ it('class name and .name both end in the 13-digit timestamp 1770200000000', () => {+ expect(NormalizeSynchronizeUuidColumns1770200000000.name.endsWith('1770200000000')).toBe(true);+ expect(migration.name.endsWith('1770200000000')).toBe(true);+ });++ // ---- SQLite: absolute no-op ----+ it('is a no-op on SQLite — issues no query and never probes tables', async () => {+ const qr = makeQueryRunner({ type: 'sqlite', uuidColumns: new Set(['sessions.id']) });+ await migration.up(qr as unknown as QueryRunner);+ expect(qr.query).not.toHaveBeenCalled();+ expect(qr.hasTable).not.toHaveBeenCalled();+ });++ // ---- healthy Postgres (already varchar): single probe, zero DDL ----+ it('on a healthy (varchar) Postgres schema probes only sessions.id once and issues no DDL', async () => {+ const qr = makeQueryRunner({ type: 'postgres', uuidColumns: new Set() });+ await migration.up(qr as unknown as QueryRunner);++ const calls = sqlOf(qr);+ expect(calls).toHaveLength(1);+ expect(calls[0]).toMatch(/information_schema\.columns/);+ expect(calls.some(q => /ALTER TABLE|DROP CONSTRAINT|ADD CONSTRAINT|SET LOCAL/i.test(q))).toBe(false);+ });++ // ---- full conversion of a synchronize-built (uuid) schema ----+ it('converts every uuid PK + session-FK to varchar and recreates the 3 CASCADE FKs', async () => {+ const discoveredHashes: Record<string, string[]> = {+ 'webhooks.sessionId': ['FK_53208331c90e332d3f13780729c'],+ 'templates.sessionId': ['FK_55c1dfd945d2c552a5313b25460'],+ 'baileys_stored_messages.sessionId': ['FK_9a8b7c6d5e4f3a2b1c0d9e8f7a6b'],+ };+ const uuidCols = new Set<string>([+ ...PK_TABLES.map(t => `${t}.id`),+ ...SESSION_FKS.map(f => `${f.table}.${f.column}`),+ ]);+ const qr = makeQueryRunner({ type: 'postgres', uuidColumns: uuidCols, fkConstraints: discoveredHashes });+ await migration.up(qr as unknown as QueryRunner);++ const calls = sqlOf(qr);++ // PG13+: no extension touch.+ expect(calls.some(q => /CREATE EXTENSION/i.test(q))).toBe(false);++ // statement_timeout lifted for the rewrite.+ expect(calls.some(q => /SET LOCAL statement_timeout\s*=\s*0/i.test(q))).toBe(true);++ // Every discovered sync-hash FK dropped; every canonical FK re-added.+ for (const hash of Object.values(discoveredHashes).flat()) {+ expect(calls.some(q => new RegExp(`DROP CONSTRAINT IF EXISTS "${hash}"`).test(q))).toBe(true);+ }+ for (const canon of [+ 'FK_d209715bb62b12255e825580af6',+ 'FK_templates_sessionId',+ 'FK_baileys_stored_messages_sessionId',+ ]) {+ expect(calls.some(q => new RegExp(`ADD CONSTRAINT "${canon}"`).test(q))).toBe(true);+ }++ // Every PK converted (DROP DEFAULT immediately before its TYPE change), every session-FK converted.+ for (const t of PK_TABLES) {+ const dropIdx = idxOf(calls, new RegExp(`ALTER TABLE "${t}" ALTER COLUMN "id" DROP DEFAULT`));+ const typeIdx = idxOf(calls, new RegExp(`ALTER TABLE "${t}" ALTER COLUMN "id" TYPE varchar USING "id"::text`));+ expect(dropIdx).toBeGreaterThanOrEqual(0);+ expect(typeIdx).toBeGreaterThan(dropIdx); // DROP DEFAULT precedes ALTER TYPE (uuid default not varchar-coercible)+ expect(+ calls.some(q =>+ new RegExp(`ALTER TABLE "${t}" ALTER COLUMN "id" SET DEFAULT gen_random_uuid\\(\\)::varchar`).test(q),+ ),+ ).toBe(true);+ }+ for (const f of SESSION_FKS) {+ expect(+ calls.some(q =>+ new RegExp(`ALTER TABLE "${f.table}" ALTER COLUMN "${f.column}" TYPE varchar USING "${f.column}"::text`).test(+ q,+ ),+ ),+ ).toBe(true);+ }+ });++ // ---- the load-bearing ordering invariant (Test E) ----+ it('drops ALL session-FKs BEFORE converting the sessions.id PK they reference', async () => {+ const uuidCols = new Set<string>([+ ...PK_TABLES.map(t => `${t}.id`),+ ...SESSION_FKS.map(f => `${f.table}.${f.column}`),+ ]);+ const qr = makeQueryRunner({+ type: 'postgres',+ uuidColumns: uuidCols,+ fkConstraints: {+ 'webhooks.sessionId': ['FK_w'],+ 'templates.sessionId': ['FK_t'],+ 'baileys_stored_messages.sessionId': ['FK_b'],+ },+ });+ await migration.up(qr as unknown as QueryRunner);++ const calls = sqlOf(qr);+ const lastDrop = Math.max(+ idxOf(calls, /DROP CONSTRAINT IF EXISTS "FK_w"/),+ idxOf(calls, /DROP CONSTRAINT IF EXISTS "FK_t"/),+ idxOf(calls, /DROP CONSTRAINT IF EXISTS "FK_b"/),+ );+ const firstPkType = idxOf(calls, /ALTER TABLE "sessions" ALTER COLUMN "id" TYPE varchar/);+ expect(lastDrop).toBeGreaterThanOrEqual(0);+ expect(firstPkType).toBeGreaterThan(lastDrop); // cannot ALTER the referenced PK while a uuid FK still points at it+ });++ // ---- per-column idempotency: a partially-drifted table is skipped for TYPE but still gets its DEFAULT ----+ it('skips ALTER TYPE on an already-varchar column but still sets its DEFAULT (partial drift)', async () => {+ const uuidCols = new Set<string>([+ ...PK_TABLES.filter(t => t !== 'messages').map(t => `${t}.id`), // messages.id already varchar+ ...SESSION_FKS.map(f => `${f.table}.${f.column}`),+ ]);+ const qr = makeQueryRunner({ type: 'postgres', uuidColumns: uuidCols, fkConstraints: {} });+ await migration.up(qr as unknown as QueryRunner);++ const calls = sqlOf(qr);+ expect(calls.some(q => /ALTER TABLE "messages" ALTER COLUMN "id" TYPE varchar/.test(q))).toBe(false);+ expect(calls.some(q => /ALTER TABLE "messages" ALTER COLUMN "id" DROP DEFAULT/.test(q))).toBe(false);+ // DEFAULT set unconditionally (idempotent) for every existing PK table.+ expect(+ calls.some(q => /ALTER TABLE "messages" ALTER COLUMN "id" SET DEFAULT gen_random_uuid\(\)::varchar/.test(q)),+ ).toBe(true);+ // other PKs still converted+ expect(calls.some(q => /ALTER TABLE "sessions" ALTER COLUMN "id" TYPE varchar/.test(q))).toBe(true);+ });++ // ---- absent tables (older sync snapshot) are skipped ----+ it('skips tables that do not exist (e.g. an older sync snapshot without templates)', async () => {+ const uuidCols = new Set<string>(['sessions.id', 'webhooks.id', 'messages.id', 'message_batches.id']);+ const qr = makeQueryRunner({+ type: 'postgres',+ existingTables: new Set(['sessions', 'webhooks', 'messages', 'message_batches']),+ uuidColumns: uuidCols,+ fkConstraints: { 'webhooks.sessionId': ['FK_w'] },+ });+ await migration.up(qr as unknown as QueryRunner);++ const calls = sqlOf(qr);+ expect(calls.some(q => /"templates"/.test(q))).toBe(false);+ expect(calls.some(q => /ALTER TABLE "sessions" ALTER COLUMN "id" TYPE varchar/.test(q))).toBe(true);+ });++ // ---- down(): inverts to native uuid (best-effort; validates via ::uuid cast) ----+ it('down() converts varchar back to native uuid and recreates the CASCADE FKs', async () => {+ const qr = makeQueryRunner({+ type: 'postgres',+ uuidColumns: new Set(), // post-up state: all varchar+ fkConstraints: {+ 'webhooks.sessionId': ['FK_d209715bb62b12255e825580af6'],+ 'templates.sessionId': ['FK_templates_sessionId'],+ 'baileys_stored_messages.sessionId': ['FK_baileys_stored_messages_sessionId'],+ },+ });+ await migration.down(qr as unknown as QueryRunner);++ const calls = sqlOf(qr);+ expect(calls.some(q => /ALTER TABLE "sessions" ALTER COLUMN "id" TYPE uuid USING "id"::uuid/.test(q))).toBe(true);+ for (const f of SESSION_FKS) {+ expect(+ calls.some(q =>+ new RegExp(`ALTER TABLE "${f.table}" ALTER COLUMN "${f.column}" TYPE uuid USING "${f.column}"::uuid`).test(q),+ ),+ ).toBe(true);+ }+ for (const canon of [+ 'FK_d209715bb62b12255e825580af6',+ 'FK_templates_sessionId',+ 'FK_baileys_stored_messages_sessionId',+ ]) {+ expect(calls.some(q => new RegExp(`ADD CONSTRAINT "${canon}"`).test(q))).toBe(true);+ }+ });++ it('down() is a no-op on SQLite', async () => {+ const qr = makeQueryRunner({ type: 'sqlite' });+ await migration.down(qr as unknown as QueryRunner);+ expect(qr.query).not.toHaveBeenCalled();+ });+});