35 lines
974 B
TypeScript
35 lines
974 B
TypeScript
/**
|
||
* 一次性脚本:给所有已有关卡回填 sortKey。
|
||
*
|
||
* 前置:prisma schema 已加 sortKey 字段,并已跑过 `pnpm run db:push`。
|
||
* 执行:pnpm tsx prisma/backfill-sort-keys.ts
|
||
*/
|
||
import { PrismaClient } from '@prisma/client'
|
||
import { generateKeyBetween } from 'fractional-indexing'
|
||
|
||
async function main() {
|
||
const db = new PrismaClient()
|
||
try {
|
||
const levels = await db.level.findMany({
|
||
orderBy: [{ sortOrder: 'asc' }, { createdAt: 'asc' }],
|
||
select: { id: true },
|
||
})
|
||
let prev: string | null = null
|
||
for (const { id } of levels) {
|
||
const key = generateKeyBetween(prev, null)
|
||
await db.level.update({ where: { id }, data: { sortKey: key } })
|
||
prev = key
|
||
}
|
||
// eslint-disable-next-line no-console
|
||
console.log(`backfilled ${levels.length} rows`)
|
||
} finally {
|
||
await db.$disconnect()
|
||
}
|
||
}
|
||
|
||
main().catch((e) => {
|
||
// eslint-disable-next-line no-console
|
||
console.error(e)
|
||
process.exit(1)
|
||
})
|