mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-24 22:03:04 +00:00
Compare commits
165 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 8d947cc900 | |||
| a0f4a8791e | |||
| 8b3c251e73 | |||
| 43611b3c7f | |||
| 3c3f985d99 | |||
| a8f3a586dd | |||
| 64df2117dc | |||
| 2b14fe1a2a | |||
| 28f93f2539 | |||
| 9f4c8e106c | |||
| f47490dd9f | |||
| 620f5a94f6 | |||
| 57a3c732f2 | |||
| e95127c945 | |||
| ccad725b29 | |||
| b5cdf3d48f | |||
| 1054d79f9e | |||
| 459c4454ad | |||
| 0460b08a79 | |||
| 9327dc309a | |||
| f4a6411511 | |||
| dc75c200b1 | |||
| 56a1a832b2 | |||
| 7d4b150859 | |||
| 5ff5e76603 | |||
| 685506d067 | |||
| 143e2ae447 | |||
| 1b216d8f48 | |||
| 6304cb2e6a | |||
| f9877d0694 | |||
| e22210aca8 | |||
| 563fef0521 | |||
| 8cfd18e6da | |||
| f19aae6821 | |||
| 861f6ba789 | |||
| fcddde71a7 | |||
| 280e9ab0d9 | |||
| 4284a90b03 | |||
| 475597a6d7 | |||
| 4f8ae98e7d | |||
| 65d55add5a | |||
| 17fff1a152 | |||
| f795508fcb | |||
| 8254ffd23b | |||
| b6618eac73 | |||
| f13d60e7e9 | |||
| 1b16fd1683 | |||
| 965a7f2ea8 | |||
| 88c2b8b991 | |||
| 3764efde7a | |||
| 11013711d6 | |||
| e083e2d480 | |||
| 59adaf2f0c | |||
| a09d16d6f7 | |||
| e1677e7d17 | |||
| 7b0f75a3a4 | |||
| 8a31a71e1a | |||
| 741bb651e5 | |||
| 97bafd3ab3 | |||
| 27c043be09 | |||
| 6159cb9011 | |||
| 6d2bf31bb6 | |||
| 62228af0d5 | |||
| 3572058917 | |||
| cfab220015 | |||
| b377c3656c | |||
| b11d8d492c | |||
| 53ab10afdc | |||
| 9631a59c2b | |||
| 40385267fc | |||
| 13b896f384 | |||
| 7bbeec9d9a | |||
| 33f777bcf8 | |||
| 6010694c08 | |||
| 03ee902c3d | |||
| 59f0c206bf | |||
| 6a9c1c287f | |||
| 4b0986e2c6 | |||
| d253267e49 | |||
| 373d272968 | |||
| ebf2a94fd6 | |||
| ac5f8ad67e | |||
| a72f4936e9 | |||
| b931b92fc0 | |||
| da7d4ff237 | |||
| f508e0b4c2 | |||
| 7e4561b469 | |||
| 40e904e237 | |||
| c848429820 | |||
| c46e34dc3a | |||
| 4e07de492b | |||
| fa193a400e | |||
| 203c7dee7e | |||
| 0eeee1e884 | |||
| 61ea6b648c | |||
| 981052224c | |||
| f311fed5c9 | |||
| 7065f87dc0 | |||
| 4eb2c3be58 | |||
| 6d8721ee82 | |||
| 36f64c51c8 | |||
| d177227519 | |||
| a6bc71787e | |||
| 5f372fa17f | |||
| 9f7efd49ea | |||
| 8e85fb1c2c | |||
| b82cd03a28 | |||
| 3460511fa4 | |||
| b345c92493 | |||
| 7a9a7c1831 | |||
| 99c3c670a5 | |||
| 7a99190550 | |||
| 7e8c74b8ff | |||
| 7bde1ec9d4 | |||
| ec733fc927 | |||
| 20fb054d27 | |||
| 90e74f4dd8 | |||
| 9c14f941ba | |||
| 6f4dfc486f | |||
| ce1c3cf62d | |||
| 28ce04d866 | |||
| 22973036b5 | |||
| 40f6efbf5b | |||
| e4b990b75e | |||
| 3b6d7238fe | |||
| 16da5dd685 | |||
| 53d875aecb | |||
| a748d6c554 | |||
| 90f1f1977d | |||
| 8c5e138150 | |||
| 1bf0670566 | |||
| 29cdc594d3 | |||
| a2d00111ca | |||
| 944ab3d29a | |||
| dc4972977c | |||
| 2318308674 | |||
| 1551f6d474 | |||
| 783ad5c0f1 | |||
| c0bae97a14 | |||
| e82968d66c | |||
| 98533f3dbe | |||
| 1c3dc93716 | |||
| b8c9184dff | |||
| f3e6480606 | |||
| 5503db4883 | |||
| 33a18f29dd | |||
| d498fe2bea | |||
| 0e93df378f | |||
| 1c73ac4c35 | |||
| ae005fc582 | |||
| 293cdbc353 | |||
| 63a2c9db00 | |||
| e848f343b5 | |||
| 4325c145ce | |||
| 53bd8505cd | |||
| 298f0409d5 | |||
| e0013bc077 | |||
| 526437926a | |||
| 3f1a786313 | |||
| c72b680fec | |||
| fc9e634d86 | |||
| 515caffa79 | |||
| a77705984e | |||
| 25f5e34558 | |||
| 62912e5db1 |
+134
-27
@@ -31,7 +31,11 @@ permissions:
|
||||
# thresholds, uploads lcov
|
||||
# Server: S3 Contract (MinIO)
|
||||
# the storage driver against MinIO
|
||||
# Server: Postgres Probe the repository SQL against Postgres
|
||||
# Server: Postgres 14/18 per supported major: the probe (the repository
|
||||
# SQL against Postgres), then the lane (every suite
|
||||
# that boots the app on the real database module,
|
||||
# plus PARITY-PG and the write lock;
|
||||
# vitest.pg.config.ts)
|
||||
# Client: Types & Checks typecheck and the strict ratchet; then the page
|
||||
# pattern and the source ratchets (RTL, size,
|
||||
# Prettier, layers, offline path, duplication,
|
||||
@@ -44,7 +48,7 @@ permissions:
|
||||
# Client: Bundle the production build, one chunk per map engine
|
||||
# Client: End-to-End the app in Chromium and WebKit
|
||||
# Plugin SDK: Types & Coverage
|
||||
# Repo: Docker Image builds the image and boots it until ready
|
||||
# Repo: Docker Image builds the image and boots it until ready, on SQLite and on Postgres 18
|
||||
# Repo: Helm Chart & Compose
|
||||
# Repo: Sonar Scan SonarCloud analysis, not required
|
||||
# ci-ok the one required check (below)
|
||||
@@ -65,9 +69,9 @@ permissions:
|
||||
# test jobs feeds the scan.
|
||||
# - Job count: GitHub runs at most 20 jobs of the organisation at once and
|
||||
# does not say in which order it starts queued ones. A code change starts
|
||||
# the 14 shards and about a dozen other jobs; seven of those (parity, the
|
||||
# SDK, the bundle, S3, Postgres, shared coverage, the chart) are done in
|
||||
# a minute or two, so what queues at the start waits about that long. The
|
||||
# the 14 shards and about a dozen other jobs; eight of those (parity, the
|
||||
# SDK, the bundle, S3, the two Postgres majors, shared coverage, the
|
||||
# chart) are done in a few minutes, so what queues at the start waits about that long. The
|
||||
# jobs that run for minutes (shards, gates, e2e, the image) must not
|
||||
# outnumber the 20 slots, or one of them waits for another to finish and
|
||||
# the run grows by a whole job: a layout with six gate jobs did exactly
|
||||
@@ -282,6 +286,15 @@ jobs:
|
||||
# migration that changes a column regenerates it in the same change.
|
||||
run: cd server && npm run check:db-types
|
||||
|
||||
- name: Postgres baseline manifest (and entities until a migration follows the cut)
|
||||
# server/assets/postgres/ is the schema a fresh Postgres database starts
|
||||
# from, generated from the entities by gen:pg-baseline. Until a migration
|
||||
# lands after its cut it must match them exactly; after, it is frozen,
|
||||
# its list of migrations is checked and the migrations after the cut are
|
||||
# listed: lint:dialect holds their engineDdl and PARITY-PG their result.
|
||||
# Either way every SQLite trigger needs its Postgres port.
|
||||
run: cd server && npm run check:pg-baseline
|
||||
|
||||
server-lint-checks:
|
||||
name: 'Server: Lint & Checks'
|
||||
needs: changes
|
||||
@@ -367,6 +380,12 @@ jobs:
|
||||
# so the code stays portable to a second engine.
|
||||
run: cd server && npm run lint:dialect
|
||||
|
||||
- name: Engine checks may only shrink
|
||||
# isSqlite(/isPostgres( and platform instanceof outside src/db/dialect/
|
||||
# and src/db/engine/ are held to scripts/engine-dispatch-baseline.json,
|
||||
# so what differs between engines stays in those two places.
|
||||
run: cd server && npm run lint:engine-dispatch
|
||||
|
||||
- name: Writes outside a transaction
|
||||
# A method that writes twice does it inside one uow.transactional.
|
||||
# Today's exceptions sit in scripts/tx-writes-baseline.json and may
|
||||
@@ -734,31 +753,48 @@ jobs:
|
||||
TREK_TEST_S3_SECRET_ACCESS_KEY: trekci-secret
|
||||
run: cd server && npx vitest run tests/unit/nest/storage/s3.driver.contract.test.ts
|
||||
|
||||
# What of the server's SQL runs on Postgres today (server/scripts/pg-probe.ts).
|
||||
# TREK runs on SQLite; the dialect layer in server/src/db/dialect/ is written
|
||||
# so a second engine is a branch there and not a sweep through the
|
||||
# repositories, and this is the job that holds it to that. Against an empty
|
||||
# Postgres it derives a schema from the entities, runs every dialect helper
|
||||
# on SQLite and Postgres (every case must pass), and calls every public
|
||||
# repository method once, each statement in its own rolled-back transaction.
|
||||
# The statements Postgres refuses as SQL are held per method to
|
||||
# TREK on Postgres, once per supported major: the oldest (14) and the newest
|
||||
# (18). Both steps run against the same service, the probe on an empty
|
||||
# database of its own, the lane on databases it creates and drops.
|
||||
#
|
||||
# The probe (server/scripts/pg-probe.ts): against an empty Postgres it
|
||||
# derives a schema from the entities, runs every dialect helper on SQLite
|
||||
# and Postgres (every case must pass), and calls every public repository
|
||||
# method once, each statement in its own rolled-back transaction. The
|
||||
# statements Postgres refuses as SQL are held per method to
|
||||
# server/scripts/pg-probe-baseline.json, and so is the list of methods it
|
||||
# could not measure (uncovered); both may only shrink. An unmeasured
|
||||
# baseline (failing or uncovered null) or a run that called no method fails. The measured
|
||||
# baseline and the full report are uploaded either way, so the first run's
|
||||
# artifact seeds the file and a change that fixes a statement can lower it
|
||||
# without a local Postgres.
|
||||
postgres-probe:
|
||||
name: 'Server: Postgres Probe'
|
||||
# could not measure (uncovered); both may only shrink, on every major. An
|
||||
# unmeasured baseline (failing or uncovered null) or a run that called no
|
||||
# method fails. The measured baseline and the full report are uploaded
|
||||
# either way (pg-probe-baseline-<major>), so a change that fixes a statement
|
||||
# can lower the file without a local Postgres.
|
||||
#
|
||||
# The lane (server/vitest.pg.config.ts): every suite that boots the app on
|
||||
# the real database module, found by server/tests/postgres/lane.ts, each file
|
||||
# on its own copy of one migrated template, plus the Postgres-only suites
|
||||
# (PARITY-PG, the write lock, the search semantics). It fails, never skips,
|
||||
# without TREK_TEST_DB_URL, and TREK_TEST_PG_MAJOR makes it refuse a service
|
||||
# of another major. It runs after a red probe too, so one run shows both.
|
||||
#
|
||||
# About four minutes per major: a minute of setup, the probe in about one,
|
||||
# the lane in about two on four workers. Past one runner's worth, add a
|
||||
# shard axis to the matrix and pass --shard=<i>/<n>; each slice builds its
|
||||
# own template.
|
||||
server-postgres:
|
||||
name: 'Server: Postgres ${{ matrix.postgres }}'
|
||||
runs-on: ubuntu-24.04
|
||||
timeout-minutes: 10
|
||||
timeout-minutes: 20
|
||||
needs: changes
|
||||
if: needs.changes.outputs.code == 'true'
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
postgres: [14, 18]
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:17
|
||||
image: postgres:${{ matrix.postgres }}
|
||||
env:
|
||||
POSTGRES_PASSWORD: probe
|
||||
POSTGRES_PASSWORD: lane
|
||||
POSTGRES_DB: trek_probe
|
||||
ports:
|
||||
- 5432:5432
|
||||
@@ -788,23 +824,30 @@ jobs:
|
||||
|
||||
- name: Run the Postgres probe
|
||||
env:
|
||||
TREK_PG_PROBE_URL: postgres://postgres:probe@127.0.0.1:5432/trek_probe
|
||||
TREK_PG_PROBE_URL: postgres://postgres:lane@127.0.0.1:5432/trek_probe
|
||||
run: >-
|
||||
cd server && npm run probe:pg --
|
||||
--next-baseline="$RUNNER_TEMP/pg-probe-baseline.json"
|
||||
--report="$RUNNER_TEMP/pg-probe-report.json"
|
||||
|
||||
- name: Upload the measured baseline and the report
|
||||
if: always()
|
||||
if: ${{ !cancelled() }}
|
||||
uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: pg-probe-baseline
|
||||
name: pg-probe-baseline-${{ matrix.postgres }}
|
||||
path: |
|
||||
${{ runner.temp }}/pg-probe-baseline.json
|
||||
${{ runner.temp }}/pg-probe-report.json
|
||||
if-no-files-found: ignore
|
||||
retention-days: 14
|
||||
|
||||
- name: Run the Postgres lane
|
||||
if: ${{ !cancelled() }}
|
||||
env:
|
||||
TREK_TEST_DB_URL: postgres://postgres:lane@127.0.0.1:5432/postgres
|
||||
TREK_TEST_PG_MAJOR: ${{ matrix.postgres }}
|
||||
run: npm run test:pg --workspace=server
|
||||
|
||||
# The server suite in seven slices. vitest.shard.config.ts is vitest.config.ts
|
||||
# without the thresholds and the coverage reports: a slice's blob carries
|
||||
# its coverage to server-coverage, which checks the whole. fail-fast is off,
|
||||
@@ -1208,10 +1251,74 @@ jobs:
|
||||
docker logs trek-ci 2>&1 | grep 'SIGTERM received' >/dev/null \
|
||||
|| { echo "::error::the server never saw SIGTERM"; exit 1; }
|
||||
|
||||
# The same image on a Postgres database (TREK_DB_URL): an empty database
|
||||
# gets the baseline schema, the admin is seeded, and the server answers
|
||||
# ready. The database runs beside it on a private network, never exposed.
|
||||
# It is the newest supported major, the one the image's client tools are
|
||||
# for; server-postgres covers the oldest.
|
||||
- name: Start the container on Postgres
|
||||
run: |
|
||||
set -euo pipefail
|
||||
docker network create trek-ci-pg
|
||||
docker run -d --name trek-ci-db --network trek-ci-pg \
|
||||
-e POSTGRES_PASSWORD=ci -e POSTGRES_DB=trek postgres:18
|
||||
for _ in $(seq 1 30); do
|
||||
docker exec trek-ci-db pg_isready -U postgres -d trek >/dev/null 2>&1 && break
|
||||
sleep 2
|
||||
done
|
||||
docker exec trek-ci-db pg_isready -U postgres -d trek \
|
||||
|| { echo "::error::Postgres did not accept connections within 60 seconds."; exit 1; }
|
||||
mkdir -p "$RUNNER_TEMP/trek-pg/data" "$RUNNER_TEMP/trek-pg/uploads"
|
||||
docker run -d --name trek-ci-on-pg --network trek-ci-pg -p 127.0.0.1:3001:3000 \
|
||||
--read-only --tmpfs /tmp:noexec,nosuid,size=128m \
|
||||
--security-opt no-new-privileges:true \
|
||||
--cap-drop ALL --cap-add CHOWN --cap-add SETUID --cap-add SETGID --cap-add KILL \
|
||||
-v "$RUNNER_TEMP/trek-pg/data:/app/data" \
|
||||
-v "$RUNNER_TEMP/trek-pg/uploads:/app/uploads" \
|
||||
-e ENCRYPTION_KEY="$(openssl rand -hex 32)" \
|
||||
-e TREK_DB_URL=postgres://postgres:ci@trek-ci-db:5432/trek \
|
||||
trek:ci
|
||||
|
||||
# Twice: the first start creates the schema in the empty database, the
|
||||
# restart finds it migrated and must start without touching it.
|
||||
- name: Wait until the server on Postgres is ready, then again after a restart
|
||||
run: |
|
||||
wait_ready() {
|
||||
for _ in $(seq 1 90); do
|
||||
if [ "$(docker inspect -f '{{.State.Running}}' trek-ci-on-pg)" != "true" ]; then
|
||||
echo "::error::The container on Postgres exited before it became ready."
|
||||
exit 1
|
||||
fi
|
||||
if curl -sf http://127.0.0.1:3001/api/health/ready; then
|
||||
echo
|
||||
return 0
|
||||
fi
|
||||
sleep 2
|
||||
done
|
||||
echo "::error::/api/health/ready on Postgres did not answer within 180 seconds."
|
||||
exit 1
|
||||
}
|
||||
wait_ready
|
||||
docker restart -t 30 trek-ci-on-pg >/dev/null
|
||||
wait_ready
|
||||
|
||||
- name: Stop the container on Postgres gracefully
|
||||
run: |
|
||||
set -euo pipefail
|
||||
docker stop -t 30 trek-ci-on-pg >/dev/null
|
||||
code="$(docker inspect -f '{{.State.ExitCode}}' trek-ci-on-pg)"
|
||||
[ "$code" = "0" ] || { echo "::error::docker stop ended with exit code $code, not a graceful shutdown"; exit 1; }
|
||||
|
||||
- name: Container log
|
||||
if: always()
|
||||
run: docker logs trek-ci 2>&1 || true
|
||||
|
||||
- name: Container log on Postgres
|
||||
if: always()
|
||||
run: |
|
||||
docker logs trek-ci-on-pg 2>&1 || true
|
||||
docker logs trek-ci-db 2>&1 | tail -50 || true
|
||||
|
||||
# The Helm chart and the compose files are what self-hosters deploy from,
|
||||
# and before this job only a release ever touched them. The chart is linted,
|
||||
# rendered with the defaults and with each secret and persistence mode, and
|
||||
@@ -1331,7 +1438,7 @@ jobs:
|
||||
- client-bundle
|
||||
- client-e2e
|
||||
- s3-contract
|
||||
- postgres-probe
|
||||
- server-postgres
|
||||
- server-tests
|
||||
- server-coverage
|
||||
- client-tests
|
||||
|
||||
@@ -31,6 +31,7 @@ Tests:
|
||||
npm run test # all workspaces
|
||||
npm run test --workspace=server # vitest run (server); also test:unit / test:integration / test:ws
|
||||
npm run test:e2e # server e2e (boots Nest against a temp SQLite)
|
||||
npm run test:pg --workspace=server # the Postgres lane (vitest.pg.config.ts; needs TREK_TEST_DB_URL, e.g. postgres://postgres:trek@127.0.0.1:55432/postgres)
|
||||
npm run test:cov # coverage (lcov) for all four packages incl. plugin-sdk
|
||||
cd client && npm run test # client vitest run
|
||||
cd client && npm run e2e # Playwright (CI runs the public and app projects; the screenshot and help-media ones are local)
|
||||
@@ -51,7 +52,9 @@ cd client && npm run lint:skips # no .only; skipped tests may
|
||||
cd client && npm run lint:i18n-keys # every key the client names exists in en; unused en keys may only shrink (CI gate)
|
||||
cd server && npm run lint:boundaries # no new import cycles or cross-domain reach-ins (CI gate)
|
||||
cd server && npm run lint:dialect # SQLite-only SQL spellings may only shrink (CI gate; rules in server/CLAUDE.md)
|
||||
cd server && npm run lint:engine-dispatch # engine checks outside src/db/dialect/ and src/db/engine/ may only shrink (CI gate)
|
||||
cd server && npm run probe:pg # dialect helpers + the repository statements it reaches against Postgres (CI job; needs TREK_PG_PROBE_URL)
|
||||
cd server && npm run check:pg-baseline # the Postgres baseline in server/assets/postgres/ matches the entities and the migrations (CI gate)
|
||||
cd server && npm run lint:tx # no new method writing twice outside one transaction (CI gate)
|
||||
cd server && npm run lint:test-sql # raw SQL fixtures in tests/ may only shrink; seed through tests/helpers/factories (CI gate)
|
||||
cd server && npm run lint:test-mocks # vi.mock of config, realtime and db modules in tests/ may only shrink (CI gate)
|
||||
@@ -134,11 +137,11 @@ These principles come out of a full-repo audit and shape all new code:
|
||||
|
||||
## Quality gates in CI
|
||||
|
||||
`.github/workflows/test.yml` runs, per package: typecheck (server also `typecheck:tests`, client also the strict-mode ratchet `lint:strict`), lint (client and server through `lint:warnings`, which also holds the warning count per rule), `lint:pages`, `lint:rtl`, `lint:size` (client and server), the server's `lint:strict`, `lint:boundaries`, `lint:tx`, `lint:dialect`, `lint:test-sql`, `lint:test-mocks`, `lint:test-new-service`, `lint:query-api`, `lint:mcp-zod`, `lint:service-http` and `lint:response-contracts`, the client's and server's `lint:format`, `lint:layers`, `lint:offline`, `lint:dup`, `lint:pairs`, `lint:skips`, `lint:i18n-keys` and `theme:lint`, shared's `contracts:open`, the repo-wide `lint:knip` (in server-lint-checks), `check:plugin-facts`, `i18n:parity:strict` (with the untranslated-strings ratchet), the S3 contract suite, the Postgres probe (`postgres-probe`: every dialect helper on SQLite and Postgres, and the statements every repository method reaches with sample arguments against a Postgres service; the SQL errors per method and the list of methods it cannot measure are held to a baseline that only shrinks and fails while it is still unmeasured; see `server/CLAUDE.md`), the browser end-to-end flows (Chromium and WebKit), a client build with `check:gl-split`, coverage for all four packages, then a SonarCloud scan. It also builds the Docker image and boots it until `/api/health/ready` answers (`docker-image`), and lints and renders the Helm chart against the Kubernetes schemas and runs `docker compose config` on every compose file (`deploy-manifests`). `lint-prettier.yml` additionally runs `lint` + `lint:format` on `shared/`, both check-only. `plugin-sdk` has no lint script and is outside the eslint gates. **Not in CI**: the screenshot and help-media Playwright projects; run them locally. There are no git hooks; nothing runs before a commit except you. Other workflows build Docker images, scan them, and publish `trek-plugin-sdk` on `plugin-sdk-v*` tags.
|
||||
`.github/workflows/test.yml` runs, per package: typecheck (server also `typecheck:tests`, client also the strict-mode ratchet `lint:strict`), lint (client and server through `lint:warnings`, which also holds the warning count per rule), `lint:pages`, `lint:rtl`, `lint:size` (client and server), the server's `lint:strict`, `lint:boundaries`, `lint:tx`, `lint:dialect`, `lint:engine-dispatch`, `lint:test-sql`, `lint:test-mocks`, `lint:test-new-service`, `lint:query-api`, `lint:mcp-zod`, `lint:service-http` and `lint:response-contracts`, the client's and server's `lint:format`, `lint:layers`, `lint:offline`, `lint:dup`, `lint:pairs`, `lint:skips`, `lint:i18n-keys` and `theme:lint`, shared's `contracts:open`, the repo-wide `lint:knip` (in server-lint-checks), `check:plugin-facts`, `i18n:parity:strict` (with the untranslated-strings ratchet), the S3 contract suite, TREK on Postgres (`server-postgres`, once per supported major, 14 and 18: first the Postgres probe, every dialect helper on SQLite and Postgres and the statements every repository method reaches with sample arguments, its SQL errors per method and the methods it cannot measure held to a baseline that only shrinks and fails while it is still unmeasured; then the Postgres lane, every suite that boots the app on the real database module, found by `server/tests/postgres/lane.ts` rather than listed, plus PARITY-PG and the write lock; see `server/CLAUDE.md`), the browser end-to-end flows (Chromium and WebKit), a client build with `check:gl-split`, coverage for all four packages, then a SonarCloud scan. It also builds the Docker image and boots it until `/api/health/ready` answers, on SQLite and on Postgres 18 (`docker-image`), and lints and renders the Helm chart against the Kubernetes schemas and runs `docker compose config` on every compose file (`deploy-manifests`). `lint-prettier.yml` additionally runs `lint` + `lint:format` on `shared/`, both check-only. `plugin-sdk` has no lint script and is outside the eslint gates. **Not in CI**: the screenshot and help-media Playwright projects; run them locally. There are no git hooks; nothing runs before a commit except you. Other workflows build Docker images, scan them, and publish `trek-plugin-sdk` on `plugin-sdk-v*` tags.
|
||||
|
||||
- **Job names read "package: what"** (`Server: Types`, `Client: Tests 3/7`), and the list at the top of `test.yml` says what each job holds. A new job follows the scheme and joins that list, and the job-count note there says when a long job needs a slot freed first.
|
||||
- **Tests run beside the gates, in shards.** The client and server suites run in slices on parallel runners (`client-tests`, `server-tests`, through each package's `vitest.shard.config.ts`), and `client-coverage`/`server-coverage` merge their blob reports and check the thresholds against the whole. A red slice is usually a failing test, a red merge job usually a threshold.
|
||||
- **`ci-ok` is the required check.** The branch ruleset requires `ci-ok` (plus `lint` and `check-target` from their own workflows), and `ci-ok` needs every job above except the scan. It fails if any of them failed or was cancelled and passes if they passed or were skipped. A new gate job counts only once it is listed in `ci-ok`'s `needs:`.
|
||||
- **`ci-ok` is the required check.** The branch ruleset requires `ci-ok` (plus `lint` and `check-target` from their own workflows), and `ci-ok` needs every job above except the scan. It fails if any of them failed or was cancelled and passes if they passed or were skipped. A new gate job counts only once it is listed in `ci-ok`'s `needs:`, and `scripts/ci/workflow-jobs.test.mjs` (in `test:ci-scripts`) fails while a job other than the scan is missing there.
|
||||
- **Guides name paths that exist**: the `changes` job runs `scripts/ci/doc-paths.mjs`, which resolves every backtick path in the CLAUDE.md files, `README.md`, `server/src/nest/README.md` and the wiki against the tracked files; the missing ones are listed in `scripts/ci/doc-paths-baseline.json`, which only shrinks (`--update` after a fix).
|
||||
- **What runs is decided by `changes`, not by `on.paths`**: `scripts/ci/changed-areas.mjs` maps the changed files to the `code`, `image` and `deploy` areas (tests: `npm run test:ci-scripts`). A path filter on the workflow would leave `ci-ok` unreported on a docs-only PR and block it. Add a new top-level file the build reads to the right area there.
|
||||
- **Runners and Node**: jobs run on `ubuntu-24.04`, not `ubuntu-latest`, and every `setup-node` reads `.nvmrc`. Third-party actions (anything outside `actions/*`) are pinned by commit SHA with the tag in a comment; Dependabot keeps both current.
|
||||
|
||||
+20
-6
@@ -72,10 +72,23 @@ COPY server/package.json ./server/
|
||||
# package, and a telemetry ping.
|
||||
# The upgrade takes the Debian security fixes the base image was built before
|
||||
# (zlib, 11/2026, failed the image scan until node:24-trixie-slim caught up).
|
||||
RUN apt-get update && \
|
||||
#
|
||||
# postgresql-client-18 brings pg_dump, pg_restore and psql to
|
||||
# /usr/lib/postgresql/18/bin, which back up and restore an install on Postgres
|
||||
# (TREK_DB_URL). A client handles every server up to its own major and refuses
|
||||
# a newer one, so the image carries the newest major TREK supports (14 to 18).
|
||||
# Debian 13 ships 17 only, so it comes from the PostgreSQL project's apt
|
||||
# repository (PGDG): the `18` component lists that major's packages and no
|
||||
# other, and the repository's signing key (fingerprint B97B 0AFC AA1A 47F0 44F2
|
||||
# 44A0 7FCC 7D46 ACCC 4CF8) is kept beside the entrypoint instead of fetched at
|
||||
# build time. Raise both together when TREK supports a newer major.
|
||||
COPY server/scripts/pgdg-apt-key.asc /etc/apt/keyrings/pgdg.asc
|
||||
RUN echo 'deb [signed-by=/etc/apt/keyrings/pgdg.asc] http://apt.postgresql.org/pub/repos/apt trixie-pgdg main 18' \
|
||||
> /etc/apt/sources.list.d/pgdg.list && \
|
||||
apt-get update && \
|
||||
apt-get upgrade -y --no-install-recommends && \
|
||||
apt-get install -y --no-install-recommends tzdata dumb-init wget ca-certificates \
|
||||
libkitinerary-bin libsqlite3-0 && \
|
||||
libkitinerary-bin libsqlite3-0 postgresql-client-18 && \
|
||||
npm ci --workspace=server --omit=dev --ignore-scripts && \
|
||||
{ ln -sf "$(find /usr/lib -name kitinerary-extractor -type f | head -1)" /usr/local/bin/kitinerary-extractor || true; } && \
|
||||
rm -rf /var/lib/apt/lists/* /usr/local/lib/node_modules/npm /usr/local/bin/npm /usr/local/bin/npx && \
|
||||
@@ -94,8 +107,9 @@ ENV KITINERARY_EXTRACTOR_PATH=/usr/local/bin/kitinerary-extractor
|
||||
|
||||
COPY --chown=node:node --from=server-builder /app/server/dist ./server/dist
|
||||
# Runtime data assets read from server/assets at runtime: airports.json (flight
|
||||
# transport search) and atlas/*.geojson.gz + atlas/admin1/*.geojson.gz (Atlas
|
||||
# country/region map). The build
|
||||
# transport search), atlas/*.geojson.gz + atlas/admin1/*.geojson.gz (Atlas
|
||||
# country/region map) and postgres/baseline.* (the schema a fresh Postgres
|
||||
# database starts from). The build
|
||||
# only emits dist, so these must be copied explicitly or the features silently
|
||||
# degrade to empty in the image.
|
||||
COPY --chown=node:node --from=server-builder /app/server/assets ./server/assets
|
||||
@@ -106,9 +120,9 @@ COPY --chown=node:node wiki ./wiki
|
||||
# tsconfig-paths/register reads this at runtime to resolve MCP SDK paths.
|
||||
COPY --chown=node:node server/tsconfig.json ./server/
|
||||
# Encryption-key rotation is run on demand via tsx (a prod dep) straight from the
|
||||
# raw .ts source — it never enters dist, so it must be copied in explicitly or
|
||||
# raw .ts source (the command and its stores module) — they never enter dist, so they must be copied in explicitly or
|
||||
# `node --import tsx scripts/migrate-encryption.ts` fails with module-not-found.
|
||||
COPY --chown=node:node server/scripts/migrate-encryption.ts ./server/scripts/migrate-encryption.ts
|
||||
COPY --chown=node:node server/scripts/migrate-encryption.ts server/scripts/migrate-encryption-stores.ts ./server/scripts/
|
||||
# Admin recovery script (node server/reset-admin.js) for locked-out installs.
|
||||
COPY --chown=node:node server/reset-admin.js ./server/reset-admin.js
|
||||
COPY --chown=node:node --from=shared-builder /app/shared/dist ./shared/dist
|
||||
|
||||
@@ -321,6 +321,11 @@ 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 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, the backups and
|
||||
how to move an existing SQLite install to Postgres with the command TREK ships for it.
|
||||
|
||||
<br />
|
||||
|
||||
<h2 id="helm-kubernetes">Helm (Kubernetes)</h2>
|
||||
|
||||
@@ -46,6 +46,7 @@ See `values.yaml` for more options.
|
||||
- Both PVCs are `ReadWriteOnce`. Set `persistence.data.accessModes` and/or `persistence.uploads.accessModes` to override, for example `[ReadWriteMany]` so a backup pod can mount the volume. On the data volume such a pod may only read: SQLite corrupts `travel.db` when a second process writes it over a network filesystem.
|
||||
- To use your own PVCs, set `persistence.data.existingClaim` and/or `persistence.uploads.existingClaim`. The other values for that volume (size, storageClassName, accessModes, annotations) are then ignored.
|
||||
- With `persistence.enabled: false`, the data and uploads volumes use an `emptyDir` — storage is ephemeral and lost on pod restart. Intended for testing only.
|
||||
- `database.url` runs TREK on a PostgreSQL database instead of the SQLite file. The chart writes it into its Secret as `TREK_DB_URL`; `database.existingSecret` and `database.existingSecretKey` read it from a Secret you manage. Leave both empty for SQLite. Keep `replicas: 1` either way. See the wiki page `Database-Postgres`.
|
||||
- `JWT_SECRET` is managed entirely by the server — auto-generated into the data PVC on first start and rotatable via the admin panel (Settings → Danger Zone). No Helm configuration needed.
|
||||
- `ENCRYPTION_KEY` encrypts stored secrets (API keys, MFA, SMTP, OIDC) at rest. Recommended: set via `secretEnv.ENCRYPTION_KEY` or `existingSecret`. If left empty, the server falls back automatically: existing installs use `data/.jwt_secret` (no action needed on upgrade); fresh installs auto-generate a key persisted to the data PVC.
|
||||
- Liveness and readiness probes are configurable under `probes`. Overrides are merged over the defaults, so `--set probes.liveness.initialDelaySeconds=60` keeps the `httpGet` handler. When switching to `exec` or `tcpSocket`, clear `httpGet` in the same override. Set `probes.liveness: null` to remove a probe.
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
{{- if and .Values.database.url (not .Values.database.existingSecret) .Values.existingSecret }}
|
||||
{{- fail "database.url is written into the chart's own Secret, which existingSecret replaces. Put TREK_DB_URL in your Secret and set database.existingSecret instead." }}
|
||||
{{- end }}
|
||||
apiVersion: apps/v1
|
||||
kind: Deployment
|
||||
metadata:
|
||||
@@ -5,11 +8,13 @@ metadata:
|
||||
labels:
|
||||
app: {{ include "trek.name" . }}
|
||||
spec:
|
||||
# One replica. Its rate limits, pending codes, permission cache and WebSocket
|
||||
# connections live in the process's memory, so a second pod would not share them. That
|
||||
# holds with database.url (PostgreSQL) too; see updateStrategy in values.yaml.
|
||||
replicas: 1
|
||||
# TREK is a single-writer SQLite app on a ReadWriteOnce PVC, so the default
|
||||
# RollingUpdate would start a second pod holding the same volume before the old one
|
||||
# exits — a Multi-Attach deadlock, or two processes on one travel.db. Recreate tears
|
||||
# the old pod down first. Keep it, see updateStrategy in values.yaml.
|
||||
# The default RollingUpdate would start a second pod on the same ReadWriteOnce PVC
|
||||
# before the old one exits: a Multi-Attach deadlock, or two processes on one travel.db.
|
||||
# Recreate tears the old pod down first. Keep it, see updateStrategy in values.yaml.
|
||||
strategy:
|
||||
type: {{ .Values.updateStrategy | default "Recreate" }}
|
||||
selector:
|
||||
@@ -61,6 +66,14 @@ spec:
|
||||
name: {{ default (printf "%s-secret" (include "trek.fullname" .)) .Values.existingSecret }}
|
||||
key: {{ .Values.existingSecretKey | default "ENCRYPTION_KEY" }}
|
||||
optional: true
|
||||
{{- if or .Values.database.url .Values.database.existingSecret }}
|
||||
# Required when set: a missing key stops the pod rather than starting it on SQLite.
|
||||
- name: TREK_DB_URL
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
name: {{ default (printf "%s-secret" (include "trek.fullname" .)) .Values.database.existingSecret }}
|
||||
key: {{ if .Values.database.existingSecret }}{{ .Values.database.existingSecretKey | default "TREK_DB_URL" }}{{ else }}TREK_DB_URL{{ end }}
|
||||
{{- end }}
|
||||
- name: ADMIN_EMAIL
|
||||
valueFrom:
|
||||
secretKeyRef:
|
||||
|
||||
@@ -8,6 +8,9 @@ metadata:
|
||||
type: Opaque
|
||||
data:
|
||||
{{ .Values.existingSecretKey | default "ENCRYPTION_KEY" }}: {{ .Values.secretEnv.ENCRYPTION_KEY | b64enc | quote }}
|
||||
{{- if .Values.database.url }}
|
||||
TREK_DB_URL: {{ .Values.database.url | b64enc | quote }}
|
||||
{{- end }}
|
||||
{{- if .Values.secretEnv.ADMIN_EMAIL }}
|
||||
ADMIN_EMAIL: {{ .Values.secretEnv.ADMIN_EMAIL | b64enc | quote }}
|
||||
{{- end }}
|
||||
@@ -65,6 +68,9 @@ stringData:
|
||||
{{- else }}
|
||||
{{ .Values.existingSecretKey | default "ENCRYPTION_KEY" }}: {{ randAlphaNum 32 | quote }}
|
||||
{{- end }}
|
||||
{{- if .Values.database.url }}
|
||||
TREK_DB_URL: {{ .Values.database.url | quote }}
|
||||
{{- end }}
|
||||
{{- if .Values.secretEnv.ADMIN_EMAIL }}
|
||||
ADMIN_EMAIL: {{ .Values.secretEnv.ADMIN_EMAIL | quote }}
|
||||
{{- end }}
|
||||
|
||||
+23
-4
@@ -4,10 +4,13 @@ image:
|
||||
# tag: latest
|
||||
pullPolicy: IfNotPresent
|
||||
|
||||
# Deployment update strategy. Keep Recreate: TREK is a single-writer SQLite app, and
|
||||
# during a RollingUpdate the new pod migrates the database while the old one still
|
||||
# writes to it. A ReadWriteMany volume does not make that safe; SQLite's WAL needs both
|
||||
# processes on one host, which network filesystems do not provide.
|
||||
# Deployment update strategy. Keep Recreate. The new pod migrates the database when it
|
||||
# starts, and during a RollingUpdate it would do that while the old pod still writes to
|
||||
# it. Recreate stops the old pod first. On SQLite two processes on one travel.db are
|
||||
# unsafe, and a ReadWriteOnce volume cannot be attached to both pods at once.
|
||||
# With database.url the database is PostgreSQL, but the reason for one replica stays: TREK
|
||||
# keeps rate limits, pending codes, the permission cache and WebSocket connections in
|
||||
# memory, so a second pod would not share them. Postgres does not make more replicas safe.
|
||||
updateStrategy: Recreate
|
||||
|
||||
# Pod-level security context. fsGroup gives the node user (uid/gid 1000) group access
|
||||
@@ -178,6 +181,22 @@ env:
|
||||
# address is sent unless you set one here.
|
||||
|
||||
|
||||
# Database. Empty (the default) keeps TREK on its SQLite file in the data volume. Set url to
|
||||
# run TREK on a PostgreSQL database instead (see the wiki page Database-Postgres). The URL
|
||||
# carries the password, so it is never a plain env value: with url, the chart writes it into
|
||||
# its own Secret as TREK_DB_URL; with existingSecret, TREK reads TREK_DB_URL from that Secret
|
||||
# under existingSecretKey and the chart writes nothing. existingSecret wins over url. The
|
||||
# variable is required when either is set: a missing Secret key stops the pod instead of
|
||||
# starting it on SQLite. The role in the URL owns TREK's database and must not be a superuser
|
||||
# (nor hold pg_execute_server_program or pg_write_server_files): a restore runs the backup's
|
||||
# SQL as that role and refuses one that could reach the database host. The wiki page shows the
|
||||
# SQL that creates such a role. PostgreSQL 14 to 18 is supported.
|
||||
# url: "postgres://trek:<password>@postgres.example.internal:5432/trek?sslmode=require"
|
||||
database:
|
||||
url: ""
|
||||
existingSecret: ""
|
||||
existingSecretKey: TREK_DB_URL
|
||||
|
||||
# Secret environment variables stored in a Kubernetes Secret.
|
||||
# JWT_SECRET is managed entirely by the server (auto-generated into the data PVC,
|
||||
# rotatable via the admin panel) — it is not configured here.
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
# TREK on a Postgres database instead of the SQLite file. See the wiki page
|
||||
# Database-Postgres for what this changes, the requirements and the backups.
|
||||
#
|
||||
# Set two passwords in a .env file beside this file (or in the shell) before
|
||||
# the first start:
|
||||
# POSTGRES_ADMIN_PASSWORD=<a long random value> the database's superuser, postgres
|
||||
# POSTGRES_PASSWORD=<another long random value> TREK's own role, trek
|
||||
# TREK connects as the role trek, which owns its database but is not a
|
||||
# superuser: a backup TREK restores is a SQL script run by that role, and a
|
||||
# superuser would let a crafted one run commands in the database container.
|
||||
# The superuser only creates that role, on the database's first start
|
||||
# (configs.trek-db-role below). TREK's password goes into TREK_DB_URL, so keep
|
||||
# it to URL-safe characters or percent-encode it. Without either password the
|
||||
# first start fails instead of creating a database nobody can reach.
|
||||
#
|
||||
# An install that started from an older version of this file runs TREK as the
|
||||
# superuser trek; the wiki page Database-Postgres ("Moving a compose install
|
||||
# off the superuser") shows how to move it to this layout.
|
||||
services:
|
||||
db:
|
||||
image: postgres:17
|
||||
container_name: trek-db
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
- POSTGRES_DB=${POSTGRES_DB:-trek}
|
||||
- POSTGRES_USER=postgres
|
||||
- POSTGRES_PASSWORD=${POSTGRES_ADMIN_PASSWORD:-}
|
||||
- TREK_DB_PASSWORD=${POSTGRES_PASSWORD:-}
|
||||
configs:
|
||||
- source: trek-db-role
|
||||
target: /docker-entrypoint-initdb.d/10-trek-role.sh
|
||||
# Executable, so the image runs it in a shell of its own instead of sourcing it.
|
||||
mode: 0555
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
# No ports are published: only the trek service on the compose network reaches the database.
|
||||
volumes:
|
||||
- trek-pgdata:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U postgres -d $${POSTGRES_DB}"]
|
||||
interval: 10s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
start_period: 10s
|
||||
logging:
|
||||
driver: json-file
|
||||
options:
|
||||
max-size: 10m
|
||||
max-file: "3"
|
||||
|
||||
app:
|
||||
image: mauriceboe/trek:latest
|
||||
container_name: trek
|
||||
depends_on:
|
||||
db:
|
||||
condition: service_healthy
|
||||
read_only: true
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
cap_drop:
|
||||
- ALL
|
||||
cap_add:
|
||||
- CHOWN
|
||||
- SETUID
|
||||
- SETGID
|
||||
# dumb-init runs as root and forwards SIGTERM to node, which runs as the
|
||||
# node user; signalling another user's process needs KILL. See docker-compose.yml.
|
||||
- KILL
|
||||
tmpfs:
|
||||
- /tmp:noexec,nosuid,size=128m
|
||||
ports:
|
||||
- "3000:3000"
|
||||
environment:
|
||||
- NODE_ENV=production
|
||||
- PORT=3000
|
||||
- ENCRYPTION_KEY=${ENCRYPTION_KEY:-} # Recommended. Generate with: openssl rand -hex 32.
|
||||
- TZ=${TZ:-UTC}
|
||||
- LOG_LEVEL=${LOG_LEVEL:-info}
|
||||
- ALLOWED_ORIGINS=${ALLOWED_ORIGINS:-}
|
||||
# The database URL, as the role trek. Its host is the service name above;
|
||||
# sslmode=disable is right on the compose network. Use sslmode=verify-full
|
||||
# with sslrootcert= for a database reached over a network you do not control.
|
||||
- TREK_DB_URL=postgres://trek:${POSTGRES_PASSWORD:-}@db:5432/${POSTGRES_DB:-trek}?sslmode=disable
|
||||
# Scale-out is not supported: keep one trek container (see Database-Postgres).
|
||||
volumes:
|
||||
- ./data:/app/data
|
||||
- ./uploads:/app/uploads
|
||||
restart: unless-stopped
|
||||
logging:
|
||||
driver: json-file
|
||||
options:
|
||||
max-size: 10m
|
||||
max-file: "3"
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "wget -qO- http://localhost:$${PORT:-3000}/api/health || exit 1"]
|
||||
interval: 30s
|
||||
timeout: 10s
|
||||
retries: 3
|
||||
start_period: 15s
|
||||
|
||||
# Run once by the postgres image, on the database's first start, as the
|
||||
# superuser: creates the role trek, which owns TREK's database and its public
|
||||
# schema, so it can create TREK's tables and its collation there, and nothing
|
||||
# more. The password reaches psql as a variable, never spliced into the SQL.
|
||||
configs:
|
||||
trek-db-role:
|
||||
content: |
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
if [ -z "$${TREK_DB_PASSWORD:-}" ]; then
|
||||
echo 'POSTGRES_PASSWORD (the password of the role trek) is not set.' >&2
|
||||
exit 1
|
||||
fi
|
||||
psql -v ON_ERROR_STOP=1 --no-psqlrc --username "$$POSTGRES_USER" --dbname "$$POSTGRES_DB" \
|
||||
--set=password="$$TREK_DB_PASSWORD" --set=database="$$POSTGRES_DB" <<'SQL'
|
||||
CREATE ROLE trek LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE PASSWORD :'password';
|
||||
ALTER DATABASE :"database" OWNER TO trek;
|
||||
ALTER SCHEMA public OWNER TO trek;
|
||||
SQL
|
||||
|
||||
volumes:
|
||||
trek-pgdata:
|
||||
@@ -48,6 +48,8 @@
|
||||
"entry": [
|
||||
"src/index.ts",
|
||||
"src/bootstrap.ts",
|
||||
// The move of a SQLite install into Postgres, run by hand (npm run db:move-to-postgres, dist/ in the image).
|
||||
"src/move-to-postgres.ts",
|
||||
// Read by the MikroORM CLI and at boot, by path.
|
||||
"src/mikro-orm.config.ts",
|
||||
// Started with child_process.fork() by the plugin supervisor (nest/plugins/paths.ts).
|
||||
|
||||
Generated
+2
-19
@@ -5684,7 +5684,6 @@
|
||||
"version": "7.2.8",
|
||||
"resolved": "https://registry.npmjs.org/@mikro-orm/postgresql/-/postgresql-7.2.8.tgz",
|
||||
"integrity": "sha512-spAGvR8xfXGK0+mwsAsN3Kt5cg2Ge3DgXT3rNOeA7IxaBXpl+NMwXu5cSWes4jHlhWKJ4jzXyTo6xH+we9fbNA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@mikro-orm/sql": "7.2.8",
|
||||
@@ -19855,7 +19854,6 @@
|
||||
"version": "8.23.1",
|
||||
"resolved": "https://registry.npmjs.org/pg/-/pg-8.23.1.tgz",
|
||||
"integrity": "sha512-aL96AHANtWjPLDOLqnhx+ngp9+UK7ETEU8VJrDCGvsSSi/mGLcWYsS6Herg7lmaBJe4uwrfqsa7gTEFaSizDoQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"pg-connection-string": "^2.14.1",
|
||||
@@ -19883,7 +19881,6 @@
|
||||
"version": "1.4.1",
|
||||
"resolved": "https://registry.npmjs.org/pg-cloudflare/-/pg-cloudflare-1.4.1.tgz",
|
||||
"integrity": "sha512-6PQbsFWZcp9EmJEwy5cGQ2La+AMWpP46lgbb8X+U/XsHIUweYDNCpeuKck5RxL2MdVFi7krbbEi5nX4Zh7JhrQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true
|
||||
},
|
||||
@@ -19891,14 +19888,12 @@
|
||||
"version": "2.14.1",
|
||||
"resolved": "https://registry.npmjs.org/pg-connection-string/-/pg-connection-string-2.14.1.tgz",
|
||||
"integrity": "sha512-qR3kGNPBLpCNtz0evbKA0Y/MRFXwSSdT+pTJvYp/bXTcReZbvX1kzF0IyTc1QnxqF7AZbOeBhNL8R5mYQZV/MA==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/pg-cursor": {
|
||||
"version": "2.22.1",
|
||||
"resolved": "https://registry.npmjs.org/pg-cursor/-/pg-cursor-2.22.1.tgz",
|
||||
"integrity": "sha512-X10ldv3wwBONQkOSwgWEbaEITMGLd92V2Zd+xsFPhDt3nhhU3hpAT08SERBChnIFmomczLax6lKXLJrHPPXfxA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"pg": "^8"
|
||||
@@ -19908,7 +19903,6 @@
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/pg-int8/-/pg-int8-1.0.1.tgz",
|
||||
"integrity": "sha512-WCtabS6t3c8SkpDBUlb1kjOs7l66xsGdKpIPZsg4wR+B3+u9UAum2odSsF9tnvxg80h4ZxLWMy4pRjOsFIqQpw==",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"engines": {
|
||||
"node": ">=4.0.0"
|
||||
@@ -19918,7 +19912,6 @@
|
||||
"version": "3.14.0",
|
||||
"resolved": "https://registry.npmjs.org/pg-pool/-/pg-pool-3.14.0.tgz",
|
||||
"integrity": "sha512-gKtPkFdQPU3DksooVLi9LsjZxrsBUZIpa+7aVx+LV5pNh0KzP4Zleud2po+ConrxbuXGBJ6Hfer6hdgpIBpBaw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"pg": ">=8.0"
|
||||
@@ -19928,14 +19921,12 @@
|
||||
"version": "1.16.1",
|
||||
"resolved": "https://registry.npmjs.org/pg-protocol/-/pg-protocol-1.16.1.tgz",
|
||||
"integrity": "sha512-p9VOFMiHB/ZbJATetbg+99PxssTVSQRnyuPSQ67mN1+1KBOjZaZ83ZQzltnxPhJwSsC3nwVjJ10DVJlerbFzLg==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/pg-types": {
|
||||
"version": "2.2.0",
|
||||
"resolved": "https://registry.npmjs.org/pg-types/-/pg-types-2.2.0.tgz",
|
||||
"integrity": "sha512-qTAAlrEsl8s4OiEQY69wDvcMIdQN6wdz5ojQiOy6YRMuynxenON0O5oCpJI6lshc6scgAY8qvJ2On/p+CXY0GA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"pg-int8": "1.0.1",
|
||||
@@ -19952,7 +19943,6 @@
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-2.0.0.tgz",
|
||||
"integrity": "sha512-VpZrUqU5A69eQyW2c5CA1jtLecCsN2U/bD6VilrFDWq5+5UIEVO7nazS3TEcHf1zuPYO/sqGvUvW62g86RXZuA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=4"
|
||||
@@ -19962,7 +19952,6 @@
|
||||
"version": "1.0.7",
|
||||
"resolved": "https://registry.npmjs.org/postgres-date/-/postgres-date-1.0.7.tgz",
|
||||
"integrity": "sha512-suDmjLVQg78nMK2UZ454hAG+OAW+HQPZ6n++TNDUX+L0+uUlLywnoxJKDou51Zm+zTCjrCl0Nq6J9C5hP9vK/Q==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
@@ -19972,7 +19961,6 @@
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/postgres-interval/-/postgres-interval-1.2.0.tgz",
|
||||
"integrity": "sha512-9ZhXKM/rw350N1ovuWHbGxnGh/SNJ4cnxHiM0rxE4VN41wsg8P8zWn9hv/buK00RP4WvlOyr/RBDiptyxVbkZQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"xtend": "^4.0.0"
|
||||
@@ -19985,7 +19973,6 @@
|
||||
"version": "1.0.5",
|
||||
"resolved": "https://registry.npmjs.org/pgpass/-/pgpass-1.0.5.tgz",
|
||||
"integrity": "sha512-FdW9r/jQZhSeohs1Z3sI1yxFQNFvMcnmfuj4WBMUTxOrAyLMaTcE1aAMBiTlbMNaXvBCQuVi0R7hd8udDSP7ug==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"split2": "^4.1.0"
|
||||
@@ -20355,7 +20342,6 @@
|
||||
"version": "3.0.4",
|
||||
"resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-3.0.4.tgz",
|
||||
"integrity": "sha512-nAUSGfSDGOaOAEGwqsRY27GPOea7CNipJPOA7lPbdEpx5Kg3qzdP0AaWC5MlhTWV9s4hFX39nomVZ+C4tnGOJQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
@@ -20365,7 +20351,6 @@
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/postgres-bytea/-/postgres-bytea-1.0.1.tgz",
|
||||
"integrity": "sha512-5+5HqXnsZPE65IJZSMkZtURARZelel2oXUEO8rH83VS/hxH5vv1uHquPg5wZs8yMAfdv971IU+kcPUczi7NVBQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
@@ -20375,7 +20360,6 @@
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmjs.org/postgres-date/-/postgres-date-2.1.0.tgz",
|
||||
"integrity": "sha512-K7Juri8gtgXVcDfZttFKVmhglp7epKb1K4pgrkLxehjqkrgPhfG6OO8LHLkfaqkbpjNRnra018XwAr1yQFWGcA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
@@ -20385,7 +20369,6 @@
|
||||
"version": "4.1.0",
|
||||
"resolved": "https://registry.npmjs.org/postgres-interval/-/postgres-interval-4.1.0.tgz",
|
||||
"integrity": "sha512-nJLACcOHi2iyRuMJeW6CuIA0Dc0i1YEpRr26XDyHAfxPjYUJOFxwZjmOc5oFFctTTh/OlRAMlnlXEJvr170fJg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
@@ -25724,7 +25707,6 @@
|
||||
"version": "4.0.2",
|
||||
"resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz",
|
||||
"integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.4"
|
||||
@@ -25933,6 +25915,7 @@
|
||||
"@mikro-orm/core": "^7.2.7",
|
||||
"@mikro-orm/migrations": "^7.2.7",
|
||||
"@mikro-orm/nestjs": "^7.1.0",
|
||||
"@mikro-orm/postgresql": "^7.2.7",
|
||||
"@mikro-orm/seeder": "^7.2.7",
|
||||
"@mikro-orm/sql": "^7.2.1",
|
||||
"@mikro-orm/sqlite": "^7.2.7",
|
||||
@@ -25969,6 +25952,7 @@
|
||||
"nodemailer": "^10.5.0",
|
||||
"otplib": "^12.0.1",
|
||||
"pdf-parse": "^2.4.5",
|
||||
"pg-cursor": "^2.22.1",
|
||||
"qrcode": "^1.5.4",
|
||||
"reflect-metadata": "^0.2.2",
|
||||
"rxjs": "^7.8.2",
|
||||
@@ -25987,7 +25971,6 @@
|
||||
"@aws-lite/s3-types": "^0.2.8",
|
||||
"@eslint/js": "^10.0.1",
|
||||
"@mikro-orm/entity-generator": "^7.2.7",
|
||||
"@mikro-orm/postgresql": "^7.2.7",
|
||||
"@nestjs/testing": "^11.2.5",
|
||||
"@swc/core": "^1.16.22",
|
||||
"@trivago/prettier-plugin-sort-imports": "^6.0.2",
|
||||
|
||||
+85
-1
@@ -169,6 +169,90 @@ Every ctx method falls into one of three kinds, listed per method in the exporte
|
||||
answer, an access token) or data you own (`ctx.db`, `ctx.meta`, another plugin's
|
||||
answer), returned as it is.
|
||||
|
||||
### Your own database on Postgres
|
||||
|
||||
`ctx.db` is a SQLite file of your own on a default TREK. When the instance runs on
|
||||
PostgreSQL (`TREK_DB_URL`), it is a schema of your own in TREK's database instead,
|
||||
named `trek_plugin_<your id>` with each dash an underscore, and no SQLite file is
|
||||
written. TREK hands your SQL to the engine as you wrote it and translates nothing, so
|
||||
ask which one you are on and write that dialect:
|
||||
|
||||
```js
|
||||
const pg = (await ctx.db.engine()) === 'postgres'
|
||||
await ctx.db.migrate('001', pg
|
||||
? 'CREATE TABLE notes (id bigserial PRIMARY KEY, body text NOT NULL)'
|
||||
: 'CREATE TABLE notes (id INTEGER PRIMARY KEY AUTOINCREMENT, body TEXT NOT NULL)')
|
||||
await ctx.db.exec(pg ? 'INSERT INTO notes (body) VALUES ($1)' : 'INSERT INTO notes (body) VALUES (?)', body)
|
||||
```
|
||||
|
||||
What changes on Postgres:
|
||||
|
||||
- **Placeholders** are `$1`, `$2`, ..., not `?`. A `?` with bound args is refused with a
|
||||
message that says so.
|
||||
- **Types and functions** are Postgres's: `bigserial`/`GENERATED ... AS IDENTITY` instead
|
||||
of `AUTOINCREMENT`, `now()` instead of `datetime('now')`, `ON CONFLICT` works on both.
|
||||
A `bigint` comes back as a number, and one past 2^53 is refused. A boolean comes back as
|
||||
`true`/`false`, not `1`/`0`.
|
||||
- **Not on a privileged role.** While TREK connects to Postgres as a superuser, a member of
|
||||
one, or another role that could reach the database server (the same roles TREK refuses
|
||||
restores for), every `ctx.db` call fails with an error that starts `Plugin databases
|
||||
(db:own) are refused on Postgres`, and TREK's boot log says so. Your SQL would run as
|
||||
that role. The admin fixes it by connecting TREK as a role that owns its database and is
|
||||
not a superuser; your plugin needs no change.
|
||||
- **Your SQL stays in your schema.** Only your schema is on the `search_path`, and a
|
||||
statement is refused before it runs when it names another schema (`public.users`,
|
||||
another plugin's), anything starting with `pg_` or `information_schema`, or a function
|
||||
that runs SQL from a string, reads settings or reaches an object by a name in a string
|
||||
(`query_to_xml`, `ts_stat`, `set_config`, `current_setting`, `nextval`, `setval`,
|
||||
`has_table_privilege` and the other `has_*_privilege` functions, `currtid2`, `to_reg*`,
|
||||
`lo_*`, `dblink`). The types that look an object up by name are refused in every
|
||||
spelling: `regclass`, `regtype`, `regproc`, `regprocedure`, `regoper`, `regoperator`,
|
||||
`regconfig`, `regdictionary`, `regnamespace`, `regrole`, `regcollation` and their arrays
|
||||
(`'x'::regtype`, `CAST('x' AS regtype)`, `regtype 'x'`). An alias that shares a schema's
|
||||
name is refused too, so pick another.
|
||||
- **You change your own objects only.** Right before an `ALTER`, `DROP`, `REFRESH`,
|
||||
`TRUNCATE` or `CREATE INDEX ... ON` runs, Postgres resolves the object it names (and the
|
||||
tables a `CREATE`/`ALTER TABLE` ties to with `REFERENCES`, `INHERITS`, `PARTITION OF`,
|
||||
`ATTACH`/`DETACH PARTITION` or `INHERIT`), and the statement is refused unless each one
|
||||
that exists is in your schema. Postgres searches its catalog before your schema, so
|
||||
`ALTER TYPE int4 ...` or `DROP TYPE text` names the built-in type and is refused; name
|
||||
your own types so they do not clash with built-in ones.
|
||||
- **Statements**: `SELECT`, `INSERT`, `UPDATE`, `DELETE`, `MERGE`, `WITH`, `VALUES`,
|
||||
`TABLE`, `TRUNCATE`, `REFRESH`, and `CREATE`/`ALTER`/`DROP` of a table, index, view,
|
||||
materialized view, sequence or type (a composite, enum or range type, `CREATE TYPE x AS
|
||||
...`). No functions, triggers, procedures, `DO` blocks, base types, temporary tables,
|
||||
`SELECT ... INTO`, `COPY`, `SET`, transaction control (`tx()` makes a batch atomic),
|
||||
`WITH RECURSIVE`, and no `ALTER` of a schema, owner or tablespace. Dollar-quoted strings,
|
||||
`E'...'` and `U&'...'` are refused; write plain single-quoted strings. `CREATE TEMP` and
|
||||
`CREATE TEMPORARY` (also after `OR REPLACE`, `LOCAL` or `GLOBAL`) are refused, and so is
|
||||
`INTO` anywhere but right after the `INSERT` or `MERGE` that is the statement's verb (or
|
||||
the verb of a `WITH` query's body): `SELECT 1 insert INTO t` is refused, because `insert`
|
||||
there is a column alias. A column named `temp` needs no quoting.
|
||||
Numbers are decimal: `0x1F`, `0o17`, `0b1` and `1_000` are refused, because Postgres
|
||||
before 16 reads them differently. Outside strings, quoted names and comments, whitespace is
|
||||
space, tab, newline, carriage return or form feed; any other control character or non-ASCII
|
||||
whitespace (a no-break space, a byte order mark) is refused. A `--` comment ends at a
|
||||
newline or a carriage return.
|
||||
- **One statement at a time.** Each statement goes to Postgres on its own, over the protocol
|
||||
that runs exactly one: `query` and each `tx` entry take one statement, and an `exec`
|
||||
script is split at its semicolons and sent statement by statement.
|
||||
- **No NUL in text.** Postgres text cannot hold the character U+0000. A bound argument
|
||||
holding one (a string, or a string in an array) and a `migrate` id holding one are refused
|
||||
with an error that names it, and so is SQL text with one anywhere, a string literal
|
||||
included; TREK never drops or changes the character, since `'a\0b'` and `'ab'` are
|
||||
different keys. Bind binary data as a `Buffer` into a `bytea` column, and use another
|
||||
separator for composite keys. On SQLite your arguments are bound exactly as you send
|
||||
them, NUL included, as they always were.
|
||||
- **Limits**: the same row cap and quota as on SQLite. The 2 s budget is a
|
||||
`statement_timeout` here, so it also stops a single long statement, and an `exec` with
|
||||
bound args is held to it too; `migrate` stays untimed. The quota counts every relation of
|
||||
your schema (tables, indexes, sequences, materialized views and each table's TOAST
|
||||
storage), and a schema may hold at most 5,000 catalog objects (relations, types, each
|
||||
table brings its row type and that type's array, constraints and enum labels). A write
|
||||
that takes your schema past 256 MB or past 5,000 objects and grows it there is rolled
|
||||
back; a delete or a drop still runs. Rows deleted or rolled back keep their space until
|
||||
Postgres vacuums them.
|
||||
|
||||
## Settings
|
||||
|
||||
Declare settings in `trek-plugin.json`; TREK renders the form, you write no settings UI.
|
||||
@@ -252,7 +336,7 @@ for a legitimate plugin and only bite a runaway or abusive one — build against
|
||||
| `ctx.ai` | 200 calls/day per plugin (UTC midnight rollover); past it throws `"daily AI budget exhausted (resets at UTC midnight)"` |
|
||||
| `ctx.notify` | 100 calls/day per plugin (UTC midnight rollover); past it throws `"daily notification budget exhausted (resets at UTC midnight)"` |
|
||||
| RPC (every `ctx.*` call) | burst 60, sustained 20/s, 16 in-flight per plugin; a throttled call is refused with `HOST_ERROR: rate limit exceeded — slow down ctx.* calls` |
|
||||
| `ctx.db` (your own sqlite) | 256 MB per plugin; a `query` or `tx` returns at most 100,000 rows (a whole `tx` batch shares one count). A `query`, a whole `tx` batch and an `exec` script without bound args each have 2 s of wall-clock time, checked between the rows a statement reads and between the statements of a batch or script; past either limit the call throws (`query exceeded its 2000 ms time budget`), a `tx` rolls back, and an `exec` script stops before its next statement once the time is up (the statements that ran stay applied, as they always did, and a transaction the script opened itself is rolled back; a script whose last statement has run counts as done, however long it took). Split a longer script over several calls, or batch it with `tx`. `migrate` has no time budget, since a migration stopped part of the way would fail again on every start. `ATTACH`, `DETACH`, `VACUUM`, `PRAGMA`, `WITH RECURSIVE` and `load_extension` are refused. The budget cannot stop a single statement, because SQLite runs it on TREK's main thread in one step: a write runs to its end (an `INSERT ... SELECT` over a cross join of large tables), and a read runs until its first row (an aggregate over one). Keep your statements indexed and bounded |
|
||||
| `ctx.db` (your own database) | 256 MB per plugin; a `query` or `tx` returns at most 100,000 rows (a whole `tx` batch shares one count). A `query`, a whole `tx` batch and an `exec` script without bound args each have 2 s of wall-clock time, checked between the rows a statement reads and between the statements of a batch or script; past either limit the call throws (`query exceeded its 2000 ms time budget`), a `tx` rolls back, and an `exec` script stops before its next statement once the time is up (the statements that ran stay applied, as they always did, and a transaction the script opened itself is rolled back; a script whose last statement has run counts as done, however long it took). Split a longer script over several calls, or batch it with `tx`. `migrate` has no time budget, since a migration stopped part of the way would fail again on every start. `ATTACH`, `DETACH`, `VACUUM`, `PRAGMA`, `WITH RECURSIVE` and `load_extension` are refused. The budget cannot stop a single statement, because SQLite runs it on TREK's main thread in one step: a write runs to its end (an `INSERT ... SELECT` over a cross join of large tables), and a read runs until its first row (an aggregate over one). Keep your statements indexed and bounded. On a TREK running on Postgres the same caps hold, and the budget also stops a single statement (see [Your own database on Postgres](#your-own-database-on-postgres)) |
|
||||
| `ctx.meta` | 64 KB per value, 256 chars per key, 100 keys per (plugin, entity) |
|
||||
| Plugin process | 300 MB RSS ceiling; auto-disabled after 5 crashes in 5 minutes |
|
||||
| Event redelivery buffer | 200 events held per plugin, dropped unreplayed after 15 minutes |
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "trek-plugin-sdk",
|
||||
"version": "1.9.1",
|
||||
"version": "1.10.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "trek-plugin-sdk",
|
||||
"version": "1.9.1",
|
||||
"version": "1.10.0",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@clack/prompts": "^1.8.1",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "trek-plugin-sdk",
|
||||
"version": "1.9.1",
|
||||
"version": "1.10.0",
|
||||
"description": "SDK for building TREK plugins: types, definePlugin, a mock host, manifest validation, and the create-trek-plugin / trek-plugin CLIs.",
|
||||
"type": "module",
|
||||
"license": "MIT",
|
||||
|
||||
@@ -203,6 +203,8 @@ function createDevContext(id: string, grants: Set<string>, fx: Fixtures, db: Plu
|
||||
query: (sql: string, ...a: unknown[]) => { need('db:own', 'db.query'); return db.query(sql, ...a); },
|
||||
exec: (sql: string, ...a: unknown[]) => { need('db:own', 'db.exec'); return db.exec(sql, ...a); },
|
||||
migrate: (mid: string, sql: string) => { need('db:own', 'db.migrate'); return db.migrate(mid, sql); },
|
||||
// `dev` always runs your plugin on SQLite; test the Postgres dialect against a TREK on Postgres.
|
||||
engine: async () => { need('db:own', 'db.engine'); return 'sqlite' as const; },
|
||||
// A functional (not strictly atomic) tx over the real dev db so read-modify-write
|
||||
// batches work in dev; production runs it in one better-sqlite3 transaction.
|
||||
tx: async (ops: Array<{ sql: string; args?: unknown[] }>) => {
|
||||
|
||||
@@ -100,6 +100,7 @@ export const METHOD_PERMISSION: Readonly<Record<string, string>> = {
|
||||
'db.query': 'db:own',
|
||||
'db.migrate': 'db:own',
|
||||
'db.tx': 'db:own',
|
||||
'db.engine': 'db:own',
|
||||
'trips.getById': 'db:read:trips',
|
||||
'trips.getPlaces': 'db:read:trips',
|
||||
'trips.getReservations': 'db:read:trips',
|
||||
@@ -214,6 +215,7 @@ export const KNOWN_METHODS: string[] = [
|
||||
'db.query',
|
||||
'db.migrate',
|
||||
'db.tx',
|
||||
'db.engine',
|
||||
'trips.getById',
|
||||
'trips.getPlaces',
|
||||
'trips.getReservations',
|
||||
@@ -927,6 +929,7 @@ export const PLUGIN_METHOD_RESULT: Readonly<Record<string, string>> = {
|
||||
'db.query': 'host',
|
||||
'db.migrate': 'host',
|
||||
'db.tx': 'host',
|
||||
'db.engine': 'host',
|
||||
'trips.getById': 'trip',
|
||||
'trips.getPlaces': 'place[]',
|
||||
'trips.getReservations': 'reservation[]',
|
||||
|
||||
@@ -74,8 +74,10 @@ export interface PluginContext {
|
||||
settings: {
|
||||
get(key: string): Promise<unknown>;
|
||||
};
|
||||
/** Your OWN sqlite database (`db:own`): a separate file the plugin never gets a
|
||||
* path or connection to directly. Quota: 256 MB per plugin (writes past it fail);
|
||||
/** Your OWN database (`db:own`): a SQLite file of its own, or, when TREK runs on
|
||||
* Postgres, a schema of its own in TREK's database, which your SQL is confined to
|
||||
* (`engine()` says which, and README § Your own database on Postgres has the rules).
|
||||
* The plugin never gets a path or connection to it directly. Quota: 256 MB per plugin (writes past it fail);
|
||||
* result sets are capped at 100,000 rows, and a `query`, a `tx` or an `exec` script
|
||||
* without args gets 2 s of wall-clock time, checked between the rows it reads and
|
||||
* the statements it runs (past it, it throws, a `tx` rolls back and a script stops
|
||||
@@ -87,6 +89,9 @@ export interface PluginContext {
|
||||
query<T = unknown>(sql: string, ...args: unknown[]): Promise<T[]>;
|
||||
exec(sql: string, ...args: unknown[]): Promise<{ changes: number }>;
|
||||
migrate(id: string, sql: string): Promise<{ applied: boolean }>;
|
||||
/** The engine your SQL runs on: 'sqlite' (the default), or 'postgres' when TREK runs on
|
||||
* Postgres. Your SQL is passed through as written, so write it in that engine's dialect. */
|
||||
engine(): Promise<'sqlite' | 'postgres'>;
|
||||
/** Run several statements atomically on your OWN db — all commit or all roll
|
||||
* back. Each op is one statement; reads see the batch's own earlier writes.
|
||||
* A read returns `{ rows }`, a write `{ changes }`. Max 100 statements. */
|
||||
|
||||
@@ -48,6 +48,8 @@ export interface MockHostOptions {
|
||||
users?: Record<number, unknown>;
|
||||
/** Optional canned db.query results, keyed by the exact sql string. */
|
||||
queryResults?: Record<string, unknown[]>;
|
||||
/** What `db.engine()` answers; 'sqlite' when unset. Set 'postgres' to test a plugin's Postgres SQL path. */
|
||||
dbEngine?: 'sqlite' | 'postgres';
|
||||
/** The host-bound acting user for costs.* (a job/onLoad has none → refused). */
|
||||
actingUserId?: number;
|
||||
/** Trip bound to the mock plugin UI's `session` helper. Required for scope: 'trip'. */
|
||||
@@ -451,6 +453,10 @@ export function createMockHost(opts: MockHostOptions = {}): MockHost {
|
||||
guardSql(sql);
|
||||
return { applied: true };
|
||||
},
|
||||
async engine() {
|
||||
need('db:own', 'db.engine');
|
||||
return opts.dbEngine ?? 'sqlite';
|
||||
},
|
||||
async tx(ops) {
|
||||
need('db:own', 'db.tx');
|
||||
// Same batch guards as the host's PluginDataDb: an op cap, the forbidden
|
||||
|
||||
@@ -511,6 +511,12 @@ describe('createMockHost', () => {
|
||||
await expect(ctx.db.tx(Array.from({ length: 101 }, () => ({ sql: 'SELECT 1' })))).rejects.toThrow(/at most 100/);
|
||||
});
|
||||
|
||||
it('db.engine says SQLite unless the mock is told the host runs Postgres, and needs db:own', async () => {
|
||||
await expect(createMockHost({ grants: ['db:own'] }).ctx.db.engine()).resolves.toBe('sqlite');
|
||||
await expect(createMockHost({ grants: ['db:own'], dbEngine: 'postgres' }).ctx.db.engine()).resolves.toBe('postgres');
|
||||
await expect(createMockHost({ grants: [] }).ctx.db.engine()).rejects.toThrow(/PERMISSION_DENIED/);
|
||||
});
|
||||
|
||||
it('member writes need member_manage + protect the owner; users.getById serves only public fields', async () => {
|
||||
const host = createMockHost({
|
||||
grants: ['db:write:members', 'db:read:users'],
|
||||
|
||||
@@ -44,6 +44,24 @@ describe('classify', () => {
|
||||
assert.deepEqual(classify(['server/src/nest/weather/weather.service.ts']), { code: true, image: true, deploy: false });
|
||||
});
|
||||
|
||||
it('runs the Postgres probe and lane for every file they read', () => {
|
||||
// server-postgres is gated on `code`; a migration, a repository, the
|
||||
// engine, the baseline or the lane's own config must never skip it.
|
||||
for (const file of [
|
||||
'server/src/db/migrations/Migration20200101046440_x.ts',
|
||||
'server/src/db/repositories/Trips.repository.ts',
|
||||
'server/src/db/dialect/sql-functions.ts',
|
||||
'server/src/db/engine/postgres/schema-bootstrap.ts',
|
||||
'server/assets/postgres/baseline.sql',
|
||||
'server/scripts/pg-probe-baseline.json',
|
||||
'server/vitest.pg.config.ts',
|
||||
'server/tests/postgres/lane.ts',
|
||||
'server/tests/postgres/snapshot-suites-baseline.json',
|
||||
]) {
|
||||
assert.equal(classify([file]).code, true, file);
|
||||
}
|
||||
});
|
||||
|
||||
it('runs the tests but not the image for a plugin-sdk change', () => {
|
||||
assert.deepEqual(classify(['plugin-sdk/src/index.ts']), { code: true, image: false, deploy: false });
|
||||
});
|
||||
|
||||
@@ -78,7 +78,6 @@
|
||||
"server/src/nest/accommodations/night-seat.ts": 1,
|
||||
"server/src/nest/app-config/index.ts": 6,
|
||||
"server/src/nest/auth/auth.helpers.ts": 1,
|
||||
"server/src/nest/backup/backup-archive.ts": 1,
|
||||
"server/src/nest/backup/backup.impl.ts": 3,
|
||||
"server/src/nest/budget/budget.service.ts": 1,
|
||||
"server/src/nest/day-notes/day-notes.service.ts": 1,
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { describe, it } from 'node:test';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
// ci-ok is the one required check, and a job counts for a merge only once it
|
||||
// is in ci-ok's needs. A new or renamed job that is left out runs, can fail,
|
||||
// and merges anyway. The scan is the one job kept out on purpose (see the
|
||||
// layout notes at the top of test.yml).
|
||||
const workflow = readFileSync(fileURLToPath(new URL('../../.github/workflows/test.yml', import.meta.url)), 'utf8');
|
||||
const NOT_REQUIRED = new Set(['ci-ok', 'scan']);
|
||||
|
||||
function jobIds() {
|
||||
const body = workflow.slice(workflow.indexOf('\njobs:\n'));
|
||||
return [...body.matchAll(/^ {2}([a-z0-9-]+):\s*$/gm)].map((match) => match[1]);
|
||||
}
|
||||
|
||||
function ciOkNeeds() {
|
||||
const block = /^ {2}ci-ok:\n {4}needs:\n((?: {6}- [a-z0-9-]+\n)+)/m.exec(workflow);
|
||||
assert.ok(block, 'test.yml must declare ci-ok with a needs: list, one job per line');
|
||||
return block[1]
|
||||
.trim()
|
||||
.split('\n')
|
||||
.map((line) => line.replace(/^\s*- /, ''));
|
||||
}
|
||||
|
||||
describe('test.yml', () => {
|
||||
it('lists every job but the scan in ci-ok needs', () => {
|
||||
const needs = new Set(ciOkNeeds());
|
||||
const missing = jobIds().filter((id) => !NOT_REQUIRED.has(id) && !needs.has(id));
|
||||
assert.deepEqual(missing, [], `add these jobs to ci-ok's needs: in test.yml: ${missing.join(', ')}`);
|
||||
});
|
||||
|
||||
it('names only jobs that exist in ci-ok needs', () => {
|
||||
const ids = new Set(jobIds());
|
||||
const unknown = ciOkNeeds().filter((id) => !ids.has(id));
|
||||
assert.deepEqual(unknown, [], `ci-ok needs jobs test.yml does not define: ${unknown.join(', ')}`);
|
||||
});
|
||||
});
|
||||
+6
-2
@@ -47,13 +47,17 @@ DEMO_MODE=false # Demo mode: resets data hourly
|
||||
# DEMO_ADMIN_EMAIL=admin@trek.app # Email of that seeded demo admin. (default: admin@trek.app)
|
||||
# DEMO_ADMIN_PASS=admin12345 # Initial password of that seeded demo admin. Change it on a public demo. (default: admin12345)
|
||||
|
||||
# RESTORE_FROM_BACKUP=/app/data/backup.zip # Restore this backup on the first start, before any setup. Ignored once a database exists.
|
||||
# RESTORE_FROM_BACKUP=/app/data/backup.zip # Restore this backup on the first start, before any setup. Ignored once a database exists (on Postgres: once the database holds a table).
|
||||
# FILE_UPLOAD_LIMIT_MB=50 # Max size (MB) of a file uploaded to a trip, a booking or a note. Videos keep their own 500 MB cap. Raise your reverse proxy's upload limit too.
|
||||
# BACKUP_MAX_DECOMPRESSED_MB=5120 # Max size (MB) a restore archive may unpack to, on both restore paths: the zip-bomb guard. Raise it if a large backup is refused with "Backup exceeds the maximum decompressed size". (default: 5120)
|
||||
# BACKUP_UPLOAD_LIMIT_MB=500 # Max size (MB) of a backup archive you can upload when restoring. Raise it if your backup exceeds 500 MB. If you sit behind a reverse proxy, raise its upload limit too (e.g. nginx client_max_body_size).
|
||||
|
||||
# TREK_DB_URL=postgres://trek:password@db:5432/trek # Run on a Postgres database instead of the SQLite file in data/. TREK creates its schema in an empty database and refuses one holding tables it did not create. sslmode=disable, require, verify-ca or verify-full (the last three always verify the certificate; sslrootcert= names the CA file). Cannot be combined with TREK_DB_FILE, TREK_DB_JOURNAL_MODE or TREK_DB_SYNCHRONOUS.
|
||||
# TREK_DB_PG_BIN_DIR=/usr/lib/postgresql/17/bin # The directory holding pg_dump, pg_restore and psql, which back up and restore a Postgres database. Unset, TREK looks in /usr/lib/postgresql/<17..14>/bin, /usr/local/bin and /usr/bin (the Docker image installs the version 17 tools, which cannot dump a newer server). Unused on SQLite.
|
||||
# TREK_DB_POOL_MAX=10 # Most connections TREK opens to the Postgres database (1 to 100). Unused on SQLite. (default: 10)
|
||||
# TREK_DB_JOURNAL_MODE=WAL # SQLite journal mode (DELETE, TRUNCATE, PERSIST, MEMORY, WAL, OFF). WAL is fastest and the right choice on local disk. Set DELETE if the data directory lives on network storage (Azure App Service, an SMB/NFS volume on a NAS) — WAL coordinates writers through a shared-memory file that those filesystems do not implement reliably. The mode is stored inside the database file, so it survives a restart; changing this applies on the next boot.
|
||||
# TREK_DB_PRE_MIGRATE_SNAPSHOT=true # Copy the database to data/pre-migrate-<schema>-<time>.db before a startup migrates it, so the previous image can run on the copy again. A copy that cannot be written stops the startup; false migrates without one.
|
||||
# TREK_DB_PRE_MIGRATE_SNAPSHOT=true # Copy the database to data/pre-migrate-<schema>-<time>.db (a .pgdump made with pg_dump on Postgres) before a startup migrates it, so the previous image can run on the copy again. A copy that cannot be written stops the startup; false migrates without one.
|
||||
# TREK_DB_IGNORE_SQLITE_FILE=false # With TREK_DB_URL set, TREK refuses to start on a Postgres database that holds no TREK data while data/travel.db holds an existing SQLite install, because it would come up as a new, empty instance beside it. Move the install with the move-to-postgres command instead (wiki: Database-Postgres). true starts on the empty database anyway. Unused on SQLite. (default: false)
|
||||
# TREK_DB_PRE_MIGRATE_SNAPSHOT_KEEP=3 # How many pre-migrate copies to keep, newest first (1 to 100). (default: 3)
|
||||
# TREK_DB_SYNCHRONOUS=NORMAL # How hard SQLite flushes to disk (OFF, NORMAL, FULL, EXTRA). Defaults to NORMAL under WAL and FULL under any other journal mode — leave it alone unless you know why you want otherwise. Both variables fall back to their default (with a warning in the log) if the value is not a mode SQLite knows.
|
||||
|
||||
|
||||
+26
-10
File diff suppressed because one or more lines are too long
@@ -0,0 +1,346 @@
|
||||
{
|
||||
"through": "Migration20200101046440_a_trip_owns_its_tags",
|
||||
"migrations": [
|
||||
"Migration20200101000000_baseline_schema",
|
||||
"Migration20200101000100_users_add_unsplash_api_key",
|
||||
"Migration20200101000200_users_add_openweather_api_key",
|
||||
"Migration20200101000300_places_add_duration_minutes",
|
||||
"Migration20200101000400_places_add_notes",
|
||||
"Migration20200101000500_places_add_image_url",
|
||||
"Migration20200101000600_places_add_transport_mode",
|
||||
"Migration20200101000700_days_add_title",
|
||||
"Migration20200101000800_reservations_add_status",
|
||||
"Migration20200101000900_trip_files_add_reservation_id",
|
||||
"Migration20200101001000_reservations_add_type",
|
||||
"Migration20200101001100_trips_add_cover_image",
|
||||
"Migration20200101001200_day_notes_add_icon",
|
||||
"Migration20200101001300_trips_add_is_archived",
|
||||
"Migration20200101001400_categories_add_user_id",
|
||||
"Migration20200101001500_users_add_avatar",
|
||||
"Migration20200101001600_users_add_oidc_sub",
|
||||
"Migration20200101001700_users_add_oidc_issuer",
|
||||
"Migration20200101001800_users_add_last_login",
|
||||
"Migration20200101001900_create_budget_items_new",
|
||||
"Migration20200101002000_day_accommodations_add_check_in",
|
||||
"Migration20200101002100_places_add_end_time",
|
||||
"Migration20200101002200_day_assignments_add_reservation_status",
|
||||
"Migration20200101002300_reservations_add_assignment_id",
|
||||
"Migration20200101002400_create_assignment_participants",
|
||||
"Migration20200101002500_create_collab_notes",
|
||||
"Migration20200101002600_day_assignments_add_assignment_time",
|
||||
"Migration20200101002700_create_budget_item_members",
|
||||
"Migration20200101002800_create_collab_message_reactions",
|
||||
"Migration20200101002900_collab_messages_add_deleted",
|
||||
"Migration20200101003000_trip_files_add_note_id",
|
||||
"Migration20200101003100_reservations_add_reservation_end_time",
|
||||
"Migration20200101003200_places_add_osm_id",
|
||||
"Migration20200101003300_trip_files_add_uploaded_by",
|
||||
"Migration20200101003400_reservations_add_accommodation_id",
|
||||
"Migration20200101003500_create_invite_tokens",
|
||||
"Migration20200101003600_users_add_mfa_enabled",
|
||||
"Migration20200101003700_create_packing_category_assignees",
|
||||
"Migration20200101003800_create_packing_templates",
|
||||
"Migration20200101003900_create_packing_bags",
|
||||
"Migration20200101004000_create_visited_countries",
|
||||
"Migration20200101004100_create_bucket_list",
|
||||
"Migration20200101004200_vacay_plans_add_weekend_days",
|
||||
"Migration20200101004300_users_add_immich_url",
|
||||
"Migration20200101004400_create_file_links",
|
||||
"Migration20200101004500_reservations_add_day_plan_position",
|
||||
"Migration20200101004600_budget_items_add_paid_by_user_id",
|
||||
"Migration20200101004700_bucket_list_add_target_date",
|
||||
"Migration20200101004800_create_notification_preferences",
|
||||
"Migration20200101004900_notification_preferences_add_notify_vacay_invite",
|
||||
"Migration20200101005000_create_share_tokens",
|
||||
"Migration20200101005100_share_tokens_add_share_map",
|
||||
"Migration20200101005200_create_audit_log",
|
||||
"Migration20200101005300_users_add_mfa_backup_codes",
|
||||
"Migration20200101005400_mcp_long_lived_api_tokens",
|
||||
"Migration20200101005500_mcp_addon_entry",
|
||||
"Migration20200101005600_index_on_mcp_tokens",
|
||||
"Migration20200101005700_ensure_mcp_addon_type_is_integration",
|
||||
"Migration20200101005800_places_add_route_geometry",
|
||||
"Migration20200101005900_users_add_must_change_password",
|
||||
"Migration20200101010000_trips_add_reminder_days",
|
||||
"Migration20200101010100_encrypt_any_plaintext_oidc_client_secret_left",
|
||||
"Migration20200101010200_encrypt_any_plaintext_smtp_pass_left_in",
|
||||
"Migration20200101010300_encrypt_any_plaintext_immich_api_key_values",
|
||||
"Migration20200101010400_budget_items_add_expense_date",
|
||||
"Migration20200101010500_create_trip_album_links",
|
||||
"Migration20200101010600_create_notifications",
|
||||
"Migration20200101010700_create_trip_photos",
|
||||
"Migration20200101010800_create_trip_album_links",
|
||||
"Migration20200101010900_users_add_synology_url",
|
||||
"Migration20200101011000_step_070",
|
||||
"Migration20200101011100_step_071",
|
||||
"Migration20200101011200_step_072",
|
||||
"Migration20200101011300_trip_photos_add_album_link_id",
|
||||
"Migration20200101011400_todo_items",
|
||||
"Migration20200101011500_backfill_addons",
|
||||
"Migration20200101011600_place_region_cache_for_sub_national_atlas",
|
||||
"Migration20200101011700_create_visited_regions",
|
||||
"Migration20200101011800_normalized_per_user_per_channel_notification_preferences",
|
||||
"Migration20200101011900_drop_the_old_notification_preferences_table",
|
||||
"Migration20200101012000_add_reservation_id_to_budget_items_for",
|
||||
"Migration20200101012100_add_quantity_to_packing_items_user_id",
|
||||
"Migration20200101012200_per_day_positions_for_multi_day_reservations",
|
||||
"Migration20200101012300_budget_category_ordering",
|
||||
"Migration20200101012400_naver_list_import_addon",
|
||||
"Migration20200101012500_oauth_2",
|
||||
"Migration20200101012600_refresh_token_rotation_chain_tracking_for_replay",
|
||||
"Migration20200101012700_public_client_support_for_browser_initiated_dynamic",
|
||||
"Migration20200101012800_make_oauth_clients",
|
||||
"Migration20200101012900_add_otp_field_skip_ssl_column_device",
|
||||
"Migration20200101013000_journey_addon",
|
||||
"Migration20200101013100_journal",
|
||||
"Migration20200101013200_journey_multi_trip_support_sharing_collaboration",
|
||||
"Migration20200101013300_journey_rebuild",
|
||||
"Migration20200101013400_journey_photos",
|
||||
"Migration20200101013500_journey_cover_image",
|
||||
"Migration20200101013600_pros_cons_for_journey_entries",
|
||||
"Migration20200101013700_journey_share_tokens",
|
||||
"Migration20200101013800_vacay_week_start_setting",
|
||||
"Migration20200101013900_unified_photo_provider_abstraction_layer",
|
||||
"Migration20200101014000_hide_skeletons_per_user_setting_on_journey",
|
||||
"Migration20200101014100_idempotency_keys_for_offline_mutation_replay",
|
||||
"Migration20200101014200_enable_naver_list_import_by_default",
|
||||
"Migration20200101014300_add_check_in_end_column_for_check",
|
||||
"Migration20200101014400_system_notices",
|
||||
"Migration20200101014500_passphrase_support_for_synology_shared_album_links",
|
||||
"Migration20200101014600_persistent_google_place_photo_disk_cache_registry",
|
||||
"Migration20200101014700_persistent_place_details_row_cache",
|
||||
"Migration20200101014800_backfill_expired_signed_google_photo_urls_to",
|
||||
"Migration20200101014900_disk_cache_metadata_for_remote_provider_photo",
|
||||
"Migration20200101015000_reservation_endpoints",
|
||||
"Migration20200101015100_reservations_add_end_day_id",
|
||||
"Migration20200101015200_opt_in_immich_auto_upload",
|
||||
"Migration20200101015300_expose_immich_auto_upload_toggle_in_the",
|
||||
"Migration20200101015400_rfc_8707_resource_indicators",
|
||||
"Migration20200101015500_password_reset",
|
||||
"Migration20200101015600_todo_due_date_reminders",
|
||||
"Migration20200101015700_security_audit_batch_1",
|
||||
"Migration20200101015800_widen_idempotency_keys_primary_key_to",
|
||||
"Migration20200101015900_sec_h6_revoke_all_oauth_tokens_issued",
|
||||
"Migration20200101020000_remove_not_null_constraint_on_day_accommodations",
|
||||
"Migration20200101020100_null_out_proxy_image_url_entries_that",
|
||||
"Migration20200101020200_clear_legacy_google_photo_urls_missed_by",
|
||||
"Migration20200101020300_journey_gallery_refactor",
|
||||
"Migration20200101020400_correct_stale_day_id_end_day_id",
|
||||
"Migration20200101020500_846_make_sort_order_authoritative_within_a",
|
||||
"Migration20200101020600_swap_inverted_start_day_id_end_day",
|
||||
"Migration20200101020700_prepare_migration_to_nest_typeorm",
|
||||
"Migration20200101020800_trim_leading_trailing_whitespace_from_stored_usernames",
|
||||
"Migration20200101020900_create_schema_version_new",
|
||||
"Migration20200101021000_oauth_2",
|
||||
"Migration20200101021100_drop_stale_atlas_cache_rows_for_territories",
|
||||
"Migration20200101021200_costs_rework",
|
||||
"Migration20200101021300_rename_the_budget_planner_addon_to_costs",
|
||||
"Migration20200101021400_webauthn_passkey_support_per_user_credentials_single",
|
||||
"Migration20200101021500_atlas_dropped_natural_earth_for_geoboundaries",
|
||||
"Migration20200101021600_step_136",
|
||||
"Migration20200101021700_users_add_airtrail_url",
|
||||
"Migration20200101021800_reservations_add_external_source",
|
||||
"Migration20200101021900_users_add_airtrail_write_enabled",
|
||||
"Migration20200101022000_store_google_maps_feature_ids_separately_from",
|
||||
"Migration20200101022100_remember_the_app_version_a_notice_was",
|
||||
"Migration20200101022200_budget_item_members_add_amount",
|
||||
"Migration20200101022300_calendar_feed_tokens",
|
||||
"Migration20200101022400_optimistic_concurrency_token_for_offline_conflict_detection",
|
||||
"Migration20200101022500_video_support",
|
||||
"Migration20200101022600_dedicated_booking_url",
|
||||
"Migration20200101022700_private_packing_items",
|
||||
"Migration20200101022800_guest_members",
|
||||
"Migration20200101022900_three_tier_packing_sharing",
|
||||
"Migration20200101023000_collections_addon",
|
||||
"Migration20200101023100_user_added_links_on_collections_saved_places",
|
||||
"Migration20200101023200_per_member_permission_role_on_a_shared",
|
||||
"Migration20200101023300_per_trip_invite_links",
|
||||
"Migration20200101023400_optional_trip_binding_on_an_admin_invite",
|
||||
"Migration20200101023500_plugin_system_scaffold",
|
||||
"Migration20200101023600_separate_the_admin_s_on_off_intent",
|
||||
"Migration20200101023700_plugin_capabilities",
|
||||
"Migration20200101023800_tofu_pin_for_a_plugin_s_author",
|
||||
"Migration20200101023900_hash_chained_capability_audit_log",
|
||||
"Migration20200101024000_per_collection_custom_labels",
|
||||
"Migration20200101024100_plugin_owned_metadata_on_core_entities",
|
||||
"Migration20200101024200_freeze_the_fx_rate_on_settle_up",
|
||||
"Migration20200101024300_1446_guests_are_per_trip_people_but",
|
||||
"Migration20200101024400_plugin_dependencies",
|
||||
"Migration20200101024500_per_user_plugin_settings",
|
||||
"Migration20200101024600_host_brokered_outbound_oauth",
|
||||
"Migration20200101024700_persistent_plugin_scheduler",
|
||||
"Migration20200101024800_durable_gdpr_erasure_queue",
|
||||
"Migration20200101024900_tombstones_for_atlas_countries_the_user_has",
|
||||
"Migration20200101025000_operator_supplied_egress_hosts_for_a_plugin",
|
||||
"Migration20200101025100_settings_page_action_buttons_a_plugin_contributes",
|
||||
"Migration20200101025200_why_a_plugin_s_update_was_refused",
|
||||
"Migration20200101025300_the_semver_range_of_trek_versions_a",
|
||||
"Migration20200101025400_place_regions_is_a_re_derivable_nominatim",
|
||||
"Migration20200101025500_tombstones_for_atlas_regions_the_user_has",
|
||||
"Migration20200101025600_half_vacation_days",
|
||||
"Migration20200101025700_read_only_vacay_calendar_sharing",
|
||||
"Migration20200101025800_collaborative_place_ratings",
|
||||
"Migration20200101025900_per_segment_travel_mode",
|
||||
"Migration20200101030000_school_holidays_are_a_visual_vacay_calendar",
|
||||
"Migration20200101030100_1517",
|
||||
"Migration20200101030200_comp_flex_days",
|
||||
"Migration20200101030300_configurable_vacation_year",
|
||||
"Migration20200101030400_manual_gpx_track_colour",
|
||||
"Migration20200101030500_backfill_the_three_places_feature_toggles_before",
|
||||
"Migration20200101030600_free_the_note_column_on_budget_items",
|
||||
"Migration20200101030700_note_colours",
|
||||
"Migration20200101030800_per_segment_travel_mode_for_boundary_legs",
|
||||
"Migration20200101030900_1298",
|
||||
"Migration20200101031000_a_reservation_day_positions_row_only_makes",
|
||||
"Migration20200101031100_1939",
|
||||
"Migration20200101031200_capture_metadata_on_the_photo_itself",
|
||||
"Migration20200101031300_a_journey_shared_while_the_trip_is",
|
||||
"Migration20200101031400_trek_studio_books",
|
||||
"Migration20200101031500_great_britain_gained_its_counties_and_boroughs",
|
||||
"Migration20200101031600_storage_slice_2",
|
||||
"Migration20200101031700_give_back_the_notes_the_ticketjson_step",
|
||||
"Migration20200101031800_a_deliberate_non_latest_plugin_install_sets",
|
||||
"Migration20200101031900_reservations_an_automated_ingest_parked_for_review",
|
||||
"Migration20200101032000_separate_an_integration_key_from_an_mcp",
|
||||
"Migration20200101032100_naver_list_import_was_typed_trip_but",
|
||||
"Migration20200101032200_whether_a_journey_s_map_draws_the",
|
||||
"Migration20200101032300_settings_field_defaults",
|
||||
"Migration20200101032400_settings_form_actions_gain_a_scope",
|
||||
"Migration20200101032500_a_journal_entry_that_is_not_a",
|
||||
"Migration20200101032600_place_shadow_log_which_search_result_a",
|
||||
"Migration20200101032700_what_kind_of_stop_a_place_is",
|
||||
"Migration20200101032800_points_a_day_s_drive_is_made",
|
||||
"Migration20200101032900_which_imported_track_a_day_s_drive",
|
||||
"Migration20200101033000_rename_the_misnamed_guangdong_province",
|
||||
"Migration20200101033100_let_a_file_hang_off_an_expense",
|
||||
"Migration20200101033200_which_chat_message_an_uploaded_image_belongs",
|
||||
"Migration20200101033300_links_somebody_shared_with_the_trip",
|
||||
"Migration20200101033400_route_usage_counters",
|
||||
"Migration20200101033500_how_full_this_stop_fills_the_tank",
|
||||
"Migration20200101033600_create_school_holiday_countries",
|
||||
"Migration20200101033700_day_assignments_add_end_day",
|
||||
"Migration20200101033800_create_roadtrip_day_boundaries",
|
||||
"Migration20200101033900_create_roadtrip_preferences",
|
||||
"Migration20200101034000_a_settle_up_payment_s_date_was",
|
||||
"Migration20200101034100_amap",
|
||||
"Migration20200101034200_dawarich_connection",
|
||||
"Migration20200101034300_reviewed_visit_suggestions",
|
||||
"Migration20200101034400_bucket_list_entries_can_now_be_ticked",
|
||||
"Migration20200101034500_where_an_atlas_country_came_from",
|
||||
"Migration20200101034600_per_key_read_scopes_for_api_v1",
|
||||
"Migration20200101034700_where_a_place_came_from_when_it",
|
||||
"Migration20200101034800_provenance_for_a_day_stop_that_a",
|
||||
"Migration20200101034900_give_every_stay_booked_before_this_release",
|
||||
"Migration20200101035000_the_same_sweep_once_more_for_the",
|
||||
"Migration20200101035100_a_suggestion_the_traveller_has_waved_away",
|
||||
"Migration20200101035200_the_country_an_entry_happened_in_resolved",
|
||||
"Migration20200101035300_which_of_the_optional_entry_fields_a",
|
||||
"Migration20200101035400_let_go_of_a_booking_the_day",
|
||||
"Migration20200101035500_a_journal_skeleton_belongs_to_a_day",
|
||||
"Migration20200101035600_document_providers_part_1_of_3_the",
|
||||
"Migration20200101035700_document_providers_part_2_of_3_the",
|
||||
"Migration20200101035800_document_providers_part_3_of_3_the",
|
||||
"Migration20200101035900_document_providers_when_trek_itself_put_a",
|
||||
"Migration20200101040000_trips_longer_than_a_year_lost_every",
|
||||
"Migration20200101040100_the_road_trip_day_boundaries_carried_the",
|
||||
"Migration20200101040200_trek_photo_cache_meta_cache_key_not_null",
|
||||
"Migration20200101040300_a_booked_night_finally_took_the_seat_a_new",
|
||||
"Migration20200101040400_immich_learns_the_switch_synology_airtrail_and",
|
||||
"Migration20200101040500_a_place_that_moves_takes_its_atlas",
|
||||
"Migration20200101040600_web_push_one_row_per_browser_a",
|
||||
"Migration20200101040700_the_2527_trigger_once_more_for_an",
|
||||
"Migration20200101040800_a_stop_kept_on_the_day_but",
|
||||
"Migration20200101040900_how_many_of_an_item_are_packed",
|
||||
"Migration20200101041000_a_bucket_list_wish_for_one_state",
|
||||
"Migration20200101041100_half_company_holidays_0_5_covers_the",
|
||||
"Migration20200101041200_a_journey_entry_still_being_written",
|
||||
"Migration20200101041300_two_narrower_ways_to_share_a_trip",
|
||||
"Migration20200101041400_a_note_on_a_settle_up_payment",
|
||||
"Migration20200101041500_google_api_calls_per_utc_day",
|
||||
"Migration20200101041600_packing_templates_remember_what_an_item_weighs",
|
||||
"Migration20200101041700_a_journey_s_state_as_its_owner",
|
||||
"Migration20200101041800_a_place_s_e_mail_and_its",
|
||||
"Migration20200101041900_a_journey_that_puts_an_entry_on",
|
||||
"Migration20200101042000_tours",
|
||||
"Migration20200101042100_a_trip_reminder_remembers_it_was_sent",
|
||||
"Migration20200101042200_an_index_on_every_foreign_key",
|
||||
"Migration20200101042300_every_tour_type_the_contract_names",
|
||||
"Migration20200101042400_one_account_per_email_whatever_its_case",
|
||||
"Migration20200101042500_a_cron_tick_runs_in_one_process",
|
||||
"Migration20200101042600_a_session_row_per_sign_in",
|
||||
"Migration20200101042700_timestamps_stored_in_one_spelling",
|
||||
"Migration20200101042800_an_email_the_account_typed_in_itself",
|
||||
"Migration20200101042900_tour_planned_total_duration",
|
||||
"Migration20200101043000_tour_break_additional_duration",
|
||||
"Migration20200101043100_an_imported_tour_has_no_hiking_difficulty",
|
||||
"Migration20200101043200_via_ferrata_tiles_outlive_a_restart",
|
||||
"Migration20200101043300_a_tour_leg_can_follow_a_via_ferrata",
|
||||
"Migration20200101043400_wanderer_connection_and_tour_sources",
|
||||
"Migration20200101043500_wanderer_difficulty_on_the_sac_scale",
|
||||
"Migration20200101043600_a_tour_remembers_the_import_it_was_derived_from",
|
||||
"Migration20200101043700_an_import_planned_over_keeps_its_recorded_track",
|
||||
"Migration20200101043800_a_tour_records_where_it_came_from",
|
||||
"Migration20200101043900_a_tour_can_be_paddled",
|
||||
"Migration20200101044000_a_paddle_tour_plans_its_portages_and_locks",
|
||||
"Migration20200101044100_paddle_obstacles_from_openstreetmap",
|
||||
"Migration20200101044200_a_paddle_tour_records_its_obstacle_decisions",
|
||||
"Migration20200101044300_a_trip_links_a_journal",
|
||||
"Migration20200101044400_a_paddle_region_builds_its_water_network",
|
||||
"Migration20200101044500_a_tour_waypoint_can_shape_the_route",
|
||||
"Migration20200101044600_a_paddle_tour_remembers_how_it_crosses_lakes",
|
||||
"Migration20200101044700_paddle_water_data_loads_where_a_paddler_plans",
|
||||
"Migration20200101044800_a_tour_counts_its_revisions",
|
||||
"Migration20200101044900_a_tour_waypoint_can_be_a_place_of_the_trip",
|
||||
"Migration20200101045000_a_hike_keeps_its_routing_preferences",
|
||||
"Migration20200101045100_a_tour_remembers_the_trip_it_was_taken_from",
|
||||
"Migration20200101045200_a_tour_can_be_ridden",
|
||||
"Migration20200101045300_a_tour_can_be_a_city_walk",
|
||||
"Migration20200101045400_a_tour_waypoint_remembers_the_kind_of_place_it_was_found_as",
|
||||
"Migration20200101045500_a_hike_can_be_marked_as_a_winter_activity",
|
||||
"Migration20200101045510_a_tour_can_be_a_run",
|
||||
"Migration20200101045520_a_tour_can_be_a_ski_track",
|
||||
"Migration20200101045600_a_tour_can_be_ridden_on_horseback",
|
||||
"Migration20200101045700_a_tour_records_the_changes_saved_from_a_proposal",
|
||||
"Migration20200101045710_a_saved_tour_change_can_be_taken_back",
|
||||
"Migration20200101045900_a_tour_keeps_the_track_it_was_done_with",
|
||||
"Migration20200101045910_a_tour_can_be_left_out_of_ones_activities",
|
||||
"Migration20200101046000_a_tour_waypoint_can_end_a_stage",
|
||||
"Migration20200101046010_a_day_can_hold_one_stage_of_a_tour",
|
||||
"Migration20200101046100_a_collection_keeps_whole_tours",
|
||||
"Migration20200101046110_a_tour_points_at_its_packing_list",
|
||||
"Migration20200101046120_a_wanderer_connection_can_watch_its_sources",
|
||||
"Migration20200101046130_snowshoeing_and_winter_hiking_are_ski_disciplines",
|
||||
"Migration20200101046140_tours_are_on_for_every_install",
|
||||
"Migration20200101046150_a_ski_tour_keeps_its_piste_router_options",
|
||||
"Migration20200101046160_a_journey_keeps_its_recorded_days",
|
||||
"Migration20200101046170_a_journey_entry_remembers_the_stays_it_came_from",
|
||||
"Migration20200101046180_journeys_can_prepare_recorded_days",
|
||||
"Migration20200101046190_a_journey_share_can_show_its_plan_and_recordings",
|
||||
"Migration20200101046200_a_tour_draft_lives_on_the_account",
|
||||
"Migration20200101046200_a_user_can_connect_an_ai_provider",
|
||||
"Migration20200101046210_the_trip_assistant_remembers_its_conversations",
|
||||
"Migration20200101046220_a_chat_message_can_say_it_came_from_the_assistant",
|
||||
"Migration20200101046230_an_admin_can_share_a_chatgpt_plan",
|
||||
"Migration20200101046240_a_photo_keeps_its_quality_signals",
|
||||
"Migration20200101046250_an_assistant_conversation_can_be_about_a_journey",
|
||||
"Migration20200101046260_a_book_keeps_its_last_revisions",
|
||||
"Migration20200101046270_a_photo_knows_its_colours_and_calm_areas",
|
||||
"Migration20200101046280_an_assistant_conversation_can_be_about_no_one_trip",
|
||||
"Migration20200101046290_a_removed_member_cannot_rejoin_by_invite_link",
|
||||
"Migration20200101046300_an_attached_file_stays_with_its_conversation",
|
||||
"Migration20200101046310_an_admin_can_run_a_plugin_outside_its_trek_range",
|
||||
"Migration20200101046320_a_place_knows_where_its_details_came_from",
|
||||
"Migration20200101046330_an_object_no_row_names_is_marked_before_it_goes",
|
||||
"Migration20200101046340_a_released_object_outlasts_every_undo_before_it_goes",
|
||||
"Migration20200101046350_a_place_lies_on_the_real_world",
|
||||
"Migration20200101046360_a_new_install_starts_with_more_addons_on",
|
||||
"Migration20200101046370_a_deleted_chat_message_keeps_no_text",
|
||||
"Migration20200101046380_ireland_gained_its_counties",
|
||||
"Migration20200101046390_a_trip_can_keep_its_costs_as_totals_only",
|
||||
"Migration20200101046400_a_booked_flight_shows_where_it_is",
|
||||
"Migration20200101046410_a_forwarded_booking_mail_lands_in_its_trip",
|
||||
"Migration20200101046420_a_visit_keeps_its_own_stay",
|
||||
"Migration20200101046430_a_paused_mail_import_can_tell_its_address_holders",
|
||||
"Migration20200101046440_a_trip_owns_its_tags"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,858 @@
|
||||
-- The schema a fresh Postgres database starts from. Generated by `npm run gen:pg-baseline`; do not edit.
|
||||
CREATE COLLATION IF NOT EXISTS nocase (provider = icu, locale = 'und-u-ks-level2', deterministic = false);
|
||||
create table "addons" ("id" text null, "name" text not null, "description" text null, "type" text not null default 'global', "icon" text null default 'Puzzle', "enabled" bigint null default 0, "config" jsonb null default '{}', "sort_order" bigint null default 0, primary key ("id"));
|
||||
create table "app_settings" ("key" text null, "value" text null, primary key ("key"));
|
||||
create table "document_providers" ("id" text null, "name" text not null, "description" text null, "icon" text null default 'FileText', "enabled" bigint null default 0, "sort_order" bigint null default 0, primary key ("id"));
|
||||
create table "document_provider_fields" ("id" bigserial primary key, "provider_id" text not null, "field_key" text not null, "label" text not null, "input_type" text not null default 'text', "placeholder" text null, "hint" text null, "required" bigint null default 0, "secret" bigint null default 0, "sort_order" bigint null default 0);
|
||||
alter table "document_provider_fields" add constraint "document_provider_fields_provider_id_field_key_unique" unique ("provider_id", "field_key");
|
||||
create table "ferrata_tiles" ("tile_key" text not null, "payload" text not null, "fetched_at" bigint not null, primary key ("tile_key"));
|
||||
create table "flight_live_states" ("callsign" text not null, "service_date" text not null, "origin" text not null, "destination" text not null, "phase" text not null default 'scheduled', "departed_at" text null, "landed_at" text null, "lat" double precision null, "lng" double precision null, "altitude_ft" double precision null, "ground_speed_kt" double precision null, "track_deg" double precision null, "vertical_rate_fpm" double precision null, "on_ground" bigint null, "registration" text null, "aircraft_type" text null, "source" text null, "first_seen_at" text null, "last_seen_at" text null, "fetched_at" text null, "next_poll_at" text null, "fail_count" bigint not null default 0, "departed_notified" bigint not null default 0, "landed_notified" bigint not null default 0, "delay_notified" bigint not null default 0, primary key ("callsign", "service_date", "origin", "destination"));
|
||||
create table "google_api_usage" ("day" text null, "calls" bigint not null default 0, primary key ("day"));
|
||||
create table "google_place_photo_meta" ("place_id" text null, "attribution" text null, "fetched_at" bigint not null, "error_at" bigint null, primary key ("place_id"));
|
||||
create table "mail_ingest_cursor" ("id" bigserial primary key, "transport" text not null, "mailbox" text not null, "uid_validity" bigint null, "last_uid" bigint null, "last_ok_at" text null, "last_error" text null, "lease_owner" text null, "lease_until" text null);
|
||||
alter table "mail_ingest_cursor" add constraint "mail_ingest_cursor_transport_mailbox_unique" unique ("transport", "mailbox");
|
||||
create table "migrations" ("id" bigserial primary key, "timestamp" bigint not null, "name" varchar(255) not null);
|
||||
create table "paddle_region_requests" ("region_id" text not null, "name" text not null, "reason" text not null, "bytes" bigint null, "requested_by" text null, "requested_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "declined_at" text null, primary key ("region_id"));
|
||||
alter table "paddle_region_requests" add constraint "paddle_region_requests_reason_check" check ("reason" in ('ask', 'too_large', 'limit'));
|
||||
create table "paddle_regions" ("id" text not null, "name" text not null, "boundary" text null, "min_lat" double precision null, "min_lng" double precision null, "max_lat" double precision null, "max_lng" double precision null, "status" text not null default 'queued', "source_timestamp" text null, "imported_at" text null, "feature_count" bigint not null default 0, "error" text null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "origin" text not null default 'admin', primary key ("id"));
|
||||
alter table "paddle_regions" add constraint "paddle_regions_status_check" check ("status" in ('queued', 'importing', 'ready', 'failed'));
|
||||
alter table "paddle_regions" add constraint "paddle_regions_origin_check" check ("origin" in ('admin', 'auto'));
|
||||
create table "paddle_features" ("id" bigserial primary key, "region_id" text not null, "osm_ref" text not null, "kind" text not null, "group_key" text null, "name" text null, "geometry" text not null, "tags" text not null, "tag_hash" text not null, "min_lat" double precision not null, "min_lng" double precision not null, "max_lat" double precision not null, "max_lng" double precision not null);
|
||||
create index "idx_paddle_features_box" on "paddle_features" ("min_lat", "max_lat", "min_lng", "max_lng");
|
||||
alter table "paddle_features" add constraint "idx_paddle_features_region_ref" unique ("region_id", "osm_ref");
|
||||
create table "paddle_water_graphs" ("region_id" text null, "file" text not null, "rev" text not null, "bytes" bigint not null, "built_at" text not null, "stats" text not null, "min_lat" double precision not null, "min_lng" double precision not null, "max_lat" double precision not null, "max_lng" double precision not null, primary key ("region_id"));
|
||||
create index "idx_paddle_water_graphs_box" on "paddle_water_graphs" ("min_lat", "max_lat", "min_lng", "max_lng");
|
||||
alter table "paddle_water_graphs" add constraint "paddle_water_graphs_region_id_unique" unique ("region_id");
|
||||
create table "photo_providers" ("id" text null, "name" text not null, "description" text null, "icon" text null default 'Image', "enabled" bigint null default 0, "sort_order" bigint null default 0, primary key ("id"));
|
||||
create table "photo_provider_fields" ("id" bigserial primary key, "provider_id" text not null, "field_key" text not null, "label" text not null, "input_type" text not null default 'text', "placeholder" text null, "hint" text null, "required" bigint null default 0, "secret" bigint null default 0, "settings_key" text null, "payload_key" text null, "sort_order" bigint null default 0);
|
||||
alter table "photo_provider_fields" add constraint "photo_provider_fields_provider_id_field_key_unique" unique ("provider_id", "field_key");
|
||||
create table "place_contrib_log" ("id" bigserial primary key, "day" text not null, "contrib_key" text not null, "place_name" text not null, "field" text not null, "value_summary" text null, "result" text not null, "reason" text null);
|
||||
create index "idx_place_contrib_log_day" on "place_contrib_log" ("day");
|
||||
create table "place_details_cache" ("place_id" text not null, "lang" text not null default '', "expanded" bigint not null default 0, "payload_json" text not null, "fetched_at" bigint not null, primary key ("place_id", "lang", "expanded"));
|
||||
create table "place_shadow_picks" ("id" bigserial primary key, "created_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "query" text not null, "lang" text null, "bias_lat" double precision null, "bias_lng" double precision null, "source" text not null, "live_rank" bigint not null, "live_count" bigint not null, "picked_name" text not null, "picked_lat" double precision not null, "picked_lng" double precision not null, "picked_place_id" text null);
|
||||
create index "idx_place_shadow_created" on "place_shadow_picks" ("created_at");
|
||||
create table "plugin_actions" ("plugin_id" text not null, "action_key" text not null, "label" text not null, "hint" text null, "danger" bigint not null default 0, "sort_order" bigint not null default 0, "scope" text not null default 'user', primary key ("plugin_id", "action_key"));
|
||||
create table "plugin_capability_audit" ("id" bigserial primary key, "plugin_id" text not null, "acting_user_id" bigint null, "method" text not null, "resource" text null, "code" text not null, "ts" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "prev_hash" text null, "hash" text not null);
|
||||
create index "idx_plugin_audit_plugin" on "plugin_capability_audit" ("plugin_id", "id");
|
||||
create table "plugin_egress_hosts" ("id" bigserial primary key, "plugin_id" text not null, "host" text not null, "created_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
|
||||
create index "idx_plugin_egress_hosts_plugin" on "plugin_egress_hosts" ("plugin_id");
|
||||
alter table "plugin_egress_hosts" add constraint "plugin_egress_hosts_plugin_id_host_unique" unique ("plugin_id", "host");
|
||||
create table "plugin_entity_metadata" ("id" bigserial primary key, "plugin_id" text not null, "entity_type" text not null, "entity_id" bigint not null, "key" text not null, "value" text null, "updated_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
|
||||
create index "idx_plugin_meta_entity" on "plugin_entity_metadata" ("plugin_id", "entity_type", "entity_id");
|
||||
alter table "plugin_entity_metadata" add constraint "plugin_entity_metadata_plugin_id_entity_type_enti_ee00f_unique" unique ("plugin_id", "entity_type", "entity_id", "key");
|
||||
create table "plugin_error_log" ("id" bigserial primary key, "plugin_id" text not null, "ts" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "level" text not null default 'error', "message" text null, "stack" text null);
|
||||
create index "idx_plugin_error_log_plugin" on "plugin_error_log" ("plugin_id", "ts");
|
||||
create table "plugin_meta_migrations" ("plugin_id" text not null, "migration_id" text not null, "applied_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), primary key ("plugin_id", "migration_id"));
|
||||
create table "plugin_oauth_state" ("state" text null, "plugin_id" text not null, "user_id" bigint not null, "verifier" text not null, "created_at" bigint not null, primary key ("state"));
|
||||
create table "plugin_oauth_tokens" ("plugin_id" text not null, "user_id" bigint not null, "access_token" text null, "refresh_token" text null, "expires_at" bigint null, "scope" text null, "updated_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), primary key ("plugin_id", "user_id"));
|
||||
create table "plugins" ("id" text null, "name" text not null, "description" text null, "type" text not null default 'integration', "icon" text null default 'Blocks', "version" text null, "api_version" bigint null default 1, "min_trek_version" text null, "permissions" text null default '[]', "granted_permissions" text null default '[]', "status" text not null default 'inactive', "config" text null default '{}', "source_repo" text null, "source_commit" text null, "sha256" text null, "crash_count" bigint not null default 0, "last_error" text null, "reviewed_at" text null, "sort_order" bigint not null default 0, "installed_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "updated_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "enabled" bigint not null default 0, "capabilities" text not null default '{}', "author_pubkey" text null, "dependencies" text not null default '{}', "operator_egress" bigint not null default 0, "update_block_code" text null, "update_block_detail" text null, "update_block_version" text null, "trek_range" text null, "update_hold" bigint not null default 0, "trek_range_accepted_version" text null, "trek_range_accepted_host" text null, primary key ("id"));
|
||||
create table "plugin_scheduled_tasks" ("id" bigserial primary key, "plugin_id" text not null, "name" text not null, "due_at" bigint not null, "payload" text not null default 'null', "every_ms" bigint null, "created_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
|
||||
create index "idx_plugin_sched_due" on "plugin_scheduled_tasks" ("due_at");
|
||||
alter table "plugin_scheduled_tasks" add constraint "plugin_scheduled_tasks_plugin_id_name_unique" unique ("plugin_id", "name");
|
||||
create table "plugin_settings_fields" ("id" bigserial primary key, "plugin_id" text not null, "field_key" text not null, "label" text null, "input_type" text not null default 'text', "placeholder" text null, "hint" text null, "required" bigint not null default 0, "secret" bigint not null default 0, "scope" text not null default 'instance', "options" text null, "oauth_config" text null, "sort_order" bigint not null default 0, "default_value" text null);
|
||||
alter table "plugin_settings_fields" add constraint "plugin_settings_fields_plugin_id_field_key_unique" unique ("plugin_id", "field_key");
|
||||
create table "plugin_user_config" ("plugin_id" text not null, "user_id" bigint not null, "config" text not null default '{}', "updated_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), primary key ("plugin_id", "user_id"));
|
||||
create table "plugin_user_erasure_queue" ("id" bigserial primary key, "plugin_id" text not null, "user_id" bigint not null, "created_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
|
||||
create index "idx_plugin_erasure_plugin" on "plugin_user_erasure_queue" ("plugin_id");
|
||||
alter table "plugin_user_erasure_queue" add constraint "plugin_user_erasure_queue_plugin_id_user_id_unique" unique ("plugin_id", "user_id");
|
||||
create table "route_usage_daily" ("day" text not null, "profile" text not null, "surface" text not null, "self_hosted" bigint not null, "requests" bigint not null default 0, "waypoints" bigint not null default 0, "km" double precision not null default 0, "failed" bigint not null default 0, primary key ("day", "profile", "surface", "self_hosted"));
|
||||
create index "idx_route_usage_day" on "route_usage_daily" ("day");
|
||||
create table "scheduler_leases" ("name" text not null, "owner" text not null, "expires_at" bigint not null, primary key ("name"));
|
||||
create table "schema_version" ("id" bigserial primary key, "version" bigint not null);
|
||||
create table "school_holiday_countries" ("code" text null, "name" text not null, primary key ("code"));
|
||||
create table "school_holiday_regions" ("id" bigserial primary key, "name" text collate "nocase" not null, "revision" bigint not null default 1, "country" text not null);
|
||||
alter table "school_holiday_regions" add constraint "school_holiday_regions_country_name_unique" unique ("country", "name");
|
||||
create table "school_holiday_periods" ("id" bigserial primary key, "region_id" bigint not null, "name" text not null, "start_date" text not null, "end_date" text not null);
|
||||
create index "idx_school_holiday_periods_region" on "school_holiday_periods" ("region_id");
|
||||
alter table "school_holiday_periods" add constraint "school_holiday_periods_end_date_check" check (end_date >= start_date);
|
||||
create table "storage_reclaim_marks" ("category" text not null, "key" text not null, "first_seen_at" text not null, "size" bigint not null, primary key ("category", "key"));
|
||||
create table "storage_release_queue" ("category" text not null, "key" text not null, "due_at" text not null, primary key ("category", "key"));
|
||||
create table "tour_types" ("key" text null, "label_key" text not null, "icon" text not null, "color" text not null, "routing_profile" text null, "is_sport" bigint not null default 1, "enabled" bigint not null default 1, "sort_order" bigint not null default 0, primary key ("key"));
|
||||
create table "trek_photo_cache_meta" ("cache_key" text not null, "content_type" text not null default 'image/jpeg', "fetched_at" bigint not null, primary key ("cache_key"));
|
||||
create index "idx_trek_photo_cache_meta_fetched_at" on "trek_photo_cache_meta" ("fetched_at");
|
||||
create table "users" ("id" bigserial primary key, "username" text not null, "email" text not null, "password_hash" text not null, "role" text not null default 'user', "maps_api_key" text null, "unsplash_api_key" text null, "amap_api_key" text null, "openweather_api_key" text null, "avatar" text null, "oidc_sub" text null, "oidc_issuer" text null, "last_login" text null, "mfa_enabled" bigint null default 0, "mfa_secret" text null, "mfa_backup_codes" text null, "immich_url" text null, "immich_access_token" text null, "synology_url" text null, "synology_username" text null, "synology_password" text null, "synology_sid" text null, "must_change_password" bigint null default 0, "password_version" bigint not null default 0, "feed_token" text null, "is_guest" bigint not null default 0, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "updated_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "immich_api_key" text null, "synology_skip_ssl" bigint not null default 0, "synology_did" text null, "first_seen_version" text not null default '0.0.0', "login_count" bigint not null default 0, "immich_auto_upload" bigint not null default 0, "airtrail_url" text null, "airtrail_api_key" text null, "airtrail_allow_insecure_tls" bigint null default 0, "airtrail_write_enabled" bigint null default 0, "display_name" text null, "immich_allow_insecure_tls" bigint not null default 0, "email_self_asserted" bigint not null default 0);
|
||||
create index "idx_users_email" on "users" ("email");
|
||||
create unique index "idx_users_feed_token" on "users" ("feed_token") where feed_token IS NOT NULL;
|
||||
alter table "users" add constraint "users_email_unique" unique ("email");
|
||||
alter table "users" add constraint "users_username_unique" unique ("username");
|
||||
CREATE UNIQUE INDEX idx_users_email_lower ON users (lower(email));
|
||||
create table "user_notice_dismissals" ("user_id" bigint not null, "notice_id" text not null, "dismissed_at" bigint not null, "dismissed_app_version" text null, primary key ("user_id", "notice_id"));
|
||||
alter table "user_notice_dismissals" add constraint "user_notice_dismissals_user_id_notice_id_unique" unique ("user_id", "notice_id");
|
||||
create table "trips" ("id" bigserial primary key, "user_id" bigint not null, "title" text not null, "description" text null, "start_date" text null, "end_date" text null, "currency" text null default 'EUR', "cover_image" text null, "is_archived" bigint null default 0, "reminder_days" bigint null default 3, "feed_token" text null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "updated_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "reminder_sent_for" text null, "costs_mode" text not null default 'split');
|
||||
create index "idx_trips_user_id" on "trips" ("user_id");
|
||||
create index "idx_trips_created_at" on "trips" ("created_at");
|
||||
create unique index "idx_trips_feed_token" on "trips" ("feed_token") where feed_token IS NOT NULL;
|
||||
alter table "trips" add constraint "trips_costs_mode_check" check ("costs_mode" in ('split', 'totals'));
|
||||
create table "roadtrip_preferences" ("trip_id" bigint not null, "key" text not null, "value" text not null, primary key ("trip_id", "key"));
|
||||
alter table "roadtrip_preferences" add constraint "roadtrip_preferences_trip_id_key_unique" unique ("trip_id", "key");
|
||||
create table "days" ("id" bigserial primary key, "trip_id" bigint not null, "day_number" bigint not null, "date" text null, "notes" text null, "title" text null, "default_transport_mode" text null);
|
||||
create index "idx_days_trip_id" on "days" ("trip_id");
|
||||
alter table "days" add constraint "days_trip_id_day_number_unique" unique ("trip_id", "day_number");
|
||||
create table "roadtrip_vias" ("id" bigserial primary key, "day_id" bigint not null, "after_order_index" bigint not null, "sequence" bigint not null default 0, "lat" double precision not null, "lng" double precision not null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
|
||||
create index "idx_roadtrip_vias_day" on "roadtrip_vias" ("day_id", "after_order_index", "sequence");
|
||||
create table "day_notes" ("id" bigserial primary key, "day_id" bigint not null, "trip_id" bigint not null, "text" text not null, "time" text null, "icon" text null default '📝', "sort_order" double precision null default 0, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "color" text null);
|
||||
create index "idx_day_notes_day_id" on "day_notes" ("day_id");
|
||||
create index "idx_day_notes_trip_id" on "day_notes" ("trip_id");
|
||||
create table "budget_category_order" ("trip_id" bigint not null, "category" text not null, "sort_order" bigint not null default 0, primary key ("trip_id", "category"));
|
||||
alter table "budget_category_order" add constraint "budget_category_order_trip_id_category_unique" unique ("trip_id", "category");
|
||||
create table "trip_members" ("id" bigserial primary key, "trip_id" bigint not null, "user_id" bigint not null, "added_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "invited_by" bigint null);
|
||||
create index "idx_trip_members_trip_id" on "trip_members" ("trip_id");
|
||||
create index "idx_trip_members_user_id" on "trip_members" ("user_id");
|
||||
create index "idx_trip_members_invited_by" on "trip_members" ("invited_by");
|
||||
alter table "trip_members" add constraint "trip_members_trip_id_user_id_unique" unique ("trip_id", "user_id");
|
||||
create table "trip_member_removals" ("id" bigserial primary key, "trip_id" bigint not null, "user_id" bigint not null, "removed_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
|
||||
create index "idx_trip_member_removals_user" on "trip_member_removals" ("user_id");
|
||||
alter table "trip_member_removals" add constraint "trip_member_removals_trip_id_user_id_unique" unique ("trip_id", "user_id");
|
||||
create table "trip_invite_tokens" ("id" bigserial primary key, "trip_id" bigint not null, "token" text not null, "expires_at" text null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "created_by" bigint null);
|
||||
create index "idx_trip_invite_tokens_token" on "trip_invite_tokens" ("token");
|
||||
create index "idx_trip_invite_tokens_created_by" on "trip_invite_tokens" ("created_by");
|
||||
alter table "trip_invite_tokens" add constraint "trip_invite_tokens_token_unique" unique ("token");
|
||||
alter table "trip_invite_tokens" add constraint "trip_invite_tokens_trip_id_unique" unique ("trip_id");
|
||||
create table "trip_album_links" ("id" bigserial primary key, "trip_id" bigint not null, "user_id" bigint not null, "provider" text not null, "album_id" text not null, "album_name" text not null default '', "sync_enabled" bigint not null default 1, "last_synced_at" text null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "passphrase" text null default NULL);
|
||||
create index "idx_trip_album_links_trip" on "trip_album_links" ("trip_id");
|
||||
create index "idx_trip_album_links_user_id" on "trip_album_links" ("user_id");
|
||||
alter table "trip_album_links" add constraint "trip_album_links_trip_id_user_id_provider_album_id_unique" unique ("trip_id", "user_id", "provider", "album_id");
|
||||
create table "trek_photos" ("id" bigserial primary key, "provider" text not null, "asset_id" text null, "owner_id" bigint null, "file_path" text null, "thumbnail_path" text null, "width" bigint null, "height" bigint null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "passphrase" text null default NULL, "media_type" text not null default 'image', "duration_ms" bigint null, "taken_at" text null, "lat" double precision null, "lng" double precision null);
|
||||
create index "idx_trek_photos_owner" on "trek_photos" ("owner_id");
|
||||
create index "idx_trek_photos_geo" on "trek_photos" ("lat", "lng") where lat IS NOT NULL AND lng IS NOT NULL;
|
||||
create unique index "idx_trek_photos_provider_asset" on "trek_photos" ("provider", "asset_id", "owner_id") where asset_id IS NOT NULL;
|
||||
create table "trip_photos" ("id" bigserial primary key, "trip_id" bigint not null, "user_id" bigint not null, "photo_id" bigint not null, "shared" bigint not null default 1, "album_link_id" bigint null, "added_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
|
||||
create index "idx_trip_photos_trip" on "trip_photos" ("trip_id");
|
||||
create index "idx_trip_photos_user_id" on "trip_photos" ("user_id");
|
||||
create index "idx_trip_photos_photo" on "trip_photos" ("photo_id");
|
||||
create index "idx_trip_photos_album_link_id" on "trip_photos" ("album_link_id");
|
||||
alter table "trip_photos" add constraint "trip_photos_trip_id_user_id_photo_id_unique" unique ("trip_id", "user_id", "photo_id");
|
||||
create table "trek_photo_signals" ("id" bigserial primary key, "photo_id" bigint not null, "algo" bigint not null, "phash" text null, "sharpness" double precision null, "luma" double precision null, "clipped" double precision null, "orig_width" bigint null, "orig_height" bigint null, "computed_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "palette" text null, "busy" text null, "sal_x" double precision null, "sal_y" double precision null);
|
||||
alter table "trek_photo_signals" add constraint "trek_photo_signals_photo_id_unique" unique ("photo_id");
|
||||
create table "tour_drafts" ("id" bigserial primary key, "trip_id" bigint not null, "user_id" bigint not null, "payload" text not null, "updated_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
|
||||
create index "idx_tour_drafts_user" on "tour_drafts" ("user_id");
|
||||
alter table "tour_drafts" add constraint "tour_drafts_trip_id_user_id_unique" unique ("trip_id", "user_id");
|
||||
create table "todo_items" ("id" bigserial primary key, "trip_id" bigint not null, "name" text not null, "checked" bigint null default 0, "category" text null, "sort_order" bigint null default 0, "due_date" text null, "description" text null, "assigned_user_id" bigint null, "priority" bigint null default 0, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "reminded_at" text null);
|
||||
create index "idx_todo_items_trip_id" on "todo_items" ("trip_id");
|
||||
create index "idx_todo_items_assigned_user_id" on "todo_items" ("assigned_user_id");
|
||||
create table "todo_category_assignees" ("id" bigserial primary key, "trip_id" bigint not null, "category_name" text not null, "user_id" bigint not null);
|
||||
create index "idx_todo_category_assignees_user_id" on "todo_category_assignees" ("user_id");
|
||||
alter table "todo_category_assignees" add constraint "todo_category_assignees_trip_id_category_name_user_id_unique" unique ("trip_id", "category_name", "user_id");
|
||||
create table "tags" ("id" bigserial primary key, "user_id" bigint not null, "name" text not null, "color" text null default '#10b981', "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "trip_id" bigint null);
|
||||
create index "idx_tags_user_id" on "tags" ("user_id");
|
||||
create index "idx_tags_trip_id" on "tags" ("trip_id");
|
||||
create table "share_tokens" ("id" bigserial primary key, "trip_id" bigint not null, "token" text not null, "share_map" bigint null default 1, "share_bookings" bigint null default 1, "share_packing" bigint null default 0, "share_budget" bigint null default 0, "share_collab" bigint null default 0, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "expires_at" text null, "share_travel_only" bigint not null default 0, "share_hide_images" bigint not null default 0, "created_by" bigint not null);
|
||||
create index "idx_share_tokens_trip_id" on "share_tokens" ("trip_id");
|
||||
create index "idx_share_tokens_token" on "share_tokens" ("token");
|
||||
create index "idx_share_tokens_created_by" on "share_tokens" ("created_by");
|
||||
alter table "share_tokens" add constraint "share_tokens_token_unique" unique ("token");
|
||||
create table "settings" ("id" bigserial primary key, "user_id" bigint not null, "key" text not null, "value" text null);
|
||||
alter table "settings" add constraint "settings_user_id_key_unique" unique ("user_id", "key");
|
||||
create table "push_subscriptions" ("id" bigserial primary key, "user_id" bigint not null, "endpoint" text not null, "p256dh" text not null, "auth" text not null, "vapid_public_key" text not null, "user_agent" text null, "created_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "last_success_at" text null, "failure_count" bigint not null default 0);
|
||||
create index "idx_push_subscriptions_user" on "push_subscriptions" ("user_id");
|
||||
alter table "push_subscriptions" add constraint "push_subscriptions_endpoint_unique" unique ("endpoint");
|
||||
create table "password_reset_tokens" ("id" bigserial primary key, "user_id" bigint not null, "token_hash" text not null, "expires_at" text not null, "consumed_at" text null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "created_ip" text null);
|
||||
create index "idx_prt_user" on "password_reset_tokens" ("user_id");
|
||||
create index "idx_prt_hash" on "password_reset_tokens" ("token_hash");
|
||||
alter table "password_reset_tokens" add constraint "password_reset_tokens_token_hash_unique" unique ("token_hash");
|
||||
create table "packing_templates" ("id" bigserial primary key, "name" text not null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "created_by" bigint not null);
|
||||
create index "idx_packing_templates_created_by" on "packing_templates" ("created_by");
|
||||
create table "packing_template_categories" ("id" bigserial primary key, "template_id" bigint not null, "name" text not null, "sort_order" bigint not null default 0);
|
||||
create index "idx_packing_template_categories_template_id" on "packing_template_categories" ("template_id");
|
||||
create table "packing_template_items" ("id" bigserial primary key, "category_id" bigint not null, "name" text not null, "sort_order" bigint not null default 0, "weight_grams" bigint null, "quantity" bigint not null default 1, "bag_name" text null);
|
||||
create index "idx_packing_template_items_category_id" on "packing_template_items" ("category_id");
|
||||
create table "packing_category_assignees" ("id" bigserial primary key, "trip_id" bigint not null, "category_name" text not null, "user_id" bigint not null);
|
||||
create index "idx_packing_category_assignees_user_id" on "packing_category_assignees" ("user_id");
|
||||
alter table "packing_category_assignees" add constraint "packing_category_assignees_trip_id_category_name_user_id_unique" unique ("trip_id", "category_name", "user_id");
|
||||
create table "packing_bags" ("id" bigserial primary key, "trip_id" bigint not null, "name" text not null, "color" text not null default '#6366f1', "weight_limit_grams" bigint null, "sort_order" bigint null default 0, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "user_id" bigint null default NULL);
|
||||
create index "idx_packing_bags_trip_id" on "packing_bags" ("trip_id");
|
||||
create index "idx_packing_bags_user_id" on "packing_bags" ("user_id");
|
||||
create table "packing_items" ("id" bigserial primary key, "trip_id" bigint not null, "name" text not null, "checked" bigint null default 0, "category" text null, "sort_order" bigint null default 0, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "weight_grams" bigint null, "bag_id" bigint null, "quantity" bigint not null default 1, "updated_at" text null, "is_private" bigint not null default 0, "owner_id" bigint null, "packed_quantity" bigint null);
|
||||
create index "idx_packing_items_trip_id" on "packing_items" ("trip_id");
|
||||
create index "idx_packing_items_bag_id" on "packing_items" ("bag_id");
|
||||
create index "idx_packing_items_owner_id" on "packing_items" ("owner_id");
|
||||
create table "packing_item_contributors" ("item_id" bigint not null, "user_id" bigint not null, "status" text not null default 'accepted', "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), primary key ("item_id", "user_id"));
|
||||
create index "idx_packing_item_contributors_user_id" on "packing_item_contributors" ("user_id");
|
||||
alter table "packing_item_contributors" add constraint "packing_item_contributors_item_id_user_id_unique" unique ("item_id", "user_id");
|
||||
create table "packing_item_recipients" ("item_id" bigint not null, "user_id" bigint not null, primary key ("item_id", "user_id"));
|
||||
create table "packing_bag_members" ("bag_id" bigint not null, "user_id" bigint not null, primary key ("bag_id", "user_id"));
|
||||
create table "oauth_clients" ("id" text null, "user_id" bigint null, "name" text not null, "client_id" text not null, "client_secret_hash" text not null, "redirect_uris" text not null default '[]', "allowed_scopes" text not null default '[]', "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "is_public" bigint not null default 0, "created_via" text not null default 'settings_ui', "allows_client_credentials" bigint not null default 0, primary key ("id"));
|
||||
create index "idx_oauth_clients_user" on "oauth_clients" ("user_id");
|
||||
alter table "oauth_clients" add constraint "idx_oauth_clients_client_id" unique ("client_id");
|
||||
alter table "oauth_clients" add constraint "oauth_clients_client_id_unique" unique ("client_id");
|
||||
create table "oauth_tokens" ("id" bigserial primary key, "client_id" text not null, "user_id" bigint not null, "access_token_hash" text not null, "refresh_token_hash" text not null, "scopes" text not null default '[]', "access_token_expires_at" text not null, "refresh_token_expires_at" text not null, "revoked_at" text null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "parent_token_id" bigint null, "audience" text null);
|
||||
create index "idx_oauth_tokens_client_id" on "oauth_tokens" ("client_id");
|
||||
create index "idx_oauth_tokens_user" on "oauth_tokens" ("user_id");
|
||||
alter table "oauth_tokens" add constraint "idx_oauth_tokens_access" unique ("access_token_hash");
|
||||
alter table "oauth_tokens" add constraint "idx_oauth_tokens_refresh" unique ("refresh_token_hash");
|
||||
create index "idx_oauth_tokens_parent" on "oauth_tokens" ("parent_token_id");
|
||||
alter table "oauth_tokens" add constraint "oauth_tokens_refresh_token_hash_unique" unique ("refresh_token_hash");
|
||||
alter table "oauth_tokens" add constraint "oauth_tokens_access_token_hash_unique" unique ("access_token_hash");
|
||||
create table "oauth_consents" ("id" bigserial primary key, "client_id" text not null, "user_id" bigint not null, "scopes" text not null default '[]', "updated_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
|
||||
create index "idx_oauth_consents_user_id" on "oauth_consents" ("user_id");
|
||||
alter table "oauth_consents" add constraint "oauth_consents_client_id_user_id_unique" unique ("client_id", "user_id");
|
||||
create table "notifications" ("id" bigserial primary key, "type" text not null, "scope" text not null, "target" bigint not null, "sender_id" bigint null, "recipient_id" bigint not null, "title_key" text not null, "title_params" text null default '{}', "text_key" text not null, "text_params" text null default '{}', "positive_text_key" text null, "negative_text_key" text null, "positive_callback" text null, "negative_callback" text null, "response" text null, "navigate_text_key" text null, "navigate_target" text null, "is_read" bigint null default 0, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
|
||||
create index "idx_notifications_sender_id" on "notifications" ("sender_id");
|
||||
create index "idx_notifications_target_scope" on "notifications" ("target", "scope");
|
||||
create index "idx_notifications_recipient_created" on "notifications" ("recipient_id", "created_at");
|
||||
create index "idx_notifications_recipient" on "notifications" ("recipient_id", "is_read", "created_at");
|
||||
create table "notification_channel_preferences" ("user_id" bigint not null, "event_type" text not null, "channel" text not null, "enabled" bigint not null default 1, primary key ("user_id", "event_type", "channel"));
|
||||
create index "idx_ncp_user" on "notification_channel_preferences" ("user_id");
|
||||
alter table "notification_channel_preferences" add constraint "notification_channel_preferences_user_id_event_ty_8d673_unique" unique ("user_id", "event_type", "channel");
|
||||
create table "mcp_tokens" ("id" bigserial primary key, "user_id" bigint not null, "name" text not null, "token_hash" text not null, "token_prefix" text not null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "last_used_at" text null, "kind" text not null default 'mcp', "scope_mode" text not null default 'all', "api_scopes" text null);
|
||||
create index "idx_mcp_tokens_user_id" on "mcp_tokens" ("user_id");
|
||||
alter table "mcp_tokens" add constraint "idx_mcp_tokens_hash" unique ("token_hash");
|
||||
create table "mail_ingest_prefs" ("id" bigserial primary key, "user_id" bigint not null, "enabled" bigint not null default 1, "ai_enabled" bigint not null default 1, "auto_add" bigint not null default 1);
|
||||
alter table "mail_ingest_prefs" add constraint "mail_ingest_prefs_user_id_unique" unique ("user_id");
|
||||
create table "mail_ingest_addresses" ("id" bigserial primary key, "token_hash" text not null, "token_enc" text not null, "user_id" bigint not null, "trip_id" bigint null, "created_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "revoked_at" text null, "last_used_at" text null);
|
||||
create index "idx_mail_ingest_addresses_trip" on "mail_ingest_addresses" ("trip_id");
|
||||
create index "idx_mail_ingest_addresses_user" on "mail_ingest_addresses" ("user_id", "trip_id");
|
||||
alter table "mail_ingest_addresses" add constraint "mail_ingest_addresses_token_hash_unique" unique ("token_hash");
|
||||
create table "mail_ingest_messages" ("id" bigserial primary key, "transport" text not null, "message_id_hdr" text null, "dedupe_hash" text not null, "address_id" bigint null, "user_id" bigint not null, "trip_id" bigint null, "from_addr" text null, "from_verified" bigint not null default 0, "auth_results" text null, "subject" text null, "received_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "size" bigint not null, "raw_eml_enc" text null, "raw_purged_at" text null, "status" text not null default 'queued', "reason" text null, "hints" text null, "attachments" text null, "forwarding_code" text null, "attempts" bigint not null default 0, "next_attempt_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "lease_until" text null, "ai_used" bigint not null default 0, "processed_at" text null);
|
||||
create index "idx_mail_ingest_messages_trip" on "mail_ingest_messages" ("trip_id");
|
||||
create index "idx_mail_ingest_messages_address" on "mail_ingest_messages" ("address_id", "received_at");
|
||||
create index "idx_mail_ingest_messages_user" on "mail_ingest_messages" ("user_id", "received_at");
|
||||
create index "idx_mail_ingest_messages_due" on "mail_ingest_messages" ("status", "next_attempt_at");
|
||||
alter table "mail_ingest_messages" add constraint "mail_ingest_messages_dedupe_hash_unique" unique ("dedupe_hash");
|
||||
create table "mail_ingest_candidates" ("id" bigserial primary key, "message_id" bigint not null, "user_id" bigint not null, "position" bigint not null default 0, "item_json" text null, "source" text null, "checks_json" text null, "uncertain_fields" text null, "match_json" text null, "suggested_trip_id" bigint null, "dedupe_key" text null, "content_hash" text null, "resolution" text not null default 'pending', "reason" text null, "resolved_trip_id" bigint null, "created_ids_json" text null, "attach_error" text null, "resolved_by" bigint null, "resolved_at" text null, "undo_until" text null, "created_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
|
||||
create index "idx_mail_ingest_candidates_suggested" on "mail_ingest_candidates" ("suggested_trip_id");
|
||||
create index "idx_mail_ingest_candidates_resolved" on "mail_ingest_candidates" ("resolved_trip_id", "content_hash");
|
||||
create index "idx_mail_ingest_candidates_user" on "mail_ingest_candidates" ("user_id", "resolution");
|
||||
create index "idx_mail_ingest_candidates_message" on "mail_ingest_candidates" ("message_id", "position");
|
||||
create table "journeys" ("id" bigserial primary key, "user_id" bigint not null, "title" text not null, "subtitle" text null, "cover_gradient" text null, "status" text null default 'draft', "created_at" bigint not null, "updated_at" bigint not null, "cover_image" text null, "show_trip_tracks" bigint not null default 0, "show_verdict" bigint not null default 1, "show_mood" bigint not null default 1, "show_weather" bigint not null default 1, "status_override" text null, "photo_location" bigint not null default 0, "auto_prepare_recordings" bigint not null default 0);
|
||||
create index "idx_journeys_user" on "journeys" ("user_id");
|
||||
create table "trip_journal_links" ("id" bigserial primary key, "trip_id" bigint not null, "journey_id" bigint not null, "created_at" bigint not null, "linked_by" bigint null);
|
||||
create index "idx_trip_journal_links_journey" on "trip_journal_links" ("journey_id");
|
||||
create index "idx_trip_journal_links_linked_by" on "trip_journal_links" ("linked_by");
|
||||
alter table "trip_journal_links" add constraint "trip_journal_links_trip_id_unique" unique ("trip_id");
|
||||
create table "trip_journal_link_members" ("link_id" bigint not null, "user_id" bigint not null, "role" text not null default 'viewer', "hide_skeletons" bigint not null default 0, "added_at" bigint not null, primary key ("link_id", "user_id"));
|
||||
create index "idx_trip_journal_link_members_user" on "trip_journal_link_members" ("user_id");
|
||||
alter table "trip_journal_link_members" add constraint "trip_journal_link_members_link_id_user_id_unique" unique ("link_id", "user_id");
|
||||
alter table "trip_journal_link_members" add constraint "trip_journal_link_members_role_check" check ("role" in ('viewer', 'editor'));
|
||||
create table "journey_trips" ("journey_id" bigint not null, "trip_id" bigint not null, "added_at" bigint not null, primary key ("journey_id", "trip_id"));
|
||||
create index "idx_journey_trips_journey" on "journey_trips" ("journey_id");
|
||||
create index "idx_journey_trips_trip_id" on "journey_trips" ("trip_id");
|
||||
alter table "journey_trips" add constraint "journey_trips_journey_id_trip_id_unique" unique ("journey_id", "trip_id");
|
||||
create table "journey_share_tokens" ("id" bigserial primary key, "journey_id" bigint not null, "token" text not null, "share_timeline" bigint null default 1, "share_gallery" bigint null default 1, "share_map" bigint null default 1, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "newest_first" bigint not null default 0, "share_plan" bigint not null default 0, "share_recordings" bigint not null default 0, "created_by" bigint not null);
|
||||
alter table "journey_share_tokens" add constraint "idx_journey_share_journey" unique ("journey_id");
|
||||
create index "idx_journey_share_tokens_created_by" on "journey_share_tokens" ("created_by");
|
||||
alter table "journey_share_tokens" add constraint "journey_share_tokens_token_unique" unique ("token");
|
||||
create table "journey_photos" ("id" bigserial primary key, "journey_id" bigint not null, "photo_id" bigint not null, "caption" text null, "shared" bigint null default 0, "sort_order" bigint null default 0, "provider" text null, "asset_id" text null, "owner_id" bigint null, "created_at" bigint not null);
|
||||
create index "idx_journey_photos_journey" on "journey_photos" ("journey_id");
|
||||
create index "idx_journey_photos_photo_id" on "journey_photos" ("photo_id");
|
||||
alter table "journey_photos" add constraint "journey_photos_journey_id_photo_id_unique" unique ("journey_id", "photo_id");
|
||||
create table "journey_book_revisions" ("id" bigserial primary key, "journey_id" bigint not null, "version" bigint not null, "document" text not null, "created_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
|
||||
create index "idx_journey_book_revisions_journey" on "journey_book_revisions" ("journey_id");
|
||||
create table "journey_recording_prep" ("id" bigserial primary key, "journey_id" bigint not null, "user_id" bigint not null, "last_attempt_at" text null, "last_success_at" text null, "last_error" text null);
|
||||
create index "idx_journey_recording_prep_user" on "journey_recording_prep" ("user_id");
|
||||
alter table "journey_recording_prep" add constraint "idx_journey_recording_prep_person" unique ("journey_id", "user_id");
|
||||
create table "journey_recorded_days" ("id" bigserial primary key, "journey_id" bigint not null, "local_date" text not null, "source" text not null default 'dawarich', "source_kind" text not null, "utc_offset_minutes" bigint not null, "window_from" text not null, "window_to" text not null, "segments" text not null, "point_count" bigint not null, "distance_m" double precision null, "content_hash" text not null, "truncated" bigint not null default 0, "fetched_at" text not null, "created_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "updated_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "imported_by" bigint null);
|
||||
create index "idx_journey_recorded_days_imported_by" on "journey_recorded_days" ("imported_by");
|
||||
alter table "journey_recorded_days" add constraint "idx_journey_recorded_days_day" unique ("journey_id", "local_date", "source");
|
||||
create table "journey_contributors" ("journey_id" bigint not null, "user_id" bigint not null, "role" text not null, "added_at" bigint not null, "hide_skeletons" bigint not null default 0, primary key ("journey_id", "user_id"));
|
||||
create index "idx_journey_contributors_user" on "journey_contributors" ("user_id");
|
||||
alter table "journey_contributors" add constraint "journey_contributors_journey_id_user_id_unique" unique ("journey_id", "user_id");
|
||||
create table "journey_books" ("id" bigserial primary key, "journey_id" bigint not null, "title" text not null default '', "document" text not null, "version" bigint not null default 1, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "updated_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "updated_by" bigint null, "created_by" bigint null);
|
||||
create index "idx_journey_books_journey" on "journey_books" ("journey_id");
|
||||
create index "idx_journey_books_updated_by" on "journey_books" ("updated_by");
|
||||
create index "idx_journey_books_created_by" on "journey_books" ("created_by");
|
||||
create table "invite_tokens" ("id" bigserial primary key, "token" text not null, "max_uses" bigint not null default 1, "used_count" bigint not null default 0, "expires_at" text null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "trip_id" bigint null, "created_by" bigint not null);
|
||||
create index "idx_invite_tokens_trip_id" on "invite_tokens" ("trip_id");
|
||||
create index "idx_invite_tokens_created_by" on "invite_tokens" ("created_by");
|
||||
alter table "invite_tokens" add constraint "invite_tokens_token_unique" unique ("token");
|
||||
create table "idempotency_keys" ("key" text not null, "user_id" bigint not null, "method" text not null, "path" text not null, "status_code" bigint not null, "response_body" text not null, "created_at" bigint not null default CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) AS bigint), primary key ("key", "user_id", "method", "path"));
|
||||
create index "idx_idempotency_keys_user_id" on "idempotency_keys" ("user_id");
|
||||
create index "idx_idempotency_keys_created" on "idempotency_keys" ("created_at");
|
||||
alter table "idempotency_keys" add constraint "idempotency_keys_key_user_id_method_path_unique" unique ("key", "user_id", "method", "path");
|
||||
create table "hidden_regions" ("id" bigserial primary key, "user_id" bigint not null, "region_code" text not null, "country_code" text not null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
|
||||
create index "idx_hidden_regions_user" on "hidden_regions" ("user_id");
|
||||
alter table "hidden_regions" add constraint "hidden_regions_user_id_region_code_unique" unique ("user_id", "region_code");
|
||||
create table "hidden_countries" ("id" bigserial primary key, "user_id" bigint not null, "country_code" text not null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
|
||||
create index "idx_hidden_countries_user" on "hidden_countries" ("user_id");
|
||||
alter table "hidden_countries" add constraint "hidden_countries_user_id_country_code_unique" unique ("user_id", "country_code");
|
||||
create table "document_connections" ("id" bigserial primary key, "trip_id" bigint not null, "provider_id" text not null, "owner_user_id" bigint not null, "base_url" text not null, "secrets" text null, "settings" text not null default '{}', "allow_insecure_tls" bigint not null default 0, "capabilities" text null, "last_probe_at" text null, "last_probe_state" text not null default 'never', "last_probe_error" text null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "updated_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
|
||||
create index "idx_document_connections_trip" on "document_connections" ("trip_id");
|
||||
create index "idx_document_connections_provider_id" on "document_connections" ("provider_id");
|
||||
create index "idx_document_connections_owner" on "document_connections" ("owner_user_id");
|
||||
alter table "document_connections" add constraint "document_connections_trip_id_provider_id_unique" unique ("trip_id", "provider_id");
|
||||
create table "trip_document_links" ("id" bigserial primary key, "trip_id" bigint not null, "connection_id" bigint not null, "provider_id" text not null, "remote_scope_key" text not null, "remote_root_id" text null, "remote_root_path" text null, "remote_label" text not null default '', "direction" text not null default 'both', "delete_policy" text not null default 'unlink', "conflict_policy" text not null default 'manual', "sync_enabled" bigint not null default 1, "webhook_token" text null, "webhook_secret" text null, "webhook_subscription_id" text null, "remote_cursor" text null, "last_sync_at" text null, "last_sync_state" text not null default 'never', "last_sync_error" text null, "failure_count" bigint not null default 0, "next_attempt_at" text null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "updated_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "created_by" bigint null);
|
||||
create index "idx_trip_document_links_trip" on "trip_document_links" ("trip_id");
|
||||
create index "idx_trip_document_links_connection_id" on "trip_document_links" ("connection_id");
|
||||
create index "idx_trip_document_links_created_by" on "trip_document_links" ("created_by");
|
||||
create index "idx_trip_document_links_due" on "trip_document_links" ("sync_enabled", "next_attempt_at");
|
||||
create unique index "idx_trip_document_links_token" on "trip_document_links" ("webhook_token") where webhook_token IS NOT NULL;
|
||||
alter table "trip_document_links" add constraint "trip_document_links_trip_id_connection_id_remote__1c36d_unique" unique ("trip_id", "connection_id", "remote_scope_key");
|
||||
create table "dawarich_connections" ("user_id" bigint null, "url" text null, "api_key" text null, "allow_insecure_tls" bigint not null default 0, "sync_enabled" bigint not null default 1, "last_sync_at" text null, "last_sync_state" text not null default 'never', "last_sync_error" text null, "capabilities" text null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "updated_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), primary key ("user_id"));
|
||||
create table "collections" ("id" bigserial primary key, "owner_id" bigint not null, "name" text not null, "description" text null, "color" text null default '#6366f1', "icon" text null default 'Bookmark', "cover_image" text null, "links" text null, "sort_order" bigint null default 0, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "updated_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
|
||||
create index "idx_collections_owner_id" on "collections" ("owner_id");
|
||||
create table "collection_tours" ("id" bigserial primary key, "collection_id" bigint not null, "name" text not null, "description" text null, "website" text null, "route_geometry" text null, "waypoints" text not null, "distance" double precision null, "elevation_gain" double precision null, "elevation_loss" double precision null, "duration" double precision null, "planned_duration_minutes" bigint null, "break_additional_minutes" bigint null, "difficulty" text null, "wanderer_ref" text null, "match_confidence" double precision null, "max_hiking_difficulty" bigint null, "bike_profile" text null, "run_profile" text null, "run_pace_seconds_per_km" bigint null, "ski_discipline" text null, "ski_technique" text null, "boat_type" text null, "water_context" text null, "paddle_speed_kmh" double precision null, "portage_speed_kmh" double precision null, "paddle_lake_style" text null, "track_marks" text null, "hiking_preferences" text null, "origin" text not null, "origin_file_name" text null, "track_started_at" text null, "track_ended_at" text null, "source_trip_title" text not null, "source_tour_name" text not null, "created_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "ski_options" text null, "tour_type" text not null, "saved_by" bigint null);
|
||||
create index "idx_collection_tours_collection" on "collection_tours" ("collection_id");
|
||||
create index "idx_collection_tours_tour_type" on "collection_tours" ("tour_type");
|
||||
create index "idx_collection_tours_saved_by" on "collection_tours" ("saved_by");
|
||||
create table "collection_labels" ("id" bigserial primary key, "collection_id" bigint not null, "name" text not null, "color" text null default '#6366f1', "sort_order" bigint null default 0, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
|
||||
create index "idx_collection_labels_collection" on "collection_labels" ("collection_id");
|
||||
create table "collection_members" ("id" bigserial primary key, "collection_id" bigint not null, "user_id" bigint not null, "status" text not null default 'pending', "role" text not null default 'editor', "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
|
||||
create index "idx_collection_members_user" on "collection_members" ("user_id");
|
||||
alter table "collection_members" add constraint "collection_members_collection_id_user_id_unique" unique ("collection_id", "user_id");
|
||||
create table "collab_polls" ("id" bigserial primary key, "trip_id" bigint not null, "user_id" bigint not null, "question" text not null, "options" text not null, "multiple" bigint null default 0, "closed" bigint null default 0, "deadline" text null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
|
||||
create index "idx_collab_polls_trip" on "collab_polls" ("trip_id");
|
||||
create index "idx_collab_polls_user_id" on "collab_polls" ("user_id");
|
||||
create table "collab_poll_votes" ("id" bigserial primary key, "poll_id" bigint not null, "user_id" bigint not null, "option_index" bigint not null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
|
||||
create index "idx_collab_poll_votes_user_id" on "collab_poll_votes" ("user_id");
|
||||
alter table "collab_poll_votes" add constraint "collab_poll_votes_poll_id_user_id_option_index_unique" unique ("poll_id", "user_id", "option_index");
|
||||
create table "collab_notes" ("id" bigserial primary key, "trip_id" bigint not null, "user_id" bigint not null, "category" text null default 'General', "title" text not null, "content" text null, "color" text null default '#6366f1', "pinned" bigint null default 0, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "updated_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "website" text null);
|
||||
create index "idx_collab_notes_trip" on "collab_notes" ("trip_id");
|
||||
create index "idx_collab_notes_user_id" on "collab_notes" ("user_id");
|
||||
create table "collab_messages" ("id" bigserial primary key, "trip_id" bigint not null, "user_id" bigint not null, "text" text not null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "deleted" bigint null default 0, "origin" text null, "reply_to" bigint null);
|
||||
create index "idx_collab_messages_trip" on "collab_messages" ("trip_id");
|
||||
create index "idx_collab_messages_user_id" on "collab_messages" ("user_id");
|
||||
create index "idx_collab_messages_reply_to" on "collab_messages" ("reply_to");
|
||||
create table "collab_message_reactions" ("id" bigserial primary key, "message_id" bigint not null, "user_id" bigint not null, "emoji" text not null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
|
||||
create index "idx_collab_reactions_msg" on "collab_message_reactions" ("message_id");
|
||||
create index "idx_collab_message_reactions_user_id" on "collab_message_reactions" ("user_id");
|
||||
alter table "collab_message_reactions" add constraint "collab_message_reactions_message_id_user_id_emoji_unique" unique ("message_id", "user_id", "emoji");
|
||||
create table "collab_links" ("id" bigserial primary key, "trip_id" bigint not null, "user_id" bigint not null, "title" text not null, "url" text not null, "pinned" bigint null default 0, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "updated_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
|
||||
create index "idx_collab_links_trip" on "collab_links" ("trip_id");
|
||||
create index "idx_collab_links_user_id" on "collab_links" ("user_id");
|
||||
create table "categories" ("id" bigserial primary key, "name" text not null, "color" text null default '#6366f1', "icon" text null default '📍', "user_id" bigint null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
|
||||
create index "idx_categories_user_id" on "categories" ("user_id");
|
||||
create table "places" ("id" bigserial primary key, "trip_id" bigint not null, "name" text not null, "description" text null, "lat" double precision null, "lng" double precision null, "address" text null, "category_id" bigint null, "price" double precision null, "currency" text null, "reservation_status" text null default 'none', "reservation_notes" text null, "reservation_datetime" text null, "place_time" text null, "end_time" text null, "duration_minutes" bigint null default 60, "notes" text null, "image_url" text null, "google_place_id" text null, "google_ftid" text null, "website" text null, "phone" text null, "transport_mode" text null default 'walking', "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "updated_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "osm_id" text null, "route_geometry" text null, "route_color" text null, "stop_type" text null, "fill_percent" bigint null, "amap_poi_id" text null, "source" text null, "email" text null, "opening_hours" text null);
|
||||
create index "idx_places_trip_id" on "places" ("trip_id");
|
||||
create index "idx_places_category_id" on "places" ("category_id");
|
||||
create table "tours" ("place_id" bigint null, "distance" double precision null, "elevation_gain" double precision null, "elevation_loss" double precision null, "duration" double precision null, "difficulty" text null, "wanderer_ref" text null, "match_confidence" double precision null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "max_hiking_difficulty" bigint null default 2, "planned_duration_minutes" bigint null, "break_additional_minutes" bigint null, "derived_from_place_id" bigint null, "recorded_route_geometry" text null, "origin" text not null default 'trek', "origin_file_name" text null, "boat_type" text null, "water_context" text null, "paddle_speed_kmh" double precision null, "portage_speed_kmh" double precision null, "track_marks" text null, "paddle_lake_style" text null, "revision" bigint not null default 1, "hiking_preferences" text null, "taken_over_from_trip_title" text null, "taken_over_from_tour_name" text null, "bike_profile" text null, "run_profile" text null, "run_pace_seconds_per_km" bigint null, "ski_technique" text null, "track_started_at" text null, "track_ended_at" text null, "ski_discipline" text null, "ski_options" text null, "tour_type" text not null, primary key ("place_id"));
|
||||
create index "idx_tours_tour_type" on "tours" ("tour_type");
|
||||
create index "idx_tours_derived_from_place_id" on "tours" ("derived_from_place_id") where derived_from_place_id IS NOT NULL;
|
||||
alter table "tours" add constraint "tours_run_pace_seconds_per_km_check" check (run_pace_seconds_per_km IS NULL OR (run_pace_seconds_per_km >= 120 AND run_pace_seconds_per_km <= 1200));
|
||||
alter table "tours" add constraint "tours_revision_check" check (revision >= 1);
|
||||
alter table "tours" add constraint "tours_origin_check" check ("origin" in ('trek', 'gpx', 'wanderer'));
|
||||
alter table "tours" add constraint "tours_boat_type_check" check ("boat_type" in ('kayak', 'canoe', 'sup', 'other'));
|
||||
alter table "tours" add constraint "tours_water_context_check" check ("water_context" in ('river', 'lake'));
|
||||
alter table "tours" add constraint "tours_paddle_lake_style_check" check ("paddle_lake_style" in ('direct', 'shore'));
|
||||
alter table "tours" add constraint "tours_bike_profile_check" check ("bike_profile" in ('touring', 'road', 'gravel', 'mtb'));
|
||||
alter table "tours" add constraint "tours_run_profile_check" check ("run_profile" in ('running', 'trail'));
|
||||
alter table "tours" add constraint "tours_ski_technique_check" check ("ski_technique" in ('classic', 'skating', 'unknown'));
|
||||
alter table "tours" add constraint "tours_ski_discipline_check" check ("ski_discipline" in ('alpine', 'snowboard', 'cross_country', 'touring', 'snowshoe', 'winter_hike'));
|
||||
create table "tour_waypoints" ("id" bigserial primary key, "place_id" bigint not null, "lat" double precision not null, "lng" double precision not null, "role" text not null, "sequence" bigint not null, "fixed_leg" text null, "lock" text null, "shaping" bigint not null default 0, "linked_place_id" bigint null, "station_key" text null, "name" text null, "stay_minutes" bigint null, "importance" text null, "protected" bigint not null default 0, "opening_hours" text null, "poi_category" text null, "stage_end" bigint not null default 0);
|
||||
create index "idx_tour_waypoints_linked_place" on "tour_waypoints" ("linked_place_id") where linked_place_id IS NOT NULL;
|
||||
alter table "tour_waypoints" add constraint "tour_waypoints_place_id_sequence_unique" unique ("place_id", "sequence");
|
||||
alter table "tour_waypoints" add constraint "tour_waypoints_stage_end_check" check (stage_end IN (0, 1));
|
||||
alter table "tour_waypoints" add constraint "tour_waypoints_protected_check" check (protected IN (0, 1));
|
||||
alter table "tour_waypoints" add constraint "tour_waypoints_stay_minutes_check" check (stay_minutes IS NULL OR (stay_minutes >= 0 AND stay_minutes <= 1440));
|
||||
alter table "tour_waypoints" add constraint "tour_waypoints_shaping_check" check (shaping IN (0, 1));
|
||||
alter table "tour_waypoints" add constraint "tour_waypoints_importance_check" check ("importance" in ('optional', 'must'));
|
||||
create table "tour_sources" ("place_id" bigint null, "provider" text not null, "instance" text not null, "external_id" text not null, "external_url" text null, "external_updated" text null, "content_hash" text not null, "local_hash" text not null, "imported_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "imported_by" bigint null, primary key ("place_id"));
|
||||
create index "idx_tour_sources_imported_by" on "tour_sources" ("imported_by");
|
||||
create index "idx_tour_sources_external" on "tour_sources" ("provider", "instance", "external_id");
|
||||
create table "tour_source_hints" ("place_id" bigint null, "user_id" bigint not null, "state" text null, "changes" text null, "reason" text null, "external_updated" text null, "seen_hash" text null, "seen_updated" text null, "checked_at" text null, primary key ("place_id"));
|
||||
create index "idx_tour_source_hints_user_id" on "tour_source_hints" ("user_id");
|
||||
alter table "tour_source_hints" add constraint "tour_source_hints_state_check" check ("state" in ('possible_change', 'changed', 'unverifiable'));
|
||||
alter table "tour_source_hints" add constraint "tour_source_hints_reason_check" check ("reason" in ('unavailable', 'no_change_time'));
|
||||
create table "tour_packing_links" ("place_id" bigint null, "category" text null, "linked_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "linked_by" bigint null, primary key ("place_id"));
|
||||
create index "idx_tour_packing_links_linked_by" on "tour_packing_links" ("linked_by");
|
||||
create table "tour_obstacle_reviews" ("place_id" bigint not null, "obstacle_key" text not null, "decision" text not null, "note" text null, "route_fingerprint" text not null, "source_fingerprint" text not null, "obstacle_snapshot" text not null, "decided_at" text not null, "decided_by" bigint null, primary key ("place_id", "obstacle_key"));
|
||||
alter table "tour_obstacle_reviews" add constraint "tour_obstacle_reviews_place_id_obstacle_key_unique" unique ("place_id", "obstacle_key");
|
||||
alter table "tour_obstacle_reviews" add constraint "tour_obstacle_reviews_decision_check" check ("decision" in ('pass', 'portage', 'reroute', 'not_affected'));
|
||||
create table "tour_change_steps" ("id" bigserial primary key, "place_id" bigint not null, "proposal_id" text not null, "base_revision" bigint not null, "revision" bigint not null, "changes" text not null, "before_state" text not null, "saved_by" bigint null, "saved_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "undone_revision" bigint null, "undone_by" bigint null, "undone_at" text null);
|
||||
alter table "tour_change_steps" add constraint "tour_change_steps_place_id_revision_unique" unique ("place_id", "revision");
|
||||
alter table "tour_change_steps" add constraint "tour_change_steps_undone_revision_check" check (undone_revision IS NULL OR undone_revision > revision);
|
||||
alter table "tour_change_steps" add constraint "tour_change_steps_revision_check" check (revision = base_revision + 1);
|
||||
alter table "tour_change_steps" add constraint "tour_change_steps_base_revision_check" check (base_revision >= 1);
|
||||
create table "tour_activity_exclusions" ("id" bigserial primary key, "user_id" bigint not null, "place_id" bigint not null, "excluded_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
|
||||
create index "idx_tour_activity_exclusions_place" on "tour_activity_exclusions" ("place_id");
|
||||
alter table "tour_activity_exclusions" add constraint "tour_activity_exclusions_user_id_place_id_unique" unique ("user_id", "place_id");
|
||||
create table "roadtrip_day_tracks" ("day_id" bigint null, "place_id" bigint not null, "stray_km" double precision null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), primary key ("day_id"));
|
||||
create index "idx_roadtrip_day_tracks_place" on "roadtrip_day_tracks" ("place_id");
|
||||
create table "place_regions" ("place_id" bigint null, "country_code" text not null, "region_code" text not null, "region_name" text not null, primary key ("place_id"));
|
||||
create index "idx_place_regions_country" on "place_regions" ("country_code");
|
||||
create index "idx_place_regions_region" on "place_regions" ("region_code");
|
||||
create table "place_ratings" ("id" bigserial primary key, "place_id" bigint not null, "user_id" bigint not null, "rating" bigint not null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
|
||||
create index "idx_place_ratings_place" on "place_ratings" ("place_id");
|
||||
create index "idx_place_ratings_user_id" on "place_ratings" ("user_id");
|
||||
alter table "place_ratings" add constraint "place_ratings_place_id_user_id_unique" unique ("place_id", "user_id");
|
||||
create table "place_field_origin" ("place_id" bigint not null, "field" text not null, "origin" text not null, "value_hash" text not null, "updated_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), primary key ("place_id", "field"));
|
||||
alter table "place_field_origin" add constraint "place_field_origin_place_id_field_unique" unique ("place_id", "field");
|
||||
create table "place_contrib_outbox" ("id" bigserial primary key, "contrib_key" text not null, "field" text not null, "value" text not null, "place_id" bigint not null, "place_name" text not null, "lat" double precision null, "lng" double precision null, "country" text null, "cid" text not null, "attempts" bigint not null default 0, "eligible_at" text not null, "next_attempt_at" text not null, "created_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
|
||||
create index "idx_place_contrib_outbox_place" on "place_contrib_outbox" ("place_id");
|
||||
create index "idx_place_contrib_outbox_due" on "place_contrib_outbox" ("next_attempt_at");
|
||||
alter table "place_contrib_outbox" add constraint "place_contrib_outbox_contrib_key_field_unique" unique ("contrib_key", "field");
|
||||
create table "place_tags" ("place_id" bigint not null, "tag_id" bigint not null, primary key ("place_id", "tag_id"));
|
||||
create table "photos" ("id" bigserial primary key, "trip_id" bigint not null, "day_id" bigint null, "place_id" bigint null, "filename" text not null, "original_name" text not null, "file_size" bigint null, "mime_type" text null, "caption" text null, "taken_at" text null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
|
||||
create index "idx_photos_trip_id" on "photos" ("trip_id");
|
||||
create index "idx_photos_day_id" on "photos" ("day_id");
|
||||
create index "idx_photos_place_id" on "photos" ("place_id");
|
||||
create table "journey_entries" ("id" bigserial primary key, "journey_id" bigint not null, "source_trip_id" bigint null, "source_place_id" bigint null, "author_id" bigint not null, "type" text not null, "title" text null, "story" text null, "entry_date" text not null, "entry_time" text null, "location_name" text null, "location_lat" double precision null, "location_lng" double precision null, "mood" text null, "weather" text null, "tags" text null, "visibility" text null default 'private', "sort_order" bigint null default 0, "created_at" bigint not null, "updated_at" bigint not null, "pros_cons" text null, "stats_excluded" bigint not null default 0, "dismissed" bigint not null default 0, "country_code" text null, "source_assignment_id" bigint null, "is_draft" bigint not null default 0);
|
||||
create index "idx_journey_entries_source_trip_id" on "journey_entries" ("source_trip_id");
|
||||
create index "idx_journey_entries_source" on "journey_entries" ("source_place_id");
|
||||
create index "idx_journey_entries_author_id" on "journey_entries" ("author_id");
|
||||
create index "idx_journey_entries_source_assignment" on "journey_entries" ("source_place_id", "source_assignment_id");
|
||||
create index "idx_journey_entries_order" on "journey_entries" ("journey_id", "entry_date", "sort_order");
|
||||
create index "idx_journey_entries_journey" on "journey_entries" ("journey_id", "entry_date");
|
||||
create table "journey_entry_stays" ("id" bigserial primary key, "journey_id" bigint not null, "entry_id" bigint not null, "source" text not null default 'dawarich', "source_visit_id" text not null, "name" text not null, "lat" double precision null, "lng" double precision null, "started_at" text not null, "ended_at" text not null, "duration_minutes" bigint not null default 0, "sort_order" bigint not null default 0, "user_id" bigint null, "created_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
|
||||
create index "idx_journey_entry_stays_entry" on "journey_entry_stays" ("entry_id");
|
||||
create index "idx_journey_entry_stays_user" on "journey_entry_stays" ("user_id");
|
||||
alter table "journey_entry_stays" add constraint "idx_journey_entry_stays_stay" unique ("journey_id", "source", "user_id", "source_visit_id");
|
||||
create table "journey_entry_photos" ("entry_id" bigint not null, "journey_photo_id" bigint not null, "sort_order" bigint null default 0, "created_at" bigint not null, primary key ("entry_id", "journey_photo_id"));
|
||||
create index "idx_journey_entry_photos_entry" on "journey_entry_photos" ("entry_id");
|
||||
create index "idx_journey_entry_photos_photo" on "journey_entry_photos" ("journey_photo_id");
|
||||
alter table "journey_entry_photos" add constraint "journey_entry_photos_entry_id_journey_photo_id_unique" unique ("entry_id", "journey_photo_id");
|
||||
create table "day_assignments" ("id" bigserial primary key, "day_id" bigint not null, "place_id" bigint not null, "order_index" bigint null default 0, "notes" text null, "reservation_status" text null default 'none', "reservation_notes" text null, "reservation_datetime" text null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "assignment_time" text null, "assignment_end_time" text null, "leg_transport_mode" text null, "incoming_leg_transport_mode" text null, "end_day" bigint not null default 0, "accommodation_id" bigint null, "route_excluded" bigint not null default 0, "tour_stage_key" text null, "stay_minutes" bigint null);
|
||||
create index "idx_day_assignments_day_id" on "day_assignments" ("day_id");
|
||||
create index "idx_day_assignments_place_id" on "day_assignments" ("place_id");
|
||||
create index "idx_day_assignments_accommodation_id" on "day_assignments" ("accommodation_id");
|
||||
create index "idx_day_assignments_tour_stage" on "day_assignments" ("place_id", "tour_stage_key") where tour_stage_key IS NOT NULL;
|
||||
create table "tour_station_visits" ("assignment_id" bigint not null, "station_key" text not null, "status" text not null, "updated_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), primary key ("assignment_id", "station_key"));
|
||||
alter table "tour_station_visits" add constraint "tour_station_visits_assignment_id_station_key_unique" unique ("assignment_id", "station_key");
|
||||
alter table "tour_station_visits" add constraint "tour_station_visits_status_check" check ("status" in ('visited', 'skipped'));
|
||||
create table "tour_activities" ("id" bigserial primary key, "place_id" bigint not null, "track_place_id" bigint not null, "assignment_id" bigint null, "assigned_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "assigned_by" bigint null);
|
||||
create index "idx_tour_activities_place" on "tour_activities" ("place_id");
|
||||
create index "idx_tour_activities_assigned_by" on "tour_activities" ("assigned_by");
|
||||
create unique index "idx_tour_activities_assignment" on "tour_activities" ("assignment_id") where assignment_id IS NOT NULL;
|
||||
alter table "tour_activities" add constraint "tour_activities_track_place_id_unique" unique ("track_place_id");
|
||||
create table "roadtrip_day_boundaries" ("trip_id" bigint not null, "day_number" bigint not null, "from_assignment_id" bigint not null, "to_assignment_id" bigint null, "fraction" double precision not null, primary key ("trip_id", "day_number"));
|
||||
create index "idx_roadtrip_day_boundaries_from_assignment_id" on "roadtrip_day_boundaries" ("from_assignment_id");
|
||||
create index "idx_roadtrip_day_boundaries_to_assignment_id" on "roadtrip_day_boundaries" ("to_assignment_id");
|
||||
alter table "roadtrip_day_boundaries" add constraint "roadtrip_day_boundaries_trip_id_day_number_unique" unique ("trip_id", "day_number");
|
||||
alter table "roadtrip_day_boundaries" add constraint "roadtrip_day_boundaries_fraction_check" check (fraction BETWEEN 0 AND 1);
|
||||
alter table "roadtrip_day_boundaries" add constraint "roadtrip_day_boundaries_day_number_check" check (day_number >= 1);
|
||||
create table "reservations" ("id" bigserial primary key, "trip_id" bigint not null, "day_id" bigint null, "end_day_id" bigint null, "place_id" bigint null, "assignment_id" bigint null, "title" text not null, "accommodation_id" text null, "reservation_time" text null, "reservation_end_time" text null, "location" text null, "confirmation_number" text null, "notes" text null, "status" text null default 'pending', "type" text null default 'other', "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "metadata" text null, "day_plan_position" double precision null default NULL, "needs_review" bigint not null default 0, "external_source" text null, "external_id" text null, "external_owner_user_id" bigint null, "external_synced_at" text null, "sync_enabled" bigint null default 1, "external_hash" text null, "url" text null, "ingest_state" text not null default 'live');
|
||||
create index "idx_reservations_trip_id" on "reservations" ("trip_id");
|
||||
create index "idx_reservations_day_id" on "reservations" ("day_id");
|
||||
create index "idx_reservations_end_day_id" on "reservations" ("end_day_id");
|
||||
create index "idx_reservations_place_id" on "reservations" ("place_id");
|
||||
create index "idx_reservations_assignment_id" on "reservations" ("assignment_id");
|
||||
alter table "reservations" add constraint "idx_reservations_external" unique ("external_source", "external_id", "trip_id");
|
||||
create table "trip_files" ("id" bigserial primary key, "trip_id" bigint not null, "place_id" bigint null, "reservation_id" bigint null, "filename" text not null, "original_name" text not null, "file_size" bigint null, "mime_type" text null, "description" text null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "note_id" bigint null, "starred" bigint null default 0, "deleted_at" text null, "message_id" bigint null, "uploaded_by" bigint null);
|
||||
create index "idx_trip_files_trip_id" on "trip_files" ("trip_id");
|
||||
create index "idx_trip_files_place_id" on "trip_files" ("place_id");
|
||||
create index "idx_trip_files_reservation_id" on "trip_files" ("reservation_id");
|
||||
create index "idx_trip_files_note_id" on "trip_files" ("note_id");
|
||||
create index "idx_trip_files_message_id" on "trip_files" ("message_id");
|
||||
create index "idx_trip_files_uploaded_by" on "trip_files" ("uploaded_by");
|
||||
create table "document_sync_items" ("id" bigserial primary key, "link_id" bigint not null, "trip_id" bigint not null, "file_id" bigint null, "trek_doc_uid" text not null, "remote_id" text null, "remote_name" text null, "remote_version" text null, "remote_size" bigint null, "remote_modified_at" text null, "content_sha256" text null, "pushed_sha256" text null, "state" text not null default 'pending', "error_code" text null, "attempts" bigint not null default 0, "next_attempt_at" text null, "remote_missing_at" text null, "first_seen_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "last_seen_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "synced_at" text null, "remote_trashed_at" text null);
|
||||
create index "idx_document_sync_items_file_id" on "document_sync_items" ("file_id");
|
||||
create index "idx_document_sync_items_due" on "document_sync_items" ("link_id", "next_attempt_at");
|
||||
create index "idx_document_sync_items_hash" on "document_sync_items" ("link_id", "content_sha256");
|
||||
create index "idx_document_sync_items_trip_state" on "document_sync_items" ("trip_id", "state");
|
||||
alter table "document_sync_items" add constraint "idx_document_sync_items_uid" unique ("link_id", "trek_doc_uid");
|
||||
create unique index "idx_document_sync_items_file" on "document_sync_items" ("link_id", "file_id") where file_id IS NOT NULL;
|
||||
create unique index "idx_document_sync_items_remote" on "document_sync_items" ("link_id", "remote_id") where remote_id IS NOT NULL;
|
||||
create table "reservation_travelers" ("id" bigserial primary key, "reservation_id" bigint not null, "user_id" bigint not null);
|
||||
create index "idx_reservation_travelers_res" on "reservation_travelers" ("reservation_id");
|
||||
create index "idx_reservation_travelers_user" on "reservation_travelers" ("user_id");
|
||||
alter table "reservation_travelers" add constraint "reservation_travelers_reservation_id_user_id_unique" unique ("reservation_id", "user_id");
|
||||
create table "reservation_endpoints" ("id" bigserial primary key, "reservation_id" bigint not null, "role" text not null, "sequence" bigint not null default 0, "name" text not null, "code" text null, "lat" double precision not null, "lng" double precision not null, "timezone" text null, "local_time" text null, "local_date" text null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
|
||||
create index "idx_reservation_endpoints_reservation_id" on "reservation_endpoints" ("reservation_id");
|
||||
create table "reservation_day_positions" ("reservation_id" bigint not null, "day_id" bigint not null, "position" double precision not null, primary key ("reservation_id", "day_id"));
|
||||
create index "idx_reservation_day_positions_day_id" on "reservation_day_positions" ("day_id");
|
||||
alter table "reservation_day_positions" add constraint "reservation_day_positions_reservation_id_day_id_unique" unique ("reservation_id", "day_id");
|
||||
create table "day_accommodations" ("id" bigserial primary key, "trip_id" bigint not null, "place_id" bigint null, "start_day_id" bigint not null, "end_day_id" bigint not null, "check_in" text null, "check_in_end" text null, "check_out" text null, "confirmation" text null, "notes" text null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
|
||||
create index "idx_day_accommodations_trip_id" on "day_accommodations" ("trip_id");
|
||||
create index "idx_day_accommodations_place_id" on "day_accommodations" ("place_id");
|
||||
create index "idx_day_accommodations_start_day_id" on "day_accommodations" ("start_day_id");
|
||||
create index "idx_day_accommodations_end_day_id" on "day_accommodations" ("end_day_id");
|
||||
create table "collection_places" ("id" bigserial primary key, "collection_id" bigint not null, "owner_id" bigint not null, "name" text not null, "description" text null, "lat" double precision null, "lng" double precision null, "address" text null, "category_id" bigint null, "price" double precision null, "currency" text null, "notes" text null, "image_url" text null, "google_place_id" text null, "google_ftid" text null, "osm_id" text null, "website" text null, "phone" text null, "status" text not null default 'idea', "source_trip_id" bigint null, "source_place_id" bigint null, "links" text null, "sort_order" bigint null default 0, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "updated_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "saved_by" bigint null);
|
||||
create index "idx_collection_places_collection" on "collection_places" ("collection_id");
|
||||
create index "idx_collection_places_owner_id" on "collection_places" ("owner_id");
|
||||
create index "idx_collection_places_category_id" on "collection_places" ("category_id");
|
||||
create index "idx_collection_places_saved_by" on "collection_places" ("saved_by");
|
||||
create table "collection_place_ratings" ("id" bigserial primary key, "collection_place_id" bigint not null, "user_id" bigint not null, "rating" bigint not null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
|
||||
create index "idx_collection_place_ratings_place" on "collection_place_ratings" ("collection_place_id");
|
||||
create index "idx_collection_place_ratings_user_id" on "collection_place_ratings" ("user_id");
|
||||
alter table "collection_place_ratings" add constraint "collection_place_ratings_collection_place_id_user_id_unique" unique ("collection_place_id", "user_id");
|
||||
create table "collection_place_tags" ("collection_place_id" bigint not null, "tag_id" bigint not null, primary key ("collection_place_id", "tag_id"));
|
||||
create table "collection_place_labels" ("collection_place_id" bigint not null, "label_id" bigint not null, primary key ("collection_place_id", "label_id"));
|
||||
create table "budget_settlements" ("id" bigserial primary key, "trip_id" bigint not null, "from_user_id" bigint not null, "to_user_id" bigint not null, "amount" double precision not null default 0, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "created_by_user_id" bigint null, "currency" text null, "exchange_rate" double precision not null default 1, "settled_at" text null, "note" text null);
|
||||
create index "idx_budget_settlements_trip" on "budget_settlements" ("trip_id");
|
||||
create index "idx_budget_settlements_from_user_id" on "budget_settlements" ("from_user_id");
|
||||
create index "idx_budget_settlements_to_user_id" on "budget_settlements" ("to_user_id");
|
||||
create index "idx_budget_settlements_created_by_user_id" on "budget_settlements" ("created_by_user_id");
|
||||
create table "budget_items" ("id" bigserial primary key, "trip_id" bigint not null, "category" text not null default 'Other', "name" text not null, "total_price" double precision not null default 0, "persons" bigint null default NULL, "days" bigint null default NULL, "note" text null, "sort_order" bigint null default 0, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "paid_by_user_id" bigint null, "expense_date" text null default NULL, "reservation_id" bigint null default NULL, "currency" text null, "exchange_rate" double precision not null default 1, "ticket_json" text null, "place_id" bigint null default NULL);
|
||||
create index "idx_budget_items_trip_id" on "budget_items" ("trip_id");
|
||||
create index "idx_budget_items_paid_by_user_id" on "budget_items" ("paid_by_user_id");
|
||||
create index "idx_budget_items_reservation_id" on "budget_items" ("reservation_id");
|
||||
create index "idx_budget_items_place_id" on "budget_items" ("place_id");
|
||||
create table "file_links" ("id" bigserial primary key, "file_id" bigint not null, "reservation_id" bigint null, "assignment_id" bigint null, "place_id" bigint null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "budget_item_id" bigint null);
|
||||
create index "idx_file_links_reservation_id" on "file_links" ("reservation_id");
|
||||
create index "idx_file_links_assignment_id" on "file_links" ("assignment_id");
|
||||
create index "idx_file_links_place_id" on "file_links" ("place_id");
|
||||
create index "idx_file_links_budget_item_id" on "file_links" ("budget_item_id");
|
||||
alter table "file_links" add constraint "idx_file_links_file_budget" unique ("file_id", "budget_item_id");
|
||||
alter table "file_links" add constraint "file_links_file_id_place_id_unique" unique ("file_id", "place_id");
|
||||
alter table "file_links" add constraint "file_links_file_id_assignment_id_unique" unique ("file_id", "assignment_id");
|
||||
alter table "file_links" add constraint "file_links_file_id_reservation_id_unique" unique ("file_id", "reservation_id");
|
||||
create table "budget_item_payers" ("id" bigserial primary key, "budget_item_id" bigint not null, "user_id" bigint not null, "amount" double precision not null default 0);
|
||||
create index "idx_budget_item_payers_item" on "budget_item_payers" ("budget_item_id");
|
||||
create index "idx_budget_item_payers_user_id" on "budget_item_payers" ("user_id");
|
||||
alter table "budget_item_payers" add constraint "budget_item_payers_budget_item_id_user_id_unique" unique ("budget_item_id", "user_id");
|
||||
create table "budget_item_members" ("id" bigserial primary key, "budget_item_id" bigint not null, "user_id" bigint not null, "paid" bigint not null default 0, "amount" double precision null);
|
||||
create index "idx_budget_item_members_item" on "budget_item_members" ("budget_item_id");
|
||||
create index "idx_budget_item_members_user" on "budget_item_members" ("user_id");
|
||||
alter table "budget_item_members" add constraint "budget_item_members_budget_item_id_user_id_unique" unique ("budget_item_id", "user_id");
|
||||
create table "bucket_list" ("id" bigserial primary key, "user_id" bigint not null, "name" text not null, "lat" double precision null, "lng" double precision null, "country_code" text null, "notes" text null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "target_date" text null default NULL, "visited_at" text null, "visited_source" text null, "region_code" text null);
|
||||
create index "idx_bucket_list_user_id" on "bucket_list" ("user_id");
|
||||
create table "dawarich_visit_suggestions" ("id" bigserial primary key, "user_id" bigint not null, "source_visit_id" text not null, "trip_id" bigint null, "name" text not null, "lat" double precision null, "lng" double precision null, "started_at" text not null, "ended_at" text not null, "duration_minutes" bigint not null default 0, "local_date" text not null, "source_status" text not null default 'suggested', "confidence" double precision null, "confidence_band" text null, "country_code" text null, "state" text not null default 'new', "target" text null, "accepted_place_id" bigint null, "accepted_journal_entry_id" bigint null, "accepted_bucket_list_item_id" bigint null, "matched_bucket_list_item_id" bigint null, "source_hash" text not null, "accepted_hash" text null, "source_missing_at" text null, "first_seen_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "last_seen_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
|
||||
create index "idx_dawarich_suggestions_trip" on "dawarich_visit_suggestions" ("trip_id");
|
||||
create index "idx_dawarich_visit_suggestions_accepted_place_id" on "dawarich_visit_suggestions" ("accepted_place_id");
|
||||
create index "idx_dawarich_visit_suggestions_accepted_bucket_list_item_id" on "dawarich_visit_suggestions" ("accepted_bucket_list_item_id");
|
||||
create index "idx_dawarich_visit_suggestions_matched_bucket_list_item_id" on "dawarich_visit_suggestions" ("matched_bucket_list_item_id");
|
||||
create index "idx_dawarich_suggestions_user_state" on "dawarich_visit_suggestions" ("user_id", "state");
|
||||
alter table "dawarich_visit_suggestions" add constraint "dawarich_visit_suggestions_user_id_source_visit_id_unique" unique ("user_id", "source_visit_id");
|
||||
create table "audit_log" ("id" bigserial primary key, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "user_id" bigint null, "action" text not null, "resource" text null, "details" text null, "ip" text null);
|
||||
create index "idx_audit_log_created" on "audit_log" ("created_at");
|
||||
create index "idx_audit_log_user_id" on "audit_log" ("user_id");
|
||||
create table "assistant_usage" ("user_id" bigint not null, "day" text not null, "paid_by" text not null, "turns" bigint not null default 0, "input_tokens" bigint not null default 0, "output_tokens" bigint not null default 0, primary key ("user_id", "day", "paid_by"));
|
||||
alter table "assistant_usage" add constraint "assistant_usage_user_id_day_paid_by_unique" unique ("user_id", "day", "paid_by");
|
||||
create table "assistant_threads" ("id" bigserial primary key, "user_id" bigint not null, "trip_id" bigint null, "journey_id" bigint null, "title" text not null, "created_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "last_message_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
|
||||
create index "idx_assistant_threads_trip" on "assistant_threads" ("trip_id");
|
||||
create index "idx_assistant_threads_journey" on "assistant_threads" ("journey_id");
|
||||
create index "idx_assistant_threads_user_trip" on "assistant_threads" ("user_id", "trip_id", "last_message_at");
|
||||
create index "idx_assistant_threads_user_journey" on "assistant_threads" ("user_id", "journey_id", "last_message_at");
|
||||
create table "assistant_messages" ("id" bigserial primary key, "thread_id" bigint not null, "role" text not null, "parts" text not null, "provider_state" text null, "status" text not null default 'complete', "model" text null, "created_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
|
||||
create index "idx_assistant_messages_thread" on "assistant_messages" ("thread_id", "id");
|
||||
create table "assistant_tool_calls" ("id" text not null, "thread_id" bigint not null, "message_id" bigint not null, "provider_call_id" text not null, "tool_name" text not null, "args" text not null, "preview" text not null, "state" text not null default 'approval_requested', "result" text null, "undo_until" text null, "created_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "decided_at" text null, primary key ("id"));
|
||||
create index "idx_assistant_tool_calls_message" on "assistant_tool_calls" ("message_id");
|
||||
alter table "assistant_tool_calls" add constraint "assistant_tool_calls_thread_id_provider_call_id_unique" unique ("thread_id", "provider_call_id");
|
||||
create table "assistant_attachments" ("id" text not null, "thread_id" bigint not null, "user_id" bigint not null, "trip_id" bigint not null, "name" text not null, "mime" text not null, "size" bigint not null, "sha256" text not null, "storage_key" text not null, "text" text null, "text_status" text not null, "shared_at" text null, "file_id" bigint null, "created_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), primary key ("id"));
|
||||
create index "idx_assistant_attachments_user" on "assistant_attachments" ("user_id");
|
||||
create index "idx_assistant_attachments_trip" on "assistant_attachments" ("trip_id");
|
||||
create index "idx_assistant_attachments_file" on "assistant_attachments" ("file_id");
|
||||
create index "idx_assistant_attachments_created" on "assistant_attachments" ("created_at");
|
||||
create index "idx_assistant_attachments_thread" on "assistant_attachments" ("thread_id", "created_at");
|
||||
create table "assignment_participants" ("id" bigserial primary key, "assignment_id" bigint not null, "user_id" bigint not null);
|
||||
create index "idx_assignment_participants_assignment" on "assignment_participants" ("assignment_id");
|
||||
create index "idx_assignment_participants_user_id" on "assignment_participants" ("user_id");
|
||||
alter table "assignment_participants" add constraint "assignment_participants_assignment_id_user_id_unique" unique ("assignment_id", "user_id");
|
||||
create table "ai_connections" ("id" bigserial primary key, "scope" text not null, "user_id" bigint null, "kind" text not null, "model" text not null, "base_url" text null, "secrets" text null, "secrets_version" bigint not null default 0, "hint" text null, "account" text null, "status" text not null default 'ok', "created_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "updated_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
|
||||
create unique index "idx_ai_connections_instance" on "ai_connections" ("scope") where user_id IS NULL;
|
||||
create unique index "idx_ai_connections_user" on "ai_connections" ("user_id") where user_id IS NOT NULL;
|
||||
create table "user_sessions" ("id" text not null, "user_id" bigint not null, "created_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "last_seen_at" text not null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "expires_at" text not null, "revoked_at" text null, "user_agent" text null, primary key ("id"));
|
||||
create index "idx_user_sessions_user" on "user_sessions" ("user_id");
|
||||
create index "idx_user_sessions_expires" on "user_sessions" ("expires_at");
|
||||
create table "vacay_plans" ("id" bigserial primary key, "owner_id" bigint not null, "block_weekends" bigint null default 1, "holidays_enabled" bigint null default 0, "holidays_region" text null default '', "school_holidays_enabled" bigint null default 0, "company_holidays_enabled" bigint null default 1, "carry_over_enabled" bigint null default 1, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "weekend_days" text null default '0,6', "week_start" bigint not null default 1);
|
||||
alter table "vacay_plans" add constraint "vacay_plans_owner_id_unique" unique ("owner_id");
|
||||
create table "vacay_plan_members" ("id" bigserial primary key, "plan_id" bigint not null, "user_id" bigint not null, "status" text null default 'pending', "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
|
||||
create index "idx_vacay_plan_members_user_id" on "vacay_plan_members" ("user_id");
|
||||
alter table "vacay_plan_members" add constraint "vacay_plan_members_plan_id_user_id_unique" unique ("plan_id", "user_id");
|
||||
create table "vacay_holiday_calendars" ("id" bigserial primary key, "plan_id" bigint not null, "type" text not null default 'public_holiday', "region" text not null, "label" text null, "color" text not null default '#fecaca', "sort_order" bigint not null default 0);
|
||||
create index "idx_vacay_holiday_calendars_plan_id" on "vacay_holiday_calendars" ("plan_id");
|
||||
create table "vacay_entries" ("id" bigserial primary key, "plan_id" bigint not null, "user_id" bigint not null, "date" text not null, "note" text null default '', "fraction" double precision not null default 1, "kind" text not null default 'vacation');
|
||||
create index "idx_vacay_entries_plan_id" on "vacay_entries" ("plan_id");
|
||||
alter table "vacay_entries" add constraint "vacay_entries_user_id_plan_id_date_unique" unique ("user_id", "plan_id", "date");
|
||||
create table "vacay_company_holidays" ("id" bigserial primary key, "plan_id" bigint not null, "date" text not null, "note" text null default '', "fraction" double precision not null default 1);
|
||||
alter table "vacay_company_holidays" add constraint "vacay_company_holidays_plan_id_date_unique" unique ("plan_id", "date");
|
||||
create table "vacay_shares" ("id" bigserial primary key, "owner_id" bigint not null, "user_id" bigint not null, "hidden" bigint not null default 0, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
|
||||
create index "idx_vacay_shares_user" on "vacay_shares" ("user_id");
|
||||
alter table "vacay_shares" add constraint "vacay_shares_owner_id_user_id_unique" unique ("owner_id", "user_id");
|
||||
create table "vacay_user_colors" ("id" bigserial primary key, "user_id" bigint not null, "plan_id" bigint not null, "color" text null default '#6366f1');
|
||||
create index "idx_vacay_user_colors_plan_id" on "vacay_user_colors" ("plan_id");
|
||||
alter table "vacay_user_colors" add constraint "vacay_user_colors_user_id_plan_id_unique" unique ("user_id", "plan_id");
|
||||
create table "vacay_user_settings" ("user_id" bigint null, "year_type" text not null default 'calendar', "year_start_month" bigint not null default 1, "year_start_day" bigint not null default 1, "hire_date" text null, primary key ("user_id"));
|
||||
create table "vacay_user_years" ("id" bigserial primary key, "user_id" bigint not null, "plan_id" bigint not null, "year" bigint not null, "vacation_days" bigint null default 30, "carried_over" bigint null default 0);
|
||||
create index "idx_vacay_user_years_plan_id" on "vacay_user_years" ("plan_id");
|
||||
alter table "vacay_user_years" add constraint "vacay_user_years_user_id_plan_id_year_unique" unique ("user_id", "plan_id", "year");
|
||||
create table "vacay_years" ("id" bigserial primary key, "plan_id" bigint not null, "year" bigint not null);
|
||||
alter table "vacay_years" add constraint "vacay_years_plan_id_year_unique" unique ("plan_id", "year");
|
||||
create table "visited_countries" ("id" bigserial primary key, "user_id" bigint not null, "country_code" text not null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "source" text not null default 'manual');
|
||||
alter table "visited_countries" add constraint "visited_countries_user_id_country_code_unique" unique ("user_id", "country_code");
|
||||
create table "visited_regions" ("id" bigserial primary key, "user_id" bigint not null, "region_code" text not null, "region_name" text not null, "country_code" text not null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
|
||||
create index "idx_visited_regions_country" on "visited_regions" ("country_code");
|
||||
alter table "visited_regions" add constraint "visited_regions_user_id_region_code_unique" unique ("user_id", "region_code");
|
||||
create table "wanderer_connections" ("user_id" bigint null, "url" text not null, "token" text null, "allow_insecure_tls" bigint not null default 0, "last_checked_at" text null, "last_check_ok" bigint null, "last_check_error" text null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "updated_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "watch_enabled" bigint not null default 0, "watch_last_run_at" text null, "watch_failures" bigint not null default 0, "watch_paused_until" text null, primary key ("user_id"));
|
||||
create table "webauthn_challenges" ("id" bigserial primary key, "challenge" text not null, "user_id" bigint null, "type" text not null, "expires_at" bigint not null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'));
|
||||
create index "idx_webauthn_challenges_user_id" on "webauthn_challenges" ("user_id");
|
||||
create index "idx_webauthn_challenges_expires" on "webauthn_challenges" ("expires_at");
|
||||
alter table "webauthn_challenges" add constraint "webauthn_challenges_challenge_unique" unique ("challenge");
|
||||
create table "webauthn_credentials" ("id" bigserial primary key, "user_id" bigint not null, "credential_id" text not null, "public_key" bytea not null, "counter" bigint not null default 0, "transports" text null, "device_type" text null, "backed_up" bigint not null default 0, "name" text null, "aaguid" text null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE 'UTC'), 'YYYY-MM-DD HH24:MI:SS'), "last_used_at" text null);
|
||||
create index "idx_webauthn_credentials_user" on "webauthn_credentials" ("user_id");
|
||||
alter table "webauthn_credentials" add constraint "webauthn_credentials_credential_id_unique" unique ("credential_id");
|
||||
alter table "document_provider_fields" add constraint "document_provider_fields_provider_id_foreign" foreign key ("provider_id") references "document_providers" ("id") on delete cascade;
|
||||
alter table "paddle_features" add constraint "paddle_features_region_id_foreign" foreign key ("region_id") references "paddle_regions" ("id") on delete cascade;
|
||||
alter table "paddle_water_graphs" add constraint "paddle_water_graphs_region_id_foreign" foreign key ("region_id") references "paddle_regions" ("id") on update cascade on delete cascade;
|
||||
alter table "photo_provider_fields" add constraint "photo_provider_fields_provider_id_foreign" foreign key ("provider_id") references "photo_providers" ("id") on delete cascade;
|
||||
alter table "school_holiday_regions" add constraint "school_holiday_regions_country_foreign" foreign key ("country") references "school_holiday_countries" ("code");
|
||||
alter table "school_holiday_periods" add constraint "school_holiday_periods_region_id_foreign" foreign key ("region_id") references "school_holiday_regions" ("id") on delete cascade;
|
||||
alter table "user_notice_dismissals" add constraint "user_notice_dismissals_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
|
||||
alter table "trips" add constraint "trips_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
|
||||
alter table "roadtrip_preferences" add constraint "roadtrip_preferences_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
|
||||
alter table "days" add constraint "days_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
|
||||
alter table "roadtrip_vias" add constraint "roadtrip_vias_day_id_foreign" foreign key ("day_id") references "days" ("id") on delete cascade;
|
||||
alter table "day_notes" add constraint "day_notes_day_id_foreign" foreign key ("day_id") references "days" ("id") on delete cascade;
|
||||
alter table "day_notes" add constraint "day_notes_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
|
||||
alter table "budget_category_order" add constraint "budget_category_order_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
|
||||
alter table "trip_members" add constraint "trip_members_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
|
||||
alter table "trip_members" add constraint "trip_members_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
|
||||
alter table "trip_members" add constraint "trip_members_invited_by_foreign" foreign key ("invited_by") references "users" ("id") on delete no action;
|
||||
alter table "trip_member_removals" add constraint "trip_member_removals_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
|
||||
alter table "trip_member_removals" add constraint "trip_member_removals_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
|
||||
alter table "trip_invite_tokens" add constraint "trip_invite_tokens_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
|
||||
alter table "trip_invite_tokens" add constraint "trip_invite_tokens_created_by_foreign" foreign key ("created_by") references "users" ("id") on delete set null;
|
||||
alter table "trip_album_links" add constraint "trip_album_links_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
|
||||
alter table "trip_album_links" add constraint "trip_album_links_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
|
||||
alter table "trek_photos" add constraint "trek_photos_owner_id_foreign" foreign key ("owner_id") references "users" ("id") on delete set null;
|
||||
alter table "trip_photos" add constraint "trip_photos_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
|
||||
alter table "trip_photos" add constraint "trip_photos_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
|
||||
alter table "trip_photos" add constraint "trip_photos_photo_id_foreign" foreign key ("photo_id") references "trek_photos" ("id") on delete cascade;
|
||||
alter table "trip_photos" add constraint "trip_photos_album_link_id_foreign" foreign key ("album_link_id") references "trip_album_links" ("id") on delete set null;
|
||||
alter table "trek_photo_signals" add constraint "trek_photo_signals_photo_id_foreign" foreign key ("photo_id") references "trek_photos" ("id") on delete cascade;
|
||||
alter table "tour_drafts" add constraint "tour_drafts_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
|
||||
alter table "tour_drafts" add constraint "tour_drafts_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
|
||||
alter table "todo_items" add constraint "todo_items_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
|
||||
alter table "todo_items" add constraint "todo_items_assigned_user_id_foreign" foreign key ("assigned_user_id") references "users" ("id") on delete set null;
|
||||
alter table "todo_category_assignees" add constraint "todo_category_assignees_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
|
||||
alter table "todo_category_assignees" add constraint "todo_category_assignees_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
|
||||
alter table "tags" add constraint "tags_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
|
||||
alter table "tags" add constraint "tags_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
|
||||
alter table "share_tokens" add constraint "share_tokens_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
|
||||
alter table "share_tokens" add constraint "share_tokens_created_by_foreign" foreign key ("created_by") references "users" ("id");
|
||||
alter table "settings" add constraint "settings_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
|
||||
alter table "push_subscriptions" add constraint "push_subscriptions_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
|
||||
alter table "password_reset_tokens" add constraint "password_reset_tokens_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
|
||||
alter table "packing_templates" add constraint "packing_templates_created_by_foreign" foreign key ("created_by") references "users" ("id") on delete cascade;
|
||||
alter table "packing_template_categories" add constraint "packing_template_categories_template_id_foreign" foreign key ("template_id") references "packing_templates" ("id") on delete cascade;
|
||||
alter table "packing_template_items" add constraint "packing_template_items_category_id_foreign" foreign key ("category_id") references "packing_template_categories" ("id") on delete cascade;
|
||||
alter table "packing_category_assignees" add constraint "packing_category_assignees_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
|
||||
alter table "packing_category_assignees" add constraint "packing_category_assignees_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
|
||||
alter table "packing_bags" add constraint "packing_bags_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
|
||||
alter table "packing_bags" add constraint "packing_bags_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete set null;
|
||||
alter table "packing_items" add constraint "packing_items_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
|
||||
alter table "packing_items" add constraint "packing_items_bag_id_foreign" foreign key ("bag_id") references "packing_bags" ("id") on delete set null;
|
||||
alter table "packing_items" add constraint "packing_items_owner_id_foreign" foreign key ("owner_id") references "users" ("id") on delete set null;
|
||||
alter table "packing_item_contributors" add constraint "packing_item_contributors_item_id_foreign" foreign key ("item_id") references "packing_items" ("id") on update cascade on delete cascade;
|
||||
alter table "packing_item_contributors" add constraint "packing_item_contributors_user_id_foreign" foreign key ("user_id") references "users" ("id") on update cascade on delete cascade;
|
||||
alter table "packing_item_recipients" add constraint "packing_item_recipients_item_id_foreign" foreign key ("item_id") references "packing_items" ("id") on update cascade on delete cascade;
|
||||
alter table "packing_item_recipients" add constraint "packing_item_recipients_user_id_foreign" foreign key ("user_id") references "users" ("id") on update cascade on delete cascade;
|
||||
alter table "packing_bag_members" add constraint "packing_bag_members_bag_id_foreign" foreign key ("bag_id") references "packing_bags" ("id") on update cascade on delete cascade;
|
||||
alter table "packing_bag_members" add constraint "packing_bag_members_user_id_foreign" foreign key ("user_id") references "users" ("id") on update cascade on delete cascade;
|
||||
alter table "oauth_clients" add constraint "oauth_clients_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
|
||||
alter table "oauth_tokens" add constraint "oauth_tokens_client_id_foreign" foreign key ("client_id") references "oauth_clients" ("client_id") on delete cascade;
|
||||
alter table "oauth_tokens" add constraint "oauth_tokens_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
|
||||
alter table "oauth_tokens" add constraint "oauth_tokens_parent_token_id_foreign" foreign key ("parent_token_id") references "oauth_tokens" ("id") on delete no action;
|
||||
alter table "oauth_consents" add constraint "oauth_consents_client_id_foreign" foreign key ("client_id") references "oauth_clients" ("client_id") on delete cascade;
|
||||
alter table "oauth_consents" add constraint "oauth_consents_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
|
||||
alter table "notifications" add constraint "notifications_sender_id_foreign" foreign key ("sender_id") references "users" ("id") on delete set null;
|
||||
alter table "notifications" add constraint "notifications_recipient_id_foreign" foreign key ("recipient_id") references "users" ("id") on delete cascade;
|
||||
alter table "notification_channel_preferences" add constraint "notification_channel_preferences_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
|
||||
alter table "mcp_tokens" add constraint "mcp_tokens_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
|
||||
alter table "mail_ingest_prefs" add constraint "mail_ingest_prefs_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
|
||||
alter table "mail_ingest_addresses" add constraint "mail_ingest_addresses_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
|
||||
alter table "mail_ingest_addresses" add constraint "mail_ingest_addresses_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
|
||||
alter table "mail_ingest_messages" add constraint "mail_ingest_messages_address_id_foreign" foreign key ("address_id") references "mail_ingest_addresses" ("id") on delete set null;
|
||||
alter table "mail_ingest_messages" add constraint "mail_ingest_messages_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
|
||||
alter table "mail_ingest_messages" add constraint "mail_ingest_messages_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete set null;
|
||||
alter table "mail_ingest_candidates" add constraint "mail_ingest_candidates_message_id_foreign" foreign key ("message_id") references "mail_ingest_messages" ("id") on delete cascade;
|
||||
alter table "mail_ingest_candidates" add constraint "mail_ingest_candidates_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
|
||||
alter table "mail_ingest_candidates" add constraint "mail_ingest_candidates_suggested_trip_id_foreign" foreign key ("suggested_trip_id") references "trips" ("id") on delete set null;
|
||||
alter table "mail_ingest_candidates" add constraint "mail_ingest_candidates_resolved_trip_id_foreign" foreign key ("resolved_trip_id") references "trips" ("id") on delete set null;
|
||||
alter table "journeys" add constraint "journeys_user_id_foreign" foreign key ("user_id") references "users" ("id");
|
||||
alter table "trip_journal_links" add constraint "trip_journal_links_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
|
||||
alter table "trip_journal_links" add constraint "trip_journal_links_journey_id_foreign" foreign key ("journey_id") references "journeys" ("id") on delete cascade;
|
||||
alter table "trip_journal_links" add constraint "trip_journal_links_linked_by_foreign" foreign key ("linked_by") references "users" ("id") on delete set null;
|
||||
alter table "trip_journal_link_members" add constraint "trip_journal_link_members_link_id_foreign" foreign key ("link_id") references "trip_journal_links" ("id") on update cascade on delete cascade;
|
||||
alter table "trip_journal_link_members" add constraint "trip_journal_link_members_user_id_foreign" foreign key ("user_id") references "users" ("id") on update cascade on delete cascade;
|
||||
alter table "journey_trips" add constraint "journey_trips_journey_id_foreign" foreign key ("journey_id") references "journeys" ("id") on update cascade on delete cascade;
|
||||
alter table "journey_trips" add constraint "journey_trips_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on update cascade on delete cascade;
|
||||
alter table "journey_share_tokens" add constraint "journey_share_tokens_journey_id_foreign" foreign key ("journey_id") references "journeys" ("id") on delete cascade;
|
||||
alter table "journey_share_tokens" add constraint "journey_share_tokens_created_by_foreign" foreign key ("created_by") references "users" ("id");
|
||||
alter table "journey_photos" add constraint "journey_photos_journey_id_foreign" foreign key ("journey_id") references "journeys" ("id") on delete cascade;
|
||||
alter table "journey_photos" add constraint "journey_photos_photo_id_foreign" foreign key ("photo_id") references "trek_photos" ("id") on delete cascade;
|
||||
alter table "journey_book_revisions" add constraint "journey_book_revisions_journey_id_foreign" foreign key ("journey_id") references "journeys" ("id") on delete cascade;
|
||||
alter table "journey_recording_prep" add constraint "journey_recording_prep_journey_id_foreign" foreign key ("journey_id") references "journeys" ("id") on delete cascade;
|
||||
alter table "journey_recording_prep" add constraint "journey_recording_prep_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
|
||||
alter table "journey_recorded_days" add constraint "journey_recorded_days_journey_id_foreign" foreign key ("journey_id") references "journeys" ("id") on delete cascade;
|
||||
alter table "journey_recorded_days" add constraint "journey_recorded_days_imported_by_foreign" foreign key ("imported_by") references "users" ("id") on delete set null;
|
||||
alter table "journey_contributors" add constraint "journey_contributors_journey_id_foreign" foreign key ("journey_id") references "journeys" ("id") on update cascade on delete cascade;
|
||||
alter table "journey_contributors" add constraint "journey_contributors_user_id_foreign" foreign key ("user_id") references "users" ("id") on update cascade on delete no action;
|
||||
alter table "journey_books" add constraint "journey_books_journey_id_foreign" foreign key ("journey_id") references "journeys" ("id") on delete cascade;
|
||||
alter table "journey_books" add constraint "journey_books_updated_by_foreign" foreign key ("updated_by") references "users" ("id") on delete set null;
|
||||
alter table "journey_books" add constraint "journey_books_created_by_foreign" foreign key ("created_by") references "users" ("id") on delete set null;
|
||||
alter table "invite_tokens" add constraint "invite_tokens_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete set null;
|
||||
alter table "invite_tokens" add constraint "invite_tokens_created_by_foreign" foreign key ("created_by") references "users" ("id") on delete cascade;
|
||||
alter table "idempotency_keys" add constraint "idempotency_keys_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
|
||||
alter table "hidden_regions" add constraint "hidden_regions_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
|
||||
alter table "hidden_countries" add constraint "hidden_countries_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
|
||||
alter table "document_connections" add constraint "document_connections_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
|
||||
alter table "document_connections" add constraint "document_connections_provider_id_foreign" foreign key ("provider_id") references "document_providers" ("id") on delete cascade;
|
||||
alter table "document_connections" add constraint "document_connections_owner_user_id_foreign" foreign key ("owner_user_id") references "users" ("id") on delete cascade;
|
||||
alter table "trip_document_links" add constraint "trip_document_links_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
|
||||
alter table "trip_document_links" add constraint "trip_document_links_connection_id_foreign" foreign key ("connection_id") references "document_connections" ("id") on delete cascade;
|
||||
alter table "trip_document_links" add constraint "trip_document_links_created_by_foreign" foreign key ("created_by") references "users" ("id") on delete set null;
|
||||
alter table "dawarich_connections" add constraint "dawarich_connections_user_id_foreign" foreign key ("user_id") references "users" ("id") on update cascade on delete cascade;
|
||||
alter table "collections" add constraint "collections_owner_id_foreign" foreign key ("owner_id") references "users" ("id") on delete cascade;
|
||||
alter table "collection_tours" add constraint "collection_tours_collection_id_foreign" foreign key ("collection_id") references "collections" ("id") on delete cascade;
|
||||
alter table "collection_tours" add constraint "collection_tours_tour_type_foreign" foreign key ("tour_type") references "tour_types" ("key");
|
||||
alter table "collection_tours" add constraint "collection_tours_saved_by_foreign" foreign key ("saved_by") references "users" ("id") on delete set null;
|
||||
alter table "collection_labels" add constraint "collection_labels_collection_id_foreign" foreign key ("collection_id") references "collections" ("id") on delete cascade;
|
||||
alter table "collection_members" add constraint "collection_members_collection_id_foreign" foreign key ("collection_id") references "collections" ("id") on delete cascade;
|
||||
alter table "collection_members" add constraint "collection_members_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
|
||||
alter table "collab_polls" add constraint "collab_polls_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
|
||||
alter table "collab_polls" add constraint "collab_polls_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
|
||||
alter table "collab_poll_votes" add constraint "collab_poll_votes_poll_id_foreign" foreign key ("poll_id") references "collab_polls" ("id") on delete cascade;
|
||||
alter table "collab_poll_votes" add constraint "collab_poll_votes_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
|
||||
alter table "collab_notes" add constraint "collab_notes_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
|
||||
alter table "collab_notes" add constraint "collab_notes_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
|
||||
alter table "collab_messages" add constraint "collab_messages_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
|
||||
alter table "collab_messages" add constraint "collab_messages_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
|
||||
alter table "collab_messages" add constraint "collab_messages_reply_to_foreign" foreign key ("reply_to") references "collab_messages" ("id") on delete set null;
|
||||
alter table "collab_message_reactions" add constraint "collab_message_reactions_message_id_foreign" foreign key ("message_id") references "collab_messages" ("id") on delete cascade;
|
||||
alter table "collab_message_reactions" add constraint "collab_message_reactions_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
|
||||
alter table "collab_links" add constraint "collab_links_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
|
||||
alter table "collab_links" add constraint "collab_links_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
|
||||
alter table "categories" add constraint "categories_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete set null;
|
||||
alter table "places" add constraint "places_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
|
||||
alter table "places" add constraint "places_category_id_foreign" foreign key ("category_id") references "categories" ("id") on delete set null;
|
||||
alter table "tours" add constraint "tours_place_id_foreign" foreign key ("place_id") references "places" ("id") on update cascade on delete cascade;
|
||||
alter table "tours" add constraint "tours_derived_from_place_id_foreign" foreign key ("derived_from_place_id") references "places" ("id") on delete set null;
|
||||
alter table "tours" add constraint "tours_tour_type_foreign" foreign key ("tour_type") references "tour_types" ("key");
|
||||
alter table "tour_waypoints" add constraint "tour_waypoints_place_id_foreign" foreign key ("place_id") references "tours" ("place_id") on delete cascade;
|
||||
alter table "tour_waypoints" add constraint "tour_waypoints_linked_place_id_foreign" foreign key ("linked_place_id") references "places" ("id") on delete set null;
|
||||
alter table "tour_sources" add constraint "tour_sources_place_id_foreign" foreign key ("place_id") references "tours" ("place_id") on update cascade on delete cascade;
|
||||
alter table "tour_sources" add constraint "tour_sources_imported_by_foreign" foreign key ("imported_by") references "users" ("id") on delete set null;
|
||||
alter table "tour_source_hints" add constraint "tour_source_hints_place_id_foreign" foreign key ("place_id") references "tour_sources" ("place_id") on update cascade on delete cascade;
|
||||
alter table "tour_source_hints" add constraint "tour_source_hints_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
|
||||
alter table "tour_packing_links" add constraint "tour_packing_links_place_id_foreign" foreign key ("place_id") references "tours" ("place_id") on update cascade on delete cascade;
|
||||
alter table "tour_packing_links" add constraint "tour_packing_links_linked_by_foreign" foreign key ("linked_by") references "users" ("id") on delete set null;
|
||||
alter table "tour_obstacle_reviews" add constraint "tour_obstacle_reviews_place_id_foreign" foreign key ("place_id") references "tours" ("place_id") on delete cascade;
|
||||
alter table "tour_change_steps" add constraint "tour_change_steps_place_id_foreign" foreign key ("place_id") references "tours" ("place_id") on delete cascade;
|
||||
alter table "tour_activity_exclusions" add constraint "tour_activity_exclusions_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
|
||||
alter table "tour_activity_exclusions" add constraint "tour_activity_exclusions_place_id_foreign" foreign key ("place_id") references "tours" ("place_id") on delete cascade;
|
||||
alter table "roadtrip_day_tracks" add constraint "roadtrip_day_tracks_day_id_foreign" foreign key ("day_id") references "days" ("id") on update cascade on delete cascade;
|
||||
alter table "roadtrip_day_tracks" add constraint "roadtrip_day_tracks_place_id_foreign" foreign key ("place_id") references "places" ("id") on delete cascade;
|
||||
alter table "place_regions" add constraint "place_regions_place_id_foreign" foreign key ("place_id") references "places" ("id") on update cascade on delete cascade;
|
||||
alter table "place_ratings" add constraint "place_ratings_place_id_foreign" foreign key ("place_id") references "places" ("id") on delete cascade;
|
||||
alter table "place_ratings" add constraint "place_ratings_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
|
||||
alter table "place_field_origin" add constraint "place_field_origin_place_id_foreign" foreign key ("place_id") references "places" ("id") on delete cascade;
|
||||
alter table "place_contrib_outbox" add constraint "place_contrib_outbox_place_id_foreign" foreign key ("place_id") references "places" ("id") on delete cascade;
|
||||
alter table "place_tags" add constraint "place_tags_place_id_foreign" foreign key ("place_id") references "places" ("id") on update cascade on delete cascade;
|
||||
alter table "place_tags" add constraint "place_tags_tag_id_foreign" foreign key ("tag_id") references "tags" ("id") on update cascade on delete cascade;
|
||||
alter table "photos" add constraint "photos_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
|
||||
alter table "photos" add constraint "photos_day_id_foreign" foreign key ("day_id") references "days" ("id") on delete set null;
|
||||
alter table "photos" add constraint "photos_place_id_foreign" foreign key ("place_id") references "places" ("id") on delete set null;
|
||||
alter table "journey_entries" add constraint "journey_entries_journey_id_foreign" foreign key ("journey_id") references "journeys" ("id") on delete cascade;
|
||||
alter table "journey_entries" add constraint "journey_entries_source_trip_id_foreign" foreign key ("source_trip_id") references "trips" ("id") on delete set null;
|
||||
alter table "journey_entries" add constraint "journey_entries_source_place_id_foreign" foreign key ("source_place_id") references "places" ("id") on delete set null;
|
||||
alter table "journey_entries" add constraint "journey_entries_author_id_foreign" foreign key ("author_id") references "users" ("id");
|
||||
alter table "journey_entry_stays" add constraint "journey_entry_stays_journey_id_foreign" foreign key ("journey_id") references "journeys" ("id") on delete cascade;
|
||||
alter table "journey_entry_stays" add constraint "journey_entry_stays_entry_id_foreign" foreign key ("entry_id") references "journey_entries" ("id") on delete cascade;
|
||||
alter table "journey_entry_stays" add constraint "journey_entry_stays_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete set null;
|
||||
alter table "journey_entry_photos" add constraint "journey_entry_photos_entry_id_foreign" foreign key ("entry_id") references "journey_entries" ("id") on update cascade on delete cascade;
|
||||
alter table "journey_entry_photos" add constraint "journey_entry_photos_journey_photo_id_foreign" foreign key ("journey_photo_id") references "journey_photos" ("id") on update cascade on delete cascade;
|
||||
alter table "day_assignments" add constraint "day_assignments_day_id_foreign" foreign key ("day_id") references "days" ("id") on delete cascade;
|
||||
alter table "day_assignments" add constraint "day_assignments_place_id_foreign" foreign key ("place_id") references "places" ("id") on delete cascade;
|
||||
alter table "tour_station_visits" add constraint "tour_station_visits_assignment_id_foreign" foreign key ("assignment_id") references "day_assignments" ("id") on delete cascade;
|
||||
alter table "tour_activities" add constraint "tour_activities_place_id_foreign" foreign key ("place_id") references "tours" ("place_id") on delete cascade;
|
||||
alter table "tour_activities" add constraint "tour_activities_track_place_id_foreign" foreign key ("track_place_id") references "tours" ("place_id") on delete cascade;
|
||||
alter table "tour_activities" add constraint "tour_activities_assignment_id_foreign" foreign key ("assignment_id") references "day_assignments" ("id") on delete set null;
|
||||
alter table "tour_activities" add constraint "tour_activities_assigned_by_foreign" foreign key ("assigned_by") references "users" ("id") on delete set null;
|
||||
alter table "roadtrip_day_boundaries" add constraint "roadtrip_day_boundaries_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
|
||||
alter table "roadtrip_day_boundaries" add constraint "roadtrip_day_boundaries_from_assignment_id_foreign" foreign key ("from_assignment_id") references "day_assignments" ("id") on delete cascade;
|
||||
alter table "roadtrip_day_boundaries" add constraint "roadtrip_day_boundaries_to_assignment_id_foreign" foreign key ("to_assignment_id") references "day_assignments" ("id") on delete cascade;
|
||||
alter table "reservations" add constraint "reservations_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
|
||||
alter table "reservations" add constraint "reservations_day_id_foreign" foreign key ("day_id") references "days" ("id") on delete set null;
|
||||
alter table "reservations" add constraint "reservations_end_day_id_foreign" foreign key ("end_day_id") references "days" ("id") on delete set null;
|
||||
alter table "reservations" add constraint "reservations_place_id_foreign" foreign key ("place_id") references "places" ("id") on delete set null;
|
||||
alter table "reservations" add constraint "reservations_assignment_id_foreign" foreign key ("assignment_id") references "day_assignments" ("id") on delete set null;
|
||||
alter table "trip_files" add constraint "trip_files_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
|
||||
alter table "trip_files" add constraint "trip_files_place_id_foreign" foreign key ("place_id") references "places" ("id") on delete set null;
|
||||
alter table "trip_files" add constraint "trip_files_reservation_id_foreign" foreign key ("reservation_id") references "reservations" ("id") on delete set null;
|
||||
alter table "trip_files" add constraint "trip_files_note_id_foreign" foreign key ("note_id") references "collab_notes" ("id") on delete set null;
|
||||
alter table "trip_files" add constraint "trip_files_message_id_foreign" foreign key ("message_id") references "collab_messages" ("id") on delete cascade;
|
||||
alter table "trip_files" add constraint "trip_files_uploaded_by_foreign" foreign key ("uploaded_by") references "users" ("id") on delete set null;
|
||||
alter table "document_sync_items" add constraint "document_sync_items_link_id_foreign" foreign key ("link_id") references "trip_document_links" ("id") on delete cascade;
|
||||
alter table "document_sync_items" add constraint "document_sync_items_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
|
||||
alter table "document_sync_items" add constraint "document_sync_items_file_id_foreign" foreign key ("file_id") references "trip_files" ("id") on delete set null;
|
||||
alter table "reservation_travelers" add constraint "reservation_travelers_reservation_id_foreign" foreign key ("reservation_id") references "reservations" ("id") on delete cascade;
|
||||
alter table "reservation_travelers" add constraint "reservation_travelers_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
|
||||
alter table "reservation_endpoints" add constraint "reservation_endpoints_reservation_id_foreign" foreign key ("reservation_id") references "reservations" ("id") on delete cascade;
|
||||
alter table "reservation_day_positions" add constraint "reservation_day_positions_reservation_id_foreign" foreign key ("reservation_id") references "reservations" ("id") on update cascade on delete cascade;
|
||||
alter table "reservation_day_positions" add constraint "reservation_day_positions_day_id_foreign" foreign key ("day_id") references "days" ("id") on update cascade on delete cascade;
|
||||
alter table "day_accommodations" add constraint "day_accommodations_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
|
||||
alter table "day_accommodations" add constraint "day_accommodations_place_id_foreign" foreign key ("place_id") references "places" ("id") on delete set null;
|
||||
alter table "day_accommodations" add constraint "day_accommodations_start_day_id_foreign" foreign key ("start_day_id") references "days" ("id") on delete cascade;
|
||||
alter table "day_accommodations" add constraint "day_accommodations_end_day_id_foreign" foreign key ("end_day_id") references "days" ("id") on delete cascade;
|
||||
alter table "collection_places" add constraint "collection_places_collection_id_foreign" foreign key ("collection_id") references "collections" ("id") on delete cascade;
|
||||
alter table "collection_places" add constraint "collection_places_owner_id_foreign" foreign key ("owner_id") references "users" ("id") on delete cascade;
|
||||
alter table "collection_places" add constraint "collection_places_category_id_foreign" foreign key ("category_id") references "categories" ("id") on delete set null;
|
||||
alter table "collection_places" add constraint "collection_places_saved_by_foreign" foreign key ("saved_by") references "users" ("id") on delete set null;
|
||||
alter table "collection_place_ratings" add constraint "collection_place_ratings_collection_place_id_foreign" foreign key ("collection_place_id") references "collection_places" ("id") on delete cascade;
|
||||
alter table "collection_place_ratings" add constraint "collection_place_ratings_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
|
||||
alter table "collection_place_tags" add constraint "collection_place_tags_collection_place_id_foreign" foreign key ("collection_place_id") references "collection_places" ("id") on update cascade on delete cascade;
|
||||
alter table "collection_place_tags" add constraint "collection_place_tags_tag_id_foreign" foreign key ("tag_id") references "tags" ("id") on update cascade on delete cascade;
|
||||
alter table "collection_place_labels" add constraint "collection_place_labels_collection_place_id_foreign" foreign key ("collection_place_id") references "collection_places" ("id") on update cascade on delete cascade;
|
||||
alter table "collection_place_labels" add constraint "collection_place_labels_label_id_foreign" foreign key ("label_id") references "collection_labels" ("id") on update cascade on delete cascade;
|
||||
alter table "budget_settlements" add constraint "budget_settlements_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
|
||||
alter table "budget_settlements" add constraint "budget_settlements_from_user_id_foreign" foreign key ("from_user_id") references "users" ("id") on delete cascade;
|
||||
alter table "budget_settlements" add constraint "budget_settlements_to_user_id_foreign" foreign key ("to_user_id") references "users" ("id") on delete cascade;
|
||||
alter table "budget_settlements" add constraint "budget_settlements_created_by_user_id_foreign" foreign key ("created_by_user_id") references "users" ("id") on delete no action;
|
||||
alter table "budget_items" add constraint "budget_items_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
|
||||
alter table "budget_items" add constraint "budget_items_paid_by_user_id_foreign" foreign key ("paid_by_user_id") references "users" ("id") on delete no action;
|
||||
alter table "budget_items" add constraint "budget_items_reservation_id_foreign" foreign key ("reservation_id") references "reservations" ("id") on delete set null;
|
||||
alter table "budget_items" add constraint "budget_items_place_id_foreign" foreign key ("place_id") references "places" ("id") on delete set null;
|
||||
alter table "file_links" add constraint "file_links_file_id_foreign" foreign key ("file_id") references "trip_files" ("id") on delete cascade;
|
||||
alter table "file_links" add constraint "file_links_reservation_id_foreign" foreign key ("reservation_id") references "reservations" ("id") on delete cascade;
|
||||
alter table "file_links" add constraint "file_links_assignment_id_foreign" foreign key ("assignment_id") references "day_assignments" ("id") on delete cascade;
|
||||
alter table "file_links" add constraint "file_links_place_id_foreign" foreign key ("place_id") references "places" ("id") on delete cascade;
|
||||
alter table "file_links" add constraint "file_links_budget_item_id_foreign" foreign key ("budget_item_id") references "budget_items" ("id") on delete set null;
|
||||
alter table "budget_item_payers" add constraint "budget_item_payers_budget_item_id_foreign" foreign key ("budget_item_id") references "budget_items" ("id") on delete cascade;
|
||||
alter table "budget_item_payers" add constraint "budget_item_payers_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
|
||||
alter table "budget_item_members" add constraint "budget_item_members_budget_item_id_foreign" foreign key ("budget_item_id") references "budget_items" ("id") on delete cascade;
|
||||
alter table "budget_item_members" add constraint "budget_item_members_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
|
||||
alter table "bucket_list" add constraint "bucket_list_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
|
||||
alter table "dawarich_visit_suggestions" add constraint "dawarich_visit_suggestions_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
|
||||
alter table "dawarich_visit_suggestions" add constraint "dawarich_visit_suggestions_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete set null;
|
||||
alter table "dawarich_visit_suggestions" add constraint "dawarich_visit_suggestions_accepted_place_id_foreign" foreign key ("accepted_place_id") references "places" ("id") on delete set null;
|
||||
alter table "dawarich_visit_suggestions" add constraint "dawarich_visit_suggestions_accepted_bucket_list_item_id_foreign" foreign key ("accepted_bucket_list_item_id") references "bucket_list" ("id") on delete set null;
|
||||
alter table "dawarich_visit_suggestions" add constraint "dawarich_visit_suggestions_matched_bucket_list_item_id_foreign" foreign key ("matched_bucket_list_item_id") references "bucket_list" ("id") on delete set null;
|
||||
alter table "audit_log" add constraint "audit_log_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete set null;
|
||||
alter table "assistant_usage" add constraint "assistant_usage_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
|
||||
alter table "assistant_threads" add constraint "assistant_threads_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
|
||||
alter table "assistant_threads" add constraint "assistant_threads_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
|
||||
alter table "assistant_threads" add constraint "assistant_threads_journey_id_foreign" foreign key ("journey_id") references "journeys" ("id") on delete cascade;
|
||||
alter table "assistant_messages" add constraint "assistant_messages_thread_id_foreign" foreign key ("thread_id") references "assistant_threads" ("id") on delete cascade;
|
||||
alter table "assistant_tool_calls" add constraint "assistant_tool_calls_thread_id_foreign" foreign key ("thread_id") references "assistant_threads" ("id") on delete cascade;
|
||||
alter table "assistant_tool_calls" add constraint "assistant_tool_calls_message_id_foreign" foreign key ("message_id") references "assistant_messages" ("id") on delete cascade;
|
||||
alter table "assistant_attachments" add constraint "assistant_attachments_thread_id_foreign" foreign key ("thread_id") references "assistant_threads" ("id") on delete cascade;
|
||||
alter table "assistant_attachments" add constraint "assistant_attachments_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
|
||||
alter table "assistant_attachments" add constraint "assistant_attachments_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade;
|
||||
alter table "assistant_attachments" add constraint "assistant_attachments_file_id_foreign" foreign key ("file_id") references "trip_files" ("id") on delete set null;
|
||||
alter table "assignment_participants" add constraint "assignment_participants_assignment_id_foreign" foreign key ("assignment_id") references "day_assignments" ("id") on delete cascade;
|
||||
alter table "assignment_participants" add constraint "assignment_participants_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
|
||||
alter table "ai_connections" add constraint "ai_connections_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
|
||||
alter table "user_sessions" add constraint "user_sessions_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
|
||||
alter table "vacay_plans" add constraint "vacay_plans_owner_id_foreign" foreign key ("owner_id") references "users" ("id") on delete cascade;
|
||||
alter table "vacay_plan_members" add constraint "vacay_plan_members_plan_id_foreign" foreign key ("plan_id") references "vacay_plans" ("id") on delete cascade;
|
||||
alter table "vacay_plan_members" add constraint "vacay_plan_members_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
|
||||
alter table "vacay_holiday_calendars" add constraint "vacay_holiday_calendars_plan_id_foreign" foreign key ("plan_id") references "vacay_plans" ("id") on delete cascade;
|
||||
alter table "vacay_entries" add constraint "vacay_entries_plan_id_foreign" foreign key ("plan_id") references "vacay_plans" ("id") on delete cascade;
|
||||
alter table "vacay_entries" add constraint "vacay_entries_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
|
||||
alter table "vacay_company_holidays" add constraint "vacay_company_holidays_plan_id_foreign" foreign key ("plan_id") references "vacay_plans" ("id") on delete cascade;
|
||||
alter table "vacay_shares" add constraint "vacay_shares_owner_id_foreign" foreign key ("owner_id") references "users" ("id") on delete cascade;
|
||||
alter table "vacay_shares" add constraint "vacay_shares_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
|
||||
alter table "vacay_user_colors" add constraint "vacay_user_colors_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
|
||||
alter table "vacay_user_colors" add constraint "vacay_user_colors_plan_id_foreign" foreign key ("plan_id") references "vacay_plans" ("id") on delete cascade;
|
||||
alter table "vacay_user_settings" add constraint "vacay_user_settings_user_id_foreign" foreign key ("user_id") references "users" ("id") on update cascade on delete cascade;
|
||||
alter table "vacay_user_years" add constraint "vacay_user_years_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
|
||||
alter table "vacay_user_years" add constraint "vacay_user_years_plan_id_foreign" foreign key ("plan_id") references "vacay_plans" ("id") on delete cascade;
|
||||
alter table "vacay_years" add constraint "vacay_years_plan_id_foreign" foreign key ("plan_id") references "vacay_plans" ("id") on delete cascade;
|
||||
alter table "visited_countries" add constraint "visited_countries_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
|
||||
alter table "visited_regions" add constraint "visited_regions_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
|
||||
alter table "wanderer_connections" add constraint "wanderer_connections_user_id_foreign" foreign key ("user_id") references "users" ("id") on update cascade on delete cascade;
|
||||
alter table "webauthn_challenges" add constraint "webauthn_challenges_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
|
||||
alter table "webauthn_credentials" add constraint "webauthn_credentials_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade;
|
||||
insert into "app_settings" ("key", "value") values ('app_version', '3.0.15'), ('places_photos_enabled', 'true'), ('places_autocomplete_enabled', 'true'), ('places_details_enabled', 'true');
|
||||
insert into "addons" ("id", "name", "description", "type", "icon", "enabled", "config", "sort_order") values ('collab', 'Collab', 'Notes, polls, and live chat for trip collaboration', 'trip', 'Users', '1', '{}', '6'), ('memories', 'Photos', NULL, 'trip', 'Image', '0', '{}', '7'), ('mcp', 'MCP', 'Model Context Protocol for AI assistant integration', 'integration', 'Terminal', '0', '{}', '12'), ('naver_list_import', 'Naver List Import', 'Import places from shared Naver Maps lists', 'integration', 'Link2', '1', '{}', '13'), ('journey', 'Journey', 'Trip tracking & travel journal — check-ins, photos, daily stories', 'global', 'Compass', '1', '{}', '35'), ('airtrail', 'AirTrail', 'Sync flights from your self-hosted AirTrail instance', 'integration', 'Plane', '0', '{}', '14'), ('collections', 'Collections', 'Personal place library — save places across trips into named lists, copy into any trip, share with others', 'global', 'Bookmark', '1', '{}', '16');
|
||||
insert into "photo_providers" ("id", "name", "description", "icon", "enabled", "sort_order") values ('synologyphotos', 'Synology Photos', 'Synology Photos integration with separate account settings', 'Image', '0', '1');
|
||||
insert into "photo_provider_fields" ("id", "provider_id", "field_key", "label", "input_type", "placeholder", "hint", "required", "secret", "settings_key", "payload_key", "sort_order") values ('1', 'synologyphotos', 'synology_url', 'providerUrl', 'url', 'https://synology.example.com', 'providerUrlHintSynology', '1', '0', 'synology_url', 'synology_url', '0'), ('2', 'synologyphotos', 'synology_username', 'providerUsername', 'text', 'Username', NULL, '1', '0', 'synology_username', 'synology_username', '1'), ('3', 'synologyphotos', 'synology_password', 'providerPassword', 'password', 'Password', NULL, '1', '1', NULL, 'synology_password', '2'), ('4', 'synologyphotos', 'synology_otp', 'providerOTP', 'text', '123456', NULL, '0', '0', NULL, 'synology_otp', '3'), ('5', 'synologyphotos', 'synology_skip_ssl', 'skipSSLVerification', 'checkbox', NULL, NULL, '0', '0', 'synology_skip_ssl', 'synology_skip_ssl', '4');
|
||||
select setval(seq, greatest(max_id, 1)) from (select pg_get_serial_sequence('"photo_provider_fields"', 'id') as seq, max("id") as max_id from "photo_provider_fields") ids where seq is not null;
|
||||
insert into "document_providers" ("id", "name", "description", "icon", "enabled", "sort_order") values ('paperless', 'Paperless-ngx', 'Two-way document sync with a Paperless-ngx instance, scoped by tag', 'FileText', '0', '0'), ('papra', 'Papra', 'Two-way document sync with a Papra organisation, scoped by tag', 'FileText', '0', '1'), ('nextcloud', 'Nextcloud', 'Two-way document sync with a Nextcloud folder over WebDAV', 'Cloud', '0', '2'), ('opencloud', 'OpenCloud', 'Two-way document sync with an OpenCloud space over WebDAV', 'Cloud', '0', '3'), ('synologydrive', 'Synology Drive', 'Two-way document sync with a folder on a Synology NAS', 'HardDrive', '0', '4');
|
||||
insert into "document_provider_fields" ("id", "provider_id", "field_key", "label", "input_type", "placeholder", "hint", "required", "secret", "sort_order") values ('1', 'paperless', 'base_url', 'providerUrl', 'url', 'https://paperless.example.com', NULL, '1', '0', '0'), ('2', 'paperless', 'api_token', 'providerApiToken', 'password', 'API token', 'hintPaperlessToken', '1', '1', '1'), ('3', 'paperless', 'allow_insecure_tls', 'allowInsecureTls', 'checkbox', NULL, NULL, '0', '0', '2'), ('4', 'papra', 'base_url', 'providerUrl', 'url', 'https://papra.example.com', NULL, '1', '0', '0'), ('5', 'papra', 'api_key', 'providerApiKey', 'password', 'ppapi_…', 'hintPapraKey', '1', '1', '1'), ('6', 'papra', 'organization_id', 'providerOrganization', 'text', 'org_…', 'hintPapraOrg', '1', '0', '2'), ('7', 'papra', 'allow_insecure_tls', 'allowInsecureTls', 'checkbox', NULL, NULL, '0', '0', '3'), ('8', 'nextcloud', 'base_url', 'providerUrl', 'url', 'https://cloud.example.com', NULL, '1', '0', '0'), ('9', 'nextcloud', 'login_name', 'providerUsername', 'text', 'username', 'hintNextcloudLogin', '1', '0', '1'), ('10', 'nextcloud', 'app_password', 'providerAppPassword', 'password', 'app password', 'hintNextcloudAppPassword', '1', '1', '2'), ('11', 'nextcloud', 'base_path', 'providerBasePath', 'text', '/TREK', 'hintBasePath', '0', '0', '3'), ('12', 'nextcloud', 'allow_insecure_tls', 'allowInsecureTls', 'checkbox', NULL, NULL, '0', '0', '4'), ('13', 'opencloud', 'base_url', 'providerUrl', 'url', 'https://opencloud.example.com', NULL, '1', '0', '0'), ('14', 'opencloud', 'username', 'providerUsername', 'text', 'username', NULL, '1', '0', '1'), ('15', 'opencloud', 'app_token', 'providerAppToken', 'password', 'app token', 'hintOpenCloudToken', '1', '1', '2'), ('16', 'opencloud', 'allow_insecure_tls', 'allowInsecureTls', 'checkbox', NULL, NULL, '0', '0', '3'), ('17', 'synologydrive', 'base_url', 'providerUrl', 'url', 'https://nas.example.com:5001', 'hintSynologyUrl', '1', '0', '0'), ('18', 'synologydrive', 'username', 'providerUsername', 'text', 'username', 'hintSynologyUser', '1', '0', '1'), ('19', 'synologydrive', 'password', 'providerPassword', 'password', 'password', NULL, '1', '1', '2'), ('20', 'synologydrive', 'otp_code', 'providerOTP', 'text', '123456', 'hintSynologyOtp', '0', '1', '3'), ('21', 'synologydrive', 'base_path', 'providerBasePath', 'text', '/trek', 'hintBasePath', '0', '0', '4'), ('22', 'synologydrive', 'allow_insecure_tls', 'allowInsecureTls', 'checkbox', NULL, NULL, '0', '0', '5');
|
||||
select setval(seq, greatest(max_id, 1)) from (select pg_get_serial_sequence('"document_provider_fields"', 'id') as seq, max("id") as max_id from "document_provider_fields") ids where seq is not null;
|
||||
insert into "tour_types" ("key", "label_key", "icon", "color", "routing_profile", "is_sport", "enabled", "sort_order") values ('hike', 'tourTypes.hike', 'Mountain', '#16a34a', 'pedestrian', '1', '1', '0'), ('bike', 'tourTypes.bike', 'Bike', '#2563eb', 'bicycle', '1', '1', '1'), ('run', 'tourTypes.run', 'Footprints', '#dc2626', 'pedestrian', '1', '1', '2'), ('ski', 'tourTypes.ski', 'MountainSnow', '#0891b2', NULL, '1', '1', '3'), ('kayak', 'tourTypes.kayak', 'Sailboat', '#0d9488', NULL, '1', '1', '4'), ('walk', 'tourTypes.walk', 'Landmark', '#9333ea', 'pedestrian', '0', '1', '5'), ('food', 'tourTypes.food', 'UtensilsCrossed', '#ea580c', 'pedestrian', '0', '0', '6'), ('horse', 'tourTypes.horse', 'Horseshoe', '#a16207', NULL, '1', '1', '7');
|
||||
CREATE FUNCTION trg_release_stop_on_stay_delete() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
UPDATE day_assignments SET accommodation_id = NULL WHERE accommodation_id = OLD.id;
|
||||
RETURN OLD;
|
||||
END
|
||||
$$;
|
||||
CREATE TRIGGER trg_release_stop_on_stay_delete AFTER DELETE ON day_accommodations FOR EACH ROW EXECUTE FUNCTION trg_release_stop_on_stay_delete();
|
||||
CREATE FUNCTION trg_place_regions_follow_place() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
DELETE FROM place_regions WHERE place_id = NEW.id;
|
||||
RETURN NEW;
|
||||
END
|
||||
$$;
|
||||
CREATE TRIGGER trg_place_regions_follow_place AFTER UPDATE OF lat, lng, address ON places FOR EACH ROW WHEN (OLD.lat IS DISTINCT FROM NEW.lat OR OLD.lng IS DISTINCT FROM NEW.lng OR OLD.address IS DISTINCT FROM NEW.address) EXECUTE FUNCTION trg_place_regions_follow_place();
|
||||
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* trek/transactions-through-unit-of-work: every transaction under src/ goes
|
||||
* through `UnitOfWork.transactional` (or `writeTransaction`, which it wraps).
|
||||
*
|
||||
* On SQLite one connection writes one transaction at a time, so a check read
|
||||
* inside a transaction (a `MAX(...) + 1` position, a count under a cap, an
|
||||
* existence before an insert) still held at the write that followed. On
|
||||
* Postgres a pool runs transactions side by side, and only the engine's write
|
||||
* lock (`DatabaseEngine.serializeWrites`), which `UnitOfWork` takes first,
|
||||
* puts them one after the other again. A transaction opened any other way,
|
||||
* `em.transactional(...)`, a repository's `getEntityManager().transactional(...)`,
|
||||
* `em.begin()`, a connection's `transactional(...)` or Kysely's
|
||||
* `db.transaction()`, does not take that lock, and its check can be raced.
|
||||
*
|
||||
* The rule reads the receiver's type: `transactional` is reported on anything
|
||||
* but a `UnitOfWork` (an untyped receiver included, so it fails closed), and
|
||||
* `begin`/`transaction` on an EntityManager, a connection or a Kysely
|
||||
* instance (better-sqlite3's own `transaction()`, the plugin's private SQLite
|
||||
* file, and unrelated `begin()` methods stay out of it). The engine and the
|
||||
* boot-time schema files open their own transactions on purpose and are left
|
||||
* out in eslint.config.mjs, each with its reason.
|
||||
*/
|
||||
const OPENERS = new Set(['transactional', 'begin', 'transaction']);
|
||||
const DATABASE_HANDLE = /EntityManager|Connection|^Kysely\b/;
|
||||
|
||||
export default {
|
||||
meta: {
|
||||
type: 'problem',
|
||||
docs: {
|
||||
description:
|
||||
'Open transactions only through UnitOfWork.transactional, which takes the engine write lock on Postgres',
|
||||
},
|
||||
schema: [],
|
||||
messages: {
|
||||
direct:
|
||||
'`.{{method}}(...)` opens a transaction without the engine write lock. Use `UnitOfWork.transactional` ' +
|
||||
'(src/nest/database/unit-of-work.ts; outside the Nest container `writeTransaction` from ' +
|
||||
'src/db/engine/write-transaction.ts), and read every check its write relies on (a count, an existence, ' +
|
||||
"a MAX + 1) inside it. A repository method runs inside its caller's unit of work instead of opening one. " +
|
||||
'See server/CLAUDE.md, "Transactions are not optional".',
|
||||
},
|
||||
},
|
||||
create(context) {
|
||||
const services = context.sourceCode.parserServices;
|
||||
if (!services?.program) return {};
|
||||
const checker = services.program.getTypeChecker();
|
||||
|
||||
return {
|
||||
CallExpression(node) {
|
||||
const callee = node.callee;
|
||||
if (callee.type !== 'MemberExpression' || callee.computed || callee.property.type !== 'Identifier') return;
|
||||
const method = callee.property.name;
|
||||
if (!OPENERS.has(method)) return;
|
||||
const type = services.getTypeAtLocation(callee.object);
|
||||
const symbol = (type.getSymbol() ?? type.aliasSymbol)?.getName();
|
||||
if (symbol === 'UnitOfWork') return;
|
||||
if (method !== 'transactional' && !DATABASE_HANDLE.test(checker.typeToString(type))) return;
|
||||
context.report({ node, messageId: 'direct', data: { method } });
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
+128
-34
@@ -1,13 +1,18 @@
|
||||
import noPromiseAsValue from './eslint-rules/no-promise-as-value.mjs';
|
||||
import transactionsThroughUnitOfWork from './eslint-rules/transactions-through-unit-of-work.mjs';
|
||||
import js from '@eslint/js';
|
||||
|
||||
import gitignore from 'eslint-config-flat-gitignore';
|
||||
import eslintConfigPrettier from 'eslint-config-prettier';
|
||||
import tseslint from 'typescript-eslint';
|
||||
|
||||
import noPromiseAsValue from './eslint-rules/no-promise-as-value.mjs';
|
||||
|
||||
// Local rules live in eslint-rules/ and are exposed under the `trek/` prefix.
|
||||
const trek = { rules: { 'no-promise-as-value': noPromiseAsValue } };
|
||||
const trek = {
|
||||
rules: {
|
||||
'no-promise-as-value': noPromiseAsValue,
|
||||
'transactions-through-unit-of-work': transactionsThroughUnitOfWork,
|
||||
},
|
||||
};
|
||||
|
||||
// The calls the outbound-timeout selectors below look at: the platform fetch and
|
||||
// the SSRF-guarded wrappers whose init is passed on to it. safeFetchLlm is not
|
||||
@@ -33,17 +38,11 @@ const ENV_SELECTORS = [
|
||||
},
|
||||
];
|
||||
|
||||
const RAW_SQL_MESSAGE =
|
||||
'Dialect SQL goes through src/db/dialect/sql-functions.ts, which dispatches on the live MikroORM platform. Code outside src/db/dialect/ and src/db/engine/ must not spell raw SQL: build the statement in a repository with the query builder, where the Postgres probe runs it.';
|
||||
const RAW_SQL_SELECTORS = [
|
||||
{
|
||||
selector: "CallExpression[callee.name='raw']",
|
||||
message:
|
||||
'Dialect SQL goes through src/db/dialect/sql-functions.ts, which dispatches on the live MikroORM platform. A repository must not spell raw SQL.',
|
||||
},
|
||||
{
|
||||
selector: "TaggedTemplateExpression[tag.name='sql']",
|
||||
message:
|
||||
'Dialect SQL goes through src/db/dialect/sql-functions.ts, which dispatches on the live MikroORM platform. A repository must not spell raw SQL.',
|
||||
},
|
||||
{ selector: "CallExpression[callee.name='raw']", message: RAW_SQL_MESSAGE },
|
||||
{ selector: "TaggedTemplateExpression[tag.name='sql']", message: RAW_SQL_MESSAGE },
|
||||
];
|
||||
|
||||
// Kysely fills InsertResult.insertId from SQLite's last_insert_rowid. Postgres
|
||||
@@ -104,7 +103,37 @@ const FETCH_SELECTORS = [
|
||||
// the method name keeps `qb.execute('run')` (a result mode, not SQL) legal.
|
||||
const SQL_TEXT = String.raw`/^\s*(SELECT|INSERT|UPDATE|DELETE|REPLACE|WITH|PRAGMA|VACUUM|CREATE|DROP|ALTER|ATTACH|BEGIN|COMMIT)\b/i`;
|
||||
const SQL_STRING_MESSAGE =
|
||||
'A SQL string handed to the connection is raw SQL too. Build it with the query builder (this.kysely(), em.createQueryBuilder) and route dialect functions through src/db/dialect/sql-functions.ts.';
|
||||
'A SQL string handed to the connection is raw SQL too. Build it in a repository with the query builder (this.kysely(), the entity methods), where the Postgres probe runs it, and route dialect functions through src/db/dialect/sql-functions.ts.';
|
||||
|
||||
// Where raw SQL may be spelled under src/: the dialect layer and the engines
|
||||
// (each engine's own SQL), the migrations (frozen, and held by lint:dialect),
|
||||
// and the boot-time lifecycle files named here, which run before or beside the
|
||||
// migrator on the raw connection. tests/unit/eslint-rules/restricted-syntax-selectors.test.ts
|
||||
// pins how many SQL strings each named file holds, so the list can only shrink.
|
||||
// The repositories and seeders have blocks of their own below.
|
||||
const RAW_SQL_HOMES = ['src/db/dialect/**', 'src/db/engine/**', 'src/db/migrations/**'];
|
||||
const RAW_SQL_LIFECYCLE_FILES = [
|
||||
'src/db/email-case-index.ts',
|
||||
'src/db/legacy-baseline.ts',
|
||||
'src/db/migration-utils.ts',
|
||||
'src/db/pre-migrate-snapshot.ts',
|
||||
];
|
||||
|
||||
// The files the config-access guard leaves out (see the src/** block below).
|
||||
const ENV_EXEMPT_FILES = [
|
||||
// The config layer itself.
|
||||
'src/app-config/**',
|
||||
'src/nest/app-config/**',
|
||||
// Key-material resolution (file persistence + runtime rotation), not env config.
|
||||
'src/config.ts',
|
||||
// Scrubbed plugin child process — must not import app-config.
|
||||
'src/nest/plugins/runtime/plugin-host-entry.ts',
|
||||
// Child-env whitelist block: the env there is an IPC channel to the sandbox.
|
||||
'src/nest/plugins/supervisor/plugin-supervisor.ts',
|
||||
// Dynamic-key caps (process.env[name] with a computed name).
|
||||
'src/nest/plugins/host/daily-budget.ts',
|
||||
'src/nest/plugins/host/plugin-audit.ts',
|
||||
];
|
||||
|
||||
const STRING_SQL_SELECTORS = [
|
||||
{
|
||||
@@ -126,8 +155,15 @@ const STRING_SQL_SELECTORS = [
|
||||
const APP_SETTING_MESSAGE =
|
||||
"Read an app setting through readAppSetting()/resolveAppSetting() from src/nest/common/app-settings.registry.ts, not getValue('<key>'): the register types the key and owns its env override.";
|
||||
const APP_SETTING_SELECTORS = [
|
||||
{ selector: "CallExpression[callee.property.name='getValue'] > Literal.arguments:first-child", message: APP_SETTING_MESSAGE },
|
||||
{ selector: "CallExpression[callee.property.name='getValue'] > TemplateLiteral.arguments:first-child[expressions.length=0]", message: APP_SETTING_MESSAGE },
|
||||
{
|
||||
selector: "CallExpression[callee.property.name='getValue'] > Literal.arguments:first-child",
|
||||
message: APP_SETTING_MESSAGE,
|
||||
},
|
||||
{
|
||||
selector:
|
||||
"CallExpression[callee.property.name='getValue'] > TemplateLiteral.arguments:first-child[expressions.length=0]",
|
||||
message: APP_SETTING_MESSAGE,
|
||||
},
|
||||
];
|
||||
|
||||
// The demo-mode write block runs once, in the MCP registry (trekDemoToolGate in
|
||||
@@ -136,7 +172,7 @@ const APP_SETTING_SELECTORS = [
|
||||
const DEMO_GATE_MESSAGE =
|
||||
'MCP tools do not check demo mode themselves: the registry gate (trekDemoToolGate) refuses every tool not annotated read-only. Annotate the tool instead.';
|
||||
const MCP_DEMO_SELECTORS = [
|
||||
{ selector: "CallExpression[callee.property.name=/^isDemoUser(Id)?$/]", message: DEMO_GATE_MESSAGE },
|
||||
{ selector: 'CallExpression[callee.property.name=/^isDemoUser(Id)?$/]', message: DEMO_GATE_MESSAGE },
|
||||
{ selector: "CallExpression[callee.name='demoDenied']", message: DEMO_GATE_MESSAGE },
|
||||
];
|
||||
|
||||
@@ -259,32 +295,90 @@ export default tseslint.config(
|
||||
// (readEnv() / derive functions / registerAs tokens). Direct process.env
|
||||
// access is banned outside the documented exemptions below — see
|
||||
// src/app-config/README.md for the rationale behind each.
|
||||
//
|
||||
// The same block holds the raw-SQL wall for all of src/: SQL text outside a
|
||||
// repository reaches Postgres unchecked, since the probe only runs what the
|
||||
// repositories send.
|
||||
files: ['src/**/*.ts'],
|
||||
ignores: [
|
||||
// The config layer itself.
|
||||
'src/app-config/**',
|
||||
'src/nest/app-config/**',
|
||||
// Key-material resolution (file persistence + runtime rotation), not env config.
|
||||
'src/config.ts',
|
||||
// Scrubbed plugin child process — must not import app-config.
|
||||
'src/nest/plugins/runtime/plugin-host-entry.ts',
|
||||
// Child-env whitelist block: the env there is an IPC channel to the sandbox.
|
||||
'src/nest/plugins/supervisor/plugin-supervisor.ts',
|
||||
// Dynamic-key caps (process.env[name] with a computed name).
|
||||
'src/nest/plugins/host/daily-budget.ts',
|
||||
'src/nest/plugins/host/plugin-audit.ts',
|
||||
],
|
||||
ignores: ENV_EXEMPT_FILES,
|
||||
rules: {
|
||||
'no-restricted-syntax': [
|
||||
'error',
|
||||
...ENV_SELECTORS,
|
||||
...FETCH_SELECTORS,
|
||||
...APP_SETTING_SELECTORS,
|
||||
...RAW_SQL_SELECTORS,
|
||||
...STRING_SQL_SELECTORS,
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
// The homes of raw SQL (RAW_SQL_HOMES, RAW_SQL_LIFECYCLE_FILES): the block
|
||||
// above restated without the raw-SQL wall.
|
||||
files: [...RAW_SQL_HOMES, ...RAW_SQL_LIFECYCLE_FILES],
|
||||
ignores: ENV_EXEMPT_FILES,
|
||||
rules: {
|
||||
'no-restricted-syntax': ['error', ...ENV_SELECTORS, ...FETCH_SELECTORS, ...APP_SETTING_SELECTORS],
|
||||
},
|
||||
},
|
||||
{
|
||||
// Restates the config-access and app-setting guards above for *.mcp.ts
|
||||
// (a later block's options replace an earlier one's) and adds the
|
||||
// The files the config-access guard leaves out still hold no raw SQL.
|
||||
files: ENV_EXEMPT_FILES,
|
||||
rules: {
|
||||
'no-restricted-syntax': ['error', ...RAW_SQL_SELECTORS, ...STRING_SQL_SELECTORS],
|
||||
},
|
||||
},
|
||||
{
|
||||
// The two seeders that still write their rows as SQL text (see the
|
||||
// repository and seeder block below, which leaves them out): the block
|
||||
// above without the SQL string rule, raw() and the sql tag still refused.
|
||||
files: ['src/db/seeders/AdminSeeder.ts', 'src/db/seeders/CategorySeeder.ts'],
|
||||
rules: {
|
||||
'no-restricted-syntax': [
|
||||
'error',
|
||||
...ENV_SELECTORS,
|
||||
...FETCH_SELECTORS,
|
||||
...APP_SETTING_SELECTORS,
|
||||
...RAW_SQL_SELECTORS,
|
||||
...INSERT_ID_SELECTORS,
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
// Every transaction goes through UnitOfWork.transactional (or writeTransaction,
|
||||
// which it wraps), the only ones that take the engine's write lock: on
|
||||
// Postgres a transaction opened any other way runs beside the others, and a
|
||||
// check read inside it can be raced. See eslint-rules/transactions-through-unit-of-work.mjs.
|
||||
files: ['src/**/*.ts'],
|
||||
ignores: [
|
||||
// The engine: writeTransaction itself, the schema bootstrap, the parity
|
||||
// diff, the move from SQLite and the plugin data schemas, each on a
|
||||
// connection or database of its own.
|
||||
'src/db/engine/**',
|
||||
// Boot-time schema steps on the raw connection, before the server takes a request.
|
||||
'src/db/email-case-index.ts',
|
||||
'src/db/legacy-baseline.ts',
|
||||
],
|
||||
plugins: { trek },
|
||||
rules: {
|
||||
'trek/transactions-through-unit-of-work': 'error',
|
||||
},
|
||||
},
|
||||
{
|
||||
// Restates the config-access, app-setting and raw-SQL guards above for
|
||||
// *.mcp.ts (a later block's options replace an earlier one's) and adds the
|
||||
// demo-gate wall.
|
||||
files: ['src/**/*.mcp.ts'],
|
||||
rules: {
|
||||
'no-restricted-syntax': ['error', ...ENV_SELECTORS, ...FETCH_SELECTORS, ...APP_SETTING_SELECTORS, ...MCP_DEMO_SELECTORS],
|
||||
'no-restricted-syntax': [
|
||||
'error',
|
||||
...ENV_SELECTORS,
|
||||
...FETCH_SELECTORS,
|
||||
...APP_SETTING_SELECTORS,
|
||||
...RAW_SQL_SELECTORS,
|
||||
...STRING_SQL_SELECTORS,
|
||||
...MCP_DEMO_SELECTORS,
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
|
||||
+8
-1
@@ -11,6 +11,7 @@
|
||||
"build": "node scripts/build.mjs",
|
||||
"start:prod": "node --require tsconfig-paths/register dist/index.js",
|
||||
"reset-admin": "node reset-admin.js",
|
||||
"db:move-to-postgres": "node --import tsx src/move-to-postgres.ts",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"typecheck:tests": "tsc -p tsconfig.tests.json --noEmit",
|
||||
"typecheck:scripts": "tsc -p tsconfig.scripts.json --noEmit",
|
||||
@@ -21,6 +22,7 @@
|
||||
"lint:strict": "node scripts/strict-lint.mjs",
|
||||
"lint:boundaries": "node scripts/import-boundaries.mjs",
|
||||
"lint:dialect": "node scripts/dialect-lint.mjs",
|
||||
"lint:engine-dispatch": "node scripts/engine-dispatch-ratchet.mjs",
|
||||
"lint:tx": "node scripts/tx-writes.mjs",
|
||||
"lint:test-sql": "node scripts/test-sql-ratchet.mjs",
|
||||
"lint:test-mocks": "node scripts/test-mocks-ratchet.mjs",
|
||||
@@ -36,6 +38,9 @@
|
||||
"check:entities": "node --import tsx scripts/generate-entities.ts --check",
|
||||
"gen:db-types": "node --import tsx scripts/generate-db-types.ts",
|
||||
"check:db-types": "node --import tsx scripts/generate-db-types.ts --check",
|
||||
"gen:pg-baseline": "node --import tsx scripts/generate-pg-baseline.ts",
|
||||
"check:pg-baseline": "node --import tsx scripts/generate-pg-baseline.ts --check",
|
||||
"gen:pg-migration": "node --import tsx scripts/generate-pg-migration.ts",
|
||||
"probe:pg": "node --import tsx scripts/pg-probe.ts",
|
||||
"format": "prettier --write \"src/**/*.ts\" \"tests/**/*.ts\"",
|
||||
"format:check": "prettier --check \"src/**/*.ts\" \"tests/**/*.ts\"",
|
||||
@@ -48,6 +53,7 @@
|
||||
"test:integration": "vitest run tests/integration",
|
||||
"test:ws": "vitest run tests/websocket",
|
||||
"test:e2e": "vitest run tests/e2e",
|
||||
"test:pg": "vitest run --config vitest.pg.config.ts",
|
||||
"test:coverage": "vitest run --coverage"
|
||||
},
|
||||
"mikro-orm": {
|
||||
@@ -63,6 +69,7 @@
|
||||
"@mikro-orm/core": "^7.2.7",
|
||||
"@mikro-orm/migrations": "^7.2.7",
|
||||
"@mikro-orm/nestjs": "^7.1.0",
|
||||
"@mikro-orm/postgresql": "^7.2.7",
|
||||
"@mikro-orm/seeder": "^7.2.7",
|
||||
"@mikro-orm/sql": "^7.2.1",
|
||||
"@mikro-orm/sqlite": "^7.2.7",
|
||||
@@ -99,6 +106,7 @@
|
||||
"nodemailer": "^10.5.0",
|
||||
"otplib": "^12.0.1",
|
||||
"pdf-parse": "^2.4.5",
|
||||
"pg-cursor": "^2.22.1",
|
||||
"qrcode": "^1.5.4",
|
||||
"reflect-metadata": "^0.2.2",
|
||||
"rxjs": "^7.8.2",
|
||||
@@ -117,7 +125,6 @@
|
||||
"@aws-lite/s3-types": "^0.2.8",
|
||||
"@eslint/js": "^10.0.1",
|
||||
"@mikro-orm/entity-generator": "^7.2.7",
|
||||
"@mikro-orm/postgresql": "^7.2.7",
|
||||
"@nestjs/testing": "^11.2.5",
|
||||
"@swc/core": "^1.16.22",
|
||||
"@trivago/prettier-plugin-sort-imports": "^6.0.2",
|
||||
|
||||
+169
-81
@@ -7,13 +7,18 @@
|
||||
*
|
||||
* Defaults to admin@trek.local with a generated password (printed below). The
|
||||
* account is flagged must_change_password, so you are prompted to set a new one
|
||||
* on first login. Honours TREK_DB_FILE, TREK_DB_JOURNAL_MODE and
|
||||
* TREK_DB_SYNCHRONOUS the same way the server does.
|
||||
* on first login.
|
||||
*
|
||||
* It works on the database the server runs on. With TREK_DB_URL set, that is
|
||||
* the Postgres database, reached through the server's own engine (its pool,
|
||||
* SSL settings and write lock, from the built server in dist/); no SQLite file
|
||||
* is opened or created then. Otherwise it is the SQLite file, honouring
|
||||
* TREK_DB_FILE, TREK_DB_JOURNAL_MODE and TREK_DB_SYNCHRONOUS the same way the
|
||||
* server does.
|
||||
*/
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const crypto = require('crypto');
|
||||
const Database = require('better-sqlite3');
|
||||
const bcrypt = require('bcryptjs');
|
||||
|
||||
// Kept in sync with the seeder/authService cost factor.
|
||||
@@ -23,91 +28,174 @@ const email = process.env.RESET_ADMIN_EMAIL || 'admin@trek.local';
|
||||
const password = process.env.RESET_ADMIN_PASSWORD || crypto.randomBytes(12).toString('base64url');
|
||||
const generated = !process.env.RESET_ADMIN_PASSWORD;
|
||||
|
||||
// journal_mode is stored in the database file header, not per connection, so
|
||||
// opening the file here decides the mode for the server too. Plain JS outside
|
||||
// the Nest context can't reach src/app-config, hence the direct read — the
|
||||
// defaults must match parsers.resolveDurability() (WAL + NORMAL, FULL once a
|
||||
// rollback journal is in play). Run this via `docker exec` and the container's
|
||||
// environment applies, same as for the server.
|
||||
const journalModes = ['DELETE', 'TRUNCATE', 'PERSIST', 'MEMORY', 'WAL', 'OFF'];
|
||||
const syncLevels = ['OFF', 'NORMAL', 'FULL', 'EXTRA'];
|
||||
|
||||
const wantedJournal = (process.env.TREK_DB_JOURNAL_MODE || '').trim().toUpperCase();
|
||||
const journalMode = journalModes.includes(wantedJournal) ? wantedJournal : 'WAL';
|
||||
if (wantedJournal && journalMode !== wantedJournal) {
|
||||
console.warn(`TREK_DB_JOURNAL_MODE="${process.env.TREK_DB_JOURNAL_MODE}" is not a SQLite journal mode — using ${journalMode}.`);
|
||||
/** What the script prints once the account is reset or created. */
|
||||
function report(outcome) {
|
||||
if (outcome.created) console.log(`\n✓ Admin account created: ${email} (username: ${outcome.username})`);
|
||||
else console.log(`\n✓ Admin password reset: ${email}`);
|
||||
if (generated) console.log(` Password: ${password}`);
|
||||
console.log(' You will be asked to change the password on first login.\n');
|
||||
}
|
||||
|
||||
const wantedSync = (process.env.TREK_DB_SYNCHRONOUS || '').trim().toUpperCase();
|
||||
const defaultSync = journalMode === 'WAL' ? 'NORMAL' : 'FULL';
|
||||
const synchronous = syncLevels.includes(wantedSync) ? wantedSync : defaultSync;
|
||||
if (wantedSync && synchronous !== wantedSync) {
|
||||
console.warn(`TREK_DB_SYNCHRONOUS="${process.env.TREK_DB_SYNCHRONOUS}" is not a SQLite synchronous level — using ${synchronous}.`);
|
||||
/** The SQLite file the server runs on, reset with better-sqlite3. */
|
||||
function resetOnSqlite() {
|
||||
const Database = require('better-sqlite3');
|
||||
|
||||
// journal_mode is stored in the database file header, not per connection, so
|
||||
// opening the file here decides the mode for the server too. Plain JS outside
|
||||
// the Nest context can't reach src/app-config, hence the direct read — the
|
||||
// defaults must match parsers.resolveDurability() (WAL + NORMAL, FULL once a
|
||||
// rollback journal is in play). Run this via `docker exec` and the container's
|
||||
// environment applies, same as for the server.
|
||||
const journalModes = ['DELETE', 'TRUNCATE', 'PERSIST', 'MEMORY', 'WAL', 'OFF'];
|
||||
const syncLevels = ['OFF', 'NORMAL', 'FULL', 'EXTRA'];
|
||||
|
||||
const wantedJournal = (process.env.TREK_DB_JOURNAL_MODE || '').trim().toUpperCase();
|
||||
const journalMode = journalModes.includes(wantedJournal) ? wantedJournal : 'WAL';
|
||||
if (wantedJournal && journalMode !== wantedJournal) {
|
||||
console.warn(`TREK_DB_JOURNAL_MODE="${process.env.TREK_DB_JOURNAL_MODE}" is not a SQLite journal mode — using ${journalMode}.`);
|
||||
}
|
||||
|
||||
const wantedSync = (process.env.TREK_DB_SYNCHRONOUS || '').trim().toUpperCase();
|
||||
const defaultSync = journalMode === 'WAL' ? 'NORMAL' : 'FULL';
|
||||
const synchronous = syncLevels.includes(wantedSync) ? wantedSync : defaultSync;
|
||||
if (wantedSync && synchronous !== wantedSync) {
|
||||
console.warn(`TREK_DB_SYNCHRONOUS="${process.env.TREK_DB_SYNCHRONOUS}" is not a SQLite synchronous level — using ${synchronous}.`);
|
||||
}
|
||||
|
||||
const dbPath = process.env.TREK_DB_FILE || path.join(__dirname, 'data/travel.db');
|
||||
// SQLite silently opens an unwritable file read-only (#2933); db.readonly can't tell.
|
||||
const notWritable = [dbPath, path.dirname(dbPath)].find((p) => {
|
||||
if (!fs.existsSync(p)) return false;
|
||||
try {
|
||||
fs.accessSync(p, fs.constants.W_OK);
|
||||
return false;
|
||||
} catch {
|
||||
return true;
|
||||
}
|
||||
});
|
||||
if (notWritable) {
|
||||
console.error(`Cannot write to ${notWritable} as uid ${process.getuid?.() ?? '?'}.`);
|
||||
console.error('Run this script as the user that owns the data directory. In the Docker image that is node:');
|
||||
console.error(' docker exec -it -u node trek node server/reset-admin.js');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const db = new Database(dbPath);
|
||||
// Spelled out rather than left to better-sqlite3's default, so switching the
|
||||
// journal mode below waits for a busy server instead of failing on the spot.
|
||||
// Five seconds, same as src/db/database.ts.
|
||||
db.exec('PRAGMA busy_timeout = 5000');
|
||||
// Temp files in memory, like every connection src/db/connection.ts opens: a
|
||||
// container with a read-only root and no tmpfs on /tmp has nowhere to put them
|
||||
// (#2518).
|
||||
db.exec('PRAGMA temp_store = MEMORY');
|
||||
db.exec(`PRAGMA journal_mode = ${journalMode}`);
|
||||
db.exec(`PRAGMA synchronous = ${synchronous}`);
|
||||
|
||||
const hash = bcrypt.hashSync(password, BCRYPT_COST);
|
||||
// Case-insensitive like login, so Admin@example.com is found as admin@example.com.
|
||||
const existing = db.prepare('SELECT id FROM users WHERE LOWER(email) = LOWER(?)').get(email);
|
||||
|
||||
let outcome;
|
||||
if (existing) {
|
||||
// password_version moves on, as on every password change in the app: it is
|
||||
// what ends the sessions still signed in to an account that needed resetting.
|
||||
db.prepare('UPDATE users SET password_hash = ?, role = ?, must_change_password = 1, password_version = COALESCE(password_version, 0) + 1 WHERE id = ?')
|
||||
.run(hash, 'admin', existing.id);
|
||||
// Its sessions end too, so the account's session list shows none of them
|
||||
// as live. The table is missing on a database that no server tracking
|
||||
// sessions has booted yet; the password_version bump above already refuses
|
||||
// every token there.
|
||||
const sessionsTable = db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'user_sessions'").get();
|
||||
if (sessionsTable) {
|
||||
db.prepare('UPDATE user_sessions SET revoked_at = CURRENT_TIMESTAMP WHERE user_id = ? AND revoked_at IS NULL')
|
||||
.run(existing.id);
|
||||
}
|
||||
outcome = { created: false };
|
||||
} else {
|
||||
// 'admin' is usually taken by the first-run seed — pick the first free username
|
||||
// so the insert can't trip the UNIQUE(username) constraint.
|
||||
let username = 'admin';
|
||||
let n = 1;
|
||||
while (db.prepare('SELECT 1 FROM users WHERE username = ?').get(username)) {
|
||||
username = `admin${n++}`;
|
||||
}
|
||||
db.prepare('INSERT INTO users (username, email, password_hash, role, must_change_password) VALUES (?, ?, ?, ?, 1)')
|
||||
.run(username, email, hash, 'admin');
|
||||
outcome = { created: true, username };
|
||||
}
|
||||
|
||||
report(outcome);
|
||||
db.close();
|
||||
}
|
||||
|
||||
const dbPath = process.env.TREK_DB_FILE || path.join(__dirname, 'data/travel.db');
|
||||
// SQLite silently opens an unwritable file read-only (#2933); db.readonly can't tell.
|
||||
const notWritable = [dbPath, path.dirname(dbPath)].find((p) => {
|
||||
if (!fs.existsSync(p)) return false;
|
||||
/**
|
||||
* The Postgres database in TREK_DB_URL, reset through the built server's
|
||||
* engine (dist/db/engine): the same pool options and SSL verification as the
|
||||
* server, and the same write lock, taken in one transaction with the reset.
|
||||
* The statements are the SQLite branch's, but for the session end, whose time
|
||||
* is written as the canonical `YYYY-MM-DD HH:MM:SS` UTC text the column holds.
|
||||
*/
|
||||
async function resetOnPostgres() {
|
||||
if ((process.env.TREK_DB_FILE || '').trim()) {
|
||||
console.error('TREK_DB_URL and TREK_DB_FILE are both set, so it is not clear which database is meant; nothing was changed.');
|
||||
process.exit(1);
|
||||
}
|
||||
let engineModule;
|
||||
try {
|
||||
fs.accessSync(p, fs.constants.W_OK);
|
||||
return false;
|
||||
} catch {
|
||||
return true;
|
||||
engineModule = require('./dist/db/engine');
|
||||
} catch (err) {
|
||||
console.error(`The built server (${path.join(__dirname, 'dist')}) is needed to reach a Postgres database: ${err.message}`);
|
||||
console.error('Run this inside the TREK container, or run `npm run build --workspace=server` first.');
|
||||
process.exit(1);
|
||||
}
|
||||
const { MikroORM } = require('@mikro-orm/core');
|
||||
const engine = engineModule.resolveEngine();
|
||||
const orm = await MikroORM.init({ ...engineModule.buildOrmConfig(engine), pool: { min: 0, max: 1 } });
|
||||
try {
|
||||
const em = orm.em.fork();
|
||||
const hash = bcrypt.hashSync(password, BCRYPT_COST);
|
||||
const now = new Date().toISOString().slice(0, 19).replace('T', ' ');
|
||||
const outcome = await em.transactional(async (tx) => {
|
||||
await engine.serializeWrites(tx);
|
||||
const connection = tx.getConnection();
|
||||
const query = (sql, params = []) => connection.execute(sql, params, 'all', tx.getTransactionContext());
|
||||
const [existing] = await query('SELECT id FROM users WHERE LOWER(email) = LOWER(?)', [email]);
|
||||
if (existing) {
|
||||
await query(
|
||||
'UPDATE users SET password_hash = ?, role = ?, must_change_password = 1, password_version = COALESCE(password_version, 0) + 1 WHERE id = ?',
|
||||
[hash, 'admin', existing.id],
|
||||
);
|
||||
const [sessions] = await query("SELECT to_regclass('user_sessions') IS NOT NULL AS present");
|
||||
if (sessions && sessions.present) {
|
||||
await query('UPDATE user_sessions SET revoked_at = ? WHERE user_id = ? AND revoked_at IS NULL', [now, existing.id]);
|
||||
}
|
||||
return { created: false };
|
||||
}
|
||||
let username = 'admin';
|
||||
let n = 1;
|
||||
while ((await query('SELECT 1 FROM users WHERE username = ?', [username])).length > 0) {
|
||||
username = `admin${n++}`;
|
||||
}
|
||||
await query('INSERT INTO users (username, email, password_hash, role, must_change_password) VALUES (?, ?, ?, ?, 1)', [
|
||||
username,
|
||||
email,
|
||||
hash,
|
||||
'admin',
|
||||
]);
|
||||
return { created: true, username };
|
||||
});
|
||||
report(outcome);
|
||||
} finally {
|
||||
await orm.close(true);
|
||||
}
|
||||
});
|
||||
if (notWritable) {
|
||||
console.error(`Cannot write to ${notWritable} as uid ${process.getuid?.() ?? '?'}.`);
|
||||
console.error('Run this script as the user that owns the data directory. In the Docker image that is node:');
|
||||
console.error(' docker exec -it -u node trek node server/reset-admin.js');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const db = new Database(dbPath);
|
||||
// Spelled out rather than left to better-sqlite3's default, so switching the
|
||||
// journal mode below waits for a busy server instead of failing on the spot.
|
||||
// Five seconds, same as src/db/database.ts.
|
||||
db.exec('PRAGMA busy_timeout = 5000');
|
||||
// Temp files in memory, like every connection src/db/connection.ts opens: a
|
||||
// container with a read-only root and no tmpfs on /tmp has nowhere to put them
|
||||
// (#2518).
|
||||
db.exec('PRAGMA temp_store = MEMORY');
|
||||
db.exec(`PRAGMA journal_mode = ${journalMode}`);
|
||||
db.exec(`PRAGMA synchronous = ${synchronous}`);
|
||||
|
||||
const hash = bcrypt.hashSync(password, BCRYPT_COST);
|
||||
// Case-insensitive like login, so Admin@example.com is found as admin@example.com.
|
||||
const existing = db.prepare('SELECT id FROM users WHERE LOWER(email) = LOWER(?)').get(email);
|
||||
|
||||
if (existing) {
|
||||
// password_version moves on, as on every password change in the app: it is
|
||||
// what ends the sessions still signed in to an account that needed resetting.
|
||||
db.prepare('UPDATE users SET password_hash = ?, role = ?, must_change_password = 1, password_version = COALESCE(password_version, 0) + 1 WHERE id = ?')
|
||||
.run(hash, 'admin', existing.id);
|
||||
// Its sessions end too, so the account's session list shows none of them
|
||||
// as live. The table is missing on a database that no server tracking
|
||||
// sessions has booted yet; the password_version bump above already refuses
|
||||
// every token there.
|
||||
const sessionsTable = db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'user_sessions'").get();
|
||||
if (sessionsTable) {
|
||||
db.prepare('UPDATE user_sessions SET revoked_at = CURRENT_TIMESTAMP WHERE user_id = ? AND revoked_at IS NULL')
|
||||
.run(existing.id);
|
||||
}
|
||||
console.log(`\n✓ Admin password reset: ${email}`);
|
||||
if ((process.env.TREK_DB_URL || '').trim()) {
|
||||
resetOnPostgres().catch((err) => {
|
||||
console.error(`Could not reset the admin account on the Postgres database: ${err && err.message ? err.message : err}`);
|
||||
process.exit(1);
|
||||
});
|
||||
} else {
|
||||
// 'admin' is usually taken by the first-run seed — pick the first free username
|
||||
// so the insert can't trip the UNIQUE(username) constraint.
|
||||
let username = 'admin';
|
||||
let n = 1;
|
||||
while (db.prepare('SELECT 1 FROM users WHERE username = ?').get(username)) {
|
||||
username = `admin${n++}`;
|
||||
}
|
||||
db.prepare('INSERT INTO users (username, email, password_hash, role, must_change_password) VALUES (?, ?, ?, ?, 1)')
|
||||
.run(username, email, hash, 'admin');
|
||||
console.log(`\n✓ Admin account created: ${email} (username: ${username})`);
|
||||
resetOnSqlite();
|
||||
}
|
||||
|
||||
if (generated) console.log(` Password: ${password}`);
|
||||
console.log(' You will be asked to change the password on first login.\n');
|
||||
|
||||
db.close();
|
||||
|
||||
@@ -26,9 +26,6 @@
|
||||
"src/db/entities/PluginUserErasureQueue.entity.ts": {
|
||||
"datetime": 1
|
||||
},
|
||||
"src/db/repositories/MaintenanceRepository.ts": {
|
||||
"pragma": 1
|
||||
},
|
||||
"src/nest/backup/backup-archive.ts": {
|
||||
"pragma": 1
|
||||
}
|
||||
|
||||
+399
-41
@@ -2,26 +2,45 @@
|
||||
/*
|
||||
* lint:dialect: SQLite-only SQL may only shrink.
|
||||
*
|
||||
* The server runs on SQLite today and is meant to run on Postgres next. What
|
||||
* stands in the way is SQL that only SQLite understands, spelled out inline:
|
||||
* INSERT OR IGNORE, datetime('now'), strftime, json_extract, GLOB,
|
||||
* last_insert_rowid, PRAGMA, AUTOINCREMENT and `||` string concatenation.
|
||||
* The server runs on SQLite and on Postgres. What stands in the way is SQL
|
||||
* that only SQLite understands, spelled out inline: INSERT OR IGNORE,
|
||||
* datetime('now'), strftime, json_extract, group_concat, ifnull and the other
|
||||
* SQLite-only functions, GLOB, last_insert_rowid, PRAGMA, AUTOINCREMENT and
|
||||
* `||` string concatenation, and LIKE, which ignores case on SQLite only.
|
||||
* Each of them has a dialect-neutral form: the query builder's onConflict(),
|
||||
* returning('id'), or a helper in src/db/dialect/ (sql-functions.ts and its
|
||||
* Kysely twin kysely-functions.ts), which dispatches on the live platform
|
||||
* and is the one place allowed to spell an engine's own forms.
|
||||
* Kysely twin kysely-functions.ts, ilike() for a search), which dispatches on
|
||||
* the live platform and is the one place allowed to spell an engine's own
|
||||
* forms. A LIKE that is exact on purpose (a key or path prefix) carries a
|
||||
* `like-exact: <reason>` comment on its line or the line above.
|
||||
*
|
||||
* The check reads every string and template literal under src/ (comments
|
||||
* never count) and every `.insertId` read, counts the hits per file and rule,
|
||||
* and holds them to scripts/dialect-baseline.json. A new hit fails, and so
|
||||
* does a baseline entry above what its file holds now, so the change that
|
||||
* removes one lowers the baseline with --update in the same commit.
|
||||
* never count), every `.insertId` read and every MikroORM `$like`, counts the
|
||||
* hits per file and rule, and holds them to scripts/dialect-baseline.json. A
|
||||
* new hit fails, and so does a baseline entry above what its file holds now,
|
||||
* so the change that removes one lowers the baseline with --update in the
|
||||
* same commit.
|
||||
*
|
||||
* Not scanned: src/db/dialect/ (the dialect layer itself) and
|
||||
* the migrations that have shipped (append-only, never edited again; the last
|
||||
* one is FROZEN_MIGRATIONS_THROUGH). A newer migration is scanned for the
|
||||
* DML rules; its DDL may still be engine specific. PRAGMA is allowed in the
|
||||
* src/db/ lifecycle files (src/db/*.ts and the migrations), nowhere else.
|
||||
* Not scanned: src/db/dialect/ (the dialect layer itself), the SQLite
|
||||
* engine's own code (src/db/engine/sqlite/) and the migrations that have
|
||||
* shipped (append-only, never edited again; the last one is
|
||||
* FROZEN_MIGRATIONS_THROUGH). A newer migration is scanned for the DML rules.
|
||||
* PRAGMA is allowed in the src/db/ lifecycle files (src/db/*.ts and the
|
||||
* migrations), nowhere else.
|
||||
*
|
||||
* A migration after the Postgres baseline's cut (`through` in
|
||||
* assets/postgres/baseline.json, or POSTGRES_FIRST_CUT when that comes
|
||||
* first: moving the manifest's cut never takes a migration off the Postgres
|
||||
* installs that already run it) runs on both engines, so it is held to
|
||||
* POST_CUT_RULES as well: each schema statement goes through
|
||||
* engineDdl(this, { sqlite: [...], postgres: [...] }), whose sqlite member
|
||||
* holds nothing but the schema change and whose postgres member is filled (or
|
||||
* says why not) and holds no SQLite spelling; each column handed to
|
||||
* addColumnIfMissing is { sqlite, postgres }; the SQLite-only helpers of
|
||||
* migration-utils are not called, and neither are the best-effort ones, which
|
||||
* abort the migration transaction on Postgres when they fail; and LIKE counts
|
||||
* there too. The post-cut rules have no allowance: the baseline file may not
|
||||
* hold an entry for them.
|
||||
*
|
||||
* npm run lint:dialect check against the baseline (CI)
|
||||
* npm run lint:dialect -- --update lower the baseline to what the files hold now;
|
||||
@@ -40,9 +59,25 @@ const ts = require('typescript');
|
||||
/** The last migration that shipped before this check existed. Later ones are scanned. */
|
||||
export const FROZEN_MIGRATIONS_THROUGH = 'Migration20200101042400';
|
||||
|
||||
/** Where the cut is read from: the migrations after its `through` run on Postgres too. */
|
||||
export const POSTGRES_BASELINE_MANIFEST = 'assets/postgres/baseline.json';
|
||||
|
||||
/**
|
||||
* The cut Postgres support shipped with. A Postgres install can stand at it,
|
||||
* and its next boot runs every later migration through the migrator, so a
|
||||
* migration after it is held to POST_CUT_RULES for good, wherever the
|
||||
* manifest's `through` moves later: regenerating the baseline over a migration
|
||||
* does not take it off the Postgres installs that already exist. Never
|
||||
* change this.
|
||||
*/
|
||||
export const POSTGRES_FIRST_CUT = 'Migration20200101046440';
|
||||
|
||||
/** The dialect layer: the one place that may spell an engine's own SQL. */
|
||||
const DIALECT_LAYER = 'src/db/dialect/';
|
||||
|
||||
/** The SQLite engine's own code, which runs on SQLite alone. */
|
||||
const SQLITE_ENGINE = 'src/db/engine/sqlite/';
|
||||
|
||||
const SQL_KEYWORDS = /\b(SELECT|UPDATE|INSERT|DELETE|WHERE|SET|CASE|WHEN|COALESCE|CAST|VALUES|FROM)\b/i;
|
||||
|
||||
/**
|
||||
@@ -72,14 +107,30 @@ export const RULES = [
|
||||
},
|
||||
{
|
||||
name: 'json',
|
||||
test: (text) => /\bjson_(extract|each|set|patch|insert|replace|remove|group_array|group_object)\b/i.test(text),
|
||||
test: (text) =>
|
||||
/\bjson_(extract|each|set|patch|insert|replace|remove|group_array|group_object)\b/i.test(text) ||
|
||||
// These read as words elsewhere (an LLM API's json_object mode), so only the call counts.
|
||||
/\bjson_(object|array|valid|type|quote)\s*\(/i.test(text),
|
||||
advice: 'read the JSON column and parse it in the service, or add a helper to sql-functions.ts',
|
||||
migrations: true,
|
||||
},
|
||||
{
|
||||
name: 'sqlite-function',
|
||||
// The call in SQL text, or the bare name handed to eb.fn('ifnull', [...]).
|
||||
// `total` and `changes` are words and column names too, so they count
|
||||
// only as a call with the parenthesis right after the name.
|
||||
test: (text) =>
|
||||
/\b(group_concat|ifnull|instr|iif|printf|typeof)\s*\(|\b(total|changes)\(/i.test(text) ||
|
||||
/^(group_concat|ifnull|instr|iif|printf)$/i.test(text.trim()),
|
||||
advice:
|
||||
'group_concat, ifnull, instr, iif, printf, typeof, total and changes are SQLite-only: use coalesce (both ' +
|
||||
'engines), aggregate in the service, or add a helper to sql-functions.ts that spells both engines',
|
||||
migrations: true,
|
||||
},
|
||||
{
|
||||
name: 'glob',
|
||||
test: (text) => /\bGLOB\b/.test(text) || text.trim().toLowerCase() === 'glob',
|
||||
advice: 'use LIKE, or startsWithIsoDate and its siblings in sql-functions.ts',
|
||||
advice: 'use startsWithIsoDate and its siblings, or ilike(), from sql-functions.ts',
|
||||
migrations: true,
|
||||
},
|
||||
{
|
||||
@@ -106,27 +157,192 @@ export const RULES = [
|
||||
test: (text, inSqlTag) => text.includes('||') && (inSqlTag || SQL_KEYWORDS.test(text)),
|
||||
advice: 'use concat/concatKysely from sql-functions.ts',
|
||||
migrations: true,
|
||||
// Postgres spells `||` itself, so a postgres member may hold it.
|
||||
postgresSpells: true,
|
||||
},
|
||||
{
|
||||
name: 'like',
|
||||
// Kysely's 'like'/'not like' operator, LIKE in a sql tag, or LIKE before a
|
||||
// SQL operand (a bound value, a quoted pattern, a call) in other SQL text,
|
||||
// so that prose ("a name like ...") does not count. MikroORM's `$like`
|
||||
// key is counted where the object is read (scanSource).
|
||||
test: (text, inSqlTag) =>
|
||||
/^(not\s+)?like$/i.test(text.trim()) ||
|
||||
(inSqlTag && /\bLIKE\b/i.test(text)) ||
|
||||
(/\bLIKE\s+(?:\?|'|:\w|\$\d|\w+\s*\()/i.test(text) && SQL_KEYWORDS.test(text)),
|
||||
advice:
|
||||
'LIKE ignores case on SQLite and not on Postgres: build a search with ilike(platform, refs) from ' +
|
||||
'sql-functions.ts. A match that is exact on purpose (a settings key, a storage path) keeps LIKE and says so ' +
|
||||
'in a `// like-exact: <reason>` comment on its line or the line above',
|
||||
// A migration up to the cut runs on SQLite alone; a later one runs on both.
|
||||
migrations: 'post-cut',
|
||||
postgresSpells: true,
|
||||
marker: /like-exact:\s*\S/,
|
||||
},
|
||||
];
|
||||
|
||||
/** `.insertId` reads, the JS face of last_insert_rowid. */
|
||||
const INSERT_ID_RULE = 'insert-id';
|
||||
|
||||
/** What every post-cut rule's advice ends with: the two steps that satisfy it. */
|
||||
const POST_CUT_ROUTINE =
|
||||
'(1) write the schema change as engineDdl(this, { sqlite: [...], postgres: [] }) from src/db/migration-utils.ts ' +
|
||||
"with the SQLite statements by hand (a column for addColumnIfMissing as { sqlite: '...', postgres: '...' }); " +
|
||||
'(2) fill postgres with what npm run gen:pg-migration prints (server/CLAUDE.md, SQL dialect, Migrations)';
|
||||
|
||||
/** A schema statement: CREATE/ALTER/DROP of a table, index, trigger or view, or a RENAME. */
|
||||
const DDL_STATEMENT =
|
||||
/\b(?:CREATE|ALTER|DROP)\s+(?:UNIQUE\s+)?(?:TEMP(?:ORARY)?\s+)?(?:TABLE|INDEX|TRIGGER|VIEW)\b|\bRENAME\s+(?:TO|COLUMN)\b/i;
|
||||
|
||||
/** SQLite's own column types and clauses, which Postgres refuses or reads differently. */
|
||||
const SQLITE_ONLY_DDL = /\bDATETIME\b|\bAUTOINCREMENT\b|\bINTEGER\s+PRIMARY\s+KEY\b|\bWITHOUT\s+ROWID\b|\bPRAGMA\b/i;
|
||||
|
||||
/** The migration-utils helpers that only speak SQLite. */
|
||||
const SQLITE_ONLY_HELPERS = new Set(['tableSql', 'createPlaceRegionsFollowPlaceTrigger']);
|
||||
|
||||
/**
|
||||
* The migration-utils helpers that swallow a failed statement. On Postgres the
|
||||
* pending migrations run in one transaction, and a failed statement aborts it,
|
||||
* so they cannot be best-effort there.
|
||||
*/
|
||||
const BEST_EFFORT_HELPERS = new Set(['execBestEffort', 'bestEffort', 'execUnlessTableMissing']);
|
||||
|
||||
/** The calls whose { sqlite, postgres } argument holds the DDL of each engine. */
|
||||
const ENGINE_DDL_CALLS = new Set(['engineDdl', 'addColumnIfMissing']);
|
||||
|
||||
/**
|
||||
* What an engineDdl sqlite member may hold, statement by statement: a schema
|
||||
* change (CREATE/DROP of a table, index or view, an ALTER TABLE), a PRAGMA,
|
||||
* and what a table rebuild needs besides: the INSERT ... SELECT that copies
|
||||
* the old table into a new one the same member creates, and the
|
||||
* sqlite_sequence bookkeeping that carries its AUTOINCREMENT counter over.
|
||||
*/
|
||||
const SQLITE_SCHEMA_STATEMENT =
|
||||
/^(?:(?:CREATE|DROP)\s+(?:UNIQUE\s+)?(?:TEMP(?:ORARY)?\s+)?(?:TABLE|INDEX|VIEW)\b|ALTER\s+TABLE\b|PRAGMA\b)/i;
|
||||
const SQLITE_SEQUENCE_STATEMENT = /^(?:UPDATE|DELETE\s+FROM|INSERT\s+INTO)\s+["`]?sqlite_sequence\b/i;
|
||||
const CREATED_TABLE = /^CREATE\s+(?:TEMP(?:ORARY)?\s+)?TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?["`]?(\w+)/i;
|
||||
const TABLE_COPY = /^INSERT\s+INTO\s+["`]?(\w+)["`]?[\s(][\s\S]*\bSELECT\b/i;
|
||||
|
||||
/** The comment that names why an engineDdl with SQLite statements leaves Postgres nothing to do. */
|
||||
const SQLITE_ONLY_MARKER = /sqlite-only:\s*\S/;
|
||||
|
||||
/**
|
||||
* The rules for a migration after the Postgres baseline's cut. A new
|
||||
* migration starts at zero: the baseline file may not hold an entry for them.
|
||||
*/
|
||||
export const POST_CUT_RULES = [
|
||||
{
|
||||
name: 'ddl',
|
||||
label: 'schema statement(s) outside engineDdl',
|
||||
advice: `a migration after the Postgres baseline's cut runs on both engines: ${POST_CUT_ROUTINE}`,
|
||||
},
|
||||
{
|
||||
name: 'sqlite-ddl',
|
||||
label: 'SQLite spelling(s) in an engineDdl postgres member',
|
||||
advice:
|
||||
'the postgres member is what Postgres runs, and DATETIME, AUTOINCREMENT, INTEGER PRIMARY KEY, WITHOUT ROWID, ' +
|
||||
'PRAGMA and the SQLite-only functions are not Postgres: replace it with what npm run gen:pg-migration prints',
|
||||
},
|
||||
{
|
||||
name: 'sqlite-member',
|
||||
label: 'statement(s) in an engineDdl sqlite member that are not a schema change',
|
||||
advice:
|
||||
'what the sqlite member holds never runs on Postgres, so it holds the schema change alone: CREATE/DROP of a ' +
|
||||
'table, index or view, ALTER TABLE, PRAGMA, and for a table rebuild the INSERT INTO <new table> ... SELECT ' +
|
||||
'and the sqlite_sequence statements, each written inline as a string. Move a data change (UPDATE, DELETE, ' +
|
||||
'INSERT) into this.addSql after the engineDdl call, where it runs on both engines under the DML rules. A ' +
|
||||
'trigger after the cut has no Postgres port (server/CLAUDE.md, SQL dialect, Migrations): do that work in the ' +
|
||||
'repository instead',
|
||||
},
|
||||
{
|
||||
name: 'empty-postgres',
|
||||
label: 'engineDdl call(s) with SQLite statements and an empty postgres member',
|
||||
advice:
|
||||
'fill the postgres member with what npm run gen:pg-migration prints. When it prints postgres: [] because the ' +
|
||||
"change is SQLite's alone (a rebuild that leaves the Postgres schema as it is), say why in a " +
|
||||
'`// sqlite-only: <reason>` comment directly above the postgres member',
|
||||
},
|
||||
{
|
||||
name: 'best-effort',
|
||||
label: 'best-effort step(s), which abort every pending migration on Postgres when they fail',
|
||||
advice:
|
||||
'execBestEffort, bestEffort and execUnlessTableMissing swallow a failed statement, but on Postgres the pending ' +
|
||||
'migrations run in one transaction that a failed statement aborts, so the next statement and the history row ' +
|
||||
'fail and the boot is refused. Write a statement that cannot fail instead: guard it in its WHERE clause, or ' +
|
||||
'check tableExists/columnNames from src/db/migration-utils.ts first',
|
||||
},
|
||||
];
|
||||
const POST_CUT_RULE_NAMES = new Set(POST_CUT_RULES.map((rule) => rule.name));
|
||||
|
||||
const SOURCE = /\.ts$/;
|
||||
const TEST = /\.(?:test|spec)\./;
|
||||
|
||||
/** 'skip', 'migration' (a newer one, DML rules only) or 'source'. */
|
||||
export function classify(file) {
|
||||
if (file.startsWith(DIALECT_LAYER)) return 'skip';
|
||||
/** The `Migration<timestamp>` a migration's class name starts with, or null. */
|
||||
function migrationId(name) {
|
||||
return /^(Migration\d+)(?:_|$)/.exec(name)?.[1] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 'skip', 'migration' (a newer one, DML rules only), 'post-cut' (one after
|
||||
* the Postgres baseline's `through` or after POSTGRES_FIRST_CUT, whichever
|
||||
* comes first: the DML rules and POST_CUT_RULES) or 'source'.
|
||||
*/
|
||||
export function classify(file, through) {
|
||||
if (file.startsWith(DIALECT_LAYER) || file.startsWith(SQLITE_ENGINE)) return 'skip';
|
||||
const migration = /^src\/db\/migrations\/(Migration\d+)_/.exec(file);
|
||||
if (migration) return migration[1] <= FROZEN_MIGRATIONS_THROUGH ? 'skip' : 'migration';
|
||||
if (migration) {
|
||||
if (migration[1] <= FROZEN_MIGRATIONS_THROUGH) return 'skip';
|
||||
const cut = [migrationId(through), POSTGRES_FIRST_CUT].sort()[0];
|
||||
return migration[1] > cut ? 'post-cut' : 'migration';
|
||||
}
|
||||
if (file.startsWith('src/db/migrations/')) return 'skip';
|
||||
return 'source';
|
||||
}
|
||||
|
||||
/** PRAGMA is fine in src/db/*.ts (connection, durability, baseline, snapshot) and the migrations. */
|
||||
/**
|
||||
* The Postgres baseline's cut, from its manifest. A missing or malformed one
|
||||
* stops the run: without it no migration would be held to POST_CUT_RULES.
|
||||
*/
|
||||
export function readThrough(serverDir) {
|
||||
let through;
|
||||
try {
|
||||
through = JSON.parse(readFileSync(join(serverDir, POSTGRES_BASELINE_MANIFEST), 'utf8')).through;
|
||||
} catch (err) {
|
||||
throw new Error(`${POSTGRES_BASELINE_MANIFEST} cannot be read: ${err.message}`);
|
||||
}
|
||||
if (typeof through !== 'string' || migrationId(through) === null) {
|
||||
throw new Error(`${POSTGRES_BASELINE_MANIFEST} must name the last migration it stands for in "through"`);
|
||||
}
|
||||
return through;
|
||||
}
|
||||
|
||||
/** The name a call is made by: `engineDdl(...)` and `utils.engineDdl(...)` alike. */
|
||||
function calleeName(node) {
|
||||
const callee = node.expression;
|
||||
if (ts.isIdentifier(callee)) return callee.text;
|
||||
if (ts.isPropertyAccessExpression(callee)) return callee.name.text;
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Whether `node` is an object literal naming both engines, the shape engineDdl and addColumnIfMissing take. */
|
||||
function isPerEngineObject(node) {
|
||||
if (!node || !ts.isObjectLiteralExpression(node)) return false;
|
||||
const names = node.properties
|
||||
.filter((property) => ts.isPropertyAssignment(property) && ts.isIdentifier(property.name))
|
||||
.map((property) => property.name.text);
|
||||
return names.includes('sqlite') && names.includes('postgres');
|
||||
}
|
||||
|
||||
/**
|
||||
* PRAGMA is fine in src/db/*.ts (connection, durability, baseline, snapshot),
|
||||
* the migrations and the SQLite engine's own folder (src/db/engine/sqlite/).
|
||||
*/
|
||||
export function pragmaAllowed(file) {
|
||||
return /^src\/db\/[^/]+\.ts$/.test(file) || file.startsWith('src/db/migrations/');
|
||||
return (
|
||||
/^src\/db\/[^/]+\.ts$/.test(file) ||
|
||||
file.startsWith('src/db/migrations/') ||
|
||||
file.startsWith('src/db/engine/sqlite/')
|
||||
);
|
||||
}
|
||||
|
||||
function isSqlTag(node) {
|
||||
@@ -135,34 +351,165 @@ function isSqlTag(node) {
|
||||
return ts.isIdentifier(tag) && tag.text === 'sql';
|
||||
}
|
||||
|
||||
/** Hits per rule in one file's source. */
|
||||
export function scanSource(file, text) {
|
||||
const kind = classify(file);
|
||||
/** The text of a string or template literal, or null. An interpolation is code, scanned on its own. */
|
||||
function literalText(node) {
|
||||
if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) return node.text;
|
||||
if (ts.isTemplateExpression(node)) {
|
||||
// An interpolated value reads as what it stands for in SQL, a bound value.
|
||||
return [node.head.text, ...node.templateSpans.map((span) => span.literal.text)].join(' ? ');
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The statements of one SQL text, `--` comments and empty ones left out. */
|
||||
function statementsOf(text) {
|
||||
return text
|
||||
.replace(/--[^\n]*/g, ' ')
|
||||
.split(';')
|
||||
.map((statement) => statement.trim())
|
||||
.filter((statement) => statement.length > 0);
|
||||
}
|
||||
|
||||
/** The `sqlite` or `postgres` property of a per-engine object. */
|
||||
function engineMember(object, name) {
|
||||
return object.properties.find(
|
||||
(property) => ts.isPropertyAssignment(property) && ts.isIdentifier(property.name) && property.name.text === name,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* How many literals of an engineDdl sqlite member hold a statement that is
|
||||
* not a schema change (SQLITE_SCHEMA_STATEMENT, the sequence bookkeeping, or
|
||||
* a copy into a table the same member creates). A member that is not an array
|
||||
* literal, and an element that is not a literal, count too: what the check
|
||||
* cannot read, it cannot let through.
|
||||
*/
|
||||
function sqliteMemberProblems(initializer) {
|
||||
if (!ts.isArrayLiteralExpression(initializer)) return 1;
|
||||
const texts = initializer.elements.map(literalText);
|
||||
const created = new Set(
|
||||
texts
|
||||
.flatMap((text) => (text === null ? [] : statementsOf(text)))
|
||||
.map((statement) => CREATED_TABLE.exec(statement)?.[1]?.toLowerCase())
|
||||
.filter(Boolean),
|
||||
);
|
||||
const isSchemaChange = (statement) =>
|
||||
SQLITE_SCHEMA_STATEMENT.test(statement) ||
|
||||
SQLITE_SEQUENCE_STATEMENT.test(statement) ||
|
||||
created.has(TABLE_COPY.exec(statement)?.[1]?.toLowerCase());
|
||||
return texts.filter((text) => text === null || !statementsOf(text).every(isSchemaChange)).length;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether an engineDdl call hands SQLite statements and Postgres none, with no
|
||||
* `sqlite-only: <reason>` comment above its postgres member.
|
||||
*/
|
||||
function emptyPostgresUnexplained(object, sourceText) {
|
||||
const sqlite = engineMember(object, 'sqlite');
|
||||
const postgres = engineMember(object, 'postgres');
|
||||
if (!ts.isArrayLiteralExpression(sqlite.initializer) || sqlite.initializer.elements.length === 0) return false;
|
||||
if (!ts.isArrayLiteralExpression(postgres.initializer) || postgres.initializer.elements.length > 0) return false;
|
||||
const comments = ts.getLeadingCommentRanges(sourceText, postgres.getFullStart()) ?? [];
|
||||
return !comments.some((range) => SQLITE_ONLY_MARKER.test(sourceText.slice(range.pos, range.end)));
|
||||
}
|
||||
|
||||
/** Whether `rule` applies to a file of `kind` ('source', 'migration' or 'post-cut'). */
|
||||
function ruleApplies(rule, kind) {
|
||||
if (kind === 'source') return true;
|
||||
if (rule.migrations === 'post-cut') return kind === 'post-cut';
|
||||
return rule.migrations;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hits per rule in one file's source. `through` is the Postgres baseline's
|
||||
* cut; a migration after it is held to POST_CUT_RULES as well.
|
||||
*/
|
||||
export function scanSource(file, text, through) {
|
||||
const kind = classify(file, through);
|
||||
const counts = {};
|
||||
if (kind === 'skip') return counts;
|
||||
const postCut = kind === 'post-cut';
|
||||
const add = (rule) => {
|
||||
counts[rule] = (counts[rule] ?? 0) + 1;
|
||||
};
|
||||
const sf = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
|
||||
const lines = text.split('\n');
|
||||
// A rule's marker comment excuses a hit on its own line or the line above.
|
||||
const marked = (rule, node) => {
|
||||
if (!rule.marker) return false;
|
||||
const line = sf.getLineAndCharacterOfPosition(node.getStart(sf)).line;
|
||||
return rule.marker.test(lines[line]) || (line > 0 && rule.marker.test(lines[line - 1]));
|
||||
};
|
||||
|
||||
const checkText = (literal, inSqlTag) => {
|
||||
// `engine` is the member of an engineDdl or addColumnIfMissing argument a
|
||||
// literal sits in: 'sqlite' (SQLite's own DDL, whose shape the engineDdl
|
||||
// call checks), 'postgres' (no SQLite spelling) or null (anywhere else).
|
||||
const checkText = (literal, node, inSqlTag, engine) => {
|
||||
if (engine === 'sqlite') return;
|
||||
if (engine === 'postgres') {
|
||||
const sqliteOnly =
|
||||
SQLITE_ONLY_DDL.test(literal) || RULES.some((rule) => !rule.postgresSpells && rule.test(literal, inSqlTag));
|
||||
if (sqliteOnly) add('sqlite-ddl');
|
||||
return;
|
||||
}
|
||||
if (postCut && DDL_STATEMENT.test(literal)) add('ddl');
|
||||
for (const rule of RULES) {
|
||||
if (kind === 'migration' && !rule.migrations) continue;
|
||||
if (!ruleApplies(rule, kind)) continue;
|
||||
if (rule.name === 'pragma' && pragmaAllowed(file)) continue;
|
||||
if (rule.test(literal, inSqlTag)) add(rule.name);
|
||||
if (rule.test(literal, inSqlTag) && !marked(rule, node)) add(rule.name);
|
||||
}
|
||||
};
|
||||
const like = RULES.find((rule) => rule.name === 'like');
|
||||
|
||||
const visitPerEngine = (object, inSqlTag) => {
|
||||
for (const property of object.properties) {
|
||||
const name = ts.isPropertyAssignment(property) && ts.isIdentifier(property.name) ? property.name.text : null;
|
||||
if (name === 'sqlite' || name === 'postgres') visit(property.initializer, inSqlTag, name);
|
||||
else visit(property, inSqlTag, null);
|
||||
}
|
||||
};
|
||||
|
||||
const visit = (node, inSqlTag) => {
|
||||
const visit = (node, inSqlTag, engine) => {
|
||||
if (ts.isTaggedTemplateExpression(node) && isSqlTag(node)) {
|
||||
ts.forEachChild(node, (child) => visit(child, true));
|
||||
ts.forEachChild(node, (child) => visit(child, true, engine));
|
||||
return;
|
||||
}
|
||||
if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) {
|
||||
checkText(node.text, inSqlTag);
|
||||
} else if (ts.isTemplateExpression(node)) {
|
||||
// The literal parts only: an interpolated value is code, scanned on its own.
|
||||
checkText([node.head.text, ...node.templateSpans.map((span) => span.literal.text)].join(' '), inSqlTag);
|
||||
if (postCut && engine === null && ts.isCallExpression(node)) {
|
||||
const name = calleeName(node);
|
||||
if (SQLITE_ONLY_HELPERS.has(name)) add('ddl');
|
||||
if (BEST_EFFORT_HELPERS.has(name)) add('best-effort');
|
||||
// A plain string would hand Postgres the SQLite spelling of the column.
|
||||
if (name === 'addColumnIfMissing' && !isPerEngineObject(node.arguments[3])) add('ddl');
|
||||
if (ENGINE_DDL_CALLS.has(name)) {
|
||||
visit(node.expression, inSqlTag, null);
|
||||
for (const argument of node.arguments) {
|
||||
if (!isPerEngineObject(argument)) {
|
||||
visit(argument, inSqlTag, null);
|
||||
continue;
|
||||
}
|
||||
if (name === 'engineDdl') {
|
||||
const problems = sqliteMemberProblems(engineMember(argument, 'sqlite').initializer);
|
||||
for (let i = 0; i < problems; i++) add('sqlite-member');
|
||||
if (emptyPostgresUnexplained(argument, text)) add('empty-postgres');
|
||||
}
|
||||
visitPerEngine(argument, inSqlTag);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
const literal = literalText(node);
|
||||
if (literal !== null) {
|
||||
checkText(literal, node, inSqlTag, engine);
|
||||
} else if (
|
||||
engine === null &&
|
||||
ruleApplies(like, kind) &&
|
||||
(ts.isPropertyAssignment(node) || ts.isShorthandPropertyAssignment(node)) &&
|
||||
(ts.isIdentifier(node.name) || ts.isStringLiteral(node.name)) &&
|
||||
node.name.text === '$like' &&
|
||||
!marked(like, node)
|
||||
) {
|
||||
// MikroORM's `{ title: { $like: ... } }` is the same LIKE as in SQL text.
|
||||
add('like');
|
||||
} else if (ts.isPropertyAccessExpression(node) && node.name.text === 'insertId') {
|
||||
add(INSERT_ID_RULE);
|
||||
} else if (
|
||||
@@ -172,9 +519,9 @@ export function scanSource(file, text) {
|
||||
) {
|
||||
add(INSERT_ID_RULE);
|
||||
}
|
||||
ts.forEachChild(node, (child) => visit(child, inSqlTag));
|
||||
ts.forEachChild(node, (child) => visit(child, inSqlTag, engine));
|
||||
};
|
||||
visit(sf, false);
|
||||
visit(sf, false, null);
|
||||
return counts;
|
||||
}
|
||||
|
||||
@@ -194,10 +541,11 @@ export function scan(serverDir) {
|
||||
if (!existsSync(src) || !statSync(src).isDirectory()) {
|
||||
throw new Error(`src/ does not exist under ${serverDir}: the check would pass without looking at anything`);
|
||||
}
|
||||
const through = readThrough(serverDir);
|
||||
const result = {};
|
||||
for (const path of walk(src)) {
|
||||
const file = relative(serverDir, path).split('\\').join('/');
|
||||
const counts = scanSource(file, readFileSync(path, 'utf8'));
|
||||
const counts = scanSource(file, readFileSync(path, 'utf8'), through);
|
||||
if (Object.keys(counts).length > 0) result[file] = sortKeys(counts);
|
||||
}
|
||||
return sortKeys(result);
|
||||
@@ -225,6 +573,12 @@ export function readBaseline(path) {
|
||||
throw new Error(`scripts/dialect-baseline.json: ${file} must map rule names to counts`);
|
||||
}
|
||||
for (const [rule, n] of Object.entries(rules)) {
|
||||
if (POST_CUT_RULE_NAMES.has(rule)) {
|
||||
throw new Error(
|
||||
`scripts/dialect-baseline.json: ${file} holds an allowance for ${rule}, which a migration after the ` +
|
||||
"Postgres baseline's cut never gets",
|
||||
);
|
||||
}
|
||||
if (!RULE_NAMES.has(rule))
|
||||
throw new Error(`scripts/dialect-baseline.json: ${file} names an unknown rule "${rule}"`);
|
||||
if (!Number.isInteger(n) || n <= 0) {
|
||||
@@ -273,7 +627,11 @@ export function compare(baseline, counts) {
|
||||
|
||||
function adviceFor(rule) {
|
||||
if (rule === INSERT_ID_RULE) return "read the new id with .returning('id'); insertId is undefined on Postgres";
|
||||
return RULES.find((r) => r.name === rule).advice;
|
||||
return [...RULES, ...POST_CUT_RULES].find((r) => r.name === rule).advice;
|
||||
}
|
||||
|
||||
function labelFor(rule) {
|
||||
return POST_CUT_RULES.find((r) => r.name === rule)?.label ?? `SQLite-only ${rule} hit(s)`;
|
||||
}
|
||||
|
||||
function main(argv) {
|
||||
@@ -291,7 +649,7 @@ function main(argv) {
|
||||
|
||||
const { grown, stale } = compare(baseline, counts);
|
||||
for (const { file, rule, n, allowed } of grown) {
|
||||
console.error(`FAIL ${file}: ${n} SQLite-only ${rule} hit(s), ${allowed} allowed. ${adviceFor(rule)}.`);
|
||||
console.error(`FAIL ${file}: ${n} ${labelFor(rule)}, ${allowed} allowed. ${adviceFor(rule)}.`);
|
||||
}
|
||||
for (const { file, rule, allowed, now } of stale) {
|
||||
console.error(
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"counts": {}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
#!/usr/bin/env node
|
||||
/*
|
||||
* lint:engine-dispatch: code outside the dialect layer and the engine port
|
||||
* never asks which database it runs on.
|
||||
*
|
||||
* What differs between SQLite and Postgres has two homes: the SQL helpers in
|
||||
* src/db/dialect/ and the engine implementations in src/db/engine/ (the
|
||||
* driver, the schema bootstrap, maintenance, backups). Anywhere else, an
|
||||
* `isSqlite(`/`isPostgres(` check, an `instanceof` on a driver or platform
|
||||
* class, a comparison with a driver class (`config.driver !==
|
||||
* SharedSqliteDriver`), and any comparison with or `case` on an engine's name
|
||||
* (`db.engine === 'postgres'`, `engine !== 'sqlite'`, `case 'postgres':`) is
|
||||
* a branch a third engine would have to find by searching, so each file is
|
||||
* held to its entry in scripts/engine-dispatch-baseline.json and a file
|
||||
* without one holds none (scripts/lib/count-ratchet.mjs has the rules).
|
||||
* Comments do not count.
|
||||
*
|
||||
* npm run lint:engine-dispatch check against the baseline (CI)
|
||||
* npm run lint:engine-dispatch -- --update lower the counts; never raises or adds an entry
|
||||
*/
|
||||
import { cliMain, stripComments } from './lib/count-ratchet.mjs';
|
||||
|
||||
/** An engine's name as a string literal. */
|
||||
const ENGINE_NAME = String.raw`['"\x60](?:sqlite|postgres)['"\x60]`;
|
||||
|
||||
/** A driver or platform class of either engine: MikroORM's (PostgreSqlPlatform) and ours (SharedSqliteDriver). */
|
||||
const ENGINE_CLASS = String.raw`\b\w*(?:Sqlite|PostgreSql)\w*(?:Driver|Platform)\b`;
|
||||
|
||||
const DISPATCH = new RegExp(
|
||||
[
|
||||
String.raw`\bis(?:Sqlite|Postgres)\s*\(`,
|
||||
String.raw`\binstanceof\s+` + ENGINE_CLASS,
|
||||
// A comparison with an engine's name, whatever stands on the other side
|
||||
// (`db.engine === 'postgres'`, `engine !== 'sqlite'`, `'postgres' == kind`),
|
||||
// and a switch over it.
|
||||
String.raw`[!=]==?\s*` + ENGINE_NAME,
|
||||
ENGINE_NAME + String.raw`\s*[!=]==?`,
|
||||
String.raw`\bcase\s+` + ENGINE_NAME + String.raw`\s*:`,
|
||||
// A comparison with a driver or platform class.
|
||||
String.raw`[!=]==?\s*` + ENGINE_CLASS,
|
||||
ENGINE_CLASS + String.raw`\s*[!=]==?`,
|
||||
].join('|'),
|
||||
'g',
|
||||
);
|
||||
|
||||
/** Where an engine may be named: the dialect helpers and the engine port. */
|
||||
const ENGINE_HOMES = ['src/db/dialect/', 'src/db/engine/'];
|
||||
|
||||
/** The engine checks in one file's text, comments left out. */
|
||||
export function countEngineDispatch(text) {
|
||||
return stripComments(text).match(DISPATCH)?.length ?? 0;
|
||||
}
|
||||
|
||||
export const check = {
|
||||
name: 'engine-dispatch',
|
||||
script: 'lint:engine-dispatch',
|
||||
root: 'src',
|
||||
baseline: 'scripts/engine-dispatch-baseline.json',
|
||||
unit: 'engine check(s)',
|
||||
advice:
|
||||
'Move the check into src/db/dialect/ (SQL that differs per engine) or the DatabaseEngine in src/db/engine/ ' +
|
||||
'(anything else, such as a guard that refuses an engine), and call that helper here instead.',
|
||||
include: (file) => file.endsWith('.ts') && !ENGINE_HOMES.some((home) => file.startsWith(home)),
|
||||
count: (text) => countEngineDispatch(text),
|
||||
};
|
||||
|
||||
cliMain(check, import.meta.url);
|
||||
@@ -6,7 +6,7 @@
|
||||
"@typescript-eslint/no-unsafe-function-type": 1,
|
||||
"@typescript-eslint/no-unused-vars": 35,
|
||||
"no-await-in-loop": 556,
|
||||
"no-console": 232,
|
||||
"no-console": 231,
|
||||
"no-empty": 6
|
||||
},
|
||||
"suppressed": {
|
||||
@@ -16,12 +16,12 @@
|
||||
"no-misleading-character-class": 1
|
||||
},
|
||||
"tests": {
|
||||
"@typescript-eslint/no-explicit-any": 1553,
|
||||
"@typescript-eslint/no-explicit-any": 1549,
|
||||
"@typescript-eslint/no-non-null-assertion": 1747,
|
||||
"@typescript-eslint/no-require-imports": 25,
|
||||
"@typescript-eslint/no-unsafe-function-type": 7,
|
||||
"@typescript-eslint/no-unused-vars": 96,
|
||||
"no-await-in-loop": 452,
|
||||
"@typescript-eslint/no-unused-vars": 87,
|
||||
"no-await-in-loop": 451,
|
||||
"no-console": 18,
|
||||
"no-empty": 2,
|
||||
"no-useless-escape": 1,
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
/**
|
||||
* The text pass for Rule 1c of `generate-entities.ts` (the flag columns in
|
||||
* `BOOLEAN_COLUMNS`, rendered as `p.type(IntegerFlagType)`), kept in a file of
|
||||
* its own because the generator is at its size baseline.
|
||||
*
|
||||
* The renderer gives such a column's class field the type
|
||||
* `IType<boolean, number>`: it sees a boolean runtime type over a number
|
||||
* column and marks it ambiguous. The entity's field is a plain boolean
|
||||
* (`IntegerFlagType` converts on the way in and out), so the wrapper is taken
|
||||
* off here, as `fixJsonClassFieldTypes` does for a JSON column. A field that
|
||||
* already reads `boolean` is left alone; any other shape fails, naming it.
|
||||
*/
|
||||
|
||||
/** A property Rule 1c retyped: its entity class and its name. */
|
||||
interface FlagFixup {
|
||||
className: string;
|
||||
propName: string;
|
||||
}
|
||||
|
||||
export function fixFlagClassFieldTypes(source: string, fixups: readonly FlagFixup[]): string {
|
||||
let result = source;
|
||||
for (const { className, propName } of fixups) {
|
||||
const name = propName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
const field = new RegExp(`^([ \\t]*${name}[?!]?: )(?:IType<boolean\\s*,\\s*number>|boolean)(.*)$`, 'm');
|
||||
const match = field.exec(result);
|
||||
if (!match) {
|
||||
throw new Error(
|
||||
`generate-entities: fixFlagClassFieldTypes found no class field for "${className}.${propName}" ` +
|
||||
'typed IType<boolean, number> to simplify; check the renderer shape.',
|
||||
);
|
||||
}
|
||||
result = result.slice(0, match.index) + `${match[1]}boolean${match[2]}` + result.slice(match.index + match[0].length);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -63,6 +63,7 @@ import {
|
||||
type ImportsResolver,
|
||||
type Platform,
|
||||
} from '@mikro-orm/core';
|
||||
import { fixFlagClassFieldTypes } from './generate-entities-flags';
|
||||
import { EntityGenerator } from '@mikro-orm/entity-generator';
|
||||
import { Migrator } from '@mikro-orm/migrations';
|
||||
import { MikroORM as SqliteMikroORM } from '@mikro-orm/sqlite';
|
||||
@@ -292,26 +293,22 @@ export function RULE1b_markJsonColumns(metadata: EntityMetadata[]): JsonColumnFi
|
||||
return fixups;
|
||||
}
|
||||
|
||||
/** Rule 1c (metadata level): mark known boolean columns so they render `p.boolean()` (see BOOLEAN_COLUMNS above). */
|
||||
/** Rule 1c (metadata level): mark known boolean columns so they render `p.type(IntegerFlagType)` (BOOLEAN_COLUMNS). */
|
||||
export function RULE1c_markBooleanColumns(metadata: EntityMetadata[]): RetypedScalarFixup[] {
|
||||
const fixups: RetypedScalarFixup[] = [];
|
||||
for (const meta of metadata) {
|
||||
for (const prop of Object.values(meta.properties)) {
|
||||
if (prop.kind !== undefined && prop.kind !== ReferenceKind.SCALAR) continue;
|
||||
if (!BOOLEAN_COLUMNS.has(`${meta.tableName}.${prop.fieldNames[0]}`)) continue;
|
||||
prop.type = 'boolean';
|
||||
// `runtimeType` must move with `type` here too, for the same reason
|
||||
// Rule 1's doc comment gives: left at its introspected value
|
||||
// (`'number'`, SQLite has no BOOLEAN storage class), the mismatch
|
||||
// against `BooleanType`'s own runtime type ('boolean') would make
|
||||
// `breakdownOfIType` treat the property as ambiguous and wrap the
|
||||
// class field in `IType<number, boolean>` — confirmed by generating
|
||||
// the real schema before this fix, not assumed.
|
||||
// `IntegerFlagType` (src/db/types) stores 0/1 on both engines; `p.boolean()` is a boolean column on Postgres.
|
||||
// The renderer wraps the class field in `IType<boolean, number>` and adds `.columnType('INTEGER')`;
|
||||
// `fixFlagClassFieldTypes` and `stripRedundantColumnType` undo both.
|
||||
prop.type = 'IntegerFlagType';
|
||||
prop.runtimeType = 'boolean';
|
||||
// The introspected DB default is always the raw SQLite value (`0`/`1`,
|
||||
// a number, since SQLite has no boolean storage class either) —
|
||||
// coerce it to a real boolean so a `p.boolean()` column's `.default()`
|
||||
// renders `.default(false)`, not the now ill-typed `.default(0)`.
|
||||
// coerce it to a real boolean so the flag's `.default()` renders
|
||||
// `.default(false)`, not the now ill-typed `.default(0)`.
|
||||
if (typeof prop.default === 'number') prop.default = prop.default !== 0;
|
||||
if (typeof prop.defaultRaw === 'string' && /^-?\d+$/.test(prop.defaultRaw)) {
|
||||
prop.defaultRaw = prop.defaultRaw !== '0' ? 'true' : 'false';
|
||||
@@ -1222,7 +1219,9 @@ export interface RuleFixups {
|
||||
defaults: DefaultFixup[];
|
||||
timestamps: TimestampFixup[];
|
||||
jsonColumns: JsonColumnFixup[];
|
||||
/** Rule 1's + Rule 1b's + Rule 2's retyped scalars together — all three need the same `.columnType()` strip (see `stripRedundantColumnType`). */
|
||||
/** Rule 1c's flags, whose class field `fixFlagClassFieldTypes` turns back into a plain boolean. */
|
||||
flags: RetypedScalarFixup[];
|
||||
/** Rule 1's + Rule 1b's + Rule 1c's + Rule 2's retyped scalars together — all need the same `.columnType()` strip (see `stripRedundantColumnType`). */
|
||||
retypedScalars: RetypedScalarFixup[];
|
||||
/** Rule 10's repository-type markers — one per entity class. */
|
||||
repositoryMarkers: RepositoryTypeMarkerFixup[];
|
||||
@@ -1249,14 +1248,10 @@ export function applyRules(
|
||||
): RuleFixups {
|
||||
const retypedByRule1 = RULE1_fixUnknownScalarTypes(metadata);
|
||||
const jsonColumns = RULE1b_markJsonColumns(metadata);
|
||||
// Unlike Rule 1's/Rule 1b's retypes, a boolean column's own declaration
|
||||
// matches its raw INTEGER column type cleanly on SQLite (BooleanType's
|
||||
// getColumnType() returns the same spelling needsExplicitColumnType()
|
||||
// compares against) — confirmed by generating the real schema: no stray
|
||||
// `.columnType()` appears, so RULE1c's fixups do NOT belong in
|
||||
// `retypedScalars` (stripRedundantColumnType's "found no .columnType() to
|
||||
// strip" throw catches this immediately if that ever stops being true).
|
||||
RULE1c_markBooleanColumns(metadata);
|
||||
// A flag picks up a `.columnType('INTEGER')` like Rule 1's retypes (the
|
||||
// renderer cannot tell that `IntegerFlagType` already declares INTEGER), so
|
||||
// its fixups join `retypedScalars`, and its class field needs its own pass.
|
||||
const flags = RULE1c_markBooleanColumns(metadata);
|
||||
RULE1d_fixNaNNumericDefaults(metadata);
|
||||
const timestamps = RULE2_datetimeToDbTimestampType(metadata);
|
||||
RULE3_integerPkAutoincrement(metadata);
|
||||
@@ -1289,7 +1284,8 @@ export function applyRules(
|
||||
defaults,
|
||||
timestamps,
|
||||
jsonColumns,
|
||||
retypedScalars: [...retypedByRule1, ...timestamps, ...jsonColumns],
|
||||
flags,
|
||||
retypedScalars: [...retypedByRule1, ...timestamps, ...jsonColumns, ...flags],
|
||||
repositoryMarkers,
|
||||
referencedColumns,
|
||||
checkExpressions,
|
||||
@@ -1400,6 +1396,7 @@ export async function collectForeignKeyDeleteRules(
|
||||
// ---------------------------------------------------------------------------
|
||||
export const onImport: ImportsResolver = (alias) => {
|
||||
if (alias === 'DbTimestampType') return { path: '../types', name: 'DbTimestampType' };
|
||||
if (alias === 'IntegerFlagType') return { path: '../types', name: 'IntegerFlagType' };
|
||||
if (alias.endsWith('Repository')) {
|
||||
const entityName = alias.slice(0, -'Repository'.length);
|
||||
return { path: `../repositories/${entityName}.repository`, name: alias };
|
||||
@@ -1901,6 +1898,7 @@ export function applyTextPasses(source: string, fixups: RuleFixups): string {
|
||||
result = stripRedundantColumnType(result, fixups.retypedScalars);
|
||||
result = injectJsonTypeParams(result, fixups.jsonColumns);
|
||||
result = fixJsonClassFieldTypes(result, fixups.jsonColumns);
|
||||
result = fixFlagClassFieldTypes(result, fixups.flags);
|
||||
result = injectJsonInterfaces(result, fixups.jsonColumns);
|
||||
result = removeUnusedCoreImportIfUnused(result, 'IType');
|
||||
result = stripHiddenTypeAnnotation(result);
|
||||
@@ -2001,6 +1999,7 @@ export async function generateEntities(): Promise<GenerateResult> {
|
||||
defaults: [],
|
||||
timestamps: [],
|
||||
jsonColumns: [],
|
||||
flags: [],
|
||||
retypedScalars: [],
|
||||
repositoryMarkers: [],
|
||||
referencedColumns: [],
|
||||
@@ -2039,6 +2038,7 @@ export async function generateEntities(): Promise<GenerateResult> {
|
||||
defaults: fixups.defaults.filter((f) => f.className === className),
|
||||
timestamps: fixups.timestamps.filter((f) => f.className === className),
|
||||
jsonColumns: fixups.jsonColumns.filter((f) => f.className === className),
|
||||
flags: fixups.flags.filter((f) => f.className === className),
|
||||
retypedScalars: fixups.retypedScalars.filter((f) => f.className === className),
|
||||
repositoryMarkers: fixups.repositoryMarkers.filter((f) => f.className === className),
|
||||
referencedColumns: fixups.referencedColumns.filter((f) => f.className === className),
|
||||
|
||||
@@ -0,0 +1,328 @@
|
||||
/**
|
||||
* Generates the Postgres baseline: the schema a fresh Postgres database starts
|
||||
* from (src/db/engine/postgres/baseline.ts says how a boot uses it).
|
||||
*
|
||||
* The entities describe the migrated SQLite schema and are pinned to it
|
||||
* (`check:entities`), so the baseline is MikroORM's schema generator over the
|
||||
* entities, for the Postgres platform, after the adjustments every Postgres
|
||||
* schema in this repository shares (src/db/engine/postgres/schema-adjust.ts):
|
||||
* TEXT timestamps, portable defaults, the `nocase` collation. Unlike the
|
||||
* probe's schema it keeps the foreign keys. No database is needed: the
|
||||
* generator reads only the metadata and the platform.
|
||||
*
|
||||
* The baseline stands for every migration up to the newest one when it was
|
||||
* generated (`through`). Once a migration lands after it, the baseline is
|
||||
* frozen like a shipped migration: the newer migration runs on Postgres
|
||||
* through the migrator, written through `engineDdl` with the Postgres side
|
||||
* from `npm run gen:pg-migration`, and `--check` verifies the manifest, that
|
||||
* every SQLite trigger still has its port, and lists the migrations after the
|
||||
* cut. Rewriting a frozen baseline moves the cut, so the default mode refuses
|
||||
* it and only `--move-cut` does it. That is safe because lint:dialect holds
|
||||
* every migration after POSTGRES_FIRST_CUT to the post-cut rules wherever the
|
||||
* cut stands, so an install created from the old baseline still reaches the
|
||||
* same schema through the migrator.
|
||||
*
|
||||
* Usage:
|
||||
* node --import tsx scripts/generate-pg-baseline.ts # rewrite server/assets/postgres/ (not while frozen)
|
||||
* node --import tsx scripts/generate-pg-baseline.ts --move-cut # rewrite it over the migrations after the cut
|
||||
* node --import tsx scripts/generate-pg-baseline.ts --check # exit 1 when it drifted (CI)
|
||||
*/
|
||||
import {
|
||||
baselineMatches,
|
||||
readPostgresBaseline,
|
||||
writePostgresBaseline,
|
||||
type PostgresBaseline,
|
||||
} from '../src/db/engine/postgres/baseline';
|
||||
import { POSTGRES_TRIGGERS } from '../src/db/engine/postgres/postgres-triggers';
|
||||
import { applyPostgresColumnAdjustments, NOCASE_COLLATION_SQL } from '../src/db/engine/postgres/schema-adjust';
|
||||
import { splitStatements } from '../src/db/engine/postgres/sql-split';
|
||||
import { ALL_ENTITIES } from '../src/db/entities';
|
||||
import { knownMigrationNames } from '../src/db/known-migrations';
|
||||
import { migrateTempDb, tempDbPath } from './generate-entities';
|
||||
import { MikroORM } from '@mikro-orm/postgresql';
|
||||
|
||||
import Database from 'better-sqlite3';
|
||||
import fs from 'node:fs';
|
||||
|
||||
/** What one pass over the migrated SQLite database yields: the baseline, and the triggers the migrations leave there. */
|
||||
interface BaselinePass {
|
||||
baseline: PostgresBaseline;
|
||||
sqliteTriggers: string[];
|
||||
}
|
||||
|
||||
/** The baseline the entities and the migrations on disk describe now, from one migration of the SQLite database. */
|
||||
async function generateBaseline(known: Set<string> = knownMigrationNames()): Promise<BaselinePass> {
|
||||
const migrations = [...known].sort();
|
||||
const through = migrations.at(-1);
|
||||
if (!through) throw new Error('no migrations found');
|
||||
const orm = await MikroORM.init({
|
||||
clientUrl: 'postgresql://generator@localhost/trek',
|
||||
entities: [...ALL_ENTITIES],
|
||||
discovery: { warnWhenNoEntities: false },
|
||||
});
|
||||
try {
|
||||
for (const meta of orm.getMetadata().getAll().values()) applyPostgresColumnAdjustments(meta.props);
|
||||
const migrated = await readMigratedSqlite();
|
||||
const statements = [
|
||||
NOCASE_COLLATION_SQL,
|
||||
...splitStatements(await orm.schema.getCreateSchemaSQL({ wrap: false })),
|
||||
...migrated.tables.flatMap((table) => rowStatements(table.name, table.rows)),
|
||||
...Object.values(POSTGRES_TRIGGERS).flat(),
|
||||
];
|
||||
return { baseline: { through, migrations, statements }, sqliteTriggers: migrated.triggers };
|
||||
} finally {
|
||||
await orm.close();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The migrations after the committed baseline's cut, in order: what a boot
|
||||
* runs on Postgres through the migrator, each written through `engineDdl`
|
||||
* (lint:dialect) and held by PARITY-PG. While there is one, the baseline is
|
||||
* frozen. `known` is every migration on disk.
|
||||
*/
|
||||
export function postCutMigrations(committed: PostgresBaseline, known: readonly string[]): string[] {
|
||||
return known.filter((name) => name > committed.through).sort();
|
||||
}
|
||||
|
||||
/**
|
||||
* What `--check` holds, as the problems it finds, each with what to do about
|
||||
* it. Every manifest must name migrations that exist and every migration up to
|
||||
* `through`. While no migration is newer than the committed baseline
|
||||
* (`through` matches), the baseline is not frozen: it must be exactly what the
|
||||
* entities generate, and each SQLite trigger needs a port. Once a newer
|
||||
* migration lands, the baseline is frozen: Postgres reaches the newer schema
|
||||
* through that migration, so only the manifest is checked here, and
|
||||
* `checkMode` lists the migrations after the cut.
|
||||
*/
|
||||
export function checkBaseline(
|
||||
committed: PostgresBaseline,
|
||||
generated: PostgresBaseline,
|
||||
matches: boolean,
|
||||
sqliteTriggers: readonly string[],
|
||||
): string[] {
|
||||
const known = new Set(generated.migrations);
|
||||
const problems: string[] = [];
|
||||
const missing = committed.migrations.filter((name) => !known.has(name));
|
||||
if (missing.length > 0) {
|
||||
problems.push(
|
||||
`the manifest names migrations that are not in src/db/migrations: ${missing.join(', ')}. ` +
|
||||
'A migration that has shipped is never renamed or deleted; restore it under its name.',
|
||||
);
|
||||
}
|
||||
const unlisted = generated.migrations.filter(
|
||||
(name) => name <= committed.through && !committed.migrations.includes(name),
|
||||
);
|
||||
if (unlisted.length > 0) {
|
||||
problems.push(
|
||||
`migrations that sort before the cut (${committed.through}) are not in the manifest: ${unlisted.join(', ')}. ` +
|
||||
`Postgres would never run them; give each a name that sorts after ${generated.through}.`,
|
||||
);
|
||||
}
|
||||
const frozen = committed.through !== generated.through;
|
||||
if (!frozen && !matches) {
|
||||
problems.push(
|
||||
'server/assets/postgres/ is not what the entities, POSTGRES_TRIGGERS and the reference rows the migrations ' +
|
||||
'insert generate now, and no migration follows its cut: run npm run gen:pg-baseline and commit ' +
|
||||
'server/assets/postgres/.',
|
||||
);
|
||||
}
|
||||
// Frozen or not: the entities carry no triggers, so this is the only check
|
||||
// that a trigger a migration leaves on SQLite exists on Postgres too.
|
||||
problems.push(...triggerPortProblems(sqliteTriggers, Object.keys(POSTGRES_TRIGGERS), frozen));
|
||||
return problems;
|
||||
}
|
||||
|
||||
/**
|
||||
* Why the default mode refuses to rewrite the baseline, or null when it may:
|
||||
* the migrations after the committed cut. Rewriting the baseline would move
|
||||
* the cut over them, which only `--move-cut` does.
|
||||
*/
|
||||
export function cutMoveRefusal(committed: PostgresBaseline, known: readonly string[]): string | null {
|
||||
const after = postCutMigrations(committed, known);
|
||||
if (after.length === 0) return null;
|
||||
return (
|
||||
`the baseline is frozen at ${committed.through}, and ${after.length} migration(s) follow its cut: ` +
|
||||
`${after.join(', ')}. A Postgres install created from it reaches them through the migrator, so the baseline ` +
|
||||
'is not regenerated for them: write their schema change through engineDdl with the postgres member that npm ' +
|
||||
'run gen:pg-migration prints (server/CLAUDE.md, SQL dialect, Migrations). To fold them into a new baseline on ' +
|
||||
'purpose, run npm run gen:pg-baseline -- --move-cut.'
|
||||
);
|
||||
}
|
||||
|
||||
/** Migration bookkeeping: the baseline's manifest stands for it on Postgres. */
|
||||
const BOOKKEEPING_TABLES = new Set(['mikro_orm_migrations', 'migrations', 'schema_version']);
|
||||
|
||||
type Row = Record<string, unknown>;
|
||||
|
||||
/** What the migrations leave in a SQLite database: its triggers, and the rows they insert, table by table in creation order. */
|
||||
interface MigratedSchema {
|
||||
triggers: string[];
|
||||
tables: Array<{ name: string; rows: Row[] }>;
|
||||
}
|
||||
|
||||
/** The tables and triggers of a SQLite database in creation order, each as its type and name. */
|
||||
function listSchemaObjects(conn: Database.Database): Array<{ type: string; name: string }> {
|
||||
return conn
|
||||
.prepare(
|
||||
"select type, name from sqlite_master where type in ('table', 'trigger') and name not like 'sqlite_%' order by rowid",
|
||||
)
|
||||
.all() as Array<{ type: string; name: string }>;
|
||||
}
|
||||
|
||||
/** Reads a migrated SQLite database, read-only. */
|
||||
function readMigratedSchema(dbPath: string): MigratedSchema {
|
||||
const conn = new Database(dbPath, { readonly: true });
|
||||
try {
|
||||
const objects = listSchemaObjects(conn);
|
||||
const tables = objects
|
||||
.filter((object) => object.type === 'table' && !BOOKKEEPING_TABLES.has(object.name))
|
||||
.map((object) => ({
|
||||
name: object.name,
|
||||
rows: conn.prepare(`select * from "${object.name}" order by rowid`).all() as Row[],
|
||||
}))
|
||||
.filter((table) => table.rows.length > 0);
|
||||
const triggers = objects
|
||||
.filter((object) => object.type === 'trigger')
|
||||
.map((object) => object.name)
|
||||
.sort();
|
||||
return { triggers, tables };
|
||||
} finally {
|
||||
conn.close();
|
||||
}
|
||||
}
|
||||
|
||||
/** Migrates a temporary SQLite database and reads what the migrations leave in it; the file is removed afterwards. */
|
||||
async function readMigratedSqlite(): Promise<MigratedSchema> {
|
||||
const dbPath = tempDbPath();
|
||||
try {
|
||||
await migrateTempDb(dbPath);
|
||||
return readMigratedSchema(dbPath);
|
||||
} finally {
|
||||
fs.rmSync(dbPath, { force: true });
|
||||
}
|
||||
}
|
||||
|
||||
/** A value as a Postgres literal the column's own type takes in: quoted text, which Postgres casts on insert. */
|
||||
function literal(value: unknown): string {
|
||||
if (value === null || value === undefined) return 'NULL';
|
||||
if (Buffer.isBuffer(value)) throw new Error('a migration inserted binary data, which the baseline cannot carry');
|
||||
return `'${String(value).replace(/'/g, "''")}'`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The rows a migration inserted into `table` (reference data such as the tour
|
||||
* types and the provider catalogues), as the statements that put them in a
|
||||
* Postgres database the baseline creates, then move the table's id sequence,
|
||||
* if it has one, past them. A migration up to the cut never runs on Postgres,
|
||||
* so without these the database would start without what every SQLite
|
||||
* install has before its first seeder.
|
||||
*/
|
||||
export function rowStatements(table: string, rows: readonly Row[]): string[] {
|
||||
if (rows.length === 0) return [];
|
||||
const columns = Object.keys(rows[0]);
|
||||
const values = rows.map((row) => `(${columns.map((column) => literal(row[column])).join(', ')})`);
|
||||
const statements = [
|
||||
`insert into "${table}" (${columns.map((c) => `"${c}"`).join(', ')}) values ${values.join(', ')}`,
|
||||
];
|
||||
if (rows.every((row) => typeof row.id === 'number')) {
|
||||
statements.push(
|
||||
`select setval(seq, greatest(max_id, 1)) from (select pg_get_serial_sequence('"${table}"', 'id') as seq, ` +
|
||||
`max("id") as max_id from "${table}") ids where seq is not null`,
|
||||
);
|
||||
}
|
||||
return statements;
|
||||
}
|
||||
|
||||
/**
|
||||
* The SQLite triggers without a Postgres port in `POSTGRES_TRIGGERS`, and the
|
||||
* ports whose trigger is gone. The entities carry no triggers, so this is
|
||||
* what keeps the hand-written ports level with the migrations. `frozen` says
|
||||
* a migration follows the baseline's cut, so the fix goes into that
|
||||
* migration rather than into a regenerated baseline.
|
||||
*/
|
||||
export function triggerPortProblems(
|
||||
sqliteTriggers: readonly string[],
|
||||
ported: readonly string[],
|
||||
frozen = false,
|
||||
): string[] {
|
||||
const problems: string[] = [];
|
||||
const missing = sqliteTriggers.filter((name) => !ported.includes(name));
|
||||
if (missing.length > 0) {
|
||||
problems.push(
|
||||
frozen
|
||||
? `SQLite triggers without a Postgres port in POSTGRES_TRIGGERS: ${missing.join(', ')}. A migration after ` +
|
||||
"the baseline's cut created them, and a trigger after the cut has no Postgres port (server/CLAUDE.md, " +
|
||||
'SQL dialect, Migrations): take it out of the migration and do its work in the repository instead.'
|
||||
: `SQLite triggers without a Postgres port in POSTGRES_TRIGGERS: ${missing.join(', ')}. Add each one's ` +
|
||||
'function and trigger to src/db/engine/postgres/postgres-triggers.ts, then run npm run gen:pg-baseline.',
|
||||
);
|
||||
}
|
||||
const stale = ported.filter((name) => !sqliteTriggers.includes(name));
|
||||
if (stale.length > 0) {
|
||||
problems.push(
|
||||
frozen
|
||||
? `POSTGRES_TRIGGERS ports triggers the migrations no longer create: ${stale.join(', ')}. A migration ` +
|
||||
"after the baseline's cut dropped them on SQLite: drop them on Postgres in the postgres member of its " +
|
||||
'engineDdl call too, and remove them from src/db/engine/postgres/postgres-triggers.ts.'
|
||||
: `POSTGRES_TRIGGERS ports triggers the migrations no longer create: ${stale.join(', ')}. Remove them from ` +
|
||||
'src/db/engine/postgres/postgres-triggers.ts, then run npm run gen:pg-baseline.',
|
||||
);
|
||||
}
|
||||
return problems;
|
||||
}
|
||||
|
||||
/**
|
||||
* The default mode: writes the baseline the entities and the migrations
|
||||
* describe, refused while the committed one is frozen unless `moveCut`.
|
||||
*/
|
||||
async function writeMode(moveCut: boolean): Promise<void> {
|
||||
const known = [...knownMigrationNames()].sort();
|
||||
const refusal = cutMoveRefusal(readPostgresBaseline(), known);
|
||||
if (refusal && !moveCut) {
|
||||
console.error(`[generate-pg-baseline] ${refusal}`);
|
||||
process.exit(1);
|
||||
}
|
||||
const { baseline } = await generateBaseline();
|
||||
writePostgresBaseline(baseline);
|
||||
console.log(`[generate-pg-baseline] wrote ${baseline.statements.length} statements through ${baseline.through}`);
|
||||
}
|
||||
|
||||
/** `--check` (CI): exits 1, naming every problem, when the committed baseline has drifted. */
|
||||
async function checkMode(): Promise<void> {
|
||||
const { baseline: generated, sqliteTriggers } = await generateBaseline();
|
||||
const committed = readPostgresBaseline();
|
||||
const problems = checkBaseline(committed, generated, baselineMatches(generated), sqliteTriggers);
|
||||
const after = postCutMigrations(committed, generated.migrations);
|
||||
if (after.length > 0) {
|
||||
// Frozen: say so, and what keeps those migrations right on Postgres, whether or not the manifest passed.
|
||||
console.log(
|
||||
`[generate-pg-baseline] --check: the baseline is frozen at ${committed.through}. ${after.length} migration(s) ` +
|
||||
`run on Postgres after its cut, through the migrator: ${after.join(', ')}. Each writes its schema change ` +
|
||||
'through engineDdl (lint:dialect) and PARITY-PG in the Postgres lane holds the result against the entities; ' +
|
||||
'the baseline is not regenerated for them.',
|
||||
);
|
||||
}
|
||||
if (problems.length > 0) {
|
||||
for (const problem of problems) console.error(`[generate-pg-baseline] ${problem}`);
|
||||
process.exit(1);
|
||||
}
|
||||
console.log(
|
||||
after.length > 0
|
||||
? `[generate-pg-baseline] --check: the manifest lists every migration through ${committed.through}`
|
||||
: '[generate-pg-baseline] --check: the Postgres baseline matches the entities and the migrations',
|
||||
);
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const args = process.argv.slice(2);
|
||||
if (args.includes('--check')) await checkMode();
|
||||
else await writeMode(args.includes('--move-cut'));
|
||||
}
|
||||
|
||||
if (require.main === module) {
|
||||
main().catch((error: unknown) => {
|
||||
console.error(error);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
/**
|
||||
* Prints the Postgres side of a new migration: the `postgres` array of its
|
||||
* `engineDdl(this, { sqlite: [...], postgres: [...] })` call
|
||||
* (src/db/migration-utils.ts).
|
||||
*
|
||||
* A migration after the Postgres baseline's cut runs on both engines, and the
|
||||
* Postgres result has to be exactly what MikroORM generates from the entities
|
||||
* (PARITY-PG). So the Postgres DDL is not written by hand: this script builds
|
||||
* a scratch database the way a boot builds an empty one (the baseline, then
|
||||
* every migration after its cut) but stops before the target migration, asks
|
||||
* MikroORM's comparator what still separates it from the entities, drops what
|
||||
* changes nothing by the rules PARITY-PG uses
|
||||
* (src/db/engine/postgres/entity-schema-diff.ts), and prints the rest.
|
||||
*
|
||||
* The routine: change the entities, write the migration's SQLite statements
|
||||
* as `engineDdl(this, { sqlite: [...], postgres: [] })`, run this, paste what
|
||||
* it prints as the `postgres` array. Nothing is written to the repository.
|
||||
*
|
||||
* It needs a Postgres server where it may create and drop a database:
|
||||
* TREK_TEST_DB_URL or --url. The scratch database is dropped again however
|
||||
* the run ends.
|
||||
*
|
||||
* Usage:
|
||||
* npm run gen:pg-migration # the newest migration
|
||||
* npm run gen:pg-migration -- --migration=<ClassName> # another one
|
||||
* npm run gen:pg-migration -- --url=postgres://user:pw@host:5432/postgres
|
||||
*/
|
||||
import { buildOrmConfig } from '../src/db/engine';
|
||||
import { readPostgresBaseline } from '../src/db/engine/postgres/baseline';
|
||||
import { diffAgainstEntities, remainingStatements } from '../src/db/engine/postgres/entity-schema-diff';
|
||||
import { PostgresEngine } from '../src/db/engine/postgres/postgres-engine';
|
||||
import { bootstrapPostgresSchema, defaultPostgresBootstrapDeps } from '../src/db/engine/postgres/schema-bootstrap';
|
||||
import { knownMigrationNames } from '../src/db/known-migrations';
|
||||
import { NO_SAFETY_NET } from '../src/db/legacy-baseline';
|
||||
import { MikroORM, type MigrationObject } from '@mikro-orm/core';
|
||||
import { MikroORM as PostgresMikroORM } from '@mikro-orm/postgresql';
|
||||
|
||||
import { randomBytes } from 'node:crypto';
|
||||
import path from 'node:path';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
|
||||
const MIGRATIONS_DIR = path.join(__dirname, '..', 'src', 'db', 'migrations');
|
||||
const TAG = '[gen:pg-migration]';
|
||||
|
||||
/** The scratch databases this script creates: a prefix nothing else uses. */
|
||||
export const SCRATCH_PREFIX = 'trek_gen_pg_migration_';
|
||||
|
||||
/** The migration the run is for: `--migration` (a full class name), else the newest one. */
|
||||
export function pickTarget(known: readonly string[], requested: string | undefined): string {
|
||||
const sorted = [...known].sort();
|
||||
if (requested === undefined) {
|
||||
const newest = sorted.at(-1);
|
||||
if (!newest) throw new Error('no migrations found');
|
||||
return newest;
|
||||
}
|
||||
if (!sorted.includes(requested)) {
|
||||
throw new Error(
|
||||
`--migration=${requested} names no migration in src/db/migrations; pass the class name, e.g. ${sorted.at(-1)}`,
|
||||
);
|
||||
}
|
||||
return requested;
|
||||
}
|
||||
|
||||
/** The migrations a boot runs on Postgres after the baseline's cut and before `target`, in order. */
|
||||
export function postCutBefore(known: readonly string[], through: string, target: string): string[] {
|
||||
return [...known].filter((name) => name > through && name < target).sort();
|
||||
}
|
||||
|
||||
/**
|
||||
* One statement as a TypeScript string literal, in the quote that needs fewer
|
||||
* escapes (Prettier's choice, so the pasted array passes lint:format as it is).
|
||||
*/
|
||||
export function quote(statement: string): string {
|
||||
const mark = statement.split("'").length > statement.split('"').length ? '"' : "'";
|
||||
const escaped = statement.replace(/\\/g, '\\\\').replace(/\n/g, '\\n').split(mark).join(`\\${mark}`);
|
||||
return `${mark}${escaped}${mark}`;
|
||||
}
|
||||
|
||||
/** The statements as the `postgres` member of an engineDdl call, ready to paste. */
|
||||
export function renderPostgresArray(statements: readonly string[]): string {
|
||||
if (statements.length === 0) return 'postgres: [],';
|
||||
return ['postgres: [', ...statements.map((statement) => ` ${quote(statement)},`), '],'].join('\n');
|
||||
}
|
||||
|
||||
/** `adminUrl` pointed at `database`, everything else (credentials, host, sslmode) kept. */
|
||||
export function databaseUrl(adminUrl: string, database: string): string {
|
||||
const url = new URL(adminUrl);
|
||||
url.pathname = `/${database}`;
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
/** Runs one statement on the admin database, outside any transaction (CREATE and DROP DATABASE refuse one). */
|
||||
async function onAdmin(adminUrl: string, sql: string): Promise<void> {
|
||||
const orm = await PostgresMikroORM.init({
|
||||
clientUrl: adminUrl,
|
||||
entities: [],
|
||||
discovery: { warnWhenNoEntities: false },
|
||||
pool: { min: 0, max: 1 },
|
||||
});
|
||||
try {
|
||||
await orm.em.getConnection().execute(sql, [], 'run');
|
||||
} finally {
|
||||
await orm.close(true);
|
||||
}
|
||||
}
|
||||
|
||||
/** The migration classes a boot would run, loaded from their files. */
|
||||
async function loadMigrations(names: readonly string[]): Promise<MigrationObject[]> {
|
||||
return Promise.all(
|
||||
names.map(async (name) => {
|
||||
const module = (await import(pathToFileURL(path.join(MIGRATIONS_DIR, `${name}.ts`)).href)) as Record<
|
||||
string,
|
||||
unknown
|
||||
>;
|
||||
const migrationClass = module[name];
|
||||
if (typeof migrationClass !== 'function') throw new Error(`${name}.ts does not export the class ${name}`);
|
||||
return { name, class: migrationClass as MigrationObject['class'] };
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Brings the empty database `url` names to the schema a boot leaves before
|
||||
* `target`: the engine's own bootstrap (baseline, then the migrations after
|
||||
* its cut), offered only the migrations in `before`, with no pre-migrate copy.
|
||||
*/
|
||||
async function bootstrapBefore(url: string, before: readonly string[]): Promise<void> {
|
||||
const config = buildOrmConfig(new PostgresEngine({ engine: 'postgres', url, poolMax: 2 }));
|
||||
const orm = await MikroORM.init({
|
||||
...config,
|
||||
// As tests/postgres/build-template.ts: the bootstrap runs SQL, which needs no entity metadata.
|
||||
entities: [],
|
||||
entitiesTs: [],
|
||||
discovery: { warnWhenNoEntities: false },
|
||||
migrations: { ...config.migrations, silent: true, migrationsList: await loadMigrations(before) },
|
||||
});
|
||||
try {
|
||||
await bootstrapPostgresSchema(orm, {
|
||||
...defaultPostgresBootstrapDeps(url),
|
||||
safetyNet: NO_SAFETY_NET,
|
||||
// A scratch database of its own: a SQLite install in the developer's data directory is beside the point.
|
||||
sqliteLeftBehind: () => null,
|
||||
});
|
||||
} finally {
|
||||
await orm.close(true);
|
||||
}
|
||||
}
|
||||
|
||||
function argument(argv: readonly string[], name: string): string | undefined {
|
||||
const prefix = `--${name}=`;
|
||||
return argv.find((arg) => arg.startsWith(prefix))?.slice(prefix.length);
|
||||
}
|
||||
|
||||
async function main(argv: readonly string[]): Promise<void> {
|
||||
const adminUrl = argument(argv, 'url') ?? process.env.TREK_TEST_DB_URL;
|
||||
if (!adminUrl) {
|
||||
throw new Error(
|
||||
'needs a Postgres server where it may create and drop a scratch database: set TREK_TEST_DB_URL or pass ' +
|
||||
'--url=postgres://user:password@host:5432/postgres (locally: docker run --rm -p 5432:5432 ' +
|
||||
'-e POSTGRES_PASSWORD=trek postgres:17).',
|
||||
);
|
||||
}
|
||||
const known = [...knownMigrationNames()].sort();
|
||||
const target = pickTarget(known, argument(argv, 'migration'));
|
||||
const { through } = readPostgresBaseline();
|
||||
const before = postCutBefore(known, through, target);
|
||||
const scratch = `${SCRATCH_PREFIX}${randomBytes(6).toString('hex')}`;
|
||||
const scratchUrl = databaseUrl(adminUrl, scratch);
|
||||
|
||||
console.error(`${TAG} target ${target}; the Postgres baseline stands for everything through ${through}`);
|
||||
if (target <= through) {
|
||||
console.error(`${TAG} ${target} is at or before the cut: it never runs on Postgres. Comparing the baseline alone.`);
|
||||
} else {
|
||||
console.error(`${TAG} building ${scratch}: the baseline, then ${before.length} migration(s) after the cut`);
|
||||
}
|
||||
|
||||
await onAdmin(adminUrl, `create database "${scratch}"`);
|
||||
try {
|
||||
await bootstrapBefore(scratchUrl, before);
|
||||
const diff = await diffAgainstEntities(scratchUrl);
|
||||
const statements = remainingStatements(diff);
|
||||
if (!diff.spellingHolds) {
|
||||
console.error(
|
||||
`${TAG} some default or check statements change the catalogue, so they are part of the change and printed below.`,
|
||||
);
|
||||
}
|
||||
if (statements.some((statement) => statement.includes('?'))) {
|
||||
console.error(`${TAG} a statement holds a "?", which the migrator would read as a parameter: rewrite it.`);
|
||||
}
|
||||
if (statements.length === 0) {
|
||||
console.error(
|
||||
target <= through
|
||||
? `${TAG} nothing to do: the baseline matches the entities.`
|
||||
: `${TAG} nothing to do: Postgres already matches the entities without ${target}; ` +
|
||||
'its engineDdl postgres array stays empty.',
|
||||
);
|
||||
} else if (target <= through) {
|
||||
console.error(
|
||||
`${TAG} the baseline differs from the entities by the statements below; npm run check:pg-baseline says why.`,
|
||||
);
|
||||
} else {
|
||||
console.error(`${TAG} paste this as the postgres array of the engineDdl call in ${target}:`);
|
||||
}
|
||||
console.log(renderPostgresArray(statements));
|
||||
} finally {
|
||||
await onAdmin(adminUrl, `drop database if exists "${scratch}" with (force)`);
|
||||
}
|
||||
}
|
||||
|
||||
if (require.main === module) {
|
||||
main(process.argv.slice(2)).catch((error: unknown) => {
|
||||
console.error(`${TAG} ${error instanceof Error ? error.message : String(error)}`);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
/**
|
||||
* The database side of the encryption key rotation (`migrate-encryption.ts`):
|
||||
* the statements it runs, on the SQLite file through better-sqlite3 or on a
|
||||
* Postgres database through the server's MikroORM connection, and where the
|
||||
* Postgres path finds the server's code. Kept beside the command so that one
|
||||
* stays within the size limit; the image copies both.
|
||||
*/
|
||||
import type { EntityManager } from '@mikro-orm/core';
|
||||
|
||||
import type Database from 'better-sqlite3';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
/** The parts of the server the Postgres path uses, loaded at run time (`loadServer`). */
|
||||
export interface ServerModules {
|
||||
engine: typeof import('../src/db/engine');
|
||||
appConfig: typeof import('../src/app-config');
|
||||
pgTools: typeof import('../src/db/engine/postgres/pg-tools');
|
||||
}
|
||||
|
||||
/**
|
||||
* The statements the rotation needs, on either engine. Every statement is
|
||||
* written once, with `?` placeholders both engines take; only the catalog
|
||||
* lookups differ. The rotation runs inside one transaction the caller opens.
|
||||
*/
|
||||
export interface SecretStore {
|
||||
all<T>(sql: string, params?: unknown[]): Promise<T[]>;
|
||||
get<T>(sql: string, params?: unknown[]): Promise<T | undefined>;
|
||||
run(sql: string, params?: unknown[]): Promise<void>;
|
||||
tableExists(name: string): Promise<boolean>;
|
||||
columnsOf(table: string): Promise<Set<string>>;
|
||||
}
|
||||
|
||||
/** The SQLite file through better-sqlite3, whose calls are synchronous; the store only wraps them. */
|
||||
export function sqliteStore(db: Database.Database): SecretStore {
|
||||
return {
|
||||
async all<T>(sql: string, params: unknown[] = []) {
|
||||
return db.prepare(sql).all(...params) as T[];
|
||||
},
|
||||
async get<T>(sql: string, params: unknown[] = []) {
|
||||
return db.prepare(sql).get(...params) as T | undefined;
|
||||
},
|
||||
async run(sql: string, params: unknown[] = []) {
|
||||
db.prepare(sql).run(...params);
|
||||
},
|
||||
async tableExists(name: string) {
|
||||
return !!db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(name);
|
||||
},
|
||||
async columnsOf(table: string) {
|
||||
const rows = db.prepare('SELECT name FROM pragma_table_info(?)').all(table) as { name: string }[];
|
||||
return new Set(rows.map((r) => r.name));
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* A Postgres database through the server's MikroORM connection, inside the
|
||||
* transaction `em` holds when it is a transactional fork. The catalog lookups
|
||||
* read the current schema, the one TREK keeps its tables in.
|
||||
*/
|
||||
export function postgresStore(em: EntityManager): SecretStore {
|
||||
const connection = em.getConnection();
|
||||
const ctx = em.getTransactionContext();
|
||||
const all = async <T>(sql: string, params: unknown[] = []): Promise<T[]> =>
|
||||
(await connection.execute(sql, params, 'all', ctx)) as T[];
|
||||
return {
|
||||
all,
|
||||
async get<T>(sql: string, params: unknown[] = []) {
|
||||
const [row] = await all<T>(sql, params);
|
||||
return row;
|
||||
},
|
||||
async run(sql: string, params: unknown[] = []) {
|
||||
await connection.execute(sql, params, 'run', ctx);
|
||||
},
|
||||
async tableExists(name: string) {
|
||||
const [row] = await all<{ present: boolean }>('SELECT to_regclass(?) IS NOT NULL AS present', [name]);
|
||||
return row?.present === true;
|
||||
},
|
||||
async columnsOf(table: string) {
|
||||
const rows = await all<{ name: string }>(
|
||||
'SELECT column_name AS name FROM information_schema.columns WHERE table_schema = current_schema() AND table_name = ?',
|
||||
[table],
|
||||
);
|
||||
return new Set(rows.map((r) => r.name));
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The server's engine, app-config and Postgres tools: from src/ under tsx in a
|
||||
* source checkout, so it runs without a build, else from the built dist/ the
|
||||
* image ships (it has no src/).
|
||||
*/
|
||||
export function loadServer(): ServerModules {
|
||||
const source = path.join(__dirname, '..', 'src');
|
||||
const root = fs.existsSync(path.join(source, 'db', 'engine', 'index.ts'))
|
||||
? source
|
||||
: path.join(__dirname, '..', 'dist');
|
||||
return {
|
||||
engine: require(path.join(root, 'db', 'engine')) as ServerModules['engine'],
|
||||
appConfig: require(path.join(root, 'app-config')) as ServerModules['appConfig'],
|
||||
pgTools: require(path.join(root, 'db', 'engine', 'postgres', 'pg-tools')) as ServerModules['pgTools'],
|
||||
};
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,21 +1,4 @@
|
||||
{
|
||||
"failing": {
|
||||
"DayAccommodationsRepository.listForTripWithPlaceAndBooking": 1,
|
||||
"DayAccommodationsRepository.listRoadtripStays": 1,
|
||||
"GoogleApiUsageRepository.recordCall": 1,
|
||||
"MaintenanceRepository.vacuumInto": 1,
|
||||
"MaintenanceRepository.walCheckpoint": 1,
|
||||
"ReservationDayPositionsRepository.upsertScoped": 1,
|
||||
"ReservationsRepository.findWithJoins": 1,
|
||||
"ReservationsRepository.listForCalendar": 1,
|
||||
"ReservationsRepository.listForTrip": 1,
|
||||
"ReservationsRepository.listPublicStaysForCalendar": 1,
|
||||
"RouteUsageDailyRepository.record": 1
|
||||
},
|
||||
"uncovered": [
|
||||
"BucketListRepository.update",
|
||||
"BudgetItemsRepository.update",
|
||||
"PackingBagsRepository.update",
|
||||
"TodoItemsRepository.update"
|
||||
]
|
||||
"failing": {},
|
||||
"uncovered": []
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
* repositories. Nothing tested that claim until this probe. Given an empty
|
||||
* Postgres database it
|
||||
*
|
||||
* 1. derives a Postgres schema from the entities (pg-probe/schema.ts);
|
||||
* 1. derives a Postgres schema from the entities (src/db/engine/postgres/schema-adjust.ts);
|
||||
* 2. runs every dialect helper on SQLite and on Postgres and checks both
|
||||
* return what the helper promises (pg-probe/helper-cases.ts); every
|
||||
* case must pass;
|
||||
@@ -15,10 +15,11 @@
|
||||
* (pg-probe/arg-samples.ts), through a MikroORM Postgres driver that
|
||||
* runs each statement in its own rolled-back transaction and records
|
||||
* whether Postgres accepted it (pg-probe/recorder.ts);
|
||||
* 4. holds the statements Postgres refuses as SQL (SQLSTATE class 42 or
|
||||
* 0A), per method, to scripts/pg-probe-baseline.json, which may only
|
||||
* shrink (pg-probe/baseline.ts); a refusal over a sample value
|
||||
* (class 22) or the empty tables is reported, not held;
|
||||
* 4. holds the statements Postgres refuses as SQL or over a value's type
|
||||
* (SQLSTATE class 42, 0A or 22), per method, to
|
||||
* scripts/pg-probe-baseline.json, which may only shrink
|
||||
* (pg-probe/baseline.ts); a constraint over a sample value (class 23) or
|
||||
* the empty tables is reported, not held;
|
||||
* 5. holds the methods whose SQL it did not see (it could not call them,
|
||||
* they sent no SQL, or they timed out) to the same file's `uncovered`
|
||||
* list, which may only shrink too, so a new method the probe cannot
|
||||
@@ -28,7 +29,7 @@
|
||||
* arguments against empty tables, not every statement the code can send: a
|
||||
* branch that only runs on data the empty tables do not hold stays unseen.
|
||||
*
|
||||
* It needs a Postgres server, so CI runs it in the `postgres-probe` job
|
||||
* It needs a Postgres server, so CI runs it in the `server-postgres` job
|
||||
* against a service container. Locally:
|
||||
*
|
||||
* docker run --rm -d -p 5432:5432 -e POSTGRES_PASSWORD=probe postgres:17
|
||||
|
||||
@@ -4,7 +4,8 @@
|
||||
* The probe has no fixtures: it reads every repository class with the
|
||||
* TypeScript checker and builds one sample argument list per public method
|
||||
* from the declared parameter types (a number is 1, a string is "probe" or a
|
||||
* date-shaped string when the name says so, an object gets every property
|
||||
* date-shaped string when the name says so, a boolean false unless it is the
|
||||
* `present` flag of a partial update's pair, an object gets every property
|
||||
* it can sample, an array one element). The values only have to get the
|
||||
* method to send its SQL; what the probe measures is whether Postgres
|
||||
* accepts that SQL against an empty schema. A sample the column cannot take
|
||||
@@ -24,6 +25,13 @@ export type MethodPlan =
|
||||
| { className: string; file: string; method: string; unprobeable: string };
|
||||
|
||||
const MAX_DEPTH = 4;
|
||||
/**
|
||||
* The label of the flag in the repositories' `[present: boolean, value]`
|
||||
* pairs (`presenceSet`): a patch whose pairs are all absent sends no SQL, so
|
||||
* this one boolean is sampled true. Every other boolean stays false. The
|
||||
* label is spelled in `presenceSet`'s signature, which a test pins.
|
||||
*/
|
||||
export const PRESENCE_LABEL = 'present';
|
||||
const SAMPLE_DATE = '2026-01-01';
|
||||
const SAMPLE_TIMESTAMP = '2026-01-01 00:00:00';
|
||||
|
||||
@@ -68,14 +76,14 @@ export function sampleFor(checker: ts.TypeChecker, type: ts.Type, name: string,
|
||||
if (type.isUnion()) {
|
||||
const members = type.types.filter((member) => !isNullish(member));
|
||||
if (members.length === 0) return OK(null);
|
||||
if (members.every((member) => member.flags & ts.TypeFlags.BooleanLiteral)) return OK(false);
|
||||
if (members.every((member) => member.flags & ts.TypeFlags.BooleanLiteral)) return OK(name === PRESENCE_LABEL);
|
||||
const numeric = members.find((member) => member.flags & ts.TypeFlags.NumberLike);
|
||||
return sampleFor(checker, numeric ?? members[0]!, name, depth + 1);
|
||||
}
|
||||
if (type.isStringLiteral()) return OK(type.value);
|
||||
if (type.isNumberLiteral()) return OK(type.value);
|
||||
if (flags & ts.TypeFlags.BooleanLiteral) return OK(checker.typeToString(type) === 'true');
|
||||
if (flags & ts.TypeFlags.BooleanLike) return OK(false);
|
||||
if (flags & ts.TypeFlags.BooleanLike) return OK(name === PRESENCE_LABEL);
|
||||
if (flags & ts.TypeFlags.BigIntLike) return OK(BigInt(1));
|
||||
if (flags & ts.TypeFlags.NumberLike) return OK(1);
|
||||
if (flags & (ts.TypeFlags.StringLike | ts.TypeFlags.TemplateLiteral)) return OK(sampleString(name));
|
||||
@@ -88,8 +96,15 @@ export function sampleFor(checker: ts.TypeChecker, type: ts.Type, name: string,
|
||||
function sampleObjectType(checker: ts.TypeChecker, type: ts.ObjectType, name: string, depth: number): Sample {
|
||||
if (checker.isTupleType(type)) {
|
||||
const values: unknown[] = [];
|
||||
const labels = ((type as ts.TypeReference).target as ts.TupleType).labeledElementDeclarations;
|
||||
for (const [i, element] of checker.getTypeArguments(type as ts.TypeReference).entries()) {
|
||||
const sample = sampleFor(checker, element, `${name}[${i}]`, depth + 1);
|
||||
const label = labels?.[i]?.name;
|
||||
const sample = sampleFor(
|
||||
checker,
|
||||
element,
|
||||
label && ts.isIdentifier(label) ? label.text : `${name}[${i}]`,
|
||||
depth + 1,
|
||||
);
|
||||
if (!sample.ok) return sample;
|
||||
values.push(sample.value);
|
||||
}
|
||||
|
||||
@@ -11,9 +11,9 @@
|
||||
* `--update` lowers entries and drops the ones that reach zero or whose
|
||||
* method is gone; it never raises or adds one.
|
||||
*
|
||||
* Only statements Postgres refuses as SQL count here (SQLSTATE classes 42
|
||||
* and 0A, see `countsTowardRatchet`). A value the sample arguments got wrong
|
||||
* (class 22, a sample string in a date column) says nothing about the
|
||||
* Statements Postgres refuses as SQL or over a value's type count here
|
||||
* (SQLSTATE classes 42, 0A and 22, see `countsTowardRatchet`). A constraint
|
||||
* the sample values break (class 23) or a timeout says nothing about the
|
||||
* dialect and is reported without being held.
|
||||
*
|
||||
* `uncovered` lists the methods whose SQL the probe did not see: the ones it
|
||||
@@ -56,12 +56,16 @@ export interface BaselineVerdict {
|
||||
/**
|
||||
* Whether a refused statement counts toward the ratchet: SQLSTATE class 42
|
||||
* (syntax error, unknown function, operator or column, datatype mismatch)
|
||||
* and class 0A (feature not supported) are what a SQLite-only spelling gets.
|
||||
* Anything else (a data exception such as 22P02 or 22007, a constraint, a
|
||||
* timeout) comes from the sample values or the empty tables, not the SQL.
|
||||
* and class 0A (feature not supported) are what a SQLite-only spelling gets,
|
||||
* and class 22 (a data exception such as 22P02 or 22007) is a value of the
|
||||
* wrong type reaching a column, which SQLite compares where Postgres refuses
|
||||
* (a query-string id bound to an integer column). The sampler sends what
|
||||
* each parameter declares, so a class 22 refusal is the code's, not the
|
||||
* sample's. A constraint (class 23) or a timeout comes from the sample values
|
||||
* or the empty tables, not the SQL.
|
||||
*/
|
||||
export function countsTowardRatchet(code: string): boolean {
|
||||
return /^(42|0A)/.test(code);
|
||||
return /^(42|0A|22)/.test(code);
|
||||
}
|
||||
|
||||
const METHOD_KEY = /^[A-Za-z_$][\w$]*\.[A-Za-z_$][\w$]*$/;
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
* SQLite database the helper cases are compared on, and the loop that calls
|
||||
* every repository method.
|
||||
*/
|
||||
import { applyPostgresColumnAdjustments, NOCASE_COLLATION_SQL } from '../../src/db/engine/postgres/schema-adjust';
|
||||
import { splitStatements } from '../../src/db/engine/postgres/sql-split';
|
||||
import { ALL_ENTITIES } from '../../src/db/entities';
|
||||
import type { MethodPlan } from './arg-samples';
|
||||
import {
|
||||
@@ -18,8 +20,7 @@ import {
|
||||
} from './helper-cases';
|
||||
import { ProbePostgresDialect, type StatementRecorder } from './recorder';
|
||||
import type { MethodResult } from './report';
|
||||
import { adjustColumns, NOCASE_COLLATION_SQL, splitStatements, type ColumnMeta } from './schema';
|
||||
import { RequestContext, type Configuration, type EntityManager, type EntityProperty } from '@mikro-orm/core';
|
||||
import { RequestContext, type Configuration, type EntityManager } from '@mikro-orm/core';
|
||||
import { MikroORM, PostgreSqlConnection, PostgreSqlDriver, type Options } from '@mikro-orm/postgresql';
|
||||
import { SqlitePlatform } from '@mikro-orm/sql';
|
||||
|
||||
@@ -129,7 +130,7 @@ export async function prepareDatabase(
|
||||
await run(NOCASE_COLLATION_SQL);
|
||||
let adjusted = 0;
|
||||
for (const meta of orm.getMetadata().getAll().values()) {
|
||||
adjusted += adjustColumns(meta.props as EntityProperty[] as ColumnMeta[]).length;
|
||||
adjusted += applyPostgresColumnAdjustments(meta.props).length;
|
||||
}
|
||||
const statements = splitStatements(await orm.schema.getCreateSchemaSQL({ wrap: false }));
|
||||
for (const statement of statements) await run(statement);
|
||||
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
castIntegerKysely,
|
||||
concatKysely,
|
||||
currentTimestampKysely,
|
||||
integerTextEqualsKysely,
|
||||
nowPlusSecondsKysely,
|
||||
startsWithIsoDateKysely,
|
||||
substringKysely,
|
||||
@@ -44,6 +45,7 @@ import {
|
||||
dateOf,
|
||||
dayDistance,
|
||||
foundAgainState,
|
||||
ilike,
|
||||
lower,
|
||||
lowerParam,
|
||||
lowerTrim,
|
||||
@@ -269,6 +271,18 @@ export const HELPER_CASES: readonly HelperCase[] = [
|
||||
raw: (p) => rawOf(dayDistance(p, 'a', '2026-09-24')),
|
||||
expect: { equals: 3 },
|
||||
},
|
||||
{
|
||||
name: 'ilike matches in other case',
|
||||
row: { a: 'Probe Place' },
|
||||
raw: (p) => ({ sql: ilike(p, ['a']), params: ['%PLACE%'] }),
|
||||
expect: { equals: true },
|
||||
},
|
||||
{
|
||||
name: 'ilike keeps the escaped wildcard literal',
|
||||
row: { a: 'Probe Place' },
|
||||
raw: (p) => ({ sql: ilike(p, ['a']), params: ['probe\\_place'] }),
|
||||
expect: { equals: false },
|
||||
},
|
||||
{
|
||||
name: 'collateNoCase',
|
||||
row: { a: 'Probe' },
|
||||
@@ -342,6 +356,26 @@ export const HELPER_CASES: readonly HelperCase[] = [
|
||||
kysely: (p, eb) => castIntegerKysely(p, eb, 'a'),
|
||||
expect: { equals: 14 },
|
||||
},
|
||||
...['14', '14.0'].map(
|
||||
(stored): HelperCase => ({
|
||||
name: `integerTextEqualsKysely matches the text ${stored} to 14`,
|
||||
row: { a: stored, n: 14 },
|
||||
kysely: (p, eb) => eb.case().when(integerTextEqualsKysely(p, eb, 'a', 'n')).then('yes').else('no').end(),
|
||||
expect: { equals: 'yes' },
|
||||
}),
|
||||
),
|
||||
{
|
||||
name: 'integerTextEqualsKysely matches the number 14 to 14',
|
||||
row: { n: 14 },
|
||||
kysely: (p, eb) => eb.case().when(integerTextEqualsKysely(p, eb, 'n', 'n')).then('yes').else('no').end(),
|
||||
expect: { equals: 'yes' },
|
||||
},
|
||||
{
|
||||
name: 'integerTextEqualsKysely tells 15.0 from 14',
|
||||
row: { a: '15.0', n: 14 },
|
||||
kysely: (p, eb) => eb.case().when(integerTextEqualsKysely(p, eb, 'a', 'n')).then('yes').else('no').end(),
|
||||
expect: { equals: 'no' },
|
||||
},
|
||||
{
|
||||
name: 'unixEpochToIsoKysely',
|
||||
row: { n: EPOCH_MS },
|
||||
|
||||
@@ -22,7 +22,7 @@ export interface FailedStatement {
|
||||
code: string;
|
||||
message: string;
|
||||
sql: string;
|
||||
/** A dialect refusal (SQLSTATE class 42 or 0A) the ratchet holds; anything else is reported only. */
|
||||
/** A refusal the ratchet holds (SQLSTATE class 42, 0A or 22); anything else is reported only. */
|
||||
counted: boolean;
|
||||
}
|
||||
|
||||
@@ -38,8 +38,9 @@ export interface ProbeSummary {
|
||||
/** Every distinct statement Postgres refused, counted toward the ratchet or not. */
|
||||
failedStatements: FailedStatement[];
|
||||
/**
|
||||
* `Class.method` → distinct statements Postgres refused as SQL (SQLSTATE
|
||||
* class 42 or 0A); every called method appears, zeros included.
|
||||
* `Class.method` → distinct statements Postgres refused as SQL or over a
|
||||
* value's type (SQLSTATE class 42, 0A or 22); every called method appears,
|
||||
* zeros included.
|
||||
*/
|
||||
failingByMethod: Map<string, number>;
|
||||
/**
|
||||
@@ -192,7 +193,8 @@ export function formatConsole(input: ReportInput): string {
|
||||
const refusals = splitRefusals(summary);
|
||||
lines.push(
|
||||
`Statements: ${summary.statements} distinct, ${summary.failedStatements.length} refused by Postgres ` +
|
||||
`(${refusals.counted.length} as SQL, held to the baseline; ${refusals.reported.length} over a sample value or the empty tables, reported only).`,
|
||||
`(${refusals.counted.length} as SQL or over a value's type, held to the baseline; ` +
|
||||
`${refusals.reported.length} over a constraint, a timeout or the empty tables, reported only).`,
|
||||
);
|
||||
for (const [code, count] of [...summary.failuresByCode.entries()].sort((a, b) => b[1] - a[1])) {
|
||||
lines.push(` ${code}: ${count}${countsTowardRatchet(code) ? '' : ' (not held)'}`);
|
||||
@@ -254,8 +256,8 @@ export function formatMarkdown(input: ReportInput): string {
|
||||
);
|
||||
out.push(`| Methods whose SQL the probe did not see | ${summary.uncovered.size} |`);
|
||||
out.push(`| Distinct statements | ${summary.statements} |`);
|
||||
out.push(`| Refused by Postgres as SQL (held) | ${refusals.counted.length} |`);
|
||||
out.push(`| Refused over a sample value or the empty tables (reported only) | ${refusals.reported.length} |`);
|
||||
out.push(`| Refused by Postgres as SQL or over a value's type (held) | ${refusals.counted.length} |`);
|
||||
out.push(`| Refused over a constraint, a timeout or the empty tables (reported only) | ${refusals.reported.length} |`);
|
||||
out.push('');
|
||||
if (probedNothing(summary))
|
||||
out.push('No repository method was called, so there is nothing to hold to the baseline.', '');
|
||||
|
||||
@@ -1,106 +0,0 @@
|
||||
/**
|
||||
* The Postgres schema the probe runs against, derived from the entities.
|
||||
*
|
||||
* The entities are generated from the migrated SQLite schema and a parity
|
||||
* test pins them to it (`npm run check:entities`), so they are the one
|
||||
* description of the tables both engines can read. MikroORM's schema
|
||||
* generator turns them into Postgres DDL after three adjustments that keep
|
||||
* the probe about the SQL the repositories send, not about the storage
|
||||
* decisions a real Postgres port still has to make:
|
||||
*
|
||||
* - timestamps stay TEXT, the storage model the services and the dialect
|
||||
* helpers are written for (server/CLAUDE.md, "Storage model");
|
||||
* - a SQLite-only default (`datetime('now')`, `strftime('%s','now')`) gets
|
||||
* its Postgres equivalent, and a column declared `COLLATE NOCASE` uses
|
||||
* the `nocase` collation `collateNoCase()` names on Postgres;
|
||||
* - no foreign keys, so a statement is never refused only because the
|
||||
* sample row it writes points at nothing (every statement meets empty
|
||||
* tables).
|
||||
*
|
||||
* Unique and partial unique indexes stay, because `ON CONFLICT` needs them.
|
||||
*/
|
||||
import { pgTimestampText, PG_UTC_NOW } from '../../src/db/dialect/platform';
|
||||
|
||||
/** SQLite's timestamp text on Postgres, for a column default. */
|
||||
export const PG_NOW_TEXT_DEFAULT = pgTimestampText(PG_UTC_NOW);
|
||||
|
||||
/** The case-insensitive collation `collateNoCase()` names on Postgres. */
|
||||
export const NOCASE_COLLATION_SQL =
|
||||
"CREATE COLLATION IF NOT EXISTS nocase (provider = icu, locale = 'und-u-ks-level2', deterministic = false)";
|
||||
|
||||
/** The Postgres spelling of a column default the entities carry in SQLite's. */
|
||||
export function portableDefault(raw: string): string {
|
||||
const text = raw
|
||||
.trim()
|
||||
.replace(/^\((.*)\)$/s, '$1')
|
||||
.trim();
|
||||
if (/^current_timestamp$/i.test(text) || /^datetime\(\s*'now'\s*\)$/i.test(text)) return PG_NOW_TEXT_DEFAULT;
|
||||
if (/^strftime\(\s*'%s'\s*,\s*'now'\s*\)$/i.test(text))
|
||||
return 'CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) AS bigint)';
|
||||
return raw;
|
||||
}
|
||||
|
||||
/**
|
||||
* Splits generated DDL into single statements on `;` outside quotes, so one
|
||||
* statement Postgres refuses does not take the rest of the schema with it.
|
||||
*/
|
||||
export function splitStatements(sql: string): string[] {
|
||||
const statements: string[] = [];
|
||||
let current = '';
|
||||
let quote: '"' | "'" | null = null;
|
||||
for (const char of sql) {
|
||||
if (quote) {
|
||||
if (char === quote) quote = null;
|
||||
current += char;
|
||||
} else if (char === "'" || char === '"') {
|
||||
quote = char;
|
||||
current += char;
|
||||
} else if (char === ';') {
|
||||
if (current.trim()) statements.push(current.trim());
|
||||
current = '';
|
||||
} else {
|
||||
current += char;
|
||||
}
|
||||
}
|
||||
if (current.trim()) statements.push(current.trim());
|
||||
return statements.filter((statement) => !/^set\s/i.test(statement));
|
||||
}
|
||||
|
||||
/** The subset of MikroORM's property metadata the schema adjustments touch. */
|
||||
export interface ColumnMeta {
|
||||
name: string;
|
||||
defaultRaw?: string;
|
||||
collation?: string;
|
||||
columnTypes?: string[];
|
||||
customType?: { constructor: { name: string } };
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies the adjustments above to one entity's properties in place:
|
||||
* timestamp columns become `text`, SQLite-only defaults and the NOCASE
|
||||
* collation their Postgres spelling. Returns the names of the properties
|
||||
* it changed, for the log.
|
||||
*/
|
||||
export function adjustColumns(properties: readonly ColumnMeta[]): string[] {
|
||||
const changed: string[] = [];
|
||||
for (const property of properties) {
|
||||
let touched = false;
|
||||
if (property.customType?.constructor.name === 'DbTimestampType' && property.columnTypes) {
|
||||
property.columnTypes = property.columnTypes.map(() => 'text');
|
||||
touched = true;
|
||||
}
|
||||
if (typeof property.defaultRaw === 'string') {
|
||||
const next = portableDefault(property.defaultRaw);
|
||||
if (next !== property.defaultRaw) {
|
||||
property.defaultRaw = next;
|
||||
touched = true;
|
||||
}
|
||||
}
|
||||
if (property.collation?.toUpperCase() === 'NOCASE') {
|
||||
property.collation = 'nocase';
|
||||
touched = true;
|
||||
}
|
||||
if (touched) changed.push(property.name);
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
-----BEGIN PGP PUBLIC KEY BLOCK-----
|
||||
|
||||
mQINBE6XR8IBEACVdDKT2HEH1IyHzXkb4nIWAY7echjRxo7MTcj4vbXAyBKOfjja
|
||||
UrBEJWHN6fjKJXOYWXHLIYg0hOGeW9qcSiaa1/rYIbOzjfGfhE4x0Y+NJHS1db0V
|
||||
G6GUj3qXaeyqIJGS2z7m0Thy4Lgr/LpZlZ78Nf1fliSzBlMo1sV7PpP/7zUO+aA4
|
||||
bKa8Rio3weMXQOZgclzgeSdqtwKnyKTQdXY5MkH1QXyFIk1nTfWwyqpJjHlgtwMi
|
||||
c2cxjqG5nnV9rIYlTTjYG6RBglq0SmzF/raBnF4Lwjxq4qRqvRllBXdFu5+2pMfC
|
||||
IZ10HPRdqDCTN60DUix+BTzBUT30NzaLhZbOMT5RvQtvTVgWpeIn20i2NrPWNCUh
|
||||
hj490dKDLpK/v+A5/i8zPvN4c6MkDHi1FZfaoz3863dylUBR3Ip26oM0hHXf4/2U
|
||||
A/oA4pCl2W0hc4aNtozjKHkVjRx5Q8/hVYu+39csFWxo6YSB/KgIEw+0W8DiTII3
|
||||
RQj/OlD68ZDmGLyQPiJvaEtY9fDrcSpI0Esm0i4sjkNbuuh0Cvwwwqo5EF1zfkVj
|
||||
Tqz2REYQGMJGc5LUbIpk5sMHo1HWV038TWxlDRwtOdzw08zQA6BeWe9FOokRPeR2
|
||||
AqhyaJJwOZJodKZ76S+LDwFkTLzEKnYPCzkoRwLrEdNt1M7wQBThnC5z6wARAQAB
|
||||
tBxQb3N0Z3JlU1FMIERlYmlhbiBSZXBvc2l0b3J5iQJOBBMBCAA4AhsDBQsJCAcD
|
||||
BRUKCQgLBRYCAwEAAh4BAheAFiEEuXsK/KoaR/BE8kSgf8x9RqzMTPgFAlhtCD8A
|
||||
CgkQf8x9RqzMTPgECxAAk8uL+dwveTv6eH21tIHcltt8U3Ofajdo+D/ayO53LiYO
|
||||
xi27kdHD0zvFMUWXLGxQtWyeqqDRvDagfWglHucIcaLxoxNwL8+e+9hVFIEskQAY
|
||||
kVToBCKMXTQDLarz8/J030Pmcv3ihbwB+jhnykMuyyNmht4kq0CNgnlcMCdVz0d3
|
||||
z/09puryIHJrD+A8y3TD4RM74snQuwc9u5bsckvRtRJKbP3GX5JaFZAqUyZNRJRJ
|
||||
Tn2OQRBhCpxhlZ2afkAPFIq2aVnEt/Ie6tmeRCzsW3lOxEH2K7MQSfSu/kRz7ELf
|
||||
Cz3NJHj7rMzC+76Rhsas60t9CjmvMuGONEpctijDWONLCuch3Pdj6XpC+MVxpgBy
|
||||
2VUdkunb48YhXNW0jgFGM/BFRj+dMQOUbY8PjJjsmVV0joDruWATQG/M4C7O8iU0
|
||||
B7o6yVv4m8LDEN9CiR6r7H17m4xZseT3f+0QpMe7iQjz6XxTUFRQxXqzmNnloA1T
|
||||
7VjwPqIIzkj/u0V8nICG/ktLzp1OsCFatWXh7LbU+hwYl6gsFH/mFDqVxJ3+DKQi
|
||||
vyf1NatzEwl62foVjGUSpvh3ymtmtUQ4JUkNDsXiRBWczaiGSuzD9Qi0ONdkAX3b
|
||||
ewqmN4TfE+XIpCPxxHXwGq9Rv1IFjOdCX0iG436GHyTLC1tTUIKF5xV4Y0+cXIOJ
|
||||
Aj0EEwEIACcCGwMFCwkIBwMFFQoJCAsFFgIDAQACHgECF4AFAlLpFRkFCQ6EJy0A
|
||||
CgkQf8x9RqzMTPjOZA//Zp0e25pcvle7cLc0YuFr9pBv2JIkLzPm83nkcwKmxaWa
|
||||
yUIG4Sv6pH6hm8+S/CHQij/yFCX+o3ngMw2J9HBUvafZ4bnbI0RGJ70GsAwraQ0V
|
||||
lkIfg7GUw3TzvoGYO42rZTru9S0K/6nFP6D1HUu+U+AsJONLeb6oypQgInfXQExP
|
||||
ZyliUnHdipei4WR1YFW6sjSkZT/5C3J1wkAvPl5lvOVthI9Zs6bZlJLZwusKxU0U
|
||||
M4Btgu1Sf3nnJcHmzisixwS9PMHE+AgPWIGSec/N27a0KmTTvImV6K6nEjXJey0K
|
||||
2+EYJuIBsYUNorOGBwDFIhfRk9qGlpgt0KRyguV+AP5qvgry95IrYtrOuE7307Si
|
||||
dEbSnvO5ezNemE7gT9Z1tM7IMPfmoKph4BfpNoH7aXiQh1Wo+ChdP92hZUtQrY2N
|
||||
m13cmkxYjQ4ZgMWfYMC+DA/GooSgZM5i6hYqyyfAuUD9kwRN6BqTbuAUAp+hCWYe
|
||||
N4D88sLYpFh3paDYNKJ+Gf7Yyi6gThcV956RUFDH3ys5Dk0vDL9NiWwdebWfRFbz
|
||||
oRM3dyGP889aOyLzS3mh6nHzZrNGhW73kslSQek8tjKrB+56hXOnb4HaElTZGDvD
|
||||
5wmrrhN94kbyGtz3cydIohvNO9d90+29h0eGEDYti7j7maHkBKUAwlcPvMg5m3aJ
|
||||
Aj0EEwEIACcCGwMFCwkIBwMFFQoJCAsFFgIDAQACHgECF4AFAlEqbZUFCQg2wEEA
|
||||
CgkQf8x9RqzMTPhFMQ//WxAfKMdpSIA9oIC/yPD/dJpY/+DyouOljpE6MucMy/Ar
|
||||
BECjFTBwi/j9NYM4ynAk34IkhuNexc1i9/05f5RM6+riLCLgAOsADDbHD4miZzoS
|
||||
xiVr6GQ3YXMbOGld9kV9Sy6mGNjcUov7iFcf5Hy5w3AjPfKuR9zXswyfzIU1YXOb
|
||||
iiZT38l55pp/BSgvGVQsvbNjsff5CbEKXS7q3xW+WzN0QWF6YsfNVhFjRGj8hKtH
|
||||
vwKcA02wwjLeLXVTm6915ZUKhZXUFc0vM4Pj4EgNswH8Ojw9AJaKWJIZmLyW+aP+
|
||||
wpu6YwVCicxBY59CzBO2pPJDfKFQzUtrErk9irXeuCCLesDyirxJhv8o0JAvmnMA
|
||||
KOLhNFUrSQ2m+3EnF7zhfz70gHW+EG8X8mL/EN3/dUM09j6TVrjtw43RLxBzwMDe
|
||||
ariFF9yC+5bLtnGgxjsB9Ik6GV5v34/NEEGf1qBiAzFmDVFRZlrNDkq6gmpvGnA5
|
||||
hUWNr+y0i01LjGyaLSWHYjgw2UEQOqcUtTFK9MNzbZze4mVaHMEz9/aMfX25R6qb
|
||||
iNqCChveIm8mYr5Ds2zdZx+G5bAKdzX7nx2IUAxFQJEE94VLSp3npAaTWv3sHr7d
|
||||
R8tSyUJ9poDwgw4W9BIcnAM7zvFYbLF5FNggg/26njHCCN70sHt8zGxKQINMc6SJ
|
||||
Aj0EEwEIACcCGwMFCwkIBwMFFQoJCAsFFgIDAQACHgECF4AFAlB5KywFCQPDFt8A
|
||||
CgkQf8x9RqzMTPhuCQ//QAjRSAOCQ02qmUAikT+mTB6baOAakkYq6uHbEO7qPZkv
|
||||
4E/M+HPIJ4wdnBNeSQjfvdNcZBA/x0hr5EMcBneKKPDj4hJ0panOIRQmNSTThQw9
|
||||
OU351gm3YQctAMPRUu1fTJAL/AuZUQf9ESmhyVtWNlH/56HBfYjE4iVeaRkkNLJy
|
||||
X3vkWdJSMwC/LO3Lw/0M3R8itDsm74F8w4xOdSQ52nSRFRh7PunFtREl+QzQ3EA/
|
||||
WB4AIj3VohIGkWDfPFCzV3cyZQiEnjAe9gG5pHsXHUWQsDFZ12t784JgkGyO5wT2
|
||||
6pzTiuApWM3k/9V+o3HJSgH5hn7wuTi3TelEFwP1fNzI5iUUtZdtxbFOfWMnZAyp
|
||||
EhaLmXNkg4zDkH44r0ss9fR0DAgUav1a25UnbOn4PgIEQy2fgHKHwRpCy20d6oCS
|
||||
lmgyWsR40EPPYvtGq49A2aK6ibXmdvvFT+Ts8Z+q2SkFpoYFX20mR2nsF0fbt1lf
|
||||
H65P64dukxeRGteWIeNakDD40bAAOH8+OaoTGVBJ2ACJfLVNM53PEoftavAwUYMr
|
||||
R910qvwYfd/46rh46g1Frr9SFMKYE9uvIJIgDsQB3QBp71houU4H55M5GD8XURYs
|
||||
+bfiQpJG1p7eB8e5jZx1SagNWc4XwL2FzQ9svrkbg1Y+359buUiP7T6QXX2zY+8=
|
||||
=XSRU
|
||||
-----END PGP PUBLIC KEY BLOCK-----
|
||||
@@ -1,18 +1,18 @@
|
||||
{
|
||||
"scripts/db-call-graph.mjs": 1036,
|
||||
"scripts/generate-entities.ts": 2259,
|
||||
"src/db/repositories/Places.repository.ts": 1437,
|
||||
"src/db/repositories/Reservations.repository.ts": 1558,
|
||||
"src/db/repositories/Places.repository.ts": 1435,
|
||||
"src/db/repositories/Reservations.repository.ts": 1550,
|
||||
"src/db/repositories/Trips.repository.ts": 1120,
|
||||
"src/db/repositories/Users.repository.ts": 1445,
|
||||
"src/db/repositories/Users.repository.ts": 1421,
|
||||
"src/nest/atlas/atlas.service.ts": 1174,
|
||||
"src/nest/auth/auth.service.ts": 1143,
|
||||
"src/nest/auth/auth.service.ts": 1141,
|
||||
"src/nest/budget/budget.service.ts": 1607,
|
||||
"src/nest/collections/collections.service.ts": 1414,
|
||||
"src/nest/doc-sync/doc-sync.service.ts": 1060,
|
||||
"src/nest/doc-sync/providers/synology-drive.client.ts": 1160,
|
||||
"src/nest/journey/journey-domain.service.ts": 1659,
|
||||
"src/nest/places/places.service.ts": 1549,
|
||||
"src/nest/places/places.service.ts": 1546,
|
||||
"src/nest/plugins/plugin-runtime.service.ts": 1460,
|
||||
"src/nest/plugins/runtime/plugin-sdk.ts": 1093,
|
||||
"src/nest/reservations/reservations.service.ts": 1168,
|
||||
|
||||
@@ -38,7 +38,6 @@
|
||||
"tests/e2e/reservations.e2e.test.ts": 1,
|
||||
"tests/e2e/roadtrip.e2e.test.ts": 1,
|
||||
"tests/e2e/school-holidays.e2e.test.ts": 1,
|
||||
"tests/e2e/session-revocation.e2e.test.ts": 1,
|
||||
"tests/e2e/sessions.e2e.test.ts": 1,
|
||||
"tests/e2e/settings.e2e.test.ts": 1,
|
||||
"tests/e2e/share.e2e.test.ts": 1,
|
||||
@@ -53,114 +52,18 @@
|
||||
"tests/e2e/trips.e2e.test.ts": 1,
|
||||
"tests/e2e/vacay.e2e.test.ts": 1,
|
||||
"tests/e2e/weather.e2e.test.ts": 1,
|
||||
"tests/integration/admin.test.ts": 1,
|
||||
"tests/integration/airtrail-sync-request-context.test.ts": 1,
|
||||
"tests/integration/api-docs.test.ts": 1,
|
||||
"tests/integration/app-config.test.ts": 1,
|
||||
"tests/integration/assignments.test.ts": 1,
|
||||
"tests/integration/async-closure-truthiness-guards.test.ts": 1,
|
||||
"tests/integration/atlas-geocode-request-context.test.ts": 1,
|
||||
"tests/integration/atlas.test.ts": 1,
|
||||
"tests/integration/auth.test.ts": 1,
|
||||
"tests/integration/backup.test.ts": 1,
|
||||
"tests/integration/boot-sweeps-request-context.test.ts": 1,
|
||||
"tests/integration/bootstrap.test.ts": 1,
|
||||
"tests/integration/budget.test.ts": 1,
|
||||
"tests/integration/categories.test.ts": 1,
|
||||
"tests/integration/collab.test.ts": 1,
|
||||
"tests/integration/collections.test.ts": 1,
|
||||
"tests/integration/dayNotes.test.ts": 1,
|
||||
"tests/integration/dayReorder.test.ts": 1,
|
||||
"tests/integration/days.test.ts": 1,
|
||||
"tests/integration/demo-seed-request-context.test.ts": 1,
|
||||
"tests/integration/doc-sync-webhook-request-context.test.ts": 1,
|
||||
"tests/integration/feeds-request-context.test.ts": 1,
|
||||
"tests/integration/files.test.ts": 1,
|
||||
"tests/integration/help.test.ts": 1,
|
||||
"tests/integration/immich.test.ts": 1,
|
||||
"tests/integration/journey-place-order.test.ts": 1,
|
||||
"tests/integration/journey.test.ts": 1,
|
||||
"tests/integration/leg-mode-incoming.test.ts": 1,
|
||||
"tests/integration/legacy-upgrade-v066.test.ts": 1,
|
||||
"tests/integration/legacy-upgrade-v082.test.ts": 1,
|
||||
"tests/integration/legacy-upgrade-v205.test.ts": 1,
|
||||
"tests/integration/legacy-upgrade-v242.test.ts": 1,
|
||||
"tests/integration/legacy-upgrade-v244.test.ts": 1,
|
||||
"tests/integration/maps.test.ts": 1,
|
||||
"tests/integration/mcp.test.ts": 1,
|
||||
"tests/integration/memories-immich.test.ts": 1,
|
||||
"tests/integration/memories-synology.test.ts": 1,
|
||||
"tests/integration/memories-unified.test.ts": 1,
|
||||
"tests/integration/misc.test.ts": 1,
|
||||
"tests/integration/notifications.test.ts": 1,
|
||||
"tests/integration/oauth-authorize.test.ts": 1,
|
||||
"tests/integration/oauth.test.ts": 1,
|
||||
"tests/integration/oidc-local-provider.test.ts": 1,
|
||||
"tests/integration/oidc.test.ts": 1,
|
||||
"tests/integration/orm-request-context-seams.test.ts": 1,
|
||||
"tests/integration/packing.test.ts": 1,
|
||||
"tests/integration/passkey.test.ts": 1,
|
||||
"tests/integration/places.test.ts": 1,
|
||||
"tests/integration/plugins/boot-registry-order.test.ts": 1,
|
||||
"tests/integration/plugins/plugin-runtime.test.ts": 1,
|
||||
"tests/integration/profile.test.ts": 1,
|
||||
"tests/integration/reservations.test.ts": 1,
|
||||
"tests/integration/scheduler-gate.test.ts": 1,
|
||||
"tests/integration/security.test.ts": 1,
|
||||
"tests/integration/settings.test.ts": 1,
|
||||
"tests/integration/share.test.ts": 1,
|
||||
"tests/integration/storage-health-notifier-request-context.test.ts": 1,
|
||||
"tests/integration/systemNotices.test.ts": 1,
|
||||
"tests/integration/tags.test.ts": 1,
|
||||
"tests/integration/todo.test.ts": 1,
|
||||
"tests/integration/trip-access-primitives.test.ts": 1,
|
||||
"tests/integration/trips.test.ts": 1,
|
||||
"tests/integration/uploads-photo-request-context.test.ts": 1,
|
||||
"tests/integration/uploads-static.test.ts": 1,
|
||||
"tests/integration/vacay.test.ts": 1,
|
||||
"tests/setup.ts": 1,
|
||||
"tests/unit/auto-backup.test.ts": 1,
|
||||
"tests/unit/db/database-lazy-open.test.ts": 1,
|
||||
"tests/unit/mcp/demo-tool-gate.test.ts": 1,
|
||||
"tests/unit/mcp/tools-addon-gating.test.ts": 1,
|
||||
"tests/unit/mcp/tools-airtrail.test.ts": 1,
|
||||
"tests/unit/mcp/tools-assignments-reservations-extra.test.ts": 1,
|
||||
"tests/unit/mcp/tools-assignments.test.ts": 1,
|
||||
"tests/unit/mcp/tools-atlas-expanded.test.ts": 1,
|
||||
"tests/unit/mcp/tools-atlas.test.ts": 1,
|
||||
"tests/unit/mcp/tools-budget-advanced.test.ts": 1,
|
||||
"tests/unit/mcp/tools-budget.test.ts": 1,
|
||||
"tests/unit/mcp/tools-categories.test.ts": 1,
|
||||
"tests/unit/mcp/tools-collab-polls-chat.test.ts": 1,
|
||||
"tests/unit/mcp/tools-collections.test.ts": 1,
|
||||
"tests/unit/mcp/tools-days-accommodations.test.ts": 1,
|
||||
"tests/unit/mcp/tools-days.test.ts": 1,
|
||||
"tests/unit/mcp/tools-feeds-invite.test.ts": 1,
|
||||
"tests/unit/mcp/tools-files.test.ts": 1,
|
||||
"tests/unit/mcp/tools-help-addons.test.ts": 1,
|
||||
"tests/unit/mcp/tools-journey.test.ts": 1,
|
||||
"tests/unit/mcp/tools-leg-transport-mode.test.ts": 1,
|
||||
"tests/unit/mcp/tools-memories.test.ts": 1,
|
||||
"tests/unit/mcp/tools-notes.test.ts": 1,
|
||||
"tests/unit/mcp/tools-notifications.test.ts": 1,
|
||||
"tests/unit/mcp/tools-packing-advanced.test.ts": 1,
|
||||
"tests/unit/mcp/tools-packing.test.ts": 1,
|
||||
"tests/unit/mcp/tools-places.test.ts": 1,
|
||||
"tests/unit/mcp/tools-plugin-pois.test.ts": 1,
|
||||
"tests/unit/mcp/tools-plugin-search.test.ts": 1,
|
||||
"tests/unit/mcp/tools-prompts.test.ts": 1,
|
||||
"tests/unit/mcp/tools-reservations.test.ts": 1,
|
||||
"tests/unit/mcp/tools-roadtrip.test.ts": 1,
|
||||
"tests/unit/mcp/tools-settings.test.ts": 1,
|
||||
"tests/unit/mcp/tools-share.test.ts": 1,
|
||||
"tests/unit/mcp/tools-tags-maps-weather.test.ts": 1,
|
||||
"tests/unit/mcp/tools-todos.test.ts": 1,
|
||||
"tests/unit/mcp/tools-transit.test.ts": 1,
|
||||
"tests/unit/mcp/tools-transports.test.ts": 1,
|
||||
"tests/unit/mcp/tools-trip-members.test.ts": 1,
|
||||
"tests/unit/mcp/tools-trip-warnings.test.ts": 1,
|
||||
"tests/unit/mcp/tools-trips.test.ts": 1,
|
||||
"tests/unit/mcp/tools-vacay.test.ts": 1,
|
||||
"tests/unit/nest/accommodations.service.test.ts": 1,
|
||||
"tests/unit/nest/admin.service.test.ts": 1,
|
||||
"tests/unit/nest/admin.version-notification.test.ts": 1,
|
||||
@@ -228,7 +131,6 @@
|
||||
"tests/unit/nest/registration-invites.service.test.ts": 1,
|
||||
"tests/unit/nest/reminder-jobs.service.test.ts": 1,
|
||||
"tests/unit/nest/reservations.service.test.ts": 1,
|
||||
"tests/unit/nest/route-inventory.test.ts": 1,
|
||||
"tests/unit/nest/settings.service.test.ts": 1,
|
||||
"tests/unit/nest/share.service.test.ts": 1,
|
||||
"tests/unit/nest/storage/storage-admin.service.test.ts": 1,
|
||||
@@ -273,8 +175,6 @@
|
||||
"tests/unit/plugins/settings-isolation.test.ts": 1,
|
||||
"tests/unit/plugins/trip-card-contributions.controller.test.ts": 1,
|
||||
"tests/unit/plugins/trip-warnings.controller.test.ts": 1,
|
||||
"tests/unit/plugins/view-contributions.controller.test.ts": 1,
|
||||
"tests/websocket/connection.test.ts": 1,
|
||||
"tests/websocket/wire-envelope.test.ts": 1
|
||||
"tests/unit/plugins/view-contributions.controller.test.ts": 1
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,9 +10,6 @@
|
||||
"tests/helpers/test-addons.ts": 1,
|
||||
"tests/helpers/test-uow.ts": 3,
|
||||
"tests/integration/dayReorder.test.ts": 3,
|
||||
"tests/integration/mcp.test.ts": 2,
|
||||
"tests/integration/oauth-authorize.test.ts": 2,
|
||||
"tests/integration/oauth.test.ts": 2,
|
||||
"tests/integration/plugins/boot-registry-order.test.ts": 7,
|
||||
"tests/integration/plugins/plugin-runtime.task2-conversion.test.ts": 17,
|
||||
"tests/integration/plugins/plugin-scheduler-sweep.test.ts": 5,
|
||||
@@ -26,12 +23,7 @@
|
||||
"tests/unit/db/repositories/MaintenanceRepository.test.ts": 2,
|
||||
"tests/unit/db/repositories/UserConnections.repository.test.ts": 3,
|
||||
"tests/unit/demo/demo-reset-sessions.test.ts": 3,
|
||||
"tests/unit/mcp/tools-airtrail.test.ts": 1,
|
||||
"tests/unit/mcp/tools-budget-advanced.test.ts": 2,
|
||||
"tests/unit/mcp/tools-categories.test.ts": 4,
|
||||
"tests/unit/mcp/tools-prompts.test.ts": 7,
|
||||
"tests/unit/mcp/tools-roadtrip.test.ts": 1,
|
||||
"tests/unit/mcp/tools-transit.test.ts": 1,
|
||||
"tests/unit/nest-rpc/plugin-guards.test.ts": 1,
|
||||
"tests/unit/nest-rpc/rpc-kit/registry.service.test.ts": 3,
|
||||
"tests/unit/nest/accommodations.service.test.ts": 1,
|
||||
@@ -143,7 +135,6 @@
|
||||
"tests/unit/nest/sessions/sessions.service.test.ts": 1,
|
||||
"tests/unit/nest/settings.service.test.ts": 1,
|
||||
"tests/unit/nest/share.service.test.ts": 3,
|
||||
"tests/unit/nest/sqlite-database-backup.test.ts": 2,
|
||||
"tests/unit/nest/storage/storage-admin.service.test.ts": 5,
|
||||
"tests/unit/nest/storage/storage-jobs.service.test.ts": 15,
|
||||
"tests/unit/nest/storage/storage-registry.service.test.ts": 3,
|
||||
@@ -198,7 +189,6 @@
|
||||
"tests/unit/plugins/settings-isolation.test.ts": 3,
|
||||
"tests/unit/plugins/trip-card-contributions.controller.test.ts": 1,
|
||||
"tests/unit/plugins/trip-warnings.controller.test.ts": 1,
|
||||
"tests/unit/plugins/view-contributions.controller.test.ts": 1,
|
||||
"tests/websocket/connection.test.ts": 1
|
||||
"tests/unit/plugins/view-contributions.controller.test.ts": 1
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,8 +19,8 @@
|
||||
* A method's "write units" are then counted over its body:
|
||||
* - a call to a write, on a constructor-injected field (`this.trips.x()`)
|
||||
* or on its own class (`this.x()`), is one unit;
|
||||
* - a `.transactional(...)` call that holds any write is one unit, however
|
||||
* many writes it holds;
|
||||
* - a `.transactional(...)` or `writeTransaction(...)` call that holds any
|
||||
* write is one unit, however many writes it holds;
|
||||
* - a call to a method of another class that is itself reported counts as
|
||||
* one unit here (the fault is reported once, where it lives);
|
||||
* - a write inside a loop, or inside a callback handed to forEach/map/
|
||||
@@ -343,7 +343,9 @@ export function analyse(classes) {
|
||||
const receiver = ts.isPropertyAccessExpression(callee)
|
||||
? count(cls, callee.expression, covered)
|
||||
: count(cls, callee, covered);
|
||||
if (method === 'transactional') {
|
||||
// `writeTransaction(em, engine, fn)` (src/db/engine/write-transaction.ts) is the
|
||||
// transaction `UnitOfWork.transactional` opens, for code outside the container.
|
||||
if (method === 'transactional' || (ts.isIdentifier(callee) && callee.text === 'writeTransaction')) {
|
||||
let inner = 0;
|
||||
frames.push([]); // what runs inside is one unit, not a list of its own
|
||||
for (const arg of node.arguments) inner += count(cls, arg, true);
|
||||
|
||||
@@ -168,6 +168,7 @@ OIDC_*, SMTP_*, FORCE_HTTPS, COOKIE_SECURE,
|
||||
ALLOWED_ORIGINS, UNSPLASH_ACCESS_KEY, WEBAUTHN_*, TZ, ADMIN_EMAIL,
|
||||
TREK_DB_PRE_MIGRATE_SNAPSHOT(_KEEP) (read when a migration run starts; the
|
||||
legacy-upgrade suites set it per file),
|
||||
TREK_DB_IGNORE_SQLITE_FILE (read when a Postgres boot finds no TREK data),
|
||||
ADMIN_PASSWORD, IDEMPOTENCY_TTL_SECONDS, MCP_RATE_LIMIT (request-path check),
|
||||
LLM_TIMEOUT_MS, LLM_MAX_OUTPUT_TOKENS, NOMINATIM_URL, VAPID_* (resolved per use by the Web Push key
|
||||
service, which the notification suites build without the container).
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
/** The databases TREK can run on. MySQL and MariaDB are out of scope (server/CLAUDE.md). */
|
||||
export type EngineId = 'sqlite' | 'postgres';
|
||||
|
||||
/**
|
||||
* Which database this process runs on, as `deriveDb` reads it from
|
||||
* `TREK_DB_URL`. The Postgres arm carries what its pool needs, so nothing
|
||||
* downstream has to check the URL again.
|
||||
*/
|
||||
export type DbEngineSettings = { engine: 'sqlite' } | { engine: 'postgres'; url: string; poolMax: number };
|
||||
|
||||
/** The most connections the Postgres pool opens (`TREK_DB_POOL_MAX` is refused above it). */
|
||||
export const DB_POOL_MAX_CEILING = 100;
|
||||
/** The pool size when `TREK_DB_POOL_MAX` is unset. */
|
||||
export const DB_POOL_MAX_DEFAULT = 10;
|
||||
@@ -14,6 +14,7 @@
|
||||
* call, which is what keeps the runtime env-mutation semantics the test suite
|
||||
* depends on. Zod validation runs once at boot (env.schema.ts), never here.
|
||||
*/
|
||||
import { DB_POOL_MAX_CEILING, DB_POOL_MAX_DEFAULT, type DbEngineSettings } from './db-settings';
|
||||
import { imageVersion } from './image-version';
|
||||
import {
|
||||
csvList,
|
||||
@@ -348,9 +349,25 @@ export function deriveBackup(raw: RawEnv) {
|
||||
};
|
||||
}
|
||||
|
||||
/** The database settings `readEnv().db` answers with. */
|
||||
export type DbSettings = ReturnType<typeof deriveDb>;
|
||||
|
||||
export function deriveDb(raw: RawEnv) {
|
||||
const durability = resolveDurability(raw.TREK_DB_JOURNAL_MODE, raw.TREK_DB_SYNCHRONOUS);
|
||||
const url = raw.TREK_DB_URL?.trim() || undefined;
|
||||
const engine: DbEngineSettings = url
|
||||
? {
|
||||
engine: 'postgres',
|
||||
// The connection URL carries the password, so it is never logged (db/engine/redact-url.ts).
|
||||
url,
|
||||
poolMax: Math.min(positiveIntOr(raw.TREK_DB_POOL_MAX, DB_POOL_MAX_DEFAULT), DB_POOL_MAX_CEILING),
|
||||
}
|
||||
: { engine: 'sqlite' };
|
||||
return {
|
||||
/** Which database this process runs on: Postgres when TREK_DB_URL names one, the SQLite file otherwise. */
|
||||
...engine,
|
||||
/** Where pg_dump and pg_restore are; unset, the usual install directories are tried (never PATH). */
|
||||
pgBinDir: raw.TREK_DB_PG_BIN_DIR?.trim() || undefined,
|
||||
trekDbFile: raw.TREK_DB_FILE,
|
||||
/** Resolved journal_mode — WAL unless the operator asked for something else (network storage needs DELETE/TRUNCATE). */
|
||||
journalMode: durability.journalMode,
|
||||
@@ -366,6 +383,11 @@ export function deriveDb(raw: RawEnv) {
|
||||
preMigrateSnapshot: parseBool(raw.TREK_DB_PRE_MIGRATE_SNAPSHOT),
|
||||
/** How many pre-migration snapshots stay in the data dir, newest first. */
|
||||
preMigrateSnapshotKeep: Math.min(positiveIntOr(raw.TREK_DB_PRE_MIGRATE_SNAPSHOT_KEEP, 3), 100),
|
||||
/**
|
||||
* Start on Postgres although data/travel.db holds a SQLite install with
|
||||
* accounts. Only an explicit true: anything else keeps the refusal.
|
||||
*/
|
||||
ignoreSqliteFile: parseBool(raw.TREK_DB_IGNORE_SQLITE_FILE) === true,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
* listed here pass through untouched (Zod strips unknown keys, it does not
|
||||
* reject them).
|
||||
*/
|
||||
import { DB_POOL_MAX_CEILING } from './db-settings';
|
||||
import {
|
||||
isP256PrivateKey,
|
||||
isServiceKeyShape,
|
||||
@@ -51,6 +52,14 @@ const url = optionalWith((v) => {
|
||||
return false;
|
||||
}
|
||||
}, 'must be a valid URL (with protocol)');
|
||||
/** A Postgres connection URL: TREK_DB_URL names no other engine. */
|
||||
const postgresUrl = optionalWith((v) => {
|
||||
try {
|
||||
return ['postgres:', 'postgresql:'].includes(new URL(v).protocol);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}, 'must be a postgres:// or postgresql:// URL');
|
||||
const duration = optionalWith((v) => parseDurationMs(v) != null, 'must be a duration like "1h", "7d" or "30d"');
|
||||
const oneOf = (values: string[]) =>
|
||||
optionalWith((v) => values.includes(v.toLowerCase()), `must be one of: ${values.join(', ')}`);
|
||||
@@ -170,6 +179,11 @@ export const envSchema = z.object({
|
||||
Path: anyString,
|
||||
|
||||
// Data / paths
|
||||
// A Postgres database instead of the SQLite file. Its value is a secret (it
|
||||
// carries the password), so it is masked in the boot report.
|
||||
TREK_DB_URL: postgresUrl,
|
||||
TREK_DB_POOL_MAX: integer(1, DB_POOL_MAX_CEILING),
|
||||
TREK_DB_PG_BIN_DIR: anyString,
|
||||
TREK_DB_FILE: anyString,
|
||||
// The two SQLite pragmas are deliberately unvalidated: a typo here must fall
|
||||
// back and warn rather than abort boot, because reset-admin.js — the way out
|
||||
@@ -183,6 +197,10 @@ export const envSchema = z.object({
|
||||
// or a misspelt "on" turn it off.
|
||||
TREK_DB_PRE_MIGRATE_SNAPSHOT: boolStr,
|
||||
TREK_DB_PRE_MIGRATE_SNAPSHOT_KEEP: integer(1, 100),
|
||||
// Starts on an empty Postgres database although the data directory holds a
|
||||
// SQLite install with accounts, which the boot otherwise refuses. Strict like
|
||||
// the switch above: a misspelt value must not let the refusal through.
|
||||
TREK_DB_IGNORE_SQLITE_FILE: boolStr,
|
||||
TREK_WIKI_DIR: anyString,
|
||||
TREK_PLACE_PHOTO_DIR: anyString,
|
||||
BACKUP_UPLOAD_LIMIT_MB: positiveNumber,
|
||||
|
||||
@@ -33,6 +33,7 @@ export const SECRET_ENV_KEYS: ReadonlySet<string> = new Set([
|
||||
'MAPBOX_ACCESS_TOKEN',
|
||||
'CARTO_API_KEY',
|
||||
'DEMO_ADMIN_PASS',
|
||||
'TREK_DB_URL',
|
||||
'MAIL_INGEST_IMAP_PASS',
|
||||
'MAIL_INGEST_WEBHOOK_SECRET',
|
||||
]);
|
||||
@@ -97,7 +98,7 @@ export function validateEnvAtBoot(raw: RawEnv = process.env as RawEnv): void {
|
||||
const key = String(issue.path[0]);
|
||||
return ` - ${key}=${reportedValue(key, raw[key])}: ${issue.message}`;
|
||||
});
|
||||
lines.push(...managedPreconditions(raw));
|
||||
lines.push(...databasePreconditions(raw), ...managedPreconditions(raw));
|
||||
if (lines.length === 0) return;
|
||||
console.error(`Invalid environment configuration:\n${lines.join('\n')}`);
|
||||
throw new Error(
|
||||
@@ -106,6 +107,25 @@ export function validateEnvAtBoot(raw: RawEnv = process.env as RawEnv): void {
|
||||
);
|
||||
}
|
||||
|
||||
/** The SQLite settings that mean nothing next to TREK_DB_URL. */
|
||||
const SQLITE_ONLY_DB_KEYS = ['TREK_DB_FILE', 'TREK_DB_JOURNAL_MODE', 'TREK_DB_SYNCHRONOUS'] as const;
|
||||
|
||||
/**
|
||||
* Cross-field rules for the database engine. TREK_DB_URL beside a SQLite
|
||||
* setting names two databases, and either guess would leave the operator on
|
||||
* the one they did not mean: it refuses instead (fail closed, see
|
||||
* server/CLAUDE.md). The URL itself never reaches the report.
|
||||
*/
|
||||
function databasePreconditions(raw: RawEnv): string[] {
|
||||
if (!raw.TREK_DB_URL?.trim()) return [];
|
||||
const sqliteKeys = SQLITE_ONLY_DB_KEYS.filter((key) => raw[key]?.trim());
|
||||
if (sqliteKeys.length === 0) return [];
|
||||
return [
|
||||
` - ambiguous database configuration: TREK_DB_URL is set together with ${sqliteKeys.join(', ')}, ` +
|
||||
'which only apply to the SQLite file. Unset one side.',
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Cross-field rules that only apply to a centrally administered install.
|
||||
*
|
||||
|
||||
@@ -2,6 +2,7 @@ export { readEnv, validateEnvAtBoot } from './env';
|
||||
export { getAppUrl, getMcpSafeUrl } from './app-url';
|
||||
export { runningVersion } from './running-version';
|
||||
export type { AppEnv, RawEnv } from './env';
|
||||
export type { DbSettings } from './derive';
|
||||
export {
|
||||
deriveAll,
|
||||
deriveApp,
|
||||
|
||||
@@ -4,6 +4,7 @@ import { applyGlobalMiddleware, routingCspOrigins } from './middleware/globalMid
|
||||
import { httpConfig } from './nest/app-config';
|
||||
import { AppModule } from './nest/app.module';
|
||||
import { apiDocsEnabled } from './nest/common/api-docs.kill-switch';
|
||||
import { nulFreeRequest } from './nest/common/nul-free-input';
|
||||
import { validateBodyContracts } from './nest/common/validate-body-contracts';
|
||||
import { validateManagedRoutes } from './nest/common/validate-managed-routes';
|
||||
import { PUBLIC_ROUTE_ALLOW_LIST, validateRouteGuards } from './nest/common/validate-route-guards';
|
||||
@@ -49,6 +50,7 @@ import nodeHttp from 'node:http';
|
||||
* 4b. setupApiDocs — Swagger UI/spec at /api/docs* when TREK_API_DOCS_ENABLED.
|
||||
* 4c. the named body-parser wrappers — the global 100kb JSON/urlencoded
|
||||
* parsers, exempting /mcp so the MCP SDK reads the raw stream.
|
||||
* 4d. nulFreeRequest — drops NUL from the path, query, body and cookies.
|
||||
* 5. app.init() — every domain controller, including the transport surface
|
||||
* that used to live pre-init: /api/health (FeaturesController), OAuth
|
||||
* discovery documents (DiscoveryController), the /oauth/consent COOP
|
||||
@@ -228,6 +230,11 @@ export async function buildApp(): Promise<INestApplication> {
|
||||
instance.use(function urlencodedParser(req: Request, res: Response, next: NextFunction) {
|
||||
return isMcp(req) ? next() : urlencoded(req, res, next);
|
||||
});
|
||||
// Every request value without NUL from here on (nest/common/nul-free-input.ts):
|
||||
// the path, the query string, the parsed body and the cookies, before any
|
||||
// guard, interceptor or controller reads them, so a key or a check made from
|
||||
// a value matches what the database stores for it.
|
||||
instance.use(nulFreeRequest);
|
||||
if (apiDocsEnabled()) setupApiDocs(app);
|
||||
// The per-request EntityManager fork every Nest route runs inside (D6). This
|
||||
// used to be @mikro-orm/nestjs's own middleware, which Nest 11 mounts as an
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
import { isPostgres, isSqlite, unsupported } from './platform';
|
||||
import type { Platform } from '@mikro-orm/core';
|
||||
|
||||
/**
|
||||
* The schema catalog, for the migrations' helpers (`db/migration-utils.ts`):
|
||||
* which tables and columns exist, each spelled the way its engine keeps them.
|
||||
* Both statements take the table name as their one bound parameter and answer
|
||||
* one row per hit with the name in `name`. Postgres reads the current schema
|
||||
* only, the one TREK's own tables live in.
|
||||
*/
|
||||
|
||||
/** Lists the columns of the table bound as `?`, one `name` per row; none for a missing table. */
|
||||
export function columnNamesSql(platform: Platform): string {
|
||||
if (isSqlite(platform)) return 'select name from pragma_table_info(?)';
|
||||
if (isPostgres(platform)) {
|
||||
return 'select column_name as name from information_schema.columns where table_schema = current_schema() and table_name = ?';
|
||||
}
|
||||
return unsupported(platform);
|
||||
}
|
||||
|
||||
/** One row when the table bound as `?` exists, none otherwise. */
|
||||
export function tableExistsSql(platform: Platform): string {
|
||||
if (isSqlite(platform)) return "select name from sqlite_master where type = 'table' and name = ?";
|
||||
if (isPostgres(platform)) {
|
||||
return 'select table_name as name from information_schema.tables where table_schema = current_schema() and table_name = ?';
|
||||
}
|
||||
return unsupported(platform);
|
||||
}
|
||||
|
||||
/**
|
||||
* The tables in the current schema, one `table_name` per row in name order:
|
||||
* the schema TREK's own tables live in. Postgres only, and the one definition
|
||||
* of that question: the bootstrap reads it through the connection, the client
|
||||
* tools' table listing hands it to psql.
|
||||
*/
|
||||
export const CURRENT_SCHEMA_TABLES_SQL =
|
||||
'select table_name from information_schema.tables where table_schema = current_schema() order by table_name';
|
||||
@@ -0,0 +1,35 @@
|
||||
import { isPostgres, isSqlite, unsupported } from './platform';
|
||||
import type { Platform } from '@mikro-orm/core';
|
||||
|
||||
/**
|
||||
* Schema statements a migration writes once per engine.
|
||||
*
|
||||
* A migration after the Postgres baseline's cut (`through` in
|
||||
* `assets/postgres/baseline.json`) runs on both engines, and their DDL is not
|
||||
* one language: SQLite rebuilds a table where Postgres alters it, and the
|
||||
* Postgres side has to read exactly as MikroORM generates it from the entities
|
||||
* (`bigint`, `bigserial` ids, `<table>_<column>_foreign` keys), or PARITY-PG
|
||||
* fails. So a migration hands both spellings to `engineDdl` in
|
||||
* `db/migration-utils.ts`, which picks the one for the engine it runs on here;
|
||||
* `npm run gen:pg-migration` writes the Postgres side and `lint:dialect`
|
||||
* refuses DDL a newer migration spells outside it.
|
||||
*/
|
||||
|
||||
/** One value per engine, picked by the platform the migration runs on. */
|
||||
interface PerEngine<T> {
|
||||
readonly sqlite: T;
|
||||
readonly postgres: T;
|
||||
}
|
||||
|
||||
/** The statements of one schema change, in the order they run, per engine. */
|
||||
export type EngineDdl = PerEngine<readonly string[]>;
|
||||
|
||||
/** A column definition (`status TEXT DEFAULT 'pending'`) per engine, for `addColumnIfMissing`. */
|
||||
export type EngineColumn = PerEngine<string>;
|
||||
|
||||
/** The member of `choices` for the engine behind `platform`; any other engine is refused. */
|
||||
export function forEngine<T>(platform: Platform, choices: PerEngine<T>): T {
|
||||
if (isSqlite(platform)) return choices.sqlite;
|
||||
if (isPostgres(platform)) return choices.postgres;
|
||||
return unsupported(platform);
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { TableNotFoundException } from '@mikro-orm/core';
|
||||
|
||||
/**
|
||||
* What a database error says, read the same way on both engines. The engines
|
||||
* report the same failure differently: SQLite (better-sqlite3) in the message
|
||||
* text, Postgres (`pg`) in a SQLSTATE `code` and, for a constraint, the
|
||||
* constraint's name. MikroORM's exception classes carry both: they copy every
|
||||
* property of the driver's error. Code outside the dialect layer asks these
|
||||
* functions instead of matching either engine's text.
|
||||
*/
|
||||
|
||||
/** Postgres's SQLSTATE for a unique violation. */
|
||||
const PG_UNIQUE_VIOLATION = '23505';
|
||||
/** Postgres's SQLSTATE for an unknown table. */
|
||||
const PG_UNDEFINED_TABLE = '42P01';
|
||||
/** SQLite's unique violation: `UNIQUE constraint failed: users.email` or `... index 'idx_users_email_lower'`. */
|
||||
const SQLITE_UNIQUE = /UNIQUE constraint failed: ([^\n]+)/;
|
||||
|
||||
/** The error's own properties a driver sets, read without trusting their types. */
|
||||
function driverFields(err: unknown): { message: string; code: unknown; constraint: unknown } | null {
|
||||
if (!(err instanceof Error)) return null;
|
||||
const fields = err as Error & { code?: unknown; constraint?: unknown };
|
||||
return { message: err.message, code: fields.code, constraint: fields.constraint };
|
||||
}
|
||||
|
||||
/**
|
||||
* The key a unique violation names, or null when `err` is not one. On
|
||||
* Postgres it is the constraint or index name (`users_email_unique`,
|
||||
* `idx_users_email_lower`); on SQLite the columns (`users.email`) or the
|
||||
* index (`index 'idx_users_email_lower'`). A caller matches the names of
|
||||
* both engines, which the baselines fix.
|
||||
*/
|
||||
export function uniqueViolationKey(err: unknown): string | null {
|
||||
const fields = driverFields(err);
|
||||
if (!fields) return null;
|
||||
if (fields.code === PG_UNIQUE_VIOLATION) return typeof fields.constraint === 'string' ? fields.constraint : '';
|
||||
return SQLITE_UNIQUE.exec(fields.message)?.[1].trim() ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a statement failed because its table does not exist: MikroORM's
|
||||
* `TableNotFoundException` (both engines), or the driver's own error where it
|
||||
* reached the caller unconverted (SQLite's message, Postgres's 42P01).
|
||||
*/
|
||||
export function isMissingTableError(err: unknown): boolean {
|
||||
if (err instanceof TableNotFoundException) return true;
|
||||
const fields = driverFields(err);
|
||||
return fields !== null && (fields.code === PG_UNDEFINED_TABLE || fields.message.includes('no such table'));
|
||||
}
|
||||
@@ -167,6 +167,23 @@ export function castIntegerKysely<DB, TB extends keyof DB>(
|
||||
return unsupported(platform);
|
||||
}
|
||||
|
||||
/**
|
||||
* `<text ref> = <integer ref>` for a TEXT column that holds an integer id,
|
||||
* written either bare or the way the services store it (`'14'`, `'14.0'`):
|
||||
* the text goes through {@link castIntegerKysely}, so both engines match
|
||||
* `'14'`, `'14.0'` and a stored 14 against the id 14 alike. A bare cast to
|
||||
* integer would do on SQLite, but Postgres refuses `CAST('14.0' AS integer)`
|
||||
* (22P02), and a bare text-to-integer comparison (42883).
|
||||
*/
|
||||
export function integerTextEqualsKysely<DB, TB extends keyof DB>(
|
||||
platform: Platform,
|
||||
eb: ExpressionBuilder<DB, TB>,
|
||||
text: ReferenceExpression<DB, TB>,
|
||||
integer: StringReference<DB, TB>,
|
||||
): ExpressionWrapper<DB, TB, SqlBool> {
|
||||
return eb(castIntegerKysely(platform, eb, text), '=', eb.ref(integer).$castTo<number>());
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Plan 3g Task 0 (R1) — no consumer yet: Task 1 (`getJourneyFull`'s gallery
|
||||
// read) and Task 3 (`getPublicJourney`'s gallery read) each fold this into
|
||||
|
||||
@@ -538,6 +538,20 @@ export function castInteger(platform: Platform, ref: string): RawQueryFragment &
|
||||
return unsupported(platform);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether `text` is a date as `YYYY-MM-DD` that the calendar has: `2024-02-29`
|
||||
* is one, `2024-02-30` and `2023-02-29` are not. A bound value either engine
|
||||
* reads as a date goes through this first, since SQLite rolls an impossible
|
||||
* day over into the next month while Postgres refuses it.
|
||||
*/
|
||||
export function isCalendarDate(text: string): boolean {
|
||||
const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(text);
|
||||
if (!match) return false;
|
||||
const [, year, month, day] = match.map(Number);
|
||||
const date = new Date(Date.UTC(year, month - 1, day));
|
||||
return date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day;
|
||||
}
|
||||
|
||||
/**
|
||||
* `ABS(JULIANDAY(<col>) - JULIANDAY(?))` — the legacy shape at
|
||||
* `reservations.service.ts:307` (RS11, `resolveDayIdFromTime`'s
|
||||
@@ -557,8 +571,16 @@ export function castInteger(platform: Platform, ref: string): RawQueryFragment &
|
||||
* comment documents; ordering by the EXPRESSION itself is what works).
|
||||
* Postgres measures the same distance in days from the epoch difference of
|
||||
* the two values cast to `timestamp`.
|
||||
*
|
||||
* `isoDate` must be a real calendar date ({@link isCalendarDate}): Postgres
|
||||
* refuses to cast `2024-02-30` while SQLite's JULIANDAY rolls it over into
|
||||
* March, so the two engines would answer it differently. Any other value is
|
||||
* refused here, on both engines alike, and the caller checks first.
|
||||
*/
|
||||
export function dayDistance(platform: Platform, ref: string, isoDate: string): RawQueryFragment & symbol {
|
||||
if (!isCalendarDate(isoDate)) {
|
||||
throw new Error(`sql-functions: dayDistance needs a calendar date (YYYY-MM-DD), got ${JSON.stringify(isoDate)}`);
|
||||
}
|
||||
if (isSqlite(platform)) return raw(`ABS(JULIANDAY(${column(ref)}) - JULIANDAY(?))`, [isoDate]);
|
||||
if (isPostgres(platform)) {
|
||||
return raw(`ABS(EXTRACT(EPOCH FROM (CAST(${column(ref)} AS timestamp) - CAST(? AS timestamp))) / 86400)`, [
|
||||
@@ -620,6 +642,17 @@ export function collateNoCase(platform: Platform, ref: string): RawQueryFragment
|
||||
return unsupported(platform);
|
||||
}
|
||||
|
||||
/**
|
||||
* A search that ignores case over `refs`: `(a LIKE ? ESCAPE '\' OR b LIKE ?
|
||||
* ...)`, one bound pattern per column, the caller escaping `%`, `_` and `\`.
|
||||
* SQLite's `LIKE` already ignores case (ASCII letters only); Postgres's is
|
||||
* exact, so it gets `ILIKE`, which folds every letter.
|
||||
*/
|
||||
export function ilike(platform: Platform, refs: readonly string[]): string {
|
||||
const operator = isSqlite(platform) ? 'LIKE' : isPostgres(platform) ? 'ILIKE' : unsupported(platform);
|
||||
return `(${refs.map((ref) => `${column(ref)} ${operator} ? ESCAPE '\\'`).join(' OR ')})`;
|
||||
}
|
||||
|
||||
/**
|
||||
* `datetime('now', '-N hours')` — the hour-granularity sibling of
|
||||
* `nowMinusDays()` above, for `reminder-jobs.service.ts#todoTick`'s
|
||||
|
||||
@@ -18,13 +18,22 @@ export async function ensureEmailCaseIndex(connection: Connection): Promise<void
|
||||
const pending: unknown[] = await connection.execute(`SELECT value FROM app_settings WHERE key = ?`, [PENDING_KEY]);
|
||||
if (pending.length === 0) return;
|
||||
|
||||
const duplicates: Array<{ ids: string }> = await connection.execute(
|
||||
`SELECT group_concat(id, ', ') AS ids FROM (SELECT id, email FROM users ORDER BY id) GROUP BY lower(email) HAVING COUNT(*) > 1`,
|
||||
// Grouped here rather than with group_concat, which Postgres spells string_agg.
|
||||
const rows: Array<{ id: number; email_key: string }> = await connection.execute(
|
||||
`SELECT id, lower(email) AS email_key FROM users WHERE lower(email) IN ` +
|
||||
`(SELECT lower(email) FROM users GROUP BY lower(email) HAVING COUNT(*) > 1) ORDER BY id`,
|
||||
);
|
||||
if (duplicates.length > 0) {
|
||||
const duplicates = new Map<string, number[]>();
|
||||
for (const row of rows) {
|
||||
const group = duplicates.get(row.email_key);
|
||||
if (group) group.push(row.id);
|
||||
else duplicates.set(row.email_key, [row.id]);
|
||||
}
|
||||
if (duplicates.size > 0) {
|
||||
const ids = [...duplicates.values()].map((group) => group.join(', '));
|
||||
console.warn(
|
||||
`[DB] ${duplicates.length} email address(es) still belong to more than one account when case is ignored ` +
|
||||
`(user ids ${duplicates.map((row) => row.ids).join('; ')}), so users.email has no case-insensitive unique ` +
|
||||
`[DB] ${duplicates.size} email address(es) still belong to more than one account when case is ignored ` +
|
||||
`(user ids ${ids.join('; ')}), so users.email has no case-insensitive unique ` +
|
||||
'index yet. Give each of those accounts its own address under Admin > Users; the next start creates it.',
|
||||
);
|
||||
return;
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import type { EngineId } from '../../app-config/db-settings';
|
||||
import type { AnyOrm } from '../orm';
|
||||
import type { EntityManager, Options } from '@mikro-orm/core';
|
||||
|
||||
/**
|
||||
* One database engine: what the ORM needs to reach it, how the connection
|
||||
* opens, closes and comes back after a restore, and how a database is brought
|
||||
* to the current schema. Code that differs by engine dispatches through this,
|
||||
* or through the helpers in `db/dialect/`, never through its own platform
|
||||
* check (`lint:engine-dispatch`).
|
||||
*
|
||||
* Free of Nest like every other file under `db/`: `src/db` does not import
|
||||
* `src/nest` (`lint:boundaries`). `DatabaseLifecycle` is the provider that
|
||||
* calls it.
|
||||
*/
|
||||
export interface DatabaseEngine {
|
||||
readonly id: EngineId;
|
||||
/** For log lines and errors: the file path, or the URL without its password. */
|
||||
describe(): string;
|
||||
/** What MikroORM needs to reach the database: the driver and its target, the pool, driver options. */
|
||||
ormOptions(): Partial<Options>;
|
||||
/**
|
||||
* Called once at boot, before the schema bootstrap. `onReopened` runs after
|
||||
* each later reopen, once the ORM is pointed at the reopened database: the
|
||||
* engine does what its own reopen needs first (SQLite hands the ORM a new
|
||||
* handle, so the ORM's connection is closed and connected again), then calls
|
||||
* it, and the caller migrates the database and runs whatever follows.
|
||||
*/
|
||||
open(orm: AnyOrm, onReopened: () => Promise<void>): void;
|
||||
/** Closes what the engine itself holds; the ORM's own pool is closed with the Nest container. */
|
||||
close(): void;
|
||||
/**
|
||||
* Comes back after the database was replaced by a restore, then runs the
|
||||
* `onReopened` that `open` registered. Throws when `open` has not run.
|
||||
*/
|
||||
reopen(): Promise<void>;
|
||||
/**
|
||||
* Brings the database to the current schema, then seeds it. `snapshot:
|
||||
* false` skips the copy taken before pending migrations (a restore, whose
|
||||
* archive is the copy).
|
||||
*/
|
||||
schemaBootstrap(orm: AnyOrm, options: { snapshot: boolean }): Promise<void>;
|
||||
/**
|
||||
* Runs first in every `UnitOfWork` transaction, on its EntityManager: makes
|
||||
* the transactions that write run one at a time, as SQLite's single writer
|
||||
* does, so a `MAX(...) + 1` read inside one cannot race another.
|
||||
*/
|
||||
serializeWrites(em: EntityManager): Promise<void>;
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import { readEnv } from '../../app-config';
|
||||
import type { DbEngineSettings } from '../../app-config/db-settings';
|
||||
import type { DbSettings } from '../../app-config/derive';
|
||||
import { ALL_ENTITIES } from '../entities';
|
||||
import { SharedSqliteDriver } from '../orm-driver';
|
||||
import type { DatabaseEngine } from './engine';
|
||||
import { PostgresEngine } from './postgres/postgres-engine';
|
||||
import { SqliteEngine } from './sqlite/sqlite-engine';
|
||||
import { defineConfig, type Options } from '@mikro-orm/core';
|
||||
import { Migrator } from '@mikro-orm/migrations';
|
||||
import { SeedManager } from '@mikro-orm/seeder';
|
||||
|
||||
export type { DatabaseEngine } from './engine';
|
||||
|
||||
/**
|
||||
* The engine this process runs on, from `TREK_DB_URL` (`readEnv().db`): the
|
||||
* SQLite file unless the URL names a Postgres database. Read afresh on every
|
||||
* call, like everything `readEnv()` answers, so nothing caches a choice a test
|
||||
* or a restart changes.
|
||||
*/
|
||||
export function resolveEngine(db: DbEngineSettings = readEnv().db): DatabaseEngine {
|
||||
if (db.engine === 'postgres') return new PostgresEngine(db);
|
||||
return new SqliteEngine();
|
||||
}
|
||||
|
||||
/**
|
||||
* The Postgres URL, the directory of its client tools and the pool's size,
|
||||
* when the settings name a Postgres database; null on SQLite. For the code
|
||||
* that drives pg_dump and pg_restore, which needs the first two, and the
|
||||
* plugin data stores, which share the pool, and must not read them from the
|
||||
* environment again.
|
||||
*/
|
||||
export function postgresTarget(db: DbSettings): { url: string; binDir: string | undefined; poolMax: number } | null {
|
||||
if (db.engine !== 'postgres') return null;
|
||||
return { url: db.url, binDir: db.pgBinDir, poolMax: db.poolMax };
|
||||
}
|
||||
|
||||
/**
|
||||
* Refuses an ORM config that does not run on the SQLite engine, with
|
||||
* `refusal` as the error. For the code that exists only for SQLite (the test
|
||||
* schema snapshot), which must say so instead of starting a SQLite ORM on
|
||||
* another engine's options; the check on the driver stays here, in the
|
||||
* engine port, like every other question about the engine.
|
||||
*/
|
||||
export function assertSqliteOrmConfig(config: Options, refusal: string): void {
|
||||
if (config.driver !== SharedSqliteDriver) throw new Error(refusal);
|
||||
}
|
||||
|
||||
/**
|
||||
* The MikroORM config for `engine`: what every engine shares (entities,
|
||||
* migrations, seeders) and what the engine adds. `src/mikro-orm.config.ts`
|
||||
* exports it for the CLI and the Nest container, so both reach the same
|
||||
* database.
|
||||
*/
|
||||
export function buildOrmConfig(engine: DatabaseEngine): Options {
|
||||
return defineConfig({
|
||||
entities: ALL_ENTITIES,
|
||||
extensions: [Migrator, SeedManager],
|
||||
migrations: {
|
||||
path: 'dist/db/migrations',
|
||||
pathTs: 'src/db/migrations',
|
||||
snapshot: false,
|
||||
},
|
||||
seeder: {
|
||||
path: 'dist/db/seeders',
|
||||
pathTs: 'src/db/seeders',
|
||||
defaultSeeder: 'DatabaseSeeder',
|
||||
},
|
||||
...engine.ormOptions(),
|
||||
}) as Options;
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import type { EngineId } from '../../app-config/db-settings';
|
||||
|
||||
/**
|
||||
* A plugin's own database (`db:own`), as the host's RPC handlers reach it.
|
||||
* One implementation per engine: on SQLite a file of the plugin's own
|
||||
* (`nest/plugins/host/plugin-data.service.ts`), on Postgres a schema of the
|
||||
* plugin's own (`postgres/plugin-data-store.ts`). The plugin's SQL is its
|
||||
* own, written for the engine `engine` names; neither implementation
|
||||
* translates it.
|
||||
*
|
||||
* The SQLite handle answers synchronously, the Postgres one with a promise,
|
||||
* so every method may return either. The caller awaits the result.
|
||||
*/
|
||||
export interface PluginDataStore {
|
||||
readonly pluginId: string;
|
||||
/** The engine the plugin's SQL runs on, which decides the SQL dialect it has to be written in. */
|
||||
readonly engine: EngineId;
|
||||
/** One read statement: its rows, up to the row cap and within the time budget. */
|
||||
query(sql: string, args?: unknown[]): MaybePromise<unknown[]>;
|
||||
/** One statement with bound args, or a script of statements without. */
|
||||
exec(sql: string, args?: unknown[]): MaybePromise<{ changes: number }>;
|
||||
/** Statements that commit or roll back together. */
|
||||
tx(ops: PluginTxOp[]): MaybePromise<PluginTxResult>;
|
||||
/** Runs `sql` once per `id`; a second call with the same id is a no-op. */
|
||||
migrate(id: string, sql: string): MaybePromise<{ applied: boolean }>;
|
||||
/** False once `close` ran: the host then opens a new store instead of reusing this one. */
|
||||
isOpen(): boolean;
|
||||
close(): void;
|
||||
}
|
||||
|
||||
type MaybePromise<T> = T | Promise<T>;
|
||||
|
||||
/** One statement of a `tx` batch. */
|
||||
export interface PluginTxOp {
|
||||
sql: string;
|
||||
args?: unknown[];
|
||||
}
|
||||
|
||||
/** A `tx` batch's results, one per op: the rows of a statement that returns rows, the change count of any other. */
|
||||
export interface PluginTxResult {
|
||||
results: Array<{ changes?: number; rows?: unknown[] }>;
|
||||
}
|
||||
|
||||
/**
|
||||
* The limits every plugin database is held to, whatever the engine. The
|
||||
* plugin-sdk README's "Runtime limits" table documents them.
|
||||
*/
|
||||
export const PLUGIN_DATA_CAPS = {
|
||||
/** The longest SQL text one call may carry. */
|
||||
maxSqlLength: 100_000,
|
||||
/** The most rows a query, or a whole tx batch, returns. */
|
||||
maxRows: 100_000,
|
||||
/** The most statements one tx batch holds. */
|
||||
maxTxOps: 100,
|
||||
/** Wall-clock time for one query, one tx batch or one exec script. */
|
||||
timeBudgetMs: 2_000,
|
||||
/** The most a plugin's data may take on disk. */
|
||||
quotaBytes: 256 * 1024 * 1024,
|
||||
} as const;
|
||||
@@ -0,0 +1,93 @@
|
||||
import { splitStatements } from './sql-split';
|
||||
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
/**
|
||||
* Where the Postgres baseline lives: `server/assets/postgres/`, which the
|
||||
* Docker image copies beside `dist/` (the same place the airports and atlas
|
||||
* data are read from), reached the same way from `src/` and from `dist/`.
|
||||
*/
|
||||
const BASELINE_DIR = path.join(__dirname, '..', '..', '..', '..', 'assets', 'postgres');
|
||||
const SQL_FILE = 'baseline.sql';
|
||||
const MANIFEST_FILE = 'baseline.json';
|
||||
|
||||
/** The manifest beside the SQL: the last migration the baseline stands for, and every migration it replaces. */
|
||||
interface BaselineManifest {
|
||||
through: string;
|
||||
migrations: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* The schema a fresh Postgres database starts from.
|
||||
*
|
||||
* The migrations up to `through` are written in SQLite and frozen, so a
|
||||
* Postgres database does not replay them: it runs these statements, generated
|
||||
* from the entities (`npm run gen:pg-baseline`), and records every migration
|
||||
* in `migrations` as executed in the same transaction. Migrations after
|
||||
* `through` run on both engines through the migrator.
|
||||
*/
|
||||
export interface PostgresBaseline extends BaselineManifest {
|
||||
statements: string[];
|
||||
}
|
||||
|
||||
/** The two files a baseline is written as, ready to compare or write. */
|
||||
export function renderBaseline(baseline: PostgresBaseline): { sql: string; manifest: string } {
|
||||
return {
|
||||
sql:
|
||||
'-- The schema a fresh Postgres database starts from. Generated by `npm run gen:pg-baseline`; do not edit.\n' +
|
||||
baseline.statements.map((statement) => `${statement};\n`).join(''),
|
||||
manifest: `${JSON.stringify({ through: baseline.through, migrations: baseline.migrations }, null, 2)}\n`,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether `data` is a manifest a baseline can be read from: a `through` naming
|
||||
* one of a non-empty list of `migrations`, every entry a string.
|
||||
*/
|
||||
function isBaselineManifest(data: unknown): data is BaselineManifest {
|
||||
if (typeof data !== 'object' || data === null || !('through' in data) || !('migrations' in data)) return false;
|
||||
const { through, migrations } = data;
|
||||
return (
|
||||
typeof through === 'string' &&
|
||||
Array.isArray(migrations) &&
|
||||
migrations.length > 0 &&
|
||||
migrations.every((name): name is string => typeof name === 'string') &&
|
||||
migrations.includes(through)
|
||||
);
|
||||
}
|
||||
|
||||
function parseManifest(text: string, file: string): BaselineManifest {
|
||||
const data: unknown = JSON.parse(text);
|
||||
if (!isBaselineManifest(data)) throw new Error(`${file} must name "through" and list it among "migrations"`);
|
||||
return { through: data.through, migrations: data.migrations };
|
||||
}
|
||||
|
||||
/** Reads the committed baseline; a missing or malformed one throws, so a boot cannot start from half a schema. */
|
||||
export function readPostgresBaseline(dir = BASELINE_DIR): PostgresBaseline {
|
||||
const manifestFile = path.join(dir, MANIFEST_FILE);
|
||||
const manifest = parseManifest(fs.readFileSync(manifestFile, 'utf8'), manifestFile);
|
||||
const statements = splitStatements(fs.readFileSync(path.join(dir, SQL_FILE), 'utf8').replace(/^--[^\n]*\n/gm, ''));
|
||||
if (statements.length === 0) throw new Error(`${path.join(dir, SQL_FILE)} holds no statements`);
|
||||
// The boot sends the baseline as one statement without parameters, where a `?` would be read as a binding.
|
||||
if (statements.some((statement) => statement.includes('?'))) {
|
||||
throw new Error(`${path.join(dir, SQL_FILE)} holds a "?", which the boot would read as a parameter`);
|
||||
}
|
||||
return { ...manifest, statements };
|
||||
}
|
||||
|
||||
/** Writes the two files (the generator's `--write`). */
|
||||
export function writePostgresBaseline(baseline: PostgresBaseline, dir = BASELINE_DIR): void {
|
||||
const { sql, manifest } = renderBaseline(baseline);
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
fs.writeFileSync(path.join(dir, SQL_FILE), sql);
|
||||
fs.writeFileSync(path.join(dir, MANIFEST_FILE), manifest);
|
||||
}
|
||||
|
||||
/** Whether the committed files are what `baseline` renders to (the generator's `--check`). */
|
||||
export function baselineMatches(baseline: PostgresBaseline, dir = BASELINE_DIR): boolean {
|
||||
const { sql, manifest } = renderBaseline(baseline);
|
||||
const read = (file: string) =>
|
||||
fs.existsSync(path.join(dir, file)) ? fs.readFileSync(path.join(dir, file), 'utf8') : null;
|
||||
return read(SQL_FILE) === sql && read(MANIFEST_FILE) === manifest;
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import { PLUGIN_SCHEMA_PREFIX, quotePluginSchema } from './plugin-schema';
|
||||
|
||||
/**
|
||||
* Drops every table, view, sequence, routine, collation and standalone type in
|
||||
* the current schema, except an extension's, before a dump is loaded: a dump
|
||||
* only recreates what it holds, so whatever a later migration added would
|
||||
* otherwise survive the restore and break the migrations the reopen runs. It
|
||||
* runs in the same transaction as the load (`pgRestore`), so a restore that
|
||||
* fails leaves the database as it was.
|
||||
*/
|
||||
export const CLEAR_SCHEMA_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$;
|
||||
`;
|
||||
|
||||
/**
|
||||
* Drops every plugin data schema TREK's role owns, then creates the ones
|
||||
* `schemas` names (a dump's) empty, for the restore script to fill: the script
|
||||
* holds what is in them, never the schemas themselves. Runs right after
|
||||
* CLEAR_SCHEMA_SQL, in the same transaction. A schema another role owns is
|
||||
* never dropped, whatever its name.
|
||||
*/
|
||||
export function pluginSchemasSql(schemas: readonly string[]): string {
|
||||
const drop = `DO $plugins$
|
||||
DECLARE r record;
|
||||
BEGIN
|
||||
FOR r IN SELECT nspname FROM pg_namespace
|
||||
WHERE starts_with(nspname, '${PLUGIN_SCHEMA_PREFIX}') AND pg_get_userbyid(nspowner) = current_user
|
||||
LOOP
|
||||
EXECUTE format('DROP SCHEMA %I CASCADE', r.nspname);
|
||||
END LOOP;
|
||||
END
|
||||
$plugins$;
|
||||
`;
|
||||
return drop + schemas.map((name) => `CREATE SCHEMA ${quotePluginSchema(name)};\n`).join('');
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
/**
|
||||
* What still separates a live Postgres database from the schema the entities
|
||||
* describe for Postgres (`schema-adjust.ts`): the one definition PARITY-PG
|
||||
* (`tests/postgres/schema-parity.test.ts`) holds at nothing and
|
||||
* `npm run gen:pg-migration` prints as the Postgres side of a new migration.
|
||||
*
|
||||
* MikroORM's comparator also reports statements that change nothing, and each
|
||||
* kind is proven so rather than recognised by its text alone:
|
||||
* - `drop not null` on a primary key column: SQLite lets a key column be null
|
||||
* and the entities say so; Postgres keeps every primary key NOT NULL (and
|
||||
* refuses the statement), checked against the live keys.
|
||||
* - a column default or a check constraint Postgres stores in its own
|
||||
* spelling (casts added, EXTRACT rewritten, BETWEEN as two comparisons):
|
||||
* such statements are applied in a transaction that is rolled back, and the
|
||||
* catalogue's own rendering of every default and check must read the same
|
||||
* after as before. A default or a bound that really differs changes it.
|
||||
* - dropping a trigger the entities cannot carry: only the triggers ported by
|
||||
* hand (`POSTGRES_TRIGGERS`), by exact name, and only while the trigger is in
|
||||
* the database on its table.
|
||||
*/
|
||||
import { ALL_ENTITIES } from '../../entities';
|
||||
import { POSTGRES_TRIGGERS } from './postgres-triggers';
|
||||
import { applyPostgresColumnAdjustments } from './schema-adjust';
|
||||
import type { Transaction } from '@mikro-orm/core';
|
||||
import { MikroORM } from '@mikro-orm/postgresql';
|
||||
import type { AbstractSqlConnection } from '@mikro-orm/sql';
|
||||
|
||||
const DROP_NOT_NULL = /^alter table "(\w+)" alter column "(\w+)" drop not null$/;
|
||||
const SPELLING =
|
||||
/^alter table "\w+" (?:alter column "\w+" set default .+|drop constraint "\w+"|add constraint "\w+" check \(.+\))$/s;
|
||||
/** MikroORM drops a trigger by its name, and the function it would have made for it as `<table>_<trigger>_fn`. */
|
||||
const DROP_TRIGGER = /^drop trigger if exists "(\w+)" on "(\w+)"$/;
|
||||
const DROP_FUNCTION = /^drop function if exists "(\w+)"\(\)$/;
|
||||
|
||||
/** Every column default and check constraint of the schema, as the catalogue renders them. */
|
||||
const FINGERPRINT_SQL = `select string_agg(item, E'\\n' order by item) as fingerprint from (
|
||||
select concat('default ', c.relname, '.', a.attname, ' = ', pg_get_expr(d.adbin, d.adrelid)) as item
|
||||
from pg_attrdef d join pg_class c on c.oid = d.adrelid join pg_attribute a on a.attrelid = d.adrelid and a.attnum = d.adnum
|
||||
where c.relnamespace = current_schema()::regnamespace
|
||||
union all
|
||||
select concat('check ', conrelid::regclass, '.', conname, ' = ', pg_get_constraintdef(oid))
|
||||
from pg_constraint where contype = 'c' and connamespace = current_schema()::regnamespace
|
||||
) items`;
|
||||
|
||||
const PRIMARY_KEYS_SQL = `select concat(c.relname, '.', a.attname) as name from pg_index i
|
||||
join pg_class c on c.oid = i.indrelid join pg_attribute a on a.attrelid = i.indrelid and a.attnum = any(i.indkey)
|
||||
where i.indisprimary and c.relnamespace = current_schema()::regnamespace`;
|
||||
|
||||
const TRIGGERS_SQL = `select concat(c.relname, '.', t.tgname) as name from pg_trigger t join pg_class c on c.oid = t.tgrelid
|
||||
where not t.tgisinternal and c.relnamespace = current_schema()::regnamespace`;
|
||||
|
||||
/** The facts of the live schema the classification needs, each as `<table>.<name>`. */
|
||||
export interface LiveSchemaFacts {
|
||||
primaryKeys: ReadonlySet<string>;
|
||||
triggers: ReadonlySet<string>;
|
||||
}
|
||||
|
||||
/** The comparator's statements sorted by what they would do. */
|
||||
interface ClassifiedDiff {
|
||||
/** Statements that change the schema: what a migration has to send. */
|
||||
changes: string[];
|
||||
/** Default and check statements that may only be Postgres's own spelling; `spellingChangesNothing` decides. */
|
||||
spelling: string[];
|
||||
/** `drop not null` on a live primary key, which Postgres keeps NOT NULL anyway. */
|
||||
keyNotNull: string[];
|
||||
/** Dropping a hand-ported trigger or its function. */
|
||||
portedTriggers: string[];
|
||||
}
|
||||
|
||||
/** The comparator's SQL (`getUpdateSchemaSQL({ wrap: false })`) as single statements without their semicolons. */
|
||||
export function splitSchemaDiff(sql: string): string[] {
|
||||
return sql
|
||||
.split(';\n')
|
||||
.map((statement) => statement.trim().replace(/;$/, ''))
|
||||
.filter((statement) => statement !== '');
|
||||
}
|
||||
|
||||
/** Sorts the comparator's statements; `ported` names the triggers `POSTGRES_TRIGGERS` carries. */
|
||||
export function classifySchemaDiff(
|
||||
statements: readonly string[],
|
||||
live: LiveSchemaFacts,
|
||||
ported: readonly string[] = Object.keys(POSTGRES_TRIGGERS),
|
||||
): ClassifiedDiff {
|
||||
const isKeyNotNull = (s: string) => {
|
||||
const m = DROP_NOT_NULL.exec(s);
|
||||
return m !== null && live.primaryKeys.has(`${m[1]}.${m[2]}`);
|
||||
};
|
||||
const isPortedTrigger = (s: string) => {
|
||||
const trigger = DROP_TRIGGER.exec(s);
|
||||
if (trigger) return ported.includes(trigger[1]) && live.triggers.has(`${trigger[2]}.${trigger[1]}`);
|
||||
const fn = DROP_FUNCTION.exec(s);
|
||||
return fn !== null && ported.some((name) => fn[1].endsWith(`_${name}_fn`));
|
||||
};
|
||||
const diff: ClassifiedDiff = { changes: [], spelling: [], keyNotNull: [], portedTriggers: [] };
|
||||
for (const statement of statements) {
|
||||
if (isKeyNotNull(statement)) diff.keyNotNull.push(statement);
|
||||
else if (isPortedTrigger(statement)) diff.portedTriggers.push(statement);
|
||||
else if (SPELLING.test(statement)) diff.spelling.push(statement);
|
||||
else diff.changes.push(statement);
|
||||
}
|
||||
return diff;
|
||||
}
|
||||
|
||||
/** The hand-ported triggers that are not in the live database. */
|
||||
export function missingPortedTriggers(
|
||||
live: LiveSchemaFacts,
|
||||
ported: readonly string[] = Object.keys(POSTGRES_TRIGGERS),
|
||||
): string[] {
|
||||
return ported.filter((name) => ![...live.triggers].some((t) => t.endsWith(`.${name}`)));
|
||||
}
|
||||
|
||||
/** Reads the live primary keys and triggers of the current schema. */
|
||||
async function readLiveSchemaFacts(connection: AbstractSqlConnection): Promise<LiveSchemaFacts> {
|
||||
const names = (sql: string) =>
|
||||
connection.execute<Array<{ name: string }>>(sql).then((rows) => new Set(rows.map((row) => row.name)));
|
||||
const [primaryKeys, triggers] = await Promise.all([names(PRIMARY_KEYS_SQL), names(TRIGGERS_SQL)]);
|
||||
return { primaryKeys, triggers };
|
||||
}
|
||||
|
||||
const ROLLBACK = new Error('roll back the spelling check');
|
||||
|
||||
/**
|
||||
* The catalogue's rendering of every default and check before and after
|
||||
* `statements`, applied in a transaction that is always rolled back: equal
|
||||
* means they change nothing.
|
||||
*/
|
||||
export async function spellingChangesNothing(
|
||||
connection: AbstractSqlConnection,
|
||||
statements: readonly string[],
|
||||
): Promise<{ before: string; after: string }> {
|
||||
const fingerprint = async (trx?: Transaction) =>
|
||||
(await connection.execute<Array<{ fingerprint: string }>>(FINGERPRINT_SQL, [], 'all', trx))[0].fingerprint;
|
||||
const before = await fingerprint();
|
||||
let after = '';
|
||||
await connection
|
||||
.transactional(async (trx) => {
|
||||
// One after the other: a drop and the add that follows name the same constraint.
|
||||
await statements.reduce<Promise<unknown>>(
|
||||
(previous, statement) => previous.then(() => connection.execute(statement, [], 'run', trx)),
|
||||
Promise.resolve(),
|
||||
);
|
||||
after = await fingerprint(trx);
|
||||
throw ROLLBACK;
|
||||
})
|
||||
.catch((err: unknown) => {
|
||||
if (err !== ROLLBACK) throw err;
|
||||
});
|
||||
return { before, after };
|
||||
}
|
||||
|
||||
/** Everything the comparison of one database with the entities found. */
|
||||
export interface EntitySchemaDiff extends ClassifiedDiff {
|
||||
/** Whether the `spelling` statements leave every default and check as it was. */
|
||||
spellingHolds: boolean;
|
||||
/** The catalogue's defaults and checks before and after the spelling statements, for a failure message. */
|
||||
fingerprint: { before: string; after: string };
|
||||
/** Hand-ported triggers missing from the database. */
|
||||
missingTriggers: string[];
|
||||
}
|
||||
|
||||
/** The statements a migration must still send: the changes, and the spelling ones when they are more than spelling. */
|
||||
export function remainingStatements(diff: EntitySchemaDiff): string[] {
|
||||
return diff.spellingHolds ? [...diff.changes] : [...diff.changes, ...diff.spelling];
|
||||
}
|
||||
|
||||
/**
|
||||
* Compares the database `url` names with the entities, read for Postgres the
|
||||
* way the baseline writes them. Nothing in the database changes.
|
||||
*/
|
||||
export async function diffAgainstEntities(url: string): Promise<EntitySchemaDiff> {
|
||||
const orm = await MikroORM.init({
|
||||
clientUrl: url,
|
||||
entities: [...ALL_ENTITIES],
|
||||
discovery: { warnWhenNoEntities: false },
|
||||
});
|
||||
try {
|
||||
for (const meta of orm.getMetadata().getAll().values()) applyPostgresColumnAdjustments(meta.props);
|
||||
const connection = orm.em.getConnection();
|
||||
const live = await readLiveSchemaFacts(connection);
|
||||
const classified = classifySchemaDiff(splitSchemaDiff(await orm.schema.getUpdateSchemaSQL({ wrap: false })), live);
|
||||
const fingerprint = await spellingChangesNothing(connection, classified.spelling);
|
||||
return {
|
||||
...classified,
|
||||
spellingHolds: fingerprint.before === fingerprint.after,
|
||||
fingerprint,
|
||||
missingTriggers: missingPortedTriggers(live),
|
||||
};
|
||||
} finally {
|
||||
await orm.close(true);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import { PostgreSqlPlatform } from '@mikro-orm/postgresql';
|
||||
|
||||
import {
|
||||
PostgresQueryCompiler,
|
||||
RawNode,
|
||||
type DatabaseIntrospector,
|
||||
type Dialect,
|
||||
type Kysely,
|
||||
type OperationNode,
|
||||
type OrderByItemNode,
|
||||
} from 'kysely';
|
||||
|
||||
/**
|
||||
* Where NULLs sort, as SQLite sorts them, for every ORDER BY TREK sends to
|
||||
* Postgres.
|
||||
*
|
||||
* SQLite takes NULL as the smallest value: first in ascending order, last in
|
||||
* descending order. Postgres takes it as the largest, the other way round, so
|
||||
* a list ordered by a nullable column (bookings without a time, trips without
|
||||
* dates, items without a position) would come back in another order on each
|
||||
* engine. Rather than every ORDER BY spelling its NULL position, which a new
|
||||
* one would forget, the Postgres engine renders the position SQLite implies
|
||||
* wherever a statement does not name one: Kysely statements through the query
|
||||
* compiler below, MikroORM's own (`find`, the query builder) through the
|
||||
* platform's ORDER BY rendering. An explicit `nulls first`/`nulls last` is
|
||||
* left as written. ORDER BY spelled inside raw SQL text is outside both.
|
||||
*/
|
||||
|
||||
/** The NULL position SQLite gives an ORDER BY item of this direction. */
|
||||
function sqliteNulls(descending: boolean): 'first' | 'last' {
|
||||
return descending ? 'last' : 'first';
|
||||
}
|
||||
|
||||
/** Whether a Kysely ORDER BY item's direction is descending (`desc`); no direction is ascending. */
|
||||
function isDescending(direction: OperationNode | undefined): boolean {
|
||||
if (!direction || !RawNode.is(direction)) return false;
|
||||
return direction.sqlFragments.join('').trim().toLowerCase() === 'desc';
|
||||
}
|
||||
|
||||
/** Postgres's query compiler, with SQLite's NULL position on every ORDER BY item that names none. */
|
||||
export class SqliteNullOrderCompiler extends PostgresQueryCompiler {
|
||||
protected override visitOrderByItem(node: OrderByItemNode): void {
|
||||
super.visitOrderByItem(node.nulls ? node : { ...node, nulls: sqliteNulls(isDescending(node.direction)) });
|
||||
}
|
||||
}
|
||||
|
||||
/** `dialect` with {@link SqliteNullOrderCompiler} as its query compiler; the rest is its own. */
|
||||
export function withSqliteNullOrder(dialect: Dialect): Dialect {
|
||||
return {
|
||||
createAdapter: () => dialect.createAdapter(),
|
||||
createDriver: () => dialect.createDriver(),
|
||||
createIntrospector: (db: Kysely<unknown>): DatabaseIntrospector => dialect.createIntrospector(db),
|
||||
createQueryCompiler: () => new SqliteNullOrderCompiler(),
|
||||
};
|
||||
}
|
||||
|
||||
/** One rendered MikroORM ORDER BY item (`"t"."start_date" desc`), with SQLite's NULL position when it names none. */
|
||||
export function withSqliteNullPosition(item: string): string {
|
||||
if (/\snulls\s+(first|last)\s*$/i.test(item)) return item;
|
||||
return `${item} nulls ${sqliteNulls(/\sdesc\s*$/i.test(item))}`;
|
||||
}
|
||||
|
||||
/** MikroORM's Postgres platform, rendering ORDER BY items with SQLite's NULL position. */
|
||||
export class SqliteNullOrderPlatform extends PostgreSqlPlatform {
|
||||
override getOrderByExpression(column: string, direction: string, collation?: string): string[] {
|
||||
return super.getOrderByExpression(column, direction, collation).map(withSqliteNullPosition);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
import { execFile, spawn } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { Transform } from 'node:stream';
|
||||
import { pipeline } from 'node:stream/promises';
|
||||
import { promisify } from 'node:util';
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
|
||||
/** The Postgres client tools a backup runs. */
|
||||
export type PgTool = 'pg_dump' | 'pg_restore' | 'psql';
|
||||
|
||||
/**
|
||||
* Where the client tools are looked for when `TREK_DB_PG_BIN_DIR` is unset:
|
||||
* Debian's versioned directories newest first (the Docker image installs 18),
|
||||
* then the usual prefixes. Newest first because a client dumps and restores
|
||||
* every server up to its own major version and refuses a newer one. Never
|
||||
* PATH: a binary is run by its absolute path.
|
||||
*/
|
||||
const DEFAULT_BIN_DIRS = [
|
||||
'/usr/lib/postgresql/18/bin',
|
||||
'/usr/lib/postgresql/17/bin',
|
||||
'/usr/lib/postgresql/16/bin',
|
||||
'/usr/lib/postgresql/15/bin',
|
||||
'/usr/lib/postgresql/14/bin',
|
||||
'/usr/local/bin',
|
||||
'/usr/bin',
|
||||
];
|
||||
|
||||
/** A dump or a restore of a large database takes minutes, not hours. */
|
||||
const TOOL_TIMEOUT_MS = 30 * 60 * 1000;
|
||||
const TOOL_MAX_OUTPUT_BYTES = 64 * 1024 * 1024;
|
||||
/** An unreachable host fails the tool in seconds instead of holding a boot or a restore. */
|
||||
const CONNECT_TIMEOUT_SECONDS = '10';
|
||||
/** How much of a tool's stderr an error keeps. */
|
||||
const STDERR_LIMIT = 2000;
|
||||
/** How much of a streaming tool's stderr is held while it runs, before it is summarized. */
|
||||
const STDERR_CAPTURE_LIMIT = 64 * 1024;
|
||||
/** stderr lines that quote SQL or row data: they stay out of errors and logs. */
|
||||
const DATA_LINE = /^\s*(Command was:|CONTEXT:|DETAIL:|LINE \d+:|QUERY:)/;
|
||||
/** libpq reads `sslrootcert=system` as the system's trusted CAs from this major on; older clients read it as a file name. */
|
||||
const SYSTEM_ROOT_CERT_SINCE = 16;
|
||||
|
||||
/** The absolute path of `tool`, or null when it is not installed where TREK looks. */
|
||||
export function resolvePgTool(tool: PgTool, binDir: string | undefined): string | null {
|
||||
const dirs = binDir ? [binDir] : DEFAULT_BIN_DIRS;
|
||||
const executable = (candidate: string): boolean => {
|
||||
try {
|
||||
fs.accessSync(candidate, fs.constants.X_OK);
|
||||
return true;
|
||||
} catch {
|
||||
return false; // missing or not executable: the next directory may have it
|
||||
}
|
||||
};
|
||||
return dirs.map((dir) => path.join(dir, tool)).find(executable) ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The libpq environment for `url`: the tools read the password from
|
||||
* PGPASSWORD, so it never appears in an argument list another process can
|
||||
* read. An sslmode that asks for SSL verifies the server's certificate, as the
|
||||
* app's own pool does (`postgres-engine.ts`): against the URL's sslrootcert,
|
||||
* else the system's trusted CAs (`system`, which `run` accepts only from a
|
||||
* client that understands it).
|
||||
*/
|
||||
export function pgConnectionEnv(url: string): Record<string, string> {
|
||||
const parsed = new URL(url);
|
||||
const env: Record<string, string> = {
|
||||
PGHOST: parsed.hostname.replace(/^\[(.*)\]$/, '$1'),
|
||||
PGPORT: parsed.port || '5432',
|
||||
PGDATABASE: decodeURIComponent(parsed.pathname.replace(/^\//, '')),
|
||||
PGCONNECT_TIMEOUT: CONNECT_TIMEOUT_SECONDS,
|
||||
};
|
||||
if (parsed.username) env.PGUSER = decodeURIComponent(parsed.username);
|
||||
if (parsed.password) env.PGPASSWORD = decodeURIComponent(parsed.password);
|
||||
const sslmode = parsed.searchParams.get('sslmode');
|
||||
if (sslmode === 'disable') env.PGSSLMODE = 'disable';
|
||||
else if (sslmode) {
|
||||
env.PGSSLMODE = 'verify-full';
|
||||
env.PGSSLROOTCERT = parsed.searchParams.get('sslrootcert') ?? 'system';
|
||||
}
|
||||
return env;
|
||||
}
|
||||
|
||||
/** A client tool, refused with a clear message when it is not installed. */
|
||||
export class PgToolMissingError extends Error {
|
||||
constructor(tool: PgTool) {
|
||||
super(
|
||||
`${tool} was not found, so a Postgres database cannot be backed up or restored. ` +
|
||||
'Install the PostgreSQL client tools (the Docker image has them) or point TREK_DB_PG_BIN_DIR at them.',
|
||||
);
|
||||
this.name = 'PgToolMissingError';
|
||||
}
|
||||
}
|
||||
|
||||
/** A tool that wrote more than the caller allowed; it was stopped and its output is incomplete. */
|
||||
export class PgOutputLimitError extends Error {
|
||||
constructor(
|
||||
tool: PgTool,
|
||||
readonly limitBytes: number,
|
||||
) {
|
||||
super(`${tool} wrote more than ${limitBytes} bytes and was stopped`);
|
||||
this.name = 'PgOutputLimitError';
|
||||
}
|
||||
}
|
||||
|
||||
/** The tool's own message, without the lines that quote SQL or rows, and bounded. */
|
||||
function summarizeStderr(stderr: string | undefined): string {
|
||||
const kept = (stderr ?? '')
|
||||
.split('\n')
|
||||
.filter((line) => line.trim() !== '' && !DATA_LINE.test(line))
|
||||
.join('\n');
|
||||
return kept.length > STDERR_LIMIT ? `${kept.slice(0, STDERR_LIMIT)}…` : kept;
|
||||
}
|
||||
|
||||
/**
|
||||
* The error a failed tool run throws: `<tool> failed: <its stderr, summarized>`.
|
||||
* Its cause names only how the process ended (exit code, signal, whether the
|
||||
* timeout killed it), never the process error itself, whose message and
|
||||
* `stderr` hold the tool's whole stderr, row data included, and would reach
|
||||
* the log through the cause chain.
|
||||
*/
|
||||
function toolFailure(tool: PgTool, failure: unknown): Error {
|
||||
const { stderr, code, signal, killed } = (failure ?? {}) as {
|
||||
stderr?: unknown;
|
||||
code?: unknown;
|
||||
signal?: unknown;
|
||||
killed?: unknown;
|
||||
};
|
||||
const message = summarizeStderr(typeof stderr === 'string' ? stderr : undefined);
|
||||
const ending = signal ? `signal ${String(signal)}` : `code ${String(code)}`;
|
||||
const cause = Object.assign(new Error(`${tool} ended with ${ending}${killed === true ? ' (timed out)' : ''}`), {
|
||||
code,
|
||||
signal,
|
||||
killed,
|
||||
});
|
||||
return new Error(`${tool} failed${message ? `: ${message}` : ''}`, { cause });
|
||||
}
|
||||
|
||||
/** The major version in a tool's `--version` line (`pg_dump (PostgreSQL) 18.1 (Debian …)`), or null. */
|
||||
function toolMajor(version: string): number | null {
|
||||
const match = /\(PostgreSQL\) (\d+)/.exec(version);
|
||||
return match ? Number(match[1]) : null;
|
||||
}
|
||||
|
||||
/** `binary --version`, read directly: the check before a run must not go through `run` itself. */
|
||||
async function binaryVersion(tool: PgTool, binary: string): Promise<string> {
|
||||
try {
|
||||
const { stdout } = await execFileAsync(binary, ['--version'], { env: {}, timeout: TOOL_TIMEOUT_MS });
|
||||
return stdout;
|
||||
} catch (err) {
|
||||
throw toolFailure(tool, err);
|
||||
}
|
||||
}
|
||||
|
||||
/** The absolute path of `tool`, or the refusal that says how to install it. */
|
||||
function locate(tool: PgTool, binDir: string | undefined): string {
|
||||
const binary = resolvePgTool(tool, binDir);
|
||||
if (!binary) throw new PgToolMissingError(tool);
|
||||
return binary;
|
||||
}
|
||||
|
||||
/**
|
||||
* Refuses to run a client older than libpq 16 with `sslrootcert=system`: it
|
||||
* would read `system` as a file name and fail on every connection. Such a
|
||||
* client needs the CA file named in the URL.
|
||||
*/
|
||||
async function refuseSystemRootCertOnOldClient(
|
||||
tool: PgTool,
|
||||
binary: string,
|
||||
env: Record<string, string>,
|
||||
): Promise<void> {
|
||||
if (env.PGSSLROOTCERT !== 'system') return;
|
||||
const version = await binaryVersion(tool, binary);
|
||||
const major = toolMajor(version);
|
||||
if (major !== null && major >= SYSTEM_ROOT_CERT_SINCE) return;
|
||||
throw new Error(
|
||||
`${tool} (${version.trim()}) cannot verify the server against the system's trusted certificate authorities, ` +
|
||||
`which needs a client of version ${SYSTEM_ROOT_CERT_SINCE} or later. Add sslrootcert=<CA file> to TREK_DB_URL, ` +
|
||||
'or point TREK_DB_PG_BIN_DIR at newer client tools (the Docker image has them).',
|
||||
);
|
||||
}
|
||||
|
||||
/** The major version of `tool` as TREK would run it. */
|
||||
async function pgToolMajor(tool: PgTool, binDir: string | undefined): Promise<number | null> {
|
||||
return toolMajor(await binaryVersion(tool, locate(tool, binDir)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Refuses `tools` when one is older than the server it is about to talk to:
|
||||
* pg_dump refuses a newer server outright, and what an older pg_restore or
|
||||
* psql makes of a newer server's dump is not something a restore should find
|
||||
* out halfway. A newer client is fine; it handles every older server.
|
||||
*/
|
||||
export async function refuseClientOlderThanServer(
|
||||
tools: readonly PgTool[],
|
||||
binDir: string | undefined,
|
||||
serverMajor: number,
|
||||
): Promise<void> {
|
||||
const majors = await Promise.all(tools.map((tool) => pgToolMajor(tool, binDir)));
|
||||
for (const [i, tool] of tools.entries()) {
|
||||
const major = majors[i];
|
||||
if (major !== null && major >= serverMajor) continue;
|
||||
throw new Error(
|
||||
`${tool} is version ${major ?? 'unknown'}, older than the PostgreSQL ${serverMajor} server, which it cannot ` +
|
||||
`back up or restore. Point TREK_DB_PG_BIN_DIR at client tools of version ${serverMajor} or later ` +
|
||||
'(the Docker image has the newest supported ones).',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs `tool` by its absolute path and resolves with its stdout. A failure
|
||||
* throws `<tool> failed: <its stderr, summarized>`.
|
||||
*/
|
||||
export async function run(
|
||||
tool: PgTool,
|
||||
binDir: string | undefined,
|
||||
args: string[],
|
||||
env: Record<string, string>,
|
||||
): Promise<string> {
|
||||
const binary = locate(tool, binDir);
|
||||
await refuseSystemRootCertOnOldClient(tool, binary, env);
|
||||
try {
|
||||
const { stdout } = await execFileAsync(binary, args, {
|
||||
env,
|
||||
timeout: TOOL_TIMEOUT_MS,
|
||||
maxBuffer: TOOL_MAX_OUTPUT_BYTES,
|
||||
});
|
||||
return stdout;
|
||||
} catch (err) {
|
||||
throw toolFailure(tool, err);
|
||||
}
|
||||
}
|
||||
|
||||
/** How a spawned tool ended: its exit, or the error that kept it from starting. */
|
||||
type Ending = { code: number | null; signal: NodeJS.Signals | null } | { error: Error };
|
||||
|
||||
/**
|
||||
* Runs `tool` and streams its stdout into `target` (which must exist; its mode
|
||||
* is kept), stopping the tool with {@link PgOutputLimitError} once more than
|
||||
* `maxBytes` have come out. The caller removes `target` on failure. A failure
|
||||
* of the tool itself throws as `run` does.
|
||||
*/
|
||||
export async function runToFile(
|
||||
tool: PgTool,
|
||||
binDir: string | undefined,
|
||||
args: string[],
|
||||
env: Record<string, string>,
|
||||
target: string,
|
||||
maxBytes: number,
|
||||
): Promise<void> {
|
||||
const binary = locate(tool, binDir);
|
||||
await refuseSystemRootCertOnOldClient(tool, binary, env);
|
||||
const child = spawn(binary, args, { env, stdio: ['ignore', 'pipe', 'pipe'], timeout: TOOL_TIMEOUT_MS });
|
||||
const ended = new Promise<Ending>((resolve) => {
|
||||
child.once('error', (error) => resolve({ error }));
|
||||
child.once('close', (code, signal) => resolve({ code, signal }));
|
||||
});
|
||||
let stderr = '';
|
||||
child.stderr.setEncoding('utf8');
|
||||
child.stderr.on('data', (chunk: string) => {
|
||||
if (stderr.length < STDERR_CAPTURE_LIMIT) stderr += chunk;
|
||||
});
|
||||
let written = 0;
|
||||
const limit = new Transform({
|
||||
transform(chunk: Buffer, _encoding, callback) {
|
||||
written += chunk.length;
|
||||
if (written > maxBytes) callback(new PgOutputLimitError(tool, maxBytes));
|
||||
else callback(null, chunk);
|
||||
},
|
||||
});
|
||||
try {
|
||||
await pipeline(child.stdout, limit, fs.createWriteStream(target, { flags: 'w' }));
|
||||
} catch (err) {
|
||||
child.kill('SIGKILL');
|
||||
await ended;
|
||||
throw err instanceof PgOutputLimitError ? err : toolFailure(tool, { stderr, code: 'stream' });
|
||||
}
|
||||
const ending = await ended;
|
||||
if ('error' in ending) throw toolFailure(tool, { stderr, code: (ending.error as { code?: unknown }).code });
|
||||
if (ending.code !== 0) throw toolFailure(tool, { stderr, code: ending.code, signal: ending.signal });
|
||||
}
|
||||
@@ -0,0 +1,323 @@
|
||||
import { CURRENT_SCHEMA_TABLES_SQL } from '../../dialect/catalog';
|
||||
import { CLEAR_SCHEMA_SQL, pluginSchemasSql } from './clear-schema';
|
||||
import { pgConnectionEnv, PgOutputLimitError, refuseClientOlderThanServer, run, runToFile } from './pg-process';
|
||||
import { isPluginSchemaName, PLUGIN_SCHEMA_PREFIX } from './plugin-schema';
|
||||
import { refuseToolsWithoutRestrict } from './restore-safety';
|
||||
import { PRIVILEGED_ROLE_DESCRIPTION, PRIVILEGED_ROLE_SQL, serverMajor } from './server-checks';
|
||||
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import readline from 'node:readline';
|
||||
|
||||
/**
|
||||
* Restore's session settings: a restore waiting on a lock another session
|
||||
* holds gives up, and rolls back, instead of hanging; the NOTICEs every
|
||||
* CASCADE prints stay out of its stderr.
|
||||
*/
|
||||
const RESTORE_SESSION_OPTIONS = '-c lock_timeout=60s -c client_min_messages=warning';
|
||||
|
||||
/** Why a restore refuses a role that could reach the database host (`PRIVILEGED_ROLE_SQL`). */
|
||||
const PRIVILEGED_RESTORE_REFUSAL =
|
||||
`TREK_DB_URL connects as ${PRIVILEGED_ROLE_DESCRIPTION}. ` +
|
||||
'A backup archive is a SQL script that runs as this role, so a crafted one could take over the database host; ' +
|
||||
'nothing was replaced. Connect TREK as a role that owns its database and is not a superuser ' +
|
||||
'(the wiki page "Database: Postgres" shows how).';
|
||||
|
||||
/** An empty file only its owner can read: the tool writing into it keeps the mode. */
|
||||
function createPrivateFile(file: string): void {
|
||||
fs.writeFileSync(file, '', { mode: 0o600 });
|
||||
}
|
||||
|
||||
/** The schema TREK's tables live in: its name, and the name as SQL quotes it (`quote_ident`). */
|
||||
interface PgSchema {
|
||||
name: string;
|
||||
quoted: string;
|
||||
}
|
||||
|
||||
/** What a dump or a restore needs to know about the server before it runs. */
|
||||
interface PgServer {
|
||||
schema: PgSchema;
|
||||
/** The plugin data schemas TREK's role owns (`plugin-schema.ts`), which a dump holds beside TREK's own. */
|
||||
pluginSchemas: string[];
|
||||
/** The server's major version, which the client tools must reach. */
|
||||
major: number;
|
||||
/** Whether TREK's role could reach the database host from SQL (`PRIVILEGED_ROLE_SQL`). */
|
||||
privileged: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* One line, tab-separated: the current schema, its quoted name, the server
|
||||
* version, whether the role is privileged, and the plugin schemas the role
|
||||
* owns, comma-separated.
|
||||
*/
|
||||
const SERVER_SQL =
|
||||
"select concat_ws(E'\\t', coalesce(current_schema(), ''), coalesce(quote_ident(current_schema()), ''), " +
|
||||
`current_setting('server_version_num'), (${PRIVILEGED_ROLE_SQL})::text, ` +
|
||||
"(select coalesce(string_agg(nspname, ',' order by nspname), '') from pg_namespace " +
|
||||
`where starts_with(nspname, '${PLUGIN_SCHEMA_PREFIX}') and pg_get_userbyid(nspowner) = current_user))`;
|
||||
|
||||
/**
|
||||
* The current schema of the database at `url`, the one TREK creates its
|
||||
* tables in, with the server's version and what TREK's role may do there. A
|
||||
* backup and a restore stay inside that schema: a hosted database (Supabase)
|
||||
* keeps the platform's own schemas, `auth` among them, beside it, and they are
|
||||
* neither TREK's to copy nor to replace.
|
||||
*/
|
||||
async function pgServer(url: string, binDir: string | undefined): Promise<PgServer> {
|
||||
const out = await run(
|
||||
'psql',
|
||||
binDir,
|
||||
['--no-psqlrc', '--no-align', '--tuples-only', `--command=${SERVER_SQL}`],
|
||||
pgConnectionEnv(url),
|
||||
);
|
||||
const [name, quoted, version, privileged, plugins = ''] = out.replace(/\n$/, '').split('\t');
|
||||
if (!name || !quoted) {
|
||||
throw new Error('The database has no current schema: set the search_path of the role in TREK_DB_URL.');
|
||||
}
|
||||
return {
|
||||
schema: { name, quoted },
|
||||
pluginSchemas: plugins.split(',').filter(isPluginSchemaName),
|
||||
major: serverMajor(version),
|
||||
privileged: privileged === 'true',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Writes a custom-format dump of the current schema of the database at `url`,
|
||||
* and of the plugin data schemas TREK's role owns, to `target`, readable by
|
||||
* its owner only. No other schema of the database is read. It is written beside the target and
|
||||
* renamed into place, so a dump that fails or is killed never leaves a file
|
||||
* that passes for a copy. A pg_dump older than the server is refused first.
|
||||
*/
|
||||
export async function pgDump(url: string, target: string, binDir: string | undefined): Promise<void> {
|
||||
const partial = `${target}.partial`;
|
||||
try {
|
||||
createPrivateFile(partial);
|
||||
const { schema, pluginSchemas, major } = await pgServer(url, binDir);
|
||||
await refuseClientOlderThanServer(['pg_dump'], binDir, major);
|
||||
await run(
|
||||
'pg_dump',
|
||||
binDir,
|
||||
[
|
||||
'--format=custom',
|
||||
'--no-owner',
|
||||
'--no-privileges',
|
||||
`--file=${partial}`,
|
||||
`--schema="${schema.name.replaceAll('"', '""')}"`,
|
||||
// A plugin schema's name holds lowercase letters, digits and underscores, none of them pattern syntax.
|
||||
...pluginSchemas.map((plugin) => `--schema=${plugin}`),
|
||||
],
|
||||
pgConnectionEnv(url),
|
||||
);
|
||||
fs.renameSync(partial, target);
|
||||
} catch (err) {
|
||||
fs.rmSync(partial, { force: true });
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/** Escapes every character a RegExp would read as syntax. */
|
||||
function escapeRegExp(text: string): string {
|
||||
return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the restore script creates TREK's migration table in `schema`: a
|
||||
* dump of TREK's own schema does. The script is read line by line and the
|
||||
* read stops at the first match: the COPY data that fills a large script is
|
||||
* never loaded, and a script past V8's maximum string length would not load
|
||||
* at all.
|
||||
*/
|
||||
async function scriptHoldsTrekSchema(script: string, schema: PgSchema): Promise<boolean> {
|
||||
const createsHistory = new RegExp(`^CREATE TABLE ${escapeRegExp(`${schema.quoted}.mikro_orm_migrations`)} \\(`);
|
||||
const input = fs.createReadStream(script, { encoding: 'utf8' });
|
||||
const lines = readline.createInterface({ input, crlfDelay: Infinity });
|
||||
try {
|
||||
for await (const line of lines) {
|
||||
if (createsHistory.test(line)) return true;
|
||||
}
|
||||
return false;
|
||||
} finally {
|
||||
lines.close();
|
||||
input.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
/** pg_restore's script for the dump at `source`, written to `script` and held to `maxBytes`. */
|
||||
async function writeRestoreScript(
|
||||
source: string,
|
||||
script: string,
|
||||
schemas: readonly string[],
|
||||
binDir: string | undefined,
|
||||
maxBytes: number,
|
||||
): Promise<void> {
|
||||
const only = schemas.map((name) => `--schema=${name}`);
|
||||
const args = ['--no-owner', '--no-privileges', ...only, '--file=-', '--', source];
|
||||
try {
|
||||
await runToFile('pg_restore', binDir, args, {}, script, maxBytes);
|
||||
} catch (err) {
|
||||
if (!(err instanceof PgOutputLimitError)) throw err;
|
||||
throw new Error(
|
||||
`The backup's database expands to more than ${Number((maxBytes / 1024 / 1024).toFixed(2))} MB of SQL, the limit ` +
|
||||
'BACKUP_MAX_DECOMPRESSED_MB sets; nothing was replaced. Raise the limit if the backup is genuine.',
|
||||
{ cause: err },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces the current schema of the database at `url` with the dump at
|
||||
* `source`, and the plugin data schemas with the dump's: pg_restore turns the
|
||||
* dump's objects in those schemas into a script beside it (anything else the
|
||||
* dump holds is left out), then psql clears the schema, drops the plugin
|
||||
* schemas TREK's role owns, creates the dump's and runs the script, all in
|
||||
* one transaction, so a restore that fails leaves the database as it was. No
|
||||
* other schema of the database is touched. Refused before anything is cleared:
|
||||
*
|
||||
* - client tools without the CVE-2025-8714 fix, or older than the server;
|
||||
* - a role that could reach the database host from SQL (`PRIVILEGED_ROLE_SQL`),
|
||||
* since the script comes from an archive and runs as that role;
|
||||
* - a script past `maxScriptBytes` (BACKUP_MAX_DECOMPRESSED_MB): the dump is
|
||||
* compressed once more inside the archive, so its script is held to the
|
||||
* limit while pg_restore writes it, not only the archive's entry;
|
||||
* - a dump without TREK's tables in that schema.
|
||||
*
|
||||
* The work files are removed whatever happens.
|
||||
*/
|
||||
export async function pgRestore(
|
||||
url: string,
|
||||
source: string,
|
||||
binDir: string | undefined,
|
||||
maxScriptBytes: number,
|
||||
): Promise<void> {
|
||||
await refuseToolsWithoutRestrict(binDir);
|
||||
const { schema, major, privileged } = await pgServer(url, binDir);
|
||||
if (privileged) throw new Error(PRIVILEGED_RESTORE_REFUSAL);
|
||||
await refuseClientOlderThanServer(['pg_restore', 'psql'], binDir, major);
|
||||
const workDir = fs.mkdtempSync(path.join(path.dirname(source), '.pg-restore-'));
|
||||
try {
|
||||
const clear = path.join(workDir, 'clear-schema.sql');
|
||||
const script = path.join(workDir, 'restore.sql');
|
||||
const pluginSchemas = await dumpPluginSchemas(source, path.join(workDir, 'toc.txt'), binDir);
|
||||
fs.writeFileSync(clear, CLEAR_SCHEMA_SQL + pluginSchemasSql(pluginSchemas), { mode: 0o600 });
|
||||
createPrivateFile(script);
|
||||
await writeRestoreScript(source, script, [schema.name, ...pluginSchemas], binDir, maxScriptBytes);
|
||||
if (!(await scriptHoldsTrekSchema(script, schema))) {
|
||||
throw new Error(`The backup holds no TREK tables in the schema "${schema.name}"; nothing was replaced.`);
|
||||
}
|
||||
await run(
|
||||
'psql',
|
||||
binDir,
|
||||
[
|
||||
'--no-psqlrc',
|
||||
'--quiet',
|
||||
'--single-transaction',
|
||||
'--set=ON_ERROR_STOP=1',
|
||||
`--output=${os.devNull}`,
|
||||
`--file=${clear}`,
|
||||
`--file=${script}`,
|
||||
],
|
||||
{ ...pgConnectionEnv(url), PGOPTIONS: RESTORE_SESSION_OPTIONS },
|
||||
);
|
||||
} finally {
|
||||
fs.rmSync(workDir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The plugin data schemas the dump at `source` holds, read from its table of
|
||||
* contents (`pg_restore --list`, written to `toc`), which has a line
|
||||
* `<id>; <oid> <oid> SCHEMA - <name> <owner>` per schema. Only a name TREK
|
||||
* gives a plugin schema counts.
|
||||
*/
|
||||
async function dumpPluginSchemas(source: string, toc: string, binDir: string | undefined): Promise<string[]> {
|
||||
createPrivateFile(toc);
|
||||
await run('pg_restore', binDir, ['--list', `--file=${toc}`, '--', source], {});
|
||||
const names = new Set<string>();
|
||||
for (const line of fs.readFileSync(toc, 'utf8').split('\n')) {
|
||||
const name = /^\d+; \d+ \d+ SCHEMA - (\S+) /.exec(line)?.[1];
|
||||
if (name !== undefined && isPluginSchemaName(name)) names.add(name);
|
||||
}
|
||||
return [...names].sort((a, b) => a.localeCompare(b));
|
||||
}
|
||||
|
||||
/** The tables in the current schema of the database at `url`, read before TREK opens it. */
|
||||
async function pgTableNames(url: string, binDir: string | undefined): Promise<string[]> {
|
||||
const out = await run(
|
||||
'psql',
|
||||
binDir,
|
||||
['--no-psqlrc', '--no-align', '--tuples-only', `--command=${CURRENT_SCHEMA_TABLES_SQL}`],
|
||||
pgConnectionEnv(url),
|
||||
);
|
||||
return out.split('\n').filter((line) => line !== '');
|
||||
}
|
||||
|
||||
/** The migration history's table, the first one a boot creates. */
|
||||
const HISTORY_TABLE = 'mikro_orm_migrations';
|
||||
|
||||
/**
|
||||
* The tables that make the current schema of the database at `url` a
|
||||
* database in use, read before TREK opens it: every table, except a
|
||||
* migration history that is the only table and records nothing. A first boot
|
||||
* that failed while it created the schema left such a table behind before
|
||||
* the bootstrap created it in the schema's own transaction, and it holds
|
||||
* nothing a restore, which clears the schema first, could lose. Any answer
|
||||
* but a count of 0 keeps the table, so the check fails closed.
|
||||
*/
|
||||
export async function pgTablesInUse(url: string, binDir: string | undefined): Promise<string[]> {
|
||||
const tables = await pgTableNames(url, binDir);
|
||||
if (tables.length !== 1 || tables[0] !== HISTORY_TABLE) return tables;
|
||||
const out = await run(
|
||||
'psql',
|
||||
binDir,
|
||||
['--no-psqlrc', '--no-align', '--tuples-only', `--command=select count(*) as history_rows from ${HISTORY_TABLE}`],
|
||||
pgConnectionEnv(url),
|
||||
);
|
||||
return out.trim() === '0' ? [] : tables;
|
||||
}
|
||||
|
||||
/**
|
||||
* The migration names in a restore script's COPY block for
|
||||
* `mikro_orm_migrations`, read from its `name` column; none when the script
|
||||
* has no such block.
|
||||
*/
|
||||
function migrationNamesFromCopy(script: string): string[] {
|
||||
const lines = script.split('\n');
|
||||
// A plugin may name a table of its own schema mikro_orm_migrations too; only TREK's counts.
|
||||
const copy = lines.findIndex((line) => {
|
||||
const match = /^COPY (?:(\S+)\.)?mikro_orm_migrations \(/.exec(line);
|
||||
return match !== null && !isPluginSchemaName(match[1] ?? '');
|
||||
});
|
||||
if (copy < 0) return [];
|
||||
const columns =
|
||||
/\(([^)]*)\)/
|
||||
.exec(lines[copy])?.[1]
|
||||
.split(',')
|
||||
.map((column) => column.trim()) ?? [];
|
||||
const nameAt = columns.indexOf('name');
|
||||
if (nameAt < 0) return [];
|
||||
const names: string[] = [];
|
||||
for (const line of lines.slice(copy + 1)) {
|
||||
if (line === '\\.' || line === '') break;
|
||||
const name = line.split('\t')[nameAt];
|
||||
if (name) names.push(name);
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
/**
|
||||
* The migrations a dump records as executed, read from the dump itself (its
|
||||
* `mikro_orm_migrations` rows as COPY text), so a restore can refuse a newer
|
||||
* TREK's backup before anything is replaced. Throws on a file that is not a
|
||||
* dump; an empty list means the dump holds no TREK history.
|
||||
*/
|
||||
export async function pgDumpMigrations(source: string, binDir: string | undefined): Promise<string[]> {
|
||||
const script = await run(
|
||||
'pg_restore',
|
||||
binDir,
|
||||
['--data-only', '--table=mikro_orm_migrations', '--file=-', '--', source],
|
||||
{},
|
||||
);
|
||||
return migrationNamesFromCopy(script);
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
import type { PluginSqlClient } from './plugin-data-store';
|
||||
import { PluginSqlRefused, type PluginStatement } from './plugin-sql-guard';
|
||||
import { PRIVILEGED_ROLE_DESCRIPTION, PRIVILEGED_ROLE_SQL } from './server-checks';
|
||||
|
||||
/**
|
||||
* The checks the Postgres plugin store (`plugin-data-store.ts`) asks the
|
||||
* database itself, behind the token guard (`plugin-sql-guard.ts`): whether
|
||||
* TREK's role may run plugin SQL at all, which schema the objects a statement
|
||||
* changes really live in, and how much the plugin's schema holds.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Why plugin databases are refused while TREK connects as a privileged role:
|
||||
* every statement a plugin sends runs as that role, and such a role may
|
||||
* change the system catalogs or reach the database host, which no check on
|
||||
* the SQL can rule out.
|
||||
*/
|
||||
export const PRIVILEGED_ROLE_PLUGIN_REFUSAL =
|
||||
`Plugin databases (db:own) are refused on Postgres while TREK_DB_URL connects as ${PRIVILEGED_ROLE_DESCRIPTION}: ` +
|
||||
"a plugin's SQL runs as TREK's role. Connect TREK as a role that owns its database and is not a superuser " +
|
||||
'(see the wiki page "Database: Postgres").';
|
||||
|
||||
/** Asks whether TREK's role is privileged before a plugin call runs on a connection. */
|
||||
export interface PluginRoleGate {
|
||||
/** Throws {@link PRIVILEGED_ROLE_PLUGIN_REFUSAL} when the role `client` is connected as is privileged. */
|
||||
refuseIfPrivileged(client: PluginSqlClient): Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* The role check of {@link PRIVILEGED_ROLE_SQL}, read once per pool
|
||||
* connection and kept for as long as that connection lives. A new connection,
|
||||
* after a restart, a reconnect or the pool replacing one, reads it again, so a
|
||||
* role that gained or lost a privilege is seen without a restart once the pool
|
||||
* has turned over; the check costs one query per connection, not per call.
|
||||
*/
|
||||
export class PrivilegedRoleGate implements PluginRoleGate {
|
||||
private readonly answers = new WeakMap<PluginSqlClient, Promise<boolean>>();
|
||||
|
||||
async refuseIfPrivileged(client: PluginSqlClient): Promise<void> {
|
||||
if (await this.privileged(client)) throw new Error(PRIVILEGED_ROLE_PLUGIN_REFUSAL);
|
||||
}
|
||||
|
||||
/** Whether the role `client` is connected as is privileged; a failed read is not kept. */
|
||||
privileged(client: PluginSqlClient): Promise<boolean> {
|
||||
let answer = this.answers.get(client);
|
||||
if (answer === undefined) {
|
||||
answer = client
|
||||
.query(`select (${PRIVILEGED_ROLE_SQL}) as privileged`)
|
||||
.then((result) => (result.rows as Array<{ privileged?: boolean }>)[0]?.privileged === true);
|
||||
void answer.catch(() => this.answers.delete(client));
|
||||
this.answers.set(client, answer);
|
||||
}
|
||||
return answer;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Refuses `statement` unless every object it changes ({@link PluginStatement.targets})
|
||||
* that exists lies in `schema`. Run inside the call's transaction right
|
||||
* before the statement, so it sees what the statements before it made,
|
||||
* renamed or dropped. Postgres resolves each name itself with `to_regclass`
|
||||
* or `to_regtype` on the plugin's `search_path`, where `pg_catalog` is
|
||||
* searched first: an unqualified `int4`, `text` or `box` is the catalog's
|
||||
* type and refused here, whatever the role may do. A name that resolves to
|
||||
* nothing is left to the statement.
|
||||
*/
|
||||
export async function refuseForeignTargets(
|
||||
client: PluginSqlClient,
|
||||
statement: PluginStatement,
|
||||
schema: string,
|
||||
): Promise<void> {
|
||||
if (statement.targets.length === 0) return;
|
||||
const result = await client.query({
|
||||
text:
|
||||
'select t.name, n.nspname from unnest($1::text[], $2::text[]) as t(name, kind) ' +
|
||||
'join pg_namespace n on n.oid = case t.kind ' +
|
||||
"when 'type' then (select typnamespace from pg_type where oid = to_regtype(t.name)) " +
|
||||
'else (select relnamespace from pg_class where oid = to_regclass(t.name)) end ' +
|
||||
'where n.nspname <> $3',
|
||||
values: [
|
||||
statement.targets.map((t) => t.name.map(quoteName).join('.')),
|
||||
statement.targets.map((t) => t.kind),
|
||||
schema,
|
||||
],
|
||||
});
|
||||
const [foreign] = result.rows as Array<{ name: string; nspname: string }>;
|
||||
if (foreign !== undefined) {
|
||||
throw new PluginSqlRefused(
|
||||
`${foreign.name} is an object of the schema "${foreign.nspname}"; a plugin changes its own objects only`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** `part` as a quoted identifier, as `to_regclass` and `to_regtype` read it. */
|
||||
function quoteName(part: string): string {
|
||||
return `"${part.replaceAll('"', '""')}"`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The most catalog objects one plugin schema may hold: its relations (tables,
|
||||
* indexes, sequences, views, materialized views), types (each table brings its
|
||||
* row type and that type's array), constraints and enum labels. An empty
|
||||
* table, a view or an enum label takes no disk space the quota sees but adds
|
||||
* rows to the system catalogs, so their number is held on its own.
|
||||
*/
|
||||
export const PLUGIN_SCHEMA_MAX_OBJECTS = 5_000;
|
||||
|
||||
/** What a plugin schema holds, as the quota measures it. */
|
||||
export interface SchemaUsage {
|
||||
/** Bytes on disk of every relation of the schema and of each one's TOAST table. */
|
||||
bytes: number;
|
||||
/** Catalog objects, as {@link PLUGIN_SCHEMA_MAX_OBJECTS} counts them. */
|
||||
objects: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* The disk space and the catalog objects of `schema`. Every relation is
|
||||
* counted once, whatever its kind (tables, partitions, indexes, sequences,
|
||||
* materialized views; a view has no storage), each with all its forks, and
|
||||
* a table's TOAST table, which lives in `pg_toast`, through its
|
||||
* `reltoastrelid` with the TOAST table's own index.
|
||||
*/
|
||||
export async function schemaUsage(client: PluginSqlClient, schema: string): Promise<SchemaUsage> {
|
||||
const result = await client.query({
|
||||
text:
|
||||
'select coalesce((select sum(' +
|
||||
"pg_relation_size(c.oid, 'main') + pg_relation_size(c.oid, 'fsm') + pg_relation_size(c.oid, 'vm') + " +
|
||||
"pg_relation_size(c.oid, 'init') + " +
|
||||
'case when c.reltoastrelid <> 0 then pg_total_relation_size(c.reltoastrelid) else 0 end) ' +
|
||||
'from pg_class c where c.relnamespace = n.oid), 0) as bytes, ' +
|
||||
'(select count(*) from pg_class c where c.relnamespace = n.oid) + ' +
|
||||
'(select count(*) from pg_type t where t.typnamespace = n.oid) + ' +
|
||||
'(select count(*) from pg_constraint k where k.connamespace = n.oid) + ' +
|
||||
'(select count(*) from pg_enum e join pg_type t on t.oid = e.enumtypid where t.typnamespace = n.oid) as objects ' +
|
||||
'from pg_namespace n where n.nspname = $1',
|
||||
values: [schema],
|
||||
});
|
||||
const [row] = result.rows as Array<{ bytes?: number | string; objects?: number | string }>;
|
||||
return { bytes: Number(row?.bytes ?? 0), objects: Number(row?.objects ?? 0) };
|
||||
}
|
||||
|
||||
/**
|
||||
* Refuses a plugin's bound value that holds U+0000 (NUL): Postgres text
|
||||
* cannot store the character, and TREK will not change what a plugin asked
|
||||
* to store or compare (`'a\0b'` and `'ab'` are different keys on SQLite).
|
||||
* A string, or a string anywhere in an array, is checked; a Buffer goes to
|
||||
* `bytea`, which holds any byte.
|
||||
*/
|
||||
export function refuseNulValues(values: readonly unknown[]): void {
|
||||
if (values.some(holdsNul)) {
|
||||
throw new Error(
|
||||
'a plugin argument holds the character U+0000 (NUL), which Postgres text cannot store; ' +
|
||||
'TREK refuses it instead of changing the value. Remove it, or bind binary data as a Buffer (bytea)',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function holdsNul(value: unknown): boolean {
|
||||
if (typeof value === 'string') return value.includes('\u0000');
|
||||
return Array.isArray(value) && value.some(holdsNul);
|
||||
}
|
||||
@@ -0,0 +1,513 @@
|
||||
import { PLUGIN_DATA_CAPS, type PluginDataStore, type PluginTxOp, type PluginTxResult } from '../plugin-data';
|
||||
import {
|
||||
PLUGIN_SCHEMA_MAX_OBJECTS,
|
||||
PrivilegedRoleGate,
|
||||
refuseForeignTargets,
|
||||
refuseNulValues,
|
||||
schemaUsage,
|
||||
type PluginRoleGate,
|
||||
type SchemaUsage,
|
||||
} from './plugin-data-checks';
|
||||
import { isPluginId, pluginSchemaName, quotePluginSchema } from './plugin-schema';
|
||||
import { checkPlaceholders, checkQualifiers, parsePluginSql, type PluginStatement } from './plugin-sql-guard';
|
||||
|
||||
import { CompiledQuery, type Kysely } from 'kysely';
|
||||
import Cursor from 'pg-cursor';
|
||||
|
||||
/**
|
||||
* A plugin's own data on Postgres (`db:own`): a schema of its own in TREK's
|
||||
* database (`plugin-schema.ts`), reached through TREK's pool.
|
||||
*
|
||||
* Every call checks a `pg` client out of the pool for itself
|
||||
* ({@link poolClients}) and runs one transaction on it directly, not through
|
||||
* Kysely. Before the transaction it refuses the call outright while TREK's
|
||||
* role is privileged (`PrivilegedRoleGate` in `plugin-data-checks.ts`, read
|
||||
* once per connection). The transaction first makes sure the schema and its
|
||||
* migration table exist, then puts only that schema on the `search_path`,
|
||||
* with `pg_temp` explicitly last so a temporary table is never found before
|
||||
* the plugin's own, and sets `statement_timeout` to the call's time budget;
|
||||
* every setting is `local` and ends with the transaction. The plugin's SQL is
|
||||
* checked by `plugin-sql-guard.ts` before it runs, so it cannot name another
|
||||
* schema; right before each statement, the existing objects it changes are
|
||||
* resolved by Postgres and must lie in the plugin's schema
|
||||
* (`refuseForeignTargets`); and each statement goes to Postgres on its own
|
||||
* over the extended query protocol, which runs one statement and no more: a
|
||||
* write as a query with `queryMode: 'extended'`, which `pg` honours even
|
||||
* without values, and a read through a `pg-cursor`, which always uses that
|
||||
* protocol. A bound value or a migration id holding U+0000 is refused before
|
||||
* anything runs, since Postgres text cannot hold it and changing it would
|
||||
* change the plugin's data. Reads stop at the row cap. A call that may write
|
||||
* measures the schema before and after (`schemaUsage`: the bytes of every
|
||||
* relation with its TOAST table, and the catalog objects), and rolls back one
|
||||
* that leaves it past the quota or the object cap and larger than it found
|
||||
* it, so a plugin at either limit can still delete. Before the client goes
|
||||
* back to the pool, whatever session state a statement could have left on it
|
||||
* is dropped ({@link END_SESSION}); a client that cannot be brought back to a
|
||||
* clean state is closed instead of reused.
|
||||
*
|
||||
* The calls of one plugin run one at a time, as they do on its SQLite file,
|
||||
* and all plugins together hold at most half of TREK's pool
|
||||
* (`pluginDataSlots`), so a busy plugin never takes the connections TREK's
|
||||
* own requests need.
|
||||
*
|
||||
* The SQLite store's semantics carry over: `query` and `tx` are held to the
|
||||
* row cap, `query`, a `tx` batch and an `exec` script to the time budget, a
|
||||
* script's statements each commit on their own, and `migrate` runs once per
|
||||
* id with no time budget. What Postgres adds is that the budget also stops a
|
||||
* single statement (`statement_timeout`), which SQLite cannot, and that an
|
||||
* `exec` with bound args is held to it as well.
|
||||
*/
|
||||
|
||||
/** The limits one store enforces. Overridable for tests; production uses `PLUGIN_DATA_CAPS`. */
|
||||
interface PostgresPluginDataLimits {
|
||||
maxRows: number;
|
||||
timeBudgetMs: number;
|
||||
quotaBytes: number;
|
||||
/** The most catalog objects the schema may hold (`PLUGIN_SCHEMA_MAX_OBJECTS`). */
|
||||
maxObjects: number;
|
||||
/** The clock the time budget reads. */
|
||||
now: () => number;
|
||||
}
|
||||
|
||||
const DEFAULT_LIMITS: PostgresPluginDataLimits = {
|
||||
maxRows: PLUGIN_DATA_CAPS.maxRows,
|
||||
timeBudgetMs: PLUGIN_DATA_CAPS.timeBudgetMs,
|
||||
quotaBytes: PLUGIN_DATA_CAPS.quotaBytes,
|
||||
maxObjects: PLUGIN_SCHEMA_MAX_OBJECTS,
|
||||
now: () => Date.now(),
|
||||
};
|
||||
|
||||
/** Postgres's SQLSTATE for a statement cancelled by `statement_timeout`. */
|
||||
const QUERY_CANCELED = '57014';
|
||||
/** Rows a cursor fetches at once. */
|
||||
const CHUNK_ROWS = 500;
|
||||
/** What better-sqlite3 says about a closed handle, which the host recognizes. */
|
||||
const CLOSED = 'The database connection is not open';
|
||||
|
||||
/**
|
||||
* What a client runs before it goes back to the pool, outside any
|
||||
* transaction: `DISCARD ALL` without the two parts that would undo the pool's
|
||||
* own session state. `RESET ALL` would drop the `search_path` every pool
|
||||
* connection sets with `pg_temp` last (`session-search-path.ts`), and
|
||||
* `DEALLOCATE ALL` the statements `pg` prepared by name for other callers.
|
||||
* The plugin's settings need neither: they are all `local`. The guard
|
||||
* refuses every statement that could leave anything this drops, so this is
|
||||
* the layer behind it.
|
||||
*/
|
||||
export const END_SESSION = 'close all; unlisten *; select pg_advisory_unlock_all(); discard temp; discard sequences';
|
||||
|
||||
/** A query result, as far as the store reads it. */
|
||||
interface PgResult {
|
||||
rows: unknown[];
|
||||
rowCount: number | null;
|
||||
}
|
||||
|
||||
/** The part of a `pg` client the store uses. It is the store's alone from checkout to release. */
|
||||
export interface PluginSqlClient {
|
||||
/** SQL of TREK's own, without values: over the simple protocol. */
|
||||
query(text: string): Promise<PgResult>;
|
||||
/** A query with values, or a plugin statement with `queryMode: 'extended'`. */
|
||||
query(config: { text: string; values: unknown[]; queryMode?: 'extended' }): Promise<PgResult>;
|
||||
/** Submits a cursor and hands it back. */
|
||||
query(cursor: Cursor): Cursor;
|
||||
/** Back to the pool, or closed when `destroy` is true. */
|
||||
release(destroy?: boolean): void;
|
||||
}
|
||||
|
||||
/** Checks a client out of the pool; resolves once one is free. */
|
||||
export type ConnectPluginClient = () => Promise<PluginSqlClient>;
|
||||
|
||||
/** The part of `pg`'s pool the store checks clients out of. */
|
||||
interface PgPool {
|
||||
connect(): Promise<PluginSqlClient>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clients of the `pg` pool behind MikroORM's Postgres connection, which its
|
||||
* `getNativeClient` hands out. Its options apply to them as to every other
|
||||
* client of the pool: the TLS settings, and the `int8` and `numeric` parsers
|
||||
* (`postgres-driver.ts`). Nothing of the pool is changed for them.
|
||||
*/
|
||||
export function poolClients(connection: { getNativeClient(): Promise<unknown> }): ConnectPluginClient {
|
||||
return async () => ((await connection.getNativeClient()) as PgPool).connect();
|
||||
}
|
||||
|
||||
/** How many plugin transactions may hold a pool connection at once: half of TREK's pool, at least one. */
|
||||
export function pluginDataSlots(poolMax: number): number {
|
||||
return Math.max(1, Math.floor(poolMax / 2));
|
||||
}
|
||||
|
||||
/** A counting semaphore: at most `size` pieces of work at once, the rest wait in order. */
|
||||
export class PluginDataSlots {
|
||||
private active = 0;
|
||||
private readonly waiting: Array<() => void> = [];
|
||||
|
||||
constructor(readonly size: number) {}
|
||||
|
||||
async run<T>(work: () => Promise<T>): Promise<T> {
|
||||
if (this.active < this.size) this.active++;
|
||||
else await new Promise<void>((resolve) => this.waiting.push(resolve));
|
||||
try {
|
||||
return await work();
|
||||
} finally {
|
||||
// A waiting call takes the slot over, so the count stays where it is.
|
||||
const next = this.waiting.shift();
|
||||
if (next) next();
|
||||
else this.active--;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** The rows one call has returned so far, against the cap they share. */
|
||||
interface RowBudget {
|
||||
count: number;
|
||||
readonly max: number;
|
||||
readonly message: string;
|
||||
}
|
||||
|
||||
/** Drops the plugin `id`'s schema and everything in it. An id no schema can be made from has none. */
|
||||
export async function dropPluginSchema(db: Kysely<object>, id: string): Promise<void> {
|
||||
if (!isPluginId(id)) return;
|
||||
const schema = quotePluginSchema(pluginSchemaName(id));
|
||||
await db.executeQuery(CompiledQuery.raw(`drop schema if exists ${schema} cascade`));
|
||||
}
|
||||
|
||||
export class PostgresPluginDataStore implements PluginDataStore {
|
||||
readonly engine = 'postgres' as const;
|
||||
private readonly schema: string;
|
||||
private readonly quoted: string;
|
||||
private readonly limits: PostgresPluginDataLimits;
|
||||
private open = true;
|
||||
private queue: Promise<unknown> = Promise.resolve();
|
||||
|
||||
constructor(
|
||||
readonly pluginId: string,
|
||||
private readonly connect: ConnectPluginClient,
|
||||
private readonly slots: PluginDataSlots,
|
||||
limits: Partial<PostgresPluginDataLimits> = {},
|
||||
private readonly roleGate: PluginRoleGate = new PrivilegedRoleGate(),
|
||||
) {
|
||||
this.schema = pluginSchemaName(pluginId);
|
||||
this.quoted = quotePluginSchema(this.schema);
|
||||
this.limits = { ...DEFAULT_LIMITS, ...limits };
|
||||
}
|
||||
|
||||
isOpen(): boolean {
|
||||
return this.open;
|
||||
}
|
||||
|
||||
/** Stops new calls. One already running finishes: it holds a pool client of its own, not this store. */
|
||||
close(): void {
|
||||
this.open = false;
|
||||
}
|
||||
|
||||
async query(sql: string, args: unknown[] = []): Promise<unknown[]> {
|
||||
const statement = this.single(sql, args);
|
||||
const { maxRows } = this.limits;
|
||||
return this.call('query', (budget) =>
|
||||
this.transaction(budget.ms, [statement], (client) => {
|
||||
const rows = { count: 0, max: maxRows, message: `query returned more than ${maxRows} rows` };
|
||||
return this.stream(client, statement, args, rows, budget.check);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
async exec(sql: string, args: unknown[] = []): Promise<{ changes: number }> {
|
||||
if (args.length > 0) {
|
||||
const statement = this.single(sql, args);
|
||||
return this.call('exec', (budget) =>
|
||||
this.transaction(budget.ms, [statement], async (client) => ({
|
||||
changes: await this.run(client, statement, args),
|
||||
})),
|
||||
);
|
||||
}
|
||||
const statements = this.parse(sql);
|
||||
return this.call('exec', async (budget) => {
|
||||
// A script runs as SQLite runs one: each statement commits on its own, and
|
||||
// the clock is read before every statement but the first.
|
||||
await inOrder(statements, (statement, index) => {
|
||||
if (index > 0) budget.check();
|
||||
return this.transaction(budget.remaining(), [statement], (client) => this.run(client, statement, []));
|
||||
});
|
||||
return { changes: 0 };
|
||||
});
|
||||
}
|
||||
|
||||
async tx(ops: PluginTxOp[]): Promise<PluginTxResult> {
|
||||
if (!Array.isArray(ops)) throw new Error('tx requires an array of { sql, args }');
|
||||
if (ops.length === 0) return { results: [] };
|
||||
if (ops.length > PLUGIN_DATA_CAPS.maxTxOps) {
|
||||
throw new Error(`tx allows at most ${PLUGIN_DATA_CAPS.maxTxOps} statements`);
|
||||
}
|
||||
const statements = ops.map((op) => this.single(op?.sql, op?.args ?? []));
|
||||
const { maxRows } = this.limits;
|
||||
return this.call('tx', (budget) =>
|
||||
this.transaction(budget.ms, statements, async (client) => {
|
||||
const rows = { count: 0, max: maxRows, message: `tx returned more than ${maxRows} rows in total` };
|
||||
const results = await inOrder(statements, async (statement, index) => {
|
||||
const args = ops[index].args ?? [];
|
||||
// One budget for the whole batch: each statement after the first gets what is left of it.
|
||||
if (index > 0) await this.setTimeout(client, budget.remaining());
|
||||
const result = statement.returnsRows
|
||||
? { rows: await this.stream(client, statement, args, rows, budget.check) }
|
||||
: { changes: await this.run(client, statement, args) };
|
||||
budget.check();
|
||||
return result;
|
||||
});
|
||||
return { results };
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/** No time budget, as on SQLite: a migration stopped part of the way would fail the same way on every start. */
|
||||
async migrate(id: string, sql: string): Promise<{ applied: boolean }> {
|
||||
const statements = this.parse(sql);
|
||||
refuseNulValues([id]);
|
||||
return this.enqueue(() =>
|
||||
this.transaction(null, statements, async (client) => {
|
||||
const seen = await client.query({
|
||||
text: `select 1 from ${this.quoted}._plugin_migrations where id = $1`,
|
||||
values: [id],
|
||||
});
|
||||
if (seen.rows.length > 0) return { applied: false };
|
||||
await inOrder(statements, (statement) => this.run(client, statement, []));
|
||||
await client.query({
|
||||
text: `insert into ${this.quoted}._plugin_migrations (id, applied_at) values ($1, $2)`,
|
||||
values: [id, Date.now()],
|
||||
});
|
||||
return { applied: true };
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/** `sql` as exactly one statement, checked against `args`. */
|
||||
private single(sql: unknown, args: readonly unknown[]): PluginStatement {
|
||||
const statements = this.parse(sql);
|
||||
if (statements.length !== 1) throw new Error('sql must hold exactly one statement here; use exec() for a script');
|
||||
checkPlaceholders(statements[0], args);
|
||||
refuseNulValues(args);
|
||||
return statements[0];
|
||||
}
|
||||
|
||||
/** The statements of `sql`, refused when the guard does not allow one or none is there. */
|
||||
private parse(sql: unknown): PluginStatement[] {
|
||||
if (!this.open) throw new Error(CLOSED);
|
||||
if (typeof sql !== 'string') throw new Error('sql must be a string');
|
||||
if (sql.length > PLUGIN_DATA_CAPS.maxSqlLength) throw new Error('sql too long');
|
||||
const statements = parsePluginSql(sql);
|
||||
if (statements.length === 0) throw new Error('The supplied SQL string contains no statements');
|
||||
return statements;
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs `work` in this plugin's turn with a time budget that starts when its
|
||||
* turn comes, and reports a statement Postgres cancelled at
|
||||
* `statement_timeout` as the budget running out.
|
||||
*/
|
||||
private call<T>(what: string, work: (budget: Budget) => Promise<T>): Promise<T> {
|
||||
const { now, timeBudgetMs } = this.limits;
|
||||
return this.enqueue(async () => {
|
||||
const startedAt = now();
|
||||
const budget: Budget = {
|
||||
ms: timeBudgetMs,
|
||||
remaining: () => Math.max(1, timeBudgetMs - (now() - startedAt)),
|
||||
check: () => {
|
||||
if (now() - startedAt > timeBudgetMs) throw new Error(`${what} exceeded its ${timeBudgetMs} ms time budget`);
|
||||
},
|
||||
};
|
||||
try {
|
||||
return await work(budget);
|
||||
} catch (err) {
|
||||
if (sqlState(err) === QUERY_CANCELED) {
|
||||
throw new Error(`${what} exceeded its ${timeBudgetMs} ms time budget`, { cause: err });
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** Queues `work` behind this plugin's earlier calls, then waits for a pool slot. */
|
||||
private enqueue<T>(work: () => Promise<T>): Promise<T> {
|
||||
const turn = this.queue.then(() => this.slots.run(work));
|
||||
this.queue = turn.catch(() => undefined);
|
||||
return turn;
|
||||
}
|
||||
|
||||
/**
|
||||
* One transaction on this plugin's schema, on a client of its own: created
|
||||
* if missing, alone on the `search_path`, with `statement_timeout` at
|
||||
* `timeoutMs` (none for null). The statements' qualified names are checked
|
||||
* against the database's schemas first, and a call that may write is held
|
||||
* to the quota. The client goes back to the pool with its session state
|
||||
* dropped, or is closed when the rollback or that cleanup fails.
|
||||
*/
|
||||
private async transaction<T>(
|
||||
timeoutMs: number | null,
|
||||
statements: readonly PluginStatement[],
|
||||
work: (client: PluginSqlClient) => Promise<T>,
|
||||
): Promise<T> {
|
||||
const client = await this.connect();
|
||||
let reusable = true;
|
||||
try {
|
||||
await this.roleGate.refuseIfPrivileged(client);
|
||||
await client.query('begin');
|
||||
try {
|
||||
const result = await this.inTransaction(client, timeoutMs, statements, work);
|
||||
await client.query('commit');
|
||||
return result;
|
||||
} catch (err) {
|
||||
await client.query('rollback').catch(() => {
|
||||
reusable = false;
|
||||
});
|
||||
throw err;
|
||||
}
|
||||
} finally {
|
||||
if (reusable) {
|
||||
await client.query(END_SESSION).catch(() => {
|
||||
reusable = false;
|
||||
});
|
||||
}
|
||||
client.release(!reusable);
|
||||
}
|
||||
}
|
||||
|
||||
/** What {@link transaction} runs between `begin` and `commit`. */
|
||||
private async inTransaction<T>(
|
||||
client: PluginSqlClient,
|
||||
timeoutMs: number | null,
|
||||
statements: readonly PluginStatement[],
|
||||
work: (client: PluginSqlClient) => Promise<T>,
|
||||
): Promise<T> {
|
||||
const setup = [
|
||||
`create schema if not exists ${this.quoted}`,
|
||||
`create table if not exists ${this.quoted}._plugin_migrations (id text primary key, applied_at bigint)`,
|
||||
`set local search_path to ${this.quoted}, pg_temp`,
|
||||
'set local standard_conforming_strings to on',
|
||||
];
|
||||
if (timeoutMs !== null) setup.push(`set local statement_timeout to ${Math.max(1, Math.floor(timeoutMs))}`);
|
||||
await client.query(setup.join(';\n'));
|
||||
if (statements.some((s) => s.qualifies)) {
|
||||
const schemas = await this.schemaNames(client);
|
||||
for (const statement of statements) checkQualifiers(statement, this.schema, schemas);
|
||||
}
|
||||
const writes = statements.some((s) => s.mayWrite);
|
||||
const before = writes ? await schemaUsage(client, this.schema) : null;
|
||||
const result = await work(client);
|
||||
if (before !== null) this.checkQuota(before, await schemaUsage(client, this.schema));
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Refuses a call that left the schema past its quota or its object cap and
|
||||
* grew it there, so a plugin at either limit can still delete.
|
||||
*/
|
||||
private checkQuota(before: SchemaUsage, after: SchemaUsage): void {
|
||||
const { quotaBytes, maxObjects } = this.limits;
|
||||
if (after.bytes > quotaBytes && after.bytes > before.bytes) {
|
||||
throw new Error(`the plugin database is past its ${quotaBytes / 1024 / 1024} MB quota`);
|
||||
}
|
||||
if (after.objects > maxObjects && after.objects > before.objects) {
|
||||
throw new Error(
|
||||
`the plugin database holds more than ${maxObjects} catalog objects (tables, indexes, sequences, views, ` +
|
||||
'types, constraints, enum labels)',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private async setTimeout(client: PluginSqlClient, ms: number): Promise<void> {
|
||||
await client.query({
|
||||
text: "select set_config('statement_timeout', $1, true)",
|
||||
values: [String(Math.max(1, Math.floor(ms)))],
|
||||
});
|
||||
}
|
||||
|
||||
/** Every schema name of the database, which a qualified name in plugin SQL may not use. */
|
||||
private async schemaNames(client: PluginSqlClient): Promise<Set<string>> {
|
||||
const result = await client.query('select nspname from pg_namespace');
|
||||
return new Set((result.rows as Array<{ nspname: string }>).map((row) => row.nspname));
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs a statement for its effect: the rows it changed, or 0 for a read,
|
||||
* whose rows are read past and dropped. Both go over the extended protocol:
|
||||
* a write as an extended query, a read through a cursor.
|
||||
*/
|
||||
private async run(client: PluginSqlClient, statement: PluginStatement, args: readonly unknown[]): Promise<number> {
|
||||
await refuseForeignTargets(client, statement, this.schema);
|
||||
if (!statement.mayWrite) {
|
||||
// Read to the end so the statement runs whole; its rows are not wanted.
|
||||
await readCursor(client.query(new Cursor(statement.text, [...args])), () => undefined);
|
||||
return 0;
|
||||
}
|
||||
const result = await client.query({ text: statement.text, values: [...args], queryMode: 'extended' });
|
||||
return result.rowCount ?? 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* The rows of a statement, read through a cursor a chunk at a time: past the
|
||||
* row cap the read stops and throws, and the clock is read between chunks.
|
||||
*/
|
||||
private async stream(
|
||||
client: PluginSqlClient,
|
||||
statement: PluginStatement,
|
||||
args: readonly unknown[],
|
||||
budget: RowBudget,
|
||||
checkTime: () => void,
|
||||
): Promise<unknown[]> {
|
||||
await refuseForeignTargets(client, statement, this.schema);
|
||||
const rows: unknown[] = [];
|
||||
await readCursor(client.query(new Cursor(statement.text, [...args])), (chunk) => {
|
||||
if (rows.length > 0) checkTime();
|
||||
for (const row of chunk) {
|
||||
rows.push(row);
|
||||
budget.count++;
|
||||
if (budget.count > budget.max) throw new Error(budget.message);
|
||||
}
|
||||
});
|
||||
return rows;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads `cursor` to its end a chunk at a time, handing each chunk to `take`
|
||||
* (which may throw to stop the read), and closes it however the read ends.
|
||||
*/
|
||||
async function readCursor(cursor: Cursor, take: (rows: unknown[]) => void): Promise<void> {
|
||||
const next = async (): Promise<void> => {
|
||||
const rows = await cursor.read(CHUNK_ROWS);
|
||||
if (rows.length === 0) return;
|
||||
take(rows);
|
||||
return next();
|
||||
};
|
||||
try {
|
||||
await next();
|
||||
} finally {
|
||||
await cursor.close();
|
||||
}
|
||||
}
|
||||
|
||||
/** `work` for each item, one after the other, each started once the one before it has finished. */
|
||||
async function inOrder<T, R>(items: readonly T[], work: (item: T, index: number) => Promise<R>): Promise<R[]> {
|
||||
const results: R[] = [];
|
||||
await items.reduce<Promise<void>>(
|
||||
(previous, item, index) =>
|
||||
previous.then(async () => {
|
||||
results.push(await work(item, index));
|
||||
}),
|
||||
Promise.resolve(),
|
||||
);
|
||||
return results;
|
||||
}
|
||||
|
||||
/** A call's time budget: its whole length, what is left of it, and a check that throws once it is spent. */
|
||||
interface Budget {
|
||||
readonly ms: number;
|
||||
remaining(): number;
|
||||
check(): void;
|
||||
}
|
||||
|
||||
/** The SQLSTATE of a `pg` error, or null. */
|
||||
function sqlState(err: unknown): string | null {
|
||||
if (typeof err !== 'object' || err === null || !('code' in err)) return null;
|
||||
return typeof err.code === 'string' ? err.code : null;
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* The schema a plugin's own data lives in on Postgres (`db:own`): one per
|
||||
* plugin, named from its id, beside TREK's schema in the same database.
|
||||
*
|
||||
* A plugin id is what the manifest allows (`PLUGIN_ID_RE` in
|
||||
* `nest/plugins/protocol/manifest-rules.ts`): a lowercase letter, then 2 to 39
|
||||
* lowercase letters, digits or dashes. The schema name is the prefix plus the
|
||||
* id with each dash spelled as an underscore. An id never holds an underscore,
|
||||
* so two ids never share a name, and the longest name (52 characters) stays
|
||||
* under Postgres's 63. The pattern is repeated here rather than imported,
|
||||
* because `src/db` does not import `src/nest`; a unit test holds the two equal.
|
||||
*
|
||||
* Every name TREK gives a plugin schema starts with the prefix, so a backup,
|
||||
* a restore and the plugin SQL guard can tell them from every other schema of
|
||||
* the database. Two TREK instances on one database would share these names,
|
||||
* so each instance needs a database of its own (the wiki says so).
|
||||
*/
|
||||
|
||||
/** What every plugin schema's name starts with. */
|
||||
export const PLUGIN_SCHEMA_PREFIX = 'trek_plugin_';
|
||||
|
||||
/** The plugin ids a schema name can be made from: the manifest's rule. */
|
||||
const PLUGIN_ID = /^[a-z][a-z0-9-]{2,39}$/;
|
||||
|
||||
/** A plugin schema's name, as `pluginSchemaName` makes it. */
|
||||
const PLUGIN_SCHEMA = /^trek_plugin_[a-z][a-z0-9_]{2,39}$/;
|
||||
|
||||
/** Whether `id` is a plugin id a schema name can be made from. */
|
||||
export function isPluginId(id: string): boolean {
|
||||
return PLUGIN_ID.test(id);
|
||||
}
|
||||
|
||||
/** The schema of the plugin `id`. Throws for anything the manifest would not accept as an id. */
|
||||
export function pluginSchemaName(id: string): string {
|
||||
if (!isPluginId(id)) throw new Error(`"${id}" is not a plugin id, so it has no data schema.`);
|
||||
return PLUGIN_SCHEMA_PREFIX + id.replaceAll('-', '_');
|
||||
}
|
||||
|
||||
/** Whether `name` is a schema name `pluginSchemaName` makes. */
|
||||
export function isPluginSchemaName(name: string): boolean {
|
||||
return PLUGIN_SCHEMA.test(name);
|
||||
}
|
||||
|
||||
/**
|
||||
* `name` as a quoted SQL identifier. Only plugin schema names reach it, which
|
||||
* hold no quote, so the quoting cannot be escaped; it is checked all the same.
|
||||
*/
|
||||
export function quotePluginSchema(name: string): string {
|
||||
if (!isPluginSchemaName(name)) throw new Error(`"${name}" is not a plugin schema name.`);
|
||||
return `"${name}"`;
|
||||
}
|
||||
@@ -0,0 +1,708 @@
|
||||
import { PLUGIN_SCHEMA_PREFIX } from './plugin-schema';
|
||||
|
||||
/**
|
||||
* What keeps a plugin's own SQL on Postgres inside its own schema.
|
||||
*
|
||||
* On SQLite a plugin's database is a file of its own, so it cannot name
|
||||
* TREK's tables at all. On Postgres its schema sits in TREK's database and
|
||||
* its statements run as TREK's role, which may read every table TREK has: a
|
||||
* role per plugin would need CREATEROLE, which TREK's role is not given. So
|
||||
* the store (`plugin-data-store.ts`) keeps it in with layers that each hold
|
||||
* on their own for what they cover, the ones after this guard enforced by
|
||||
* the database itself:
|
||||
*
|
||||
* 1. No plugin SQL at all while TREK's role is privileged in the sense of the
|
||||
* restore check (`PRIVILEGED_ROLE_SQL` in `server-checks.ts`: a superuser
|
||||
* or a member of one, a role that may reach the server's files or
|
||||
* programs, ...): every `db:own` call fails with
|
||||
* `PRIVILEGED_ROLE_PLUGIN_REFUSAL`, and the boot log says why
|
||||
* (`plugin-data-checks.ts`). Such a role may change the system catalogs,
|
||||
* which no check on the SQL text can rule out.
|
||||
* 2. This guard holds each statement to what cannot leave the schema, before
|
||||
* it runs (below).
|
||||
* 3. Every existing object a statement changes ({@link PluginTarget}: the
|
||||
* target of an ALTER, DROP, REFRESH, TRUNCATE or CREATE INDEX ... ON, and
|
||||
* the tables a CREATE or ALTER TABLE ties to its own) is resolved by
|
||||
* Postgres in the transaction, right before the statement, with
|
||||
* `to_regclass` or `to_regtype` on the plugin's `search_path`, and the
|
||||
* statement is refused unless each one found lies in the plugin's schema.
|
||||
* `pg_catalog` is searched first, so an unqualified `int4`, `text` or
|
||||
* `box` is the catalog's type and refused, on a superuser connection too.
|
||||
* 4. The store sends every statement on its own over the extended query
|
||||
* protocol, on a pool client it checked out for the call: Postgres parses
|
||||
* exactly one statement there, so a second statement the guard missed is
|
||||
* an error, never run.
|
||||
* 5. The transaction puts the plugin's schema on the `search_path` with
|
||||
* `pg_temp` explicitly last, TREK's own pool connections put `pg_temp`
|
||||
* last too (`session-search-path.ts`), and the store drops every
|
||||
* temporary table on its client before giving it back, so a temporary
|
||||
* table never stands in for a table of TREK's or of the plugin's.
|
||||
* 6. A call that may write is held to the disk quota, counted over every
|
||||
* relation of the schema with its TOAST table, and to
|
||||
* `PLUGIN_SCHEMA_MAX_OBJECTS` catalog objects, so views, types and enum
|
||||
* labels, which take no disk space of their own, are bounded too.
|
||||
*
|
||||
* The SQL is split into tokens the way Postgres's own lexer splits it (string
|
||||
* and identifier quoting, comments, dollar signs). Where JavaScript and the
|
||||
* Postgres lexer would read a character differently, the guard refuses it
|
||||
* instead of guessing: whitespace is exactly what Postgres skips (space, tab,
|
||||
* CR, LF, form feed), a `--` comment ends at CR or LF as it does there, and
|
||||
* any other control character, or whitespace past ASCII (U+00A0, U+FEFF,
|
||||
* U+2028, ...), outside a string, a quoted name or a comment is refused. A
|
||||
* NUL is refused anywhere, strings included: the protocol ends a statement's
|
||||
* text there. The SQL is refused when it holds:
|
||||
*
|
||||
* - a statement other than SELECT, INSERT, UPDATE, DELETE, MERGE, WITH,
|
||||
* VALUES, TABLE, TRUNCATE, REFRESH, or a CREATE, ALTER or DROP of a table,
|
||||
* index, view, materialized view, sequence or type (a composite, enum or
|
||||
* range type; a base type is built from C functions). No function, schema,
|
||||
* role, setting, transaction control, COPY, LOCK, prepared statement or
|
||||
* notification. Several statements are split at their semicolons and each
|
||||
* is checked;
|
||||
* - a qualified name whose qualifier is another schema of the database
|
||||
* (`public.users`, another plugin's schema), or any name starting with
|
||||
* `pg_` or naming `information_schema`: the catalogs, the server functions
|
||||
* and the temporary schema;
|
||||
* - a function that runs SQL handed to it as text (`query_to_xml`, `ts_stat`,
|
||||
* `ts_rewrite`), reads or changes settings (`set_config`,
|
||||
* `current_setting`), reaches objects by a name in a string (`nextval`,
|
||||
* `setval`, `has_table_privilege` and its siblings, `currtid2`, the BRIN
|
||||
* and GIN maintenance functions, `to_reg*`), large objects (`lo_*`) or
|
||||
* `dblink`;
|
||||
* - the object identifier types that look an object up by name
|
||||
* (`regclass`, `regtype`, `regproc`, `regprocedure`, `regoper`,
|
||||
* `regoperator`, `regconfig`, `regdictionary`, `regnamespace`, `regrole`,
|
||||
* `regcollation`, and their array types `_regclass`, ...), in every
|
||||
* spelling: `'x'::regtype`, `CAST('x' AS regtype)`, `regtype 'x'`, quoted;
|
||||
* - a temporary object: CREATE TEMP or TEMPORARY (also after OR REPLACE,
|
||||
* LOCAL or GLOBAL), and SELECT ... INTO TEMP; a temporary table outlives
|
||||
* the call on a pooled connection. Elsewhere `temp` is an ordinary name;
|
||||
* - INTO anywhere but right after the verb INSERT or MERGE of the statement
|
||||
* itself or of a WITH query's body, at any depth of parentheses: `SELECT
|
||||
* ... INTO` creates a table outside what CREATE is held to, and in `SELECT
|
||||
* 1 insert INTO t` the word `insert` is only a column alias;
|
||||
* - `WITH RECURSIVE`, refused on SQLite too;
|
||||
* - in an ALTER, a change of a table's schema, owner or tablespace;
|
||||
* - escape strings (`E'...'`), Unicode escapes (`U&'...'`), dollar-quoted
|
||||
* strings, hexadecimal, octal and binary numbers, digit separators (`1_000`)
|
||||
* and a number running straight into a name, whose reading differs between
|
||||
* Postgres versions and settings (before 16, Postgres reads `0x1F` as `0 AS x1F`).
|
||||
*
|
||||
* An alias that happens to share a schema's name (`auth.id` on a database
|
||||
* that has an `auth` schema) is refused too; the plugin renames the alias.
|
||||
*/
|
||||
|
||||
/** Why a plugin's SQL is refused. The message is the plugin's to read, so it says what to change. */
|
||||
export class PluginSqlRefused extends Error {
|
||||
constructor(reason: string) {
|
||||
super(`statement type not allowed for plugin databases: ${reason}`);
|
||||
this.name = 'PluginSqlRefused';
|
||||
}
|
||||
}
|
||||
|
||||
/** One token of plugin SQL. A word is a name or a keyword: `value` is folded to lower case unless it was quoted. */
|
||||
type Token = (
|
||||
| { kind: 'word'; value: string; quoted: boolean }
|
||||
| { kind: 'string' }
|
||||
| { kind: 'number' }
|
||||
| { kind: 'param' }
|
||||
| { kind: 'punct'; value: string }
|
||||
) & {
|
||||
/** Where the token starts in the SQL text. */
|
||||
at: number;
|
||||
};
|
||||
|
||||
/** One statement of plugin SQL: its tokens, without the semicolon that ended it. */
|
||||
export interface PluginStatement {
|
||||
/** The statement's own text, as Postgres is handed it. */
|
||||
readonly text: string;
|
||||
readonly tokens: readonly Token[];
|
||||
/** Whether it returns rows: a SELECT, VALUES or TABLE, or anything with a RETURNING clause. */
|
||||
readonly returnsRows: boolean;
|
||||
/** Whether it may change data or schema, which is what the disk quota is checked after. */
|
||||
readonly mayWrite: boolean;
|
||||
/** Whether it names a qualified object (`x.y`), which needs the database's schema names to check. */
|
||||
readonly qualifies: boolean;
|
||||
/** How many `$n` placeholders it holds. */
|
||||
readonly params: number;
|
||||
/**
|
||||
* The existing objects it changes, which the store resolves in the
|
||||
* transaction right before the statement runs and refuses unless each one
|
||||
* found lies in the plugin's own schema ({@link PluginTarget}).
|
||||
*/
|
||||
readonly targets: readonly PluginTarget[];
|
||||
}
|
||||
|
||||
/**
|
||||
* An existing object a statement changes: the table, index, view,
|
||||
* materialized view or sequence (`relation`) or the type an ALTER, DROP,
|
||||
* REFRESH or TRUNCATE names, the table a CREATE INDEX is ON, and the tables a
|
||||
* CREATE or ALTER TABLE ties to its own (REFERENCES, INHERITS, PARTITION OF,
|
||||
* ATTACH, DETACH and INHERIT). `name` holds the name's parts as Postgres
|
||||
* keeps them (folded unless quoted, cut to 63 bytes), qualifier first. A
|
||||
* name that resolves to nothing is left to Postgres, which reports it missing
|
||||
* or, with IF EXISTS, skips it.
|
||||
*/
|
||||
export interface PluginTarget {
|
||||
readonly kind: 'relation' | 'type';
|
||||
readonly name: readonly string[];
|
||||
}
|
||||
|
||||
/** Postgres keeps the first 63 bytes of a name (NAMEDATALEN - 1) and drops the rest. */
|
||||
const MAX_NAME_BYTES = 63;
|
||||
|
||||
/** The first word of each statement a plugin may run. */
|
||||
const STATEMENTS = new Set([
|
||||
'select',
|
||||
'insert',
|
||||
'update',
|
||||
'delete',
|
||||
'merge',
|
||||
'with',
|
||||
'values',
|
||||
'table',
|
||||
'truncate',
|
||||
'refresh',
|
||||
'create',
|
||||
'alter',
|
||||
'drop',
|
||||
]);
|
||||
|
||||
/** Transaction control: every call already runs in a transaction of the host's. */
|
||||
const TRANSACTION_CONTROL = new Set(['begin', 'start', 'commit', 'end', 'rollback', 'abort', 'savepoint', 'release']);
|
||||
|
||||
/** What a CREATE, ALTER or DROP may act on. */
|
||||
const OBJECTS = new Set(['table', 'index', 'view', 'materialized', 'sequence', 'type']);
|
||||
|
||||
/** The words that make up a statement's main verb, after a WITH clause. */
|
||||
const VERBS = new Set(['select', 'insert', 'update', 'delete', 'merge', 'values', 'table']);
|
||||
|
||||
/** The verbs of a statement that only reads. */
|
||||
const READ_VERBS = new Set(['select', 'values', 'table']);
|
||||
|
||||
/**
|
||||
* The object identifier types whose input looks an object up by a name in a
|
||||
* string (`'public.users'::regclass`, `CAST('int4' AS regtype)`,
|
||||
* `regtype 'text'`), refused in every spelling, their array types
|
||||
* (`_regclass`) too.
|
||||
*/
|
||||
const NAME_LOOKUP_TYPES = [
|
||||
'regclass',
|
||||
'regtype',
|
||||
'regproc',
|
||||
'regprocedure',
|
||||
'regoper',
|
||||
'regoperator',
|
||||
'regconfig',
|
||||
'regdictionary',
|
||||
'regnamespace',
|
||||
'regrole',
|
||||
'regcollation',
|
||||
];
|
||||
|
||||
/** Functions and types refused under any spelling, quoted or not. */
|
||||
const REFUSED_NAMES = new Set([
|
||||
'set_config',
|
||||
'current_setting',
|
||||
'ts_stat',
|
||||
'ts_rewrite',
|
||||
'nextval',
|
||||
'setval',
|
||||
'currval',
|
||||
'lastval',
|
||||
'loread',
|
||||
'lowrite',
|
||||
...NAME_LOOKUP_TYPES,
|
||||
...NAME_LOOKUP_TYPES.map((type) => `_${type}`),
|
||||
// Functions that take a relation, a type or another object by a name in a
|
||||
// string, or reach an index by one to maintain it.
|
||||
'has_any_column_privilege',
|
||||
'has_column_privilege',
|
||||
'has_database_privilege',
|
||||
'has_foreign_data_wrapper_privilege',
|
||||
'has_function_privilege',
|
||||
'has_language_privilege',
|
||||
'has_parameter_privilege',
|
||||
'has_schema_privilege',
|
||||
'has_sequence_privilege',
|
||||
'has_server_privilege',
|
||||
'has_table_privilege',
|
||||
'has_tablespace_privilege',
|
||||
'has_type_privilege',
|
||||
'row_security_active',
|
||||
'currtid2',
|
||||
'brin_summarize_new_values',
|
||||
'brin_summarize_range',
|
||||
'brin_desummarize_range',
|
||||
'gin_clean_pending_list',
|
||||
'information_schema',
|
||||
]);
|
||||
|
||||
/** Name prefixes refused under any spelling. */
|
||||
const REFUSED_PREFIXES = ['pg_', 'lo_', 'dblink', 'to_reg', 'binary_upgrade_'];
|
||||
|
||||
/** A name refused wherever it appears: the XML exports of a query, a table, a schema or the database. */
|
||||
const XML_EXPORT = /_to_xml/;
|
||||
|
||||
/** Starts a name: a letter, an underscore or any character past ASCII, as Postgres reads it. */
|
||||
const NAME_START = /[A-Za-z_\u0080-]/;
|
||||
/** Continues a name; a dollar sign is part of one. */
|
||||
const NAME_PART = /[A-Za-z0-9_$\u0080-]/;
|
||||
/** The single-character punctuation and operator characters. */
|
||||
const PUNCT = new Set([...'.,()[];+-*/<>=~!@#%^&|?']);
|
||||
/**
|
||||
* What the Postgres lexer skips as whitespace (`space` in scan.l). Vertical
|
||||
* tab is whitespace only from Postgres 16 on, so it is refused instead.
|
||||
*/
|
||||
const WHITESPACE = new Set([' ', '\t', '\n', '\r', '\f']);
|
||||
/** The verbs INTO may follow. Anywhere else it makes a table (`SELECT ... INTO`). */
|
||||
const INTO_AFTER = new Set(['insert', 'merge']);
|
||||
/** The words that make an object temporary right after CREATE (`CREATE LOCAL TEMP TABLE`). */
|
||||
const TEMPORARY = new Set(['temp', 'temporary']);
|
||||
|
||||
/**
|
||||
* Whether JavaScript and the Postgres lexer read `ch` differently: a control
|
||||
* character Postgres does not skip, or whitespace past ASCII, which
|
||||
* JavaScript's `\s` skips and Postgres reads as part of a name.
|
||||
*/
|
||||
function divergent(ch: string): boolean {
|
||||
if (WHITESPACE.has(ch)) return false;
|
||||
const code = ch.charCodeAt(0);
|
||||
return code < 0x20 || code === 0x7f || /\s/.test(ch);
|
||||
}
|
||||
|
||||
/** Refuses `ch` when {@link divergent}. */
|
||||
function refuseDivergent(ch: string): void {
|
||||
if (divergent(ch)) {
|
||||
const code = ch.charCodeAt(0).toString(16).toUpperCase().padStart(4, '0');
|
||||
throw new PluginSqlRefused(
|
||||
`the character U+${code} is read differently by Postgres; outside a string use plain spaces, tabs and newlines`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** `name` lower-cased the way Postgres folds an unquoted name: ASCII letters only. */
|
||||
function fold(name: string): string {
|
||||
return name.replace(/[A-Z]/g, (c) => c.toLowerCase());
|
||||
}
|
||||
|
||||
/** `name` cut to the bytes Postgres keeps of it, never in the middle of a character. */
|
||||
function truncateName(name: string): string {
|
||||
if (Buffer.byteLength(name, 'utf8') <= MAX_NAME_BYTES) return name;
|
||||
let out = '';
|
||||
for (const ch of name) {
|
||||
if (Buffer.byteLength(out + ch, 'utf8') > MAX_NAME_BYTES) break;
|
||||
out += ch;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Splits `sql` into tokens, or refuses what this guard does not read the way Postgres would. */
|
||||
export function tokenize(sql: string): Token[] {
|
||||
if (sql.includes('\u0000')) {
|
||||
// The protocol ends a statement's text at a NUL, so what Postgres would read is not what was checked.
|
||||
throw new PluginSqlRefused(
|
||||
'the SQL holds the character U+0000 (NUL), which Postgres cannot read in a statement or store in text',
|
||||
);
|
||||
}
|
||||
const tokens: Token[] = [];
|
||||
let i = 0;
|
||||
const n = sql.length;
|
||||
while (i < n) {
|
||||
const at = i;
|
||||
const c = sql[i];
|
||||
const next = sql[i + 1];
|
||||
refuseDivergent(c);
|
||||
if (WHITESPACE.has(c)) {
|
||||
i++;
|
||||
} else if (c === '-' && next === '-') {
|
||||
// Postgres ends a line comment at either newline character (`non_newline` in scan.l).
|
||||
while (i < n && sql[i] !== '\n' && sql[i] !== '\r') i++;
|
||||
} else if (c === '/' && next === '*') {
|
||||
i = skipBlockComment(sql, i);
|
||||
} else if (c === "'") {
|
||||
i = skipQuoted(sql, i, "'", 'a string');
|
||||
tokens.push({ kind: 'string', at });
|
||||
} else if (c === '"') {
|
||||
const end = skipQuoted(sql, i, '"', 'a quoted name');
|
||||
const value = sql.slice(i + 1, end - 1).replaceAll('""', '"');
|
||||
if (value === '') throw new PluginSqlRefused('a quoted name may not be empty');
|
||||
tokens.push({ kind: 'word', value: truncateName(value), quoted: true, at });
|
||||
i = end;
|
||||
} else if (c === '$') {
|
||||
if (!/[0-9]/.test(next ?? '')) {
|
||||
throw new PluginSqlRefused('dollar-quoted strings are not accepted; write the string in single quotes');
|
||||
}
|
||||
i++;
|
||||
while (i < n && /[0-9]/.test(sql[i])) i++;
|
||||
tokens.push({ kind: 'param', at });
|
||||
} else if (/[0-9]/.test(c) || (c === '.' && /[0-9]/.test(next ?? ''))) {
|
||||
if (c === '0' && /[xXoObB]/.test(next ?? '')) {
|
||||
throw new PluginSqlRefused(
|
||||
'hexadecimal, octal and binary numbers are not accepted: Postgres before 16 reads 0x1F as 0 AS x1F; write it in decimal',
|
||||
);
|
||||
}
|
||||
i = skipNumber(sql, i);
|
||||
if (sql[i] === '_') {
|
||||
throw new PluginSqlRefused('digit separators (1_000) are not accepted: Postgres before 16 does not read them');
|
||||
}
|
||||
if (i < n) refuseDivergent(sql[i]);
|
||||
if (i < n && NAME_PART.test(sql[i])) {
|
||||
throw new PluginSqlRefused('a number may not run straight into a name; put a space between them');
|
||||
}
|
||||
tokens.push({ kind: 'number', at });
|
||||
} else if (NAME_START.test(c)) {
|
||||
if ((c === 'e' || c === 'E') && next === "'") {
|
||||
throw new PluginSqlRefused("escape strings (E'...') are not accepted; write the string in single quotes");
|
||||
}
|
||||
if ((c === 'u' || c === 'U') && next === '&' && (sql[i + 2] === "'" || sql[i + 2] === '"')) {
|
||||
throw new PluginSqlRefused('Unicode escapes (U&) are not accepted');
|
||||
}
|
||||
while (i < n && NAME_PART.test(sql[i])) {
|
||||
refuseDivergent(sql[i]);
|
||||
i++;
|
||||
}
|
||||
tokens.push({ kind: 'word', value: truncateName(fold(sql.slice(at, i))), quoted: false, at });
|
||||
} else if (c === ':' && next === ':') {
|
||||
tokens.push({ kind: 'punct', value: '::', at });
|
||||
i += 2;
|
||||
} else if (c === ':' || PUNCT.has(c)) {
|
||||
tokens.push({ kind: 'punct', value: c, at });
|
||||
i++;
|
||||
} else {
|
||||
throw new PluginSqlRefused(`unexpected character ${JSON.stringify(c)}`);
|
||||
}
|
||||
}
|
||||
return tokens;
|
||||
}
|
||||
|
||||
/** The index past a block comment starting at `start`; Postgres nests them. */
|
||||
function skipBlockComment(sql: string, start: number): number {
|
||||
let depth = 0;
|
||||
let i = start;
|
||||
while (i < sql.length) {
|
||||
if (sql[i] === '/' && sql[i + 1] === '*') {
|
||||
depth++;
|
||||
i += 2;
|
||||
} else if (sql[i] === '*' && sql[i + 1] === '/') {
|
||||
depth--;
|
||||
i += 2;
|
||||
if (depth === 0) return i;
|
||||
} else {
|
||||
i++;
|
||||
}
|
||||
}
|
||||
throw new PluginSqlRefused('a comment is not closed');
|
||||
}
|
||||
|
||||
/** The index past a quoted string or name starting at `start`; a doubled quote stands for one. */
|
||||
function skipQuoted(sql: string, start: number, quote: string, what: string): number {
|
||||
let i = start + 1;
|
||||
while (i < sql.length) {
|
||||
if (sql[i] === quote) {
|
||||
if (sql[i + 1] === quote) {
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
return i + 1;
|
||||
}
|
||||
i++;
|
||||
}
|
||||
throw new PluginSqlRefused(`${what} is not closed`);
|
||||
}
|
||||
|
||||
/** The index past a decimal numeric constant starting at `start`, with a fraction and an exponent. */
|
||||
function skipNumber(sql: string, start: number): number {
|
||||
const match = /^(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)(?:[eE][+-]?[0-9]+)?/.exec(sql.slice(start));
|
||||
return start + (match ? match[0].length : 1);
|
||||
}
|
||||
|
||||
/** Splits `sql` into its statements, each checked on its own; empty ones (`;;`, a comment) are dropped. */
|
||||
export function parsePluginSql(sql: string): PluginStatement[] {
|
||||
const statements: PluginStatement[] = [];
|
||||
let current: Token[] = [];
|
||||
const flush = (end: number) => {
|
||||
if (current.length > 0) statements.push(describe(sql.slice(current[0].at, end).trimEnd(), current));
|
||||
current = [];
|
||||
};
|
||||
for (const token of tokenize(sql)) {
|
||||
if (token.kind === 'punct' && token.value === ';') flush(token.at);
|
||||
else current.push(token);
|
||||
}
|
||||
flush(sql.length);
|
||||
return statements;
|
||||
}
|
||||
|
||||
/** The unquoted keyword at `token`, or null for anything else. */
|
||||
function keyword(token: Token | undefined): string | null {
|
||||
return token?.kind === 'word' && !token.quoted ? token.value : null;
|
||||
}
|
||||
|
||||
/** Whether `token` is the punctuation `value`. */
|
||||
function isPunct(token: Token | undefined, value: string): boolean {
|
||||
return token?.kind === 'punct' && token.value === value;
|
||||
}
|
||||
|
||||
/** Reads what a statement's caller needs to know about it, and refuses one this guard does not allow. */
|
||||
function describe(text: string, tokens: Token[]): PluginStatement {
|
||||
const first = tokens[0];
|
||||
const opensWithParen = first.kind === 'punct' && first.value === '(';
|
||||
const verb = opensWithParen ? 'select' : keyword(first);
|
||||
if (verb !== null && TRANSACTION_CONTROL.has(verb)) {
|
||||
throw new PluginSqlRefused(
|
||||
'transaction-control statements are not allowed: each call runs in its own transaction, and tx() makes a batch atomic',
|
||||
);
|
||||
}
|
||||
if (verb === null || !STATEMENTS.has(verb)) {
|
||||
throw new PluginSqlRefused(`a statement may not start with ${describeToken(first)}`);
|
||||
}
|
||||
if (verb === 'create' || verb === 'alter' || verb === 'drop' || verb === 'refresh') checkObject(verb, tokens);
|
||||
const targets = targetsOf(verb, tokens);
|
||||
|
||||
let depth = 0;
|
||||
let main: string | null = verb === 'with' ? null : verb;
|
||||
// Where the statement's own verb stands: its first token, or after a WITH clause the verb at depth 0.
|
||||
let mainAt = verb === 'with' ? -1 : 0;
|
||||
let returning = false;
|
||||
let params = 0;
|
||||
let qualifies = false;
|
||||
for (const [index, token] of tokens.entries()) {
|
||||
if (token.kind === 'param') params++;
|
||||
if (token.kind === 'punct' && token.value === '(') depth++;
|
||||
if (token.kind === 'punct' && token.value === ')') depth--;
|
||||
if (token.kind !== 'word') continue;
|
||||
checkName(token.value);
|
||||
const after = tokens[index + 1];
|
||||
if (after?.kind === 'punct' && after.value === '.') qualifies = true;
|
||||
if (token.quoted) continue;
|
||||
checkKeyword(token.value);
|
||||
if (token.value === 'into') checkInto(tokens, index, mainAt);
|
||||
if (verb === 'alter' && (token.value === 'schema' || token.value === 'owner')) {
|
||||
throw new PluginSqlRefused(`an ALTER may not change the ${token.value}`);
|
||||
}
|
||||
if (depth !== 0) continue;
|
||||
if (main === null && VERBS.has(token.value)) {
|
||||
main = token.value;
|
||||
mainAt = index;
|
||||
}
|
||||
if (token.value === 'returning') returning = true;
|
||||
}
|
||||
|
||||
const reads = main !== null && READ_VERBS.has(main);
|
||||
const writesInside = tokens.some((t) => {
|
||||
const word = keyword(t);
|
||||
return word !== null && ['insert', 'update', 'delete', 'merge'].includes(word);
|
||||
});
|
||||
return {
|
||||
text,
|
||||
tokens,
|
||||
returnsRows: reads || returning,
|
||||
mayWrite: !reads || writesInside,
|
||||
qualifies,
|
||||
params,
|
||||
targets,
|
||||
};
|
||||
}
|
||||
|
||||
/** Refuses a CREATE, ALTER, DROP or REFRESH of anything but the objects a plugin keeps in its schema. */
|
||||
function checkObject(verb: string, tokens: readonly Token[]): void {
|
||||
let at = 1;
|
||||
if (verb === 'create') {
|
||||
if (keyword(tokens[at]) === 'or' && keyword(tokens[at + 1]) === 'replace') at += 2;
|
||||
const scope = keyword(tokens[at]);
|
||||
if (
|
||||
TEMPORARY.has(scope ?? '') ||
|
||||
((scope === 'local' || scope === 'global') && TEMPORARY.has(keyword(tokens[at + 1]) ?? ''))
|
||||
) {
|
||||
throw new PluginSqlRefused(
|
||||
`CREATE ${describeToken(tokens[at])} is not allowed: a temporary object outlives the call on a pooled connection`,
|
||||
);
|
||||
}
|
||||
while (keyword(tokens[at]) === 'unique' || keyword(tokens[at]) === 'unlogged') at++;
|
||||
}
|
||||
const object = keyword(tokens[at]);
|
||||
const allowed = verb === 'refresh' ? object === 'materialized' : object !== null && OBJECTS.has(object);
|
||||
if (!allowed) {
|
||||
throw new PluginSqlRefused(`${verb.toUpperCase()} ${describeToken(tokens[at])} is not allowed`);
|
||||
}
|
||||
// A base type is made of C functions and needs a superuser; a composite, enum or range type says AS.
|
||||
if (verb === 'create' && object === 'type' && isPunct(tokens[at + 2], '(')) {
|
||||
throw new PluginSqlRefused('CREATE TYPE may make a composite, enum or range type (CREATE TYPE x AS ...) only');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Refuses an unquoted keyword that is never safe, at whatever depth of
|
||||
* parentheses it sits.
|
||||
*/
|
||||
function checkKeyword(word: string): void {
|
||||
if (word === 'recursive') throw new PluginSqlRefused('WITH RECURSIVE is not allowed');
|
||||
if (word === 'tablespace') throw new PluginSqlRefused('a tablespace may not be named');
|
||||
}
|
||||
|
||||
/**
|
||||
* Refuses the INTO at `index` unless it follows the verb INSERT or MERGE of
|
||||
* the statement itself (`mainAt`) or of a WITH query's body (`AS (INSERT
|
||||
* INTO ...`). Anywhere else it is `SELECT ... INTO`, which makes a table (a
|
||||
* temporary one with TEMP) past what CREATE is held to, at any depth of
|
||||
* parentheses: `(SELECT ... INTO t)`, `WITH x AS (...) SELECT ... INTO t`,
|
||||
* and `SELECT 1 insert INTO t`, where `insert` is only a column alias.
|
||||
*/
|
||||
function checkInto(tokens: readonly Token[], index: number, mainAt: number): void {
|
||||
const verbAt = index - 1;
|
||||
const verb = keyword(tokens[verbAt]);
|
||||
if (verb !== null && INTO_AFTER.has(verb) && (verbAt === mainAt || opensQueryBody(tokens, verbAt))) return;
|
||||
const next = keyword(tokens[index + 1]);
|
||||
if (next !== null && TEMPORARY.has(next)) {
|
||||
throw new PluginSqlRefused(`SELECT ... INTO ${next.toUpperCase()} is not allowed: no temporary tables`);
|
||||
}
|
||||
throw new PluginSqlRefused('SELECT ... INTO is not allowed; use CREATE TABLE ... AS');
|
||||
}
|
||||
|
||||
/** Whether the token at `index` is the first of a WITH query's body: `AS (`, `AS [NOT] MATERIALIZED (`. */
|
||||
function opensQueryBody(tokens: readonly Token[], index: number): boolean {
|
||||
if (!isPunct(tokens[index - 1], '(')) return false;
|
||||
const before = keyword(tokens[index - 2]);
|
||||
return before === 'as' || (before === 'materialized' && keyword(tokens[index - 3]) !== null);
|
||||
}
|
||||
|
||||
/** A name of up to three parts (`t`, `s.t`, `db.s.t`) at `at` and the index past it; null when none starts there. */
|
||||
function readName(tokens: readonly Token[], at: number): { name: string[]; next: number } | null {
|
||||
const name: string[] = [];
|
||||
let i = at;
|
||||
for (;;) {
|
||||
const token = tokens[i];
|
||||
if (token?.kind !== 'word') return name.length === 0 ? null : { name, next: i };
|
||||
name.push(token.value);
|
||||
if (!isPunct(tokens[i + 1], '.')) return { name, next: i + 1 };
|
||||
if (name.length === 3) throw new PluginSqlRefused('a name may have at most three parts');
|
||||
i += 2;
|
||||
}
|
||||
}
|
||||
|
||||
/** The index past the unquoted keywords `words` at `at`, or `at` when they are not there. */
|
||||
function skip(tokens: readonly Token[], at: number, ...words: string[]): number {
|
||||
return words.every((word, i) => keyword(tokens[at + i]) === word) ? at + words.length : at;
|
||||
}
|
||||
|
||||
/** The comma-separated names starting at `at`, each optionally led by ONLY or followed by `*` (TRUNCATE). */
|
||||
function readNames(tokens: readonly Token[], at: number, what: string): string[][] {
|
||||
const names: string[][] = [];
|
||||
let i = at;
|
||||
for (;;) {
|
||||
const read = readName(tokens, skip(tokens, i, 'only'));
|
||||
if (read === null) throw new PluginSqlRefused(`the object ${what} acts on could not be read`);
|
||||
names.push(read.name);
|
||||
i = read.next;
|
||||
if (isPunct(tokens[i], '*')) i++;
|
||||
if (!isPunct(tokens[i], ',')) return names;
|
||||
i++;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The existing objects a statement changes ({@link PluginTarget}). The one an
|
||||
* ALTER, DROP, REFRESH, TRUNCATE or CREATE INDEX acts on must be readable, or
|
||||
* the statement is refused; the tables a CREATE or ALTER ties to its own are
|
||||
* every name after REFERENCES, INHERITS (, PARTITION OF, ATTACH PARTITION,
|
||||
* DETACH PARTITION and INHERIT, read generously: a word there that is no
|
||||
* table resolves to nothing and changes nothing.
|
||||
*/
|
||||
function targetsOf(verb: string, tokens: readonly Token[]): PluginTarget[] {
|
||||
const targets: PluginTarget[] = [];
|
||||
const add = (kind: PluginTarget['kind'], names: string[][]) => {
|
||||
for (const name of names) targets.push({ kind, name });
|
||||
};
|
||||
const object = keyword(tokens[1]);
|
||||
const kind = object === 'type' ? 'type' : 'relation';
|
||||
if (verb === 'alter') {
|
||||
const at = skip(tokens, object === 'materialized' ? 3 : 2, 'if', 'exists');
|
||||
add(kind, readNames(tokens, at, 'an ALTER').slice(0, 1));
|
||||
} else if (verb === 'drop') {
|
||||
const at = skip(tokens, skip(tokens, object === 'materialized' ? 3 : 2, 'concurrently'), 'if', 'exists');
|
||||
add(kind, readNames(tokens, at, 'a DROP'));
|
||||
} else if (verb === 'refresh') {
|
||||
add('relation', readNames(tokens, skip(tokens, 3, 'concurrently'), 'a REFRESH').slice(0, 1));
|
||||
} else if (verb === 'truncate') {
|
||||
add('relation', readNames(tokens, skip(tokens, 1, 'table'), 'a TRUNCATE'));
|
||||
} else if (verb === 'create' && keyword(tokens[skip(tokens, 1, 'unique')]) === 'index') {
|
||||
const on = tokens.findIndex((t, i) => keyword(t) === 'on' && depthAt(tokens, i) === 0);
|
||||
if (on < 0) throw new PluginSqlRefused('a CREATE INDEX must name its table with ON');
|
||||
add('relation', readNames(tokens, on + 1, 'a CREATE INDEX').slice(0, 1));
|
||||
}
|
||||
if (verb === 'create' || verb === 'alter') add('relation', tiedTables(tokens));
|
||||
return targets;
|
||||
}
|
||||
|
||||
/** The names after REFERENCES, INHERITS (, PARTITION OF, ATTACH/DETACH PARTITION and INHERIT. */
|
||||
function tiedTables(tokens: readonly Token[]): string[][] {
|
||||
const names: string[][] = [];
|
||||
for (const [index, token] of tokens.entries()) {
|
||||
const word = keyword(token);
|
||||
let at = -1;
|
||||
if (word === 'references' || word === 'inherit') at = index + 1;
|
||||
else if (word === 'partition' && keyword(tokens[index + 1]) === 'of') at = index + 2;
|
||||
else if (word === 'partition' && ['attach', 'detach'].includes(keyword(tokens[index - 1]) ?? '')) at = index + 1;
|
||||
else if (word === 'inherits' && isPunct(tokens[index + 1], '(')) {
|
||||
names.push(...readNames(tokens, index + 2, 'INHERITS'));
|
||||
continue;
|
||||
}
|
||||
const read = at < 0 ? null : readName(tokens, at);
|
||||
if (read !== null) names.push(read.name);
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
/** How deep in parentheses the token at `index` sits. */
|
||||
function depthAt(tokens: readonly Token[], index: number): number {
|
||||
let depth = 0;
|
||||
for (const token of tokens.slice(0, index)) {
|
||||
if (token.kind === 'punct' && token.value === '(') depth++;
|
||||
if (token.kind === 'punct' && token.value === ')') depth--;
|
||||
}
|
||||
return depth;
|
||||
}
|
||||
|
||||
/** Refuses a name that reaches past the plugin's schema whatever qualifies it. */
|
||||
function checkName(name: string): void {
|
||||
if (REFUSED_NAMES.has(name) || REFUSED_PREFIXES.some((p) => name.startsWith(p)) || XML_EXPORT.test(name)) {
|
||||
throw new PluginSqlRefused(`"${name}" may not be named in a plugin's SQL`);
|
||||
}
|
||||
}
|
||||
|
||||
/** A token as an error message shows it. */
|
||||
function describeToken(token: Token | undefined): string {
|
||||
if (token === undefined) return 'nothing';
|
||||
if (token.kind === 'word') return token.quoted ? `"${token.value}"` : token.value.toUpperCase();
|
||||
if (token.kind === 'punct') return `"${token.value}"`;
|
||||
return `a ${token.kind}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Refuses a qualified name in `statement` whose qualifier is a schema other
|
||||
* than `ownSchema`: one of `schemas` (every schema of the database), or one
|
||||
* named like a plugin schema even before it exists.
|
||||
*/
|
||||
export function checkQualifiers(statement: PluginStatement, ownSchema: string, schemas: ReadonlySet<string>): void {
|
||||
const { tokens } = statement;
|
||||
for (const [index, token] of tokens.entries()) {
|
||||
const after = tokens[index + 1];
|
||||
if (token.kind !== 'word' || after?.kind !== 'punct' || after.value !== '.') continue;
|
||||
if (token.value === ownSchema) continue;
|
||||
if (schemas.has(token.value) || token.value.startsWith(PLUGIN_SCHEMA_PREFIX) || token.value === 'public') {
|
||||
throw new PluginSqlRefused(`"${token.value}" is another schema; a plugin reaches its own tables only`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Refuses `?` placeholders where bound args were given: Postgres numbers its
|
||||
* placeholders `$1`, `$2`, ..., and reads a `?` as an operator.
|
||||
*/
|
||||
export function checkPlaceholders(statement: PluginStatement, args: readonly unknown[]): void {
|
||||
if (args.length === 0 || statement.params > 0) return;
|
||||
const questionMark = statement.tokens.some((t) => t.kind === 'punct' && t.value === '?');
|
||||
if (questionMark) {
|
||||
throw new PluginSqlRefused('this TREK runs on Postgres, which numbers its placeholders $1, $2, ... instead of ?');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import { nulFreeJson, stripNul, withNulFreeParameters } from '../../nul-free';
|
||||
import { SqliteNullOrderPlatform, withSqliteNullOrder } from './null-order';
|
||||
import { type Configuration, type TransformContext } from '@mikro-orm/core';
|
||||
import { PostgreSqlConnection, PostgreSqlDriver } from '@mikro-orm/postgresql';
|
||||
|
||||
/** `int8` (bigint), a `pg_type.oid`: every integer column and every `count(*)` on Postgres. */
|
||||
const INT8_OID = 20;
|
||||
/** `numeric`: what `sum()` of a bigint and `avg()` answer. */
|
||||
const NUMERIC_OID = 1700;
|
||||
|
||||
/**
|
||||
* Reads a `bigint` as a JavaScript number, the way better-sqlite3 hands
|
||||
* SQLite's 64-bit INTEGER to the services. `pg` returns it as a string to
|
||||
* keep precision past 2^53; no TREK value comes near that (ids, counts,
|
||||
* epoch milliseconds, cents), so one that does is refused rather than
|
||||
* rounded.
|
||||
*/
|
||||
export function parseInt8(text: string): number {
|
||||
const value = Number(text);
|
||||
if (!Number.isSafeInteger(value)) throw new Error(`A bigint of ${text} is beyond what TREK reads exactly (2^53).`);
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a `numeric` as a number, as SQLite answers `sum()` and `avg()`. `NaN`
|
||||
* and the infinities are refused, as is an integral result past 2^53, which is
|
||||
* refused like a bigint; a fraction is a double, the precision SQLite's REAL has.
|
||||
*/
|
||||
export function parseNumeric(text: string): number {
|
||||
const value = Number(text);
|
||||
if (!Number.isFinite(value)) {
|
||||
throw new Error(`A numeric of ${text} is not a finite number, which TREK does not read.`);
|
||||
}
|
||||
if (/^-?\d+$/.test(text) && !Number.isSafeInteger(value)) {
|
||||
throw new Error(`A numeric of ${text} is beyond what TREK reads exactly (2^53).`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* MikroORM's `PostgreSqlConnection`, with the pool's own type parsers replaced
|
||||
* for `int8` and `numeric`. MikroORM keeps dates as text, so only these two
|
||||
* change. `mapOptions` builds the `pg` pool options, whose `types` is the
|
||||
* `pg` TypeOverrides, the object that holds the parsers.
|
||||
*/
|
||||
class NumberTypesConnection extends PostgreSqlConnection {
|
||||
override mapOptions(overrides: Parameters<PostgreSqlConnection['mapOptions']>[0]) {
|
||||
const options = super.mapOptions(overrides);
|
||||
const types = options.types as { setTypeParser(oid: number, parse: (text: string) => unknown): void };
|
||||
types.setTypeParser(INT8_OID, parseInt8);
|
||||
types.setTypeParser(NUMERIC_OID, parseNumeric);
|
||||
return options;
|
||||
}
|
||||
|
||||
/**
|
||||
* The pool's Kysely dialect, compiling every ORDER BY with SQLite's NULL
|
||||
* position (`null-order.ts`) and sending every parameter without NUL
|
||||
* (`nul-free.ts`).
|
||||
*/
|
||||
override createKyselyDialect(overrides: Parameters<PostgreSqlConnection['createKyselyDialect']>[0]) {
|
||||
return withNulFreeParameters(withSqliteNullOrder(super.createKyselyDialect(overrides))) as ReturnType<
|
||||
PostgreSqlConnection['createKyselyDialect']
|
||||
>;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The Postgres platform TREK runs on: ORDER BY with SQLite's NULL position
|
||||
* (`null-order.ts`), and no NUL in a string it inlines into a statement or a
|
||||
* JSON value it serializes, which Postgres text cannot hold (`nul-free.ts`).
|
||||
*/
|
||||
export class TrekPostgreSqlPlatform extends SqliteNullOrderPlatform {
|
||||
override escape(value: unknown): string {
|
||||
return super.escape(typeof value === 'string' ? stripNul(value) : value);
|
||||
}
|
||||
|
||||
override convertJsonToDatabaseValue(value: unknown, context?: TransformContext): unknown {
|
||||
return super.convertJsonToDatabaseValue(nulFreeJson(value), context);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* MikroORM's Postgres driver on a connection that reads `bigint` and `numeric`
|
||||
* as numbers, and on the platform above with a query compiler that sorts NULLs
|
||||
* where SQLite does (`null-order.ts`). The parsers belong to this pool only:
|
||||
* nothing global in `pg` changes.
|
||||
*/
|
||||
export class TrekPostgreSqlDriver extends PostgreSqlDriver {
|
||||
constructor(config: Configuration) {
|
||||
super(config);
|
||||
// PostgreSqlDriver's constructor hardcodes its connection and platform
|
||||
// classes, as SqliteDriver's does (`db/orm-driver.ts`). It keeps both in
|
||||
// fields, which are not public, so they are replaced here, before anything
|
||||
// connects and before the configuration reads the platform.
|
||||
(this as unknown as { connection: PostgreSqlConnection }).connection = new NumberTypesConnection(config);
|
||||
(this as unknown as { platform: TrekPostgreSqlPlatform }).platform = new TrekPostgreSqlPlatform();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
import type { DbEngineSettings } from '../../../app-config/db-settings';
|
||||
import { NO_SAFETY_NET } from '../../legacy-baseline';
|
||||
import { finishSchemaBootstrap, type AnyOrm } from '../../orm';
|
||||
import type { DatabaseEngine } from '../engine';
|
||||
import { redactUrl } from '../redact-url';
|
||||
import { TrekPostgreSqlDriver } from './postgres-driver';
|
||||
import { bootstrapPostgresSchema, defaultPostgresBootstrapDeps, type PostgresBootstrapDeps } from './schema-bootstrap';
|
||||
import { putTempSchemaLast } from './session-search-path';
|
||||
import { sslOptionFor } from './ssl';
|
||||
import type { EntityManager } from '@mikro-orm/core';
|
||||
|
||||
import type { DatabaseConnection } from 'kysely';
|
||||
|
||||
/** What `TREK_DB_URL` and `TREK_DB_POOL_MAX` resolve to, when they name a Postgres database. */
|
||||
type PostgresSettings = Extract<DbEngineSettings, { engine: 'postgres' }>;
|
||||
|
||||
/** The advisory lock key every write transaction takes: "TREK" in ASCII. */
|
||||
const TREK_WRITE_LOCK = 0x5452454b;
|
||||
|
||||
/**
|
||||
* The Postgres engine: MikroORM's own `pg` driver on `TREK_DB_URL`, with a
|
||||
* pool of at most `TREK_DB_POOL_MAX` connections that keeps none open while
|
||||
* idle. The pool belongs to the ORM, which the Nest container closes; the
|
||||
* schema comes from the baseline plus the migrations after it
|
||||
* (`schema-bootstrap.ts`).
|
||||
*/
|
||||
export class PostgresEngine implements DatabaseEngine {
|
||||
readonly id = 'postgres';
|
||||
|
||||
constructor(
|
||||
private readonly settings: PostgresSettings,
|
||||
private readonly bootstrapDeps: (url: string) => PostgresBootstrapDeps = defaultPostgresBootstrapDeps,
|
||||
) {}
|
||||
|
||||
private onReopened: (() => Promise<void>) | null = null;
|
||||
|
||||
/**
|
||||
* Nothing of its own to open: the ORM connects the pool. Keeps what a reopen
|
||||
* runs. A reopen replaces the database's contents, which the pool's own
|
||||
* connections keep reaching, so the ORM is not pointed at anything new and
|
||||
* the pool is never closed (ending a pool waits for every connection it has
|
||||
* lent out, and one lent to a job during the restore would never come back).
|
||||
*/
|
||||
open(_orm: AnyOrm, onReopened: () => Promise<void>): void {
|
||||
this.onReopened = onReopened;
|
||||
}
|
||||
|
||||
close(): void {
|
||||
// Nothing of its own to close: the pool goes with the ORM.
|
||||
}
|
||||
|
||||
/**
|
||||
* After `pg_restore` replaced the database's contents: the restored
|
||||
* database is migrated forward on the same pool (`onReopened`, which
|
||||
* `DatabaseLifecycle` hands to `open`).
|
||||
*/
|
||||
async reopen(): Promise<void> {
|
||||
if (!this.onReopened) throw new Error('The Postgres engine was reopened before it was opened.');
|
||||
await this.onReopened();
|
||||
}
|
||||
|
||||
/**
|
||||
* `pg_advisory_xact_lock` on one key for the whole database: held until the
|
||||
* transaction commits or rolls back, taken again by a savepoint in the same
|
||||
* session without waiting, and shared by every process on the database.
|
||||
*/
|
||||
async serializeWrites(em: EntityManager): Promise<void> {
|
||||
await em
|
||||
.getConnection()
|
||||
.execute('select pg_advisory_xact_lock(?)', [TREK_WRITE_LOCK], 'run', em.getTransactionContext());
|
||||
}
|
||||
|
||||
/** `snapshot: false` (a restore, whose archive is the copy) migrates without a pg_dump first. */
|
||||
async schemaBootstrap(orm: AnyOrm, options: { snapshot: boolean }): Promise<void> {
|
||||
const deps = this.bootstrapDeps(this.settings.url);
|
||||
await bootstrapPostgresSchema(orm, options.snapshot ? deps : { ...deps, safetyNet: NO_SAFETY_NET });
|
||||
await finishSchemaBootstrap(orm);
|
||||
}
|
||||
|
||||
describe(): string {
|
||||
return `Postgres ${redactUrl(this.settings.url)}`;
|
||||
}
|
||||
|
||||
/** Every new pool connection first puts `pg_temp` last on its `search_path` (`session-search-path.ts`). */
|
||||
ormOptions() {
|
||||
const ssl = sslOptionFor(this.settings.url);
|
||||
return {
|
||||
driver: TrekPostgreSqlDriver,
|
||||
clientUrl: this.settings.url,
|
||||
pool: { min: 0, max: this.settings.poolMax },
|
||||
driverOptions: ssl === undefined ? {} : { ssl },
|
||||
onCreateConnection: (connection: unknown) => putTempSchemaLast(connection as DatabaseConnection),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
/**
|
||||
* The SQLite schema's triggers as Postgres writes them. The entities describe
|
||||
* tables only, so the baseline (`scripts/generate-pg-baseline.ts`) adds these
|
||||
* after the tables, and `check:pg-baseline` fails while a trigger in the
|
||||
* migrated SQLite schema has no entry here. Each entry is the trigger's
|
||||
* function and the trigger that runs it, under the SQLite trigger's name.
|
||||
*/
|
||||
export const POSTGRES_TRIGGERS: Readonly<Record<string, readonly string[]>> = {
|
||||
// A deleted stay releases the day stops it claimed (no foreign key holds the link).
|
||||
trg_release_stop_on_stay_delete: [
|
||||
`CREATE FUNCTION trg_release_stop_on_stay_delete() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
UPDATE day_assignments SET accommodation_id = NULL WHERE accommodation_id = OLD.id;
|
||||
RETURN OLD;
|
||||
END
|
||||
$$`,
|
||||
'CREATE TRIGGER trg_release_stop_on_stay_delete AFTER DELETE ON day_accommodations ' +
|
||||
'FOR EACH ROW EXECUTE FUNCTION trg_release_stop_on_stay_delete()',
|
||||
],
|
||||
// A place that moved or was renamed drops the region it was resolved to (#2527).
|
||||
trg_place_regions_follow_place: [
|
||||
`CREATE FUNCTION trg_place_regions_follow_place() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
DELETE FROM place_regions WHERE place_id = NEW.id;
|
||||
RETURN NEW;
|
||||
END
|
||||
$$`,
|
||||
'CREATE TRIGGER trg_place_regions_follow_place AFTER UPDATE OF lat, lng, address ON places FOR EACH ROW ' +
|
||||
'WHEN (OLD.lat IS DISTINCT FROM NEW.lat OR OLD.lng IS DISTINCT FROM NEW.lng OR OLD.address IS DISTINCT FROM NEW.address) ' +
|
||||
'EXECUTE FUNCTION trg_place_regions_follow_place()',
|
||||
],
|
||||
};
|
||||
@@ -0,0 +1,51 @@
|
||||
import { run } from './pg-process';
|
||||
|
||||
/**
|
||||
* The client-tool versions a restore accepts (CVE-2025-8714). A script from a
|
||||
* dump an admin uploaded is run by psql, which would also run a psql
|
||||
* meta-command (`\!` runs a shell command) smuggled into an object name. A
|
||||
* fixed pg_restore opens the script with `\restrict <random key>`, and a fixed
|
||||
* psql then refuses every meta-command until the matching `\unrestrict`.
|
||||
*
|
||||
* RESTRICT_SINCE holds, per major, the first minor that carries the fix, for
|
||||
* every major TREK supports (14 to 18; 18 has it from 18.0). Every major after
|
||||
* the last one listed has it from its first release.
|
||||
*/
|
||||
const RESTRICT_SINCE: Readonly<Partial<Record<number, number>>> = { 14: 19, 15: 14, 16: 10, 17: 6, 18: 0 };
|
||||
const LAST_MAJOR_WITHOUT_IT = Math.max(...Object.keys(RESTRICT_SINCE).map(Number));
|
||||
|
||||
/** Whether `version` (`pg_restore (PostgreSQL) 17.11 (Debian …)`) carries the fix. */
|
||||
export function hasRestrictFix(version: string): boolean {
|
||||
const match = /\(PostgreSQL\) (\d+)\.(\d+)/.exec(version);
|
||||
if (!match) return false;
|
||||
const major = Number(match[1]);
|
||||
const minor = Number(match[2]);
|
||||
if (major > LAST_MAJOR_WITHOUT_IT) return true;
|
||||
const firstFixedMinor = RESTRICT_SINCE[major];
|
||||
return firstFixedMinor !== undefined && minor >= firstFixedMinor;
|
||||
}
|
||||
|
||||
/** The minimum versions as the error names them, newest major first: "18.0, 17.6, 16.10, 15.14 or 14.19". */
|
||||
function minimumVersionsText(): string {
|
||||
const floors = Object.keys(RESTRICT_SINCE)
|
||||
.map(Number)
|
||||
.sort((a, b) => b - a)
|
||||
.map((major) => `${major}.${RESTRICT_SINCE[major]}`);
|
||||
const last = floors.pop() ?? '';
|
||||
return floors.length > 0 ? `${floors.join(', ')} or ${last}` : last;
|
||||
}
|
||||
|
||||
/**
|
||||
* Refuses the restore when pg_restore or psql predates the fix. The tools'
|
||||
* own versions are checked, not the script, whose text the dump controls.
|
||||
*/
|
||||
export async function refuseToolsWithoutRestrict(binDir: string | undefined): Promise<void> {
|
||||
const tools = ['pg_restore', 'psql'] as const;
|
||||
const versions = await Promise.all(tools.map((tool) => run(tool, binDir, ['--version'], {})));
|
||||
const stale = tools.findIndex((_, i) => !hasRestrictFix(versions[i]));
|
||||
if (stale < 0) return;
|
||||
throw new Error(
|
||||
`${tools[stale]} is too old to restore safely (${versions[stale].trim()}): it must be at least ${minimumVersionsText()} ` +
|
||||
'(the Docker image has 18). Upgrade the PostgreSQL client tools or point TREK_DB_PG_BIN_DIR at newer ones.',
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
/**
|
||||
* How the entities' schema is written in Postgres: the one definition the
|
||||
* Postgres baseline (`scripts/generate-pg-baseline.ts`), the schema parity
|
||||
* check and the probe (`scripts/pg-probe.ts`) share.
|
||||
*
|
||||
* The entities are generated from the migrated SQLite schema and a parity
|
||||
* test pins them to it (`npm run check:entities`), so they are the one
|
||||
* description of the tables both engines can read. MikroORM's schema
|
||||
* generator turns them into Postgres DDL after the adjustments below, which
|
||||
* keep the storage model the services and the dialect helpers are written
|
||||
* for (server/CLAUDE.md, "Storage model"):
|
||||
*
|
||||
* - timestamps stay TEXT;
|
||||
* - an INTEGER column is `bigint`: SQLite's INTEGER holds 64 bits, so a
|
||||
* column written with epoch milliseconds or a byte count past 2 GB would
|
||||
* overflow Postgres's 32-bit `integer` (the engine's driver reads
|
||||
* `bigint` back as a number, `postgres-driver.ts`);
|
||||
* - a SQLite-only default (`datetime('now')`, `strftime('%s','now')`,
|
||||
* `CURRENT_TIMESTAMP` in a TEXT column) gets its Postgres equivalent, and
|
||||
* a column declared `COLLATE NOCASE` uses the `nocase` collation
|
||||
* `collateNoCase()` names on Postgres.
|
||||
*
|
||||
* The baseline keeps the foreign keys; the probe leaves them out, so a
|
||||
* statement it sends is never refused only because the sample row it writes
|
||||
* points at nothing. The triggers the SQLite schema has are in
|
||||
* `postgres-triggers.ts`.
|
||||
*/
|
||||
import { pgTimestampText, PG_UTC_NOW } from '../../dialect/platform';
|
||||
import { DbTimestampType } from '../../types';
|
||||
|
||||
/** SQLite's timestamp text on Postgres, for a column default. */
|
||||
export const PG_NOW_TEXT_DEFAULT = pgTimestampText(PG_UTC_NOW);
|
||||
|
||||
/** The case-insensitive collation `collateNoCase()` names on Postgres. */
|
||||
export const NOCASE_COLLATION_SQL =
|
||||
"CREATE COLLATION IF NOT EXISTS nocase (provider = icu, locale = 'und-u-ks-level2', deterministic = false)";
|
||||
|
||||
/** The Postgres spelling of a column default the entities carry in SQLite's. */
|
||||
export function portableDefault(raw: string): string {
|
||||
const text = raw
|
||||
.trim()
|
||||
.replace(/^\((.*)\)$/s, '$1')
|
||||
.trim();
|
||||
if (/^current_timestamp$/i.test(text) || /^datetime\(\s*'now'\s*\)$/i.test(text)) return PG_NOW_TEXT_DEFAULT;
|
||||
if (/^strftime\(\s*'%s'\s*,\s*'now'\s*\)$/i.test(text))
|
||||
return 'CAST(EXTRACT(EPOCH FROM CURRENT_TIMESTAMP) AS bigint)';
|
||||
return raw;
|
||||
}
|
||||
|
||||
/** A column type SQLite stores as its 64-bit INTEGER. */
|
||||
const INTEGER_TYPE = /^(integer|int)$/i;
|
||||
|
||||
/**
|
||||
* The subset of MikroORM's property metadata the adjustments read and write.
|
||||
* An entity's `props` satisfy it as they are, so no cast is needed.
|
||||
*/
|
||||
export interface ColumnMeta {
|
||||
name: string;
|
||||
defaultRaw?: string;
|
||||
collation?: string;
|
||||
columnTypes?: string[];
|
||||
customType?: unknown;
|
||||
}
|
||||
|
||||
/** A timestamp column becomes text. Returns whether it changed. */
|
||||
function timestampAsText(column: ColumnMeta): boolean {
|
||||
if (!(column.customType instanceof DbTimestampType) || !column.columnTypes) return false;
|
||||
column.columnTypes = column.columnTypes.map(() => 'text');
|
||||
return true;
|
||||
}
|
||||
|
||||
/** An integer column becomes bigint. Returns whether it changed. */
|
||||
function integerAsBigint(column: ColumnMeta): boolean {
|
||||
if (!column.columnTypes?.some((type) => INTEGER_TYPE.test(type))) return false;
|
||||
column.columnTypes = column.columnTypes.map((type) => (INTEGER_TYPE.test(type) ? 'bigint' : type));
|
||||
return true;
|
||||
}
|
||||
|
||||
/** A SQLite-only default gets its Postgres spelling. Returns whether it changed. */
|
||||
function defaultAsPostgres(column: ColumnMeta): boolean {
|
||||
if (typeof column.defaultRaw !== 'string') return false;
|
||||
const next = portableDefault(column.defaultRaw);
|
||||
if (next === column.defaultRaw) return false;
|
||||
column.defaultRaw = next;
|
||||
return true;
|
||||
}
|
||||
|
||||
/** A NOCASE column uses the `nocase` collation. Returns whether it changed. */
|
||||
function nocaseAsCollation(column: ColumnMeta): boolean {
|
||||
if (column.collation?.toUpperCase() !== 'NOCASE') return false;
|
||||
column.collation = 'nocase';
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies the adjustments above to an entity's properties, in place, and
|
||||
* returns the names of the properties it changed, for the log. A timestamp
|
||||
* column is text, so the integer adjustment never sees it.
|
||||
*/
|
||||
export function applyPostgresColumnAdjustments(properties: readonly ColumnMeta[]): string[] {
|
||||
const changed: string[] = [];
|
||||
for (const property of properties) {
|
||||
const typeChanged = timestampAsText(property) || integerAsBigint(property);
|
||||
const defaultChanged = defaultAsPostgres(property);
|
||||
const collationChanged = nocaseAsCollation(property);
|
||||
if (typeChanged || defaultChanged || collationChanged) changed.push(property.name);
|
||||
}
|
||||
return changed;
|
||||
}
|
||||
@@ -0,0 +1,319 @@
|
||||
import { readEnv, type AppEnv } from '../../../app-config';
|
||||
import { resolveDataPaths } from '../../../app-config/data-paths';
|
||||
import { CURRENT_SCHEMA_TABLES_SQL } from '../../dialect/catalog';
|
||||
import { knownMigrationNames } from '../../known-migrations';
|
||||
import { migrationLabel, REFUSAL, refuseNewerDatabase, type MigrationSafetyNet } from '../../legacy-baseline';
|
||||
import type { AnyOrm } from '../../orm';
|
||||
import { listSnapshots, PREFIX, pruneSnapshots, stamp } from '../../pre-migrate-snapshot';
|
||||
import { sqliteInstallHoldsAccounts } from '../sqlite/sqlite-source';
|
||||
import { readPostgresBaseline, type PostgresBaseline } from './baseline';
|
||||
import { pgDump } from './pg-tools';
|
||||
import { PRIVILEGED_ROLE_SQL, PRIVILEGED_ROLE_WARNING, refuseUnsupportedServer, serverMajor } from './server-checks';
|
||||
import type { Connection } from '@mikro-orm/core';
|
||||
import type { Migrator } from '@mikro-orm/migrations';
|
||||
import { Logger } from '@nestjs/common';
|
||||
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
const logger = new Logger('DB');
|
||||
|
||||
/** A Postgres copy is a pg_dump custom-format archive. */
|
||||
const DUMP_EXTENSION = '.pgdump';
|
||||
|
||||
/** What a Postgres bootstrap reads, passed in so a test can supply its own. */
|
||||
export interface PostgresBootstrapDeps {
|
||||
baseline: () => PostgresBaseline;
|
||||
known: Set<string>;
|
||||
safetyNet: MigrationSafetyNet;
|
||||
/**
|
||||
* The SQLite install a boot on a database without TREK data would leave
|
||||
* behind: the path of a SQLite file in the data directory that holds
|
||||
* accounts, or null when there is none (or the operator said to start
|
||||
* anyway). Read only when the database holds no TREK data, so a boot on a
|
||||
* database in use never opens the file.
|
||||
*/
|
||||
sqliteLeftBehind: () => string | null;
|
||||
}
|
||||
|
||||
/** The command that moves a SQLite install into Postgres, as the refusal names it. */
|
||||
const MOVE_COMMAND_HINT =
|
||||
'docker compose run --rm --user node -w /app/server app node --require tsconfig-paths/register ' +
|
||||
'dist/move-to-postgres.js (npm run db:move-to-postgres in server/ outside Docker)';
|
||||
|
||||
/**
|
||||
* The refusal of a boot that would come up empty on Postgres while `file`
|
||||
* holds the install's data.
|
||||
*/
|
||||
function leftBehindRefusal(file: string): string {
|
||||
return (
|
||||
`${REFUSAL} TREK_DB_URL points at a Postgres database that holds no TREK data, while ${file} holds an ` +
|
||||
'existing SQLite install with accounts. Starting would bring up a new, empty TREK beside it. To move that ' +
|
||||
`install to Postgres, stop TREK and run the move command: ${MOVE_COMMAND_HINT}. The wiki page ` +
|
||||
'Database-Postgres ("Moving an existing install to Postgres") has the steps. To start on the empty ' +
|
||||
'database on purpose, set TREK_DB_IGNORE_SQLITE_FILE=true; to keep running on SQLite, unset TREK_DB_URL.'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the database holds an account. A database TREK created always does
|
||||
* once its first boot finished; one without is what a move that stopped part
|
||||
* of the way, or a first boot that died before seeding, leaves.
|
||||
*/
|
||||
async function holdsAccounts(connection: Connection, tables: readonly string[]): Promise<boolean> {
|
||||
if (!tables.includes('users')) return false;
|
||||
const rows: unknown[] = await connection.execute('select 1 as present from users limit 1');
|
||||
return rows.length > 0;
|
||||
}
|
||||
|
||||
/** Refuses the boot when `sqliteLeftBehind` names a SQLite install this boot would leave behind. */
|
||||
function refuseLeavingSqliteBehind(deps: PostgresBootstrapDeps): void {
|
||||
const file = deps.sqliteLeftBehind();
|
||||
if (file !== null) throw new Error(leftBehindRefusal(file));
|
||||
}
|
||||
|
||||
/**
|
||||
* The tables in the current schema. A database with no TREK migration history
|
||||
* must hold none: TREK creates its schema in an empty database and never
|
||||
* adopts tables something else made. Read before anything is written, so a
|
||||
* refused database is left exactly as it was.
|
||||
*/
|
||||
async function currentTables(connection: Connection): Promise<string[]> {
|
||||
const rows: Array<{ table_name: string }> = await connection.execute(CURRENT_SCHEMA_TABLES_SQL);
|
||||
return rows.map((row) => row.table_name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the schema in an empty Postgres database: the migration history's
|
||||
* table, the baseline's statements and the record of every migration it
|
||||
* stands for, in one transaction (DDL is transactional on Postgres, so the
|
||||
* database ends with all of it or none, not even an empty history table). A
|
||||
* database holding tables beside no TREK history is refused before anything is
|
||||
* written.
|
||||
*/
|
||||
async function createFromBaseline(
|
||||
connection: Connection,
|
||||
storage: ReturnType<Migrator['getStorage']>,
|
||||
tables: readonly string[],
|
||||
historyTable: string,
|
||||
baseline: () => PostgresBaseline,
|
||||
): Promise<void> {
|
||||
const foreign = tables.filter((table) => table !== historyTable);
|
||||
if (foreign.length > 0) {
|
||||
throw new Error(
|
||||
`${REFUSAL} the database holds ${foreign.length} table(s) (${foreign.slice(0, 5).join(', ')}) but no TREK ` +
|
||||
'migration history. Point TREK_DB_URL at an empty database.',
|
||||
);
|
||||
}
|
||||
const schema = baseline();
|
||||
logger.log(`Creating the schema in an empty Postgres database (through ${migrationLabel(schema.through)})`);
|
||||
await connection.transactional(async (trx) => {
|
||||
// The history table is created inside the transaction too: MikroORM
|
||||
// creates it on the storage's master transaction, and without one it would
|
||||
// commit on its own, so a baseline that fails would leave it behind and a
|
||||
// later RESTORE_FROM_BACKUP would take the database for one in use.
|
||||
storage.setMasterMigration(trx);
|
||||
try {
|
||||
await storage.ensureTable();
|
||||
await connection.execute(schema.statements.join(';\n'), [], 'run', trx);
|
||||
await Promise.all(schema.migrations.map((name) => storage.logMigration({ name }, trx)));
|
||||
} finally {
|
||||
storage.unsetMasterMigration();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Refuses a database whose recorded history names a migration this build does
|
||||
* not know: a newer TREK migrated it. The refusal names the copy taken before
|
||||
* that migration, when there is one.
|
||||
*/
|
||||
async function refuseNewerHistory(executed: string[], deps: PostgresBootstrapDeps): Promise<void> {
|
||||
const thisRelease = migrationLabel([...deps.known].sort().at(-1) ?? '');
|
||||
refuseNewerDatabase(executed, deps.known, await deps.safetyNet.restoreHint(thisRelease));
|
||||
}
|
||||
|
||||
/** The migration history's table, without a schema. */
|
||||
const HISTORY_TABLE = 'mikro_orm_migrations';
|
||||
|
||||
/** What the boot reads about the server before it writes anything. */
|
||||
interface ServerFacts {
|
||||
schema: string | null;
|
||||
version: string;
|
||||
privileged: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Refuses a server version TREK does not support, warns about a role that
|
||||
* could reach the database host (a restore refuses it), and points MikroORM's
|
||||
* migration history at the current schema, where TREK's tables live.
|
||||
*
|
||||
* The history table is created without a schema, so it lands in the current
|
||||
* schema beside the tables, but MikroORM looks for it in `public` unless told
|
||||
* otherwise. On a role whose search_path resolves to another schema (a role
|
||||
* `trek` with a schema `trek`, which the default `"$user", public` picks) it
|
||||
* would find none there on the second boot and try to create it again. The
|
||||
* name is qualified here, before the migrator reads it; the migrator reads
|
||||
* the option on every use, so a restore's re-bootstrap sets it again alike.
|
||||
* Returns the table's name without the schema.
|
||||
*/
|
||||
async function checkServerAndPlaceHistory(orm: AnyOrm, connection: Connection): Promise<string> {
|
||||
const [facts] = await connection.execute<ServerFacts[]>(
|
||||
"select current_schema() as schema, current_setting('server_version_num') as version, " +
|
||||
`(${PRIVILEGED_ROLE_SQL}) as privileged`,
|
||||
);
|
||||
refuseUnsupportedServer(serverMajor(facts?.version));
|
||||
if (facts?.privileged) logger.warn(PRIVILEGED_ROLE_WARNING);
|
||||
const schema = facts?.schema;
|
||||
if (!schema || schema.includes('.')) {
|
||||
const why = schema ? `the current schema "${schema}", whose name holds a dot` : 'no current schema';
|
||||
throw new Error(
|
||||
`${REFUSAL} the role in TREK_DB_URL has ${why}. Set its search_path to a schema TREK may create its tables in.`,
|
||||
);
|
||||
}
|
||||
const migrations = orm.config.get('migrations');
|
||||
migrations.tableName = `${schema}.${HISTORY_TABLE}`;
|
||||
return HISTORY_TABLE;
|
||||
}
|
||||
|
||||
/**
|
||||
* Brings a Postgres database to the current schema: inspect what it holds,
|
||||
* then create the schema or verify the history it has, then migrate.
|
||||
*
|
||||
* - No migration recorded and no table: the baseline is created
|
||||
* (`createFromBaseline`).
|
||||
* - No migration recorded but tables present: refused, naming a few of them.
|
||||
* - Migrations recorded: refused when one is unknown to this build, else the
|
||||
* pending migrations run, after the safety net. A database the baseline just
|
||||
* created runs the migrations after the baseline's cut without it: there is
|
||||
* nothing yet to lose.
|
||||
*/
|
||||
export async function bootstrapPostgresSchema(orm: AnyOrm, deps: PostgresBootstrapDeps): Promise<void> {
|
||||
const migrator = orm.config.getExtension('@mikro-orm/migrator') as Migrator;
|
||||
const connection = orm.em.getConnection();
|
||||
const historyTable = await checkServerAndPlaceHistory(orm, connection);
|
||||
|
||||
const tables = await currentTables(connection);
|
||||
const executed = tables.includes(historyTable) ? (await migrator.getExecuted()).map((row) => row.name) : [];
|
||||
|
||||
if (executed.length === 0) {
|
||||
// An empty database (a database holding other tables is refused below, with its own message).
|
||||
if (tables.every((table) => table === historyTable)) refuseLeavingSqliteBehind(deps);
|
||||
await createFromBaseline(connection, migrator.getStorage(), tables, historyTable, deps.baseline);
|
||||
} else {
|
||||
await refuseNewerHistory(executed, deps);
|
||||
// A schema without a single account holds no TREK data either; only then is the SQLite file looked at.
|
||||
if (!(await holdsAccounts(connection, tables))) refuseLeavingSqliteBehind(deps);
|
||||
}
|
||||
|
||||
const pending = await migrator.getPending();
|
||||
if (pending.length === 0) return;
|
||||
// Only a database with history has a last migration to label its copy by; a
|
||||
// database the baseline just created has nothing yet to lose.
|
||||
const latest = [...executed].sort().at(-1);
|
||||
if (latest !== undefined) await deps.safetyNet.beforeMigrate(migrationLabel(latest));
|
||||
logger.log(`Applying ${pending.length} pending migration(s)`);
|
||||
await migrator.up();
|
||||
}
|
||||
|
||||
/** Dumps a killed boot left half-written: never a copy, only disk taken. */
|
||||
function removeOrphanedPartials(dir: string): void {
|
||||
for (const file of fs.readdirSync(dir)) {
|
||||
if (file.startsWith(PREFIX) && file.endsWith(`${DUMP_EXTENSION}.partial`)) {
|
||||
fs.rmSync(path.join(dir, file), { force: true });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The Postgres safety net before pending migrations, as the SQLite file's
|
||||
* (`db/pre-migrate-snapshot.ts`): a `pg_dump` of the database to
|
||||
* `<data>/pre-migrate-<schema>-<time>.pgdump`, the newest
|
||||
* `TREK_DB_PRE_MIGRATE_SNAPSHOT_KEEP` kept. A copy that cannot be written
|
||||
* (pg_dump missing, the data dir full) refuses the boot before anything is
|
||||
* migrated, unless `TREK_DB_PRE_MIGRATE_SNAPSHOT=false`. Off under
|
||||
* NODE_ENV=test unless a suite asks for it.
|
||||
*/
|
||||
export function postgresSafetyNet(
|
||||
url: string,
|
||||
env: () => AppEnv = readEnv,
|
||||
now: () => Date = () => new Date(),
|
||||
dataDir: () => string = () => resolveDataPaths(env()).dataDir,
|
||||
): MigrationSafetyNet {
|
||||
return {
|
||||
async beforeMigrate(from) {
|
||||
const { db, app } = env();
|
||||
if (db.preMigrateSnapshot === undefined && app.isTest) return;
|
||||
if (db.preMigrateSnapshot === false) {
|
||||
logger.warn('TREK_DB_PRE_MIGRATE_SNAPSHOT is off: migrating the Postgres database without a copy');
|
||||
return;
|
||||
}
|
||||
const target = path.join(dataDir(), `${PREFIX}${from ?? 'unversioned'}-${stamp(now())}${DUMP_EXTENSION}`);
|
||||
try {
|
||||
fs.mkdirSync(dataDir(), { recursive: true });
|
||||
removeOrphanedPartials(dataDir());
|
||||
await pgDump(url, target, db.pgBinDir);
|
||||
} catch (err) {
|
||||
throw new Error(
|
||||
`${REFUSAL} could not write a copy of the database to ${target} before migrating it ` +
|
||||
`(${err instanceof Error ? err.message : String(err)}). Nothing was migrated. Fix that, ` +
|
||||
'or set TREK_DB_PRE_MIGRATE_SNAPSHOT=false to migrate without a copy.',
|
||||
{ cause: err },
|
||||
);
|
||||
}
|
||||
logger.log(`Copy of the database before migrating: ${target}`);
|
||||
pruneSnapshots(dataDir(), db.preMigrateSnapshotKeep, DUMP_EXTENSION);
|
||||
},
|
||||
|
||||
async restoreHint(thisRelease) {
|
||||
const snapshots = listSnapshots(dataDir(), DUMP_EXTENSION);
|
||||
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 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) {
|
||||
return `Copies taken before earlier migrations are in ${dataDir()} (${PREFIX}*${DUMP_EXTENSION}), none of them from this release.`;
|
||||
}
|
||||
return null;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The SQLite install a Postgres boot would leave behind (`PostgresBootstrapDeps.sqliteLeftBehind`):
|
||||
* the SQLite file the data directory resolves to (`data/travel.db`), when it
|
||||
* holds accounts. A file that cannot be read counts as holding them, so the
|
||||
* check fails closed. `TREK_DB_IGNORE_SQLITE_FILE=true` lets the boot through
|
||||
* with a warning. Off under NODE_ENV=test, where the data directory is the
|
||||
* developer's own.
|
||||
*/
|
||||
export function sqliteLeftBehindCheck(
|
||||
env: () => AppEnv = readEnv,
|
||||
holdsAccounts: (file: string) => boolean = sqliteInstallHoldsAccounts,
|
||||
): () => string | null {
|
||||
return () => {
|
||||
const current = env();
|
||||
if (current.app.isTest) return null;
|
||||
const file = resolveDataPaths(current).dbFile;
|
||||
if (!holdsAccounts(file)) return null;
|
||||
if (current.db.ignoreSqliteFile) {
|
||||
logger.warn(`TREK_DB_IGNORE_SQLITE_FILE is set: starting on Postgres beside the SQLite install in ${file}`);
|
||||
return null;
|
||||
}
|
||||
return file;
|
||||
};
|
||||
}
|
||||
|
||||
/** What a production boot passes: the committed baseline, the migrations on disk, the safety net and the check above. */
|
||||
export function defaultPostgresBootstrapDeps(url: string): PostgresBootstrapDeps {
|
||||
return {
|
||||
baseline: readPostgresBaseline,
|
||||
known: knownMigrationNames(),
|
||||
safetyNet: postgresSafetyNet(url),
|
||||
sqliteLeftBehind: sqliteLeftBehindCheck(),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
import { REFUSAL } from '../../legacy-baseline';
|
||||
|
||||
/**
|
||||
* What TREK checks about the Postgres server and its own role: the server
|
||||
* versions it supports, and whether the role could reach the database host.
|
||||
* Read at boot (`schema-bootstrap.ts`) and before a dump or a restore
|
||||
* (`pg-tools.ts`).
|
||||
*/
|
||||
|
||||
/** The PostgreSQL majors TREK supports and CI runs: the oldest and the newest. */
|
||||
const SUPPORTED_SERVER_MAJORS = { oldest: 14, newest: 18 } as const;
|
||||
|
||||
/**
|
||||
* The `pg_catalog` functions that read, list or write files on the database
|
||||
* server, or move a large object to or from one. PostgreSQL revokes EXECUTE on
|
||||
* them from PUBLIC (since 11) instead of checking for a superuser, so a grant
|
||||
* of one hands that reach to an ordinary role. The `pg_file_*` ones are
|
||||
* adminpack's, which installs into `pg_catalog` where it exists at all. The
|
||||
* `pg_ls_*dir` functions `pg_monitor` holds only list fixed directories and
|
||||
* are not counted.
|
||||
*/
|
||||
const SERVER_FILE_FUNCTIONS = [
|
||||
'lo_import',
|
||||
'lo_export',
|
||||
'pg_read_file',
|
||||
'pg_read_binary_file',
|
||||
'pg_ls_dir',
|
||||
'pg_stat_file',
|
||||
'pg_file_write',
|
||||
'pg_file_rename',
|
||||
'pg_file_unlink',
|
||||
'pg_file_sync',
|
||||
];
|
||||
|
||||
/**
|
||||
* A privilege on a server setting that an ordinary role does not have:
|
||||
* `ALTER SYSTEM` on any parameter (it rewrites `postgresql.auto.conf`, where
|
||||
* `archive_command` or a preload library runs on the host), or `SET` on one
|
||||
* that only a superuser may set (`lo_compat_privileges` turns off the large
|
||||
* object checks). A grant to PUBLIC counts, and so does one on a parameter
|
||||
* this server does not know yet. `pg_parameter_acl` exists from PostgreSQL 15
|
||||
* on, and a statement naming it does not even parse on 14, so the query runs
|
||||
* through `query_to_xml` and only on 15 or later; it answers an empty string
|
||||
* when no row matches.
|
||||
*/
|
||||
const PARAMETER_GRANT_SQL =
|
||||
'select 1 from pg_catalog.pg_parameter_acl a, aclexplode(a.paracl) e' +
|
||||
" where (e.privilege_type = 'ALTER SYSTEM'" +
|
||||
" or coalesce((select s.context from pg_catalog.pg_settings s where s.name = a.parname), 'superuser') <> 'user')" +
|
||||
" and case when e.grantee = 0 then true else pg_has_role(current_user, e.grantee, 'MEMBER') end limit 1";
|
||||
|
||||
/** `text` as a SQL string literal. */
|
||||
const literal = (text: string) => `'${text.replaceAll("'", "''")}'`;
|
||||
|
||||
/**
|
||||
* True when the current role could reach the database host, or make itself
|
||||
* able to, from SQL. A restored archive is a SQL script run as that role, so
|
||||
* such a role turns a crafted archive into a way onto the host. It counts:
|
||||
*
|
||||
* - membership in any superuser role, its own included: `SET ROLE` to one is a
|
||||
* superuser session, whatever the role's own `rolsuper` says;
|
||||
* - membership in `pg_execute_server_program` (`COPY ... PROGRAM`),
|
||||
* `pg_write_server_files` or `pg_read_server_files` (`COPY` to or from a
|
||||
* server file), which a superuser holds implicitly;
|
||||
* - EXECUTE on one of {@link SERVER_FILE_FUNCTIONS} (`lo_export` writes a
|
||||
* server file and keeps it after its transaction rolled back);
|
||||
* - from PostgreSQL 15 on, a privilege on a server setting an ordinary role
|
||||
* lacks ({@link PARAMETER_GRANT_SQL});
|
||||
* - before PostgreSQL 16, membership in a role with CREATEROLE, its own
|
||||
* included: such a role may grant itself any role that is not a superuser,
|
||||
* those predefined roles included, and a member may `SET ROLE` to it first,
|
||||
* since role attributes are not inherited but the grant checks the role in
|
||||
* effect. From 16 on it needs ADMIN OPTION on a role to grant it, which the
|
||||
* checks above already see.
|
||||
*
|
||||
* `MEMBER` is membership whatever its INHERIT and SET options, since a member
|
||||
* that can neither may still be one that can grant itself the rest. The
|
||||
* version-gated parts sit in CASE, whose branches PostgreSQL evaluates only
|
||||
* when taken.
|
||||
*/
|
||||
export const PRIVILEGED_ROLE_SQL =
|
||||
"exists (select 1 from pg_roles r where r.rolsuper and pg_has_role(current_user, r.oid, 'MEMBER'))" +
|
||||
" or pg_has_role(current_user, 'pg_execute_server_program', 'MEMBER')" +
|
||||
" or pg_has_role(current_user, 'pg_write_server_files', 'MEMBER')" +
|
||||
" or pg_has_role(current_user, 'pg_read_server_files', 'MEMBER')" +
|
||||
" or exists (select 1 from pg_proc p where p.pronamespace = 'pg_catalog'::regnamespace" +
|
||||
` and p.proname in (${SERVER_FILE_FUNCTIONS.map(literal).join(', ')})` +
|
||||
" and has_function_privilege(current_user, p.oid, 'EXECUTE'))" +
|
||||
" or (case when current_setting('server_version_num')::int >= 150000" +
|
||||
` then query_to_xml(${literal(PARAMETER_GRANT_SQL)}, false, true, '')::text <> '' else false end)` +
|
||||
" or (case when current_setting('server_version_num')::int < 160000" +
|
||||
" then exists (select 1 from pg_roles r where r.rolcreaterole and pg_has_role(current_user, r.oid, 'MEMBER'))" +
|
||||
' else false end)';
|
||||
|
||||
/** What {@link PRIVILEGED_ROLE_SQL} refuses, as the boot warning and the restore refusal say it. */
|
||||
export const PRIVILEGED_ROLE_DESCRIPTION =
|
||||
'a superuser or a member of a superuser role, a role that may run programs or read or write files on the ' +
|
||||
'database server (through a predefined role or a granted server file function such as lo_export), a role ' +
|
||||
'granted ALTER SYSTEM or a superuser-only setting (PostgreSQL 15 and later), or (before PostgreSQL 16) a ' +
|
||||
'member of a role with CREATEROLE, which may grant itself those';
|
||||
|
||||
/** The major version in `server_version_num` (`170011` is 17, `180001` is 18). Throws on anything else. */
|
||||
export function serverMajor(versionNum: string | number | undefined): number {
|
||||
const value = Number(versionNum);
|
||||
if (!Number.isInteger(value) || value < 10000) {
|
||||
throw new Error(`The Postgres server reported the version number "${String(versionNum)}", which TREK cannot read.`);
|
||||
}
|
||||
return Math.floor(value / 10000);
|
||||
}
|
||||
|
||||
/**
|
||||
* Refuses a server outside {@link SUPPORTED_SERVER_MAJORS} before TREK writes
|
||||
* anything to it: an older one lacks what the schema uses, and a newer one is
|
||||
* untested and may be newer than the client tools that back it up.
|
||||
*/
|
||||
export function refuseUnsupportedServer(major: number): void {
|
||||
const { oldest, newest } = SUPPORTED_SERVER_MAJORS;
|
||||
if (major >= oldest && major <= newest) return;
|
||||
throw new Error(
|
||||
`${REFUSAL} the Postgres server is version ${major}; TREK supports PostgreSQL ${oldest} to ${newest}. ` +
|
||||
'Point TREK_DB_URL at a server of a supported version.',
|
||||
);
|
||||
}
|
||||
|
||||
/** The boot warning for a privileged role (see {@link PRIVILEGED_ROLE_SQL}); a restore refuses such a role outright. */
|
||||
export const PRIVILEGED_ROLE_WARNING =
|
||||
`TREK_DB_URL connects as ${PRIVILEGED_ROLE_DESCRIPTION}. ` +
|
||||
'Restores are refused for such a role. Connect TREK as a role that owns its database and is not a superuser ' +
|
||||
'(see the wiki page "Database: Postgres").';
|
||||
@@ -0,0 +1,43 @@
|
||||
import { CompiledQuery, type DatabaseConnection } from 'kysely';
|
||||
|
||||
/**
|
||||
* Puts `pg_temp` last on the `search_path` of every connection of TREK's pool.
|
||||
*
|
||||
* Postgres searches the session's temporary schema before everything on the
|
||||
* `search_path` unless the path names `pg_temp` itself, and a temporary table
|
||||
* lives as long as its connection. On a pool, whatever one caller left there
|
||||
* would stand in for TREK's tables (`users`, `sessions`, ...) for every later
|
||||
* caller of that connection. Named last, the temporary schema is searched
|
||||
* after every schema TREK uses, so its tables are never found first. The rest
|
||||
* of the path stays as the role or the database configured it: TREK may run
|
||||
* in a schema other than `public`, and finds it through that path.
|
||||
*
|
||||
* Plugin transactions set their own path the same way
|
||||
* (`plugin-data-store.ts`); `plugin-sql-guard.ts` explains the layers.
|
||||
*/
|
||||
|
||||
/** `path` (as `SHOW search_path` prints it) with every `pg_temp` entry taken out and one put last. */
|
||||
export function searchPathWithTempLast(path: string): string {
|
||||
const entries: string[] = [];
|
||||
let current = '';
|
||||
let quoted = false;
|
||||
for (const ch of path) {
|
||||
if (ch === '"') quoted = !quoted;
|
||||
if (ch === ',' && !quoted) {
|
||||
entries.push(current.trim());
|
||||
current = '';
|
||||
} else {
|
||||
current += ch;
|
||||
}
|
||||
}
|
||||
entries.push(current.trim());
|
||||
const kept = entries.filter((entry) => entry !== '' && entry.toLowerCase() !== 'pg_temp' && entry !== '"pg_temp"');
|
||||
return [...kept, 'pg_temp'].join(', ');
|
||||
}
|
||||
|
||||
/** The connection hook (`onCreateConnection`) that sets {@link searchPathWithTempLast} for the session. */
|
||||
export async function putTempSchemaLast(connection: DatabaseConnection): Promise<void> {
|
||||
const shown = await connection.executeQuery<{ search_path: string }>(CompiledQuery.raw('show search_path'));
|
||||
const path = searchPathWithTempLast(shown.rows[0]?.search_path ?? '');
|
||||
await connection.executeQuery(CompiledQuery.raw("select set_config('search_path', $1, false)", [path]));
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
/**
|
||||
* Splits generated DDL into single statements, so one statement Postgres
|
||||
* refuses does not take the rest of the schema with it.
|
||||
*
|
||||
* Understood: `;` outside quotes, `'` and `"` quoted text, and the `$$` dollar
|
||||
* quote a function body is written in, which is the only dollar quote TREK's
|
||||
* generated DDL and baseline contain. A tagged dollar quote (`$tag$`) is not
|
||||
* understood, so it is refused rather than split inside.
|
||||
*/
|
||||
|
||||
/** A tagged dollar quote (`$tag$`), matched where the scan stands. */
|
||||
const TAGGED_DOLLAR_QUOTE = /\$[A-Za-z_]\w*\$/y;
|
||||
|
||||
function refuseTaggedDollarQuote(sql: string, at: number): void {
|
||||
TAGGED_DOLLAR_QUOTE.lastIndex = at;
|
||||
const tag = TAGGED_DOLLAR_QUOTE.exec(sql)?.[0];
|
||||
if (tag) throw new Error(`splitStatements understands only the $$ dollar quote, not ${tag} (at ${at})`);
|
||||
}
|
||||
|
||||
/**
|
||||
* The statements in `sql`, trimmed and in order. A statement that sets a
|
||||
* session parameter (`SET ...`) is dropped: a dump's preamble, which a schema
|
||||
* the entities generate never needs.
|
||||
*/
|
||||
export function splitStatements(sql: string): string[] {
|
||||
const statements: string[] = [];
|
||||
let current = '';
|
||||
let quote: '"' | "'" | '$$' | null = null;
|
||||
for (let i = 0; i < sql.length; i++) {
|
||||
const char = sql[i];
|
||||
const dollar = sql.startsWith('$$', i);
|
||||
if (quote === '$$') {
|
||||
if (dollar) {
|
||||
quote = null;
|
||||
current += '$';
|
||||
i++;
|
||||
}
|
||||
current += char;
|
||||
} else if (quote) {
|
||||
if (char === quote) quote = null;
|
||||
current += char;
|
||||
} else if (dollar) {
|
||||
quote = '$$';
|
||||
current += '$$';
|
||||
i++;
|
||||
} else if (char === "'" || char === '"') {
|
||||
quote = char;
|
||||
current += char;
|
||||
} else if (char === ';') {
|
||||
if (current.trim()) statements.push(current.trim());
|
||||
current = '';
|
||||
} else {
|
||||
if (char === '$') refuseTaggedDollarQuote(sql, i);
|
||||
current += char;
|
||||
}
|
||||
}
|
||||
if (current.trim()) statements.push(current.trim());
|
||||
return statements.filter((statement) => !/^set\s/i.test(statement));
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
import { quoteIdentifier, run, type CopiedSequence, type TableSpec, type Trx } from './copy';
|
||||
import { planCopyOrder, type ForeignKey } from './order';
|
||||
import { columnKind } from './values';
|
||||
|
||||
/**
|
||||
* TREK's tables as the target database holds them after the engine's
|
||||
* bootstrap, and how each one is filled from the table of the same name in
|
||||
* the SQLite file. The target's catalog decides the column types; the SQLite
|
||||
* file only has to hold the same tables and columns, which a file at this
|
||||
* build's migration level does.
|
||||
*/
|
||||
|
||||
/** The migration history: each side keeps its own, and the bootstrap wrote the target's. */
|
||||
const HISTORY_TABLE = 'mikro_orm_migrations';
|
||||
|
||||
interface TargetColumn {
|
||||
name: string;
|
||||
dataType: string;
|
||||
nullable: boolean;
|
||||
}
|
||||
|
||||
interface TargetTable {
|
||||
name: string;
|
||||
columns: TargetColumn[];
|
||||
primaryKey: string[];
|
||||
}
|
||||
|
||||
export interface TargetSchema {
|
||||
tables: TargetTable[];
|
||||
foreignKeys: ForeignKey[];
|
||||
/** Every column a sequence fills, by table. */
|
||||
sequences: Array<{ table: string; column: string; sequence: string }>;
|
||||
}
|
||||
|
||||
/** Reads the tables, keys and sequences of the current schema. */
|
||||
export async function readTargetSchema(trx: Trx): Promise<TargetSchema> {
|
||||
const columns = await run<{ table_name: string; column_name: string; data_type: string; is_nullable: string }>(
|
||||
trx,
|
||||
'select c.table_name, c.column_name, c.data_type, c.is_nullable from information_schema.columns c ' +
|
||||
'join information_schema.tables t on t.table_schema = c.table_schema and t.table_name = c.table_name ' +
|
||||
"where c.table_schema = current_schema() and t.table_type = 'BASE TABLE' order by c.table_name, c.ordinal_position",
|
||||
);
|
||||
const constraints = await run<{ kind: string; table_name: string; target_name: string | null; columns: string[] }>(
|
||||
trx,
|
||||
'select c.contype as kind, src.relname as table_name, dst.relname as target_name, ' +
|
||||
'array_agg(a.attname::text order by k.ord) as columns from pg_constraint c ' +
|
||||
'join pg_class src on src.oid = c.conrelid left join pg_class dst on dst.oid = c.confrelid ' +
|
||||
'cross join lateral unnest(c.conkey) with ordinality as k(attnum, ord) ' +
|
||||
'join pg_attribute a on a.attrelid = c.conrelid and a.attnum = k.attnum ' +
|
||||
"where c.connamespace = current_schema()::regnamespace and c.contype in ('p', 'f') " +
|
||||
'group by c.oid, c.contype, src.relname, dst.relname',
|
||||
);
|
||||
const sequences = await run<{ table_name: string; column_name: string; sequence: string }>(
|
||||
trx,
|
||||
"select table_name, column_name, pg_get_serial_sequence(format('%I', table_name), column_name) as sequence " +
|
||||
'from information_schema.columns where table_schema = current_schema() ' +
|
||||
"and pg_get_serial_sequence(format('%I', table_name), column_name) is not null order by table_name, column_name",
|
||||
);
|
||||
|
||||
const tables = new Map<string, TargetTable>();
|
||||
for (const column of columns) {
|
||||
const table = tables.get(column.table_name) ?? { name: column.table_name, columns: [], primaryKey: [] };
|
||||
table.columns.push({
|
||||
name: column.column_name,
|
||||
dataType: column.data_type,
|
||||
nullable: column.is_nullable === 'YES',
|
||||
});
|
||||
tables.set(column.table_name, table);
|
||||
}
|
||||
const foreignKeys: ForeignKey[] = [];
|
||||
for (const constraint of constraints) {
|
||||
if (constraint.kind === 'p') {
|
||||
const table = tables.get(constraint.table_name);
|
||||
if (table) table.primaryKey = constraint.columns;
|
||||
} else if (constraint.target_name) {
|
||||
foreignKeys.push({
|
||||
table: constraint.table_name,
|
||||
columns: constraint.columns,
|
||||
references: constraint.target_name,
|
||||
});
|
||||
}
|
||||
}
|
||||
return {
|
||||
tables: [...tables.values()],
|
||||
foreignKeys,
|
||||
sequences: sequences.map((row) => ({ table: row.table_name, column: row.column_name, sequence: row.sequence })),
|
||||
};
|
||||
}
|
||||
|
||||
/** The tables and columns of the SQLite file, as the move compares them with the target. */
|
||||
export type SourceTables = ReadonlyMap<string, readonly string[]>;
|
||||
|
||||
interface TrekCopyPlan {
|
||||
/** The tables in the order they are filled. */
|
||||
specs: TableSpec[];
|
||||
sequences: CopiedSequence[];
|
||||
/** Why the two schemas do not match; the move refuses when there is any. */
|
||||
problems: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Pairs every table of the target with the SQLite table of the same name and
|
||||
* puts them in foreign key order. Anything the two do not share, or a column
|
||||
* type the move has no rule for, is a problem: copying around it would lose
|
||||
* data or guess.
|
||||
*/
|
||||
export function planTrekTables(target: TargetSchema, source: SourceTables): TrekCopyPlan {
|
||||
const problems: string[] = [];
|
||||
const tables = target.tables.filter((table) => table.name !== HISTORY_TABLE);
|
||||
const names = new Set(tables.map((table) => table.name));
|
||||
for (const name of source.keys()) {
|
||||
if (name !== HISTORY_TABLE && !names.has(name)) problems.push(`the SQLite table ${name} has no Postgres table`);
|
||||
}
|
||||
const plan = planCopyOrder(
|
||||
tables.map((table) => table.name),
|
||||
target.foreignKeys,
|
||||
);
|
||||
const byName = new Map(tables.map((table) => [table.name, table]));
|
||||
const specs: TableSpec[] = [];
|
||||
for (const name of plan.order) {
|
||||
const table = byName.get(name);
|
||||
const sourceColumns = source.get(name);
|
||||
if (!table) continue;
|
||||
if (!sourceColumns) {
|
||||
problems.push(`the Postgres table ${name} has no SQLite table`);
|
||||
continue;
|
||||
}
|
||||
for (const column of sourceColumns) {
|
||||
if (!table.columns.some((candidate) => candidate.name === column)) {
|
||||
problems.push(`the SQLite column ${name}.${column} has no Postgres column`);
|
||||
}
|
||||
}
|
||||
const columns = table.columns.flatMap((column) => {
|
||||
const kind = columnKind(column.dataType);
|
||||
if (!sourceColumns.includes(column.name))
|
||||
problems.push(`the Postgres column ${name}.${column.name} has no SQLite column`);
|
||||
else if (kind === null)
|
||||
problems.push(
|
||||
`the Postgres column ${name}.${column.name} has the type ${column.dataType}, which the move does not know`,
|
||||
);
|
||||
else return [{ name: column.name, kind }];
|
||||
return [];
|
||||
});
|
||||
const deferred = plan.deferred.get(name) ?? [];
|
||||
for (const column of deferred) {
|
||||
if (!table.columns.find((candidate) => candidate.name === column)?.nullable) {
|
||||
problems.push(`${name}.${column} refers back to a table filled later and cannot be NULL meanwhile`);
|
||||
}
|
||||
}
|
||||
specs.push({
|
||||
source: name,
|
||||
target: quoteIdentifier(name),
|
||||
label: name,
|
||||
columns,
|
||||
deferred,
|
||||
primaryKey: table.primaryKey,
|
||||
});
|
||||
}
|
||||
const sequences = target.sequences
|
||||
.filter((entry) => names.has(entry.table))
|
||||
.map((entry) => ({ ...entry, target: quoteIdentifier(entry.table) }));
|
||||
return { specs, sequences, problems };
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
import { readEnv, type AppEnv } from '../../../../app-config';
|
||||
import { resolveDataPaths } from '../../../../app-config/data-paths';
|
||||
import { knownMigrationNames } from '../../../known-migrations';
|
||||
import type { AnyOrm } from '../../../orm';
|
||||
import { buildOrmConfig, resolveEngine } from '../../index';
|
||||
import { redactUrl } from '../../redact-url';
|
||||
import { readPostgresBaseline } from '../baseline';
|
||||
import { MoveRefusal, moveSqliteToPostgres, renderSummary, type MoveOptions } from './move';
|
||||
import { MikroORM } from '@mikro-orm/core';
|
||||
|
||||
import path from 'node:path';
|
||||
|
||||
/**
|
||||
* The command around the move (`src/move-to-postgres.ts` runs it): reads
|
||||
* TREK_DB_URL as the server does, takes the SQLite file from the data
|
||||
* directory or `--from=<file>`, the plugin data from the plugins' data
|
||||
* directory, runs the move and prints its summary. Answers the exit code.
|
||||
*/
|
||||
|
||||
export const USAGE =
|
||||
'Usage: move-to-postgres [--from=<SQLite file>]\n' +
|
||||
'Copies a TREK SQLite database (data/travel.db by default) into the empty Postgres database TREK_DB_URL names.';
|
||||
|
||||
export interface MoveCommandIo {
|
||||
env: () => AppEnv;
|
||||
out: (line: string) => void;
|
||||
err: (line: string) => void;
|
||||
/** An ORM on the target database, from the Postgres engine's own config. */
|
||||
openOrm: (env: AppEnv) => Promise<AnyOrm>;
|
||||
move: (options: MoveOptions) => ReturnType<typeof moveSqliteToPostgres>;
|
||||
}
|
||||
|
||||
/** The ORM the move runs on: the engine's config, without entity discovery (the move runs SQL only). */
|
||||
async function openTargetOrm(env: AppEnv): Promise<AnyOrm> {
|
||||
const config = buildOrmConfig(resolveEngine(env.db));
|
||||
return MikroORM.init({
|
||||
...config,
|
||||
entities: [],
|
||||
entitiesTs: [],
|
||||
discovery: { warnWhenNoEntities: false },
|
||||
migrations: { ...config.migrations, silent: true },
|
||||
});
|
||||
}
|
||||
|
||||
const defaultIo: MoveCommandIo = {
|
||||
env: readEnv,
|
||||
out: (line) => process.stdout.write(`${line}\n`),
|
||||
err: (line) => process.stderr.write(`${line}\n`),
|
||||
openOrm: openTargetOrm,
|
||||
move: moveSqliteToPostgres,
|
||||
};
|
||||
|
||||
const FROM = '--from=';
|
||||
|
||||
async function run(argv: readonly string[], io: MoveCommandIo): Promise<number> {
|
||||
if (argv.includes('--help') || argv.includes('-h')) {
|
||||
io.out(USAGE);
|
||||
return 0;
|
||||
}
|
||||
const unknown = argv.find((arg) => !arg.startsWith(FROM));
|
||||
if (unknown !== undefined) throw new MoveRefusal(`Unknown argument ${unknown}.\n${USAGE}`);
|
||||
const env = io.env();
|
||||
if (env.db.engine !== 'postgres')
|
||||
throw new MoveRefusal('Set TREK_DB_URL to the empty Postgres database to move into.');
|
||||
|
||||
const paths = resolveDataPaths(env);
|
||||
const from = argv.find((arg) => arg.startsWith(FROM))?.slice(FROM.length);
|
||||
const sqliteFile = path.resolve(from || paths.dbFile);
|
||||
const target = redactUrl(env.db.url);
|
||||
io.out(`Moving ${sqliteFile} into ${target}`);
|
||||
const orm = await io.openOrm(env);
|
||||
try {
|
||||
const summary = await io.move({
|
||||
sqliteFile,
|
||||
pluginsDataDir: env.plugins.dataDir || path.join(paths.dataDir, 'plugins-data'),
|
||||
orm,
|
||||
known: knownMigrationNames(),
|
||||
baseline: readPostgresBaseline,
|
||||
log: (line) => io.out(` ${line}`),
|
||||
});
|
||||
io.out('');
|
||||
io.out(renderSummary(summary, target));
|
||||
return 0;
|
||||
} finally {
|
||||
await orm.close(true);
|
||||
}
|
||||
}
|
||||
|
||||
/** Runs the command and answers its exit code: 0 once the move committed, 1 for a refusal or a failure. */
|
||||
export async function runMoveCommand(argv: readonly string[], io: Partial<MoveCommandIo> = {}): Promise<number> {
|
||||
const resolved = { ...defaultIo, ...io };
|
||||
try {
|
||||
return await run(argv, resolved);
|
||||
} catch (err) {
|
||||
if (err instanceof MoveRefusal) resolved.err(`\nThe move was refused: ${err.message}`);
|
||||
else {
|
||||
const text = err instanceof Error ? (err.stack ?? err.message) : String(err);
|
||||
resolved.err(
|
||||
`\nThe move failed; the Postgres database is left as the move found it unless this says otherwise: ${text}`,
|
||||
);
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,302 @@
|
||||
import type { SqliteSource } from '../../sqlite/sqlite-source';
|
||||
import {
|
||||
beyondSafeInteger,
|
||||
canonicalFromPostgres,
|
||||
canonicalFromSent,
|
||||
convertValue,
|
||||
TableChecksum,
|
||||
type ColumnKind,
|
||||
type PostgresValue,
|
||||
type SqliteValue,
|
||||
} from './values';
|
||||
|
||||
import { CompiledQuery, type Kysely, type Transaction } from 'kysely';
|
||||
|
||||
/**
|
||||
* Copying one table from the SQLite file into Postgres and proving the copy,
|
||||
* inside the move's transaction. The same steps serve TREK's own tables and a
|
||||
* plugin's: read the rows one at a time, convert each value to its column's
|
||||
* type, insert in batches, then read the table back and compare its row count
|
||||
* and checksum with what was sent.
|
||||
*/
|
||||
|
||||
export type Trx = Transaction<object>;
|
||||
|
||||
/** Rows per INSERT at most; fewer for a wide table, so a batch stays far below Postgres's 65535 parameters. */
|
||||
const MAX_BATCH_ROWS = 500;
|
||||
const MAX_BATCH_PARAMS = 30_000;
|
||||
/** Rows a verification cursor fetches at once. */
|
||||
const FETCH_ROWS = 2_000;
|
||||
/** The most refused values a refusal lists one by one. */
|
||||
export const MAX_LISTED_PROBLEMS = 20;
|
||||
|
||||
/** One column of a table the move copies. */
|
||||
interface CopyColumn {
|
||||
name: string;
|
||||
kind: ColumnKind;
|
||||
}
|
||||
|
||||
/** What the move copies from one SQLite table into one Postgres table. */
|
||||
export interface TableSpec {
|
||||
/** The table in the SQLite file. */
|
||||
source: string;
|
||||
/** The Postgres table, quoted and qualified as SQL needs it. */
|
||||
target: string;
|
||||
/** A name for messages: `users`, or `plugin my-plugin: notes`. */
|
||||
label: string;
|
||||
columns: CopyColumn[];
|
||||
/** Foreign key columns inserted as NULL first and set once every table is in (`order.ts`). */
|
||||
deferred: string[];
|
||||
/** The primary key's columns, which the deferred update finds a row by. */
|
||||
primaryKey: string[];
|
||||
}
|
||||
|
||||
/** A row's deferred values, kept until every table is in. */
|
||||
interface DeferredRow {
|
||||
key: PostgresValue[];
|
||||
values: PostgresValue[];
|
||||
}
|
||||
|
||||
/** What copying one table found. */
|
||||
export interface CopiedTable {
|
||||
spec: TableSpec;
|
||||
rows: number;
|
||||
checksum: string;
|
||||
/** Values the Postgres column cannot hold exactly, listed up to `MAX_LISTED_PROBLEMS`; the move refuses on any. */
|
||||
problems: string[];
|
||||
problemCount: number;
|
||||
/** Integer values beyond 2^53, which TREK's Postgres driver refuses to read back. */
|
||||
unsafeIntegers: number;
|
||||
deferredRows: DeferredRow[];
|
||||
}
|
||||
|
||||
/** `name` as a Postgres identifier. */
|
||||
export function quoteIdentifier(name: string): string {
|
||||
return `"${name.replaceAll('"', '""')}"`;
|
||||
}
|
||||
|
||||
/** Runs one statement, in the move's transaction or on the pool, and returns its rows. */
|
||||
export async function run<R = Record<string, unknown>>(
|
||||
trx: Kysely<object>,
|
||||
sql: string,
|
||||
params: unknown[] = [],
|
||||
): Promise<R[]> {
|
||||
const result = await trx.executeQuery<R>(CompiledQuery.raw(sql, params));
|
||||
return result.rows;
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs `work` for each item, one after the other, each started once the one
|
||||
* before it has finished: the move's statements share one transaction, which
|
||||
* runs one statement at a time.
|
||||
*/
|
||||
export async function inOrder<T>(items: readonly T[], work: (item: T) => Promise<void>): Promise<void> {
|
||||
await items.reduce<Promise<void>>((previous, item) => previous.then(() => work(item)), Promise.resolve());
|
||||
}
|
||||
|
||||
/** A Postgres error with its detail and the constraint it broke, which `pg` keeps apart from the message. */
|
||||
export function describePgError(err: unknown): string {
|
||||
if (!(err instanceof Error)) return String(err);
|
||||
const extra = err as Error & { detail?: string; constraint?: string };
|
||||
const parts = [err.message];
|
||||
if (extra.constraint) parts.push(`constraint ${extra.constraint}`);
|
||||
if (extra.detail) parts.push(extra.detail);
|
||||
return parts.join('; ');
|
||||
}
|
||||
|
||||
/** How many rows one INSERT carries for a table of `columns` columns. */
|
||||
export function batchRows(columns: number): number {
|
||||
return Math.max(1, Math.min(MAX_BATCH_ROWS, Math.floor(MAX_BATCH_PARAMS / Math.max(1, columns))));
|
||||
}
|
||||
|
||||
/** The INSERT of `rows` rows into the table, with numbered parameters row by row. */
|
||||
export function insertSql(spec: Pick<TableSpec, 'target' | 'columns'>, rows: number): string {
|
||||
const names = spec.columns.map((column) => quoteIdentifier(column.name)).join(', ');
|
||||
const width = spec.columns.length;
|
||||
const tuples = Array.from(
|
||||
{ length: rows },
|
||||
(_, row) => `(${spec.columns.map((_column, index) => `$${row * width + index + 1}`).join(', ')})`,
|
||||
);
|
||||
return `insert into ${spec.target} (${names}) values ${tuples.join(', ')}`;
|
||||
}
|
||||
|
||||
async function insertBatch(trx: Trx, spec: TableSpec, batch: PostgresValue[][]): Promise<void> {
|
||||
if (batch.length === 0) return;
|
||||
try {
|
||||
await run(trx, insertSql(spec, batch.length), batch.flat());
|
||||
} catch (err) {
|
||||
throw new Error(`Postgres refused rows of ${spec.label}: ${describePgError(err)}`, { cause: err });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Copies the rows of one table. Every value is converted first; once one
|
||||
* cannot be, nothing more is inserted, but the rest of the table is still read
|
||||
* so the refusal can list every problem at once. With `insert: false` it only
|
||||
* reads and converts, once an earlier table was refused.
|
||||
*/
|
||||
export async function copyTable(
|
||||
trx: Trx,
|
||||
source: SqliteSource,
|
||||
spec: TableSpec,
|
||||
options: { insert: boolean } = { insert: true },
|
||||
): Promise<CopiedTable> {
|
||||
const result: CopiedTable = {
|
||||
spec,
|
||||
rows: 0,
|
||||
checksum: '',
|
||||
problems: [],
|
||||
problemCount: 0,
|
||||
unsafeIntegers: 0,
|
||||
deferredRows: [],
|
||||
};
|
||||
const checksum = new TableChecksum();
|
||||
const deferredAt = spec.deferred.map((name) => spec.columns.findIndex((column) => column.name === name));
|
||||
const keyAt = spec.primaryKey.map((name) => spec.columns.findIndex((column) => column.name === name));
|
||||
const size = batchRows(spec.columns.length);
|
||||
|
||||
/** How a refusal names a row: by its primary key, or by its place in the table without one. */
|
||||
const rowName = (raw: unknown[]): string => {
|
||||
if (keyAt.length === 0 || keyAt.includes(-1)) return `row ${result.rows}`;
|
||||
return `row ${spec.primaryKey.map((name, index) => `${name}=${String(raw[keyAt[index]])}`).join(', ')}`;
|
||||
};
|
||||
|
||||
/** One SQLite row as the values sent to Postgres, or null once a value was refused. */
|
||||
const convertRow = (raw: unknown[]): PostgresValue[] | null => {
|
||||
result.rows++;
|
||||
const values: PostgresValue[] = [];
|
||||
spec.columns.forEach((column, index) => {
|
||||
const converted = convertValue(raw[index] as SqliteValue, column.kind);
|
||||
// Narrowed by `in`: the server compiles without strictNullChecks, where `ok` does not narrow the union.
|
||||
if (!('reason' in converted)) {
|
||||
values.push(converted.value);
|
||||
if (column.kind === 'integer' && beyondSafeInteger(converted.value)) result.unsafeIntegers++;
|
||||
return;
|
||||
}
|
||||
values.push(null);
|
||||
result.problemCount++;
|
||||
if (result.problems.length < MAX_LISTED_PROBLEMS) {
|
||||
result.problems.push(`${spec.label} ${rowName(raw)}, column ${column.name}: ${converted.reason}`);
|
||||
}
|
||||
});
|
||||
if (result.problemCount > 0) return null;
|
||||
checksum.add(values.map((value, index) => canonicalFromSent(value, spec.columns[index].kind)));
|
||||
if (deferredAt.length > 0) {
|
||||
const later = deferredAt.map((index) => values[index]);
|
||||
if (later.some((value) => value !== null)) {
|
||||
result.deferredRows.push({ key: keyAt.map((index) => values[index]), values: later });
|
||||
}
|
||||
for (const index of deferredAt) values[index] = null;
|
||||
}
|
||||
return values;
|
||||
};
|
||||
|
||||
const rows = source.rows(
|
||||
spec.source,
|
||||
spec.columns.map((column) => column.name),
|
||||
);
|
||||
/** Reads up to one batch of rows; `done` once the table has no more. */
|
||||
const nextBatch = (): { batch: PostgresValue[][]; done: boolean } => {
|
||||
const batch: PostgresValue[][] = [];
|
||||
while (batch.length < size) {
|
||||
const next = rows.next();
|
||||
if (next.done) return { batch, done: true };
|
||||
const values = convertRow(next.value);
|
||||
if (values) batch.push(values);
|
||||
}
|
||||
return { batch, done: false };
|
||||
};
|
||||
const pump = async (): Promise<void> => {
|
||||
const { batch, done } = nextBatch();
|
||||
// Always awaited, so the next batch starts on a fresh stack even when nothing is inserted.
|
||||
await (options.insert && result.problemCount === 0 ? insertBatch(trx, spec, batch) : Promise.resolve());
|
||||
if (!done) await pump();
|
||||
};
|
||||
try {
|
||||
await pump();
|
||||
} finally {
|
||||
// An iterator left open keeps the SQLite handle busy.
|
||||
rows.return?.();
|
||||
}
|
||||
result.checksum = checksum.hex();
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Sets the foreign key columns `copyTable` held back, once every table is in. */
|
||||
export async function applyDeferred(trx: Trx, copied: CopiedTable): Promise<void> {
|
||||
const { spec } = copied;
|
||||
if (copied.deferredRows.length === 0) return;
|
||||
if (spec.primaryKey.length === 0) throw new Error(`${spec.label} has no primary key to set its deferred columns by.`);
|
||||
const width = spec.deferred.length;
|
||||
const sets = spec.deferred.map((name, index) => `${quoteIdentifier(name)} = $${index + 1}`).join(', ');
|
||||
const where = spec.primaryKey.map((name, index) => `${quoteIdentifier(name)} = $${width + index + 1}`).join(' and ');
|
||||
const sql = `update ${spec.target} set ${sets} where ${where}`;
|
||||
// One row at a time: only the rows of a table that points at itself, a handful in practice.
|
||||
await inOrder(copied.deferredRows, async (row) => {
|
||||
try {
|
||||
await run(trx, sql, [...row.values, ...row.key]);
|
||||
} catch (err) {
|
||||
throw new Error(`Postgres refused a reference in ${spec.label}: ${describePgError(err)}`, { cause: err });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads a table back through a cursor, every column as text, and answers its
|
||||
* row count and checksum, which must equal what `copyTable` sent.
|
||||
*/
|
||||
export async function readBack(trx: Trx, spec: TableSpec): Promise<{ rows: number; checksum: string }> {
|
||||
const checksum = new TableChecksum();
|
||||
const list = spec.columns.map((column, index) => `${quoteIdentifier(column.name)}::text as c${index}`).join(', ');
|
||||
const fetchAll = async (): Promise<void> => {
|
||||
const rows = await run<Record<string, string | null>>(trx, `fetch forward ${FETCH_ROWS} from trek_move_verify`);
|
||||
for (const row of rows) {
|
||||
checksum.add(spec.columns.map((column, index) => canonicalFromPostgres(row[`c${index}`] ?? null, column.kind)));
|
||||
}
|
||||
if (rows.length === FETCH_ROWS) await fetchAll();
|
||||
};
|
||||
await run(trx, `declare trek_move_verify no scroll cursor for select ${list} from ${spec.target}`);
|
||||
try {
|
||||
await fetchAll();
|
||||
} finally {
|
||||
await run(trx, 'close trek_move_verify');
|
||||
}
|
||||
return { rows: checksum.rows, checksum: checksum.hex() };
|
||||
}
|
||||
|
||||
/** A sequence behind a copied column: `table` names it in the SQLite file, `target` in Postgres. */
|
||||
export interface CopiedSequence {
|
||||
table: string;
|
||||
target: string;
|
||||
column: string;
|
||||
sequence: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Moves every sequence of the copied tables past the ids they now hold, and
|
||||
* past the highest id an AUTOINCREMENT table ever handed out in the SQLite
|
||||
* file, so a new row never takes an id SQLite would not have reused.
|
||||
*/
|
||||
export async function advanceSequences(
|
||||
trx: Trx,
|
||||
sequences: readonly CopiedSequence[],
|
||||
autoincrementSeen: ReadonlyMap<string, bigint>,
|
||||
): Promise<number> {
|
||||
await inOrder(sequences, async (entry) => {
|
||||
const [row] = await run<{ max: string | null }>(
|
||||
trx,
|
||||
`select max(${quoteIdentifier(entry.column)})::text as max from ${entry.target}`,
|
||||
);
|
||||
const seen = autoincrementSeen.get(entry.table) ?? null;
|
||||
const copied = row?.max ? BigInt(row.max) : null;
|
||||
const highest = seen !== null && (copied === null || seen > copied) ? seen : copied;
|
||||
// Nothing copied: the next id is 1, as on a new database.
|
||||
const called = highest !== null && highest >= 1n;
|
||||
await run(trx, 'select setval($1::regclass, $2::bigint, $3::boolean)', [
|
||||
entry.sequence,
|
||||
called ? highest.toString() : '1',
|
||||
called,
|
||||
]);
|
||||
});
|
||||
return sequences.length;
|
||||
}
|
||||
@@ -0,0 +1,360 @@
|
||||
import { NO_SAFETY_NET } from '../../../legacy-baseline';
|
||||
import type { AnyOrm } from '../../../orm';
|
||||
import { SqliteSource } from '../../sqlite/sqlite-source';
|
||||
import type { PostgresBaseline } from '../baseline';
|
||||
import { CLEAR_SCHEMA_SQL } from '../clear-schema';
|
||||
import { PLUGIN_SCHEMA_PREFIX } from '../plugin-schema';
|
||||
import { bootstrapPostgresSchema } from '../schema-bootstrap';
|
||||
import { planTrekTables, readTargetSchema, type SourceTables } from './catalog';
|
||||
import {
|
||||
advanceSequences,
|
||||
applyDeferred,
|
||||
copyTable,
|
||||
inOrder,
|
||||
MAX_LISTED_PROBLEMS,
|
||||
readBack,
|
||||
run,
|
||||
type CopiedSequence,
|
||||
type CopiedTable,
|
||||
type Trx,
|
||||
} from './copy';
|
||||
import {
|
||||
createPluginSchema,
|
||||
findPluginDataFiles,
|
||||
planPluginData,
|
||||
resolveIdentitySequences,
|
||||
type PluginPlan,
|
||||
} from './plugin-data';
|
||||
import type { AbstractSqlConnection } from '@mikro-orm/sql';
|
||||
|
||||
import type { Kysely } from 'kysely';
|
||||
|
||||
/**
|
||||
* Moves a SQLite install into an empty Postgres database (`npm run
|
||||
* db:move-to-postgres`, `dist/move-to-postgres.js` in the image).
|
||||
*
|
||||
* 1. The SQLite file must be at this build's migration level: an older one is
|
||||
* migrated by starting this TREK on it once, a newer one belongs to the
|
||||
* TREK that wrote it. Nothing else is checked by guess.
|
||||
* 2. The Postgres database must hold no table and no plugin schema.
|
||||
* 3. The schema is created exactly as a first boot creates it (the engine's
|
||||
* bootstrap: the baseline and the migrations after its cut), without the
|
||||
* seeders, since every row comes from the file.
|
||||
* 4. In one transaction: the rows the bootstrap seeded are cleared, every
|
||||
* table is filled in foreign key order, each plugin's `plugin.db` goes into
|
||||
* its schema, the sequences are moved past the copied ids, and every table
|
||||
* is read back and compared with what was sent (row count and a checksum
|
||||
* over all rows). Only a copy that matches is committed.
|
||||
* 5. Anything that fails leaves the database as it was found: the
|
||||
* transaction rolls back and the schema the bootstrap created is dropped.
|
||||
*
|
||||
* The SQLite files are opened read-only and never written. Uploads are not
|
||||
* the database's: they stay where the storage driver keeps them.
|
||||
*/
|
||||
|
||||
/** A refusal the operator can act on: printed without a stack. */
|
||||
export class MoveRefusal extends Error {}
|
||||
|
||||
export interface MoveOptions {
|
||||
/** The SQLite file to move: `data/travel.db` by default. */
|
||||
sqliteFile: string;
|
||||
/** Where the plugins keep their data directories (`plugin.db` files). */
|
||||
pluginsDataDir: string;
|
||||
/** An ORM on the target database, from the Postgres engine's own config. */
|
||||
orm: AnyOrm;
|
||||
/** The migrations this build ships. */
|
||||
known: ReadonlySet<string>;
|
||||
baseline: () => PostgresBaseline;
|
||||
/** Where progress lines go. */
|
||||
log: (line: string) => void;
|
||||
}
|
||||
|
||||
interface MovedTable {
|
||||
label: string;
|
||||
rows: number;
|
||||
checksum: string;
|
||||
}
|
||||
|
||||
export interface MoveSummary {
|
||||
sqliteFile: string;
|
||||
tables: MovedTable[];
|
||||
plugins: Array<{ pluginId: string; schema: string; tables: MovedTable[]; notCarried: string[] }>;
|
||||
sequences: number;
|
||||
warnings: string[];
|
||||
seconds: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Why the SQLite file is not at this build's migration level, or null when it
|
||||
* is: it must have recorded exactly the migrations this build ships.
|
||||
*/
|
||||
export function migrationLevelProblem(recorded: readonly string[] | null, known: ReadonlySet<string>): string | null {
|
||||
const startOnce =
|
||||
'Start this TREK version on it once, without TREK_DB_URL, so it brings the file up to date; stop it; then run the move again.';
|
||||
if (recorded === null || recorded.length === 0) {
|
||||
return `the SQLite file has no TREK migration history (an install from before 5.0, or not a TREK database). ${startOnce}`;
|
||||
}
|
||||
const unknown = recorded.filter((name) => !known.has(name));
|
||||
if (unknown.length > 0) {
|
||||
return (
|
||||
`a newer TREK migrated the SQLite file (${unknown.length} migration(s) this version does not know, ` +
|
||||
`the last ${[...unknown].sort().at(-1)}). Run the move with the TREK version that last ran on it.`
|
||||
);
|
||||
}
|
||||
const have = new Set(recorded);
|
||||
const missing = [...known].filter((name) => !have.has(name));
|
||||
if (missing.length > 0) {
|
||||
return `the SQLite file is ${missing.length} migration(s) behind this TREK version. ${startOnce}`;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function listed(problems: readonly string[], total: number): string {
|
||||
const lines = problems.map((problem) => ` - ${problem}`);
|
||||
if (total > problems.length) lines.push(` - and ${total - problems.length} more`);
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
/** Refuses a database that holds a table or a plugin schema: the move fills an empty database only. */
|
||||
async function refuseNonEmptyTarget(db: Kysely<object>): Promise<void> {
|
||||
const tables = await run<{ table_name: string }>(
|
||||
db,
|
||||
'select table_name from information_schema.tables where table_schema = current_schema() order by table_name limit 5',
|
||||
);
|
||||
const schemas = await run<{ nspname: string }>(
|
||||
db,
|
||||
'select nspname from pg_namespace where starts_with(nspname, $1) order by nspname limit 5',
|
||||
[PLUGIN_SCHEMA_PREFIX],
|
||||
);
|
||||
const found = [...tables.map((row) => row.table_name), ...schemas.map((row) => `schema ${row.nspname}`)];
|
||||
if (found.length === 0) return;
|
||||
throw new MoveRefusal(
|
||||
`The Postgres database is not empty (${found.join(', ')}). The move fills an empty database only, so it never ` +
|
||||
'mixes two installs. Point TREK_DB_URL at a new, empty database. If an earlier move stopped part of the way, ' +
|
||||
'drop that database and create it again.',
|
||||
);
|
||||
}
|
||||
|
||||
/** Opens every plugin's data file and plans its copy; the sources stay open for the copy. */
|
||||
function planPlugins(root: string, warnings: string[]): Array<{ source: SqliteSource; plan: PluginPlan }> {
|
||||
const { files, skipped } = findPluginDataFiles(root);
|
||||
for (const file of skipped) warnings.push(`${file} is in a directory whose name is no plugin id; it was not moved.`);
|
||||
const plugins: Array<{ source: SqliteSource; plan: PluginPlan }> = [];
|
||||
for (const { pluginId, file } of files) {
|
||||
const source = SqliteSource.open(file);
|
||||
plugins.push({ source, plan: planPluginData(pluginId, source) });
|
||||
}
|
||||
return plugins;
|
||||
}
|
||||
|
||||
/** Compares a copied table with what Postgres holds now: the SQLite count, the rows sent and the checksum. */
|
||||
async function verify(trx: Trx, copied: CopiedTable, sqliteCount: number): Promise<string | null> {
|
||||
const back = await readBack(trx, copied.spec);
|
||||
if (back.rows !== sqliteCount || copied.rows !== sqliteCount) {
|
||||
return `${copied.spec.label}: the SQLite file holds ${sqliteCount} rows, ${copied.rows} were sent, Postgres holds ${back.rows}`;
|
||||
}
|
||||
if (back.checksum !== copied.checksum)
|
||||
return `${copied.spec.label}: the rows Postgres holds differ from the rows sent`;
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Everything the copy transaction does, in order; throws on the first thing that does not hold. */
|
||||
async function copyAll(
|
||||
trx: Trx,
|
||||
source: SqliteSource,
|
||||
plugins: ReadonlyArray<{ source: SqliteSource; plan: PluginPlan }>,
|
||||
options: MoveOptions,
|
||||
summary: MoveSummary,
|
||||
): Promise<void> {
|
||||
await run(trx, "set local bytea_output = 'hex'");
|
||||
const sourceTables: SourceTables = new Map(
|
||||
source.tables().map((table) => [table, source.columns(table).map((column) => column.name)]),
|
||||
);
|
||||
const plan = planTrekTables(await readTargetSchema(trx), sourceTables);
|
||||
if (plan.problems.length > 0) {
|
||||
throw new MoveRefusal(
|
||||
`The SQLite file and this TREK's Postgres schema differ:\n${listed(plan.problems, plan.problems.length)}`,
|
||||
);
|
||||
}
|
||||
// The bootstrap's own rows (default settings, addons, providers) give way to the file's.
|
||||
await run(trx, `truncate table ${plan.specs.map((spec) => spec.target).join(', ')}`);
|
||||
|
||||
const copied: CopiedTable[] = [];
|
||||
let refused = 0;
|
||||
const copyOne = (from: SqliteSource) => async (spec: CopiedTable['spec']) => {
|
||||
options.log(`Copying ${spec.label}`);
|
||||
const result = await copyTable(trx, from, spec, { insert: refused === 0 });
|
||||
refused += result.problemCount;
|
||||
copied.push(result);
|
||||
};
|
||||
await inOrder(plan.specs, copyOne(source));
|
||||
// Once a value was refused nothing more is inserted, so there are no rows to point at each other.
|
||||
if (refused === 0) await inOrder(copied, (table) => applyDeferred(trx, table));
|
||||
|
||||
const sequences: CopiedSequence[] = [...plan.sequences];
|
||||
const pluginTables = new Map<string, CopiedTable[]>();
|
||||
await inOrder(plugins, async ({ source: pluginSource, plan: pluginPlan }) => {
|
||||
if (refused > 0) return;
|
||||
await createPluginSchema(trx, pluginPlan);
|
||||
const before = copied.length;
|
||||
await inOrder(pluginPlan.specs, copyOne(pluginSource));
|
||||
pluginTables.set(pluginPlan.pluginId, copied.slice(before));
|
||||
});
|
||||
if (refused > 0) {
|
||||
const problems = copied.flatMap((table) => table.problems).slice(0, MAX_LISTED_PROBLEMS);
|
||||
throw new MoveRefusal(
|
||||
`${refused} value(s) in the SQLite file cannot be stored in Postgres exactly; nothing was written:\n` +
|
||||
`${listed(problems, refused)}\nCorrect those rows (or ask for help with them), then run the move again.`,
|
||||
);
|
||||
}
|
||||
|
||||
options.log('Moving the id sequences past the copied rows');
|
||||
summary.sequences = await advanceSequences(trx, sequences, source.autoincrementSeen());
|
||||
await inOrder(plugins, async ({ source: pluginSource, plan: pluginPlan }) => {
|
||||
summary.sequences += await advanceSequences(
|
||||
trx,
|
||||
await resolveIdentitySequences(trx, pluginPlan),
|
||||
pluginSource.autoincrementSeen(),
|
||||
);
|
||||
});
|
||||
|
||||
options.log('Verifying every table');
|
||||
const mismatches: string[] = [];
|
||||
const sourceOf = (table: CopiedTable) =>
|
||||
plugins.find(({ plan: pluginPlan }) => pluginPlan.specs.includes(table.spec))?.source ?? source;
|
||||
await inOrder(copied, async (table) => {
|
||||
const mismatch = await verify(trx, table, sourceOf(table).count(table.spec.source));
|
||||
if (mismatch) mismatches.push(mismatch);
|
||||
});
|
||||
if (mismatches.length > 0) {
|
||||
throw new Error(
|
||||
`The copy does not match the SQLite file; nothing was written:\n${listed(mismatches, mismatches.length)}`,
|
||||
);
|
||||
}
|
||||
|
||||
const moved = (table: CopiedTable): MovedTable => ({
|
||||
label: table.spec.source,
|
||||
rows: table.rows,
|
||||
checksum: table.checksum,
|
||||
});
|
||||
const pluginCopies = new Set([...pluginTables.values()].flat());
|
||||
summary.tables = copied.filter((table) => !pluginCopies.has(table)).map(moved);
|
||||
summary.plugins = plugins.map(({ plan: pluginPlan }) => ({
|
||||
pluginId: pluginPlan.pluginId,
|
||||
schema: pluginPlan.schema,
|
||||
tables: (pluginTables.get(pluginPlan.pluginId) ?? []).map(moved),
|
||||
notCarried: pluginPlan.notCarried,
|
||||
}));
|
||||
const unsafe = copied.filter((table) => table.unsafeIntegers > 0);
|
||||
for (const table of unsafe) {
|
||||
summary.warnings.push(
|
||||
`${table.spec.label} holds ${table.unsafeIntegers} integer(s) beyond 2^53, which TREK refuses to read on Postgres.`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Drops what the bootstrap created after a move failed (the database was
|
||||
* empty before it, so everything in its schema is the move's). When even that
|
||||
* fails, the error says so, since the database then needs dropping by hand.
|
||||
*/
|
||||
async function emptyAgain(db: Kysely<object>, failure: unknown): Promise<void> {
|
||||
try {
|
||||
await run(db, CLEAR_SCHEMA_SQL);
|
||||
} catch (err) {
|
||||
throw new Error(
|
||||
`The move failed (${failure instanceof Error ? failure.message : String(failure)}), and the schema it had created ` +
|
||||
`could not be dropped (${err instanceof Error ? err.message : String(err)}). Drop the Postgres database and ` +
|
||||
'create it again before the next attempt.',
|
||||
{ cause: err },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** Runs the move. Throws a `MoveRefusal` for what the operator can fix, and leaves the target as it found it. */
|
||||
export async function moveSqliteToPostgres(options: MoveOptions): Promise<MoveSummary> {
|
||||
const started = Date.now();
|
||||
const summary: MoveSummary = {
|
||||
sqliteFile: options.sqliteFile,
|
||||
tables: [],
|
||||
plugins: [],
|
||||
sequences: 0,
|
||||
warnings: [],
|
||||
seconds: 0,
|
||||
};
|
||||
const db = (options.orm.em.getConnection() as AbstractSqlConnection).getClient<object>();
|
||||
let source: SqliteSource;
|
||||
try {
|
||||
source = SqliteSource.open(options.sqliteFile);
|
||||
} catch (err) {
|
||||
throw new MoveRefusal(
|
||||
`Cannot read the SQLite file ${options.sqliteFile}: ${err instanceof Error ? err.message : String(err)}. ` +
|
||||
'Stop TREK first, and point --from at the file if it is not data/travel.db.',
|
||||
);
|
||||
}
|
||||
const plugins: Array<{ source: SqliteSource; plan: PluginPlan }> = [];
|
||||
try {
|
||||
const level = migrationLevelProblem(source.migrationNames(), options.known);
|
||||
if (level) throw new MoveRefusal(`Cannot move ${options.sqliteFile}: ${level}`);
|
||||
const orphans = source.orphans(MAX_LISTED_PROBLEMS);
|
||||
if (orphans.length > 0) {
|
||||
throw new MoveRefusal(
|
||||
`${options.sqliteFile} holds rows whose reference points at nothing, which Postgres refuses:\n` +
|
||||
listed(
|
||||
orphans.map((row) => `${row.table} row ${String(row.rowid)} refers to a missing row of ${row.parent}`),
|
||||
orphans.length,
|
||||
),
|
||||
);
|
||||
}
|
||||
plugins.push(...planPlugins(options.pluginsDataDir, summary.warnings));
|
||||
await refuseNonEmptyTarget(db);
|
||||
|
||||
try {
|
||||
options.log('Creating the schema as a first boot does');
|
||||
await bootstrapPostgresSchema(options.orm, {
|
||||
baseline: options.baseline,
|
||||
known: new Set(options.known),
|
||||
safetyNet: NO_SAFETY_NET,
|
||||
// This is the move itself.
|
||||
sqliteLeftBehind: () => null,
|
||||
});
|
||||
await db.transaction().execute((trx) => copyAll(trx, source, plugins, options, summary));
|
||||
} catch (err) {
|
||||
// The copy rolled back; what the bootstrap created goes too, so the database is empty again.
|
||||
await emptyAgain(db, err);
|
||||
throw err;
|
||||
}
|
||||
} finally {
|
||||
source.close();
|
||||
for (const plugin of plugins) plugin.source.close();
|
||||
}
|
||||
summary.seconds = Math.round((Date.now() - started) / 100) / 10;
|
||||
return summary;
|
||||
}
|
||||
|
||||
/** The summary the command prints once the move committed. */
|
||||
export function renderSummary(summary: MoveSummary, target: string): string {
|
||||
const rows = summary.tables.reduce((sum, table) => sum + table.rows, 0);
|
||||
const lines = [
|
||||
`Moved ${summary.sqliteFile} into ${target} in ${summary.seconds} s.`,
|
||||
` ${summary.tables.length} tables, ${rows} rows, each table verified by row count and checksum.`,
|
||||
` ${summary.sequences} id sequence(s) moved past the copied rows.`,
|
||||
];
|
||||
for (const table of summary.tables.filter((entry) => entry.rows > 0)) {
|
||||
lines.push(` ${table.label}: ${table.rows}`);
|
||||
}
|
||||
for (const plugin of summary.plugins) {
|
||||
const pluginRows = plugin.tables.reduce((sum, table) => sum + table.rows, 0);
|
||||
lines.push(
|
||||
` Plugin ${plugin.pluginId}: ${plugin.tables.length} table(s), ${pluginRows} rows, into schema ${plugin.schema}.`,
|
||||
);
|
||||
for (const item of plugin.notCarried) lines.push(` not carried over: ${item}`);
|
||||
}
|
||||
for (const warning of summary.warnings) lines.push(` Warning: ${warning}`);
|
||||
lines.push(
|
||||
'',
|
||||
'The SQLite file and the uploads were not changed. Next: set TREK_DB_URL for TREK, start it, sign in and check',
|
||||
`your trips. To go back, unset TREK_DB_URL: TREK starts on ${summary.sqliteFile} as before.`,
|
||||
);
|
||||
return lines.join('\n');
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
/**
|
||||
* The order the move fills the tables in, from the target's foreign keys: a
|
||||
* table after every table it points at, so each row it inserts finds the row
|
||||
* it references. Ties go by name, so two runs over one schema copy in the
|
||||
* same order.
|
||||
*
|
||||
* A foreign key that cannot be satisfied by the order alone (a table pointing
|
||||
* at itself, like a reply at its message, or a cycle between tables) is
|
||||
* deferred: its columns are inserted as NULL and set once every row of the
|
||||
* tables is in, still inside the move's one transaction. Postgres checks each
|
||||
* foreign key when the row is written, so this is what lets a parent row
|
||||
* arrive after its child.
|
||||
*/
|
||||
|
||||
/** One foreign key of the target: `columns` of `table` point at `references`. */
|
||||
export interface ForeignKey {
|
||||
table: string;
|
||||
columns: readonly string[];
|
||||
references: string;
|
||||
}
|
||||
|
||||
interface CopyPlan {
|
||||
/** Every table, each after the tables it points at. */
|
||||
order: string[];
|
||||
/** Per table, the foreign key columns written as NULL first and set after all rows are in. */
|
||||
deferred: Map<string, string[]>;
|
||||
}
|
||||
|
||||
function defer(plan: CopyPlan, fk: ForeignKey): void {
|
||||
const columns = plan.deferred.get(fk.table) ?? [];
|
||||
for (const column of fk.columns) if (!columns.includes(column)) columns.push(column);
|
||||
plan.deferred.set(fk.table, columns);
|
||||
}
|
||||
|
||||
/** Plans the order for `tables`. A foreign key to a table outside the list (one the move does not copy) is ignored. */
|
||||
export function planCopyOrder(tables: readonly string[], foreignKeys: readonly ForeignKey[]): CopyPlan {
|
||||
const plan: CopyPlan = { order: [], deferred: new Map() };
|
||||
const known = new Set(tables);
|
||||
const pending = new Set([...tables].sort());
|
||||
const keys = foreignKeys.filter((fk) => known.has(fk.table) && known.has(fk.references));
|
||||
for (const fk of keys) if (fk.table === fk.references) defer(plan, fk);
|
||||
const between = keys.filter((fk) => fk.table !== fk.references);
|
||||
|
||||
while (pending.size > 0) {
|
||||
const waitsOn = (table: string) => between.filter((fk) => fk.table === table && pending.has(fk.references));
|
||||
let next = [...pending].find((table) => waitsOn(table).length === 0);
|
||||
if (next === undefined) {
|
||||
// A cycle: break it at the first table by name, deferring its keys into the rest of the cycle.
|
||||
next = [...pending][0];
|
||||
for (const fk of waitsOn(next)) defer(plan, fk);
|
||||
}
|
||||
plan.order.push(next);
|
||||
pending.delete(next);
|
||||
}
|
||||
return plan;
|
||||
}
|
||||
@@ -0,0 +1,226 @@
|
||||
import { SqliteSource, type SqliteColumn, type SqliteIndex } from '../../sqlite/sqlite-source';
|
||||
import { isPluginId, pluginSchemaName, quotePluginSchema } from '../plugin-schema';
|
||||
import { portableDefault } from '../schema-adjust';
|
||||
import { inOrder, quoteIdentifier, run, type CopiedSequence, type TableSpec, type Trx } from './copy';
|
||||
import type { ColumnKind } from './values';
|
||||
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
/**
|
||||
* A plugin's own database (`db:own`) moved from its `plugin.db` file into the
|
||||
* schema TREK gives it on Postgres (`plugin-schema.ts`), so a plugin finds its
|
||||
* rows where the Postgres store (`plugin-data-store.ts`) reads them.
|
||||
*
|
||||
* A plugin's tables are its own, created by its own SQL, so the move derives
|
||||
* each Postgres table from the SQLite one: the column's type from SQLite's
|
||||
* type affinity (and from the values it holds where the affinity leaves it
|
||||
* open), NOT NULL, the primary key, a default that has a Postgres spelling,
|
||||
* and the indexes over plain columns. The plugin's migration record
|
||||
* (`_plugin_migrations`) is copied as it is, so the plugin does not run its
|
||||
* migrations again over the copied tables. What has no Postgres counterpart
|
||||
* here (foreign keys between its tables, views, triggers, partial or
|
||||
* expression indexes, other defaults) is not created and is listed in the
|
||||
* summary. The file itself stays where it is, untouched.
|
||||
*/
|
||||
|
||||
/** The plugin store's own record of the migrations it ran, created exactly as the store creates it. */
|
||||
const LEDGER = '_plugin_migrations';
|
||||
const LEDGER_DDL = (schema: string) => `create table ${schema}.${LEDGER} (id text primary key, applied_at bigint)`;
|
||||
|
||||
/** The Postgres type the move gives each kind. */
|
||||
const PG_TYPE: Record<ColumnKind, string> = {
|
||||
integer: 'bigint',
|
||||
float: 'double precision',
|
||||
text: 'text',
|
||||
json: 'jsonb',
|
||||
bytes: 'bytea',
|
||||
};
|
||||
|
||||
/**
|
||||
* The kind of a plugin's column, by SQLite's affinity rules (the declared
|
||||
* type's text decides, in this order: INT, then CHAR/CLOB/TEXT, then BLOB or
|
||||
* none, then REAL/FLOA/DOUB, else NUMERIC). Where the affinity leaves the
|
||||
* storage open (none, or NUMERIC), the values the column holds decide, and
|
||||
* text is the answer that holds every one of them.
|
||||
*/
|
||||
export function pluginColumnKind(declaredType: string, storage: ReadonlySet<string>): ColumnKind {
|
||||
const declared = declaredType.toUpperCase();
|
||||
const only = (...classes: string[]) => storage.size > 0 && [...storage].every((value) => classes.includes(value));
|
||||
if (declared.includes('INT')) return 'integer';
|
||||
if (/CHAR|CLOB|TEXT/.test(declared)) return 'text';
|
||||
if (declared.includes('BLOB')) return only('blob', 'text') ? 'bytes' : 'text';
|
||||
if (/REAL|FLOA|DOUB/.test(declared)) return only('integer', 'real') || storage.size === 0 ? 'float' : 'text';
|
||||
if (only('integer')) return 'integer';
|
||||
if (only('integer', 'real')) return 'float';
|
||||
if (only('blob')) return 'bytes';
|
||||
return 'text';
|
||||
}
|
||||
|
||||
const NUMBER_LITERAL = /^[+-]?(\d+\.?\d*|\.\d+)(e[+-]?\d+)?$/i;
|
||||
const STRING_LITERAL = /^'(?:[^']|'')*'$/s;
|
||||
|
||||
/** The Postgres spelling of a column default, or null when it has none the move can trust. */
|
||||
export function pluginDefault(sql: string | null, kind: ColumnKind): string | null {
|
||||
if (sql === null) return null;
|
||||
const text = sql
|
||||
.trim()
|
||||
.replace(/^\((.*)\)$/s, '$1')
|
||||
.trim();
|
||||
const ported = portableDefault(text);
|
||||
if (ported !== text) return ported;
|
||||
if (/^null$/i.test(text)) return 'null';
|
||||
if (NUMBER_LITERAL.test(text)) return kind === 'text' ? `'${text}'` : text;
|
||||
if (/^(true|false)$/i.test(text)) return kind === 'integer' ? (/^true$/i.test(text) ? '1' : '0') : null;
|
||||
if (STRING_LITERAL.test(text)) return text;
|
||||
return null;
|
||||
}
|
||||
|
||||
/** One plugin's database as the move plans to copy it. */
|
||||
export interface PluginPlan {
|
||||
pluginId: string;
|
||||
file: string;
|
||||
schema: string;
|
||||
/** The DDL that creates its tables and indexes, in order. */
|
||||
ddl: string[];
|
||||
specs: TableSpec[];
|
||||
sequences: CopiedSequence[];
|
||||
/** What the move does not carry over, for the summary. */
|
||||
notCarried: string[];
|
||||
}
|
||||
|
||||
function columnDdl(column: SqliteColumn, kind: ColumnKind, identity: boolean, notes: string[], table: string): string {
|
||||
const parts = [quoteIdentifier(column.name), PG_TYPE[kind]];
|
||||
if (identity) parts.push('generated by default as identity');
|
||||
if (column.notNull && !identity) parts.push('not null');
|
||||
if (column.defaultSql !== null && !identity) {
|
||||
const value = pluginDefault(column.defaultSql, kind);
|
||||
if (value === null) notes.push(`the default ${column.defaultSql} of ${table}.${column.name}`);
|
||||
else parts.push(`default ${value}`);
|
||||
}
|
||||
return parts.join(' ');
|
||||
}
|
||||
|
||||
function indexDdl(index: SqliteIndex, target: string, notes: string[], table: string): string | null {
|
||||
if (index.origin === 'pk') return null;
|
||||
if (index.partial || index.columns === null) {
|
||||
notes.push(`the index ${index.name} on ${table} (partial or over an expression)`);
|
||||
return null;
|
||||
}
|
||||
const columns = index.columns.map(quoteIdentifier).join(', ');
|
||||
return `create ${index.unique ? 'unique ' : ''}index on ${target} (${columns})`;
|
||||
}
|
||||
|
||||
/** Plans the copy of one plugin's `plugin.db`: what to create in its schema and what to fill. */
|
||||
export function planPluginData(pluginId: string, source: SqliteSource): PluginPlan {
|
||||
const schemaName = pluginSchemaName(pluginId);
|
||||
const schema = quotePluginSchema(schemaName);
|
||||
const plan: PluginPlan = {
|
||||
pluginId,
|
||||
file: source.file,
|
||||
schema: schemaName,
|
||||
ddl: [`create schema ${schema}`],
|
||||
specs: [],
|
||||
sequences: [],
|
||||
notCarried: [],
|
||||
};
|
||||
for (const item of source.viewsAndTriggers()) plan.notCarried.push(`the ${item.type} ${item.name}`);
|
||||
const tables = source.tables();
|
||||
if (!tables.includes(LEDGER)) plan.ddl.push(LEDGER_DDL(schema));
|
||||
for (const table of tables) {
|
||||
const target = `${schema}.${quoteIdentifier(table)}`;
|
||||
const label = `plugin ${pluginId}: ${table}`;
|
||||
const columns = source.columns(table);
|
||||
if (table === LEDGER) {
|
||||
plan.ddl.push(LEDGER_DDL(schema));
|
||||
plan.specs.push({
|
||||
source: table,
|
||||
target,
|
||||
label,
|
||||
columns: [
|
||||
{ name: 'id', kind: 'text' },
|
||||
{ name: 'applied_at', kind: 'integer' },
|
||||
],
|
||||
deferred: [],
|
||||
primaryKey: ['id'],
|
||||
});
|
||||
continue;
|
||||
}
|
||||
const keys = columns.filter((column) => column.primaryKey > 0).sort((a, b) => a.primaryKey - b.primaryKey);
|
||||
const kinds = columns.map((column) =>
|
||||
pluginColumnKind(column.declaredType, source.storageClasses(table, column.name)),
|
||||
);
|
||||
// SQLite's rowid alias: the one INTEGER PRIMARY KEY column, which hands out its own ids.
|
||||
const rowid = keys.length === 1 && keys[0].declaredType.toUpperCase() === 'INTEGER' ? keys[0].name : null;
|
||||
const definitions = columns.map((column, index) =>
|
||||
columnDdl(column, kinds[index], column.name === rowid, plan.notCarried, table),
|
||||
);
|
||||
if (keys.length > 0) definitions.push(`primary key (${keys.map((key) => quoteIdentifier(key.name)).join(', ')})`);
|
||||
plan.ddl.push(`create table ${target} (${definitions.join(', ')})`);
|
||||
for (const index of source.indexes(table)) {
|
||||
const ddl = indexDdl(index, target, plan.notCarried, table);
|
||||
if (ddl) plan.ddl.push(ddl);
|
||||
}
|
||||
plan.specs.push({
|
||||
source: table,
|
||||
target,
|
||||
label,
|
||||
columns: columns.map((column, index) => ({ name: column.name, kind: kinds[index] })),
|
||||
deferred: [],
|
||||
primaryKey: keys.map((key) => key.name),
|
||||
});
|
||||
// The identity's sequence is named by Postgres; resolveIdentitySequences reads it once the table exists.
|
||||
if (rowid) plan.sequences.push({ table, target, column: rowid, sequence: '' });
|
||||
}
|
||||
return plan;
|
||||
}
|
||||
|
||||
/** A plugin's data file under the plugins' data directory, by plugin id. */
|
||||
interface PluginDataFile {
|
||||
pluginId: string;
|
||||
file: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* The `plugin.db` files under `root`, one per plugin directory. A directory
|
||||
* whose name is no plugin id cannot have a schema, and is reported instead.
|
||||
*/
|
||||
export function findPluginDataFiles(root: string): { files: PluginDataFile[]; skipped: string[] } {
|
||||
if (!fs.existsSync(root)) return { files: [], skipped: [] };
|
||||
const files: PluginDataFile[] = [];
|
||||
const skipped: string[] = [];
|
||||
for (const entry of fs.readdirSync(root, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
|
||||
const file = path.join(root, entry.name, 'plugin.db');
|
||||
if (!entry.isDirectory() || !fs.existsSync(file)) continue;
|
||||
if (isPluginId(entry.name)) files.push({ pluginId: entry.name, file });
|
||||
else skipped.push(file);
|
||||
}
|
||||
return { files, skipped };
|
||||
}
|
||||
|
||||
/** Creates a plugin's schema, tables and indexes in the move's transaction. */
|
||||
export async function createPluginSchema(trx: Trx, plan: PluginPlan): Promise<void> {
|
||||
await inOrder(plan.ddl, async (statement) => {
|
||||
try {
|
||||
await run(trx, statement);
|
||||
} catch (err) {
|
||||
throw new Error(
|
||||
`Postgres refused the table of plugin ${plan.pluginId} (${statement}): ${err instanceof Error ? err.message : String(err)}`,
|
||||
{ cause: err },
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** The plan's identity columns with the sequence Postgres gave each, read from the catalog. */
|
||||
export async function resolveIdentitySequences(trx: Trx, plan: PluginPlan): Promise<CopiedSequence[]> {
|
||||
const resolved: CopiedSequence[] = [];
|
||||
await inOrder(plan.sequences, async (entry) => {
|
||||
const [row] = await run<{ sequence: string | null }>(trx, 'select pg_get_serial_sequence($1, $2) as sequence', [
|
||||
entry.target,
|
||||
entry.column,
|
||||
]);
|
||||
if (row?.sequence) resolved.push({ ...entry, sequence: row.sequence });
|
||||
});
|
||||
return resolved;
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
import { nulFreeJson, stripNul } from '../../../nul-free';
|
||||
|
||||
import { createHash } from 'node:crypto';
|
||||
|
||||
/**
|
||||
* How a value read from a SQLite file becomes the value a Postgres column of
|
||||
* the move's target takes, and the one text form both sides are compared in.
|
||||
*
|
||||
* SQLite stores a value by what it is, not by the column's declared type, so
|
||||
* a column may hold text where the schema says integer. The move never
|
||||
* guesses: a value the Postgres column cannot hold exactly is refused with
|
||||
* the reason, and the move stops before it commits anything. The one
|
||||
* exception is a NUL character in text or JSON, which TREK stores on neither
|
||||
* engine (`db/nul-free.ts`): the move drops it, as every write does.
|
||||
*
|
||||
* The SQLite side is read with better-sqlite3's safe integers, so an integer
|
||||
* arrives as a `bigint` and keeps all 64 bits.
|
||||
*/
|
||||
|
||||
/** The Postgres column types the move writes, by what they hold. */
|
||||
export type ColumnKind = 'integer' | 'float' | 'text' | 'json' | 'bytes';
|
||||
|
||||
/** What a SQLite cell can be: NULL, INTEGER, REAL, TEXT or BLOB. */
|
||||
export type SqliteValue = null | bigint | number | string | Uint8Array;
|
||||
|
||||
/** A value Postgres takes as a parameter: a decimal string for an integer, a Buffer for bytes. */
|
||||
export type PostgresValue = null | string | number | Buffer;
|
||||
|
||||
type Converted = { ok: true; value: PostgresValue } | { ok: false; reason: string };
|
||||
|
||||
const INT64_MIN = -(2n ** 63n);
|
||||
const INT64_MAX = 2n ** 63n - 1n;
|
||||
const SAFE_MAX = BigInt(Number.MAX_SAFE_INTEGER);
|
||||
const DECIMAL_INTEGER = /^[+-]?\d+$/;
|
||||
const DECIMAL_NUMBER = /^[+-]?(\d+\.?\d*|\.\d+)(e[+-]?\d+)?$/i;
|
||||
|
||||
/**
|
||||
* The kind of a Postgres column, from `information_schema.columns.data_type`.
|
||||
* Null for a type the move has no rule for: the caller refuses the move then,
|
||||
* so a new column type fails loudly here instead of being copied by guess.
|
||||
*/
|
||||
export function columnKind(dataType: string): ColumnKind | null {
|
||||
switch (dataType) {
|
||||
case 'bigint':
|
||||
case 'integer':
|
||||
case 'smallint':
|
||||
return 'integer';
|
||||
case 'double precision':
|
||||
case 'real':
|
||||
return 'float';
|
||||
case 'text':
|
||||
case 'character varying':
|
||||
case 'character':
|
||||
return 'text';
|
||||
case 'json':
|
||||
case 'jsonb':
|
||||
return 'json';
|
||||
case 'bytea':
|
||||
return 'bytes';
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function refuse(reason: string): Converted {
|
||||
return { ok: false, reason };
|
||||
}
|
||||
|
||||
function describe(value: SqliteValue): string {
|
||||
if (value instanceof Uint8Array) return `a ${value.length}-byte BLOB`;
|
||||
if (typeof value === 'string')
|
||||
return `the text ${JSON.stringify(value.length > 40 ? `${value.slice(0, 40)}...` : value)}`;
|
||||
return `the value ${String(value)}`;
|
||||
}
|
||||
|
||||
function toInteger(value: Exclude<SqliteValue, null>): Converted {
|
||||
let whole: bigint;
|
||||
if (typeof value === 'bigint') whole = value;
|
||||
else if (typeof value === 'number') {
|
||||
if (!Number.isInteger(value)) return refuse(`${describe(value)} is not a whole number`);
|
||||
whole = BigInt(value);
|
||||
} else if (typeof value === 'string' && DECIMAL_INTEGER.test(value.trim())) {
|
||||
whole = BigInt(value.trim());
|
||||
} else {
|
||||
return refuse(`${describe(value)} is not a whole number`);
|
||||
}
|
||||
if (whole < INT64_MIN || whole > INT64_MAX) return refuse(`${describe(value)} does not fit in 64 bits`);
|
||||
return { ok: true, value: whole.toString() };
|
||||
}
|
||||
|
||||
function toFloat(value: Exclude<SqliteValue, null>): Converted {
|
||||
if (typeof value === 'number') return { ok: true, value };
|
||||
if (typeof value === 'bigint') {
|
||||
const number = Number(value);
|
||||
if (BigInt(number) !== value) return refuse(`${describe(value)} has more digits than a double holds`);
|
||||
return { ok: true, value: number };
|
||||
}
|
||||
if (typeof value === 'string' && DECIMAL_NUMBER.test(value.trim())) {
|
||||
const number = Number(value.trim());
|
||||
if (Number.isFinite(number)) return { ok: true, value: number };
|
||||
}
|
||||
return refuse(`${describe(value)} is not a number`);
|
||||
}
|
||||
|
||||
function toText(value: Exclude<SqliteValue, null>): Converted {
|
||||
if (typeof value === 'string') return { ok: true, value: stripNul(value) };
|
||||
if (typeof value === 'bigint' || typeof value === 'number') return { ok: true, value: String(value) };
|
||||
return refuse(`${describe(value)} is not text`);
|
||||
}
|
||||
|
||||
function toJson(value: Exclude<SqliteValue, null>): Converted {
|
||||
if (typeof value === 'bigint' || typeof value === 'number') return { ok: true, value: String(value) };
|
||||
if (typeof value !== 'string') return refuse(`${describe(value)} is not JSON text`);
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(value);
|
||||
} catch {
|
||||
return refuse(`${describe(value)} is not valid JSON`);
|
||||
}
|
||||
// Valid JSON holds a NUL only escaped, which jsonb refuses as well: the value is written again without it.
|
||||
return { ok: true, value: value.includes('\\u0000') ? JSON.stringify(nulFreeJson(parsed)) : value };
|
||||
}
|
||||
|
||||
function toBytes(value: Exclude<SqliteValue, null>): Converted {
|
||||
if (value instanceof Uint8Array) return { ok: true, value: Buffer.from(value) };
|
||||
// A text value in a BLOB column: its UTF-8 bytes, what SQLite's CAST(x AS BLOB) answers.
|
||||
if (typeof value === 'string') return { ok: true, value: Buffer.from(value, 'utf8') };
|
||||
return refuse(`${describe(value)} is not a BLOB`);
|
||||
}
|
||||
|
||||
/** `value` as the Postgres column of `kind` takes it, or the reason it cannot hold it exactly. */
|
||||
export function convertValue(value: SqliteValue, kind: ColumnKind): Converted {
|
||||
if (value === null) return { ok: true, value: null };
|
||||
switch (kind) {
|
||||
case 'integer':
|
||||
return toInteger(value);
|
||||
case 'float':
|
||||
return toFloat(value);
|
||||
case 'text':
|
||||
return toText(value);
|
||||
case 'json':
|
||||
return toJson(value);
|
||||
case 'bytes':
|
||||
return toBytes(value);
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether an integer value read back would be beyond what TREK's Postgres driver reads (2^53). */
|
||||
export function beyondSafeInteger(value: PostgresValue): boolean {
|
||||
if (typeof value !== 'string' || !DECIMAL_INTEGER.test(value)) return false;
|
||||
const whole = BigInt(value);
|
||||
return whole > SAFE_MAX || whole < -SAFE_MAX;
|
||||
}
|
||||
|
||||
/** JSON text with its object keys sorted, so two spellings of one value compare equal (jsonb reorders keys). */
|
||||
export function stableJson(text: string): string {
|
||||
const sort = (value: unknown): unknown => {
|
||||
if (Array.isArray(value)) return value.map(sort);
|
||||
if (value !== null && typeof value === 'object') {
|
||||
return Object.fromEntries(
|
||||
Object.keys(value)
|
||||
.sort()
|
||||
.map((key) => [key, sort((value as Record<string, unknown>)[key])]),
|
||||
);
|
||||
}
|
||||
return value;
|
||||
};
|
||||
return JSON.stringify(sort(JSON.parse(text)));
|
||||
}
|
||||
|
||||
/**
|
||||
* The text a value is compared in, from the value the move sent to Postgres.
|
||||
* `canonicalFromPostgres` must answer the same for what Postgres stored.
|
||||
*/
|
||||
export function canonicalFromSent(value: PostgresValue, kind: ColumnKind): string | null {
|
||||
if (value === null) return null;
|
||||
switch (kind) {
|
||||
case 'integer':
|
||||
return BigInt(String(value)).toString();
|
||||
case 'float':
|
||||
return String(Number(value));
|
||||
case 'text':
|
||||
return String(value);
|
||||
case 'json':
|
||||
return stableJson(String(value));
|
||||
case 'bytes':
|
||||
return Buffer.isBuffer(value) ? value.toString('hex') : Buffer.from(String(value), 'utf8').toString('hex');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The text a value is compared in, from the column read back as `::text`
|
||||
* (with `bytea_output = hex`, so bytes read as `\x` and their hex digits).
|
||||
*/
|
||||
export function canonicalFromPostgres(text: string | null, kind: ColumnKind): string | null {
|
||||
if (text === null) return null;
|
||||
switch (kind) {
|
||||
case 'integer':
|
||||
return BigInt(text).toString();
|
||||
case 'float':
|
||||
return String(Number(text));
|
||||
case 'text':
|
||||
return text;
|
||||
case 'json':
|
||||
return stableJson(text);
|
||||
case 'bytes':
|
||||
return text.startsWith('\\x') ? text.slice(2).toLowerCase() : text;
|
||||
}
|
||||
}
|
||||
|
||||
const CHECKSUM_MODULUS = 2n ** 256n;
|
||||
|
||||
/**
|
||||
* An order-free checksum over a table's rows: the sum of each row's SHA-256
|
||||
* modulo 2^256. Postgres and SQLite need not hand the rows back in the same
|
||||
* order (their collations differ), and a row that is missing, added, doubled
|
||||
* or changed changes the sum.
|
||||
*/
|
||||
export class TableChecksum {
|
||||
private sum = 0n;
|
||||
rows = 0;
|
||||
|
||||
add(canonicalRow: ReadonlyArray<string | null>): void {
|
||||
const digest = createHash('sha256').update(JSON.stringify(canonicalRow)).digest('hex');
|
||||
this.sum = (this.sum + BigInt(`0x${digest}`)) % CHECKSUM_MODULUS;
|
||||
this.rows++;
|
||||
}
|
||||
|
||||
hex(): string {
|
||||
return this.sum.toString(16).padStart(64, '0');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
|
||||
/** The sslmode values that verify the server, read the way the `pg` driver reads them. */
|
||||
const VERIFYING_MODES = new Set(['require', 'verify-ca', 'verify-full']);
|
||||
|
||||
/** The `ssl` option of a `pg` pool, as `sslOptionFor` builds it. */
|
||||
type PgSslOption = false | { rejectUnauthorized: true; ca?: string };
|
||||
|
||||
/**
|
||||
* The `ssl` option for the pool, from the URL's `sslmode` and `sslrootcert`.
|
||||
*
|
||||
* MikroORM builds the pool from the URL's host, port, user, password and
|
||||
* database alone and drops the rest of the query, so an `sslmode` in
|
||||
* `TREK_DB_URL` would be ignored without this. `require`, `verify-ca` and
|
||||
* `verify-full` all verify the server's certificate, as the `pg` driver itself
|
||||
* treats them; `disable` turns SSL off, and no `sslmode` leaves the driver's
|
||||
* default (no SSL). A mode that would connect without verifying (`prefer`,
|
||||
* `allow`, `no-verify`) or that is misspelt refuses, rather than quietly
|
||||
* connecting with less than was asked. `sslrootcert` names the CA file a host
|
||||
* that signs its own certificates needs (Supabase's, say).
|
||||
*/
|
||||
export function sslOptionFor(url: string): PgSslOption | undefined {
|
||||
const params = new URL(url).searchParams;
|
||||
const mode = params.get('sslmode');
|
||||
const rootCert = params.get('sslrootcert');
|
||||
if (mode === null) {
|
||||
if (rootCert !== null) throw new Error('TREK_DB_URL names an sslrootcert without sslmode=verify-full.');
|
||||
return undefined;
|
||||
}
|
||||
if (mode === 'disable') return false;
|
||||
if (!VERIFYING_MODES.has(mode)) {
|
||||
throw new Error(
|
||||
`TREK_DB_URL has sslmode "${mode}"; use disable, require, verify-ca or verify-full (all but disable verify the server).`,
|
||||
);
|
||||
}
|
||||
if (rootCert === null) return { rejectUnauthorized: true };
|
||||
try {
|
||||
return { rejectUnauthorized: true, ca: readFileSync(rootCert, 'utf8') };
|
||||
} catch (error) {
|
||||
throw new Error(`TREK_DB_URL names sslrootcert ${rootCert}, which cannot be read.`, { cause: error });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
* A connection URL fit for a log line: the password masked and the query
|
||||
* dropped, since libpq reads a password from the query too
|
||||
* (`?password=...`). A value that does not parse is not echoed at all.
|
||||
*/
|
||||
export function redactUrl(url: string): string {
|
||||
let parsed: URL;
|
||||
try {
|
||||
parsed = new URL(url);
|
||||
} catch {
|
||||
return '<unparseable URL>';
|
||||
}
|
||||
if (parsed.password) parsed.password = '***';
|
||||
parsed.search = '';
|
||||
parsed.hash = '';
|
||||
return parsed.toString();
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { closeDb, getRawConnection, registerReinitializeHook, reinitialize } from '../../database';
|
||||
import { resolveDbPath } from '../../db-path';
|
||||
import { runSchemaBootstrap, type AnyOrm } from '../../orm';
|
||||
import { SharedSqliteDriver } from '../../orm-driver';
|
||||
import type { DatabaseEngine } from '../engine';
|
||||
import type { EntityManager } from '@mikro-orm/core';
|
||||
|
||||
/**
|
||||
* The SQLite file engine, TREK's default: one better-sqlite3 handle that
|
||||
* `db/database.ts` owns and the ORM's bound driver shares (`db/orm-driver.ts`),
|
||||
* on `TREK_DB_FILE` or `data/travel.db` (`:memory:` under test). A restore
|
||||
* swaps the file and reopens the handle; the schema comes from the migration
|
||||
* chain (`db/orm.ts`).
|
||||
*/
|
||||
export class SqliteEngine implements DatabaseEngine {
|
||||
readonly id = 'sqlite';
|
||||
|
||||
describe(): string {
|
||||
return `SQLite file ${resolveDbPath()}`;
|
||||
}
|
||||
|
||||
ormOptions() {
|
||||
return { driver: SharedSqliteDriver, dbName: resolveDbPath() };
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens the file (normally a no-op: the ORM's first connect inside
|
||||
* NestFactory.create() already did, said here so the boot does not depend on
|
||||
* that), and registers the reopen. A reopen swaps the file under the same
|
||||
* handle, which Kysely caches, so the ORM's connection is closed and connected
|
||||
* again first: the driver then reaches the new handle through
|
||||
* `createKyselyDialect()`. The bound driver's `destroy()` is a no-op
|
||||
* (`orm-driver.ts`), so the close never reaches the handle `db/database.ts` owns.
|
||||
*/
|
||||
open(orm: AnyOrm, onReopened: () => Promise<void>): void {
|
||||
getRawConnection();
|
||||
registerReinitializeHook(async () => {
|
||||
const connection = orm.em.getConnection();
|
||||
await connection.close(true);
|
||||
await connection.connect();
|
||||
await onReopened();
|
||||
});
|
||||
}
|
||||
|
||||
close(): void {
|
||||
closeDb();
|
||||
}
|
||||
|
||||
reopen(): Promise<void> {
|
||||
return reinitialize();
|
||||
}
|
||||
|
||||
schemaBootstrap(orm: AnyOrm, options: { snapshot: boolean }): Promise<void> {
|
||||
return runSchemaBootstrap(orm, options);
|
||||
}
|
||||
|
||||
/** A no-op: SQLite has one connection and one writer, so its transactions already run one at a time. */
|
||||
serializeWrites(_em: EntityManager): Promise<void> {
|
||||
return Promise.resolve();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import type { EntityManager } from '@mikro-orm/core';
|
||||
|
||||
/**
|
||||
* The SQLite engine's whole-file maintenance: the two statements a backup,
|
||||
* a restore and the demo reset need that are about the database file rather
|
||||
* than any table (`PRAGMA wal_checkpoint`, `VACUUM INTO`). Neither has a
|
||||
* Postgres spelling, so they live under the engine that owns the file instead
|
||||
* of in `MaintenanceRepository`, whose remaining statements run on every
|
||||
* engine (and which the Postgres probe calls method by method).
|
||||
*
|
||||
* Provided through Nest DI by `MaintenanceModule` (`nest/database/`), a
|
||||
* factory over the context-resolving global `EntityManager`, and injected by
|
||||
* the SQLite backup port (`SqliteDatabaseBackup`). Free of Nest decorators
|
||||
* like every other file under `db/`, so a test can build one over its own
|
||||
* `EntityManager`.
|
||||
*/
|
||||
export class SqliteMaintenance {
|
||||
constructor(private readonly em: EntityManager) {}
|
||||
|
||||
/**
|
||||
* MikroORM's own validating `getContext()`: throws outside a request
|
||||
* context, the fail-closed check `TrekRepository` applies to every
|
||||
* repository, since a raw `connection.execute()` has no such guard.
|
||||
*/
|
||||
private validateRequestContext(): void {
|
||||
this.em.getContext();
|
||||
}
|
||||
|
||||
/**
|
||||
* `PRAGMA wal_checkpoint(TRUNCATE)`: flushes the WAL into the main file
|
||||
* before a snapshot or a swap. Reached through the backup port's
|
||||
* `checkpoint()`; every caller treats it as best effort.
|
||||
*/
|
||||
async walCheckpoint(): Promise<void> {
|
||||
this.validateRequestContext();
|
||||
await this.em.getConnection().execute('PRAGMA wal_checkpoint(TRUNCATE)');
|
||||
}
|
||||
|
||||
/**
|
||||
* `` VACUUM INTO '<path>' ``: a consistent point-in-time copy of the file
|
||||
* under concurrent writers, reached through the backup port's
|
||||
* `snapshot()`. Single quotes in `path` are escaped by doubling.
|
||||
*/
|
||||
async vacuumInto(path: string): Promise<void> {
|
||||
this.validateRequestContext();
|
||||
const escaped = path.replaceAll("'", "''");
|
||||
await this.em.getConnection().execute(`VACUUM INTO '${escaped}'`);
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user