Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IndexedDB handle data migration onupgradeneeded

i'm developing a offline-webapplication with IndexedDB. So I thought a lot about data migration in case of a version change.

For example, I had 3 ObjectStores in DB Version 3. Now i noticed, that i should have a specific index at all 3 ObjectStores. But its not possible to add an index afterwards to an existing ObjectStore, without losing data.

What could be the solution to handle data migration in an "onupgradeneeded"-event?

like image 559
Steffen Avatar asked Sep 06 '25 23:09

Steffen


1 Answers

No Need to kill the StoreObject just update it like this :

request.onupgradeneeded = function(evt) {

        var dataBase = evt.target.result;
        var txn = evt.target.transaction;
        //////////
        var storeCreateIndex = function (objectStore, name, options) {
            if (!objectStore.indexNames.contains(name)) {
                objectStore.createIndex(name, name, options);
            }
        }
        //////////
        var catalogItem, mangaItem, chapterItem, artworkItem;
        if (evt.newVersion != evt.oldVersion) {
            // Get exiting objectStore
            catalogItem = txn.objectStore('CatalogItem');
            mangaItem = txn.objectStore('MangaItem');
            chapterItem = txn.objectStore('ChapterItem');
            artworkItem = txn.objectStore('ArtworkList');
        } else {
            // Fist creation of database objectStore
            catalogItem = dataBase.db.createObjectStore("CatalogItem", { keyPath: "key" });
            mangaItem = dataBase.db.createObjectStore("MangaItem", { keyPath: "key" });
            chapterItem = dataBase.db.createObjectStore("ChapterItem", { keyPath: "key" });
            artworkItem = dataBase.db.createObjectStore("ArtworkList", { keyPath: "key" });
        }
        //////////
        storeCreateIndex(catalogItem, "popularity", { unique: false });
        storeCreateIndex(catalogItem, "author", { unique: false });
        storeCreateIndex(catalogItem, "status", { unique: false });
        storeCreateIndex(catalogItem, "isFavorite", { unique: false });
        storeCreateIndex(chapterItem, "isBookmarked", { unique: false });
        storeCreateIndex(chapterItem, "isDownloaded", { unique: false });
}
like image 116
user3187999 Avatar answered Sep 08 '25 11:09

user3187999