refactor(db): migrate app pages and APIs from Prisma facade to Drizzle (2)

Co-authored-by: Cursor <[email protected]>
This commit is contained in:
SimoandCursor committed 2026-08-01 14:15:28 +02:00
1 parent 7c39aef5d9
commit 2cd0863cb8
40 files changed
+1069 -726

No files matched your search

+80 -26
View File
@@ -1,3 +1,4 @@
import { count, eq, gt, gte, sql } from "drizzle-orm";
import {
ArrowLeftRight,
Clock,
@@ -12,8 +13,8 @@ import { DashboardChart } from "@/components/admin/dashboard-chart";
import { PeakHoursHeatmap } from "@/components/admin/peak-hours-heatmap";
import { StatsCard } from "@/components/admin/stats-card";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Ban, db, Rooms, RoomTradeLog, User } from "@/lib/db";
import { canAccess, getAdminContext, PERMS } from "@/lib/permissions";
import { prisma } from "@/lib/prisma";
import { redisCache } from "@/lib/redis-cache";
type AnalyticsData = {
@@ -57,6 +58,11 @@ async function safeCount(
}
}
async function rawRows<T>(query: ReturnType<typeof sql>): Promise<T[]> {
const [rows] = (await db.execute(query)) as unknown as [T[], unknown];
return rows ?? [];
}
async function getAnalyticsData(
locale: string,
): Promise<{ data: AnalyticsData; degraded: boolean }> {
@@ -78,30 +84,82 @@ async function getAnalyticsData(
weekTrades,
weekBans,
] = await Promise.all([
safeCount(() => prisma.user.count()),
safeCount(() => prisma.user.count({ where: { online: "1" } })),
safeCount(() =>
prisma.user.count({ where: { accountCreated: { gte: weekAgo } } }),
safeCount(async () =>
Number((await db.select({ total: count() }).from(User))[0]?.total ?? 0),
),
safeCount(() =>
prisma.user.count({ where: { accountCreated: { gte: monthAgo } } }),
safeCount(async () =>
Number(
(
await db
.select({ total: count() })
.from(User)
.where(eq(User.online, "1"))
)[0]?.total ?? 0,
),
),
safeCount(async () =>
Number(
(
await db
.select({ total: count() })
.from(User)
.where(gte(User.accountCreated, weekAgo))
)[0]?.total ?? 0,
),
),
safeCount(async () =>
Number(
(
await db
.select({ total: count() })
.from(User)
.where(gte(User.accountCreated, monthAgo))
)[0]?.total ?? 0,
),
),
safeCount(async () =>
Number(
(await db.select({ total: count() }).from(Rooms))[0]?.total ?? 0,
),
),
safeCount(async () =>
Number(
(
await db
.select({ total: count() })
.from(Rooms)
.where(gt(Rooms.users, 0))
)[0]?.total ?? 0,
),
),
safeCount(() => prisma.rooms.count()),
safeCount(() => prisma.rooms.count({ where: { users: { gt: 0 } } })),
(async () => {
try {
const rows = await prisma.$queryRaw<{ count: bigint }[]>`
SELECT COUNT(*) AS count FROM chatlogs_room WHERE timestamp >= ${weekAgo}`;
const rows = await rawRows<{ count: bigint }>(sql`
SELECT COUNT(*) AS count FROM chatlogs_room WHERE timestamp >= ${weekAgo}`);
return { value: Number(rows[0]?.count ?? 0), ok: true };
} catch {
return { value: 0, ok: false };
}
})(),
safeCount(() =>
prisma.roomTradeLog.count({ where: { timestamp: { gte: weekAgo } } }),
safeCount(async () =>
Number(
(
await db
.select({ total: count() })
.from(RoomTradeLog)
.where(gte(RoomTradeLog.timestamp, weekAgo))
)[0]?.total ?? 0,
),
),
safeCount(() =>
prisma.ban.count({ where: { timestamp: { gte: weekAgo } } }),
safeCount(async () =>
Number(
(
await db
.select({ total: count() })
.from(Ban)
.where(gte(Ban.timestamp, weekAgo))
)[0]?.total ?? 0,
),
),
]);
@@ -121,14 +179,12 @@ async function getAnalyticsData(
let registrationChart: { label: string; value: number }[] = [];
try {
const regRows = await prisma.$queryRaw<
{ day_bucket: bigint; count: bigint }[]
>`
const regRows = await rawRows<{ day_bucket: bigint; count: bigint }>(sql`
SELECT FLOOR(account_created / 86400) AS day_bucket, COUNT(*) AS count
FROM users
WHERE account_created >= ${monthAgo}
GROUP BY day_bucket ORDER BY day_bucket
`;
`);
const regCountMap = new Map(
regRows.map((r) => [Number(r.day_bucket), Number(r.count)]),
);
@@ -152,23 +208,21 @@ async function getAnalyticsData(
const grid: number[][] = Array.from({ length: 7 }, () => Array(24).fill(0));
let max = 0;
try {
const peakRows = await prisma.$queryRaw<
{ d: number; h: number; c: bigint }[]
>`
const peakRows = await rawRows<{ d: number; h: number; c: bigint }>(sql`
SELECT ((DAYOFWEEK(FROM_UNIXTIME(last_online)) + 5) % 7) AS d,
HOUR(FROM_UNIXTIME(last_online)) AS h,
COUNT(*) AS c
FROM users
WHERE last_online >= ${weekAgo}
GROUP BY d, h
`;
`);
for (const r of peakRows) {
const day = Number(r.d);
const hour = Number(r.h);
if (day < 0 || day > 6 || hour < 0 || hour > 23) continue;
const count = Number(r.c);
grid[day][hour] = count;
if (count > max) max = count;
const cnt = Number(r.c);
grid[day][hour] = cnt;
if (cnt > max) max = cnt;
}
} catch {
degraded = true;