W3C

Indexed Database API

W3C Working Draft 19 April 2011

This version:
http://www.w3.org/TR/2011/WD-IndexedDB-20110419/
Latest published version:
http://www.w3.org/TR/IndexedDB/
Latest editor's draft:
http://dvcs.w3.org/hg/IndexedDB/raw-file/tip/Overview.html
Previous versions:
http://www.w3.org/TR/2010/WD-IndexedDB-20100819/
http://www.w3.org/TR/2010/WD-IndexedDB-20100105/
http://www.w3.org/TR/2009/WD-WebSimpleDB-20090929/
Editors:
Nikunj Mehta, Invited Expert
Jonas Sicking, Mozilla
Eliot Graff, Microsoft
Andrei Popescu, Google
Jeremy Orlow, Google

Abstract

This document defines APIs for a database of records holding simple values and hierarchical objects. Each record consists of a key and some value. Moreover, the database maintains indexes over records it stores. An application developer directly uses an API to locate records either by their key or by using an index. A query language can be layered on this API. An indexed database can be implemented using a persistent B-tree data structure.

Status of This Document

This section describes the status of this document at the time of its publication. Other documents may supersede this document. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at http://www.w3.org/TR/.

This document was published by the Web Applications Working Group as a Working Draft. This document is intended to become a W3C Recommendation. If you wish to make comments regarding this document, please send them to public-webapps@w3.org (subscribe, archives). All feedback is welcome.

Publication as a Working Draft does not imply endorsement by the W3C Membership. This is a draft document and may be updated, replaced or obsoleted by other documents at any time. It is inappropriate to cite this document as other than work in progress.

This document was produced by a group operating under the 5 February 2004 W3C Patent Policy. W3C maintains a public list of any patent disclosures made in connection with the deliverables of the group; that page also includes instructions for disclosing a patent. An individual who has actual knowledge of a patent which the individual believes contains Essential Claim(s) must disclose the information in accordance with section 6 of the W3C Patent Policy.

Table of Contents

1. Introduction

This section is non-normative.

User agents need to store large numbers of objects locally in order to satisfy off-line data requirements of Web applications. [WEBSTORAGE] is useful for storing pairs of keys and their corresponding values. However, it does not provide in-order retrieval of keys, efficient searching over values, or storage of duplicate values for a key.

This specification provides a concrete API to perform advanced key-value data management that is at the heart of most sophisticated query processors. It does so by using transactional databases to store keys and their corresponding values (one or more per key), and providing a means of traversing keys in a deterministic order. This is often implemented through the use of persistent B-tree data structures that are considered efficient for insertion and deletion as well as in-order traversal of very large numbers of data records.

TODO: Add examples using the sync and the async APIs.

2. Conformance

As well as sections marked as non-normative, all authoring guidelines, diagrams, examples, and notes in this specification are non-normative. Everything else in this specification is normative.

The key words must, must not, required, should, should not, recommended, may, and optional in this specification are to be interpreted as described in [RFC2119].

This specification defines one class of products:

Conforming user agent

A user agent must behave as described in this specification in order to be considered conformant.

User agents may implement algorithms given in this specification in any way desired, so long as the end result is indistinguishable from the result that would be obtained by the specification's algorithms.

A conforming Indexed Database API user agent must also be a conforming implementation of the IDL fragments of this specification, as described in the “Web IDL” specification. [WEBIDL]

This specification uses both the terms "conforming user agent(s)" and "user agent(s)" to refer to this product class.

2.1 Dependencies

This specification relies on several other underlying specifications.

DOM-LEVEL-3-EVENTS
The terms default action and propagation path are defined by the Document Object Model (DOM) Level 3 Events Specification [DOM-LEVEL-3-EVENTS].
HTML5
The terms and algorithms document base URL, event handler attributes, event handler event type, Function, origin, same origin, structured clone, structured clone algorithm, task, task source, and queue a task are defined by the HTML 5 specification [HTML5].
WebIDL
Many of the interface definitions and all of the IDL in this spec depends on [[!!WEBIDL]].
WebWorkers
The term Worker is defined by the WebWorkers specification [WEBWORKERS].

3. Indexed Database API

3.1 Constructs

3.1.1 Database

Each origin has an associated set of databases. A database comprises one or more object stores which hold the data stored in the database.

Every database has a name which identifies it within a specific origin. The name can be any string value, including the empty string, and stays constant for the lifetime of the database. Each database also has a current version. When a database is first created, its version is the empty string.

Implementations must support all names. If a implementation uses a storage mechanism which can't handle arbitrary database names, the implementation must use an escaping mechanism or something similar to map the provided name to a name that it can handle.

Each database has one version at a time; a database can't exist in multiple versions at once. The only way to change the version is using a VERSION_CHANGE transaction.

Databases has a delete pending flag which is used during deletion. When a database is requested to be deleted the flag is set to true and all attempts at opening the database are stalled until the database can be deleted.

The act of opening a database creates a connection. There may be multiple connections to a given database at any given time. Each connection has a closePending flag which initially is set to false.

When a connection is initially created it is in opened state. The connection can be closed through several means. If the connection is GCed or execution context where the connection is created is destroyed (for example due to the user navigating away from that page), the connection is closed. The connection can also be closed explicitly using the steps for closing a database connection. When the connection is closed the closePending flag is always set to true if it hasn't already been.

The IDBDatabase and IDBDatabaseSync interfaces represent a connection to a database.

3.1.2 Object Store

An object store is the primary storage mechanism for storing data in a database.

Each database contain a set of object stores. The set of object stores can be changed, but can only be changed using a VERSION_CHANGE transactions. When a new database is created it doesn't contain any object stores and has the empty string as version.

The object store has a list of records which hold the data stored in the object store. Each record consists of a key and a value. The list is sorted according to key in ascending order. There can never be multiple records in a given object store with the same key.

Every object store has a name. The name is unique within the database to which it belongs. Every object store also optionally has a key generator and an optional key path. If the object store has a key path it is said to use in-line keys. Otherwise it is said to use out-of-line keys.

The object store can derive the key from one of three sources. Which source is used is determined when the object store is created. The three sources are:

  1. A key generator. A key generator generates a monotonically increasing numbers every time a key is needed.

    specify that generators are not shared between stores.

  2. Keys can be derived via a key path.
  3. Keys can also be explicitly specified when a value is stored in the object store.

The IDBObjectStore and IDBObjectStoreSync interfaces represent a object store. Note however that multiple instances of those interfaces representing the same object store can exist.

3.1.3 Keys

In order to efficiently retrieve records stored in an indexed database, each record is organized according to its key. A value is said to be a valid key if it is one of the following types: Array JavaScript objects [ECMA-262], DOMString [WEBIDL], Date [ECMA-262] or float [WEBIDL]. However Arrays are only valid keys if every item in the array is defined and is a valid key (i.e. sparse arrays can not be valid keys). Any non-numeric properties are ignored, and thus does not affect if the Array is a valid key. Additionally, if the value is of type float, it is only a valid key if it is not NaN. Conforming user agents must support all valid keys as keys.

Infinite float values are valid keys. As are empty Arrays.

For purposes of comparison, all Arrays are greater than all DOMString, Date and float values; all DOMString values are greater than all Date and float values; and all Date values are greater than all float values. Values of type float are compared to other float values numerically. Values of type Date are compared to other Date values chronologically. Values of type DOMString are compared to other values of type DOMString according to the collation of the object store or index where the value is used as a key. Values of type Array are compared to other values of type Array as follows:

  1. Let A be the first Array value and B be the second Array value.
  2. Let length be the lesser of A's length and B's length.
  3. Let i be 0.
  4. If the ith value of A is less than the ith value of B, then A is less than B. Skip the remaining steps.
  5. If the ith value of A is greater than the ith value of B, then A is greater than B. Skip the remaining steps.
  6. Increase i by 1.
  7. If i is not equal to length, go back to step 4. Otherwise continue to next step.
  8. If A's length is less than B's length, then A is less than B. If A's length is greater than B's length, then A is greater than B. Otherwise A and B are equal.

Note that Arrays that contain other Arrays are allowed as valid keys. In this case the algorithm above runs recursively when comparing the individual values in the arrays.

As a result of the above rules, an empty Array is the lowest possible key, while positive infinity is the highest possible key.

The terms greater than, less than and equal to is defined in the terms of the above comparisons.

3.1.4 Values

Each record is associated with a value. Conforming user agents must support any value supported by the structured clone algorithm [HTML5]. This includes simple types such as DOMString and Date as well as Object and Array instances.

3.1.5 Key Path

A key path is a DOMString that defines how to extract a key from a value. A valid key path is either the empty string, a JavaScript identifier, or multiple Javascript identifiers separated by periods (ASCII character code 46) [ECMA-262]. (Note that spaces are not allowed within a key path.) To evaluate a key path, run the steps for extracting a key from a value using a key path.

3.1.6 Index

It is sometimes useful to retrieve records in a object store through other means than their key. A index allows looking up records in a object store using properties of the values in the object stores records.

An index is a specialized persistent key-value storage and has a referenced object store. The index has a list of records which hold the data stored in the index. The records in an index are automatically populated whenever records in the referenced object store are inserted, updated or deleted. There can be several indexes referencing the same object store, in which changes to the object store cause all such indexes to get updated.

The values in the index's records are always values of keys in the index's referenced object store. The keys are derived from the referenced object store's values using a key path. If a given record with key X in the object store referenced by the index has the value A, and evaluating the index's key path on A yields the result Y, then the index will contain a record with key Y and value X.

Records in an index are said to have a referenced value. This is the value of the record in the index's referenced object store which has a key equal to the index's record's value. So in the example above, the record in the index whose key is Y and value is X has a referenced value of A.

Each record in an index reference one and only one record in the index's referenced object store. However there can be multiple records in an index which reference the same record in the object store. And there can also be no records in an index which reference a given record in an object store.

The records in an index are always sorted according to the records key. However unlike object stores, a given index can contain multiple records with the same key. Such records are additionally sorted according to the records value.

An index contains a unique flag. When this flag is set to true, the index enforces that no two records in the index has the same key. If a record in the index's referenced object store is attempted to be inserted or modified such that evaluating the index's key path on the records new value yields a result which already exists in the index, then the attempted modification to the object store fails.

An index also contains a multirow flag. This flag affects how the index behaves when the result of evaluating the index's key path yields an Array. If the multirow flag is false, then a single record whose key is an Array is added to the index. If the multirow flag is true, then the one record is added to the index for each item in the Array. The key for each record is the value of respective item in the Array.

The IDBIndex and IDBIndexSync interfaces provide access to the metadata of an index. Note however that multiple instances of those interfaces representing the same index can exist.

3.1.7 Transaction

A transaction is used to interact with the data in a database. Whenever data is read or written to the database this is done using a transaction.

All transactions are created using a connection, which is the transactions connection. The transaction has a mode which determines which types of interactions can be performed using the transaction. The mode is set when the transaction is created and remains constant for the lifetime of the transaction. The transaction also has a scope which determines which object stores the transaction can interact with. Finally, transactions have a active flag, which determines if new requests can currently be placed against the transaction. Finally, transactions also contain a request list of requests which have been placed against the transaction.

Transactions have a constant scope which is determined when the transaction is created and remains constant for the lifetime of the transaction.

Transactions offer some protection from application and system failures. A transaction may be used to store multiple data records or to conditionally modify certain data records. A transaction represents an atomic and durable set of data access and mutation operations.

Transactions are expected to be short lived. This is encouraged using the automatically committing functionality described below. Authors can still cause transactions to run for a long time, however this is generally not a usage pattern which is recommended and can lead to bad user experience in some implementations.

The lifetime of a transaction is as follows:

  1. A transaction is created using IDBDatabase.transaction. The arguments passed determine what the scope of the transaction is and whether it's read only or not. When a transaction is created its active flag is initially set to true.
  2. The implementation must allow requests to be placed against the transaction whenever the active flag is true. This is the case even if the transaction has not yet been started. Until the transaction is started the implementation must not execute these requests, but the implementation must still keep track of the requests and their order. Requests may only be placed against the transaction while the transaction is active. If a request is attempted to be placed against a transaction when it is not active, the implementation must reject the attempt by throwing a TRANSACTION_INACTIVE_ERR exception.
  3. Once an implementation is able to enforce the constraints defined for the mode of the transaction, defined below, the implementation must asynchronously start the transaction. When this happens is affected by the mode in which the transaction is opened, and which object stores are included in scope of the transaction.
  4. Once the transaction has been started the implementation can start executing the requests placed against the transaction. Unless otherwise defined requests must be executed in the order they are placed against the transaction. Likewise, their result must be returned in the order the request was placed against a specific transaction. There is no guarantee about the order that results from requests in different transactions are returned. Similarly, the isolation mode ensure that it doesn't matter which order requests placed against different transactions are executed.
  5. At any time a transaction can be aborted, even if the transaction isn't currently active. When a transaction is aborted the implementation must undo (roll back) any changes made to the database using the transaction. This includes both changes to the contents of object stores as well as additions and removals of object stores and indexes.

    A transaction can be aborted at any time before it is finished. Including if it isn't active or hasn't yet started.

  6. Once a transaction no longer can become active, and if the transaction hasn't been aborted, the implementation must automatically attempt to commit it. This usually happens after all requests placed against the transaction has been executed and their returned results handled, but no new requests has been placed against the transaction. When a transaction is committed implementation must atomically write any changes to the database made by requests placed against the transaction. That is, either all of the changes must be written, or if an error occurs, such as a disk write error, the implementation must not write any of the changes to the database. If such an error occurs the implementation must abort the transaction by following the steps for aborting a transaction, otherwise it must commit the transaction by following the steps for committing a transaction.
  7. When a transaction is committed or aborted, it is said to be finished. If a transaction can't be finished, for example due to the implementation crashing or the user taking some explicit action to cancel it, the implementation must abort the transaction.

Transactions are opened in one of three modes. The mode determine how concurrent access to object stores in the transaction is isolated.

  1. READ_ONLY
  2. READ_WRITE
  3. VERSION_CHANGE

The transaction mode determines both which operations are allowed to be performed during the transaction, as well whether two transactions can run concurrently or not. Which operations are allowed be be performed are defined in detail below, but in general transactions opened in READ_ONLY mode are only allowed to perform reading operations which does not change data. READ_WRITE transactions are allowed to perform reading and writing transactions to existing object stores, where as VERSION_CHANGE transactions are allowed to perform any operations, including ones that delete and create object stores and indexes.

A VERSION_CHANGE transaction can never run concurrently with other transactions. When a VERSION_CHANGE transaction is created, the implementation must wait to start the VERSION_CHANGE transaction until no other transactions against the same database are running. As long as the VERSION_CHANGE transaction, the implementation must wait with starting any other transactions against the same database until the VERSION_CHANGE transaction is finished.

Any number of transactions opened in READ_ONLY mode are allowed to run concurrently, even if the transaction's scope overlap and include the same object stores. As long as a READ_ONLY transaction is running, the data that the implementation returns through requests created with that transaction must remain constant. That is, two requests to read the same piece of data must yield the same result both for the case when data is found and the result is that data, and for the case when data is not found and a lack of data is indicated.

