fix: 同步引擎主键感知(setting 表字符串主键导致的 Invalid key)

This commit is contained in:
root
2026-10-16 13:24:18 +08:00
parent 5a67b2f59a
commit f387ac0194
6 changed files with 39 additions and 31 deletions
+11 -3
View File
@@ -38,6 +38,11 @@ async function getTable(name: string): Promise<AnyRow[]> {
return db.table(name).toArray()
}
// 主键访问:setting 表主键为字符串 key,其余表为自增 id
function pkOf(t: string, row: AnyRow): any {
return t === 'setting' ? row.key : row.id
}
// 一次性补齐 uuid 与 updated_at,缺失时回填
async function ensureSyncFields(): Promise<void> {
for (const t of TABLES) {
@@ -48,7 +53,7 @@ async function ensureSyncFields(): Promise<void> {
const patch: AnyRow = {}
if (!row.uuid) patch.uuid = newUuid()
if (!row.updated_at) patch.updated_at = row.created_at || nowLocalISO()
if (Object.keys(patch).length) await table.update(row.id, patch)
if (Object.keys(patch).length) await table.update(pkOf(t, row), patch)
}
}
}
@@ -299,7 +304,7 @@ async function doRunSync(config: SyncConfig): Promise<SyncResult> {
for (const [u, row] of byUuid) {
if (dead.has(u)) {
await table.delete(row.id)
await table.delete(pkOf(t, row))
removed++
}
}
@@ -313,7 +318,10 @@ async function doRunSync(config: SyncConfig): Promise<SyncResult> {
const localUa = String(local.updated_at || '')
const serverUa = String(srow.updated_at || '')
if (serverUa > localUa) {
await table.update(local.id, { ...srow })
const patch: AnyRow = { ...srow }
// setting 表主键为 key,禁止通过 update 修改主键字段
if (t === 'setting') delete patch.key
await table.update(pkOf(t, local), patch)
pulled++
}
}