Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(db): quote mediaPath in the partial index predicate
Yudhi Armyndhariscd4932caae24
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex d52c68acb..ad84c9e4c 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -234,15 +234,19 @@ jobs:# Runtime-proves BuiltInFtsProvider on Postgres (websearch_to_tsquery + ts_headline against the# STORED body_ts tsvector), the boot-migration advisory lock (two concurrent migrators on one- # database), and that a paged message list has a total order (Postgres sorts a tie group- # differently between two statements, so an unstable order drops rows from a page walk). All- # three self-skip unless DATABASE_TYPE=postgres, so they are a no-op in the default test job- # and only execute here against the postgres:16 service.- - name: Postgres specs (FTS provider + boot-migration lock + list ordering)+ # database), that a paged message list has a total order (Postgres sorts a tie group+ # differently between two statements, so an unstable order drops rows from a page walk), and+ # that the data entities can build their own schema (raw SQL the ORM passes through verbatim,+ # such as a partial index predicate, only case-folds on a real server). All four self-skip+ # unless DATABASE_TYPE=postgres, so they are a no-op in the default test job and only execute+ # here against the postgres:16 service.+ - name: Postgres specs (FTS provider + boot-migration lock + list ordering + entity synchronize)# --runInBand: the specs issue DDL against the one shared service database, and jest's# default file-parallelism races their catalog writes (pg_type duplicate-key). The lock- # spec's own two-migrator race is in-file (Promise.all) and unaffected by runInBand.- run: npx jest --runInBand src/database/migrations/__tests__/1782400000000-AddMessagesFts.pg.spec.ts src/database/migrations/__tests__/pg-boot-migrations.pg.spec.ts src/modules/message/message-list-ordering.pg.spec.ts+ # spec's own two-migrator race is in-file (Promise.all) and unaffected by runInBand. The+ # synchronize spec additionally CREATEs and DROPs a scratch database of its own, which is+ # only safe serialized.+ run: npx jest --runInBand src/database/migrations/__tests__/1782400000000-AddMessagesFts.pg.spec.ts src/database/migrations/__tests__/pg-boot-migrations.pg.spec.ts src/modules/message/message-list-ordering.pg.spec.ts src/database/migrations/__tests__/pg-entity-synchronize.pg.spec.tsenv:DATABASE_TYPE: postgresDATABASE_HOST: localhostdiff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 144e9c4c6..0c47d49d3 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -216,16 +216,18 @@ jobs:# Runtime-proves BuiltInFtsProvider on Postgres (websearch_to_tsquery + ts_headline against the# STORED body_ts tsvector), the boot-migration advisory lock (two concurrent migrators on one- # database), and that a paged message list has a total order. All three self-skip unless- # DATABASE_TYPE=postgres, so they are a no-op in the default test job and only execute here- # against the postgres:16 service.- - name: Postgres specs (FTS provider + boot-migration lock + list ordering)+ # database), that a paged message list has a total order, and that the data entities can build+ # their own schema (raw SQL the ORM passes through verbatim, such as a partial index predicate,+ # only case-folds on a real server). All four self-skip unless DATABASE_TYPE=postgres, so they+ # are a no-op in the default test job and only execute here against the postgres:16 service.+ - name: Postgres specs (FTS provider + boot-migration lock + list ordering + entity synchronize)# --runInBand: same reason the CI job passes it — both specs issue DDL against the one# shared service database, and jest's default file-parallelism races their catalog writes# (the first v0.19.0 tag failed this step on `relation "messages" already exists` over a# tree CI had passed minutes earlier). The lock spec's own two-migrator race is in-file- # (Promise.all) and unaffected by runInBand.- run: npx jest --runInBand src/database/migrations/__tests__/1782400000000-AddMessagesFts.pg.spec.ts src/database/migrations/__tests__/pg-boot-migrations.pg.spec.ts src/modules/message/message-list-ordering.pg.spec.ts+ # (Promise.all) and unaffected by runInBand. The synchronize spec additionally CREATEs and+ # DROPs a scratch database of its own, which is only safe serialized.+ run: npx jest --runInBand src/database/migrations/__tests__/1782400000000-AddMessagesFts.pg.spec.ts src/database/migrations/__tests__/pg-boot-migrations.pg.spec.ts src/modules/message/message-list-ordering.pg.spec.ts src/database/migrations/__tests__/pg-entity-synchronize.pg.spec.tsenv:DATABASE_TYPE: postgresDATABASE_HOST: localhostdiff --git a/src/database/migrations/__tests__/pg-entity-synchronize.pg.spec.ts b/src/database/migrations/__tests__/pg-entity-synchronize.pg.spec.tsnew file mode 100644index 000000000..34cb54807--- /dev/null+++ b/src/database/migrations/__tests__/pg-entity-synchronize.pg.spec.ts@@ -0,0 +1,96 @@+/* istanbul ignore file -- PG-gated: only runs under DATABASE_TYPE=postgres (test-postgres CI job);+ skipped in the default test job, so its lines would be unread and skew the global coverage gate. */+import 'reflect-metadata';+import { DataSource, DataSourceOptions } from 'typeorm';+import { join } from 'path';++/**+ * Entity metadata builds a PostgreSQL schema (synchronize gate).+ *+ * Raw SQL that TypeORM passes through VERBATIM is not checked by any other suite. A partial index+ * predicate is the case that bit: `@Index(name, { where: 'mediaPath IS NOT NULL' })` reaches the+ * server unquoted, PostgreSQL folds the bare identifier to lower case, and CREATE INDEX fails with+ * `column "mediapath" does not exist`. Quoting the column in the predicate is the fix.+ *+ * Nothing caught it. The migration-chain suites run on better-sqlite3, which does not case-fold, so+ * they pass either way. The drift gate (migration-drift.spec.ts) cannot see it either, in any+ * dialect: TypeORM's schema differ does not compare predicate TEXT, so an unquoted `where` reports+ * zero drift against a chain-built schema that carries the quoted one. Verified against postgres:16,+ * both forms report the same (empty) mediaPath drift.+ *+ * This suite closes that gap the only way that actually fails: it runs synchronize itself. The+ * entity set is the whole `data` connection rather than Message alone, so any future entity that+ * embeds an unquoted identifier in raw SQL fails here too, not just the one that prompted it.+ *+ * Deployments never take this path. app.module.ts leaves the Postgres data connection on+ * migrations, and env.validation.ts rejects DATABASE_SYNCHRONIZE=true with DATABASE_TYPE=postgres+ * outright. What breaks is any DataSource built on these entities with synchronize enabled, which+ * is the natural shape for a Postgres harness written against the real entities.+ *+ * Runs on its OWN database: synchronize builds a schema from entity metadata, which must not land+ * on the migration-built database the sibling PG specs share.+ */+const POSTGRES_ENABLED = process.env.DATABASE_TYPE === 'postgres';++/** Named for the suite so a crashed run leaves an obvious orphan rather than a mystery database. */+const SCRATCH_DB = 'openwa_entity_synchronize_probe';++const repoRoot = join(__dirname, '../../../..');++/** The `data` connection's entity set, mirroring app.module.ts and data-source.ts. */+const dataEntities = [+ join(repoRoot, 'src/modules/session/**/*.entity{.ts,.js}'),+ join(repoRoot, 'src/modules/webhook/**/*.entity{.ts,.js}'),+ join(repoRoot, 'src/modules/message/**/*.entity{.ts,.js}'),+ join(repoRoot, 'src/modules/template/**/*.entity{.ts,.js}'),+ join(repoRoot, 'src/engine/**/*.entity{.ts,.js}'),+ join(repoRoot, 'src/modules/integration/**/*.entity{.ts,.js}'),+ join(repoRoot, 'src/modules/status-store/**/*.entity{.ts,.js}'),+ join(repoRoot, 'src/modules/automation/**/*.entity{.ts,.js}'),+];++const connection = (database: string): DataSourceOptions => ({+ type: 'postgres',+ host: process.env.DATABASE_HOST || 'localhost',+ port: Number(process.env.DATABASE_PORT || 5432),+ username: process.env.DATABASE_USERNAME || 'openwa',+ password: process.env.DATABASE_PASSWORD || 'openwa',+ database,+});++(POSTGRES_ENABLED ? describe : describe.skip)('data entities synchronize onto PostgreSQL', () => {+ let admin: DataSource;+ let scratch: DataSource | undefined;++ beforeAll(async () => {+ admin = new DataSource(connection(process.env.DATABASE_NAME || 'openwa'));+ await admin.initialize();+ // CREATE/DROP DATABASE cannot run inside a transaction, so they are issued on the admin+ // connection rather than through a query runner.+ await admin.query(`DROP DATABASE IF EXISTS "${SCRATCH_DB}"`);+ await admin.query(`CREATE DATABASE "${SCRATCH_DB}"`);+ }, 60_000);++ afterAll(async () => {+ await scratch?.destroy().catch(() => undefined);+ await admin?.query(`DROP DATABASE IF EXISTS "${SCRATCH_DB}"`).catch(() => undefined);+ await admin?.destroy().catch(() => undefined);+ });++ it('builds the whole schema, quoting the mediaPath partial index predicate', async () => {+ scratch = new DataSource({ ...connection(SCRATCH_DB), entities: dataEntities, synchronize: true });++ // The assertion IS initialize(): an unquoted identifier in any entity's raw SQL rejects here+ // with `column "<folded name>" does not exist` before a single expect() runs.+ await scratch.initialize();++ const indexes = await scratch.query<{ indexdef: string }[]>(+ `SELECT indexdef FROM pg_indexes WHERE indexname = 'IDX_messages_mediaPath'`,+ );++ // Read back from the catalog, not from the entity: this is what the server actually stored, and+ // it is the form the migration that owns the same index name produces.+ expect(indexes).toHaveLength(1);+ expect(indexes[0].indexdef).toContain('WHERE ("mediaPath" IS NOT NULL)');+ }, 120_000);+});diff --git a/src/modules/message/entities/message.entity.ts b/src/modules/message/entities/message.entity.tsindex c1b44550b..f34c2338f 100644--- a/src/modules/message/entities/message.entity.ts+++ b/src/modules/message/entities/message.entity.ts@@ -98,7 +98,10 @@ export class Message {// every un-archived row (archiving is opt-in), so the WHERE clause keeps the index to rows that// can ever match. The explicit name matches the migration that creates it on synchronize-disabled// deployments, so both schema paths converge on one index.- @Index('IDX_messages_mediaPath', { where: 'mediaPath IS NOT NULL' })+ // The column name is QUOTED in the predicate on purpose: PostgreSQL folds a bare identifier to+ // lower case, so `mediaPath IS NOT NULL` makes synchronize fail on `column "mediapath" does not+ // exist`. The migration below already quotes it, so this is also what keeps the two in step.+ @Index('IDX_messages_mediaPath', { where: '"mediaPath" IS NOT NULL' })@Column({ nullable: true })mediaPath?: string;