docs(db): Postgres 14 to 18, the database role, restore limits and the manual rollback

- Database-Postgres: supported versions, the version 18 client and the tool
  search order, sslrootcert with a client before 16, how to create a role
  that is not a superuser and move an older compose install to one, a
  current schema other than public, and the space a restore needs.
- Updating: the manual rollback clears the whole schema and loads the copy
  in one transaction, as TREK's restore does; dropping only the tables left
  the collation, the trigger functions and the sequences behind. A unit
  test keeps the printed statement equal to CLEAR_SCHEMA_SQL, and the boot's
  rollback hint points at that section.
- Troubleshooting, Install-Docker-Compose, Environment-Variables, README
  and server/CLAUDE.md follow.
This commit is contained in:
Maurice
2026-11-17 11:58:35 +01:00
parent eab501925f
commit 633e9bcdc1
10 changed files with 164 additions and 33 deletions
+1 -1
View File
@@ -321,7 +321,7 @@ docker compose up -d
See [Install with Docker Compose](https://github.com/liketrek/TREK/wiki/Install-Docker-Compose)
for the full walkthrough.
TREK stores its data in SQLite by default. Set `TREK_DB_URL` to run it on a PostgreSQL 14 to 17 database instead. The
TREK stores its data in SQLite by default. Set `TREK_DB_URL` to run it on a PostgreSQL 14 to 18 database instead. The
[`docker-compose.postgres.yml`](docker-compose.postgres.yml) example starts one beside TREK, and the
[Postgres guide](https://github.com/liketrek/TREK/wiki/Database-Postgres) covers the requirements and the backups.
+1 -1
View File
File diff suppressed because one or more lines are too long
@@ -216,8 +216,9 @@ export function postgresSafetyNet(
const match = snapshots.find((snapshot) => path.basename(snapshot).startsWith(`${PREFIX}${thisRelease}-`));
if (match) {
return (
`The copy taken right before the newer TREK migrated it is ${match}: stop TREK, empty the database ` +
'(drop and recreate it), and restore it with pg_restore --no-owner --no-privileges --single-transaction.'
`The copy taken right before the newer TREK migrated it is ${match}: stop TREK and load it as the wiki ` +
'page Updating describes ("Rolling back a Postgres update"), which clears the schema and runs ' +
'pg_restore --no-owner --no-privileges in one transaction with psql.'
);
}
if (snapshots.length > 0) {
@@ -0,0 +1,38 @@
/**
* The manual rollback in wiki/Updating.md ("Rolling back a Postgres update")
* prints the statement TREK's restore clears the schema with
* (src/db/engine/postgres/clear-schema.ts), so a rollback by hand clears the
* same objects as the tested restore. The page holds a copy; this keeps it the
* same as the code.
*/
import { CLEAR_SCHEMA_SQL } from '../../../../../src/db/engine/postgres/clear-schema';
import fs from 'node:fs';
import path from 'node:path';
import { describe, expect, it } from 'vitest';
const repoRoot = path.resolve(__dirname, '../../../../../..');
/** The `sql` code blocks of a Markdown text, with the indentation of their fence removed. */
function sqlBlocks(markdown: string): string[] {
const blocks: string[] = [];
const fence = /^( *)```sql\n([\s\S]*?)\n\1```$/gm;
for (const match of markdown.replace(/\r\n?/g, '\n').matchAll(fence)) {
const indent = match[1].length;
blocks.push(
match[2]
.split('\n')
.map((line) => line.slice(Math.min(indent, line.length - line.trimStart().length)))
.join('\n'),
);
}
return blocks;
}
describe('clear-schema', () => {
it('CLEARSCHEMA-001: the manual rollback on the wiki clears the schema with the statement the restore runs', () => {
const page = fs.readFileSync(path.join(repoRoot, 'wiki', 'Updating.md'), 'utf8');
const section = page.slice(page.indexOf('### Rolling back a Postgres update'));
expect(sqlBlocks(section)).toContain(CLEAR_SCHEMA_SQL.trimEnd());
});
});
@@ -318,7 +318,7 @@ describe('postgresSafetyNet', () => {
await expect(hint.restoreHint('20200101000100')).resolves.toMatch(/none of them from this release/);
writeFileSync(path.join(dir, 'pre-migrate-20200101000100-20250102T000000Z.pgdump'), 'mine');
await expect(hint.restoreHint('20200101000100')).resolves.toMatch(
/pre-migrate-20200101000100-20250102T000000Z\.pgdump: stop TREK, empty the database .*pg_restore --no-owner/,
/pre-migrate-20200101000100-20250102T000000Z\.pgdump: stop TREK and load it as the wiki page Updating .*pg_restore --no-owner/,
);
});
});
+45 -15
View File
@@ -12,12 +12,12 @@ Postgres does not make TREK scale out. TREK still runs as one process. See [Limi
## Requirements
- **PostgreSQL 14 to 17.**
- **PostgreSQL 14 to 18.** TREK refuses to start on any other server version, before it writes anything.
- **An empty database dedicated to TREK.** TREK creates its schema in an empty database. It refuses a database that holds tables it did not create, and a restore replaces everything in the schema it loads into. Do not share the database with another application.
- **A role that is not a superuser,** which owns the database or can create objects in its schema. A backup archive is a SQL script run by this role during a restore, so a role with fewer privileges limits what a crafted archive can do.
- **A role that is not a superuser,** which owns the database or can create objects in its schema. A backup archive is a SQL script run by this role during a restore, so a role with fewer privileges limits what a crafted archive can do. A restore refuses a superuser and a role that holds `pg_execute_server_program` or `pg_write_server_files`, and TREK warns about such a role when it starts. See [A role that is not a superuser](#a-role-that-is-not-a-superuser).
- **ICU support in the server.** The schema creates the collation `nocase` with `provider = icu`, so the server must be built with ICU. The official `postgres` images include it.
- **PostgreSQL client tools** (`pg_dump`, `pg_restore`, `psql`) for backups, restores and the copy TREK takes before a migration. The Docker image installs the version 17 client. The client cannot dump a server newer than 17, so a PostgreSQL 18 server needs a client of the same major version, installed on the host or in a custom image, and pointed at with `TREK_DB_PG_BIN_DIR`. See [Configuration](#configuration).
- **Client tool versions that carry the CVE-2025-8714 fix.** A restore refuses `pg_restore` or `psql` older than 17.6, 16.10, 15.14 or 14.19.
- **PostgreSQL client tools** (`pg_dump`, `pg_restore`, `psql`) for backups, restores and the copy TREK takes before a migration. The Docker image installs the version 18 client, which works with every supported server. A client works with servers up to its own major version, so a client outside the image must be at least as new as the server; TREK refuses an older one with a message that names both versions. See [Configuration](#configuration).
- **Client tool versions that carry the CVE-2025-8714 fix.** A restore refuses `pg_restore` or `psql` older than 18.0, 17.6, 16.10, 15.14 or 14.19.
## Configuration
@@ -45,24 +45,52 @@ The `sslmode` parameter in the URL selects how the connection is secured:
Without `sslmode`, the connection pool uses no SSL. The client tools use the libpq default for an unset `sslmode`, so set `sslmode` explicitly. For the backup and restore tools, every mode other than `disable` verifies the server, including its host name.
`sslrootcert=` names the file holding the certificate authority that signs the server's certificate. It is needed when the server uses a certificate from a private CA, and it is valid only together with one of the verifying modes. The file must be readable inside the container, so mount it into the container and point the URL at the path inside the container. Without `sslrootcert`, the system's trusted certificate authorities are used.
`sslrootcert=` names the file holding the certificate authority that signs the server's certificate. It is needed when the server uses a certificate from a private CA, and it is valid only together with one of the verifying modes. The file must be readable inside the container, so mount it into the container and point the URL at the path inside the container. Without `sslrootcert`, the system's trusted certificate authorities are used. The client tools read the system's authorities only from version 16 on, so with an older client (outside the Docker image) set `sslrootcert`; TREK refuses a backup or restore with such a client otherwise and says so.
### Where the client tools are found
TREK runs the tools by their absolute path. It does not search `PATH`. When `TREK_DB_PG_BIN_DIR` is unset, TREK looks in these directories, in order, and uses the first one that holds the tool:
1. `/usr/lib/postgresql/17/bin`
2. `/usr/lib/postgresql/16/bin`
3. `/usr/lib/postgresql/15/bin`
4. `/usr/lib/postgresql/14/bin`
5. `/usr/local/bin`
6. `/usr/bin`
1. `/usr/lib/postgresql/18/bin`
2. `/usr/lib/postgresql/17/bin`
3. `/usr/lib/postgresql/16/bin`
4. `/usr/lib/postgresql/15/bin`
5. `/usr/lib/postgresql/14/bin`
6. `/usr/local/bin`
7. `/usr/bin`
The newest version comes first, because a client works with every server up to its own major version and refuses a newer one.
The password is passed to the tools in the `PGPASSWORD` environment variable of their process. It never appears on a command line, where other processes could read it.
### Compose example
[`docker-compose.postgres.yml`](https://github.com/liketrek/TREK/blob/main/docker-compose.postgres.yml) runs a `postgres:17` service beside TREK, on a named volume, with the TREK container waiting for the database to pass its health check. Set `POSTGRES_PASSWORD` in a `.env` file beside it before the first start. See [Install: Docker Compose](Install-Docker-Compose#running-on-postgres).
[`docker-compose.postgres.yml`](https://github.com/liketrek/TREK/blob/main/docker-compose.postgres.yml) runs a `postgres:17` service beside TREK, on a named volume, with the TREK container waiting for the database to pass its health check. Set two passwords in a `.env` file beside it before the first start: `POSTGRES_ADMIN_PASSWORD` for the database's superuser `postgres`, and `POSTGRES_PASSWORD` for the role `trek` that TREK connects as. On the database's first start, the superuser creates the role `trek`, which owns TREK's database and is not a superuser. See [Install: Docker Compose](Install-Docker-Compose#running-on-postgres).
### A role that is not a superuser
TREK connects as the role in `TREK_DB_URL`. That role creates TREK's schema, and during a restore it runs the backup's SQL, so it should own TREK's database and nothing more. On a server you administer, create it as a superuser once:
```sql
CREATE ROLE trek LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE PASSWORD '<a long random value>';
CREATE DATABASE trek OWNER trek;
\c trek
ALTER SCHEMA public OWNER TO trek;
```
Then use `postgres://trek:<password>@<host>:5432/trek` as `TREK_DB_URL`. A restore refuses a role that is a superuser, or that holds `pg_execute_server_program` or `pg_write_server_files`, because a crafted archive could use those to run commands or write files on the database server. TREK also logs a warning about such a role when it starts.
TREK creates its tables in the role's current schema, normally `public`. A role whose `search_path` points at a schema of its own works too: TREK keeps its tables and its migration history there, and backups and restores cover that schema.
### Moving a compose install off the superuser
An install that started from an older `docker-compose.postgres.yml` connects as `trek`, which the `postgres` image created as the superuser. Its backups work, but restores are refused until TREK runs as a role that is not a superuser. With the containers running:
1. Create a second superuser for administration, so the database keeps one: `docker exec -it trek-db psql -U trek -d trek -c "CREATE ROLE postgres LOGIN SUPERUSER PASSWORD '<a long random value>'"`.
2. Take the superuser right from `trek`: `docker exec -it trek-db psql -U postgres -d trek -c "ALTER ROLE trek NOSUPERUSER NOCREATEDB NOCREATEROLE"`.
3. Update `docker-compose.postgres.yml` to the current version. Set `POSTGRES_ADMIN_PASSWORD` to the password from step 1 in `.env`, and keep `POSTGRES_PASSWORD` as it is (it stays the password of `trek`). Then run `docker compose -f docker-compose.postgres.yml up -d`.
The database already exists, so the new init script does not run again, and TREK keeps its data.
## First boot
@@ -101,7 +129,9 @@ Restoring a backup on Postgres follows these rules:
- **The current database is replaced.** TREK first keeps a copy of it as `data/pre-restore-<time>.pgdump`. `pg_restore` then turns the archive's dump into a SQL script, and `psql` clears the current schema, which drops its tables, views, sequences, functions, types and collations, and runs the script. Both steps run in one transaction, so a restore that fails leaves the database as it was.
- **TREK checks the archive before it replaces anything.** The archive must hold a Postgres dump, not a SQLite file. The dump must carry TREK's migration history, and it must not come from a newer TREK. TREK refuses the restore with a message saying which check failed.
- **The client tools must be recent enough.** The restore refuses `pg_restore` or `psql` older than 17.6, 16.10, 15.14 or 14.19.
- **The client tools must be recent enough.** The restore refuses `pg_restore` or `psql` older than 18.0, 17.6, 16.10, 15.14 or 14.19, and tools older than the server.
- **The role must not be a superuser.** The restore refuses a role that is a superuser or holds `pg_execute_server_program` or `pg_write_server_files`. See [A role that is not a superuser](#a-role-that-is-not-a-superuser).
- **The restore needs free space in the data directory.** `pg_restore` writes the dump out as a SQL script next to the unpacked archive before `psql` runs it, and the script is several times larger than the dump. It may grow to `BACKUP_MAX_DECOMPRESSED_MB` (5 GB by default); a larger one is stopped, nothing is replaced, and the work files are removed. Raise the limit for a genuine backup that needs more.
`RESTORE_FROM_BACKUP` works on Postgres too. On the first start, TREK loads the archive's dump into the database when that database holds no tables. When the database already has tables, the variable is ignored and TREK logs a warning. See [Backups: Restoring on a new install, before setup](Backups#restoring-on-a-new-install-before-setup).
@@ -110,7 +140,7 @@ Restoring a backup on Postgres follows these rules:
- **No migration from SQLite to Postgres** in this first release. Start a new install on Postgres, or keep the SQLite install.
- **No more than one TREK replica.** TREK keeps state in memory: rate limits, pending one-time codes, the permission cache and the WebSocket connections. Each process has its own copy, so two replicas would disagree with each other. Keep `replicas: 1` in the Helm chart and one `trek` container. Postgres does not change that.
- **Two processes booting on one database at once are not coordinated.** Start one process for the first boot and for each upgrade, then continue with one.
- **Client tools for server version 18 and later.** The Docker image's client is version 17, which cannot dump a newer server. Point `TREK_DB_PG_BIN_DIR` at a matching client.
- **PostgreSQL 14 to 18 only.** A newer server is refused until a TREK release supports it, because the image's client tools would not be able to back it up.
- **Writes are serialized.** TREK takes a database-wide advisory lock for each write transaction, as the SQLite engine does with its single writer. Heavy concurrent writes wait on that lock.
## Supabase
@@ -120,7 +150,7 @@ Supabase runs PostgreSQL and can host TREK's database. The checklist below has b
- **Use the direct connection or the session pooler.** The direct connection uses port 5432. Its host resolves only to IPv6 unless the project has the IPv4 add-on. A container on a network without IPv6 (Docker Desktop's default network, for example) cannot reach it; use the session pooler there, which also listens on port 5432 on its own host.
- **Do not use the transaction pooler** (port 6543) for TREK. `pg_dump` and `psql` need a session that lasts for the whole run, and the transaction pooler does not give one.
- **Verify the server with Supabase's CA.** Supabase's certificate is signed by its own certificate authority, which the system's trusted authorities do not include, so `sslmode=require` alone fails for the backup and restore tools. Download the CA certificate from the project's database settings, mount it into the container, and use `sslmode=verify-full&sslrootcert=/certs/<file>.crt` with the path inside the container.
- **The `postgres` role works as TREK's role.** It is not a superuser, and it can create the schema and the `nocase` collation.
- **The `postgres` role works as TREK's role.** It is not a superuser, and it can create the schema and the `nocase` collation. If a restore refuses it because it holds `pg_execute_server_program` or `pg_write_server_files`, create a dedicated role as in [A role that is not a superuser](#a-role-that-is-not-a-superuser) (the `postgres` role may create roles) and connect TREK as that one.
- **The database's `public` schema must hold no tables** when TREK first starts, because TREK refuses a database with tables it did not create. A new project's `public` schema is empty.
- **Backups hold only TREK's schema.** The project's own schemas (`auth`, `storage` and the others Supabase manages) are left out of every backup, and a restore replaces only TREK's schema.
- **Pick a region close to the TREK server.** Every statement crosses the network, so a distant region makes the first boot and a restore take minutes. During a restore, scheduled jobs that touch the database can log statement timeouts; they run again on their next schedule.
+1 -1
View File
@@ -507,7 +507,7 @@ through environment variables. `TREK_PLACE_PHOTO_DIR` below is unaffected.
| `BACKUP_UPLOAD_LIMIT_MB` | Maximum **compressed** size (in MB) of a restore-backup archive that may be uploaded. Raise it if your backups (which include the `uploads/` directory) exceed the default. Non-positive or invalid values abort startup. | `500` |
| `RESTORE_FROM_BACKUP` | Path to a backup ZIP to restore on the **first** start, before any setup. Only acts while no database exists; afterwards it is ignored with a warning. A backup that fails the restore checks stops the start. See [Backups](Backups#restoring-on-a-new-install-before-setup). | none |
| `BACKUP_MAX_DECOMPRESSED_MB` | Maximum **decompressed** size (in MB) of a restore-backup archive — the zip-bomb guard. Independent of `BACKUP_UPLOAD_LIMIT_MB` and enforced on both restore paths, so a restore that fits the upload cap can still be refused with `Backup exceeds the maximum decompressed size.` Raise both when restoring a very large instance. | `5120` (5 GB) |
| `TREK_DB_URL` | Run TREK on a PostgreSQL database instead of the SQLite file: `postgres://user:password@host:5432/database` (or `postgresql://`). Needs PostgreSQL 14 to 17 and an empty database of its own. Percent-encode special characters in the password. See [Database: Postgres](Database-Postgres). | unset (SQLite) |
| `TREK_DB_URL` | Run TREK on a PostgreSQL database instead of the SQLite file: `postgres://user:password@host:5432/database` (or `postgresql://`). Needs PostgreSQL 14 to 18, an empty database of its own and a role that is not a superuser. Percent-encode special characters in the password. See [Database: Postgres](Database-Postgres). | unset (SQLite) |
| `TREK_DB_POOL_MAX` | Most connections TREK opens to the PostgreSQL database, from 1 to 100. Unused on SQLite. | `10` |
| `TREK_DB_PG_BIN_DIR` | Directory holding `pg_dump`, `pg_restore` and `psql`, which back up and restore a PostgreSQL database. Unset, TREK looks in `/usr/lib/postgresql/17` to `14` (`bin`), `/usr/local/bin` and `/usr/bin`. Unused on SQLite. See [Database: Postgres](Database-Postgres#where-the-client-tools-are-found). | unset |
| `TREK_DB_FILE` | Explicit path of the SQLite database file. Unset, TREK uses `travel.db` in the data directory. Not used with `TREK_DB_URL`. | unset |
+3 -3
View File
@@ -120,14 +120,14 @@ See [Reverse-Proxy](Reverse-Proxy) for complete proxy configuration examples.
[`docker-compose.postgres.yml`](https://github.com/liketrek/TREK/blob/main/docker-compose.postgres.yml) runs TREK beside a `postgres:17` service instead of the SQLite file. Its `db` service keeps the database in a named volume and publishes no port, and the `trek` service waits for the database's health check before it starts.
Put a password in a `.env` file beside the compose file, then start it:
Put two passwords in a `.env` file beside the compose file, then start it:
```bash
echo 'POSTGRES_PASSWORD=<a long random value>' > .env
printf 'POSTGRES_ADMIN_PASSWORD=%s\nPOSTGRES_PASSWORD=%s\n' '<a long random value>' '<another long random value>' > .env
docker compose -f docker-compose.postgres.yml up -d
```
The password goes into `TREK_DB_URL`, so use URL-safe characters or percent-encode it. Without `POSTGRES_PASSWORD` the database does not initialize and TREK does not start. To run it against a database that already exists elsewhere, use the plain `docker-compose.yml` and set `TREK_DB_URL` yourself.
`POSTGRES_ADMIN_PASSWORD` is the password of the database's superuser `postgres`, which on the first start only creates the role `trek`. `POSTGRES_PASSWORD` is the password of `trek`, the role TREK connects as: it owns TREK's database and is not a superuser, so a crafted backup restored into it cannot reach the database container. That password goes into `TREK_DB_URL`, so use URL-safe characters or percent-encode it. Without either password the database does not initialize and TREK does not start. An install made with an older version of the compose file connects as a superuser; [Database: Postgres](Database-Postgres#moving-a-compose-install-off-the-superuser) shows how to move it. To run it against a database that already exists elsewhere, use the plain `docker-compose.yml` and set `TREK_DB_URL` yourself.
Read [Database: Postgres](Database-Postgres) before you use it. It covers the requirements, SSL, backups and restores, and the limits of a Postgres install.
+20 -4
View File
@@ -672,17 +672,33 @@ See [Notifications](Notifications#web-push) for the details.
## Postgres: "pg_dump was not found" when backing up or restoring
**Cause:** The backup, restore or pre-migration copy runs `pg_dump`, `pg_restore` or `psql` by its absolute path. None of them is in the directories TREK searches (`/usr/lib/postgresql/17` down to `14`, `/usr/local/bin`, `/usr/bin`), and `PATH` is not searched.
**Cause:** The backup, restore or pre-migration copy runs `pg_dump`, `pg_restore` or `psql` by its absolute path. None of them is in the directories TREK searches (`/usr/lib/postgresql/18` down to `14`, `/usr/local/bin`, `/usr/bin`), and `PATH` is not searched.
**Fix:** Install the `postgresql-client` package, or set `TREK_DB_PG_BIN_DIR` to the directory that holds the three tools. The Docker image already includes the version 17 client. See [Database-Postgres](Database-Postgres#where-the-client-tools-are-found).
**Fix:** Install the `postgresql-client` package, or set `TREK_DB_PG_BIN_DIR` to the directory that holds the three tools. The Docker image already includes the version 18 client. See [Database-Postgres](Database-Postgres#where-the-client-tools-are-found).
---
## Postgres: a backup or restore fails with "server version mismatch" or a version error
**Cause:** Two different problems produce messages about versions. `pg_dump` from version 17 cannot dump a server running version 18 or later, and fails with `aborting because of server version mismatch`. A restore also refuses a `pg_restore` or `psql` older than 17.6, 16.10, 15.14 or 14.19, because those versions cannot restore a dump safely (CVE-2025-8714). The error names the version it found.
**Cause:** Three different problems produce messages about versions. A client tool works with servers up to its own major version, so TREK refuses a backup or restore with tools older than the server (`pg_dump is version 17, older than the PostgreSQL 18 server`). A restore also refuses a `pg_restore` or `psql` older than 18.0, 17.6, 16.10, 15.14 or 14.19, because those versions cannot restore a dump safely (CVE-2025-8714). And a client older than 16 cannot use the system's certificate authorities, so with `sslmode` set and no `sslrootcert` it is refused too. Each error names the version it found.
**Fix:** For a newer server, point `TREK_DB_PG_BIN_DIR` at client tools of the same major version as the server. For an old client, install a newer `postgresql-client` package, or use a newer image. The Docker image's client is version 17, so it works with servers 14 to 17.
**Fix:** Use the Docker image's tools, which are version 18 and work with every supported server (14 to 18), or point `TREK_DB_PG_BIN_DIR` at client tools at least as new as the server. For the certificate message, add `sslrootcert=<CA file>` to `TREK_DB_URL` or use newer tools.
---
## Postgres: TREK refuses to start because of the server version
**Cause:** TREK supports PostgreSQL 14 to 18 and refuses any other server before it writes anything (`the Postgres server is version 19; TREK supports PostgreSQL 14 to 18`).
**Fix:** Run TREK on a server of a supported version. A newer major is supported once a TREK release ships client tools for it.
---
## Postgres: a restore is refused because of the database role
**Cause:** `TREK_DB_URL` connects as a superuser, or as a role that holds `pg_execute_server_program` or `pg_write_server_files`. A backup is a SQL script that runs as this role, so TREK refuses to restore it with a role that could run commands or write files on the database server. TREK also logs a warning about such a role at startup.
**Fix:** Connect TREK as a role that owns its database and is not a superuser. See [Database-Postgres](Database-Postgres#a-role-that-is-not-a-superuser), which also shows how to move an install made with an older `docker-compose.postgres.yml`.
---
+51 -5
View File
@@ -100,16 +100,62 @@ An image from 5.0 on that refuses a newer database names the copy it can run, if
On a [PostgreSQL database](Database-Postgres) the copy TREK takes before a migration is `data/pre-migrate-<schema>-<time>.pgdump`, a `pg_dump` custom-format file, and the procedure is different from the SQLite one above. The copy holds the database only. Anything written after it was taken is lost when you roll back, and the uploads are not affected.
The copy cannot be loaded over the migrated schema: it recreates TREK's tables, its `nocase` collation, its trigger functions and its sequences, and every one of them still exists. Dropping only the tables is not enough, because the functions, the collation and the sequences a table does not own stay behind, and the load then stops at the first one that already exists. So the steps below clear the whole schema and load the copy in one transaction, the way TREK's own restore does: a load that fails leaves the database as it was.
1. Stop TREK.
2. Empty the database: drop it and create it again with the same owner, or drop the tables in its schema. `pg_restore` cannot load into a database that still holds the migrated tables.
3. Load the copy with the client tools of a version that carries the CVE-2025-8714 fix (17.6, 16.10, 15.14 or 14.19 at least):
2. Turn the copy into a SQL script, with client tools of a version that carries the CVE-2025-8714 fix (18.0, 17.6, 16.10, 15.14 or 14.19 at least) and that is at least as new as the server. Name the schema TREK's tables are in, normally `public`:
```bash
pg_restore --no-owner --no-privileges --single-transaction -d "postgres://user:password@host:5432/trek?sslmode=require" data/pre-migrate-<schema>-<time>.pgdump
pg_restore --no-owner --no-privileges --schema=public --file=restore.sql data/pre-migrate-<schema>-<time>.pgdump
```
Use the same connection URL as `TREK_DB_URL`. The password can also come from the `PGPASSWORD` environment variable, which keeps it out of the command line.
4. Start the previous image with the same `TREK_DB_URL`.
3. Save this block as `clear-schema.sql`. It drops every table, view, sequence, function, collation and type in the current schema, which is what TREK's restore runs before it loads a backup:
```sql
DO $clear$
DECLARE r record;
BEGIN
FOR r IN SELECT c.oid::regclass AS name, c.relkind FROM pg_class c
WHERE c.relnamespace = current_schema()::regnamespace AND c.relkind IN ('r', 'p', 'v', 'm', 'S', 'f')
AND NOT EXISTS (SELECT 1 FROM pg_depend d WHERE d.objid = c.oid AND d.deptype IN ('e', 'a', 'i'))
LOOP
EXECUTE format('DROP %s IF EXISTS %s CASCADE',
CASE r.relkind WHEN 'v' THEN 'VIEW' WHEN 'm' THEN 'MATERIALIZED VIEW' WHEN 'S' THEN 'SEQUENCE'
WHEN 'f' THEN 'FOREIGN TABLE' ELSE 'TABLE' END, r.name);
END LOOP;
FOR r IN SELECT p.oid::regprocedure AS sig FROM pg_proc p
WHERE p.pronamespace = current_schema()::regnamespace
AND NOT EXISTS (SELECT 1 FROM pg_depend d WHERE d.objid = p.oid AND d.deptype = 'e')
LOOP
EXECUTE format('DROP ROUTINE IF EXISTS %s CASCADE', r.sig);
END LOOP;
FOR r IN SELECT format('%I.%I', n.nspname, c.collname) AS name FROM pg_collation c
JOIN pg_namespace n ON n.oid = c.collnamespace
WHERE n.nspname = current_schema()
AND NOT EXISTS (SELECT 1 FROM pg_depend d WHERE d.objid = c.oid AND d.deptype = 'e')
LOOP
EXECUTE format('DROP COLLATION IF EXISTS %s CASCADE', r.name);
END LOOP;
FOR r IN SELECT t.oid::regtype AS name FROM pg_type t
WHERE t.typnamespace = current_schema()::regnamespace AND t.typtype IN ('e', 'd', 'r')
AND NOT EXISTS (SELECT 1 FROM pg_depend d WHERE d.objid = t.oid AND d.deptype IN ('e', 'i'))
LOOP
EXECUTE format('DROP TYPE IF EXISTS %s CASCADE', r.name);
END LOOP;
END
$clear$;
```
4. Clear the schema and load the script in one transaction, connected as TREK's own role (the URL in `TREK_DB_URL`):
```bash
psql "postgres://user@host:5432/trek?sslmode=require" --no-psqlrc --single-transaction --set=ON_ERROR_STOP=1 --file=clear-schema.sql --file=restore.sql
```
Put the password in the `PGPASSWORD` environment variable rather than in the URL, which keeps it out of the command line. Delete `restore.sql` afterwards: it holds the whole database in plain text.
5. Start the previous image with the same `TREK_DB_URL`.
On a server you administer, dropping the database and creating it again with the same owner, then loading the copy with `pg_restore --no-owner --no-privileges --single-transaction -d <url> <copy>`, works as well.
A TREK image without PostgreSQL support cannot read this database at all. It would start on a new SQLite file instead. An image from 5.0 on that refuses a newer database names the copy it can run, if one is in the data directory.