There are a number of ways that an implementation ensure this. It can prevent READ_WRITE transactions whose scope overlap the scope of the READ_ONLY transaction from starting until the READ_ONLY transaction is finished. Or it can allow the READ_ONLY transaction to see a snapshot of the contents of the object stores which is taken when the READ_ONLY transaction is started.

Similarly, implementations must ensure that a READ_WRITE transaction is only affected by changes to object stores that are made using the transaction itself. I.e. the implementation must ensure that another transaction does not modify the contents of object stores in the READ_WRITE transactions scope. The implementation must also ensure that if the READ_WRITE transaction completes successfully, that the changes written to object stores using the transaction can be committed to the database without merge conflicts. An implementation must not abort a transaction due to merge conflicts.

An implementation must not start any transaction until all other READ_WRITE transactions with overlapping scope have completed. When multiple transactions are eligible to be started, older transactions should be started first.

User agents must ensure a reasonable level of fairness across transactions to prevent starvation. For example if multiple READ_ONLY transaction are started one after another the implementation must ensure that that doesn't indefinitely prevent a pending READ_WRITE transaction from starting.

Conforming user agents must automatically abort a transaction at the end of the scope in which it was created, if an exception is propagated to that scope.

Transaction objects implement the IDBTransaction or the IDBTransactionSync interfaces.

3.1.8 Requests

Each reading and writing operation on a database is done using a request. Every request represents one read or write operation. Requests have a done flag which initially is false, and a source object. Every request also has a result and an errorCode, neither of which are accessible until the done flag is set to true.

Finally, requests have a request transaction. When a request is created, it is always placed against a transaction using either the steps to a asynchronously execute a request or the steps to a synchronously execute a request. This sets the request transaction to be that request. The only exceptions to this are the request returned from a IDBFactory.open call and the request returned from a IDBDatabase.setVersion call, which create requests which have a null request transaction.

3.1.9 Key Range

Records can be retrieved from object stores and indexes using either keys or key ranges. A key range is a continuous interval over some data type used for keys.

A key range may be lower-bounded or upper-bounded if there is a value that is, respectively, smaller than or larger than all its elements. A key range is said to be bounded if it is both lower- and upper-bounded and unbounded otherwise. A key range may be open, i.e., not including its endpoints or closed, i.e., including its endpoints. A key range may consist of a single value.

The IDBKeyRange interface defines a key range.

interface IDBKeyRange {
    readonly attribute any     lower;
    readonly attribute any     upper;
    readonly attribute boolean lowerOpen;
    readonly attribute boolean upperOpen;
    static IDBKeyRange only (in any value) raises (IDBDatabaseException);
    static IDBKeyRange lowerBound (in any bound, in optional boolean open) raises (IDBDatabaseException);
    static IDBKeyRange upperBound (in any bound, in optional boolean open) raises (IDBDatabaseException);
    static IDBKeyRange bound (in any lower, in any upper, in optional boolean lowerOpen, in optional boolean upperOpen) raises (IDBDatabaseException);
};
Attributes
lower of type any, readonly
This value is the lower-bound of the key range.
No exceptions.
lowerOpen of type boolean, readonly
Returns false if the lower-bound value is included in the key range.
No exceptions.
upper of type any, readonly
This value is the upper-bound of the key range.
No exceptions.
upperOpen of type boolean, readonly
Returns false if the upper-bound value is included in the key range.
No exceptions.
Methods
bound
Creates and returns a new key range with lower set to lower, lowerOpen set to lowerOpen, upper set to upper and upperOpen set to upperOpen.
Parameter Type Nullable Optional Description
lower any The lower-bound value
upper any The upper-bound value
lowerOpen boolean Is the lower-bound value included in the key range. Defaults to false.
upperOpen boolean Is the upper-bound value included in the key range. Defaults to false.
Exception Description
IDBDatabaseException
DATA_ERR Either the lower or upper parameters were not passed a valid key or the lower key is greater than the upper key or the lower key and upper key match and either of the bounds are open.
Return type: static IDBKeyRange
lowerBound
Creates and returns a new key range with lower set to lower, lowerOpen set to open, upper set to undefined and and upperOpen set to true.
Parameter Type Nullable Optional Description
bound any The lower bound value
open boolean Is the lower-bound value included in the key range. Defaults to false.
Exception Description
IDBDatabaseException
DATA_ERR The value parameter was not passed a valid key.
Return type: static IDBKeyRange
only
Creates and returns a new key range with both lower and upper set to value and both lowerOpen and upperOpen set to false.
Parameter Type Nullable Optional Description
value any The only value
Exception Description
IDBDatabaseException
DATA_ERR The value parameter was not passed a valid key.
Return type: static IDBKeyRange
upperBound
Creates and returns a new key range with lower set to undefined, lowerOpen set to true, upper set to value and and upperOpen set to open.
Parameter Type Nullable Optional Description
bound any The upper bound value
open boolean Is the upper-bound value included in the key range. Defaults to false.
Exception Description
IDBDatabaseException
DATA_ERR The value parameter was not passed a valid key.
Return type: static IDBKeyRange

A key is in a key range if both the following conditions are fulfilled:

3.1.10 Cursor

Cursors are a transient mechanism used to iterate over multiple records in a database. The storage operations are performed on the underlying index or an object store.

A cursor comprises a range of records in either an index or an object store. The cursor has a source indicating which index or object store whose records it is iterating. A cursor maintains a position over this series, which moves in a direction that is either monotonically increasing or decreasing order of the record keys. Cursors also have a key and a value which represent the key and the value of the last iterated record. Cursors finally have a got value flag. When this flag is false, the cursor is either in the process of loading the next value or it has reached the end of its range, when it is true, it indicates that the cursor is currently holding a value and that it is ready to iterate to the next one.

If the source of a cursor is a object store, the effective object store of the cursor is that object store and the effective key of the cursor is the cursors position. If the source of a cursor is a index, the effective object store of the cursor is that index's referenced object store and the effective key is the cursors object store position.

It is possible for the list of records which the cursor is iterating over to change before the full range of the cursor has been iterated. In order to handle this, cursors maintain their position not as an index, but rather as a key of the previously returned record. For a forward iterating cursor, the next time the cursor is asked to iterate to the next record it returns the record with the lowest key greater than the one previously returned. For a backwards iterating cursor, the situation is opposite and it returns the record with the highest key less than the one previously returned.

For cursors iterating indexes the situation is a little bit more complicated since multiple records can have the same key and are therefor also sorted by value. When iterating indexes the cursor's also has a object store position, which indicates the value of the previously found record in the index. Both position and the object store position is used when finding the next appropriate record.

Cursor objects implement the IDBCursor or the IDBCursorSync interfaces. There is only ever one IDBCursor or IDBCursorSync instance representing a given cursor. However there is no limit on how many cursors can be used at the same time.

3.1.11 The IDBDatabaseException Interface

exception IDBDatabaseException {
    const unsigned short UNKNOWN_ERR = 1;
    const unsigned short NON_TRANSIENT_ERR = 2;
    const unsigned short NOT_FOUND_ERR = 3;
    const unsigned short CONSTRAINT_ERR = 4;
    const unsigned short DATA_ERR = 5;
    const unsigned short NOT_ALLOWED_ERR = 6;
    const unsigned short TRANSACTION_INACTIVE_ERR = 7;
    const unsigned short ABORT_ERR = 8;
    const unsigned short READ_ONLY_ERR = 9;
    const unsigned short TIMEOUT_ERR = 10;
    const unsigned short QUOTA_ERR = 11;;
    attribute unsigned short code;
    attribute DOMString      message;
};
Fields
code of type attribute unsigned short
Return the most appropriate error code.
message of type attribute DOMString
Return an error message describing the exception raised. The message should be localized to the user's language.
Constants
ABORT_ERR of type unsigned short
A request was aborted, for example through a call to IDBTransaction.abort.
CONSTRAINT_ERR of type unsigned short
A mutation operation in the transaction failed due to a because a constraint was not satisfied. For example, an object such as an object store or index already exists and a new one was being attempted to be created.
DATA_ERR of type unsigned short
Data provided to an operation does not meet requirements.
NON_TRANSIENT_ERR of type unsigned short
This error occurred because an operation was not allowed on an object. A retry of the same operation would fail unless the cause of the error is corrected.
NOT_ALLOWED_ERR of type unsigned short
A operation called on an object on which it is not allowed or at a time when it is not allowed. The TRANSACTION_INACTIVE_ERR and READ_ONLY_ERR errors are more specific variants of this error.
NOT_FOUND_ERR of type unsigned short
The operation failed because the requested database object could not be found. For example, an object store did not exist but was being opened.
QUOTA_ERR of type unsigned short
The operation failed because there was not enough remaining storage space, or the storage quota was reached and the user declined to give more space to the database.
READ_ONLY_ERR of type unsigned short
The mutating operation was attempted in a READ_ONLY transaction.
TIMEOUT_ERR of type unsigned short
A lock for the transaction could not be obtained in a reasonable time.
TRANSACTION_INACTIVE_ERR of type unsigned short
A request was placed against a transaction which is currently not active, or which is finished.
UNKNOWN_ERR of type unsigned short
The operation failed for reasons unrelated to the database itself and not covered by any other error code.

These codes are in flux and may change entirely as exception/error handling may be changing in the WebIDL spec.

3.1.12 Options Object

Options objects are simply JavaScript objects [ECMA-262] which are used to supply optional parameters to some indexedDB functions like createObjectStore and createIndex. The attributes on the object correspond to optional parameters on the function called. The domain of valid attributes/parameters depends on the function called. If an attribute is present in the object which is not part of that domain, a NON_TRANSIENT_ERR exception must be thrown. Similarly, if any attribute has a getter function or its value is an object, a NOT_TRANSIENT_ERR exception must be thrown.

We disallow getters and objects because the getter function and the toString function can execute arbitrary JavaScript which exposes many obscure corner cases which aren't worth speccing out. For example, navigating the page or adding an objectStore while inside a createObjectStore call.

This should probably be moved into the WebIDL spec.

3.2 Asynchronous APIs

The asynchronous API methods return without blocking the calling thread. All asynchronous operations immediately return an IDBRequest instance. This object does not initially contain any information about the result of the operation. Once information becomes available, an event is fired on the request and the information becomes available thorugh the properties of the IDBRequest instance.

3.2.1 The IDBRequest Interface

The IDBRequest interface provides means to access results of asynchronous requests to databases and database objects using event handler attributes [DOM-LEVEL-3-EVENTS].

Example

In the following example, we open a database asynchronously. Various event handlers are registered for responding to various situations.

ECMAScript

 var request = indexedDB.open('AddressBook', 'Address Book');
 request.onsuccess = function(evt) {...};
 request.onerror = function(evt) {...};
            
interface IDBRequest : EventTarget {
    readonly attribute any            result getraises (IDBDatabaseException);
    readonly attribute unsigned short errorCode getraises (IDBDatabaseException);
    readonly attribute Object         source;
    readonly attribute IDBTransaction transaction;
    const unsigned short LOADING = 1;
    const unsigned short DONE = 2;
    readonly attribute unsigned short readyState;
             attribute Function       onsuccess;
             attribute Function       onerror;
};
Attributes
errorCode of type unsigned short, readonly
When the done flag is true, getting this property must return the errorCode of the request. This is NO_ERR when no error occurred. When the done flag is false, getting this property must throw a NOT_ALLOWED_ERR exception.
Exception On Get On Set Description
IDBDatabaseException
NOT_ALLOWED_ERR Thrown when this attribute was read when the done flag was set to false.
onerror of type Function
The event handler for the error event
No exceptions.
onsuccess of type Function
The event handler for the success event
No exceptions.
readyState of type unsigned short, readonly
When the done flag is false, returns LOADING, otherwise returns DONE.
No exceptions.
result of type any, readonly
When the done flag is true, getting this property must return the result of the request. This is undefined when the request resulted in an error. When the done flag is false, getting this property must throw a NOT_ALLOWED_ERR exception.
Exception On Get On Set Description
IDBDatabaseException
NOT_ALLOWED_ERR Thrown when this attribute was read when the done flag was set to false.
source of type Object, readonly
Getting this property must return the source for the request.
No exceptions.
transaction of type IDBTransaction, readonly
Getting this property must return the transaction for the request. This property can be null for certain requests, such as for request returned from IDBFactory.open and IDBDatabase.setVersion.
No exceptions.
Constants
DONE of type unsigned short
This state indicates that a result to a previous request is available in the result attribute.
LOADING of type unsigned short
This state indicates that a request has been started but its results is not yet available.

When a request is made, a new request is returned with its readyState set to LOADING. If a request completes successfully, the readyState is changed to DONE, the result is set to the result of the request, and a event with type success is fired at the request.

If an error occurs while performing the operation, the readyState is changed to DONE, the errorCode is set to the code of the error, and a event with type error is fired at the request.

The setVersion function on IDBDatabase uses a separate interface for its requests in order to make use of the blocked event eaiser.

interface IDBVersionChangeRequest : IDBRequest {
    attribute Function onblocked;
};
Attributes
onblocked of type Function
The event handler for the blocked event
No exceptions.

The task source for these tasks is the database access task source.

3.2.2 Event interfaces

This specification fires events with the following custom interfaces:

interface IDBVersionChangeEvent : Event {
    readonly attribute DOMString version;
};
Attributes
version of type DOMString, readonly
Returns the new version of the database during a VERSION_CHANGE transaction. See the steps for running a VERSION_CHANGE transaction.
No exceptions.

3.2.3 Opening a database

Window and WorkerUtils objects must implement the IDBEnvironment interface.

Window implements IDBEnvironment;

All instances of the Window type are defined to also implement the IDBEnvironment interface.

WorkerUtils implements IDBEnvironment;

All instances of the WorkerUtils type are defined to also implement the IDBEnvironment interface.

[NoInterfaceObject]
interface IDBEnvironment {
    readonly attribute IDBFactory indexedDB;
};
Attributes
indexedDB of type IDBFactory, readonly
This attribute provides applications a mechanism for accessing capabilities of indexed databases.
No exceptions.

Every method for making asynchronous requests returns an IDBRequest object that communicates back to the requesting application through events. This design means that any number of requests can be active on any database or object handle at a time.

interface IDBFactory {
    IDBRequest open (in DOMString name);
    IDBRequest deleteDatabase (in DOMString name);
    int        cmp (in any first, in any second) raises (IDBDatabaseException);
};
Methods
cmp

When invoked, this method must compare two keys. It'll return -1 if the first key is greater than the second, 1 if the first is less than the second, and 0 if the first is equal to the second.

This should probably take a collation parameter as well. In fact, it might make sense for this to be on the IDBDatabase, IDBObjectStore, and IDBIndex as well and do the comparison with their default collation.

Parameter Type Nullable Optional Description
first any The first key to compare.
second any The second key to compare.
Exception Description
IDBDatabaseException
NON_TRANSIENT_ERR One of the supplied keys was not a valid key.
Return type: int
deleteDatabase

