IndexedDb - Check table exists and contains data
Asked Answered
C

4

6

Using IndexedDB when my app first runs I populate it with some data, I want to ensure that when the database and tables are created that they do not already exists.

Can I query the length of a table to see if it contains and data in JavaScript?

Costate answered 21/5, 2012 at 14:35 Comment(1)
CLiown, toske has the correct answer please accept it if it solves your case.Malamud
N
8

We can use the objectStoreNames property of IndexDB to check the existence of an ObjectStore.

var db_object, object_store;
if( !db.objectStoreNames.contains(currentobjectstore) )
{
  db_object =  i_db.createObjectStore(currentobjectstore, {autoIncrement:true} );
 object_store = db.transaction(currentobjectstore, 'readwrite').objectStore(currentobjectstore);
} else {
 object_store = db.transaction(currentobjectstore, 'readwrite').objectStore(currentobjectstore);
}
Nautch answered 7/7, 2022 at 7:13 Comment(0)
T
6

Best way is trying to open objectStore in try catch block. It is synchronous also. In case of an error you can create store for example:

var store;
  try {
    store = request.transaction.objectStore('yourStore');
  }
  catch(e) {
    store = db.createObjectStore('yourStore');
}
Tally answered 13/10, 2019 at 14:31 Comment(0)
T
1

You can use objectStore.count() function, but i recommend storing some kind of meta-data that would say that your local db is initialized. Otherwise, you can have page-reload in middle of data creation and never have your data fully synced with remote data.

Tuppeny answered 31/5, 2012 at 13:28 Comment(0)
D
-1

The database is created if a database with the specified name does not exist else it opens it

eg.var request = indexedDB.open("DataTbl");

So if your db already exists it will just open it and about you checking if the contents in the table already exists then you can make an xyz objectstore and store some key/value flag pair inside it saying that the insertion was successful and check it later everytime when page is reloaded.

Also you can give at try to count function specified by @toske

ref :

Dagda answered 6/12, 2013 at 4:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.