Opening a database is an asynchronous operation. We need to send a request to open our database and then listen for events so we know when it's ready.
We'll open a DemoDB database. If it doesn't exist yet, it will get created when we send the request.
The 2
below says that we're asking for version 2 of our database. Only one version
exists at any time, but we can use the version number to upgrade old data, as you'll see.
var db = null, // We'll use this once we have our database
request = window.indexedDB.open("DemoDB", 2);
// Listen for success. This will be called after onupgradeneeded runs, if it does at all
request.onsuccess = function() {
db = request.result; // We have a database!
doThingsWithDB(db);
};
// If our database didn't exist before, or it was an older version than what we requested,
// the `onupgradeneeded` event will be fired.
//
// We can use this to setup a new database and upgrade an old one with new data stores
request.onupgradeneeded = function(event) {
db = request.result;
// If the oldVersion is less than 1, then the database didn't exist. Let's set it up
if (event.oldVersion < 1) {
// We'll create a new "things" store with `autoIncrement`ing keys
var store = db.createObjectStore("things", { autoIncrement: true });
}
// In version 2 of our database, we added a new index by the name of each thing
if (event.oldVersion < 2) {
// Let's load the things store and create an index
var store = request.transaction.objectStore("things");
store.createIndex("by_name", "name");
}
};
// Handle any errors
request.onerror = function() {
console.error("Something went wrong when we tried to request the database!");
};