From 49e3b3e5b9bbf1ce356ef68f301d50c689ceecb9 Mon Sep 17 00:00:00 2001 From: Florian Dold Date: Thu, 19 Dec 2019 13:48:37 +0100 Subject: prepare for schema migrations --- src/db.ts | 37 ++++++++++++++++++++++++++++++------- 1 file changed, 30 insertions(+), 7 deletions(-) (limited to 'src/db.ts') diff --git a/src/db.ts b/src/db.ts index e1c5c8f85..da43cf827 100644 --- a/src/db.ts +++ b/src/db.ts @@ -1,7 +1,7 @@ import { Stores } from "./types/dbTypes"; -import { openDatabase, Database } from "./util/query"; +import { openDatabase, Database, Store, Index } from "./util/query"; -const TALER_DB_NAME = "taler"; +const TALER_DB_NAME = "taler-wallet"; /** * Current database version, should be incremented @@ -9,7 +9,7 @@ const TALER_DB_NAME = "taler"; * In the future we might consider adding migration functions for * each version increment. */ -export const WALLET_DB_VERSION = 28; +export const WALLET_DB_VERSION = 1; /** * Return a promise that resolves @@ -18,18 +18,41 @@ export const WALLET_DB_VERSION = 28; export function openTalerDatabase( idbFactory: IDBFactory, onVersionChange: () => void, - onUpgradeUnsupported: (oldVersion: number, newVersion: number) => void, ): Promise { + const onUpgradeNeeded = ( + db: IDBDatabase, + oldVersion: number, + newVersion: number, + ) => { + switch (oldVersion) { + case 0: // DB does not exist yet + for (const n in Stores) { + if ((Stores as any)[n] instanceof Store) { + const si: Store = (Stores as any)[n]; + const s = db.createObjectStore(si.name, si.storeParams); + for (const indexName in si as any) { + if ((si as any)[indexName] instanceof Index) { + const ii: Index = (si as any)[indexName]; + s.createIndex(ii.indexName, ii.keyPath, ii.options); + } + } + } + } + break; + default: + throw Error("unsupported existig DB version"); + } + }; + return openDatabase( idbFactory, TALER_DB_NAME, WALLET_DB_VERSION, - Stores, onVersionChange, - onUpgradeUnsupported, + onUpgradeNeeded, ); } export function deleteTalerDatabase(idbFactory: IDBFactory) { Database.deleteDatabase(idbFactory, TALER_DB_NAME); -} \ No newline at end of file +} -- cgit v1.2.3