IDBDatabase

The IDBDatabase interface of the IndexedDB API provides asynchronous access to a connection to a database. Use it to create, manipulate, and delete objects in that database. The interface also provides the only way to get a transaction and manage versions on that database.

Inherits from: EventTarget

About this document

This document was last updated on October 15, 2011 and follows the W3C Specifications (Editor's Draft) drafted on August 25, 2011. The specification has since changed, but none of the browsers have implemented the changes yet. So this article documents what is currently supported by the browsers, not what is defined in the latest specification. Be aware that some methods have either changed or been dropped in the latest version of the specification.

This document has not yet been verified.

Basic concepts

Everything you do in IndexedDB always happens in the context of a transaction. A transaction represents interactions with data in the database. All objects in IndexedDB—including object stores, indexes, and cursors—are tied to a particular transaction. Thus, you cannot execute commands, access data, or open anything outside of a transaction.

A transaction has a scope and a database to which it applies. And you open transactions in one of three modes: READ_ONLY, READ_WRITE, and VERSION_CHANGE. You can create or delete an object store only in a VERSION_CHANGE transaction.

This section discusses the following:

The basic steps

To make changes to the database, do the following:

  1. Open a connection to the database using indexedDB.open().

    An IDBRequest object is returned. (All asynchronous methods return that object.)

  2. Attach event listeners to the IDBRequest object.

    If the open request is successful, the onsuccess callback is executed.

  3. Check the version of the database to ensure that you are not stomping on changes the user might have made in other tabs that have been opened to your application.

    When the other tabs have finished their transactions, the database closes the transaction and sends a success event.

  4. Start a transaction.
    • If the database is not the expected version, call setVersion() to start a VERSION_CHANGE transaction.
    • If it's the right version and you are just modifying an existing object store, call IDBDatabase.transaction().

    An IDBRequest object is returned.

  5. Attach callbacks to the IDBRequest object.

  6. If the callback is successful, create, modify, or delete the object store.

Example

In the following code snippet, we open a database asynchronously and make a request.  Because the specification is still evolving, Chrome and Firefox put prefixes in the methods. Chrome uses the webkit prefix while Firefox uses the moz prefix. Event handlers are registered for responding to various situations.

// Taking care of the browser-specific prefixes.
if ('webkitIndexedDB' in window) {
   window.indexedDB = window.webkitIndexedDB;
   window.IDBTransaction = window.webkitIDBTransaction;
} else if ('mozIndexedDB' in window) {
   window.indexedDB = window.mozIndexedDB;
}

//Open a connection to the database with the name "creatures" 
//with the empty string as its version.  

var creatures = {};
creatures.indexedDB = {};

creatures.indexedDB.open = function() {
  var request = indexedDB.open("creatures");

  //The open request isn't executed yet, but an IDBRequest object is returned. 
  //Create listeners to the IDBRequest. 
  //If the open request is successful, the onsuccess callback is executed. 

  request.onsuccess = function(event) {
    var version = "1.0 beta";
    creatures.indexedDB.db = event.target.result;
    var db = creatures.indexedDB.db;

    //Check the database version, which is a string. 
    //If it isn't the expected version, call setVersion().     
    //setVersion() is where you can create and delete object stores and indexes. 
    
    if(version != db.version) {
      var setVersionRequest = db.setVersion(version);

      // setVersion() returns IDBRequest object.
      // Attach callbacks to IDBRequest. 

      setVersionRequest.onsuccess = function(event) {

        // If it's successful, create an object store called "swamp"
        // and define an optional parameter object, the "terrorizedPopulace" keyPath.        
        // The keyPath must be what makes an object unique and every object must have it.  
        // If every creature had a unique identification number, that would also be a good keyPath. 
        
        var datastore = db.createObjectStore("swamp",
          {keyPath: "terrorizedPopulace"});

       setVersionRequest.onfailure = creatures.indexedDB.onerror;  

        //After the object store is created, call the method, getAllSwampCreatures. 
        creatures.indexedDB.getAllSwampCreatures();
      };
                  
    }

    creatures.indexedDB.getAllSwampCreatures();
  };

  request.onfailure = creatures.indexedDB.onerror;
}

Accessing data

To create or delete object stores or indexes, open a VERSION_CHANGE transaction by calling the the setVersion() method. The VERSION_CHANGE mode is for updating the version number of transactions. Transactions of this mode cannot run concurrently with other transactions.

To access data in an existing data store, open a transaction using the transaction() method. The arguments you pass determines the scope of the transaction and its mode. By default, a transaction is read-only.

Example

The following is an example of how to open a read-write transaction.

//Open a transaction with a scope of data stores and a read-write mode.
var trans = db.transaction(['list-of-store-names'], IDBTransaction.READ_WRITE);

//"objectStore()" is an IDBTransaction method that returns an object store 
//that has already been added to the scope of the transaction.  
var store = trans.objectStore('your-store-name');
   var req = store.put(value, key); 
   req.onsuccess = ...; 
   req.onerror = ...;

Method overview

IDBObjectStore createObjectStore (in DOMString name, in optional Object optionalParameters) raises (IDBDatabaseException);
IDBRequest deleteObjectStore (in DOMString name) raises (IDBDatabaseException);
IDBVersionChangeRequest setVersion ([TreatNullAs=EmptyString] in DOMString version);
IDBTransaction transaction (in any storeNames, in optional unsigned short mode) raises (IDBDatabaseException);
void close();

Attributes

Attribute Type Description
name readonly DOMString Name of the connected database.
version readonly DOMString The version of the connected database. When a database is first created, this attribute is the empty string.
objectStoreNames readonly DOMStringList A list of the names of the object stores currently in the connected database.

Methods

createObjectStore()

Creates and returns a new object store or index. The method takes the name of the store as well as a parameter object. The parameter object lets you define important optional properties. You can use the property to uniquely identify individual objects in the store. As the property is an identifier, it should be unique to every object, and every object should have that property.

But before you can create any object store or index, you must first call the setVersion() method.

IDBObjectStore createObjectStore(
  in DOMString name,
  in Object optionalParameters
) raises (IDBDatabaseException);
Parameters
name
The name of the new object store.
optionalParameters
Warning: The latest draft of the specification changed this to IDBDatabaseOptionalParameters, which is not yet recognized by any browser

Optional. Options object whose attributes are optional parameters to the method. It includes the following properties:

Attribute Description
keyPath The key path to be used by the new object store. If empty or not specified, the object store is created without a key path and uses out-of-line keys.
autoIncrement If true, the object store has a key generator. Defaults to false.
Returns
IDBObjectStore
The newly created object store.
Exceptions

This method can raise an IDBDatabaseException with the following codes:

Attribute Description
NOT_ALLOWED_ERR The method was not called from a VERSION_CHANGE transaction callback. You must call setVersion() first.
CONSTRAINT_ERR An object store with the given name (based on case-sensitive comparison) already exists in the connected database.
NON_TRANSIENT_ERR optionalParameters has attributes other than keyPath and autoIncrement.

deleteObjectStore()

Destroys the object store with the given name in the connected database, along with any indexes that reference it. 

As with createObjectStore(), this method can be called only within a VERSION_CHANGE transaction. So you must call the setVersion() method first before you can remove any object store or index.

IDBRequest deleteObjectStore(
  in DOMString name
) raises (IDBDatabaseException);
Parameters
name
The name of the data store to delete.
Returns

void

Exceptions

This method can raise an IDBDatabaseException with the following codes:

Attribute Description
NOT_ALLOWED_ERR The method was not called from a VERSION_CHANGE transaction callback. You must call setVersion() first.
NOT_FOUND_ERR You are trying to delete an object store that does not exist. Names are case sensitive.

setVersion()

Warning: The latest draft of the specification dropped this method. Naturally, when the new specification is implemented by browsers, the way you set versions and the way you create and delete object stores change.

Updates the version of the database. Returns immediately and runs a VERSION_CHANGE transaction on the connected database in a separate thread.

Call this method before creating or deleting an object store.

IDBVersionChangeRequest setVersion(
  in DOMString version
) raises (IDBDatabaseException);
Parameters
version
The version to store in the database.
Returns
IDBVersionChangeRequest
The request to change the version of a database.

transaction()

Immediately returns an IDBTransaction object, and starts a transaction in a separate thread. Transactions have scopes that encompass object stores and indexes. They also have modes, which determine which types of interactions can be performed in the transactions.

IDBTransaction transaction(
  in optional any storeNames,
  in optional unsigned short mode  
) raises (IDBDatabaseException);
Parameters
storeNames
The names of object stores and indexes that are in the scope of the new transaction.
mode
Optional. The types of access that can be performed in the transaction. Transactions are opened in one of three modes: READ_ONLY, READ_WRITE, and VERSION_CHANGE. If you don't provide the parameter, the default access mode is READ_ONLY.
Returns
IDBTransaction
The transaction object
Exceptions

This method can raise an IDBDatabaseException with the following codes:

Attribute Description
NOT_ALLOWED_ERR The error is thrown for one of two reasons:
  • The close() method has been called on this IDBDatabase instance.
  • The object store has been deleted or removed.
NOT_FOUND_ERR One of the object stores doesn't exist in the connected database.

close()

Returns immediately and closes the connection in a separate thread. The connection is not actually closed until all transactions created using this connection are complete. No new transactions can be created for this connection once this method is called. Methods that create transactions throw an exception if a closing operation is pending.

void close();

Event handlers

Event handler Event handler type
onabort Abort
onerror Error
onversionchange Version change

Browser compatibility

  • Desktop
  • Mobile

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Basic support 12 -webkit 4.0 (2.0) -- -- --
Feature Android Firefox Mobile (Gecko) IE Phone Opera Mobile Safari Mobile
Basic support -- 6.0 (6.0) ? -- --

Tags (0)

Edit tags
  • No tags

Attachments (0)

 

Attach file