brackt/app/models/tournament-result.ts
Chris Parsons 5a47300110
feat(models): add canonical tournament, participant, result, surface-elo models
Adds CRUD modules for the canonical tables created in commit 775b905.
Each module mirrors existing app/models conventions (database() from
~/database/context, schema from ~/database/schema, mock-based tests).

Key implementation notes:
- participant.ts exports use "Canonical" prefix (CanonicalParticipant,
  createCanonicalParticipant, etc.) to avoid collision with existing
  season-participant.ts exports
- All four models include comprehensive unit tests following the
  audit-log.test.ts pattern
- Tests use mocked db responses (no real database access)
- Upsert functions use onConflictDoUpdate for appropriate unique constraints

Part of Phase 1b of canonical tournament layer migration.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-01 20:16:53 +00:00

61 lines
1.7 KiB
TypeScript

import { eq, and, asc } from "drizzle-orm";
import { database } from "~/database/context";
import * as schema from "~/database/schema";
export type TournamentResult = typeof schema.tournamentResults.$inferSelect;
export type NewTournamentResult = typeof schema.tournamentResults.$inferInsert;
export async function upsertTournamentResult(
data: NewTournamentResult
): Promise<TournamentResult> {
if (!data.tournamentId || !data.participantId) {
throw new Error("tournamentId and participantId are required");
}
const db = database();
const [result] = await db
.insert(schema.tournamentResults)
.values(data)
.onConflictDoUpdate({
target: [
schema.tournamentResults.tournamentId,
schema.tournamentResults.participantId,
],
set: {
placement: data.placement,
rawScore: data.rawScore,
updatedAt: new Date(),
},
})
.returning();
return result;
}
export async function getTournamentResults(
tournamentId: string
): Promise<TournamentResult[]> {
const db = database();
return await db
.select()
.from(schema.tournamentResults)
.where(eq(schema.tournamentResults.tournamentId, tournamentId))
.orderBy(asc(schema.tournamentResults.placement));
}
export async function getTournamentResultByParticipant(
tournamentId: string,
participantId: string
): Promise<TournamentResult | null> {
const db = database();
const results = await db
.select()
.from(schema.tournamentResults)
.where(
and(
eq(schema.tournamentResults.tournamentId, tournamentId),
eq(schema.tournamentResults.participantId, participantId)
)
)
.limit(1);
return results[0] ?? null;
}