When invoked, this method must create a request and return it. The created request has no source. The method then asynchronously runs the steps for deleting a database. Let origin be the origin of the IDBEnvironment used to access this IDBFactory and name be the name parameter passed to this function.

If an error is returned from the steps above, the implementation must set the errorCode of the request to the code of the error returned and fire a error event at the request.

If the steps above are successful, the implementation must set the result of the request to null and fire a success event at the request.

Parameter Type Nullable Optional Description
name DOMString The name for the database
No exceptions.
Return type: IDBRequest
open

When invoked, this method must create a request and return it. The created request has no source. The method then asynchronously runs the steps for opening a database. Let origin be the origin of the IDBEnvironment used to access this IDBFactory and name be the name parameter passed to this function.

If an error is returned from the steps above, the implementation must set the errorCode of the request to the code of the error returned and fire a error event at the request.

If the steps above are successful, the implementation must set the result of the request to the connection created by the steps above and fire a success event at the request.

Parameter Type Nullable Optional Description
name DOMString The name for the database
No exceptions.
Return type: IDBRequest

3.2.4 Database

A database object can be used to manipulate the objects of that database. That is also the only way to obtaining a transaction for that database.

interface IDBDatabase : EventTarget {
    readonly attribute DOMString     name;
    readonly attribute DOMString     version;
    readonly attribute DOMStringList objectStoreNames;
    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 ();
             attribute Function      onabort;
             attribute Function      onerror;
             attribute Function      onversionchange;
};
Attributes
name of type DOMString, readonly
On getting, this attribute must return the name of the connected database. The function must return this name even if the closePending flag is set on the connection. In other words, the return value from this function stays constant for the lifetime of the IDBDatabase instance.
No exceptions.
objectStoreNames of type DOMStringList, readonly
On getting, this attribute must return a list of names of the object stores currently in the connected database. Once the closePending flag is set on the connection, this function must return a snapshot of the list of names of the object stores taken at the time when the close method was called. Even if other connections are later used to change the set of object stores that exist in the database. In other words, the return value from this function stays constant for the lifetime of the IDBDatabase instance, unless setVersion and createObjectStore or deleteObjectStore is called on this IDBDatabase instance itself.
No exceptions.
onabort of type Function
The event handler for the abort event.
No exceptions.
onerror of type Function
The event handler for the error event.
No exceptions.
onversionchange of type Function
The event handler for the versionchange event.
No exceptions.
version of type DOMString, readonly
On getting, this attribute must return the version of this database. This attribute has the empty string value when the connected database is first created. Once the closePending flag is set on the connection, this function must return a snapshot of the version taken when the close method was called. Even if other connections are later used to change the version of the database. In other words, the return value from this function stays constant for the lifetime of the IDBDatabase instance, unless setVersion is called on this IDBDatabase instance itself.
No exceptions.
Methods
close
This method returns immediately and performs the steps for closing a database connection.
No parameters.
No exceptions.
Return type: void
createObjectStore

This method creates and returns a new object store with the given name in the connected database. If this function is called from outside a VERSION_CHANGE transaction callback, the implementation must throw a NOT_ALLOWED_ERR exception. If an objectStore with the same name already exists, the implementation must throw a CONSTRAINT_ERR exception. Otherwise, the implementation must create a new object store and return a IDBObjectStore object representing it.

If the optionalParameters argument is specified and has a keyPath property which is not undefined or null, then set keyPath to the value of this property. If keyPath is an Array, then each item in the array is converted to a string. If keyPath is not an Array, it is converted to a string.

If keyPath is an Array and any items in the array is not a valid key path, or if keyPath is a string and is not a valid key path then a NON_TRANSIENT_ERR error must be thrown. Otherwise set the created object store's key path is set to the value of keyPath.

In some implementations it's possible for the implementation to asynchronously run into problems creating the object store after the createObjectStore function has returned. For example in implementations where metadata about the newly created objectStore is inserted into the database asynchronously, or where the implementation might need to ask the user for permission for quota reasons. Such implementations must still create and return a IDBObjectStore object. Instead, once the implementation realizes that creating the objectStore has failed, it must abort the transaction using the steps for aborting a transaction.

Parameter Type Nullable Optional Description
name DOMString The name of a new object store
optionalParameters Object The options object whose attributes are optional parameters to this function. Valid attributes are keyPath and autoIncrement. keyPath specifies the key path of the new object store. If the attribute is null, undefined, or not present, no key path is specified and thus keys are out-of-line. autoIncrement specifies whether the object store created should have a key generator. It defaults to false.
Exception Description
IDBDatabaseException
NOT_ALLOWED_ERR This method was not called from a VERSION_CHANGE transaction callback.
CONSTRAINT_ERR An object store with the same name, compared in a case-sensitive manner, already exists in the connected database.
NON_TRANSIENT_ERR optionalParameters has attributes other than keyPath and autoIncrement.
Return type: IDBObjectStore
deleteObjectStore

This method destroys the object store with the given name in the connected database as well as all indexes that are referencing that object store. Note that this method must only be called from a VERSION_CHANGE transaction callback.

Parameter Type Nullable Optional Description
name DOMString The name of an existing object store
Exception Description
IDBDatabaseException
NOT_ALLOWED_ERR This method was not called from a VERSION_CHANGE transaction callback.
NOT_FOUND_ERR There is no object store with the given name, compared in a case-sensitive manner, in the connected database.
Return type: IDBRequest
setVersion
This method updates the version of the database by following the steps for running a VERSION_CHANGE transaction using the version argument as version and the IDBDatabase this function was called on as connection. Return the IDBVersionChangeRequest returned by those steps.
Parameter Type Nullable Optional Description
version DOMString The version to store in the database
No exceptions.
transaction

This method, when called must execute the steps for creating a transaction in a asychronous fashion. The storeNames and mode arguments are forwarded to the algorithm as-is. The callback argument is set to null. The timeout argument is set to infinite. The connection argument is set to the IDBDatabase that the transaction() method was called on.

The method returns a IDBTransaction object representing the transaction returned by the steps above.

Parameter Type Nullable Optional Description
storeNames any The names of object stores and indexes in the scope of the new transaction
mode unsigned short The mode for isolating access to data inside the given object stores. If this parameter is not provided, the default access mode is READ_ONLY.
Exception Description
IDBDatabaseException
NOT_ALLOWED_ERR The close() method has been called on this IDBDatabase instance.
NOT_FOUND_ERR One of the names provided in the storeNames argument doesn't exist in this database.
Return type: IDBTransaction

3.2.5 Object Store

Object store objects implement the following interface:
interface IDBObjectStore {
    readonly attribute DOMString      name;
    readonly attribute DOMString      keyPath;
    readonly attribute DOMStringList  indexNames;
    readonly attribute IDBTransaction transaction;
    IDBRequest put (in any value, in optional any key) raises (IDBDatabaseException, DOMException);
    IDBRequest add (in any value, in optional any key) raises (IDBDatabaseException, DOMException);
    IDBRequest delete (in any key) raises (IDBDatabaseException);
    IDBRequest get (in any key) raises (IDBDatabaseException);
    IDBRequest clear () raises (IDBDatabaseException);
    IDBRequest openCursor (in optional any range, in optional unsigned short direction) raises (IDBDatabaseException);
    IDBIndex   createIndex (in DOMString name, in DOMString keyPath, in optional Object optionalParameters) raises (IDBDatabaseException);
    IDBIndex   index (in DOMString name) raises (IDBDatabaseException);
    void       deleteIndex (in DOMString indexName) raises (IDBDatabaseException);
};
Attributes
indexNames of type DOMStringList, readonly
On getting, provide a list of the names of indexes on objects in this object store.
No exceptions.
keyPath of type DOMString, readonly
On getting, provide the key path of this object store. If this attribute is null, the application must provide a key value for each modification operation.
No exceptions.
name of type DOMString, readonly
On getting, provide the name of this object store.
No exceptions.
transaction of type IDBTransaction, readonly
On getting, returns the transaction this object store belongs to.
No exceptions.
Methods
add

This method throws a READ_ONLY_ERR if the transaction which this IDBObjectStore belongs to is has its mode set to READ_ONLY. If any of the following conditions are true, this method throws a DATA_ERR exception:

Otherwise this method creates a structured clone of the value parameter. If this throws an exception that exception is rethrown. It then runs the steps for asynchronously executing a request and returns the IDBRequest created by these steps. The steps are run with this IDBObjectStore as source and the steps for storing a record into an object store as operation, using this IDBObjectStore as store, the created clone as value, the key parameter as key, and with the no-overwrite flag flag set to true.

Parameter Type Nullable Optional Description
value any The value to be stored in the record
key any The key used to identify the record
Exception Description
IDBDatabaseException
TRANSACTION_INACTIVE_ERR The transaction this IDBObjectStore belongs to is not active.
READ_ONLY_ERR The mode of the associated transaction is READ_ONLY.
DATA_ERR The calculated key for the insertion was not a valid key. Also thrown if the calculated key for any of the indexes which belong to this object store had a calculated key which was not a valid key
DOMException
DATA_CLONE_ERR The data being stored could not be cloned by the internal structured cloning algorithm.
Return type: IDBRequest
clear

This method throws a READ_ONLY_ERR if the transaction which this IDBObjectStore belongs to is has its mode set to READ_ONLY.

Otherwise this method runs the steps for asynchronously executing a request and returns the IDBRequest created by these steps. The steps are run with this IDBObjectStore as source and the steps for clearing an object store as operation, using this IDBObjectStore as store.

No parameters.
Exception Description
IDBDatabaseException
TRANSACTION_INACTIVE_ERR The transaction this IDBObjectStore belongs to is not active.
READ_ONLY_ERR The mode of the transaction this IDBObjectStore belongs to is READ_ONLY.
Return type: IDBRequest
createIndex

This method creates and returns a new index with the given name and parameters in the connected database. If this function is called from outside a VERSION_CHANGE transaction callback, the implementation must throw a NOT_ALLOWED_ERR exception. If an index with the same name already exists, the implementation must throw a CONSTRAINT_ERR exception. Otherwise, the implementation must create a new index and return a IDBIndex object representing it. The created index has its unique and multirow flags are set to the values of the unique and multirow properties in the optionalParameters argument.

If the keyPath argument is an Array, then each item in the array is converted to a string. If keyPath is not an Array, it is converted to a string.

If keyPath is an Array and any items in the array is not a valid key path, or if keyPath is a string and is not a valid key path, or if keyPath is and Array and the multirow property in the optionalParameters is true, then a NON_TRANSIENT_ERR error must be thrown. Otherwise set the created object store's key path is set to the value of keyPath.

The index that is requested to be created can contain constraints on the data allowed in the index's referenced object store, such as requiring uniqueness of the values referenced by the index's keyPath. If the referenced object store already contains data which violates these constraints, this must not cause the implementation of createIndex to throw an exception or affect what it returns. The implementation must still create and return a IDBIndex object. Instead the implementation must asynchronously abort the VERSION_CHANGE transaction which was used for the createIndex call.

In some implementations it's possible for the implementation to asynchronously run into problems creating the index after the createIndex function has returned. For example in implementations where metadata about the newly created index is inserted into the database asynchronously, or where the implementation might need to ask the user for permission for quota reasons. Such implementations must still create and return a IDBIndex object. Instead, once the implementation realizes that creating the index has failed, it must abort the transaction using the steps for aborting a transaction.

Parameter Type Nullable Optional Description
name DOMString The name of a new index
keyPath DOMString The key path used by the new index
optionalParameters Object The options object whose attributes are optional parameters to this function. The valid options are unique and multirow. unique specifies whether the index's unique flag is set. It defaults to false. multirow specifies whether the index's multirow flag is set. It defaults to false.
Exception Description
IDBDatabaseException
NOT_ALLOWED_ERR This method was not called from a VERSION_CHANGE transaction callback.
CONSTRAINT_ERR An index with the same name, compared in a case-sensitive manner, already exists in the connected database.
NON_TRANSIENT_ERR optionalParameters has attributes other than unique.
Return type: IDBIndex
delete

This method throws a READ_ONLY_ERR if the transaction which this IDBObjectStore belongs to is has its mode set to READ_ONLY. If the key parameter is not a valid key this method throws a DATA_ERR exception.

Otherwise this method runs the steps for asynchronously executing a request and returns the IDBRequest created by these steps. The steps are run with this IDBObjectStore as source and the steps for deleting a record from an object store as operation, using this IDBObjectStore as store and the key parameter as key.

Parameter Type Nullable Optional Description
key any Key identifying the record to be deleted
Exception Description
IDBDatabaseException
TRANSACTION_INACTIVE_ERR The transaction this IDBObjectStore belongs to is not active.
READ_ONLY_ERR The mode of the transaction this IDBObjectStore belongs to is READ_ONLY.
Return type: IDBRequest
deleteIndex

This method destroys the index with the given name in the connected database. Note that this method must only be called from a VERSION_CHANGE transaction callback.

Parameter Type Nullable Optional Description
indexName DOMString The name of an existing index
Exception Description
IDBDatabaseException
NOT_ALLOWED_ERR This method was not called from a VERSION_CHANGE transaction callback.
NOT_FOUND_ERR There is no index with the given name, compared in a case-sensitive manner, in the connected database.
Return type: void
get

If the key parameter is not a valid key or a key range, this method throws a DATA_ERR exception. Otherwise, this method runs the steps for asynchronously executing a request and returns the IDBRequest created by these steps. The steps are run with this IDBObjectStore as source and the steps for retrieving a value from an object store as operation, using this IDBObjectStore as store and the key parameter as key.

This function produces the same result if a record with the given key doesn't exist as when a record exists, but has undefined as value. If you need to tell the two situations apart, you can use openCursor with the same key. This will return a cursor with undefined as value if a record exists, or no cursor if no such record exists.

Parameter Type Nullable Optional Description
key any Key identifying the record to be retrieved. This can also be a IDBKeyRange in which case the function retreives the first existing value in that range.
Exception Description
IDBDatabaseException
TRANSACTION_INACTIVE_ERR The transaction this IDBObjectStore belongs to is not active.
DATA_ERR The key parameter was not passed a valid value.
Return type: IDBRequest
index
Returns a IDBIndex representing a index that is part of the to this object store. Every call to this function on the same IDBObjectStore instance and with the same name returns the same IDBIndex instance. However the retured IDBIndex instance is specific to this IDBObjectStore instance. If this function is called on a different IDBObjectStore instance, a different IDBIndex instance is returned. A result of this is that different IDBTransactions use different IDBIndex instances to represent the same index.
Parameter Type Nullable Optional Description
name DOMString The name of an existing index
Exception Description
IDBDatabaseException
NOT_FOUND_ERR There is no index with the given name, compared in a case-sensitive manner, in the connected database.
Return type: IDBIndex
openCursor

If the range parameter is specified but is not a valid key or a key range, this method throws a DATA_ERR exception. Otherwise, this method creates a cursor. The cursor must implement the IDBCursorWithValue interface.

