fix(database): 快照恢复失败时回滚并保留原库
This commit is contained in:
1 parent
ff33d163e3
commit
f60114af85
1 file changed
+23
-9
@@ -1,7 +1,7 @@
|
|||||||
import { refreshClassSubscriptions } from '../realtime/bus.js';
|
import { refreshClassSubscriptions } from '../realtime/bus.js';
|
||||||
import { invalidateAuthPrincipals } from './authz/principal.js';
|
import { invalidateAuthPrincipals } from './authz/principal.js';
|
||||||
import { migratePermissionScope } from '@classhelper/shared';
|
import { migratePermissionScope } from '@classhelper/shared';
|
||||||
import type { PrismaClient } from '../generated/prisma/client.js';
|
import type { Prisma, PrismaClient } from '../generated/prisma/client.js';
|
||||||
import type { DatabaseProvider } from './db.js';
|
import type { DatabaseProvider } from './db.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -15,7 +15,7 @@ import type { DatabaseProvider } from './db.js';
|
|||||||
* 而 `Class.archivedYearId` / `Student.archivedYearId → ArchivedYear` 又是另一条;
|
* 而 `Class.archivedYearId` / `Student.archivedYearId → ArchivedYear` 又是另一条;
|
||||||
* 恢复时必须**临时关闭外键检查**再按序写入,否则任何排序都会被其中一侧卡死。
|
* 恢复时必须**临时关闭外键检查**再按序写入,否则任何排序都会被其中一侧卡死。
|
||||||
* - SQLite:PRAGMA foreign_keys=OFF(libsql 连接级,进程内安全)
|
* - SQLite:PRAGMA foreign_keys=OFF(libsql 连接级,进程内安全)
|
||||||
* - MySQL:SET FOREIGN_KEY_CHECKS=0/1(会话级,连接池下同一客户端实例内生效)
|
* - MySQL:SET FOREIGN_KEY_CHECKS=0/1(会话级,恢复事务使用同一连接)
|
||||||
*/
|
*/
|
||||||
|
|
||||||
export const SNAPSHOT_FORMAT = 'classhelper-snapshot';
|
export const SNAPSHOT_FORMAT = 'classhelper-snapshot';
|
||||||
@@ -94,7 +94,7 @@ interface ModelDelegate {
|
|||||||
deleteMany(): Promise<unknown>;
|
deleteMany(): Promise<unknown>;
|
||||||
}
|
}
|
||||||
|
|
||||||
function delegatesOf(prisma: PrismaClient): Record<SnapshotTable, ModelDelegate> {
|
function delegatesOf(prisma: Prisma.TransactionClient): Record<SnapshotTable, ModelDelegate> {
|
||||||
return prisma as unknown as Record<SnapshotTable, ModelDelegate>;
|
return prisma as unknown as Record<SnapshotTable, ModelDelegate>;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -103,7 +103,7 @@ const CHUNK_SIZE = 200;
|
|||||||
|
|
||||||
/** 导出全库快照(行内 DateTime 为 Date 对象,JSON.stringify 时自动转 ISO) */
|
/** 导出全库快照(行内 DateTime 为 Date 对象,JSON.stringify 时自动转 ISO) */
|
||||||
export async function exportSnapshot(
|
export async function exportSnapshot(
|
||||||
prisma: PrismaClient,
|
prisma: Prisma.TransactionClient,
|
||||||
provider: DatabaseProvider,
|
provider: DatabaseProvider,
|
||||||
): Promise<DatabaseSnapshot> {
|
): Promise<DatabaseSnapshot> {
|
||||||
const delegates = delegatesOf(prisma);
|
const delegates = delegatesOf(prisma);
|
||||||
@@ -150,7 +150,7 @@ export function assertValidSnapshot(value: unknown): asserts value is DatabaseSn
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function setForeignKeys(
|
async function setForeignKeys(
|
||||||
prisma: PrismaClient,
|
prisma: Prisma.TransactionClient,
|
||||||
provider: DatabaseProvider,
|
provider: DatabaseProvider,
|
||||||
enabled: boolean,
|
enabled: boolean,
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
@@ -172,11 +172,16 @@ export async function restoreSnapshot(
|
|||||||
options: { clean?: boolean } = {},
|
options: { clean?: boolean } = {},
|
||||||
): Promise<{ counts: Record<string, number> }> {
|
): Promise<{ counts: Record<string, number> }> {
|
||||||
assertValidSnapshot(snapshot);
|
assertValidSnapshot(snapshot);
|
||||||
const delegates = delegatesOf(prisma);
|
|
||||||
const clean = options.clean !== false;
|
const clean = options.clean !== false;
|
||||||
const counts: Record<string, number> = {};
|
const counts: Record<string, number> = {};
|
||||||
|
|
||||||
await setForeignKeys(prisma, provider, false);
|
// SQLite 只能在事务外切换外键;MySQL 的会话设置必须使用事务固定的连接。
|
||||||
|
if (provider === 'sqlite') await setForeignKeys(prisma, provider, false);
|
||||||
|
try {
|
||||||
|
await prisma.$transaction(
|
||||||
|
async (tx) => {
|
||||||
|
const delegates = delegatesOf(tx);
|
||||||
|
if (provider === 'mysql') await setForeignKeys(tx, provider, false);
|
||||||
try {
|
try {
|
||||||
if (clean) {
|
if (clean) {
|
||||||
// 反向清空,保证被引用的表最后清(外键关闭后只是防御性的,保持确定性)
|
// 反向清空,保证被引用的表最后清(外键关闭后只是防御性的,保持确定性)
|
||||||
@@ -201,7 +206,10 @@ export async function restoreSnapshot(
|
|||||||
const group = snapshot.data.PermissionGroup.find((g) => g.id === row.groupId);
|
const group = snapshot.data.PermissionGroup.find((g) => g.id === row.groupId);
|
||||||
return {
|
return {
|
||||||
...row,
|
...row,
|
||||||
...migratePermissionScope(String(group?.scope ?? 'TEACHING'), String(group?.scopeValue ?? '')),
|
...migratePermissionScope(
|
||||||
|
String(group?.scope ?? 'TEACHING'),
|
||||||
|
String(group?.scopeValue ?? ''),
|
||||||
|
),
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
if (table === 'StudentClassTransfer') {
|
if (table === 'StudentClassTransfer') {
|
||||||
@@ -228,7 +236,13 @@ export async function restoreSnapshot(
|
|||||||
counts[table] = rows.length;
|
counts[table] = rows.length;
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
await setForeignKeys(prisma, provider, true).catch(() => undefined);
|
if (provider === 'mysql') await setForeignKeys(tx, provider, true);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{ timeout: 120_000 },
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
if (provider === 'sqlite') await setForeignKeys(prisma, provider, true);
|
||||||
}
|
}
|
||||||
invalidateAuthPrincipals();
|
invalidateAuthPrincipals();
|
||||||
refreshClassSubscriptions();
|
refreshClassSubscriptions();
|
||||||
|
|||||||
Reference in new issue
Block a user