forge
Explore
Log in

Don't you dare go Hollow

Compose-stack deploy plus in-tree schema work

Browse files at this commit

57fad2c07b2395b558338e2c6a912aa9a736aa69Ahmet Kaan GümüşParent: 804bd3c
  • feat
    • compose-stack deploy plus in-tree schema work
Show full message
✨ feat: compose-stack deploy plus in-tree schema work

Production deploy is podman compose (postgres + backend + openobserve)
instead of a systemd binary. CI stays a throwaway postgres sidecar.
Operator credentials live in ~/hezarfen_backend/hezarfen_backend.env
(0600); the deploy never writes that file.

Also lands the working-tree schema/junction and .sqlx updates that were
already sitting next to this change.

156 changed files +3966 -2842

.github/workflows/main.ymlmodified+218 -106
@@ -1,30 +1,39 @@
1-# VPS deploy, im-style, split into two jobs so failure recovery is cheap:1+# VPS deploy, compose-style, split into two jobs so failure recovery is cheap:
2 #2 #
3 # Build and test — Postgres sidecar, clippy, the whole suite, the release3 # Build and test — Postgres sidecar, clippy, the whole suite, the release
4-# build; uploads the staged release as the run's artifact.4+# build; packs the stripped binary + migrations into the
5-# Deploy — SSH release-dir swap + systemd user-unit restart,5+# runtime image (deploy/Containerfile.runtime) and
6-# /health gated on THIS build's process, rollback on6+# uploads the image tarball + compose files as the run's
7-# failure, independent after-the-fact verify.7+# artifact.
8+# Deploy — SSH: podman load the image, point the deploy-owned
9+# stack.env's HEZARFEN_TAG at it, install compose.yaml +
10+# the hezarfen-compose user unit + the backup script,
11+# restart the stack, /health-gated rollback to the
12+# previous tag, independent after-the-fact verify.
8 #13 #
9 # The split is the recovery story, not ceremony:14 # The split is the recovery story, not ceremony:
10 # * "Re-run failed jobs" on a run whose Deploy step failed re-runs ONLY the15 # * "Re-run failed jobs" on a run whose Deploy step failed re-runs ONLY the
11-# ~1-minute deploy job — the built release is still in the run's artifact.16+# ~1-minute deploy job — the built image is still in the run's artifact.
12 # * workflow_dispatch (the manual door: Actions tab → Run workflow on main,17 # * workflow_dispatch (the manual door: Actions tab → Run workflow on main,
13 # or `gh workflow run main.yml --ref main`) deploys WITHOUT the suite: it18 # or `gh workflow run main.yml --ref main`) deploys WITHOUT the suite: it
14 # takes the newest artifact a green Build-and-test produced — which can19 # takes the newest artifact a green Build-and-test produced — which can
15 # lag HEAD while a push is mid-CI, and that is the point: redeploy the20 # lag HEAD while a push is mid-CI, and that is the point: redeploy the
16-# known-good release, e.g. after a server-side fix (env file, proxy,21+# known-good image, e.g. after a server-side fix (env file, proxy,
17 # database). For env-only changes a plain22 # database). For env-only changes a plain
18-# `ssh <vps> 'systemctl --user restart hezarfen'` needs no workflow at23+# `ssh <vps> 'systemctl --user restart hezarfen-compose'` needs no
19-# all: the process reads its env at boot.24+# workflow at all: the stack re-reads its env files on the next
25+# `podman compose up`.
20 #26 #
21 # One-time prerequisites, outside the workflow's reach:27 # One-time prerequisites, outside the workflow's reach:
22-# * the repo secrets SSH_PRIVATE_KEY / SSH_HOST / SSH_USER (im's values28+# * the repo secrets SSH_PRIVATE_KEY / SSH_HOST / SSH_USER;
23-# work if this deploys as the same user);
24 # * `loginctl enable-linger <user>` on the server unless the deploy user29 # * `loginctl enable-linger <user>` on the server unless the deploy user
25-# already has it (im's does) — user units need a running user manager;30+# already has it — user units need a running user manager;
26-# * a Postgres the backend can reach, and ~/hezarfen_backend/hezarfen_backend.env (0600)31+# * podman plus a compose provider on the server (the deploy checks for
27-# with at least DATABASE_URL — see deploy/hezarfen.service for the keys.32+# both and fails with a one-line install hint);
33+# * the operator's ~/hezarfen_backend/hezarfen_backend.env (0600), written
34+# once by hand from deploy/hezarfen_backend.env.example — at minimum the
35+# POSTGRES_PASSWORD and BUILDER_PASSWORD lines. The deploy never
36+# creates or overwrites it.
28 37
29 name: VPS deploy38 name: VPS deploy
30 39
@@ -35,30 +44,34 @@ on:
35 # The manual redeploy door — see the header comment for how and why.44 # The manual redeploy door — see the header comment for how and why.
36 workflow_dispatch:45 workflow_dispatch:
37 46
38-# One deploy at a time: the deploy swaps a release directory and restarts one47+# One deploy at a time: the deploy reloads one compose stack; two of them
39-# service; two of them racing would leave the binary and the running process48+# racing would interleave container recreations and could leave the served
40-# from different builds. A dispatched redeploy queues behind any in-flight49+# image and the tag files from different builds. A dispatched redeploy
41-# push deploy rather than racing it.50+# queues behind any in-flight push deploy rather than racing it.
42 concurrency:51 concurrency:
43 group: deploy52 group: deploy
44 cancel-in-progress: false53 cancel-in-progress: false
45 54
46 env:55 env:
47- # A gnu binary links against the runner's glibc, so the runner is pinned56+ # A gnu binary links against the toolchain's glibc, so the runner is
48- # (see runs-on below) to the same 24.04 the server runs; the day either57+ # pinned (see runs-on below) to 24.04, and the runtime image is
49- # side moves, the pin is what forces a conscious decision rather than a58+ # debian:trixie-slim: move either side without thinking and the binary
50- # broken deploy. In exchange: no cross-toolchain, and the linker is59+ # stops loading inside the container. The pin is what forces a conscious
51- # rustc's default bundled lld.60+ # decision rather than a broken deploy. In exchange: no cross-toolchain,
61+ # and the linker is rustc's default bundled lld.
52 TARGET: x86_64-unknown-linux-gnu62 TARGET: x86_64-unknown-linux-gnu
53- # The systemd user unit that owns the process. See deploy/hezarfen.service.63+ # The systemd user unit that wraps `podman compose`. See
54- SERVICE: hezarfen64+ # deploy/hezarfen-compose.service.
65+ SERVICE: hezarfen-compose
55 # The deploy lives in this subdirectory of the SSH user's home. The home66 # The deploy lives in this subdirectory of the SSH user's home. The home
56 # itself is resolved on the server ($HOME), so switching the deploy user67 # itself is resolved on the server ($HOME), so switching the deploy user
57 # moves the path with it — a baked-in absolute path once kept pointing at68 # moves the path with it — a baked-in absolute path once kept pointing at
58 # the previous user's home and failed the deploy on permissions.69 # the previous user's home and failed the deploy on permissions.
59 DEPLOY_SUBDIR: hezarfen_backend70 DEPLOY_SUBDIR: hezarfen_backend
60- # The unit reads its secrets from this file on the server; the deploy71+ # Compose interpolates its secrets from this file on the server (passed
61- # never writes it, only checks it exists and holds DATABASE_URL.72+ # as --env-file, and to the backend container as env_file). The deploy
73+ # never writes it, only checks it exists and carries the
74+ # POSTGRES_PASSWORD / BUILDER_PASSWORD lines prod must not run without.
62 ENV_FILE_NAME: hezarfen_backend.env75 ENV_FILE_NAME: hezarfen_backend.env
63 # The Postgres the test suite mints its per-test databases on. Credentials76 # The Postgres the test suite mints its per-test databases on. Credentials
64 # and port match the harness default (HEZARFEN_TEST_DATABASE_URL), so the77 # and port match the harness default (HEZARFEN_TEST_DATABASE_URL), so the
@@ -77,9 +90,9 @@ jobs:
77 # Pushes only: a manual redeploy reuses the newest green artifact90 # Pushes only: a manual redeploy reuses the newest green artifact
78 # instead of paying the suite again.91 # instead of paying the suite again.
79 if: github.event_name == 'push'92 if: github.event_name == 'push'
80- # Pinned, not `latest`: ubuntu-latest floating to the next LTS would93+ # Pinned, not `latest`: the gnu build links the runner's glibc and the
81- # one day ship a glibc newer than the server's, and the gnu binary94+ # runtime image is debian:trixie-slim — float either side carelessly
82- # would stop running there. See the TARGET comment above.95+ # and the binary stops loading. See the TARGET comment above.
83 runs-on: ubuntu-24.0496 runs-on: ubuntu-24.04
84 env:97 env:
85 # The 41 test binaries each link the full tonic/otlp/axum/sqlx stack;98 # The 41 test binaries each link the full tonic/otlp/axum/sqlx stack;
@@ -155,12 +168,36 @@ jobs:
155 cp "target/$TARGET/release/hezarfen_backend" stage/hezarfen_backend168 cp "target/$TARGET/release/hezarfen_backend" stage/hezarfen_backend
156 # The migrators resolve `migrations/` beside the binary when the169 # The migrators resolve `migrations/` beside the binary when the
157 # compile-time checkout path is absent (see migrations_path), so170 # compile-time checkout path is absent (see migrations_path), so
158- # the schema ships with the release it belongs to.171+ # the schema ships inside the image, next to /app/hezarfen_backend.
159 cp -r migrations stage/migrations172 cp -r migrations stage/migrations
160- cp deploy/hezarfen.service stage/hezarfen.service
161 strip stage/hezarfen_backend173 strip stage/hezarfen_backend
162 ls -l stage174 ls -l stage
163 175
176+ - name: Build the runtime image
177+ run: |
178+ set -euo pipefail
179+ # Pack the already-built, already-stripped gnu binary into the
180+ # runtime image. Never build from source here: a second rust
181+ # compile blows the runner's disk.
182+ docker build -f deploy/Containerfile.runtime -t localhost/hezarfen-backend:$GITHUB_SHA stage/
183+ docker save localhost/hezarfen-backend:$GITHUB_SHA | gzip > stage/hezarfen-backend.tar.gz
184+
185+ - name: Stage the compose bundle
186+ run: |
187+ set -euo pipefail
188+ cp compose.yaml deploy/hezarfen-compose.service deploy/backup-postgres.sh stage/
189+ echo -n "$GITHUB_SHA" > stage/tag
190+ # Everything the deploy installs on the server must be here; a
191+ # missing piece fails here, on the runner, not mid-deploy on the
192+ # VPS. The raw binary and migrations may linger as docker build
193+ # context — they are no longer load-bearing.
194+ test -f stage/hezarfen-backend.tar.gz
195+ test -f stage/compose.yaml
196+ test -f stage/hezarfen-compose.service
197+ test -f stage/backup-postgres.sh
198+ test -f stage/tag
199+ ls -l stage
200+
164 # The deploy job (and, later, a manual redeploy) consumes this. 30201 # The deploy job (and, later, a manual redeploy) consumes this. 30
165 # days is also the dispatch door's reach-back window: an older green202 # days is also the dispatch door's reach-back window: an older green
166 # build's artifact is gone, and the redeploy fails loudly instead of203 # build's artifact is gone, and the redeploy fails loudly instead of
@@ -226,12 +263,16 @@ jobs:
226 run-id: ${{ env.run_id }}263 run-id: ${{ env.run_id }}
227 github-token: ${{ github.token }}264 github-token: ${{ github.token }}
228 265
266+ # The dispatch path downloads a possibly-days-old artifact; re-check
267+ # the bundle is whole before pointing any of it at the server.
229 - name: Check the release is complete268 - name: Check the release is complete
230 run: |269 run: |
231 set -euo pipefail270 set -euo pipefail
232- test -f stage/hezarfen_backend271+ test -f stage/hezarfen-backend.tar.gz
233- test -d stage/migrations/control272+ test -f stage/compose.yaml
234- test -f stage/hezarfen.service273+ test -f stage/hezarfen-compose.service
274+ test -f stage/backup-postgres.sh
275+ test -f stage/tag
235 276
236 - name: Install SSH keys277 - name: Install SSH keys
237 run: |278 run: |
@@ -260,19 +301,19 @@ jobs:
260 ;;301 ;;
261 esac302 esac
262 deploy_path=$HOME/$1303 deploy_path=$HOME/$1
263- # The deploy path is the service's working tree: hezarfen_backend.env and304+ # The deploy path holds the operator's hezarfen_backend.env, the
264- # data/ live there and are never touched from here. Only 'current'305+ # compose files and the tag files; nothing in it is deleted
265- # is replaced.306+ # wholesale, ever.
266 mkdir -p -- "$deploy_path"307 mkdir -p -- "$deploy_path"
267- rm -rf -- "$deploy_path/current.new"
268- mkdir -p -- "$deploy_path/current.new"
269 REMOTE308 REMOTE
270- # stdin carries the tarball, so the script cannot; the extraction309+ # stdin carries the bundle, so the script cannot; the extraction
271 # still goes through bash -c because the login shell is not bash310 # still goes through bash -c because the login shell is not bash
272- # and would not expand $HOME.311+ # and would not expand $HOME. Only the five deploy files ship —
273- tar -C stage -czf - . | ssh "$ssh_target" "bash -c 'exec tar -xzf - -C \"\$HOME/\$1/current.new\"' -- '$DEPLOY_SUBDIR'"312+ # the raw binary and migrations stay on the runner (they were
313+ # docker build context, nothing more).
314+ tar -C stage -czf - hezarfen-backend.tar.gz compose.yaml hezarfen-compose.service backup-postgres.sh tag | ssh "$ssh_target" "bash -c 'exec tar -xzf - -C \"\$HOME/\$1\"' -- '$DEPLOY_SUBDIR'"
274 315
275- - name: Swap and restart316+ - name: Load the image and restart the stack
276 run: |317 run: |
277 set -euo pipefail318 set -euo pipefail
278 ssh_target="${{ secrets.SSH_USER }}@${{ secrets.SSH_HOST }}"319 ssh_target="${{ secrets.SSH_USER }}@${{ secrets.SSH_HOST }}"
@@ -285,72 +326,139 @@ jobs:
285 service=$2326 service=$2
286 env_file=$deploy_path/$3327 env_file=$deploy_path/$3
287 export XDG_RUNTIME_DIR=/run/user/$(id -u)328 export XDG_RUNTIME_DIR=/run/user/$(id -u)
329+ # compose.yaml is resolved from the working directory: the unit's
330+ # ExecStart carries WorkingDirectory, but the rollback compose up
331+ # and a first-deploy down run from right here.
332+ cd -- "$deploy_path"
333+
288 # Read before anything moves: the env file is the operator's, on334 # Read before anything moves: the env file is the operator's, on
289- # the server, written once (see deploy/hezarfen.service for the335+ # the server, written once by hand (see
290- # keys). A missing file or a missing DATABASE_URL is a failure to336+ # deploy/hezarfen_backend.env.example for the keys). The deploy
291- # stop on, not one to roll back from.337+ # never creates or overwrites it. The password and OpenObserve lines
338+ # are load-bearing: without them compose would silently run the stack
339+ # on its laptop defaults.
292 if [ ! -f "$env_file" ]; then340 if [ ! -f "$env_file" ]; then
293- echo "missing $env_file — create it (0600) with at least DATABASE_URL; see deploy/hezarfen.service" >&2341+ echo "missing $env_file — create it (0600) from deploy/hezarfen_backend.env.example" >&2
294 exit 1342 exit 1
295 fi343 fi
296 chmod 0600 -- "$env_file"344 chmod 0600 -- "$env_file"
297- if ! grep -q '^DATABASE_URL=' "$env_file"; then345+ for key in POSTGRES_PASSWORD BUILDER_PASSWORD ZO_ROOT_USER_EMAIL ZO_ROOT_USER_PASSWORD; do
298- echo "no DATABASE_URL in $env_file" >&2346+ grep -Eq "^${key}=.+" "$env_file" || {
347+ echo "no non-empty ${key}= line in $env_file — prod must not run on the compose defaults" >&2
348+ exit 1
349+ }
350+ done
351+
352+ # Rootless podman plus a compose provider; fail with the fix, not
353+ # a bare command-not-found three steps in.
354+ command -v podman >/dev/null || {
355+ echo "podman not found — install podman and a compose provider (e.g. dnf install podman podman-compose)" >&2
299 exit 1356 exit 1
357+ }
358+ podman compose version >/dev/null 2>&1 || {
359+ echo "'podman compose' unavailable — install a compose provider (podman-compose or docker-compose)" >&2
360+ exit 1
361+ }
362+
363+ # Load THIS build's image and read the tag the build stamped into
364+ # it (build time and deploy time must agree on what is shipping).
365+ gunzip -c "$deploy_path/hezarfen-backend.tar.gz" | podman load
366+ tag=$(cat -- "$deploy_path/tag")
367+
368+ # Tag rotation: previous_tag is the rollback target (absent on a
369+ # first deploy); current_tag records what should now be running.
370+ if [ -f "$deploy_path/current_tag" ]; then
371+ cp -- "$deploy_path/current_tag" "$deploy_path/previous_tag"
300 fi372 fi
301- # The unit defaults to 7656; the env file may override.373+ printf '%s\n' "$tag" > "$deploy_path/current_tag"
302- port=$(sed -n 's/^PORT=\([0-9][0-9]*\)$/\1/p' "$env_file" | tail -n1)374+
303- port=${port:-7656}375+ # stack.env is deploy-owned (unlike the secrets file): it carries
304- mkdir -p -- "$deploy_path/data/files"376+ # only the image tag, and --env-file order makes it win over the
305- chmod +x -- "$deploy_path/current.new/hezarfen_backend"377+ # operator's file for HEZARFEN_TAG.
306- rm -rf -- "$deploy_path/current.previous"378+ printf 'HEZARFEN_TAG=%s\n' "$tag" > "$deploy_path/stack.env"
307- if [ -e "$deploy_path/current" ]; then379+
308- mv -- "$deploy_path/current" "$deploy_path/current.previous"380+ # The freshly extracted bundle: compose file and unit are
309- fi381+ # world-readable, the backup script is run by hand or a timer.
310- mv -- "$deploy_path/current.new" "$deploy_path/current"382+ chmod 0644 -- "$deploy_path/compose.yaml" "$deploy_path/hezarfen-compose.service"
383+ chmod 0755 -- "$deploy_path/backup-postgres.sh"
384+ # The image tarball was only a transport; the image is loaded into
385+ # podman's storage now.
386+ rm -f -- "$deploy_path/hezarfen-backend.tar.gz"
387+
388+ compose_up() {
389+ podman compose --env-file "$env_file" --env-file "$deploy_path/stack.env" up -d --no-build
390+ }
391+ rollback() {
392+ if [ -f "$deploy_path/previous_tag" ]; then
393+ prev=$(cat -- "$deploy_path/previous_tag")
394+ printf 'HEZARFEN_TAG=%s\n' "$prev" > "$deploy_path/stack.env"
395+ printf '%s\n' "$prev" > "$deploy_path/current_tag"
396+ compose_up
397+ echo "rolled back to $prev" >&2
398+ else
399+ # First deploy: nothing to roll back to, so stop the
400+ # half-brought-up stack. Plain down — the volumes hold the
401+ # operator's data and postgres's first-boot password.
402+ podman compose --env-file "$env_file" --env-file "$deploy_path/stack.env" down
403+ echo 'first deploy failed; stack stopped, volumes kept' >&2
404+ fi
405+ }
406+
311 # The unit ships with the release: a freshly provisioned box has407 # The unit ships with the release: a freshly provisioned box has
312 # no unit until the first deploy writes it, and a changed unit408 # no unit until the first deploy writes it, and a changed unit
313- # lands with the code that needs it. Enabling is idempotent.409+ # lands with the compose file that needs it.
314 mkdir -p -- "$HOME/.config/systemd/user"410 mkdir -p -- "$HOME/.config/systemd/user"
315- install -m 644 -- "$deploy_path/current/hezarfen.service" "$HOME/.config/systemd/user/$service.service"411+ install -m 0644 -- "$deploy_path/hezarfen-compose.service" "$HOME/.config/systemd/user/$service.service"
316 systemctl --user daemon-reload412 systemctl --user daemon-reload
413+ # Retire the binary-era unit: disable it (absent on fresh boxes)
414+ # and drop its unit file so it can never come back at boot.
415+ systemctl --user disable --now hezarfen.service 2>/dev/null || true; rm -f -- "$HOME/.config/systemd/user/hezarfen.service"
416+
417+ # The unit is a oneshot with RemainAfterExit, so `start` on the
418+ # active (exited) unit would be a no-op — every deploy restarts
419+ # to re-run ExecStart. A failed restart (bad interpolation, a
420+ # provider hiccup) must still reach the health gate below: it
421+ # decides between rollback and success.
317 systemctl --user enable -- "$service"422 systemctl --user enable -- "$service"
318- systemctl --user restart "$service"423+ systemctl --user restart "$service" || true
319- # The unit is Type=simple, so a restart returns before the new424+
320- # process has bound its port — and before an old one has let go425+ # The oneshot returns before the containers have bound their
321- # of it. Wait for the health route rather than a clock: /health426+ # ports. Wait for the health route rather than a clock: /health
322 # answers 503 (curl -f fails) while the database is unreachable,427 # answers 503 (curl -f fails) while the database is unreachable,
323- # so a 200 here already means status "ok".428+ # so a 200 whose body says "status":"ok" means the new stack is
324- rollback() {429+ # truly serving. 90 attempts, not 30: a first deploy also pulls
325- rm -rf -- "$deploy_path/current"430+ # the postgres and observability base images.
326- mv -- "$deploy_path/current.previous" "$deploy_path/current"431+ health_ok=0
327- systemctl --user restart "$service"432+ for _ in $(seq 1 90); do
328- }433+ served=$(curl -fsS http://127.0.0.1:7656/health 2>/dev/null) || true
329- for _ in $(seq 1 30); do434+ case "$served" in
330- served=$(curl -fsS "http://127.0.0.1:$port/health" 2>/dev/null) || { sleep 1; continue; }435+ *'"status":"ok"'*) health_ok=1; break ;;
331- # A stale process from an older deploy can answer too, so the
332- # running binary must be THIS release's, or it rolls back.
333- pid=$(systemctl --user show -p MainPID --value "$service")
334- exe=$(readlink "/proc/$pid/exe")
335- case "$exe" in
336- "$deploy_path/current/hezarfen_backend") ;;
337- *)
338- echo "/health answered, but the process is '$exe' — not this release; rolling back" >&2
339- rollback
340- exit 1
341- ;;
342 esac436 esac
343- echo 'hezarfen is up'437+ sleep 1
344- rm -rf -- "$deploy_path/current.previous"
345- exit 0
346 done438 done
347- echo 'hezarfen did not answer /health; rolling back' >&2439+ if [ "$health_ok" -ne 1 ]; then
348- rollback440+ echo '/health never said "status":"ok"; rolling back' >&2
349- exit 1441+ rollback
442+ exit 1
443+ fi
444+
445+ # A stale stack from an older deploy can answer too, so the
446+ # running container must be THIS build's image, or it rolls back.
447+ image=$(podman inspect -f '{{.Config.Image}}' hezarfen-backend)
448+ case "$image" in
449+ *"$tag"*) ;;
450+ *)
451+ echo "/health answered, but the container runs '$image' — not this build ($tag); rolling back" >&2
452+ rollback
453+ exit 1
454+ ;;
455+ esac
456+ echo 'hezarfen-compose is up'
350 REMOTE457 REMOTE
351 458
352- # The independent after-the-fact check: the process answering must459+ # The independent after-the-fact check: the container answering must
353- # still be this release's, and the validation contract must be served.460+ # still be the current tag's, and the validation contract must be
461+ # served.
354 - name: Verify the served API462 - name: Verify the served API
355 run: |463 run: |
356 set -euo pipefail464 set -euo pipefail
@@ -358,22 +466,26 @@ jobs:
358 # One remote script, im-style: mixing runner-side and server-side466 # One remote script, im-style: mixing runner-side and server-side
359 # variables in nested ssh quoting once shipped a check that failed467 # variables in nested ssh quoting once shipped a check that failed
360 # on a healthy deploy. Everything happens inside the heredoc.468 # on a healthy deploy. Everything happens inside the heredoc.
361- ssh "$ssh_target" "bash -se -- '$DEPLOY_SUBDIR' '$SERVICE' '$ENV_FILE_NAME'" <<'REMOTE'469+ ssh "$ssh_target" "bash -se -- '$DEPLOY_SUBDIR'" <<'REMOTE'
362 set -euo pipefail470 set -euo pipefail
363 deploy_path=$HOME/$1471 deploy_path=$HOME/$1
364- service=$2
365- env_file=$deploy_path/$3
366 export XDG_RUNTIME_DIR=/run/user/$(id -u)472 export XDG_RUNTIME_DIR=/run/user/$(id -u)
367- port=$(sed -n 's/^PORT=\([0-9][0-9]*\)$/\1/p' "$env_file" | tail -n1)473+ cd -- "$deploy_path"
368- port=${port:-7656}474+ tag=$(cat -- "$deploy_path/current_tag")
369- pid=$(systemctl --user show -p MainPID --value "$service")475+ image=$(podman inspect -f '{{.Config.Image}}' hezarfen-backend)
370- exe=$(readlink "/proc/$pid/exe")476+ case "$image" in
371- [ "$exe" = "$deploy_path/current/hezarfen_backend" ] || {477+ *"$tag"*) ;;
372- echo "serving '$exe', not the current release" >&2478+ *)
373- exit 1479+ echo "container runs '$image', not the current tag '$tag'" >&2
374- }480+ exit 1
375- curl -fsS "http://127.0.0.1:$port/health" | grep -q '"status":"ok"'481+ ;;
376- curl -fsS -o /dev/null "http://127.0.0.1:$port/limits"482+ esac
483+ served=$(curl -fsS http://127.0.0.1:7656/health) || { echo '/health failed' >&2; exit 1; }
484+ case "$served" in
485+ *'"status":"ok"'*) ;;
486+ *) echo '/health did not report "status":"ok"' >&2; exit 1 ;;
487+ esac
488+ curl -fsS -o /dev/null http://127.0.0.1:7656/limits
377 echo 'health ok, limits served'489 echo 'health ok, limits served'
378 REMOTE490 REMOTE
379 491
.sqlx/query-000fbca60257b293277232cb808c98da0c49fac2b2f178ec9a521f6b070aca70.jsonadded+14 -0
@@ -0,0 +1,14 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "DELETE FROM rag_output_source WHERE output = $1",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid"
9+ ]
10+ },
11+ "nullable": []
12+ },
13+ "hash": "000fbca60257b293277232cb808c98da0c49fac2b2f178ec9a521f6b070aca70"
14+}
.sqlx/query-0345094de481bdd86f0ac699bc987840bfde048747904ead52da7a2a6961f9a2.jsondeleted+0 -15
@@ -1,15 +0,0 @@
1-{
2- "db_name": "PostgreSQL",
3- "query": "UPDATE class_blueprint SET courses = array_remove(courses, $2) WHERE grade = $1",
4- "describe": {
5- "columns": [],
6- "parameters": {
7- "Left": [
8- "Text",
9- "Uuid"
10- ]
11- },
12- "nullable": []
13- },
14- "hash": "0345094de481bdd86f0ac699bc987840bfde048747904ead52da7a2a6961f9a2"
15-}
.sqlx/query-03c775aaaa23fc44b29fe4a4d64074eb43d881555a2d278f30abf5ef6b4cef54.jsonadded+14 -0
@@ -0,0 +1,14 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "INSERT INTO settings_attendance_status (settings, status)\n SELECT 'school', t.status FROM unnest($1::text[]) AS t(status)",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "TextArray"
9+ ]
10+ },
11+ "nullable": []
12+ },
13+ "hash": "03c775aaaa23fc44b29fe4a4d64074eb43d881555a2d278f30abf5ef6b4cef54"
14+}
.sqlx/query-095bbc7dc251d30a4ae7bfaf71d50ff42e92738d5bf32d42b3471178a0439d7b.jsondeleted+0 -136
@@ -1,136 +0,0 @@
1-{
2- "db_name": "PostgreSQL",
3- "query": "UPDATE board\n SET participants = array_remove(participants, $1)\n WHERE $1 = ANY(participants) OR creator = $1\n RETURNING id AS \"id: BoardId\",\n creator AS \"creator: UserId\",\n title AS \"title: BoardTitle\",\n participants AS \"participants: Vec<UserId>\",\n locked,\n locked_by AS \"locked_by: UserId\",\n locked_at AS \"locked_at: Timestamp\",\n epoch,\n closed_at AS \"closed_at: Timestamp\",\n created_at AS \"created_at: Timestamp\"",
4- "describe": {
5- "columns": [
6- {
7- "ordinal": 0,
8- "name": "id: BoardId",
9- "type_info": "Uuid",
10- "origin": {
11- "Table": {
12- "table": "board",
13- "name": "id"
14- }
15- }
16- },
17- {
18- "ordinal": 1,
19- "name": "creator: UserId",
20- "type_info": "Uuid",
21- "origin": {
22- "Table": {
23- "table": "board",
24- "name": "creator"
25- }
26- }
27- },
28- {
29- "ordinal": 2,
30- "name": "title: BoardTitle",
31- "type_info": "Text",
32- "origin": {
33- "Table": {
34- "table": "board",
35- "name": "title"
36- }
37- }
38- },
39- {
40- "ordinal": 3,
41- "name": "participants: Vec<UserId>",
42- "type_info": "UuidArray",
43- "origin": {
44- "Table": {
45- "table": "board",
46- "name": "participants"
47- }
48- }
49- },
50- {
51- "ordinal": 4,
52- "name": "locked",
53- "type_info": "Bool",
54- "origin": {
55- "Table": {
56- "table": "board",
57- "name": "locked"
58- }
59- }
60- },
61- {
62- "ordinal": 5,
63- "name": "locked_by: UserId",
64- "type_info": "Uuid",
65- "origin": {
66- "Table": {
67- "table": "board",
68- "name": "locked_by"
69- }
70- }
71- },
72- {
73- "ordinal": 6,
74- "name": "locked_at: Timestamp",
75- "type_info": "Int8",
76- "origin": {
77- "Table": {
78- "table": "board",
79- "name": "locked_at"
80- }
81- }
82- },
83- {
84- "ordinal": 7,
85- "name": "epoch",
86- "type_info": "Int8",
87- "origin": {
88- "Table": {
89- "table": "board",
90- "name": "epoch"
91- }
92- }
93- },
94- {
95- "ordinal": 8,
96- "name": "closed_at: Timestamp",
97- "type_info": "Int8",
98- "origin": {
99- "Table": {
100- "table": "board",
101- "name": "closed_at"
102- }
103- }
104- },
105- {
106- "ordinal": 9,
107- "name": "created_at: Timestamp",
108- "type_info": "Int8",
109- "origin": {
110- "Table": {
111- "table": "board",
112- "name": "created_at"
113- }
114- }
115- }
116- ],
117- "parameters": {
118- "Left": [
119- "Uuid"
120- ]
121- },
122- "nullable": [
123- false,
124- false,
125- false,
126- false,
127- false,
128- true,
129- true,
130- false,
131- true,
132- false
133- ]
134- },
135- "hash": "095bbc7dc251d30a4ae7bfaf71d50ff42e92738d5bf32d42b3471178a0439d7b"
136-}
.sqlx/query-13a9d4d1e07a6bd0ab6bcd5d0798cd309907f23262685f8b3b267399f06ff730.jsonadded+16 -0
@@ -0,0 +1,16 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "INSERT INTO class_blueprint (id, grade, creator)\n VALUES ($1, $2, $3)",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid",
9+ "Text",
10+ "Uuid"
11+ ]
12+ },
13+ "nullable": []
14+ },
15+ "hash": "13a9d4d1e07a6bd0ab6bcd5d0798cd309907f23262685f8b3b267399f06ff730"
16+}
.sqlx/query-8c4b65a9c0a081238e9f3d154ee1e2cef90809aa9c81ba4a2109ffaf8caf4170.json → .sqlx/query-171dde095199b0d28722a55df522824bacb3b971bb88a99db0fbeb148045048d.jsonrenamed+3 -16
@@ -1,6 +1,6 @@
1 {1 {
2 "db_name": "PostgreSQL",2 "db_name": "PostgreSQL",
3- "query": "INSERT INTO rag_output (id, course_note, course, sources, payload, generated_at)\n VALUES ($1, $2, $3, $4, $5, $6)\n RETURNING id AS \"id: RagOutputId\", course_note AS \"course_note: CourseNoteId\",\n course AS \"course: CourseId\",\n sources AS \"sources: Vec<CourseNoteFileId>\",\n payload AS \"payload: Json<Value>\",\n generated_at AS \"generated_at: Timestamp\"",3+ "query": "INSERT INTO rag_output (id, course_note, course, payload, generated_at)\n VALUES ($1, $2, $3, $4, $5)\n RETURNING id AS \"id: RagOutputId\", course_note AS \"course_note: CourseNoteId\",\n course AS \"course: CourseId\",\n payload AS \"payload: Json<Value>\",\n generated_at AS \"generated_at: Timestamp\"",
4 "describe": {4 "describe": {
5 "columns": [5 "columns": [
6 {6 {
@@ -38,17 +38,6 @@
38 },38 },
39 {39 {
40 "ordinal": 3,40 "ordinal": 3,
41- "name": "sources: Vec<CourseNoteFileId>",
42- "type_info": "UuidArray",
43- "origin": {
44- "Table": {
45- "table": "rag_output",
46- "name": "sources"
47- }
48- }
49- },
50- {
51- "ordinal": 4,
52 "name": "payload: Json<Value>",41 "name": "payload: Json<Value>",
53 "type_info": "Jsonb",42 "type_info": "Jsonb",
54 "origin": {43 "origin": {
@@ -59,7 +48,7 @@
59 }48 }
60 },49 },
61 {50 {
62- "ordinal": 5,51+ "ordinal": 4,
63 "name": "generated_at: Timestamp",52 "name": "generated_at: Timestamp",
64 "type_info": "Int8",53 "type_info": "Int8",
65 "origin": {54 "origin": {
@@ -75,7 +64,6 @@
75 "Uuid",64 "Uuid",
76 "Uuid",65 "Uuid",
77 "Uuid",66 "Uuid",
78- "UuidArray",
79 "Jsonb",67 "Jsonb",
80 "Int8"68 "Int8"
81 ]69 ]
@@ -85,9 +73,8 @@
85 false,73 false,
86 false,74 false,
87 false,75 false,
88- false,
89 false76 false
90 ]77 ]
91 },78 },
92- "hash": "8c4b65a9c0a081238e9f3d154ee1e2cef90809aa9c81ba4a2109ffaf8caf4170"79+ "hash": "171dde095199b0d28722a55df522824bacb3b971bb88a99db0fbeb148045048d"
93 }80 }
.sqlx/query-1849fc54c3514fc57c3ad18cc02b0d075c1d724f9f0b05890953e52cbe4f08e3.jsonadded+14 -0
@@ -0,0 +1,14 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "DELETE FROM rag_output_source WHERE output IN\n (SELECT id FROM rag_output WHERE course_note = $1)",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid"
9+ ]
10+ },
11+ "nullable": []
12+ },
13+ "hash": "1849fc54c3514fc57c3ad18cc02b0d075c1d724f9f0b05890953e52cbe4f08e3"
14+}
.sqlx/query-1ab734e07505d4c74ae50901fb3144f303f578b1048bf96689e513848eca9185.jsonadded+40 -0
@@ -0,0 +1,40 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "SELECT course AS \"course: CourseId\", teacher AS \"teacher: UserId\"\n FROM course_teacher WHERE course = ANY($1)",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "course: CourseId",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "course_teacher",
13+ "name": "course"
14+ }
15+ }
16+ },
17+ {
18+ "ordinal": 1,
19+ "name": "teacher: UserId",
20+ "type_info": "Uuid",
21+ "origin": {
22+ "Table": {
23+ "table": "course_teacher",
24+ "name": "teacher"
25+ }
26+ }
27+ }
28+ ],
29+ "parameters": {
30+ "Left": [
31+ "UuidArray"
32+ ]
33+ },
34+ "nullable": [
35+ false,
36+ false
37+ ]
38+ },
39+ "hash": "1ab734e07505d4c74ae50901fb3144f303f578b1048bf96689e513848eca9185"
40+}
.sqlx/query-0c551290ec429e8663d0cd33e307b195d00ed6a90dbd095f9066c87ec9cec8b3.json → .sqlx/query-1c45fc4d105c7dc58a1145c9921fa27ef52f014385003a3b5c3c1fae1768de6b.jsonrenamed+5 -10
@@ -1,6 +1,6 @@
1 {1 {
2 "db_name": "PostgreSQL",2 "db_name": "PostgreSQL",
3- "query": "SELECT id AS \"id: MenuDishId\", menu AS \"menu: MenuId\", name AS \"name: DishName\", description AS \"description: DishDescription\", price_minor AS \"price_minor: DishPrice\", tags AS \"tags: DishTags\", created_at AS \"created_at: Timestamp\"\n FROM menu_dish WHERE menu = ANY($1) ORDER BY id ASC",3+ "query": "SELECT id AS \"id: MenuDishId\", menu AS \"menu: MenuId\", name AS \"name: DishName\", description AS \"description: DishDescription\", price_minor AS \"price_minor: DishPrice\",\n COALESCE((SELECT array_agg(t.tag ORDER BY t.ord) FROM menu_dish_tag t WHERE t.dish = menu_dish.id), '{}'::text[]) AS \"tags!: DishTags\",\n created_at AS \"created_at: Timestamp\"\n FROM menu_dish WHERE menu = ANY($1) ORDER BY id ASC",
4 "describe": {4 "describe": {
5 "columns": [5 "columns": [
6 {6 {
@@ -60,14 +60,9 @@
60 },60 },
61 {61 {
62 "ordinal": 5,62 "ordinal": 5,
63- "name": "tags: DishTags",63+ "name": "tags!: DishTags",
64 "type_info": "TextArray",64 "type_info": "TextArray",
65- "origin": {65+ "origin": "Expression"
66- "Table": {
67- "table": "menu_dish",
68- "name": "tags"
69- }
70- }
71 },66 },
72 {67 {
73 "ordinal": 6,68 "ordinal": 6,
@@ -92,9 +87,9 @@
92 false,87 false,
93 true,88 true,
94 false,89 false,
95- false,90+ null,
96 false91 false
97 ]92 ]
98 },93 },
99- "hash": "0c551290ec429e8663d0cd33e307b195d00ed6a90dbd095f9066c87ec9cec8b3"94+ "hash": "1c45fc4d105c7dc58a1145c9921fa27ef52f014385003a3b5c3c1fae1768de6b"
100 }95 }
.sqlx/query-5e5f34152d7edc6330e583d24ae75d9d3486569a45b1dd375f7298e542e410a6.json → .sqlx/query-1f177f50cbca268c6586d099964dc9970bcc3aea1a65bb486f4510803f4d0019.jsonrenamed+6 -18
@@ -1,6 +1,6 @@
1 {1 {
2 "db_name": "PostgreSQL",2 "db_name": "PostgreSQL",
3- "query": "SELECT id AS \"id: CourseId\", creator AS \"creator: UserId\",\n teachers AS \"teachers: Vec<UserId>\", title AS \"title: CourseTitle\",\n description AS \"description: CourseDescription\",\n kind AS \"kind: CourseKind\", term AS \"term: TermId\", capacity\n FROM course ORDER BY id DESC",3+ "query": "SELECT id AS \"id: CourseId\", creator AS \"creator: UserId\",\n title AS \"title: CourseTitle\",\n description AS \"description: CourseDescription\",\n kind AS \"kind: CourseKind\", term AS \"term: TermId\", capacity\n FROM course ORDER BY id DESC",
4 "describe": {4 "describe": {
5 "columns": [5 "columns": [
6 {6 {
@@ -27,17 +27,6 @@
27 },27 },
28 {28 {
29 "ordinal": 2,29 "ordinal": 2,
30- "name": "teachers: Vec<UserId>",
31- "type_info": "UuidArray",
32- "origin": {
33- "Table": {
34- "table": "course",
35- "name": "teachers"
36- }
37- }
38- },
39- {
40- "ordinal": 3,
41 "name": "title: CourseTitle",30 "name": "title: CourseTitle",
42 "type_info": "Text",31 "type_info": "Text",
43 "origin": {32 "origin": {
@@ -48,7 +37,7 @@
48 }37 }
49 },38 },
50 {39 {
51- "ordinal": 4,40+ "ordinal": 3,
52 "name": "description: CourseDescription",41 "name": "description: CourseDescription",
53 "type_info": "Text",42 "type_info": "Text",
54 "origin": {43 "origin": {
@@ -59,7 +48,7 @@
59 }48 }
60 },49 },
61 {50 {
62- "ordinal": 5,51+ "ordinal": 4,
63 "name": "kind: CourseKind",52 "name": "kind: CourseKind",
64 "type_info": "Text",53 "type_info": "Text",
65 "origin": {54 "origin": {
@@ -70,7 +59,7 @@
70 }59 }
71 },60 },
72 {61 {
73- "ordinal": 6,62+ "ordinal": 5,
74 "name": "term: TermId",63 "name": "term: TermId",
75 "type_info": "Uuid",64 "type_info": "Uuid",
76 "origin": {65 "origin": {
@@ -81,7 +70,7 @@
81 }70 }
82 },71 },
83 {72 {
84- "ordinal": 7,73+ "ordinal": 6,
85 "name": "capacity",74 "name": "capacity",
86 "type_info": "Int8",75 "type_info": "Int8",
87 "origin": {76 "origin": {
@@ -101,10 +90,9 @@
101 false,90 false,
102 false,91 false,
103 false,92 false,
104- false,
105 true,93 true,
106 true94 true
107 ]95 ]
108 },96 },
109- "hash": "5e5f34152d7edc6330e583d24ae75d9d3486569a45b1dd375f7298e542e410a6"97+ "hash": "1f177f50cbca268c6586d099964dc9970bcc3aea1a65bb486f4510803f4d0019"
110 }98 }
.sqlx/query-25e11c52a36dd51246aaa35fb7b86650a361821b38809f8cc2c8b28a01952c83.jsondeleted+0 -14
@@ -1,14 +0,0 @@
1-{
2- "db_name": "PostgreSQL",
3- "query": "UPDATE class_blueprint SET courses = array_remove(courses, $1)\n WHERE $1 = ANY(courses)",
4- "describe": {
5- "columns": [],
6- "parameters": {
7- "Left": [
8- "Uuid"
9- ]
10- },
11- "nullable": []
12- },
13- "hash": "25e11c52a36dd51246aaa35fb7b86650a361821b38809f8cc2c8b28a01952c83"
14-}
.sqlx/query-26379a9428e3236693332d0c236c0c46b1e0aa1efe82ea16208b41b253de74d9.jsonadded+15 -0
@@ -0,0 +1,15 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "DELETE FROM rag_output_source WHERE output IN\n (SELECT id FROM rag_output WHERE course_note = $1 AND id < $2)",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid",
9+ "Uuid"
10+ ]
11+ },
12+ "nullable": []
13+ },
14+ "hash": "26379a9428e3236693332d0c236c0c46b1e0aa1efe82ea16208b41b253de74d9"
15+}
.sqlx/query-27a509ab3a8873474dffaa26b61511e77c81d4e7efe639591f7db00efaca2f54.jsonadded+15 -0
@@ -0,0 +1,15 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "INSERT INTO rag_output_source (output, source)\n SELECT $1, s FROM unnest($2::uuid[]) AS t(s)",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid",
9+ "UuidArray"
10+ ]
11+ },
12+ "nullable": []
13+ },
14+ "hash": "27a509ab3a8873474dffaa26b61511e77c81d4e7efe639591f7db00efaca2f54"
15+}
.sqlx/query-27dd38ebf96a18059c72db4b6b23f70b916a6273b29e768e303d612a29609fb1.jsonadded+15 -0
@@ -0,0 +1,15 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "DELETE FROM course_teacher WHERE course = $1 AND teacher = $2",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid",
9+ "Uuid"
10+ ]
11+ },
12+ "nullable": []
13+ },
14+ "hash": "27dd38ebf96a18059c72db4b6b23f70b916a6273b29e768e303d612a29609fb1"
15+}
.sqlx/query-0a2e0d2d5ca8d25286d988af36998657122706c2873ed4ed1b499f262a4c78d9.json → .sqlx/query-284241b54bd6674d3d77a88d5cb63cb74660d9bbddaa7fc876d2230184f3430c.jsonrenamed+5 -10
@@ -1,6 +1,6 @@
1 {1 {
2 "db_name": "PostgreSQL",2 "db_name": "PostgreSQL",
3- "query": "UPDATE board SET locked = $2, locked_by = $3, locked_at = $4 WHERE id = $1\n RETURNING id AS \"id: BoardId\", creator AS \"creator: UserId\",\n title AS \"title: BoardTitle\",\n participants AS \"participants: Vec<UserId>\", locked,\n locked_by AS \"locked_by: UserId\",\n locked_at AS \"locked_at: Timestamp\", epoch,\n closed_at AS \"closed_at: Timestamp\",\n created_at AS \"created_at: Timestamp\"",3+ "query": "UPDATE board SET locked = $2, locked_by = $3, locked_at = $4 WHERE id = $1\n RETURNING id AS \"id: BoardId\", creator AS \"creator: UserId\",\n title AS \"title: BoardTitle\",\n ARRAY(SELECT p.participant FROM board_participant p\n WHERE p.board = board.id ORDER BY p.participant)\n AS \"participants!: Vec<UserId>\", locked,\n locked_by AS \"locked_by: UserId\",\n locked_at AS \"locked_at: Timestamp\", epoch,\n closed_at AS \"closed_at: Timestamp\",\n created_at AS \"created_at: Timestamp\"",
4 "describe": {4 "describe": {
5 "columns": [5 "columns": [
6 {6 {
@@ -38,14 +38,9 @@
38 },38 },
39 {39 {
40 "ordinal": 3,40 "ordinal": 3,
41- "name": "participants: Vec<UserId>",41+ "name": "participants!: Vec<UserId>",
42 "type_info": "UuidArray",42 "type_info": "UuidArray",
43- "origin": {43+ "origin": "Expression"
44- "Table": {
45- "table": "board",
46- "name": "participants"
47- }
48- }
49 },44 },
50 {45 {
51 "ordinal": 4,46 "ordinal": 4,
@@ -126,7 +121,7 @@
126 false,121 false,
127 false,122 false,
128 false,123 false,
129- false,124+ null,
130 false,125 false,
131 true,126 true,
132 true,127 true,
@@ -135,5 +130,5 @@
135 false130 false
136 ]131 ]
137 },132 },
138- "hash": "0a2e0d2d5ca8d25286d988af36998657122706c2873ed4ed1b499f262a4c78d9"133+ "hash": "284241b54bd6674d3d77a88d5cb63cb74660d9bbddaa7fc876d2230184f3430c"
139 }134 }
.sqlx/query-290550b5ce584441f5343802004891866199a2dd3d3c822cccc471061d842c71.jsondeleted+0 -155
@@ -1,155 +0,0 @@
1-{
2- "db_name": "PostgreSQL",
3- "query": "INSERT INTO settings (id, exam_kinds, attendance_statuses, grade_bands,\n max_file_bytes, chatbot_history_turns,\n max_chatbot_message_len, max_chatbot_threads,\n meal_slots, dietary_tags, meal_cancel_cutoff_minutes)\n VALUES ('school', $1, $2, $3, $4, $5, $6, $7, $8, $9, $10)\n ON CONFLICT (id) DO UPDATE SET\n exam_kinds = $1,\n attendance_statuses = $2,\n grade_bands = $3,\n max_file_bytes = $4,\n chatbot_history_turns = $5,\n max_chatbot_message_len = $6,\n max_chatbot_threads = $7,\n meal_slots = $8,\n dietary_tags = $9,\n meal_cancel_cutoff_minutes = $10\n WHERE settings.exam_kinds IS NOT DISTINCT FROM $11\n AND settings.attendance_statuses IS NOT DISTINCT FROM $12\n AND settings.grade_bands IS NOT DISTINCT FROM $13\n AND settings.max_file_bytes IS NOT DISTINCT FROM $14\n AND settings.chatbot_history_turns IS NOT DISTINCT FROM $15\n AND settings.max_chatbot_message_len IS NOT DISTINCT FROM $16\n AND settings.max_chatbot_threads IS NOT DISTINCT FROM $17\n AND settings.meal_slots IS NOT DISTINCT FROM $18\n AND settings.dietary_tags IS NOT DISTINCT FROM $19\n AND settings.meal_cancel_cutoff_minutes IS NOT DISTINCT FROM $20\n RETURNING\n exam_kinds AS \"exam_kinds: Json<Vec<ExamKindDef>>\",\n attendance_statuses,\n grade_bands AS \"grade_bands: Json<Vec<GradeBand>>\",\n max_file_bytes,\n chatbot_history_turns,\n max_chatbot_message_len,\n max_chatbot_threads,\n meal_slots AS \"meal_slots: Json<Vec<MealSlotDef>>\",\n dietary_tags,\n meal_cancel_cutoff_minutes",
4- "describe": {
5- "columns": [
6- {
7- "ordinal": 0,
8- "name": "exam_kinds: Json<Vec<ExamKindDef>>",
9- "type_info": "Jsonb",
10- "origin": {
11- "Table": {
12- "table": "settings",
13- "name": "exam_kinds"
14- }
15- }
16- },
17- {
18- "ordinal": 1,
19- "name": "attendance_statuses",
20- "type_info": "TextArray",
21- "origin": {
22- "Table": {
23- "table": "settings",
24- "name": "attendance_statuses"
25- }
26- }
27- },
28- {
29- "ordinal": 2,
30- "name": "grade_bands: Json<Vec<GradeBand>>",
31- "type_info": "Jsonb",
32- "origin": {
33- "Table": {
34- "table": "settings",
35- "name": "grade_bands"
36- }
37- }
38- },
39- {
40- "ordinal": 3,
41- "name": "max_file_bytes",
42- "type_info": "Int8",
43- "origin": {
44- "Table": {
45- "table": "settings",
46- "name": "max_file_bytes"
47- }
48- }
49- },
50- {
51- "ordinal": 4,
52- "name": "chatbot_history_turns",
53- "type_info": "Int8",
54- "origin": {
55- "Table": {
56- "table": "settings",
57- "name": "chatbot_history_turns"
58- }
59- }
60- },
61- {
62- "ordinal": 5,
63- "name": "max_chatbot_message_len",
64- "type_info": "Int8",
65- "origin": {
66- "Table": {
67- "table": "settings",
68- "name": "max_chatbot_message_len"
69- }
70- }
71- },
72- {
73- "ordinal": 6,
74- "name": "max_chatbot_threads",
75- "type_info": "Int8",
76- "origin": {
77- "Table": {
78- "table": "settings",
79- "name": "max_chatbot_threads"
80- }
81- }
82- },
83- {
84- "ordinal": 7,
85- "name": "meal_slots: Json<Vec<MealSlotDef>>",
86- "type_info": "Jsonb",
87- "origin": {
88- "Table": {
89- "table": "settings",
90- "name": "meal_slots"
91- }
92- }
93- },
94- {
95- "ordinal": 8,
96- "name": "dietary_tags",
97- "type_info": "TextArray",
98- "origin": {
99- "Table": {
100- "table": "settings",
101- "name": "dietary_tags"
102- }
103- }
104- },
105- {
106- "ordinal": 9,
107- "name": "meal_cancel_cutoff_minutes",
108- "type_info": "Int8",
109- "origin": {
110- "Table": {
111- "table": "settings",
112- "name": "meal_cancel_cutoff_minutes"
113- }
114- }
115- }
116- ],
117- "parameters": {
118- "Left": [
119- "Jsonb",
120- "TextArray",
121- "Jsonb",
122- "Int8",
123- "Int8",
124- "Int8",
125- "Int8",
126- "Jsonb",
127- "TextArray",
128- "Int8",
129- "Jsonb",
130- "TextArray",
131- "Jsonb",
132- "Int8",
133- "Int8",
134- "Int8",
135- "Int8",
136- "Jsonb",
137- "TextArray",
138- "Int8"
139- ]
140- },
141- "nullable": [
142- false,
143- false,
144- false,
145- true,
146- true,
147- true,
148- true,
149- true,
150- true,
151- true
152- ]
153- },
154- "hash": "290550b5ce584441f5343802004891866199a2dd3d3c822cccc471061d842c71"
155-}
.sqlx/query-2a15712642955d8e832f14d5173c9f44414871c3bca6f106e33eea0aaf7ba82e.jsonadded+28 -0
@@ -0,0 +1,28 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "DELETE FROM board_participant WHERE participant = $1 RETURNING board",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "board",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "board_participant",
13+ "name": "board"
14+ }
15+ }
16+ }
17+ ],
18+ "parameters": {
19+ "Left": [
20+ "Uuid"
21+ ]
22+ },
23+ "nullable": [
24+ false
25+ ]
26+ },
27+ "hash": "2a15712642955d8e832f14d5173c9f44414871c3bca6f106e33eea0aaf7ba82e"
28+}
.sqlx/query-aeb5df78c83af8be112917b0cf0b034e94d2b305db968ffaae53785a3af93dab.json → .sqlx/query-2ab51ad375937884da43590de2ca4810dd0a8bfb1290a626ae40f31ca469a632.jsonrenamed+6 -18
@@ -1,6 +1,6 @@
1 {1 {
2 "db_name": "PostgreSQL",2 "db_name": "PostgreSQL",
3- "query": "SELECT id AS \"id: CourseId\", creator AS \"creator: UserId\",\n teachers AS \"teachers: Vec<UserId>\", title AS \"title: CourseTitle\",\n description AS \"description: CourseDescription\",\n kind AS \"kind: CourseKind\", term AS \"term: TermId\", capacity\n FROM course WHERE id = ANY($1)",3+ "query": "SELECT id AS \"id: CourseId\", creator AS \"creator: UserId\",\n title AS \"title: CourseTitle\",\n description AS \"description: CourseDescription\",\n kind AS \"kind: CourseKind\", term AS \"term: TermId\", capacity\n FROM course WHERE id = ANY($1)",
4 "describe": {4 "describe": {
5 "columns": [5 "columns": [
6 {6 {
@@ -27,17 +27,6 @@
27 },27 },
28 {28 {
29 "ordinal": 2,29 "ordinal": 2,
30- "name": "teachers: Vec<UserId>",
31- "type_info": "UuidArray",
32- "origin": {
33- "Table": {
34- "table": "course",
35- "name": "teachers"
36- }
37- }
38- },
39- {
40- "ordinal": 3,
41 "name": "title: CourseTitle",30 "name": "title: CourseTitle",
42 "type_info": "Text",31 "type_info": "Text",
43 "origin": {32 "origin": {
@@ -48,7 +37,7 @@
48 }37 }
49 },38 },
50 {39 {
51- "ordinal": 4,40+ "ordinal": 3,
52 "name": "description: CourseDescription",41 "name": "description: CourseDescription",
53 "type_info": "Text",42 "type_info": "Text",
54 "origin": {43 "origin": {
@@ -59,7 +48,7 @@
59 }48 }
60 },49 },
61 {50 {
62- "ordinal": 5,51+ "ordinal": 4,
63 "name": "kind: CourseKind",52 "name": "kind: CourseKind",
64 "type_info": "Text",53 "type_info": "Text",
65 "origin": {54 "origin": {
@@ -70,7 +59,7 @@
70 }59 }
71 },60 },
72 {61 {
73- "ordinal": 6,62+ "ordinal": 5,
74 "name": "term: TermId",63 "name": "term: TermId",
75 "type_info": "Uuid",64 "type_info": "Uuid",
76 "origin": {65 "origin": {
@@ -81,7 +70,7 @@
81 }70 }
82 },71 },
83 {72 {
84- "ordinal": 7,73+ "ordinal": 6,
85 "name": "capacity",74 "name": "capacity",
86 "type_info": "Int8",75 "type_info": "Int8",
87 "origin": {76 "origin": {
@@ -103,10 +92,9 @@
103 false,92 false,
104 false,93 false,
105 false,94 false,
106- false,
107 true,95 true,
108 true96 true
109 ]97 ]
110 },98 },
111- "hash": "aeb5df78c83af8be112917b0cf0b034e94d2b305db968ffaae53785a3af93dab"99+ "hash": "2ab51ad375937884da43590de2ca4810dd0a8bfb1290a626ae40f31ca469a632"
112 }100 }
.sqlx/query-f6ab1a10c0ebdc295fe7ea726b189838548d9535470d0eafce7c8911d71015d7.json → .sqlx/query-2c4a5e96ccd5b0b27c2c99846f574e7bf1fb475a7aefa88b9ce817ee05ad8582.jsonrenamed+5 -10
@@ -1,6 +1,6 @@
1 {1 {
2 "db_name": "PostgreSQL",2 "db_name": "PostgreSQL",
3- "query": "DELETE FROM board WHERE id = $1\n RETURNING id AS \"id: BoardId\", creator AS \"creator: UserId\",\n title AS \"title: BoardTitle\",\n participants AS \"participants: Vec<UserId>\", locked,\n locked_by AS \"locked_by: UserId\",\n locked_at AS \"locked_at: Timestamp\", epoch,\n closed_at AS \"closed_at: Timestamp\",\n created_at AS \"created_at: Timestamp\"",3+ "query": "DELETE FROM board WHERE id = $1\n RETURNING id AS \"id: BoardId\", creator AS \"creator: UserId\",\n title AS \"title: BoardTitle\",\n ARRAY(SELECT p.participant FROM board_participant p\n WHERE p.board = board.id ORDER BY p.participant)\n AS \"participants!: Vec<UserId>\", locked,\n locked_by AS \"locked_by: UserId\",\n locked_at AS \"locked_at: Timestamp\", epoch,\n closed_at AS \"closed_at: Timestamp\",\n created_at AS \"created_at: Timestamp\"",
4 "describe": {4 "describe": {
5 "columns": [5 "columns": [
6 {6 {
@@ -38,14 +38,9 @@
38 },38 },
39 {39 {
40 "ordinal": 3,40 "ordinal": 3,
41- "name": "participants: Vec<UserId>",41+ "name": "participants!: Vec<UserId>",
42 "type_info": "UuidArray",42 "type_info": "UuidArray",
43- "origin": {43+ "origin": "Expression"
44- "Table": {
45- "table": "board",
46- "name": "participants"
47- }
48- }
49 },44 },
50 {45 {
51 "ordinal": 4,46 "ordinal": 4,
@@ -123,7 +118,7 @@
123 false,118 false,
124 false,119 false,
125 false,120 false,
126- false,121+ null,
127 false,122 false,
128 true,123 true,
129 true,124 true,
@@ -132,5 +127,5 @@
132 false127 false
133 ]128 ]
134 },129 },
135- "hash": "f6ab1a10c0ebdc295fe7ea726b189838548d9535470d0eafce7c8911d71015d7"130+ "hash": "2c4a5e96ccd5b0b27c2c99846f574e7bf1fb475a7aefa88b9ce817ee05ad8582"
136 }131 }
.sqlx/query-f0d305ba65359dea4a9d7b4a0577ae43db1c7ef01adc22450f75c0cd37c0d950.json → .sqlx/query-321f0103b33607cbfda238c631fc4f0a47d8f3231e8fdfe3dfe60ae82eacf532.jsonrenamed+3 -15
@@ -1,6 +1,6 @@
1 {1 {
2 "db_name": "PostgreSQL",2 "db_name": "PostgreSQL",
3- "query": "SELECT id AS \"id: RagOutputId\", course_note AS \"course_note: CourseNoteId\",\n course AS \"course: CourseId\",\n sources AS \"sources: Vec<CourseNoteFileId>\",\n payload AS \"payload: Json<Value>\",\n generated_at AS \"generated_at: Timestamp\"\n FROM rag_output WHERE id = $1",3+ "query": "SELECT id AS \"id: RagOutputId\", course_note AS \"course_note: CourseNoteId\",\n course AS \"course: CourseId\",\n payload AS \"payload: Json<Value>\",\n generated_at AS \"generated_at: Timestamp\"\n FROM rag_output WHERE id = $1",
4 "describe": {4 "describe": {
5 "columns": [5 "columns": [
6 {6 {
@@ -38,17 +38,6 @@
38 },38 },
39 {39 {
40 "ordinal": 3,40 "ordinal": 3,
41- "name": "sources: Vec<CourseNoteFileId>",
42- "type_info": "UuidArray",
43- "origin": {
44- "Table": {
45- "table": "rag_output",
46- "name": "sources"
47- }
48- }
49- },
50- {
51- "ordinal": 4,
52 "name": "payload: Json<Value>",41 "name": "payload: Json<Value>",
53 "type_info": "Jsonb",42 "type_info": "Jsonb",
54 "origin": {43 "origin": {
@@ -59,7 +48,7 @@
59 }48 }
60 },49 },
61 {50 {
62- "ordinal": 5,51+ "ordinal": 4,
63 "name": "generated_at: Timestamp",52 "name": "generated_at: Timestamp",
64 "type_info": "Int8",53 "type_info": "Int8",
65 "origin": {54 "origin": {
@@ -80,9 +69,8 @@
80 false,69 false,
81 false,70 false,
82 false,71 false,
83- false,
84 false72 false
85 ]73 ]
86 },74 },
87- "hash": "f0d305ba65359dea4a9d7b4a0577ae43db1c7ef01adc22450f75c0cd37c0d950"75+ "hash": "321f0103b33607cbfda238c631fc4f0a47d8f3231e8fdfe3dfe60ae82eacf532"
88 }76 }
.sqlx/query-99469fccd450e6d9fae93713e93936de6a95cefbdefaae798d88c8cda1da9fc6.json → .sqlx/query-329a782baf49baadc80e6c3a233f203c9eea7308e773738dfd905a9eb131dcb2.jsonrenamed+2 -2
@@ -1,6 +1,6 @@
1 {1 {
2 "db_name": "PostgreSQL",2 "db_name": "PostgreSQL",
3- "query": "DELETE FROM rag_output WHERE $1 = ANY(sources)",3+ "query": "DELETE FROM course_teacher WHERE course = $1",
4 "describe": {4 "describe": {
5 "columns": [],5 "columns": [],
6 "parameters": {6 "parameters": {
@@ -10,5 +10,5 @@
10 },10 },
11 "nullable": []11 "nullable": []
12 },12 },
13- "hash": "99469fccd450e6d9fae93713e93936de6a95cefbdefaae798d88c8cda1da9fc6"13+ "hash": "329a782baf49baadc80e6c3a233f203c9eea7308e773738dfd905a9eb131dcb2"
14 }14 }
.sqlx/query-32cf492f2994793969ed61eb7f2a0dc99b92d06993df0e078263d773feb3fff1.jsonmodified+1 -1
@@ -5,7 +5,7 @@
5 "columns": [],5 "columns": [],
6 "parameters": {6 "parameters": {
7 "Left": [7 "Left": [
8- "Text"8+ "Uuid"
9 ]9 ]
10 },10 },
11 "nullable": []11 "nullable": []
.sqlx/query-13d7f63724ed14449a9d6bfd3735072ce7eded7b6e5c40c33fc6140ae8747ec0.json → .sqlx/query-33937eda61e33ee52f82bf7e6338428bdccf4e2d95f2499d9feb46ff6238f51d.jsonrenamed+2 -2
@@ -1,6 +1,6 @@
1 {1 {
2 "db_name": "PostgreSQL",2 "db_name": "PostgreSQL",
3- "query": "DELETE FROM homework WHERE id = $1\n RETURNING id AS \"id: HomeworkId\",\n course AS \"course: CourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END\n AS \"assigned: Vec<UserId>\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"",3+ "query": "DELETE FROM homework WHERE id = $1\n RETURNING id AS \"id: HomeworkId\",\n course AS \"course: CourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a\n WHERE a.homework = homework.id) AS \"assigned: Vec<UserId>\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"",
4 "describe": {4 "describe": {
5 "columns": [5 "columns": [
6 {6 {
@@ -115,5 +115,5 @@
115 false115 false
116 ]116 ]
117 },117 },
118- "hash": "13d7f63724ed14449a9d6bfd3735072ce7eded7b6e5c40c33fc6140ae8747ec0"118+ "hash": "33937eda61e33ee52f82bf7e6338428bdccf4e2d95f2499d9feb46ff6238f51d"
119 }119 }
.sqlx/query-3a2e8db644faec7cc2aab62aba2649c8707018d8af8f511c04310aa2357d8a4b.jsonadded+15 -0
@@ -0,0 +1,15 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "INSERT INTO menu_dish_tag (dish, tag, ord)\n SELECT $1, tag, ord FROM unnest($2::text[]) WITH ORDINALITY AS t(tag, ord)",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid",
9+ "TextArray"
10+ ]
11+ },
12+ "nullable": []
13+ },
14+ "hash": "3a2e8db644faec7cc2aab62aba2649c8707018d8af8f511c04310aa2357d8a4b"
15+}
.sqlx/query-3c78ef010f90748dd6f60c086761e68d2e630763fc4732795891e4243e5e0eea.jsonadded+15 -0
@@ -0,0 +1,15 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "DELETE FROM blueprint_course\n WHERE blueprint = $1 AND NOT (course = ANY($2))",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid",
9+ "UuidArray"
10+ ]
11+ },
12+ "nullable": []
13+ },
14+ "hash": "3c78ef010f90748dd6f60c086761e68d2e630763fc4732795891e4243e5e0eea"
15+}
.sqlx/query-3d1db83ef8c406a80281be9cfc968dc81304180cd047d1ae2b65951528e1d4b1.jsonadded+14 -0
@@ -0,0 +1,14 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "DELETE FROM blueprint_course WHERE course = $1",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid"
9+ ]
10+ },
11+ "nullable": []
12+ },
13+ "hash": "3d1db83ef8c406a80281be9cfc968dc81304180cd047d1ae2b65951528e1d4b1"
14+}
.sqlx/query-3e68616aab7908522dcb7aef662a6cc355fa9ce81fc609ad25450d2a1d8cf555.jsonadded+18 -0
@@ -0,0 +1,18 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "INSERT INTO dietary_profile (student, note, updated_by, updated_at)\n VALUES ($1, $2, $3, $4)\n ON CONFLICT (student) DO UPDATE SET\n note = CASE WHEN $5 THEN $2 ELSE dietary_profile.note END,\n updated_by = $3,\n updated_at = $4",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid",
9+ "Text",
10+ "Uuid",
11+ "Int8",
12+ "Bool"
13+ ]
14+ },
15+ "nullable": []
16+ },
17+ "hash": "3e68616aab7908522dcb7aef662a6cc355fa9ce81fc609ad25450d2a1d8cf555"
18+}
.sqlx/query-258c27c5e706ee3493229f3aacace4fa9ae874106c106a768b087e09f2234dcd.json → .sqlx/query-3f35044808071da4e1275f141b5f80b6974dff0cb59238f7ab0e1b51a389e6b1.jsonrenamed+2 -2
@@ -1,6 +1,6 @@
1 {1 {
2 "db_name": "PostgreSQL",2 "db_name": "PostgreSQL",
3- "query": "SELECT id AS \"id: HomeworkId\",\n course AS \"course: CourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END\n AS \"assigned: Vec<UserId>\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"\n FROM homework WHERE id = $1 FOR UPDATE",3+ "query": "SELECT id AS \"id: HomeworkId\",\n course AS \"course: CourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a\n WHERE a.homework = homework.id) AS \"assigned: Vec<UserId>\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"\n FROM homework WHERE id = $1 FOR UPDATE",
4 "describe": {4 "describe": {
5 "columns": [5 "columns": [
6 {6 {
@@ -115,5 +115,5 @@
115 false115 false
116 ]116 ]
117 },117 },
118- "hash": "258c27c5e706ee3493229f3aacace4fa9ae874106c106a768b087e09f2234dcd"118+ "hash": "3f35044808071da4e1275f141b5f80b6974dff0cb59238f7ab0e1b51a389e6b1"
119 }119 }
.sqlx/query-685fff635ecc5f67628da31ddcc229a97ac0ee9dbb5d8c73732e921e0613a1b0.json → .sqlx/query-4033f72b27577d747740c96aa418736c7f8df98bf1a17083a72371155b0b553d.jsonrenamed+8 -19
@@ -1,6 +1,6 @@
1 {1 {
2 "db_name": "PostgreSQL",2 "db_name": "PostgreSQL",
3- "query": "INSERT INTO course (id, creator, teachers, title, description, kind, term, capacity)\n VALUES ($1, $2, $3, $4, $5, $6, NULL, $7)\n RETURNING id AS \"id: CourseId\", creator AS \"creator: UserId\",\n teachers AS \"teachers: Vec<UserId>\", title AS \"title: CourseTitle\",\n description AS \"description: CourseDescription\",\n kind AS \"kind: CourseKind\", term AS \"term: TermId\", capacity",3+ "query": "WITH seat AS (\n UPDATE term\n SET course_count = course_count + 1\n WHERE id = $7 AND course_count < $8\n RETURNING 1)\n INSERT INTO course (id, creator, title, description, kind, term, capacity)\n SELECT $1, $2, $3, $4, $5, $7, $6 WHERE EXISTS (SELECT 1 FROM seat)\n RETURNING id AS \"id: CourseId\", creator AS \"creator: UserId\",\n title AS \"title: CourseTitle\",\n description AS \"description: CourseDescription\",\n kind AS \"kind: CourseKind\", term AS \"term: TermId\", capacity",
4 "describe": {4 "describe": {
5 "columns": [5 "columns": [
6 {6 {
@@ -27,17 +27,6 @@
27 },27 },
28 {28 {
29 "ordinal": 2,29 "ordinal": 2,
30- "name": "teachers: Vec<UserId>",
31- "type_info": "UuidArray",
32- "origin": {
33- "Table": {
34- "table": "course",
35- "name": "teachers"
36- }
37- }
38- },
39- {
40- "ordinal": 3,
41 "name": "title: CourseTitle",30 "name": "title: CourseTitle",
42 "type_info": "Text",31 "type_info": "Text",
43 "origin": {32 "origin": {
@@ -48,7 +37,7 @@
48 }37 }
49 },38 },
50 {39 {
51- "ordinal": 4,40+ "ordinal": 3,
52 "name": "description: CourseDescription",41 "name": "description: CourseDescription",
53 "type_info": "Text",42 "type_info": "Text",
54 "origin": {43 "origin": {
@@ -59,7 +48,7 @@
59 }48 }
60 },49 },
61 {50 {
62- "ordinal": 5,51+ "ordinal": 4,
63 "name": "kind: CourseKind",52 "name": "kind: CourseKind",
64 "type_info": "Text",53 "type_info": "Text",
65 "origin": {54 "origin": {
@@ -70,7 +59,7 @@
70 }59 }
71 },60 },
72 {61 {
73- "ordinal": 6,62+ "ordinal": 5,
74 "name": "term: TermId",63 "name": "term: TermId",
75 "type_info": "Uuid",64 "type_info": "Uuid",
76 "origin": {65 "origin": {
@@ -81,7 +70,7 @@
81 }70 }
82 },71 },
83 {72 {
84- "ordinal": 7,73+ "ordinal": 6,
85 "name": "capacity",74 "name": "capacity",
86 "type_info": "Int8",75 "type_info": "Int8",
87 "origin": {76 "origin": {
@@ -96,10 +85,11 @@
96 "Left": [85 "Left": [
97 "Uuid",86 "Uuid",
98 "Uuid",87 "Uuid",
99- "UuidArray",
100 "Text",88 "Text",
101 "Text",89 "Text",
102 "Text",90 "Text",
91+ "Int8",
92+ "Uuid",
103 "Int8"93 "Int8"
104 ]94 ]
105 },95 },
@@ -109,10 +99,9 @@
109 false,99 false,
110 false,100 false,
111 false,101 false,
112- false,
113 true,102 true,
114 true103 true
115 ]104 ]
116 },105 },
117- "hash": "685fff635ecc5f67628da31ddcc229a97ac0ee9dbb5d8c73732e921e0613a1b0"106+ "hash": "4033f72b27577d747740c96aa418736c7f8df98bf1a17083a72371155b0b553d"
118 }107 }
.sqlx/query-8890b0928a86ed9b08e5803dc4fd3dca14b305482d4614abbbd19f982c9fd732.json → .sqlx/query-40b8fe75dcbef4923d4d7f774d4cd2985cdd8768d31b752c235d4d5bbc2549d1.jsonrenamed+3 -15
@@ -1,6 +1,6 @@
1 {1 {
2 "db_name": "PostgreSQL",2 "db_name": "PostgreSQL",
3- "query": "DELETE FROM rag_output WHERE id = $1\n RETURNING id AS \"id: RagOutputId\", course_note AS \"course_note: CourseNoteId\",\n course AS \"course: CourseId\",\n sources AS \"sources: Vec<CourseNoteFileId>\",\n payload AS \"payload: Json<Value>\",\n generated_at AS \"generated_at: Timestamp\"",3+ "query": "DELETE FROM rag_output WHERE id = $1\n RETURNING id AS \"id: RagOutputId\", course_note AS \"course_note: CourseNoteId\",\n course AS \"course: CourseId\",\n payload AS \"payload: Json<Value>\",\n generated_at AS \"generated_at: Timestamp\"",
4 "describe": {4 "describe": {
5 "columns": [5 "columns": [
6 {6 {
@@ -38,17 +38,6 @@
38 },38 },
39 {39 {
40 "ordinal": 3,40 "ordinal": 3,
41- "name": "sources: Vec<CourseNoteFileId>",
42- "type_info": "UuidArray",
43- "origin": {
44- "Table": {
45- "table": "rag_output",
46- "name": "sources"
47- }
48- }
49- },
50- {
51- "ordinal": 4,
52 "name": "payload: Json<Value>",41 "name": "payload: Json<Value>",
53 "type_info": "Jsonb",42 "type_info": "Jsonb",
54 "origin": {43 "origin": {
@@ -59,7 +48,7 @@
59 }48 }
60 },49 },
61 {50 {
62- "ordinal": 5,51+ "ordinal": 4,
63 "name": "generated_at: Timestamp",52 "name": "generated_at: Timestamp",
64 "type_info": "Int8",53 "type_info": "Int8",
65 "origin": {54 "origin": {
@@ -80,9 +69,8 @@
80 false,69 false,
81 false,70 false,
82 false,71 false,
83- false,
84 false72 false
85 ]73 ]
86 },74 },
87- "hash": "8890b0928a86ed9b08e5803dc4fd3dca14b305482d4614abbbd19f982c9fd732"75+ "hash": "40b8fe75dcbef4923d4d7f774d4cd2985cdd8768d31b752c235d4d5bbc2549d1"
88 }76 }
.sqlx/query-425c4b69c806d2f70999dea4dfd56f471b95a2e0c99a880e428f5550abc05695.jsonadded+14 -0
@@ -0,0 +1,14 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "DELETE FROM course_teacher WHERE teacher = $1",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid"
9+ ]
10+ },
11+ "nullable": []
12+ },
13+ "hash": "425c4b69c806d2f70999dea4dfd56f471b95a2e0c99a880e428f5550abc05695"
14+}
.sqlx/query-42dcb34cc907c4d361d0950c3a843ea62604494f00d597051e46eba1ae56625d.jsonadded+12 -0
@@ -0,0 +1,12 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "DELETE FROM settings_attendance_status WHERE settings = 'school'",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": []
8+ },
9+ "nullable": []
10+ },
11+ "hash": "42dcb34cc907c4d361d0950c3a843ea62604494f00d597051e46eba1ae56625d"
12+}
.sqlx/query-43d5cd5b3c47c16859989d22ad3a672b6ecd3a55bebac6efa1ade9a7620b564a.jsonadded+14 -0
@@ -0,0 +1,14 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "DELETE FROM rag_output_source WHERE output IN (\n SELECT id FROM rag_output WHERE course = $1)",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid"
9+ ]
10+ },
11+ "nullable": []
12+ },
13+ "hash": "43d5cd5b3c47c16859989d22ad3a672b6ecd3a55bebac6efa1ade9a7620b564a"
14+}
.sqlx/query-4a7ac53dc8e09c518c8f2cf1a992062f7c591143cdb056bf5a250235bbb12609.jsonadded+14 -0
@@ -0,0 +1,14 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "DELETE FROM homework_assignment WHERE homework = $1",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid"
9+ ]
10+ },
11+ "nullable": []
12+ },
13+ "hash": "4a7ac53dc8e09c518c8f2cf1a992062f7c591143cdb056bf5a250235bbb12609"
14+}
.sqlx/query-4ade3a1620e48bd3d8bdd32450abc35b300037ef875d14026eaa226d3e543ef9.jsonadded+14 -0
@@ -0,0 +1,14 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "DELETE FROM class_blueprint WHERE id = $1",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid"
9+ ]
10+ },
11+ "nullable": []
12+ },
13+ "hash": "4ade3a1620e48bd3d8bdd32450abc35b300037ef875d14026eaa226d3e543ef9"
14+}
.sqlx/query-4caddc18b673f2dfff6b63b51b271b205edd9f9550412eeba7f22e16a16971f2.jsondeleted+0 -113
@@ -1,113 +0,0 @@
1-{
2- "db_name": "PostgreSQL",
3- "query": "UPDATE course SET teachers = array_remove(teachers, $2)\n WHERE id = $1\n RETURNING id AS \"id: CourseId\", creator AS \"creator: UserId\",\n teachers AS \"teachers: Vec<UserId>\", title AS \"title: CourseTitle\",\n description AS \"description: CourseDescription\",\n kind AS \"kind: CourseKind\", term AS \"term: TermId\", capacity",
4- "describe": {
5- "columns": [
6- {
7- "ordinal": 0,
8- "name": "id: CourseId",
9- "type_info": "Uuid",
10- "origin": {
11- "Table": {
12- "table": "course",
13- "name": "id"
14- }
15- }
16- },
17- {
18- "ordinal": 1,
19- "name": "creator: UserId",
20- "type_info": "Uuid",
21- "origin": {
22- "Table": {
23- "table": "course",
24- "name": "creator"
25- }
26- }
27- },
28- {
29- "ordinal": 2,
30- "name": "teachers: Vec<UserId>",
31- "type_info": "UuidArray",
32- "origin": {
33- "Table": {
34- "table": "course",
35- "name": "teachers"
36- }
37- }
38- },
39- {
40- "ordinal": 3,
41- "name": "title: CourseTitle",
42- "type_info": "Text",
43- "origin": {
44- "Table": {
45- "table": "course",
46- "name": "title"
47- }
48- }
49- },
50- {
51- "ordinal": 4,
52- "name": "description: CourseDescription",
53- "type_info": "Text",
54- "origin": {
55- "Table": {
56- "table": "course",
57- "name": "description"
58- }
59- }
60- },
61- {
62- "ordinal": 5,
63- "name": "kind: CourseKind",
64- "type_info": "Text",
65- "origin": {
66- "Table": {
67- "table": "course",
68- "name": "kind"
69- }
70- }
71- },
72- {
73- "ordinal": 6,
74- "name": "term: TermId",
75- "type_info": "Uuid",
76- "origin": {
77- "Table": {
78- "table": "course",
79- "name": "term"
80- }
81- }
82- },
83- {
84- "ordinal": 7,
85- "name": "capacity",
86- "type_info": "Int8",
87- "origin": {
88- "Table": {
89- "table": "course",
90- "name": "capacity"
91- }
92- }
93- }
94- ],
95- "parameters": {
96- "Left": [
97- "Uuid",
98- "Uuid"
99- ]
100- },
101- "nullable": [
102- false,
103- false,
104- false,
105- false,
106- false,
107- false,
108- true,
109- true
110- ]
111- },
112- "hash": "4caddc18b673f2dfff6b63b51b271b205edd9f9550412eeba7f22e16a16971f2"
113-}
.sqlx/query-4ef82265de6a27ab50351320b610fe0412bbf6be669731377fa8bf033f5cc072.jsonadded+14 -0
@@ -0,0 +1,14 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "DELETE FROM dietary_profile_tag WHERE student = $1",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid"
9+ ]
10+ },
11+ "nullable": []
12+ },
13+ "hash": "4ef82265de6a27ab50351320b610fe0412bbf6be669731377fa8bf033f5cc072"
14+}
.sqlx/query-092ffc9c8c3d159f1792968df3591104dcd0e08206d94a092646c0cea5aff32a.json → .sqlx/query-5258fa19ca184606b7078160ecbc6717830c3ca1ff9954c376d6c9c674ff4b5b.jsonrenamed+5 -10
@@ -1,6 +1,6 @@
1 {1 {
2 "db_name": "PostgreSQL",2 "db_name": "PostgreSQL",
3- "query": "WITH seat AS (\n UPDATE app_user SET board_count = board_count + 1\n WHERE id = $1 AND board_count < $2\n RETURNING 1)\n INSERT INTO board (id, creator, title, participants, locked, locked_by, locked_at,\n epoch, closed_at, created_at)\n SELECT $3, $1, $4, $5, false, NULL, NULL, 0, NULL, $6\n WHERE EXISTS (SELECT 1 FROM seat)\n RETURNING id AS \"id: BoardId\", creator AS \"creator: UserId\",\n title AS \"title: BoardTitle\",\n participants AS \"participants: Vec<UserId>\", locked,\n locked_by AS \"locked_by: UserId\",\n locked_at AS \"locked_at: Timestamp\", epoch,\n closed_at AS \"closed_at: Timestamp\",\n created_at AS \"created_at: Timestamp\"",3+ "query": "WITH seat AS (\n UPDATE app_user SET board_count = board_count + 1\n WHERE id = $1 AND board_count < $2\n RETURNING 1),\n new_board AS (\n INSERT INTO board (id, creator, title, locked, locked_by, locked_at,\n epoch, closed_at, created_at)\n SELECT $3, $1, $4, false, NULL, NULL, 0, NULL, $6\n WHERE EXISTS (SELECT 1 FROM seat)\n RETURNING id, creator, title, locked, locked_by, locked_at,\n epoch, closed_at, created_at),\n roster AS (\n INSERT INTO board_participant (board, participant)\n SELECT $3, t.x FROM unnest($5::uuid[]) AS t(x)\n WHERE EXISTS (SELECT 1 FROM new_board)\n RETURNING participant)\n SELECT nb.id AS \"id: BoardId\", nb.creator AS \"creator: UserId\",\n nb.title AS \"title: BoardTitle\",\n COALESCE((SELECT array_agg(r.participant ORDER BY r.participant)\n FROM roster r), '{}')\n AS \"participants!: Vec<UserId>\",\n nb.locked, nb.locked_by AS \"locked_by: UserId\",\n nb.locked_at AS \"locked_at: Timestamp\", nb.epoch,\n nb.closed_at AS \"closed_at: Timestamp\",\n nb.created_at AS \"created_at: Timestamp\"\n FROM new_board nb",
4 "describe": {4 "describe": {
5 "columns": [5 "columns": [
6 {6 {
@@ -38,14 +38,9 @@
38 },38 },
39 {39 {
40 "ordinal": 3,40 "ordinal": 3,
41- "name": "participants: Vec<UserId>",41+ "name": "participants!: Vec<UserId>",
42 "type_info": "UuidArray",42 "type_info": "UuidArray",
43- "origin": {43+ "origin": "Expression"
44- "Table": {
45- "table": "board",
46- "name": "participants"
47- }
48- }
49 },44 },
50 {45 {
51 "ordinal": 4,46 "ordinal": 4,
@@ -128,7 +123,7 @@
128 false,123 false,
129 false,124 false,
130 false,125 false,
131- false,126+ null,
132 false,127 false,
133 true,128 true,
134 true,129 true,
@@ -137,5 +132,5 @@
137 false132 false
138 ]133 ]
139 },134 },
140- "hash": "092ffc9c8c3d159f1792968df3591104dcd0e08206d94a092646c0cea5aff32a"135+ "hash": "5258fa19ca184606b7078160ecbc6717830c3ca1ff9954c376d6c9c674ff4b5b"
141 }136 }
.sqlx/query-532d2d0011fe140007ad8f56fa63229d4ba5108df18938a8629ecfb70725b5ff.jsonadded+40 -0
@@ -0,0 +1,40 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "SELECT output, source AS \"source: CourseNoteFileId\"\n FROM rag_output_source WHERE output = ANY($1) ORDER BY source",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "output",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "rag_output_source",
13+ "name": "output"
14+ }
15+ }
16+ },
17+ {
18+ "ordinal": 1,
19+ "name": "source: CourseNoteFileId",
20+ "type_info": "Uuid",
21+ "origin": {
22+ "Table": {
23+ "table": "rag_output_source",
24+ "name": "source"
25+ }
26+ }
27+ }
28+ ],
29+ "parameters": {
30+ "Left": [
31+ "UuidArray"
32+ ]
33+ },
34+ "nullable": [
35+ false,
36+ false
37+ ]
38+ },
39+ "hash": "532d2d0011fe140007ad8f56fa63229d4ba5108df18938a8629ecfb70725b5ff"
40+}
.sqlx/query-54a4303671c7acb834b45dabd55d93332990a094273f6ac2adb05bf94397010f.jsondeleted+0 -14
@@ -1,14 +0,0 @@
1-{
2- "db_name": "PostgreSQL",
3- "query": "UPDATE course SET teachers = array_remove(teachers, $1)\n WHERE $1 = ANY(teachers)",
4- "describe": {
5- "columns": [],
6- "parameters": {
7- "Left": [
8- "Uuid"
9- ]
10- },
11- "nullable": []
12- },
13- "hash": "54a4303671c7acb834b45dabd55d93332990a094273f6ac2adb05bf94397010f"
14-}
.sqlx/query-553487a166d9b3d9c0e3d4c7a5270c13768fb537393c70e006466df156a319a2.jsonadded+105 -0
@@ -0,0 +1,105 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "INSERT INTO course (id, creator, title, description, kind, term, capacity)\n VALUES ($1, $2, $3, $4, $5, NULL, $6)\n RETURNING id AS \"id: CourseId\", creator AS \"creator: UserId\",\n title AS \"title: CourseTitle\",\n description AS \"description: CourseDescription\",\n kind AS \"kind: CourseKind\", term AS \"term: TermId\", capacity",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "id: CourseId",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "course",
13+ "name": "id"
14+ }
15+ }
16+ },
17+ {
18+ "ordinal": 1,
19+ "name": "creator: UserId",
20+ "type_info": "Uuid",
21+ "origin": {
22+ "Table": {
23+ "table": "course",
24+ "name": "creator"
25+ }
26+ }
27+ },
28+ {
29+ "ordinal": 2,
30+ "name": "title: CourseTitle",
31+ "type_info": "Text",
32+ "origin": {
33+ "Table": {
34+ "table": "course",
35+ "name": "title"
36+ }
37+ }
38+ },
39+ {
40+ "ordinal": 3,
41+ "name": "description: CourseDescription",
42+ "type_info": "Text",
43+ "origin": {
44+ "Table": {
45+ "table": "course",
46+ "name": "description"
47+ }
48+ }
49+ },
50+ {
51+ "ordinal": 4,
52+ "name": "kind: CourseKind",
53+ "type_info": "Text",
54+ "origin": {
55+ "Table": {
56+ "table": "course",
57+ "name": "kind"
58+ }
59+ }
60+ },
61+ {
62+ "ordinal": 5,
63+ "name": "term: TermId",
64+ "type_info": "Uuid",
65+ "origin": {
66+ "Table": {
67+ "table": "course",
68+ "name": "term"
69+ }
70+ }
71+ },
72+ {
73+ "ordinal": 6,
74+ "name": "capacity",
75+ "type_info": "Int8",
76+ "origin": {
77+ "Table": {
78+ "table": "course",
79+ "name": "capacity"
80+ }
81+ }
82+ }
83+ ],
84+ "parameters": {
85+ "Left": [
86+ "Uuid",
87+ "Uuid",
88+ "Text",
89+ "Text",
90+ "Text",
91+ "Int8"
92+ ]
93+ },
94+ "nullable": [
95+ false,
96+ false,
97+ false,
98+ false,
99+ false,
100+ true,
101+ true
102+ ]
103+ },
104+ "hash": "553487a166d9b3d9c0e3d4c7a5270c13768fb537393c70e006466df156a319a2"
105+}
.sqlx/query-57a63446535fbaf09ea123221182709ac1102fcafffd227c1fa1dc4e36a944af.jsonadded+28 -0
@@ -0,0 +1,28 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "SELECT id FROM board WHERE id = $1 FOR NO KEY UPDATE",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "id",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "board",
13+ "name": "id"
14+ }
15+ }
16+ }
17+ ],
18+ "parameters": {
19+ "Left": [
20+ "Uuid"
21+ ]
22+ },
23+ "nullable": [
24+ false
25+ ]
26+ },
27+ "hash": "57a63446535fbaf09ea123221182709ac1102fcafffd227c1fa1dc4e36a944af"
28+}
.sqlx/query-a70bfbf0b8ea81aab2f5b907a40ed1a4236cff0484bf3bc652e24133407283e5.json → .sqlx/query-59e72e6dab4c94b31994810b4bf1d195587319a4ab757166a046b394e86938a5.jsonrenamed+2 -3
@@ -1,6 +1,6 @@
1 {1 {
2 "db_name": "PostgreSQL",2 "db_name": "PostgreSQL",
3- "query": "WITH seat AS (\n UPDATE subject SET homework_count = homework_count + 1\n WHERE id = $1\n RETURNING 1\n )\n INSERT INTO homework (id, course, subject, title, description, due_at, assigned, created_by, created_at)\n SELECT $2, $3, $1, $4, $5, $6, $7, $8, $9 WHERE EXISTS (SELECT 1 FROM seat)\n RETURNING id AS \"id: HomeworkId\",\n course AS \"course: CourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END\n AS \"assigned: Vec<UserId>\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"",3+ "query": "WITH seat AS (\n UPDATE subject SET homework_count = homework_count + 1\n WHERE id = $1\n RETURNING 1\n )\n INSERT INTO homework (id, course, subject, title, description, due_at, created_by, created_at)\n SELECT $2, $3, $1, $4, $5, $6, $7, $8 WHERE EXISTS (SELECT 1 FROM seat)\n RETURNING id AS \"id: HomeworkId\",\n course AS \"course: CourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n NULL::uuid[] AS \"assigned: Vec<UserId>\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"",
4 "describe": {4 "describe": {
5 "columns": [5 "columns": [
6 {6 {
@@ -106,7 +106,6 @@
106 "Text",106 "Text",
107 "Text",107 "Text",
108 "Int8",108 "Int8",
109- "UuidArray",
110 "Uuid",109 "Uuid",
111 "Int8"110 "Int8"
112 ]111 ]
@@ -123,5 +122,5 @@
123 false122 false
124 ]123 ]
125 },124 },
126- "hash": "a70bfbf0b8ea81aab2f5b907a40ed1a4236cff0484bf3bc652e24133407283e5"125+ "hash": "59e72e6dab4c94b31994810b4bf1d195587319a4ab757166a046b394e86938a5"
127 }126 }
.sqlx/query-bac093371039a68fb29a6739b77ad3e835ae128d3c7f0a712793da3cbdd9d429.json → .sqlx/query-5d88e06f2106d13aa6bc807c6c7dfae53259b9db0048d350758a546836021e3c.jsonrenamed+5 -17
@@ -1,16 +1,16 @@
1 {1 {
2 "db_name": "PostgreSQL",2 "db_name": "PostgreSQL",
3- "query": "SELECT grade AS \"id: ClassBlueprintId\", grade AS \"grade: ClassGrade\",\n courses AS \"courses: Vec<CourseId>\", creator AS \"creator: UserId\"\n FROM class_blueprint WHERE grade = $1",3+ "query": "SELECT id AS \"key: uuid::Uuid\", grade AS \"grade: ClassGrade\",\n creator AS \"creator: UserId\"\n FROM class_blueprint WHERE grade = $1 FOR UPDATE",
4 "describe": {4 "describe": {
5 "columns": [5 "columns": [
6 {6 {
7 "ordinal": 0,7 "ordinal": 0,
8- "name": "id: ClassBlueprintId",8+ "name": "key: uuid::Uuid",
9- "type_info": "Text",9+ "type_info": "Uuid",
10 "origin": {10 "origin": {
11 "Table": {11 "Table": {
12 "table": "class_blueprint",12 "table": "class_blueprint",
13- "name": "grade"13+ "name": "id"
14 }14 }
15 }15 }
16 },16 },
@@ -27,17 +27,6 @@
27 },27 },
28 {28 {
29 "ordinal": 2,29 "ordinal": 2,
30- "name": "courses: Vec<CourseId>",
31- "type_info": "UuidArray",
32- "origin": {
33- "Table": {
34- "table": "class_blueprint",
35- "name": "courses"
36- }
37- }
38- },
39- {
40- "ordinal": 3,
41 "name": "creator: UserId",30 "name": "creator: UserId",
42 "type_info": "Uuid",31 "type_info": "Uuid",
43 "origin": {32 "origin": {
@@ -54,11 +43,10 @@
54 ]43 ]
55 },44 },
56 "nullable": [45 "nullable": [
57- false,
58 false,46 false,
59 false,47 false,
60 false48 false
61 ]49 ]
62 },50 },
63- "hash": "bac093371039a68fb29a6739b77ad3e835ae128d3c7f0a712793da3cbdd9d429"51+ "hash": "5d88e06f2106d13aa6bc807c6c7dfae53259b9db0048d350758a546836021e3c"
64 }52 }
.sqlx/query-97e71a885347d2ee6ee809e3608825b108349bb0dde0046d5817dfcc56d6a583.json → .sqlx/query-60dc8924b722dbdeafa1686248b574aca9089ae24b9d87521a134267f4f76caa.jsonrenamed+3 -4
@@ -1,6 +1,6 @@
1 {1 {
2 "db_name": "PostgreSQL",2 "db_name": "PostgreSQL",
3- "query": "UPDATE homework SET subject = $2, title = $3, description = $4,\n due_at = $5, assigned = $6\n WHERE id = $1\n RETURNING id AS \"id: HomeworkId\",\n course AS \"course: CourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END\n AS \"assigned: Vec<UserId>\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"",3+ "query": "UPDATE homework SET subject = $2, title = $3, description = $4,\n due_at = $5\n WHERE id = $1\n RETURNING id AS \"id: HomeworkId\",\n course AS \"course: CourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a\n WHERE a.homework = homework.id) AS \"assigned: Vec<UserId>\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"",
4 "describe": {4 "describe": {
5 "columns": [5 "columns": [
6 {6 {
@@ -104,8 +104,7 @@
104 "Uuid",104 "Uuid",
105 "Text",105 "Text",
106 "Text",106 "Text",
107- "Int8",107+ "Int8"
108- "UuidArray"
109 ]108 ]
110 },109 },
111 "nullable": [110 "nullable": [
@@ -120,5 +119,5 @@
120 false119 false
121 ]120 ]
122 },121 },
123- "hash": "97e71a885347d2ee6ee809e3608825b108349bb0dde0046d5817dfcc56d6a583"122+ "hash": "60dc8924b722dbdeafa1686248b574aca9089ae24b9d87521a134267f4f76caa"
124 }123 }
.sqlx/query-61c84c00d51c17a737b8358ac320d7b7d17420cdc12bd26939b3eca27088d275.jsonadded+14 -0
@@ -0,0 +1,14 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "DELETE FROM homework_assignment WHERE homework IN (\n SELECT id FROM homework WHERE course = $1)",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid"
9+ ]
10+ },
11+ "nullable": []
12+ },
13+ "hash": "61c84c00d51c17a737b8358ac320d7b7d17420cdc12bd26939b3eca27088d275"
14+}
.sqlx/query-633c525f787d9597ef6d6e5ca7019918a413158e9446b39fe5b69da534810e60.jsondeleted+0 -15
@@ -1,15 +0,0 @@
1-{
2- "db_name": "PostgreSQL",
3- "query": "DELETE FROM class_blueprint WHERE grade = $1 AND courses = $2",
4- "describe": {
5- "columns": [],
6- "parameters": {
7- "Left": [
8- "Text",
9- "UuidArray"
10- ]
11- },
12- "nullable": []
13- },
14- "hash": "633c525f787d9597ef6d6e5ca7019918a413158e9446b39fe5b69da534810e60"
15-}
.sqlx/query-63bdf7314ccc48750af75af20167e573b36ded45dc3f8050b95ea6823ae3177a.jsonadded+14 -0
@@ -0,0 +1,14 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "DELETE FROM menu_dish_tag WHERE dish = $1",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid"
9+ ]
10+ },
11+ "nullable": []
12+ },
13+ "hash": "63bdf7314ccc48750af75af20167e573b36ded45dc3f8050b95ea6823ae3177a"
14+}
.sqlx/query-42ec2891956481a4fb70b81cc230621f4481f2fc57e10e3680043fb83c850c66.json → .sqlx/query-63e9be4296079ff969f4a3e464e6dd9ad20d54e788a7af2e04e50658bcc1c45c.jsonrenamed+5 -10
@@ -1,6 +1,6 @@
1 {1 {
2 "db_name": "PostgreSQL",2 "db_name": "PostgreSQL",
3- "query": "SELECT id AS \"id: MenuDishId\", menu AS \"menu: MenuId\", name AS \"name: DishName\", description AS \"description: DishDescription\", price_minor AS \"price_minor: DishPrice\", tags AS \"tags: DishTags\", created_at AS \"created_at: Timestamp\"\n FROM menu_dish WHERE id = $1",3+ "query": "SELECT id AS \"id: MenuDishId\", menu AS \"menu: MenuId\", name AS \"name: DishName\", description AS \"description: DishDescription\", price_minor AS \"price_minor: DishPrice\",\n COALESCE((SELECT array_agg(t.tag ORDER BY t.ord) FROM menu_dish_tag t WHERE t.dish = menu_dish.id), '{}'::text[]) AS \"tags!: DishTags\",\n created_at AS \"created_at: Timestamp\"\n FROM menu_dish WHERE id = $1",
4 "describe": {4 "describe": {
5 "columns": [5 "columns": [
6 {6 {
@@ -60,14 +60,9 @@
60 },60 },
61 {61 {
62 "ordinal": 5,62 "ordinal": 5,
63- "name": "tags: DishTags",63+ "name": "tags!: DishTags",
64 "type_info": "TextArray",64 "type_info": "TextArray",
65- "origin": {65+ "origin": "Expression"
66- "Table": {
67- "table": "menu_dish",
68- "name": "tags"
69- }
70- }
71 },66 },
72 {67 {
73 "ordinal": 6,68 "ordinal": 6,
@@ -92,9 +87,9 @@
92 false,87 false,
93 true,88 true,
94 false,89 false,
95- false,90+ null,
96 false91 false
97 ]92 ]
98 },93 },
99- "hash": "42ec2891956481a4fb70b81cc230621f4481f2fc57e10e3680043fb83c850c66"94+ "hash": "63e9be4296079ff969f4a3e464e6dd9ad20d54e788a7af2e04e50658bcc1c45c"
100 }95 }
.sqlx/query-07f5872671b049dca356394ea98c9840bf57fd5e586b4ff36ffabb988a8423c5.json → .sqlx/query-6907da40c5b42ea56fb9c257cd9b486869381275626163e8bd75e928188875b1.jsonrenamed+6 -18
@@ -1,6 +1,6 @@
1 {1 {
2 "db_name": "PostgreSQL",2 "db_name": "PostgreSQL",
3- "query": "SELECT id AS \"id: CourseId\", creator AS \"creator: UserId\",\n teachers AS \"teachers: Vec<UserId>\", title AS \"title: CourseTitle\",\n description AS \"description: CourseDescription\",\n kind AS \"kind: CourseKind\", term AS \"term: TermId\", capacity\n FROM course WHERE id = $1",3+ "query": "SELECT id AS \"id: CourseId\", creator AS \"creator: UserId\",\n title AS \"title: CourseTitle\",\n description AS \"description: CourseDescription\",\n kind AS \"kind: CourseKind\", term AS \"term: TermId\", capacity\n FROM course WHERE id = $1",
4 "describe": {4 "describe": {
5 "columns": [5 "columns": [
6 {6 {
@@ -27,17 +27,6 @@
27 },27 },
28 {28 {
29 "ordinal": 2,29 "ordinal": 2,
30- "name": "teachers: Vec<UserId>",
31- "type_info": "UuidArray",
32- "origin": {
33- "Table": {
34- "table": "course",
35- "name": "teachers"
36- }
37- }
38- },
39- {
40- "ordinal": 3,
41 "name": "title: CourseTitle",30 "name": "title: CourseTitle",
42 "type_info": "Text",31 "type_info": "Text",
43 "origin": {32 "origin": {
@@ -48,7 +37,7 @@
48 }37 }
49 },38 },
50 {39 {
51- "ordinal": 4,40+ "ordinal": 3,
52 "name": "description: CourseDescription",41 "name": "description: CourseDescription",
53 "type_info": "Text",42 "type_info": "Text",
54 "origin": {43 "origin": {
@@ -59,7 +48,7 @@
59 }48 }
60 },49 },
61 {50 {
62- "ordinal": 5,51+ "ordinal": 4,
63 "name": "kind: CourseKind",52 "name": "kind: CourseKind",
64 "type_info": "Text",53 "type_info": "Text",
65 "origin": {54 "origin": {
@@ -70,7 +59,7 @@
70 }59 }
71 },60 },
72 {61 {
73- "ordinal": 6,62+ "ordinal": 5,
74 "name": "term: TermId",63 "name": "term: TermId",
75 "type_info": "Uuid",64 "type_info": "Uuid",
76 "origin": {65 "origin": {
@@ -81,7 +70,7 @@
81 }70 }
82 },71 },
83 {72 {
84- "ordinal": 7,73+ "ordinal": 6,
85 "name": "capacity",74 "name": "capacity",
86 "type_info": "Int8",75 "type_info": "Int8",
87 "origin": {76 "origin": {
@@ -103,10 +92,9 @@
103 false,92 false,
104 false,93 false,
105 false,94 false,
106- false,
107 true,95 true,
108 true96 true
109 ]97 ]
110 },98 },
111- "hash": "07f5872671b049dca356394ea98c9840bf57fd5e586b4ff36ffabb988a8423c5"99+ "hash": "6907da40c5b42ea56fb9c257cd9b486869381275626163e8bd75e928188875b1"
112 }100 }
.sqlx/query-69308bfda3e686112dfaa6493e2729e250ce149537408ac7b0124b3d33582980.jsondeleted+0 -14
@@ -1,14 +0,0 @@
1-{
2- "db_name": "PostgreSQL",
3- "query": "UPDATE course SET teachers = array_remove(teachers, $1) WHERE $1 = ANY(teachers)",
4- "describe": {
5- "columns": [],
6- "parameters": {
7- "Left": [
8- "Uuid"
9- ]
10- },
11- "nullable": []
12- },
13- "hash": "69308bfda3e686112dfaa6493e2729e250ce149537408ac7b0124b3d33582980"
14-}
.sqlx/query-96175480de70dd3d01e7b9d4a5edd779f04ace47d43143e0e1ed353c3a8ce3fc.json → .sqlx/query-6c518ef0581ca1549988917c39135198f1bf92d9a7b4984b227849771bec8699.jsonrenamed+2 -2
@@ -1,6 +1,6 @@
1 {1 {
2 "db_name": "PostgreSQL",2 "db_name": "PostgreSQL",
3- "query": "SELECT id AS \"id: HomeworkId\",\n course AS \"course: CourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END\n AS \"assigned: Vec<UserId>\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"\n FROM homework ORDER BY id DESC",3+ "query": "SELECT id AS \"id: HomeworkId\",\n course AS \"course: CourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a\n WHERE a.homework = homework.id) AS \"assigned: Vec<UserId>\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"\n FROM homework ORDER BY id DESC",
4 "describe": {4 "describe": {
5 "columns": [5 "columns": [
6 {6 {
@@ -113,5 +113,5 @@
113 false113 false
114 ]114 ]
115 },115 },
116- "hash": "96175480de70dd3d01e7b9d4a5edd779f04ace47d43143e0e1ed353c3a8ce3fc"116+ "hash": "6c518ef0581ca1549988917c39135198f1bf92d9a7b4984b227849771bec8699"
117 }117 }
.sqlx/query-6ce14f236c940b29b7107569aed2d0c176065c36a5ba34a1757c9f3cef17d15f.jsonadded+132 -0
@@ -0,0 +1,132 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "SELECT b.id AS \"id: BoardId\", b.creator AS \"creator: UserId\",\n b.title AS \"title: BoardTitle\",\n ARRAY(SELECT p.participant FROM board_participant p\n WHERE p.board = b.id ORDER BY p.participant)\n AS \"participants!: Vec<UserId>\",\n b.locked, b.locked_by AS \"locked_by: UserId\",\n b.locked_at AS \"locked_at: Timestamp\", b.epoch,\n b.closed_at AS \"closed_at: Timestamp\",\n b.created_at AS \"created_at: Timestamp\"\n FROM board b\n WHERE b.id = ANY($1::uuid[]) OR b.creator = $2\n ORDER BY b.id",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "id: BoardId",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "board",
13+ "name": "id"
14+ }
15+ }
16+ },
17+ {
18+ "ordinal": 1,
19+ "name": "creator: UserId",
20+ "type_info": "Uuid",
21+ "origin": {
22+ "Table": {
23+ "table": "board",
24+ "name": "creator"
25+ }
26+ }
27+ },
28+ {
29+ "ordinal": 2,
30+ "name": "title: BoardTitle",
31+ "type_info": "Text",
32+ "origin": {
33+ "Table": {
34+ "table": "board",
35+ "name": "title"
36+ }
37+ }
38+ },
39+ {
40+ "ordinal": 3,
41+ "name": "participants!: Vec<UserId>",
42+ "type_info": "UuidArray",
43+ "origin": "Expression"
44+ },
45+ {
46+ "ordinal": 4,
47+ "name": "locked",
48+ "type_info": "Bool",
49+ "origin": {
50+ "Table": {
51+ "table": "board",
52+ "name": "locked"
53+ }
54+ }
55+ },
56+ {
57+ "ordinal": 5,
58+ "name": "locked_by: UserId",
59+ "type_info": "Uuid",
60+ "origin": {
61+ "Table": {
62+ "table": "board",
63+ "name": "locked_by"
64+ }
65+ }
66+ },
67+ {
68+ "ordinal": 6,
69+ "name": "locked_at: Timestamp",
70+ "type_info": "Int8",
71+ "origin": {
72+ "Table": {
73+ "table": "board",
74+ "name": "locked_at"
75+ }
76+ }
77+ },
78+ {
79+ "ordinal": 7,
80+ "name": "epoch",
81+ "type_info": "Int8",
82+ "origin": {
83+ "Table": {
84+ "table": "board",
85+ "name": "epoch"
86+ }
87+ }
88+ },
89+ {
90+ "ordinal": 8,
91+ "name": "closed_at: Timestamp",
92+ "type_info": "Int8",
93+ "origin": {
94+ "Table": {
95+ "table": "board",
96+ "name": "closed_at"
97+ }
98+ }
99+ },
100+ {
101+ "ordinal": 9,
102+ "name": "created_at: Timestamp",
103+ "type_info": "Int8",
104+ "origin": {
105+ "Table": {
106+ "table": "board",
107+ "name": "created_at"
108+ }
109+ }
110+ }
111+ ],
112+ "parameters": {
113+ "Left": [
114+ "UuidArray",
115+ "Uuid"
116+ ]
117+ },
118+ "nullable": [
119+ false,
120+ false,
121+ false,
122+ null,
123+ false,
124+ true,
125+ true,
126+ false,
127+ true,
128+ false
129+ ]
130+ },
131+ "hash": "6ce14f236c940b29b7107569aed2d0c176065c36a5ba34a1757c9f3cef17d15f"
132+}
.sqlx/query-5942f054f1c660ec1eaf894afdf37c2ed8aa3ec0dfecf243b26193210619377f.json → .sqlx/query-6ce455efe2f18ee3bf4a217db31b91d188bfff40e5e1e0af2789e92ca110c71f.jsonrenamed+6 -18
@@ -1,6 +1,6 @@
1 {1 {
2 "db_name": "PostgreSQL",2 "db_name": "PostgreSQL",
3- "query": "SELECT id AS \"id: CourseId\", creator AS \"creator: UserId\",\n teachers AS \"teachers: Vec<UserId>\", title AS \"title: CourseTitle\",\n description AS \"description: CourseDescription\",\n kind AS \"kind: CourseKind\", term AS \"term: TermId\", capacity\n FROM course WHERE creator = $1 OR $2 = ANY(teachers) ORDER BY id DESC",3+ "query": "SELECT id AS \"id: CourseId\", creator AS \"creator: UserId\",\n title AS \"title: CourseTitle\",\n description AS \"description: CourseDescription\",\n kind AS \"kind: CourseKind\", term AS \"term: TermId\", capacity\n FROM course WHERE creator = $1 OR id IN (\n SELECT course FROM course_teacher WHERE teacher = $2)\n ORDER BY id DESC",
4 "describe": {4 "describe": {
5 "columns": [5 "columns": [
6 {6 {
@@ -27,17 +27,6 @@
27 },27 },
28 {28 {
29 "ordinal": 2,29 "ordinal": 2,
30- "name": "teachers: Vec<UserId>",
31- "type_info": "UuidArray",
32- "origin": {
33- "Table": {
34- "table": "course",
35- "name": "teachers"
36- }
37- }
38- },
39- {
40- "ordinal": 3,
41 "name": "title: CourseTitle",30 "name": "title: CourseTitle",
42 "type_info": "Text",31 "type_info": "Text",
43 "origin": {32 "origin": {
@@ -48,7 +37,7 @@
48 }37 }
49 },38 },
50 {39 {
51- "ordinal": 4,40+ "ordinal": 3,
52 "name": "description: CourseDescription",41 "name": "description: CourseDescription",
53 "type_info": "Text",42 "type_info": "Text",
54 "origin": {43 "origin": {
@@ -59,7 +48,7 @@
59 }48 }
60 },49 },
61 {50 {
62- "ordinal": 5,51+ "ordinal": 4,
63 "name": "kind: CourseKind",52 "name": "kind: CourseKind",
64 "type_info": "Text",53 "type_info": "Text",
65 "origin": {54 "origin": {
@@ -70,7 +59,7 @@
70 }59 }
71 },60 },
72 {61 {
73- "ordinal": 6,62+ "ordinal": 5,
74 "name": "term: TermId",63 "name": "term: TermId",
75 "type_info": "Uuid",64 "type_info": "Uuid",
76 "origin": {65 "origin": {
@@ -81,7 +70,7 @@
81 }70 }
82 },71 },
83 {72 {
84- "ordinal": 7,73+ "ordinal": 6,
85 "name": "capacity",74 "name": "capacity",
86 "type_info": "Int8",75 "type_info": "Int8",
87 "origin": {76 "origin": {
@@ -104,10 +93,9 @@
104 false,93 false,
105 false,94 false,
106 false,95 false,
107- false,
108 true,96 true,
109 true97 true
110 ]98 ]
111 },99 },
112- "hash": "5942f054f1c660ec1eaf894afdf37c2ed8aa3ec0dfecf243b26193210619377f"100+ "hash": "6ce455efe2f18ee3bf4a217db31b91d188bfff40e5e1e0af2789e92ca110c71f"
113 }101 }
.sqlx/query-3dbbe1738727b434a5bf46e535e16b293dc59a120c861b79ab3166cf0a0e27df.json → .sqlx/query-6fcc2a42e243df55569ca080ec3cbb8a71f134255f4f9283bbde0e90537c6501.jsonrenamed+5 -10
@@ -1,6 +1,6 @@
1 {1 {
2 "db_name": "PostgreSQL",2 "db_name": "PostgreSQL",
3- "query": "UPDATE board SET title = $2 WHERE id = $1\n RETURNING id AS \"id: BoardId\", creator AS \"creator: UserId\",\n title AS \"title: BoardTitle\",\n participants AS \"participants: Vec<UserId>\", locked,\n locked_by AS \"locked_by: UserId\",\n locked_at AS \"locked_at: Timestamp\", epoch,\n closed_at AS \"closed_at: Timestamp\",\n created_at AS \"created_at: Timestamp\"",3+ "query": "UPDATE board SET title = $2 WHERE id = $1\n RETURNING id AS \"id: BoardId\", creator AS \"creator: UserId\",\n title AS \"title: BoardTitle\",\n ARRAY(SELECT p.participant FROM board_participant p\n WHERE p.board = board.id ORDER BY p.participant)\n AS \"participants!: Vec<UserId>\", locked,\n locked_by AS \"locked_by: UserId\",\n locked_at AS \"locked_at: Timestamp\", epoch,\n closed_at AS \"closed_at: Timestamp\",\n created_at AS \"created_at: Timestamp\"",
4 "describe": {4 "describe": {
5 "columns": [5 "columns": [
6 {6 {
@@ -38,14 +38,9 @@
38 },38 },
39 {39 {
40 "ordinal": 3,40 "ordinal": 3,
41- "name": "participants: Vec<UserId>",41+ "name": "participants!: Vec<UserId>",
42 "type_info": "UuidArray",42 "type_info": "UuidArray",
43- "origin": {43+ "origin": "Expression"
44- "Table": {
45- "table": "board",
46- "name": "participants"
47- }
48- }
49 },44 },
50 {45 {
51 "ordinal": 4,46 "ordinal": 4,
@@ -124,7 +119,7 @@
124 false,119 false,
125 false,120 false,
126 false,121 false,
127- false,122+ null,
128 false,123 false,
129 true,124 true,
130 true,125 true,
@@ -133,5 +128,5 @@
133 false128 false
134 ]129 ]
135 },130 },
136- "hash": "3dbbe1738727b434a5bf46e535e16b293dc59a120c861b79ab3166cf0a0e27df"131+ "hash": "6fcc2a42e243df55569ca080ec3cbb8a71f134255f4f9283bbde0e90537c6501"
137 }132 }
.sqlx/query-3b8dd2053a8627a7e965b5aabb4640b02fbf9653ac9da6af47e5d0732e611a29.json → .sqlx/query-72cd9aa43384131ba5489ac5b79e9108aabe3ddb6dc9522530787d3fa632b595.jsonrenamed+2 -2
@@ -1,6 +1,6 @@
1 {1 {
2 "db_name": "PostgreSQL",2 "db_name": "PostgreSQL",
3- "query": "SELECT id AS \"id: HomeworkId\",\n course AS \"course: CourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END\n AS \"assigned: Vec<UserId>\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"\n FROM homework WHERE course = $1 ORDER BY id DESC",3+ "query": "SELECT id AS \"id: HomeworkId\",\n course AS \"course: CourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a\n WHERE a.homework = homework.id) AS \"assigned: Vec<UserId>\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"\n FROM homework WHERE id = $1",
4 "describe": {4 "describe": {
5 "columns": [5 "columns": [
6 {6 {
@@ -115,5 +115,5 @@
115 false115 false
116 ]116 ]
117 },117 },
118- "hash": "3b8dd2053a8627a7e965b5aabb4640b02fbf9653ac9da6af47e5d0732e611a29"118+ "hash": "72cd9aa43384131ba5489ac5b79e9108aabe3ddb6dc9522530787d3fa632b595"
119 }119 }
.sqlx/query-743dc724aee85af2244e80c69a71610a2d9f88eee804fad8c4936cd23e4770d3.jsonadded+14 -0
@@ -0,0 +1,14 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "DELETE FROM blueprint_course WHERE blueprint = $1",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid"
9+ ]
10+ },
11+ "nullable": []
12+ },
13+ "hash": "743dc724aee85af2244e80c69a71610a2d9f88eee804fad8c4936cd23e4770d3"
14+}
.sqlx/query-771928c37367daef7caef3a0faa381d01bd34a4f4a6559c362499376a0518bfd.jsonadded+12 -0
@@ -0,0 +1,12 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "DELETE FROM settings_dietary_tag WHERE settings = 'school'",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": []
8+ },
9+ "nullable": []
10+ },
11+ "hash": "771928c37367daef7caef3a0faa381d01bd34a4f4a6559c362499376a0518bfd"
12+}
.sqlx/query-800bb78fa5b427d8ccb72cf3ba69e8fb9c8d3bffb022d47939e9ee0269eb764a.jsonadded+15 -0
@@ -0,0 +1,15 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "INSERT INTO blueprint_course (blueprint, course)\n SELECT $1, x FROM unnest($2::uuid[]) AS t(x)\n ON CONFLICT DO NOTHING",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid",
9+ "UuidArray"
10+ ]
11+ },
12+ "nullable": []
13+ },
14+ "hash": "800bb78fa5b427d8ccb72cf3ba69e8fb9c8d3bffb022d47939e9ee0269eb764a"
15+}
.sqlx/query-c9176c3fd78effbb5626b81d72d2f9d02c841a21271501ed5d27f64c8b08fbad.json → .sqlx/query-8cfb7acdfe6bb096f83920c104c8c45fafa1e717db6630c7e3fde77816d9e3a7.jsonrenamed+2 -2
@@ -1,6 +1,6 @@
1 {1 {
2 "db_name": "PostgreSQL",2 "db_name": "PostgreSQL",
3- "query": "SELECT id AS \"id: HomeworkId\",\n course AS \"course: CourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END\n AS \"assigned: Vec<UserId>\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"\n FROM homework WHERE course = ANY($1) ORDER BY id DESC",3+ "query": "SELECT id AS \"id: HomeworkId\",\n course AS \"course: CourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a\n WHERE a.homework = homework.id) AS \"assigned: Vec<UserId>\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"\n FROM homework WHERE course = ANY($1) ORDER BY id DESC",
4 "describe": {4 "describe": {
5 "columns": [5 "columns": [
6 {6 {
@@ -115,5 +115,5 @@
115 false115 false
116 ]116 ]
117 },117 },
118- "hash": "c9176c3fd78effbb5626b81d72d2f9d02c841a21271501ed5d27f64c8b08fbad"118+ "hash": "8cfb7acdfe6bb096f83920c104c8c45fafa1e717db6630c7e3fde77816d9e3a7"
119 }119 }
.sqlx/query-befcf1a2da3632684bcc6d741540c05719315260192d47a8cd50c1d45eb32e8d.json → .sqlx/query-8d7ae20c108d3c74fd9d841f7b36eed4cc0cbc04fc93ff05b33e6c70a91116e2.jsonrenamed+5 -5
@@ -1,16 +1,16 @@
1 {1 {
2 "db_name": "PostgreSQL",2 "db_name": "PostgreSQL",
3- "query": "SELECT courses AS \"courses: Vec<CourseId>\"\n FROM class_blueprint WHERE grade = $1 FOR UPDATE",3+ "query": "SELECT id AS \"key: uuid::Uuid\" FROM class_blueprint\n WHERE grade = $1 FOR UPDATE",
4 "describe": {4 "describe": {
5 "columns": [5 "columns": [
6 {6 {
7 "ordinal": 0,7 "ordinal": 0,
8- "name": "courses: Vec<CourseId>",8+ "name": "key: uuid::Uuid",
9- "type_info": "UuidArray",9+ "type_info": "Uuid",
10 "origin": {10 "origin": {
11 "Table": {11 "Table": {
12 "table": "class_blueprint",12 "table": "class_blueprint",
13- "name": "courses"13+ "name": "id"
14 }14 }
15 }15 }
16 }16 }
@@ -24,5 +24,5 @@
24 false24 false
25 ]25 ]
26 },26 },
27- "hash": "befcf1a2da3632684bcc6d741540c05719315260192d47a8cd50c1d45eb32e8d"27+ "hash": "8d7ae20c108d3c74fd9d841f7b36eed4cc0cbc04fc93ff05b33e6c70a91116e2"
28 }28 }
.sqlx/query-8e4568e7dfb68793acc1aa2a9c142314670484e5eacfdcf9b4fec3ed887b6b0d.jsonadded+15 -0
@@ -0,0 +1,15 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "INSERT INTO blueprint_course (blueprint, course)\n SELECT $1, x FROM unnest($2::uuid[]) AS t(x)\n ON CONFLICT DO NOTHING",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid",
9+ "UuidArray"
10+ ]
11+ },
12+ "nullable": []
13+ },
14+ "hash": "8e4568e7dfb68793acc1aa2a9c142314670484e5eacfdcf9b4fec3ed887b6b0d"
15+}
.sqlx/query-8e687f07237ef09a151a945cd4046978aa69cbda3bd53e1c79157f840edf1443.jsondeleted+0 -107
@@ -1,107 +0,0 @@
1-{
2- "db_name": "PostgreSQL",
3- "query": "INSERT INTO menu_dish (id, menu, name, description, price_minor, tags, created_at)\n SELECT $1, $2, $3, $4, $5, $6, $7\n WHERE (SELECT count(*) FROM menu_dish WHERE menu = $2) < $8\n RETURNING id AS \"id: MenuDishId\", menu AS \"menu: MenuId\", name AS \"name: DishName\", description AS \"description: DishDescription\", price_minor AS \"price_minor: DishPrice\", tags AS \"tags: DishTags\", created_at AS \"created_at: Timestamp\"",
4- "describe": {
5- "columns": [
6- {
7- "ordinal": 0,
8- "name": "id: MenuDishId",
9- "type_info": "Uuid",
10- "origin": {
11- "Table": {
12- "table": "menu_dish",
13- "name": "id"
14- }
15- }
16- },
17- {
18- "ordinal": 1,
19- "name": "menu: MenuId",
20- "type_info": "Text",
21- "origin": {
22- "Table": {
23- "table": "menu_dish",
24- "name": "menu"
25- }
26- }
27- },
28- {
29- "ordinal": 2,
30- "name": "name: DishName",
31- "type_info": "Text",
32- "origin": {
33- "Table": {
34- "table": "menu_dish",
35- "name": "name"
36- }
37- }
38- },
39- {
40- "ordinal": 3,
41- "name": "description: DishDescription",
42- "type_info": "Text",
43- "origin": {
44- "Table": {
45- "table": "menu_dish",
46- "name": "description"
47- }
48- }
49- },
50- {
51- "ordinal": 4,
52- "name": "price_minor: DishPrice",
53- "type_info": "Int8",
54- "origin": {
55- "Table": {
56- "table": "menu_dish",
57- "name": "price_minor"
58- }
59- }
60- },
61- {
62- "ordinal": 5,
63- "name": "tags: DishTags",
64- "type_info": "TextArray",
65- "origin": {
66- "Table": {
67- "table": "menu_dish",
68- "name": "tags"
69- }
70- }
71- },
72- {
73- "ordinal": 6,
74- "name": "created_at: Timestamp",
75- "type_info": "Int8",
76- "origin": {
77- "Table": {
78- "table": "menu_dish",
79- "name": "created_at"
80- }
81- }
82- }
83- ],
84- "parameters": {
85- "Left": [
86- "Uuid",
87- "Text",
88- "Text",
89- "Text",
90- "Int8",
91- "TextArray",
92- "Int8",
93- "Int8"
94- ]
95- },
96- "nullable": [
97- false,
98- false,
99- false,
100- true,
101- false,
102- false,
103- false
104- ]
105- },
106- "hash": "8e687f07237ef09a151a945cd4046978aa69cbda3bd53e1c79157f840edf1443"
107-}
.sqlx/query-409b3b702b6cd4ad4dcd34f5330d20b16f3093821553a6af4f55a53cc4c69fb7.json → .sqlx/query-90ca4d8c108622034298f4da1ac3a4db6a284b2f95e0fe8a69bbec9117f5d0a0.jsonrenamed+2 -2
@@ -1,6 +1,6 @@
1 {1 {
2 "db_name": "PostgreSQL",2 "db_name": "PostgreSQL",
3- "query": "SELECT s.slug AS \"slug: Slug\",\n s.name,\n s.status AS \"status: SchoolStatus\"\n FROM person_school ps\n JOIN school s ON s.slug = ps.school\n WHERE ps.person = $1\n ORDER BY s.slug",3+ "query": "SELECT s.slug AS \"slug: Slug\",\n s.name,\n s.status AS \"status: SchoolStatus\"\n FROM person_school ps\n JOIN school s ON s.id = ps.school\n WHERE ps.person = $1\n ORDER BY s.slug",
4 "describe": {4 "describe": {
5 "columns": [5 "columns": [
6 {6 {
@@ -48,5 +48,5 @@
48 false48 false
49 ]49 ]
50 },50 },
51- "hash": "409b3b702b6cd4ad4dcd34f5330d20b16f3093821553a6af4f55a53cc4c69fb7"51+ "hash": "90ca4d8c108622034298f4da1ac3a4db6a284b2f95e0fe8a69bbec9117f5d0a0"
52 }52 }
.sqlx/query-915d3bcbbe66341824b280bde6cb5eb01f3868fd3d98bd29a9efc85a80176e95.jsonadded+18 -0
@@ -0,0 +1,18 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "UPDATE menu_dish SET\n name = COALESCE($2, name),\n description = CASE WHEN $3 THEN $4 ELSE description END,\n price_minor = COALESCE($5, price_minor)\n WHERE id = $1",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid",
9+ "Text",
10+ "Bool",
11+ "Text",
12+ "Int8"
13+ ]
14+ },
15+ "nullable": []
16+ },
17+ "hash": "915d3bcbbe66341824b280bde6cb5eb01f3868fd3d98bd29a9efc85a80176e95"
18+}
.sqlx/query-935e0ed64846d8c1ad7e317725d31da05a618a6ab0e628482399affad99261c8.jsonadded+137 -0
@@ -0,0 +1,137 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "WITH new_row AS (\n INSERT INTO settings (id, exam_kinds, grade_bands, max_file_bytes,\n chatbot_history_turns, max_chatbot_message_len,\n max_chatbot_threads, meal_slots,\n meal_cancel_cutoff_minutes)\n VALUES ('school', $1, $3, $4, $5, $6, $7, $8, $10)\n ON CONFLICT (id) DO UPDATE SET\n exam_kinds = $1,\n grade_bands = $3,\n max_file_bytes = $4,\n chatbot_history_turns = $5,\n max_chatbot_message_len = $6,\n max_chatbot_threads = $7,\n meal_slots = $8,\n meal_cancel_cutoff_minutes = $10\n WHERE settings.exam_kinds IS NOT DISTINCT FROM $1\n AND settings.grade_bands IS NOT DISTINCT FROM $3\n AND settings.max_file_bytes IS NOT DISTINCT FROM $4\n AND settings.chatbot_history_turns IS NOT DISTINCT FROM $5\n AND settings.max_chatbot_message_len IS NOT DISTINCT FROM $6\n AND settings.max_chatbot_threads IS NOT DISTINCT FROM $7\n AND settings.meal_slots IS NOT DISTINCT FROM $8\n AND settings.meal_cancel_cutoff_minutes IS NOT DISTINCT FROM $10\n AND COALESCE((SELECT array_agg(s.status ORDER BY s.status)\n FROM settings_attendance_status s\n WHERE s.settings = settings.id), '{}')\n IS NOT DISTINCT FROM $11::text[]\n AND (SELECT array_agg(t.tag ORDER BY t.tag)\n FROM settings_dietary_tag t\n WHERE t.settings = settings.id)\n IS NOT DISTINCT FROM $12::text[]\n RETURNING exam_kinds, grade_bands, max_file_bytes,\n chatbot_history_turns, max_chatbot_message_len,\n max_chatbot_threads, meal_slots, meal_cancel_cutoff_minutes),\n status_del AS (\n DELETE FROM settings_attendance_status\n WHERE settings = 'school' AND EXISTS (SELECT 1 FROM new_row)\n RETURNING 1),\n status_ins AS (\n INSERT INTO settings_attendance_status (settings, status)\n SELECT 'school', t.status FROM unnest($2::text[]) AS t(status)\n CROSS JOIN (SELECT count(*) AS deleted FROM status_del) d\n WHERE EXISTS (SELECT 1 FROM new_row)\n RETURNING status),\n tag_del AS (\n DELETE FROM settings_dietary_tag\n WHERE settings = 'school' AND EXISTS (SELECT 1 FROM new_row)\n RETURNING 1),\n tag_ins AS (\n INSERT INTO settings_dietary_tag (settings, tag)\n SELECT 'school', t.tag FROM unnest($9::text[]) AS t(tag)\n CROSS JOIN (SELECT count(*) AS deleted FROM tag_del) d\n WHERE EXISTS (SELECT 1 FROM new_row)\n RETURNING tag)\n SELECT r.exam_kinds AS \"exam_kinds: Json<Vec<ExamKindDef>>\",\n COALESCE((SELECT array_agg(status ORDER BY status)\n FROM status_ins), '{}') AS \"attendance_statuses!: Vec<String>\",\n r.grade_bands AS \"grade_bands: Json<Vec<GradeBand>>\",\n r.max_file_bytes,\n r.chatbot_history_turns,\n r.max_chatbot_message_len,\n r.max_chatbot_threads,\n r.meal_slots AS \"meal_slots: Json<Vec<MealSlotDef>>\",\n (SELECT array_agg(tag ORDER BY tag) FROM tag_ins) AS dietary_tags,\n r.meal_cancel_cutoff_minutes\n FROM new_row r",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "exam_kinds: Json<Vec<ExamKindDef>>",
9+ "type_info": "Jsonb",
10+ "origin": {
11+ "Table": {
12+ "table": "settings",
13+ "name": "exam_kinds"
14+ }
15+ }
16+ },
17+ {
18+ "ordinal": 1,
19+ "name": "attendance_statuses!: Vec<String>",
20+ "type_info": "TextArray",
21+ "origin": "Expression"
22+ },
23+ {
24+ "ordinal": 2,
25+ "name": "grade_bands: Json<Vec<GradeBand>>",
26+ "type_info": "Jsonb",
27+ "origin": {
28+ "Table": {
29+ "table": "settings",
30+ "name": "grade_bands"
31+ }
32+ }
33+ },
34+ {
35+ "ordinal": 3,
36+ "name": "max_file_bytes",
37+ "type_info": "Int8",
38+ "origin": {
39+ "Table": {
40+ "table": "settings",
41+ "name": "max_file_bytes"
42+ }
43+ }
44+ },
45+ {
46+ "ordinal": 4,
47+ "name": "chatbot_history_turns",
48+ "type_info": "Int8",
49+ "origin": {
50+ "Table": {
51+ "table": "settings",
52+ "name": "chatbot_history_turns"
53+ }
54+ }
55+ },
56+ {
57+ "ordinal": 5,
58+ "name": "max_chatbot_message_len",
59+ "type_info": "Int8",
60+ "origin": {
61+ "Table": {
62+ "table": "settings",
63+ "name": "max_chatbot_message_len"
64+ }
65+ }
66+ },
67+ {
68+ "ordinal": 6,
69+ "name": "max_chatbot_threads",
70+ "type_info": "Int8",
71+ "origin": {
72+ "Table": {
73+ "table": "settings",
74+ "name": "max_chatbot_threads"
75+ }
76+ }
77+ },
78+ {
79+ "ordinal": 7,
80+ "name": "meal_slots: Json<Vec<MealSlotDef>>",
81+ "type_info": "Jsonb",
82+ "origin": {
83+ "Table": {
84+ "table": "settings",
85+ "name": "meal_slots"
86+ }
87+ }
88+ },
89+ {
90+ "ordinal": 8,
91+ "name": "dietary_tags",
92+ "type_info": "TextArray",
93+ "origin": "Expression"
94+ },
95+ {
96+ "ordinal": 9,
97+ "name": "meal_cancel_cutoff_minutes",
98+ "type_info": "Int8",
99+ "origin": {
100+ "Table": {
101+ "table": "settings",
102+ "name": "meal_cancel_cutoff_minutes"
103+ }
104+ }
105+ }
106+ ],
107+ "parameters": {
108+ "Left": [
109+ "Jsonb",
110+ "TextArray",
111+ "Jsonb",
112+ "Int8",
113+ "Int8",
114+ "Int8",
115+ "Int8",
116+ "Jsonb",
117+ "TextArray",
118+ "Int8",
119+ "TextArray",
120+ "TextArray"
121+ ]
122+ },
123+ "nullable": [
124+ false,
125+ null,
126+ false,
127+ true,
128+ true,
129+ true,
130+ true,
131+ true,
132+ null,
133+ true
134+ ]
135+ },
136+ "hash": "935e0ed64846d8c1ad7e317725d31da05a618a6ab0e628482399affad99261c8"
137+}
.sqlx/query-93c7d6a0aa9805cda59508aa0baf349fb341315f8899c7c61cd669916f292609.jsondeleted+0 -105
@@ -1,105 +0,0 @@
1-{
2- "db_name": "PostgreSQL",
3- "query": "UPDATE menu_dish SET\n name = COALESCE($2, name),\n description = CASE WHEN $3 THEN $4 ELSE description END,\n price_minor = COALESCE($5, price_minor),\n tags = COALESCE($6, tags)\n WHERE id = $1\n RETURNING id AS \"id: MenuDishId\", menu AS \"menu: MenuId\", name AS \"name: DishName\", description AS \"description: DishDescription\", price_minor AS \"price_minor: DishPrice\", tags AS \"tags: DishTags\", created_at AS \"created_at: Timestamp\"",
4- "describe": {
5- "columns": [
6- {
7- "ordinal": 0,
8- "name": "id: MenuDishId",
9- "type_info": "Uuid",
10- "origin": {
11- "Table": {
12- "table": "menu_dish",
13- "name": "id"
14- }
15- }
16- },
17- {
18- "ordinal": 1,
19- "name": "menu: MenuId",
20- "type_info": "Text",
21- "origin": {
22- "Table": {
23- "table": "menu_dish",
24- "name": "menu"
25- }
26- }
27- },
28- {
29- "ordinal": 2,
30- "name": "name: DishName",
31- "type_info": "Text",
32- "origin": {
33- "Table": {
34- "table": "menu_dish",
35- "name": "name"
36- }
37- }
38- },
39- {
40- "ordinal": 3,
41- "name": "description: DishDescription",
42- "type_info": "Text",
43- "origin": {
44- "Table": {
45- "table": "menu_dish",
46- "name": "description"
47- }
48- }
49- },
50- {
51- "ordinal": 4,
52- "name": "price_minor: DishPrice",
53- "type_info": "Int8",
54- "origin": {
55- "Table": {
56- "table": "menu_dish",
57- "name": "price_minor"
58- }
59- }
60- },
61- {
62- "ordinal": 5,
63- "name": "tags: DishTags",
64- "type_info": "TextArray",
65- "origin": {
66- "Table": {
67- "table": "menu_dish",
68- "name": "tags"
69- }
70- }
71- },
72- {
73- "ordinal": 6,
74- "name": "created_at: Timestamp",
75- "type_info": "Int8",
76- "origin": {
77- "Table": {
78- "table": "menu_dish",
79- "name": "created_at"
80- }
81- }
82- }
83- ],
84- "parameters": {
85- "Left": [
86- "Uuid",
87- "Text",
88- "Bool",
89- "Text",
90- "Int8",
91- "TextArray"
92- ]
93- },
94- "nullable": [
95- false,
96- false,
97- false,
98- true,
99- false,
100- false,
101- false
102- ]
103- },
104- "hash": "93c7d6a0aa9805cda59508aa0baf349fb341315f8899c7c61cd669916f292609"
105-}
.sqlx/query-94bc804bff53b231870f54a09eaaf732f6ab3b158fad47d4daab3c52426e9564.jsondeleted+0 -120
@@ -1,120 +0,0 @@
1-{
2- "db_name": "PostgreSQL",
3- "query": "WITH seat AS (\n UPDATE term\n SET course_count = course_count + 1\n WHERE id = $8 AND course_count < $9\n RETURNING 1)\n INSERT INTO course (id, creator, teachers, title, description, kind, term, capacity)\n SELECT $1, $2, $3, $4, $5, $6, $8, $7 WHERE EXISTS (SELECT 1 FROM seat)\n RETURNING id AS \"id: CourseId\", creator AS \"creator: UserId\",\n teachers AS \"teachers: Vec<UserId>\", title AS \"title: CourseTitle\",\n description AS \"description: CourseDescription\",\n kind AS \"kind: CourseKind\", term AS \"term: TermId\", capacity",
4- "describe": {
5- "columns": [
6- {
7- "ordinal": 0,
8- "name": "id: CourseId",
9- "type_info": "Uuid",
10- "origin": {
11- "Table": {
12- "table": "course",
13- "name": "id"
14- }
15- }
16- },
17- {
18- "ordinal": 1,
19- "name": "creator: UserId",
20- "type_info": "Uuid",
21- "origin": {
22- "Table": {
23- "table": "course",
24- "name": "creator"
25- }
26- }
27- },
28- {
29- "ordinal": 2,
30- "name": "teachers: Vec<UserId>",
31- "type_info": "UuidArray",
32- "origin": {
33- "Table": {
34- "table": "course",
35- "name": "teachers"
36- }
37- }
38- },
39- {
40- "ordinal": 3,
41- "name": "title: CourseTitle",
42- "type_info": "Text",
43- "origin": {
44- "Table": {
45- "table": "course",
46- "name": "title"
47- }
48- }
49- },
50- {
51- "ordinal": 4,
52- "name": "description: CourseDescription",
53- "type_info": "Text",
54- "origin": {
55- "Table": {
56- "table": "course",
57- "name": "description"
58- }
59- }
60- },
61- {
62- "ordinal": 5,
63- "name": "kind: CourseKind",
64- "type_info": "Text",
65- "origin": {
66- "Table": {
67- "table": "course",
68- "name": "kind"
69- }
70- }
71- },
72- {
73- "ordinal": 6,
74- "name": "term: TermId",
75- "type_info": "Uuid",
76- "origin": {
77- "Table": {
78- "table": "course",
79- "name": "term"
80- }
81- }
82- },
83- {
84- "ordinal": 7,
85- "name": "capacity",
86- "type_info": "Int8",
87- "origin": {
88- "Table": {
89- "table": "course",
90- "name": "capacity"
91- }
92- }
93- }
94- ],
95- "parameters": {
96- "Left": [
97- "Uuid",
98- "Uuid",
99- "UuidArray",
100- "Text",
101- "Text",
102- "Text",
103- "Int8",
104- "Uuid",
105- "Int8"
106- ]
107- },
108- "nullable": [
109- false,
110- false,
111- false,
112- false,
113- false,
114- false,
115- true,
116- true
117- ]
118- },
119- "hash": "94bc804bff53b231870f54a09eaaf732f6ab3b158fad47d4daab3c52426e9564"
120-}
.sqlx/query-9d2466aa569f86333f3eb28871eabc72dc0058951a26855a52cc688e21e21685.jsonadded+15 -0
@@ -0,0 +1,15 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "INSERT INTO menu_dish_tag (dish, tag, ord)\n SELECT $1, tag, ord FROM unnest($2::text[]) WITH ORDINALITY AS t(tag, ord)",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid",
9+ "TextArray"
10+ ]
11+ },
12+ "nullable": []
13+ },
14+ "hash": "9d2466aa569f86333f3eb28871eabc72dc0058951a26855a52cc688e21e21685"
15+}
.sqlx/query-ea0e9333278dc82972ebfc2aa5efee079814899bebf6c2a495a47e6fdc0b5834.json → .sqlx/query-9d9cce760c2a87090f4b3cf5da4afc868d6fb3c91a7ba9ae5b553dfb48be9353.jsonrenamed+2 -2
@@ -1,6 +1,6 @@
1 {1 {
2 "db_name": "PostgreSQL",2 "db_name": "PostgreSQL",
3- "query": "SELECT s.slug AS \"slug: Slug\",\n s.name,\n s.status AS \"status: SchoolStatus\"\n FROM person_school ps\n JOIN school s ON s.slug = ps.school\n WHERE ps.person = $1 AND ps.school = $2",3+ "query": "SELECT s.slug AS \"slug: Slug\",\n s.name,\n s.status AS \"status: SchoolStatus\"\n FROM person_school ps\n JOIN school s ON s.id = ps.school\n WHERE ps.person = $1 AND s.slug = $2",
4 "describe": {4 "describe": {
5 "columns": [5 "columns": [
6 {6 {
@@ -49,5 +49,5 @@
49 false49 false
50 ]50 ]
51 },51 },
52- "hash": "ea0e9333278dc82972ebfc2aa5efee079814899bebf6c2a495a47e6fdc0b5834"52+ "hash": "9d9cce760c2a87090f4b3cf5da4afc868d6fb3c91a7ba9ae5b553dfb48be9353"
53 }53 }
.sqlx/query-9e64583ead1738639a6fdc7e6158cc313f9c8ddd2afd3a9728462819f5db30dd.jsonadded+14 -0
@@ -0,0 +1,14 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "DELETE FROM menu_dish WHERE id = $1",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid"
9+ ]
10+ },
11+ "nullable": []
12+ },
13+ "hash": "9e64583ead1738639a6fdc7e6158cc313f9c8ddd2afd3a9728462819f5db30dd"
14+}
.sqlx/query-9e70ed1446d7ca45b78aa8dfb9842a877dfac056dea7b17e702bdea174b0993a.jsonadded+15 -0
@@ -0,0 +1,15 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "INSERT INTO course_teacher (course, teacher)\n SELECT $1, $2 WHERE EXISTS (SELECT 1 FROM course WHERE id = $1)\n ON CONFLICT DO NOTHING",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid",
9+ "Uuid"
10+ ]
11+ },
12+ "nullable": []
13+ },
14+ "hash": "9e70ed1446d7ca45b78aa8dfb9842a877dfac056dea7b17e702bdea174b0993a"
15+}
.sqlx/query-a48289705d949851428efdaa1cdd18a7b8397112582a9d8a0c386491e1c2bfad.jsonadded+15 -0
@@ -0,0 +1,15 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "DELETE FROM blueprint_course\n WHERE course = $2\n AND blueprint = (SELECT id FROM class_blueprint WHERE grade = $1)",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Text",
9+ "Uuid"
10+ ]
11+ },
12+ "nullable": []
13+ },
14+ "hash": "a48289705d949851428efdaa1cdd18a7b8397112582a9d8a0c386491e1c2bfad"
15+}
.sqlx/query-a659d3ffcdac1279b32d1d0673a6b36c168cb3c9ddbf00ebb402e8598b995f13.jsonadded+14 -0
@@ -0,0 +1,14 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "INSERT INTO settings_dietary_tag (settings, tag)\n SELECT 'school', t.tag FROM unnest($1::text[]) AS t(tag)",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "TextArray"
9+ ]
10+ },
11+ "nullable": []
12+ },
13+ "hash": "a659d3ffcdac1279b32d1d0673a6b36c168cb3c9ddbf00ebb402e8598b995f13"
14+}
.sqlx/query-a6baebb365f43380e7bf289cc9a660d9b628c5529195edfbe634c2c21818a345.jsonadded+28 -0
@@ -0,0 +1,28 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "SELECT course AS \"course: CourseId\" FROM blueprint_course\n WHERE blueprint = $1 ORDER BY course",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "course: CourseId",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "blueprint_course",
13+ "name": "course"
14+ }
15+ }
16+ }
17+ ],
18+ "parameters": {
19+ "Left": [
20+ "Uuid"
21+ ]
22+ },
23+ "nullable": [
24+ false
25+ ]
26+ },
27+ "hash": "a6baebb365f43380e7bf289cc9a660d9b628c5529195edfbe634c2c21818a345"
28+}
.sqlx/query-a8f1d82b2d0a543ea09ea62f8bb88a7365573ea7f566f9ff3f625e6a034d181c.jsonadded+14 -0
@@ -0,0 +1,14 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "DELETE FROM menu_dish_tag WHERE dish IN (SELECT id FROM menu_dish WHERE menu = $1)",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Text"
9+ ]
10+ },
11+ "nullable": []
12+ },
13+ "hash": "a8f1d82b2d0a543ea09ea62f8bb88a7365573ea7f566f9ff3f625e6a034d181c"
14+}
.sqlx/query-aee5be56a586cd5424cbc0532b4337dfa6d93ddd6e5909c4fd6950e2e468ad6e.jsondeleted+0 -138
@@ -1,138 +0,0 @@
1-{
2- "db_name": "PostgreSQL",
3- "query": "UPDATE board\n SET participants = (SELECT coalesce(array_agg(DISTINCT x), '{}')\n FROM unnest(participants || $2::uuid[]) AS x)\n WHERE id = $1\n AND cardinality((SELECT coalesce(array_agg(DISTINCT x), '{}')\n FROM unnest(participants || $2::uuid[]) AS x)) <= $3\n RETURNING id AS \"id: BoardId\", creator AS \"creator: UserId\",\n title AS \"title: BoardTitle\",\n participants AS \"participants: Vec<UserId>\", locked,\n locked_by AS \"locked_by: UserId\",\n locked_at AS \"locked_at: Timestamp\", epoch,\n closed_at AS \"closed_at: Timestamp\",\n created_at AS \"created_at: Timestamp\"",
4- "describe": {
5- "columns": [
6- {
7- "ordinal": 0,
8- "name": "id: BoardId",
9- "type_info": "Uuid",
10- "origin": {
11- "Table": {
12- "table": "board",
13- "name": "id"
14- }
15- }
16- },
17- {
18- "ordinal": 1,
19- "name": "creator: UserId",
20- "type_info": "Uuid",
21- "origin": {
22- "Table": {
23- "table": "board",
24- "name": "creator"
25- }
26- }
27- },
28- {
29- "ordinal": 2,
30- "name": "title: BoardTitle",
31- "type_info": "Text",
32- "origin": {
33- "Table": {
34- "table": "board",
35- "name": "title"
36- }
37- }
38- },
39- {
40- "ordinal": 3,
41- "name": "participants: Vec<UserId>",
42- "type_info": "UuidArray",
43- "origin": {
44- "Table": {
45- "table": "board",
46- "name": "participants"
47- }
48- }
49- },
50- {
51- "ordinal": 4,
52- "name": "locked",
53- "type_info": "Bool",
54- "origin": {
55- "Table": {
56- "table": "board",
57- "name": "locked"
58- }
59- }
60- },
61- {
62- "ordinal": 5,
63- "name": "locked_by: UserId",
64- "type_info": "Uuid",
65- "origin": {
66- "Table": {
67- "table": "board",
68- "name": "locked_by"
69- }
70- }
71- },
72- {
73- "ordinal": 6,
74- "name": "locked_at: Timestamp",
75- "type_info": "Int8",
76- "origin": {
77- "Table": {
78- "table": "board",
79- "name": "locked_at"
80- }
81- }
82- },
83- {
84- "ordinal": 7,
85- "name": "epoch",
86- "type_info": "Int8",
87- "origin": {
88- "Table": {
89- "table": "board",
90- "name": "epoch"
91- }
92- }
93- },
94- {
95- "ordinal": 8,
96- "name": "closed_at: Timestamp",
97- "type_info": "Int8",
98- "origin": {
99- "Table": {
100- "table": "board",
101- "name": "closed_at"
102- }
103- }
104- },
105- {
106- "ordinal": 9,
107- "name": "created_at: Timestamp",
108- "type_info": "Int8",
109- "origin": {
110- "Table": {
111- "table": "board",
112- "name": "created_at"
113- }
114- }
115- }
116- ],
117- "parameters": {
118- "Left": [
119- "Uuid",
120- "UuidArray",
121- "Int4"
122- ]
123- },
124- "nullable": [
125- false,
126- false,
127- false,
128- false,
129- false,
130- true,
131- true,
132- false,
133- true,
134- false
135- ]
136- },
137- "hash": "aee5be56a586cd5424cbc0532b4337dfa6d93ddd6e5909c4fd6950e2e468ad6e"
138-}
.sqlx/query-123a9c9b6be7c9bed57fb3c22ac699108abd335fa898d098652bc0f16541cab4.json → .sqlx/query-b0b72a673261825bb0103bef5882c803494d402b4611dbfb646d8973af96896a.jsonrenamed+5 -10
@@ -1,6 +1,6 @@
1 {1 {
2 "db_name": "PostgreSQL",2 "db_name": "PostgreSQL",
3- "query": "DELETE FROM menu_dish WHERE id = $1\n RETURNING id AS \"id: MenuDishId\", menu AS \"menu: MenuId\", name AS \"name: DishName\", description AS \"description: DishDescription\", price_minor AS \"price_minor: DishPrice\", tags AS \"tags: DishTags\", created_at AS \"created_at: Timestamp\"",3+ "query": "SELECT id AS \"id: MenuDishId\", menu AS \"menu: MenuId\", name AS \"name: DishName\", description AS \"description: DishDescription\", price_minor AS \"price_minor: DishPrice\",\n COALESCE((SELECT array_agg(t.tag ORDER BY t.ord) FROM menu_dish_tag t WHERE t.dish = menu_dish.id), '{}'::text[]) AS \"tags!: DishTags\",\n created_at AS \"created_at: Timestamp\"\n FROM menu_dish WHERE id = $1",
4 "describe": {4 "describe": {
5 "columns": [5 "columns": [
6 {6 {
@@ -60,14 +60,9 @@
60 },60 },
61 {61 {
62 "ordinal": 5,62 "ordinal": 5,
63- "name": "tags: DishTags",63+ "name": "tags!: DishTags",
64 "type_info": "TextArray",64 "type_info": "TextArray",
65- "origin": {65+ "origin": "Expression"
66- "Table": {
67- "table": "menu_dish",
68- "name": "tags"
69- }
70- }
71 },66 },
72 {67 {
73 "ordinal": 6,68 "ordinal": 6,
@@ -92,9 +87,9 @@
92 false,87 false,
93 true,88 true,
94 false,89 false,
95- false,90+ null,
96 false91 false
97 ]92 ]
98 },93 },
99- "hash": "123a9c9b6be7c9bed57fb3c22ac699108abd335fa898d098652bc0f16541cab4"94+ "hash": "b0b72a673261825bb0103bef5882c803494d402b4611dbfb646d8973af96896a"
100 }95 }
.sqlx/query-74d97285fdc1081f2efdca29cbfc9a4832c0ae927e24be87f216855fe631e40c.json → .sqlx/query-b63d7258825b3b578664bd4e8f1347c918f564d0022954a7efc0e98dc8d03df4.jsonrenamed+5 -10
@@ -1,6 +1,6 @@
1 {1 {
2 "db_name": "PostgreSQL",2 "db_name": "PostgreSQL",
3- "query": "SELECT id AS \"id: BoardId\", creator AS \"creator: UserId\",\n title AS \"title: BoardTitle\",\n participants AS \"participants: Vec<UserId>\", locked,\n locked_by AS \"locked_by: UserId\",\n locked_at AS \"locked_at: Timestamp\", epoch,\n closed_at AS \"closed_at: Timestamp\",\n created_at AS \"created_at: Timestamp\"\n FROM board WHERE id = $1",3+ "query": "SELECT b.id AS \"id: BoardId\", b.creator AS \"creator: UserId\",\n b.title AS \"title: BoardTitle\",\n ARRAY(SELECT p.participant FROM board_participant p\n WHERE p.board = b.id ORDER BY p.participant)\n AS \"participants!: Vec<UserId>\",\n b.locked, b.locked_by AS \"locked_by: UserId\",\n b.locked_at AS \"locked_at: Timestamp\", b.epoch,\n b.closed_at AS \"closed_at: Timestamp\",\n b.created_at AS \"created_at: Timestamp\"\n FROM board b WHERE b.id = $1",
4 "describe": {4 "describe": {
5 "columns": [5 "columns": [
6 {6 {
@@ -38,14 +38,9 @@
38 },38 },
39 {39 {
40 "ordinal": 3,40 "ordinal": 3,
41- "name": "participants: Vec<UserId>",41+ "name": "participants!: Vec<UserId>",
42 "type_info": "UuidArray",42 "type_info": "UuidArray",
43- "origin": {43+ "origin": "Expression"
44- "Table": {
45- "table": "board",
46- "name": "participants"
47- }
48- }
49 },44 },
50 {45 {
51 "ordinal": 4,46 "ordinal": 4,
@@ -123,7 +118,7 @@
123 false,118 false,
124 false,119 false,
125 false,120 false,
126- false,121+ null,
127 false,122 false,
128 true,123 true,
129 true,124 true,
@@ -132,5 +127,5 @@
132 false127 false
133 ]128 ]
134 },129 },
135- "hash": "74d97285fdc1081f2efdca29cbfc9a4832c0ae927e24be87f216855fe631e40c"130+ "hash": "b63d7258825b3b578664bd4e8f1347c918f564d0022954a7efc0e98dc8d03df4"
136 }131 }
.sqlx/query-b8cd6149b5f42e615c31018d2fdf306f157f5275587ae57d1e5146c9a76a51d3.jsondeleted+0 -17
@@ -1,17 +0,0 @@
1-{
2- "db_name": "PostgreSQL",
3- "query": "INSERT INTO class_blueprint (id, grade, courses, creator)\n VALUES ($1, $2, $3, $4)",
4- "describe": {
5- "columns": [],
6- "parameters": {
7- "Left": [
8- "Uuid",
9- "Text",
10- "UuidArray",
11- "Uuid"
12- ]
13- },
14- "nullable": []
15- },
16- "hash": "b8cd6149b5f42e615c31018d2fdf306f157f5275587ae57d1e5146c9a76a51d3"
17-}
.sqlx/query-bd7a06a5112f3a1489d0f3800e42bee96cd9acec380c29c4006c9d68f5becd57.jsonadded+40 -0
@@ -0,0 +1,40 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "SELECT blueprint, course AS \"course: CourseId\" FROM blueprint_course\n WHERE blueprint = ANY($1) ORDER BY blueprint, course",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "blueprint",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "blueprint_course",
13+ "name": "blueprint"
14+ }
15+ }
16+ },
17+ {
18+ "ordinal": 1,
19+ "name": "course: CourseId",
20+ "type_info": "Uuid",
21+ "origin": {
22+ "Table": {
23+ "table": "blueprint_course",
24+ "name": "course"
25+ }
26+ }
27+ }
28+ ],
29+ "parameters": {
30+ "Left": [
31+ "UuidArray"
32+ ]
33+ },
34+ "nullable": [
35+ false,
36+ false
37+ ]
38+ },
39+ "hash": "bd7a06a5112f3a1489d0f3800e42bee96cd9acec380c29c4006c9d68f5becd57"
40+}
.sqlx/query-bdfda68f7d0dedef148b54d5911a7798ced19472830ac9421f024eb43c784318.jsonadded+15 -0
@@ -0,0 +1,15 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "INSERT INTO dietary_profile_tag (student, tag, ord)\n SELECT $1, tag, ord FROM unnest($2::text[]) WITH ORDINALITY AS t(tag, ord)",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid",
9+ "TextArray"
10+ ]
11+ },
12+ "nullable": []
13+ },
14+ "hash": "bdfda68f7d0dedef148b54d5911a7798ced19472830ac9421f024eb43c784318"
15+}
.sqlx/query-be12adc83910edf8922a2b22308e76093cdd89e6173043354ee6ee66e7c2a518.jsondeleted+0 -113
@@ -1,113 +0,0 @@
1-{
2- "db_name": "PostgreSQL",
3- "query": "UPDATE course\n SET teachers = (SELECT array_agg(DISTINCT x)\n FROM unnest(course.teachers || $2::uuid) AS x)\n WHERE id = $1\n RETURNING id AS \"id: CourseId\", creator AS \"creator: UserId\",\n teachers AS \"teachers: Vec<UserId>\", title AS \"title: CourseTitle\",\n description AS \"description: CourseDescription\",\n kind AS \"kind: CourseKind\", term AS \"term: TermId\", capacity",
4- "describe": {
5- "columns": [
6- {
7- "ordinal": 0,
8- "name": "id: CourseId",
9- "type_info": "Uuid",
10- "origin": {
11- "Table": {
12- "table": "course",
13- "name": "id"
14- }
15- }
16- },
17- {
18- "ordinal": 1,
19- "name": "creator: UserId",
20- "type_info": "Uuid",
21- "origin": {
22- "Table": {
23- "table": "course",
24- "name": "creator"
25- }
26- }
27- },
28- {
29- "ordinal": 2,
30- "name": "teachers: Vec<UserId>",
31- "type_info": "UuidArray",
32- "origin": {
33- "Table": {
34- "table": "course",
35- "name": "teachers"
36- }
37- }
38- },
39- {
40- "ordinal": 3,
41- "name": "title: CourseTitle",
42- "type_info": "Text",
43- "origin": {
44- "Table": {
45- "table": "course",
46- "name": "title"
47- }
48- }
49- },
50- {
51- "ordinal": 4,
52- "name": "description: CourseDescription",
53- "type_info": "Text",
54- "origin": {
55- "Table": {
56- "table": "course",
57- "name": "description"
58- }
59- }
60- },
61- {
62- "ordinal": 5,
63- "name": "kind: CourseKind",
64- "type_info": "Text",
65- "origin": {
66- "Table": {
67- "table": "course",
68- "name": "kind"
69- }
70- }
71- },
72- {
73- "ordinal": 6,
74- "name": "term: TermId",
75- "type_info": "Uuid",
76- "origin": {
77- "Table": {
78- "table": "course",
79- "name": "term"
80- }
81- }
82- },
83- {
84- "ordinal": 7,
85- "name": "capacity",
86- "type_info": "Int8",
87- "origin": {
88- "Table": {
89- "table": "course",
90- "name": "capacity"
91- }
92- }
93- }
94- ],
95- "parameters": {
96- "Left": [
97- "Uuid",
98- "Uuid"
99- ]
100- },
101- "nullable": [
102- false,
103- false,
104- false,
105- false,
106- false,
107- false,
108- true,
109- true
110- ]
111- },
112- "hash": "be12adc83910edf8922a2b22308e76093cdd89e6173043354ee6ee66e7c2a518"
113-}
.sqlx/query-5faf6a7b5f0ae1ff707c72f2a8985e65d83dcd7a4cad37c752908c361a460d86.json → .sqlx/query-c1bac901f8e1b2a8ee9aa2aa15e4ec7eab955fb80167fec8768a381cd012f4b5.jsonrenamed+16 -6
@@ -1,10 +1,21 @@
1 {1 {
2 "db_name": "PostgreSQL",2 "db_name": "PostgreSQL",
3- "query": "UPDATE class_blueprint SET courses = $2\n WHERE grade = $1 AND courses = $3\n RETURNING grade AS \"grade: ClassGrade\", creator AS \"creator: UserId\"",3+ "query": "SELECT id AS \"key: uuid::Uuid\", grade AS \"grade: ClassGrade\",\n creator AS \"creator: UserId\"\n FROM class_blueprint WHERE grade = $1",
4 "describe": {4 "describe": {
5 "columns": [5 "columns": [
6 {6 {
7 "ordinal": 0,7 "ordinal": 0,
8+ "name": "key: uuid::Uuid",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "class_blueprint",
13+ "name": "id"
14+ }
15+ }
16+ },
17+ {
18+ "ordinal": 1,
8 "name": "grade: ClassGrade",19 "name": "grade: ClassGrade",
9 "type_info": "Text",20 "type_info": "Text",
10 "origin": {21 "origin": {
@@ -15,7 +26,7 @@
15 }26 }
16 },27 },
17 {28 {
18- "ordinal": 1,29+ "ordinal": 2,
19 "name": "creator: UserId",30 "name": "creator: UserId",
20 "type_info": "Uuid",31 "type_info": "Uuid",
21 "origin": {32 "origin": {
@@ -28,15 +39,14 @@
28 ],39 ],
29 "parameters": {40 "parameters": {
30 "Left": [41 "Left": [
31- "Text",42+ "Text"
32- "UuidArray",
33- "UuidArray"
34 ]43 ]
35 },44 },
36 "nullable": [45 "nullable": [
46+ false,
37 false,47 false,
38 false48 false
39 ]49 ]
40 },50 },
41- "hash": "5faf6a7b5f0ae1ff707c72f2a8985e65d83dcd7a4cad37c752908c361a460d86"51+ "hash": "c1bac901f8e1b2a8ee9aa2aa15e4ec7eab955fb80167fec8768a381cd012f4b5"
42 }52 }
.sqlx/query-866efd5fe0b7f2b4524f747d9ef26100e13c48d4cb35d390d29c327180681c60.json → .sqlx/query-c3232a6de8535065f4fc7e1a19494dd17acb47f65cca634b739f9ff6cd0a6894.jsonrenamed+2 -2
@@ -1,6 +1,6 @@
1 {1 {
2 "db_name": "PostgreSQL",2 "db_name": "PostgreSQL",
3- "query": "SELECT due_at AS \"due_at: Timestamp\" FROM homework\n WHERE id = $1 AND (cardinality(assigned) = 0 OR $2 = ANY(assigned))\n FOR UPDATE",3+ "query": "SELECT due_at AS \"due_at: Timestamp\" FROM homework\n WHERE id = $1\n AND (NOT EXISTS (SELECT 1 FROM homework_assignment a\n WHERE a.homework = homework.id)\n OR EXISTS (SELECT 1 FROM homework_assignment a\n WHERE a.homework = homework.id AND a.student = $2))\n FOR UPDATE",
4 "describe": {4 "describe": {
5 "columns": [5 "columns": [
6 {6 {
@@ -25,5 +25,5 @@
25 false25 false
26 ]26 ]
27 },27 },
28- "hash": "866efd5fe0b7f2b4524f747d9ef26100e13c48d4cb35d390d29c327180681c60"28+ "hash": "c3232a6de8535065f4fc7e1a19494dd17acb47f65cca634b739f9ff6cd0a6894"
29 }29 }
.sqlx/query-b364954dae05a5a23861686a2f9b9ce478f5ee272d09c11e288d335d05f43fd8.json → .sqlx/query-c41fb6b0ecd0a378198552f4c36085f8c0d229a7a83b23fb3ba02c1e6b675fe6.jsonrenamed+6 -16
@@ -1,6 +1,6 @@
1 {1 {
2 "db_name": "PostgreSQL",2 "db_name": "PostgreSQL",
3- "query": "INSERT INTO dietary_profile (student, tags, note, updated_by, updated_at)\n VALUES ($1, COALESCE($2, '{}'::text[]), $3, $4, $5)\n ON CONFLICT (student) DO UPDATE SET\n tags = COALESCE($2, dietary_profile.tags),\n note = CASE WHEN $6 THEN $3 ELSE dietary_profile.note END,\n updated_by = $4,\n updated_at = $5\n RETURNING student AS \"student: UserId\", tags AS \"tags: DietaryTags\", note AS \"note: DietaryNote\", updated_by AS \"updated_by: UserId\", updated_at AS \"updated_at: Timestamp\"",3+ "query": "SELECT student AS \"student: UserId\",\n COALESCE((SELECT array_agg(t.tag ORDER BY t.ord) FROM dietary_profile_tag t WHERE t.student = dietary_profile.student), '{}'::text[]) AS \"tags!: DietaryTags\",\n note AS \"note: DietaryNote\", updated_by AS \"updated_by: UserId\", updated_at AS \"updated_at: Timestamp\"\n FROM dietary_profile WHERE student = $1",
4 "describe": {4 "describe": {
5 "columns": [5 "columns": [
6 {6 {
@@ -16,14 +16,9 @@
16 },16 },
17 {17 {
18 "ordinal": 1,18 "ordinal": 1,
19- "name": "tags: DietaryTags",19+ "name": "tags!: DietaryTags",
20 "type_info": "TextArray",20 "type_info": "TextArray",
21- "origin": {21+ "origin": "Expression"
22- "Table": {
23- "table": "dietary_profile",
24- "name": "tags"
25- }
26- }
27 },22 },
28 {23 {
29 "ordinal": 2,24 "ordinal": 2,
@@ -61,21 +56,16 @@
61 ],56 ],
62 "parameters": {57 "parameters": {
63 "Left": [58 "Left": [
64- "Uuid",59+ "Uuid"
65- "TextArray",
66- "Text",
67- "Uuid",
68- "Int8",
69- "Bool"
70 ]60 ]
71 },61 },
72 "nullable": [62 "nullable": [
73 false,63 false,
74- false,64+ null,
75 true,65 true,
76 false,66 false,
77 false67 false
78 ]68 ]
79 },69 },
80- "hash": "b364954dae05a5a23861686a2f9b9ce478f5ee272d09c11e288d335d05f43fd8"70+ "hash": "c41fb6b0ecd0a378198552f4c36085f8c0d229a7a83b23fb3ba02c1e6b675fe6"
81 }71 }
.sqlx/query-c79d72b0f40ff99077904b1d479bb80ed92b3f86eef355cc301bcb1178d3ca4d.jsondeleted+0 -137
@@ -1,137 +0,0 @@
1-{
2- "db_name": "PostgreSQL",
3- "query": "UPDATE board SET participants = $2 WHERE id = $1\n RETURNING id AS \"id: BoardId\", creator AS \"creator: UserId\",\n title AS \"title: BoardTitle\",\n participants AS \"participants: Vec<UserId>\", locked,\n locked_by AS \"locked_by: UserId\",\n locked_at AS \"locked_at: Timestamp\", epoch,\n closed_at AS \"closed_at: Timestamp\",\n created_at AS \"created_at: Timestamp\"",
4- "describe": {
5- "columns": [
6- {
7- "ordinal": 0,
8- "name": "id: BoardId",
9- "type_info": "Uuid",
10- "origin": {
11- "Table": {
12- "table": "board",
13- "name": "id"
14- }
15- }
16- },
17- {
18- "ordinal": 1,
19- "name": "creator: UserId",
20- "type_info": "Uuid",
21- "origin": {
22- "Table": {
23- "table": "board",
24- "name": "creator"
25- }
26- }
27- },
28- {
29- "ordinal": 2,
30- "name": "title: BoardTitle",
31- "type_info": "Text",
32- "origin": {
33- "Table": {
34- "table": "board",
35- "name": "title"
36- }
37- }
38- },
39- {
40- "ordinal": 3,
41- "name": "participants: Vec<UserId>",
42- "type_info": "UuidArray",
43- "origin": {
44- "Table": {
45- "table": "board",
46- "name": "participants"
47- }
48- }
49- },
50- {
51- "ordinal": 4,
52- "name": "locked",
53- "type_info": "Bool",
54- "origin": {
55- "Table": {
56- "table": "board",
57- "name": "locked"
58- }
59- }
60- },
61- {
62- "ordinal": 5,
63- "name": "locked_by: UserId",
64- "type_info": "Uuid",
65- "origin": {
66- "Table": {
67- "table": "board",
68- "name": "locked_by"
69- }
70- }
71- },
72- {
73- "ordinal": 6,
74- "name": "locked_at: Timestamp",
75- "type_info": "Int8",
76- "origin": {
77- "Table": {
78- "table": "board",
79- "name": "locked_at"
80- }
81- }
82- },
83- {
84- "ordinal": 7,
85- "name": "epoch",
86- "type_info": "Int8",
87- "origin": {
88- "Table": {
89- "table": "board",
90- "name": "epoch"
91- }
92- }
93- },
94- {
95- "ordinal": 8,
96- "name": "closed_at: Timestamp",
97- "type_info": "Int8",
98- "origin": {
99- "Table": {
100- "table": "board",
101- "name": "closed_at"
102- }
103- }
104- },
105- {
106- "ordinal": 9,
107- "name": "created_at: Timestamp",
108- "type_info": "Int8",
109- "origin": {
110- "Table": {
111- "table": "board",
112- "name": "created_at"
113- }
114- }
115- }
116- ],
117- "parameters": {
118- "Left": [
119- "Uuid",
120- "UuidArray"
121- ]
122- },
123- "nullable": [
124- false,
125- false,
126- false,
127- false,
128- false,
129- true,
130- true,
131- false,
132- true,
133- false
134- ]
135- },
136- "hash": "c79d72b0f40ff99077904b1d479bb80ed92b3f86eef355cc301bcb1178d3ca4d"
137-}
.sqlx/query-c853378f65634bdb7e00a372fa188979bc2758176b486ac554a763653e04c718.jsonadded+24 -0
@@ -0,0 +1,24 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "SELECT ((SELECT count(*) FROM board_participant WHERE board = $1)\n + (SELECT count(*) FROM unnest($2::uuid[]) AS t(x)\n WHERE NOT EXISTS (SELECT 1 FROM board_participant bp\n WHERE bp.board = $1 AND bp.participant = t.x)))\n AS \"filled!\"",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "filled!",
9+ "type_info": "Int8",
10+ "origin": "Expression"
11+ }
12+ ],
13+ "parameters": {
14+ "Left": [
15+ "Uuid",
16+ "UuidArray"
17+ ]
18+ },
19+ "nullable": [
20+ null
21+ ]
22+ },
23+ "hash": "c853378f65634bdb7e00a372fa188979bc2758176b486ac554a763653e04c718"
24+}
.sqlx/query-c95bf5c2dfe3ef6919ddb41983f1ab4392ea31250f0c00db33e0864a33dfde42.jsonadded+14 -0
@@ -0,0 +1,14 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "DELETE FROM rag_output_source WHERE output IN\n (SELECT id FROM rag_output WHERE course_note = $1)",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid"
9+ ]
10+ },
11+ "nullable": []
12+ },
13+ "hash": "c95bf5c2dfe3ef6919ddb41983f1ab4392ea31250f0c00db33e0864a33dfde42"
14+}
.sqlx/query-cb8b95b85f0f40ad61f2135d211ae1a44da4173d3d7e10b6e2e3dddad51d952e.jsonadded+15 -0
@@ -0,0 +1,15 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "INSERT INTO homework_assignment (homework, student)\n SELECT $2, s FROM unnest($1::uuid[]) AS t(s)",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "UuidArray",
9+ "Uuid"
10+ ]
11+ },
12+ "nullable": []
13+ },
14+ "hash": "cb8b95b85f0f40ad61f2135d211ae1a44da4173d3d7e10b6e2e3dddad51d952e"
15+}
.sqlx/query-cbf6dd44326403b41940e572a66285a17bd52337a3b586b99deb4bfc5250bbe5.jsonadded+28 -0
@@ -0,0 +1,28 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "SELECT source AS \"source: CourseNoteFileId\"\n FROM rag_output_source WHERE output = $1 ORDER BY source",
4+ "describe": {
5+ "columns": [
6+ {
7+ "ordinal": 0,
8+ "name": "source: CourseNoteFileId",
9+ "type_info": "Uuid",
10+ "origin": {
11+ "Table": {
12+ "table": "rag_output_source",
13+ "name": "source"
14+ }
15+ }
16+ }
17+ ],
18+ "parameters": {
19+ "Left": [
20+ "Uuid"
21+ ]
22+ },
23+ "nullable": [
24+ false
25+ ]
26+ },
27+ "hash": "cbf6dd44326403b41940e572a66285a17bd52337a3b586b99deb4bfc5250bbe5"
28+}
.sqlx/query-cdd48454144e721a0c3bab8b0859396b9a134f3b85a727c8fb08b01c9fa1fd6b.jsonadded+20 -0
@@ -0,0 +1,20 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "INSERT INTO menu_dish (id, menu, name, description, price_minor, created_at)\n SELECT $1, $2, $3, $4, $5, $6\n WHERE (SELECT count(*) FROM menu_dish WHERE menu = $2) < $7",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid",
9+ "Text",
10+ "Text",
11+ "Text",
12+ "Int8",
13+ "Int8",
14+ "Int8"
15+ ]
16+ },
17+ "nullable": []
18+ },
19+ "hash": "cdd48454144e721a0c3bab8b0859396b9a134f3b85a727c8fb08b01c9fa1fd6b"
20+}
.sqlx/query-cf84beaac0eb97a92e8a2fde1cc7688b2d1a239f0604d945885c1c3a09b305b4.jsonadded+21 -0
@@ -0,0 +1,21 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "INSERT INTO settings (id, exam_kinds, grade_bands, max_file_bytes,\n chatbot_history_turns, max_chatbot_message_len,\n max_chatbot_threads, meal_slots,\n meal_cancel_cutoff_minutes)\n VALUES ('school', $1, $2, $3, $4, $5, $6, $7, $8)\n ON CONFLICT (id) DO UPDATE SET\n exam_kinds = EXCLUDED.exam_kinds,\n grade_bands = EXCLUDED.grade_bands,\n max_file_bytes = EXCLUDED.max_file_bytes,\n chatbot_history_turns = EXCLUDED.chatbot_history_turns,\n max_chatbot_message_len = EXCLUDED.max_chatbot_message_len,\n max_chatbot_threads = EXCLUDED.max_chatbot_threads,\n meal_slots = EXCLUDED.meal_slots,\n meal_cancel_cutoff_minutes = EXCLUDED.meal_cancel_cutoff_minutes",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Jsonb",
9+ "Jsonb",
10+ "Int8",
11+ "Int8",
12+ "Int8",
13+ "Int8",
14+ "Jsonb",
15+ "Int8"
16+ ]
17+ },
18+ "nullable": []
19+ },
20+ "hash": "cf84beaac0eb97a92e8a2fde1cc7688b2d1a239f0604d945885c1c3a09b305b4"
21+}
.sqlx/query-cfd796a16bdfb74c118bd76c0558e33b7c575b5510df2bf6547c818481be5eaa.jsonadded+15 -0
@@ -0,0 +1,15 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "INSERT INTO board_participant (board, participant)\n SELECT $1, t.x FROM unnest($2::uuid[]) AS t(x)\n ON CONFLICT DO NOTHING",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid",
9+ "UuidArray"
10+ ]
11+ },
12+ "nullable": []
13+ },
14+ "hash": "cfd796a16bdfb74c118bd76c0558e33b7c575b5510df2bf6547c818481be5eaa"
15+}
.sqlx/query-da48c3255d2e13ec4031617c4e549cd7f9e911516b7615c36e1dfe07959ff51c.jsondeleted+0 -145
@@ -1,145 +0,0 @@
1-{
2- "db_name": "PostgreSQL",
3- "query": "INSERT INTO settings (id, exam_kinds, attendance_statuses, grade_bands,\n max_file_bytes, chatbot_history_turns,\n max_chatbot_message_len, max_chatbot_threads,\n meal_slots, dietary_tags, meal_cancel_cutoff_minutes)\n VALUES ('school', $1, $2, $3, $4, $5, $6, $7, $8, $9, $10)\n ON CONFLICT (id) DO UPDATE SET\n exam_kinds = EXCLUDED.exam_kinds,\n attendance_statuses = EXCLUDED.attendance_statuses,\n grade_bands = EXCLUDED.grade_bands,\n max_file_bytes = EXCLUDED.max_file_bytes,\n chatbot_history_turns = EXCLUDED.chatbot_history_turns,\n max_chatbot_message_len = EXCLUDED.max_chatbot_message_len,\n max_chatbot_threads = EXCLUDED.max_chatbot_threads,\n meal_slots = EXCLUDED.meal_slots,\n dietary_tags = EXCLUDED.dietary_tags,\n meal_cancel_cutoff_minutes = EXCLUDED.meal_cancel_cutoff_minutes\n RETURNING\n exam_kinds AS \"exam_kinds: Json<Vec<ExamKindDef>>\",\n attendance_statuses,\n grade_bands AS \"grade_bands: Json<Vec<GradeBand>>\",\n max_file_bytes,\n chatbot_history_turns,\n max_chatbot_message_len,\n max_chatbot_threads,\n meal_slots AS \"meal_slots: Json<Vec<MealSlotDef>>\",\n dietary_tags,\n meal_cancel_cutoff_minutes",
4- "describe": {
5- "columns": [
6- {
7- "ordinal": 0,
8- "name": "exam_kinds: Json<Vec<ExamKindDef>>",
9- "type_info": "Jsonb",
10- "origin": {
11- "Table": {
12- "table": "settings",
13- "name": "exam_kinds"
14- }
15- }
16- },
17- {
18- "ordinal": 1,
19- "name": "attendance_statuses",
20- "type_info": "TextArray",
21- "origin": {
22- "Table": {
23- "table": "settings",
24- "name": "attendance_statuses"
25- }
26- }
27- },
28- {
29- "ordinal": 2,
30- "name": "grade_bands: Json<Vec<GradeBand>>",
31- "type_info": "Jsonb",
32- "origin": {
33- "Table": {
34- "table": "settings",
35- "name": "grade_bands"
36- }
37- }
38- },
39- {
40- "ordinal": 3,
41- "name": "max_file_bytes",
42- "type_info": "Int8",
43- "origin": {
44- "Table": {
45- "table": "settings",
46- "name": "max_file_bytes"
47- }
48- }
49- },
50- {
51- "ordinal": 4,
52- "name": "chatbot_history_turns",
53- "type_info": "Int8",
54- "origin": {
55- "Table": {
56- "table": "settings",
57- "name": "chatbot_history_turns"
58- }
59- }
60- },
61- {
62- "ordinal": 5,
63- "name": "max_chatbot_message_len",
64- "type_info": "Int8",
65- "origin": {
66- "Table": {
67- "table": "settings",
68- "name": "max_chatbot_message_len"
69- }
70- }
71- },
72- {
73- "ordinal": 6,
74- "name": "max_chatbot_threads",
75- "type_info": "Int8",
76- "origin": {
77- "Table": {
78- "table": "settings",
79- "name": "max_chatbot_threads"
80- }
81- }
82- },
83- {
84- "ordinal": 7,
85- "name": "meal_slots: Json<Vec<MealSlotDef>>",
86- "type_info": "Jsonb",
87- "origin": {
88- "Table": {
89- "table": "settings",
90- "name": "meal_slots"
91- }
92- }
93- },
94- {
95- "ordinal": 8,
96- "name": "dietary_tags",
97- "type_info": "TextArray",
98- "origin": {
99- "Table": {
100- "table": "settings",
101- "name": "dietary_tags"
102- }
103- }
104- },
105- {
106- "ordinal": 9,
107- "name": "meal_cancel_cutoff_minutes",
108- "type_info": "Int8",
109- "origin": {
110- "Table": {
111- "table": "settings",
112- "name": "meal_cancel_cutoff_minutes"
113- }
114- }
115- }
116- ],
117- "parameters": {
118- "Left": [
119- "Jsonb",
120- "TextArray",
121- "Jsonb",
122- "Int8",
123- "Int8",
124- "Int8",
125- "Int8",
126- "Jsonb",
127- "TextArray",
128- "Int8"
129- ]
130- },
131- "nullable": [
132- false,
133- false,
134- false,
135- true,
136- true,
137- true,
138- true,
139- true,
140- true,
141- true
142- ]
143- },
144- "hash": "da48c3255d2e13ec4031617c4e549cd7f9e911516b7615c36e1dfe07959ff51c"
145-}
.sqlx/query-df8f0dba6da244501e34e5f0108236148b27134bbec41d9084704143e35d90ea.jsonadded+14 -0
@@ -0,0 +1,14 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "DELETE FROM board_participant WHERE board = $1",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid"
9+ ]
10+ },
11+ "nullable": []
12+ },
13+ "hash": "df8f0dba6da244501e34e5f0108236148b27134bbec41d9084704143e35d90ea"
14+}
.sqlx/query-9ebc278fccb979dbd426a4a24b7ab5261e0c26c29786b1abc23c03d76c27e7a9.json → .sqlx/query-e468a344c54e212f2ad3d4159206fa97a212a9111135b4ca576962cc64267757.jsonrenamed+5 -10
@@ -1,6 +1,6 @@
1 {1 {
2 "db_name": "PostgreSQL",2 "db_name": "PostgreSQL",
3- "query": "UPDATE board SET closed_at = $2 WHERE id = $1 AND closed_at IS NULL\n RETURNING id AS \"id: BoardId\", creator AS \"creator: UserId\",\n title AS \"title: BoardTitle\",\n participants AS \"participants: Vec<UserId>\", locked,\n locked_by AS \"locked_by: UserId\",\n locked_at AS \"locked_at: Timestamp\", epoch,\n closed_at AS \"closed_at: Timestamp\",\n created_at AS \"created_at: Timestamp\"",3+ "query": "UPDATE board SET closed_at = $2 WHERE id = $1 AND closed_at IS NULL\n RETURNING id AS \"id: BoardId\", creator AS \"creator: UserId\",\n title AS \"title: BoardTitle\",\n ARRAY(SELECT p.participant FROM board_participant p\n WHERE p.board = board.id ORDER BY p.participant)\n AS \"participants!: Vec<UserId>\", locked,\n locked_by AS \"locked_by: UserId\",\n locked_at AS \"locked_at: Timestamp\", epoch,\n closed_at AS \"closed_at: Timestamp\",\n created_at AS \"created_at: Timestamp\"",
4 "describe": {4 "describe": {
5 "columns": [5 "columns": [
6 {6 {
@@ -38,14 +38,9 @@
38 },38 },
39 {39 {
40 "ordinal": 3,40 "ordinal": 3,
41- "name": "participants: Vec<UserId>",41+ "name": "participants!: Vec<UserId>",
42 "type_info": "UuidArray",42 "type_info": "UuidArray",
43- "origin": {43+ "origin": "Expression"
44- "Table": {
45- "table": "board",
46- "name": "participants"
47- }
48- }
49 },44 },
50 {45 {
51 "ordinal": 4,46 "ordinal": 4,
@@ -124,7 +119,7 @@
124 false,119 false,
125 false,120 false,
126 false,121 false,
127- false,122+ null,
128 false,123 false,
129 true,124 true,
130 true,125 true,
@@ -133,5 +128,5 @@
133 false128 false
134 ]129 ]
135 },130 },
136- "hash": "9ebc278fccb979dbd426a4a24b7ab5261e0c26c29786b1abc23c03d76c27e7a9"131+ "hash": "e468a344c54e212f2ad3d4159206fa97a212a9111135b4ca576962cc64267757"
137 }132 }
.sqlx/query-8c457fff4a76cedba9338135a894713e2609cb8aed0e963ba491118d3aebe0a3.json → .sqlx/query-ede2ad9dfbe1e9e069bd8912acb49d13f43f251bc7276d1a6b6fe249920677ad.jsonrenamed+2 -2
@@ -1,6 +1,6 @@
1 {1 {
2 "db_name": "PostgreSQL",2 "db_name": "PostgreSQL",
3- "query": "INSERT INTO person_school (person, school, created_at) VALUES ($1, $2, $3) ON CONFLICT DO NOTHING",3+ "query": "INSERT INTO person_school (person, school, created_at)\n SELECT $1, s.id, $3 FROM school s WHERE s.slug = $2\n ON CONFLICT DO NOTHING",
4 "describe": {4 "describe": {
5 "columns": [],5 "columns": [],
6 "parameters": {6 "parameters": {
@@ -12,5 +12,5 @@
12 },12 },
13 "nullable": []13 "nullable": []
14 },14 },
15- "hash": "8c457fff4a76cedba9338135a894713e2609cb8aed0e963ba491118d3aebe0a3"15+ "hash": "ede2ad9dfbe1e9e069bd8912acb49d13f43f251bc7276d1a6b6fe249920677ad"
16 }16 }
.sqlx/query-1604ab0a5b6f69c82c52fbdd8a4a54422aaacfa006d1a05d5ea37ed20baa355f.json → .sqlx/query-f19d64790b8c145113b680276ff897b1f4786e15116846e0288035e6ef1ca091.jsonrenamed+2 -2
@@ -1,6 +1,6 @@
1 {1 {
2 "db_name": "PostgreSQL",2 "db_name": "PostgreSQL",
3- "query": "SELECT id AS \"id: HomeworkId\",\n course AS \"course: CourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END\n AS \"assigned: Vec<UserId>\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"\n FROM homework\n WHERE course = $1 AND (cardinality(assigned) = 0 OR $2 = ANY(assigned))\n ORDER BY id DESC",3+ "query": "SELECT id AS \"id: HomeworkId\",\n course AS \"course: CourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a\n WHERE a.homework = homework.id) AS \"assigned: Vec<UserId>\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"\n FROM homework\n WHERE course = $1\n AND (NOT EXISTS (SELECT 1 FROM homework_assignment a\n WHERE a.homework = homework.id)\n OR EXISTS (SELECT 1 FROM homework_assignment a\n WHERE a.homework = homework.id AND a.student = $2))\n ORDER BY id DESC",
4 "describe": {4 "describe": {
5 "columns": [5 "columns": [
6 {6 {
@@ -116,5 +116,5 @@
116 false116 false
117 ]117 ]
118 },118 },
119- "hash": "1604ab0a5b6f69c82c52fbdd8a4a54422aaacfa006d1a05d5ea37ed20baa355f"119+ "hash": "f19d64790b8c145113b680276ff897b1f4786e15116846e0288035e6ef1ca091"
120 }120 }
.sqlx/query-f3d94b7ff35a9dfabb0459303432942bc8828d833df5fe56e8201b2aa8cae80c.jsonadded+15 -0
@@ -0,0 +1,15 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "INSERT INTO homework_assignment (homework, student)\n SELECT $2, s FROM unnest($1::uuid[]) AS t(s)",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "UuidArray",
9+ "Uuid"
10+ ]
11+ },
12+ "nullable": []
13+ },
14+ "hash": "f3d94b7ff35a9dfabb0459303432942bc8828d833df5fe56e8201b2aa8cae80c"
15+}
.sqlx/query-f5de8fdcec4e2b21ebb8fbfbd12202947538687c018b94967578f68be3358864.jsonadded+14 -0
@@ -0,0 +1,14 @@
1+{
2+ "db_name": "PostgreSQL",
3+ "query": "DELETE FROM rag_output_source WHERE source = $1",
4+ "describe": {
5+ "columns": [],
6+ "parameters": {
7+ "Left": [
8+ "Uuid"
9+ ]
10+ },
11+ "nullable": []
12+ },
13+ "hash": "f5de8fdcec4e2b21ebb8fbfbd12202947538687c018b94967578f68be3358864"
14+}
.sqlx/query-d33066aa6a8214a7ceb38922c1fa0ad45fcb45e4a4cebbc26efbcf8c31691517.json → .sqlx/query-f7d2187dc89a2bba3b521b0ea67282392ba1739904fcb1d40006e34c78d4afa9.jsonrenamed+2 -2
@@ -1,6 +1,6 @@
1 {1 {
2 "db_name": "PostgreSQL",2 "db_name": "PostgreSQL",
3- "query": "SELECT id AS \"id: HomeworkId\",\n course AS \"course: CourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END\n AS \"assigned: Vec<UserId>\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"\n FROM homework WHERE id = $1",3+ "query": "SELECT id AS \"id: HomeworkId\",\n course AS \"course: CourseId\",\n subject AS \"subject: SubjectId\",\n title AS \"title: HomeworkTitle\",\n description AS \"description: HomeworkDescription\",\n due_at AS \"due_at: Timestamp\",\n (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a\n WHERE a.homework = homework.id) AS \"assigned: Vec<UserId>\",\n created_by AS \"created_by: UserId\",\n created_at AS \"created_at: Timestamp\"\n FROM homework WHERE course = $1 ORDER BY id DESC",
4 "describe": {4 "describe": {
5 "columns": [5 "columns": [
6 {6 {
@@ -115,5 +115,5 @@
115 false115 false
116 ]116 ]
117 },117 },
118- "hash": "d33066aa6a8214a7ceb38922c1fa0ad45fcb45e4a4cebbc26efbcf8c31691517"118+ "hash": "f7d2187dc89a2bba3b521b0ea67282392ba1739904fcb1d40006e34c78d4afa9"
119 }119 }
.sqlx/query-8a2042be8e7358d9c9f9f8a906ff113f71fa4ac519aec8519ee6b40bc51f694d.json → .sqlx/query-fb46d17a76c6111308068c735184bbb68a2b726f7a1c98068d506d51aa52785e.jsonrenamed+7 -17
@@ -1,6 +1,6 @@
1 {1 {
2 "db_name": "PostgreSQL",2 "db_name": "PostgreSQL",
3- "query": "SELECT\n exam_kinds AS \"exam_kinds: Json<Vec<ExamKindDef>>\",\n attendance_statuses,\n grade_bands AS \"grade_bands: Json<Vec<GradeBand>>\",\n max_file_bytes,\n chatbot_history_turns,\n max_chatbot_message_len,\n max_chatbot_threads,\n meal_slots AS \"meal_slots: Json<Vec<MealSlotDef>>\",\n dietary_tags,\n meal_cancel_cutoff_minutes\n FROM settings WHERE id = 'school'",3+ "query": "SELECT s.exam_kinds AS \"exam_kinds: Json<Vec<ExamKindDef>>\",\n COALESCE((SELECT array_agg(t.status ORDER BY t.status)\n FROM settings_attendance_status t\n WHERE t.settings = s.id), '{}') AS \"attendance_statuses!: Vec<String>\",\n s.grade_bands AS \"grade_bands: Json<Vec<GradeBand>>\",\n s.max_file_bytes,\n s.chatbot_history_turns,\n s.max_chatbot_message_len,\n s.max_chatbot_threads,\n s.meal_slots AS \"meal_slots: Json<Vec<MealSlotDef>>\",\n (SELECT array_agg(t.tag ORDER BY t.tag)\n FROM settings_dietary_tag t\n WHERE t.settings = s.id) AS dietary_tags,\n s.meal_cancel_cutoff_minutes\n FROM settings s WHERE s.id = 'school'",
4 "describe": {4 "describe": {
5 "columns": [5 "columns": [
6 {6 {
@@ -16,14 +16,9 @@
16 },16 },
17 {17 {
18 "ordinal": 1,18 "ordinal": 1,
19- "name": "attendance_statuses",19+ "name": "attendance_statuses!: Vec<String>",
20 "type_info": "TextArray",20 "type_info": "TextArray",
21- "origin": {21+ "origin": "Expression"
22- "Table": {
23- "table": "settings",
24- "name": "attendance_statuses"
25- }
26- }
27 },22 },
28 {23 {
29 "ordinal": 2,24 "ordinal": 2,
@@ -95,12 +90,7 @@
95 "ordinal": 8,90 "ordinal": 8,
96 "name": "dietary_tags",91 "name": "dietary_tags",
97 "type_info": "TextArray",92 "type_info": "TextArray",
98- "origin": {93+ "origin": "Expression"
99- "Table": {
100- "table": "settings",
101- "name": "dietary_tags"
102- }
103- }
104 },94 },
105 {95 {
106 "ordinal": 9,96 "ordinal": 9,
@@ -119,16 +109,16 @@
119 },109 },
120 "nullable": [110 "nullable": [
121 false,111 false,
112+ null,
122 false,113 false,
123- false,
124- true,
125 true,114 true,
126 true,115 true,
127 true,116 true,
128 true,117 true,
129 true,118 true,
119+ null,
130 true120 true
131 ]121 ]
132 },122 },
133- "hash": "8a2042be8e7358d9c9f9f8a906ff113f71fa4ac519aec8519ee6b40bc51f694d"123+ "hash": "fb46d17a76c6111308068c735184bbb68a2b726f7a1c98068d506d51aa52785e"
134 }124 }
.sqlx/query-1f1dc2c17f96a49d8ae036569ba1d67db0558b58f0c2a463d54ad923254fba8c.json → .sqlx/query-fd31503ac762b761089f28233e0b2e425f8a349b2715ae2062fdda16d1c86d00.jsonrenamed+5 -10
@@ -1,6 +1,6 @@
1 {1 {
2 "db_name": "PostgreSQL",2 "db_name": "PostgreSQL",
3- "query": "SELECT student AS \"student: UserId\", tags AS \"tags: DietaryTags\", note AS \"note: DietaryNote\", updated_by AS \"updated_by: UserId\", updated_at AS \"updated_at: Timestamp\"\n FROM dietary_profile WHERE student = $1",3+ "query": "SELECT student AS \"student: UserId\",\n COALESCE((SELECT array_agg(t.tag ORDER BY t.ord) FROM dietary_profile_tag t WHERE t.student = dietary_profile.student), '{}'::text[]) AS \"tags!: DietaryTags\",\n note AS \"note: DietaryNote\", updated_by AS \"updated_by: UserId\", updated_at AS \"updated_at: Timestamp\"\n FROM dietary_profile WHERE student = $1",
4 "describe": {4 "describe": {
5 "columns": [5 "columns": [
6 {6 {
@@ -16,14 +16,9 @@
16 },16 },
17 {17 {
18 "ordinal": 1,18 "ordinal": 1,
19- "name": "tags: DietaryTags",19+ "name": "tags!: DietaryTags",
20 "type_info": "TextArray",20 "type_info": "TextArray",
21- "origin": {21+ "origin": "Expression"
22- "Table": {
23- "table": "dietary_profile",
24- "name": "tags"
25- }
26- }
27 },22 },
28 {23 {
29 "ordinal": 2,24 "ordinal": 2,
@@ -66,11 +61,11 @@
66 },61 },
67 "nullable": [62 "nullable": [
68 false,63 false,
69- false,64+ null,
70 true,65 true,
71 false,66 false,
72 false67 false
73 ]68 ]
74 },69 },
75- "hash": "1f1dc2c17f96a49d8ae036569ba1d67db0558b58f0c2a463d54ad923254fba8c"70+ "hash": "fd31503ac762b761089f28233e0b2e425f8a349b2715ae2062fdda16d1c86d00"
76 }71 }
.sqlx/query-fe740c4ecd33f9510af45852fdbb70712754d6d6095b27404cb77dc106774341.json → .sqlx/query-fe26461b2872573cafe05ba8d0b70ce84a117296bdf0c18e643293bb0b1e153e.jsonrenamed+5 -10
@@ -1,6 +1,6 @@
1 {1 {
2 "db_name": "PostgreSQL",2 "db_name": "PostgreSQL",
3- "query": "SELECT id AS \"id: BoardId\", creator AS \"creator: UserId\",\n title AS \"title: BoardTitle\",\n participants AS \"participants: Vec<UserId>\", locked,\n locked_by AS \"locked_by: UserId\",\n locked_at AS \"locked_at: Timestamp\", epoch,\n closed_at AS \"closed_at: Timestamp\",\n created_at AS \"created_at: Timestamp\"\n FROM board WHERE id = $1 FOR UPDATE",3+ "query": "SELECT id AS \"id: BoardId\", creator AS \"creator: UserId\",\n title AS \"title: BoardTitle\",\n ARRAY(SELECT p.participant FROM board_participant p\n WHERE p.board = board.id ORDER BY p.participant)\n AS \"participants!: Vec<UserId>\", locked,\n locked_by AS \"locked_by: UserId\",\n locked_at AS \"locked_at: Timestamp\", epoch,\n closed_at AS \"closed_at: Timestamp\",\n created_at AS \"created_at: Timestamp\"\n FROM board WHERE id = $1 FOR UPDATE",
4 "describe": {4 "describe": {
5 "columns": [5 "columns": [
6 {6 {
@@ -38,14 +38,9 @@
38 },38 },
39 {39 {
40 "ordinal": 3,40 "ordinal": 3,
41- "name": "participants: Vec<UserId>",41+ "name": "participants!: Vec<UserId>",
42 "type_info": "UuidArray",42 "type_info": "UuidArray",
43- "origin": {43+ "origin": "Expression"
44- "Table": {
45- "table": "board",
46- "name": "participants"
47- }
48- }
49 },44 },
50 {45 {
51 "ordinal": 4,46 "ordinal": 4,
@@ -123,7 +118,7 @@
123 false,118 false,
124 false,119 false,
125 false,120 false,
126- false,121+ null,
127 false,122 false,
128 true,123 true,
129 true,124 true,
@@ -132,5 +127,5 @@
132 false127 false
133 ]128 ]
134 },129 },
135- "hash": "fe740c4ecd33f9510af45852fdbb70712754d6d6095b27404cb77dc106774341"130+ "hash": "fe26461b2872573cafe05ba8d0b70ce84a117296bdf0c18e643293bb0b1e153e"
136 }131 }
README.mdmodified+72 -18
@@ -242,14 +242,40 @@ so the build never touches a database — the macros read the committed
242 `postgres:18-alpine` image, `max_connections=500` so the test suite's242 `postgres:18-alpine` image, `max_connections=500` so the test suite's
243 parallel control+school pools fit) and the backend, which waits for the243 parallel control+school pools fit) and the backend, which waits for the
244 database's healthcheck and connects over `DATABASE_URL`244 database's healthcheck and connects over `DATABASE_URL`
245-(`postgres://hezarfen:hezarfen@postgres:5432/hezarfen_control`). Each has245+(`postgres://hezarfen:hezarfen@postgres:5432/hezarfen_control`). The backend
246-its own named volume — `pgdata` holds the database, `hezarfen-data` the246+port is published on loopback only — `127.0.0.1:7656:7656` — so a server
247-uploaded note files (`/data/files`). `HOST` is forced to `0.0.0.0` inside the247+deployment sits behind a reverse proxy and the API is never directly
248-container so the published port works. Production knobs (`COOKIE_SECURE`,248+reachable (`HOST` is forced to `0.0.0.0` inside the container so the publish
249-`CORS_ALLOWED_ORIGINS`, rate limits, `TRUST_PROXY`) are commented in249+works). Each service has its own named volume: `pgdata` holds the database
250-`compose.yaml` — uncomment as needed. Leaving `CORS_ALLOWED_ORIGINS` unset250+— it is mounted at `/var/lib/postgresql`, which the postgres:18 image keeps
251-means dev mirror mode without credentials; a cookie-using browser frontend251+its cluster under (`/var/lib/postgresql/18/docker`), so the data really
252-must be allowlisted explicitly. Works with `docker compose` too.252+lands in the volume — and `hezarfen-data` holds the
253+uploaded note files (`/data/files`). Production knobs (`COOKIE_SECURE`,
254+`CORS_ALLOWED_ORIGINS`, rate limits, `TRUST_PROXY`) reach the backend through
255+the env file (below), not through `compose.yaml`. Leaving
256+`CORS_ALLOWED_ORIGINS` unset means dev mirror mode without credentials; a
257+cookie-using browser frontend must be allowlisted explicitly. Works with
258+`docker compose` too.
259+
260+**Credentials live in three places and are never mixed.** CI's postgres
261+sidecar uses a throwaway `hezarfen`/`hezarfen` pair declared in the workflow
262+— no GitHub secrets involved. Local compose interpolates dev defaults
263+(`hezarfen`/`hezarfen` for postgres, `builder`/`builder123` for the builder
264+account, `admin@hezarfen.local` / `Hezarfen_dev1!` for OpenObserve), so the
265+`up` above works with zero extra files. Production is the operator's job:
266+ssh to the VPS, copy `deploy/hezarfen_backend.env.example` to
267+`$HOME/hezarfen_backend/hezarfen_backend.env`, `chmod 0600` it, and set the
268+real passwords — the deploy pipeline never creates, overwrites or uploads
269+that file, it only refuses to run unless the file exists at mode `0600` with
270+non-empty `POSTGRES_PASSWORD=`, `BUILDER_PASSWORD=`, `ZO_ROOT_USER_EMAIL=` and
271+`ZO_ROOT_USER_PASSWORD=` values (prod never silently falls back to the dev defaults). The first `podman compose up` bakes
272+`POSTGRES_PASSWORD` into the `pgdata` volume: changing the env file
273+afterwards does not re-key the database, so the real password must be in
274+place before that first up, and it must be URL-safe (no `@`, `:`, `/` — it
275+is interpolated into `DATABASE_URL`). The same file is the backend's
276+optional `env_file`, so extra keys it carries (`COOKIE_SECURE`,
277+`TRUST_PROXY`, `CORS_*`, `RATE_LIMIT_*`, `OTEL_*`) reach the container
278+without being listed in `environment:`.
253 279
254 One more service is the telemetry sink: `openobserve`, a single Rust binary280 One more service is the telemetry sink: `openobserve`, a single Rust binary
255 that stores logs, metrics and traces itself — no sidecar databases and no281 that stores logs, metrics and traces itself — no sidecar databases and no
@@ -258,13 +284,38 @@ container socket. Its UI, search API and OTLP/HTTP ingest share
258 http://127.0.0.1:5080 as the `ZO_ROOT_USER_EMAIL`/`ZO_ROOT_USER_PASSWORD` pair284 http://127.0.0.1:5080 as the `ZO_ROOT_USER_EMAIL`/`ZO_ROOT_USER_PASSWORD` pair
259 set on the service (`admin@hezarfen.local` / `Hezarfen_dev1!` for local dev —285 set on the service (`admin@hezarfen.local` / `Hezarfen_dev1!` for local dev —
260 OpenObserve rejects a weaker password at boot). Retention is per stream in286 OpenObserve rejects a weaker password at boot). Retention is per stream in
261-days, defaulted globally to 90 by `ZO_COMPACT_DATA_RETENTION_DAYS`. Uncomment287+days, defaulted globally to 90 by `ZO_COMPACT_DATA_RETENTION_DAYS`. Traces,
262-the backend's `OTEL_EXPORTER_OTLP_ENDPOINT` (`http://openobserve:5081`) and288+metrics and logs start landing when the backend's environment carries
289+`OTEL_EXPORTER_OTLP_ENDPOINT` (`http://openobserve:5081`) and
263 `OTEL_EXPORTER_OTLP_HEADERS` (`Authorization=Basic <base64 email:password>`290 `OTEL_EXPORTER_OTLP_HEADERS` (`Authorization=Basic <base64 email:password>`
264-plus `organization=default,stream-name=default`), and traces, metrics and logs291+plus `organization=default,stream-name=default`) — those keys belong in the
265-start landing; the commented OTLP/HTTP variant uses292+env file (production: `hezarfen_backend.env`; locally: an optional file of
266-`http://openobserve:5080/api/default` with `OTEL_EXPORTER_OTLP_PROTOCOL:293+the same name beside `compose.yaml`), never in `compose.yaml` itself, where
267-http/protobuf` instead.294+an empty OTEL value would switch export on and fail the boot. The OTLP/HTTP
295+variant (`http://openobserve:5080/api/default` with
296+`OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf`) is the alternative.
297+
298+Running a server means running its backups too. `./backup-postgres.sh` —
299+shipped with the deploy artifact and living next to `compose.yaml` on the VPS
300+— streams `pg_dumpall` out of the postgres container into
301+`backups/hezarfen-<UTC>.sql.gz`, mode `0600`. `pg_dumpall` rather than
302+`pg_dump`, because every school is its own database and one dump has to cover
303+the control database and all of them. Restore with:
304+
305+```sh
306+gunzip -c backups/FILE.sql.gz | podman exec -i hezarfen-postgres psql -U hezarfen -d postgres
307+```
308+
309+Deploying is GitHub Actions' job, not the server's: the workflow packs the
310+already-built binary and the migrations into a runtime image
311+(`deploy/Containerfile.runtime`), ships the image tarball together with
312+`compose.yaml`, the `hezarfen-compose.service` unit and the backup script as
313+an artifact, and the deploy job loads it on the VPS and starts the stack with
314+`podman compose up -d --no-build` — the image tag travels in a deploy-owned
315+`stack.env`, so a release never rewrites the operator's secrets file. The
316+operator's only manual step is writing the env file once (above). Reboots
317+heal themselves: the user session lingers (`loginctl enable-linger`) and the
318+`hezarfen-compose.service` user unit runs compose again at boot.
268 319
269 The backend survives the database going away, at boot and at runtime.320 The backend survives the database going away, at boot and at runtime.
270 321
@@ -959,9 +1010,11 @@ if an older build already emptied a school's admin set): run
959 UPDATE app_user SET role = 'admin' WHERE username = 'ada';1010 UPDATE app_user SET role = 'admin' WHERE username = 'ada';
960 ```1011 ```
961 1012
962-against the **school's** database (`{control}_school_{slug}`), not the1013+against the **school's** database (`{control}_school_{uuid hex}` — the hex of
963-control one — e.g. `podman exec -it hezarfen-postgres psql -U hezarfen -d1014+the school's registry `id`, no dashes), not the control one. List the school
964-hezarfen_control_school_demo` for the compose stack.1015+databases with `\l` — e.g. `podman exec -it hezarfen-postgres psql -U hezarfen
1016+-d hezarfen_control -c "SELECT slug, id FROM school"` names each school and
1017+its database suffix for the compose stack.
965 1018
966 ## Endpoints1019 ## Endpoints
967 1020
@@ -4866,7 +4919,8 @@ driven by a client that shares no code with the backend).
4866 Every suite runs against a **real** PostgreSQL, because production is real4919 Every suite runs against a **real** PostgreSQL, because production is real
4867 PostgreSQL. The harness (tests/common) mints each test a private pair of4920 PostgreSQL. The harness (tests/common) mints each test a private pair of
4868 databases on one server — `heztest_<16 hex>` for the control side and its4921 databases on one server — `heztest_<16 hex>` for the control side and its
4869-`heztest_<…>_school_demo` school, template-cloned so a schema edit migrates4922+`heztest_<…>_school_<uuid hex>` school (the school's registry id, clipped to
4923+Postgres's 63-byte identifier cap), template-cloned so a schema edit migrates
4870 the shared template once — and drops them when the deployment's last handle4924 the shared template once — and drops them when the deployment's last handle
4871 dies; a janitor sweeps what a crashed run left behind. The server comes from4925 dies; a janitor sweeps what a crashed run left behind. The server comes from
4872 `HEZARFEN_TEST_DATABASE_URL` (default: the compose stack's maintenance4926 `HEZARFEN_TEST_DATABASE_URL` (default: the compose stack's maintenance
compose.yamlmodified+52 -43
@@ -1,3 +1,20 @@
1+# The whole stack: postgres + backend + OpenObserve behind podman compose.
2+#
3+# Credentials live in three places, never mixed (see README):
4+# laptop the ${VAR:-default} interpolations below — `podman compose up`
5+# works with zero extra files
6+# CI the workflow's throwaway postgres sidecar (hezarfen/hezarfen)
7+# VPS prod ~/hezarfen_backend/hezarfen_backend.env (0600, written by hand
8+# from deploy/hezarfen_backend.env.example)
9+#
10+# Interpolation reads the --env-file arguments (hezarfen_backend.env first,
11+# deploy-owned stack.env second). The `env_file:` on the backend passes the
12+# same secrets file into the container so extra keys (OTEL_*, COOKIE_SECURE,
13+# TRUST_PROXY, CORS_*, RATE_LIMIT_*) reach it without being listed in
14+# `environment:`. `environment:` wins over `env_file`, which is why
15+# DATABASE_URL is always constructed here: a leftover DATABASE_URL in the env
16+# file cannot point the container at the host.
17+
1 services:18 services:
2 postgres:19 postgres:
3 image: docker.io/library/postgres:18-alpine20 image: docker.io/library/postgres:18-alpine
@@ -6,16 +23,21 @@ services:
6 # (nextest runs ~a dozen concurrently), which exhausts the 100 default.23 # (nextest runs ~a dozen concurrently), which exhausts the 100 default.
7 command: ["postgres", "-c", "max_connections=500"]24 command: ["postgres", "-c", "max_connections=500"]
8 environment:25 environment:
9- POSTGRES_USER: hezarfen26+ POSTGRES_USER: ${POSTGRES_USER:-hezarfen}
10- POSTGRES_PASSWORD: hezarfen27+ POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-hezarfen}
11- POSTGRES_DB: hezarfen_control28+ POSTGRES_DB: ${POSTGRES_DB:-hezarfen_control}
12 ports:29 ports:
13 - "127.0.0.1:5432:5432"30 - "127.0.0.1:5432:5432"
14 volumes:31 volumes:
15- - pgdata:/data32+ # postgres:18 declares VOLUME /var/lib/postgresql (PGDATA is
33+ # /var/lib/postgresql/18/docker); mounting the parent keeps the whole
34+ # data dir — including future major-version subdirs — in the volume.
35+ - pgdata:/var/lib/postgresql
16 restart: unless-stopped36 restart: unless-stopped
17 healthcheck:37 healthcheck:
18- test: ["CMD-SHELL", "pg_isready -U hezarfen -d hezarfen_control"]38+ # $$ keeps compose from interpolating; the shell inside the container
39+ # expands the image's own POSTGRES_USER / POSTGRES_DB.
40+ test: ["CMD-SHELL", "pg_isready -U $$POSTGRES_USER -d $$POSTGRES_DB"]
19 interval: 10s41 interval: 10s
20 timeout: 5s42 timeout: 5s
21 retries: 543 retries: 5
@@ -25,52 +47,40 @@ services:
25 build:47 build:
26 context: .48 context: .
27 dockerfile: Containerfile49 dockerfile: Containerfile
28- image: localhost/hezarfen-backend:latest50+ # HEZARFEN_TAG comes from the deploy-owned stack.env (--env-file), or the
51+ # latest local build on a laptop.
52+ image: localhost/hezarfen-backend:${HEZARFEN_TAG:-latest}
29 container_name: hezarfen-backend53 container_name: hezarfen-backend
30 ports:54 ports:
31- - "7656:7656"55+ # Loopback only: terminate TLS on a reverse proxy in front of this.
56+ - "127.0.0.1:7656:7656"
32 # AI bridge (QUIC = UDP). Paired with AI_QUIC_ADDR below.57 # AI bridge (QUIC = UDP). Paired with AI_QUIC_ADDR below.
33 - "8090:8090/udp"58 - "8090:8090/udp"
59+ env_file:
60+ # Written once by the operator on the VPS (0600); absent on a laptop.
61+ - path: hezarfen_backend.env
62+ required: false
34 environment:63 environment:
35 HOST: 0.0.0.064 HOST: 0.0.0.0
36 PORT: "7656"65 PORT: "7656"
37 # The control database: the school registry + the builder accounts. Each66 # The control database: the school registry + the builder accounts. Each
38 # school lives in a Postgres database of its own, named from its slug.67 # school lives in a Postgres database of its own, named from its slug.
39- DATABASE_URL: postgres://hezarfen:hezarfen@postgres:5432/hezarfen_control68+ # Constructed from POSTGRES_* and always aimed at the compose postgres.
69+ DATABASE_URL: postgres://${POSTGRES_USER:-hezarfen}:${POSTGRES_PASSWORD:-hezarfen}@postgres:5432/${POSTGRES_DB:-hezarfen_control}
70+ # Hardcoded: must not pick up an old systemd host path from the env file.
40 FILES_PATH: /data/files71 FILES_PATH: /data/files
41 RUST_LOG: info,hezarfen_backend=debug72 RUST_LOG: info,hezarfen_backend=debug
42 # First-boot builder seed: the operator who creates and suspends schools,73 # First-boot builder seed: the operator who creates and suspends schools,
43- # created once if the username doesn't exist yet. Local-dev credentials —74+ # created once if the username doesn't exist yet.
44- # change or remove before exposing this anywhere.75+ BUILDER_USERNAME: ${BUILDER_USERNAME:-builder}
45- BUILDER_USERNAME: builder76+ BUILDER_PASSWORD: ${BUILDER_PASSWORD:-builder123}
46- BUILDER_PASSWORD: builder123
47- # Production knobs — uncomment as needed (see .env.example for docs):
48- # COOKIE_SECURE: "true"
49- # CORS_ALLOWED_ORIGINS: https://app.example.com
50- # RATE_LIMIT_AUTH_PER_MINUTE: "10"
51- # RATE_LIMIT_API_PER_MINUTE: "300"
52- # TRUST_PROXY: "true"
53- # Telemetry — export traces, metrics and logs to OpenObserve over OTLP.
54- # The Authorization value is base64("<ZO_ROOT_USER_EMAIL>:<password>");
55- # for the local-dev pair above that is the string below. gRPC carries the
56- # organization and the target stream as metadata headers.
57- # OTEL_EXPORTER_OTLP_ENDPOINT: http://openobserve:5081
58- # OTEL_EXPORTER_OTLP_HEADERS: "Authorization=Basic YWRtaW5AaGV6YXJmZW4ubG9jYWw6SGV6YXJmZW5fZGV2MSE=,organization=default,stream-name=default"
59- # OTEL_SERVICE_NAME: hezarfen-backend
60- # OTLP/HTTP instead: the org goes in the path (the SDK appends
61- # /v1/{traces,metrics,logs}) and only Authorization is needed.
62- # OTEL_EXPORTER_OTLP_ENDPOINT: http://openobserve:5080/api/default
63- # OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf
64- # OTEL_EXPORTER_OTLP_HEADERS: "Authorization=Basic YWRtaW5AaGV6YXJmZW4ubG9jYWw6SGV6YXJmZW5fZGV2MSE="
65 # AI bridge — the AI services dial IN over QUIC. Unset means off; a77 # AI bridge — the AI services dial IN over QUIC. Unset means off; a
66 # bad address or a missing token fails the boot rather than leaving a78 # bad address or a missing token fails the boot rather than leaving a
67 # silently dead feature. Listening with no service connected is fine:79 # silently dead feature. Listening with no service connected is fine:
68 # chat answers 503 until one registers `chat.reply`.80 # chat answers 503 until one registers `chat.reply`.
69- AI_QUIC_ADDR: 0.0.0.0:809081+ AI_QUIC_ADDR: ${AI_QUIC_ADDR:-0.0.0.0:8090}
70- # Every service must present this to register. Local-dev value — change82+ # Every service must present this to register.
71- # it before this is reachable from anywhere but your machine.83+ AI_SHARED_TOKEN: ${AI_SHARED_TOKEN:-change-me}
72- AI_SHARED_TOKEN: change-me
73- # AI_REQUEST_TIMEOUT_SECS: "30"
74 volumes:84 volumes:
75 - hezarfen-data:/data85 - hezarfen-data:/data
76 depends_on:86 depends_on:
@@ -88,18 +98,17 @@ services:
88 # OpenObserve is the only telemetry sink (no Grafana/Jaeger/Loki): one Rust98 # OpenObserve is the only telemetry sink (no Grafana/Jaeger/Loki): one Rust
89 # binary, its own storage, no container socket and no sidecar databases. It99 # binary, its own storage, no container socket and no sidecar databases. It
90 # speaks OTLP itself — HTTP on 5080 (also the UI and the search API), gRPC on100 # speaks OTLP itself — HTTP on 5080 (also the UI and the search API), gRPC on
91- # 5081. Both are published on loopback only.101+ # 5081. Both are published on loopback only. The backend exports to it only
102+ # when OTEL_* keys are present in hezarfen_backend.env (see the example).
92 openobserve:103 openobserve:
93 image: docker.io/openobserve/openobserve:v1.0.0-rc2104 image: docker.io/openobserve/openobserve:v1.0.0-rc2
94 container_name: hezarfen-openobserve105 container_name: hezarfen-openobserve
95 environment:106 environment:
96- # First-boot root account, created once. Local-dev credentials, same107+ # First-boot root account, created once. OpenObserve enforces a password
97- # status as the root/root above — change them before this is reachable108+ # policy (8-128 chars, upper + lower + digit + special) and panics on
98- # from anywhere but your machine. OpenObserve enforces a password policy109+ # boot otherwise.
99- # (8-128 chars, upper + lower + digit + special) and panics on boot110+ ZO_ROOT_USER_EMAIL: ${ZO_ROOT_USER_EMAIL:-admin@hezarfen.local}
100- # otherwise, hence the shape of this one.111+ ZO_ROOT_USER_PASSWORD: ${ZO_ROOT_USER_PASSWORD:-Hezarfen_dev1!}
101- ZO_ROOT_USER_EMAIL: admin@hezarfen.local
102- ZO_ROOT_USER_PASSWORD: Hezarfen_dev1!
103 ZO_DATA_DIR: /data112 ZO_DATA_DIR: /data
104 # Retention is per stream in days; this is the global default applied to113 # Retention is per stream in days; this is the global default applied to
105 # streams that don't override it (upstream default is 3650).114 # streams that don't override it (upstream default is 3650).
deploy/Containerfile.runtimeadded+37 -0
@@ -0,0 +1,37 @@
1+# CI-only runtime image: built from the gnu binary the workflow already
2+# compiled and stripped on ubuntu-24.04 — never from source here (a second
3+# rust compile blows the runner's disk; the source `Containerfile` stays for
4+# laptop `podman compose up --build`).
5+#
6+# Build context is stage/, populated by CI:
7+# docker build -f deploy/Containerfile.runtime \
8+# -t localhost/hezarfen-backend:$GITHUB_SHA stage/
9+# with stage/hezarfen_backend (the binary) and stage/migrations/.
10+FROM docker.io/library/debian:trixie-slim
11+
12+# curl answers the compose healthcheck; ca-certificates for TLS the backend
13+# may dial (OTLP endpoints, the AI bridge).
14+RUN apt-get update && \
15+ apt-get install -y --no-install-recommends curl ca-certificates && \
16+ rm -rf /var/lib/apt/lists/* && \
17+ useradd --system --uid 10001 hezarfen && \
18+ mkdir /data && chown hezarfen:hezarfen /data
19+
20+# Migrations MUST sit beside the binary at /app/hezarfen_backend: the CI
21+# runner's CARGO_MANIFEST_DIR does not exist in the image, so the app resolves
22+# the schema next to the executable (migrations_path in the source).
23+COPY hezarfen_backend /app/hezarfen_backend
24+COPY migrations /app/migrations
25+
26+WORKDIR /app
27+USER hezarfen
28+
29+# DATABASE_URL is deliberately not baked in: compose constructs it in
30+# `environment:` from POSTGRES_* (see compose.yaml), which also wins over the
31+# operator's env_file.
32+ENV HOST=0.0.0.0 \
33+ PORT=7656
34+
35+EXPOSE 7656
36+
37+ENTRYPOINT ["/app/hezarfen_backend"]
deploy/backup-postgres.shadded+26 -0
@@ -0,0 +1,26 @@
1+#!/usr/bin/env bash
2+# Dump every database in the hezarfen compose stack to backups/ next to this
3+# script. pg_dumpall is required (not pg_dump): each school is its own
4+# postgres database, and a control-only dump would lose them all.
5+#
6+# Keeps: backups/hezarfen-<UTC>.sql.gz, mode 0600.
7+# Cron example (daily 04:20):
8+# 20 4 * * * $HOME/hezarfen_backend/backup-postgres.sh
9+#
10+# Restore (from ~/hezarfen_backend):
11+# gunzip -c backups/FILE.sql.gz | podman exec -i hezarfen-postgres psql -U hezarfen -d postgres
12+set -euo pipefail
13+
14+dir="$(cd "$(dirname "$0")" && pwd)"
15+mkdir -p "$dir/backups"
16+
17+# POSTGRES_USER lives in the env file beside this script (plain KEY=value
18+# lines, no quotes/export); default hezarfen.
19+user="$(awk -F= '/^POSTGRES_USER=/{print $2; exit}' "$dir/hezarfen_backend.env" 2>/dev/null || true)"
20+user="${user:-hezarfen}"
21+
22+out="$dir/backups/hezarfen-$(date -u +%Y%m%dT%H%M%SZ).sql.gz"
23+umask 077
24+# pipefail (set above): a failed pg_dumpall must not leave a "good" empty dump.
25+podman exec hezarfen-postgres pg_dumpall -U "$user" | gzip > "$out"
26+echo "wrote $out ($(du -h "$out" | cut -f1))"
deploy/hezarfen-compose.serviceadded+47 -0
@@ -0,0 +1,47 @@
1+# systemd USER unit running the whole stack via podman compose (replaces the
2+# old bare-binary unit). Files expected in %h/hezarfen_backend:
3+# compose.yaml from the deploy artifact
4+# hezarfen_backend.env 0600, written ONCE BY HAND from
5+# deploy/hezarfen_backend.env.example — the
6+# deploy never creates or overwrites it
7+# stack.env deploy-owned; carries HEZARFEN_TAG
8+# backup-postgres.sh from the deploy artifact (0755)
9+#
10+# Required hezarfen_backend.env keys (full docs in
11+# deploy/hezarfen_backend.env.example):
12+# POSTGRES_USER/PASSWORD/DB first-boot postgres credentials;
13+# POSTGRES_PASSWORD is baked into the pgdata
14+# volume on the FIRST up and must be URL-safe
15+# (no @ : / — it is interpolated into
16+# DATABASE_URL)
17+# BUILDER_USERNAME/PASSWORD first-boot operator seed
18+# COOKIE_SECURE true behind TLS
19+# TRUST_PROXY true behind the reverse proxy
20+# CORS_ALLOWED_ORIGINS the browser frontends' origins
21+# AI_QUIC_ADDR/AI_SHARED_TOKEN the QUIC AI bridge
22+# OTEL_* OTLP export to http://openobserve:5081
23+# ZO_ROOT_USER_EMAIL/PASSWORD OpenObserve first-boot root account
24+# DEPLOY_ENV production
25+#
26+# Env-only restart (restart re-runs `compose up -d`, recreating containers
27+# whose environment changed):
28+# systemctl --user restart hezarfen-compose
29+
30+[Unit]
31+Description=Hezarfen backend compose stack (postgres + backend + openobserve)
32+After=network-online.target
33+Wants=network-online.target
34+
35+[Service]
36+Type=oneshot
37+RemainAfterExit=yes
38+WorkingDirectory=%h/hezarfen_backend
39+# Later --env-file wins for duplicate keys: the operator's secrets file
40+# first, the deploy-owned stack.env (HEZARFEN_TAG) second.
41+ExecStart=/usr/bin/podman compose --env-file %h/hezarfen_backend/hezarfen_backend.env --env-file %h/hezarfen_backend/stack.env up -d --no-build
42+# No -v: the pgdata/hezarfen-data/openobserve-data volumes must survive stop.
43+ExecStop=/usr/bin/podman compose down
44+TimeoutStartSec=180
45+
46+[Install]
47+WantedBy=default.target
deploy/hezarfen.servicedeleted+0 -41
@@ -1,41 +0,0 @@
1-# The systemd user unit the deploy installs to ~/.config/systemd/user/ and
2-# restarts. The release layout: ~/hezarfen_backend/current/hezarfen_backend with
3-# migrations/ beside the binary (the app resolves the schema there when the
4-# compile-time checkout path is absent — see migrations_path in the source).
5-#
6-# ~/hezarfen_backend/hezarfen_backend.env (0600, written once by hand, never by the deploy)
7-# carries the deployment's own values and overrides the Environment= lines
8-# below:
9-# DATABASE_URL required — a Postgres with the control database
10-# (first boot creates the schema; each school is
11-# minted as its own database by the builder API)
12-# BUILDER_USERNAME/PASSWORD first-boot operator seed
13-# AI_QUIC_ADDR + AI_SHARED_TOKEN the AI bridge (UDP); unset = off
14-# COOKIE_SECURE=true behind TLS
15-# CORS_ALLOWED_ORIGINS a lone `*` reflects any origin with credentials
16-# ("anywhere, for now"); list the real origins
17-# once the frontends are known
18-# TRUST_PROXY=true client IPs from X-Forwarded-For behind a proxy
19-#
20-# The service binds loopback only by default — terminate TLS on a reverse
21-# proxy and forward to 127.0.0.1:7656.
22-
23-[Unit]
24-Description=Hezarfen backend (school management API)
25-After=network-online.target
26-Wants=network-online.target
27-
28-[Service]
29-Type=simple
30-ExecStart=%h/hezarfen_backend/current/hezarfen_backend
31-WorkingDirectory=%h/hezarfen_backend/current
32-Environment=HOST=127.0.0.1
33-Environment=PORT=7656
34-Environment=FILES_PATH=%h/hezarfen_backend/data/files
35-Environment=RUST_LOG=info,hezarfen_backend=debug
36-EnvironmentFile=%h/hezarfen_backend/hezarfen_backend.env
37-Restart=on-failure
38-RestartSec=2
39-
40-[Install]
41-WantedBy=default.target
deploy/hezarfen_backend.env.exampleadded+67 -0
@@ -0,0 +1,67 @@
1+# hezarfen_backend.env — production secrets for the podman compose stack.
2+#
3+# One-time setup ON THE VPS, by hand:
4+# mkdir -p ~/hezarfen_backend
5+# cp hezarfen_backend.env.example ~/hezarfen_backend/hezarfen_backend.env
6+# <fill in the empty values below>
7+# chmod 0600 ~/hezarfen_backend/hezarfen_backend.env
8+#
9+# The deploy NEVER creates, overwrites, or uploads this file — the operator
10+# owns it; compose only reads it (compose --env-file, plus env_file into the
11+# backend container). Plain KEY=value lines: no quotes, no `export`.
12+#
13+# POSTGRES_*/BUILDER_*/ZO_*/AI_* are ALSO compose interpolations (the stack
14+# file builds DATABASE_URL and the postgres/openobserve config from them).
15+# Every other key (COOKIE_SECURE, TRUST_PROXY, CORS_*, RATE_LIMIT_*, OTEL_*,
16+# DEPLOY_ENV) is passed into the backend container verbatim via env_file.
17+
18+# ── Postgres (first boot) ────────────────────────────────────────────────────
19+# POSTGRES_PASSWORD is baked into the pgdata volume on the FIRST `compose up`;
20+# changing it here later does NOT re-key the database. Set the real password
21+# BEFORE the first production start. It is interpolated into DATABASE_URL, so
22+# it must be URL-safe: no `@`, `:`, or `/`.
23+POSTGRES_USER=hezarfen
24+POSTGRES_PASSWORD=
25+POSTGRES_DB=hezarfen_control
26+
27+# ── First-boot builder (operator) account ────────────────────────────────────
28+# Seeded once on boot if the username doesn't exist; existing accounts are
29+# never promoted to builder or re-keyed (resolve conflicts by hand).
30+BUILDER_USERNAME=builder
31+BUILDER_PASSWORD=
32+
33+# ── HTTP posture ─────────────────────────────────────────────────────────────
34+# Session-cookie Secure flag: true (the stack sits behind a TLS reverse proxy).
35+COOKIE_SECURE=true
36+# Derive client IPs from X-Forwarded-For behind the reverse proxy: true.
37+TRUST_PROXY=true
38+# Browser origins allowed to send the credentialed session cookie,
39+# comma-separated. A lone `*` mirrors EVERY origin with credentials — list the
40+# real frontends once known.
41+CORS_ALLOWED_ORIGINS=
42+
43+# ── AI bridge (QUIC over UDP 8090) ───────────────────────────────────────────
44+# Empty overrides the laptop compose default (0.0.0.0:8090 / change-me) and
45+# keeps the bridge off. Set BOTH to enable; address without token fails boot.
46+AI_QUIC_ADDR=
47+AI_SHARED_TOKEN=
48+# Per-request deadline; defaults to 30s. Anything above the 300s stale-answer
49+# horizon is clamped down at startup.
50+#AI_REQUEST_TIMEOUT_SECS=30
51+
52+# ── Telemetry (OpenObserve over OTLP) ────────────────────────────────────────
53+# Leave commented to keep export off (stdout logs only). Uncomment after
54+# ZO_ROOT_USER_* below are set; Authorization is
55+# base64("<ZO_ROOT_USER_EMAIL>:<ZO_ROOT_USER_PASSWORD>"):
56+# printf '%s:%s' 'admin@example.com' 'PASSWORD' | base64
57+#OTEL_EXPORTER_OTLP_ENDPOINT=http://openobserve:5081
58+#OTEL_EXPORTER_OTLP_HEADERS=Authorization=Basic <base64>,organization=default,stream-name=default
59+#OTEL_SERVICE_NAME=hezarfen-backend
60+# Names the deployment in every exported signal.
61+#DEPLOY_ENV=production
62+
63+# ── OpenObserve root account (first boot) ────────────────────────────────────
64+# OpenObserve enforces a password policy — 8-128 chars, upper + lower + digit
65+# + special — and panics on boot otherwise.
66+ZO_ROOT_USER_EMAIL=
67+ZO_ROOT_USER_PASSWORD=
migrations/control/20260912000001_control.sqlmodified+19 -10
@@ -12,9 +12,10 @@
12 -- default); timestamps stay BIGINT unix-ms. All FKs are ON DELETE NO ACTION —12 -- default); timestamps stay BIGINT unix-ms. All FKs are ON DELETE NO ACTION —
13 -- cascades stay explicit application transactions.13 -- cascades stay explicit application transactions.
14 --14 --
15--- Renames (reserved words, never quoted): table `school` keeps its name (its15+-- Renames (reserved words, never quoted): table `school` keeps its name. Its
16--- Surreal record id WAS the slug, so slug is the PRIMARY KEY, constraint16+-- Surreal record id WAS the slug; the Postgres table instead carries an
17--- carrying the old index name school_slug).17+-- app-minted uuid PRIMARY KEY (`id`) so the slug is a renameable label, with
18+-- the old PK index name `school_slug` kept as the UNIQUE constraint on slug.
18 --19 --
19 -- `rate_limit` exists ONLY here, not in the school schema: rate limiting is20 -- `rate_limit` exists ONLY here, not in the school schema: rate limiting is
20 -- billed against the control handle before any cookie names a school (see the21 -- billed against the control handle before any cookie names a school (see the
@@ -23,17 +24,25 @@
23 -- `tier:client:window` key, so the PK is TEXT.24 -- `tier:client:window` key, so the PK is TEXT.
24 25
25 CREATE TABLE school (26 CREATE TABLE school (
26- -- Immutable: a rename is blocked by the school_slug primary key below and27+ -- Surrogate identity, app-minted uuid v7 (no DB default): the per-school
27- -- by the per-school database name ({control}_school_{slug}) minted from28+ -- database name is minted from it (see tenant::school_db_name), so a slug
28- -- it — a slug change would orphan the database.29+ -- rename — once offered — can never orphan a database. Immutable keys
30+ -- belong to the uuid, never to the label.
31+ id uuid PRIMARY KEY,
29 slug TEXT NOT NULL,32 slug TEXT NOT NULL,
30 name TEXT NOT NULL,33 name TEXT NOT NULL,
31 status TEXT NOT NULL CONSTRAINT school_status CHECK (status IN ('active', 'suspended')),34 status TEXT NOT NULL CONSTRAINT school_status CHECK (status IN ('active', 'suspended')),
32 created_at BIGINT NOT NULL,35 created_at BIGINT NOT NULL,
33- -- Which product modules this school has bought; names bound from36+ CONSTRAINT school_slug UNIQUE (slug)
34- -- Module::ALL at write time, never spelled here.37+);
35- modules TEXT[] NOT NULL DEFAULT '{}',38+
36- CONSTRAINT school_slug PRIMARY KEY (slug)39+-- One row per product module the school has bought; names bound from
40+-- Module::ALL at write time, never spelled here. The pair is the key: the
41+-- membership is the link, and a read joins it back onto the school row.
42+CREATE TABLE school_module (
43+ school uuid NOT NULL REFERENCES school(id) ON DELETE NO ACTION,
44+ module TEXT NOT NULL,
45+ PRIMARY KEY (school, module)
37 );46 );
38 47
39 CREATE TABLE builder (48 CREATE TABLE builder (
migrations/control/20260913000001_person.sqlmodified+3 -1
@@ -27,7 +27,9 @@ CREATE TABLE person (
27 27
28 CREATE TABLE person_school (28 CREATE TABLE person_school (
29 person uuid NOT NULL REFERENCES person(id) ON DELETE NO ACTION,29 person uuid NOT NULL REFERENCES person(id) ON DELETE NO ACTION,
30- school TEXT NOT NULL REFERENCES school(slug) ON DELETE NO ACTION,30+ -- Points at the school's uuid identity, not its slug: the slug is a
31+ -- renameable label, and a membership must survive one.
32+ school uuid NOT NULL REFERENCES school(id) ON DELETE NO ACTION,
31 created_at BIGINT NOT NULL,33 created_at BIGINT NOT NULL,
32 CONSTRAINT person_school_person_school PRIMARY KEY (person, school)34 CONSTRAINT person_school_person_school PRIMARY KEY (person, school)
33 );35 );
migrations/school/20260912000001_identity.sqlmodified+31 -7
@@ -195,7 +195,6 @@ CREATE TABLE board (
195 id uuid PRIMARY KEY,195 id uuid PRIMARY KEY,
196 creator uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION,196 creator uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION,
197 title TEXT NOT NULL,197 title TEXT NOT NULL,
198- participants uuid[] NOT NULL DEFAULT '{}',
199 locked BOOLEAN NOT NULL DEFAULT false,198 locked BOOLEAN NOT NULL DEFAULT false,
200 locked_by uuid NULL REFERENCES app_user(id) ON DELETE NO ACTION,199 locked_by uuid NULL REFERENCES app_user(id) ON DELETE NO ACTION,
201 locked_at BIGINT NULL,200 locked_at BIGINT NULL,
@@ -207,9 +206,20 @@ CREATE TABLE board (
207 );206 );
208 207
209 CREATE INDEX board_creator ON board (creator);208 CREATE INDEX board_creator ON board (creator);
210--- The board list asks `creator = $u OR participants CONTAINS $u`; the GIN209+
211--- index covers the membership half ($1 = ANY(participants) at query sites).210+-- The roster, one row per (board, invited user). The membership predicate
212-CREATE INDEX board_participants ON board USING GIN (participants);211+-- everywhere is `creator = $u OR EXISTS (… WHERE participant = $u)` over
212+-- this table; the participant-side index is what the board list, the
213+-- demotion strip in src/db/user.rs and the cap checks read through. Rows
214+-- carry no order: every reader sorts by participant, so the assembled
215+-- roster is deterministic.
216+CREATE TABLE board_participant (
217+ board uuid NOT NULL REFERENCES board(id) ON DELETE NO ACTION,
218+ participant uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION,
219+ CONSTRAINT board_participant_board_participant PRIMARY KEY (board, participant)
220+);
221+
222+CREATE INDEX board_participant_participant ON board_participant (participant);
213 223
214 CREATE TABLE board_stroke (224 CREATE TABLE board_stroke (
215 id uuid PRIMARY KEY,225 id uuid PRIMARY KEY,
@@ -256,20 +266,34 @@ CREATE INDEX chatbot_message_user ON chatbot_message (user_id);
256 CREATE INDEX chatbot_message_status_created ON chatbot_message (status, created_at);266 CREATE INDEX chatbot_message_status_created ON chatbot_message (status, created_at);
257 267
258 CREATE TABLE settings (268 CREATE TABLE settings (
259- -- Singleton row: id = 'school'.
260 id TEXT PRIMARY KEY,269 id TEXT PRIMARY KEY,
261 exam_kinds JSONB NOT NULL,270 exam_kinds JSONB NOT NULL,
262- attendance_statuses TEXT[] NOT NULL,
263 grade_bands JSONB NOT NULL,271 grade_bands JSONB NOT NULL,
264 max_file_bytes BIGINT NULL,272 max_file_bytes BIGINT NULL,
265 chatbot_history_turns BIGINT NULL,273 chatbot_history_turns BIGINT NULL,
266 max_chatbot_message_len BIGINT NULL,274 max_chatbot_message_len BIGINT NULL,
267 max_chatbot_threads BIGINT NULL,275 max_chatbot_threads BIGINT NULL,
268 meal_slots JSONB NULL,276 meal_slots JSONB NULL,
269- dietary_tags TEXT[] NULL,
270 meal_cancel_cutoff_minutes BIGINT NULL277 meal_cancel_cutoff_minutes BIGINT NULL
271 );278 );
272 279
280+-- The settings singleton's two vocabulary lists, one row per entry. They
281+-- replace TEXT[] columns; the compare-and-set guard in src/db/settings.rs
282+-- compares these row *sets*, so nothing here carries order — every reader
283+-- sorts, and an absent set (never configured) and an explicitly empty one
284+-- both read as zero rows.
285+CREATE TABLE settings_attendance_status (
286+ settings TEXT NOT NULL REFERENCES settings(id) ON DELETE NO ACTION,
287+ status TEXT NOT NULL,
288+ CONSTRAINT settings_attendance_status_settings_status PRIMARY KEY (settings, status)
289+);
290+
291+CREATE TABLE settings_dietary_tag (
292+ settings TEXT NOT NULL REFERENCES settings(id) ON DELETE NO ACTION,
293+ tag TEXT NOT NULL,
294+ CONSTRAINT settings_dietary_tag_settings_tag PRIMARY KEY (settings, tag)
295+);
296+
273 -- Reference counters, one row per *name* the settings offer. Created by the297 -- Reference counters, one row per *name* the settings offer. Created by the
274 -- first claim; an absent row reads as zero references, in service.298 -- first claim; an absent row reads as zero references, in service.
275 CREATE TABLE kind_ref (299 CREATE TABLE kind_ref (
migrations/school/20260912000002_courses.sqlmodified+44 -11
@@ -33,15 +33,14 @@ CREATE TABLE term (
33 -- locked FOR UPDATE and refused while its enrollment_count is non-zero. The33 -- locked FOR UPDATE and refused while its enrollment_count is non-zero. The
34 -- child order is the FK-safest one: exam results/attempts/answers/images and34 -- child order is the FK-safest one: exam results/attempts/answers/images and
35 -- questions, homework files/submissions/results, rag output, note files and35 -- questions, homework files/submissions/results, rag output, note files and
36--- notes, class_course links (each class gets its class_course_count back and36+-- notes, class_course links (each class gets its class_course_count back),
37--- every blueprint drops the id from its list), session_attendance and37+-- blueprint_course and course_teacher links, session_attendance and
38 -- course_session, enrollment (each seat given back), then the exam, homework38 -- course_session, enrollment (each seat given back), then the exam, homework
39 -- and subject rows themselves. Bank questions keep their templates; only39 -- and subject rows themselves. Bank questions keep their templates; only
40 -- their subject/source_exam links are cleared.40 -- their subject/source_exam links are cleared.
41 CREATE TABLE course (41 CREATE TABLE course (
42 id uuid PRIMARY KEY,42 id uuid PRIMARY KEY,
43 creator uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION,43 creator uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION,
44- teachers uuid[] NOT NULL DEFAULT '{}',
45 title TEXT NOT NULL,44 title TEXT NOT NULL,
46 description TEXT NOT NULL,45 description TEXT NOT NULL,
47 kind TEXT NOT NULL DEFAULT 'course',46 kind TEXT NOT NULL DEFAULT 'course',
@@ -49,9 +48,20 @@ CREATE TABLE course (
49 capacity BIGINT NULL,48 capacity BIGINT NULL,
50 enrollment_count BIGINT NOT NULL DEFAULT 049 enrollment_count BIGINT NOT NULL DEFAULT 0
51 );50 );
52--- No GIN on teachers, faithful to the Surreal schema: the teachers-membership51+
53--- read stays a scan, exactly as today (see src/db/course.rs — the Surreal52+-- The staff a manager assigned to run a course. The old `teachers uuid[]` on
54--- per-element index form returned zero rows and was never defined).53+-- the course row is a junction now, like enrollment: membership is a row with
54+-- a foreign key, so an assigned user is a real reference (no dangling id a
55+-- demotion sweep or a delete can strand), the membership read is an index
56+-- lookup instead of an array scan, and "assigned to a course that is gone" is
57+-- unrepresentable rather than swept.
58+CREATE TABLE course_teacher (
59+ course uuid NOT NULL REFERENCES course(id) ON DELETE NO ACTION,
60+ teacher uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION,
61+ CONSTRAINT course_teacher_course_teacher PRIMARY KEY (course, teacher)
62+);
63+
64+CREATE INDEX course_teacher_teacher ON course_teacher (teacher);
55 65
56 CREATE TABLE subject (66 CREATE TABLE subject (
57 id uuid PRIMARY KEY,67 id uuid PRIMARY KEY,
@@ -91,15 +101,24 @@ CREATE TABLE rag_output (
91 id uuid PRIMARY KEY,101 id uuid PRIMARY KEY,
92 course_note uuid NOT NULL REFERENCES course_note(id) ON DELETE NO ACTION,102 course_note uuid NOT NULL REFERENCES course_note(id) ON DELETE NO ACTION,
93 course uuid NOT NULL REFERENCES course(id) ON DELETE NO ACTION,103 course uuid NOT NULL REFERENCES course(id) ON DELETE NO ACTION,
94- sources uuid[] NOT NULL DEFAULT '{}',
95 payload JSONB NOT NULL,104 payload JSONB NOT NULL,
96 generated_at BIGINT NOT NULL105 generated_at BIGINT NOT NULL
97 );106 );
98 107
99 CREATE INDEX rag_output_note ON rag_output (course_note);108 CREATE INDEX rag_output_note ON rag_output (course_note);
100--- The source cascade asks `sources CONTAINS $file`; the GIN index makes it a109+
101--- lookup instead of a scan.110+-- Citations: which course-note files an output was built from, as link rows
102-CREATE INDEX rag_output_source ON rag_output USING GIN (sources);111+-- with real foreign keys rather than an array column. A file delete sweeps
112+-- the links that cite it before the file row goes, and deleting an output
113+-- sweeps its links before the output row does — `ON DELETE NO ACTION` makes
114+-- the refusal (23503) the backstop if a sweep is forgotten.
115+CREATE TABLE rag_output_source (
116+ output uuid NOT NULL REFERENCES rag_output(id) ON DELETE NO ACTION,
117+ source uuid NOT NULL REFERENCES course_note_file(id) ON DELETE NO ACTION,
118+ CONSTRAINT rag_output_source_output_source PRIMARY KEY (output, source)
119+);
120+
121+CREATE INDEX rag_output_source_source ON rag_output_source (source);
103 122
104 CREATE TABLE course_session (123 CREATE TABLE course_session (
105 id uuid PRIMARY KEY,124 id uuid PRIMARY KEY,
@@ -150,10 +169,24 @@ CREATE INDEX class_group_grade ON class_group (grade);
150 CREATE TABLE class_blueprint (169 CREATE TABLE class_blueprint (
151 id uuid PRIMARY KEY,170 id uuid PRIMARY KEY,
152 grade TEXT NOT NULL CONSTRAINT class_blueprint_grade_key UNIQUE,171 grade TEXT NOT NULL CONSTRAINT class_blueprint_grade_key UNIQUE,
153- courses uuid[] NOT NULL DEFAULT '{}',
154 creator uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION172 creator uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION
155 );173 );
156 174
175+-- A template's course list. The old `courses uuid[]` on the blueprint row is
176+-- a junction now, like the class_course links it pumps: a course in a
177+-- template is a foreign-keyed row, so the course delete's own cascade takes
178+-- the link out (no dangling id a prune had to chase), the compare-and-set
179+-- edits compare row sets, and the grade-with-no-sections case loses its dead
180+-- course for free.
181+CREATE TABLE blueprint_course (
182+ blueprint uuid NOT NULL REFERENCES class_blueprint(id) ON DELETE NO ACTION,
183+ course uuid NOT NULL REFERENCES course(id) ON DELETE NO ACTION,
184+ CONSTRAINT blueprint_course_blueprint_course PRIMARY KEY (blueprint, course)
185+);
186+
187+-- The course delete's sweep strikes the link by course.
188+CREATE INDEX blueprint_course_course ON blueprint_course (course);
189+
157 CREATE TABLE class_member (190 CREATE TABLE class_member (
158 class uuid NOT NULL REFERENCES class_group(id) ON DELETE NO ACTION,191 class uuid NOT NULL REFERENCES class_group(id) ON DELETE NO ACTION,
159 app_user uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION,192 app_user uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION,
migrations/school/20260912000003_exams.sqlmodified+12 -2
@@ -215,14 +215,24 @@ CREATE TABLE homework (
215 title TEXT NOT NULL,215 title TEXT NOT NULL,
216 description TEXT NULL,216 description TEXT NULL,
217 due_at BIGINT NOT NULL,217 due_at BIGINT NOT NULL,
218- -- NULL/empty means the whole course.
219- assigned uuid[] NOT NULL DEFAULT '{}',
220 created_by uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION,218 created_by uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION,
221 created_at BIGINT NOT NULL219 created_at BIGINT NOT NULL
222 );220 );
223 221
224 CREATE INDEX homework_course ON homework (course);222 CREATE INDEX homework_course ON homework (course);
225 223
224+-- The audience of a homework: no rows = the whole course (whoever is enrolled
225+-- when they submit — later enrollees included); rows name the student subset,
226+-- a fixed snapshot taken at assign (or last PATCH) time. NO ACTION orders the
227+-- deletes: these rows go before the homework they scope.
228+CREATE TABLE homework_assignment (
229+ homework uuid NOT NULL REFERENCES homework(id) ON DELETE NO ACTION,
230+ student uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION,
231+ CONSTRAINT homework_assignment_homework_student PRIMARY KEY (homework, student)
232+);
233+
234+CREATE INDEX homework_assignment_student ON homework_assignment (student);
235+
226 CREATE TABLE homework_result (236 CREATE TABLE homework_result (
227 id uuid PRIMARY KEY,237 id uuid PRIMARY KEY,
228 homework uuid NOT NULL REFERENCES homework(id) ON DELETE NO ACTION,238 homework uuid NOT NULL REFERENCES homework(id) ON DELETE NO ACTION,
migrations/school/20260912000004_food_appointments_fees.sqlmodified+22 -2
@@ -95,21 +95,41 @@ CREATE TABLE menu_dish (
95 description TEXT NULL,95 description TEXT NULL,
96 -- Money is minor units (kuruş) as an integer, everywhere. Never decimal.96 -- Money is minor units (kuruş) as an integer, everywhere. Never decimal.
97 price_minor BIGINT NOT NULL,97 price_minor BIGINT NOT NULL,
98- tags TEXT[] NOT NULL DEFAULT '{}',
99 created_at BIGINT NOT NULL98 created_at BIGINT NOT NULL
100 );99 );
101 100
102 CREATE INDEX menu_dish_menu ON menu_dish (menu);101 CREATE INDEX menu_dish_menu ON menu_dish (menu);
103 102
103+-- The dish's dietary tags, one row each (was a TEXT[] column). `ord` keeps
104+-- the order the kitchen gave the list in: a profile intersection reports
105+-- conflicts in dish-tag order. Deleting a dish sweeps these rows first —
106+-- the FK is NO ACTION.
107+CREATE TABLE menu_dish_tag (
108+ dish uuid NOT NULL REFERENCES menu_dish(id) ON DELETE NO ACTION,
109+ tag TEXT NOT NULL,
110+ ord SMALLINT NOT NULL,
111+ CONSTRAINT menu_dish_tag_dish_tag PRIMARY KEY (dish, tag)
112+);
113+
104 CREATE TABLE dietary_profile (114 CREATE TABLE dietary_profile (
105 student uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION,115 student uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION,
106- tags TEXT[] NOT NULL DEFAULT '{}',
107 note TEXT NULL,116 note TEXT NULL,
108 updated_by uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION,117 updated_by uuid NOT NULL REFERENCES app_user(id) ON DELETE NO ACTION,
109 updated_at BIGINT NOT NULL,118 updated_at BIGINT NOT NULL,
110 CONSTRAINT dietary_profile_student PRIMARY KEY (student)119 CONSTRAINT dietary_profile_student PRIMARY KEY (student)
111 );120 );
112 121
122+-- The student's dietary tags, one row each (was a TEXT[] column): the same
123+-- vocabulary and the same `ord` order-preservation as menu_dish_tag. The
124+-- profile is the parent (no app_user FK of its own), so a tag exists only
125+-- while its profile row stands.
126+CREATE TABLE dietary_profile_tag (
127+ student uuid NOT NULL REFERENCES dietary_profile(student) ON DELETE NO ACTION,
128+ tag TEXT NOT NULL,
129+ ord SMALLINT NOT NULL,
130+ CONSTRAINT dietary_profile_tag_student_tag PRIMARY KEY (student, tag)
131+);
132+
113 -- A cancel flips `status` and stamps `cancelled_at`; the row stays so the133 -- A cancel flips `status` and stamps `cancelled_at`; the row stays so the
114 -- freed seat is still auditable against the ledger line it charged.134 -- freed seat is still auditable against the ledger line it charged.
115 CREATE TABLE meal_booking (135 CREATE TABLE meal_booking (
src/database.rsmodified+19 -11
@@ -28,7 +28,7 @@ use crate::domain::timestamp::Timestamp;
28 use crate::domain::user::{Password, Username};28 use crate::domain::user::{Password, Username};
29 use crate::error::AppError;29 use crate::error::AppError;
30 use crate::module::ModuleSet;30 use crate::module::ModuleSet;
31-use crate::tenant::{DEMO_SLUG, SchoolStatus, Slug, Tenants, school_db_name};31+use crate::tenant::{DEMO_SLUG, SchoolId, SchoolStatus, Tenants, school_db_name};
32 32
33 /// The shared database handle.33 /// The shared database handle.
34 ///34 ///
@@ -134,9 +134,10 @@ pub(crate) async fn school_pool(
134 /// A `CREATE DATABASE` / `DROP DATABASE` statement for a quoted identifier.134 /// A `CREATE DATABASE` / `DROP DATABASE` statement for a quoted identifier.
135 /// The names passed here are the control database's name (from135 /// The names passed here are the control database's name (from
136 /// `DATABASE_URL`), the template's (`{control}_school_template`) or136 /// `DATABASE_URL`), the template's (`{control}_school_template`) or
137-/// [`crate::tenant::school_db_name`]'s output — never user input: the slug137+/// [`crate::tenant::school_db_name`]'s output — never user input: the control
138-/// charset is `[a-z0-9-]` and an embedded quote is doubled, so the statement138+/// and template names come from configuration, the school name from a uuid's
139-/// cannot be escaped from. That manual audit is what licenses the139+/// hex (fixed `[0-9a-f]`), and an embedded quote is doubled besides, so the
140+/// statement cannot be escaped from. That manual audit is what licenses the
140 /// `AssertSqlSafe` wrapper every caller applies (sqlx refuses non-literal141 /// `AssertSqlSafe` wrapper every caller applies (sqlx refuses non-literal
141 /// query strings without it).142 /// query strings without it).
142 pub(crate) fn create_database_sql(statement: &str, name: &str) -> String {143 pub(crate) fn create_database_sql(statement: &str, name: &str) -> String {
@@ -451,7 +452,7 @@ fn builder_credentials(cfg: &Config) -> Result<Option<(Username, Password)>, App
451 //452 //
452 // Every test run gets a **private pair of databases** on the compose Postgres:453 // Every test run gets a **private pair of databases** on the compose Postgres:
453 // a control database and the demo school's database, both named after one454 // a control database and the demo school's database, both named after one
454-// random suffix — `heztest_<16 hex>` and `heztest_<…>_school_demo` — so455+// random suffix — `heztest_<16 hex>` and `heztest_<…>_school_<uuid hex>` — so
455 // nextest's parallel processes neither collide nor see each other's rows. The456 // nextest's parallel processes neither collide nor see each other's rows. The
456 // school schema is not migrated per test: it is cloned from a shared template457 // school schema is not migrated per test: it is cloned from a shared template
457 // database whose name carries a hash of `migrations/school`, so a schema edit458 // database whose name carries a hash of `migrations/school`, so a schema edit
@@ -612,9 +613,8 @@ pub async fn init_test_tenants() -> Tenants {
612 .unwrap_or_else(|err| panic!("migrate the test control database {control_db}: {err}"));613 .unwrap_or_else(|err| panic!("migrate the test control database {control_db}: {err}"));
613 614
614 let template = ensure_test_template(&maintenance, &base).await;615 let template = ensure_test_template(&maintenance, &base).await;
615-616+ let demo_id = SchoolId::generate();
616- let demo = Slug::try_new(DEMO_SLUG).expect("the demo slug");617+ let school_db = school_db_name(&control_db, demo_id.uuid());
617- let school_db = school_db_name(&control_db, &demo);
618 create_database(&maintenance, &school_db, Some(&template)).await;618 create_database(&maintenance, &school_db, Some(&template)).await;
619 lease.track(&school_db);619 lease.track(&school_db);
620 let school = school_pool(&base, &school_db)620 let school = school_pool(&base, &school_db)
@@ -625,24 +625,32 @@ pub async fn init_test_tenants() -> Tenants {
625 // without the per-school migration its `bring_up` runs, which the625 // without the per-school migration its `bring_up` runs, which the
626 // template clone has just replaced.626 // template clone has just replaced.
627 sqlx::query(627 sqlx::query(
628- "INSERT INTO school (slug, name, status, created_at, modules)628+ "INSERT INTO school (id, slug, name, status, created_at)
629 VALUES ($1, $2, $3, $4, $5)",629 VALUES ($1, $2, $3, $4, $5)",
630 )630 )
631+ .bind(demo_id.uuid())
631 .bind(DEMO_SLUG)632 .bind(DEMO_SLUG)
632 .bind("Demo School")633 .bind("Demo School")
633 .bind(SchoolStatus::Active)634 .bind(SchoolStatus::Active)
634 .bind(Timestamp::now().as_millis())635 .bind(Timestamp::now().as_millis())
635- .bind(ModuleSet::all().names())
636 .execute(&control)636 .execute(&control)
637 .await637 .await
638 .expect("register the test demo school");638 .expect("register the test demo school");
639+ for module in ModuleSet::all().names() {
640+ sqlx::query("INSERT INTO school_module (school, module) VALUES ($1, $2)")
641+ .bind(demo_id.uuid())
642+ .bind(module)
643+ .execute(&control)
644+ .await
645+ .expect("register the test demo school's modules");
646+ }
639 647
640 Tenants::new_test_adopting(648 Tenants::new_test_adopting(
641 control,649 control,
642 base.database(&control_db),650 base.database(&control_db),
643 control_db,651 control_db,
644 lease,652 lease,
645- [(demo, school)],653+ [(demo_id, school)],
646 )654 )
647 }655 }
648 656
src/db/board.rsmodified+163 -88
@@ -28,26 +28,40 @@ pub async fn create(
28 closed_at: None,28 closed_at: None,
29 created_at: Timestamp::now(),29 created_at: Timestamp::now(),
30 };30 };
31- // The seat claim and the row are one statement (the `cap::claim_and_create`31+ // The seat claim, the row and the roster are one statement (the
32- // CTE, spelled out at its call site): a refused insert takes its own32+ // `cap::claim_and_create` CTE, spelled out at its call site): a refused
33- // seat bump back, so the counter can never count a row that did not commit.33+ // insert takes its own seat bump back, so the counter can never count a
34+ // row that did not commit, and the roster can never trail the row. The
35+ // `participants` array is aggregated from the roster CTE's RETURNING —
36+ // the statement cannot see its own writes to `board_participant`.
34 let saved = sqlx::query_as!(37 let saved = sqlx::query_as!(
35 Board,38 Board,
36 r#"WITH seat AS (39 r#"WITH seat AS (
37 UPDATE app_user SET board_count = board_count + 140 UPDATE app_user SET board_count = board_count + 1
38 WHERE id = $1 AND board_count < $241 WHERE id = $1 AND board_count < $2
39- RETURNING 1)42+ RETURNING 1),
40- INSERT INTO board (id, creator, title, participants, locked, locked_by, locked_at,43+ new_board AS (
41- epoch, closed_at, created_at)44+ INSERT INTO board (id, creator, title, locked, locked_by, locked_at,
42- SELECT $3, $1, $4, $5, false, NULL, NULL, 0, NULL, $645+ epoch, closed_at, created_at)
43- WHERE EXISTS (SELECT 1 FROM seat)46+ SELECT $3, $1, $4, false, NULL, NULL, 0, NULL, $6
44- RETURNING id AS "id: BoardId", creator AS "creator: UserId",47+ WHERE EXISTS (SELECT 1 FROM seat)
45- title AS "title: BoardTitle",48+ RETURNING id, creator, title, locked, locked_by, locked_at,
46- participants AS "participants: Vec<UserId>", locked,49+ epoch, closed_at, created_at),
47- locked_by AS "locked_by: UserId",50+ roster AS (
48- locked_at AS "locked_at: Timestamp", epoch,51+ INSERT INTO board_participant (board, participant)
49- closed_at AS "closed_at: Timestamp",52+ SELECT $3, t.x FROM unnest($5::uuid[]) AS t(x)
50- created_at AS "created_at: Timestamp""#,53+ WHERE EXISTS (SELECT 1 FROM new_board)
54+ RETURNING participant)
55+ SELECT nb.id AS "id: BoardId", nb.creator AS "creator: UserId",
56+ nb.title AS "title: BoardTitle",
57+ COALESCE((SELECT array_agg(r.participant ORDER BY r.participant)
58+ FROM roster r), '{}')
59+ AS "participants!: Vec<UserId>",
60+ nb.locked, nb.locked_by AS "locked_by: UserId",
61+ nb.locked_at AS "locked_at: Timestamp", nb.epoch,
62+ nb.closed_at AS "closed_at: Timestamp",
63+ nb.created_at AS "created_at: Timestamp"
64+ FROM new_board nb"#,
51 board.creator.uuid(),65 board.creator.uuid(),
52 MAX_BOARDS_PER_CREATOR,66 MAX_BOARDS_PER_CREATOR,
53 board.id.uuid(),67 board.id.uuid(),
@@ -77,17 +91,26 @@ pub async fn create(
77 }91 }
78 }92 }
79 93
80-pub async fn read(db: &Database, id: &BoardId) -> Result<Option<Board>, AppError> {94+/// The one board read: row columns plus the roster, re-assembled from
95+/// `board_participant` (the array column is gone). The junction keeps no
96+/// insertion order, so every reader sorts by participant and the wire list
97+/// is deterministic.
98+async fn read_row<'e, E>(db: E, id: &BoardId) -> Result<Option<Board>, AppError>
99+where
100+ E: sqlx::PgExecutor<'e>,
101+{
81 let board = sqlx::query_as!(102 let board = sqlx::query_as!(
82 Board,103 Board,
83- r#"SELECT id AS "id: BoardId", creator AS "creator: UserId",104+ r#"SELECT b.id AS "id: BoardId", b.creator AS "creator: UserId",
84- title AS "title: BoardTitle",105+ b.title AS "title: BoardTitle",
85- participants AS "participants: Vec<UserId>", locked,106+ ARRAY(SELECT p.participant FROM board_participant p
86- locked_by AS "locked_by: UserId",107+ WHERE p.board = b.id ORDER BY p.participant)
87- locked_at AS "locked_at: Timestamp", epoch,108+ AS "participants!: Vec<UserId>",
88- closed_at AS "closed_at: Timestamp",109+ b.locked, b.locked_by AS "locked_by: UserId",
89- created_at AS "created_at: Timestamp"110+ b.locked_at AS "locked_at: Timestamp", b.epoch,
90- FROM board WHERE id = $1"#,111+ b.closed_at AS "closed_at: Timestamp",
112+ b.created_at AS "created_at: Timestamp"
113+ FROM board b WHERE b.id = $1"#,
91 id.uuid()114 id.uuid()
92 )115 )
93 .fetch_optional(db)116 .fetch_optional(db)
@@ -95,6 +118,10 @@ pub async fn read(db: &Database, id: &BoardId) -> Result<Option<Board>, AppError
95 Ok(board)118 Ok(board)
96 }119 }
97 120
121+pub async fn read(db: &Database, id: &BoardId) -> Result<Option<Board>, AppError> {
122+ read_row(db, id).await
123+}
124+
98 /// Every board `user` may open: the ones they created and the ones they125 /// Every board `user` may open: the ones they created and the ones they
99 /// were invited to. Newest first — the ids are monotonic, so `id` is the126 /// were invited to. Newest first — the ids are monotonic, so `id` is the
100 /// creation order.127 /// creation order.
@@ -111,12 +138,26 @@ pub async fn list_for_user(
111 offset: i64,138 offset: i64,
112 ) -> Result<(Vec<Board>, i64), AppError> {139 ) -> Result<(Vec<Board>, i64), AppError> {
113 let open_clause = match open {140 let open_clause = match open {
114- Some(true) => " AND closed_at IS NULL",141+ Some(true) => " AND b.closed_at IS NULL",
115- Some(false) => " AND closed_at IS NOT NULL",142+ Some(false) => " AND b.closed_at IS NOT NULL",
116 None => "",143 None => "",
117 };144 };
145+ // `PagedList` wraps `from_where` in `SELECT * FROM (…)`, so the window
146+ // is a whole derived table: the row columns plus the roster
147+ // re-assembled from `board_participant`, and the membership half of the
148+ // predicate as an `EXISTS` over it (the participant-side index covers
149+ // it, as the GIN index once did).
118 PagedList::new(150 PagedList::new(
119- format!("board WHERE (creator = $1 OR $2 = ANY(participants)){open_clause}"),151+ format!(
152+ "(SELECT b.id, b.creator, b.title,
153+ ARRAY(SELECT p.participant FROM board_participant p
154+ WHERE p.board = b.id ORDER BY p.participant) AS participants,
155+ b.locked, b.locked_by, b.locked_at, b.epoch, b.closed_at, b.created_at
156+ FROM board b
157+ WHERE (b.creator = $1
158+ OR EXISTS (SELECT 1 FROM board_participant bp
159+ WHERE bp.board = b.id AND bp.participant = $2)){open_clause})"
160+ ),
120 "ORDER BY id DESC",161 "ORDER BY id DESC",
121 )162 )
122 .bind(user.uuid())163 .bind(user.uuid())
@@ -125,33 +166,38 @@ pub async fn list_for_user(
125 .await166 .await
126 }167 }
127 168
128-/// Re-invite. Field-scoped, like every write here: a stroke landing169+/// Re-invite: the creator-driven roster replace. The write is the
129-/// concurrently is moving the counters this struct does not carry.170+/// junction's — rows go in one transaction with the read-back, because the
171+/// old single `UPDATE` both wrote the array and returned the row; a read
172+/// issued apart from the write could answer a roster someone else had
173+/// replaced in between.
130 pub async fn set_participants(174 pub async fn set_participants(
131 db: &Database,175 db: &Database,
132 board: &Board,176 board: &Board,
133 participants: Vec<UserId>,177 participants: Vec<UserId>,
134 ) -> Result<Board, AppError> {178 ) -> Result<Board, AppError> {
135 let participants = checked_participants(participants)?;179 let participants = checked_participants(participants)?;
136- let updated = sqlx::query_as!(180+ let ids: Vec<uuid::Uuid> = participants.iter().map(UserId::uuid).collect();
137- Board,181+ let id = board.id.clone();
138- r#"UPDATE board SET participants = $2 WHERE id = $1182+ tx_with_retry(db, true, async move |tx| {
139- RETURNING id AS "id: BoardId", creator AS "creator: UserId",183+ sqlx::query!("DELETE FROM board_participant WHERE board = $1", id.uuid())
140- title AS "title: BoardTitle",184+ .execute(&mut *tx)
141- participants AS "participants: Vec<UserId>", locked,185+ .await?;
142- locked_by AS "locked_by: UserId",186+ sqlx::query!(
143- locked_at AS "locked_at: Timestamp", epoch,187+ "INSERT INTO board_participant (board, participant)
144- closed_at AS "closed_at: Timestamp",188+ SELECT $1, t.x FROM unnest($2::uuid[]) AS t(x)
145- created_at AS "created_at: Timestamp""#,189+ ON CONFLICT DO NOTHING",
146- board.id.uuid(),190+ id.uuid(),
147- &participants191+ &ids,
148- .iter()192+ )
149- .map(UserId::uuid)193+ .execute(&mut *tx)
150- .collect::<Vec<uuid::Uuid>>()194+ .await?;
151- )195+ // The read-back is under the write path's own transaction: None here
152- .fetch_optional(db)196+ // means the board vanished between the caller's read and this tx,
153- .await?;197+ // which is the same 404 the old `UPDATE … RETURNING` produced.
154- one(updated)198+ read_row(&mut *tx, &id).await?.ok_or(AppError::NotFound)
199+ })
200+ .await
155 }201 }
156 202
157 pub async fn set_title(db: &Database, board: &Board, title: BoardTitle) -> Result<Board, AppError> {203 pub async fn set_title(db: &Database, board: &Board, title: BoardTitle) -> Result<Board, AppError> {
@@ -160,7 +206,9 @@ pub async fn set_title(db: &Database, board: &Board, title: BoardTitle) -> Resul
160 r#"UPDATE board SET title = $2 WHERE id = $1206 r#"UPDATE board SET title = $2 WHERE id = $1
161 RETURNING id AS "id: BoardId", creator AS "creator: UserId",207 RETURNING id AS "id: BoardId", creator AS "creator: UserId",
162 title AS "title: BoardTitle",208 title AS "title: BoardTitle",
163- participants AS "participants: Vec<UserId>", locked,209+ ARRAY(SELECT p.participant FROM board_participant p
210+ WHERE p.board = board.id ORDER BY p.participant)
211+ AS "participants!: Vec<UserId>", locked,
164 locked_by AS "locked_by: UserId",212 locked_by AS "locked_by: UserId",
165 locked_at AS "locked_at: Timestamp", epoch,213 locked_at AS "locked_at: Timestamp", epoch,
166 closed_at AS "closed_at: Timestamp",214 closed_at AS "closed_at: Timestamp",
@@ -187,7 +235,9 @@ pub async fn set_locked(
187 r#"UPDATE board SET locked = $2, locked_by = $3, locked_at = $4 WHERE id = $1235 r#"UPDATE board SET locked = $2, locked_by = $3, locked_at = $4 WHERE id = $1
188 RETURNING id AS "id: BoardId", creator AS "creator: UserId",236 RETURNING id AS "id: BoardId", creator AS "creator: UserId",
189 title AS "title: BoardTitle",237 title AS "title: BoardTitle",
190- participants AS "participants: Vec<UserId>", locked,238+ ARRAY(SELECT p.participant FROM board_participant p
239+ WHERE p.board = board.id ORDER BY p.participant)
240+ AS "participants!: Vec<UserId>", locked,
191 locked_by AS "locked_by: UserId",241 locked_by AS "locked_by: UserId",
192 locked_at AS "locked_at: Timestamp", epoch,242 locked_at AS "locked_at: Timestamp", epoch,
193 closed_at AS "closed_at: Timestamp",243 closed_at AS "closed_at: Timestamp",
@@ -202,13 +252,14 @@ pub async fn set_locked(
202 one(updated)252 one(updated)
203 }253 }
204 254
205-/// Union a bulk invite's resolved ids into the roster — the atomic-array255+/// Union a bulk invite's resolved ids into the roster — the atomic-union
206-/// replacement for the old process-wide roster lock. The merge and the256+/// replacement for the old process-wide roster lock. The merge is `INSERT
207-/// participant cap are one guarded statement: `SET` and `WHERE` both read257+/// … ON CONFLICT DO NOTHING`, and the board row is locked (`FOR NO KEY
208-/// the row version this `UPDATE` is acting on, so of two concurrent invites258+/// UPDATE`) before the cap counts: that lock is what the old guarded array
209-/// each sees the other's committed roster and the cap refuses the second —259+/// `UPDATE` got from its own row write, and it keeps the same property —
210-/// neither can drop the other's group, which is what the lock existed to260+/// of two concurrent invites the second waits, counts against the first's
211-/// prevent.261+/// committed roster, and the cap refuses it — neither can drop the other's
262+/// group.
212 ///263 ///
213 /// `None` means the guard refused (or the board is gone): the roster was264 /// `None` means the guard refused (or the board is gone): the roster was
214 /// left exactly as it was, and the caller re-reads to pick the message.265 /// left exactly as it was, and the caller re-reads to pick the message.
@@ -217,31 +268,46 @@ pub(crate) async fn invite_group(
217 board: &BoardId,268 board: &BoardId,
218 invited: Vec<UserId>,269 invited: Vec<UserId>,
219 ) -> Result<Option<Board>, AppError> {270 ) -> Result<Option<Board>, AppError> {
220- let updated = sqlx::query_as!(271+ let invited: Vec<uuid::Uuid> = invited.iter().map(UserId::uuid).collect();
221- Board,272+ let board = board.clone();
222- r#"UPDATE board273+ tx_with_retry(db, true, async move |tx| {
223- SET participants = (SELECT coalesce(array_agg(DISTINCT x), '{}')274+ // The serialization point; a vanished board refuses here, exactly
224- FROM unnest(participants || $2::uuid[]) AS x)275+ // like the old conditional `UPDATE` matching nothing.
225- WHERE id = $1276+ let live = sqlx::query!(
226- AND cardinality((SELECT coalesce(array_agg(DISTINCT x), '{}')277+ "SELECT id FROM board WHERE id = $1 FOR NO KEY UPDATE",
227- FROM unnest(participants || $2::uuid[]) AS x)) <= $3278+ board.uuid()
228- RETURNING id AS "id: BoardId", creator AS "creator: UserId",279+ )
229- title AS "title: BoardTitle",280+ .fetch_optional(&mut *tx)
230- participants AS "participants: Vec<UserId>", locked,281+ .await?;
231- locked_by AS "locked_by: UserId",282+ if live.is_none() {
232- locked_at AS "locked_at: Timestamp", epoch,283+ return Ok(None);
233- closed_at AS "closed_at: Timestamp",284+ }
234- created_at AS "created_at: Timestamp""#,285+ let would_be: i64 = sqlx::query_scalar!(
235- board.uuid(),286+ r#"SELECT ((SELECT count(*) FROM board_participant WHERE board = $1)
236- &invited287+ + (SELECT count(*) FROM unnest($2::uuid[]) AS t(x)
237- .iter()288+ WHERE NOT EXISTS (SELECT 1 FROM board_participant bp
238- .map(UserId::uuid)289+ WHERE bp.board = $1 AND bp.participant = t.x)))
239- .collect::<Vec<uuid::Uuid>>(),290+ AS "filled!""#,
240- MAX_BOARD_PARTICIPANTS as i64291+ board.uuid(),
241- )292+ &invited,
242- .fetch_optional(db)293+ )
243- .await?;294+ .fetch_one(&mut *tx)
244- Ok(updated)295+ .await?;
296+ if would_be > MAX_BOARD_PARTICIPANTS as i64 {
297+ return Ok(None);
298+ }
299+ sqlx::query!(
300+ "INSERT INTO board_participant (board, participant)
301+ SELECT $1, t.x FROM unnest($2::uuid[]) AS t(x)
302+ ON CONFLICT DO NOTHING",
303+ board.uuid(),
304+ &invited,
305+ )
306+ .execute(&mut *tx)
307+ .await?;
308+ read_row(&mut *tx, &board).await
309+ })
310+ .await
245 }311 }
246 312
247 // The demotion sweep — stripping a user off every roster they are listed313 // The demotion sweep — stripping a user off every roster they are listed
@@ -258,7 +324,9 @@ pub async fn close(db: &Database, board: &Board) -> Result<Board, AppError> {
258 r#"UPDATE board SET closed_at = $2 WHERE id = $1 AND closed_at IS NULL324 r#"UPDATE board SET closed_at = $2 WHERE id = $1 AND closed_at IS NULL
259 RETURNING id AS "id: BoardId", creator AS "creator: UserId",325 RETURNING id AS "id: BoardId", creator AS "creator: UserId",
260 title AS "title: BoardTitle",326 title AS "title: BoardTitle",
261- participants AS "participants: Vec<UserId>", locked,327+ ARRAY(SELECT p.participant FROM board_participant p
328+ WHERE p.board = board.id ORDER BY p.participant)
329+ AS "participants!: Vec<UserId>", locked,
262 locked_by AS "locked_by: UserId",330 locked_by AS "locked_by: UserId",
263 locked_at AS "locked_at: Timestamp", epoch,331 locked_at AS "locked_at: Timestamp", epoch,
264 closed_at AS "closed_at: Timestamp",332 closed_at AS "closed_at: Timestamp",
@@ -280,12 +348,17 @@ pub async fn close(db: &Database, board: &Board) -> Result<Board, AppError> {
280 /// transaction — a release issued afterwards can be lost, and the counter348 /// transaction — a release issued afterwards can be lost, and the counter
281 /// would then ratchet the creator's limit shut forever.349 /// would then ratchet the creator's limit shut forever.
282 ///350 ///
283-/// The stroke cascade rides in that same transaction: it is the one and351+/// The roster and the stroke cascade ride in that same transaction: the FK
284-/// only legitimate delete of `board_stroke` rows (a clear deletes nothing),352+/// is NO ACTION, so the junction rows go before the board row they name,
285-/// and issued separately it could leave a board's whole history orphaned353+/// and the stroke delete is the one and only legitimate delete of
286-/// under a record that no longer exists.354+/// `board_stroke` rows (a clear deletes nothing) — issued separately it
355+/// could leave a board's whole history orphaned under a record that no
356+/// longer exists.
287 pub async fn delete(db: &Database, board: Board) -> Result<Board, AppError> {357 pub async fn delete(db: &Database, board: Board) -> Result<Board, AppError> {
288 tx_with_retry(db, true, async move |conn| {358 tx_with_retry(db, true, async move |conn| {
359+ sqlx::query!("DELETE FROM board_participant WHERE board = $1", board.id.uuid())
360+ .execute(&mut *conn)
361+ .await?;
289 sqlx::query!("DELETE FROM board_stroke WHERE board = $1", board.id.uuid())362 sqlx::query!("DELETE FROM board_stroke WHERE board = $1", board.id.uuid())
290 .execute(&mut *conn)363 .execute(&mut *conn)
291 .await?;364 .await?;
@@ -294,7 +367,9 @@ pub async fn delete(db: &Database, board: Board) -> Result<Board, AppError> {
294 r#"DELETE FROM board WHERE id = $1367 r#"DELETE FROM board WHERE id = $1
295 RETURNING id AS "id: BoardId", creator AS "creator: UserId",368 RETURNING id AS "id: BoardId", creator AS "creator: UserId",
296 title AS "title: BoardTitle",369 title AS "title: BoardTitle",
297- participants AS "participants: Vec<UserId>", locked,370+ ARRAY(SELECT p.participant FROM board_participant p
371+ WHERE p.board = board.id ORDER BY p.participant)
372+ AS "participants!: Vec<UserId>", locked,
298 locked_by AS "locked_by: UserId",373 locked_by AS "locked_by: UserId",
299 locked_at AS "locked_at: Timestamp", epoch,374 locked_at AS "locked_at: Timestamp", epoch,
300 closed_at AS "closed_at: Timestamp",375 closed_at AS "closed_at: Timestamp",
src/db/board_stroke.rsmodified+3 -1
@@ -176,7 +176,9 @@ pub async fn clear(db: &Database, board: &BoardId, by: &UserId) -> Result<BoardS
176 Board,176 Board,
177 r#"SELECT id AS "id: BoardId", creator AS "creator: UserId",177 r#"SELECT id AS "id: BoardId", creator AS "creator: UserId",
178 title AS "title: BoardTitle",178 title AS "title: BoardTitle",
179- participants AS "participants: Vec<UserId>", locked,179+ ARRAY(SELECT p.participant FROM board_participant p
180+ WHERE p.board = board.id ORDER BY p.participant)
181+ AS "participants!: Vec<UserId>", locked,
180 locked_by AS "locked_by: UserId",182 locked_by AS "locked_by: UserId",
181 locked_at AS "locked_at: Timestamp", epoch,183 locked_at AS "locked_at: Timestamp", epoch,
182 closed_at AS "closed_at: Timestamp",184 closed_at AS "closed_at: Timestamp",
src/db/class_blueprint.rsmodified+234 -69
@@ -6,6 +6,8 @@
6 6
7 use sqlx::postgres::PgConnection;7 use sqlx::postgres::PgConnection;
8 8
9+use std::collections::HashMap;
10+
9 use crate::constant::CLASS_BLUEPRINT_TABLE;11 use crate::constant::CLASS_BLUEPRINT_TABLE;
10 use crate::database::{Database, tx_with_retry, unique_violation};12 use crate::database::{Database, tx_with_retry, unique_violation};
11 use crate::db::class_pump;13 use crate::db::class_pump;
@@ -17,6 +19,86 @@ use crate::domain::monotonic_id::next_uuid;
17 use crate::domain::user::UserId;19 use crate::domain::user::UserId;
18 use crate::error::{AppError, ValidationError};20 use crate::error::{AppError, ValidationError};
19 21
22+/// The stored columns of one `class_blueprint` row. A template's course list
23+/// is *not* one of them — it lives across the `blueprint_course` junction and
24+/// is joined on in a batch after the read ([`with_courses`]), because the
25+/// paged list here reads whole rows (`SELECT *`), a shape no aggregate column
26+/// can ride.
27+#[derive(Debug, sqlx::FromRow)]
28+struct BlueprintRow {
29+ /// The surrogate uuid primary key — the key the junction rows reference.
30+ #[sqlx(rename = "id")]
31+ key: uuid::Uuid,
32+ grade: ClassGrade,
33+ creator: UserId,
34+}
35+
36+impl BlueprintRow {
37+ fn into_blueprint(self, courses: Vec<CourseId>) -> ClassBlueprint {
38+ ClassBlueprint {
39+ // The API identity is the grade label, which the key column also
40+ // stores — the id *is* the grade.
41+ id: ClassBlueprintId::for_grade(&self.grade),
42+ grade: self.grade,
43+ courses,
44+ creator: self.creator,
45+ }
46+ }
47+}
48+
49+/// The stored course list of one blueprint, sorted by course. Every read goes
50+/// through this ordering, which is what makes the compare-and-set below a
51+/// plain vector comparison: both sides of it are junction reads.
52+async fn junction_courses<'e, E>(
53+ executor: E,
54+ blueprint: uuid::Uuid,
55+) -> Result<Vec<CourseId>, AppError>
56+where
57+ E: sqlx::PgExecutor<'e>,
58+{
59+ let rows = sqlx::query!(
60+ r#"SELECT course AS "course: CourseId" FROM blueprint_course
61+ WHERE blueprint = $1 ORDER BY course"#,
62+ blueprint,
63+ )
64+ .fetch_all(executor)
65+ .await?;
66+ Ok(rows.into_iter().map(|row| row.course).collect())
67+}
68+
69+/// Join the stored course lists onto a batch of blueprint rows, one junction
70+/// read for the lot.
71+async fn with_courses(
72+ db: &Database,
73+ rows: Vec<BlueprintRow>,
74+) -> Result<Vec<ClassBlueprint>, AppError> {
75+ if rows.is_empty() {
76+ return Ok(Vec::new());
77+ }
78+ let keys: Vec<uuid::Uuid> = rows.iter().map(|row| row.key).collect();
79+ let links = sqlx::query!(
80+ r#"SELECT blueprint, course AS "course: CourseId" FROM blueprint_course
81+ WHERE blueprint = ANY($1) ORDER BY blueprint, course"#,
82+ &keys,
83+ )
84+ .fetch_all(db)
85+ .await?;
86+ let mut by_blueprint: HashMap<uuid::Uuid, Vec<CourseId>> = HashMap::new();
87+ for link in links {
88+ by_blueprint
89+ .entry(link.blueprint)
90+ .or_default()
91+ .push(link.course);
92+ }
93+ Ok(rows
94+ .into_iter()
95+ .map(|row| {
96+ let courses = by_blueprint.remove(&row.key).unwrap_or_default();
97+ row.into_blueprint(courses)
98+ })
99+ .collect())
100+}
101+
20 /// One `class_course` row, projected down to the pair that answers "does this102 /// One `class_course` row, projected down to the pair that answers "does this
21 /// section carry that course". `source` is deliberately not read: a link of any103 /// section carry that course". `source` is deliberately not read: a link of any
22 #[derive(Debug, sqlx::FromRow)]104 #[derive(Debug, sqlx::FromRow)]
@@ -67,11 +149,12 @@ fn no_such_course() -> AppError {
67 })149 })
68 }150 }
69 151
70-/// Write the blueprint's row. A second one for the same grade is a 409 the152+/// Write the blueprint's row — and its `blueprint_course` rows, in the same
71-/// store itself decides — the grade carries a UNIQUE constraint, so the153+/// transaction, under the same per-course proof ([`courses_alive`]). A second
72-/// duplicate is seen rather than raced (`23505` on154+/// blueprint for the same grade is a 409 the store itself decides — the grade
73-/// `class_blueprint_grade_key`, mapped right here: a duplicate is a155+/// carries a UNIQUE constraint, so the duplicate is seen rather than raced
74-/// decision, never a retry). The surrogate `id` is minted here and never156+/// (`23505` on `class_blueprint_grade_key`, mapped right here: a duplicate is
157+/// a decision, never a retry). The surrogate `id` is minted here and never
75 /// read back: the grade label stays the only identity the API speaks.158 /// read back: the grade label stays the only identity the API speaks.
76 pub async fn create(159 pub async fn create(
77 db: &Database,160 db: &Database,
@@ -90,17 +173,27 @@ pub async fn create(
90 tx_with_retry(db, false, async move |tx| {173 tx_with_retry(db, false, async move |tx| {
91 courses_alive(tx, &courses).await?;174 courses_alive(tx, &courses).await?;
92 let inserted = sqlx::query!(175 let inserted = sqlx::query!(
93- r#"INSERT INTO class_blueprint (id, grade, courses, creator)176+ r#"INSERT INTO class_blueprint (id, grade, creator)
94- VALUES ($1, $2, $3, $4)"#,177+ VALUES ($1, $2, $3)"#,
95 id,178 id,
96 grade as _,179 grade as _,
97- courses as _,
98 creator as _180 creator as _
99 )181 )
100 .execute(&mut *tx)182 .execute(&mut *tx)
101 .await;183 .await;
102 match inserted {184 match inserted {
103- Ok(_) => Ok(blueprint.clone()),185+ Ok(_) => {
186+ sqlx::query!(
187+ r#"INSERT INTO blueprint_course (blueprint, course)
188+ SELECT $1, x FROM unnest($2::uuid[]) AS t(x)
189+ ON CONFLICT DO NOTHING"#,
190+ id,
191+ courses as _,
192+ )
193+ .execute(&mut *tx)
194+ .await?;
195+ Ok(blueprint.clone())
196+ }
104 Err(e) if unique_violation(&e) == Some("class_blueprint_grade_key") => Err(197 Err(e) if unique_violation(&e) == Some("class_blueprint_grade_key") => Err(
105 AppError::Conflict("a blueprint already exists for that grade"),198 AppError::Conflict("a blueprint already exists for that grade"),
106 ),199 ),
@@ -114,20 +207,22 @@ pub async fn read(
114 db: &Database,207 db: &Database,
115 id: &ClassBlueprintId,208 id: &ClassBlueprintId,
116 ) -> Result<Option<ClassBlueprint>, AppError> {209 ) -> Result<Option<ClassBlueprint>, AppError> {
117- let row = sqlx::query!(210+ let row = sqlx::query_as!(
118- r#"SELECT grade AS "id: ClassBlueprintId", grade AS "grade: ClassGrade",211+ BlueprintRow,
119- courses AS "courses: Vec<CourseId>", creator AS "creator: UserId"212+ r#"SELECT id AS "key: uuid::Uuid", grade AS "grade: ClassGrade",
213+ creator AS "creator: UserId"
120 FROM class_blueprint WHERE grade = $1"#,214 FROM class_blueprint WHERE grade = $1"#,
121 id as _215 id as _
122 )216 )
123 .fetch_optional(db)217 .fetch_optional(db)
124 .await?;218 .await?;
125- Ok(row.map(|row| ClassBlueprint {219+ match row {
126- id: row.id,220+ Some(row) => {
127- grade: row.grade,221+ let courses = junction_courses(db, row.key).await?;
128- courses: row.courses,222+ Ok(Some(row.into_blueprint(courses)))
129- creator: row.creator,223+ }
130- }))224+ None => Ok(None),
225+ }
131 }226 }
132 227
133 /// Every blueprint, by grade label — the id *is* the label, so this is the228 /// Every blueprint, by grade label — the id *is* the label, so this is the
@@ -137,17 +232,26 @@ pub async fn list_all(
137 limit: Option<i64>,232 limit: Option<i64>,
138 offset: i64,233 offset: i64,
139 ) -> Result<(Vec<ClassBlueprint>, i64), AppError> {234 ) -> Result<(Vec<ClassBlueprint>, i64), AppError> {
140- PagedList::new(CLASS_BLUEPRINT_TABLE, "ORDER BY grade ASC")235+ let (rows, total) = PagedList::new(CLASS_BLUEPRINT_TABLE, "ORDER BY grade ASC")
141- .run(limit, offset, db)236+ .run::<BlueprintRow>(limit, offset, db)
142- .await237+ .await?;
238+ Ok((with_courses(db, rows).await?, total))
143 }239 }
144 240
145-/// Write the course list only while the stored row still carries the list241+/// Write the course list only while the stored rows still answer to the list
146 /// this caller read: two managers editing the same grade cannot have one's242 /// this caller read: two managers editing the same grade cannot have one's
147-/// list silently pump the other's diff. `None` means the conditional write243+/// list silently pump the other's diff. `None` means the claim matched
148-/// matched nothing — the row is gone, or its list moved since the caller read244+/// nothing — the row is gone, or its list moved since the caller read it, and
149-/// it, and only the caller can tell those apart (the workflow re-reads and245+/// only the caller can tell those apart (the workflow re-reads and answers a
150-/// answers a `409` or a `404`).246+/// `409` or a `404`).
247+///
248+/// The write is a claim (`FOR UPDATE` on the row), a comparison (the stored
249+/// `blueprint_course` rows, read under that lock, against `held` — both
250+/// sorted the same way, so the comparison is a plain vector equality), then
251+/// the diff: rows `wanted` dropped are deleted, rows it added are inserted.
252+/// All of it rides one transaction, and the row lock it holds is the same
253+/// strength the blueprint delete takes, so a pump's `FOR KEY SHARE` claim on
254+/// this row waits out the whole write exactly as it waits out a delete.
151 ///255 ///
152 /// A template naming a course that is gone refuses inside the transaction256 /// A template naming a course that is gone refuses inside the transaction
153 /// with the pre-flight `400` ([`courses_alive`]).257 /// with the pre-flight `400` ([`courses_alive`]).
@@ -157,21 +261,49 @@ pub async fn set_courses_if_unchanged(
157 held: Vec<CourseId>,261 held: Vec<CourseId>,
158 wanted: Vec<CourseId>,262 wanted: Vec<CourseId>,
159 ) -> Result<Option<ClassBlueprint>, AppError> {263 ) -> Result<Option<ClassBlueprint>, AppError> {
160- let id = id.clone();264+ let grade = id.clone();
265+ let mut held = held;
266+ held.sort_by_key(|course| course.uuid());
267+ let keys: Vec<uuid::Uuid> = wanted.iter().map(CourseId::uuid).collect();
161 tx_with_retry(db, false, async move |tx| {268 tx_with_retry(db, false, async move |tx| {
162 courses_alive(tx, &wanted).await?;269 courses_alive(tx, &wanted).await?;
163- let updated = sqlx::query!(270+ let row = sqlx::query!(
164- r#"UPDATE class_blueprint SET courses = $2271+ r#"SELECT id AS "key: uuid::Uuid", grade AS "grade: ClassGrade",
165- WHERE grade = $1 AND courses = $3272+ creator AS "creator: UserId"
166- RETURNING grade AS "grade: ClassGrade", creator AS "creator: UserId""#,273+ FROM class_blueprint WHERE grade = $1 FOR UPDATE"#,
167- id as _,274+ grade.key(),
168- wanted as _,
169- held as _
170 )275 )
171 .fetch_optional(&mut *tx)276 .fetch_optional(&mut *tx)
172 .await?;277 .await?;
173- Ok(updated.map(|row| ClassBlueprint {278+ let Some(row) = row else {
174- id: id.clone(),279+ return Ok(None);
280+ };
281+ let stored = junction_courses(&mut *tx, row.key).await?;
282+ if stored != held {
283+ return Ok(None);
284+ }
285+ // The diff, from the list this caller stored: rows it dropped go,
286+ // rows it added come (a duplicate in `wanted` is one row — the
287+ // workflow deduplicates, and the key does the rest).
288+ sqlx::query!(
289+ r#"DELETE FROM blueprint_course
290+ WHERE blueprint = $1 AND NOT (course = ANY($2))"#,
291+ row.key,
292+ &keys,
293+ )
294+ .execute(&mut *tx)
295+ .await?;
296+ sqlx::query!(
297+ r#"INSERT INTO blueprint_course (blueprint, course)
298+ SELECT $1, x FROM unnest($2::uuid[]) AS t(x)
299+ ON CONFLICT DO NOTHING"#,
300+ row.key,
301+ &keys,
302+ )
303+ .execute(&mut *tx)
304+ .await?;
305+ Ok(Some(ClassBlueprint {
306+ id: ClassBlueprintId::for_grade(&row.grade),
175 grade: row.grade,307 grade: row.grade,
176 courses: wanted.clone(),308 courses: wanted.clone(),
177 creator: row.creator,309 creator: row.creator,
@@ -180,10 +312,10 @@ pub async fn set_courses_if_unchanged(
180 .await312 .await
181 }313 }
182 314
183-/// Delete the row, but only while it still carries the list this caller read315+/// Delete the row — but only while its stored list is still the one this
184-/// — the edit race answers the caller, not a silent delete of somebody316+/// caller read; the edit race answers the caller, not a silent delete of
185-/// else's additions. `false` means the conditional delete matched nothing:317+/// somebody else's additions. `false` means the claim matched nothing: the
186-/// the row is gone, or its list moved since the caller read it, and only the318+/// row is gone, or its list moved since the caller read it, and only the
187 /// caller can tell those apart.319 /// caller can tell those apart.
188 ///320 ///
189 /// The `DELETE` is also the whole of the serialization against the attaches321 /// The `DELETE` is also the whole of the serialization against the attaches
@@ -196,32 +328,60 @@ pub async fn delete_if_unchanged(
196 id: &ClassBlueprintId,328 id: &ClassBlueprintId,
197 held: Vec<CourseId>,329 held: Vec<CourseId>,
198 ) -> Result<bool, AppError> {330 ) -> Result<bool, AppError> {
199- let deleted = sqlx::query!(331+ let grade = id.clone();
200- r#"DELETE FROM class_blueprint WHERE grade = $1 AND courses = $2"#,332+ tx_with_retry(db, false, async move |tx| {
201- id as _,333+ delete_claimed(&mut *tx, &grade, &held).await
202- held as _334+ })
203- )335+ .await
204- .execute(db)
205- .await?;
206- Ok(deleted.rows_affected() > 0)
207 }336 }
208 337
209 /// [`delete_if_unchanged`] inside the caller's transaction — the blueprint338 /// [`delete_if_unchanged`] inside the caller's transaction — the blueprint
210 /// delete rides the row lock its claim took, so the sourced links are swept339 /// delete rides the row lock its claim took, so the sourced links are swept
211-/// while the window the claim opened is still closed.340+/// while the window the claim opened is still closed. The claim and the
341+/// comparison re-run here: in the delete workflow's own transaction the
342+/// [`held_courses_for_update`] claim has already settled both, so they are a
343+/// formality; the standalone path above gets its whole CAS from this one
344+/// body.
212 pub(crate) async fn delete_if_unchanged_in(345 pub(crate) async fn delete_if_unchanged_in(
213 tx: &mut sqlx::PgConnection,346 tx: &mut sqlx::PgConnection,
214 id: &ClassBlueprintId,347 id: &ClassBlueprintId,
215 held: &[CourseId],348 held: &[CourseId],
216 ) -> Result<bool, AppError> {349 ) -> Result<bool, AppError> {
217- let deleted = sqlx::query!(350+ delete_claimed(tx, id, held).await
218- r#"DELETE FROM class_blueprint WHERE grade = $1 AND courses = $2"#,351+}
352+
353+/// The delete's core: claim the row, compare the stored junction rows with
354+/// `held`, and take the junction rows before the blueprint row they
355+/// reference — the `NO ACTION` foreign key is checked the moment the final
356+/// `DELETE` runs.
357+async fn delete_claimed(
358+ tx: &mut PgConnection,
359+ id: &ClassBlueprintId,
360+ held: &[CourseId],
361+) -> Result<bool, AppError> {
362+ let row = sqlx::query!(
363+ r#"SELECT id AS "key: uuid::Uuid" FROM class_blueprint
364+ WHERE grade = $1 FOR UPDATE"#,
219 id as _,365 id as _,
220- held as _
221 )366 )
222- .execute(&mut *tx)367+ .fetch_optional(&mut *tx)
223 .await?;368 .await?;
224- Ok(deleted.rows_affected() > 0)369+ let Some(row) = row else {
370+ return Ok(false);
371+ };
372+ let mut held = held.to_vec();
373+ held.sort_by_key(|course| course.uuid());
374+ let stored = junction_courses(&mut *tx, row.key).await?;
375+ if stored != held {
376+ return Ok(false);
377+ }
378+ sqlx::query!(r#"DELETE FROM blueprint_course WHERE blueprint = $1"#, row.key)
379+ .execute(&mut *tx)
380+ .await?;
381+ sqlx::query!(r#"DELETE FROM class_blueprint WHERE id = $1"#, row.key)
382+ .execute(&mut *tx)
383+ .await?;
384+ Ok(true)
225 }385 }
226 386
227 /// The stored course list of one blueprint, read `FOR UPDATE` — the claim387 /// The stored course list of one blueprint, read `FOR UPDATE` — the claim
@@ -234,13 +394,16 @@ pub(crate) async fn held_courses_for_update(
234 id: &ClassBlueprintId,394 id: &ClassBlueprintId,
235 ) -> Result<Option<Vec<CourseId>>, AppError> {395 ) -> Result<Option<Vec<CourseId>>, AppError> {
236 let row = sqlx::query!(396 let row = sqlx::query!(
237- r#"SELECT courses AS "courses: Vec<CourseId>"397+ r#"SELECT id AS "key: uuid::Uuid" FROM class_blueprint
238- FROM class_blueprint WHERE grade = $1 FOR UPDATE"#,398+ WHERE grade = $1 FOR UPDATE"#,
239- id as _399+ id as _,
240 )400 )
241 .fetch_optional(&mut *tx)401 .fetch_optional(&mut *tx)
242 .await?;402 .await?;
243- Ok(row.map(|row| row.courses))403+ match row {
404+ Some(row) => Ok(Some(junction_courses(&mut *tx, row.key).await?)),
405+ None => Ok(None),
406+ }
244 }407 }
245 408
246 /// Every `class_course` row held by any of `classes`, projected down to the409 /// Every `class_course` row held by any of `classes`, projected down to the
@@ -265,15 +428,15 @@ pub async fn held_links(db: &Database, classes: Vec<ClassGroupId>) -> Result<Vec
265 428
266 /// Drop a course that no longer exists out of a blueprint's list.429 /// Drop a course that no longer exists out of a blueprint's list.
267 ///430 ///
268-/// The delete does this itself now: the course's own cascade sweeps431+/// The delete does this itself now — twice over: the course's own cascade
269-/// `class_blueprint` in the same transaction that takes the course's432+/// sweeps `blueprint_course` (the junction row is a foreign key now, so a
270-/// `class_course` links, so a template stops naming a course the instant that433+/// template physically cannot keep naming a course whose row is gone) in the
271-/// course goes. This used to be the *only* thing that could remove such an id,434+/// same transaction that takes the course's `class_course` links. This used
272-/// and that was the bug: it fires only while walking a section, so a grade435+/// to be the *only* thing that could remove such an id, and that was the bug:
273-/// with no sections could never reach it, and the repair every doc surface436+/// it fires only while walking a section, so a grade with no sections could
274-/// pointed at (`PATCH` the list back as it stands) is a `400` for naming a437+/// never reach it, and the repair every doc surface pointed at (`PATCH` the
275-/// course that does not exist. A permanent dangling id, and no call that could438+/// list back as it stands) is a `400` for naming a course that does not
276-/// clear it.439+/// exist. A permanent dangling id, and no call that could clear it.
277 ///440 ///
278 /// What is left for this to do is the **window** the sweep cannot cover: a441 /// What is left for this to do is the **window** the sweep cannot cover: a
279 /// pump walks a snapshot of the list it read, so a course deleted after442 /// pump walks a snapshot of the list it read, so a course deleted after
@@ -298,9 +461,11 @@ pub async fn prune(
298 course: &CourseId,461 course: &CourseId,
299 ) -> Result<(), AppError> {462 ) -> Result<(), AppError> {
300 sqlx::query!(463 sqlx::query!(
301- r#"UPDATE class_blueprint SET courses = array_remove(courses, $2) WHERE grade = $1"#,464+ r#"DELETE FROM blueprint_course
465+ WHERE course = $2
466+ AND blueprint = (SELECT id FROM class_blueprint WHERE grade = $1)"#,
302 id as _,467 id as _,
303- course as _468+ course as _,
304 )469 )
305 .execute(db)470 .execute(db)
306 .await?;471 .await?;
src/db/course.rsmodified+199 -109
@@ -12,6 +12,80 @@ use crate::domain::term::{self, TermId};
12 use crate::domain::user::UserId;12 use crate::domain::user::UserId;
13 use crate::error::AppError;13 use crate::error::AppError;
14 14
15+use std::collections::HashMap;
16+
17+/// The stored columns of a `course` row. The assigned teachers live across
18+/// the `course_teacher` junction, not on this row, so every read joins them
19+/// on in one batch afterwards ([`into_courses`]) — the two generic readers
20+/// below (the paged list and the field-scoped PATCH) both read whole rows
21+/// (`SELECT *` / `RETURNING *`), which is a shape no aggregate column can
22+/// ride.
23+#[derive(Debug, sqlx::FromRow)]
24+struct CourseRow {
25+ id: CourseId,
26+ creator: UserId,
27+ title: CourseTitle,
28+ description: CourseDescription,
29+ kind: CourseKind,
30+ term: Option<TermId>,
31+ capacity: Option<i64>,
32+}
33+
34+impl CourseRow {
35+ fn into_course(self, teachers: Vec<UserId>) -> Course {
36+ Course {
37+ id: self.id,
38+ creator: self.creator,
39+ teachers,
40+ title: self.title,
41+ description: self.description,
42+ kind: self.kind,
43+ term: self.term,
44+ capacity: self.capacity,
45+ }
46+ }
47+}
48+
49+/// Assemble [`Course`]s (their assigned teachers included) out of row reads:
50+/// one `course_teacher` query for the whole batch, a course nobody is
51+/// assigned to reading an empty list.
52+async fn into_courses(db: &Database, rows: Vec<CourseRow>) -> Result<Vec<Course>, AppError> {
53+ if rows.is_empty() {
54+ return Ok(Vec::new());
55+ }
56+ let ids: Vec<uuid::Uuid> = rows.iter().map(|row| row.id.uuid()).collect();
57+ let links = sqlx::query!(
58+ r#"SELECT course AS "course: CourseId", teacher AS "teacher: UserId"
59+ FROM course_teacher WHERE course = ANY($1)"#,
60+ &ids,
61+ )
62+ .fetch_all(db)
63+ .await?;
64+ let mut by_course: HashMap<uuid::Uuid, Vec<UserId>> = HashMap::new();
65+ for link in links {
66+ by_course
67+ .entry(link.course.uuid())
68+ .or_default()
69+ .push(link.teacher);
70+ }
71+ Ok(rows
72+ .into_iter()
73+ .map(|row| {
74+ let teachers = by_course.remove(&row.id.uuid()).unwrap_or_default();
75+ row.into_course(teachers)
76+ })
77+ .collect())
78+}
79+
80+/// [`into_courses`] for a single row.
81+async fn one_course(db: &Database, row: CourseRow) -> Result<Course, AppError> {
82+ let course = into_courses(db, vec![row])
83+ .await?
84+ .pop()
85+ .expect("one row in, one course out");
86+ Ok(course)
87+}
88+
15 pub async fn create(89 pub async fn create(
16 db: &Database,90 db: &Database,
17 creator: &UserId,91 creator: &UserId,
@@ -24,16 +98,15 @@ pub async fn create(
24 let id = CourseId::generate();98 let id = CourseId::generate();
25 let Some(term) = term else {99 let Some(term) = term else {
26 let created = sqlx::query_as!(100 let created = sqlx::query_as!(
27- Course,101+ CourseRow,
28- r#"INSERT INTO course (id, creator, teachers, title, description, kind, term, capacity)102+ r#"INSERT INTO course (id, creator, title, description, kind, term, capacity)
29- VALUES ($1, $2, $3, $4, $5, $6, NULL, $7)103+ VALUES ($1, $2, $3, $4, $5, NULL, $6)
30 RETURNING id AS "id: CourseId", creator AS "creator: UserId",104 RETURNING id AS "id: CourseId", creator AS "creator: UserId",
31- teachers AS "teachers: Vec<UserId>", title AS "title: CourseTitle",105+ title AS "title: CourseTitle",
32 description AS "description: CourseDescription",106 description AS "description: CourseDescription",
33 kind AS "kind: CourseKind", term AS "term: TermId", capacity"#,107 kind AS "kind: CourseKind", term AS "term: TermId", capacity"#,
34 id.uuid(),108 id.uuid(),
35 creator.uuid(),109 creator.uuid(),
36- &Vec::<uuid::Uuid>::new(),
37 title.as_str(),110 title.as_str(),
38 description.as_str(),111 description.as_str(),
39 kind.as_str(),112 kind.as_str(),
@@ -41,7 +114,8 @@ pub async fn create(
41 )114 )
42 .fetch_one(db)115 .fetch_one(db)
43 .await?;116 .await?;
44- return Ok(created);117+ // A new course has no assigned teachers; the join reads an empty list.
118+ return one_course(db, created).await;
45 };119 };
46 // Claim a reference on the term in the *same statement* as the row: the120 // Claim a reference on the term in the *same statement* as the row: the
47 // claim is a conditional write on the term row, so it fails when the121 // claim is a conditional write on the term row, so it fails when the
@@ -50,21 +124,20 @@ pub async fn create(
50 // which a claim sent as its own query could (the count would strand and124 // which a claim sent as its own query could (the count would strand and
51 // the term be undeletable forever).125 // the term be undeletable forever).
52 let created = sqlx::query_as!(126 let created = sqlx::query_as!(
53- Course,127+ CourseRow,
54 r#"WITH seat AS (128 r#"WITH seat AS (
55 UPDATE term129 UPDATE term
56 SET course_count = course_count + 1130 SET course_count = course_count + 1
57- WHERE id = $8 AND course_count < $9131+ WHERE id = $7 AND course_count < $8
58 RETURNING 1)132 RETURNING 1)
59- INSERT INTO course (id, creator, teachers, title, description, kind, term, capacity)133+ INSERT INTO course (id, creator, title, description, kind, term, capacity)
60- SELECT $1, $2, $3, $4, $5, $6, $8, $7 WHERE EXISTS (SELECT 1 FROM seat)134+ SELECT $1, $2, $3, $4, $5, $7, $6 WHERE EXISTS (SELECT 1 FROM seat)
61 RETURNING id AS "id: CourseId", creator AS "creator: UserId",135 RETURNING id AS "id: CourseId", creator AS "creator: UserId",
62- teachers AS "teachers: Vec<UserId>", title AS "title: CourseTitle",136+ title AS "title: CourseTitle",
63 description AS "description: CourseDescription",137 description AS "description: CourseDescription",
64 kind AS "kind: CourseKind", term AS "term: TermId", capacity"#,138 kind AS "kind: CourseKind", term AS "term: TermId", capacity"#,
65 id.uuid(),139 id.uuid(),
66 creator.uuid(),140 creator.uuid(),
67- &Vec::<uuid::Uuid>::new(),
68 title.as_str(),141 title.as_str(),
69 description.as_str(),142 description.as_str(),
70 kind.as_str(),143 kind.as_str(),
@@ -75,7 +148,7 @@ pub async fn create(
75 .fetch_one(db)148 .fetch_one(db)
76 .await;149 .await;
77 match created {150 match created {
78- Ok(created) => Ok(created),151+ Ok(created) => one_course(db, created).await,
79 // Uncapped, so "full" can only mean the conditional write matched no152 // Uncapped, so "full" can only mean the conditional write matched no
80 // term row at all — the existence check the pre-flight lookup makes.153 // term row at all — the existence check the pre-flight lookup makes.
81 Err(sqlx::Error::RowNotFound) => Err(term::gone_error()),154 Err(sqlx::Error::RowNotFound) => Err(term::gone_error()),
@@ -87,33 +160,40 @@ pub async fn create(
87 }160 }
88 }161 }
89 162
90-pub async fn read(db: &Database, id: &CourseId) -> Result<Option<Course>, AppError> {163+async fn read_row(db: &Database, id: &CourseId) -> Result<Option<CourseRow>, AppError> {
91- let course = sqlx::query_as!(164+ sqlx::query_as!(
92- Course,165+ CourseRow,
93 r#"SELECT id AS "id: CourseId", creator AS "creator: UserId",166 r#"SELECT id AS "id: CourseId", creator AS "creator: UserId",
94- teachers AS "teachers: Vec<UserId>", title AS "title: CourseTitle",167+ title AS "title: CourseTitle",
95 description AS "description: CourseDescription",168 description AS "description: CourseDescription",
96 kind AS "kind: CourseKind", term AS "term: TermId", capacity169 kind AS "kind: CourseKind", term AS "term: TermId", capacity
97 FROM course WHERE id = $1"#,170 FROM course WHERE id = $1"#,
98 id.uuid(),171 id.uuid(),
99 )172 )
100 .fetch_optional(db)173 .fetch_optional(db)
101- .await?;174+ .await
102- Ok(course)175+ .map_err(Into::into)
176+}
177+
178+pub async fn read(db: &Database, id: &CourseId) -> Result<Option<Course>, AppError> {
179+ match read_row(db, id).await? {
180+ Some(row) => Ok(Some(one_course(db, row).await?)),
181+ None => Ok(None),
182+ }
103 }183 }
104 184
105 pub async fn list_all(db: &Database) -> Result<Vec<Course>, AppError> {185 pub async fn list_all(db: &Database) -> Result<Vec<Course>, AppError> {
106 let rows = sqlx::query_as!(186 let rows = sqlx::query_as!(
107- Course,187+ CourseRow,
108 r#"SELECT id AS "id: CourseId", creator AS "creator: UserId",188 r#"SELECT id AS "id: CourseId", creator AS "creator: UserId",
109- teachers AS "teachers: Vec<UserId>", title AS "title: CourseTitle",189+ title AS "title: CourseTitle",
110 description AS "description: CourseDescription",190 description AS "description: CourseDescription",
111 kind AS "kind: CourseKind", term AS "term: TermId", capacity191 kind AS "kind: CourseKind", term AS "term: TermId", capacity
112 FROM course ORDER BY id DESC"#,192 FROM course ORDER BY id DESC"#,
113 )193 )
114 .fetch_all(db)194 .fetch_all(db)
115 .await?;195 .await?;
116- Ok(rows)196+ into_courses(db, rows).await
117 }197 }
118 198
119 /// The courses `user` is enrolled in — the spine of `/courses/me` and the199 /// The courses `user` is enrolled in — the spine of `/courses/me` and the
@@ -124,42 +204,39 @@ pub async fn list_enrolled(
124 limit: Option<i64>,204 limit: Option<i64>,
125 offset: i64,205 offset: i64,
126 ) -> Result<(Vec<Course>, i64), AppError> {206 ) -> Result<(Vec<Course>, i64), AppError> {
127- PagedList::new(207+ let (rows, total) = PagedList::new(
128 "course WHERE id IN (SELECT course FROM enrollment WHERE app_user = $1)",208 "course WHERE id IN (SELECT course FROM enrollment WHERE app_user = $1)",
129 "ORDER BY id DESC",209 "ORDER BY id DESC",
130 )210 )
131 .bind(user.uuid())211 .bind(user.uuid())
132- .run::<Course>(limit, offset, db)212+ .run::<CourseRow>(limit, offset, db)
133- .await213+ .await?;
214+ Ok((into_courses(db, rows).await?, total))
134 }215 }
135 216
136 /// The courses `user` runs — the ones they created plus the ones a manager217 /// The courses `user` runs — the ones they created plus the ones a manager
137 /// assigned them to. A teacher's slice of the catalog.218 /// assigned them to. A teacher's slice of the catalog.
138 ///219 ///
139-/// corner-cut: unpaged full table scan, and it stays one — every profile220+/// The assigned half reads `course_teacher` by its `teacher` index (the
140-/// read of a teacher pays it, so the ceiling is the course table's size.221+/// shape `enrollment` already has) instead of an array membership test —
141-/// Under Postgres the `OR` halves could each use an index on `creator` /222+/// that test was the corner-cut here once, and the junction is exactly the
142-/// `teachers` (a GIN), but the old per-element index the membership half223+/// upgrade path the old comment called structural.
143-/// would have needed was *wrong*, not merely useless — `$usr IN teachers`
144-/// returned **no rows at all** with it, which is what the integration test
145-/// `assigned_teacher_manages_course_without_owning_it` catches. The upgrade
146-/// path is structural: a `course_teacher` link table indexed on `user`, the
147-/// shape `enrollment` already has, turning this into two index-backed
148-/// reads. No schema carries it yet, so the scan stays.
149 pub async fn list_for_teacher(db: &Database, user: &UserId) -> Result<Vec<Course>, AppError> {224 pub async fn list_for_teacher(db: &Database, user: &UserId) -> Result<Vec<Course>, AppError> {
150 let rows = sqlx::query_as!(225 let rows = sqlx::query_as!(
151- Course,226+ CourseRow,
152 r#"SELECT id AS "id: CourseId", creator AS "creator: UserId",227 r#"SELECT id AS "id: CourseId", creator AS "creator: UserId",
153- teachers AS "teachers: Vec<UserId>", title AS "title: CourseTitle",228+ title AS "title: CourseTitle",
154 description AS "description: CourseDescription",229 description AS "description: CourseDescription",
155 kind AS "kind: CourseKind", term AS "term: TermId", capacity230 kind AS "kind: CourseKind", term AS "term: TermId", capacity
156- FROM course WHERE creator = $1 OR $2 = ANY(teachers) ORDER BY id DESC"#,231+ FROM course WHERE creator = $1 OR id IN (
232+ SELECT course FROM course_teacher WHERE teacher = $2)
233+ ORDER BY id DESC"#,
157 user.uuid(),234 user.uuid(),
158 user.uuid(),235 user.uuid(),
159 )236 )
160 .fetch_all(db)237 .fetch_all(db)
161 .await?;238 .await?;
162- Ok(rows)239+ into_courses(db, rows).await
163 }240 }
164 241
165 /// Load every course behind `ids` (one query) — the join half of the242 /// Load every course behind `ids` (one query) — the join half of the
@@ -170,9 +247,9 @@ pub async fn list_by_ids(db: &Database, ids: &[CourseId]) -> Result<Vec<Course>,
170 }247 }
171 let keys: Vec<uuid::Uuid> = ids.iter().map(CourseId::uuid).collect();248 let keys: Vec<uuid::Uuid> = ids.iter().map(CourseId::uuid).collect();
172 let rows = sqlx::query_as!(249 let rows = sqlx::query_as!(
173- Course,250+ CourseRow,
174 r#"SELECT id AS "id: CourseId", creator AS "creator: UserId",251 r#"SELECT id AS "id: CourseId", creator AS "creator: UserId",
175- teachers AS "teachers: Vec<UserId>", title AS "title: CourseTitle",252+ title AS "title: CourseTitle",
176 description AS "description: CourseDescription",253 description AS "description: CourseDescription",
177 kind AS "kind: CourseKind", term AS "term: TermId", capacity254 kind AS "kind: CourseKind", term AS "term: TermId", capacity
178 FROM course WHERE id = ANY($1)"#,255 FROM course WHERE id = ANY($1)"#,
@@ -180,19 +257,22 @@ pub async fn list_by_ids(db: &Database, ids: &[CourseId]) -> Result<Vec<Course>,
180 )257 )
181 .fetch_all(db)258 .fetch_all(db)
182 .await?;259 .await?;
183- Ok(rows)260+ into_courses(db, rows).await
184 }261 }
185 262
186-/// Request-scoped: `teachers` is written by [`assign_teacher`],263+/// Field-scoped: nothing guards the course row across the handler's read
187-/// [`unassign_teacher`] and the demotion sweep, and nothing guards264+/// and this write (its `TERM_LOCK` window guards the *term* it links, and
188-/// the course row across the handler's read and this write (its `TERM_LOCK`265+/// the assign path takes no lock at all) — so a field the request omitted
189-/// window guards the *term* it links, and the assign path takes no lock at266+/// (`None`) is not written at all. Sending the snapshot's value back
190-/// all) — so a field the request omitted (`None`) is not written at all.267+/// instead would revert a concurrent edit of that field; scoping the `SET`
191-/// Sending the snapshot's value back instead would revert a concurrent268+/// alone does not stop that, the values have to come from the request.
192-/// edit of that field; scoping the `SET` alone does not stop that, the269+/// `term` and `capacity` are nullable, so they take the outer/inner
193-/// values have to come from the request. `term` and `capacity` are270+/// `Option<Option<_>>`: `None` = omitted (keep), `Some(None)` = clear.
194-/// nullable, so they take the outer/inner `Option<Option<_>>`: `None` =271+///
195-/// omitted (keep), `Some(None)` = clear.272+/// The assigned teachers are not fields of this row — they are
273+/// `course_teacher` rows, written only by [`assign_teacher`],
274+/// [`unassign_teacher`] and the demotion sweep — so a PATCH can neither
275+/// carry nor clobber them.
196 pub async fn update(276 pub async fn update(
197 db: &Database,277 db: &Database,
198 course: Course,278 course: Course,
@@ -208,7 +288,7 @@ pub async fn update(
208 // without its count. A PATCH that carried no `term_id`, or re-stated the288 // without its count. A PATCH that carried no `term_id`, or re-stated the
209 // link it already had, moves neither counter.289 // link it already had, moves neither counter.
210 let (claim, release) = term::ref_move(course.term.as_ref(), &term);290 let (claim, release) = term::ref_move(course.term.as_ref(), &term);
211- FieldUpdate::new(COURSE_TABLE, course.id.uuid())291+ let row = FieldUpdate::new(COURSE_TABLE, course.id.uuid())
212 .set("title", title.map(|title| title.as_str().to_owned()))292 .set("title", title.map(|title| title.as_str().to_owned()))
213 .set(293 .set(
214 "description",294 "description",
@@ -229,18 +309,17 @@ pub async fn update(
229 release: release.map(|term| term.uuid()),309 release: release.map(|term| term.uuid()),
230 refused: term::gone_error(),310 refused: term::gone_error(),
231 })311 })
232- .run::<Course>(db)312+ .run::<CourseRow>(db)
233- .await313+ .await?;
314+ // The teachers are joined on after the write, off the junction.
315+ one_course(db, row).await
234 }316 }
235 317
236 /// Assign `teacher` to run this course, or return the course untouched if318 /// Assign `teacher` to run this course, or return the course untouched if
237-/// they already run it — assignment is idempotent, like enrollment.319+/// they already run it — assignment is idempotent, like enrollment: the
238-/// Field-scoped, and the new list is folded server-side out of the *stored*320+/// link is an `INSERT` whose `(course, teacher)` key answers a duplicate
239-/// one: a course PATCH awaits a term lookup between its read and its write,321+/// with `DO NOTHING`, so two requests naming the same teacher at once land
240-/// so a whole-row save from either side would revert the other. The322+/// one row (the early return only sees a stale snapshot).
241-/// `array_agg(DISTINCT …)` keeps the assignment idempotent even when two
242-/// requests name the same teacher at once (the early return only sees a
243-/// stale row).
244 pub async fn assign_teacher(323 pub async fn assign_teacher(
245 db: &Database,324 db: &Database,
246 course: Course,325 course: Course,
@@ -249,22 +328,22 @@ pub async fn assign_teacher(
249 if course.is_assigned(teacher) {328 if course.is_assigned(teacher) {
250 return Ok(course);329 return Ok(course);
251 }330 }
252- let updated = sqlx::query_as!(331+ // `WHERE EXISTS` keeps the insert a no-op when the course went between
253- Course,332+ // the caller's read and this write — the answer is the `NotFound` the
254- r#"UPDATE course333+ // fresh read below gives, not a foreign-key 500.
255- SET teachers = (SELECT array_agg(DISTINCT x)334+ sqlx::query!(
256- FROM unnest(course.teachers || $2::uuid) AS x)335+ r#"INSERT INTO course_teacher (course, teacher)
257- WHERE id = $1336+ SELECT $1, $2 WHERE EXISTS (SELECT 1 FROM course WHERE id = $1)
258- RETURNING id AS "id: CourseId", creator AS "creator: UserId",337+ ON CONFLICT DO NOTHING"#,
259- teachers AS "teachers: Vec<UserId>", title AS "title: CourseTitle",
260- description AS "description: CourseDescription",
261- kind AS "kind: CourseKind", term AS "term: TermId", capacity"#,
262 course.id.uuid(),338 course.id.uuid(),
263 teacher.uuid(),339 teacher.uuid(),
264 )340 )
265- .fetch_optional(db)341+ .execute(db)
266 .await?;342 .await?;
267- updated.ok_or(AppError::NotFound)343+ // Fresh read, like the `RETURNING` this replaced: the snapshot's
344+ // teacher list can be stale (a concurrent assign).
345+ let row = read_row(db, &course.id).await?.ok_or(AppError::NotFound)?;
346+ one_course(db, row).await
268 }347 }
269 348
270 /// Drop `teacher` from this course. `None` when they weren't assigned, so349 /// Drop `teacher` from this course. `None` when they weren't assigned, so
@@ -277,35 +356,26 @@ pub async fn unassign_teacher(
277 if !course.is_assigned(teacher) {356 if !course.is_assigned(teacher) {
278 return Ok(None);357 return Ok(None);
279 }358 }
280- // Same field-scoped story as [`assign_teacher`]; `array_remove` drops359+ let deleted = sqlx::query!(
281- // the one link off the stored list without touching the course's own360+ r#"DELETE FROM course_teacher WHERE course = $1 AND teacher = $2"#,
282- // text.
283- let updated = sqlx::query_as!(
284- Course,
285- r#"UPDATE course SET teachers = array_remove(teachers, $2)
286- WHERE id = $1
287- RETURNING id AS "id: CourseId", creator AS "creator: UserId",
288- teachers AS "teachers: Vec<UserId>", title AS "title: CourseTitle",
289- description AS "description: CourseDescription",
290- kind AS "kind: CourseKind", term AS "term: TermId", capacity"#,
291 course.id.uuid(),361 course.id.uuid(),
292 teacher.uuid(),362 teacher.uuid(),
293 )363 )
294- .fetch_optional(db)364+ .execute(db)
295 .await?;365 .await?;
296- Ok(updated)366+ if deleted.rows_affected() == 0 {
367+ // Unassigned under the caller's feet — nothing was removed.
368+ return Ok(None);
369+ }
370+ read(db, &course.id).await
297 }371 }
298 372
299 /// Strip `user` from every course they were assigned to — the sweep for a373 /// Strip `user` from every course they were assigned to — the sweep for a
300 /// user demoted below `teacher`, who may no longer run anything.374 /// user demoted below `teacher`, who may no longer run anything.
301 pub async fn unassign_everywhere(db: &Database, user: &UserId) -> Result<(), AppError> {375 pub async fn unassign_everywhere(db: &Database, user: &UserId) -> Result<(), AppError> {
302- sqlx::query!(376+ sqlx::query!(r#"DELETE FROM course_teacher WHERE teacher = $1"#, user.uuid(),)
303- r#"UPDATE course SET teachers = array_remove(teachers, $1)377+ .execute(db)
304- WHERE $1 = ANY(teachers)"#,378+ .await?;
305- user.uuid(),
306- )
307- .execute(db)
308- .await?;
309 Ok(())379 Ok(())
310 }380 }
311 381
@@ -330,15 +400,14 @@ pub async fn unassign_everywhere(db: &Database, user: &UserId) -> Result<(), App
330 /// ever visits that column) and at a dead subject the next `PATCH`400 /// ever visits that column) and at a dead subject the next `PATCH`
331 /// omitting `subject_id` writes straight back.401 /// omitting `subject_id` writes straight back.
332 ///402 ///
333-/// The **grade blueprints** naming it are swept in that same transaction.403+/// The **grade blueprints** naming it are swept in that same transaction —
334-/// Nothing else can reach them — a blueprint holds its courses as a list on404+/// their `blueprint_course` link rows are FK children now, deleted right
335-/// its own row, not as link rows this cascade could delete — and an id left405+/// here like any other link, so a template stops naming a course the
336-/// behind is permanent rather than merely stale: the pump's own406+/// instant that course goes (the old `teachers`-style array made the id a
337-/// [`crate::db::class_blueprint::prune`] fires only while walking a407+/// permanent dangling value only the pump's [`crate::db::class_blueprint::
338-/// section, so a grade with no sections can never drop one, and every408+/// prune`] could chase). The same transaction takes the course's
339-/// `PATCH` of that template is refused for naming a course that does not409+/// `course_teacher` assignment rows: an assigned teacher loses the course
340-/// exist, which is precisely the call documented as the repair. A dozen-row410+/// with it.
341-/// table scanned unindexed, deliberately: a course delete is rare.
342 ///411 ///
343 /// The **derived AI rows** (`rag_output` carries a denormalized `course`412 /// The **derived AI rows** (`rag_output` carries a denormalized `course`
344 /// besides its note link) and the event **audience links** are FK children413 /// besides its note link) and the event **audience links** are FK children
@@ -358,9 +427,9 @@ pub async fn unassign_everywhere(db: &Database, user: &UserId) -> Result<(), App
358 /// and question images before `exam_question`; `exam_question` before427 /// and question images before `exam_question`; `exam_question` before
359 /// `exam`; homework files before submissions before results before428 /// `exam`; homework files before submissions before results before
360 /// `homework`; roll-call rows before `course_session`; note files and429 /// `homework`; roll-call rows before `course_session`; note files and
361-/// rag rows before `course_note`; every one of them before the `course`430+/// rag rows before `course_note`; `blueprint_course` and `course_teacher`
362-/// row itself, whose `NO ACTION` FKs are checked the moment the final431+/// before the `course` row itself, whose `NO ACTION` FKs are checked the
363-/// `DELETE` runs.432+/// moment the final `DELETE` runs.
364 ///433 ///
365 /// `false` = refused, nothing was written: someone is still enrolled. The434 /// `false` = refused, nothing was written: someone is still enrolled. The
366 /// guard locks the course row (`FOR UPDATE`) and reads its own435 /// guard locks the course row (`FOR UPDATE`) and reads its own
@@ -470,7 +539,15 @@ pub async fn delete(db: &Database, course: Course) -> Result<bool, AppError> {
470 )539 )
471 .execute(&mut *tx)540 .execute(&mut *tx)
472 .await?;541 .await?;
473- // Derived AI rows for this course's notes.542+ // Derived AI rows for this course's notes — links before the rows
543+ // (`ON DELETE NO ACTION`).
544+ sqlx::query!(
545+ r#"DELETE FROM rag_output_source WHERE output IN (
546+ SELECT id FROM rag_output WHERE course = $1)"#,
547+ course.id.uuid(),
548+ )
549+ .execute(&mut *tx)
550+ .await?;
474 sqlx::query!(551 sqlx::query!(
475 r#"DELETE FROM rag_output WHERE course = $1"#,552 r#"DELETE FROM rag_output WHERE course = $1"#,
476 course.id.uuid()553 course.id.uuid()
@@ -504,8 +581,14 @@ pub async fn delete(db: &Database, course: Course) -> Result<bool, AppError> {
504 .execute(&mut *tx)581 .execute(&mut *tx)
505 .await?;582 .await?;
506 sqlx::query!(583 sqlx::query!(
507- r#"UPDATE class_blueprint SET courses = array_remove(courses, $1)584+ r#"DELETE FROM blueprint_course WHERE course = $1"#,
508- WHERE $1 = ANY(courses)"#,585+ course.id.uuid(),
586+ )
587+ .execute(&mut *tx)
588+ .await?;
589+ // The assignment links die with the course, before the row itself.
590+ sqlx::query!(
591+ r#"DELETE FROM course_teacher WHERE course = $1"#,
509 course.id.uuid(),592 course.id.uuid(),
510 )593 )
511 .execute(&mut *tx)594 .execute(&mut *tx)
@@ -549,6 +632,13 @@ pub async fn delete(db: &Database, course: Course) -> Result<bool, AppError> {
549 sqlx::query!(r#"DELETE FROM exam WHERE course = $1"#, course.id.uuid())632 sqlx::query!(r#"DELETE FROM exam WHERE course = $1"#, course.id.uuid())
550 .execute(&mut *tx)633 .execute(&mut *tx)
551 .await?;634 .await?;
635+ sqlx::query!(
636+ r#"DELETE FROM homework_assignment WHERE homework IN (
637+ SELECT id FROM homework WHERE course = $1)"#,
638+ course.id.uuid(),
639+ )
640+ .execute(&mut *tx)
641+ .await?;
552 sqlx::query!(642 sqlx::query!(
553 r#"DELETE FROM homework WHERE course = $1"#,643 r#"DELETE FROM homework WHERE course = $1"#,
554 course.id.uuid()644 course.id.uuid()
src/db/course_note.rsmodified+9 -0
@@ -118,6 +118,15 @@ pub async fn delete(
118 note: CourseNote,118 note: CourseNote,
119 ) -> Result<(CourseNote, Vec<CourseNoteFile>), AppError> {119 ) -> Result<(CourseNote, Vec<CourseNoteFile>), AppError> {
120 tx_with_retry(db, true, async move |conn| {120 tx_with_retry(db, true, async move |conn| {
121+ // Links before rows: the outputs' citation links are their children
122+ // (`ON DELETE NO ACTION`).
123+ sqlx::query!(
124+ "DELETE FROM rag_output_source WHERE output IN
125+ (SELECT id FROM rag_output WHERE course_note = $1)",
126+ note.id.uuid()
127+ )
128+ .execute(&mut *conn)
129+ .await?;
121 sqlx::query!("DELETE FROM rag_output WHERE course_note = $1", note.id.uuid())130 sqlx::query!("DELETE FROM rag_output WHERE course_note = $1", note.id.uuid())
122 .execute(&mut *conn)131 .execute(&mut *conn)
123 .await?;132 .await?;
src/db/dietary_profile.rsmodified+64 -32
@@ -1,11 +1,12 @@
1 //! The `dietary_profile` table: one row per student (the primary key *is*1 //! The `dietary_profile` table: one row per student (the primary key *is*
2 //! the student), created on first write and afterwards patched2 //! the student), created on first write and afterwards patched
3-//! field-by-field — both by one `INSERT … ON CONFLICT DO UPDATE`. The3+//! field-by-field — the row by one `INSERT … ON CONFLICT DO UPDATE`, the
4-//! tag/note newtypes and the pure tag intersection live in4+//! tags by child rows in `dietary_profile_tag` replaced under the same
5+//! transaction. The tag/note newtypes and the pure tag intersection live in
5 //! [`crate::domain::dietary_profile`]; the web layer reads through6 //! [`crate::domain::dietary_profile`]; the web layer reads through
6 //! [`crate::service::dietary_profile`].7 //! [`crate::service::dietary_profile`].
7 8
8-use crate::database::Database;9+use crate::database::{Database, tx_with_retry};
9 use crate::domain::dietary_profile::{DietaryNote, DietaryProfile, DietaryTags};10 use crate::domain::dietary_profile::{DietaryNote, DietaryProfile, DietaryTags};
10 use crate::domain::timestamp::Timestamp;11 use crate::domain::timestamp::Timestamp;
11 use crate::domain::user::UserId;12 use crate::domain::user::UserId;
@@ -16,7 +17,9 @@ use crate::error::AppError;
16 pub async fn read(db: &Database, student: &UserId) -> Result<Option<DietaryProfile>, AppError> {17 pub async fn read(db: &Database, student: &UserId) -> Result<Option<DietaryProfile>, AppError> {
17 let row = sqlx::query_as!(18 let row = sqlx::query_as!(
18 DietaryProfile,19 DietaryProfile,
19- "SELECT student AS \"student: UserId\", tags AS \"tags: DietaryTags\", note AS \"note: DietaryNote\", updated_by AS \"updated_by: UserId\", updated_at AS \"updated_at: Timestamp\"20+ "SELECT student AS \"student: UserId\",
21+ COALESCE((SELECT array_agg(t.tag ORDER BY t.ord) FROM dietary_profile_tag t WHERE t.student = dietary_profile.student), '{}'::text[]) AS \"tags!: DietaryTags\",
22+ note AS \"note: DietaryNote\", updated_by AS \"updated_by: UserId\", updated_at AS \"updated_at: Timestamp\"
20 FROM dietary_profile WHERE student = $1",23 FROM dietary_profile WHERE student = $1",
21 student.uuid(),24 student.uuid(),
22 )25 )
@@ -38,14 +41,15 @@ pub async fn tags_of(db: &Database, student: &UserId) -> Result<Vec<String>, App
38 /// afterwards only the named fields move, because a whole-row save would41 /// afterwards only the named fields move, because a whole-row save would
39 /// also revert a concurrent edit of the other field.42 /// also revert a concurrent edit of the other field.
40 ///43 ///
41-/// Both paths are one statement: an absent `tags` keeps the stored list44+/// The base row is one upsert — an absent `note` keeps the stored one, a
42-/// (`COALESCE`), an absent `note` keeps the stored one, a `Some(None)` note45+/// `Some(None)` clears it and a `Some(Some)` overwrites it (the same
43-/// clears it and a `Some(Some)` overwrites it — the same three-way shape,46+/// three-way shape, spelled with a "was the field on the request?" flag
44-/// spelled with a "was the field on the request?" flag plus its nullable47+/// plus its nullable value) — and an absent `tags` leaves the stored tag
45-/// value. A rival `PATCH` that created the row a moment ago turns this48+/// rows alone while a carried `tags` replaces the whole set, all under one
46-/// call's `INSERT` into the `DO UPDATE` arm: a plain field write after all,49+/// transaction. A rival `PATCH` that created the row a moment ago turns
47-/// exactly as it would have been a moment later — without the error the old50+/// this call's `INSERT` into the `DO UPDATE` arm: a plain field write
48-/// store's create-then-patch pair had to catch.51+/// after all, exactly as it would have been a moment later — without the
52+/// error the old store's create-then-patch pair had to catch.
49 pub async fn save(53 pub async fn save(
50 db: &Database,54 db: &Database,
51 student: &UserId,55 student: &UserId,
@@ -53,24 +57,52 @@ pub async fn save(
53 note: Option<Option<DietaryNote>>,57 note: Option<Option<DietaryNote>>,
54 by: &UserId,58 by: &UserId,
55 ) -> Result<DietaryProfile, AppError> {59 ) -> Result<DietaryProfile, AppError> {
56- let row = sqlx::query_as!(60+ let student_key = student.uuid();
57- DietaryProfile,61+ let by_key = by.uuid();
58- "INSERT INTO dietary_profile (student, tags, note, updated_by, updated_at)62+ let now = Timestamp::now().as_millis();
59- VALUES ($1, COALESCE($2, '{}'::text[]), $3, $4, $5)63+ tx_with_retry(db, false, async move |tx| {
60- ON CONFLICT (student) DO UPDATE SET64+ sqlx::query!(
61- tags = COALESCE($2, dietary_profile.tags),65+ "INSERT INTO dietary_profile (student, note, updated_by, updated_at)
62- note = CASE WHEN $6 THEN $3 ELSE dietary_profile.note END,66+ VALUES ($1, $2, $3, $4)
63- updated_by = $4,67+ ON CONFLICT (student) DO UPDATE SET
64- updated_at = $568+ note = CASE WHEN $5 THEN $2 ELSE dietary_profile.note END,
65- RETURNING student AS \"student: UserId\", tags AS \"tags: DietaryTags\", note AS \"note: DietaryNote\", updated_by AS \"updated_by: UserId\", updated_at AS \"updated_at: Timestamp\"",69+ updated_by = $3,
66- student.uuid(),70+ updated_at = $4",
67- tags.as_ref().map(|t| t.as_slice()),71+ student_key,
68- note.as_ref().and_then(|n| n.as_ref()).map(|n| n.as_str()),72+ note.as_ref().and_then(|n| n.as_ref()).map(|n| n.as_str()),
69- by.uuid(),73+ by_key,
70- Timestamp::now().as_millis(),74+ now,
71- note.is_some(),75+ note.is_some(),
72- )76+ )
73- .fetch_one(db)77+ .execute(&mut *tx)
74- .await?;78+ .await?;
75- Ok(row)79+ if let Some(tags) = &tags {
80+ sqlx::query!(
81+ "DELETE FROM dietary_profile_tag WHERE student = $1",
82+ student_key,
83+ )
84+ .execute(&mut *tx)
85+ .await?;
86+ sqlx::query!(
87+ "INSERT INTO dietary_profile_tag (student, tag, ord)
88+ SELECT $1, tag, ord FROM unnest($2::text[]) WITH ORDINALITY AS t(tag, ord)",
89+ student_key,
90+ tags.as_slice(),
91+ )
92+ .execute(&mut *tx)
93+ .await?;
94+ }
95+ let row = sqlx::query_as!(
96+ DietaryProfile,
97+ "SELECT student AS \"student: UserId\",
98+ COALESCE((SELECT array_agg(t.tag ORDER BY t.ord) FROM dietary_profile_tag t WHERE t.student = dietary_profile.student), '{}'::text[]) AS \"tags!: DietaryTags\",
99+ note AS \"note: DietaryNote\", updated_by AS \"updated_by: UserId\", updated_at AS \"updated_at: Timestamp\"
100+ FROM dietary_profile WHERE student = $1",
101+ student_key,
102+ )
103+ .fetch_one(&mut *tx)
104+ .await?;
105+ Ok(row)
106+ })
107+ .await
76 }108 }
src/db/homework.rsmodified+214 -74
@@ -51,7 +51,9 @@ pub async fn create(
51 // is the 400 the web layer's pre-flight check answers with. The subject51 // is the 400 the web layer's pre-flight check answers with. The subject
52 // delete is refused while this counter is non-zero, so the two writers52 // delete is refused while this counter is non-zero, so the two writers
53 // contend on the subject row itself, and a crash cannot strand a claim53 // contend on the subject row itself, and a crash cannot strand a claim
54- // that would make the subject undeletable forever.54+ // that would make the subject undeletable forever. The audience rows
55+ // ride the same transaction: a subset homework never appears
56+ // whole-course, not even for the instant of its create.
55 let homework = Homework {57 let homework = Homework {
56 id: HomeworkId::generate(),58 id: HomeworkId::generate(),
57 course: course.clone(),59 course: course.clone(),
@@ -70,47 +72,86 @@ pub async fn create(
70 .iter()72 .iter()
71 .map(UserId::uuid)73 .map(UserId::uuid)
72 .collect();74 .collect();
73- // The fresh v7 id cannot collide, so the pair-unique answer has no rival75+ // The subset the caller passed is the truth — the store holds no roster
74- // here; the mapping is kept for symmetry with the other claim sites.76+ // column to read back; the whole-course case stays `None`. Cloned out
75- let created = sqlx::query_as!(77+ // here because the closure below consumes `homework`.
76- Homework,78+ let assigned = homework.assigned.clone();
77- r#"WITH seat AS (79+ // Owned BEFORE the closure. A reference parameter captured by the
78- UPDATE subject SET homework_count = homework_count + 180+ // coroutine (`&CourseId`, `&SubjectId`) leaves that borrow in the
79- WHERE id = $181+ // statement future, and the `Send` proof at the `routes!` registration
80- RETURNING 182+ // comes back "not general enough" over the higher-ranked connection
81- )83+ // lease — every tx_with_retry site captures only owned values.
82- INSERT INTO homework (id, course, subject, title, description, due_at, assigned, created_by, created_at)84+ let subject = *subject;
83- SELECT $2, $3, $1, $4, $5, $6, $7, $8, $9 WHERE EXISTS (SELECT 1 FROM seat)85+ let course = course.clone();
84- RETURNING id AS "id: HomeworkId",86+ tx_with_retry(db, false, async move |tx| {
85- course AS "course: CourseId",87+ // And every bind is a precomputed value of this coroutine's own: a
86- subject AS "subject: SubjectId",88+ // bind expression reading a capture inside the macro keeps that
87- title AS "title: HomeworkTitle",89+ // borrow alive across the await to the same `Send` end.
88- description AS "description: HomeworkDescription",90+ let subject_uuid = subject.uuid();
89- due_at AS "due_at: Timestamp",91+ let course_uuid = course.uuid();
90- CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END92+ let homework_uuid = homework.id.uuid();
91- AS "assigned: Vec<UserId>",93+ let title = homework.title.clone();
92- created_by AS "created_by: UserId",94+ let description = homework.description.clone();
93- created_at AS "created_at: Timestamp""#,95+ let due_at_millis = homework.due_at.as_millis();
94- subject.uuid(),96+ let created_by_uuid = homework.created_by.uuid();
95- homework.id.uuid(),97+ let created_at_millis = homework.created_at.as_millis();
96- course.uuid(),98+ let assigned_values = assigned_values.clone();
97- homework.title.as_str(),99+ let created = sqlx::query_as!(
98- homework.description.as_ref().map(HomeworkDescription::as_str),100+ Homework,
99- homework.due_at.as_millis(),101+ r#"WITH seat AS (
100- &assigned_values,102+ UPDATE subject SET homework_count = homework_count + 1
101- homework.created_by.uuid(),103+ WHERE id = $1
102- homework.created_at.as_millis(),104+ RETURNING 1
103- )105+ )
104- .fetch_optional(db)106+ INSERT INTO homework (id, course, subject, title, description, due_at, created_by, created_at)
105- .await107+ SELECT $2, $3, $1, $4, $5, $6, $7, $8 WHERE EXISTS (SELECT 1 FROM seat)
106- .map_err(|err| {108+ RETURNING id AS "id: HomeworkId",
107- if crate::database::unique_violation(&err).is_some() {109+ course AS "course: CourseId",
108- AppError::Internal("failed to create homework".into())110+ subject AS "subject: SubjectId",
109- } else {111+ title AS "title: HomeworkTitle",
110- AppError::from(err)112+ description AS "description: HomeworkDescription",
113+ due_at AS "due_at: Timestamp",
114+ NULL::uuid[] AS "assigned: Vec<UserId>",
115+ created_by AS "created_by: UserId",
116+ created_at AS "created_at: Timestamp""#,
117+ subject_uuid,
118+ homework_uuid,
119+ course_uuid,
120+ title.as_str(),
121+ description.as_ref().map(HomeworkDescription::as_str),
122+ due_at_millis,
123+ created_by_uuid,
124+ created_at_millis,
125+ )
126+ .fetch_optional(&mut *tx)
127+ .await
128+ .map_err(|err| {
129+ if crate::database::unique_violation(&err).is_some() {
130+ AppError::Internal("failed to create homework".into())
131+ } else {
132+ AppError::from(err)
133+ }
134+ })?;
135+ // The audience subset, written beside the row it scopes: a refused
136+ // create (subject gone) writes no audience either, and any other
137+ // failure rolls the homework row back with its audience rows.
138+ if created.is_some() && !assigned_values.is_empty() {
139+ sqlx::query!(
140+ "INSERT INTO homework_assignment (homework, student)
141+ SELECT $2, s FROM unnest($1::uuid[]) AS t(s)",
142+ &assigned_values,
143+ homework_uuid
144+ )
145+ .execute(&mut *tx)
146+ .await?;
111 }147 }
112- })?;148+ created.ok_or_else(subject_gone)
113- created.ok_or_else(subject_gone)149+ })
150+ .await
151+ .map(move |mut created| {
152+ created.assigned = assigned;
153+ created
154+ })
114 }155 }
115 156
116 pub async fn read(db: &Database, id: &HomeworkId) -> Result<Option<Homework>, AppError> {157 pub async fn read(db: &Database, id: &HomeworkId) -> Result<Option<Homework>, AppError> {
@@ -122,8 +163,8 @@ pub async fn read(db: &Database, id: &HomeworkId) -> Result<Option<Homework>, Ap
122 title AS "title: HomeworkTitle",163 title AS "title: HomeworkTitle",
123 description AS "description: HomeworkDescription",164 description AS "description: HomeworkDescription",
124 due_at AS "due_at: Timestamp",165 due_at AS "due_at: Timestamp",
125- CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END166+ (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a
126- AS "assigned: Vec<UserId>",167+ WHERE a.homework = homework.id) AS "assigned: Vec<UserId>",
127 created_by AS "created_by: UserId",168 created_by AS "created_by: UserId",
128 created_at AS "created_at: Timestamp"169 created_at AS "created_at: Timestamp"
129 FROM homework WHERE id = $1"#,170 FROM homework WHERE id = $1"#,
@@ -144,8 +185,8 @@ pub async fn list_for_course(db: &Database, course: &CourseId) -> Result<Vec<Hom
144 title AS "title: HomeworkTitle",185 title AS "title: HomeworkTitle",
145 description AS "description: HomeworkDescription",186 description AS "description: HomeworkDescription",
146 due_at AS "due_at: Timestamp",187 due_at AS "due_at: Timestamp",
147- CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END188+ (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a
148- AS "assigned: Vec<UserId>",189+ WHERE a.homework = homework.id) AS "assigned: Vec<UserId>",
149 created_by AS "created_by: UserId",190 created_by AS "created_by: UserId",
150 created_at AS "created_at: Timestamp"191 created_at AS "created_at: Timestamp"
151 FROM homework WHERE course = $1 ORDER BY id DESC"#,192 FROM homework WHERE course = $1 ORDER BY id DESC"#,
@@ -166,8 +207,8 @@ pub async fn list_all(db: &Database) -> Result<Vec<Homework>, AppError> {
166 title AS "title: HomeworkTitle",207 title AS "title: HomeworkTitle",
167 description AS "description: HomeworkDescription",208 description AS "description: HomeworkDescription",
168 due_at AS "due_at: Timestamp",209 due_at AS "due_at: Timestamp",
169- CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END210+ (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a
170- AS "assigned: Vec<UserId>",211+ WHERE a.homework = homework.id) AS "assigned: Vec<UserId>",
171 created_by AS "created_by: UserId",212 created_by AS "created_by: UserId",
172 created_at AS "created_at: Timestamp"213 created_at AS "created_at: Timestamp"
173 FROM homework ORDER BY id DESC"#,214 FROM homework ORDER BY id DESC"#,
@@ -196,8 +237,8 @@ pub async fn list_for_courses(
196 title AS "title: HomeworkTitle",237 title AS "title: HomeworkTitle",
197 description AS "description: HomeworkDescription",238 description AS "description: HomeworkDescription",
198 due_at AS "due_at: Timestamp",239 due_at AS "due_at: Timestamp",
199- CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END240+ (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a
200- AS "assigned: Vec<UserId>",241+ WHERE a.homework = homework.id) AS "assigned: Vec<UserId>",
201 created_by AS "created_by: UserId",242 created_by AS "created_by: UserId",
202 created_at AS "created_at: Timestamp"243 created_at AS "created_at: Timestamp"
203 FROM homework WHERE course = ANY($1) ORDER BY id DESC"#,244 FROM homework WHERE course = ANY($1) ORDER BY id DESC"#,
@@ -225,12 +266,16 @@ pub async fn list_for_user_in_course(
225 title AS "title: HomeworkTitle",266 title AS "title: HomeworkTitle",
226 description AS "description: HomeworkDescription",267 description AS "description: HomeworkDescription",
227 due_at AS "due_at: Timestamp",268 due_at AS "due_at: Timestamp",
228- CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END269+ (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a
229- AS "assigned: Vec<UserId>",270+ WHERE a.homework = homework.id) AS "assigned: Vec<UserId>",
230 created_by AS "created_by: UserId",271 created_by AS "created_by: UserId",
231 created_at AS "created_at: Timestamp"272 created_at AS "created_at: Timestamp"
232 FROM homework273 FROM homework
233- WHERE course = $1 AND (cardinality(assigned) = 0 OR $2 = ANY(assigned))274+ WHERE course = $1
275+ AND (NOT EXISTS (SELECT 1 FROM homework_assignment a
276+ WHERE a.homework = homework.id)
277+ OR EXISTS (SELECT 1 FROM homework_assignment a
278+ WHERE a.homework = homework.id AND a.student = $2))
234 ORDER BY id DESC"#,279 ORDER BY id DESC"#,
235 course.uuid(),280 course.uuid(),
236 user.uuid()281 user.uuid()
@@ -248,7 +293,8 @@ pub async fn list_for_user_in_course(
248 /// and `created_at` are readonly and never appear in the write.293 /// and `created_at` are readonly and never appear in the write.
249 ///294 ///
250 /// `description` takes `Some(None)` to clear; `assigned` takes `Some(None)`295 /// `description` takes `Some(None)` to clear; `assigned` takes `Some(None)`
251-/// to widen back to the whole course (stored as `'{}'`, read back as `None`).296+/// to widen back to the whole course (stored as no `homework_assignment` rows,
297+/// read back as `None`).
252 /// The web layer has already re-checked a new `due_at` against now, a new298 /// The web layer has already re-checked a new `due_at` against now, a new
253 /// `subject` against the course, and — inside the transaction here — the299 /// `subject` against the course, and — inside the transaction here — the
254 /// narrowing against the work that would be orphaned by it.300 /// narrowing against the work that would be orphaned by it.
@@ -277,8 +323,8 @@ pub async fn update(
277 title AS "title: HomeworkTitle",323 title AS "title: HomeworkTitle",
278 description AS "description: HomeworkDescription",324 description AS "description: HomeworkDescription",
279 due_at AS "due_at: Timestamp",325 due_at AS "due_at: Timestamp",
280- CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END326+ (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a
281- AS "assigned: Vec<UserId>",327+ WHERE a.homework = homework.id) AS "assigned: Vec<UserId>",
282 created_by AS "created_by: UserId",328 created_by AS "created_by: UserId",
283 created_at AS "created_at: Timestamp"329 created_at AS "created_at: Timestamp"
284 FROM homework WHERE id = $1 FOR UPDATE"#,330 FROM homework WHERE id = $1 FOR UPDATE"#,
@@ -331,6 +377,29 @@ pub async fn update(
331 if subject.is_some() && current.subject != homework.subject {377 if subject.is_some() && current.subject != homework.subject {
332 return Err(AppError::Conflict(STALE_MOVE));378 return Err(AppError::Conflict(STALE_MOVE));
333 }379 }
380+ // The carried `assigned` replaces the junction rows wholesale —
381+ // delete-then-insert under the row lock, so the audience (or its
382+ // absence, = whole course) is exactly what the request named. An
383+ // uncarried `assigned` writes no rows, keeping the stored audience.
384+ if let Some(resolved) = assigned.as_ref() {
385+ sqlx::query!(
386+ "DELETE FROM homework_assignment WHERE homework = $1",
387+ homework.get_id().uuid()
388+ )
389+ .execute(&mut *tx)
390+ .await?;
391+ let values: Vec<uuid::Uuid> = resolved.iter().flatten().map(UserId::uuid).collect();
392+ if !values.is_empty() {
393+ sqlx::query!(
394+ "INSERT INTO homework_assignment (homework, student)
395+ SELECT $2, s FROM unnest($1::uuid[]) AS t(s)",
396+ &values,
397+ homework.get_id().uuid()
398+ )
399+ .execute(&mut *tx)
400+ .await?;
401+ }
402+ }
334 403
335 // What the PATCH carried is written; what it did not carry keeps the404 // What the PATCH carried is written; what it did not carry keeps the
336 // value just read under the lock. Under that lock this resolved405 // value just read under the lock. Under that lock this resolved
@@ -345,22 +414,10 @@ pub async fn update(
345 Some(Some(text)) => Some(text),414 Some(Some(text)) => Some(text),
346 };415 };
347 let new_due_at = due_at.unwrap_or(current.due_at);416 let new_due_at = due_at.unwrap_or(current.due_at);
348- let new_assigned = match assigned.clone() {
349- None => current.assigned.clone(),
350- // Clear = the whole course, stored as `'{}'`.
351- Some(None) => None,
352- Some(Some(subset)) => Some(subset),
353- };
354- let assigned_values: Vec<uuid::Uuid> = new_assigned
355- .as_deref()
356- .unwrap_or_default()
357- .iter()
358- .map(UserId::uuid)
359- .collect();
360 sqlx::query_as!(417 sqlx::query_as!(
361 Homework,418 Homework,
362 r#"UPDATE homework SET subject = $2, title = $3, description = $4,419 r#"UPDATE homework SET subject = $2, title = $3, description = $4,
363- due_at = $5, assigned = $6420+ due_at = $5
364 WHERE id = $1421 WHERE id = $1
365 RETURNING id AS "id: HomeworkId",422 RETURNING id AS "id: HomeworkId",
366 course AS "course: CourseId",423 course AS "course: CourseId",
@@ -368,8 +425,8 @@ pub async fn update(
368 title AS "title: HomeworkTitle",425 title AS "title: HomeworkTitle",
369 description AS "description: HomeworkDescription",426 description AS "description: HomeworkDescription",
370 due_at AS "due_at: Timestamp",427 due_at AS "due_at: Timestamp",
371- CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END428+ (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a
372- AS "assigned: Vec<UserId>",429+ WHERE a.homework = homework.id) AS "assigned: Vec<UserId>",
373 created_by AS "created_by: UserId",430 created_by AS "created_by: UserId",
374 created_at AS "created_at: Timestamp""#,431 created_at AS "created_at: Timestamp""#,
375 homework.get_id().uuid(),432 homework.get_id().uuid(),
@@ -377,7 +434,6 @@ pub async fn update(
377 new_title.as_str(),434 new_title.as_str(),
378 new_description.as_ref().map(HomeworkDescription::as_str),435 new_description.as_ref().map(HomeworkDescription::as_str),
379 new_due_at.as_millis(),436 new_due_at.as_millis(),
380- &assigned_values,
381 )437 )
382 .fetch_optional(&mut *tx)438 .fetch_optional(&mut *tx)
383 .await?439 .await?
@@ -445,7 +501,8 @@ async fn ensure_no_orphans(
445 /// vanished homework. The cascade runs children-first (every FK here is501 /// vanished homework. The cascade runs children-first (every FK here is
446 /// `ON DELETE NO ACTION`): files, then submissions — whose `graded_by_result`502 /// `ON DELETE NO ACTION`): files, then submissions — whose `graded_by_result`
447 /// stamp points at a result row, so they must be gone before it — then the503 /// stamp points at a result row, so they must be gone before it — then the
448-/// results, then the homework. The submission file *blobs* are the web504+/// results, the audience rows, then the homework. The submission file *blobs*
505+/// are the web
449 /// layer's to unlink: their names are returned (collected inside the506 /// layer's to unlink: their names are returned (collected inside the
450 /// transaction, before the wipes — a file row inserted after an507 /// transaction, before the wipes — a file row inserted after an
451 /// out-of-transaction collection would be deleted here while its key was508 /// out-of-transaction collection would be deleted here while its key was
@@ -485,6 +542,12 @@ pub async fn delete(
485 )542 )
486 .execute(&mut *tx)543 .execute(&mut *tx)
487 .await?;544 .await?;
545+ sqlx::query!(
546+ "DELETE FROM homework_assignment WHERE homework = $1",
547+ homework.get_id().uuid()
548+ )
549+ .execute(&mut *tx)
550+ .await?;
488 let deleted = sqlx::query_as!(551 let deleted = sqlx::query_as!(
489 Homework,552 Homework,
490 r#"DELETE FROM homework WHERE id = $1553 r#"DELETE FROM homework WHERE id = $1
@@ -494,8 +557,8 @@ pub async fn delete(
494 title AS "title: HomeworkTitle",557 title AS "title: HomeworkTitle",
495 description AS "description: HomeworkDescription",558 description AS "description: HomeworkDescription",
496 due_at AS "due_at: Timestamp",559 due_at AS "due_at: Timestamp",
497- CASE WHEN cardinality(assigned) = 0 THEN NULL ELSE assigned END560+ (SELECT array_agg(a.student ORDER BY a.student) FROM homework_assignment a
498- AS "assigned: Vec<UserId>",561+ WHERE a.homework = homework.id) AS "assigned: Vec<UserId>",
499 created_by AS "created_by: UserId",562 created_by AS "created_by: UserId",
500 created_at AS "created_at: Timestamp""#,563 created_at AS "created_at: Timestamp""#,
501 homework.get_id().uuid()564 homework.get_id().uuid()
@@ -822,4 +885,81 @@ mod tests {
822 );885 );
823 assert_eq!(count_on(to.get_id(), &db).await, 1, "claimed once, still");886 assert_eq!(count_on(to.get_id(), &db).await, 1, "claimed once, still");
824 }887 }
888+
889+ /// The audience contract in SQL: no `homework_assignment` rows = the whole
890+ /// course (every student's list, later enrollees included); rows name the
891+ /// subset, and `list_for_user_in_course` answers it to the named student
892+ /// alone. The read-back roster is the junction itself.
893+ #[tokio::test]
894+ async fn a_subset_reaches_only_the_named_and_widening_clears_the_rows() {
895+ let (db, _leases) = crate::database::init_test_db().await;
896+ let subject = a_subject("tarih", &db).await;
897+ let teacher = UserId::generate();
898+ sqlx::query(
899+ "INSERT INTO app_user (id, username, created_at, role) \
900+ VALUES ($1, $2, 0, 'teacher')",
901+ )
902+ .bind(teacher.uuid())
903+ .bind(format!("homework-audience-{}", &teacher.key()[30..]))
904+ .execute(&db)
905+ .await
906+ .unwrap();
907+ let ali = UserId::generate();
908+ sqlx::query(
909+ "INSERT INTO app_user (id, username, created_at, role) \
910+ VALUES ($1, $2, 0, 'student')",
911+ )
912+ .bind(ali.uuid())
913+ .bind(format!("homework-audience-{}", &ali.key()[30..]))
914+ .execute(&db)
915+ .await
916+ .unwrap();
917+ let veli = UserId::generate();
918+ sqlx::query(
919+ "INSERT INTO app_user (id, username, created_at, role) \
920+ VALUES ($1, $2, 0, 'student')",
921+ )
922+ .bind(veli.uuid())
923+ .bind(format!("homework-audience-{}", &veli.key()[30..]))
924+ .execute(&db)
925+ .await
926+ .unwrap();
927+ let course = crate::db::course::a_test_course(&db).await;
928+ let homework = create(
929+ &db,
930+ &course,
931+ subject.get_id(),
932+ HomeworkTitle::try_new("essay").unwrap(),
933+ None,
934+ Timestamp::from_millis(1),
935+ Some(vec![ali]),
936+ &teacher,
937+ )
938+ .await
939+ .unwrap();
940+ assert_eq!(homework.get_assigned(), Some(&[ali][..]));
941+ assert_eq!(
942+ list_for_user_in_course(&db, &course, &ali).await.unwrap().len(),
943+ 1,
944+ "the named student sees the subset"
945+ );
946+ assert!(
947+ list_for_user_in_course(&db, &course, &veli)
948+ .await
949+ .unwrap()
950+ .is_empty(),
951+ "an unnamed student sees nothing"
952+ );
953+ // Widening back to the whole course (`Some(None)`) empties the
954+ // junction: everyone — including the never-named student — is covered.
955+ let widened = update(&db, homework, None, None, None, None, Some(None))
956+ .await
957+ .unwrap();
958+ assert_eq!(widened.get_assigned(), None);
959+ assert_eq!(
960+ list_for_user_in_course(&db, &course, &veli).await.unwrap().len(),
961+ 1,
962+ "whole-course reaches the never-named student"
963+ );
964+ }
825 }965 }
src/db/homework_submission.rsmodified+5 -1
@@ -79,7 +79,11 @@ pub async fn upsert(
79 // student the homework no longer names must read as gone — the79 // student the homework no longer names must read as gone — the
80 // same 404 their own lookup answers.80 // same 404 their own lookup answers.
81 r#"SELECT due_at AS "due_at: Timestamp" FROM homework81 r#"SELECT due_at AS "due_at: Timestamp" FROM homework
82- WHERE id = $1 AND (cardinality(assigned) = 0 OR $2 = ANY(assigned))82+ WHERE id = $1
83+ AND (NOT EXISTS (SELECT 1 FROM homework_assignment a
84+ WHERE a.homework = homework.id)
85+ OR EXISTS (SELECT 1 FROM homework_assignment a
86+ WHERE a.homework = homework.id AND a.student = $2))
83 FOR UPDATE"#,87 FOR UPDATE"#,
84 homework_id.uuid(),88 homework_id.uuid(),
85 user.uuid()89 user.uuid()
src/db/menu.rsmodified+9 -3
@@ -240,12 +240,18 @@ pub async fn delete(db: &Database, menu: Menu) -> Result<Menu, AppError> {
240 if guard.is_none() {240 if guard.is_none() {
241 return Ok(None);241 return Ok(None);
242 }242 }
243- // The children go first: both `menu_dish.menu` and243+ // The children go first: `menu_dish_tag.dish`, `menu_dish.menu` and
244- // `meal_attendance.menu` are `ON DELETE NO ACTION`, so the parent244+ // `meal_attendance.menu` are all `ON DELETE NO ACTION`, so the
245- // row cannot leave while they stand.245+ // parent rows cannot leave while they stand.
246 sqlx::query!("DELETE FROM meal_attendance WHERE menu = $1", key)246 sqlx::query!("DELETE FROM meal_attendance WHERE menu = $1", key)
247 .execute(&mut *tx)247 .execute(&mut *tx)
248 .await?;248 .await?;
249+ sqlx::query!(
250+ "DELETE FROM menu_dish_tag WHERE dish IN (SELECT id FROM menu_dish WHERE menu = $1)",
251+ key,
252+ )
253+ .execute(&mut *tx)
254+ .await?;
249 sqlx::query!("DELETE FROM menu_dish WHERE menu = $1", key)255 sqlx::query!("DELETE FROM menu_dish WHERE menu = $1", key)
250 .execute(&mut *tx)256 .execute(&mut *tx)
251 .await?;257 .await?;
src/db/menu_dish.rsmodified+82 -26
@@ -50,30 +50,47 @@ pub async fn create(
50 )50 )
51 .execute(&mut *tx)51 .execute(&mut *tx)
52 .await?;52 .await?;
53- let placed = sqlx::query_as!(53+ let placed = sqlx::query!(
54- MenuDish,54+ "INSERT INTO menu_dish (id, menu, name, description, price_minor, created_at)
55- "INSERT INTO menu_dish (id, menu, name, description, price_minor, tags, created_at)55+ SELECT $1, $2, $3, $4, $5, $6
56- SELECT $1, $2, $3, $4, $5, $6, $756+ WHERE (SELECT count(*) FROM menu_dish WHERE menu = $2) < $7",
57- WHERE (SELECT count(*) FROM menu_dish WHERE menu = $2) < $8
58- RETURNING id AS \"id: MenuDishId\", menu AS \"menu: MenuId\", name AS \"name: DishName\", description AS \"description: DishDescription\", price_minor AS \"price_minor: DishPrice\", tags AS \"tags: DishTags\", created_at AS \"created_at: Timestamp\"",
59 id.uuid(),57 id.uuid(),
60 menu_key,58 menu_key,
61 name.as_str(),59 name.as_str(),
62 description.as_ref().map(|d| d.as_str()),60 description.as_ref().map(|d| d.as_str()),
63 price_minor.as_minor(),61 price_minor.as_minor(),
64- tags.as_slice(),
65 created_at.as_millis(),62 created_at.as_millis(),
66 cap,63 cap,
67 )64 )
68- .fetch_optional(&mut *tx)65+ .execute(&mut *tx)
69 .await?;66 .await?;
70- match placed {67+ if placed.rows_affected() == 0 {
71- Some(dish) => Ok(dish),
72 // The menu exists (locked above), so an empty result is the cap.68 // The menu exists (locked above), so an empty result is the cap.
73- None => Err(AppError::Conflict(69+ return Err(AppError::Conflict(
74 "the menu already carries the maximum number of dishes",70 "the menu already carries the maximum number of dishes",
75- )),71+ ));
76 }72 }
73+ // The tags are child rows: one per tag, `ord` carrying the order
74+ // the caller gave the list in (already deduplicated by DishTags).
75+ sqlx::query!(
76+ "INSERT INTO menu_dish_tag (dish, tag, ord)
77+ SELECT $1, tag, ord FROM unnest($2::text[]) WITH ORDINALITY AS t(tag, ord)",
78+ id.uuid(),
79+ tags.as_slice(),
80+ )
81+ .execute(&mut *tx)
82+ .await?;
83+ let row = sqlx::query_as!(
84+ MenuDish,
85+ "SELECT id AS \"id: MenuDishId\", menu AS \"menu: MenuId\", name AS \"name: DishName\", description AS \"description: DishDescription\", price_minor AS \"price_minor: DishPrice\",
86+ COALESCE((SELECT array_agg(t.tag ORDER BY t.ord) FROM menu_dish_tag t WHERE t.dish = menu_dish.id), '{}'::text[]) AS \"tags!: DishTags\",
87+ created_at AS \"created_at: Timestamp\"
88+ FROM menu_dish WHERE id = $1",
89+ id.uuid(),
90+ )
91+ .fetch_one(&mut *tx)
92+ .await?;
93+ Ok(row)
77 })94 })
78 .await95 .await
79 }96 }
@@ -81,7 +98,9 @@ pub async fn create(
81 pub async fn read(db: &Database, id: &MenuDishId) -> Result<Option<MenuDish>, AppError> {98 pub async fn read(db: &Database, id: &MenuDishId) -> Result<Option<MenuDish>, AppError> {
82 let row = sqlx::query_as!(99 let row = sqlx::query_as!(
83 MenuDish,100 MenuDish,
84- "SELECT id AS \"id: MenuDishId\", menu AS \"menu: MenuId\", name AS \"name: DishName\", description AS \"description: DishDescription\", price_minor AS \"price_minor: DishPrice\", tags AS \"tags: DishTags\", created_at AS \"created_at: Timestamp\"101+ "SELECT id AS \"id: MenuDishId\", menu AS \"menu: MenuId\", name AS \"name: DishName\", description AS \"description: DishDescription\", price_minor AS \"price_minor: DishPrice\",
102+ COALESCE((SELECT array_agg(t.tag ORDER BY t.ord) FROM menu_dish_tag t WHERE t.dish = menu_dish.id), '{}'::text[]) AS \"tags!: DishTags\",
103+ created_at AS \"created_at: Timestamp\"
85 FROM menu_dish WHERE id = $1",104 FROM menu_dish WHERE id = $1",
86 id.uuid(),105 id.uuid(),
87 )106 )
@@ -104,7 +123,9 @@ pub async fn list_for_menus(db: &Database, menus: &[MenuId]) -> Result<Vec<MenuD
104 let keys: Vec<String> = menus.iter().map(|m| m.key().to_string()).collect();123 let keys: Vec<String> = menus.iter().map(|m| m.key().to_string()).collect();
105 let rows = sqlx::query_as!(124 let rows = sqlx::query_as!(
106 MenuDish,125 MenuDish,
107- "SELECT id AS \"id: MenuDishId\", menu AS \"menu: MenuId\", name AS \"name: DishName\", description AS \"description: DishDescription\", price_minor AS \"price_minor: DishPrice\", tags AS \"tags: DishTags\", created_at AS \"created_at: Timestamp\"126+ "SELECT id AS \"id: MenuDishId\", menu AS \"menu: MenuId\", name AS \"name: DishName\", description AS \"description: DishDescription\", price_minor AS \"price_minor: DishPrice\",
127+ COALESCE((SELECT array_agg(t.tag ORDER BY t.ord) FROM menu_dish_tag t WHERE t.dish = menu_dish.id), '{}'::text[]) AS \"tags!: DishTags\",
128+ created_at AS \"created_at: Timestamp\"
108 FROM menu_dish WHERE menu = ANY($1) ORDER BY id ASC",129 FROM menu_dish WHERE menu = ANY($1) ORDER BY id ASC",
109 &keys,130 &keys,
110 )131 )
@@ -144,25 +165,50 @@ pub async fn update(
144 if bumped.is_none() {165 if bumped.is_none() {
145 return Err(AppError::NotFound);166 return Err(AppError::NotFound);
146 }167 }
147- let row = sqlx::query_as!(168+ let updated = sqlx::query!(
148- MenuDish,
149 "UPDATE menu_dish SET169 "UPDATE menu_dish SET
150 name = COALESCE($2, name),170 name = COALESCE($2, name),
151 description = CASE WHEN $3 THEN $4 ELSE description END,171 description = CASE WHEN $3 THEN $4 ELSE description END,
152- price_minor = COALESCE($5, price_minor),172+ price_minor = COALESCE($5, price_minor)
153- tags = COALESCE($6, tags)173+ WHERE id = $1",
154- WHERE id = $1
155- RETURNING id AS \"id: MenuDishId\", menu AS \"menu: MenuId\", name AS \"name: DishName\", description AS \"description: DishDescription\", price_minor AS \"price_minor: DishPrice\", tags AS \"tags: DishTags\", created_at AS \"created_at: Timestamp\"",
156 dish_key,174 dish_key,
157 name.as_ref().map(|n| n.as_str()),175 name.as_ref().map(|n| n.as_str()),
158 description.is_some(),176 description.is_some(),
159 description.as_ref().and_then(|d| d.as_ref()).map(|d| d.as_str()),177 description.as_ref().and_then(|d| d.as_ref()).map(|d| d.as_str()),
160 price_minor.map(DishPrice::as_minor),178 price_minor.map(DishPrice::as_minor),
161- tags.as_ref().map(|t| t.as_slice()),
162 )179 )
163- .fetch_optional(&mut *tx)180+ .execute(&mut *tx)
181+ .await?;
182+ if updated.rows_affected() == 0 {
183+ return Err(AppError::NotFound);
184+ }
185+ // The tags are child rows now: an absent field keeps the stored
186+ // ones, a carried field replaces the whole set (an empty list
187+ // clears it) — under the same transaction as the bump above.
188+ if let Some(tags) = &tags {
189+ sqlx::query!("DELETE FROM menu_dish_tag WHERE dish = $1", dish_key)
190+ .execute(&mut *tx)
191+ .await?;
192+ sqlx::query!(
193+ "INSERT INTO menu_dish_tag (dish, tag, ord)
194+ SELECT $1, tag, ord FROM unnest($2::text[]) WITH ORDINALITY AS t(tag, ord)",
195+ dish_key,
196+ tags.as_slice(),
197+ )
198+ .execute(&mut *tx)
199+ .await?;
200+ }
201+ let row = sqlx::query_as!(
202+ MenuDish,
203+ "SELECT id AS \"id: MenuDishId\", menu AS \"menu: MenuId\", name AS \"name: DishName\", description AS \"description: DishDescription\", price_minor AS \"price_minor: DishPrice\",
204+ COALESCE((SELECT array_agg(t.tag ORDER BY t.ord) FROM menu_dish_tag t WHERE t.dish = menu_dish.id), '{}'::text[]) AS \"tags!: DishTags\",
205+ created_at AS \"created_at: Timestamp\"
206+ FROM menu_dish WHERE id = $1",
207+ dish_key,
208+ )
209+ .fetch_one(&mut *tx)
164 .await?;210 .await?;
165- row.ok_or(AppError::NotFound)211+ Ok(row)
166 })212 })
167 .await213 .await
168 }214 }
@@ -183,13 +229,23 @@ pub async fn delete(db: &Database, dish: MenuDish) -> Result<MenuDish, AppError>
183 }229 }
184 let row = sqlx::query_as!(230 let row = sqlx::query_as!(
185 MenuDish,231 MenuDish,
186- "DELETE FROM menu_dish WHERE id = $1232+ "SELECT id AS \"id: MenuDishId\", menu AS \"menu: MenuId\", name AS \"name: DishName\", description AS \"description: DishDescription\", price_minor AS \"price_minor: DishPrice\",
187- RETURNING id AS \"id: MenuDishId\", menu AS \"menu: MenuId\", name AS \"name: DishName\", description AS \"description: DishDescription\", price_minor AS \"price_minor: DishPrice\", tags AS \"tags: DishTags\", created_at AS \"created_at: Timestamp\"",233+ COALESCE((SELECT array_agg(t.tag ORDER BY t.ord) FROM menu_dish_tag t WHERE t.dish = menu_dish.id), '{}'::text[]) AS \"tags!: DishTags\",
234+ created_at AS \"created_at: Timestamp\"
235+ FROM menu_dish WHERE id = $1",
188 dish_key,236 dish_key,
189 )237 )
190 .fetch_optional(&mut *tx)238 .fetch_optional(&mut *tx)
191 .await?;239 .await?;
192- row.ok_or(AppError::NotFound)240+ let dish = row.ok_or(AppError::NotFound)?;
241+ // The tag rows go first: `menu_dish_tag.dish` is NO ACTION too.
242+ sqlx::query!("DELETE FROM menu_dish_tag WHERE dish = $1", dish_key)
243+ .execute(&mut *tx)
244+ .await?;
245+ sqlx::query!("DELETE FROM menu_dish WHERE id = $1", dish_key)
246+ .execute(&mut *tx)
247+ .await?;
248+ Ok(dish)
193 })249 })
194 .await250 .await
195 }251 }
src/db/note.rsmodified+9 -0
@@ -108,6 +108,15 @@ pub async fn update(
108 /// separate `delete_for_note` call stays, as a harmless idempotent repeat.108 /// separate `delete_for_note` call stays, as a harmless idempotent repeat.
109 pub async fn delete(db: &Database, note: Note) -> Result<(Note, Vec<NoteFile>), AppError> {109 pub async fn delete(db: &Database, note: Note) -> Result<(Note, Vec<NoteFile>), AppError> {
110 tx_with_retry(db, true, async move |conn| {110 tx_with_retry(db, true, async move |conn| {
111+ // Links before rows: the outputs' citation links are their children
112+ // (`ON DELETE NO ACTION`).
113+ sqlx::query!(
114+ "DELETE FROM rag_output_source WHERE output IN
115+ (SELECT id FROM rag_output WHERE course_note = $1)",
116+ note.id.uuid()
117+ )
118+ .execute(&mut *conn)
119+ .await?;
111 sqlx::query!("DELETE FROM rag_output WHERE course_note = $1", note.id.uuid())120 sqlx::query!("DELETE FROM rag_output WHERE course_note = $1", note.id.uuid())
112 .execute(&mut *conn)121 .execute(&mut *conn)
113 .await?;122 .await?;
src/db/person.rsmodified+13 -8
@@ -11,7 +11,7 @@ use crate::domain::session::{SessionId, SessionToken};
11 use crate::domain::timestamp::Timestamp;11 use crate::domain::timestamp::Timestamp;
12 use crate::domain::user::{PasswordHash, Username};12 use crate::domain::user::{PasswordHash, Username};
13 use crate::error::AppError;13 use crate::error::AppError;
14-use crate::tenant::{SchoolStatus, Slug};14+use crate::tenant::{SchoolId, SchoolStatus, Slug};
15 15
16 /// The raw account insert behind [`crate::service::person::create_or_load`].16 /// The raw account insert behind [`crate::service::person::create_or_load`].
17 /// The unique index on `username` is the whole availability check; the loser17 /// The unique index on `username` is the whole availability check; the loser
@@ -75,7 +75,7 @@ pub async fn memberships(db: &Database, person: &PersonId) -> Result<Vec<Members
75 s.name,75 s.name,
76 s.status AS "status: SchoolStatus"76 s.status AS "status: SchoolStatus"
77 FROM person_school ps77 FROM person_school ps
78- JOIN school s ON s.slug = ps.school78+ JOIN school s ON s.id = ps.school
79 WHERE ps.person = $179 WHERE ps.person = $1
80 ORDER BY s.slug"#,80 ORDER BY s.slug"#,
81 person.uuid()81 person.uuid()
@@ -99,8 +99,8 @@ pub async fn membership_of(
99 s.name,99 s.name,
100 s.status AS "status: SchoolStatus"100 s.status AS "status: SchoolStatus"
101 FROM person_school ps101 FROM person_school ps
102- JOIN school s ON s.slug = ps.school102+ JOIN school s ON s.id = ps.school
103- WHERE ps.person = $1 AND ps.school = $2"#,103+ WHERE ps.person = $1 AND s.slug = $2"#,
104 person.uuid(),104 person.uuid(),
105 slug.as_str()105 slug.as_str()
106 )106 )
@@ -110,10 +110,15 @@ pub async fn membership_of(
110 }110 }
111 111
112 /// Attach a person to a school. Idempotent by the primary key: a racing or112 /// Attach a person to a school. Idempotent by the primary key: a racing or
113-/// repeated join is a no-op, not an error.113+/// repeated join is a no-op, not an error. The membership carries the
114+/// school's uuid, resolved from the slug in the same statement — so a school
115+/// deleted mid-flight joins nothing instead of erroring, which is the honest
116+/// outcome (there is nothing left to join).
114 pub async fn add_membership(db: &Database, person: &PersonId, slug: &Slug) -> Result<(), AppError> {117 pub async fn add_membership(db: &Database, person: &PersonId, slug: &Slug) -> Result<(), AppError> {
115 sqlx::query!(118 sqlx::query!(
116- "INSERT INTO person_school (person, school, created_at) VALUES ($1, $2, $3) ON CONFLICT DO NOTHING",119+ "INSERT INTO person_school (person, school, created_at)
120+ SELECT $1, s.id, $3 FROM school s WHERE s.slug = $2
121+ ON CONFLICT DO NOTHING",
117 person.uuid(),122 person.uuid(),
118 slug.as_str(),123 slug.as_str(),
119 Timestamp::now().as_millis()124 Timestamp::now().as_millis()
@@ -127,8 +132,8 @@ pub async fn add_membership(db: &Database, person: &PersonId, slug: &Slug) -> Re
127 /// first control-plane half, so `ON DELETE NO ACTION` never refuses the132 /// first control-plane half, so `ON DELETE NO ACTION` never refuses the
128 /// registry delete. Persons themselves survive: a person is a global133 /// registry delete. Persons themselves survive: a person is a global
129 /// account, not the school's.134 /// account, not the school's.
130-pub async fn delete_memberships_by_school(db: &Database, slug: &Slug) -> Result<(), AppError> {135+pub async fn delete_memberships_by_school(db: &Database, school: &SchoolId) -> Result<(), AppError> {
131- sqlx::query!("DELETE FROM person_school WHERE school = $1", slug.as_str())136+ sqlx::query!("DELETE FROM person_school WHERE school = $1", school.uuid())
132 .execute(db)137 .execute(db)
133 .await?;138 .await?;
134 Ok(())139 Ok(())
src/db/rag_output.rsmodified+227 -68
@@ -4,12 +4,14 @@
4 //! the answer), which is what keeps the api-read bridge GET-only. Derived,4 //! the answer), which is what keeps the api-read bridge GET-only. Derived,
5 //! disposable data: the row is dropped and regenerated whenever its input5 //! disposable data: the row is dropped and regenerated whenever its input
6 //! changes, so the cascades below — [`delete_for_note`] when the note goes,6 //! changes, so the cascades below — [`delete_for_note`] when the note goes,
7-//! [`delete_with_source`] when one of the attachments it was built from goes7+//! [`delete_with_source`] dropping the citation links a file delete strands
8-//! — keep a stale output from outliving its input, even in a deployment with8+//! — keep the stored shape from outliving its input, even in a deployment
9-//! no AI service connected. The row shape lives in9+//! with no AI service connected. The row shape lives in
10 //! [`crate::domain::rag_output`].10 //! [`crate::domain::rag_output`].
11 11
12-use crate::database::Database;12+use std::collections::HashMap;
13+
14+use crate::database::{Database, tx_with_retry};
13 use crate::db::page::PagedList;15 use crate::db::page::PagedList;
14 use crate::domain::course::CourseId;16 use crate::domain::course::CourseId;
15 use crate::domain::course_note::CourseNoteId;17 use crate::domain::course_note::CourseNoteId;
@@ -19,53 +21,122 @@ use crate::domain::timestamp::Timestamp;
19 use crate::error::AppError;21 use crate::error::AppError;
20 use serde_json::Value;22 use serde_json::Value;
21 use sqlx::types::Json;23 use sqlx::types::Json;
24+use uuid::Uuid;
25+
26+/// The plain `rag_output` columns. A citation list is not a column on the
27+/// row — the links live in `rag_output_source`, and the `query!` macros
28+/// cannot join an aggregate into a row — so every read decodes this shape
29+/// and one batch junction statement supplies the links that
30+/// [`RagOutputRow::into_rag_output`](RagOutputRow::into_rag_output) attaches.
31+#[derive(Debug, sqlx::FromRow)]
32+struct RagOutputRow {
33+ id: RagOutputId,
34+ course_note: CourseNoteId,
35+ course: CourseId,
36+ payload: Json<Value>,
37+ generated_at: Timestamp,
38+}
39+
40+impl RagOutputRow {
41+ fn into_rag_output(self, sources: Vec<CourseNoteFileId>) -> RagOutput {
42+ RagOutput {
43+ id: self.id,
44+ course_note: self.course_note,
45+ course: self.course,
46+ sources,
47+ payload: self.payload,
48+ generated_at: self.generated_at,
49+ }
50+ }
51+}
52+
53+/// The citation links of many outputs in one statement, grouped by output
54+/// uuid (the domain id newtype is not `Hash`), every list in `source` order —
55+/// the one order all reads rebuild, so a create's answer and any later read
56+/// hand back equal `Vec`s.
57+async fn sources_for_many(
58+ db: &Database,
59+ outputs: &[RagOutputId],
60+) -> Result<HashMap<Uuid, Vec<CourseNoteFileId>>, AppError> {
61+ let keys: Vec<Uuid> = outputs.iter().map(|output| output.uuid()).collect();
62+ let links = sqlx::query!(
63+ r#"SELECT output, source AS "source: CourseNoteFileId"
64+ FROM rag_output_source WHERE output = ANY($1) ORDER BY source"#,
65+ &keys
66+ )
67+ .fetch_all(db)
68+ .await?;
69+ let mut grouped: HashMap<Uuid, Vec<CourseNoteFileId>> = HashMap::new();
70+ for link in links {
71+ grouped.entry(link.output).or_default().push(link.source);
72+ }
73+ Ok(grouped)
74+}
75+
76+/// The citation links of one output, in `source` order.
77+async fn sources_for(
78+ db: &Database,
79+ output: &RagOutputId,
80+) -> Result<Vec<CourseNoteFileId>, AppError> {
81+ let mut grouped = sources_for_many(db, std::slice::from_ref(output)).await?;
82+ Ok(grouped.remove(&output.uuid()).unwrap_or_default())
83+}
22 84
23 pub async fn create(85 pub async fn create(
24 db: &Database,86 db: &Database,
25 note: &CourseNoteId,87 note: &CourseNoteId,
26 course: &CourseId,88 course: &CourseId,
27- sources: Vec<CourseNoteFileId>,89+ mut sources: Vec<CourseNoteFileId>,
28 payload: Value,90 payload: Value,
29 ) -> Result<RagOutput, AppError> {91 ) -> Result<RagOutput, AppError> {
30- let row = RagOutput {92+ // Link rows carry no order of their own; the source id is the order.
31- id: RagOutputId::generate(),93+ // Sorting here makes `create`'s answer equal to any later read's.
32- course_note: note.clone(),94+ sources.sort_by_key(|file| file.uuid());
33- course: course.clone(),95+ let keys: Vec<Uuid> = sources.iter().map(|file| file.uuid()).collect();
34- sources,96+ let id = RagOutputId::generate();
35- payload: sqlx::types::Json(payload),97+ let generated_at = Timestamp::now();
36- generated_at: Timestamp::now(),98+ // Owned binds: capturing `&CourseNoteId` / `&CourseId` across the
37- };99+ // `tx_with_retry` await poisons Send at every caller (ai/rag, course_notes).
38- // whole-row-save-ok: insert of a fresh UUID row built in place — there is no prior row to clobber100+ let id_u = id.uuid();
39- let created = sqlx::query_as!(101+ let note_u = note.uuid();
40- RagOutput,102+ let course_u = course.uuid();
41- r#"INSERT INTO rag_output (id, course_note, course, sources, payload, generated_at)103+ let at = generated_at.as_millis();
42- VALUES ($1, $2, $3, $4, $5, $6)104+ let row = tx_with_retry(db, false, async move |tx| {
43- RETURNING id AS "id: RagOutputId", course_note AS "course_note: CourseNoteId",105+ let created = sqlx::query_as!(
44- course AS "course: CourseId",106+ RagOutputRow,
45- sources AS "sources: Vec<CourseNoteFileId>",107+ r#"INSERT INTO rag_output (id, course_note, course, payload, generated_at)
46- payload AS "payload: Json<Value>",108+ VALUES ($1, $2, $3, $4, $5)
47- generated_at AS "generated_at: Timestamp""#,109+ RETURNING id AS "id: RagOutputId", course_note AS "course_note: CourseNoteId",
48- row.id.uuid(),110+ course AS "course: CourseId",
49- row.course_note.uuid(),111+ payload AS "payload: Json<Value>",
50- row.course.uuid(),112+ generated_at AS "generated_at: Timestamp""#,
51- &row.sources113+ id_u,
52- .iter()114+ note_u,
53- .map(CourseNoteFileId::uuid)115+ course_u,
54- .collect::<Vec<uuid::Uuid>>(),116+ &payload,
55- row.payload.0,117+ at
56- row.generated_at.as_millis()118+ )
57- )119+ .fetch_one(&mut *tx)
58- .fetch_one(db)120+ .await?;
121+ sqlx::query!(
122+ "INSERT INTO rag_output_source (output, source)
123+ SELECT $1, s FROM unnest($2::uuid[]) AS t(s)",
124+ created.id.uuid(),
125+ &keys
126+ )
127+ .execute(&mut *tx)
128+ .await?;
129+ Ok(created)
130+ })
59 .await?;131 .await?;
60- Ok(created)132+ Ok(row.into_rag_output(sources))
61 }133 }
62 134
63 pub async fn read(db: &Database, id: &RagOutputId) -> Result<Option<RagOutput>, AppError> {135 pub async fn read(db: &Database, id: &RagOutputId) -> Result<Option<RagOutput>, AppError> {
64 let row = sqlx::query_as!(136 let row = sqlx::query_as!(
65- RagOutput,137+ RagOutputRow,
66 r#"SELECT id AS "id: RagOutputId", course_note AS "course_note: CourseNoteId",138 r#"SELECT id AS "id: RagOutputId", course_note AS "course_note: CourseNoteId",
67 course AS "course: CourseId",139 course AS "course: CourseId",
68- sources AS "sources: Vec<CourseNoteFileId>",
69 payload AS "payload: Json<Value>",140 payload AS "payload: Json<Value>",
70 generated_at AS "generated_at: Timestamp"141 generated_at AS "generated_at: Timestamp"
71 FROM rag_output WHERE id = $1"#,142 FROM rag_output WHERE id = $1"#,
@@ -73,7 +144,13 @@ pub async fn read(db: &Database, id: &RagOutputId) -> Result<Option<RagOutput>,
73 )144 )
74 .fetch_optional(db)145 .fetch_optional(db)
75 .await?;146 .await?;
76- Ok(row)147+ match row {
148+ Some(row) => {
149+ let sources = sources_for(db, &row.id).await?;
150+ Ok(Some(row.into_rag_output(sources)))
151+ }
152+ None => Ok(None),
153+ }
77 }154 }
78 155
79 /// A note's outputs, newest first.156 /// A note's outputs, newest first.
@@ -83,31 +160,67 @@ pub async fn list_for(
83 limit: Option<i64>,160 limit: Option<i64>,
84 offset: i64,161 offset: i64,
85 ) -> Result<(Vec<RagOutput>, i64), AppError> {162 ) -> Result<(Vec<RagOutput>, i64), AppError> {
86- PagedList::new("rag_output WHERE course_note = $1", "ORDER BY id DESC")163+ let (rows, total) = PagedList::new("rag_output WHERE course_note = $1", "ORDER BY id DESC")
87 .bind(note.uuid())164 .bind(note.uuid())
88- .run::<RagOutput>(limit, offset, db)165+ .run::<RagOutputRow>(limit, offset, db)
89- .await166+ .await?;
167+ let ids: Vec<RagOutputId> = rows.iter().map(|row| row.id).collect();
168+ let grouped = sources_for_many(db, &ids).await?;
169+ let items = rows
170+ .into_iter()
171+ .map(|row| {
172+ let sources = grouped.get(&row.id.uuid()).cloned().unwrap_or_default();
173+ row.into_rag_output(sources)
174+ })
175+ .collect();
176+ Ok((items, total))
90 }177 }
91 178
92 pub async fn delete(db: &Database, id: &RagOutputId) -> Result<RagOutput, AppError> {179 pub async fn delete(db: &Database, id: &RagOutputId) -> Result<RagOutput, AppError> {
93- let deleted = sqlx::query_as!(180+ let id_u = id.uuid();
94- RagOutput,181+ let (row, sources) = tx_with_retry(db, false, async move |tx| {
95- r#"DELETE FROM rag_output WHERE id = $1182+ let sources = sqlx::query!(
96- RETURNING id AS "id: RagOutputId", course_note AS "course_note: CourseNoteId",183+ r#"SELECT source AS "source: CourseNoteFileId"
97- course AS "course: CourseId",184+ FROM rag_output_source WHERE output = $1 ORDER BY source"#,
98- sources AS "sources: Vec<CourseNoteFileId>",185+ id_u
99- payload AS "payload: Json<Value>",186+ )
100- generated_at AS "generated_at: Timestamp""#,187+ .fetch_all(&mut *tx)
101- id.uuid()188+ .await?
102- )189+ .into_iter()
103- .fetch_optional(db)190+ .map(|link| link.source)
191+ .collect::<Vec<_>>();
192+ sqlx::query!("DELETE FROM rag_output_source WHERE output = $1", id_u)
193+ .execute(&mut *tx)
194+ .await?;
195+ sqlx::query_as!(
196+ RagOutputRow,
197+ r#"DELETE FROM rag_output WHERE id = $1
198+ RETURNING id AS "id: RagOutputId", course_note AS "course_note: CourseNoteId",
199+ course AS "course: CourseId",
200+ payload AS "payload: Json<Value>",
201+ generated_at AS "generated_at: Timestamp""#,
202+ id_u
203+ )
204+ .fetch_optional(&mut *tx)
205+ .await?
206+ .map(|row| (row, sources))
207+ .ok_or(AppError::NotFound)
208+ })
104 .await?;209 .await?;
105- deleted.ok_or(AppError::NotFound)210+ Ok(row.into_rag_output(sources))
106 }211 }
107 212
108 /// Cascade: every output of `note`. Deleting none is a success — a note213 /// Cascade: every output of `note`. Deleting none is a success — a note
109-/// no service ever indexed has nothing to drop.214+/// no service ever indexed has nothing to drop. The links go before the
215+/// rows: they are the rows' children (`ON DELETE NO ACTION`).
110 pub async fn delete_for_note(db: &Database, note: &CourseNoteId) -> Result<(), AppError> {216 pub async fn delete_for_note(db: &Database, note: &CourseNoteId) -> Result<(), AppError> {
217+ sqlx::query!(
218+ "DELETE FROM rag_output_source WHERE output IN
219+ (SELECT id FROM rag_output WHERE course_note = $1)",
220+ note.uuid()
221+ )
222+ .execute(db)
223+ .await?;
111 sqlx::query!("DELETE FROM rag_output WHERE course_note = $1", note.uuid())224 sqlx::query!("DELETE FROM rag_output WHERE course_note = $1", note.uuid())
112 .execute(db)225 .execute(db)
113 .await?;226 .await?;
@@ -129,6 +242,17 @@ pub async fn replace_for_note(
129 payload: Value,242 payload: Value,
130 ) -> Result<RagOutput, AppError> {243 ) -> Result<RagOutput, AppError> {
131 let created = create(db, note, course, sources, payload).await?;244 let created = create(db, note, course, sources, payload).await?;
245+ // The superseded rows' links go first (`ON DELETE NO ACTION`), then the
246+ // rows themselves. Neither delete can touch the row just written: its id
247+ // is above every id the generator has minted before it.
248+ sqlx::query!(
249+ "DELETE FROM rag_output_source WHERE output IN
250+ (SELECT id FROM rag_output WHERE course_note = $1 AND id < $2)",
251+ note.uuid(),
252+ created.id.uuid()
253+ )
254+ .execute(db)
255+ .await?;
132 sqlx::query!(256 sqlx::query!(
133 "DELETE FROM rag_output WHERE course_note = $1 AND id < $2",257 "DELETE FROM rag_output WHERE course_note = $1 AND id < $2",
134 note.uuid(),258 note.uuid(),
@@ -139,13 +263,15 @@ pub async fn replace_for_note(
139 Ok(created)263 Ok(created)
140 }264 }
141 265
142-/// Cascade: every output built from `file`. Runs on a file delete even266+/// Cascade: the citation links that point at `file`. Runs on a file delete
143-/// with no AI service connected, so a stale output cannot survive its267+/// even with no AI service connected — `ON DELETE NO ACTION` refuses the
144-/// source. The GIN index on `sources` turns the containment test into a268+/// file row while any link still cites it. An output a link belonged to
145-/// lookup.269+/// stops being true the moment its source is gone; the re-index a file
270+/// delete triggers regenerates it from what is left, and until then it
271+/// reads as a shorter — possibly empty — citation list.
146 pub async fn delete_with_source(db: &Database, file: &CourseNoteFileId) -> Result<(), AppError> {272 pub async fn delete_with_source(db: &Database, file: &CourseNoteFileId) -> Result<(), AppError> {
147 sqlx::query!(273 sqlx::query!(
148- "DELETE FROM rag_output WHERE $1 = ANY(sources)",274+ "DELETE FROM rag_output_source WHERE source = $1",
149 file.uuid()275 file.uuid()
150 )276 )
151 .execute(db)277 .execute(db)
@@ -216,8 +342,9 @@ mod tests {
216 .unwrap()342 .unwrap()
217 }343 }
218 344
219- /// A stored round-trips through JSONB with its sources list intact, and345+ /// A stored round-trips through JSONB with its citations intact, the
220- /// the note cascade takes every row of the note with it.346+ /// file row refuses to go while a citation stands (23503), and the note
347+ /// cascade sweeps the links with the rows so the file can go after.
221 #[tokio::test]348 #[tokio::test]
222 async fn create_reads_back_and_cascades_from_the_note() {349 async fn create_reads_back_and_cascades_from_the_note() {
223 let (db, _leases) = crate::database::init_test_db().await;350 let (db, _leases) = crate::database::init_test_db().await;
@@ -236,14 +363,29 @@ mod tests {
236 assert_eq!(read_back.get_payload(), &json!({"answer": "x"}));363 assert_eq!(read_back.get_payload(), &json!({"answer": "x"}));
237 assert_eq!(read_back.get_sources(), &[file.get_id().clone()]);364 assert_eq!(read_back.get_sources(), &[file.get_id().clone()]);
238 365
366+ let refused = sqlx::query("DELETE FROM course_note_file WHERE id = $1")
367+ .bind(file.get_id().uuid())
368+ .execute(&db)
369+ .await;
370+ let err = refused.unwrap_err();
371+ assert!(crate::database::foreign_key_violation(&err), "{err}");
372+
239 delete_for_note(&db, note.get_id()).await.unwrap();373 delete_for_note(&db, note.get_id()).await.unwrap();
240 assert!(read(&db, row.get_id()).await.unwrap().is_none());374 assert!(read(&db, row.get_id()).await.unwrap().is_none());
375+ // The cascade swept the links with the outputs: the file row goes now.
376+ sqlx::query("DELETE FROM course_note_file WHERE id = $1")
377+ .bind(file.get_id().uuid())
378+ .execute(&db)
379+ .await
380+ .unwrap();
241 }381 }
242 382
243 /// Replace leaves exactly one row — the newest — and the source cascade383 /// Replace leaves exactly one row — the newest — and the source cascade
244- /// drops a row built from a file that is gone.384+ /// drops the link a file delete strands: the row survives reading as an
385+ /// empty citation list until the re-index replaces it, and the file row
386+ /// can go.
245 #[tokio::test]387 #[tokio::test]
246- async fn replace_is_newest_wins_and_source_cascade_drops() {388+ async fn replace_is_newest_wins_and_source_cascade_empties_the_citations() {
247 let (db, _leases) = crate::database::init_test_db().await;389 let (db, _leases) = crate::database::init_test_db().await;
248 let note = note_of(&db, "n").await;390 let note = note_of(&db, "n").await;
249 let file = a_file(&db, &note).await;391 let file = a_file(&db, &note).await;
@@ -272,19 +414,36 @@ mod tests {
272 414
273 delete_with_source(&db, file.get_id()).await.unwrap();415 delete_with_source(&db, file.get_id()).await.unwrap();
274 let (_, total) = list_for(&db, note.get_id(), None, 0).await.unwrap();416 let (_, total) = list_for(&db, note.get_id(), None, 0).await.unwrap();
275- assert_eq!(total, 0);417+ assert_eq!(total, 1);
418+ let survivor = read(&db, second.get_id()).await.unwrap().unwrap();
419+ assert!(survivor.get_sources().is_empty());
420+ // Links first, file after: with the link gone the file row deletes.
421+ sqlx::query("DELETE FROM course_note_file WHERE id = $1")
422+ .bind(file.get_id().uuid())
423+ .execute(&db)
424+ .await
425+ .unwrap();
276 }426 }
277 427
278- /// Deleting one row returns it; deleting it again is a 404.428+ /// Deleting one row returns it, citations included; deleting it again is
429+ /// a 404.
279 #[tokio::test]430 #[tokio::test]
280 async fn delete_returns_the_row_then_refuses() {431 async fn delete_returns_the_row_then_refuses() {
281 let (db, _leases) = crate::database::init_test_db().await;432 let (db, _leases) = crate::database::init_test_db().await;
282 let note = note_of(&db, "n").await;433 let note = note_of(&db, "n").await;
283- let row = create(&db, note.get_id(), note.get_course(), Vec::new(), json!({}))434+ let file = a_file(&db, &note).await;
284- .await435+ let row = create(
285- .unwrap();436+ &db,
437+ note.get_id(),
438+ note.get_course(),
439+ vec![file.get_id().clone()],
440+ json!({}),
441+ )
442+ .await
443+ .unwrap();
286 let gone = delete(&db, row.get_id()).await.unwrap();444 let gone = delete(&db, row.get_id()).await.unwrap();
287 assert_eq!(gone.get_id(), row.get_id());445 assert_eq!(gone.get_id(), row.get_id());
446+ assert_eq!(gone.get_sources(), &[file.get_id().clone()]);
288 assert!(matches!(447 assert!(matches!(
289 delete(&db, row.get_id()).await,448 delete(&db, row.get_id()).await,
290 Err(AppError::NotFound)449 Err(AppError::NotFound)
src/db/settings.rsmodified+216 -135
@@ -1,37 +1,106 @@
1 //! The `settings` singleton: one row (`settings`, id `'school'`) holding the1 //! The `settings` singleton: one row (`settings`, id `'school'`) holding the
2 //! school's policy knobs. An absent row reads as the built-in defaults2 //! school's policy knobs. An absent row reads as the built-in defaults
3 //! everywhere.3 //! everywhere.
4+//!
5+//! The two vocabulary lists (`attendance_statuses`, `dietary_tags`) are no
6+//! longer array columns: they live in the child tables
7+//! `settings_attendance_status` and `settings_dietary_tag`, one row per
8+//! entry. The junction keeps no order, so every read sorts by entry and the
9+//! compare-and-set guard below compares row *sets*, not bytes.
4 10
5 use sqlx::types::Json;11 use sqlx::types::Json;
6 12
7-use crate::database::Database;13+use crate::database::{Database, tx_with_retry};
8 use crate::domain::settings::{ExamKindDef, GradeBand, MealSlotDef, Settings};14 use crate::domain::settings::{ExamKindDef, GradeBand, MealSlotDef, Settings};
9 use crate::error::AppError;15 use crate::error::AppError;
10 16
11-pub async fn load(db: &Database) -> Result<Settings, AppError> {17+/// Both sides of every set compare are sorted: the child tables keep no
18+/// order, and set equality does not want one.
19+fn sorted(values: &[String]) -> Vec<String> {
20+ let mut sorted = values.to_vec();
21+ sorted.sort();
22+ sorted
23+}
24+
25+/// The one read: row columns plus both vocabularies re-assembled from their
26+/// child tables. An absent dietary set reads as `None` — the same shape an
27+/// unset column used to carry.
28+async fn load_row<'e, E>(db: E) -> Result<Option<Settings>, AppError>
29+where
30+ E: sqlx::PgExecutor<'e>,
31+{
12 let settings = sqlx::query_as!(32 let settings = sqlx::query_as!(
13 Settings,33 Settings,
14- r#"SELECT34+ r#"SELECT s.exam_kinds AS "exam_kinds: Json<Vec<ExamKindDef>>",
15- exam_kinds AS "exam_kinds: Json<Vec<ExamKindDef>>",35+ COALESCE((SELECT array_agg(t.status ORDER BY t.status)
16- attendance_statuses,36+ FROM settings_attendance_status t
17- grade_bands AS "grade_bands: Json<Vec<GradeBand>>",37+ WHERE t.settings = s.id), '{}') AS "attendance_statuses!: Vec<String>",
18- max_file_bytes,38+ s.grade_bands AS "grade_bands: Json<Vec<GradeBand>>",
19- chatbot_history_turns,39+ s.max_file_bytes,
20- max_chatbot_message_len,40+ s.chatbot_history_turns,
21- max_chatbot_threads,41+ s.max_chatbot_message_len,
22- meal_slots AS "meal_slots: Json<Vec<MealSlotDef>>",42+ s.max_chatbot_threads,
23- dietary_tags,43+ s.meal_slots AS "meal_slots: Json<Vec<MealSlotDef>>",
24- meal_cancel_cutoff_minutes44+ (SELECT array_agg(t.tag ORDER BY t.tag)
25- FROM settings WHERE id = 'school'"#45+ FROM settings_dietary_tag t
46+ WHERE t.settings = s.id) AS dietary_tags,
47+ s.meal_cancel_cutoff_minutes
48+ FROM settings s WHERE s.id = 'school'"#
26 )49 )
27 .fetch_optional(db)50 .fetch_optional(db)
28 .await?;51 .await?;
52+ Ok(settings)
53+}
54+
55+pub async fn load(db: &Database) -> Result<Settings, AppError> {
56+ let settings = load_row(db).await?;
29 Ok(settings.unwrap_or_else(Settings::defaults))57 Ok(settings.unwrap_or_else(Settings::defaults))
30 }58 }
31 59
32-/// Persist the policy (single UPSERT on the fixed singleton id),60+/// Replace the attendance vocabulary wholesale. Callers run inside a
33-/// unconditionally — last write wins. Prefer [`save_if_unchanged`]61+/// transaction (or inside the single CAS statement), so the delete and the
34-/// wherever the new policy was merged from a loaded snapshot.62+/// insert cannot be observed apart.
63+async fn replace_statuses(
64+ conn: &mut sqlx::PgConnection,
65+ statuses: &[String],
66+) -> Result<(), AppError> {
67+ sqlx::query!("DELETE FROM settings_attendance_status WHERE settings = 'school'")
68+ .execute(&mut *conn)
69+ .await?;
70+ sqlx::query!(
71+ "INSERT INTO settings_attendance_status (settings, status)
72+ SELECT 'school', t.status FROM unnest($1::text[]) AS t(status)",
73+ statuses,
74+ )
75+ .execute(&mut *conn)
76+ .await?;
77+ Ok(())
78+}
79+
80+/// Replace the dietary vocabulary wholesale. `None` and `Some(empty)` both
81+/// write zero rows — "explicitly empty" and "never set" are the same state
82+/// on the child tables.
83+async fn replace_tags(
84+ conn: &mut sqlx::PgConnection,
85+ tags: Option<&[String]>,
86+) -> Result<(), AppError> {
87+ sqlx::query!("DELETE FROM settings_dietary_tag WHERE settings = 'school'")
88+ .execute(&mut *conn)
89+ .await?;
90+ sqlx::query!(
91+ "INSERT INTO settings_dietary_tag (settings, tag)
92+ SELECT 'school', t.tag FROM unnest($1::text[]) AS t(tag)",
93+ tags,
94+ )
95+ .execute(&mut *conn)
96+ .await?;
97+ Ok(())
98+}
99+
100+/// Persist the policy (single UPSERT on the fixed singleton id plus a
101+/// wholesale rewrite of both vocabularies, one transaction), unconditionally
102+/// — last write wins. Prefer [`save_if_unchanged`] wherever the new policy
103+/// was merged from a loaded snapshot.
35 pub async fn save(db: &Database, settings: Settings) -> Result<Settings, AppError> {104 pub async fn save(db: &Database, settings: Settings) -> Result<Settings, AppError> {
36 // whole-row-save-ok: test-only seeding; every production write merges from a loaded snapshot and goes through save_if_unchanged105 // whole-row-save-ok: test-only seeding; every production write merges from a loaded snapshot and goes through save_if_unchanged
37 let exam_kinds = serde_json::to_value(&settings.exam_kinds.0)106 let exam_kinds = serde_json::to_value(&settings.exam_kinds.0)
@@ -44,49 +113,40 @@ pub async fn save(db: &Database, settings: Settings) -> Result<Settings, AppErro
44 .map(|slots| serde_json::to_value(&slots.0))113 .map(|slots| serde_json::to_value(&slots.0))
45 .transpose()114 .transpose()
46 .map_err(|e| AppError::Internal(format!("settings encode: {e}")))?;115 .map_err(|e| AppError::Internal(format!("settings encode: {e}")))?;
47- let saved = sqlx::query_as!(116+ let attendance = sorted(&settings.attendance_statuses);
48- Settings,117+ let dietary = settings.dietary_tags.clone();
49- r#"INSERT INTO settings (id, exam_kinds, attendance_statuses, grade_bands,118+ tx_with_retry(db, true, async move |tx| {
50- max_file_bytes, chatbot_history_turns,119+ sqlx::query!(
51- max_chatbot_message_len, max_chatbot_threads,120+ r#"INSERT INTO settings (id, exam_kinds, grade_bands, max_file_bytes,
52- meal_slots, dietary_tags, meal_cancel_cutoff_minutes)121+ chatbot_history_turns, max_chatbot_message_len,
53- VALUES ('school', $1, $2, $3, $4, $5, $6, $7, $8, $9, $10)122+ max_chatbot_threads, meal_slots,
54- ON CONFLICT (id) DO UPDATE SET123+ meal_cancel_cutoff_minutes)
55- exam_kinds = EXCLUDED.exam_kinds,124+ VALUES ('school', $1, $2, $3, $4, $5, $6, $7, $8)
56- attendance_statuses = EXCLUDED.attendance_statuses,125+ ON CONFLICT (id) DO UPDATE SET
57- grade_bands = EXCLUDED.grade_bands,126+ exam_kinds = EXCLUDED.exam_kinds,
58- max_file_bytes = EXCLUDED.max_file_bytes,127+ grade_bands = EXCLUDED.grade_bands,
59- chatbot_history_turns = EXCLUDED.chatbot_history_turns,128+ max_file_bytes = EXCLUDED.max_file_bytes,
60- max_chatbot_message_len = EXCLUDED.max_chatbot_message_len,129+ chatbot_history_turns = EXCLUDED.chatbot_history_turns,
61- max_chatbot_threads = EXCLUDED.max_chatbot_threads,130+ max_chatbot_message_len = EXCLUDED.max_chatbot_message_len,
62- meal_slots = EXCLUDED.meal_slots,131+ max_chatbot_threads = EXCLUDED.max_chatbot_threads,
63- dietary_tags = EXCLUDED.dietary_tags,132+ meal_slots = EXCLUDED.meal_slots,
64- meal_cancel_cutoff_minutes = EXCLUDED.meal_cancel_cutoff_minutes133+ meal_cancel_cutoff_minutes = EXCLUDED.meal_cancel_cutoff_minutes"#,
65- RETURNING134+ exam_kinds,
66- exam_kinds AS "exam_kinds: Json<Vec<ExamKindDef>>",135+ grade_bands,
67- attendance_statuses,136+ settings.max_file_bytes,
68- grade_bands AS "grade_bands: Json<Vec<GradeBand>>",137+ settings.chatbot_history_turns,
69- max_file_bytes,138+ settings.max_chatbot_message_len,
70- chatbot_history_turns,139+ settings.max_chatbot_threads,
71- max_chatbot_message_len,140+ meal_slots,
72- max_chatbot_threads,141+ settings.meal_cancel_cutoff_minutes,
73- meal_slots AS "meal_slots: Json<Vec<MealSlotDef>>",142+ )
74- dietary_tags,143+ .execute(&mut *tx)
75- meal_cancel_cutoff_minutes"#,144+ .await?;
76- exam_kinds,145+ replace_statuses(&mut *tx, &attendance).await?;
77- settings.attendance_statuses.as_slice(),146+ replace_tags(&mut *tx, dietary.as_deref()).await?;
78- grade_bands,147+ load_row(&mut *tx).await?.ok_or(AppError::NotFound)
79- settings.max_file_bytes,148+ })
80- settings.chatbot_history_turns,149+ .await
81- settings.max_chatbot_message_len,
82- settings.max_chatbot_threads,
83- meal_slots,
84- settings.dietary_tags.as_deref(),
85- settings.meal_cancel_cutoff_minutes,
86- )
87- .fetch_one(db)
88- .await?;
89- Ok(saved)
90 }150 }
91 151
92 /// Persist the policy only while the stored row still matches `expected`152 /// Persist the policy only while the stored row still matches `expected`
@@ -97,25 +157,26 @@ pub async fn save(db: &Database, settings: Settings) -> Result<Settings, AppErro
97 /// same snapshot; the later whole-row write restores its stale copy of157 /// same snapshot; the later whole-row write restores its stale copy of
98 /// the other's field).158 /// the other's field).
99 ///159 ///
100-/// ONE guarded statement, where the old engine needed a seed insert and a160+/// ONE guarded statement, generic over the executor so the workflow can run
101-/// separate guarded update: the `INSERT` arm materializes the defaults-as-161+/// the same guarded save inside its own transaction (a stale save must roll
102-/// loaded state when no row exists yet (`load` reported the defaults, so162+/// its retirements back, which only an abort can do). The `INSERT` arm
103-/// the defaults are what the caller merged over — nothing to compare), and163+/// materializes the defaults-as-loaded state when no row exists yet (`load`
104-/// the `ON CONFLICT DO UPDATE … WHERE` arm applies `settings` only if the164+/// reported the defaults, so the defaults are what the caller merged over —
105-/// row (still) equals `expected`, every column compared with165+/// nothing to compare), and the `ON CONFLICT DO UPDATE … WHERE` arm applies
106-/// `IS NOT DISTINCT FROM` so "never set" (`NULL`) stays distinct from166+/// `settings` only if the stored state (still) equals `expected`: row
107-/// "explicitly empty" and an unset column matches an unset expectation.167+/// columns each compared with `IS NOT DISTINCT FROM`, and the two
108-///168+/// vocabularies compared as sorted aggregates over their child tables — the
109-/// The old `meal_slots` projection dance was an artifact of the old engine169+/// row *sets*, since the junctions keep no order. The settings row's own
110-/// *dropping* object keys whose value was `NONE` on write, which made a170+/// lock is the serialization point: a waiter for the same row re-runs the
111-/// plain equality guard never match a slot without a serving time. Both171+/// whole guard against the winner's committed state, and its child-table
112-/// sides of this comparison are written by the same Rust serialization,172+/// subqueries then read the winner's committed vocabulary.
113-/// which round-trips through JSONB unchanged — the shapes cannot diverge,
114-/// so the columns are compared whole.
115 ///173 ///
116-/// Generic over the executor so the workflow can run the same guarded save174+/// The vocabulary rewrites are CTEs gated on the row write having produced a
117-/// inside its own transaction (a stale save must roll its retirements back,175+/// row (`new_row`), and each insert waits for its delete through the
118-/// which only an abort can do).176+/// delete's RETURNING count — data-modifying CTEs share one snapshot, so
177+/// without that chain the insert could race its own delete and drop rows.
178+/// The returned row's vocabulary comes from the inserts' RETURNING, not a
179+/// re-read: the statement cannot see its own writes to the child tables.
119 pub async fn save_if_unchanged<'e, E>(180 pub async fn save_if_unchanged<'e, E>(
120 db: E,181 db: E,
121 settings: Settings,182 settings: Settings,
@@ -134,57 +195,85 @@ where
134 .map(|slots| serde_json::to_value(&slots.0))195 .map(|slots| serde_json::to_value(&slots.0))
135 .transpose()196 .transpose()
136 .map_err(|e| AppError::Internal(format!("settings encode: {e}")))?;197 .map_err(|e| AppError::Internal(format!("settings encode: {e}")))?;
137- let expected_exam_kinds = serde_json::to_value(&expected.exam_kinds.0)198+ let attendance = sorted(&settings.attendance_statuses);
138- .map_err(|e| AppError::Internal(format!("settings encode: {e}")))?;199+ let expected_attendance = sorted(&expected.attendance_statuses);
139- let expected_grade_bands = serde_json::to_value(&expected.grade_bands.0)200+ // An empty `Some` must compare equal to the stored NULL an empty set
140- .map_err(|e| AppError::Internal(format!("settings encode: {e}")))?;201+ // reads as, so it is normalized away on the expected side.
141- let expected_meal_slots = expected202+ let expected_dietary = expected
142- .meal_slots203+ .dietary_tags
143 .as_ref()204 .as_ref()
144- .map(|slots| serde_json::to_value(&slots.0))205+ .filter(|tags| !tags.is_empty())
145- .transpose()206+ .map(|tags| tags.as_slice());
146- .map_err(|e| AppError::Internal(format!("settings encode: {e}")))?;
147 let saved = sqlx::query_as!(207 let saved = sqlx::query_as!(
148 Settings,208 Settings,
149- r#"INSERT INTO settings (id, exam_kinds, attendance_statuses, grade_bands,209+ r#"WITH new_row AS (
150- max_file_bytes, chatbot_history_turns,210+ INSERT INTO settings (id, exam_kinds, grade_bands, max_file_bytes,
151- max_chatbot_message_len, max_chatbot_threads,211+ chatbot_history_turns, max_chatbot_message_len,
152- meal_slots, dietary_tags, meal_cancel_cutoff_minutes)212+ max_chatbot_threads, meal_slots,
153- VALUES ('school', $1, $2, $3, $4, $5, $6, $7, $8, $9, $10)213+ meal_cancel_cutoff_minutes)
154- ON CONFLICT (id) DO UPDATE SET214+ VALUES ('school', $1, $3, $4, $5, $6, $7, $8, $10)
155- exam_kinds = $1,215+ ON CONFLICT (id) DO UPDATE SET
156- attendance_statuses = $2,216+ exam_kinds = $1,
157- grade_bands = $3,217+ grade_bands = $3,
158- max_file_bytes = $4,218+ max_file_bytes = $4,
159- chatbot_history_turns = $5,219+ chatbot_history_turns = $5,
160- max_chatbot_message_len = $6,220+ max_chatbot_message_len = $6,
161- max_chatbot_threads = $7,221+ max_chatbot_threads = $7,
162- meal_slots = $8,222+ meal_slots = $8,
163- dietary_tags = $9,223+ meal_cancel_cutoff_minutes = $10
164- meal_cancel_cutoff_minutes = $10224+ WHERE settings.exam_kinds IS NOT DISTINCT FROM $1
165- WHERE settings.exam_kinds IS NOT DISTINCT FROM $11225+ AND settings.grade_bands IS NOT DISTINCT FROM $3
166- AND settings.attendance_statuses IS NOT DISTINCT FROM $12226+ AND settings.max_file_bytes IS NOT DISTINCT FROM $4
167- AND settings.grade_bands IS NOT DISTINCT FROM $13227+ AND settings.chatbot_history_turns IS NOT DISTINCT FROM $5
168- AND settings.max_file_bytes IS NOT DISTINCT FROM $14228+ AND settings.max_chatbot_message_len IS NOT DISTINCT FROM $6
169- AND settings.chatbot_history_turns IS NOT DISTINCT FROM $15229+ AND settings.max_chatbot_threads IS NOT DISTINCT FROM $7
170- AND settings.max_chatbot_message_len IS NOT DISTINCT FROM $16230+ AND settings.meal_slots IS NOT DISTINCT FROM $8
171- AND settings.max_chatbot_threads IS NOT DISTINCT FROM $17231+ AND settings.meal_cancel_cutoff_minutes IS NOT DISTINCT FROM $10
172- AND settings.meal_slots IS NOT DISTINCT FROM $18232+ AND COALESCE((SELECT array_agg(s.status ORDER BY s.status)
173- AND settings.dietary_tags IS NOT DISTINCT FROM $19233+ FROM settings_attendance_status s
174- AND settings.meal_cancel_cutoff_minutes IS NOT DISTINCT FROM $20234+ WHERE s.settings = settings.id), '{}')
175- RETURNING235+ IS NOT DISTINCT FROM $11::text[]
176- exam_kinds AS "exam_kinds: Json<Vec<ExamKindDef>>",236+ AND (SELECT array_agg(t.tag ORDER BY t.tag)
177- attendance_statuses,237+ FROM settings_dietary_tag t
178- grade_bands AS "grade_bands: Json<Vec<GradeBand>>",238+ WHERE t.settings = settings.id)
179- max_file_bytes,239+ IS NOT DISTINCT FROM $12::text[]
180- chatbot_history_turns,240+ RETURNING exam_kinds, grade_bands, max_file_bytes,
181- max_chatbot_message_len,241+ chatbot_history_turns, max_chatbot_message_len,
182- max_chatbot_threads,242+ max_chatbot_threads, meal_slots, meal_cancel_cutoff_minutes),
183- meal_slots AS "meal_slots: Json<Vec<MealSlotDef>>",243+ status_del AS (
184- dietary_tags,244+ DELETE FROM settings_attendance_status
185- meal_cancel_cutoff_minutes"#,245+ WHERE settings = 'school' AND EXISTS (SELECT 1 FROM new_row)
246+ RETURNING 1),
247+ status_ins AS (
248+ INSERT INTO settings_attendance_status (settings, status)
249+ SELECT 'school', t.status FROM unnest($2::text[]) AS t(status)
250+ CROSS JOIN (SELECT count(*) AS deleted FROM status_del) d
251+ WHERE EXISTS (SELECT 1 FROM new_row)
252+ RETURNING status),
253+ tag_del AS (
254+ DELETE FROM settings_dietary_tag
255+ WHERE settings = 'school' AND EXISTS (SELECT 1 FROM new_row)
256+ RETURNING 1),
257+ tag_ins AS (
258+ INSERT INTO settings_dietary_tag (settings, tag)
259+ SELECT 'school', t.tag FROM unnest($9::text[]) AS t(tag)
260+ CROSS JOIN (SELECT count(*) AS deleted FROM tag_del) d
261+ WHERE EXISTS (SELECT 1 FROM new_row)
262+ RETURNING tag)
263+ SELECT r.exam_kinds AS "exam_kinds: Json<Vec<ExamKindDef>>",
264+ COALESCE((SELECT array_agg(status ORDER BY status)
265+ FROM status_ins), '{}') AS "attendance_statuses!: Vec<String>",
266+ r.grade_bands AS "grade_bands: Json<Vec<GradeBand>>",
267+ r.max_file_bytes,
268+ r.chatbot_history_turns,
269+ r.max_chatbot_message_len,
270+ r.max_chatbot_threads,
271+ r.meal_slots AS "meal_slots: Json<Vec<MealSlotDef>>",
272+ (SELECT array_agg(tag ORDER BY tag) FROM tag_ins) AS dietary_tags,
273+ r.meal_cancel_cutoff_minutes
274+ FROM new_row r"#,
186 exam_kinds,275 exam_kinds,
187- settings.attendance_statuses.as_slice(),276+ &attendance,
188 grade_bands,277 grade_bands,
189 settings.max_file_bytes,278 settings.max_file_bytes,
190 settings.chatbot_history_turns,279 settings.chatbot_history_turns,
@@ -193,16 +282,8 @@ where
193 meal_slots,282 meal_slots,
194 settings.dietary_tags.as_deref(),283 settings.dietary_tags.as_deref(),
195 settings.meal_cancel_cutoff_minutes,284 settings.meal_cancel_cutoff_minutes,
196- expected_exam_kinds,285+ &expected_attendance,
197- expected.attendance_statuses.as_slice(),286+ expected_dietary,
198- expected_grade_bands,
199- expected.max_file_bytes,
200- expected.chatbot_history_turns,
201- expected.max_chatbot_message_len,
202- expected.max_chatbot_threads,
203- expected_meal_slots,
204- expected.dietary_tags.as_deref(),
205- expected.meal_cancel_cutoff_minutes,
206 )287 )
207 .fetch_optional(db)288 .fetch_optional(db)
208 .await?;289 .await?;
src/db/user.rsmodified+31 -17
@@ -512,7 +512,12 @@ pub async fn set_role_cascade(
512 // board and its whole history, and the creator's `board_count`512 // board and its whole history, and the creator's `board_count`
513 // seat stays taken, which is correct while the row it counts513 // seat stays taken, which is correct while the row it counts
514 // exists. Stamped *before* the roster strip so the strip's514 // exists. Stamped *before* the roster strip so the strip's
515- // `RETURNING` carries the closed row the caller fans out.515+ // read-back below carries the closed row the caller fans out.
516+ // The strip itself is the junction's: the demoted user's roster
517+ // rows are deleted and their board ids collected from
518+ // RETURNING, then the affected rooms are read back in the same
519+ // transaction — the junction delete cannot return the whole
520+ // row the way the old `array_remove` `UPDATE` did.
516 sqlx::query!(521 sqlx::query!(
517 "UPDATE board SET closed_at = $2 WHERE creator = $1 AND closed_at IS NULL",522 "UPDATE board SET closed_at = $2 WHERE creator = $1 AND closed_at IS NULL",
518 target.uuid(),523 target.uuid(),
@@ -520,21 +525,29 @@ pub async fn set_role_cascade(
520 )525 )
521 .execute(&mut *tx)526 .execute(&mut *tx)
522 .await?;527 .await?;
528+ let stripped = sqlx::query!(
529+ "DELETE FROM board_participant WHERE participant = $1 RETURNING board",
530+ target.uuid(),
531+ )
532+ .fetch_all(&mut *tx)
533+ .await?;
534+ let stripped_boards: Vec<uuid::Uuid> =
535+ stripped.into_iter().map(|row| row.board).collect();
523 let boards = sqlx::query_as!(536 let boards = sqlx::query_as!(
524 Board,537 Board,
525- r#"UPDATE board538+ r#"SELECT b.id AS "id: BoardId", b.creator AS "creator: UserId",
526- SET participants = array_remove(participants, $1)539+ b.title AS "title: BoardTitle",
527- WHERE $1 = ANY(participants) OR creator = $1540+ ARRAY(SELECT p.participant FROM board_participant p
528- RETURNING id AS "id: BoardId",541+ WHERE p.board = b.id ORDER BY p.participant)
529- creator AS "creator: UserId",542+ AS "participants!: Vec<UserId>",
530- title AS "title: BoardTitle",543+ b.locked, b.locked_by AS "locked_by: UserId",
531- participants AS "participants: Vec<UserId>",544+ b.locked_at AS "locked_at: Timestamp", b.epoch,
532- locked,545+ b.closed_at AS "closed_at: Timestamp",
533- locked_by AS "locked_by: UserId",546+ b.created_at AS "created_at: Timestamp"
534- locked_at AS "locked_at: Timestamp",547+ FROM board b
535- epoch,548+ WHERE b.id = ANY($1::uuid[]) OR b.creator = $2
536- closed_at AS "closed_at: Timestamp",549+ ORDER BY b.id"#,
537- created_at AS "created_at: Timestamp""#,550+ &stripped_boards,
538 target.uuid(),551 target.uuid(),
539 )552 )
540 .fetch_all(&mut *tx)553 .fetch_all(&mut *tx)
@@ -549,10 +562,11 @@ pub async fn set_role_cascade(
549 }562 }
550 563
551 if !role.at_least(Role::Teacher) {564 if !role.at_least(Role::Teacher) {
552- // Course staffing goes — only teacher+ may hold a seat on the565+ // Course staffing goes — only teacher+ may hold a seat, and the
553- // list.566+ // seat is a `course_teacher` row now: one `DELETE` by its
567+ // `teacher` index takes every assignment.
554 sqlx::query!(568 sqlx::query!(
555- "UPDATE course SET teachers = array_remove(teachers, $1) WHERE $1 = ANY(teachers)",569+ "DELETE FROM course_teacher WHERE teacher = $1",
556 target.uuid(),570 target.uuid(),
557 )571 )
558 .execute(&mut *tx)572 .execute(&mut *tx)
src/domain/class_blueprint.rsmodified+7 -6
@@ -48,13 +48,14 @@ impl ClassBlueprintId {
48 }48 }
49 }49 }
50 50
51-/// One grade's template. `grade` is stored beside the key it *is*, so a read51+/// One grade's template. The id is the grade label itself — the key one
52-/// never has to parse a record id back into a domain value.52+/// grade always maps to — stored here beside the `grade` field so a read
53-#[derive(Debug, Clone, sqlx::FromRow)]53+/// never has to parse a record id back into a domain value. `courses` is
54+/// not a column of the row: it is the `blueprint_course` junction, joined
55+/// on by the db layer (sorted by course, which is the order every CAS
56+/// comparison relies on).
57+#[derive(Debug, Clone)]
54 pub struct ClassBlueprint {58 pub struct ClassBlueprint {
55- /// The table's `TEXT` primary key column, stored once and read into both
56- /// this field and `grade` — the key *is* the grade label.
57- #[sqlx(rename = "grade")]
58 pub(crate) id: ClassBlueprintId,59 pub(crate) id: ClassBlueprintId,
59 pub(crate) grade: ClassGrade,60 pub(crate) grade: ClassGrade,
60 pub(crate) courses: Vec<CourseId>,61 pub(crate) courses: Vec<CourseId>,
src/domain/course.rsmodified+5 -3
@@ -96,11 +96,12 @@ impl CourseKind {
96 /// `creator` owns the course for good — only they (or a manager+) may delete96 /// `creator` owns the course for good — only they (or a manager+) may delete
97 /// it. `teachers` are the staff a manager assigned to run it: full management97 /// it. `teachers` are the staff a manager assigned to run it: full management
98 /// rights inside the course, no power to delete it or change the assignment98 /// rights inside the course, no power to delete it or change the assignment
99-/// list.99+/// list. The assignment itself is `course_teacher` rows; the struct carries
100+/// the resolved list, joined on by the db layer.
100 ///101 ///
101 /// Fields are crate-visible: [`crate::db::course`] mints the rows on create102 /// Fields are crate-visible: [`crate::db::course`] mints the rows on create
102 /// and reads the id when updating and cascading a delete.103 /// and reads the id when updating and cascading a delete.
103-#[derive(Debug, Clone, sqlx::FromRow)]104+#[derive(Debug, Clone)]
104 pub struct Course {105 pub struct Course {
105 pub(crate) id: CourseId,106 pub(crate) id: CourseId,
106 pub(crate) creator: UserId,107 pub(crate) creator: UserId,
@@ -146,7 +147,8 @@ impl Course {
146 &self.creator == user147 &self.creator == user
147 }148 }
148 149
149- /// The staff assigned to run this course, in assignment order.150+ /// The staff assigned to run this course. Assignment order is not kept:
151+ /// the links are `course_teacher` rows now, and a set has no order.
150 pub fn get_teachers(&self) -> &[UserId] {152 pub fn get_teachers(&self) -> &[UserId] {
151 &self.teachers153 &self.teachers
152 }154 }
src/domain/dietary_profile.rsmodified+2 -1
@@ -43,7 +43,8 @@ impl DietaryProfileId {
43 43
44 /// The tags a student's diet carries, drawn from the school's `dietary_tags`44 /// The tags a student's diet carries, drawn from the school's `dietary_tags`
45 /// list — the same vocabulary a dish is tagged from, deduplicated and in the45 /// list — the same vocabulary a dish is tagged from, deduplicated and in the
46-/// order given. Stored as a `TEXT[]` column. `no_pg_array` skips the derive's46+/// order given. Stored one row per tag in `dietary_profile_tag` (an `ord`
47+/// column keeps the given order). `no_pg_array` skips the derive's
47 /// element-array assertion (which a `Vec` inner cannot satisfy); the impls48 /// element-array assertion (which a `Vec` inner cannot satisfy); the impls
48 /// still delegate to `Vec<String>`.49 /// still delegate to `Vec<String>`.
49 #[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]50 #[derive(Debug, Clone, PartialEq, Eq, sqlx::Type)]
src/domain/homework.rsmodified+6 -5
@@ -81,11 +81,12 @@ impl HomeworkDescription {
81 }81 }
82 }82 }
83 83
84-/// A homework assignment. `assigned` is the optional student subset (`uuid[]84+/// A homework assignment. `assigned` is the optional student subset,
85-/// NULL`): `NULL` and an empty list both mean "the whole course" — see85+/// assembled from the `homework_assignment` child rows (`None` = no rows =
86-/// [`Homework::student_sees`]. Because whole-course homework carries no roster,86+/// the whole course — see [`Homework::student_sees`]). Because whole-course
87-/// a student who enrolls later is covered automatically; a subset is a fixed87+/// homework carries no roster, a student who enrolls later is covered
88-/// snapshot of the students named at assign (or last PATCH) time.88+/// automatically; a subset is a fixed snapshot of the students named at
89+/// assign (or last PATCH) time.
89 #[derive(Debug, Clone, sqlx::FromRow)]90 #[derive(Debug, Clone, sqlx::FromRow)]
90 pub struct Homework {91 pub struct Homework {
91 pub(crate) id: HomeworkId,92 pub(crate) id: HomeworkId,
src/domain/menu_dish.rsmodified+3 -2
@@ -111,8 +111,9 @@ impl DishPrice {
111 111
112 /// The dietary tags a dish carries, drawn from the school's `dietary_tags`112 /// The dietary tags a dish carries, drawn from the school's `dietary_tags`
113 /// list. Deduplicated, order preserved — the list is what a student's profile113 /// list. Deduplicated, order preserved — the list is what a student's profile
114-/// is matched against, so a repeat carries no extra meaning. Stored as a114+/// is matched against, so a repeat carries no extra meaning. Stored one row
115-/// `TEXT[]` column.115+/// per tag in `menu_dish_tag` — an `ord` column keeps the given order, and
116+/// reads re-aggregate in that order.
116 #[derive(Debug, Clone, PartialEq, Eq, Type)]117 #[derive(Debug, Clone, PartialEq, Eq, Type)]
117 #[sqlx(transparent, no_pg_array)]118 #[sqlx(transparent, no_pg_array)]
118 pub struct DishTags(Vec<String>);119 pub struct DishTags(Vec<String>);
src/domain/rag_output.rsmodified+9 -6
@@ -9,7 +9,7 @@
9 //! from both sides of what it was built from —9 //! from both sides of what it was built from —
10 //! [`delete_for_note`](crate::db::rag_output::delete_for_note) when the note10 //! [`delete_for_note`](crate::db::rag_output::delete_for_note) when the note
11 //! goes, [`delete_with_source`](crate::db::rag_output::delete_with_source)11 //! goes, [`delete_with_source`](crate::db::rag_output::delete_with_source)
12-//! when one of the attachments it was built from goes — so a stale output12+//! dropping the citation links a file delete strands — so the stored shape
13 //! never outlives its input, even in a deployment with no AI service13 //! never outlives its input, even in a deployment with no AI service
14 //! connected. Persistence lives in [`crate::db::rag_output`].14 //! connected. Persistence lives in [`crate::db::rag_output`].
15 15
@@ -57,16 +57,19 @@ impl RagOutputId {
57 }57 }
58 }58 }
59 59
60-#[derive(Debug, Clone, sqlx::FromRow)]60+/// The backend's stored rag-output row. No `sqlx::FromRow`: the citations
61+/// are `rag_output_source` link rows, not columns — the db layer decodes
62+/// its own plain-columns struct and attaches the links.
63+#[derive(Debug, Clone)]
61 pub struct RagOutput {64 pub struct RagOutput {
62 pub(crate) id: RagOutputId,65 pub(crate) id: RagOutputId,
63 pub(crate) course_note: CourseNoteId,66 pub(crate) course_note: CourseNoteId,
64 /// The note's course, denormalised so a course-wide read needs no join.67 /// The note's course, denormalised so a course-wide read needs no join.
65 pub(crate) course: CourseId,68 pub(crate) course: CourseId,
66- /// The attachments the output was built from, as they stood at generation69+ /// The attachments the output was built from, in source-id order.
67- /// time. Deleting any one of them drops this row70+ /// Stored as `rag_output_source` link rows; deleting a file drops its
68- /// ([`delete_with_source`](crate::db::rag_output::delete_with_source))71+ /// links ([`delete_with_source`](crate::db::rag_output::delete_with_source))
69- /// rather than leaving an output citing a file that no longer exists.72+ /// and deleting an output drops its links, before either parent goes.
70 pub(crate) sources: Vec<CourseNoteFileId>,73 pub(crate) sources: Vec<CourseNoteFileId>,
71 /// The service's answer, stored verbatim in a JSONB column. Opaque to the74 /// The service's answer, stored verbatim in a JSONB column. Opaque to the
72 /// backend — it is a service-owned shape, so this side neither validates75 /// backend — it is a service-owned shape, so this side neither validates
src/service/board.rsmodified+5 -5
@@ -1,5 +1,5 @@
1 //! Board workflows: the roster gates the REST surface drives, and the1 //! Board workflows: the roster gates the REST surface drives, and the
2-//! atomic-array write that replaced the old process-wide roster lock. The2+//! atomic-union insert that replaced the old process-wide roster lock. The
3 //! queries live in [`crate::db::board`]; the room's WebSocket keeps its3 //! queries live in [`crate::db::board`]; the room's WebSocket keeps its
4 //! own binding policy in [`crate::web::board_ws`], reading through here.4 //! own binding policy in [`crate::web::board_ws`], reading through here.
5 5
@@ -117,10 +117,10 @@ pub async fn resolve_participants(
117 /// **all-or-nothing**: an over-full union is refused with a `409` naming the117 /// **all-or-nothing**: an over-full union is refused with a `409` naming the
118 /// two numbers and the roster is left exactly as it was.118 /// two numbers and the roster is left exactly as it was.
119 ///119 ///
120-/// The merge itself is one atomic guarded statement120+/// The merge itself is one serialized union ([`board::invite_group`]): the
121-/// ([`board::invite_group`]): `SET` and guard both read the row version the121+/// board row is locked first, so of two concurrent invites the second
122-/// `UPDATE` is acting on, so of two concurrent invites neither can drop the122+/// waits, counts against the first's committed roster and the cap refuses
123-/// other's group and the cap refuses the second — the property the old123+/// it — neither can drop the other's group, the property the old
124 /// process-wide roster lock existed to provide, now enforced by the row124 /// process-wide roster lock existed to provide, now enforced by the row
125 /// itself. Nothing else here writes between the read and the write, so125 /// itself. Nothing else here writes between the read and the write, so
126 /// there is no lock left to hold.126 /// there is no lock left to hold.
src/service/class_blueprint.rsmodified+19 -1
@@ -171,7 +171,8 @@ pub async fn set_courses(
171 /// a silent detach of somebody else's additions. Known hole, accepted: the171 /// a silent detach of somebody else's additions. Known hole, accepted: the
172 /// grade label *is* the primary key and the comparison is by **content**, so172 /// grade label *is* the primary key and the comparison is by **content**, so
173 /// a blueprint deleted and recreated at the same grade with the same list173 /// a blueprint deleted and recreated at the same grade with the same list
174-/// satisfies `WHERE courses = $held` and this call deletes the *new* row.174+/// names the same course set as the stored junction rows, and this call
175+/// deletes the *new* row.
175 ///176 ///
176 /// Content-equal is intent-equal — the end state is the one the caller177 /// Content-equal is intent-equal — the end state is the one the caller
177 /// asked for — and telling the two apart needs a revision column on the178 /// asked for — and telling the two apart needs a revision column on the
@@ -448,6 +449,15 @@ mod tests {
448 .unwrap()449 .unwrap()
449 .unwrap();450 .unwrap();
450 let blueprint = a_blueprint(vec![course.clone()], &db).await;451 let blueprint = a_blueprint(vec![course.clone()], &db).await;
452+ // Children first, the ordering the course's own cascade runs: with the
453+ // junction row standing, the raw course delete below is a foreign-key
454+ // refusal. What is left is exactly the pump-window state the handle
455+ // still walks.
456+ sqlx::query("DELETE FROM blueprint_course WHERE course = $1")
457+ .bind(course.uuid())
458+ .execute(&db)
459+ .await
460+ .unwrap();
451 sqlx::query("DELETE FROM course WHERE id = $1")461 sqlx::query("DELETE FROM course WHERE id = $1")
452 .bind(course.uuid())462 .bind(course.uuid())
453 .execute(&db)463 .execute(&db)
@@ -810,6 +820,14 @@ mod tests {
810 let a = a_section("9-A", &db).await;820 let a = a_section("9-A", &db).await;
811 let b = a_section("9-B", &db).await;821 let b = a_section("9-B", &db).await;
812 let mut blueprint = a_blueprint(vec![astronomy.clone(), algebra.clone()], &db).await;822 let mut blueprint = a_blueprint(vec![astronomy.clone(), algebra.clone()], &db).await;
823+ // Children first, the ordering the course's own cascade runs — the
824+ // junction row standing would make the raw delete a foreign-key
825+ // refusal. The handle below still walks the list it read.
826+ sqlx::query("DELETE FROM blueprint_course WHERE course = $1")
827+ .bind(astronomy.uuid())
828+ .execute(&db)
829+ .await
830+ .unwrap();
813 sqlx::query("DELETE FROM course WHERE id = $1")831 sqlx::query("DELETE FROM course WHERE id = $1")
814 .bind(astronomy.uuid())832 .bind(astronomy.uuid())
815 .execute(&db)833 .execute(&db)
src/service/course.rsmodified+5 -4
@@ -17,10 +17,11 @@ use crate::service::term;
17 /// accepted race (see README concurrency model): a term archived after this17 /// accepted race (see README concurrency model): a term archived after this
18 /// read still lets the write through.18 /// read still lets the write through.
19 pub async fn require_open(db: &Database, course: &Course) -> Result<(), AppError> {19 pub async fn require_open(db: &Database, course: &Course) -> Result<(), AppError> {
20- match course.get_term() {20+ let Some(term) = course.get_term().cloned() else {
21- None => Ok(()),21+ return Ok(());
22- Some(term) => term::require_open(db, term).await,22+ };
23- }23+ let db = db.clone();
24+ term::require_open(&db, &term).await
24 }25 }
25 26
26 pub async fn create(27 pub async fn create(
src/service/rag_output.rsmodified+3 -3
@@ -35,9 +35,9 @@ pub async fn delete_for_note(db: &Database, note: &CourseNoteId) -> Result<(), A
35 rag_output::delete_for_note(db, note).await35 rag_output::delete_for_note(db, note).await
36 }36 }
37 37
38-/// Cascade: every output built from `file`. Runs on a file delete even38+/// Cascade: the citation links pointing at `file`. Runs on a file delete
39-/// with no AI service connected, so a stale output cannot survive its39+/// even with no AI service connected — the file row refuses to go while a
40-/// source.40+/// link still cites it.
41 pub async fn delete_with_source(db: &Database, file: &CourseNoteFileId) -> Result<(), AppError> {41 pub async fn delete_with_source(db: &Database, file: &CourseNoteFileId) -> Result<(), AppError> {
42 rag_output::delete_with_source(db, file).await42 rag_output::delete_with_source(db, file).await
43 }43 }
src/tenant.rsmodified+191 -122
@@ -23,10 +23,13 @@ use serde::Serialize;
23 use sqlx::postgres::PgConnectOptions;23 use sqlx::postgres::PgConnectOptions;
24 24
25 use crate::constant::{MAX_SLUG_LEN, MIN_SLUG_LEN};25 use crate::constant::{MAX_SLUG_LEN, MIN_SLUG_LEN};
26+use uuid::Uuid;
27+
26 use crate::database::{28 use crate::database::{
27 Database, create_database_sql, is_duplicate_database, migrate_school, school_pool,29 Database, create_database_sql, is_duplicate_database, migrate_school, school_pool,
28 unique_violation,30 unique_violation,
29 };31 };
32+use crate::domain::monotonic_id::next_uuid;
30 use crate::domain::timestamp::Timestamp;33 use crate::domain::timestamp::Timestamp;
31 use crate::error::{AppError, ValidationError};34 use crate::error::{AppError, ValidationError};
32 use crate::module::ModuleSet;35 use crate::module::ModuleSet;
@@ -44,12 +47,12 @@ pub const DEMO_SLUG: &str = "demo";
44 /// aimed at them.47 /// aimed at them.
45 pub const RESERVED_SLUGS: [&str; 3] = ["builder", "control", "person"];48 pub const RESERVED_SLUGS: [&str; 3] = ["builder", "control", "person"];
46 49
47-/// A school's identity everywhere it is named: the cookie prefix, the database50+/// A school's public label: the cookie prefix, the URL paths and the files
48-/// name, and the files subdirectory. The character set is deliberately the51+/// subdirectory. The character set is deliberately the intersection of what
49-/// intersection of what all three accept — lowercase alphanumerics and `-`,52+/// all three accept — lowercase alphanumerics and `-`, starting with an
50-/// starting with an alphanumeric. It is also what makes the database names53+/// alphanumeric. It is no longer the school's identity: the registry row's
51-/// injective: `school_db_name` maps `-` to `_`, and `_` is not in the slug54+/// uuid is (see [`SchoolId`]), which is why a label rename can no longer
52-/// charset, so two slugs can never collide onto one database.55+/// orphan anything structural.
53 #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, sqlx::Type)]56 #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, sqlx::Type)]
54 #[serde(transparent)]57 #[serde(transparent)]
55 #[sqlx(transparent)]58 #[sqlx(transparent)]
@@ -98,11 +101,17 @@ impl std::fmt::Display for Slug {
98 }101 }
99 }102 }
100 103
101-/// A school database's name: `{control_db}_school_{slug}`, the slug's `-`104+/// A school database's name: `{control_db}_school_{uuid hex}` — the uuid's
102-/// spelled `_` (Postgres identifiers allow `-` only quoted, and the name is105+/// lowercase hex without dashes (the contract's example:
103-/// built, not user-typed). Injective — see [`Slug`]'s charset note.106+/// `019732e3-7b00-7000-8000-00000000dead` →
104-pub fn school_db_name(control_db: &str, slug: &Slug) -> String {107+/// `…_school_019732e37b007000800000000000dead`). Fixed-width and injective:
105- format!("{}_school_{}", control_db, slug.as_str().replace('-', "_"))108+/// two uuids never share a database, and the slug appears nowhere, so a slug
109+/// rename can never orphan one. The server's 63-byte identifier cap can clip
110+/// the name's tail on deployments with a long control-database name — uuid
111+/// v7's random tail still separates schools far past any realistic registry
112+/// size, and creator and dialler truncate identically.
113+pub fn school_db_name(control_db: &str, id: Uuid) -> String {
114+ format!("{}_school_{}", control_db, id.simple())
106 }115 }
107 116
108 /// Whether a school may be reached at all. Suspension is immediate and total:117 /// Whether a school may be reached at all. Suspension is immediate and total:
@@ -137,39 +146,51 @@ impl SchoolStatus {
137 }146 }
138 }147 }
139 148
140-/// A school's id **is** its slug — the registry can never hold two rows for149+/// A school's identity inside the control plane: the registry row's uuid
141-/// one school, and the database name is derived from the same word.150+/// primary key, app-minted uuid v7. The database name and every structural
142-#[derive(Debug, Clone, PartialEq, Eq, Hash)]151+/// reference (person_school) mint from it; the slug — the public label — never.
143-pub struct SchoolId(Slug);152+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
153+pub struct SchoolId(Uuid);
144 154
145 impl SchoolId {155 impl SchoolId {
146- pub fn from_slug(slug: &Slug) -> Self {156+ /// Wrap a uuid read off a registry row — naming a school that already
147- Self(slug.clone())157+ /// exists (a test evicting the demo pool, say) rather than minting one.
158+ pub fn from_uuid(id: Uuid) -> Self {
159+ Self(id)
160+ }
161+
162+ /// The next id in write order — see
163+ /// [`crate::domain::monotonic_id::next_uuid`].
164+ pub fn generate() -> Self {
165+ Self(next_uuid())
148 }166 }
149 167
150- pub fn key(&self) -> &str {168+ pub fn uuid(self) -> Uuid {
151- self.0.as_str()169+ self.0
152 }170 }
153 }171 }
154 172
155-/// A row in the control database's school registry.
156 #[derive(Debug, Clone, sqlx::FromRow)]173 #[derive(Debug, Clone, sqlx::FromRow)]
157 pub struct School {174 pub struct School {
175+ id: Uuid,
158 slug: Slug,176 slug: Slug,
159 name: String,177 name: String,
160 status: SchoolStatus,178 status: SchoolStatus,
161 created_at: Timestamp,179 created_at: Timestamp,
162- /// Which product modules this school has bought, as their stored names.180+ /// Which product modules this school has bought, as their stored names —
163- /// Kept as strings rather than a [`ModuleSet`] so a name this binary does181+ /// joined in from `school_module` by every read below, never a column of
164- /// not know (an older deploy reading a newer row) is data to ignore, not a182+ /// `school`. Kept as strings rather than a [`ModuleSet`] so a name this
165- /// deserialization failure that would lock the school out entirely.183+ /// binary does not know (an older deploy reading a newer row) is data to
184+ /// ignore, not a deserialization failure that would lock the school out
185+ /// entirely.
166 modules: Vec<String>,186 modules: Vec<String>,
167 }187 }
168 188
169 impl School {189 impl School {
170- /// The id is the slug; rebuilt rather than stored a second copy.190+ /// The row's uuid — the identity the database name and every structural
191+ /// reference (person_school) mint from. The slug is not it.
171 pub fn get_id(&self) -> SchoolId {192 pub fn get_id(&self) -> SchoolId {
172- SchoolId::from_slug(&self.slug)193+ SchoolId(self.id)
173 }194 }
174 195
175 pub fn slug(&self) -> &Slug {196 pub fn slug(&self) -> &Slug {
@@ -207,7 +228,11 @@ impl School {
207 228
208 pub async fn read(slug: &Slug, control: &Database) -> Result<Option<School>, AppError> {229 pub async fn read(slug: &Slug, control: &Database) -> Result<Option<School>, AppError> {
209 sqlx::query_as::<_, School>(230 sqlx::query_as::<_, School>(
210- "SELECT slug, name, status, created_at, modules FROM school WHERE slug = $1",231+ "SELECT s.id, s.slug, s.name, s.status, s.created_at,
232+ COALESCE(array_agg(sm.module) FILTER (WHERE sm.module IS NOT NULL), '{}') AS modules
233+ FROM school s LEFT JOIN school_module sm ON sm.school = s.id
234+ WHERE s.slug = $1
235+ GROUP BY s.id",
211 )236 )
212 .bind(slug.as_str())237 .bind(slug.as_str())
213 .fetch_optional(control)238 .fetch_optional(control)
@@ -224,8 +249,11 @@ impl School {
224 control: &Database,249 control: &Database,
225 ) -> Result<(Vec<School>, i64), AppError> {250 ) -> Result<(Vec<School>, i64), AppError> {
226 let rows = sqlx::query_as::<_, School>(251 let rows = sqlx::query_as::<_, School>(
227- "SELECT slug, name, status, created_at, modules FROM school252+ "SELECT s.id, s.slug, s.name, s.status, s.created_at,
228- ORDER BY created_at DESC, slug DESC253+ COALESCE(array_agg(sm.module) FILTER (WHERE sm.module IS NOT NULL), '{}') AS modules
254+ FROM school s LEFT JOIN school_module sm ON sm.school = s.id
255+ GROUP BY s.id
256+ ORDER BY s.created_at DESC, s.slug DESC
229 LIMIT $1 OFFSET $2",257 LIMIT $1 OFFSET $2",
230 )258 )
231 .bind(limit)259 .bind(limit)
@@ -238,16 +266,24 @@ impl School {
238 Ok((rows, total))266 Ok((rows, total))
239 }267 }
240 268
241- /// Rename a school. The slug is immutable — it names a database and a269+ /// Rename a school — its display `name`, not its slug. The slug is
242- /// directory, so it is the one field a rename must not touch.270+ /// immutable in this cut (it is the cookie prefix and the files
271+ /// subdirectory), though it no longer names the database: the uuid does.
243 pub async fn update_name(272 pub async fn update_name(
244 slug: &Slug,273 slug: &Slug,
245 name: &str,274 name: &str,
246 control: &Database,275 control: &Database,
247 ) -> Result<School, AppError> {276 ) -> Result<School, AppError> {
248 sqlx::query_as::<_, School>(277 sqlx::query_as::<_, School>(
249- "UPDATE school SET name = $1 WHERE slug = $2278+ "WITH updated AS (
250- RETURNING slug, name, status, created_at, modules",279+ UPDATE school SET name = $1 WHERE slug = $2
280+ RETURNING id, slug, name, status, created_at
281+ )
282+ SELECT u.id, u.slug, u.name, u.status, u.created_at,
283+ COALESCE(array_agg(sm.module) FILTER (WHERE sm.module IS NOT NULL), '{}') AS modules
284+ FROM updated u
285+ LEFT JOIN school_module sm ON sm.school = u.id
286+ GROUP BY u.id, u.slug, u.name, u.status, u.created_at",
251 )287 )
252 .bind(name)288 .bind(name)
253 .bind(slug.as_str())289 .bind(slug.as_str())
@@ -261,6 +297,9 @@ impl School {
261 #[derive(Clone)]297 #[derive(Clone)]
262 pub struct Tenants {298 pub struct Tenants {
263 control: Database,299 control: Database,
300+ /// Live school pools, keyed by the school's uuid hex (no dashes — the
301+ /// same form [`school_db_name`] spells). The slug never keys it: a pool
302+ /// belongs to a school's identity, not to its current label.
264 cache: Arc<RwLock<HashMap<String, Database>>>,303 cache: Arc<RwLock<HashMap<String, Database>>>,
265 /// Dial options for the Postgres server the control pool came from — a304 /// Dial options for the Postgres server the control pool came from — a
266 /// school pool is the same dial with only the database swapped.305 /// school pool is the same dial with only the database swapped.
@@ -297,11 +336,11 @@ impl Tenants {
297 base: PgConnectOptions,336 base: PgConnectOptions,
298 control_db: String,337 control_db: String,
299 leases: crate::database::TestDatabases,338 leases: crate::database::TestDatabases,
300- prewarmed: impl IntoIterator<Item = (Slug, Database)>,339+ prewarmed: impl IntoIterator<Item = (SchoolId, Database)>,
301 ) -> Tenants {340 ) -> Tenants {
302 let cache: HashMap<String, Database> = prewarmed341 let cache: HashMap<String, Database> = prewarmed
303 .into_iter()342 .into_iter()
304- .map(|(slug, db)| (slug.as_str().to_owned(), db))343+ .map(|(id, db)| (id.uuid().simple().to_string(), db))
305 .collect();344 .collect();
306 Tenants {345 Tenants {
307 control,346 control,
@@ -346,12 +385,12 @@ impl Tenants {
346 match School::read(slug, &self.control).await? {385 match School::read(slug, &self.control).await? {
347 None => Err(AppError::Unauthorized),386 None => Err(AppError::Unauthorized),
348 Some(school) if school.status == SchoolStatus::Suspended => {387 Some(school) if school.status == SchoolStatus::Suspended => {
349- self.evict(slug).await;388+ self.evict(school.get_id()).await;
350 Err(AppError::Forbidden("school is suspended"))389 Err(AppError::Forbidden("school is suspended"))
351 }390 }
352 Some(school) => Ok(ResolvedTenant {391 Some(school) => Ok(ResolvedTenant {
353 slug: slug.clone(),392 slug: slug.clone(),
354- db: self.handle(slug).await?,393+ db: self.handle(school.get_id()).await?,
355 modules: school.modules(),394 modules: school.modules(),
356 }),395 }),
357 }396 }
@@ -364,14 +403,17 @@ impl Tenants {
364 let school = School::read(slug, &self.control)403 let school = School::read(slug, &self.control)
365 .await?404 .await?
366 .ok_or(AppError::NotFound)?;405 .ok_or(AppError::NotFound)?;
367- Ok((self.handle(slug).await?, school.status))406+ Ok((self.handle(school.get_id()).await?, school.status))
368 }407 }
369 408
370 /// Register a school and bring its database into being: registry row first409 /// Register a school and bring its database into being: registry row first
371 /// (so a lost race is a `409` and not a half-made database), then410 /// (so a lost race is a `409` and not a half-made database), then
372- /// `CREATE DATABASE`, then the school schema.411+ /// `CREATE DATABASE`, then the school schema. The caller mints the id —
412+ /// the web create path is the one minter — and it becomes the row's PK,
413+ /// the database name's source and the pool cache key.
373 pub async fn create(414 pub async fn create(
374 &self,415 &self,
416+ id: SchoolId,
375 slug: &Slug,417 slug: &Slug,
376 name: &str,418 name: &str,
377 modules: ModuleSet,419 modules: ModuleSet,
@@ -380,37 +422,53 @@ impl Tenants {
380 // every violation at once), but the registry refuses an unsatisfiable422 // every violation at once), but the registry refuses an unsatisfiable
381 // set too, so no future caller can persist one.423 // set too, so no future caller can persist one.
382 modules.validate()?;424 modules.validate()?;
425+ // The registry row and its entitlements land as one transaction: a
426+ // school row never stands without the modules its creation asked for.
427+ let mut tx = self.control.begin().await?;
383 let inserted = sqlx::query(428 let inserted = sqlx::query(
384- "INSERT INTO school (slug, name, status, created_at, modules)429+ "INSERT INTO school (id, slug, name, status, created_at)
385 VALUES ($1, $2, $3, $4, $5)",430 VALUES ($1, $2, $3, $4, $5)",
386 )431 )
432+ .bind(id.uuid())
387 .bind(slug.as_str())433 .bind(slug.as_str())
388 .bind(name)434 .bind(name)
389 .bind(SchoolStatus::Active)435 .bind(SchoolStatus::Active)
390 .bind(Timestamp::now().as_millis())436 .bind(Timestamp::now().as_millis())
391- .bind(modules.names())437+ .execute(&mut *tx)
392- .execute(&self.control)
393 .await;438 .await;
394 if let Err(err) = inserted {439 if let Err(err) = inserted {
395- // The slug is the table's only unique key, so a unique violation440+ // The slug's UNIQUE constraint (`school_slug`) is the only key a
396- // here is exactly "taken" — a rival's row, or the row already441+ // rival can collide on — a fresh uuid v7 does not repeat. So a
397- // stood. Same verdict either way, as it always was.442+ // unique violation here is exactly "taken": a rival's row, or the
443+ // row already stood. Same verdict either way, as it always was.
398 if unique_violation(&err).is_some() {444 if unique_violation(&err).is_some() {
399 return Err(AppError::Conflict("school slug already taken"));445 return Err(AppError::Conflict("school slug already taken"));
400 }446 }
401 return Err(err.into());447 return Err(err.into());
402 }448 }
449+ for name in modules.names() {
450+ sqlx::query("INSERT INTO school_module (school, module) VALUES ($1, $2)")
451+ .bind(id.uuid())
452+ .bind(name)
453+ .execute(&mut *tx)
454+ .await?;
455+ }
456+ tx.commit().await?;
403 457
404 // Everything past the registry row rolls that row back on failure:458 // Everything past the registry row rolls that row back on failure:
405 // the row is what makes the slug "taken", and a slug taken by a459 // the row is what makes the slug "taken", and a slug taken by a
406 // school that never came to exist is wedged for good. (A database460 // school that never came to exist is wedged for good. (A database
407 // created before the failure is not a wedge: the adopt branch in461 // created before the failure is not a wedge: the adopt branch in
408 // [`Self::bring_up`] picks it up, migrations being idempotent.)462 // [`Self::bring_up`] picks it up, migrations being idempotent.)
409- let db = match self.bring_up(slug).await {463+ let db = match self.bring_up(id).await {
410 Ok(db) => db,464 Ok(db) => db,
411 Err(err) => {465 Err(err) => {
412- let _ = sqlx::query("DELETE FROM school WHERE slug = $1")466+ let _ = sqlx::query("DELETE FROM school_module WHERE school = $1")
413- .bind(slug.as_str())467+ .bind(id.uuid())
468+ .execute(&self.control)
469+ .await;
470+ let _ = sqlx::query("DELETE FROM school WHERE id = $1")
471+ .bind(id.uuid())
414 .execute(&self.control)472 .execute(&self.control)
415 .await;473 .await;
416 return Err(err);474 return Err(err);
@@ -418,14 +476,14 @@ impl Tenants {
418 };476 };
419 let size = {477 let size = {
420 let mut cache = self.cache.write().expect("tenant cache lock");478 let mut cache = self.cache.write().expect("tenant cache lock");
421- cache.insert(slug.as_str().to_string(), db.clone());479+ cache.insert(id.uuid().simple().to_string(), db.clone());
422 cache.len()480 cache.len()
423 };481 };
424 Self::report_size(size);482 Self::report_size(size);
425 // A test deployment's lease learns every school the deployment483 // A test deployment's lease learns every school the deployment
426 // mints, so a school created mid-test dies with the deployment.484 // mints, so a school created mid-test dies with the deployment.
427 if let Some(leases) = &self.leases {485 if let Some(leases) = &self.leases {
428- leases.track(&school_db_name(&self.control_db, slug));486+ leases.track(&school_db_name(&self.control_db, id.uuid()));
429 }487 }
430 Ok(db)488 Ok(db)
431 }489 }
@@ -433,8 +491,8 @@ impl Tenants {
433 /// Create (or adopt) the school's database and apply the school schema to491 /// Create (or adopt) the school's database and apply the school schema to
434 /// it. Split out of [`Tenants::create`] so one `?` chain can be rolled492 /// it. Split out of [`Tenants::create`] so one `?` chain can be rolled
435 /// back as a unit.493 /// back as a unit.
436- async fn bring_up(&self, slug: &Slug) -> Result<Database, AppError> {494+ async fn bring_up(&self, id: SchoolId) -> Result<Database, AppError> {
437- let db_name = school_db_name(&self.control_db, slug);495+ let db_name = school_db_name(&self.control_db, id.uuid());
438 // `CREATE DATABASE` cannot run inside a transaction; `Pool::execute`496 // `CREATE DATABASE` cannot run inside a transaction; `Pool::execute`
439 // sends it as a bare autocommit statement. A name left over by a497 // sends it as a bare autocommit statement. A name left over by a
440 // create that died before its rollback is adopted, not fought.498 // create that died before its rollback is adopted, not fought.
@@ -459,19 +517,17 @@ impl Tenants {
459 /// Flip a school between active and suspended. Suspending also drops the517 /// Flip a school between active and suspended. Suspending also drops the
460 /// cached pool, so nothing that already resolved keeps serving.518 /// cached pool, so nothing that already resolved keeps serving.
461 pub async fn set_status(&self, slug: &Slug, status: SchoolStatus) -> Result<(), AppError> {519 pub async fn set_status(&self, slug: &Slug, status: SchoolStatus) -> Result<(), AppError> {
462- let updated = sqlx::query_as::<_, School>(520+ let updated: Option<Uuid> =
463- "UPDATE school SET status = $1 WHERE slug = $2521+ sqlx::query_scalar("UPDATE school SET status = $1 WHERE slug = $2 RETURNING id")
464- RETURNING slug, name, status, created_at, modules",522+ .bind(status)
465- )523+ .bind(slug.as_str())
466- .bind(status)524+ .fetch_optional(&self.control)
467- .bind(slug.as_str())525+ .await?;
468- .fetch_optional(&self.control)526+ let Some(id) = updated else {
469- .await?;
470- if updated.is_none() {
471 return Err(AppError::NotFound);527 return Err(AppError::NotFound);
472- }528+ };
473 if status == SchoolStatus::Suspended {529 if status == SchoolStatus::Suspended {
474- self.evict(slug).await;530+ self.evict(SchoolId(id)).await;
475 }531 }
476 Ok(())532 Ok(())
477 }533 }
@@ -482,17 +538,29 @@ impl Tenants {
482 /// stale answer.538 /// stale answer.
483 pub async fn set_modules(&self, slug: &Slug, modules: &ModuleSet) -> Result<(), AppError> {539 pub async fn set_modules(&self, slug: &Slug, modules: &ModuleSet) -> Result<(), AppError> {
484 modules.validate()?;540 modules.validate()?;
485- let updated = sqlx::query_as::<_, School>(541+ // The swap is parent + children in one transaction: take the registry
486- "UPDATE school SET modules = $1 WHERE slug = $2542+ // row's lock so racing sellers serialize, then replace the whole shelf.
487- RETURNING slug, name, status, created_at, modules",543+ let mut tx = self.control.begin().await?;
488- )544+ let id: Option<Uuid> =
489- .bind(modules.names())545+ sqlx::query_scalar("SELECT id FROM school WHERE slug = $1 FOR UPDATE")
490- .bind(slug.as_str())546+ .bind(slug.as_str())
491- .fetch_optional(&self.control)547+ .fetch_optional(&mut *tx)
492- .await?;548+ .await?;
493- if updated.is_none() {549+ let Some(id) = id else {
494 return Err(AppError::NotFound);550 return Err(AppError::NotFound);
551+ };
552+ sqlx::query("DELETE FROM school_module WHERE school = $1")
553+ .bind(id)
554+ .execute(&mut *tx)
555+ .await?;
556+ for name in modules.names() {
557+ sqlx::query("INSERT INTO school_module (school, module) VALUES ($1, $2)")
558+ .bind(id)
559+ .bind(name)
560+ .execute(&mut *tx)
561+ .await?;
495 }562 }
563+ tx.commit().await?;
496 Ok(())564 Ok(())
497 }565 }
498 566
@@ -500,26 +568,38 @@ impl Tenants {
500 /// pool. Irreversible on purpose — there is no soft-delete state, that is568 /// pool. Irreversible on purpose — there is no soft-delete state, that is
501 /// what [`SchoolStatus::Suspended`] is for.569 /// what [`SchoolStatus::Suspended`] is for.
502 pub async fn drop(&self, slug: &Slug) -> Result<(), AppError> {570 pub async fn drop(&self, slug: &Slug) -> Result<(), AppError> {
571+ // The id comes off the row: the database is named by the uuid, not
572+ // the slug. A row already gone means the goal state stands — nothing
573+ // to destroy left.
574+ let Some(school) = School::read(slug, &self.control).await? else {
575+ return Ok(());
576+ };
577+ let id = school.get_id();
503 // Close the pool first: nothing should be dialling a school whose578 // Close the pool first: nothing should be dialling a school whose
504 // database is about to go away, and `WITH (FORCE)` should never find579 // database is about to go away, and `WITH (FORCE)` should never find
505 // one of our connections to kill.580 // one of our connections to kill.
506- self.evict(slug).await;581+ self.evict(id).await;
507- // The control-plane membership rows point at the school by slug, and582+ // The control-plane rows pointing at the school by uuid — membership
508- // `ON DELETE NO ACTION` would refuse the registry delete while any583+ // and entitlement alike — go first: `ON DELETE NO ACTION` would refuse
509- // stand. Person sessions carry no school, so only memberships go —584+ // the registry delete while any stand. Person sessions carry no
510- // the persons themselves survive (a person is a global account, not585+ // school, so only memberships go — the persons themselves survive (a
511- // the school's).586+ // person is a global account, not the school's).
512- crate::db::person::delete_memberships_by_school(&self.control, slug).await?;587+ crate::db::person::delete_memberships_by_school(&self.control, &id).await?;
513- sqlx::query("DELETE FROM school WHERE slug = $1")588+ sqlx::query("DELETE FROM school_module WHERE school = $1")
514- .bind(slug.as_str())589+ .bind(id.uuid())
515 .execute(&self.control)590 .execute(&self.control)
516 .await?;591 .await?;
517- let db_name = school_db_name(&self.control_db, slug);592+ let db_name = school_db_name(&self.control_db, id.uuid());
518 sqlx::query(sqlx::AssertSqlSafe(593 sqlx::query(sqlx::AssertSqlSafe(
519 create_database_sql("DROP DATABASE IF EXISTS", &db_name) + " WITH (FORCE)",594 create_database_sql("DROP DATABASE IF EXISTS", &db_name) + " WITH (FORCE)",
520 ))595 ))
521 .execute(&self.control)596 .execute(&self.control)
522 .await?;597 .await?;
598+ sqlx::query("DELETE FROM school WHERE id = $1")
599+ .bind(id.uuid())
600+ .execute(&self.control)
601+ .await?;
602+
523 Ok(())603 Ok(())
524 }604 }
525 605
@@ -530,43 +610,40 @@ impl Tenants {
530 /// re-reads the registry row on every request, so a suspension is refused610 /// re-reads the registry row on every request, so a suspension is refused
531 /// whether or not a pool survived it. [`Tenants::drop`], which does mean611 /// whether or not a pool survived it. [`Tenants::drop`], which does mean
532 /// to destroy the store, evicts unconditionally.612 /// to destroy the store, evicts unconditionally.
533- pub async fn evict(&self, slug: &Slug) {613+ pub async fn evict(&self, id: SchoolId) {
534- if let Some(pool) = self.forget(slug) {614+ if let Some(pool) = self.forget(id) {
535 pool.close().await;615 pool.close().await;
536 }616 }
537 }617 }
538 618
539- fn forget(&self, slug: &Slug) -> Option<Database> {619+ fn forget(&self, id: SchoolId) -> Option<Database> {
620+ let key = id.uuid().simple().to_string();
540 let (removed, size) = {621 let (removed, size) = {
541 let mut cache = self.cache.write().expect("tenant cache lock");622 let mut cache = self.cache.write().expect("tenant cache lock");
542- (cache.remove(slug.as_str()), cache.len())623+ (cache.remove(&key), cache.len())
543 };624 };
544 if removed.is_some() {625 if removed.is_some() {
545- tracing::info!(school = %slug, "tenant pool evicted");626+ tracing::info!(school = %id.uuid(), "tenant pool evicted");
546 Self::report_size(size);627 Self::report_size(size);
547 }628 }
548 removed629 removed
549 }630 }
550 631
551 /// The cached pool, or a freshly dialled one.632 /// The cached pool, or a freshly dialled one.
552- async fn handle(&self, slug: &Slug) -> Result<Database, AppError> {633+ async fn handle(&self, id: SchoolId) -> Result<Database, AppError> {
553- if let Some(db) = self634+ let key = id.uuid().simple().to_string();
554- .cache635+ if let Some(db) = self.cache.read().expect("tenant cache lock").get(&key) {
555- .read()
556- .expect("tenant cache lock")
557- .get(slug.as_str())
558- {
559 return Ok(db.clone());636 return Ok(db.clone());
560 }637 }
561- let db = school_pool(&self.base, &school_db_name(&self.control_db, slug)).await?;638+ let db = school_pool(&self.base, &school_db_name(&self.control_db, id.uuid())).await?;
562 // Losing the race here is harmless — both pools are equivalent — but639 // Losing the race here is harmless — both pools are equivalent — but
563 // the winner is kept so two requests never diverge onto two pools.640 // the winner is kept so two requests never diverge onto two pools.
564 let (db, size) = {641 let (db, size) = {
565 let mut cache = self.cache.write().expect("tenant cache lock");642 let mut cache = self.cache.write().expect("tenant cache lock");
566- let db = cache.entry(slug.as_str().to_string()).or_insert(db).clone();643+ let db = cache.entry(key).or_insert(db).clone();
567 (db, cache.len())644 (db, cache.len())
568 };645 };
569- tracing::info!(school = %slug, "tenant pool opened");646+ tracing::info!(school = %id.uuid(), "tenant pool opened");
570 Self::report_size(size);647 Self::report_size(size);
571 Ok(db)648 Ok(db)
572 }649 }
@@ -583,9 +660,6 @@ impl Tenants {
583 mod tests {660 mod tests {
584 use super::*;661 use super::*;
585 662
586- fn slug(value: &str) -> Slug {
587- Slug::try_new(value).expect(value)
588- }
589 663
590 #[test]664 #[test]
591 fn a_slug_names_a_school_and_nothing_reserved() {665 fn a_slug_names_a_school_and_nothing_reserved() {
@@ -611,35 +685,30 @@ mod tests {
611 }685 }
612 686
613 /// The database-per-school model lives or dies by this mapping: two687 /// The database-per-school model lives or dies by this mapping: two
614- /// schools sharing a database name would share every row in it. `-`688+ /// schools sharing a database name would share every row in it. The name
615- /// becoming `_` is the only rewrite, and `_` is not in the slug charset,689+ /// now mints from the school's uuid — lowercase hex without dashes, fixed
616- /// so no two slugs can land on one name.690+ /// width — so it is injective by construction, and the slug appears
691+ /// nowhere: a slug rename can never orphan a database.
617 #[test]692 #[test]
618 fn school_db_names_are_injective() {693 fn school_db_names_are_injective() {
619 let control = "hezarfen_control";694 let control = "hezarfen_control";
695+ // The contract's example, pinned byte for byte.
696+ let id = Uuid::try_parse("019732e3-7b00-7000-8000-00000000dead").unwrap();
620 assert_eq!(697 assert_eq!(
621- school_db_name(control, &slug("demo")),698+ school_db_name(control, id),
622- "hezarfen_control_school_demo"699+ "hezarfen_control_school_019732e37b007000800000000000dead"
623 );700 );
624- assert_eq!(701+ // Two uuids never collide onto one database, and no slug is in the
625- school_db_name(control, &slug("ata-koleji")),702+ // name — not even the slug the uuid was minted for.
626- "hezarfen_control_school_ata_koleji"703+ let other = Uuid::try_parse("019732e3-7b00-7000-8000-00000000beef").unwrap();
704+ assert_ne!(
705+ school_db_name(control, id),
706+ school_db_name(control, other),
707+ "two uuids must not share a database"
627 );708 );
628- // Slugs are at least two characters, so the shortest pair stands in709+ assert!(!school_db_name(control, id).contains("demo"));
629- // for the old single-letter probe.
630- for a in ["ab", "a-b", "abc", "a1b", "1a", "x-y-z"] {
631- for b in ["ab", "a-b", "abc", "a1b", "1a", "x-y-z"] {
632- if a != b {
633- assert_ne!(
634- school_db_name(control, &slug(a)),
635- school_db_name(control, &slug(b)),
636- "{a:?} and {b:?} must not share a database"
637- );
638- }
639- }
640- }
641 // The control database's own name is never a school's name: the710 // The control database's own name is never a school's name: the
642 // suffix keeps the namespaces apart.711 // suffix keeps the namespaces apart.
643- assert_ne!(school_db_name(control, &slug("school")), control);712+ assert_ne!(school_db_name(control, id), control);
644 }713 }
645 }714 }
src/web/builder.rsmodified+12 -6
@@ -34,7 +34,7 @@ use crate::module::{Module, ModuleSet, Package};
34 use crate::rate_limit::{RateLimitConfig, RateLimiter};34 use crate::rate_limit::{RateLimitConfig, RateLimiter};
35 use crate::service;35 use crate::service;
36 use crate::state::AppState;36 use crate::state::AppState;
37-use crate::tenant::{School, SchoolStatus, Slug};37+use crate::tenant::{School, SchoolId, SchoolStatus, Slug};
38 use crate::validate::validate_required;38 use crate::validate::validate_required;
39 use crate::web::tenant_state::school_files_path;39 use crate::web::tenant_state::school_files_path;
40 40
@@ -124,8 +124,9 @@ impl SchoolResponse {
124 #[derive(Deserialize, ToSchema)]124 #[derive(Deserialize, ToSchema)]
125 struct CreateSchool {125 struct CreateSchool {
126 /// Lowercase `a-z`, `0-9` and `-`, starting with a letter or digit. Names126 /// Lowercase `a-z`, `0-9` and `-`, starting with a letter or digit. Names
127- /// the school's database, its blob directory and its cookie prefix, so it127+ /// the school's blob directory and its cookie prefix. It is the school's
128- /// is immutable once taken.128+ /// public label, not its identity — the uuid minted at create time is —
129+ /// and it must stay unique across the deployment.
129 #[schema(example = "ata-koleji", min_length = 2, max_length = 32)]130 #[schema(example = "ata-koleji", min_length = 2, max_length = 32)]
130 slug: String,131 slug: String,
131 #[schema(example = "Ata Koleji", max_length = 120)]132 #[schema(example = "Ata Koleji", max_length = 120)]
@@ -369,7 +370,11 @@ async fn create_school(
369 ));370 ));
370 }371 }
371 372
372- let db = st.tenants.create(&slug, &name, modules).await?;373+ // The school's uuid is minted here, on the one path that creates schools:
374+ // it becomes the registry row's PK and the database name's source, and
375+ // the slug stays a label the wire keeps answering with.
376+ let id = SchoolId::generate();
377+ let db = st.tenants.create(id, &slug, &name, modules).await?;
373 let seeded = async {378 let seeded = async {
374 crate::service::user::create_with_role(&db, username, Some(*person.get_id()), Role::Admin)379 crate::service::user::create_with_role(&db, username, Some(*person.get_id()), Role::Admin)
375 .await?;380 .await?;
@@ -444,8 +449,9 @@ async fn get_school(
444 }449 }
445 450
446 /// Rename a school and/or flip it between `active` and `suspended`. Omitted451 /// Rename a school and/or flip it between `active` and `suspended`. Omitted
447-/// fields keep their value. The slug itself is immutable — it names a database452+/// fields keep their value. The slug itself is immutable in this cut — it is
448-/// and a directory.453+/// the cookie prefix and the blob directory — though it no longer names the
454+/// database (the school's uuid does); a rename API is not offered yet.
449 ///455 ///
450 /// Suspending is immediate and total for the school's own users: their next456 /// Suspending is immediate and total for the school's own users: their next
451 /// request is a `403`, live session or not.457 /// request is a `403`, live session or not.
src/web/course_notes.rsmodified+17 -16
@@ -56,11 +56,12 @@ pub fn routes() -> OpenApiRouter<AppState> {
56 56
57 /// The note plus its course, or a 404 — every entity handler here gates on57 /// The note plus its course, or a 404 — every entity handler here gates on
58 /// the parent course, so they always travel together.58 /// the parent course, so they always travel together.
59-async fn note_with_course(id: &str, db: &Database) -> Result<(CourseNote, Course), AppError> {59+async fn note_with_course(id: String, db: Database) -> Result<(CourseNote, Course), AppError> {
60- let note = service::course_note::read(db, &CourseNoteId::from_key(id))60+ let id = CourseNoteId::from_key(&id);
61+ let note = service::course_note::read(&db, &id)
61 .await?62 .await?
62 .ok_or(AppError::NotFound)?;63 .ok_or(AppError::NotFound)?;
63- let course = crate::service::course::read(db, note.get_course())64+ let course = crate::service::course::read(&db, note.get_course())
64 .await?65 .await?
65 .ok_or(AppError::NotFound)?;66 .ok_or(AppError::NotFound)?;
66 Ok((note, course))67 Ok((note, course))
@@ -214,7 +215,7 @@ async fn get_one(
214 CurrentUser(user): CurrentUser,215 CurrentUser(user): CurrentUser,
215 Path(id): Path<String>,216 Path(id): Path<String>,
216 ) -> Result<Json<CourseNoteResponse>, AppError> {217 ) -> Result<Json<CourseNoteResponse>, AppError> {
217- let (note, course) = note_with_course(&id, &st.db).await?;218+ let (note, course) = note_with_course(id.clone(), st.db.clone()).await?;
218 if !can_view_course(&course, &user, &st.db).await? {219 if !can_view_course(&course, &user, &st.db).await? {
219 return Err(AppError::Forbidden(220 return Err(AppError::Forbidden(
220 "only enrolled users, the course creator, an assigned teacher, or a manager/admin can view this course note",221 "only enrolled users, the course creator, an assigned teacher, or a manager/admin can view this course note",
@@ -249,7 +250,7 @@ async fn update(
249 Path(id): Path<String>,250 Path(id): Path<String>,
250 Json(req): Json<UpdateCourseNote>,251 Json(req): Json<UpdateCourseNote>,
251 ) -> Result<Json<CourseNoteResponse>, AppError> {252 ) -> Result<Json<CourseNoteResponse>, AppError> {
252- let (note, course) = note_with_course(&id, &st.db).await?;253+ let (note, course) = note_with_course(id.clone(), st.db.clone()).await?;
253 if !can_manage_course(&course, &user) {254 if !can_manage_course(&course, &user) {
254 return Err(AppError::Forbidden(255 return Err(AppError::Forbidden(
255 "only the course creator, an assigned teacher, or a manager/admin can edit this course note",256 "only the course creator, an assigned teacher, or a manager/admin can edit this course note",
@@ -295,7 +296,7 @@ async fn delete_one(
295 RequireTeacher(user): RequireTeacher,296 RequireTeacher(user): RequireTeacher,
296 Path(id): Path<String>,297 Path(id): Path<String>,
297 ) -> Result<StatusCode, AppError> {298 ) -> Result<StatusCode, AppError> {
298- let (note, course) = note_with_course(&id, &st.db).await?;299+ let (note, course) = note_with_course(id.clone(), st.db.clone()).await?;
299 if !can_manage_course(&course, &user) {300 if !can_manage_course(&course, &user) {
300 return Err(AppError::Forbidden(301 return Err(AppError::Forbidden(
301 "only the course creator, an assigned teacher, or a manager/admin can delete this course note",302 "only the course creator, an assigned teacher, or a manager/admin can delete this course note",
@@ -373,7 +374,7 @@ async fn upload_file(
373 Path(id): Path<String>,374 Path(id): Path<String>,
374 mut multipart: Multipart,375 mut multipart: Multipart,
375 ) -> Result<(StatusCode, Json<CourseNoteFileResponse>), AppError> {376 ) -> Result<(StatusCode, Json<CourseNoteFileResponse>), AppError> {
376- let (note, course) = note_with_course(&id, &st.db).await?;377+ let (note, course) = note_with_course(id.clone(), st.db.clone()).await?;
377 if !can_manage_course(&course, &user) {378 if !can_manage_course(&course, &user) {
378 return Err(AppError::Forbidden(379 return Err(AppError::Forbidden(
379 "only the course creator, an assigned teacher, or a manager/admin can add a file to this course note",380 "only the course creator, an assigned teacher, or a manager/admin can add a file to this course note",
@@ -436,7 +437,7 @@ async fn list_files(
436 Query(page): Query<PageParams>,437 Query(page): Query<PageParams>,
437 ) -> Result<Json<Page<CourseNoteFileResponse>>, AppError> {438 ) -> Result<Json<Page<CourseNoteFileResponse>>, AppError> {
438 let (limit, offset) = page.resolve()?;439 let (limit, offset) = page.resolve()?;
439- let (note, course) = note_with_course(&id, &st.db).await?;440+ let (note, course) = note_with_course(id.clone(), st.db.clone()).await?;
440 if !can_view_course(&course, &user, &st.db).await? {441 if !can_view_course(&course, &user, &st.db).await? {
441 return Err(AppError::Forbidden(442 return Err(AppError::Forbidden(
442 "only enrolled users, the course creator, an assigned teacher, or a manager/admin can view this course note's files",443 "only enrolled users, the course creator, an assigned teacher, or a manager/admin can view this course note's files",
@@ -471,7 +472,7 @@ async fn download_file(
471 CurrentUser(user): CurrentUser,472 CurrentUser(user): CurrentUser,
472 Path((id, file_id)): Path<(String, String)>,473 Path((id, file_id)): Path<(String, String)>,
473 ) -> Result<Response, AppError> {474 ) -> Result<Response, AppError> {
474- let (note, course) = note_with_course(&id, &st.db).await?;475+ let (note, course) = note_with_course(id.clone(), st.db.clone()).await?;
475 if !can_view_course(&course, &user, &st.db).await? {476 if !can_view_course(&course, &user, &st.db).await? {
476 return Err(AppError::Forbidden(477 return Err(AppError::Forbidden(
477 "only enrolled users, the course creator, an assigned teacher, or a manager/admin can download this course note's files",478 "only enrolled users, the course creator, an assigned teacher, or a manager/admin can download this course note's files",
@@ -533,7 +534,7 @@ async fn delete_file(
533 RequireTeacher(user): RequireTeacher,534 RequireTeacher(user): RequireTeacher,
534 Path((id, file_id)): Path<(String, String)>,535 Path((id, file_id)): Path<(String, String)>,
535 ) -> Result<StatusCode, AppError> {536 ) -> Result<StatusCode, AppError> {
536- let (note, course) = note_with_course(&id, &st.db).await?;537+ let (note, course) = note_with_course(id.clone(), st.db.clone()).await?;
537 if !can_manage_course(&course, &user) {538 if !can_manage_course(&course, &user) {
538 return Err(AppError::Forbidden(539 return Err(AppError::Forbidden(
539 "only the course creator, an assigned teacher, or a manager/admin can delete this course note's files",540 "only the course creator, an assigned teacher, or a manager/admin can delete this course note's files",
@@ -547,10 +548,10 @@ async fn delete_file(
547 )548 )
548 .await?549 .await?
549 .ok_or(AppError::NotFound)?;550 .ok_or(AppError::NotFound)?;
550- // Drop every output built from this file before the file itself, so a551+ // Drop every link citing this file before the file itself — the file
551- // stale index cannot outlive its source in a deployment with no AI service552+ // row refuses to go while one stands — so a failure here leaves the file
552- // at all, and a failure here leaves the file whole instead of stranding its553+ // whole instead of stranding its blob; the re-index rebuilds the
553- // blob; the re-index rebuilds from what is left, if a service is connected.554+ // outputs from what is left, if a service is connected.
554 service::rag_output::delete_with_source(&st.db, file.get_id()).await?;555 service::rag_output::delete_with_source(&st.db, file.get_id()).await?;
555 let file = service::course_note_file::delete(&st.db, file).await?;556 let file = service::course_note_file::delete(&st.db, file).await?;
556 remove_blob(&st.files_path, &file.get_id().key()).await;557 remove_blob(&st.files_path, &file.get_id().key()).await;
@@ -615,7 +616,7 @@ async fn list_rag(
615 Query(page): Query<PageParams>,616 Query(page): Query<PageParams>,
616 ) -> Result<Json<Page<RagOutputResponse>>, AppError> {617 ) -> Result<Json<Page<RagOutputResponse>>, AppError> {
617 let (limit, offset) = page.resolve()?;618 let (limit, offset) = page.resolve()?;
618- let (note, course) = note_with_course(&id, &st.db).await?;619+ let (note, course) = note_with_course(id.clone(), st.db.clone()).await?;
619 if !can_view_course(&course, &user, &st.db).await? {620 if !can_view_course(&course, &user, &st.db).await? {
620 return Err(AppError::Forbidden(621 return Err(AppError::Forbidden(
621 "only enrolled users, the course creator, an assigned teacher, or a manager/admin can view this course note's AI outputs",622 "only enrolled users, the course creator, an assigned teacher, or a manager/admin can view this course note's AI outputs",
@@ -652,7 +653,7 @@ async fn delete_rag(
652 RequireTeacher(user): RequireTeacher,653 RequireTeacher(user): RequireTeacher,
653 Path((id, output_id)): Path<(String, String)>,654 Path((id, output_id)): Path<(String, String)>,
654 ) -> Result<StatusCode, AppError> {655 ) -> Result<StatusCode, AppError> {
655- let (note, course) = note_with_course(&id, &st.db).await?;656+ let (note, course) = note_with_course(id.clone(), st.db.clone()).await?;
656 if !can_manage_course(&course, &user) {657 if !can_manage_course(&course, &user) {
657 return Err(AppError::Forbidden(658 return Err(AppError::Forbidden(
658 "only the course creator, an assigned teacher, or a manager/admin can delete this course note's AI outputs",659 "only the course creator, an assigned teacher, or a manager/admin can delete this course note's AI outputs",
tests/ai_bridge.rsmodified+6 -1
@@ -1784,7 +1784,12 @@ async fn an_index_dispatch_names_the_notes_own_school_and_stores_the_answer_ther
1784 let (app, demo_db, tenants) = common::app_with_ai_tenants(Some(bridge.clone())).await;1784 let (app, demo_db, tenants) = common::app_with_ai_tenants(Some(bridge.clone())).await;
1785 let beta = Slug::try_new("beta").unwrap();1785 let beta = Slug::try_new("beta").unwrap();
1786 let beta_db = tenants1786 let beta_db = tenants
1787- .create(&beta, "Beta College", ModuleSet::all())1787+ .create(
1788+ hezarfen_backend::tenant::SchoolId::generate(),
1789+ &beta,
1790+ "Beta College",
1791+ ModuleSet::all(),
1792+ )
1788 .await1793 .await
1789 .expect("beta");1794 .expect("beta");
1790 1795
tests/ai_protocol.rsmodified+1 -0
@@ -1208,6 +1208,7 @@ async fn two_schools(bridge: &AiBridge) -> (axum::Router, Tenants, String, Strin
1208 let (app, demo_db, tenants) = common::app_with_ai_tenants(Some(bridge.clone())).await;1208 let (app, demo_db, tenants) = common::app_with_ai_tenants(Some(bridge.clone())).await;
1209 let beta_db = tenants1209 let beta_db = tenants
1210 .create(1210 .create(
1211+ hezarfen_backend::tenant::SchoolId::generate(),
1211 &Slug::try_new("beta").unwrap(),1212 &Slug::try_new("beta").unwrap(),
1212 "Beta College",1213 "Beta College",
1213 ModuleSet::all(),1214 ModuleSet::all(),
tests/builder_api.rsmodified+9 -5
@@ -2082,11 +2082,15 @@ async fn probe_a_refused_batch_leaves_the_row_byte_identical() {
2082 let builder = builder_login(&app).await;2082 let builder = builder_login(&app).await;
2083 2083
2084 async fn raw_row(tenants: &Tenants) -> Vec<String> {2084 async fn raw_row(tenants: &Tenants) -> Vec<String> {
2085- sqlx::query_scalar("SELECT modules FROM school WHERE slug = $1")2085+ sqlx::query_scalar(
2086- .bind(DEMO_SLUG)2086+ "SELECT sm.module FROM school_module sm
2087- .fetch_one(tenants.control())2087+ JOIN school s ON s.id = sm.school
2088- .await2088+ WHERE s.slug = $1 ORDER BY sm.module",
2089- .expect("raw read")2089+ )
2090+ .bind(DEMO_SLUG)
2091+ .fetch_all(tenants.control())
2092+ .await
2093+ .expect("raw read")
2090 }2094 }
2091 2095
2092 let before = raw_row(&tenants).await;2096 let before = raw_row(&tenants).await;
tests/common/mod.rsmodified+1 -0
@@ -641,6 +641,7 @@ pub async fn deployment_with(schools: &[(&str, &str)]) -> TestDeployment {
641 for (slug, name) in schools {641 for (slug, name) in schools {
642 tenants642 tenants
643 .create(643 .create(
644+ hezarfen_backend::tenant::SchoolId::generate(),
644 &Slug::try_new(slug).expect("a school slug"),645 &Slug::try_new(slug).expect("a school slug"),
645 name,646 name,
646 ModuleSet::all(),647 ModuleSet::all(),
tests/integration.rsmodified+39 -9
@@ -6638,8 +6638,14 @@ async fn db_down_refuses_before_touching_the_database() {
6638 6638
6639 // Recovery is eviction: the dead pool leaves the cache, the next request6639 // Recovery is eviction: the dead pool leaves the cache, the next request
6640 // dials fresh — and the refused write is still not in the database.6640 // dials fresh — and the refused write is still not in the database.
6641+ let demo_id: Uuid = sqlx::query_scalar("SELECT id FROM school WHERE slug = 'demo'")
6642+ .fetch_one(tenants.control())
6643+ .await
6644+ .expect("demo id");
6641 let slug = Slug::try_new("demo").expect("slug");6645 let slug = Slug::try_new("demo").expect("slug");
6642- tenants.evict(&slug).await;6646+ tenants
6647+ .evict(hezarfen_backend::tenant::SchoolId::from_uuid(demo_id))
6648+ .await;
6643 let live = tenants.get(&slug).await.expect("redial after eviction");6649 let live = tenants.get(&slug).await.expect("redial after eviction");
6644 assert_eq!(6650 assert_eq!(
6645 count_rows(&live, "app_user").await,6651 count_rows(&live, "app_user").await,
@@ -27406,7 +27412,12 @@ async fn two_schools() -> (
27406 let (app, db_a, tenants) = common::app_and_tenants().await;27412 let (app, db_a, tenants) = common::app_and_tenants().await;
27407 let slug_b = Slug::try_new("beta").expect("slug");27413 let slug_b = Slug::try_new("beta").expect("slug");
27408 let db_b = tenants27414 let db_b = tenants
27409- .create(&slug_b, "Beta Koleji", ModuleSet::all())27415+ .create(
27416+ hezarfen_backend::tenant::SchoolId::generate(),
27417+ &slug_b,
27418+ "Beta Koleji",
27419+ ModuleSet::all(),
27420+ )
27410 .await27421 .await
27411 .expect("school B");27422 .expect("school B");
27412 (app, db_a, db_b, tenants)27423 (app, db_a, db_b, tenants)
@@ -28475,7 +28486,8 @@ async fn remote_probe_remote_mode_keeps_two_schools_apart() {
28475 // -------------------------------------------------------------------------28486 // -------------------------------------------------------------------------
28476 28487
28477 /// The server's database list, off the control handle: the control database28488 /// The server's database list, off the control handle: the control database
28478-/// itself plus every school database, named `{control}_school_{slug}`.28489+/// itself plus every school database, named `{control}_school_{uuid hex}` —
28490+/// the school's uuid, never its slug.
28479 async fn namespace_databases(tenants: &Tenants) -> Vec<String> {28491 async fn namespace_databases(tenants: &Tenants) -> Vec<String> {
28480 let control = tenants.control();28492 let control = tenants.control();
28481 let control_db: String = sqlx::query_scalar("SELECT current_database()")28493 let control_db: String = sqlx::query_scalar("SELECT current_database()")
@@ -28495,6 +28507,22 @@ async fn namespace_databases(tenants: &Tenants) -> Vec<String> {
28495 names28507 names
28496 }28508 }
28497 28509
28510+/// A school database's name, read off the registry: the control database's
28511+/// name plus the school's uuid in lowercase hex, no dashes. Postgres
28512+/// truncates identifiers at 63 bytes (NAMEDATALEN - 1), and a test control
28513+/// database's `heztest_` prefix runs the name one character past that — the
28514+/// server creates and dials the truncated name on both sides, so the
28515+/// expectation truncates with it.
28516+async fn school_db_by_slug(control_db: &str, slug: &str, control: &sqlx::PgPool) -> String {
28517+ let id: Uuid = sqlx::query_scalar("SELECT id FROM school WHERE slug = $1")
28518+ .bind(slug)
28519+ .fetch_one(control)
28520+ .await
28521+ .expect("school id");
28522+ let name = format!("{control_db}_school_{}", id.simple());
28523+ name.chars().take(63).collect()
28524+}
28525+
28498 /// A school **is** a database, so the server must hold exactly the created28526 /// A school **is** a database, so the server must hold exactly the created
28499 /// schools plus the control database — and `DELETE /schools/{slug}` must drop28527 /// schools plus the control database — and `DELETE /schools/{slug}` must drop
28500 /// the database, not merely delete the registry row.28528 /// the database, not merely delete the registry row.
@@ -28505,13 +28533,13 @@ async fn remote_probe_a_school_is_a_database_and_delete_removes_it() {
28505 .fetch_one(d.tenants.control())28533 .fetch_one(d.tenants.control())
28506 .await28534 .await
28507 .expect("control name");28535 .expect("control name");
28536+ let demo_db = school_db_by_slug(&control_db, DEMO_SLUG, d.tenants.control()).await;
28537+ let beta_db = school_db_by_slug(&control_db, "beta", d.tenants.control()).await;
28538+ let mut expected = vec![control_db.clone(), demo_db.clone(), beta_db];
28539+ expected.sort();
28508 assert_eq!(28540 assert_eq!(
28509 namespace_databases(&d.tenants).await,28541 namespace_databases(&d.tenants).await,
28510- vec![28542+ expected,
28511- control_db.clone(),
28512- format!("{control_db}_school_beta"),
28513- format!("{control_db}_school_demo"),
28514- ],
28515 "the server holds exactly the two schools and the control database"28543 "the server holds exactly the two schools and the control database"
28516 );28544 );
28517 28545
@@ -28535,9 +28563,11 @@ async fn remote_probe_a_school_is_a_database_and_delete_removes_it() {
28535 28563
28536 let res = send(&d.app, "DELETE", "/schools/beta", Some(&builder), None).await;28564 let res = send(&d.app, "DELETE", "/schools/beta", Some(&builder), None).await;
28537 assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body);28565 assert_eq!(res.status, StatusCode::NO_CONTENT, "{}", res.body);
28566+ let mut expected = vec![control_db.clone(), demo_db];
28567+ expected.sort();
28538 assert_eq!(28568 assert_eq!(
28539 namespace_databases(&d.tenants).await,28569 namespace_databases(&d.tenants).await,
28540- vec![control_db.clone(), format!("{control_db}_school_demo")],28570+ expected,
28541 "DELETE /schools/beta dropped beta's database"28571 "DELETE /schools/beta dropped beta's database"
28542 );28572 );
28543 }28573 }
tests/persistence.rsmodified+58 -42
@@ -571,10 +571,12 @@ async fn settings_slots_without_a_serving_minute_still_patch() {
571 &app,571 &app,
572 "PATCH",572 "PATCH",
573 "/settings",573 "/settings",
574- Some(&send(&app, "POST", "/auth/login", None, Some(login.clone()))574+ Some(
575- .await575+ &send(&app, "POST", "/auth/login", None, Some(login.clone()))
576- .cookie576+ .await
577- .unwrap()),577+ .cookie
578+ .unwrap(),
579+ ),
578 Some(json!({ "meal_slots": [{ "name": "lunch" }] })),580 Some(json!({ "meal_slots": [{ "name": "lunch" }] })),
579 )581 )
580 .await;582 .await;
@@ -810,22 +812,19 @@ async fn boards_and_their_strokes_survive_remigration() {
810 // the rows: a re-migration must not have reset either of them.812 // the rows: a re-migration must not have reset either of them.
811 use sqlx::Row as _;813 use sqlx::Row as _;
812 let board_id = hezarfen_backend::domain::board::BoardId::from_key(&board);814 let board_id = hezarfen_backend::domain::board::BoardId::from_key(&board);
813- let row = sqlx::query(815+ let row = sqlx::query("SELECT epoch_stroke_count, total_stroke_count FROM board WHERE id = $1")
814- "SELECT epoch_stroke_count, total_stroke_count FROM board WHERE id = $1",816+ .bind(board_id.uuid())
815- )817+ .fetch_one(&db)
816- .bind(board_id.uuid())818+ .await
817- .fetch_one(&db)819+ .expect("board row");
818- .await
819- .expect("board row");
820 let epoch_count: i64 = row.try_get(0).unwrap();820 let epoch_count: i64 = row.try_get(0).unwrap();
821 let total_count: i64 = row.try_get(1).unwrap();821 let total_count: i64 = row.try_get(1).unwrap();
822 let user_id = hezarfen_backend::domain::user::UserId::from_key(&ali_id);822 let user_id = hezarfen_backend::domain::user::UserId::from_key(&ali_id);
823- let board_count: i64 =823+ let board_count: i64 = sqlx::query_scalar("SELECT board_count FROM app_user WHERE id = $1")
824- sqlx::query_scalar("SELECT board_count FROM app_user WHERE id = $1")824+ .bind(user_id.uuid())
825- .bind(user_id.uuid())825+ .fetch_one(&db)
826- .fetch_one(&db)826+ .await
827- .await827+ .expect("creator row");
828- .expect("creator row");
829 assert_eq!(828 assert_eq!(
830 (epoch_count, total_count, board_count),829 (epoch_count, total_count, board_count),
831 (1, 4, 1),830 (1, 4, 1),
@@ -859,7 +858,12 @@ async fn an_empty_module_list_survives_a_second_boot() {
859 let tenants = database::init_test_tenants().await;858 let tenants = database::init_test_tenants().await;
860 let slug = Slug::try_new("bare").unwrap();859 let slug = Slug::try_new("bare").unwrap();
861 tenants860 tenants
862- .create(&slug, "Bare School", ModuleSet::empty())861+ .create(
862+ hezarfen_backend::tenant::SchoolId::generate(),
863+ &slug,
864+ "Bare School",
865+ ModuleSet::empty(),
866+ )
863 .await867 .await
864 .expect("a school with nothing switched on");868 .expect("a school with nothing switched on");
865 869
@@ -867,18 +871,17 @@ async fn an_empty_module_list_survives_a_second_boot() {
867 .await871 .await
868 .expect("a second boot");872 .expect("a second boot");
869 873
870- use sqlx::Row as _;874+ let stored: i64 = sqlx::query_scalar(
871- let stored: Option<Vec<String>> = sqlx::query(875+ "SELECT count(*) FROM school_module sm
872- "SELECT modules FROM school WHERE slug = $1",876+ JOIN school s ON s.id = sm.school
877+ WHERE s.slug = $1",
873 )878 )
874 .bind(slug.as_str())879 .bind(slug.as_str())
875- .fetch_optional(tenants.control())880+ .fetch_one(tenants.control())
876 .await881 .await
877- .expect("read the row back")882+ .expect("read the row back");
878- .map(|row| row.try_get::<Vec<String>, _>(0).unwrap());
879 assert_eq!(883 assert_eq!(
880- stored.unwrap_or_default(),884+ stored, 0,
881- Vec::<String>::new(),
882 "an empty list is a decision, never a hole to fill"885 "an empty list is a decision, never a hole to fill"
883 );886 );
884 }887 }
@@ -901,7 +904,12 @@ async fn probe_control_migration_is_idempotent_over_aged_rows() {
901 ("narrow", "Narrow School", narrow),904 ("narrow", "Narrow School", narrow),
902 ] {905 ] {
903 tenants906 tenants
904- .create(&Slug::try_new(slug).unwrap(), name, modules)907+ .create(
908+ hezarfen_backend::tenant::SchoolId::generate(),
909+ &Slug::try_new(slug).unwrap(),
910+ name,
911+ modules,
912+ )
905 .await913 .await
906 .unwrap_or_else(|err| panic!("create {slug}: {err}"));914 .unwrap_or_else(|err| panic!("create {slug}: {err}"));
907 }915 }
@@ -921,21 +929,29 @@ async fn probe_control_migration_is_idempotent_over_aged_rows() {
921 assert_eq!(before, after, "a re-run must not disturb school rows");929 assert_eq!(before, after, "a re-run must not disturb school rows");
922 }930 }
923 931
924-/// Every school row as `(slug, name, status, modules)`, in slug order.932+/// Every school row as `(slug, name, status, modules)`, in slug order — the
933+/// modules aggregated off the `school_module` child table, as every read path
934+/// assembles them.
925 async fn school_rows(control: &Database) -> Vec<(String, String, String, Vec<String>)> {935 async fn school_rows(control: &Database) -> Vec<(String, String, String, Vec<String>)> {
926 use sqlx::Row as _;936 use sqlx::Row as _;
927- sqlx::query("SELECT slug, name, status, modules FROM school ORDER BY slug")937+ sqlx::query(
928- .fetch_all(control)938+ "SELECT s.slug, s.name, s.status,
929- .await939+ COALESCE(array_agg(sm.module) FILTER (WHERE sm.module IS NOT NULL), '{}')
930- .expect("school rows")940+ FROM school s LEFT JOIN school_module sm ON sm.school = s.id
931- .into_iter()941+ GROUP BY s.id
932- .map(|row| {942+ ORDER BY s.slug",
933- (943+ )
934- row.try_get::<String, _>(0).unwrap(),944+ .fetch_all(control)
935- row.try_get::<String, _>(1).unwrap(),945+ .await
936- row.try_get::<String, _>(2).unwrap(),946+ .unwrap()
937- row.try_get::<Vec<String>, _>(3).unwrap(),947+ .into_iter()
938- )948+ .map(|row| {
939- })949+ (
940- .collect()950+ row.try_get::<String, _>(0).unwrap(),
951+ row.try_get::<String, _>(1).unwrap(),
952+ row.try_get::<String, _>(2).unwrap(),
953+ row.try_get::<Vec<String>, _>(3).unwrap(),
954+ )
955+ })
956+ .collect()
941 }957 }
tests/regress_blueprints.rsmodified+46 -23
@@ -74,7 +74,9 @@ async fn source_of(class: &str, course: &str, db: &Database) -> Option<String> {
74 /// Does that grade's template still name that course, in the store?74 /// Does that grade's template still name that course, in the store?
75 async fn templated(grade: &str, course: &str, db: &Database) -> bool {75 async fn templated(grade: &str, course: &str, db: &Database) -> bool {
76 sqlx::query_scalar::<_, i64>(76 sqlx::query_scalar::<_, i64>(
77- "SELECT count(*) FROM class_blueprint WHERE grade = $1 AND $2 = ANY(courses)",77+ "SELECT count(*) FROM blueprint_course bc \
78+ JOIN class_blueprint b ON b.id = bc.blueprint \
79+ WHERE b.grade = $1 AND bc.course = $2",
78 )80 )
79 .bind(grade)81 .bind(grade)
80 .bind(CourseId::from_key(course))82 .bind(CourseId::from_key(course))
@@ -459,13 +461,14 @@ async fn creating_a_class_stocks_it_from_its_grades_blueprint() {
459 /// A create whose stocking cannot place everything still creates the class: the461 /// A create whose stocking cannot place everything still creates the class: the
460 /// pair that did not fit comes back in `skipped`, best-effort exactly like462 /// pair that did not fit comes back in `skipped`, best-effort exactly like
461 /// every other pump here.463 /// every other pump here.
462-///
463 /// The dead course is forged in the store rather than deleted through the API,464 /// The dead course is forged in the store rather than deleted through the API,
464-/// because `DELETE /courses/{id}` now takes the id out of every template naming465+/// because `DELETE /courses/{id}` takes the id out of every template naming it
465-/// it (see `deleting_a_course_takes_it_out_of_every_blueprint`) and would leave466+/// (see `deleting_a_course_takes_it_out_of_every_blueprint`) and would leave
466-/// nothing to skip. What is left here is exactly the state that still occurs: a467+/// nothing to skip. Under the `blueprint_course` junction the live store cannot
467-/// row written before that cascade existed, and the pump's own window — a468+/// hold this state at all — the link is a foreign key — so the course row is
468-/// course deleted after the pump read the list it walks.469+/// deleted with FK triggers suspended: the legacy-row state the prune still
470+/// exists for, and the same shape the pump's own window meets (a course gone
471+/// after the pump read the list it walks).
469 #[tokio::test]472 #[tokio::test]
470 async fn a_create_reports_what_its_blueprint_could_not_stock() {473 async fn a_create_reports_what_its_blueprint_could_not_stock() {
471 let (app, db) = app_and_db().await;474 let (app, db) = app_and_db().await;
@@ -486,12 +489,21 @@ async fn a_create_reports_what_its_blueprint_could_not_stock() {
486 // the state the delete's own sweep no longer produces, and the one a pump489 // the state the delete's own sweep no longer produces, and the one a pump
487 // meets when a course goes after it read the list. Nothing carries it yet490 // meets when a course goes after it read the list. Nothing carries it yet
488 // (no section exists at grade 9), so this is the pair that cannot fit when491 // (no section exists at grade 9), so this is the pair that cannot fit when
489- // the first one is created.492+ // the first one is created. The junction makes the live state impossible —
493+ // `blueprint_course.course` is a foreign key — so the course row goes with
494+ // FK triggers suspended: exactly what a row written before that cascade
495+ // existed looks like, which is the state the prune still exists for.
496+ let mut tx = db.begin().await.unwrap();
497+ sqlx::query("SET LOCAL session_replication_role = replica")
498+ .execute(&mut *tx)
499+ .await
500+ .unwrap();
490 sqlx::query("DELETE FROM course WHERE id = $1")501 sqlx::query("DELETE FROM course WHERE id = $1")
491 .bind(CourseId::from_key(&physics))502 .bind(CourseId::from_key(&physics))
492- .execute(&db)503+ .execute(&mut *tx)
493 .await504 .await
494 .unwrap();505 .unwrap();
506+ tx.commit().await.unwrap();
495 assert!(507 assert!(
496 templated("9", &physics, &db).await,508 templated("9", &physics, &db).await,
497 "the id is still listed"509 "the id is still listed"
@@ -1424,11 +1436,15 @@ async fn a_half_swept_removal_is_finished_by_the_documented_re_patch() {
1424 1436
1425 // The state a sweep that died half-way leaves: the list is stored without1437 // The state a sweep that died half-way leaves: the list is stored without
1426 // history, its attachment is not.1438 // history, its attachment is not.
1427- sqlx::query("UPDATE class_blueprint SET courses = $1 WHERE grade = '9'")1439+ sqlx::query(
1428- .bind(vec![CourseId::from_key(&algebra)])1440+ "DELETE FROM blueprint_course \
1429- .execute(&db)1441+ WHERE course = $1 \
1430- .await1442+ AND blueprint = (SELECT id FROM class_blueprint WHERE grade = '9')",
1431- .unwrap();1443+ )
1444+ .bind(CourseId::from_key(&history))
1445+ .execute(&db)
1446+ .await
1447+ .unwrap();
1432 1448
1433 let courses = held(&app, &manager, "9").await;1449 let courses = held(&app, &manager, "9").await;
1434 assert_eq!(1450 assert_eq!(
@@ -1491,9 +1507,10 @@ async fn a_half_swept_removal_is_finished_by_the_documented_re_patch() {
1491 /// the `201`/`200` listed a course the `GET` a moment later did not.1507 /// the `201`/`200` listed a course the `GET` a moment later did not.
1492 ///1508 ///
1493 /// Both write routes are driven, and the window is opened by the schema rather1509 /// Both write routes are driven, and the window is opened by the schema rather
1494-/// than by a lucky interleaving: a `DEFINE EVENT` on `class_blueprint` fires1510+/// than by a lucky interleaving: a trigger on `blueprint_course` fires inside
1495-/// inside the very transaction that stores the list, which is exactly "after1511+/// the very transaction that stores the list — after the link row landed, so
1496-/// the courses were resolved, before the pump runs", every single time.1512+/// the foreign key allows the course's own death — which is exactly "after the
1513+/// courses were resolved, before the pump runs", every single time.
1497 #[tokio::test]1514 #[tokio::test]
1498 async fn a_course_pruned_mid_pump_is_out_of_the_body_that_pruned_it() {1515 async fn a_course_pruned_mid_pump_is_out_of_the_body_that_pruned_it() {
1499 let (app, db) = app_and_db().await;1516 let (app, db) = app_and_db().await;
@@ -1505,10 +1522,13 @@ async fn a_course_pruned_mid_pump_is_out_of_the_body_that_pruned_it() {
1505 let mut conn = db.acquire().await.expect("acquire for the trigger");1522 let mut conn = db.acquire().await.expect("acquire for the trigger");
1506 sqlx::raw_sql(sqlx::AssertSqlSafe(format!(1523 sqlx::raw_sql(sqlx::AssertSqlSafe(format!(
1507 "CREATE FUNCTION heztest_kill_on_create() RETURNS trigger AS $$1524 "CREATE FUNCTION heztest_kill_on_create() RETURNS trigger AS $$
1508- BEGIN DELETE FROM course WHERE id = '{algebra}'; RETURN NULL; END;1525+ BEGIN DELETE FROM blueprint_course WHERE blueprint = NEW.blueprint \
1526+ AND course = NEW.course;
1527+ DELETE FROM course WHERE id = NEW.course; RETURN NULL; END;
1509 $$ LANGUAGE plpgsql;1528 $$ LANGUAGE plpgsql;
1510- CREATE TRIGGER heztest_kill_on_create AFTER INSERT ON class_blueprint1529+ CREATE TRIGGER heztest_kill_on_create AFTER INSERT ON blueprint_course
1511- FOR EACH ROW EXECUTE FUNCTION heztest_kill_on_create();"1530+ FOR EACH ROW WHEN (NEW.course = '{algebra}')
1531+ EXECUTE FUNCTION heztest_kill_on_create();"
1512 )))1532 )))
1513 .execute(&mut *conn)1533 .execute(&mut *conn)
1514 .await1534 .await
@@ -1540,10 +1560,13 @@ async fn a_course_pruned_mid_pump_is_out_of_the_body_that_pruned_it() {
1540 // The same window on the edit route.1560 // The same window on the edit route.
1541 sqlx::raw_sql(sqlx::AssertSqlSafe(format!(1561 sqlx::raw_sql(sqlx::AssertSqlSafe(format!(
1542 "CREATE FUNCTION heztest_kill_on_update() RETURNS trigger AS $$1562 "CREATE FUNCTION heztest_kill_on_update() RETURNS trigger AS $$
1543- BEGIN DELETE FROM course WHERE id = '{history}'; RETURN NULL; END;1563+ BEGIN DELETE FROM blueprint_course WHERE blueprint = NEW.blueprint \
1564+ AND course = NEW.course;
1565+ DELETE FROM course WHERE id = NEW.course; RETURN NULL; END;
1544 $$ LANGUAGE plpgsql;1566 $$ LANGUAGE plpgsql;
1545- CREATE TRIGGER heztest_kill_on_update AFTER UPDATE ON class_blueprint1567+ CREATE TRIGGER heztest_kill_on_update AFTER INSERT ON blueprint_course
1546- FOR EACH ROW EXECUTE FUNCTION heztest_kill_on_update();"1568+ FOR EACH ROW WHEN (NEW.course = '{history}')
1569+ EXECUTE FUNCTION heztest_kill_on_update();"
1547 )))1570 )))
1548 .execute(&mut *conn)1571 .execute(&mut *conn)
1549 .await1572 .await
tests/regress_classes.rsmodified+1 -1
@@ -1610,7 +1610,7 @@ async fn a_course_assignment_whose_teacher_is_demoted_mid_write_is_undone() {
1610 );1610 );
1611 assert_eq!(role_of(&teacher_id, &db).await, "student", "the seam fired");1611 assert_eq!(role_of(&teacher_id, &db).await, "student", "the seam fired");
1612 assert_eq!(1612 assert_eq!(
1613- counter("SELECT COALESCE(sum(cardinality(teachers)), 0)::bigint FROM course", &db).await,1613+ counter("SELECT count(*) FROM course_teacher", &db).await,
1614 0,1614 0,
1615 "the assignment must be dropped again, not left granting nothing"1615 "the assignment must be dropped again, not left granting nothing"
1616 );1616 );