IDBCursor

The IDBCursor interface of the IndexedDB API represents a cursor for traversing or iterating over multiple records in a database.

About this document

This document was last updated on October 26, 2011 and follows the W3C Specifications (Editor's Draft) drafted on October 26, 2011. 

Basic concepts

The cursor has a source that indicates which index or object store it is iterating. It has a position within the range, and moves in a direction that is increasing or decreasing in the order of record keys. The cursor enables an application to asynchronously process all the records in the cursor's range.

You can have an unlimited number of cursors at the same time. You always get the same  IDBCursor object representing for a given cursor. Operations are performed on the underlying index or object store.

Example

In the following code snippet, we open a transaction and manipulate an entire data set using a cursor. Because the specification is still evolving, Chrome uses prefixes in the methods. Chrome uses the webkit prefix. For example, instead of just IDBCursor.NEXT, use webkitIDBCursor.NEXT. Firefox does not use prefixes, except in the opening method (mozIndexedDB). Event handlers are registered for responding to various situations.

// Taking care of the browser-specific prefixes.
window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB;
window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction;
window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange;
window.IDBCursor = window.IDBCursor || window.webkitIDBCursor;
var db;

...

function cursorTest() {
  // Start a transaction on an object store called "my-store-name"
  // By default, transactions are opened with read-only access.
  // If you want to have write access, see IDBDatabase.
  var trans = db.transaction('my-store-name');
  // Get a reference to the object store.
  var store = trans.objectStore('my-store-name');
  // Create a cursor with two optional parameters.  
  // The first parameter sets the cursor over a specified key range;
  // while the second one sets the direction of the cursor.  
  // In this case, the direction is set to IDBCursor.PREV,  
  // which lets you start at the upper bound of the key range
  // and then moves downwards. 
  // If you don't want duplicates included, use PREV_NO_DUPLICATE instead.
  var curreq = store.openCursor(IDBKeyRange.bound(1, 4), IDBCursor.PREV); 
  // The "onsuccess" event fires when the cursor is created and 
  // every time the cursor iterates over data. 
  // The following block of code runs multiple times,
  // until the cursor runs out of data to iterate over.
  // At that point, the result's request becomes null.
  curreq.onsuccess = function (e) {
    var cursor = curreq.result;
    // If the cursor is pointing at something, ask for the data.    
    if (cursor) {
      var getreq = store.get(cursor.key);
      // After the data has been retrieved, show it.
      getreq.onsuccess = function (e) {
        console.log('key:', cursor.key, 'value:', getreq.result);
        // OK, now move the cursor to the next item. 
        cursor.continue();
      };
    }
  };
};

To learn more about various topics, see the following

Method overview

IDBRequest update (in any value) raises (IDBDatabaseException, DOMException);
void advance (in long count) raises (IDBDatabaseException);
void continue (in optional any key) raises (IDBDatabaseException);
IDBRequest delete () raises (IDBDatabaseException);

Attributes

Attribute Type Description
source readonly Object On getting, returns the IDBObjectStore or IDBIndex that the cursor is iterating. This function never returns null or throws an exception, even if the cursor is currently being iterated, has iterated past its end, or its transaction is not active.
direction readonly unsigned short On getting, returns the direction of traversal of the cursor. See Constants for possible values.
key readonly any Returns the key for the record at the cursor's position. If the cursor is outside its range, this is undefined.
primaryKey readonly any

Returns the cursor's current effective key. If the cursor is currently being iterated or has iterated outside its range, this is undefined.

Constants

Constant Value Description
NEXT 0 The cursor shows all records, including duplicates. It starts at the lower bound of the key range and moves upwards (monotonically increasing in the order of keys).
NEXT_NO_DUPLICATE 1 The cursor shows all records, excluding duplicates. If multiple records exist with the same key, only the first one iterated is retrieved. It starts at the lower bound of the key range and moves upwards.
PREV 2 The cursor shows all records, including duplicates. It starts at the upper bound of the key range and moves downwards (monotonically decreasing in the order of keys).
PREV_NO_DUPLICATE 3 The cursor shows all records, excluding duplicates. If multiple records exist with the same key, only the first one iterated is retrieved. It starts at the upper bound of the key range and moves downwards.

Methods

update()

Returns an IDBRequest object, and, in a separate thread, updates the value at the current position of the cursor in the object store. If the cursor points to a record that has just been deleted, a new record is created.

IDBRequest update (
  in any value
) raises (IDBDatabaseException, DOMException);
Parameter
value
The value to be stored.
Returns
IDBRequest
A request object on which subsequent events related to this operation are fired.
Exceptions

This method can raise an IDBDatabaseException with the following codes:

Exception Description
DATA_ERR

The underlying object store uses in-line keys, and the key for the cursor's position does not match the value property at the object store's key path.

NOT_ALLOWED_ERR The cursor was created using openKeyCursor(), or if it is currently being iterated (you cannot call this method again until the new cursor data has been loaded), or if it has iterated past the end of its range.
READ_ONLY_ERR The cursor is in a transaction whose mode is READ_ONLY.
TRANSACTION_INACTIVE_ERR The transaction that this cursor belongs to is inactive.

It can also raise a DOMException with the following code:

Attribute Description
DATA_CLONE_ERR If the value could not be cloned.

advance()

Sets the number times a cursor should move its position forward.

IDBRequest advance (
  in long count
) raises (IDBDatabaseException);
Parameter
count
The number of advances forward the cursor should make.
Returns
void
Exceptions

This method can raise an IDBDatabaseException with the following codes:

Exception Description
NON_TRANSIENT_ERR

The value passed into the count parameter was zero or a negative number.

NOT_ALLOWED_ERR The cursor was created using openKeyCursor(), or if it is currently being iterated (you cannot call this method again until the new cursor data has been loaded), or if it has iterated past the end of its range.
TRANSACTION_INACTIVE_ERR The transaction that this cursor belongs to is inactive.

continue()

Advances the cursor to the next position along its direction, to the item whose key matches the optional key parameter. If no key is specified, advance to the immediate next position, based on the cursor's direction.

void continue (
  in optional any key
) raises (IDBDatabaseException);
Returns
void
Parameters
key
The key to position the cursor at.
Exceptions

This method can raise an IDBDatabaseException, with the following codes:

Exception Description
DATA_ERR If the key parameter was specified, but did not contain a valid key.
NOT_ALLOWED_ERR The cursor was created using openKeyCursor(), or if it is currently being iterated (you cannot call this method again until the new cursor data has been loaded), or if it has iterated past the end of its range.
TRANSACTION_INACTIVE_ERR The transaction that this cursor belongs to is inactive.

delete()

Returns an IDBRequest object, and, in a separate thread, deletes the record at the cursor's position, without changing the cursor's position. Once the record is deleted, the cursor's value is set to null.

IDBRequest delete (
) raises (IDBDatabaseException);
Returns
IDBRequest
A request object on which subsequent events related to this operation are fired. The result attribute is set to undefined.
Exceptions

This method can raise an IDBDatabaseException with the following code:

Exception Description
NOT_ALLOWED_ERR The cursor was created using openKeyCursor(), or if it is currently being iterated (you cannot call this method again until the new cursor data has been loaded), or if it has iterated past the end of its range.
READ_ONLY_ERR The cursor is in a transaction whose mode is READ_ONLY.
TRANSACTION_INACTIVE_ERR The transaction that this cursor belongs to is inactive.

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