gongxiangp2/scripts/migrate-departments-from-users.ts

76 lines
2.0 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 数据迁移脚本:从用户表同步部门到 Department 表
*
* 使用方法:
* npx tsx scripts/migrate-departments-from-users.ts
*/
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
async function main() {
console.log('开始从用户表同步部门到 Department 表...\n');
// 1. 获取已有的部门记录
const existingDepartments = await prisma.department.findMany({
select: { name: true },
});
const existingNames = new Set(existingDepartments.map((d) => d.name));
console.log(`当前 Department 表中已有部门数量:${existingNames.size}`);
// 2. 从用户表中取出所有非空部门(去重)
const usersWithDept = await prisma.user.findMany({
where: {
department: {
not: '',
},
},
select: {
department: true,
},
});
const userDeptNames = Array.from(
new Set(
usersWithDept
.map((u) => (u.department || '').trim())
.filter((name) => name.length > 0),
),
);
console.log(`从用户表中发现 ${userDeptNames.length} 个去重后的部门名称:`);
userDeptNames.forEach((name) => console.log(` - ${name}`));
// 3. 过滤出需要新建的部门
const toCreate = userDeptNames.filter((name) => !existingNames.has(name));
if (toCreate.length === 0) {
console.log('\n无需创建新部门,Department 表已包含所有用户部门。');
} else {
console.log(`\n需要新建 ${toCreate.length} 个部门,将写入 Department 表...`);
await prisma.department.createMany({
data: toCreate.map((name) => ({ name })),
skipDuplicates: true,
});
console.log('✅ 新部门写入完成。');
}
// 4. 打印最终统计
const finalCount = await prisma.department.count();
console.log(`\n同步完成!当前 Department 表部门总数:${finalCount}`);
}
main()
.catch((error) => {
console.error('同步部门失败:', error);
process.exit(1);
})
.finally(async () => {
await prisma.$disconnect();
});