IndexedDB: how to reseed/reset auto-increment key to 0 (or 1)
Asked Answered
G

3

13

Simple question, but I haven't been able to find an answer.

How can I reset an object store in IndexedDB so the auto-increment key starts at 0 (or 1) again?

I am using IDBWrapper currently, but could use an alternative library if it is easier. I am using in-line keys.

From here: http://jensarps.de/2011/11/25/working-with-idbwrapper-part-1

If you need to clear the store from all stored entries, you can use the clear method. Note that this won’t reset Chrome’s autoIncrement counter.

If I manually clear the object store in Chrome Developer tools, this does not reset the key to 0 (or 1).

I did find this rejected bug: https://bugzilla.mozilla.org/show_bug.cgi?id=635551 and from there, this outline of key generation: http://www.w3.org/TR/2012/WD-IndexedDB-20120524/#key-generator-concept

Presumably I could write my own logic to remember when the store was last cleared and then alter the code where records are inserted to manually override the key to be 0 (or 1), but is this really necessary?

Glooming answered 6/9, 2013 at 8:15 Comment(0)
C
10

You can't reset the generator, without deleting and recreating the object store.

As noted in https://w3c.github.io/IndexedDB/#key-generator-construct the maximum generated key is 9007199254740992 and:

If you generate a new key 1000 times per second day and night, you won’t run into this limit for over 285000 years.

Crossway answered 23/6, 2016 at 15:54 Comment(1)
Sounds solid enough for meKaoliang
L
1

According to spec, generated key value can be anything depending on browser implementation. Your code should not rely on it.

Lab answered 7/9, 2013 at 1:3 Comment(1)
I wasn't planning on hard-coding against any specific keys, just wondering as it seems messy that the keys will just keep incrementing forever, seemingly until the object store itself is deleted. Over the lifetime of an app the keys could become pretty long.Glooming
T
1

You can't reset the generator, without deleting and recreating the object store. https://github.com/Tesfaye-Eshetie/reusable-comment-component/blob/store-comments-IndexedDB/js/idb/indexedDB.js

Torrential answered 8/8, 2022 at 19:31 Comment(2)
you can also use the follow function to delete the database to restart the key: import { openDB, deleteDB } from 'idb'; (function createStore() { openDB('myDB', 1, { upgrade(db) { db.createObjectStore('store', { autoIncrement: true }); }, }); })(); (function deleteMyDB() { await deleteDB('myDB', { blocked() { console.log('deletions is successful'); }, }); })();Torrential
Your answer should rather be a comment.Frail

© 2022 - 2024 — McMap. All rights reserved.