Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions packages/api/src/routers/hackathon/admin/status.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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())`,
}
: {}),
})
Expand Down
5 changes: 2 additions & 3 deletions packages/api/src/services/points.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
2 changes: 1 addition & 1 deletion packages/auth/src/adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
},
Expand Down
4 changes: 2 additions & 2 deletions packages/auth/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
});
Expand Down
24 changes: 21 additions & 3 deletions packages/db/scripts/check-drift.mts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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'`,
);
Expand All @@ -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<string, Set<string>>();
const liveTypes = new Map<string, string>();
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[] = [];
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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.",
);
6 changes: 3 additions & 3 deletions packages/db/src/schemas/admins.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 }) => ({
Expand Down
6 changes: 3 additions & 3 deletions packages/db/src/schemas/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) => [
Expand Down Expand Up @@ -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)],
);
Expand All @@ -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.
Expand Down
4 changes: 2 additions & 2 deletions packages/db/src/schemas/bootcamp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions packages/db/src/schemas/club-projects.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
8 changes: 4 additions & 4 deletions packages/db/src/schemas/events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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),
/**
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down
Loading
Loading