The newly created cursor must have an undefined position, a direction set to the value of the direction parameter, false as iterable flag value, and undefined key and value. The source of the cursor is the IDBObjectStore this function was called on.

If the range parameter is a key range then the cursor's range must be set to that range. Otherwise, if the range parameter is a valid key then the cursor's range is set to key range containing only that key value. If the range parameter is not specified, the cursor's key range is left as undefined.

This method runs the steps for asynchronously executing a request and returns the IDBRequest created by these steps. The steps are run with this IDBObjectStore as source and the steps for iterating a cursor as operation, using the created cursor as cursor and with undefined as key.

Parameter Type Nullable Optional Description
range any The key range to use as the cursor's range
direction unsigned short The cursor's required direction
Exception Description
IDBDatabaseException
TRANSACTION_INACTIVE_ERR The transaction this IDBObjectStore belongs to is not active.
DATA_ERR The range parameter was not passed key range or a valid key.
Return type: IDBRequest
put

This method throws a READ_ONLY_ERR if the transaction which this IDBObjectStore belongs to is has its mode set to READ_ONLY. If any of the following conditions are true, this method throws a DATA_ERR exception:

Otherwise this method creates a structured clone of the value parameter. If this throws an exception that exception is rethrown. It then runs the steps for asynchronously executing a request and returns the IDBRequest created by these steps. The steps are run with this IDBObjectStore as source and the steps for storing a record into an object store as operation, using this IDBObjectStore as store, the created clone as value, the key parameter as key, and with the no-overwrite flag flag set to false.

Parameter Type Nullable Optional Description
value any The value to be stored in the record
key any The key used to identify the record
Exception Description
IDBDatabaseException
TRANSACTION_INACTIVE_ERR The transaction this IDBObjectStore belongs to is not active.
READ_ONLY_ERR The mode of the associated transaction is READ_ONLY.
DATA_ERR The calculated key for the insertion was not a valid key. Also thrown if the calculated key for any of the indexes which belong to this object store had a calculated key which was not a valid key
DOMException
DATA_CLONE_ERR The data being stored could not be cloned by the internal structured cloning algorithm.
Return type: IDBRequest

3.2.6 Index

Index objects implement the following interface:

interface IDBIndex {
    readonly attribute DOMString      name;
    readonly attribute IDBObjectStore objectStore;
    readonly attribute DOMString      keyPath;
    readonly attribute boolean        unique;
    IDBRequest openCursor (in optional IDBKeyRange range, in optional unsigned short direction) raises (IDBDatabaseException);
    IDBRequest openKeyCursor (in optional IDBKeyRange range, in optional unsigned short direction) raises (IDBDatabaseException);
    IDBRequest get (in any key) raises (IDBDatabaseException);
    IDBRequest getKey (in any key) raises (IDBDatabaseException);
};
Attributes
keyPath of type DOMString, readonly
On getting, provide the key path of this index. If this attribute is null, this index is not auto-populated.
No exceptions.
name of type DOMString, readonly
On getting, provide the name of this index.
No exceptions.
objectStore of type IDBObjectStore, readonly
On getting, returns a reference to the IDBObjectStore instance for the referenced object store in this IDBIndex's transaction. This must return the same IDBObjectStore instance as was used to get a reference to this IDBIndex.
No exceptions.
unique of type boolean, readonly
On getting, provide the unique flag of this index.
No exceptions.
Methods
get

If the key parameter is not a valid key or a key range, this method throws a DATA_ERR exception. This method runs the steps for asynchronously executing a request and returns the IDBRequest created by these steps. The steps are run with this IDBObjectStore as source and the steps for retrieving a referenced value from an index as operation, using this IDBIndex as index and the key parameter as key.

This function produces the same result if a record with the given key doesn't exist as when a record exists, but has undefined as value. If you need to tell the two situations apart, you can use openCursor with the same key. This will return a cursor with undefined as value if a record exists, or no cursor if no such record exists.

Parameter Type Nullable Optional Description
key any Key identifying the record to be retrieved. This can also be a IDBKeyRange in which case the function retreives the first existing value in that range.
Exception Description
IDBDatabaseException
TRANSACTION_INACTIVE_ERR The transaction this IDBIndex belongs to is not active.
DATA_ERR The key parameter was not passed a valid value.
Return type: IDBRequest
getKey

If the key parameter is not a valid key or a key range, this method throws a DATA_ERR exception. This method runs the steps for asynchronously executing a request and returns the IDBRequest created by these steps. The steps are run with this IDBObjectStore as source and the steps for retrieving a value from an index as operation, using this IDBIndex as index and the key parameter as key.

This function produces the same result if a record with the given key doesn't exist as when a record exists, but has undefined as value. If you need to tell the two situations apart, you can use openKeyCursor with the same key. This will return a cursor with undefined as value if a record exists, or no cursor if no such record exists.

Parameter Type Nullable Optional Description
key any Key identifying the record to be retrieved. This can also be a IDBKeyRange in which case the function retreives the first existing value in that range.
Exception Description
IDBDatabaseException
TRANSACTION_INACTIVE_ERR The transaction this IDBIndex belongs to is not active.
DATA_ERR The key parameter was not passed a valid value.
Return type: IDBRequest
openCursor

If the range parameter is specified but is not a valid key or a key range, this method throws a DATA_ERR exception. Otherwise, this method creates a cursor. The cursor must implement the IDBCursorWithValue interface.

The newly created cursor must have an undefined position, a direction set to the value of the direction parameter, false as iterable flag value, and undefined key and value. The source of the cursor is the IDBIndex this function was called on.

If the range parameter is a key range then the cursor's range is set to that range. Otherwise, if the range parameter is a valid key then the cursor's range is set to key range containing only that key value. If the range parameter is not specified, the cursor's key range is left as undefined.

This method runs the steps for asynchronously executing a request and returns the IDBRequest created by these steps. The steps are run with this IDBIndex as source and the steps for iterating a cursor as operation, using the created cursor as cursor and with undefined as key

Parameter Type Nullable Optional Description
range IDBKeyRange The key range to use as the cursor's range
direction unsigned short The cursor's required direction
Exception Description
IDBDatabaseException
TRANSACTION_INACTIVE_ERR The transaction this IDBIndex belongs to is not active.
DATA_ERR The range parameter was not passed key range or a valid key.
Return type: IDBRequest
openKeyCursor

If the range parameter is specified but is not a valid key or a key range, this method throws a DATA_ERR exception. Otherwise, this method creates a cursor. The cursor must implement the IDBCursor interface, but must not implement the IDBCursorWithValue interface.

The newly created cursor must have an undefined position, a direction set to the value of the direction parameter, false as iterable flag value, and undefined key and value. The source of the cursor is the IDBIndex this function was called on.

If the range parameter is a key range then the cursor's range is set to that range. Otherwise, if the range parameter is a valid key then the cursor's range is set to key range containing only that key value. If the range parameter is not specified, the cursor's key range is left as undefined.

This method runs the steps for asynchronously executing a request and returns the IDBRequest created by these steps. The steps are run with this IDBObjectStore as source and the steps for iterating a cursor as operation, using the created cursor as cursor and with undefined as key

Parameter Type Nullable Optional Description
range IDBKeyRange The key range to use as the cursor's range
direction unsigned short The cursor's required direction
Exception Description
IDBDatabaseException
TRANSACTION_INACTIVE_ERR The transaction this IDBIndex belongs to is not active.
DATA_ERR The range parameter was not passed key range or a valid key.
Return type: IDBRequest

3.2.7 Cursor

Cursor objects implement the following interface:

interface IDBCursor {
    const unsigned short NEXT = 0;
    const unsigned short NEXT_NO_DUPLICATE = 1;
    const unsigned short PREV = 2;
    const unsigned short PREV_NO_DUPLICATE = 3;
    readonly attribute Object         source;
    readonly attribute unsigned short direction;
    readonly attribute any            key;
    readonly attribute any            primaryKey;
    IDBRequest update (in any value) raises (IDBDatabaseException, DOMException);
    void       advance (in int count);
    void       continue (in optional any key) raises (IDBDatabaseException);
    IDBRequest delete () raises (IDBDatabaseException);
};
Attributes
direction of type unsigned short, readonly
On getting, provide the traversal direction of the cursor.
No exceptions.
key of type any, readonly
Returns the cursor's current key. However if the cursor's got value flag is false it returns undefined. I.e. if it's currently being iterated or has iterated past the end of its range.
No exceptions.
primaryKey of type any, readonly
Returns the cursor's current effective key. However if the cursor's got value flag is false it returns undefined. I.e. if it's currently being iterated or has iterated past the end of its range.
No exceptions.
source of type Object, readonly
On getting, returns the IDBObjectStore or IDBIndex which this cursor is iterating. This function never returns null or throws an exception, even if the is currently being iterated, has iterated past its end, or its transaction is not active.
No exceptions.
Methods
advance

This method runs the steps for asynchronously executing a request. However, the steps are slightly modified such that instead of creating a new IDBRequest, it reuses the request originally created when this cursor was created. The done flag on the request is set to false before the request is returned. The steps are run with the cursor's source as source. The operation runs the steps for iterating a cursor count number of times with null as key and this cursor as cursor.

Parameter Type Nullable Optional Description
count int The number of advances forward the cursor should make.
No exceptions.
Return type: void
continue

If this cursor's got value flag is false, this method throws a NOT_ALLOWED_ERR. If the key parameter is specified and fulfills any of these conditions this method must throw a DATA_ERR exception:

Otherwise this method runs the steps for asynchronously executing a request. However, the steps are slightly modified such that instead of creating a new IDBRequest, it reuses the request originally created when this cursor was created. The done flag on the request is set to false before the request is returned. The steps are run with the cursor's source as source and the steps for iterating a cursor as operation, using this cursor as cursor and the key parameter as key.

Before this method returns, unless an exception was thrown, it sets the got value flag on the cursor to false.

Parameter Type Nullable Optional Description
key any The next key to position this cursor at
Exception Description
IDBDatabaseException
TRANSACTION_INACTIVE_ERR The transaction this IDBCursor belongs to is not active.
NOT_ALLOWED_ERR The cursor is currently being iterated, or has iterated past its end.
DATA_ERR The key parameter was specified but did not contain a valid key.
Return type: void
delete

This method throws a READ_ONLY_ERR if the transaction which this IDBCursor belongs to has its mode set to READ_ONLY. If this cursor's got value flag is false, or if this cursor was created using openKeyCursor a NOT_ALLOWED_ERR is thrown.

Otherwise this method runs the steps for asynchronously executing a request and returns the IDBRequest created by these steps. The steps are run with this IDBCursor as source and the steps for deleting a record from an object store as operation, using this cursor's effective object store and effective key as store and key respectively.

This method used to set this cursor's value to null. Do we want to keep that?

No parameters.
Exception Description
IDBDatabaseException
TRANSACTION_INACTIVE_ERR The transaction this IDBCursor belongs to is not active.
READ_ONLY_ERR The mode of the transaction this IDBCursor belongs to is READ_ONLY.
NOT_ALLOWED_ERR The cursor was created using openKeyCursor or the cursor is currently being iterated or has iterated past the end.
Return type: IDBRequest
update

This method throws a READ_ONLY_ERR if the transaction which this IDBCursor belongs to has its mode set to READ_ONLY. If this cursor's got value flag is false or if this cursor was created using openKeyCursor. This method throws a NOT_ALLOWED_ERR. If the effective object store of this cursor uses in-line keys and evaluating the key path of the value parameter results in a different value than the cursor's effective key, this method throws DATA_ERR.

Otherwise this method creates a structured clone of the value parameter. If this throws an exception that exception is rethrown. It then runs the steps for asynchronously executing a request and returns the IDBRequest created by these steps. The steps are run with this IDBCursor as source and the steps for storing a record into an object store as operation, using this cursor's effective object store as store, the created clone as value, this cursor's effective key as key, and with the no-overwrite flag flag set to false.

A result of running the steps for storing a record into an object store is that if the record has been deleted since the cursor moved to it, a new record will be created.

Parameter Type Nullable Optional Description
value any The new value to store at the current position.
Exception Description
IDBDatabaseException
TRANSACTION_INACTIVE_ERR The transaction this IDBCursor belongs to is not active.
READ_ONLY_ERR The mode of the transaction this IDBCursor belongs to is READ_ONLY
NOT_ALLOWED_ERR Thrown if cursor was created using openKeyCursor or if the cursor is currently being iterated or has iterated past the end.
DATA_ERR The underlying object store uses in-line keys and the property in value at the object store's key path does not match the key in this cursor's position.
DOMException
DATA_CLONE_ERR The data being stored could not be cloned by the internal structured cloning algorithm.
Return type: IDBRequest
Constants
NEXT of type unsigned short
indicates that this cursor should yield all records, including duplicates and its direction is monotonically increasing order of keys.
NEXT_NO_DUPLICATE of type unsigned short
indicates that this cursor should yield all records, not including duplicates and its direction is monotonically increasing order of keys. For every key with duplicate values, only the first record is yielded.
PREV of type unsigned short
indicates that cursor should yield all records, including duplicates and its direction is monotonically decreasing order of keys.
PREV_NO_DUPLICATE of type unsigned short
indicates that this cursor should yield all records, not including duplicates and its direction is monotonically decreasing order of keys. For every key with duplicate values, only the first record is yielded.
interface IDBCursorWithValue : IDBCursor {
    readonly attribute any value;
};
Attributes
value of type any, readonly
Returns the cursor's current value. However if the cursor's got value flag is false it returns undefined. I.e. if it's currently being iterated or has iterated past the end of its range. Note that if this property returns an object, it returns the same object instance every time it is inspected, until the cursor is iterated. This means that if the object is modified, those modifications will be seen by anyone inspecting the value of the cursor. However modifying such an object does not modify the contents of the database.
No exceptions.

3.2.8 Transaction

Transaction objects implement the following interface:

interface IDBTransaction : EventTarget {
    const unsigned short READ_ONLY = 0;
    const unsigned short READ_WRITE = 1;
    const unsigned short VERSION_CHANGE = 2;
    readonly attribute unsigned short mode;
    readonly attribute IDBDatabase    db;
    IDBObjectStore objectStore (in DOMString name) raises (IDBDatabaseException);
    void           abort () raises (IDBDatabaseException);
             attribute Function       onabort;
             attribute Function       oncomplete;
             attribute Function       onerror;
};
Attributes
db of type IDBDatabase, readonly
The database connection of which this transaction is a part
No exceptions.
mode of type unsigned short, readonly
On getting, provide the mode for isolating access to data inside the object stores that are in the scope of the transaction.
No exceptions.
onabort of type Function
The event handler for the abort event.
No exceptions.
oncomplete of type Function
The event handler for the complete event.
No exceptions.
onerror of type Function
The event handler for the error event.
No exceptions.
Methods
abort
If this transaction is finished, throw a NOT_ALLOWED_ERR exception. Otherwise this method aborts the transaction by running the steps for aborting a transaction with code set to ABORT_ERR.
No parameters.
Exception Description
IDBDatabaseException
NOT_ALLOWED_ERR If this transaction has already been committed or aborted.
Return type: void
objectStore
Returns a IDBObjectStore representing a object store that is part of the to the scope of this transaction. Every call to this function on the same IDBTransaction instance and with the same name returns the same IDBObjectStore instance. However the returned IDBObjectStore instance is specific to this IDBTransaction. If this function is called on a different IDBTransaction, a different IDBObjectStore instance is returned.
Parameter Type Nullable Optional Description
name DOMString The requested object store
Exception Description
IDBDatabaseException
NOT_FOUND_ERR If the requested object store is not in this transaction's scope.
Return type: IDBObjectStore
Constants
READ_ONLY of type unsigned short
Modification operations are not allowed in the transaction in this mode.
READ_WRITE of type unsigned short
Modification operations are allowed in the transactions in this mode.
VERSION_CHANGE of type unsigned short
This mode is used solely for updating the version number of transactions started using the setVersion() method of IDBDatabase.

