86 lines
2.2 KiB
JavaScript
86 lines
2.2 KiB
JavaScript
/* eslint-disable no-console */
|
||
/**
|
||
* 批量重写已有素材 ID,格式:FLNXI + 日期(yyyyMMdd) + 五位序号
|
||
* 用于测试数据批量重命名。
|
||
*/
|
||
const { PrismaClient } = require('@prisma/client')
|
||
|
||
const prisma = new PrismaClient()
|
||
const MATERIAL_ID_PREFIX = 'FLNXI'
|
||
|
||
function formatDateKey(date) {
|
||
const year = date.getFullYear()
|
||
const month = `${date.getMonth() + 1}`.padStart(2, '0')
|
||
const day = `${date.getDate()}`.padStart(2, '0')
|
||
return `${year}${month}${day}`
|
||
}
|
||
|
||
function buildMaterialId(dateKey, sequence) {
|
||
return `${MATERIAL_ID_PREFIX}${dateKey}${`${sequence}`.padStart(5, '0')}`
|
||
}
|
||
|
||
async function main() {
|
||
console.log('[BackfillMaterialIds] 开始读取素材列表...')
|
||
const materials = await prisma.material.findMany({
|
||
orderBy: { createdAt: 'asc' },
|
||
select: { id: true, createdAt: true },
|
||
})
|
||
|
||
if (!materials.length) {
|
||
console.log('[BackfillMaterialIds] 没有素材需要处理。')
|
||
return
|
||
}
|
||
|
||
const usedIds = new Set(materials.map((m) => m.id))
|
||
const dateCounters = new Map()
|
||
const updates = []
|
||
|
||
for (const material of materials) {
|
||
const dateKey = formatDateKey(new Date(material.createdAt))
|
||
let sequence = dateCounters.get(dateKey) || 0
|
||
let candidate
|
||
|
||
do {
|
||
sequence += 1
|
||
candidate = buildMaterialId(dateKey, sequence)
|
||
} while (candidate !== material.id && usedIds.has(candidate))
|
||
|
||
dateCounters.set(dateKey, sequence)
|
||
|
||
if (candidate === material.id) {
|
||
continue
|
||
}
|
||
|
||
usedIds.delete(material.id)
|
||
usedIds.add(candidate)
|
||
updates.push({ oldId: material.id, newId: candidate })
|
||
}
|
||
|
||
if (!updates.length) {
|
||
console.log('[BackfillMaterialIds] 所有素材 ID 已符合要求,无需更新。')
|
||
return
|
||
}
|
||
|
||
console.log(`[BackfillMaterialIds] 准备更新 ${updates.length} 条记录...`)
|
||
|
||
for (const { oldId, newId } of updates) {
|
||
await prisma.material.update({
|
||
where: { id: oldId },
|
||
data: { id: newId },
|
||
})
|
||
console.log(` - ${oldId} -> ${newId}`)
|
||
}
|
||
|
||
console.log('[BackfillMaterialIds] 处理完成。')
|
||
}
|
||
|
||
main()
|
||
.catch((error) => {
|
||
console.error('[BackfillMaterialIds] 执行失败:', error)
|
||
process.exitCode = 1
|
||
})
|
||
.finally(async () => {
|
||
await prisma.$disconnect()
|
||
})
|
||
|