Files
zhuiguang-ai/scripts/cleanup-task-logs.mjs
T

57 lines
1.8 KiB
JavaScript

// 清理 30 天前的 task_log 数据,避免表无限膨胀
import { PrismaClient } from "@prisma/client";
import { PrismaMariaDb } from "@prisma/adapter-mariadb";
import "dotenv/config";
const base = process.env.DATABASE_URL.replace("mysql://", "mariadb://");
const sep = base.includes("?") ? "&" : "?";
const connectionString = `${base}${sep}connection_limit=2&pool_timeout=10`;
const adapter = new PrismaMariaDb(connectionString);
const prisma = new PrismaClient({ adapter });
const RETENTION_DAYS = 30;
async function main() {
const startedAt = new Date();
const cutoff = new Date(Date.now() - RETENTION_DAYS * 24 * 60 * 60 * 1000);
const before = await prisma.taskLog.count();
const { count } = await prisma.taskLog.deleteMany({
where: { startedAt: { lt: cutoff } },
});
const after = await prisma.taskLog.count();
console.log(`清理完成:删除 ${count} 条,剩 ${after} 条 (清理前 ${before})`);
await prisma.taskLog.create({
data: {
taskKey: "cleanup-task-logs",
taskName: "清理任务日志",
status: "success",
startedAt,
finishedAt: new Date(),
duration: Date.now() - startedAt.getTime(),
triggerBy: "cron",
result: { deleted: count, remaining: after, cutoff: cutoff.toISOString() },
},
});
}
main()
.catch(async (e) => {
console.error(e);
try {
await prisma.taskLog.create({
data: {
taskKey: "cleanup-task-logs",
taskName: "清理任务日志",
status: "failed",
startedAt: new Date(),
finishedAt: new Date(),
triggerBy: "cron",
error: (e && e.message ? e.message : String(e)).slice(0, 1000),
},
});
} catch {}
process.exit(1);
})
.finally(() => prisma.$disconnect());