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

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. The scope can be either static or dynamic. If the scope is static, either it can cover all of the object stores and indexes in the database, or it may include a subset of them. Also, transactions can be 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.

Transactions are expected to be short-lived, so browsers might terminate a transaction that takes too long, in order to free up storage resources. 

To learn more about transactions, see IDBTransactions.

This section discusses the following:

Best practices

You can speed up data access by limiting the scope and mode in the transaction. Here's a couple of tips:

  • When defining the scope, specify only the object stores you need. This way, you can run multiple transactions with non-overlapping scopes concurrently.
  • Only specify a READ_WRITE transaction mode when necessary. You can concurrently run multiple READ_ONLY transactions with overlapping scopes, but you can have only one READ_WRITE transaction for an object store. To learn more, see the definition for transactions in the Basic Concepts article.

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 object of that type.)

  2. Attach event listeners to the IDBRequest object.
    If the version of the database is greater than the one in the persistent storage, the onupgradeneeded callback is executed. That's the only place where a CHANGE_VERSION transaction is opened and where objects stores can be created or deleted.

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

  3. Start a transaction by calling IDBDatabase.transaction().

    An IDBRequest object is returned.

  4. Attach callbacks to the IDBRequest object.

  5. 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 version of the db changes, the onupgradeneeded callback is executed.
  request.onupgradeneeded = function(event) {
    // event.target.trans is a CHANGE_VERSION transaction
    
    // 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"});
  }
  
  //If the open request is successful, the onsuccess callback is executed. 
  request.onsuccess = function(event) {
    creatures.indexedDB.db = event.target.result;     
    creatures.indexedDB.getAllSwampCreatures();
  };

  request.onerror = creatures.indexedDB.onerror;
}

Accessing data

To create or delete object stores or indexes, open a VERSION_CHANGE transaction by calling the the IDBFactory.open() method with a version parameter greater than the current database. This will execute the onupgradeneeded handler with a transaction in the VERSION_CHANGE mode. 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); Deprecated

Warning: this method has been removed from the specificaton but is still used by some not up-to-date browsers. Please see the compatibility table to know if you are in that case.
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 unsigned long long 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.

Unknown parameters are ignored.

Returns
IDBObjectStore
The newly created object store.
Exceptions

This method can raise an IDBDatabaseException with the following codes:

Exception 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:

Exception 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() Deprecated

Warning: The latest draft of the specification dropped this method. Some not up-to-date browsers still implement this method. The new way is to define the version in the IDBDatabase.open() method and to create and delete object stores in the onupdateneeded event handler associated to the returned request.

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.  The method returns a transaction object (IDBTransaction) containing the objectStore() method, which you can use to access your object store. 

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. Specify only the object stores that you need to access.
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. To avoid slowing things down, don't open a READ_WRITE transaction, unless you actually need to write into the database.
Sample code

To start a transaction with the following scope, you can use the code snippets in the table. As noted earlier:

  • Add prefixes to the methods in WebKit browsers, (that is, instead of IDBTransaction.READ_ONLY, use webkitIDBTransaction.READ_ONLY).
  • The default mode is READ_ONLY, so you don't really have to specify it. Of course, if you need to write into the object store, you can open the transaction in the READ_WRITE mode.
Scope Code
Single object store

var transaction = db.transaction(['my-store-name'], IDBTransaction.READ_ONLY);

Alternatively:

var transaction = db.transaction('my-store-name', IDBTransaction.READ_ONLY);

Multiple object stores var transaction = db.transaction(['my-store-name', 'my-store-name2'], IDBTransaction.READ_ONLY);
All object stores

var transaction = db.transaction(db.objectStoreNames, IDBTransaction.READ_ONLY);

You cannot pass an empty array into the storeNames parameter, such as in the following: var transaction = db.transaction([], IDBTransaction.READ_ONLY);.

Warning:  Accessing all obejct stores under the READ_WRITE mode means that you can run only that transaction. You cannot have writing transactions with overlapping scopes.
Returns
IDBTransaction
The transaction object.
Exceptions

This method can raise an IDBDatabaseException with the following codes:

Exception 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) -- -- --
setVersion 12 webkit From 4.0 (2.0) to 9.0 (9.0) -- -- --
2-parameter open -- 10.0 (10.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