From 61d516f1b12778c6b9578422ddfea8209be53a1c Mon Sep 17 00:00:00 2001 From: Adrian Bonpin Date: Wed, 20 May 2026 02:19:42 +0800 Subject: [PATCH] feat(db): backfill slugs for existing non-Steam games --- lib/db/migrations/backfill-slugs.ts | 50 +++++++++++++++++++++++++++++ lib/utils/slug.ts | 9 ++++++ 2 files changed, 59 insertions(+) create mode 100644 lib/db/migrations/backfill-slugs.ts create mode 100644 lib/utils/slug.ts diff --git a/lib/db/migrations/backfill-slugs.ts b/lib/db/migrations/backfill-slugs.ts new file mode 100644 index 0000000..2960466 --- /dev/null +++ b/lib/db/migrations/backfill-slugs.ts @@ -0,0 +1,50 @@ +import { db } from "@/lib/db/index" +import { games } from "@/lib/db/schema" +import { generateSlug } from "@/lib/utils/slug" +import { ne, isNull, isNotNull, and, eq } from "drizzle-orm" + +async function backfillSlugs() { + const nonSteamGames = await db + .select({ id: games.id, title: games.title }) + .from(games) + .where(and(ne(games.source, "steam"), isNull(games.slug))) + + console.log(`Found ${nonSteamGames.length} non-Steam games without slugs`) + + const usedSlugs = new Set() + const existing = await db + .select({ slug: games.slug }) + .from(games) + .where(isNotNull(games.slug)) + for (const row of existing) { + if (row.slug) usedSlugs.add(row.slug) + } + + let updated = 0 + let errors = 0 + for (const game of nonSteamGames) { + let slug = generateSlug(game.title) + if (!slug) { + slug = `game-${game.id.slice(0, 8)}` + } + let candidate = slug + let suffix = 2 + while (usedSlugs.has(candidate)) { + candidate = `${slug}-${suffix}` + suffix++ + } + usedSlugs.add(candidate) + try { + await db.update(games).set({ slug: candidate }).where(eq(games.id, game.id)) + updated++ + } catch (err) { + console.error(`Failed to update ${game.title} (${game.id}):`, err) + errors++ + } + } + console.log(`Backfill complete: ${updated} updated, ${errors} errors`) +} + +backfillSlugs() + .then(() => process.exit(0)) + .catch((err) => { console.error("Backfill failed:", err); process.exit(1) }) \ No newline at end of file diff --git a/lib/utils/slug.ts b/lib/utils/slug.ts new file mode 100644 index 0000000..fba34fc --- /dev/null +++ b/lib/utils/slug.ts @@ -0,0 +1,9 @@ +export function generateSlug(title: string): string { + return title + .toLowerCase() + .replace(/[^a-z0-9]+/g, "-") + .replace(/-+/g, "-") + .replace(/^-|-$/g, "") + .slice(0, 80) + .replace(/-$/g, "") +} \ No newline at end of file