Reputation: 716
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;
}
}
Upvotes: 38
Views: 37081
Reputation: 133
For those of you who land here in >= 2024.
Browsers now support event.oldVersion
and event.newVersion
pretty well.
var dbexists=false;
var request = window.indexedDB.open("TestDatabase");
request.onupgradeneeded = function(e) {
db = e.target.result;
enter code here
if (e.oldVersion == 0) {
db.close();
indexedDB.deleteDatabase("TestDatabase");
} else {
dbexists=true;
}
}
Upvotes: 0
Reputation: 21
Here is a async util function returns true false to check if a db exist with given name and version.
const indexedDBUtil = {
dbExist: async(dbName: string, version = 1)=> {
let newDb = false;
await ((): Promise<void>=>{
return new Promise((resolve, reject)=>{
const req = indexedDB.open(dbName, version );
req.onupgradeneeded = ()=>{
req.transaction.abort();
newDb = true;
resolve();
}
req.onsuccess = () => {
resolve();
}
});
})();
return newDb;
}
}
Upvotes: 2
Reputation: 4180
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. One 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
Upvotes: 25
Reputation: 62
This function checks if the database exists. Use the onupgradeneeded event, if the version is 1 and the event is triggered, it means that the database does not exist, but is created with the window.indexedDB.open(name) function, which means that you should remove it.
When the onsuccess event fires, but not the onupgradeneeded event (Variable dbExists remains true) indicates that the database existed before and returns true.
/**
* Check if a database exists
* @param {string} name Database name
* @param {function} callback Function to return the response
* @returns {bool} True if the database exists
*/
function databaseExists(name, callback) {
var dbExists = true;
var request = window.indexedDB.open(name);
request.onupgradeneeded = function (e) {
if (request.result.version === 1) {
dbExists = false;
window.indexedDB.deleteDatabase(name);
if (callback) callback(dbExists);
}
};
request.onsuccess = function (e) {
if (dbExists) {
if (callback) callback(dbExists);
}
};
}
The output of the function is through a callback function. The form of use is as follows:
var name = "TestDatabase";
databaseExists(name, function (exists) {
if (exists) {
console.debug("database " + name + " exists");
} else {
console.debug("database " + name + " does not exists");
}
});
[sorry for my english]
Upvotes: 2
Reputation: 37815
function databaseExists(name) {
return new Promise(function (resolve, reject) {
var db = indexedDB,
req;
try {
// See if it exist
req = db.webkitGetDatabaseNames();
req.onsuccess = function (evt) {
~[].slice.call(evt.target.result).indexOf(name)
? resolve(true)
: reject(false);
};
} catch (e) {
// Try if it exist
req = db.open(name);
req.onsuccess = function () {
req.result.close();
resolve(true);
};
req.onupgradeneeded = function (evt) {
evt.target.transaction.abort();
reject(false);
};
}
});
}
Usage:
databaseExists("foo").then(AlreadyTaken, createDatabase)
Upvotes: 2
Reputation: 54812
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);
Upvotes: 24
Reputation: 34
Another way to do this (on Chrome but not Firefox) is with an async function as follows:
/**
* Checks the IndexedDB "web-server" to see if an specific database exists.
* Must be called with await, for example, var dbFound = await doesDbExist('mySuperDB');
* @param {string} dbName The database name to look for.
* @returns {boolean} Whether a database name was found.
*/
async function doesDbExist(dbName) {
var result = await indexedDB.databases();
var dbFound = false;
for (var i = 0; i < result.length && !dbFound; i++) {
dbFound = result[i].name === dbName;
}
return dbFound;
}
Then just call the function as follows:
var dbFound = await doesDbExist('mySuperDB');
Upvotes: 0
Reputation: 3833
If you are using alasql you could use something like:
async existsDatabase(myDatabase) {
return !(await alasql.promise(`
create indexeddb database if not exists ${myDatabase};
`));
}
This will create the database if it not exists but it was the best solution that I've found until now so far. You can delete the database if it exists with a similar query too: drop indexeddb database if exists ${myDatabase};
Upvotes: 1
Reputation: 6114
Hi i know this question is already answered and accepted , but i think one of the good way to do it like this
var indexeddbReq = $window.indexedDB.webkitGetDatabaseNames();
indexeddbReq.onsuccess = function(evt){
if(evt.target.result.contains(
// SUCCESS YOU FOUND THE DB
}
else{
// DB NOT FOUND
}
}
Upvotes: -1
Reputation: 21971
I spent more than an hour playing with it and basically the only deterministic and reliable way to do that is using webkit's webkitGetDatabaseNames
.
There is literally like 10 ways to test if DB exists using onupgradeneeded, but that just doesn't work in production. It got either blocked for several seconds, sometimes completely on deleting database. Those tips to abort transaction are nonsense because
window.indexeddb.open("db")
request does not contain transaction object... req.transaction == null
I can't believe this is real...
Upvotes: 5
Reputation: 5691
The following code works. I have tested it with Chrome, IE and Opera. Tested with both locally open databases and closed and with databases of different versions, so it should be accurate. The creation/deletion of the database is needed. However, it will be an atomic operation with no risk for race conditions because the spec promises to not launch to open requests in parallell if the open request results in a database creation.
function databaseExists(dbname, callback) {
var req = indexedDB.open(dbname);
var existed = true;
req.onsuccess = function () {
req.result.close();
if (!existed)
indexedDB.deleteDatabase(dbname);
callback(existed);
}
req.onupgradeneeded = function () {
existed = false;
}
}
To use the function, do:
databaseExists(dbName, function (yesno) {
alert (dbName + " exists? " + yesno);
});
Upvotes: 8