fix: prevent conflicts when event moves lines

This commit is contained in:
Matej Stieranka 2025-07-01 12:54:35 +02:00
parent 3d01ce2e72
commit 4604463a8e
2 changed files with 17 additions and 6 deletions

View file

@ -19,11 +19,16 @@ export async function refetchAllData() {
const lines = await getLines(); const lines = await getLines();
await saveLines(lines); await saveLines(lines);
const allEvents = [];
for (const line of lines) { for (const line of lines) {
const lineId = line.id; const lineId = line.id;
const schedule = await getScheduleForLine(lineId); const schedule = await getScheduleForLine(lineId);
const allEvents = schedule.flatMap((day) => day.events); const dayEvents = schedule.flatMap((day) => day.events);
await updateLineEvents(lineId, allEvents); allEvents.push(...dayEvents);
}
await updateLineEvents(allEvents);
if (allEvents.length === 0) {
redirect("/?message=No events found to refetch.");
} }
revalidatePath("/", "layout"); revalidatePath("/", "layout");
redirect("/?message=All data has been successfully refetched and saved."); redirect("/?message=All data has been successfully refetched and saved.");

View file

@ -1,6 +1,6 @@
import type { Event, Line } from "@/common/parser"; import type { Event, Line } from "@/common/parser";
import "dotenv/config"; import "dotenv/config";
import { and, eq, gte, inArray, like, lte, or } from "drizzle-orm"; import { and, eq, gte, ilike, inArray, lte, or, sql } from "drizzle-orm";
import { getDbInstance } from "./getInstance"; import { getDbInstance } from "./getInstance";
import { eventsTable, linesTable } from "./schema"; import { eventsTable, linesTable } from "./schema";
@ -19,12 +19,18 @@ export async function saveLines(lines: Line[]) {
description: line.description, description: line.description,
})), })),
) )
.onConflictDoNothing(); .onConflictDoUpdate({
target: linesTable.id,
set: {
name: sql.raw(`excluded.${linesTable.name.name}`),
description: sql.raw(`excluded.${linesTable.description.name}`),
},
});
} }
export async function updateLineEvents(lineId: number, events: Event[]) { export async function updateLineEvents(events: Event[]) {
await db.transaction(async (tx) => { await db.transaction(async (tx) => {
await tx.delete(eventsTable).where(eq(eventsTable.lineId, lineId)); await tx.delete(eventsTable);
await tx.insert(eventsTable).values(events); await tx.insert(eventsTable).values(events);
}); });
} }