3.3 Synchronous APIs

The synchronous database API methods provide a blocking access pattern to IndexedDB databases. Since they block the calling thread they are only available from workers.

3.3.1 Opening a database

WorkerUtils objects must implement the IDBEnvironmentSync interface.

WorkerUtils implements IDBEnvironmentSync;
[NoInterfaceObject]
interface IDBEnvironmentSync {
    readonly attribute IDBFactorySync indexedDBSync;
};
Attributes
indexedDBSync of type IDBFactorySync, readonly
This attribute provides applications a mechanism for accessing capabilities of indexed databases.
No exceptions.
interface IDBFactorySync {
    IDBDatabaseSync open (in DOMString name);
    void            deleteDatabase (in DOMString name);
};
Methods
deleteDatabase

When invoked, this method synchronously runs the steps for deleting a database. Let origin be the origin of the IDBEnvironmentSync used to access this IDBFactorySync and name be the name argument passed to this function.

If an error is returned from the steps above, then the implementation must throw an IDBDatabaseException with its code and message set to appropriate values for the error.

Parameter Type Nullable Optional Description
name DOMString The name of the database to be deleted.
No exceptions.
Return type: void
open

When invoked, this method synchronously runs the steps for opening a database. Let origin be the origin of the IDBEnvironmentSync used to access this IDBFactorySync and name be the name argument passed to this function.

If an error is returned from the steps above, then the implementation must throw an IDBDatabaseException with its code and message set to appropriate values for the error.

If the steps above are successful, the implementation must create a IDBDatabaseSync object representing the created connection and return it.

Parameter Type Nullable Optional Description
name DOMString The name for the database
No exceptions.
Return type: IDBDatabaseSync

3.3.2 Database

A database object provides access to the schema and data of a particular database.

interface IDBDatabaseSync {
    readonly attribute DOMString     name;
    readonly attribute DOMString     version;
    readonly attribute DOMStringList objectStoreNames;
    IDBObjectStoreSync createObjectStore (in DOMString name, in optional Object optionalParameters) raises (IDBDatabaseException);
    void               deleteObjectStore (in DOMString name) raises (IDBDatabaseException);
    IDBTransactionSync setVersion ([TreatNullAs=EmptyString] in DOMString version);
    void               transaction (in any storeNames, in IDBTransactionCallback callback, in optional unsigned short mode, in optional unsigned long timeout) raises (IDBDatabaseException);
    void               close ();
};
Attributes
name of type DOMString, readonly
On getting, this attribute must return the name of the connected database. The function must return this name even if the closePending flag is set on the connection. In other words, the return value from this function stays constant for the lifetime of the IDBDatabaseSync instance.
No exceptions.
objectStoreNames of type DOMStringList, readonly
On getting, this attribute must return a list of names of the object stores currently in the connected database. Once the closePending flag is set on the connection, this function must return a snapshot of the list of names of the object stores taken at the time when the close method was called. Even if other connections are later used to change the set of object stores that exist in the database. In other words, the return value from this function stays constant for the lifetime of the IDBDatabaseSync instance, unless setVersion and createObjectStore or deleteObjectStore is called on this IDBDatabaseSync instance itself.
No exceptions.
version of type DOMString, readonly
On getting, this attribute must return the version of this database. This attribute has the empty string value when the connected database is first created. Once the closePending flag is set on the connection, this function must return a snapshot of the version taken when the close method was called. Even if other connections are later used to change the version of the database. In other words, the return value from this function stays constant for the lifetime of the IDBDatabaseSync instance, unless setVersion is called on this IDBDatabaseSync instance itself.
No exceptions.
Methods
close
This method synchronously performs the steps for closing a database connection and returns once the database has been closed.
No parameters.
No exceptions.
Return type: void
createObjectStore

This method creates a and returns a new object store with the given name in the connected database. This method should only be called from inside a VERSION_CHANGE transaction.

If the optionalParameters argument is specified and has a keyPath property which is not undefined or null, then set keyPath to the value of this property. If keyPath is an Array, then each item in the array is converted to a string. If keyPath is not an Array, it is converted to a string.

If keyPath is an Array and any items in the array is not a valid key path, or if keyPath is a string and is not a valid key path then a NON_TRANSIENT_ERR error must be thrown. Otherwise set the created object store's key path is set to the value of keyPath.

Parameter Type Nullable Optional Description
name DOMString The name of a new object store
optionalParameters Object The options object whose attributes are optional parameters to this function. Valid attributes are keyPath and autoIncrement. keyPath specifies the key path of the new object store. If the attribute is null, undefined, the empty string, or not present, no key path is specified and thus keys are out-of-line. autoIncrement specifies whether the object store created should have a key generator. It defaults to false.
Exception Description
IDBDatabaseException
NOT_ALLOWED_ERR This method was not called from a VERSION_CHANGE transaction.
CONSTRAINT_ERR If an object store with the same name, compared in a case-sensitive manner, already exists in the connected database.
NON_TRANSIENT_ERR optionalParameters has attributes other than keyPath and autoIncrement.
Return type: IDBObjectStoreSync
deleteObjectStore

This method destroys an object store with the given name as well as all indexes that are referencing that object store. This method should only be called from inside a VERSION_CHANGE transaction.

Parameter Type Nullable Optional Description
name DOMString The name of an existing object store
Exception Description
IDBDatabaseException
NOT_ALLOWED_ERR This method was not called from a VERSION_CHANGE transaction callback.
NOT_FOUND_ERR If the object store with the given name, compared in a case-sensitive manner, does not already exist in the connected database.
Return type: void
setVersion
This method updates the version of the database by following the steps for running a VERSION_CHANGE transaction using the version argument as version and the IDBDatabaseSync this function was called on as connection. It returns the transaction object that should be used to perform the changes to the database required for the new version.

Processing a setVersion call may take a long time as it requires all other connections to the database to be closed, which in turn may depend on user input or other long-running tasks. If blocking for a long period of time is not acceptable for a given scenario then the asynchronous API should be used for version changes.

Parameter Type Nullable Optional Description
version DOMString The version to store in the database
No exceptions.
Return type: IDBTransactionSync
transaction

This method, when called must execute the steps for creating a transaction in a sychronous fashion. The storeNames, callback, mode, and timeout arguments are forwarded to the algorithm as-is. The connection argument is set to the IDBDatabaseSync that the transaction() method was called on.

The method returns a IDBTransactionSync object representing the transaction returned by the steps above.

Parameter Type Nullable Optional Description
storeNames any The names of object stores and indexes in the scope of the new transaction
callback IDBTransactionCallback A callback which will be called with the newly created transaction. When the callback returns, the transaction is committed.
mode unsigned short The mode for isolating access to data inside the given object stores. If this parameter is not provided, the default access mode is READ_ONLY.
timeout unsigned long The interval in milliseconds which this operation is allowed to take to reserve all the database objects identified in the new transaction's scope. The default is user agent specific
Exception Description
IDBDatabaseException
TIMEOUT_ERR If starting the transaction takes longer than the specified timeout.
NOT_ALLOWED_ERR The close() method has been called on this IDBDatabase instance.
NOT_FOUND_ERR One of the names provided in the storeNames argument doesn't exist in this database.
Return type: void
[NoInterfaceObject, Callback=FunctionOnly]
interface IDBTransactionCallback {
    void handleEvent (in IDBTransactionSync transaction);
};
Methods
handleEvent

The transaction that was just started.

Parameter Type Nullable Optional Description
transaction IDBTransactionSync
No exceptions.
Return type: void

3.3.3 Object Store

Example

In the following example, we set up an object store to use the key path id. This object store is also designed to use a key generator.

ECMAScript
var db = indexedDBSync.open('AddressBook');
if (db.version !== '1') {
    var vtx = db.setVersion('1');
    vtx.createObjectStore('Contact', 'id', true);
}
            

The scenario above doesn't actually work well because you have to unwind to the event loop to get the version transaction to commit before you can do something else. Leaving it like this for now, as this will get sorted out when we add callbacks for transactions in the sync API (we'll have to do it for the setVersion transaction as well).

Using this database, we can store records in the Contact object store.

ECMAScript
var tx = db.transaction();
var store = tx.objectStore('Contact');
var contact = store.add({name: 'Lincoln', number: '7012'});
// contact.id === 1
            

A stored value can be retrieved using the same key used by the first put operation.

ECMAScript
var contact = store.get(1);
// contact.name === 'Lincoln'

A put operation will overwrite the record stored by the first add operation with the same key.

ECMAScript
var abraham = {id: 1, name: 'Abraham', number: '2107'};
store.put(abraham);

Now when the object store is read with the same key, the result is different compared to the object read earlier.

ECMAScript
var contact = store.get(1);
// contact.id === 1 && contact.name === 'Abraham';

Additionally, all the records of an object store matching a certain key range can be retrieved in key order.

ECMAScript
var range = new IDBKeyRange.bound(2, 4);
var cursor = store.openCursor(range);
// each value is a contact and each key is the id for that  
// contact whose id is between 2 and 4, both inclusive
cursor.continue();
interface IDBObjectStoreSync {
    readonly attribute DOMString          name;
    readonly attribute DOMString          keyPath;
    readonly attribute DOMStringList      indexNames;
    readonly attribute IDBTransactionSync transaction;
    any                    put (in any value, in optional any key) raises (IDBDatabaseException, DOMException);
    any                    add (in any value, in optional any key) raises (IDBDatabaseException, DOMException);
    void                   delete (in any key) raises (IDBDatabaseException);
    any                    get (in any key) raises (IDBDatabaseException);
    void                   clear () raises (IDBDatabaseException);
    IDBIndexSync           createIndex (in DOMString name, in DOMString keyPath, in optional Object optionalParameters) raises (IDBDatabaseException);
    IDBIndexSync           index (in DOMString name) raises (IDBDatabaseException);
    void                   deleteIndex (in DOMString indexName) raises (IDBDatabaseException);
    IDBCursorWithValueSync openCursor (in optional any range, in optional unsigned short direction) raises (IDBDatabaseException);
};
Attributes
indexNames of type DOMStringList, readonly
On getting, provide a list of the names of indexes on objects in this object store.
No exceptions.
keyPath of type DOMString, readonly
On getting, provide the key path of this object store. If this attribute is null, the application must provide a key value for each modification operation.
No exceptions.
name of type DOMString, readonly
On getting, provide the name of this object store.
No exceptions.
transaction of type IDBTransactionSync, readonly
On getting, returns the transaction this object store belongs to.
No exceptions.
Methods
add

This method throws a READ_ONLY_ERR if the transaction which this IDBObjectStoreSync belongs to is has its mode set to READ_ONLY. If any of the following conditions are true, this method throws a DATA_ERR exception:

Otherwise this method creates a structured clone of the value parameter. If this throws an exception that exception is rethrown. It then runs the steps for synchronously executing a request and returns the key of the stored object. The steps are run with this IDBObjectStoreSync as source and the steps for storing a record into an object store as operation, using this IDBObjectStoreSync as store, the created clone as value, the key parameter as key, and with the no-overwrite flag flag set to true.

Parameter Type Nullable Optional Description
value any The value to be stored in the record
key any The key used to identify the record
Exception Description
IDBDatabaseException
TRANSACTION_INACTIVE_ERR The transaction this IDBObjectStoreSync belongs to is not active.
READ_ONLY_ERR The mode of the associated transaction is READ_ONLY.
DATA_ERR The calculated key for the insertion was not a valid key. Also thrown if the calculated key for any of the indexes which belong to this object store had a calculated key which was not a valid key
CONSTRAINT_ERR A record exists in this object store for the key key parameter, or another record in this object store has the same value for the keyPath of a unique index.
DOMException
DATA_CLONE_ERR The data being stored could not be cloned by the internal structured cloning algorithm.
Return type: any
clear

This method throws a READ_ONLY_ERR if the transaction which this IDBObjectStoreSync belongs to is has its mode set to READ_ONLY.

Otherwise this method runs the steps for synchronously executing a request. The steps are run with this IDBObjectStoreSync as source and the steps for clearing an object store as operation, using this IDBObjectStoreSync as store.

No parameters.
Exception Description
IDBDatabaseException
TRANSACTION_INACTIVE_ERR The transaction this IDBObjectStoreSync belongs to is not active.
READ_ONLY_ERR The mode of the transaction this IDBObjectStoreSync belongs to is READ_ONLY.
Return type: void
createIndex

This creates and returns a new index with the given name and parameters in the connected database. Note that this method must only be called from a VERSION_CHANGE transaction. The created index has its unique and multirow flags are set to the values of the unique and multirow properties in the optionalParameters argument.

If the keyPath argument is an Array, then each item in the array is converted to a string. If keyPath is not an Array, it is converted to a string.

If keyPath is an Array and any items in the array is not a valid key path, or if keyPath is a string and is not a valid key path, or if keyPath is and Array and the multirow property in the optionalParameters is true, then a NON_TRANSIENT_ERR error must be thrown. Otherwise set the created object store's key path is set to the value of keyPath.

Parameter Type Nullable Optional Description
name DOMString The name of a new index
keyPath DOMString The key path used by the new index
optionalParameters Object The options object whose attributes are optional parameters to this function. The valid options are unique and multirow. unique specifies whether the index's unique flag is set. It defaults to false. multirow specifies whether the index's multirow flag is set. It defaults to false.
Exception Description
IDBDatabaseException
NOT_ALLOWED_ERR This method was not called from a VERSION_CHANGE transaction.
CONSTRAINT_ERR An index with the same name, compared in a case-sensitive manner, already exists in the connected database. Also thrown when creating a unique index on top of an object store that already contains records that violate the unique constraint.
NON_TRANSIENT_ERR optionalParameters has attributes other than unique.
Return type: IDBIndexSync
delete

This method throws a READ_ONLY_ERR if the transaction which this IDBObjectStoreSync belongs to is has its mode set to READ_ONLY. If the key parameter is not a valid key this method throws a DATA_ERR exception.

Otherwise this method runs the steps for synchronously executing a request. The steps are run with this IDBObjectStoreSync as source and the steps for deleting a record from an object store as operation, using this IDBObjectStoreSync as store and the key parameter as key.

