Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if IndexedDB database exists

Tags:

Is there a way to check if an IndexedDB database already exists? When a program tries to open a database that does not exists the database is created. The only way that I can think of is something like the following, where I test if an objectStore already exists, if it doesn't, the database is deleted:

var dbexists=false; var request = window.indexedDB.open("TestDatabase"); request.onupgradeneeded = function(e) {     db = e.target.result;     if (!db.objectStoreNames.contains('todo')) {        db.close();        indexedDB.deleteDatabase("TestDatabase");     } else {        dbexists=true;     } } 
like image 225
Pedro Almeida Avatar asked Jul 04 '13 11:07

Pedro Almeida


People also ask

Is IndexedDB relational database?

IndexedDB is not a relational database with tables representing collections of rows and columns. This important and fundamental difference affects the way you design and build your applications.

What type of database is IndexedDB?

IndexedDB is a transactional database system, like an SQL-based RDBMS. However, unlike SQL-based RDBMSes, which use fixed-column tables, IndexedDB is a JavaScript-based object-oriented database.


2 Answers

In the onupgradeneeded callback you can check the version. (e.target.result.oldversion). If it is 0, the db didn't exist.

Edit: After some investigation. You can't be 100% sure if a new db is created. 1 thing I am sure of is the fact that you can only work with an indexeddb if it has a version 1 or higher. I believe that a db can exist and have a version 0 (The only fact is you can't work with it and the onupgradeneeded event will be called).

I have build my own indexeddbviewer. In that I open the indexeddb without version and if I come in to the onupgradeneeded event, that means the db doesn't exist. In that case I call the abort so it doesn't upgrade to a version 1. This is the way I check it.

var dbExists = true; var request = window.indexeddb.open("db"); request.onupgradeneeded = function (e){     e.target.transaction.abort();     dbExists = false; } 

but as mentioned. It is possible that the db will continue to exist in that case, but the onupgradeneeded will always be called

like image 110
Kristof Degrave Avatar answered Nov 09 '22 10:11

Kristof Degrave


With ES6 you can find an IndexedDB database by its name using the following code:

const dbName = 'TestDatabase'; const isExisting = (await window.indexedDB.databases()).map(db => db.name).includes(dbName);  
like image 43
Benny Neugebauer Avatar answered Nov 09 '22 09:11

Benny Neugebauer