diff --git a/docs/architecture.md b/docs/architecture.md index c3bfa7c5..c710cef0 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -95,7 +95,7 @@ Edition-scoped event operations. Everything hangs off `hackathon`. - Editions, interest list, registration, teams, project submission - Weekend schedule (`hackathon_event`) and badge scans - Judge roster (`judge`, `judge_assignment`): applications and approval -- Judging: room-based judging with Devpost import — `judging_*` tables (`judging.ts`). The older pool-dispatch tables (`judging_project`, `judge_vote`, `judge_queue`, `hackathon_result`) are retired and kept for past editions' results +- Judging: room-based judging with Devpost import — `judging_*` tables (`judging.ts`). The older pool-dispatch tables (`judging_project`, `judge_vote`, `hackathon_result`) are retired and kept for past editions' results - Points: `hackathon_event` points, staff adjustments and the point store (`points.ts`) - Event check-in rules: nobody is checked into two events that run at the same time, or into two less than 30 minutes apart (meals are exempt). `recordEventAttendance` enforces this for pass scans, event codes and manual check-in - Check-in rule-break flags: each refused attempt is recorded (`hackathon_check_in_flag`, `services/check-in-flags.ts`) and shown in judging on the hacker's team, in full to organisers and as a bare marker to judges. Organisers decide whether to pull the team from prizes (`judging_entry.prize_ineligible_at`). A flag outlives the events it names (deleting one clears its id and the organiser view shows "A deleted event"). Hackers never see flags, and they stay out of public and cached payloads diff --git a/docs/bootcamp-materials.md b/docs/bootcamp-materials.md index 367e0eb2..ffa5c128 100644 --- a/docs/bootcamp-materials.md +++ b/docs/bootcamp-materials.md @@ -50,4 +50,4 @@ An upload and a removal of the same file can race, because the object write and ## Legacy table -`bootcamp_material` (#390's per-event handouts) is still declared in the schema, but nothing reads or writes it. Deploys run `drizzle-kit push`, and removing the declaration would make push stop at a DROP TABLE prompt. Drop the table in a separate change. +`bootcamp_material` (#390's per-event handouts) was dropped in November 2026 (`packages/db/sql/2026-11-drop-retired.sql`); nothing had read or written it since `bootcamp_workshop` replaced it. diff --git a/docs/features/events.md b/docs/features/events.md index 87ea07f6..85f13c3a 100644 --- a/docs/features/events.md +++ b/docs/features/events.md @@ -49,7 +49,7 @@ sequenceDiagram | Already has a row for this event | `CONFLICT` "Already checked in" | | Count of `event_check_in` rows `>= maxCheckIns` (event row locked `FOR UPDATE`, only when capped) | `BAD_REQUEST` "Event is full" | -There is no earliest time: a scan is accepted before the event starts. Membership is not checked. The member row is looked up only so a member's check-in carries `member_id`. The `events.membersOnly` column is no longer read. +There is no earliest time: a scan is accepted before the event starts. Membership is not checked. The member row is looked up only so a member's check-in carries `member_id`. The 24 hour limit matches the public list, which stops marking an event open after the same cutoff, so a photographed QR cannot keep admitting people. @@ -119,7 +119,7 @@ The scanner hook (`components/portal/EventCheckIn.tsx`) also recognises a hackat | `event` | `title`, `event_date`, `qr_code` (unique), `check_in_enabled`, `max_check_ins`, `bootcamp_week`, `bootcamp_term`, `bootcamp_only`, `kind` (generated), `created_by_id` | | `event_check_in` | `event_id`, `user_id`, `member_id` (null for non-members), `check_in_method` (`qr_code` or `manual`), `checked_in_at`. Unique on `(event_id, user_id)` | -The check-in count is `count(*)` of `event_check_in` rows, taken under the event row lock for the capacity check and as a subquery for `currentCheckIns` in event reads. The old `current_check_ins` column is no longer read or written and will be dropped in a later change. +The check-in count is `count(*)` of `event_check_in` rows, taken under the event row lock for the capacity check, and by one grouped query per list for `currentCheckIns` in event reads (`services/derived-counts.ts`). There is no stored counter. ## Code and tests diff --git a/docs/features/hackathons.md b/docs/features/hackathons.md index 16760ddd..ebe65792 100644 --- a/docs/features/hackathons.md +++ b/docs/features/hackathons.md @@ -82,7 +82,7 @@ Roles come from `packages/api/src/middleware/procedures.ts`. `isAdmin` is full s | `sendMassAcceptanceEmails` | Mails accepted people in batches. Resumable per person through `acceptance_email_sent_at`. | | `analytics` | Counts for the dashboard. | -`max_participants` caps acceptances, not applications. Seats taken are counted from `approved` plus `checked_in` rows on every read (`currentParticipants` in hackathon reads) and under the hackathon row lock in `assertSeats`. The `current_participants` and team `current_members` columns are no longer read or written and will be dropped in a later change. +`max_participants` caps acceptances, not applications. Seats taken are counted from `approved` plus `checked_in` rows on every read (`currentParticipants` in hackathon reads) and under the hackathon row lock in `assertSeats`. A team's `currentMembers` is its participant rows the same way. Neither is a stored column. ### Interest list (`interest.ts`) diff --git a/docs/features/judge-portal.md b/docs/features/judge-portal.md index 7f20d35f..7a56fbda 100644 --- a/docs/features/judge-portal.md +++ b/docs/features/judge-portal.md @@ -73,7 +73,7 @@ Schema: `packages/db/src/schemas/judge.ts`. | `judge_assignment` | The application: edition, `track`, `status` (`pending`, `approved`, `rejected`), `is_lead`. | | `judge_interest` | Public interest leads from the Hacklytics site (above). | -The same file also declares `judging_project`, `judge_vote`, `hackathon_result` and `judge_queue` from the retired pool-dispatch judging. Nothing writes them now, but past editions' data stays, and `hackathon.getResults` still reads `hackathon_result`. +The same file also declares `judging_project`, `judge_vote` and `hackathon_result` from the retired pool-dispatch judging. Nothing writes them now, but past editions' data stays, and `hackathon.getResults` still reads `hackathon_result`. ## Code and tests diff --git a/docs/judging/README.md b/docs/judging/README.md index d0c2410d..a66c6998 100644 --- a/docs/judging/README.md +++ b/docs/judging/README.md @@ -87,7 +87,7 @@ The order is a checklist, not a hard gate. `judging.admin.checklist` reports sev | `judging_repo_check` | Per project: GitHub last-push check against the submission deadline and the organiser decision, see [repo check](./repo-check.md) | | `judging_announcement` | The pinned message for all judges or one room | -The older `judging_project`, `judge_vote`, `judge_queue` and `hackathon_result` tables are retired and kept for past editions. `hackathon.getResults` still merges their published rows with new placements. +The older `judging_project`, `judge_vote` and `hackathon_result` tables are retired and kept for past editions. `hackathon.getResults` still merges their published rows with new placements. ## Where the code lives diff --git a/docs/packages/db.md b/docs/packages/db.md index 49f5080f..f55a2f38 100644 --- a/docs/packages/db.md +++ b/docs/packages/db.md @@ -28,13 +28,13 @@ Files in `src/schemas/`, re-exported from `schemas/index.ts`. `drizzle.config.ts | `members.ts` | `user_profile`, `member`, `membership_history` | | `admins.ts` | `admin` | | `hackathons.ts` | `hackathon`, `hackathon_team`, `hackathon_participant`, `hackathon_project`, `hackathon_interest`, `hackathon_event`, `hackathon_event_attendee`, `hackathon_check_in_flag`, `hackathon_announcement`, `hackathon_announcement_recipient` | -| `judge.ts` | `judge`, `judge_assignment` (live roster); `judging_project`, `judge_vote`, `judge_queue`, `hackathon_result` (retired, kept for past editions) | +| `judge.ts` | `judge`, `judge_assignment` (live roster); `judging_project`, `judge_vote`, `hackathon_result` (retired, kept for past editions) | | `judging.ts` | `judging_*`: config, entries and members, challenges, buildings, rooms and room links, judges, guest sessions, presence, schedule and appointments, rubric, evaluations, deliberation, placements, repo checks | | `points.ts` | `hackathon_point_adjustment`, `hackathon_store_item`, `hackathon_store_purchase` | | `retired.ts` | Enum types the retired panel judging service left in the database, declared so push does not try to drop them | | `initiatives.ts` | `project_leader`, `initiative`, `initiative_application` | | `events.ts` | `event`, `event_check_in` | -| `bootcamp.ts` | `bootcamp_workshop` (metadata; the ZIPs are in Cloud Storage). `bootcamp_material` is legacy and unused | +| `bootcamp.ts` | `bootcamp_workshop` (metadata; the ZIPs are in Cloud Storage) | | `stripe.ts` | `stripe_payment`, `user_account_link` | | `security.ts` | `audit_logs` (+ `security_severity` enum) | | `settings.ts` | `system_settings` (single row, `id = 'default'`) | @@ -122,7 +122,7 @@ erDiagram judging_entry ||--o{ judging_placement : "final placement" ``` -Other tables include: `user_profile`, `club_project`, `subteam` and `subteam_application`, `member_resume`, `bootcamp_workshop` and `bootcamp_material`, `hackathon_announcement` and recipients, `hackathon_ban`, `hackathon_check_in_flag`, point adjustments, store items and purchases, `audit_logs`, `system_settings`, `admin`, `project_leader`, `user_account_link`, `verificationToken`, `judging_announcement`, `judging_rubric_item`, `judging_evaluation_draft` and `judging_evaluation_response`. The older `judging_project`, `judge_vote`, `judge_queue` and `hackathon_result` tables are retired and kept for past editions. +Other tables include: `user_profile`, `club_project`, `subteam` and `subteam_application`, `member_resume`, `bootcamp_workshop`, `hackathon_announcement` and recipients, `hackathon_ban`, `hackathon_check_in_flag`, point adjustments, store items and purchases, `audit_logs`, `system_settings`, `admin`, `project_leader`, `user_account_link`, `verificationToken`, `judging_announcement`, `judging_rubric_item`, `judging_evaluation_draft` and `judging_evaluation_response`. The older `judging_project`, `judge_vote` and `hackathon_result` tables are retired and kept for past editions. ## Membership service @@ -148,6 +148,16 @@ pnpm --filter @query/db db:seed # scripts/seed.ts The repo is **push-based**: `packages/db/drizzle/meta/_journal.json` has no migration entries. App Hosting runs `drizzle-kit push --verbose < /dev/null` then `db:check`. Destructive prompts cannot be confirmed, so the push aborts rather than dropping columns; `db:check` is the real gate (push can still exit 0). +### Dropping a column or table + +Push never drops anything in a deploy, so a drop ships as two things in one change: the schema stops declaring it, and a file in `packages/db/sql/` drops it. Run that file against production **before** the change deploys: + +```bash +psql "$PROD_DATABASE_URL" -v ON_ERROR_STOP=1 -f packages/db/sql/.sql +``` + +The other order is the dangerous one. If the schema stops declaring a column production still has, every later push stops at the data-loss prompt and applies nothing, so new columns stop reaching production too. Each file runs in one transaction and uses `IF EXISTS`, so a failure changes nothing and a second run is a no-op. Rehearse it on a PGX clone first: run the file, then `migrate:push` should report no drops, and `db:check` should pass. + `scripts/link-payments.ts` is a one-off to attach historical paid Stripe rows to matching user emails: ```bash diff --git a/packages/api/src/.internal-tests/derived-counts.db.test.ts b/packages/api/src/.internal-tests/derived-counts.db.test.ts index 834e42f6..454ddad2 100644 --- a/packages/api/src/.internal-tests/derived-counts.db.test.ts +++ b/packages/api/src/.internal-tests/derived-counts.db.test.ts @@ -15,8 +15,7 @@ import type * as CountHelpers from "../services/derived-counts"; * * Needs TEST_DATABASE_URL (a local, disposable database; never Neon or * production) and skips without it. It inserts its own rows under a random - * suffix and removes them afterwards. The stored counters are set to wrong - * numbers on purpose, so a read that still used them would fail. + * suffix and removes them afterwards. */ const URL = process.env.TEST_DATABASE_URL; @@ -58,7 +57,7 @@ describe.skipIf(!URL)("derived counts against a real database", () => { userIds.map((id) => ({ id, email: `${id}@example.test`, name: id })), ); - // Event with 3 check-ins and a stored counter of 99. + // Event with 3 check-ins. const [event] = await db .insert(S.events) .values({ @@ -66,7 +65,6 @@ describe.skipIf(!URL)("derived counts against a real database", () => { eventDate: new Date(), qrCode: crypto.randomUUID(), createdById: userIds[0]!, - currentCheckIns: 99, }) .returning({ id: S.events.id }); eventId = event!.id; @@ -74,7 +72,7 @@ describe.skipIf(!URL)("derived counts against a real database", () => { userIds.slice(0, 3).map((userId) => ({ eventId, userId })), ); - // Capped event: cap 2, two real rows, stored counter 0. + // Capped event: cap 2, two real rows. cappedQr = crypto.randomUUID(); const [capped] = await db .insert(S.events) @@ -84,7 +82,6 @@ describe.skipIf(!URL)("derived counts against a real database", () => { qrCode: cappedQr, createdById: userIds[0]!, maxCheckIns: 2, - currentCheckIns: 0, }) .returning({ id: S.events.id }); cappedEventId = capped!.id; @@ -92,8 +89,7 @@ describe.skipIf(!URL)("derived counts against a real database", () => { userIds.slice(0, 2).map((userId) => ({ eventId: cappedEventId, userId })), ); - // Hackathon: 2 approved + 1 checked_in + 2 pending/rejected = 3 seats, - // stored counter 42. + // Hackathon: 2 approved + 1 checked_in + 2 pending/rejected = 3 seats. const [hackathon] = await db .insert(S.hackathons) .values({ @@ -102,7 +98,6 @@ describe.skipIf(!URL)("derived counts against a real database", () => { endDate: new Date(Date.now() + 2 * 86_400_000), status: "open", maxParticipants: 10, - currentParticipants: 42, }) .returning({ id: S.hackathons.id }); hackathonId = hackathon!.id; @@ -114,13 +109,11 @@ describe.skipIf(!URL)("derived counts against a real database", () => { hackathonId, name: `dc team ${suffix}`, captainId: userIds[0]!, - currentMembers: 7, }, { hackathonId, name: `dc empty ${suffix}`, captainId: userIds[5]!, - currentMembers: 3, }, ]) .returning({ id: S.hackathonTeams.id }); @@ -194,7 +187,7 @@ describe.skipIf(!URL)("derived counts against a real database", () => { expect(counts.size).toBe(0); }); - it("events.list returns the row count, not the stored counter", async () => { + it("events.list returns the row count", async () => { const { cache } = await import("../middleware/cache"); cache.clear(); const list = await appRouter.createCaller(ctx()).events.list(); @@ -205,7 +198,7 @@ describe.skipIf(!URL)("derived counts against a real database", () => { ); }); - it("hackathon.getById returns the seats held by rows, not the stored counter", async () => { + it("hackathon.getById returns the seats held by rows", async () => { const { cache } = await import("../middleware/cache"); cache.clear(); const row = await appRouter @@ -223,7 +216,7 @@ describe.skipIf(!URL)("derived counts against a real database", () => { ).toBe(3); }); - it("team.list returns the roster size, not the stored counter", async () => { + it("team.list returns the roster size", async () => { const { cache } = await import("../middleware/cache"); cache.clear(); const teams = await appRouter @@ -235,7 +228,7 @@ describe.skipIf(!URL)("derived counts against a real database", () => { ); }); - it("refuses a check-in when rows fill the event although the stored counter reads 0", async () => { + it("refuses a check-in when the rows fill the event", async () => { await expect( appRouter .createCaller(ctx(userIds[4])) @@ -243,10 +236,10 @@ describe.skipIf(!URL)("derived counts against a real database", () => { ).rejects.toMatchObject({ message: "Event is full" }); }); - it("admits a check-in once the rows leave room although the stored counter reads full", async () => { + it("admits a check-in once a row leaves room", async () => { const db = S.db!; const { and, eq } = drizzleOps; - // Free a seat by deleting a row, and set the counter to read full. + // Free a seat by deleting a row. await db .delete(S.eventCheckIns) .where( @@ -255,11 +248,6 @@ describe.skipIf(!URL)("derived counts against a real database", () => { eq(S.eventCheckIns.userId, userIds[1]!), ), ); - await db - .update(S.events) - .set({ currentCheckIns: 2 }) - .where(eq(S.events.id, cappedEventId)); - await expect( appRouter .createCaller(ctx(userIds[4])) diff --git a/packages/api/src/routers/events.ts b/packages/api/src/routers/events.ts index 2eec6ad3..c87baead 100644 --- a/packages/api/src/routers/events.ts +++ b/packages/api/src/routers/events.ts @@ -99,7 +99,8 @@ export const eventRouter = createTRPCRouter({ // Invalidate all event-related cache entries after creation ctx.cache.deletePattern("event*"); - return newEvent; + // A new event has nobody checked in, and the QR modal shows the count. + return newEvent && { ...newEvent, currentCheckIns: 0 }; }), // Corrects a club event in place. Without it the only way to fix a typo was diff --git a/packages/api/src/routers/hackathon/crud.ts b/packages/api/src/routers/hackathon/crud.ts index 078fcc49..f79f5ef7 100644 --- a/packages/api/src/routers/hackathon/crud.ts +++ b/packages/api/src/routers/hackathon/crud.ts @@ -110,9 +110,9 @@ export const hackathonCrudRouter = createTRPCRouter({ ) .query(async ({ ctx, input }) => { type DB = DrizzleDB; - type HackathonList = Awaited< + type HackathonList = (Awaited< ReturnType - >; + >[number] & { currentParticipants: number })[]; // Staff-only statuses stay listable by admins (the setup and judging pages // pick a hackathon off this endpoint), so both the rows and the cache entry @@ -187,9 +187,11 @@ export const hackathonCrudRouter = createTRPCRouter({ .input(z.object({ id: z.string() })) .query(async ({ ctx, input }) => { type DB = DrizzleDB; - type HackathonItem = Awaited< - ReturnType - >; + type HackathonItem = + | (NonNullable< + Awaited> + > & { currentParticipants: number }) + | undefined; // list() hides staff-only statuses, but this endpoint is reachable by id or // name, so a draft stays fetchable by anyone who guesses either. The cache // entry is shared, so visibility is enforced on the way out — otherwise one diff --git a/packages/db/sql/2026-11-drop-retired.sql b/packages/db/sql/2026-11-drop-retired.sql new file mode 100644 index 00000000..ed5e6de8 --- /dev/null +++ b/packages/db/sql/2026-11-drop-retired.sql @@ -0,0 +1,30 @@ +-- Drops what the schema stopped declaring in the same change as this file. +-- +-- Run it against production BEFORE that change deploys. Deploys run +-- `drizzle-kit push < /dev/null`: a declared-but-missing column is created, +-- but an undeclared-but-present one is a DROP, which push will only do after a +-- prompt the build cannot answer. It then exits 0 having applied nothing, and +-- every later schema change is silently skipped until the drop happens. +-- +-- Nothing in the app reads or writes any of these: +-- event.current_check_ins, hackathon_team.current_members, +-- hackathon.current_participants counters, now counted from rows +-- event.members_only check-in is open to everyone signed in +-- hackathon.judging_backend retired panel judging switch +-- bootcamp_material superseded by bootcamp_workshop +-- judge_queue retired pool-judging visit log +-- +-- Irreversible: the dropped data is gone. One transaction, so a failure +-- changes nothing. IF EXISTS makes a second run a no-op. + +begin; + +alter table "event" drop column if exists "current_check_ins"; +alter table "event" drop column if exists "members_only"; +alter table "hackathon_team" drop column if exists "current_members"; +alter table "hackathon" drop column if exists "current_participants"; +alter table "hackathon" drop column if exists "judging_backend"; +drop table if exists "bootcamp_material"; +drop table if exists "judge_queue"; + +commit; diff --git a/packages/db/sql/preflight-2026-11-constraints.sql b/packages/db/sql/preflight-2026-11-constraints.sql new file mode 100644 index 00000000..b3540312 --- /dev/null +++ b/packages/db/sql/preflight-2026-11-constraints.sql @@ -0,0 +1,149 @@ +-- Read-only. Counts the rows that would break each constraint proposed for the +-- next schema change, so a constraint is only added where this says 0: adding +-- one that existing rows violate fails the deploy's push. +-- +-- psql "$DATABASE_URL" -v ON_ERROR_STOP=1 -f packages/db/sql/preflight-2026-11-constraints.sql +-- +-- Runs in a read-only transaction; it cannot change anything. + +begin transaction read only; + +select check_name, violations from ( + -- user.email is not unique; the auth adapter looks users up by it. + select 'user.email unique (case-insensitive)' as check_name, + coalesce(sum(n - 1), 0) as violations + from (select count(*) n from "user" group by lower(email) having count(*) > 1) d + + -- Child rows whose hackathon_id disagrees with their parent's. A composite + -- FK (parent_id, hackathon_id) -> parent(id, hackathon_id) would forbid it. + union all select 'hackathon_participant.team_id same edition', count(*) + from hackathon_participant c join hackathon_team p on p.id = c.team_id + where p.hackathon_id <> c.hackathon_id + union all select 'hackathon_project.team_id same edition', count(*) + from hackathon_project c join hackathon_team p on p.id = c.team_id + where p.hackathon_id <> c.hackathon_id + union all select 'hackathon_project.submitted_by_id same edition', count(*) + from hackathon_project c join hackathon_participant p on p.id = c.submitted_by_id + where p.hackathon_id <> c.hackathon_id + union all select 'hackathon_event_attendee event/participant same edition', count(*) + from hackathon_event_attendee a + join hackathon_event e on e.id = a.event_id + join hackathon_participant p on p.id = a.participant_id + where e.hackathon_id <> p.hackathon_id + union all select 'hackathon_point_adjustment.participant_id same edition', count(*) + from hackathon_point_adjustment c join hackathon_participant p on p.id = c.participant_id + where p.hackathon_id <> c.hackathon_id + union all select 'hackathon_store_purchase.participant_id same edition', count(*) + from hackathon_store_purchase c join hackathon_participant p on p.id = c.participant_id + where p.hackathon_id <> c.hackathon_id + union all select 'hackathon_store_purchase.item_id same edition', count(*) + from hackathon_store_purchase c join hackathon_store_item p on p.id = c.item_id + where p.hackathon_id <> c.hackathon_id + union all select 'hackathon_check_in_flag.participant_id same edition', count(*) + from hackathon_check_in_flag c join hackathon_participant p on p.id = c.participant_id + where p.hackathon_id <> c.hackathon_id + union all select 'judge_assignment.judge_id same edition', count(*) + from judge_assignment c join judge p on p.id = c.judge_id + where p.hackathon_id <> c.hackathon_id + union all select 'judging_entry_member.entry_id same edition', count(*) + from judging_entry_member c join judging_entry p on p.id = c.entry_id + where p.hackathon_id <> c.hackathon_id + union all select 'judging_repo_check.entry_id same edition', count(*) + from judging_repo_check c join judging_entry p on p.id = c.entry_id + where p.hackathon_id <> c.hackathon_id + union all select 'judging_claim_link.member_id same edition', count(*) + from judging_claim_link c join judging_entry_member p on p.id = c.member_id + where p.hackathon_id <> c.hackathon_id + union all select 'judging_entry_challenge entry/challenge same edition', count(*) + from judging_entry_challenge c + join judging_entry e on e.id = c.entry_id + join judging_challenge ch on ch.id = c.challenge_id + where e.hackathon_id <> c.hackathon_id or ch.hackathon_id <> c.hackathon_id + union all select 'judging_challenge.parent_id same edition', count(*) + from judging_challenge c join judging_challenge p on p.id = c.parent_id + where p.hackathon_id <> c.hackathon_id + union all select 'judging_room challenge/building same edition', count(*) + from judging_room c + join judging_challenge ch on ch.id = c.challenge_id + left join judging_building b on b.id = c.building_id + where ch.hackathon_id <> c.hackathon_id or b.hackathon_id <> c.hackathon_id + union all select 'judging_room_link.room_id same edition', count(*) + from judging_room_link c join judging_room p on p.id = c.room_id + where p.hackathon_id <> c.hackathon_id + union all select 'judging_guest_session link/room same edition', count(*) + from judging_guest_session c + join judging_room_link l on l.id = c.link_id + join judging_room r on r.id = c.room_id + where l.hackathon_id <> c.hackathon_id or r.hackathon_id <> c.hackathon_id + union all select 'judging_presence judge/room same edition', count(*) + from judging_presence c + join judging_judge j on j.id = c.judge_id + join judging_room r on r.id = c.room_id + where j.hackathon_id <> c.hackathon_id or r.hackathon_id <> c.hackathon_id + union all select 'judging_appointment parents same edition', count(*) + from judging_appointment c + join judging_schedule s on s.id = c.schedule_id + join judging_entry e on e.id = c.entry_id + join judging_challenge ch on ch.id = c.challenge_id + join judging_room r on r.id = c.room_id + left join judging_judge j on j.id = c.assigned_judge_id + where s.hackathon_id <> c.hackathon_id or e.hackathon_id <> c.hackathon_id + or ch.hackathon_id <> c.hackathon_id or r.hackathon_id <> c.hackathon_id + or j.hackathon_id <> c.hackathon_id + union all select 'judging_evaluation parents same edition', count(*) + from judging_evaluation c + join judging_judge j on j.id = c.judge_id + join judging_entry e on e.id = c.entry_id + join judging_challenge ch on ch.id = c.challenge_id + where j.hackathon_id <> c.hackathon_id or e.hackathon_id <> c.hackathon_id + or ch.hackathon_id <> c.hackathon_id + union all select 'judging_evaluation_draft parents same edition', count(*) + from judging_evaluation_draft c + join judging_judge j on j.id = c.judge_id + join judging_entry e on e.id = c.entry_id + join judging_challenge ch on ch.id = c.challenge_id + where j.hackathon_id <> c.hackathon_id or e.hackathon_id <> c.hackathon_id + or ch.hackathon_id <> c.hackathon_id + union all select 'judging_placement.entry_id same edition', count(*) + from judging_placement c join judging_entry p on p.id = c.entry_id + where p.hackathon_id <> c.hackathon_id + union all select 'judging_announcement.room_id same edition', count(*) + from judging_announcement c join judging_room p on p.id = c.room_id + where p.hackathon_id <> c.hackathon_id + + -- Ranges the API enforces today, which CHECK constraints would hold in the + -- database as well. + union all select 'judging_evaluation_rating.value between 1 and 5', count(*) + from judging_evaluation_rating where value not between 1 and 5 + union all select 'hackathon end_date >= start_date', count(*) + from hackathon where end_date < start_date + union all select 'hackathon_event end_time >= start_time', count(*) + from hackathon_event where end_time < start_time + union all select 'judging_schedule window_end > window_start', count(*) + from judging_schedule where window_end <= window_start + union all select 'judging_appointment starts <= deadline <= ends', count(*) + from judging_appointment where not (starts_at <= deadline_at and deadline_at <= ends_at) + union all select 'hackathon.max_participants > 0', count(*) + from hackathon where max_participants <= 0 + union all select 'hackathon_team.max_members > 0', count(*) + from hackathon_team where max_members <= 0 + union all select 'event.max_check_ins > 0', count(*) + from event where max_check_ins <= 0 + union all select 'initiative.max_members > 0', count(*) + from initiative where max_members <= 0 + union all select 'hackathon_store_item price >= 0 and stock >= 0', count(*) + from hackathon_store_item where price < 0 or stock < 0 + union all select 'hackathon_store_purchase quantity > 0, total = unit_price * quantity', count(*) + from hackathon_store_purchase where quantity <= 0 or unit_price < 0 or total <> unit_price * quantity + union all select 'hackathon_point_adjustment.delta nonzero, -1000..1000', count(*) + from hackathon_point_adjustment where delta = 0 or delta not between -1000 and 1000 + union all select 'hackathon_event.points >= 0', count(*) + from hackathon_event where points < 0 + union all select 'judging_schedule minutes >= 0', count(*) + from judging_schedule + where least(setup_minutes, judging_minutes, teardown_minutes, + same_building_break_minutes, cross_building_break_minutes) < 0 +) checks +order by violations desc, check_name; + +rollback; diff --git a/packages/db/src/index.ts b/packages/db/src/index.ts index 098af6a7..ed29051a 100644 --- a/packages/db/src/index.ts +++ b/packages/db/src/index.ts @@ -12,7 +12,6 @@ export { hackathonProjects, } from "./schemas/hackathons"; export { events, eventCheckIns } from "./schemas/events"; -export { bootcampMaterials } from "./schemas/bootcamp"; export { clubProjects, clubProjectStatuses } from "./schemas/club-projects"; export { bootcampWorkshops } from "./schemas/bootcamp"; export { auditLogs, securitySeverityEnum } from "./schemas/security"; diff --git a/packages/db/src/schemas/bootcamp.ts b/packages/db/src/schemas/bootcamp.ts index 231ca685..d4d7ae58 100644 --- a/packages/db/src/schemas/bootcamp.ts +++ b/packages/db/src/schemas/bootcamp.ts @@ -8,8 +8,6 @@ import { uniqueIndex, uuid, } from "drizzle-orm/pg-core"; -import { users } from "./auth"; -import { events } from "./events"; /** * One editable row per week of a bootcamp term. The ZIP bytes live in Cloud @@ -59,27 +57,3 @@ export const bootcampWorkshops = pgTable( ); export type BootcampWorkshop = typeof bootcampWorkshops.$inferSelect; - -/** - * Superseded by `bootcamp_workshop`; nothing reads or writes it. Still declared - * because deploys run `drizzle-kit push`, and removing it here would make push - * stop at a DROP TABLE prompt. Drop it in a change of its own. - */ -export const bootcampMaterials = pgTable( - "bootcamp_material", - { - id: uuid("id").defaultRandom().primaryKey(), - eventId: uuid("event_id") - .notNull() - .references(() => events.id, { onDelete: "cascade" }), - storageKey: text("storage_key").notNull(), - fileName: text("file_name").notNull(), - contentType: text("content_type").notNull(), - sizeBytes: integer("size_bytes").notNull(), - uploadedById: text("uploaded_by_id").references(() => users.id, { - onDelete: "set null", - }), - uploadedAt: timestamp("uploaded_at").defaultNow().notNull(), - }, - (table) => [index("bootcamp_material_event_idx").on(table.eventId)], -); diff --git a/packages/db/src/schemas/events.ts b/packages/db/src/schemas/events.ts index 929372a0..b721abc4 100644 --- a/packages/db/src/schemas/events.ts +++ b/packages/db/src/schemas/events.ts @@ -26,9 +26,6 @@ export const events = pgTable( eventDate: timestamp("event_date").notNull(), qrCode: text("qr_code").notNull().unique(), checkInEnabled: boolean("check_in_enabled").notNull().default(true), - // No longer read: check-in is open to everyone signed in. Kept because - // schema changes here are additive only; drop it in a later change. - membersOnly: boolean("members_only").notNull().default(true), /** * Week N of the bootcamp. Null on every event that is not a scheduled * session, which includes a session whose date was cleared. @@ -46,9 +43,9 @@ export const events = pgTable( kind: text("kind", { enum: ["club", "bootcamp"] }).generatedAlwaysAs( sql`case when bootcamp_term is null then 'club' else 'bootcamp' end`, ), + // How many check-ins the event takes. The count is the event_check_in rows + // (services/derived-counts.ts in the api), not a stored column. maxCheckIns: integer("max_check_ins"), - // No longer read or written: derived from rows (see services/derived-counts.ts). Dropped in a later change. - currentCheckIns: integer("current_check_ins").notNull().default(0), createdById: text("created_by_id") .notNull() .references(() => users.id, { onDelete: "cascade" }), diff --git a/packages/db/src/schemas/hackathons.ts b/packages/db/src/schemas/hackathons.ts index 0663153d..793f989b 100644 --- a/packages/db/src/schemas/hackathons.ts +++ b/packages/db/src/schemas/hackathons.ts @@ -34,9 +34,9 @@ export const hackathons = pgTable( endDate: timestamp("end_date").notNull(), registrationDeadline: timestamp("registration_deadline"), hackingStartTime: timestamp("hacking_start_time"), + // Seats taken are the approved and checked-in participant rows + // (services/derived-counts.ts in the api), not a stored column. maxParticipants: integer("max_participants"), - // No longer read or written: derived from rows (see services/derived-counts.ts). Dropped in a later change. - currentParticipants: integer("current_participants").notNull().default(0), // `announced` is the gap between hidden and open: the edition is public and // collects interest, but takes no registrations and is NOT the edition // memberships attach to. See PRE_CURRENT_STATUSES below. @@ -56,12 +56,6 @@ export const hackathons = pgTable( websiteUrl: text("website_url"), isPublic: boolean("is_public").notNull().default(true), judgingActive: boolean("judging_active").notNull().default(false), - // Retired with the panel judging service; nothing reads it. Still declared - // because a database that already has the column would otherwise see push - // propose dropping it, which stops every deploy at a TTY prompt. - judgingBackend: text("judging_backend", { enum: ["legacy", "panel"] }) - .notNull() - .default("legacy"), // Point store. Hidden and closed until an organiser opens it; the location // is where hackers pick up what they bought. storeCatalogVisible: boolean("store_catalog_visible") @@ -91,9 +85,8 @@ export const hackathonTeams = pgTable( .references(() => hackathons.id, { onDelete: "cascade" }), name: text("name").notNull(), description: text("description"), + // The roster is the participant rows with this team_id, not a stored count. maxMembers: integer("max_members").notNull().default(4), - // No longer read or written: derived from rows (see services/derived-counts.ts). Dropped in a later change. - currentMembers: integer("current_members").notNull().default(0), captainId: text("captain_id") .notNull() .references(() => users.id, { onDelete: "cascade" }), diff --git a/packages/db/src/schemas/judge.ts b/packages/db/src/schemas/judge.ts index 0f2fe96a..5bac93cb 100644 --- a/packages/db/src/schemas/judge.ts +++ b/packages/db/src/schemas/judge.ts @@ -16,10 +16,10 @@ import { hackathons, hackathonProjects } from "./hackathons"; // The judge roster is live: `judge` (one row per person per edition) and // `judge_assignment` (their application, with the track they would like). // -// judging_project, judge_vote, hackathon_result and judge_queue belong to the -// retired pool-dispatch judging. Nothing writes them any more. They stay -// declared for past editions' data: hackathon.getResults still reads -// hackathon_result. Room judging is in judging.ts. +// judging_project, judge_vote and hackathon_result belong to the retired +// pool-dispatch judging. Nothing writes them any more. They stay declared for +// past editions' data: hackathon.getResults still reads hackathon_result. +// Room judging is in judging.ts. export const judges = pgTable( "judge", @@ -228,51 +228,6 @@ export const hackathonResults = pgTable( ], ); -// Retired (see the top of this file). One row per visit: written when the -// judging pool handed a judge a table. -export const judgeQueue = pgTable( - "judge_queue", - { - id: uuid("id").defaultRandom().primaryKey(), - judgeId: uuid("judge_id") - .notNull() - .references(() => judges.id, { onDelete: "cascade" }), - hackathonId: uuid("hackathon_id") - .notNull() - .references(() => hackathons.id, { onDelete: "cascade" }), - projectId: uuid("project_id") - .notNull() - .references(() => judgingProjects.id, { onDelete: "cascade" }), - order: integer("order").notNull(), // nth table this judge was handed - isCompleted: boolean("is_completed").notNull().default(false), - completedAt: timestamp("completed_at"), - // Stamped when the pool hands this table to the judge. Holds the table - // while they walk over (JUDGE_WALK_LIMIT_SECONDS); a judge who never - // arrives releases it rather than blocking it until an admin steps in. - startedAt: timestamp("started_at"), - // When the judge tapped the table's NFC tag or scanned its card and - // actually began. The judging clock and the hard cutoff run from here; - // the gap from startedAt is walking, none of which is judging. - arrivedAt: timestamp("arrived_at"), - }, - (table) => [ - // No judge_id index: queue_todo_idx leads with it. - index("queue_hackathon_id_idx").on(table.hackathonId), - // Critical for "next table" logic - index("queue_todo_idx").on( - table.judgeId, - table.hackathonId, - table.isCompleted, - ), - // Answers "is anyone else at this table right now" for the claim check. - index("queue_project_active_idx").on( - table.projectId, - table.isCompleted, - table.startedAt, - ), - ], -); - // Relations export const judgesRelations = relations(judges, ({ one, many }) => ({ user: one(users, { @@ -285,7 +240,6 @@ export const judgesRelations = relations(judges, ({ one, many }) => ({ }), assignments: many(judgeAssignments), votes: many(judgeVotes), - queue: many(judgeQueue), })); export const judgeAssignmentsRelations = relations( @@ -310,7 +264,6 @@ export const judgingProjectsRelations = relations( references: [hackathons.id], }), votes: many(judgeVotes), - queueEntries: many(judgeQueue), }), ); @@ -343,20 +296,6 @@ export const hackathonResultsRelations = relations( }), ); -export const judgeQueueRelations = relations(judgeQueue, ({ one }) => ({ - judge: one(judges, { - fields: [judgeQueue.judgeId], - references: [judges.id], - }), - hackathon: one(hackathons, { - fields: [judgeQueue.hackathonId], - references: [hackathons.id], - }), - project: one(judgingProjects, { - fields: [judgeQueue.projectId], - references: [judgingProjects.id], - }), -})); // "I might judge." A short public form on the Hacklytics site, no account. It // is a lead list, not an application: nobody here has a user row, so it is