Parameter Type Nullable Optional Description
key any Key identifying the record to be deleted
Exception Description
IDBDatabaseException
TRANSACTION_INACTIVE_ERR The transaction this IDBObjectStoreSync belongs to is not active.
READ_ONLY_ERR The mode of the transaction this IDBObjectStoreSync belongs to is READ_ONLY.
NOT_FOUND_ERR A record did not exist in this object store for the key key parameter.
Return type: void
deleteIndex

This method destroys the index with the given name in the connected database. Note that this method must only be called from a VERSION_CHANGE transaction.

Parameter Type Nullable Optional Description
indexName DOMString The name of an existing index
Exception Description
IDBDatabaseException
NOT_FOUND_ERR If the index with the given name does not exist in the connected database.
NOT_ALLOWED_ERR This method was not called from a VERSION_CHANGE transaction.
Return type: void
get

If the key parameter is not a valid key or a key range, this method throws a DATA_ERR exception. Otherwise, this method runs the steps for synchronously executing a request and returns the result of the operation. The steps are run with this IDBObjectStoreSync as source and the steps for retrieving a value from an object store as operation, using this IDBObjectStoreSync as store and the key parameter as key.

This function produces the same result if a record with the given key doesn't exist as when a record exists, but has undefined as value. If you need to tell the two situations apart, you can use openCursor with the same key. This will return a cursor with undefined as value if a record exists, or no cursor if no such record exists.

Parameter Type Nullable Optional Description
key any Key identifying the record to be retrieved. This can also be a IDBKeyRange in which case the function retrieves the first existing value in that range.
Exception Description
IDBDatabaseException
TRANSACTION_INACTIVE_ERR The transaction this IDBObjectStoreSync belongs to is not active.
DATA_ERR The key parameter was not passed a valid value.
Return type: any
index
Returns a IDBIndexSync representing a index that is part of the to this object store. Every call to this function on the same IDBObjectStoreSync instance and with the same name returns the same IDBIndexSync instance. However the retured IDBIndexSync instance is specific to this IDBObjectStoreSync instance. If this function is called on a different IDBObjectStoreSync instance, a different IDBIndexSync instance is returned. A result of this is that different IDBTransactionSyncs use different IDBIndexSync instances to represent the same index.
Parameter Type Nullable Optional Description
name DOMString The name of an existing index
Exception Description
IDBDatabaseException
NOT_FOUND_ERR If the index with the given name does not exist in the connected database.
Return type: IDBIndexSync
openCursor

If the range parameter is specified but is not a valid key or a key range, this method throws a DATA_ERR exception. Otherwise, this method creates a cursor. The cursor must implement the IDBCursorWithValueSync interface.

The newly created cursor must have an undefined position, a direction set to the value of the direction parameter, false as iterable flag value, and undefined key and value. The source of the cursor is the IDBObjectStoreSync this function was called on.

If the range parameter is a key range then the cursor's range is set to that range. Otherwise, if the range parameter is a valid key then the cursor's range is set to key range containing only that key value. If the range parameter is not specified, the cursor's key range is left as undefined.

This method runs the steps for synchronously executing a request and returns the result of the operation, in this case an IDBCursorSync object. The steps are run with this IDBObjectStoreSync as source and the steps for iterating a cursor as operation, using the created cursor as cursor and with undefined as key.

Parameter Type Nullable Optional Description
range any The key range to use as the cursor's range
direction unsigned short The cursor's required direction
Exception Description
IDBDatabaseException
TRANSACTION_INACTIVE_ERR The transaction this IDBObjectStoreSync belongs to is not active.
DATA_ERR The range parameter was not passed key range or a valid key.
put

This method throws a READ_ONLY_ERR if the transaction which this IDBObjectStoreSync belongs to has its mode set to READ_ONLY. If any of the following conditions are true, this method throws a DATA_ERR exception:

Otherwise this method creates a structured clone of the value parameter. If this throws an exception that exception is rethrown. It then runs the steps for synchronously executing a request and returns the result, in this case the key of the stored object. The steps are run with this IDBObjectStoreSync as source and the steps for storing a record into an object store as operation, using this IDBObjectStoreSync as store, the created clone as value, the key parameter as key, and with the no-overwrite flag flag set to false.

Parameter Type Nullable Optional Description
value any The value to be stored in the record
key any The key used to identify the record
Exception Description
IDBDatabaseException
TRANSACTION_INACTIVE_ERR The transaction this IDBObjectStoreSync belongs to is not active.
READ_ONLY_ERR The mode of the associated transaction is READ_ONLY.
DATA_ERR The calculated key for the insertion was not a valid key. Also thrown if the calculated key for any of the indexes which belong to this object store had a calculated key which was not a valid key
CONSTRAINT_ERR Another record in this object store has the same value for the keyPath of a unique index.
DOMException
DATA_CLONE_ERR The data being stored could not be cloned by the internal structured cloning algorithm.
Return type: any

3.3.4 Index

Example

An index can be created for retrieving records other than by using record keys. Continuing the earlier example, an index could be maintained on the name property of objects in the Contact object store.

ECMAScript
var db = indexedDBSync.open('AddressBook');
if (db.version === '1') {
    var vtx = db.setVersion('2');
    var store = vtx.objectStore('Contact');
    store.createIndex('ContactName', 'name', false);
}

The scenario above doesn't actually work well because you have to unwind to the event loop to get the version transaction to commit before you can do something else. Leaving it like this for now, as this will get sorted out when we add callbacks for transactions in the sync API (we'll have to do it for the setVersion transaction as well).

For example, the id of an object with the name property value 'Lincoln' can be retrieved using the ContactName index.

ECMAScript
var index = store.openIndex('ContactName');
var id = index.get('Lincoln');
// id === 1

Additionally, all the records of an object store matching a certain range index keys can be retrieved in key order. When objects are retrieved from the Contact object store, they are arranged by the value of the id attribute. On the other hand, when objects are retrieved using the ContactName index, they are arranged by the value of the name property.

ECMAScript
var range = new IDBKeyRange.bound('L', 'M');
var cursor = index.openCursor(range);
// each value is a contact and each key is the name for that  
// contact whose name's first letter is either L or M
cursor.continue();

If, on the other hand, we only want the names and keys but not the whole Contact objects for a given range, then we can use a different mechanism for that.

ECMAScript
var range = new IDBKeyRange.bound('L', 'M');
var cursor = index.openKeyCursor(range);
// each value is a contact id and each key is the name for that  
// contact whose name's first letter is either L or M
cursor.continue();
interface IDBIndexSync {
    readonly attribute DOMString          name;
    readonly attribute IDBObjectStoreSync objectStore;
    readonly attribute DOMString          keyPath;
    readonly attribute boolean            unique;
    IDBCursorWithValueSync openCursor (in optional IDBKeyRange range, in optional unsigned short direction) raises (IDBDatabaseException);
    IDBCursorSync          openKeyCursor (in optional IDBKeyRange range, in optional unsigned short direction) raises (IDBDatabaseException);
    any                    get (in any key) raises (IDBDatabaseException);
    any                    getKey (in any key) raises (IDBDatabaseException);
};
Attributes
keyPath of type DOMString, readonly
On getting, provide the key path of this index. If this attribute is null, this index is not auto-populated.
No exceptions.
name of type DOMString, readonly
On getting, provide the name of this index.
No exceptions.
objectStore of type IDBObjectStoreSync, readonly
On getting, returns a reference to the IDBObjectStoreSync instance for the referenced object store in this IDBIndexSync's transaction. This must return the same IDBObjectStoreSync instance as was used to get a reference to this IDBIndexSync.
No exceptions.
unique of type boolean, readonly
On getting, provide the unique flag of this index.
No exceptions.
Methods
get

If the key parameter is not a valid key or a key range, this method throws a DATA_ERR exception. This method runs the steps for synchronously executing a request and returns the result from that, in this case an object from the underlying store. The steps are run with this IDBIndexSync as source and the steps for retrieving a referenced value from an index as operation, using this IDBIndexSync as index and the key parameter as key.

This function produces the same result if a record with the given key doesn't exist as when a record exists, but has undefined as value. If you need to tell the two situations apart, you can use openCursor with the same key. This will return a cursor with undefined as value if a record exists, or no cursor if no such record exists.

Parameter Type Nullable Optional Description
key any Key identifying the record to be retrieved. This can also be a IDBKeyRange in which case the function retreives the first existing value in that range.
Exception Description
IDBDatabaseException
TRANSACTION_INACTIVE_ERR The transaction this IDBIndexSync belongs to is not active.
DATA_ERR The key parameter was not passed a valid value.
Return type: any
getKey

If the key parameter is not a valid key or a key range, this method throws a DATA_ERR exception. This method runs the steps for synchronously executing a request and returns the result from that, in this case an index value (a key). The steps are run with the IDBObjectStoreSync associated with this index as source and the steps for retrieving a value from an index as operation, using this IDBIndexSync as index and the key parameter as key.

This function produces the same result if a record with the given key doesn't exist as when a record exists, but has undefined as value. If you need to tell the two situations apart, you can use openCursor with the same key. This will return a cursor with undefined as value if a record exists, or no cursor if no such record exists.

Parameter Type Nullable Optional Description
key any Key identifying the record to be retrieved. This can also be a IDBKeyRange in which case the function retreives the first existing value in that range.
Exception Description
IDBDatabaseException
TRANSACTION_INACTIVE_ERR The transaction this IDBIndexSync belongs to is not active.
DATA_ERR The key parameter was not passed a valid value.
Return type: any
openCursor

If the range parameter is specified but is not a valid key or a key range, this method throws a DATA_ERR exception. Otherwise, this method creates a cursor. The cursor must implement the IDBCursorWithValueSync interface.

The newly created cursor must have an undefined position, a direction set to the value of the direction parameter, false as iterable flag value, and undefined key and value. The source of the cursor is the IDBIndexSync this function was called on.

If the range parameter is a key range then the cursor's range is set to that range. Otherwise, if the range parameter is a valid key then the cursor's range is set to key range containing only that key value. If the range parameter is not specified, the cursor's key range is left as undefined.

This method runs the steps for synchronously executing a request and returns the result, in this case a cursor object. The steps are run with this IDBIndexSync as source and the steps for iterating a cursor as operation, using the created cursor as cursor and with undefined as key

Parameter Type Nullable Optional Description
range IDBKeyRange The key range to use as the cursor's range
direction unsigned short The cursor's required direction
Exception Description
IDBDatabaseException
TRANSACTION_INACTIVE_ERR The transaction this IDBIndexSync belongs to is not active.
DATA_ERR The range parameter was not passed a valid value.
openKeyCursor

If the range parameter is specified but is not a valid key or a key range, this method throws a DATA_ERR exception. Otherwise, this method creates a cursor. The cursor must implement the IDBCursorSync interface and must not implement the IDBCursorWithValueSync interface.

The newly created cursor must have an undefined position, a direction set to the value of the direction parameter, false as iterable flag value, and undefined key and value. The source of the cursor is the IDBIndexSync this function was called on.

If the range parameter is a key range then the cursor's range is set to that range. Otherwise, if the range parameter is a valid key then the cursor's range is set to key range containing only that key value. If the range parameter is not specified, the cursor's key range is left as undefined.

This method runs the steps for synchronously executing a request and returns the result, in this case a cursor object. The steps are run with this IDBIndexSync as source and the steps for iterating a cursor as operation, using the created cursor as cursor and with undefined as key

Parameter Type Nullable Optional Description
range IDBKeyRange The key range to use as the cursor's range
direction unsigned short The cursor's required direction
Exception Description
IDBDatabaseException
TRANSACTION_INACTIVE_ERR The transaction this IDBIndexSync belongs to is not active.
DATA_ERR The range parameter was not passed key range or a valid key.
Return type: IDBCursorSync

3.3.5 Cursor

Using the synchronous API, an application can process all the records in the cursor's range.

Example

By default, a cursor walks over objects starting at the first record and ending at the last record including all the duplicates encountered along the way.

ECMAScript
var tx = db.transaction('Contact');
var store = tx.objectStore('Contact');
var cursor = store.openCursor();
while(cursor.continue()) {
    var value = cursor.value;
    // act on each object or key
}

To start at the last record and end in the first record, the cursor should be created with the direction parameter PREV.

ECMAScript
var cursor = store.openCursor(IDBCursorSync.PREV);
while(cursor.continue()) {
    // act on each object or key
}

To start at a certain key and end in the last record, i.e., for a lower-bounded cursor, while skipping duplicates, the cursor should be created with both the required start key and the direction parameter.

ECMAScript
var range = IDBKeyRange.leftBound(key);
var cursor = store.openCursor(range, IDBCursorSync.NEXT_NO_DUPLICATE);

It is also possible to create a bounded cursor, i.e., with application-specified starting and ending points, the cursor should be created with both the required keys. If the range is inclusive of both keys, then additional flags are required. In the following example, all keys with values in the inclusive range (start, end) are returned with all their duplicates, from the beginning of the range to its end.

ECMAScript
var range = IDBKeyRange.bound(start, end);
var cursor = objects.openCursor(range);
interface IDBCursorSync {
    const unsigned short NEXT = 0;
    const unsigned short NEXT_NO_DUPLICATE = 1;
    const unsigned short PREV = 2;
    const unsigned short PREV_NO_DUPLICATE = 3;
    readonly attribute Object         source;
    readonly attribute unsigned short direction;
    readonly attribute any            key;
    IDBRequest update (in any value) raises (IDBDatabaseException, DOMException);
    void       advance (in int count);
    boolean    continue (in optional any key) raises (IDBDatabaseException);
    void       delete () raises (IDBDatabaseException);
};
Attributes
direction of type unsigned short, readonly
On getting, provide the traversal direction of the cursor.
No exceptions.
key of type any, readonly
The key for the record at the cursor's position. However if the cursor's got value flag is false it returns undefined. I.e. if it's currently being iterated or has iterated past the end of its range.
No exceptions.
source of type Object, readonly
On getting, returns the IDBObjectStoreSync or IDBIndexSync which this cursor is iterating. This function never returns null or throws an exception, even if the is currently being iterated, has iterated past its end, or its transaction is not active.
No exceptions.
Methods
advance

This method runs the steps for synchronously executing a request. The steps are run with the cursor's source as source. The operation runs the steps for iterating a cursor count number of times with null as key and this cursor as cursor.

Parameter Type Nullable Optional Description
count int The number of advances forward the cursor should make.
No exceptions.
Return type: void
continue

If this cursor's got value flag is false, this method throws a NOT_ALLOWED_ERR. If the key parameter is specified and fulfills any of these conditions this method must throw a DATA_ERR exception:

Otherwise this method runs the steps for synchronously executing a request. The steps are run with the cursor's source as source and the steps for iterating a cursor as operation, using the cursor this is called on as cursor and the key parameter as key.

Before this method returns, unless an exception was thrown, it sets the got value flag in the cursor to false.

