Files
MemeStudio/prisma/backfill-sort-keys.ts
2026-05-01 08:44:56 +08:00

35 lines
974 B
TypeScript
Raw Permalink 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.
/**
* 一次性脚本:给所有已有关卡回填 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)
})