112 lines
2.5 KiB
TypeScript
112 lines
2.5 KiB
TypeScript
import { PrismaClient } from '@prisma/client'
|
||
|
||
/**
|
||
* 一次性脚本:回填 Material 的归属字段
|
||
*
|
||
* 目标:
|
||
* - 对所有已有素材,确保:
|
||
* - ownerType 统一为 'TEAM'
|
||
* - ownerId 统一为 'default-team'
|
||
* - createdByUserId 如果为空且存在 userId,则设置为 userId
|
||
*
|
||
* 特点:
|
||
* - 幂等:可以安全多次执行,后续再次运行几乎不会有更新
|
||
* - 不覆盖已经手动修改过的 createdByUserId / ownerType / ownerId(如果后面你改成别的也没问题)
|
||
*/
|
||
|
||
const prisma = new PrismaClient()
|
||
|
||
async function main() {
|
||
const BATCH_SIZE = 200
|
||
let skip = 0
|
||
|
||
let total = 0
|
||
let updated = 0
|
||
let missingUserId = 0
|
||
|
||
console.log('=== Backfill Material Ownership Fields ===')
|
||
|
||
while (true) {
|
||
const materials = await prisma.material.findMany({
|
||
skip,
|
||
take: BATCH_SIZE,
|
||
orderBy: { createdAt: 'asc' },
|
||
select: {
|
||
id: true,
|
||
userId: true,
|
||
ownerType: true,
|
||
ownerId: true,
|
||
createdByUserId: true,
|
||
},
|
||
})
|
||
|
||
if (!materials.length) break
|
||
|
||
console.log(`Processing batch: skip=${skip}, count=${materials.length}`)
|
||
|
||
for (const m of materials) {
|
||
total++
|
||
|
||
const data: any = {}
|
||
|
||
// 统一 ownerType / ownerId 为团队空间
|
||
if (m.ownerType !== 'TEAM') {
|
||
data.ownerType = 'TEAM'
|
||
}
|
||
|
||
if (!m.ownerId || m.ownerId.trim().length === 0 || m.ownerId === 'unknown') {
|
||
data.ownerId = 'default-team'
|
||
}
|
||
|
||
// 回填 createdByUserId:仅在当前为空且存在 userId 时设置
|
||
if (!m.createdByUserId) {
|
||
if (m.userId) {
|
||
data.createdByUserId = m.userId
|
||
} else {
|
||
missingUserId++
|
||
}
|
||
}
|
||
|
||
if (Object.keys(data).length > 0) {
|
||
await prisma.material.update({
|
||
where: { id: m.id },
|
||
data,
|
||
})
|
||
updated++
|
||
}
|
||
}
|
||
|
||
skip += materials.length
|
||
}
|
||
|
||
console.log('=== Backfill Completed ===')
|
||
console.log(
|
||
JSON.stringify(
|
||
{
|
||
totalMaterialsScanned: total,
|
||
totalRowsUpdated: updated,
|
||
rowsWithMissingUserId: missingUserId,
|
||
},
|
||
null,
|
||
2
|
||
)
|
||
)
|
||
|
||
if (missingUserId > 0) {
|
||
console.log(
|
||
'注意: 有部分素材没有 userId,未设置 createdByUserId。后续如果需要,可以在后台手动修复这些数据。'
|
||
)
|
||
}
|
||
}
|
||
|
||
main()
|
||
.catch((err) => {
|
||
console.error('Backfill failed:', err)
|
||
process.exitCode = 1
|
||
})
|
||
.finally(async () => {
|
||
await prisma.$disconnect()
|
||
})
|
||
|
||
|