Parameter Type Nullable Optional Description
key any The next key to position this cursor at
Exception Description
IDBDatabaseException
TRANSACTION_INACTIVE_ERR The transaction this IDBCursor belongs to is not active.
NOT_ALLOWED_ERR The cursor has iterated past its end.
DATA_ERR The key parameter was specified but did not contain a valid key.
Return type: boolean
delete

This method throws a READ_ONLY_ERR if the transaction which this IDBCursorSync belongs to has its mode set to READ_ONLY. If this cursor's got value flag is false, or if this cursor was created using openKeyCursor a NOT_ALLOWED_ERR is thrown.

Otherwise this method runs the steps for synchronously executing a request. The steps are run with this IDBCursorSync as source and the steps for deleting a record from an object store as operation, using this cursor's effective object store and effective key as store and key respectively.

This method used to set this cursor's value to null. Do we want to keep that?

No parameters.
Exception Description
IDBDatabaseException
TRANSACTION_INACTIVE_ERR The transaction this IDBCursorSync belongs to is not active.
READ_ONLY_ERR The mode of the transaction this IDBCursorSync belongs to is READ_ONLY.
NOT_ALLOWED_ERR The cursor was created using openKeyCursor or the cursor is currently being iterated or has iterated past the end.
Return type: void
update

This method throws a READ_ONLY_ERR if the transaction which this IDBCursorSync belongs to has its mode set to READ_ONLY. If this cursor's got value flag is false or if this cursor was created using openKeyCursor. This method throws a NOT_ALLOWED_ERR. If the effective object store of this cursor uses in-line keys and evaluating the key path of the value parameter results in a different value than the cursor's effective key, this method throws DATA_ERR.

Otherwise this method creates a structured clone of the value parameter. If this throws an exception that exception is rethrown. It then runs the steps for synchronously executing a request and returns the result returned by these steps. The steps are run with this IDBCursorSync as source and the steps for storing a record into an object store as operation, using this cursor's effective object store as store, the created clone as value, this cursor's effective key as key, and with the no-overwrite flag flag set to false.

A result of running the steps for storing a record into an object store is that if the record has been deleted since the cursor moved to it, a new record will be created.

Parameter Type Nullable Optional Description
value any The new value to store at the current position.
Exception Description
IDBDatabaseException
TRANSACTION_INACTIVE_ERR The transaction this IDBCursor belongs to is not active.
READ_ONLY_ERR The mode of the transaction this IDBCursor belongs to is READ_ONLY
NOT_ALLOWED_ERR Thrown if cursor was created using openKeyCursor or if the cursor is currently being iterated or has iterated past the end.
DATA_ERR The underlying object store uses in-line keys and the property in value at the object store's key path does not match the key in this cursor's position.
DOMException
DATA_CLONE_ERR The data being stored could not be cloned by the internal structured cloning algorithm.
Return type: IDBRequest
Constants
NEXT of type unsigned short
indicates that this cursor should yield all records, including duplicates and its direction is monotonically increasing order of keys.
NEXT_NO_DUPLICATE of type unsigned short
indicates that this cursor should yield all records, not including duplicates and its direction is monotonically increasing order of keys. For every key with duplicate values, only the first record is yielded.
PREV of type unsigned short
indicates that cursor should yield all records, including duplicates and its direction is monotonically decreasing order of keys.
PREV_NO_DUPLICATE of type unsigned short
indicates that this cursor should yield all records, not including duplicates and its direction is monotonically decreasing order of keys. For every key with duplicate values, only the first record is yielded.
interface IDBCursorWithValueSync : IDBCursorSync {
    attribute any value;
};
Attributes
value of type any
The value for the record at the cursor's position. However if the cursor's got value flag is false it returns undefined. I.e. if it's currently being iterated or has iterated past the end of its range. Note that if this property returns an object, it returns the same object instance every time it is inspected, until the cursor is iterated. This means that if the object is modified, those modifications will be seen by anyone inspecting the value of the cursor. However modifying such an object does not modify the contents of the database.
No exceptions.

3.3.6 Transaction

When an application creates a transaction synchronously, it blocks until the user agent is able to reserve the required database objects.

interface IDBTransactionSync {
    const unsigned short READ_ONLY = 0;
    const unsigned short READ_WRITE = 1;
    const unsigned short VERSION_CHANGE = 2;
    readonly attribute unsigned short  mode;
             attribute IDBDatabaseSync db;
    IDBObjectStoreSync objectStore (in DOMString name) raises (IDBDatabaseException);
    void               abort () raises (IDBDatabaseException);
};
Attributes
db of type IDBDatabaseSync
The database connection of which this transaction is a part
No exceptions.
mode of type unsigned short, readonly
On getting, provide the mode for isolating access to data inside the object stores that are in the scope of the transaction.
No exceptions.
Methods
abort
If this transaction is finished, throw a NOT_ALLOWED_ERR exception. Otherwise this method aborts the transaction by running the steps for aborting a transaction with code set to ABORT_ERR.
No parameters.
Exception Description
IDBDatabaseException
NOT_ALLOWED_ERR If this transaction has already been committed or aborted.
Return type: void
objectStore
Returns a IDBObjectStoreSync representing a object store that is part of the to the scope of this transaction. Every call to this function on the same IDBTransactionSync instance and with the same name returns the same IDBObjectStoreSync instance. However the retured IDBObjectStoreSync instance is specific to this IDBTransactionSync. If this function is called on a different IDBTransactionSync, a different IDBObjectStoreSync instance is returned.
Parameter Type Nullable Optional Description
nameDOMString The requested object store
Exception Description
IDBDatabaseException
NOT_FOUND_ERR If the requested object store is not in this transaction's scope.
Return type: IDBObjectStoreSync
Constants
READ_ONLY of type unsigned short
Modification operations are not allowed in the transaction in this mode.
READ_WRITE of type unsigned short
Modification operations are allowed in the transactions in this mode.
VERSION_CHANGE of type unsigned short
This mode is used solely for updating the version number of transactions started using the setVersion() method of IDBDatabaseSync.
Applications must not assume that committing the transaction produces an instantaneously durable result. The user agent may delay flushing data to durable storage until an appropriate time.

Once a transaction is aborted or committed, the active transaction on this database connection is removed. A new transaction can be created to perform operations atomically.

4. Algorithms

4.1 Opening the database

The steps for opening a database are as follows. The algorithm in these steps take two arguments. A origin which requested the database to be opened, a database name. It also optionally takes a request which represents a request used when opening the database is done using an asynchronous API.

  1. If these steps fail for any reason, return a error with the appropriate code and abort this algorithm.
  2. If there is already a database with the given name from the origin origin, then let db be that database.
  3. If db was found in the previous step, wait until no already existing connections to db, have non-finished VERSION_CHANGE transactions. If db has its delete pending flag set, wait until db has been deleted.

    There can potentially be several connections waiting for a VERSION_CHANGE transaction to finish. Once that transaction finishes another connection could be created and a new VERSION_CHANGE transaction could be started before these steps has a chance to continue. In that case the implementation must keep waiting at this step. Similarly, at any point while waiting for VERSION_CHANTE transactions to finish, the delete pending flag could be set. In that case the implementation must keep waiting at this step until db has been deleted.

  4. If no database with the given name from the origin origin was found, or if it was deleted during the previous step, then create a database with name name, with the empty string as version, and with no object stores. Let db be the new database.
  5. Create a connection to db and return it.

4.2 Transaction Creation steps

When the user agent is to create a transaction it must run the following steps. This algorithm takes five parameters: A connection, a mode, a list of storeNames of object stores to be included in the scope of the transaction, a timeout for the transaction starting, and a callbacks parameter for synchronously created transactions.

  1. If these steps are already running synchronously (a transaction was created within a transaction callback), throw a NOT_ALLOWED_ERR.

    This should be specified more precisely. Maybe with some sort of global variable locked?

  2. If storeNames is of type DOMStringList or Array leave it as is. Otherwise, interpret it as an Array with one value, and that value is the stringified version of storeNames. If any of the strings in storeNames identifies an object store which doesn't exist, throw a NOT_FOUND_ERR exception.
  3. If the closePending flag is set on connection the throw a NOT_ALLOWED_ERR.
  4. Create a transaction using connection as connection, mode as mode, and the object stores identified in storeNames as scope.
  5. If these steps are running asynchronously, return the created transaction and run the remaining steps asynchronously. When control is returned to the event loop, the implementation must set the active flag to false.
  6. Wait until the transaction can be started according to the transaction lifetime rules. If this takes longer than the specified timeout then a TIMEOUT_ERR exception error should be thrown.

    Because the asynchronous API always passes in a timeout of infinite, only the synchronous API will ever time out.

  7. If these steps are running synchronously, the implementation must synchronously call callback with a single parameter which is the transaction. If an exception is thrown and not caught within the scope of the callback, the implementation must abort the transaction by following the steps for aborting a transaction, abort this algorithm without taking any further steps, and re-throw the exception.
  8. If these steps are running synchronously, the implementation must commit the transaction synchrnously.

4.3 Steps for committing a transaction

When taking the steps for committing a transaction the implementation must execute the following algorithm. This algorithm takes one parameter, the transaction to commit.

  1. All the changes made to the database the transaction uses are written to the database.
  2. Asynchronously dispatch an event at transaction. The event must use the Event interface and have its type set to "commit". The event does not bubble and is not cancelable. The propagation path for the event is transaction's connection and then transaction.

4.4 Steps for aborting a transaction

When taking the steps for aborting a transaction the implementation must execute the following algorithm. This algorithm takes two parameter, the transaction to abort and a code.

  1. All the changes made to the database the transaction uses are reverted. For VERSION_CHANGE transactions this includes changes to the set of object stores and indexes, as well as the change to the version.
  2. If the transaction's request list contain any requests whose done flag is still false, abort the steps for asynchronously executing a request for each such transaction and queue a task to perform the following steps:
    1. Set the done flag on the request to true, set result of the request to undefined and set errorCode of the request to ABORT_ERR.
    2. Fire an error event at the request.
  3. Asynchronously dispatch an event at transaction. The event must use the Event interface and have its type set to "abort". The event does bubble but is not cancelable. The propagation path for the event is transaction's connection and then transaction.

4.5 Steps for asynchronously executing a request

When taking the steps for asynchronously executing a request the implementation must run the following algorithm. The algorithm takes a source object and a operation to perform on a database.

These steps can be aborted at any point if the transaction the created request belongs to is aborted using the steps for aborting a transaction

  1. Set transaction to the transaction associated with source.
  2. If transaction is not active throw a TRANSACTION_INACTIVE_ERR exception.
  3. Create a IDBRequest object and set request to this object. Set request's source to source and add request to the end of the list of requests in transaction. Return this object and run the remaining steps in this algorithm asynchronously.

    Cursors override this step to reuse an existing IDBRequest. However they still put the IDBRequest at the end of the list of requests in transaction.

  4. Wait until all previously added requests in transaction have their done flag set to true.
  5. Perform operation.
  6. If performing operation succeeded then set the done flag on the request to true, set result of the request to the result of the request and set errorCode of the request to NO_ERR. Finally fire a success event at request.
  7. If performing operation failed then revert all changes made by operation, set the done flag on the request to true, set result of the request to undefined and set errorCode of the request to the code of the error from operation. Finally fire an error event at request.
    This only reverts the changes done by this request, not any other changes made by the transaction.

4.6 Steps for synchronously executing a request

When taking the steps for synchronously executing a request the implementation must run the following algorithm. The algorithm takes a source object and a operation to perform on a database.

  1. If the transaction associated with source is not active throw a TRANSACTION_INACTIVE_ERR exception.
  2. Perform operation.
  3. If performing operation succeeded then return the result of the operation.
  4. If performing operation failed then throw a IDBDatabaseException with the code of the error from operation.

4.7 Steps for extracting a key from a value using a key path

When taking the steps for extracting a key from a value using a key path, the implementation must run the following algorithm. The algorithm takes a key path named keyPath and a value named value and in some cases returns a key which may or may not be a valid key.

  1. If keyPath is the empty string, return value and skip the remaining steps.
  2. Let remainingKeypath be keyPath and object be value.
  3. If remainingKeypath has a period in it, assign remainingKeypath to be everything after the first period and assign attribute to be everything before that first period. Otherwise, assignattribute to be remainingKeypath and assign remainingKeypath to be null.
  4. If object does not have an attribute named attribute, then skip the rest of these steps and no value is returned.
  5. Assign object to be the value of the attribute named attribute on object.
  6. If remainingKeypath is not null, go to step 3.
  7. Return object.

4.8 VERSION_CHANGE transaction steps

The steps for running a VERSION_CHANGE transaction are as follows. This algorithm takes two parameters - a connection object which is used to update the database and a new version number to be set for the database.

  1. Create a new transaction with mode set to VERSION_CHANGE and connection used as connection. The scope of the transaction includes every object store in connection. Set its active flag to false.
  2. If running asynchronously, create a new request which uses the IDBVersionChangeRequest interface, return it, and run the remaining steps in this algorithm asynchronously.
  3. Let openDatabases be the set of all IDBDatabase and IDBDatabaseSync objects, except connection, connected to the same database as connection.
  4. Fire a versionchange event at each object in openDatabases that is open. The event must not be fired on objects which has the closePending flag set. The event must use the IDBVersionChangeEvent interface and have the version property set to version number. This event must not bubble or be cancelable. The propagation path for the event is just the IDBDatabase object itself.

    Firing this event might cause one or more of the other objects in openDatabases to be closed, in which case the versionchange event must not be fired at those objects if that hasn't yet been done.

  5. If running asynchronously and any of the connections in openDatabases are still not closed, fire a blocked event at request. The event must use the IDBVersionChangeEvent interface and have the version property set to version number. This event must not bubble or be cancelable. The propagation path for the event is just request.

  6. Wait until either all objects in openDatabases are closed and all of their transactions are finished or connection has its closePending flag set to true.

    If .close() is called immediately but a transaction associated with the connection keeps running for a "long time", should we also fire a blocked event?

  7. If connection has its closePending flag set to true, abort the transaction by following the steps for aborting a transaction and abort this algorithm without taking any further steps.
  8. Start the transaction that will be used during the version change. Note that until this transaction is finished, no other connections can be opened to the same database.
  9. Set the version of database to the given version number. This change is considered part of the transaction, and so if the transaction is aborted, this change is reverted.
  10. If running asynchronously, fire a success event targeted at the request object. The result propety of the event should be set to a new IDBTransaction object representing the VERSION_CHANGE transaction created in step 4. If running synchronously, return the IDBTransactionSync created in step 4 to the caller.
  11. Follow the normal steps for executing a transaction and let the transaction finish normally.

4.9 Database closing steps

The steps for closing a database connection are as follows. These steps take one argument, a connection object.

  1. Set the internal closePending flag of connection to true.
  2. Wait for all transactions created using connection to complete. Once they are complete, connection is closed.

Once the closePending flag has ben set to true no new transactions can be created using connection. All functions that create transactions first check the the closePending flag first and throw an exception if it is true.

Once the connection is closed, this can unblock the steps for running a VERSION_CHANGE transaction, and the steps for deleting a database, which both wait for connections to a given database to be closed before continuing.

