From 66ca30c1771e24b28b0417477353cb04e6dd89b7 Mon Sep 17 00:00:00 2001 From: aamoghS Date: Sat, 14 Nov 2026 18:47:38 -0500 Subject: [PATCH 1/3] refactor(db): store every timestamp with its time zone All 156 timestamp columns were timestamp without time zone. They held UTC wall time only because production sessions run in GMT and drizzle writes toISOString(); a session in another zone, or raw SQL comparing them with now(), would read them hours off. Declare them withTimezone, as status_sample already was. push converts each with SET DATA TYPE, which casts through the session zone (GMT in production), so every stored instant is kept. The one raw write that worked around the old type (now() at time zone 'utc' in admin/status.ts) is now plain now(). Rehearsed on a PGX copy: 156 conversions, no prompt, sampled instants unchanged, full suite passes. --- .../api/src/routers/hackathon/admin/status.ts | 8 +- packages/api/src/services/points.ts | 5 +- packages/db/src/schemas/admins.ts | 6 +- packages/db/src/schemas/auth.ts | 6 +- packages/db/src/schemas/bootcamp.ts | 4 +- packages/db/src/schemas/club-projects.ts | 4 +- packages/db/src/schemas/events.ts | 8 +- packages/db/src/schemas/hackathons.ts | 82 ++++++------ packages/db/src/schemas/initiatives.ts | 18 +-- packages/db/src/schemas/judge.ts | 22 ++-- packages/db/src/schemas/judging.ts | 120 +++++++++--------- packages/db/src/schemas/members.ts | 20 +-- packages/db/src/schemas/points.ts | 10 +- packages/db/src/schemas/resumes.ts | 2 +- packages/db/src/schemas/security.ts | 2 +- packages/db/src/schemas/settings.ts | 2 +- packages/db/src/schemas/stripe.ts | 8 +- packages/db/src/schemas/subteams.ts | 10 +- 18 files changed, 168 insertions(+), 169 deletions(-) diff --git a/packages/api/src/routers/hackathon/admin/status.ts b/packages/api/src/routers/hackathon/admin/status.ts index 48400f73..cb0e95c6 100644 --- a/packages/api/src/routers/hackathon/admin/status.ts +++ b/packages/api/src/routers/hackathon/admin/status.ts @@ -488,12 +488,12 @@ export const statusProcedures = { registrationStatus: status, updatedAt: new Date(), // coalesce so re-checking in someone who already arrived keeps their original - // time. `at time zone 'utc'` because the column is timestamp-without-tz: a - // bare now() goes through the session TimeZone and would disagree with the - // `new Date()` updateParticipantStatus writes for the same event. + // time. The column stores a time zone, so now() is the same instant the + // `new Date()` in updateParticipantStatus writes, whatever the session's + // TimeZone. ...(status === "checked_in" ? { - checkedInAt: sql`coalesce(${hackathonParticipants.checkedInAt}, now() at time zone 'utc')`, + checkedInAt: sql`coalesce(${hackathonParticipants.checkedInAt}, now())`, } : {}), }) diff --git a/packages/api/src/services/points.ts b/packages/api/src/services/points.ts index 26e9de54..2aeebee4 100644 --- a/packages/api/src/services/points.ts +++ b/packages/api/src/services/points.ts @@ -397,9 +397,8 @@ export async function recordEventAttendance( }, ): Promise<{ pointsAwarded: number }> { const { event, participant, method, actorId } = input; - // One clock for the rule and the row it writes. Left to the database's - // now(), checked_in_at (no time zone) follows the session's TimeZone and - // would not compare with this one. + // One clock for the rule and the row it writes, so the overlap and + // too-soon checks compare the very instant that gets stored. const now = new Date(); try { diff --git a/packages/db/src/schemas/admins.ts b/packages/db/src/schemas/admins.ts index 0ed67b5b..fc443631 100644 --- a/packages/db/src/schemas/admins.ts +++ b/packages/db/src/schemas/admins.ts @@ -23,9 +23,9 @@ export const admins = pgTable("admin", { isActive: boolean("is_active").notNull().default(true), // End of a fixed-term appointment. NULL is a standing appointment, which is // what the founding super admins hold, so the column revokes nothing alone. - expiresAt: timestamp("expires_at"), - createdAt: timestamp("created_at").defaultNow().notNull(), - updatedAt: timestamp("updated_at").defaultNow().notNull(), + expiresAt: timestamp("expires_at", { withTimezone: true }), + createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(), + updatedAt: timestamp("updated_at", { withTimezone: true }).defaultNow().notNull(), }); export const adminsRelations = relations(admins, ({ one }) => ({ diff --git a/packages/db/src/schemas/auth.ts b/packages/db/src/schemas/auth.ts index bbde80d5..9a3c9a9f 100644 --- a/packages/db/src/schemas/auth.ts +++ b/packages/db/src/schemas/auth.ts @@ -16,7 +16,7 @@ export const users = pgTable( id: text("id").notNull().primaryKey(), name: text("name"), email: text("email").notNull(), - emailVerified: timestamp("emailVerified", { mode: "date" }), + emailVerified: timestamp("emailVerified", { mode: "date", withTimezone: true }), image: text("image"), }, (table) => [ @@ -62,7 +62,7 @@ export const sessions = pgTable( userId: text("userId") .notNull() .references(() => users.id, { onDelete: "cascade" }), - expires: timestamp("expires", { mode: "date" }).notNull(), + expires: timestamp("expires", { mode: "date", withTimezone: true }).notNull(), }, (table) => [index("session_user_id_idx").on(table.userId)], ); @@ -72,7 +72,7 @@ export const verificationTokens = pgTable( { identifier: text("identifier").notNull(), token: text("token").notNull(), - expires: timestamp("expires", { mode: "date" }).notNull(), + expires: timestamp("expires", { mode: "date", withTimezone: true }).notNull(), // Wrong guesses against this identifier's sign-in code. Counted here, not // in the per-instance rate limiter, so every instance sees the same total // and a code dies after MAX_CODE_ATTEMPTS misses however requests spread. diff --git a/packages/db/src/schemas/bootcamp.ts b/packages/db/src/schemas/bootcamp.ts index d4d7ae58..b9e1826c 100644 --- a/packages/db/src/schemas/bootcamp.ts +++ b/packages/db/src/schemas/bootcamp.ts @@ -41,8 +41,8 @@ export const bootcampWorkshops = pgTable( recordingUrl: text("recording_url"), // Draft by default so saving metadata cannot expose a half-uploaded week. isPublished: boolean("is_published").notNull().default(false), - createdAt: timestamp("created_at").defaultNow().notNull(), - updatedAt: timestamp("updated_at").defaultNow().notNull(), + createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(), + updatedAt: timestamp("updated_at", { withTimezone: true }).defaultNow().notNull(), }, (table) => [ // A unique index, not a constraint: drizzle-kit reads constraint columns diff --git a/packages/db/src/schemas/club-projects.ts b/packages/db/src/schemas/club-projects.ts index 5734df9a..b4772a97 100644 --- a/packages/db/src/schemas/club-projects.ts +++ b/packages/db/src/schemas/club-projects.ts @@ -47,8 +47,8 @@ export const clubProjects = pgTable( }), sortOrder: integer("sort_order").notNull().default(0), isPublished: boolean("is_published").notNull().default(true), - createdAt: timestamp("created_at").defaultNow().notNull(), - updatedAt: timestamp("updated_at").defaultNow().notNull(), + createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(), + updatedAt: timestamp("updated_at", { withTimezone: true }).defaultNow().notNull(), }, (table) => [ index("club_project_status_idx").on(table.status), diff --git a/packages/db/src/schemas/events.ts b/packages/db/src/schemas/events.ts index f0565c2c..cfd48c4d 100644 --- a/packages/db/src/schemas/events.ts +++ b/packages/db/src/schemas/events.ts @@ -24,7 +24,7 @@ export const events = pgTable( title: text("title").notNull(), description: text("description"), location: text("location"), - eventDate: timestamp("event_date").notNull(), + eventDate: timestamp("event_date", { withTimezone: true }).notNull(), qrCode: text("qr_code").notNull().unique(), checkInEnabled: boolean("check_in_enabled").notNull().default(true), /** @@ -50,8 +50,8 @@ export const events = pgTable( createdById: text("created_by_id") .notNull() .references(() => users.id, { onDelete: "cascade" }), - createdAt: timestamp("created_at").defaultNow().notNull(), - updatedAt: timestamp("updated_at").defaultNow().notNull(), + createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(), + updatedAt: timestamp("updated_at", { withTimezone: true }).defaultNow().notNull(), }, (table) => [ // One event per week per bootcamp. Nulls count as distinct in Postgres, so @@ -85,7 +85,7 @@ export const eventCheckIns = pgTable( checkInMethod: text("check_in_method", { enum: ["qr_code", "manual"] }) .notNull() .default("qr_code"), - checkedInAt: timestamp("checked_in_at").defaultNow().notNull(), + checkedInAt: timestamp("checked_in_at", { withTimezone: true }).defaultNow().notNull(), }, (table) => [ // A person is at a given event once. events.checkIn already treats a 23505 diff --git a/packages/db/src/schemas/hackathons.ts b/packages/db/src/schemas/hackathons.ts index 1fb9e45c..0d0daf46 100644 --- a/packages/db/src/schemas/hackathons.ts +++ b/packages/db/src/schemas/hackathons.ts @@ -31,10 +31,10 @@ export const hackathons = pgTable( name: text("name").notNull(), description: text("description"), location: text("location"), - startDate: timestamp("start_date").notNull(), - endDate: timestamp("end_date").notNull(), - registrationDeadline: timestamp("registration_deadline"), - hackingStartTime: timestamp("hacking_start_time"), + startDate: timestamp("start_date", { withTimezone: true }).notNull(), + endDate: timestamp("end_date", { withTimezone: true }).notNull(), + registrationDeadline: timestamp("registration_deadline", { withTimezone: true }), + hackingStartTime: timestamp("hacking_start_time", { withTimezone: true }), // 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"), @@ -64,8 +64,8 @@ export const hackathons = pgTable( .default(false), storeOpen: boolean("store_open").notNull().default(false), storeLocation: text("store_location"), - createdAt: timestamp("created_at").defaultNow().notNull(), - updatedAt: timestamp("updated_at").defaultNow().notNull(), + createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(), + updatedAt: timestamp("updated_at", { withTimezone: true }).defaultNow().notNull(), }, (table) => [ index("hackathon_status_idx").on(table.status), @@ -94,8 +94,8 @@ export const hackathonTeams = pgTable( .notNull() .references(() => users.id, { onDelete: "cascade" }), isOpen: boolean("is_open").notNull().default(true), - createdAt: timestamp("created_at").defaultNow().notNull(), - updatedAt: timestamp("updated_at").defaultNow().notNull(), + createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(), + updatedAt: timestamp("updated_at", { withTimezone: true }).defaultNow().notNull(), }, (table) => [ index("team_hackathon_id_idx").on(table.hackathonId), @@ -172,23 +172,23 @@ export const hackathonParticipants = pgTable( mlhInformationalEmails: boolean("mlh_informational_emails").default(false), // Participation tracking - checkedInAt: timestamp("checked_in_at"), + checkedInAt: timestamp("checked_in_at", { withTimezone: true }), // Set when an accepted hacker says they are coming. Null means no answer, // which is what organisers chase to free seats before the event. - attendanceConfirmedAt: timestamp("attendance_confirmed_at"), + attendanceConfirmedAt: timestamp("attendance_confirmed_at", { withTimezone: true }), hasSubmittedProject: boolean("has_submitted_project") .notNull() .default(false), // Stamped per participant as their acceptance mail leaves. A mass send is // thousands of round trips and can die halfway; without a per-row marker the // only safe retry is none, and the unsafe one mails everybody twice. - acceptanceEmailSentAt: timestamp("acceptance_email_sent_at"), + acceptanceEmailSentAt: timestamp("acceptance_email_sent_at", { withTimezone: true }), // Which acceptance wave took this applicant, 1-based. Null while pending, and // null forever for anyone accepted one at a time from the table. acceptanceWave: integer("acceptance_wave"), - registeredAt: timestamp("registered_at").defaultNow().notNull(), - updatedAt: timestamp("updated_at").defaultNow().notNull(), + registeredAt: timestamp("registered_at", { withTimezone: true }).defaultNow().notNull(), + updatedAt: timestamp("updated_at", { withTimezone: true }).defaultNow().notNull(), }, (table) => [ // No standalone hackathon_id index: it leads both the composite below and @@ -249,12 +249,12 @@ export const hackathonProjects = pgTable( .default("draft"), score: integer("score"), ranking: integer("ranking"), - submittedAt: timestamp("submitted_at"), + submittedAt: timestamp("submitted_at", { withTimezone: true }), // Set when an organiser pulls the project. A team's own withdrawal leaves // it null, which is how submitProject tells the two drafts apart. - withdrawnByAdminAt: timestamp("withdrawn_by_admin_at"), - createdAt: timestamp("created_at").defaultNow().notNull(), - updatedAt: timestamp("updated_at").defaultNow().notNull(), + withdrawnByAdminAt: timestamp("withdrawn_by_admin_at", { withTimezone: true }), + createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(), + updatedAt: timestamp("updated_at", { withTimezone: true }).defaultNow().notNull(), }, (table) => [ index("project_hackathon_id_idx").on(table.hackathonId), @@ -306,19 +306,19 @@ export const hackathonInterest = pgTable( // whole reason the list exists, and a send of thousands runs in batches from // an admin's browser — so it has to be resumable per recipient, exactly like // acceptanceEmailSentAt. - registrationOpenEmailSentAt: timestamp("registration_open_email_sent_at"), + registrationOpenEmailSentAt: timestamp("registration_open_email_sent_at", { withTimezone: true }), /** Same claim mechanism as the announcement recipients above. */ - registrationOpenEmailClaimedAt: timestamp( - "registration_open_email_claimed_at", - ), + registrationOpenEmailClaimedAt: timestamp("registration_open_email_claimed_at", { + withTimezone: true, + }), // Set when the provider rejected this address, so a retry can tell a // never-attempted recipient from a failed one, and a permanently bad address // cannot keep the send reporting itself unfinished. - registrationOpenEmailFailedAt: timestamp( - "registration_open_email_failed_at", - ), - createdAt: timestamp("created_at").defaultNow().notNull(), - updatedAt: timestamp("updated_at").defaultNow().notNull(), + registrationOpenEmailFailedAt: timestamp("registration_open_email_failed_at", { + withTimezone: true, + }), + createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(), + updatedAt: timestamp("updated_at", { withTimezone: true }).defaultNow().notNull(), }, (table) => [ // hackathon_id alone leads hackathon_interest_hackathon_user_idx below, which already @@ -407,8 +407,8 @@ export const hackathonEvents = pgTable( enum: ["workshop", "meal", "ceremony", "activity", "sponsor_session"], }).notNull(), location: text("location").notNull(), - startTime: timestamp("start_time").notNull(), - endTime: timestamp("end_time").notNull(), + startTime: timestamp("start_time", { withTimezone: true }).notNull(), + endTime: timestamp("end_time", { withTimezone: true }).notNull(), // What attending is worth. Copied onto each attendance row at check-in, so // editing it later never changes what anyone already earned. points: integer("points").notNull().default(0), @@ -418,8 +418,8 @@ export const hackathonEvents = pgTable( // event is running. checkInCode: text("check_in_code"), selfCheckIn: boolean("self_check_in").notNull().default(false), - createdAt: timestamp("created_at").defaultNow().notNull(), - updatedAt: timestamp("updated_at").defaultNow().notNull(), + createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(), + updatedAt: timestamp("updated_at", { withTimezone: true }).defaultNow().notNull(), }, (table) => [ index("event_hackathon_id_idx").on(table.hackathonId), @@ -441,7 +441,7 @@ export const hackathonEventAttendees = pgTable( .notNull() .references(() => hackathonEvents.id, { onDelete: "cascade" }), participantId: uuid("participant_id").notNull(), - checkedInAt: timestamp("checked_in_at").defaultNow().notNull(), + checkedInAt: timestamp("checked_in_at", { withTimezone: true }).defaultNow().notNull(), // The event's points at the moment of check-in. Null on rows from before // points existed, which count as zero. No default on purpose: every writer // must copy the event's value, or the number is invented. @@ -530,12 +530,12 @@ export const hackathonCheckInFlags = pgTable( onDelete: "set null", }), attempts: integer("attempts").notNull().default(1), - // Written from the app clock, like checked_in_at: the rule compares against - // it, and the database's now() follows the session's TimeZone. - createdAt: timestamp("created_at").defaultNow().notNull(), - lastAttemptAt: timestamp("last_attempt_at").defaultNow().notNull(), + // Written from the app clock, like checked_in_at, which the rule compares + // against. + createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(), + lastAttemptAt: timestamp("last_attempt_at", { withTimezone: true }).defaultNow().notNull(), // An organiser reviewed the flag and cleared it. It stays on record. - dismissedAt: timestamp("dismissed_at"), + dismissedAt: timestamp("dismissed_at", { withTimezone: true }), dismissedById: text("dismissed_by_id").references(() => users.id, { onDelete: "set null", }), @@ -615,7 +615,7 @@ export const hackathonAnnouncements = pgTable( createdById: text("created_by_id").references(() => users.id, { onDelete: "set null", }), - createdAt: timestamp("created_at").defaultNow().notNull(), + createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(), }, (table) => [ index("hackathon_announcement_hackathon_id_idx").on(table.hackathonId), @@ -643,11 +643,11 @@ export const hackathonAnnouncementRecipients = pgTable( // overlapping requests both select the same `sent_at IS NULL` rows and both // send. The claim is an atomic UPDATE, so exactly one wins each row, and a // claim older than CLAIM_TIMEOUT is reclaimable so a dead batch resumes. - claimedAt: timestamp("claimed_at"), - sentAt: timestamp("sent_at"), + claimedAt: timestamp("claimed_at", { withTimezone: true }), + sentAt: timestamp("sent_at", { withTimezone: true }), // Set when the provider rejected this address, so a retry can tell a // never-attempted recipient from a failed one. - failedAt: timestamp("failed_at"), + failedAt: timestamp("failed_at", { withTimezone: true }), }, (table) => [ index("hackathon_announcement_recipient_pending_idx").on( @@ -707,7 +707,7 @@ export const hackathonBans = pgTable( bannedBy: text("banned_by").references(() => users.id, { onDelete: "set null", }), - createdAt: timestamp("created_at").defaultNow().notNull(), + createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(), }, (table) => [uniqueIndex("hackathon_ban_email_idx").on(table.email)], ); diff --git a/packages/db/src/schemas/initiatives.ts b/packages/db/src/schemas/initiatives.ts index 996d4c43..9e5f175e 100644 --- a/packages/db/src/schemas/initiatives.ts +++ b/packages/db/src/schemas/initiatives.ts @@ -35,8 +35,8 @@ export const projectLeaders = pgTable( appointedBy: text("appointed_by").references(() => users.id, { onDelete: "set null", }), - createdAt: timestamp("created_at").defaultNow().notNull(), - updatedAt: timestamp("updated_at").defaultNow().notNull(), + createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(), + updatedAt: timestamp("updated_at", { withTimezone: true }).defaultNow().notNull(), }, (table) => [ // The unique constraint below indexes user_id already. @@ -86,16 +86,16 @@ export const initiatives = pgTable( // four is a leader plus three at `maxMembers = 3`. Null means uncapped; zero // would be an initiative nobody can join. maxMembers: integer("max_members"), - archivedAt: timestamp("archived_at"), + archivedAt: timestamp("archived_at", { withTimezone: true }), /** Set when an admin approves or declines a proposal. */ - reviewedAt: timestamp("reviewed_at"), + reviewedAt: timestamp("reviewed_at", { withTimezone: true }), reviewedById: text("reviewed_by_id").references(() => users.id, { onDelete: "set null", }), /** The admin's note back to the proposer, shown on a decline. */ reviewNote: text("review_note"), - createdAt: timestamp("created_at").defaultNow().notNull(), - updatedAt: timestamp("updated_at").defaultNow().notNull(), + createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(), + updatedAt: timestamp("updated_at", { withTimezone: true }).defaultNow().notNull(), }, (table) => [ index("initiative_leader_idx").on(table.leaderUserId), @@ -137,11 +137,11 @@ export const initiativeApplications = pgTable( // PDF and never selected by the queue query, only by applicantResume. resumeFileName: text("resume_file_name"), resumeData: text("resume_data"), - resumeUploadedAt: timestamp("resume_uploaded_at"), + resumeUploadedAt: timestamp("resume_uploaded_at", { withTimezone: true }), // Re-stamped on re-apply, so the leader's queue is ordered by when the hand // actually went up. - appliedAt: timestamp("applied_at").defaultNow().notNull(), - decidedAt: timestamp("decided_at"), + appliedAt: timestamp("applied_at", { withTimezone: true }).defaultNow().notNull(), + decidedAt: timestamp("decided_at", { withTimezone: true }), decidedById: text("decided_by_id").references(() => users.id, { onDelete: "set null", }), diff --git a/packages/db/src/schemas/judge.ts b/packages/db/src/schemas/judge.ts index 5bac93cb..225f81ce 100644 --- a/packages/db/src/schemas/judge.ts +++ b/packages/db/src/schemas/judge.ts @@ -44,8 +44,8 @@ export const judges = pgTable( shirtSize: text("shirt_size"), whyJudge: text("why_judge"), isActive: boolean("is_active").notNull().default(false), - createdAt: timestamp("created_at").defaultNow().notNull(), - updatedAt: timestamp("updated_at").defaultNow().notNull(), + createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(), + updatedAt: timestamp("updated_at", { withTimezone: true }).defaultNow().notNull(), }, (table) => [ // user_id alone leads the unique index below, which is what the portal's @@ -69,7 +69,7 @@ export const judgeAssignments = pgTable( hackathonId: uuid("hackathon_id") .notNull() .references(() => hackathons.id, { onDelete: "cascade" }), - assignedAt: timestamp("assigned_at").defaultNow().notNull(), + assignedAt: timestamp("assigned_at", { withTimezone: true }).defaultNow().notNull(), status: text("status", { enum: ["pending", "approved", "rejected"] }) .notNull() .default("pending"), @@ -126,8 +126,8 @@ export const judgingProjects = pgTable( // Set when an organiser pulls the submission out of the event. A flag rather // than a delete: judge_vote cascades off this row, so deleting would erase // real scores and shift the z-score normalisation for every other project. - withdrawnAt: timestamp("withdrawn_at"), - createdAt: timestamp("created_at").defaultNow().notNull(), + withdrawnAt: timestamp("withdrawn_at", { withTimezone: true }), + createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(), }, (table) => [ index("judging_project_hackathon_id_idx").on(table.hackathonId), @@ -168,8 +168,8 @@ export const judgeVotes = pgTable( scoreSoundness: integer("score_soundness"), // Soundness & Accuracy comment: text("comment"), durationSeconds: integer("duration_seconds"), // how long the judge spent on this project - votedAt: timestamp("voted_at").defaultNow().notNull(), - updatedAt: timestamp("updated_at").defaultNow().notNull(), + votedAt: timestamp("voted_at", { withTimezone: true }).defaultNow().notNull(), + updatedAt: timestamp("updated_at", { withTimezone: true }).defaultNow().notNull(), }, (table) => [ index("vote_project_id_idx").on(table.projectId), @@ -213,8 +213,8 @@ export const hackathonResults = pgTable( voteCount: integer("vote_count").notNull().default(0), // Null while the snapshot is a draft. Set on publish, cleared on unpublish, // which is what makes publishing reversible. - publishedAt: timestamp("published_at"), - computedAt: timestamp("computed_at").defaultNow().notNull(), + publishedAt: timestamp("published_at", { withTimezone: true }), + computedAt: timestamp("computed_at", { withTimezone: true }).defaultNow().notNull(), }, (table) => [ // One placing per project per prize. Recomputing upserts onto this rather @@ -315,8 +315,8 @@ export const judgeInterest = pgTable( expertise: text("expertise"), linkedinUrl: text("linkedin_url"), message: text("message"), - createdAt: timestamp("created_at").defaultNow().notNull(), - updatedAt: timestamp("updated_at").defaultNow().notNull(), + createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(), + updatedAt: timestamp("updated_at", { withTimezone: true }).defaultNow().notNull(), }, (table) => [ // The conflict target for the upsert, so a double submit is one row. diff --git a/packages/db/src/schemas/judging.ts b/packages/db/src/schemas/judging.ts index 2b5d2276..f77ea466 100644 --- a/packages/db/src/schemas/judging.ts +++ b/packages/db/src/schemas/judging.ts @@ -42,24 +42,24 @@ export const judgingConfigs = pgTable("judging_config", { state: text("state", { enum: JUDGING_STATES }) .notNull() .default("draft"), - openedAt: timestamp("opened_at"), - closedAt: timestamp("closed_at"), + openedAt: timestamp("opened_at", { withTimezone: true }), + closedAt: timestamp("closed_at", { withTimezone: true }), // Member judges see every scoped score, not only projects they judged. // Guests never do. showAllScores: boolean("show_all_scores").notNull().default(false), // Set by the first room link or the first claim. After it, a Devpost import // only adds projects; replacing the inventory needs typed confirmation. - inventoryLockedAt: timestamp("inventory_locked_at"), + inventoryLockedAt: timestamp("inventory_locked_at", { withTimezone: true }), inventoryLockedById: text("inventory_locked_by_id").references( () => users.id, { onDelete: "set null" }, ), - groupsInitializedAt: timestamp("groups_initialized_at"), + groupsInitializedAt: timestamp("groups_initialized_at", { withTimezone: true }), // Hackers see their times and rooms only once this is on. itineraryPublished: boolean("itinerary_published").notNull().default(false), // Schedule fell over: hackers get project search, roster and feedback hide. emergencyMode: boolean("emergency_mode").notNull().default(false), - claimsStartedAt: timestamp("claims_started_at"), + claimsStartedAt: timestamp("claims_started_at", { withTimezone: true }), // While judging runs, presentations of a judge who left or went quiet move // to judges who are here. autoRebalance: boolean("auto_rebalance").notNull().default(true), @@ -70,9 +70,9 @@ export const judgingConfigs = pgTable("judging_config", { repoCheckGraceMinutes: integer("repo_check_grace_minutes") .notNull() .default(0), - repoCheckLastRunAt: timestamp("repo_check_last_run_at"), - createdAt: timestamp("created_at").defaultNow().notNull(), - updatedAt: timestamp("updated_at").defaultNow().notNull(), + repoCheckLastRunAt: timestamp("repo_check_last_run_at", { withTimezone: true }), + createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(), + updatedAt: timestamp("updated_at", { withTimezone: true }).defaultNow().notNull(), }); // A judged project. `source` says where it came from: a Devpost export row @@ -97,23 +97,23 @@ export const judgingEntries = pgTable( universities: text("universities").array().notNull(), prizeCategories: text("prize_categories").array().notNull(), participantCount: integer("participant_count").notNull().default(1), - projectCreatedAt: timestamp("project_created_at"), - submittedAt: timestamp("submitted_at"), + projectCreatedAt: timestamp("project_created_at", { withTimezone: true }), + submittedAt: timestamp("submitted_at", { withTimezone: true }), // Soft delete: evaluations and deliberation notes keep pointing at it. - deletedAt: timestamp("deleted_at"), + deletedAt: timestamp("deleted_at", { withTimezone: true }), deletedById: text("deleted_by_id").references(() => users.id, { onDelete: "set null", }), // An organiser pulled this entry from prizes, usually after a check-in rule // break. Judges still score it, so nothing about the room schedule changes; // only placements and results leave it out. - prizeIneligibleAt: timestamp("prize_ineligible_at"), + prizeIneligibleAt: timestamp("prize_ineligible_at", { withTimezone: true }), prizeIneligibleById: text("prize_ineligible_by_id").references( () => users.id, { onDelete: "set null" }, ), - createdAt: timestamp("created_at").defaultNow().notNull(), - updatedAt: timestamp("updated_at").defaultNow().notNull(), + createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(), + updatedAt: timestamp("updated_at", { withTimezone: true }).defaultNow().notNull(), }, (table) => [ index("judging_entry_hackathon_idx").on(table.hackathonId), @@ -151,12 +151,12 @@ export const judgingEntryMembers = pgTable( userId: text("user_id").references(() => users.id, { onDelete: "set null", }), - claimedAt: timestamp("claimed_at"), + claimedAt: timestamp("claimed_at", { withTimezone: true }), // Set when a claimed teammate added this person, rather than Devpost. invitedById: text("invited_by_id").references(() => users.id, { onDelete: "set null", }), - createdAt: timestamp("created_at").defaultNow().notNull(), + createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(), }, (table) => [ index("judging_entry_member_entry_idx").on(table.entryId), @@ -188,7 +188,7 @@ export const judgingRepoChecks = pgTable( enum: ["ok", "late", "no_repo", "unreadable", "error"], }).notNull(), // GitHub's own clock for the last push to any branch. - pushedAt: timestamp("pushed_at"), + pushedAt: timestamp("pushed_at", { withTimezone: true }), // At most 20 commits and 20 pushes; shown for context, never decided on. evidence: jsonb("evidence").$type<{ commits: { @@ -200,7 +200,7 @@ export const judgingRepoChecks = pgTable( }[]; pushes: { at: string; ref: string | null; pusher: string | null }[]; }>(), - checkedAt: timestamp("checked_at").notNull(), + checkedAt: timestamp("checked_at", { withTimezone: true }).notNull(), decision: text("decision", { enum: ["pending", "disqualified", "cleared"], }) @@ -209,12 +209,12 @@ export const judgingRepoChecks = pgTable( decidedById: text("decided_by_id").references(() => users.id, { onDelete: "set null", }), - decidedAt: timestamp("decided_at"), + decidedAt: timestamp("decided_at", { withTimezone: true }), note: text("note"), removedEntry: boolean("removed_entry").notNull().default(false), // The `deletedAt` the disqualification set, so reinstating undoes only // that removal and not a later manual one. - removedDeletedAt: timestamp("removed_deleted_at"), + removedDeletedAt: timestamp("removed_deleted_at", { withTimezone: true }), // Every repo checked for the entry (at most 3); the columns above describe // the one that decided the outcome. repos: jsonb("repos").$type< @@ -258,13 +258,13 @@ export const judgingClaimLinks = pgTable( .notNull() .references(() => hackathons.id, { onDelete: "cascade" }), token: text("token"), - sentAt: timestamp("sent_at"), - expiresAt: timestamp("expires_at").notNull(), - consumedAt: timestamp("consumed_at"), + sentAt: timestamp("sent_at", { withTimezone: true }), + expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), + consumedAt: timestamp("consumed_at", { withTimezone: true }), consumedById: text("consumed_by_id").references(() => users.id, { onDelete: "set null", }), - createdAt: timestamp("created_at").defaultNow().notNull(), + createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(), }, (table) => [ uniqueIndex("judging_claim_link_member_idx").on(table.memberId), @@ -297,7 +297,7 @@ export const judgingChallenges = pgTable( .notNull() .default("scheduled"), displayOrder: integer("display_order").notNull().default(0), - createdAt: timestamp("created_at").defaultNow().notNull(), + createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(), }, (table) => [ index("judging_challenge_hackathon_idx").on(table.hackathonId), @@ -356,7 +356,7 @@ export const judgingBuildings = pgTable( .notNull() .references(() => hackathons.id, { onDelete: "cascade" }), name: text("name").notNull(), - createdAt: timestamp("created_at").defaultNow().notNull(), + createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(), }, (table) => [ uniqueIndex("judging_building_name_idx").on(table.hackathonId, table.name), @@ -386,8 +386,8 @@ export const judgingRooms = pgTable( name: text("name").notNull(), kind: text("kind", { enum: judgingRoomKinds }).notNull().default("room"), displayOrder: integer("display_order").notNull().default(0), - archivedAt: timestamp("archived_at"), - createdAt: timestamp("created_at").defaultNow().notNull(), + archivedAt: timestamp("archived_at", { withTimezone: true }), + createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(), }, (table) => [ index("judging_room_hackathon_idx").on(table.hackathonId), @@ -413,8 +413,8 @@ export const judgingRoomLinks = pgTable( createdById: text("created_by_id").references(() => users.id, { onDelete: "set null", }), - createdAt: timestamp("created_at").defaultNow().notNull(), - revokedAt: timestamp("revoked_at"), + createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(), + revokedAt: timestamp("revoked_at", { withTimezone: true }), revokedById: text("revoked_by_id").references(() => users.id, { onDelete: "set null", }), @@ -438,7 +438,7 @@ export const judgingJudges = pgTable( kind: text("kind", { enum: ["member", "guest"] }).notNull(), userId: text("user_id").references(() => users.id, { onDelete: "cascade" }), displayName: text("display_name").notNull(), - createdAt: timestamp("created_at").defaultNow().notNull(), + createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(), }, (table) => [ index("judging_judge_hackathon_idx").on(table.hackathonId), @@ -467,10 +467,10 @@ export const judgingGuestSessions = pgTable( judgeId: uuid("judge_id").references(() => judgingJudges.id, { onDelete: "set null", }), - expiresAt: timestamp("expires_at").notNull(), - completedAt: timestamp("completed_at"), - revokedAt: timestamp("revoked_at"), - createdAt: timestamp("created_at").defaultNow().notNull(), + expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(), + completedAt: timestamp("completed_at", { withTimezone: true }), + revokedAt: timestamp("revoked_at", { withTimezone: true }), + createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(), }, (table) => [ uniqueIndex("judging_guest_session_token_idx").on(table.tokenHash), @@ -492,9 +492,9 @@ export const judgingPresence = pgTable( hackathonId: uuid("hackathon_id") .notNull() .references(() => hackathons.id, { onDelete: "cascade" }), - joinedAt: timestamp("joined_at").defaultNow().notNull(), - lastSeenAt: timestamp("last_seen_at").defaultNow().notNull(), - leftAt: timestamp("left_at"), + joinedAt: timestamp("joined_at", { withTimezone: true }).defaultNow().notNull(), + lastSeenAt: timestamp("last_seen_at", { withTimezone: true }).defaultNow().notNull(), + leftAt: timestamp("left_at", { withTimezone: true }), }, (table) => [ uniqueIndex("judging_presence_open_idx") @@ -513,8 +513,8 @@ export const judgingSchedules = pgTable( hackathonId: uuid("hackathon_id") .notNull() .references(() => hackathons.id, { onDelete: "cascade" }), - windowStart: timestamp("window_start").notNull(), - windowEnd: timestamp("window_end").notNull(), + windowStart: timestamp("window_start", { withTimezone: true }).notNull(), + windowEnd: timestamp("window_end", { withTimezone: true }).notNull(), setupMinutes: integer("setup_minutes").notNull().default(2), judgingMinutes: integer("judging_minutes").notNull().default(6), teardownMinutes: integer("teardown_minutes").notNull().default(2), @@ -526,17 +526,17 @@ export const judgingSchedules = pgTable( .default(20), // Saved from a relaxed solve, where cross-building walks got only the // same-building break. An organiser had to say yes to that. - reducedBreaksAcknowledgedAt: timestamp("reduced_breaks_acknowledged_at"), + reducedBreaksAcknowledgedAt: timestamp("reduced_breaks_acknowledged_at", { withTimezone: true }), // The first submitted evaluation. After it the schedule cannot be dropped. - firstResultAt: timestamp("first_result_at"), + firstResultAt: timestamp("first_result_at", { withTimezone: true }), // The last time judges were re-balanced on their own, and how many // presentations that moved. - lastRebalancedAt: timestamp("last_rebalanced_at"), + lastRebalancedAt: timestamp("last_rebalanced_at", { withTimezone: true }), lastRebalanceChanged: integer("last_rebalance_changed").notNull().default(0), createdById: text("created_by_id").references(() => users.id, { onDelete: "set null", }), - createdAt: timestamp("created_at").defaultNow().notNull(), + createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(), }, (table) => [ uniqueIndex("judging_schedule_hackathon_idx").on(table.hackathonId), @@ -567,9 +567,9 @@ export const judgingAppointments = pgTable( roomId: uuid("room_id") .notNull() .references(() => judgingRooms.id, { onDelete: "cascade" }), - startsAt: timestamp("starts_at").notNull(), - deadlineAt: timestamp("deadline_at").notNull(), - endsAt: timestamp("ends_at").notNull(), + startsAt: timestamp("starts_at", { withTimezone: true }).notNull(), + deadlineAt: timestamp("deadline_at", { withTimezone: true }).notNull(), + endsAt: timestamp("ends_at", { withTimezone: true }).notNull(), // Compare-and-swap for moves made from two organiser screens at once. revision: integer("revision").notNull().default(0), // The one judge who grades this presentation. Null until judges are @@ -622,8 +622,8 @@ export const judgingAnnouncements = pgTable( createdById: text("created_by_id").references(() => users.id, { onDelete: "set null", }), - createdAt: timestamp("created_at").defaultNow().notNull(), - clearedAt: timestamp("cleared_at"), + createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(), + clearedAt: timestamp("cleared_at", { withTimezone: true }), }, (table) => [ uniqueIndex("judging_announcement_global_idx") @@ -656,7 +656,7 @@ export const judgingRubricItems = pgTable( guestVisibility: text("guest_visibility", { enum: ["public", "optional", "private"], }), - createdAt: timestamp("created_at").defaultNow().notNull(), + createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(), }, (table) => [index("judging_rubric_item_hackathon_idx").on(table.hackathonId)], ); @@ -680,11 +680,11 @@ export const judgingEvaluations = pgTable( appointmentId: uuid("appointment_id"), isComplete: boolean("is_complete").notNull().default(false), revision: integer("revision").notNull().default(1), - submittedAt: timestamp("submitted_at").defaultNow().notNull(), + submittedAt: timestamp("submitted_at", { withTimezone: true }).defaultNow().notNull(), // Set when a draft ran past its deadline and was submitted for the judge. - autoSubmittedAt: timestamp("auto_submitted_at"), - createdAt: timestamp("created_at").defaultNow().notNull(), - updatedAt: timestamp("updated_at").defaultNow().notNull(), + autoSubmittedAt: timestamp("auto_submitted_at", { withTimezone: true }), + createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(), + updatedAt: timestamp("updated_at", { withTimezone: true }).defaultNow().notNull(), }, (table) => [ uniqueIndex("judging_evaluation_task_idx").on( @@ -732,9 +732,9 @@ export const judgingEvaluationDrafts = pgTable( appointmentId: uuid("appointment_id"), ratings: jsonb("ratings").$type().notNull(), responses: jsonb("responses").$type().notNull(), - deadlineAt: timestamp("deadline_at"), + deadlineAt: timestamp("deadline_at", { withTimezone: true }), revision: integer("revision").notNull().default(0), - updatedAt: timestamp("updated_at").defaultNow().notNull(), + updatedAt: timestamp("updated_at", { withTimezone: true }).defaultNow().notNull(), }, (table) => [ uniqueIndex("judging_evaluation_draft_task_idx").on( @@ -820,7 +820,7 @@ export const judgingEvaluationRevisions = pgTable( evaluationId: uuid("evaluation_id").notNull(), revision: integer("revision").notNull(), snapshot: jsonb("snapshot").$type().notNull(), - createdAt: timestamp("created_at").defaultNow().notNull(), + createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(), }, (table) => [ index("judging_evaluation_revision_eval_idx").on(table.evaluationId), @@ -842,7 +842,7 @@ export const judgingDeliberationSections = pgTable( .references(() => judgingJudges.id, { onDelete: "cascade" }), title: text("title").notNull(), displayOrder: integer("display_order").notNull().default(0), - createdAt: timestamp("created_at").defaultNow().notNull(), + createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(), }, (table) => [index("judging_deliberation_section_judge_idx").on(table.judgeId)], ); @@ -893,8 +893,8 @@ export const judgingPlacements = pgTable( // calibration existed. rawScore: numeric("raw_score", { precision: 4, scale: 2 }), evaluationCount: integer("evaluation_count").notNull().default(0), - publishedAt: timestamp("published_at"), - computedAt: timestamp("computed_at").defaultNow().notNull(), + publishedAt: timestamp("published_at", { withTimezone: true }), + computedAt: timestamp("computed_at", { withTimezone: true }).defaultNow().notNull(), }, (table) => [ // Leads with hackathon_id, so it also serves the by-edition reads. diff --git a/packages/db/src/schemas/members.ts b/packages/db/src/schemas/members.ts index 5d813a43..a1f5f8ac 100644 --- a/packages/db/src/schemas/members.ts +++ b/packages/db/src/schemas/members.ts @@ -28,8 +28,8 @@ export const userProfiles = pgTable( // accounts cannot claim the same one; Postgres treats NULLs as distinct, so // everyone else can still leave it empty. gtEmail: text("gt_email").unique(), - createdAt: timestamp("created_at").defaultNow().notNull(), - updatedAt: timestamp("updated_at").defaultNow().notNull(), + createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(), + updatedAt: timestamp("updated_at", { withTimezone: true }).defaultNow().notNull(), }, // No user_id index: the unique constraint on it is one. ); @@ -61,17 +61,17 @@ export const members = pgTable( // expires, so it cannot be the access check for a one-semester program — // every gate compares this against currentTerm(). bootcampTerm: text("bootcamp_term"), - joinedAt: timestamp("joined_at").defaultNow().notNull(), - membershipStartDate: timestamp("membership_start_date").notNull(), - membershipEndDate: timestamp("membership_end_date"), + joinedAt: timestamp("joined_at", { withTimezone: true }).defaultNow().notNull(), + membershipStartDate: timestamp("membership_start_date", { withTimezone: true }).notNull(), + membershipEndDate: timestamp("membership_end_date", { withTimezone: true }), renewalCount: integer("renewal_count").notNull().default(0), skills: text("skills").array(), interests: text("interests").array(), linkedinUrl: text("linkedin_url"), githubUrl: text("github_url"), portfolioUrl: text("portfolio_url"), - createdAt: timestamp("created_at").defaultNow().notNull(), - updatedAt: timestamp("updated_at").defaultNow().notNull(), + createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(), + updatedAt: timestamp("updated_at", { withTimezone: true }).defaultNow().notNull(), }, (table) => [ // For the "Active Members" directory listing. user_id is indexed by @@ -96,10 +96,10 @@ export const membershipHistory = pgTable( action: text("action", { enum: ["joined", "renewed", "expired", "cancelled"], }).notNull(), - startDate: timestamp("start_date").notNull(), - endDate: timestamp("end_date"), + startDate: timestamp("start_date", { withTimezone: true }).notNull(), + endDate: timestamp("end_date", { withTimezone: true }), notes: text("notes"), - createdAt: timestamp("created_at").defaultNow().notNull(), + createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(), }, (table) => [index("history_member_id_idx").on(table.memberId)], ); diff --git a/packages/db/src/schemas/points.ts b/packages/db/src/schemas/points.ts index b7ed826a..bcddc09f 100644 --- a/packages/db/src/schemas/points.ts +++ b/packages/db/src/schemas/points.ts @@ -39,7 +39,7 @@ export const hackathonPointAdjustments = pgTable( actorId: text("actor_id").references(() => users.id, { onDelete: "set null", }), - createdAt: timestamp("created_at").defaultNow().notNull(), + createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(), }, (table) => [ index("point_adjustment_participant_idx").on( @@ -76,8 +76,8 @@ export const hackathonStoreItems = pgTable( displayOrder: integer("display_order").notNull().default(0), // Optimistic lock for two organisers editing the same item. revision: integer("revision").notNull().default(0), - createdAt: timestamp("created_at").defaultNow().notNull(), - updatedAt: timestamp("updated_at").defaultNow().notNull(), + createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(), + updatedAt: timestamp("updated_at", { withTimezone: true }).defaultNow().notNull(), }, (table) => [ index("store_item_hackathon_idx").on(table.hackathonId), @@ -108,8 +108,8 @@ export const hackathonStorePurchases = pgTable( actorId: text("actor_id").references(() => users.id, { onDelete: "set null", }), - createdAt: timestamp("created_at").defaultNow().notNull(), - voidedAt: timestamp("voided_at"), + createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(), + voidedAt: timestamp("voided_at", { withTimezone: true }), voidedById: text("voided_by_id").references(() => users.id, { onDelete: "set null", }), diff --git a/packages/db/src/schemas/resumes.ts b/packages/db/src/schemas/resumes.ts index e57945d4..166e128d 100644 --- a/packages/db/src/schemas/resumes.ts +++ b/packages/db/src/schemas/resumes.ts @@ -15,5 +15,5 @@ export const memberResumes = pgTable("member_resume", { storageKey: text("storage_key").notNull(), fileName: text("file_name").notNull(), sizeBytes: integer("size_bytes").notNull(), - uploadedAt: timestamp("uploaded_at").defaultNow().notNull(), + uploadedAt: timestamp("uploaded_at", { withTimezone: true }).defaultNow().notNull(), }); diff --git a/packages/db/src/schemas/security.ts b/packages/db/src/schemas/security.ts index 57c5a39c..dbb49ba9 100644 --- a/packages/db/src/schemas/security.ts +++ b/packages/db/src/schemas/security.ts @@ -23,7 +23,7 @@ export const auditLogs = pgTable( resourceId: text("resource_id"), metadata: jsonb("metadata"), severity: securitySeverityEnum("severity").default("info").notNull(), - createdAt: timestamp("created_at", { mode: "date" }).defaultNow().notNull(), + createdAt: timestamp("created_at", { mode: "date", withTimezone: true }).defaultNow().notNull(), }, (table) => [ index("audit_user_id_idx").on(table.userId), diff --git a/packages/db/src/schemas/settings.ts b/packages/db/src/schemas/settings.ts index 9f61f330..3e67cdc5 100644 --- a/packages/db/src/schemas/settings.ts +++ b/packages/db/src/schemas/settings.ts @@ -13,5 +13,5 @@ export const systemSettings = pgTable("system_settings", { allowPublicRegistration: boolean("allow_public_registration") .notNull() .default(true), - updatedAt: timestamp("updated_at").defaultNow().notNull(), + updatedAt: timestamp("updated_at", { withTimezone: true }).defaultNow().notNull(), }); diff --git a/packages/db/src/schemas/stripe.ts b/packages/db/src/schemas/stripe.ts index 66b73cae..3ef38905 100644 --- a/packages/db/src/schemas/stripe.ts +++ b/packages/db/src/schemas/stripe.ts @@ -37,12 +37,12 @@ export const stripePayments = pgTable( linkedUserId: text("linked_user_id").references(() => users.id, { onDelete: "set null", }), - linkedAt: timestamp("linked_at"), + linkedAt: timestamp("linked_at", { withTimezone: true }), // Metadata metadata: text("metadata"), // JSON string for any extra Stripe metadata - createdAt: timestamp("created_at").defaultNow().notNull(), - updatedAt: timestamp("updated_at").defaultNow().notNull(), + createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(), + updatedAt: timestamp("updated_at", { withTimezone: true }).defaultNow().notNull(), }, (table) => [ index("stripe_payment_customer_email_idx").on(table.customerEmail), @@ -79,7 +79,7 @@ export const userAccountLinks = pgTable( // Status isVerified: boolean("is_verified").notNull().default(true), - createdAt: timestamp("created_at").defaultNow().notNull(), + createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(), }, (table) => [ // linkAccount and attemptAutoLink both assume one link per user and one per diff --git a/packages/db/src/schemas/subteams.ts b/packages/db/src/schemas/subteams.ts index 7275f39a..ad995c11 100644 --- a/packages/db/src/schemas/subteams.ts +++ b/packages/db/src/schemas/subteams.ts @@ -56,12 +56,12 @@ export const subteams = pgTable( // questions are written. isOpen: boolean("is_open").notNull().default(false), /** Archived is hidden from members; its applications stay on the record. */ - archivedAt: timestamp("archived_at"), + archivedAt: timestamp("archived_at", { withTimezone: true }), createdById: text("created_by_id").references(() => users.id, { onDelete: "set null", }), - createdAt: timestamp("created_at").defaultNow().notNull(), - updatedAt: timestamp("updated_at").defaultNow().notNull(), + createdAt: timestamp("created_at", { withTimezone: true }).defaultNow().notNull(), + updatedAt: timestamp("updated_at", { withTimezone: true }).defaultNow().notNull(), }, (table) => [index("subteam_archived_idx").on(table.archivedAt)], ); @@ -103,8 +103,8 @@ export const subteamApplications = pgTable( .default(sql`'[]'::jsonb`), /** Anything else they want the admins to know. */ note: text("note"), - appliedAt: timestamp("applied_at").defaultNow().notNull(), - decidedAt: timestamp("decided_at"), + appliedAt: timestamp("applied_at", { withTimezone: true }).defaultNow().notNull(), + decidedAt: timestamp("decided_at", { withTimezone: true }), decidedById: text("decided_by_id").references(() => users.id, { onDelete: "set null", }), From 8a9b61c178b3c7c31ede42b5ceee4a558f89cfa7 Mon Sep 17 00:00:00 2001 From: aamoghS Date: Sat, 14 Nov 2026 18:55:13 -0500 Subject: [PATCH 2/3] fix(auth): cast sign-in expiries as timestamptz The verification-token SQL cast its ISO instants with ::timestamp, which drops the Z and lets the session TimeZone reinterpret the wall time once verificationToken.expires stores a zone. In a non-UTC session that shifts code expiry and the once-a-minute send gate by hours. ::timestamptz keeps the instant. --- packages/auth/src/adapter.ts | 2 +- packages/auth/src/config.ts | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/auth/src/adapter.ts b/packages/auth/src/adapter.ts index cc4a40cd..f8ec442a 100644 --- a/packages/auth/src/adapter.ts +++ b/packages/auth/src/adapter.ts @@ -44,7 +44,7 @@ function createAdapter(): Adapter | undefined { const expiresISO = token.expires.toISOString(); await db.execute(sql` INSERT INTO "verificationToken" ("identifier", "token", "expires") - VALUES (${token.identifier}, ${token.token}, ${expiresISO}::timestamp) + VALUES (${token.identifier}, ${token.token}, ${expiresISO}::timestamptz) `); return token; }, diff --git a/packages/auth/src/config.ts b/packages/auth/src/config.ts index 859d2778..11f33357 100644 --- a/packages/auth/src/config.ts +++ b/packages/auth/src/config.ts @@ -179,7 +179,7 @@ export const authConfig: NextAuthConfig = { const recent = await tx.execute(sql` SELECT 1 FROM "verificationToken" WHERE "identifier" = ${identifier} AND "token" LIKE 'custom:%' - AND "expires" > ${issuedWithinMinute}::timestamp + AND "expires" > ${issuedWithinMinute}::timestamptz LIMIT 1 `); if (recent.rows.length > 0) return false; @@ -190,7 +190,7 @@ export const authConfig: NextAuthConfig = { `); await tx.execute(sql` INSERT INTO "verificationToken" ("identifier", "token", "expires") - VALUES (${identifier}, ${customToken}, ${expiresISO}::timestamp) + VALUES (${identifier}, ${customToken}, ${expiresISO}::timestamptz) `); return true; }); From 66cd0c567d7dd813d89b94187badc8bdf3f4e95d Mon Sep 17 00:00:00 2001 From: aamoghS Date: Sat, 14 Nov 2026 18:57:53 -0500 Subject: [PATCH 3/3] fix(db): fail the deploy when a timestamp's time zone did not apply db:check only confirmed that declared columns exist, so a push that skipped a type change (timestamp to timestamptz) left the old type and still passed, and the build shipped code expecting the new one. It now compares every timestamp column's time zone with the declaration and fails the build on a mismatch, which keeps the running revision in place. --- packages/db/scripts/check-drift.mts | 24 +++++++++++++++++++++--- 1 file changed, 21 insertions(+), 3 deletions(-) diff --git a/packages/db/scripts/check-drift.mts b/packages/db/scripts/check-drift.mts index 6e04d9b0..b6edaaa0 100644 --- a/packages/db/scripts/check-drift.mts +++ b/packages/db/scripts/check-drift.mts @@ -5,7 +5,9 @@ * because the code leans on them for idempotency (23505 handling, "safe to * re-run"), and `drizzle-kit push < /dev/null` skips one that needs * confirmation — duplicates already in the table — while still exiting 0. - * Types and plain indexes are not checked. + * Timestamp columns are checked for their time zone: a type change push did + * not apply leaves the old type behind with every column still present. + * Other types and plain indexes are not checked. */ import * as dotenv from "dotenv"; import path from "path"; @@ -48,8 +50,9 @@ await client.connect(); const { rows } = await client.query<{ table_name: string; column_name: string; + data_type: string; }>( - `select table_name, column_name + `select table_name, column_name, data_type from information_schema.columns where table_schema = 'public'`, ); @@ -62,9 +65,11 @@ const { rows: indexRows } = await client.query<{ indexname: string }>( const liveIndexes = new Set(indexRows.map((row) => row.indexname)); const live = new Map>(); +const liveTypes = new Map(); for (const row of rows) { if (!live.has(row.table_name)) live.set(row.table_name, new Set()); live.get(row.table_name)!.add(row.column_name); + liveTypes.set(`${row.table_name}.${row.column_name}`, row.data_type); } const problems: string[] = []; @@ -92,6 +97,19 @@ for (const exported of Object.values(schema)) { problems.push(`table "${table.name}" is missing: ${missing.join(", ")}`); } + const wrongZone = table.columns.flatMap((column) => { + const declared = column.getSQLType(); + if (!declared.startsWith("timestamp")) return []; + const expected = declared.includes("with time zone") + ? "timestamp with time zone" + : "timestamp without time zone"; + const actual = liveTypes.get(`${table.name}.${column.name}`); + return actual && actual !== expected ? [`${column.name} is ${actual}`] : []; + }); + if (wrongZone.length > 0) { + problems.push(`table "${table.name}" has the wrong timestamp type: ${wrongZone.join(", ")}`); + } + const uniques = [ ...table.indexes .filter((index) => index.config.unique) @@ -120,5 +138,5 @@ if (problems.length > 0) { } console.log( - "Schema check passed: every declared table, column and unique constraint exists.", + "Schema check passed: every declared table, column and unique constraint exists, and timestamps carry the declared time zone.", );