fix(postgres): connect over a Unix socket

TREK_DB_URL could not name a Unix socket. MikroORM builds the pool from the
URL's own host and drops a host parameter, so
postgresql://trek@localhost/trek?host=/var/run/postgresql connected to
localhost over TCP. A percent-encoded socket path as the host reached the
pool, but the client tools got it undecoded in PGHOST, so backups, restores
and the safety copy before a migration failed.

The server address is now read once, the way libpq reads a connection URL:
a host or port parameter takes the place of the URL's own, and a host
written into the URL is percent-decoded. The pool and the client tools both
get that address. The wiki and .env.example show the socket form.
This commit is contained in:
Maurice
2026-11-24 23:15:26 +01:00
parent aa79d6286a
commit f928f4b1ca
8 changed files with 100 additions and 4 deletions
@@ -77,6 +77,15 @@ describe('pg-tools', () => {
PGUSER: 'u',
PGCONNECT_TIMEOUT: '10',
});
// A Unix socket: the host parameter wins over the URL's host, as in libpq, and an encoded host is decoded.
expect(pgConnectionEnv('postgresql://u@localhost/d?host=/var/run/postgresql&port=5433')).toMatchObject({
PGHOST: '/var/run/postgresql',
PGPORT: '5433',
});
expect(pgConnectionEnv('postgresql://u@%2Fvar%2Frun%2Fpostgresql/d')).toMatchObject({
PGHOST: '/var/run/postgresql',
PGPORT: '5432',
});
});
it('PGTOOLS-003: SSL is verified as the app pool verifies it, against the URL root certificate when it names one', () => {
@@ -0,0 +1,38 @@
/**
* Where TREK_DB_URL says the Postgres server listens, read as libpq reads a
* connection URL, so the pool and the client tools reach the same server.
*/
import { pgServerAddress } from '../../../../../src/db/engine/postgres/server-address';
import { describe, expect, it } from 'vitest';
describe('pgServerAddress', () => {
it('PGADDR-001: a TCP host and port come from the URL itself', () => {
expect(pgServerAddress('postgresql://trek:pw@db.example:6543/trek')).toEqual({ host: 'db.example', port: 6543 });
expect(pgServerAddress('postgres://trek@[::1]/trek')).toEqual({ host: '::1', port: undefined });
});
it('PGADDR-002: a host or port parameter takes the place of the URL’s own, as in libpq', () => {
expect(pgServerAddress('postgresql://trek@localhost/trek?host=/var/run/postgresql')).toEqual({
host: '/var/run/postgresql',
port: undefined,
});
expect(pgServerAddress('postgresql:///trek?host=/run/postgresql&port=5433')).toEqual({
host: '/run/postgresql',
port: 5433,
});
});
it('PGADDR-003: a socket directory written into the URL is percent-decoded', () => {
expect(pgServerAddress('postgresql://trek@%2Fvar%2Frun%2Fpostgresql/trek')).toEqual({
host: '/var/run/postgresql',
port: undefined,
});
});
it('PGADDR-004: a port that is no port number is refused', () => {
for (const port of ['0', '65536', 'abc', '54x']) {
expect(() => pgServerAddress(`postgresql://trek@localhost/trek?port=${port}`), port).toThrow(/not a port number/);
}
});
});