#1 PDF Application on GitHub that lets you edit PDFs on any device anywhere
TypeScript dockerhacktoberfestjavapdfpdf-converterpdf-editorpdf-manipulationpdf-mergerpdf-ocrpdf-toolspdf-web-appspdfmergerself-hosted
Test PostgreSQL upgrades from v2.5.0 and bump to 3.0.0 (#8128)
Anthony Stirlingdd5bc781c474
diff --git a/.github/aur/stirling-pdf-desktop/PKGBUILD b/.github/aur/stirling-pdf-desktop/PKGBUILDindex c47c8e3ee7..cb46ce13cf 100644--- a/.github/aur/stirling-pdf-desktop/PKGBUILD+++ b/.github/aur/stirling-pdf-desktop/PKGBUILD@@ -1,6 +1,6 @@# Maintainer: Stirling PDF Inc <[email protected]>pkgname=stirling-pdf-desktop-pkgver=2.14.3+pkgver=3.0.0pkgrel=1pkgdesc="Locally hosted, web-based PDF manipulation tool (Tauri desktop app, official Stirling PDF Inc build)"arch=('x86_64')diff --git a/.github/aur/stirling-pdf-server-bin/PKGBUILD b/.github/aur/stirling-pdf-server-bin/PKGBUILDindex d6159ddce3..3fd7d32531 100644--- a/.github/aur/stirling-pdf-server-bin/PKGBUILD+++ b/.github/aur/stirling-pdf-server-bin/PKGBUILD@@ -1,6 +1,6 @@# Maintainer: Stirling PDF Inc <[email protected]>pkgname=stirling-pdf-server-bin-pkgver=2.14.3+pkgver=3.0.0pkgrel=1pkgdesc="Locally hosted, web-based PDF manipulation tool (server JAR, prebuilt)"arch=('any')diff --git a/.github/workflows/db-migration-test.yml b/.github/workflows/db-migration-test.ymlindex 9a49e39eab..93b8bfbbf4 100644--- a/.github/workflows/db-migration-test.yml+++ b/.github/workflows/db-migration-test.yml@@ -1,23 +1,34 @@name: DB migration smoke test-# Boots the current Stirling-PDF JAR against H2 fixtures captured from past-# releases (v2.0.0 / v2.5.0 / v2.10.0) and verifies admin login still works.+# Tests all H2 fixtures and native PostgreSQL upgrades from v2.5.0 onwards.+# Historical releases need PREMIUM_KEY_ENTERPRISE to connect to PostgreSQL.# Catches schema changes that would break existing user databases under# Hibernate's `ddl-auto=update` upgrade path.on:workflow_call:+ workflow_dispatch:permissions:contents: readjobs:+ pick:+ uses: ./.github/workflows/_runner-pick.yml+migration-test:+ needs: pick+ name: DB upgrade (${{ matrix.database }})+ strategy:+ fail-fast: false+ matrix:+ # Historical releases require a license secret unavailable to fork PRs.+ database: ${{ fromJSON(needs.pick.outputs.is_fork == 'true' && '["h2"]' || '["h2", "postgresql"]') }}environment:name: ci-unsigneddeployment: falseruns-on: ubuntu-latest- timeout-minutes: 30+ timeout-minutes: 45steps:- name: Harden Runneruses: step-security/harden-runner@05e31511f85b41b11d1cf0ef85d0992719546e2c # v2.21.0@@ -27,6 +38,20 @@ jobs:- name: Checkout repositoryuses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2+ - name: Report PostgreSQL coverage unavailable for forks+ if: needs.pick.outputs.is_fork == 'true'+ run: echo 'PostgreSQL upgrade tests skipped on this fork PR because the enterprise license secret is unavailable. H2 upgrade tests still run.' >> "$GITHUB_STEP_SUMMARY"++ - name: Require license for historical PostgreSQL releases+ if: matrix.database == 'postgresql'+ env:+ PREMIUM_KEY: ${{ secrets.PREMIUM_KEY_ENTERPRISE }}+ run: |+ if [[ -z "$PREMIUM_KEY" ]]; then+ echo '::error::PREMIUM_KEY_ENTERPRISE is required for the PostgreSQL upgrade test.'+ exit 1+ fi+- name: Restore cache Gradle User Homeuses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0with:@@ -65,19 +90,30 @@ jobs:echo "path=$jar" >> "$GITHUB_OUTPUT"echo "Built JAR: $jar"- - name: Run migration smoke test+ - name: Run H2 migration smoke test+ if: matrix.database == 'h2'env:STIRLING_JAR: ${{ steps.jar.outputs.path }}run: bash scripts/db-migration/run-migration-test.sh+ - name: Run PostgreSQL migration smoke test+ if: matrix.database == 'postgresql'+ env:+ STIRLING_JAR: ${{ steps.jar.outputs.path }}+ PREMIUM_KEY: ${{ secrets.PREMIUM_KEY_ENTERPRISE }}+ run: python3 scripts/db-migration/run-postgres-migration-test.py --work-dir "${{ runner.temp }}/db-migration/postgresql"+- name: Upload app logs on failureif: failure()uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1with:- name: db-migration-app-logs+ name: db-migration-${{ matrix.database }}-logs# Path matches the preserved workdir in run-migration-test.sh -# only failing fixtures leave a directory behind.- path: /tmp/stirling-migration-failed-*/app.log+ path: |+ /tmp/stirling-migration-failed-*/app.log+ ${{ runner.temp }}/db-migration/postgresql/**/app.log+ ${{ runner.temp }}/db-migration/postgresql/**/postgres.logretention-days: 7if-no-files-found: warndiff --git a/app/proprietary/src/test/resources/db-migration-fixtures/README.md b/app/proprietary/src/test/resources/db-migration-fixtures/README.mdindex 25450cf7f7..2ebefbd418 100644--- a/app/proprietary/src/test/resources/db-migration-fixtures/README.md+++ b/app/proprietary/src/test/resources/db-migration-fixtures/README.md@@ -48,6 +48,64 @@ compatible with an existing user database. Common causes:* Changing a column type in an incompatible way.* Dropping or renaming a foreign-key target.+## PostgreSQL upgrade coverage++The same CI workflow also runs `scripts/db-migration/run-postgres-migration-test.py`+against PostgreSQL 16. For each version named by the H2 fixtures from v2.5.0+onwards, it boots the historical release on a disposable PostgreSQL database,+then dumps and restores that database before starting the current JAR.++The historical app creates the same core data as the H2 fixtures, then the test+uses its authenticated APIs (including CSRF handling) to populate:++* Two custom teams: Migration Finance and Migration Operations.+* Three regular users across those teams, including one disabled account.+* Nine user settings, including Unicode text.+* Real audit events from creating teams/users, updating settings, and login activity.++Seeding fails if any API call fails, any expected record is missing, or async+audit writes do not persist events for the admin and every fixture user.+Each fixture contains five users and four teams in total, including defaults.++After upgrading, the test checks that enabled users can log in and the disabled+user cannot. It compares user IDs, usernames, authentication types, enabled+states, team memberships, password hashes/API keys, roles, teams, and settings.+Every captured historical audit event must retain its ID, principal, type,+timestamp, and JSON payload; additional events from the new app are allowed.++Stirling-PDF v2.0.0 PostgreSQL coverage is deferred because its legacy large-object storage+requires a separate migration fix. The PostgreSQL test rejects versions before+v2.5.0; the existing H2 test still includes its v2.0.0 fixture.++Generated values can differ between H2 and PostgreSQL; each PostgreSQL upgrade+must preserve its own values. User timestamps and license entitlements are+excluded because startup may change them. File storage, workflows, invites,+and HTTP sessions are not seeded by this test.++Historical releases require a license for custom databases and an Enterprise+license to populate audit history.+CI uses `PREMIUM_KEY_ENTERPRISE` from the `ci-unsigned` environment. Missing or+invalid licenses fail the test, including any fallback to H2. Fork PRs run H2+only and report the missing PostgreSQL coverage in the job summary.++To run locally, install Docker, Python 3.10+, and Java 25; set `PREMIUM_KEY` to a+valid test license or an absolute `file:` license reference; then run:++```bash+python scripts/db-migration/run-postgres-migration-test.py \+ --jar /absolute/path/to/current-stirling-pdf.jar \+ --work-dir /absolute/path/to/new-migration-results+```++Use a fresh work directory per run. `--versions v2.5.0` narrows the releases;+`--release-jar-dir /path/to/jars` reuses files named `stirling-pdf-v2.5.0.jar`.+`--postgres-image postgres:16` and `--startup-timeout 300` can be overridden.++Only containers created by the script are used and removed. SQL dumps and logs+remain in the work directory; CI uploads only app/PostgreSQL logs on failure.+This tests application schema upgrades on PostgreSQL 16, not PostgreSQL server+major-version upgrades or every possible data/schema change.+## Regenerating fixturesThere's no automated regenerator script - fixtures are rare to refresh and thediff --git a/build.gradle b/build.gradleindex d9cc712331..4a0c995cde 100644--- a/build.gradle+++ b/build.gradle@@ -121,7 +121,7 @@ springBoot {allprojects {group = 'stirling.software'- version = '2.14.3'+ version = '3.0.0'configurations.configureEach {exclude group: "org.springframework.boot", module: "spring-boot-starter-tomcat"diff --git a/frontend/editor/src-tauri/tauri.conf.json b/frontend/editor/src-tauri/tauri.conf.jsonindex 8087119dd3..212b22cc0c 100644--- a/frontend/editor/src-tauri/tauri.conf.json+++ b/frontend/editor/src-tauri/tauri.conf.json@@ -2,7 +2,7 @@"$schema": "../node_modules/@tauri-apps/cli/config.schema.json","productName": "Stirling PDF","mainBinaryName": "Stirling-PDF",- "version": "2.14.3",+ "version": "3.0.0","identifier": "stirling.pdf.dev","build": {"frontendDist": "../dist",diff --git a/frontend/editor/src/core/testing/serverExperienceSimulations.ts b/frontend/editor/src/core/testing/serverExperienceSimulations.tsindex 55ab79c111..01bdf8712e 100644--- a/frontend/editor/src/core/testing/serverExperienceSimulations.ts+++ b/frontend/editor/src/core/testing/serverExperienceSimulations.ts@@ -38,7 +38,7 @@ const FREE_LICENSE_INFO: LicenseInfo = {const BASE_NO_LOGIN_CONFIG: AppConfig = {enableAnalytics: true,- appVersion: "2.14.3",+ appVersion: "3.0.0",serverCertificateEnabled: false,enableAlphaFunctionality: false,serverPort: 8080,diff --git a/frontend/editor/src/proprietary/testing/serverExperienceSimulations.ts b/frontend/editor/src/proprietary/testing/serverExperienceSimulations.tsindex 0519b9afb8..0ad81fb0d5 100644--- a/frontend/editor/src/proprietary/testing/serverExperienceSimulations.ts+++ b/frontend/editor/src/proprietary/testing/serverExperienceSimulations.ts@@ -48,7 +48,7 @@ const FREE_LICENSE_INFO: LicenseInfo = {const BASE_NO_LOGIN_CONFIG: AppConfig = {enableAnalytics: true,- appVersion: "2.14.3",+ appVersion: "3.0.0",serverCertificateEnabled: false,enableAlphaFunctionality: false,enableDesktopInstallSlide: true,diff --git a/scripts/db-migration/run-postgres-migration-test.py b/scripts/db-migration/run-postgres-migration-test.pynew file mode 100644index 0000000000..50998921e1--- /dev/null+++ b/scripts/db-migration/run-postgres-migration-test.py@@ -0,0 +1,491 @@+#!/usr/bin/env python3+"""Boot historical releases on PostgreSQL, seed data, then test the current JAR.++Requires Docker, Java 25, and an Enterprise PREMIUM_KEY for audit fixtures.+Only disposable containers created by this script are used. No external DB is touched.+"""++import argparse+import http.cookiejar+import json+import os+from pathlib import Path+import re+import shutil+import socket+import subprocess+import tempfile+import time+import urllib.error+import urllib.parse+import urllib.request+++REPO_ROOT = Path(__file__).resolve().parents[2]+FIXTURES = REPO_ROOT / "app/proprietary/src/test/resources/db-migration-fixtures"+FIXTURE_PASSWORD = "migration-test-password"+FIXTURE_USERS = {+ "migration_alice": "Migration Finance",+ "migration_bob": "Migration Operations",+ "migration_disabled": "Migration Finance",+}+FIXTURE_SETTINGS = {+ "theme": "dark",+ "language": "en-GB",+ "migrationNote": "R\u00e9sum\u00e9 \u03a9 \u2014 preserved setting",+}+SCHEMA_ERRORS = re.compile(+ r"SchemaManagementException|GenerationTarget encountered exception|Flyway.*FAILED",+ re.IGNORECASE,+)+# Compare persistent identity/credential/relationship data, excluding timestamps and+# license entitlements which may legitimately change when the new app starts.+SNAPSHOT_SQL = """+SELECT json_build_object(+ 'users', (SELECT json_agg(row_to_json(u) ORDER BY u.user_id) FROM+ (SELECT user_id, username, team_id, enabled, authenticationtype FROM users) u),+ 'credentials', (SELECT json_agg(row_to_json(u) ORDER BY u.user_id) FROM+ (SELECT user_id, username, password, api_key FROM users+ WHERE username IN ('admin', 'migration_alice', 'migration_bob', 'migration_disabled')) u),+ 'authorities', (SELECT json_agg(row_to_json(a) ORDER BY a.user_id, a.authority) FROM+ (SELECT user_id, authority FROM authorities) a),+ 'teams', (SELECT json_agg(row_to_json(t) ORDER BY t.team_id) FROM+ (SELECT team_id, name FROM teams) t)+);+"""+++def log(message):+ print(f"[postgres-migration] {message}", flush=True)+++def run(*args, **kwargs):+ return subprocess.run(args, check=True, text=True, encoding="utf-8", capture_output=True, **kwargs).stdout.strip()+++def sql(container, statement):+ return run(+ "docker",+ "exec",+ "-i",+ container,+ "psql",+ "-X",+ "-qAt",+ "-v",+ "ON_ERROR_STOP=1",+ "-U",+ "migration",+ "-d",+ "stirling",+ input=statement,+ )+++def free_port():+ with socket.socket() as sock:+ sock.bind(("127.0.0.1", 0))+ return sock.getsockname()[1]+++def request(base_url, path, data=None, *, token=None, form=False):+ payload = None+ headers = {"Content-Type": "application/x-www-form-urlencoded" if form else "application/json"}+ if data is not None:+ payload = (urllib.parse.urlencode(data) if form else json.dumps(data)).encode()+ if token:+ headers["Authorization"] = f"Bearer {token}"+ cookies = http.cookiejar.CookieJar()+ opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cookies))+ if token and data is not None:+ # Historical releases require a CSRF cookie/header even with a JWT.+ with opener.open(urllib.request.Request(base_url + "/api/v1/info/status", headers=headers), timeout=30):+ pass+ for cookie in cookies:+ if cookie.name == "XSRF-TOKEN":+ headers["X-XSRF-TOKEN"] = urllib.parse.unquote(cookie.value)+ req = urllib.request.Request(base_url + path, data=payload, headers=headers)+ try:+ with opener.open(req, timeout=30) as response:+ return response.status, response.read()+ except urllib.error.HTTPError as exc:+ return exc.code, exc.read()+++def api(base_url, path, data=None, **kwargs):+ code, body = request(base_url, path, data, **kwargs)+ if code != 200:+ raise RuntimeError(f"{path} returned HTTP {code}: {body.decode(errors='replace')[:300]}")+ return json.loads(body)+++def login(base_url, username, password):+ response = api(base_url, "/api/v1/auth/login", {"username": username, "password": password})+ token = response.get("session", {}).get("access_token")+ if not token or response.get("user", {}).get("username") != username:+ raise RuntimeError(f"Login did not authenticate {username}")+ return token+++def settings_for(username):+ return {**FIXTURE_SETTINGS, "migrationNote": f"{FIXTURE_SETTINGS['migrationNote']} ({username})"}+++def seed_data(base_url, container, admin_token):+ for name in sorted(set(FIXTURE_USERS.values())):+ api(base_url, "/api/v1/team/create", {"name": name}, token=admin_token, form=True)+ team_ids = {+ row["name"]: row["team_id"]+ for row in json.loads(sql(container, "SELECT json_agg(t) FROM (SELECT team_id, name FROM teams) t;"))+ }+ for username, team in FIXTURE_USERS.items():+ api(+ base_url,+ "/api/v1/user/admin/saveUser",+ {+ "username": username,+ "password": FIXTURE_PASSWORD,+ "role": "ROLE_USER",+ "authType": "WEB",+ "forceChange": "false",+ "teamId": team_ids[team],+ },+ token=admin_token,+ form=True,+ )+ token = login(base_url, username, FIXTURE_PASSWORD)+ api(base_url, "/api/v1/user/updateUserSettings", settings_for(username), token=token)+ log(f"Seeded {username}: {team}, ROLE_USER, and {len(FIXTURE_SETTINGS)} settings")+ api(+ base_url,+ "/api/v1/user/admin/changeUserEnabled/migration_disabled",+ {"enabled": "false"},+ token=admin_token,+ form=True,+ )+ # Audit writes are asynchronous and fail open in historical releases. An+ # HTTP success alone must not let an empty audit table pass as a fixture.+ for _ in range(30):+ principals = json.loads(+ sql(container, "SELECT coalesce(json_agg(DISTINCT principal), '[]') FROM audit_events;")+ )+ if {"admin", *FIXTURE_USERS} <= set(principals):+ return+ time.sleep(1)+ raise RuntimeError("Historical release did not persist audit events for every seeded user and admin")+++def snapshot(container, *, audit_ids=None):+ result = json.loads(sql(container, SNAPSHOT_SQL))+ result["settings"] = json.loads(+ sql(+ container,+ """+ SELECT coalesce(json_agg(row_to_json(s) ORDER BY s.username, s.setting_key), '[]') FROM+ (SELECT u.username, s.setting_key, s.setting_value+ FROM user_settings s JOIN users u ON u.user_id = s.user_id+ WHERE u.username IN ('migration_alice', 'migration_bob', 'migration_disabled')+ AND s.setting_key IN ('theme', 'language', 'migrationNote')) s;+ """,+ )+ )+ condition = "principal IN ('admin', 'migration_alice', 'migration_bob', 'migration_disabled')"+ if audit_ids is not None:+ condition = "id IN (" + ",".join(str(int(event_id)) for event_id in audit_ids) + ")"+ result["audit"] = json.loads(+ sql(+ container,+ f"""+ SELECT coalesce(json_agg(row_to_json(a) ORDER BY a.id), '[]') FROM+ (SELECT id, principal, type, timestamp, data FROM audit_events WHERE {condition}) a;+ """,+ )+ )+ for event in result["audit"]:+ event["data"] = json.loads(event["data"])+ return result+++def validate_fixture(result):+ users = {user["username"]: user for user in result["users"] or []}+ teams = {team["team_id"]: team["name"] for team in result["teams"] or []}+ if not {"admin", "STIRLING-PDF-BACKEND-API-USER", *FIXTURE_USERS} <= users.keys():+ raise RuntimeError("Missing users from the fixture")+ if not {"Default", "Internal", *FIXTURE_USERS.values()} <= set(teams.values()):+ raise RuntimeError("Missing default or custom teams")+ for username, team in FIXTURE_USERS.items():+ user = users[username]+ if teams.get(user["team_id"]) != team or user["enabled"] != (username != "migration_disabled"):+ raise RuntimeError(f"Incorrect team or enabled state for {username}")+ if {"user_id": user["user_id"], "authority": "ROLE_USER"} not in result["authorities"]:+ raise RuntimeError(f"Missing role for {username}")+ settings = {s["setting_key"]: s["setting_value"] for s in result["settings"] if s["username"] == username}+ if settings != settings_for(username):+ raise RuntimeError(f"User settings were not preserved for {username}")+ if {"user_id": users["admin"]["user_id"], "authority": "ROLE_ADMIN"} not in result["authorities"]:+ raise RuntimeError("Missing admin authority")+ if len(result["credentials"]) != 4 or any(not user["password"] for user in result["credentials"]):+ raise RuntimeError("Missing fixture credentials")+ if not {"admin", *FIXTURE_USERS} <= {event["principal"] for event in result["audit"]}:+ raise RuntimeError("Missing audit history for fixture users")+ if any(not isinstance(event["data"], dict) or not event["data"] for event in result["audit"]):+ raise RuntimeError("Audit history is missing its JSON payloads")+++def stop_app(process):+ if process is None or process.poll() is not None:+ return+ process.terminate()+ try:+ process.wait(timeout=20)+ except subprocess.TimeoutExpired:+ process.kill()+ process.wait(timeout=10)+++def boot_and_check(jar, workdir, db_port, timeout, container, seed_version=None, audit_ids=None):+ workdir.mkdir(parents=True)+ port = free_port()+ base_url = f"http://127.0.0.1:{port}"+ env = os.environ.copy()+ env.update(+ {+ "PREMIUM_ENABLED": "true",+ "PREMIUM_ENTERPRISEFEATURES_AUDIT_ENABLED": "true",+ "PREMIUM_ENTERPRISEFEATURES_AUDIT_LEVEL": "2",+ "PREMIUM_ENTERPRISEFEATURES_AUDIT_RETENTIONDAYS": "0",+ "SECURITY_ENABLELOGIN": "true",+ "SECURITY_INITIALLOGIN_USERNAME": "admin",+ "SECURITY_INITIALLOGIN_PASSWORD": "stirling",+ "SYSTEM_ENABLEANALYTICS": "false",+ "SYSTEM_DATASOURCE_ENABLECUSTOMDATABASE": "true",+ "SYSTEM_DATASOURCE_CUSTOMDATABASEURL": f"jdbc:postgresql://127.0.0.1:{db_port}/stirling",+ "SYSTEM_DATASOURCE_TYPE": "postgresql",+ "SYSTEM_DATASOURCE_USERNAME": "migration",+ "SYSTEM_DATASOURCE_PASSWORD": "migration-test-only",+ }+ )+ log_file = workdir / "app.log"+ process = None+ try:+ with log_file.open("w", encoding="utf-8") as output:+ process = subprocess.Popen(+ [+ "java",+ "-Xmx1g",+ "-jar",+ str(jar),+ f"--server.port={port}",+ "--spring.jpa.hibernate.ddl-auto=update",+ "--spring.jpa.show-sql=false",+ "--logging.level.root=WARN",+ "--logging.level.stirling=INFO",+ "--logging.level.org.hibernate.tool.schema=INFO",+ ],+ cwd=workdir,+ env=env,+ stdout=output,+ stderr=subprocess.STDOUT,+ creationflags=subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0,+ )+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ if process.poll() is not None:+ raise RuntimeError(f"App exited with code {process.returncode}: {log_file}")+ try:+ code, _ = request(base_url, "/api/v1/info/status")+ if code == 200:+ break+ except (urllib.error.URLError, TimeoutError, ConnectionError):+ pass+ time.sleep(2)+ else:+ raise RuntimeError(f"App did not become ready: {log_file}")++ contents = log_file.read_text(encoding="utf-8", errors="replace")+ if SCHEMA_ERRORS.search(contents):+ raise RuntimeError(f"Schema migration errors: {log_file}")+ if "Using custom database configuration" not in contents or "Using default H2 database" in contents:+ raise RuntimeError(f"App did not select PostgreSQL; check PREMIUM_KEY: {log_file}")+ # A live connection to this exact DB, plus rows in PostgreSQL, guards+ # against accidentally testing H2 or connecting to a different database.+ if (+ int(+ sql(+ container,+ "SELECT count(*) FROM pg_stat_activity WHERE datname = 'stirling' AND backend_type = 'client backend' AND pid <> pg_backend_pid();",+ )+ )+ < 1+ ):+ raise RuntimeError("No app connection to the test PostgreSQL database")+ admin_token = login(base_url, "admin", "stirling")+ if seed_version is not None:+ seed_data(base_url, container, admin_token)+ for username in FIXTURE_USERS:+ if username == "migration_disabled":+ code, _ = request(+ base_url, "/api/v1/auth/login", {"username": username, "password": FIXTURE_PASSWORD}+ )+ if code not in (401, 403):+ raise RuntimeError("Disabled user was not denied login")+ else:+ login(base_url, username, FIXTURE_PASSWORD)+ result = snapshot(container, audit_ids=audit_ids)+ if int(sql(container, "SELECT count(*) FROM user_license_settings;")) != 1:+ raise RuntimeError("Missing license settings singleton")+ log(+ f"Read {len(result['users'])} users, {len(result['teams'])} teams, "+ f"{len(result['settings'])} settings, and {len(result['audit'])} audit events"+ )+ return result+ finally:+ stop_app(process)+++def release_jar(version, directory):+ directory.mkdir(parents=True, exist_ok=True)+ jar = directory / f"stirling-pdf-{version}.jar"+ if not jar.is_file():+ log(f"Downloading historical release {version}")+ url = f"https://github.com/Stirling-Tools/Stirling-PDF/releases/download/{version}/Stirling-PDF-with-login.jar"+ partial = jar.with_suffix(".jar.part")+ with (+ urllib.request.urlopen(url, timeout=120) as response,+ partial.open("wb") as output,+ ):+ shutil.copyfileobj(response, output)+ partial.replace(jar)+ return jar.resolve()+++def test_version(version, old_jar, current_jar, workdir, image, timeout):+ workdir.mkdir(parents=True)+ container = None+ try:+ # Docker allocates the host port; bind only to loopback. Every release+ # gets its own DB and volume, and only the returned container is removed.+ container = run(+ "docker",+ "run",+ "--detach",+ "--publish",+ "127.0.0.1::5432",+ "--env",+ "POSTGRES_USER=migration",+ "--env",+ "POSTGRES_PASSWORD=migration-test-only",+ "--env",+ "POSTGRES_DB=stirling",+ image,+ )+ db_port = int(run("docker", "port", container, "5432/tcp").rsplit(":", 1)[1])+ deadline = time.monotonic() + 90+ while time.monotonic() < deadline:+ try:+ if sql(container, "SELECT 1;") == "1":+ break+ except subprocess.CalledProcessError:+ pass+ time.sleep(2)+ else:+ raise RuntimeError("PostgreSQL did not become ready")++ log(f"{version}: creating native PostgreSQL schema and fixture data")+ before = boot_and_check(old_jar, workdir / "historical", db_port, timeout, container, version)+ validate_fixture(before)+ # Keep a real PostgreSQL dump for reproducing failures / inspecting the+ # pre-upgrade schema. Restore it into a clean database before upgrading.+ dump = run(+ "docker",+ "exec",+ container,+ "pg_dump",+ "-U",+ "migration",+ "-d",+ "stirling",+ "--no-owner",+ "--no-privileges",+ )+ (workdir / "fixture.sql").write_text(dump + "\n", encoding="utf-8")+ run("docker", "exec", container, "dropdb", "-U", "migration", "stirling")+ run("docker", "exec", container, "createdb", "-U", "migration", "stirling")+ sql(container, dump)+ audit_ids = [event["id"] for event in before["audit"]]+ if snapshot(container, audit_ids=audit_ids) != before:+ raise RuntimeError("Restoring the PostgreSQL fixture changed its data")++ log(f"{version}: upgrading restored fixture with {current_jar.name}")+ # Startup and verification logins may append audit events. Compare all+ # original IDs so new activity cannot hide deleted or changed history.+ after = boot_and_check(current_jar, workdir / "upgraded", db_port, timeout, container, audit_ids=audit_ids)+ if before != after:+ changed = [key for key in before if before[key] != after[key]]+ raise RuntimeError(f"Upgrade changed fixture data: {', '.join(changed)}")+ log(f"PASS {version}: PostgreSQL upgrade, user logins, settings, and audit preservation")+ finally:+ if container:+ try:+ result = subprocess.run(["docker", "logs", container], text=True, capture_output=True)+ (workdir / "postgres.log").write_text(result.stdout + result.stderr, encoding="utf-8")+ finally:+ run("docker", "rm", "--force", "--volumes", container)+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument(+ "--jar",+ type=Path,+ default=os.environ.get("STIRLING_JAR"),+ required=not os.environ.get("STIRLING_JAR"),+ )+ parser.add_argument("--release-jar-dir", type=Path)+ parser.add_argument("--work-dir", type=Path)+ parser.add_argument("--versions", nargs="+", help="Defaults to H2 fixture versions from v2.5.0 onwards")+ parser.add_argument("--postgres-image", default="postgres:16")+ parser.add_argument("--startup-timeout", type=int, default=300)+ args = parser.parse_args()+ if not os.environ.get("PREMIUM_KEY"):+ parser.error("PREMIUM_KEY is required: historical releases need an Enterprise license for audit fixtures")+ if not args.jar.is_file():+ parser.error(f"Current JAR does not exist: {args.jar}")+ versions = args.versions or sorted(+ p.name.removeprefix("stirling-pdf-").removesuffix(".mv.db") for p in FIXTURES.glob("stirling-pdf-*.mv.db")+ )+ if not versions or any(not re.fullmatch(r"v\d+\.\d+\.\d+", version) for version in versions):+ parser.error("Expected fixture versions such as v2.5.0")+ version_numbers = {version: tuple(map(int, version[1:].split("."))) for version in versions}+ if args.versions and any(number < (2, 5, 0) for number in version_numbers.values()):+ parser.error("PostgreSQL upgrade coverage starts at v2.5.0")+ versions = sorted(+ (version for version in versions if version_numbers[version] >= (2, 5, 0)), key=version_numbers.get+ )+ if not versions:+ parser.error("No PostgreSQL fixtures at or after v2.5.0 were found")+ workdir = (args.work_dir or Path(tempfile.mkdtemp(prefix="stirling-mig-postgres-"))).resolve()+ release_dir = (args.release_jar_dir or workdir / "jars").resolve()+ log(f"Logs and pre-upgrade SQL fixtures: {workdir}")+ failed = []+ for version in versions:+ try:+ old_jar = release_jar(version, release_dir)+ test_version(+ version,+ old_jar,+ args.jar.resolve(),+ workdir / version,+ args.postgres_image,+ args.startup_timeout,+ )+ except (RuntimeError, OSError, ValueError, subprocess.SubprocessError) as exc:+ log(f"FAIL {version}: {exc}")+ failed.append(version)+ if failed:+ raise SystemExit(f"PostgreSQL migration failures: {', '.join(failed)}")+ log(f"All {len(versions)} PostgreSQL fixtures migrated cleanly")+++if __name__ == "__main__":+ main()