From 3f5b12440daf3ff34506363f45e180b3d7268609 Mon Sep 17 00:00:00 2001 From: aamoghS Date: Sat, 14 Nov 2026 17:47:55 -0500 Subject: [PATCH 1/3] feat(db): enforce unique email and value ranges in the database user.email gets a unique index (the auth adapter already assumed one row per address), and 14 CHECK constraints hold ranges the API enforces today: ratings 1-5, end after start on hackathons, events and judging schedules, appointment times in order, positive caps, non-negative prices, stock and points, purchase totals equal to unit price times quantity, and point adjustments non-zero within -1000..1000. The production preflight (packages/db/sql/preflight-2026-11-constraints.sql) found no row breaking any of these. It found one initiative with max_members = 0, so that check is left out until the row is corrected. --- packages/db/src/schemas/auth.ts | 6 +++++- packages/db/src/schemas/events.ts | 2 ++ packages/db/src/schemas/hackathons.ts | 6 ++++++ packages/db/src/schemas/judging.ts | 20 +++++++++++++++++--- packages/db/src/schemas/points.ts | 20 ++++++++++++++++---- 5 files changed, 46 insertions(+), 8 deletions(-) diff --git a/packages/db/src/schemas/auth.ts b/packages/db/src/schemas/auth.ts index d95a1d3a..b3c1bdb8 100644 --- a/packages/db/src/schemas/auth.ts +++ b/packages/db/src/schemas/auth.ts @@ -5,6 +5,7 @@ import { primaryKey, integer, index, + uniqueIndex, } from "drizzle-orm/pg-core"; import type { AdapterAccount } from "next-auth/adapters"; @@ -18,7 +19,10 @@ export const users = pgTable( image: text("image"), }, (table) => [ - index("user_email_idx").on(table.email), + // One account per address: the auth adapter looks users up by email and + // assumes one row comes back. A unique index rather than a constraint, for + // the column-order reason in events.ts. + uniqueIndex("user_email_unique_idx").on(table.email), index("user_name_idx").on(table.name), ], ); diff --git a/packages/db/src/schemas/events.ts b/packages/db/src/schemas/events.ts index b721abc4..f0565c2c 100644 --- a/packages/db/src/schemas/events.ts +++ b/packages/db/src/schemas/events.ts @@ -7,6 +7,7 @@ import { integer, index, uniqueIndex, + check, } from "drizzle-orm/pg-core"; import { relations, sql } from "drizzle-orm"; import { users } from "./auth"; @@ -64,6 +65,7 @@ export const events = pgTable( ), // Both bootcamp pages read every session of one term. index("event_bootcamp_term_idx").on(table.bootcampTerm), + check("event_max_check_ins_check", sql`${table.maxCheckIns} > 0`), ], ); diff --git a/packages/db/src/schemas/hackathons.ts b/packages/db/src/schemas/hackathons.ts index 793f989b..1fb9e45c 100644 --- a/packages/db/src/schemas/hackathons.ts +++ b/packages/db/src/schemas/hackathons.ts @@ -10,6 +10,7 @@ import { unique, uniqueIndex, foreignKey, + check, } from "drizzle-orm/pg-core"; import { relations, sql } from "drizzle-orm"; import { users } from "./auth"; @@ -72,6 +73,8 @@ export const hackathons = pgTable( // non-uuid argument on this column — two editions sharing a name make one // permanently unreachable through the admin UI, with no error. unique("unique_hackathon_name").on(table.name), + check("hackathon_dates_check", sql`${table.endDate} >= ${table.startDate}`), + check("hackathon_max_participants_check", sql`${table.maxParticipants} > 0`), ], ); @@ -97,6 +100,7 @@ export const hackathonTeams = pgTable( (table) => [ index("team_hackathon_id_idx").on(table.hackathonId), index("team_captain_id_idx").on(table.captainId), + check("team_max_members_check", sql`${table.maxMembers} > 0`), ], ); @@ -423,6 +427,8 @@ export const hackathonEvents = pgTable( uniqueIndex("event_check_in_code_idx") .on(table.hackathonId, table.checkInCode) .where(sql`${table.checkInCode} is not null`), + check("hackathon_event_times_check", sql`${table.endTime} >= ${table.startTime}`), + check("hackathon_event_points_check", sql`${table.points} >= 0`), ], ); diff --git a/packages/db/src/schemas/judging.ts b/packages/db/src/schemas/judging.ts index 4a8f8b45..4c980c11 100644 --- a/packages/db/src/schemas/judging.ts +++ b/packages/db/src/schemas/judging.ts @@ -11,6 +11,7 @@ import { uniqueIndex, primaryKey, foreignKey, + check, } from "drizzle-orm/pg-core"; import { relations, sql } from "drizzle-orm"; import { users } from "./auth"; @@ -26,8 +27,9 @@ import { hackathons, hackathonProjects } from "./hackathons"; // (judge.ts) and the retired panel's tables share this database: `project`, // `track`, `vote`, `judging_project` and `judge` are all taken. // -// No CHECK constraints, matching the rest of the schema: ranges are enforced -// by the API, which is the only writer. +// The API enforces every range. The CHECK constraints below repeat the ones +// a wrong number would corrupt (ratings, schedule arithmetic), so a bug or a +// hand-written UPDATE fails loudly instead of skewing results. // One row per edition: the state machine and the switches organisers flip on // judging day. @@ -529,7 +531,14 @@ export const judgingSchedules = pgTable( }), createdAt: timestamp("created_at").defaultNow().notNull(), }, - (table) => [uniqueIndex("judging_schedule_hackathon_idx").on(table.hackathonId)], + (table) => [ + uniqueIndex("judging_schedule_hackathon_idx").on(table.hackathonId), + check("judging_schedule_window_check", sql`${table.windowEnd} > ${table.windowStart}`), + check( + "judging_schedule_minutes_check", + sql`least(${table.setupMinutes}, ${table.judgingMinutes}, ${table.teardownMinutes}, ${table.sameBuildingBreakMinutes}, ${table.crossBuildingBreakMinutes}) >= 0`, + ), + ], ); // One presentation: a project, for one challenge, in one room, at one time. @@ -576,6 +585,10 @@ export const judgingAppointments = pgTable( ), index("judging_appointment_entry_idx").on(table.entryId), index("judging_appointment_judge_idx").on(table.assignedJudgeId), + check( + "judging_appointment_times_check", + sql`${table.startsAt} <= ${table.deadlineAt} and ${table.deadlineAt} <= ${table.endsAt}`, + ), foreignKey({ name: "judging_appointment_challenge_fk", columns: [table.challengeId], @@ -748,6 +761,7 @@ export const judgingEvaluationRatings = pgTable( }, (table) => [ primaryKey({ columns: [table.evaluationId, table.itemId] }), + check("judging_eval_rating_value_check", sql`${table.value} between 1 and 5`), foreignKey({ name: "judging_eval_rating_evaluation_fk", columns: [table.evaluationId], diff --git a/packages/db/src/schemas/points.ts b/packages/db/src/schemas/points.ts index f531e56a..b7ed826a 100644 --- a/packages/db/src/schemas/points.ts +++ b/packages/db/src/schemas/points.ts @@ -7,8 +7,9 @@ import { integer, index, foreignKey, + check, } from "drizzle-orm/pg-core"; -import { relations } from "drizzle-orm"; +import { relations, sql } from "drizzle-orm"; import { users } from "./auth"; import { hackathons, hackathonParticipants } from "./hackathons"; @@ -32,7 +33,7 @@ export const hackathonPointAdjustments = pgTable( .notNull() .references(() => hackathons.id, { onDelete: "cascade" }), participantId: uuid("participant_id").notNull(), - // Non-zero, -1000 to 1000. Checked by the API. + // Non-zero, -1000 to 1000. Checked by the API and by the constraint below. delta: integer("delta").notNull(), reason: text("reason").notNull(), actorId: text("actor_id").references(() => users.id, { @@ -50,6 +51,10 @@ export const hackathonPointAdjustments = pgTable( columns: [table.participantId], foreignColumns: [hackathonParticipants.id], }).onDelete("cascade"), + check( + "point_adjustment_delta_check", + sql`${table.delta} <> 0 and ${table.delta} between -1000 and 1000`, + ), ], ); @@ -74,7 +79,10 @@ export const hackathonStoreItems = pgTable( createdAt: timestamp("created_at").defaultNow().notNull(), updatedAt: timestamp("updated_at").defaultNow().notNull(), }, - (table) => [index("store_item_hackathon_idx").on(table.hackathonId)], + (table) => [ + index("store_item_hackathon_idx").on(table.hackathonId), + check("store_item_price_check", sql`${table.price} >= 0 and ${table.stock} >= 0`), + ], ); // An organiser handing something over at the store table. The id comes from @@ -94,7 +102,7 @@ export const hackathonStorePurchases = pgTable( itemName: text("item_name").notNull(), unitPrice: integer("unit_price").notNull(), quantity: integer("quantity").notNull(), - // unitPrice * quantity, written by the API. + // unitPrice * quantity, written by the API and held by the constraint below. total: integer("total").notNull(), stockTracked: boolean("stock_tracked").notNull(), actorId: text("actor_id").references(() => users.id, { @@ -124,6 +132,10 @@ export const hackathonStorePurchases = pgTable( columns: [table.itemId], foreignColumns: [hackathonStoreItems.id], }).onDelete("set null"), + check( + "store_purchase_amount_check", + sql`${table.quantity} > 0 and ${table.unitPrice} >= 0 and ${table.total} = ${table.unitPrice} * ${table.quantity}`, + ), ], ); From e3028da2f972bc09e166308f002c9a5b6140a200 Mon Sep 17 00:00:00 2001 From: aamoghS Date: Sat, 14 Nov 2026 17:57:03 -0500 Subject: [PATCH 2/3] fix(db): stop push re-creating judging_entry_challenge's primary key drizzle-kit reads a primary key's columns from constraint_column_usage, which lists them by name (challenge_id, entry_id), and compared that with the declared entry-first order. Every deploy's push dropped and re-added the key. Declare it in the order drizzle-kit reads, under the name it already has; the key in the database is unchanged. --- packages/db/src/schemas/judging.ts | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/packages/db/src/schemas/judging.ts b/packages/db/src/schemas/judging.ts index 4c980c11..2b5d2276 100644 --- a/packages/db/src/schemas/judging.ts +++ b/packages/db/src/schemas/judging.ts @@ -331,7 +331,14 @@ export const judgingEntryChallenges = pgTable( isOptIn: boolean("is_opt_in").notNull().default(true), }, (table) => [ - primaryKey({ columns: [table.entryId, table.challengeId] }), + // Declared in the order drizzle-kit reads it back (constraint_column_usage, + // which lists columns by name), under the name the key already has. Written + // entry-first, push saw a different key on every deploy and dropped and + // re-added it. The key in the database stays (entry_id, challenge_id). + primaryKey({ + name: "judging_entry_challenge_entry_id_challenge_id_pk", + columns: [table.challengeId, table.entryId], + }), index("judging_entry_challenge_challenge_idx").on(table.challengeId), foreignKey({ name: "judging_entry_challenge_challenge_fk", From a2c5fdf2cf43d8ac99c11c2b8d62b392bb05aa7e Mon Sep 17 00:00:00 2001 From: aamoghS Date: Sat, 14 Nov 2026 18:03:50 -0500 Subject: [PATCH 3/3] fix(db): make the email uniqueness case-insensitive The auth adapter looks users up by lower(email), and providers keep the casing an address was typed in, so a unique index on the raw column still allowed Ada@x.com and ada@x.com as two accounts. Index lower(email) instead, and keep the plain email index the exact-match lookups use. Production has no two addresses that collide once lowercased. --- packages/db/src/schemas/auth.ts | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/packages/db/src/schemas/auth.ts b/packages/db/src/schemas/auth.ts index b3c1bdb8..bbde80d5 100644 --- a/packages/db/src/schemas/auth.ts +++ b/packages/db/src/schemas/auth.ts @@ -7,6 +7,7 @@ import { index, uniqueIndex, } from "drizzle-orm/pg-core"; +import { sql } from "drizzle-orm"; import type { AdapterAccount } from "next-auth/adapters"; export const users = pgTable( @@ -19,10 +20,12 @@ export const users = pgTable( image: text("image"), }, (table) => [ - // One account per address: the auth adapter looks users up by email and - // assumes one row comes back. A unique index rather than a constraint, for - // the column-order reason in events.ts. - uniqueIndex("user_email_unique_idx").on(table.email), + // For the exact-match lookups (admin grant, manual check-in, bans). + index("user_email_idx").on(table.email), + // One account per address, case-insensitive: the auth adapter looks users + // up by lower(email) and assumes one row comes back, while providers keep + // whatever casing the address was typed in. + uniqueIndex("user_email_lower_unique_idx").on(sql`lower(${table.email})`), index("user_name_idx").on(table.name), ], );