Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix(database): improve pg17 compat and migration reliability

[._.]/ Adam Eivy03b9340220cb
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 21951f3b1c..ba75796eb7 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -31,7 +31,7 @@
## Fixed
-- **Database sync/migrate failures** — Fixed `start_native` in db.sh crashing when native PostgreSQL was already running (pg_ctl "another server might be running" error). Rewrote sync route to use a temporary port (5562) for the target backend so the active database never goes down during sync — eliminates pool errors and connection drops
+- **Database sync/migrate failures** — Fixed `start_native` in db.sh crashing when native PostgreSQL was already running (pg_ctl "another server might be running" error). Rewrote sync route to use a temporary port (5562) for the target backend so the active database never goes down during sync — eliminates pool errors and connection drops. Fixed pg17 dump compatibility (strip `\restrict`/`\unrestrict` and `transaction_timeout`). Prefer Docker's pg17 psql for imports to avoid version mismatch. Homebrew pg17 path detection now works on both arm64 and Intel Macs. Native setup grants SUPERUSER for extension management. Sync route auto-creates portos role/database on native target.
- **Self-build crash** — Fixed PortOS build button killing the server mid-build. `npm install` in `server/` triggered PM2's file watcher restart (SIGINT) which killed the build child process. Self-builds now skip server install (already running) and use `shell: true` for proper PATH resolution. Build error messages now include exit code, signal, and stdout/stderr output.
diff --git a/scripts/db.sh b/scripts/db.sh
index d5c79b45ca..2b5756bc90 100755
--- a/scripts/db.sh
+++ b/scripts/db.sh
@@ -122,12 +122,15 @@ native_running() {
PGPASSWORD="$PGPASSWORD" pg_isready -h "$PGHOST" -p "$PGPORT" -U "$PGUSER" >/dev/null 2>&1
}
-# Auto-detect Homebrew PostgreSQL on macOS and add to PATH
-if [ "$(uname)" = "Darwin" ] && command -v brew >/dev/null 2>&1; then
- _pg_bin="$(brew --prefix postgresql@17 2>/dev/null)/bin"
- if [ -d "$_pg_bin" ]; then
- export PATH="$_pg_bin:$PATH"
- fi
+# Auto-detect Homebrew PostgreSQL 17 on macOS and add to PATH
+# Check both arm64 (/opt/homebrew) and Intel (/usr/local) prefixes
+if [ "$(uname)" = "Darwin" ]; then
+ for _prefix in /opt/homebrew/opt/postgresql@17 /usr/local/opt/postgresql@17; do
+ if [ -x "$_prefix/bin/psql" ]; then
+ export PATH="$_prefix/bin:$PATH"
+ break
+ fi
+ done
fi
# Check if native PostgreSQL is installed
@@ -475,13 +478,13 @@ cmd_setup_native() {
if ! psql -h "$PGHOST" -p "$PGPORT" -U "$sys_user" -d postgres -tAc "SELECT 1 FROM pg_roles WHERE rolname='$PGUSER'" 2>/dev/null | grep -q 1; then
info "Creating database user: $PGUSER"
psql -h "$PGHOST" -p "$PGPORT" -U "$sys_user" -d postgres \
- -v pw="$PGPASSWORD" -v user="$PGUSER" -c "CREATE ROLE :\"user\" WITH LOGIN PASSWORD :'pw' CREATEDB;"
+ -c "CREATE ROLE $PGUSER WITH LOGIN PASSWORD '$PGPASSWORD' CREATEDB SUPERUSER;"
log "User $PGUSER created"
else
log "User $PGUSER already exists"
- # Ensure password is set correctly
+ # Ensure password and superuser are set correctly (superuser needed for extension management)
psql -h "$PGHOST" -p "$PGPORT" -U "$sys_user" -d postgres \
- -v pw="$PGPASSWORD" -v user="$PGUSER" -c "ALTER USER :\"user\" WITH PASSWORD :'pw';" 2>/dev/null || true
+ -c "ALTER USER $PGUSER WITH PASSWORD '$PGPASSWORD' SUPERUSER;" 2>/dev/null || true
fi
# Step 4: Create portos database if it doesn't exist
@@ -525,14 +528,14 @@ run_psql() {
fi
}
-# Run pg_dump, using Docker exec in Docker mode if host pg_dump is unavailable
+# Run pg_dump, preferring Docker exec in Docker mode to avoid version mismatch
run_pg_dump() {
local mode
mode=$(get_mode)
- if command -v pg_dump >/dev/null 2>&1; then
- PGPASSWORD="$PGPASSWORD" pg_dump -h "$PGHOST" -p "$PGPORT" -U "$PGUSER" -d "$PGDATABASE" "$@"
- elif [ "$mode" = "docker" ] && docker_running; then
+ if [ "$mode" = "docker" ] && docker_running; then
docker exec -e PGPASSWORD="$PGPASSWORD" portos-db pg_dump -U "$PGUSER" -d "$PGDATABASE" "$@"
+ elif command -v pg_dump >/dev/null 2>&1; then
+ PGPASSWORD="$PGPASSWORD" pg_dump -h "$PGHOST" -p "$PGPORT" -U "$PGUSER" -d "$PGDATABASE" "$@"
else
err "pg_dump not found on host and Docker DB is not running"
exit 1
@@ -575,12 +578,35 @@ cmd_import() {
info "Importing $dumpfile..."
- # Use stdin redirection so the dump is accessible even in Docker exec mode
- run_psql -v ON_ERROR_STOP=1 --single-transaction < "$dumpfile"
+ # Strip pg17-only features for compatibility with older psql versions:
+ # - \restrict/\unrestrict (pg17 dump security tokens)
+ # - SET transaction_timeout (pg17 config parameter)
+ sed -e '/^\\restrict /d' -e '/^\\unrestrict /d' -e '/^SET transaction_timeout/d' "$dumpfile" | run_psql -v ON_ERROR_STOP=1 --single-transaction
log "Import complete"
}
+# Import a dump into a specific target using Docker's pg17 psql when available.
+# This avoids version-mismatch issues when the host psql is older than the dump format.
+import_to_target() {
+ local dumpfile="$1"
+ local target_port="$2"
+
+ # Strip pg17-only features for compat with older psql
+ local filtered
+ filtered="$(sed -e '/^\\restrict /d' -e '/^\\unrestrict /d' -e '/^SET transaction_timeout/d' "$dumpfile")"
+
+ # Prefer Docker's pg17 psql to avoid version mismatch with host psql
+ if docker_running; then
+ echo "$filtered" | docker exec -i -e PGPASSWORD="$PGPASSWORD" portos-db \
+ psql -h host.docker.internal -p "$target_port" -U "$PGUSER" -d "$PGDATABASE" \
+ -v ON_ERROR_STOP=1 --single-transaction
+ else
+ echo "$filtered" | PGPASSWORD="$PGPASSWORD" psql -h "$PGHOST" -p "$target_port" -U "$PGUSER" -d "$PGDATABASE" \
+ -v ON_ERROR_STOP=1 --single-transaction
+ fi
+}
+
# Migrate data between Docker and native
cmd_migrate() {
local current_mode
@@ -611,32 +637,54 @@ cmd_migrate() {
local dumpfile
dumpfile=$(cmd_export "migrate-$(date +%Y%m%d-%H%M%S)")
- # Stop source
- info "Stopping $current_mode..."
- cmd_stop
+ # Determine target port
+ local target_port
+ target_port=$([ "$target_mode" = "native" ] && echo "5432" || echo "5561")
- # Switch mode and start target — restore mode on failure or interruption
- set_mode "$target_mode"
- # Recalculate port for the new mode
- PGPORT=$(get_port)
+ # Ensure target is running (keep source running too — they use different ports)
+ if [ "$target_mode" = "native" ]; then
+ # Ensure native pg is up (don't stop Docker — we need its pg17 psql)
+ if ! pg_isready -h "$PGHOST" -p "$target_port" >/dev/null 2>&1; then
+ start_native
+ fi
+ else
+ # Start Docker if not running
+ if ! docker_running; then
+ require_docker_compose
+ cd "$ROOT_DIR"
+ docker compose up -d db
+ info "Waiting for Docker PostgreSQL..."
+ for i in $(seq 1 30); do
+ if docker compose exec -T db pg_isready -U "$PGUSER" >/dev/null 2>&1; then break; fi
+ sleep 1
+ done
+ fi
+ fi
+
+ # Restore mode on failure or interruption
_migrate_cleanup() {
warn "Migration aborted — restoring mode to $current_mode"
set_mode "$current_mode"
}
trap '_migrate_cleanup' ERR INT TERM
- if [ "$target_mode" = "native" ]; then
- start_native
- else
- start_docker
- fi
-
# Import into target
- cmd_import "$dumpfile"
+ info "Importing into $target_mode (port $target_port)..."
+ import_to_target "$dumpfile" "$target_port"
+
+ # Switch mode to target
+ set_mode "$target_mode"
+ PGPORT=$(get_port)
# Clear traps after successful import
trap - ERR INT TERM
+ # Stop the old source if desired (both can coexist, but stop to save resources)
+ if [ "$current_mode" = "docker" ]; then
+ info "Stopping Docker..."
+ stop_docker
+ fi
+
# Verify
local new_count
new_count=$(run_psql -tAc "SELECT count(*) FROM memories" 2>/dev/null || echo "0")
diff --git a/server/routes/database.js b/server/routes/database.js
index 1066f3188e..2e56a498cc 100644
--- a/server/routes/database.js
+++ b/server/routes/database.js
@@ -1,5 +1,6 @@
import { Router } from 'express';
-import { execFile } from 'child_process';
+import { execFile, execFileSync } from 'child_process';
+import { existsSync } from 'fs';
import { dirname, join } from 'path';
import { fileURLToPath } from 'url';
import { asyncHandler } from '../lib/errorHandler.js';
@@ -257,12 +258,23 @@ const pgPassword = process.env.PGPASSWORD || 'portos';
const NATIVE_PORT = '5432';
const DOCKER_PORT = '5561';
+// Prefer Homebrew postgresql@17 binaries over system pg (avoids version mismatch)
+// Check both arm64 (/opt/homebrew) and Intel (/usr/local) prefixes
+const pg17Bin = (() => {
+ for (const prefix of ['/opt/homebrew/opt/postgresql@17', '/usr/local/opt/postgresql@17']) {
+ const bin = `${prefix}/bin`;
+ if (existsSync(`${bin}/psql`)) return bin;
+ }
+ return null;
+})();
+
/**
* Build env object with PGPASSWORD for passing to child processes.
* Avoids interpolating password into shell strings (shell metacharacter safety).
*/
const pgEnv = (port) => ({
...process.env,
+ ...(pg17Bin ? { PATH: `${pg17Bin}:${process.env.PATH}` } : {}),
PGPASSWORD: pgPassword,
PGHOST: 'localhost',
PGPORT: String(port),
@@ -293,20 +305,45 @@ router.post('/sync', asyncHandler(async (req, res) => {
const dumpFile = exportLines[exportLines.length - 1]?.trim();
console.log(`🗄️ Sync: exported to ${dumpFile}`);
- // Step 2: Ensure target is running
+ // Step 2: Ensure target is running and configured
emit('start', { message: `Checking ${targetMode} is running...` });
const readyResult = await runCmd('pg_isready', [
- '-h', 'localhost', '-p', targetPort, '-U', pgUser
+ '-h', 'localhost', '-p', targetPort
], 5_000, pgEnv(targetPort));
if (readyResult.exitCode !== 0) {
emit('error', { message: `${targetMode} database not running on port ${targetPort}. Start it first.` });
return res.status(400).json({ error: `${targetMode} database not running on port ${targetPort}. Start it first.` });
}
+ // Ensure target has the portos role and database (native pg may lack the role)
+ if (targetMode === 'native') {
+ emit('start', { message: 'Ensuring native database role and schema exist...' });
+ const sysUser = process.env.USER || 'postgres';
+ const sysEnv = pgEnv(targetPort);
+ // Create role if missing (connect as system superuser)
+ await runCmd('psql', ['-h', 'localhost', '-p', targetPort, '-U', sysUser, '-d', 'postgres',
+ '-c', `DO $$ BEGIN IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname='${pgUser}') THEN CREATE ROLE ${pgUser} WITH LOGIN PASSWORD '${pgPassword}' CREATEDB SUPERUSER; END IF; END $$;`
+ ], 10_000, sysEnv);
+ // Create database if missing
+ const dbCheck = await runCmd('psql', ['-h', 'localhost', '-p', targetPort, '-U', sysUser, '-d', 'postgres',
+ '-tAc', `SELECT 1 FROM pg_database WHERE datname='${pgDb}'`
+ ], 5_000, sysEnv);
+ if (!dbCheck.stdout.trim().includes('1')) {
+ await runCmd('psql', ['-h', 'localhost', '-p', targetPort, '-U', sysUser, '-d', 'postgres',
+ '-c', `CREATE DATABASE ${pgDb} OWNER ${pgUser};`
+ ], 10_000, sysEnv);
+ }
+ // Best-effort extensions (non-fatal — dump may handle schema, and pgvector may not be installed)
+ await runCmd('psql', ['-h', 'localhost', '-p', targetPort, '-U', sysUser, '-d', pgDb,
+ '-c', 'CREATE EXTENSION IF NOT EXISTS vector; CREATE EXTENSION IF NOT EXISTS pgcrypto;'
+ ], 10_000, sysEnv);
+ }
+
// Step 3: Import into target (active backend untouched — different port)
+ // Strip pg17-only features for compat with older psql: \restrict/\unrestrict, transaction_timeout
emit('start', { message: `Importing into ${targetMode} (port ${targetPort})...` });
const importResult = await runCmd('bash', ['-c',
- `psql -h localhost -p ${targetPort} -U ${pgUser} -d ${pgDb} -v ON_ERROR_STOP=1 --single-transaction < "${dumpFile}"`
+ `sed -e '/^\\\\restrict /d' -e '/^\\\\unrestrict /d' -e '/^SET transaction_timeout/d' "${dumpFile}" | psql -h localhost -p ${targetPort} -U ${pgUser} -d ${pgDb} -v ON_ERROR_STOP=1 --single-transaction`
], 120_000, pgEnv(targetPort));
if (importResult.exitCode !== 0) {