Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

feat(database): add Postgres schema selection support (#651)

LikKee Richie02f7bc71c2ea
diff --git a/.env.example b/.env.example
index 86fad7f84..1ba7f4ad3 100644
--- a/.env.example
+++ b/.env.example
@@ -136,6 +136,12 @@ POSTGRES_BUILTIN=false # Use built-in PostgreSQL container?
DATABASE_HOST=localhost
DATABASE_PORT=5432
DATABASE_NAME=openwa
+# PostgreSQL schema (ignored for sqlite). Default 'public' keeps the historical behavior.
+# Set to a dedicated schema to isolate OpenWA's tables + migration ledger (e.g. on managed
+# Postgres where you get a project schema, or to share one DB across apps). The schema must
+# already exist — the built-in container creates it; for external/managed Postgres create it
+# once (CREATE SCHEMA openwa;). A missing schema fails fast at migration time.
+POSTGRES_SCHEMA=public
DATABASE_USERNAME=openwa
# MUST set a strong, unique value before using Postgres — no default is shipped.
# Production refuses to start if this is empty or a known placeholder when DATABASE_TYPE=postgres.
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a41004241..0942a3a9c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,7 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
-- **Opt-in `VALIDATION_ERROR_DETAIL`** exposes field-level validation error messages on `400` responses (hidden by default in production, where a bad request otherwise returns a generic message so the DTO shape isn't reflected back). Set it to `true` to debug an SDK/integration against a production instance without flipping `NODE_ENV`, or `false` to force it off everywhere.
+- **PostgreSQL schema selection via `POSTGRES_SCHEMA`.** OpenWA's tables and the TypeORM migration ledger can now be placed in a dedicated Postgres schema (default `public` preserves historical behavior). Set `POSTGRES_SCHEMA` to isolate OpenWA from other apps sharing a database, or to use a managed-Postgres project schema. The schema must already exist (the built-in container creates it; for external Postgres run `CREATE SCHEMA <name>;` once). SQLite ignores this setting. The dashboard Infrastructure page exposes the field, and the environment variable is validated as a legal, non-reserved Postgres identifier at boot.
### Changed
diff --git a/dashboard/package-lock.json b/dashboard/package-lock.json
index fb9b9bca6..70df9e72e 100644
--- a/dashboard/package-lock.json
+++ b/dashboard/package-lock.json
@@ -700,9 +700,6 @@
"arm64"
],
"dev": true,
- "libc": [
- "glibc"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -720,9 +717,6 @@
"arm64"
],
"dev": true,
- "libc": [
- "musl"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -740,9 +734,6 @@
"ppc64"
],
"dev": true,
- "libc": [
- "glibc"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -760,9 +751,6 @@
"s390x"
],
"dev": true,
- "libc": [
- "glibc"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -780,9 +768,6 @@
"x64"
],
"dev": true,
- "libc": [
- "glibc"
- ],
"license": "MIT",
"optional": true,
"os": [
@@ -800,9 +785,6 @@
"x64"
],
"dev": true,
- "libc": [
- "musl"
- ],
"license": "MIT",
"optional": true,
"os": [
diff --git a/dashboard/src/i18n/locales/ar.json b/dashboard/src/i18n/locales/ar.json
index e03408890..94f4656df 100644
--- a/dashboard/src/i18n/locales/ar.json
+++ b/dashboard/src/i18n/locales/ar.json
@@ -594,6 +594,8 @@
"useBuiltIn": "استخدام حاوية PostgreSQL المدمجة",
"builtInDesc": "سيدير OpenWA حاوية PostgreSQL نيابةً عنك",
"dbName": "اسم قاعدة البيانات",
+ "schema": "المخطط",
+ "schemaDesc": "مخطط PostgreSQL (يُتجاهل لـ SQLite). الافتراضي 'public'. يجب أن يكون المخطط موجوداً مسبقاً.",
"poolSize": "حجم المجموعة",
"ssl": "اتصال SSL",
"sslDesc": "تفعيل TLS/SSL لاتصالات آمنة بقاعدة البيانات",
diff --git a/dashboard/src/i18n/locales/en.json b/dashboard/src/i18n/locales/en.json
index f27dd0c9c..968ed1dae 100644
--- a/dashboard/src/i18n/locales/en.json
+++ b/dashboard/src/i18n/locales/en.json
@@ -590,6 +590,8 @@
"useBuiltIn": "Use Built-in PostgreSQL Container",
"builtInDesc": "OpenWA will manage a PostgreSQL container for you",
"dbName": "Database Name",
+ "schema": "Schema",
+ "schemaDesc": "PostgreSQL schema (ignored for SQLite). Default 'public'. The schema must already exist.",
"poolSize": "Pool Size",
"ssl": "SSL Connection",
"sslDesc": "Enable TLS/SSL for secure database connections",
diff --git a/dashboard/src/i18n/locales/es.json b/dashboard/src/i18n/locales/es.json
index 2e52f0a0e..1cab0b26b 100644
--- a/dashboard/src/i18n/locales/es.json
+++ b/dashboard/src/i18n/locales/es.json
@@ -590,6 +590,8 @@
"useBuiltIn": "Usar contenedor PostgreSQL integrado",
"builtInDesc": "OpenWA gestionará un contenedor PostgreSQL por ti",
"dbName": "Nombre de la base de datos",
+ "schema": "Esquema",
+ "schemaDesc": "Esquema de PostgreSQL (ignorado para SQLite). Predeterminado 'public'. El esquema debe existir previamente.",
"poolSize": "Tamaño del pool",
"ssl": "Conexión SSL",
"sslDesc": "Habilitar TLS/SSL para conexiones seguras a la base de datos",
diff --git a/dashboard/src/i18n/locales/fr.json b/dashboard/src/i18n/locales/fr.json
index 2ca21e49c..9831e1d28 100644
--- a/dashboard/src/i18n/locales/fr.json
+++ b/dashboard/src/i18n/locales/fr.json
@@ -590,6 +590,8 @@
"useBuiltIn": "Utiliser le conteneur PostgreSQL intégré",
"builtInDesc": "OpenWA gérera un conteneur PostgreSQL pour vous",
"dbName": "Nom de la base de données",
+ "schema": "Schéma",
+ "schemaDesc": "Schéma PostgreSQL (ignoré pour SQLite). Par défaut 'public'. Le schéma doit déjà exister.",
"poolSize": "Taille du pool",
"ssl": "Connexion SSL",
"sslDesc": "Activer TLS/SSL pour des connexions sécurisées à la base de données",
diff --git a/dashboard/src/i18n/locales/he.json b/dashboard/src/i18n/locales/he.json
index 2b80874c3..0693d1f28 100644
--- a/dashboard/src/i18n/locales/he.json
+++ b/dashboard/src/i18n/locales/he.json
@@ -591,6 +591,8 @@
"useBuiltIn": "שימוש בקונטיינר PostgreSQL מובנה",
"builtInDesc": "OpenWA ינהל עבורך קונטיינר PostgreSQL",
"dbName": "שם מסד הנתונים",
+ "schema": "סכמה",
+ "schemaDesc": "סכמת PostgreSQL (לא חלה על SQLite). ברירת מחדל 'public'. הסכמה חייבת להיות קיימת מראש.",
"poolSize": "גודל Pool",
"ssl": "חיבור SSL",
"sslDesc": "הפעלת TLS/SSL לחיבור מאובטח למסד הנתונים",
diff --git a/dashboard/src/i18n/locales/it.json b/dashboard/src/i18n/locales/it.json
index 1b9089f99..b7558f734 100644
--- a/dashboard/src/i18n/locales/it.json
+++ b/dashboard/src/i18n/locales/it.json
@@ -590,6 +590,8 @@
"useBuiltIn": "Usa Container PostgreSQL Integrato",
"builtInDesc": "OpenWA gestirà un container PostgreSQL per te",
"dbName": "Nome Database",
+ "schema": "Schema",
+ "schemaDesc": "Schema PostgreSQL (ignorato per SQLite). Predefinito 'public'. Lo schema deve esistere già.",
"poolSize": "Dimensione del Pool",
"ssl": "Connessione SSL",
"sslDesc": "Abilita TLS/SSL per connessioni sicure al database",
diff --git a/dashboard/src/i18n/locales/pt-BR.json b/dashboard/src/i18n/locales/pt-BR.json
index ef406ab23..da5b0390d 100644
--- a/dashboard/src/i18n/locales/pt-BR.json
+++ b/dashboard/src/i18n/locales/pt-BR.json
@@ -590,6 +590,8 @@
"useBuiltIn": "Usar contêiner PostgreSQL integrado",
"builtInDesc": "OpenWA gerenciará um contêiner PostgreSQL para você",
"dbName": "Nome do banco de dados",
+ "schema": "Esquema",
+ "schemaDesc": "Esquema do PostgreSQL (ignorado para SQLite). Padrão 'public'. O esquema já deve existir.",
"poolSize": "Tamanho do pool",
"ssl": "Conexão SSL",
"sslDesc": "Habilitar TLS/SSL para conexões seguras ao banco de dados",
diff --git a/dashboard/src/i18n/locales/te.json b/dashboard/src/i18n/locales/te.json
index fc8b0066c..418171964 100644
--- a/dashboard/src/i18n/locales/te.json
+++ b/dashboard/src/i18n/locales/te.json
@@ -590,6 +590,8 @@
"useBuiltIn": "ఇన్-బిల్ట్ PostgreSQL కంటైనర్‌ను ఉపయోగించండి",
"builtInDesc": "OpenWA మీ కోసం ఒక PostgreSQL కంటైనర్‌ను నిర్వహిస్తుంది",
"dbName": "డేటాబేస్ పేరు",
+ "schema": "స్కీమా",
+ "schemaDesc": "PostgreSQL స్కీమా (SQLite కోసం వదిలివేయబడుతుంది). డిఫాల్ట్ 'public'. స్కీమా ఇప్పటికే ఉనికిలో ఉండాలి.",
"poolSize": "పూల్ సైజు",
"ssl": "SSL కనెక్షన్",
"sslDesc": "సురక్షిత డేటాబేస్ కనెక్షన్ల కోసం TLS/SSLని ప్రారంభించండి",
diff --git a/dashboard/src/i18n/locales/zh-CN.json b/dashboard/src/i18n/locales/zh-CN.json
index bbf43d865..634916ca8 100644
--- a/dashboard/src/i18n/locales/zh-CN.json
+++ b/dashboard/src/i18n/locales/zh-CN.json
@@ -590,6 +590,8 @@
"useBuiltIn": "使用内置 PostgreSQL 容器",
"builtInDesc": "OpenWA 将为你管理 PostgreSQL 容器",
"dbName": "数据库名称",
+ "schema": "模式",
+ "schemaDesc": "PostgreSQL 模式(SQLite 忽略)。默认为 'public'。该模式必须已存在。",
"poolSize": "连接池大小",
"ssl": "SSL 连接",
"sslDesc": "启用 TLS/SSL 以保障数据库连接安全",
diff --git a/dashboard/src/i18n/locales/zh-HK.json b/dashboard/src/i18n/locales/zh-HK.json
index 9453353fd..7cae754bb 100644
--- a/dashboard/src/i18n/locales/zh-HK.json
+++ b/dashboard/src/i18n/locales/zh-HK.json
@@ -590,6 +590,8 @@
"useBuiltIn": "使用內置 PostgreSQL 容器",
"builtInDesc": "OpenWA 會為你管理 PostgreSQL 容器",
"dbName": "資料庫名稱",
+ "schema": "結構描述",
+ "schemaDesc": "PostgreSQL 結構描述(SQLite 會忽略)。預設為 'public'。該結構描述必須已存在。",
"poolSize": "連線池大小",
"ssl": "SSL 連線",
"sslDesc": "啟用 TLS/SSL 以保障資料庫連線安全",
diff --git a/dashboard/src/pages/Infrastructure.css b/dashboard/src/pages/Infrastructure.css
index 8f44cc912..8a9709fe7 100644
--- a/dashboard/src/pages/Infrastructure.css
+++ b/dashboard/src/pages/Infrastructure.css
@@ -208,6 +208,12 @@
border-color: var(--primary);
}
+.infrastructure-page .form-group small{
+ font-size: 0.75rem;
+ color: var(--text-muted);
+ opacity: 0.85;
+}
+
/* Toggle */
.infrastructure-page .toggle-row{
display: flex;
diff --git a/dashboard/src/pages/Infrastructure.tsx b/dashboard/src/pages/Infrastructure.tsx
index e6a1ad3ec..18e20a3fa 100644
--- a/dashboard/src/pages/Infrastructure.tsx
+++ b/dashboard/src/pages/Infrastructure.tsx
@@ -39,6 +39,7 @@ interface DatabaseConfig {
username: string;
password: string;
database: string;
+ schema: string;
poolSize: number;
sslEnabled: boolean;
sslRejectUnauthorized: boolean;
@@ -98,6 +99,7 @@ export function Infrastructure() {
username: 'postgres',
password: '',
database: 'openwa',
+ schema: 'public',
poolSize: 10,
sslEnabled: false,
sslRejectUnauthorized: true,
@@ -202,6 +204,7 @@ export function Infrastructure() {
port: savedConfig.database.port || prev.port,
username: savedConfig.database.username || prev.username,
database: savedConfig.database.database || prev.database,
+ schema: savedConfig.database.schema || prev.schema,
poolSize: savedConfig.database.poolSize,
sslEnabled: savedConfig.database.sslEnabled,
sslRejectUnauthorized: savedConfig.database.sslRejectUnauthorized,
@@ -568,6 +571,18 @@ export function Infrastructure() {
/>
</div>
</div>
+ <div className="form-row">
+ <div className="form-group">
+ <label>{t('infrastructure.database.schema')}</label>
+ <input
+ type="text"
+ value={dbConfig.schema}
+ onChange={e => updateDbConfig('schema', e.target.value)}
+ placeholder="public"
+ />
+ <small>{t('infrastructure.database.schemaDesc')}</small>
+ </div>
+ </div>
<div className="toggle-row">
<div className="toggle-info">
<span>{t('infrastructure.database.ssl')}</span>
diff --git a/dashboard/src/services/api.ts b/dashboard/src/services/api.ts
index 1d66cce7b..b8c5fb3e8 100644
--- a/dashboard/src/services/api.ts
+++ b/dashboard/src/services/api.ts
@@ -237,6 +237,7 @@ export interface SavedConfig {
port: string;
username: string;
database: string;
+ schema: string;
poolSize: number;
sslEnabled: boolean;
sslRejectUnauthorized: boolean;
@@ -265,6 +266,7 @@ export interface SaveConfigPayload {
username?: string;
password?: string;
database?: string;
+ schema?: string;
poolSize?: number;
sslEnabled?: boolean;
sslRejectUnauthorized?: boolean;
diff --git a/docker-compose.yml b/docker-compose.yml
index 5766d5fd5..e1ff45042 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -99,6 +99,9 @@ services:
# No committed default secret; blank unless the operator sets it (built-in Postgres is provisioned
# with its own credentials by the orchestrator, not via this line).
- DATABASE_PASSWORD=${DATABASE_PASSWORD:-}
+ # PostgreSQL schema (blank-forwarded like the other DATABASE_* keys so a dashboard-saved
+ # POSTGRES_SCHEMA in data/.env.generated applies; a real host value pins). Ignored for sqlite.
+ - POSTGRES_SCHEMA=${POSTGRES_SCHEMA:-}
- DATABASE_SYNCHRONIZE=${DATABASE_SYNCHRONIZE:-false}
# Engine. Forwarded empty by default so the dashboard (Infrastructure > Engine) selects the
# active engine via data/.env.generated (defaults to whatsapp-web.js); main.ts treats a blank
@@ -199,8 +202,16 @@ services:
# production boot guard rejects empty/placeholder secrets before startup.
POSTGRES_PASSWORD: ${DATABASE_PASSWORD:-}
POSTGRES_DB: ${DATABASE_NAME:-openwa}
+ # PostgreSQL schema for OpenWA's tables + migration ledger. Default 'public'. The init
+ # script below creates the schema (if non-public) and sets the database default search_path,
+ # so the built-in container works zero-config with a custom schema. Ignored when 'public'.
+ POSTGRES_SCHEMA: ${POSTGRES_SCHEMA:-public}
volumes:
- postgres-data:/var/lib/postgresql/data
+ # Runs only on first init (postgres image docker-entrypoint-initdb.d semantics): creates the
+ # configured schema and sets the DB default search_path. No-op for 'public'; does not re-run
+ # on an already-initialized volume (see the note in scripts/postgres-init-schema.sh).
+ - ./scripts/postgres-init-schema.sh:/docker-entrypoint-initdb.d/01-create-schema.sh:ro
healthcheck:
test: ['CMD-SHELL', 'pg_isready -U ${DATABASE_USERNAME:-openwa}']
interval: 5s
diff --git a/docs/05-database-design.md b/docs/05-database-design.md
index 876fd0452..73d91c525 100644
--- a/docs/05-database-design.md
+++ b/docs/05-database-design.md
@@ -81,6 +81,40 @@ if (process.env.POSTGRES_BUILTIN === 'true') {
const app = await NestFactory.create(AppModule); // Then bootstrap
```
+#### PostgreSQL Schema Selection
+
+When using PostgreSQL, OpenWA can place its tables and migration ledger in a dedicated schema via the `POSTGRES_SCHEMA` environment variable:
+
+| Setting | Default | Description |
+| ------------------ | ------- | --------------------------------------------------------------------------- |
+| `POSTGRES_SCHEMA` | `public` | PostgreSQL schema for OpenWA tables and TypeORM migration ledger |
+
+**Use Cases:**
+- **Managed PostgreSQL:** Use your cloud provider's project schema (e.g., a schema provisioned by the provider)
+- **Multi-tenant databases:** Isolate OpenWA from other applications sharing the same database
+- **Clean separation:** Keep OpenWA's tables organized separately from other schemas
+
+**Configuration:**
+```bash
+# .env or dashboard Infrastructure page
+POSTGRES_SCHEMA=openwa # Use a dedicated schema
+POSTGRES_SCHEMA=public # Default behavior (historical)
+```
+
+**Requirements:**
+- The schema must already exist before migration time
+- Built-in PostgreSQL container automatically creates the schema via init script
+- External/managed PostgreSQL: run `CREATE SCHEMA <name>;` once before first startup
+- SQLite ignores this setting
+
+**Validation:**
+- Schema name is validated at boot as a legal Postgres identifier (letters, digits, underscores, max 63 chars)
+- Reserved `pg_` prefix is rejected to prevent conflicts with system schemas
+- Invalid values cause fast boot failure rather than migration-time errors
+
+> [!NOTE]
+> TypeORM's `schema` option alone does not set the session `search_path`. OpenWA additionally sets `search_path=<schema>,public` via PostgreSQL's startup `options` parameter so raw, unqualified migration DDL resolves to the configured schema. The migration ledger and all tables land in the specified schema while keeping `public` accessible for `pg_catalog` and helpers.
+
#### Data Migration API
OpenWA provides endpoints for migrating data between database types:
diff --git a/scripts/pg-uuid-smoke.js b/scripts/pg-uuid-smoke.js
index a05b92889..a54d435bb 100644
--- a/scripts/pg-uuid-smoke.js
+++ b/scripts/pg-uuid-smoke.js
@@ -16,14 +16,20 @@ const { DataSource } = require('typeorm');
const APP_GENERATED_ID_TABLES = ['ingress_events', 'plugin_instances'];
async function main() {
+ // Mirror the migration CLI (data-source.ts): a non-public POSTGRES_SCHEMA sets the session
+ // search_path so the raw, unqualified migration DDL + the typeorm_migrations ledger land in it.
+ const schema = process.env.POSTGRES_SCHEMA || 'public';
+ const useCustomSearchPath = schema !== 'public';
const ds = new DataSource({
type: 'postgres',
+ schema,
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: process.env.DATABASE_NAME || 'openwa',
migrations: [path.join(__dirname, '..', 'dist', 'database', 'migrations', '*.js')],
+ ...(useCustomSearchPath ? { extra: { options: `-c search_path=${schema},public` } } : {}),
});
await ds.initialize();
@@ -34,7 +40,8 @@ async function main() {
// missing gen_random_uuid(). This catches current AND future tables without a maintained list.
const noDefaultRows = await ds.query(
`SELECT table_name FROM information_schema.columns
- WHERE table_schema = 'public' AND column_name = 'id' AND column_default IS NULL`,
+ WHERE table_schema = $1 AND column_name = 'id' AND column_default IS NULL`,
+ [schema],
);
const offenders = noDefaultRows
.map((r) => r.table_name)
@@ -43,8 +50,8 @@ async function main() {
// Belt-and-suspenders: positively assert the two tables this migration set fixes carry a default.
for (const t of ['conversation_mappings', 'integration_delivery_failures']) {
const rows = await ds.query(
- `SELECT column_default FROM information_schema.columns WHERE table_name = $1 AND column_name = 'id'`,
- [t],
+ `SELECT column_default FROM information_schema.columns WHERE table_schema = $1 AND table_name = $2 AND column_name = 'id'`,
+ [schema, t],
);
if (!rows.length || rows[0].column_default == null) offenders.push(`${t} (expected a default, found none)`);
}
diff --git a/scripts/postgres-init-schema.sh b/scripts/postgres-init-schema.sh
new file mode 100755
index 000000000..2cb94688f
--- /dev/null
+++ b/scripts/postgres-init-schema.sh
@@ -0,0 +1,36 @@
+#!/bin/bash
+# OpenWA — built-in PostgreSQL schema init.
+#
+# Mounted at /docker-entrypoint-initdb.d/01-create-schema.sh by docker-compose.yml, so the
+# official postgres image runs it ONCE on first initialization (before any app migration).
+# It creates the configured POSTGRES_SCHEMA and sets the database default search_path so the
+# built-in container works zero-config with a custom schema — the app's TypeORM `schema` option
+# + `extra.options search_path` then resolve every table + the migration ledger into it.
+#
+# No-op when POSTGRES_SCHEMA is empty or 'public' (the default): the public schema always
+# exists and the default search_path already includes it, so there is nothing to do.
+#
+# Limitation: the postgres image only runs docker-entrypoint-initdb.d scripts on FIRST init.
+# An existing postgres-data volume will NOT re-run this script. To adopt a custom schema on an
+# already-initialized volume, create it manually once (e.g. `CREATE SCHEMA openwa;`) and set
+# POSTGRES_SCHEMA on the openwa-api service.
+set -euo pipefail
+
+schema="${POSTGRES_SCHEMA:-public}"
+
+if [ -z "$schema" ] || [ "$schema" = "public" ]; then
+ echo "postgres-init-schema: POSTGRES_SCHEMA is '${schema}' (default) — nothing to do."
+ exit 0
+fi
+
+echo "postgres-init-schema: creating schema '${schema}' and setting default search_path."
+
+# The postgres image exports POSTGRES_USER + POSTGRES_DB for docker-entrypoint-initdb.d
+# scripts; connect as the provisioning role (superuser for the fresh cluster) against the
+# just-created database. AUTHORIZATION grants ownership so the app role can create tables.
+psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" <<SQL
+CREATE SCHEMA IF NOT EXISTS "$schema" AUTHORIZATION "$POSTGRES_USER";
+ALTER DATABASE "$POSTGRES_DB" SET search_path TO "$schema", public;
+SQL
+
+echo "postgres-init-schema: done."
diff --git a/src/app.module.ts b/src/app.module.ts
index 3e4666f4e..eb5204228 100644
--- a/src/app.module.ts
+++ b/src/app.module.ts
@@ -140,10 +140,19 @@ if (dashboardServingEnabled && dashboardBuildPresent) {
};
if (dbType === 'postgres') {
+ // Schema selection: 'public' (default) is a no-op vs the historical behavior. A non-public
+ // schema additionally sets the session search_path via pg's startup `options` parameter so
+ // the project's RAW, unqualified migration SQL (CREATE TABLE "x"..., ALTER TABLE "y"...)
+ // resolves to the configured schema — TypeORM's `schema` option alone does NOT set
+ // search_path, so without this raw DDL would land in `public` while the migration ledger
+ // lands in the configured schema.
+ const schema = configService.get<string>('dataDatabase.schema', 'public');
+ const useCustomSearchPath = schema && schema !== 'public';
return {
...baseConfig,
name: 'data',
type: 'postgres' as const,
+ schema,
host: configService.get<string>('dataDatabase.host'),
port: configService.get<number>('dataDatabase.port'),
username: configService.get<string>('dataDatabase.username'),
@@ -170,6 +179,9 @@ if (dashboardServingEnabled && dashboardBuildPresent) {
statement_timeout: configService.get<number>('dataDatabase.statementTimeoutMs', 30000),
idleTimeoutMillis: configService.get<number>('dataDatabase.idleTimeoutMs', 30000),
connectionTimeoutMillis: configService.get<number>('dataDatabase.connectionTimeoutMs', 10000),
+ // Only set for a non-public schema (see above). `<schema>,public` keeps public on the
+ // path so pg_catalog + any public helpers still resolve; the configured schema wins.
+ ...(useCustomSearchPath ? { options: `-c search_path=${schema},public` } : {}),
},
};
}
diff --git a/src/common/services/logger.service.spec.ts b/src/common/services/logger.service.spec.ts
index e47764bd3..27afb547b 100644
--- a/src/common/services/logger.service.spec.ts
+++ b/src/common/services/logger.service.spec.ts
@@ -157,7 +157,8 @@ describe('LoggerService', () => {
const output = getRawOutput(errorSpy);
expect(output).toContain('Error message');
- expect(output).toContain('\nstack trace line');
+ expect(output).toContain('stack trace line');
+ expect(output).toMatch(/\n.*stack trace line/);
});
});
diff --git a/src/config/configuration.ts b/src/config/configuration.ts
index ee87b91ba..98046be81 100644
--- a/src/config/configuration.ts
+++ b/src/config/configuration.ts
@@ -44,6 +44,12 @@ export default () => ({
// DATABASE_NAME env as the migration CLI (data-source.ts) so the runtime factory and
// migrations never target different databases. Distinct sqlite-vs-pg defaults.
name: process.env.DATABASE_NAME || 'openwa',
+ // PostgreSQL schema (used when type is postgres). Default 'public' preserves the historical
+ // behavior; set POSTGRES_SCHEMA to place OpenWA's tables + the TypeORM migration ledger in a
+ // dedicated schema (e.g. a managed-Postgres project schema, or to isolate OpenWA from other
+ // apps sharing the database). The schema must already exist — a missing one fails fast at
+ // migration time rather than silently falling back to public. SQLite ignores this.
+ schema: process.env.POSTGRES_SCHEMA || 'public',
// PostgreSQL/MySQL connection (used when type is postgres/mysql)
host: process.env.DATABASE_HOST || 'localhost',
port: parseInt(process.env.DATABASE_PORT || '5432', 10),
diff --git a/src/config/env-precedence.ts b/src/config/env-precedence.ts
index b5c5b2c0b..b3a34e40f 100644
--- a/src/config/env-precedence.ts
+++ b/src/config/env-precedence.ts
@@ -26,6 +26,8 @@ export const BLANK_SHADOWED_ENV_KEYS: string[] = [
'DATABASE_USERNAME',
'DATABASE_NAME',
'DATABASE_PASSWORD',
+ // PostgreSQL schema (dashboard-managed + compose blank-forwarded, like the other DATABASE_* keys)
+ 'POSTGRES_SCHEMA',
// Storage selection + S3 details (#488)
'STORAGE_TYPE',
'STORAGE_LOCAL_PATH',
diff --git a/src/config/env.validation.spec.ts b/src/config/env.validation.spec.ts
index 30d55392b..60ded4bc3 100644
--- a/src/config/env.validation.spec.ts
+++ b/src/config/env.validation.spec.ts
@@ -18,6 +18,25 @@ describe('validateEnv', () => {
).not.toThrow();
});
+ it('validates POSTGRES_SCHEMA as a legal, non-reserved Postgres identifier when set', () => {
+ const pg = { DATABASE_TYPE: 'postgres', DATABASE_HOST: 'db', DATABASE_USERNAME: 'u', DATABASE_PASSWORD: 'p' };
+ // unset / 'public' (default) and ordinary identifiers are fine
+ expect(() => validateEnv({ ...pg })).not.toThrow();
+ expect(() => validateEnv({ ...pg, POSTGRES_SCHEMA: 'public' })).not.toThrow();
+ expect(() => validateEnv({ ...pg, POSTGRES_SCHEMA: 'openwa' })).not.toThrow();
+ expect(() => validateEnv({ ...pg, POSTGRES_SCHEMA: 'my_app_2' })).not.toThrow();
+ // invalid identifier characters (would reach CREATE TABLE "<schema>"."..." or a search_path SET)
+ expect(() => validateEnv({ ...pg, POSTGRES_SCHEMA: 'openwa; DROP' })).toThrow(/POSTGRES_SCHEMA/);
+ expect(() => validateEnv({ ...pg, POSTGRES_SCHEMA: '1bad' })).toThrow(/POSTGRES_SCHEMA/);
+ expect(() => validateEnv({ ...pg, POSTGRES_SCHEMA: 'has space' })).toThrow(/POSTGRES_SCHEMA/);
+ expect(() => validateEnv({ ...pg, POSTGRES_SCHEMA: 'a.b' })).toThrow(/POSTGRES_SCHEMA/);
+ // reserved pg_ prefix rejected (case-insensitive)
+ expect(() => validateEnv({ ...pg, POSTGRES_SCHEMA: 'pg_catalog' })).toThrow(/POSTGRES_SCHEMA/);
+ expect(() => validateEnv({ ...pg, POSTGRES_SCHEMA: 'Pg_temp' })).toThrow(/POSTGRES_SCHEMA/);
+ // ignored for sqlite: a bogus value must NOT trip when not on postgres
+ expect(() => validateEnv({ DATABASE_TYPE: 'sqlite', POSTGRES_SCHEMA: '1bad' })).not.toThrow();
+ });
+
it('rejects a non-integer / out-of-range port', () => {
expect(() => validateEnv({ DATABASE_PORT: 'abc' })).toThrow(/DATABASE_PORT/);
expect(() => validateEnv({ PORT: '70000' })).toThrow(/PORT/);
diff --git a/src/config/env.validation.ts b/src/config/env.validation.ts
index 636df5b44..d90dc2c34 100644
--- a/src/config/env.validation.ts
+++ b/src/config/env.validation.ts
@@ -45,6 +45,19 @@ export function validateEnv(config: EnvConfig): EnvConfig {
errors.push(`${key} is required when DATABASE_TYPE=postgres`);
}
}
+ // POSTGRES_SCHEMA is optional (defaults to 'public' in configuration.ts). When set, validate it
+ // is a legal, non-reserved Postgres identifier so a typo / injection-ish value fails fast at boot
+ // rather than reaching CREATE TABLE "<schema>"."..." (or a search_path SET) at migration time.
+ const pgSchema = str('POSTGRES_SCHEMA');
+ if (pgSchema !== undefined) {
+ if (!/^[A-Za-z_][A-Za-z0-9_]{0,62}$/.test(pgSchema)) {
+ errors.push(
+ `POSTGRES_SCHEMA must be a valid Postgres identifier (a letter or underscore, then letters/digits/underscores, max 63 chars; got ${JSON.stringify(pgSchema)})`,
+ );
+ } else if (pgSchema.toLowerCase().startsWith('pg_')) {
+ errors.push(`POSTGRES_SCHEMA must not use the reserved "pg_" prefix (got ${JSON.stringify(pgSchema)})`);
+ }
+ }
} else {
// SQLite (explicit or default): DATABASE_NAME is a file path for the 'data' connection. It must
// not resolve to the 'main' DB file — two TypeORM connections on one SQLite file run separate
diff --git a/src/database/data-source.spec.ts b/src/database/data-source.spec.ts
index 8170ea81c..2dafb12ce 100644
--- a/src/database/data-source.spec.ts
+++ b/src/database/data-source.spec.ts
@@ -1,5 +1,5 @@
import { globSync } from 'glob';
-import dataDataSource, { postgresDataSourceOptions } from './data-source';
+import dataDataSource, { postgresDataSourceOptions, buildPostgresDataSourceOptions } from './data-source';
// The data CLI DataSource manages the DATA connection's migrations (session/webhook/message/
// template/engine). It must NOT pull in the auth/audit entities — those belong to the always-SQLite
@@ -48,3 +48,35 @@ describe('Postgres migration connection pool timeouts', () => {
expect(extra.statement_timeout).toBeUndefined();
});
});
+
+// POSTGRES_SCHEMA: a non-public schema sets TypeORM's `schema` option AND the session search_path (via
+// pg's startup `options` param) so the project's raw, unqualified migration DDL + the typeorm_migrations
+// ledger resolve to the configured schema. The default (public) path stays byte-identical to the
+// pre-schema-selection behavior — no `options` key is added. The builder is tested directly so no
+// process.env mutation or module reload is needed.
+describe('PostgreSQL schema selection (POSTGRES_SCHEMA)', () => {
+ // The builder returns the broad DataSourceOptions union; narrow to the postgres-specific fields
+ // under test (both are optional on the union — schema only on postgres, extra on every member).
+ type PgOpts = { schema?: string; extra?: Record<string, unknown> };
+
+ it('defaults schema to "public" and does NOT set a search_path when POSTGRES_SCHEMA is unset', () => {
+ const opts = buildPostgresDataSourceOptions({}) as PgOpts;
+ expect(opts.schema).toBe('public');
+ expect(opts.extra?.options).toBeUndefined();
+ });
+
+ it('passes schema through and sets extra.options search_path for a non-public schema', () => {
+ const opts = buildPostgresDataSourceOptions({ POSTGRES_SCHEMA: 'openwa' }) as PgOpts;
+ expect(opts.schema).toBe('openwa');
+ expect(opts.extra?.options).toBe('-c search_path=openwa,public');
+ });
+
+ it('keeps the pool timeouts under a custom schema (only adds options; never drops them or adds statement_timeout)', () => {
+ const opts = buildPostgresDataSourceOptions({ POSTGRES_SCHEMA: 'openwa' }) as PgOpts;
+ expect(opts.extra?.max).toBe(10);
+ expect(opts.extra?.idleTimeoutMillis).toBe(30000);
+ expect(opts.extra?.connectionTimeoutMillis).toBe(10000);
+ // the migration connection must STILL never carry a statement_timeout
+ expect(opts.extra?.statement_timeout).toBeUndefined();
+ });
+});
diff --git a/src/database/data-source.ts b/src/database/data-source.ts
index a147cb426..1e9267005 100644
--- a/src/database/data-source.ts
+++ b/src/database/data-source.ts
@@ -39,31 +39,49 @@ const sqliteDataSourceOptions: DataSourceOptions = {
// rejects a data-source file that exports more than one DataSource instance ("must contain only one
// export of DataSource"). Keeping the postgres config as an options object leaves exactly one instance
// export (the default below) so every `migration:*` command resolves it.
-export const postgresDataSourceOptions: DataSourceOptions = {
- type: 'postgres',
- host: process.env.DATABASE_HOST || 'localhost',
- port: parseInt(process.env.DATABASE_PORT || '5432', 10),
- username: process.env.DATABASE_USERNAME,
- password: process.env.DATABASE_PASSWORD,
- database: process.env.DATABASE_NAME || 'openwa',
- entities: dataEntities,
- migrations: dataMigrations,
- synchronize: false, // Never auto-sync in production
- logging: process.env.DATABASE_LOGGING === 'true',
- ssl:
- process.env.DATABASE_SSL === 'true'
- ? {
- rejectUnauthorized: process.env.DATABASE_SSL_REJECT_UNAUTHORIZED !== 'false',
- }
- : false,
- extra: {
- max: parseInt(process.env.DATABASE_POOL_SIZE || '10', 10),
- // Pool resilience only. NO statement_timeout here: this connection runs migrations, and a
- // long CREATE INDEX / backfill must not be aborted mid-flight.
- idleTimeoutMillis: parseInt(process.env.DATABASE_IDLE_TIMEOUT_MS || '30000', 10),
- connectionTimeoutMillis: parseInt(process.env.DATABASE_CONNECTION_TIMEOUT_MS || '10000', 10),
- },
-};
+// Schema selection: a non-public POSTGRES_SCHEMA sets TypeORM's `schema` option AND the session
+// search_path (via pg's startup `options` parameter) so the project's RAW, unqualified migration SQL
+// (CREATE TABLE "x"..., ALTER TABLE "y"...) resolves to the configured schema. TypeORM's `schema`
+// option alone does NOT set search_path — without the `options` override, raw DDL would land in
+// `public` while the migration ledger lands in the configured schema. `<schema>,public` keeps public
+// on the path so pg_catalog + any public helpers still resolve; the configured schema wins.
+//
+// Exported as a builder so the schema/search_path logic is unit-testable without mutating process.env
+// or reloading the module. The default `postgresDataSourceOptions` reads the loaded env at module eval.
+export function buildPostgresDataSourceOptions(env: NodeJS.ProcessEnv = process.env): DataSourceOptions {
+ const schema = env.POSTGRES_SCHEMA || 'public';
+ const useCustomSearchPath = schema !== 'public';
+ return {
+ type: 'postgres',
+ schema,
+ host: env.DATABASE_HOST || 'localhost',
+ port: parseInt(env.DATABASE_PORT || '5432', 10),
+ username: env.DATABASE_USERNAME,
+ password: env.DATABASE_PASSWORD,
+ database: env.DATABASE_NAME || 'openwa',
+ entities: dataEntities,
+ migrations: dataMigrations,
+ synchronize: false, // Never auto-sync in production
+ logging: env.DATABASE_LOGGING === 'true',
+ ssl:
+ env.DATABASE_SSL === 'true'
+ ? {
+ rejectUnauthorized: env.DATABASE_SSL_REJECT_UNAUTHORIZED !== 'false',
+ }
+ : false,
+ extra: {
+ max: parseInt(env.DATABASE_POOL_SIZE || '10', 10),
+ // Pool resilience only. NO statement_timeout here: this connection runs migrations, and a
+ // long CREATE INDEX / backfill must not be aborted mid-flight.
+ idleTimeoutMillis: parseInt(env.DATABASE_IDLE_TIMEOUT_MS || '30000', 10),
+ connectionTimeoutMillis: parseInt(env.DATABASE_CONNECTION_TIMEOUT_MS || '10000', 10),
+ // Only set for a non-public schema (see above).
+ ...(useCustomSearchPath ? { options: `-c search_path=${schema},public` } : {}),
+ },
+ };
+}
+
+export const postgresDataSourceOptions: DataSourceOptions = buildPostgresDataSourceOptions();
// Exactly ONE DataSource instance is exported (the default), selected by DATABASE_TYPE.
export default new DataSource(dbType === 'postgres' ? postgresDataSourceOptions : sqliteDataSourceOptions);
diff --git a/src/modules/infra/infra.controller.spec.ts b/src/modules/infra/infra.controller.spec.ts
index d74591d53..44071d815 100644
--- a/src/modules/infra/infra.controller.spec.ts
+++ b/src/modules/infra/infra.controller.spec.ts
@@ -172,6 +172,61 @@ describe('InfraController.saveConfig SSL reject-unauthorized', () => {
});
});
+describe('InfraController PostgreSQL schema (POSTGRES_SCHEMA)', () => {
+ const newController = () =>
+ new InfraController(
+ {} as never,
+ {} as never,
+ {} as never,
+ {} as never,
+ {} as never,
+ {} as never,
+ {} as never,
+ {} as never,
+ );
+
+ function written(config: unknown, existing?: string): string {
+ (fs.existsSync as jest.Mock).mockReturnValue(existing !== undefined);
+ (fs.readFileSync as jest.Mock).mockReturnValue(existing ?? '');
+ (fs.writeFileSync as jest.Mock).mockClear();
+ newController().saveConfig(config as never);
+ const content = ((fs.writeFileSync as jest.Mock).mock.calls as Array<[string, string]>)[0][1];
+ (fs.existsSync as jest.Mock).mockReturnValue(false);
+ (fs.readFileSync as jest.Mock).mockReturnValue('');
+ return content;
+ }
+
+ it('writes POSTGRES_SCHEMA for external Postgres', () => {
+ const env = written({ database: { type: 'postgres', builtIn: false, host: 'db', schema: 'openwa' } });
+ expect(env).toContain('POSTGRES_SCHEMA=openwa');
+ });
+
+ it('defaults POSTGRES_SCHEMA to public for external Postgres when no schema is provided', () => {
+ const env = written({ database: { type: 'postgres', builtIn: false, host: 'db' } });
+ expect(env).toContain('POSTGRES_SCHEMA=public');
+ });
+
+ it('pins POSTGRES_SCHEMA=public for the built-in Postgres container', () => {
+ const env = written({ database: { type: 'postgres', builtIn: true } });
+ expect(env).toContain('POSTGRES_SCHEMA=public');
+ });
+
+ it('does not write POSTGRES_SCHEMA for sqlite', () => {
+ const env = written({ database: { type: 'sqlite' } });
+ expect(env).not.toContain('POSTGRES_SCHEMA=');
+ });
+
+ it('getConfig surfaces the saved POSTGRES_SCHEMA, defaulting to public', () => {
+ (fs.existsSync as jest.Mock).mockReturnValue(true);
+ (fs.readFileSync as jest.Mock).mockReturnValue('DATABASE_TYPE=postgres\nPOSTGRES_SCHEMA=openwa\n');
+ expect(newController().getConfig().database.schema).toBe('openwa');
+ (fs.readFileSync as jest.Mock).mockReturnValue('DATABASE_TYPE=postgres\n');
+ expect(newController().getConfig().database.schema).toBe('public');
+ (fs.existsSync as jest.Mock).mockReturnValue(false);
+ (fs.readFileSync as jest.Mock).mockReturnValue('');
+ });
+});
+
describe('InfraController.saveConfig writes the generated env owner-only', () => {
// data/.env.generated holds DB/S3/Redis credentials, so it must be written 0600 — not the
// default 0644 (world-readable). The write must go through the same owner-only path the
@@ -258,13 +313,15 @@ describe('InfraController.saveConfig env-name correctness and merge (#226)', ()
expect(env).toContain('DATABASE_HOST=db');
});
- it('drops stale postgres keys when switching to sqlite', () => {
- const existing = 'DATABASE_TYPE=postgres\nDATABASE_HOST=oldhost\nDATABASE_PASSWORD=secret\nDATABASE_PORT=5432\n';
+ it('drops stale postgres keys (including POSTGRES_SCHEMA) when switching to sqlite', () => {
+ const existing =
+ 'DATABASE_TYPE=postgres\nDATABASE_HOST=oldhost\nDATABASE_PASSWORD=secret\nDATABASE_PORT=5432\nPOSTGRES_SCHEMA=openwa\n';
const env = written({ database: { type: 'sqlite' } }, existing);
expect(env).toContain('DATABASE_TYPE=sqlite');
expect(env).not.toContain('DATABASE_HOST=');
expect(env).not.toContain('DATABASE_PASSWORD=');
expect(env).not.toContain('DATABASE_PORT=');
+ expect(env).not.toContain('POSTGRES_SCHEMA=');
});
it('drops stale S3 keys when switching storage to local', () => {
diff --git a/src/modules/infra/infra.controller.ts b/src/modules/infra/infra.controller.ts
index 8f22e3c45..f9c866226 100644
--- a/src/modules/infra/infra.controller.ts
+++ b/src/modules/infra/infra.controller.ts
@@ -56,6 +56,7 @@ interface SaveConfigDto {
username?: string;
password?: string;
database?: string;
+ schema?: string;
poolSize?: number;
sslEnabled?: boolean;
sslRejectUnauthorized?: boolean;
@@ -207,6 +208,7 @@ interface SavedConfigResponse {
port: string;
username: string;
database: string;
+ schema: string;
poolSize: number;
sslEnabled: boolean;
sslRejectUnauthorized: boolean;
@@ -412,6 +414,7 @@ export class InfraController {
port: saved.DATABASE_PORT || '',
username: saved.DATABASE_USERNAME || '',
database: saved.DATABASE_NAME || '',
+ schema: saved.POSTGRES_SCHEMA || 'public',
poolSize: Number(saved.DATABASE_POOL_SIZE) || 10,
sslEnabled: saved.DATABASE_SSL === 'true',
sslRejectUnauthorized: saved.DATABASE_SSL_REJECT_UNAUTHORIZED !== 'false',
@@ -483,6 +486,10 @@ export class InfraController {
updates.DATABASE_USERNAME = 'openwa';
updates.DATABASE_PASSWORD = 'openwa';
updates.DATABASE_NAME = 'openwa';
+ // Built-in Postgres is initialized with the default 'public' schema (see
+ // scripts/postgres-init-schema.sh). Pin it so a later switch from a custom-schema
+ // external DB to built-in doesn't carry a stale POSTGRES_SCHEMA forward.
+ updates.POSTGRES_SCHEMA = 'public';
profiles.push('postgres');
} else {
// External PostgreSQL
@@ -491,6 +498,7 @@ export class InfraController {
updates.DATABASE_USERNAME = config.database.username || 'postgres';
setSecret('DATABASE_PASSWORD', config.database.password);
updates.DATABASE_NAME = config.database.database || 'openwa';
+ updates.POSTGRES_SCHEMA = config.database.schema || 'public';
}
updates.DATABASE_POOL_SIZE = String(config.database.poolSize || 10);
updates.DATABASE_SSL = config.database.sslEnabled ? 'true' : 'false';
@@ -511,6 +519,7 @@ export class InfraController {
'DATABASE_POOL_SIZE',
'DATABASE_SSL',
'DATABASE_SSL_REJECT_UNAUTHORIZED',
+ 'POSTGRES_SCHEMA',
]) {
staleKeys.add(k);
}