4.10 Database deletion steps

The steps for deleting a database are as follows. The algorithm in these steps take three arguments. A origin which requested the database to be deleted, a database name. It also optionally takes a request which represents a request used when deleting the database is done using an asynchronous API.

  1. If there is already a database with the given name from the origin origin, then let db be that database.
  2. If no database was found, then these steps are considered successful. Abort these steps.
  3. Set db's delete pending flag to true.
  4. Let openDatabases be the set of all IDBDatabase and IDBDatabaseSync objects connected to db.
  5. Fire a versionchange event at each object in openDatabases that is open. The event must not be fired on objects which has the closePending flag set. The event must use the IDBVersionChangeEvent interface and have the version property set to null. This event must not bubble or be cancelable.

    Firing this event might cause one or more of the other objects in openDatabases to be closed, in which case the versionchange event must not be fired at those objects if that hasn't yet been done.

  6. If any of the connections in openDatabases are still not closed, and request was provided, fire a blocked event at request. The event must use the IDBVersionChangeEvent interface and have the version property set to null. This event must not bubble or be cancelable.

  7. Wait until all objects in openDatabases are closed and all of their transactions are finished.

    Should we allow blocked to be fired here too, if waiting takes "too long"?

  8. Delete db.

4.11 Fire a success event

To fire a success event at a request, the implementation must run the following steps:

  1. Set transaction to the transaction associated with the source.
  2. Set the active flag of transaction to true.
  3. Dispatch an event at request. The event must use the Event interface and have its type set to "success". The event does not bubble or be cancelable. The propagation path for the event is transaction's connection, then transaction and finally request. However if transaction is null, then the propagation path is simply request.
  4. Set the active flag of transaction to false.
  5. If an exception was propagated out from any event handler while dispatching the event in step 3, abort the transaction by following the steps for aborting a transaction.

4.12 Fire an error event

To fire a error event at a request, the implementation must run the following steps:

  1. Set transaction to the transaction associated with the source.
  2. Set the active flag of transaction to true.
  3. Dispatch an event at request. The event must use the Event interface and have its type set to "error". The event does bubble and is cancelable. The propagation path for the event is transaction's connection, then transaction and finally request. The event's default action is to abort the transaction by running steps for aborting a transaction. However if transaction is null, then the propagation path is simply request, there is no default action and is not cancelable.
  4. Set the active flag of transaction to false.
  5. If an exception was propagated out from any event handler while dispatching the event in step 3, abort the transaction by following the steps for aborting a transaction.

TODO: need to define more error handling here.

5. Database operations

This section describes various operations done on the data in object stores and indexes in a database. These operations are run by the steps for asynchronously executing a request and the steps for synchronously executing a request.

5.1 Object Store Storage Operation

The steps for storing a record into an object store are as follows. The algorithm run by these steps takes four parameters: a object store store, a value, an optional key, and a no-overwrite flag.

  1. If store does use in-line keys and evaluting store's key path on value does yield a value, then set key to that result.
  2. If store uses a key generator and key is undefined, set key to the next generated key. If store also uses in-line keys, then set the property in value pointed to by store's key path to the new value for key.
  3. If store uses a key generator, this key generator was not used to generate a value for key in the previous step, key is defined to a long or a float and this number is larger than, or equal to, the next key that store's key generator would generate, change store's key generator such that the next key it generates is the lowest integer larger than key.
  4. If the no-overwrite flag was passed to these steps and is set, and a record already exists in store with its key equal to key, then terminate these steps and set error code to CONSTRAINT_ERR and abort this algorithm without taking any further steps.
  5. If a record already exists in store with its key equal to key, then remove the record from store using the steps for deleting a record from an object store.
  6. Store a record in store containing key as its key and object as its value. The record is stored in the the object store's list such that the list is sorted according key of the records in ascending order.
  7. If there are any indexes which reference store, perform the following sub steps on each such index.
    1. Set index to the index.
    2. If index's key path is a string, then evaluate it on value. If this does not yield a value don't take any further actions for this index. Otherwise set the result to index key.
    3. If index's key path is an Array, then set index key to a newly created empty Array. For each item in index's key path evaluate the item on value. If this does not yield a value don't take any further actions for this index. Otherwise add the value to the end of the index key Array.
    4. The places invoking these steps ensures that index key is always a valid key by the time we get to this step.
    5. If index's multirow flag is false, or if index key is not an Array, and if index already contains a record with key equal to index key, and index has it's unique flag set to true, then set error code to CONSTRAINT_ERR and abort this algorithm without taking any further steps.
    6. If index's multirow flag is true and index key is an Array, and if index already contains a record with key equal to any of the values in index key, and index has it's unique flag set to true, then set error code to CONSTRAINT_ERR and abort this algorithm without taking any further steps.
    7. If index's multirow flag is false, or if index key is not an Array, then store a record in index containig index key as its key and key as its value. The record is stored in index's list of records such that the list is sorted primarily on the records keys, and secondarily on the records values, in ascending order.
    8. If index's multirow flag is true and index key is an Array, then for each item in index key store a record in index containig the items value as its key and key as its value. The records are stored in index's list of records such that the list is sorted primarily on the records keys, and secondarily on the records values, in ascending order.
      Note that it is legal for the Array to have length 0, in this case no records are added to the index.
      If any of the items in the Array are themselves an Array, then the inner Array is used as a key for that entry. In other words, Arrays are not recursively "unpacked" to produce multiple rows. Only the outer-most Array is.
  8. The result of this algorithm is key.

5.2 Object Store Retrieval Operation

The steps for retrieving a value from an object store are as follows. These steps must be run with two parameters - the record key and the object store.

  1. Let key be the key and store be the object store passed to these steps.
  2. If key is not a key range then retreive the record with key key from store. If key is a key range, then retreive the first record from store whose key is in key.
  3. If no record was found, the result of this algorithm is undefined.
  4. The result of this algorithm is a new structured clone of the value in the found record.

5.3 Index Referenced Value Retrieval Operation

The steps for retrieving a referenced value from an index are as follows. These steps must be run with two parameters - the record key and the index.

  1. Let key be the key and index be the index passed to these steps.
  2. If key is not a key range then find the first record with key key from index. If key is a key range, then find the first record from index whose key is in key.
  3. If no record was found, the result of this algorithm is undefined.
  4. Otherwise, the result of the operation is a structured clone of the referenced value of the found record.

5.4 Index Value Retrieval Operation

The steps for retrieving a value from an index are as follows. These steps must be run with two parameters - the record key and the index.

  1. Let key be the key and index be the index passed to these steps.
  2. If key is not a key range then find the first record with key key from index. If key is a key range, then find the first record from index whose key is in key.
  3. If no record was found, the result of this algorithm is undefined.
  4. If a record was found, the result of this algorithm is the value of the found record.

5.5 Object Store Deletion Operation

The steps for deleting a record from an object store are as follows. The algorithm run by these steps takes two parameters: a object store store and a key.

  1. If no record exists with key key in store, then the result of this algorithm is false and no more steps in this algorithm are executed.
  2. Remove the record from store with key key.
  3. In all indexes which reference store, remove all records with value key.
  4. The result of this algorithm is true.

5.6 Object Store Clear Operation

The steps for clearing an object store are as follows. The algorithm run by these steps takes one parameter: a object store store.

  1. Remove all records from store.
  2. In all indexes which reference store, remove all records.
  3. The result of this algorithm is undefined.

5.7 Cursor Iteration Operation

The steps for iterating a cursor are as follows. The algorithm run by these steps takes two parameters: a cursor and optional key to iterate to.

  1. Let source be cursor's source, let records be list of records in source, let direction be cursor's direction, let position be cursor's position, let object store position be cursor's object store position and let range be cursor's range.

    source is always a object store or a index.

    records is always sorted in ascending key order. In the case of source being an index, records is secondarily sorted in ascending value order.

  2. If direction is NEXT, let found record be the first record in records which satisfy all of the following requirements:

    If direction is NEXT_NO_DUPLICATE, let found record be the first record in records which satisfy all of the following requirements:

    • If key is defined, the record's key is greater than or equal to key.
    • If position is defined, the record's key is greater than position.
    • If range is defined, the record's key is in range.

    If direction is PREV, let found record be the last record in records which satisfy all of the following requirements:

    • If key is defined, the record's key is less than or equal to key.
    • If position is defined, and source is a object store, the record's key is less than position.
    • If position is defined, and source is an index, the record's key is equal to position and the record's value is less than object store position or the record's key is less than position.
    • If range is defined, the record's key is in range.

    If direction is PREV_NO_DUPLICATE, let temp record be the last record in records which satisfy all of the following requirements:

    • If key is defined, the record's key is less than or equal to key.
    • If position is defined, the record's key is less than position.
    • If range is defined, the record's key is in range.

    If temp record is defined, let found record be the first record in records whose key is equal to temp record's key.

  3. If found record is not defined, the result of this algorithm is undefined. Abort these steps.
  4. Set cursor's position to found record's key. If source is a index, set cursor's object store position to found record's value.

  5. Set cursor's key to found record's key.

    If cursor implements IDBCursorWithValue or IDBCursorWithValueSync, then set cursor's value to a structured clone of found record referenced value.

  6. Set cursor's got value flag to true.

    This should only be done right before firing the success event. Not asynchronously before. Not sure how/where to express that.

  7. The result of the algorithm is cursor.

6. Privacy

6.1 User tracking

A third-party host (or any object capable of getting content distributed to multiple sites) could use a unique identifier stored in its client-side database to track a user across multiple sessions, building a profile of the user's activities. In conjunction with a site that is aware of the user's real id object (for example an e-commerce site that requires authenticated credentials), this could allow oppressive groups to target individuals with greater accuracy than in a world with purely anonymous Web usage.

There are a number of techniques that can be used to mitigate the risk of user tracking:

Blocking third-party storage
User agents may restrict access to the database objects to scripts originating at the domain of the top-level document of the browsing context, for instance denying access to the API for pages from other domains running in iframes.
Expiring stored data

User agents may automatically delete stored data after a period of time.

This can restrict the ability of a site to track a user, as the site would then only be able to track the user across multiple sessions when he authenticates with the site itself (e.g. by making a purchase or logging in to a service).

However, this also puts the user's data at risk.

Treating persistent storage as cookies

User agents should present the database feature to the user in a way that associates them strongly with HTTP session cookies. [COOKIES]

This might encourage users to view such storage with healthy suspicion.

Site-specific white-listing of access to databases

User agents may require the user to authorize access to databases before a site can use the feature.

Origin-tracking of stored data

User agents may record the origins of sites that contained content from third-party origins that caused data to be stored.

If this information is then used to present the view of data currently in persistent storage, it would allow the user to make informed decisions about which parts of the persistent storage to prune. Combined with a blacklist ("delete this data and prevent this domain from ever storing data again"), the user can restrict the use of persistent storage to sites that he trusts.

Shared blacklists

User agents may allow users to share their persistent storage domain blacklists.

This would allow communities to act together to protect their privacy.

While these suggestions prevent trivial use of this API for user tracking, they do not block it altogether. Within a single domain, a site can continue to track the user during a session, and can then pass all this information to the third party along with any identifying information (names, credit card numbers, addresses) obtained by the site. If a third party cooperates with multiple sites to obtain such information, a profile can still be created.

However, user tracking is to some extent possible even with no cooperation from the user agent whatsoever, for instance by using session identifiers in URLs, a technique already commonly used for innocuous purposes but easily repurposed for user tracking (even retroactively). This information can then be shared with other sites, using using visitors' IP addresses and other user-specific data (e.g. user-agent headers and configuration settings) to combine separate sessions into coherent user profiles.

6.3 Sensitivity of data

User agents should treat persistently stored data as potentially sensitive; it's quite possible for e-mails, calendar appointments, health records, or other confidential documents to be stored in this mechanism.

To this end, user agents should ensure that when deleting data, it is promptly deleted from the underlying storage.

7. Authorization

7.1 DNS spoofing attacks

Because of the potential for DNS spoofing attacks, one cannot guarantee that a host claiming to be in a certain domain really is from that domain. To mitigate this, pages can use SSL. Pages using SSL can be sure that only pages using SSL that have certificates identifying them as being from the same domain can access their databases.

7.2 Cross-directory attacks

Different authors sharing one host name, for example users hosting content on geocities.com, all share one set of databases.

There is no feature to restrict the access by pathname. Authors on shared hosts are therefore recommended to avoid using these features, as it would be trivial for other authors to read the data and overwrite it.

Even if a path-restriction feature was made available, the usual DOM scripting security model would make it trivial to bypass this protection and access the data from any path.

7.3 Implementation risks

The two primary risks when implementing these persistent storage features are letting hostile sites read information from other domains, and letting hostile sites write information that is then read from other domains.

Letting third-party sites read data that is not supposed to be read from their domain causes information leakage, For example, a user's shopping wish list on one domain could be used by another domain for targeted advertising; or a user's work-in-progress confidential documents stored by a word-processing site could be examined by the site of a competing company.

Letting third-party sites write data to the persistent storage of other domains can result in information spoofing, which is equally dangerous. For example, a hostile site could add records to a user's wish list; or a hostile site could set a user's session identifier to a known ID that the hostile site can then use to track the user's actions on the victim site.

Thus, strictly following the origin model described in this specification is important for user security.

A. Requirements

Requirements will be written with an aim to verify that these were actually met by the API specified in this document.

B. Acknowledgements

The editor of this specification was employed by Oracle Corp during its early drafts.
Garret Swart was extremely influential in the design of this specification. Feedback from Margo Seltzer, Jonas Sicking, Arun Ranganathan, Shawn Wilsher, Pablo Castro, Kris Zyp, Chris Anderson, and Dana Florescu have led to improvements to this specification over time.

C. References

C.1 Normative references

[COOKIES]
Adam Barth. HTTP State Management Mechanism. IETF, November 2009
[DOM-LEVEL-3-EVENTS]
Björn Höhrmann; Tom Pixley; Philippe Le Hégaret. Document Object Model (DOM) Level 3 Events Specification. 21 December 2007. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2007/WD-DOM-Level-3-Events-20071221
[ECMA-262]
ECMAScript Language Specification, Third Edition. December 1999. URL: http://www.ecma-international.org/publications/standards/Ecma-262.htm
[HTML5]
Ian Hickson; David Hyatt. HTML 5. 4 March 2010. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2010/WD-html5-20100304/
[RFC2119]
S. Bradner. Key words for use in RFCs to Indicate Requirement Levels. March 1997. Internet RFC 2119. URL: http://www.ietf.org/rfc/rfc2119.txt
[WEBIDL]
Cameron McCormack. Web IDL. 19 December 2008. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2008/WD-WebIDL-20081219
[WEBWORKERS]
Ian Hickson. Web Workers. 22 December 2009. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2009/WD-workers-20091222/

C.2 Informative references

[WEBSTORAGE]
Ian Hickson. Web Storage. 10 September 2009. W3C Working Draft. (Work in progress.) URL: http://www.w3.org/TR/2009/WD-webstorage-20090910/