Files

81 lines
2.4 KiB
TypeScript

// xuchao: 考试试卷种子——src/content/exam/*.json 灌入 exam_paper;表空全量,否则增量(按 paperId 跳过,seq 续接)
import fs from "node:fs";
import path from "node:path";
import { sql } from "drizzle-orm";
import { drizzle } from "drizzle-orm/mysql2";
import mysql from "mysql2/promise";
import { examPapers } from "../src/db/schema";
type ExamPaper = {
id: string;
subject?: string;
grade: string;
semester: string;
month: number;
examType: string;
title: string;
region?: string;
year?: number;
duration?: number;
fullScore?: number;
sourceUrl?: string;
summary?: string;
questions: unknown[];
};
type ExamFile = { papers: ExamPaper[] };
async function main() {
const dir = path.join(process.cwd(), "src/content/exam");
if (!fs.existsSync(dir)) {
console.log("src/content/exam 不存在,跳过考试种子");
return;
}
const files: ExamFile[] = fs
.readdirSync(dir)
.filter((f) => f.endsWith(".json"))
.sort()
.map((f) => JSON.parse(fs.readFileSync(path.join(dir, f), "utf8")));
const conn = await mysql.createConnection(process.env.DATABASE_URL!);
const db = drizzle(conn);
const [cnt] = await db.select({ n: sql<number>`COUNT(*)` }).from(examPapers);
if (cnt.n > 0) console.log("exam_paper 已有", cnt.n, "条,增量模式(跳过已存在 paperId)");
const [mx] = await db.select({ m: sql<number>`COALESCE(MAX(seq),0)` }).from(examPapers);
let seq = mx.m;
const existing = new Set(
(await db.select({ paperId: examPapers.paperId }).from(examPapers)).map((r) => r.paperId),
);
let added = 0;
for (const file of files) {
for (const p of file.papers) {
if (existing.has(p.id)) continue;
seq += 1;
await db.insert(examPapers).values({
paperId: p.id,
subject: p.subject ?? "math",
grade: p.grade,
semester: p.semester,
month: p.month,
examType: p.examType,
title: p.title,
region: p.region ?? null,
year: p.year ?? null,
duration: p.duration ?? null,
fullScore: p.fullScore ?? null,
sourceUrl: p.sourceUrl ?? null,
summary: p.summary ?? null,
questions: JSON.stringify(p.questions),
seq,
});
added++;
}
}
const [tot] = await db.select({ n: sql<number>`COUNT(*)` }).from(examPapers);
console.log("新增试卷:", added, "| 试卷总数:", tot.n);
await conn.end();
}
main();