wallet-core: make DB migration logic more tolerant

This commit is contained in:
Florian Dold 2023-01-23 13:56:22 +01:00
parent 509011f9bc
commit 3222617b81
No known key found for this signature in database
GPG Key ID: D2E4F00F29D02A4B

View File

@ -2468,8 +2468,14 @@ export async function applyFixups(
}); });
} }
/**
* Upgrade an IndexedDB in an upgrade transaction.
*
* The upgrade is made based on a store map, i.e. the metadata
* structure that describes all the object stores and indexes.
*/
function upgradeFromStoreMap( function upgradeFromStoreMap(
storeMap: any, storeMap: any, // FIXME: nail down type
db: IDBDatabase, db: IDBDatabase,
oldVersion: number, oldVersion: number,
newVersion: number, newVersion: number,
@ -2511,16 +2517,23 @@ function upgradeFromStoreMap(
continue; continue;
} }
let s: IDBObjectStore; let s: IDBObjectStore;
try { // Be tolerant if object store already exists.
s = db.createObjectStore(swi.storeName, { // Probably means somebody deployed without
autoIncrement: storeDesc.autoIncrement, // adding the "addedInVersion" attribute.
keyPath: storeDesc.keyPath, if (!upgradeTransaction.objectStoreNames.contains(swi.storeName)) {
}); try {
} catch (e) { s = db.createObjectStore(swi.storeName, {
const moreInfo = e instanceof Error ? ` Reason: ${e.message}` : ""; autoIncrement: storeDesc.autoIncrement,
throw Error( keyPath: storeDesc.keyPath,
`Migration failed. Could not create store ${swi.storeName}.${moreInfo}`, });
); } catch (e) {
const moreInfo = e instanceof Error ? ` Reason: ${e.message}` : "";
throw Error(
`Migration failed. Could not create store ${swi.storeName}.${moreInfo}`,
);
}
} else {
s = upgradeTransaction.objectStore(swi.storeName);
} }
for (const indexName in swi.indexMap as any) { for (const indexName in swi.indexMap as any) {
const indexDesc: IndexDescriptor = swi.indexMap[indexName]; const indexDesc: IndexDescriptor = swi.indexMap[indexName];
@ -2528,16 +2541,21 @@ function upgradeFromStoreMap(
if (indexAddedVersion <= oldVersion) { if (indexAddedVersion <= oldVersion) {
continue; continue;
} }
try { // Be tolerant if index already exists.
s.createIndex(indexDesc.name, indexDesc.keyPath, { // Probably means somebody deployed without
multiEntry: indexDesc.multiEntry, // adding the "addedInVersion" attribute.
unique: indexDesc.unique, if (!s.indexNames.contains(indexDesc.name)) {
}); try {
} catch (e) { s.createIndex(indexDesc.name, indexDesc.keyPath, {
const moreInfo = e instanceof Error ? ` Reason: ${e.message}` : ""; multiEntry: indexDesc.multiEntry,
throw Error( unique: indexDesc.unique,
`Migration failed. Could not create index ${indexDesc.name}/${indexDesc.keyPath}.${moreInfo}`, });
); } catch (e) {
const moreInfo = e instanceof Error ? ` Reason: ${e.message}` : "";
throw Error(
`Migration failed. Could not create index ${indexDesc.name}/${indexDesc.keyPath}.${moreInfo}`,
);
}
} }
} }
} }