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 DocumentThis 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 is the W3C Recommendation for the Indexed Database API. Changes to this specification since the previous publication are summarized and enumerated in this document's Revision History appendix.
This specification's bugs and issues are managed in Bugzilla (new bug, open bugs). Feature requests for the next version of this specification are kept in the Indexed Database Features document.
This document was published by the Web Applications Working Group as a Recommendation. If you wish to make comments regarding this document, please send them to public-webapps@w3.org (subscribe, archives). All comments are welcome.
Please see the Working Group's implementation report.
By publishing this Proposed Recommendation, W3C expects that the functionality specified in this Proposed Recommendation will not be affected by changes to DOM Level 3 Events, DOM4, Web IDL or Web Workers as those specifications proceed to Recommendation.
This document has been reviewed by W3C Members, by software developers, and by other W3C groups and interested parties, and is endorsed by the Director as a W3C Recommendation. It is a stable document and may be used as reference material or cited from another document. W3C's role in making the Recommendation is to draw attention to the specification and to promote its widespread deployment. This enhances the functionality and interoperability of the Web.
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.
This document is governed by the 14 October 2005 W3C Process Document.
Table of Contents 1. IntroductionThis 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.
Example 1
In the following example, the API is used to access a "library" database that holds books stored by their "isbn" attribute. Additionally, an index is maintained on the "title" attribute of the objects stored in the object store. This index can be used to look up books by title, and enforces a uniqueness constraint. Another index is maintained on the "author" attribute of the objects, and can be used to look up books by author.
A connection to the database is opened. If the "library" database did not already exist, it is created and an event handler creates the object store and indexes. Finally, the opened connection is saved for use in subsequent examples.
Example
var request = indexedDB.open("library"); request.onupgradeneeded = function() { // The database did not previously exist, so create object stores and indexes. var db = request.result; var store = db.createObjectStore("books", {keyPath: "isbn"}); var titleIndex = store.createIndex("by_title", "title", {unique: true}); var authorIndex = store.createIndex("by_author", "author"); // Populate with initial data. store.put({title: "Quarry Memories", author: "Fred", isbn: 123456}); store.put({title: "Water Buffaloes", author: "Fred", isbn: 234567}); store.put({title: "Bedrock Nights", author: "Barney", isbn: 345678}); }; request.onsuccess = function() { db = request.result; };
The following example populates the database using a transaction.
Example
var tx = db.transaction("books", "readwrite"); var store = tx.objectStore("books"); store.put({title: "Quarry Memories", author: "Fred", isbn: 123456}); store.put({title: "Water Buffaloes", author: "Fred", isbn: 234567}); store.put({title: "Bedrock Nights", author: "Barney", isbn: 345678}); tx.oncomplete = function() { // All requests have succeeded and the transaction has committed. };
The following example looks up a single book in the database by title using an index.
Example
var tx = db.transaction("books", "readonly"); var store = tx.objectStore("books"); var index = store.index("by_title"); var request = index.get("Bedrock Nights"); request.onsuccess = function() { var matching = request.result; if (matching !== undefined) { // A match was found. report(matching.isbn, matching.title, matching.author); } else { // No match was found. report(null); } };
The following example looks up all books in the database by author using an index and a cursor.
Example
var tx = db.transaction("books", "readonly"); var store = tx.objectStore("books"); var index = store.index("by_author"); var request = index.openCursor(IDBKeyRange.only("Fred")); request.onsuccess = function() { var cursor = request.result; if (cursor) { // Called for each matching record. report(cursor.value.isbn, cursor.value.title, cursor.value.author); cursor.continue(); } else { // No more matching records. report(null); } };
The following example shows how errors could be handled when a request fails.
Example
var tx = db.transaction("books", "readwrite"); var store = tx.objectStore("books"); var request = store.put({title: "Water Buffaloes", author: "Slate", isbn: 987654}); request.onerror = function() { // The uniqueness constraint of the "by_title" index failed. report(request.error); // Could call request.preventDefault() to prevent the transaction from aborting. }; tx.onabort = function() { // Otherwise the transaction will automatically abort due the failed request. report(tx.error); };
The database connection may be closed when it is no longer needed.
In the future, the database may have grown to contain other object stores and indexes. The following example shows one way to handle opening an older version of the database.
Example
var request = indexedDB.open("library", 3); // Request version 3. request.onupgradeneeded = function(event) { var db = request.result; if (event.oldVersion < 1) { // Version 1 is the first version of the database. var store = db.createObjectStore("books", {keyPath: "isbn"}); var titleIndex = store.createIndex("by_title", "title", {unique: true}); var authorIndex = store.createIndex("by_author", "author"); } if (event.oldVersion < 2) { // Version 2 introduces a new index of books by year. var bookStore = request.transaction.objectStore("books"); var yearIndex = bookStore.createIndex("by_year", "year"); } if (event.oldVersion < 3) { // Version 3 introduces a new object store for magazines with two indexes. var magazines = db.createObjectStore("magazines"); var publisherIndex = magazines.createIndex("by_publisher", "publisher"); var frequencyIndex = magazines.createIndex("by_frequency", "frequency"); } }; request.onsuccess = function() { db = request.result; // db.version will be 3. };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 MAY, MUST, and MUST NOT are to be interpreted as described in [RFC2119].
This specification defines one class of products:
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]
Note
This specification uses both the terms "conforming user agent(s)" and "user agent(s)" to refer to this product class.
This specification relies on several other underlying specifications.
DOMException
and Event
are defined by the W3C DOM4 Specification [DOM4].
Function
, origin, same origin, structured clone, structured clone algorithm, task, task source, and queue a task are defined by the HTML 5 specification [HTML5].
Worker
and WorkerUtils
are defined by the WebWorkers specification [WEBWORKERS].
A database's origin is the same as the origin of the document or worker. Each origin has an associated set of databases.
Note
The database origin is not affected by changes to document.domain
.
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 0.
Note
Implementations MUST support all names. If an 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.
Note
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 "versionchange"
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
interface represents a connection to a database.
An object store is the primary storage mechanism for storing data in a database.
Each database has a set of object stores. The set of object stores can be changed, but can only be changed using a "versionchange"
transaction, i.e. in response to a upgradeneeded
event. When a new database is created it doesn't contain any object stores.
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:
The IDBObjectStore
interface represents an object store. Note however that multiple instances of those interfaces representing the same object store can exist.
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 ECMAScript [ECMA-262] types: Number
primitive value, String
primitive value, Date
object, or Array
object. An Array
is only a valid key if every item in the array is defined and is a valid key (i.e. sparse arrays can not be valid keys) and if the Array
doesn't directly or indirectly contain itself. Any non-numeric properties on an Array
are ignored, and thus do not affect whether the Array
is a valid key. If the value is of type Number
, it is only a valid key if it is not NaN
. If the value is of type Date
it is only a valid key if its [[PrimitiveValue]]
internal property, as defined by [ECMA-262], is not NaN
. Conforming user agents MUST support all valid keys as keys.
Note
Infinite Number
values are valid keys. As are empty Array
s.
Operations that accept keys MUST perform as if each key parameter value, in order, is copied by the structured clone algorithm [HTML5] and the copy is instead used as input to the operation, before proceding with rest of the operation.
Note
This implicit copying step ensures that key values do not change after the operation begins, due to side effects such as ECMAScript [ECMA-262] getters, setters and type conversion functions including toString()
and valueOf()
.
For purposes of comparison, all Array
s are greater than all String
, Date
and Number
values; all String
values are greater than all Date
and Number
values; and all Date
values are greater than all Number
values. Values of type Number
are compared to other Number
values numerically. Values of type Date
are compared to other Date
values chronologically. Values of type String
are compared to other values of type String
by using the algorithm defined by step 4 of section 11.8.5, The Abstract Relational Comparison Algorithm, of the ECMAScript Language Specification [ECMA-262]. Values of type Array
are compared to other values of type Array
as follows:
Array
value and B be the second Array
value.Note
Note that Array
s that contain other Array
s are allowed as valid keys. In this case the algorithm above runs recursively when comparing the individual values in the arrays.
Note
As a result of the above rules, negative infinity is the lowest possible value for a key. There is no highest possible key value. This is because an Array
of any candidate highest key followed by another valid key is even higher.
The terms greater than, less than and equal to are defined in the terms of the above comparisons.
The following examples illustrate the different behaviors when trying to use in-line keys and key generators to save an object to an object store.
Example 2
If the following conditions are true:
Then the value provided by the key generator is used to populate the key value. In the example below the key path for the object store is "foo.bar"
. The actual object has no value for the bar
property, { foo: {} }
. When the object is saved in the object store the bar
property is assigned a value of 4 because that is the next key generated by the object store.
Example
"foo.bar" { foo: {} }
If the following conditions are true:
Then the value associated with the key path property is used. The auto-generated key is not used. In the example below the key path for the object store is "foo.bar"
. The actual object has a value of 10 for the bar
property, { foo: { bar: 10} }
. When the object is saved in the object store the bar
property keeps its value of 10, because that is the key value.
Example
"foo.bar" { foo: { bar: 10 } }
The following example illustrates the scenario when the specified in-line key is defined through a key path but there is no property matching it. The value provided by the key generator is then used to populate the key value and the system is responsible for creating as many properties as it requires to suffice the property dependencies on the hierarchy chain. In the example below the key path for the object store is "foo.bar.baz"
. The actual object has no value for the foo
property, { zip: {} }
. When the object is saved in the object store the foo
, bar
, and baz
properties are created each as a child of the other until a value for foo.bar.baz
can be assigned. The value for foo.bar.baz
is the next key generated by the object store.
Example
"foo.bar.baz" { zip: {} }
Attempting to store a property on a primitive value will fail and throw an error. In the first example below the key path for the object store is "foo"
. The actual object is a primitive with the value, 4
. Trying to define a property on that primitive value fails. The same is true for arrays. Properties are not allowed on an array. In the second example below, the actual object is an array, [10]
. Trying to define a property on the array fails.
Example
// The key generation will attempt to create and store the key path property on this primitive. "foo" 4 // The key generation will attempt to create and store the key path property on this array. "foo" [10]3.1.4 Values
Each record is associated with a value. Conforming user agents MUST support any ECMAScript [ECMA-262] value supported by the structured clone algorithm [HTML5]. This includes simple types such as String
primitive values and Date
objects as well as Object
and Array
instances, File
objects, Blob
objects, ImageData
objects, and so on. Record values are stored and retrieved by value rather than by reference; later changes to a value have no effect on the record stored in the database.
A key path is a DOMString
or sequence<DOMString>
that defines how to extract a key from a value. A valid key path is one of:
DOMString
.DOMString
matching the IdentifierName
production from the ECMAScript Language Specification [ECMA-262].DOMString
consisting of two or more identifiers separated by periods (ASCII character code 46).sequence<DOMString>
containing only DOMString
s conforming to the above requirements.Note
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.
Key path values can only be accessed from properties explicitly copied by the structured clone algorithm, as well as the following properties:
Blob.size
Blob.type
File.name
File.lastModifiedDate
Array.length
String.length
It is sometimes useful to retrieve records in an object store through other means than their key. An index allows looking up records in an 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.
Example 3
For example, if an index's referenced object store contains a record with the key123
and the value { first: "Alice", last: "Smith" }
, and the index's key path is "first"
then the index would contain a record with the key "Alice"
and the value 123
.
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.
Example 4
In the preceding example, the record in the index with key"Alice"
and value 123
would have a referenced value of { first: "Alice", last: "Smith" }
.
Note
Each record in an index references 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 record's key. However unlike object stores, a given index can contain multiple records with the same key. Such records are additionally sorted according to the index's record's value (meaning the key of the record in the referenced object store).
Every index has a name. The name is unique within index's referenced object store.
Each index also has 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.
Each index also has a multiEntry flag. This flag affects how the index behaves when the result of evaluating the index's key path yields an Array
. If the multiEntry flag is false, then a single record whose key is an Array
is added to the index. If the multiEntry 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
interface provides access to the metadata of an index. Note however that multiple instances of those interfaces representing the same index can exist.
A transaction is used to interact with the data in a database. Whenever data is read or written to the database it is done by using a transaction.
All transactions are created through a connection, which is the transaction's connection. The transaction has a mode that determines which types of interactions can be performed upon that transaction. The mode is set when the transaction is created and remains fixed for the life of the transaction. The transaction also has a scope that determines the object stores with which the transaction may interact. Transactions have an active flag, which determines if new requests can be made against the transaction. Finally, transactions also contain a request list of requests which have been made against the transaction.
Each transaction has a fixed scope, determined when the transaction is created. A transaction's scope remains fixed for the lifetime of that 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 data mutation operations.
Transactions are expected to be short lived. This is encouraged by the automatic committing functionality described below. Authors can still cause transactions to run for a long time; however, this usage pattern is not generally recommended as it can lead to a bad user experience.
The lifetime of a transaction is as follows:
IDBDatabase.transaction
. The arguments passed determine the scope of the transaction and whether the transaction is read-only. When a transaction is created its active flag is initially set to true.DOMException
of type TransactionInactiveError
.IDBRequest
. For example due to IO errors when committing the transaction, or due to running into a quota limit where the implementation can't tie exceeding the quota to a partcular request. In this case the implementation MUST run the steps for aborting a transaction using the transaction as transaction and the appropriate error type as error. For example if quota was exceeded then QuotaExceededError
should be used as error, and if an IO error happened, UnknownError
should be used as error.Transactions are opened in one of three modes. The mode determines how concurrent access to object stores in the transaction are isolated.
enum IDBTransactionMode { "readonly", "readwrite", "versionchange" };Enumeration description
readonly
A "readonly"
transaction is only allowed to read data. No modifications can be done by this type of transaction. This has the advantage that several "readonly"
transactions can run at the same time even if their scopes are overlapping, i.e. if they are using the same object stores. This type of transaction can be created any time once a database has been opened using the IDBDatabase.transaction
method. readwrite
A "readwrite"
transaction is allowed to read, modify and delete data from existing object stores. However object stores and indexes can't be added or removed. Multiple "readwrite"
transactions can't run at the same time if their scopes are overlapping since that would mean that they can modify each other's data in the middle of the transaction. This type of transaction can be created any time once a database has been opened using the IDBDatabase.transaction
method. versionchange
A "versionchange"
transaction is similar to a "readwrite"
transaction, however it can additionally create and remove object stores and indexes. It is the only type of transaction that can do so. This type of transaction can't be manually created, but instead is created automatically when a upgradeneeded
event is fired.
Any number of transactions opened in "readonly"
mode are allowed to run concurrently, even if the transaction's scope overlap and include the same object stores. As long as a "readonly"
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 ensures this. The implementation can prevent any "readwrite"
transaction, whose scope overlaps the scope of the "readonly"
transaction, from starting until the "readonly"
transaction finishes. Or the implementation can allow the "readonly"
transaction to see a snapshot of the contents of the object stores which is taken when the "readonly"
transaction started.
Similarly, implementations MUST ensure that a "readwrite"
transaction is only affected by changes to object stores that are made using the transaction itself. For example, the implementation MUST ensure that another transaction does not modify the contents of object stores in the "readwrite"
transaction's scope. The implementation MUST also ensure that if the "readwrite"
transaction completes successfully, 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.
If multiple "readwrite"
transactions are attempting to access the same object store (i.e. if they have overlapping scope), the transaction that was created first MUST be the transaction which gets access to the object store first. Due to the requirements in the previous paragraph, this also means that it is the only transaction which has access to the object store until the transaction is finished.
Any transaction created after a "readwrite"
transaction MUST see the changes written by the "readwrite"
transaction. So if a "readwrite"
transaction, A, is created, and later another transaction B, is created, and the two transactions have overlapping scopes, then B MUST see any changes made to any object stores that are part of that overlapping scope. Due to the requirements in the previous paragraph, this also means that the B transaction does not have access to any object stores in that overlapping scope until the A transaction is finished.
Note
Generally speaking, the above requirements mean that any transaction which has an overlapping scope with a "readwrite"
transaction and which was created after that "readwrite"
transaction, can't run in parallel with that "readwrite"
transaction.
A "versionchange"
transaction never run concurrently with other transactions. When a database is opened with a version number higher than the current version, a new "versionchange"
transaction is automatically created and made available through the upgradeneeded
event. The upgradeneeded
event isn't fired, and thus the "versionchange"
transaction isn't started, until all other connections to the same database are closed. This ensures that all other transactions are finished.
As long as a "versionchange"
transaction is running, attempts to open more connections to the same database are delayed, and any attempts to use the same connection to start additional transactions will result in an exception being thrown. Thus "versionchange"
transactions not only ensure that no other transactions are running concurrently, but also ensure that no other transactions are queued against the same database as long as the transaction is running.
Note
"versionchange"
transaction is automatically created when a database version number is provided that is greater than the current database version. This transaction will be active inside the upgradeneeded
event handler, allowing the creation of new object stores and indexes.
User agents MUST ensure a reasonable level of fairness across transactions to prevent starvation. For example, if multiple "readonly"
transactions are started one after another the implementation MUST NOT indefinitely prevent a pending "readwrite"
transaction from starting.
Each transaction object implement the IDBTransaction
interface.
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 error attribute, 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 the steps for asynchronously executing a request. The steps set the request transaction to be that transaction. The steps do not set the request transaction to be that request for the request returned from an IDBFactory.open
call however. That function create requests which have a null request transaction.
enum IDBRequestReadyState { "pending", "done" };Enumeration description
pending
The done flag of the request is false. done
The done flag of the request is true. 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 (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-bounded and upper-bounded. If a key range is neither lower-bounded nor upper-bounded it is said to be unbounded. A key range MAY be open (the key range does not include its endpoints) or closed (the key range includes 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; staticIDBKeyRange
only (any value); staticIDBKeyRange
lowerBound (any lower, optional boolean open = false); staticIDBKeyRange
upperBound (any upper, optional boolean open = false); staticIDBKeyRange
bound (any lower, any upper, optional boolean lowerOpen = false, optional boolean upperOpen = false); };
lower
of type any, readonly
lowerOpen
of type boolean, readonly
upper
of type any, readonly
upperOpen
of type boolean, readonly
bound
, static
If either the lower parameter or upper parameter is not 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, the implementation MUST throw a DOMException
of type DataError
.
any
✘ ✘ The lower-bound value upper any
✘ ✘ The upper-bound value lowerOpen boolean = false
✘ ✔ Set to false if the lower-bound should be included in the key range. Set to true if the lower-bound value should be excluded from the key range. Defaults to false (lower-bound value is included). upperOpen boolean = false
✘ ✔ Set to false if the upper-bound should be included in the key range. Set to true if the upper-bound value should be excluded from the key range. Defaults to false (upper-bound value is included).
lowerBound
, static
undefined
and upperOpen set to true.
If the value parameter is not a valid key, the implementation MUST throw a DOMException
of type DataError
.
any
✘ ✘ The lower bound value open boolean = false
✘ ✔ Set to false if the lower-bound should be included in the key range. Set to true if the lower-bound value should be excluded from the key range. Defaults to false (lower-bound value is included).
only
, static
If the value parameter is not a valid key, the implementation MUST throw a DOMException
of type DataError
.
any
✘ ✘ The only value
upperBound
, static
undefined
, lowerOpen set to true, upper set to upper and upperOpen set to open.
If the value parameter is not a valid key, the implementation MUST throw a DOMException
of type DataError
.
any
✘ ✘ The upper bound value open boolean = false
✘ ✔ Set to false if the upper-bound should be included in the key range. Set to true if the upper-bound value should be excluded from the key range. Defaults to false (upper-bound value is included).
A key is in a key range if both the following conditions are fulfilled:
lower
value is undefined
or less than key. It may also be equal to key if lowerOpen
is false
.upper
value is undefined
or greater than key. It may also be equal to key if upperOpen
is false
.Cursors are a transient mechanism used to iterate over multiple records in a database. 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 that indicates which index or object store is associated with the records over which the cursor is iterating. A cursor maintains a position over this series, which moves in a direction that is in 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.
There are four possible values for a cursor's direction. The direction of a cursor determines if the cursor initial position is at the start of its source or at its end. It also determines in which direction the cursor moves when iterated, and if it skips duplicated values when iterating indexes. The allowed values for a cursor's direction is as follows:
enum IDBCursorDirection { "next", "nextunique", "prev", "prevunique" };Enumeration description
next
This direction causes the cursor to be opened at the start of the source. When iterated, the cursor should yield all records, including duplicates, in monotonically increasing order of keys. nextunique
This direction causes the cursor to be opened at the start of the source. When iterated, the cursor should not yield records with the same key, but otherwise yield all records, in monotonically increasing order of keys. For every key with duplicate values, only the first record is yielded. When the source is an object store or a unique index, this direction has the exact same behavior as "next"
. prev
This direction causes the cursor to be opened at the end of the source. When iterated, the cursor should yield all records, including duplicates, in monotonically decreasing order of keys. prevunique
This direction causes the cursor to be opened at the end of the source. When iterated, the cursor should not yield records with the same key, but otherwise yield all records, in monotonically decreasing order of keys. For every key with duplicate values, only the first record is yielded. When the source is an object store or a unique index, this direction has the exact same behavior as "prev"
.
If the source of a cursor is an object store, the effective object store of the cursor is that object store and the effective key of the cursor is the cursor's position. If the source of a cursor is an index, the effective object store of the cursor is that index's referenced object store and the effective key is the cursor's 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 therefore also sorted by value. When iterating indexes the cursor also has an object store position, which indicates the value of the previously found record in the index. Both position and the object store position are used when finding the next appropriate record.
Cursor objects implement the IDBCursor
interfaces. There is only ever one IDBCursor
instance representing a given cursor. However there is no limit on how many cursors can be used at the same time.
Each of the exceptions defined in the IndexedDB spec is a DOMException
with a specific type. [DOM4] Existing DOM Level 4 exceptions will set their code to a legacy value; however, the new indexedDB type exceptions will have a code value of 0. The message value is optional.
IndexedDB uses the following new DOMException
types with their various messages. All of these new types will have a code value of 0
zero.
UnknownError
The operation failed for reasons unrelated to the database itself and not covered by any other errors. ConstraintError
A mutation operation in the transaction failed because a constraint was not satisfied. For example, an object such as an object store or index already exists and a request attempted to create a new one. DataError
Data provided to an operation does not meet requirements. TransactionInactiveError
A request was placed against a transaction which is currently not active, or which is finished. ReadOnlyError
The mutating operation was attempted in a "readonly"
transaction. VersionError
An attempt was made to open a database using a lower version than the existing version.
IndexedDB reuses the following existing DOMException types from [DOM4]. These types will continue to return the codes and names as specified in DOM4; however, they will have the following messages when thrown from an IndexedDB API:
Type Message (Optional)NotFoundError
The operation failed because the requested database object could not be found. For example, an object store did not exist but was being opened. InvalidStateError
An operation was called on an object on which it is not allowed or at a time when it is not allowed. Also occurs if a request is made on a source object that has been deleted or removed. Use TransactionInactiveError or ReadOnlyError when possible, as they are more specific variations of InvalidStateError. InvalidAccessError
An invalid operation was performed on an object. For example transaction creation attempt was made, but an empty scope was provided. AbortError
A request was aborted, for example through a call to IDBTransaction.abort
. TimeoutError
A lock for the transaction could not be obtained in a reasonable time. QuotaExceededError
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. SyntaxError
The keypath
argument contains an invalid key path. DataCloneError
The data being stored could not be cloned by the internal structured cloning algorithm. 3.1.12 Options Object
Options objects are dictionary objects [WEBIDL] 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 following WebIDL defines IDBObjectStoreParameters dictionary type.
dictionary IDBObjectStoreParameters { (DOMString or sequence<DOMString>)? keyPath = null; boolean autoIncrement = false; };
autoIncrement
of type boolean, defaulting to false
keyPath
of type (DOMString or sequence<DOMString>), nullable, defaulting to null
The following WebIDL defines IDBIndexParameters dictionary type.
dictionary IDBIndexParameters { boolean unique = false; boolean multiEntry = false; };
multiEntry
of type boolean, defaulting to false
unique
of type boolean, defaulting to false
The following WebIDL defines IDBVersionChangeEventInit dictionary type.
dictionary IDBVersionChangeEventInit : EventInit { unsigned long long oldVersion = 0; unsigned long long? newVersion = null; };
newVersion
of type unsigned long long, nullable, defaulting to null
oldVersion
of type unsigned long long, defaulting to 0
When a object store is created it can be specified to use a key generator. A key generator keeps an internal current number. The current number is always a positive integer. Whenever the key generator is used to generate a new key, the generator's current number is returned and then incremented to prepare for the next time a new key is needed. Implementations MUST use the following rules for generating numbers when a key generator is used.
1
when the object store for that key generator is first created.1
.When a record is stored and an key value is specified in the call to store the record, if the specified key value is a Number
greater than or equal to the key generator's current number, then the key generator's current number is set to the smallest integer number greater than the explicit key. A key can be specified both for object stores which use in-line keys, by setting the property on the stored value which the object store's key path points to, and for object stores which use out-of-line keys, by passing a key argument to the call to store the record.
Only specified keys values which are Number
values affect the current number of the key generator. Date
s and Array
s which contain Number
s do not affect the current number of the key generator. Nor do DOMString
values which could be parsed as numbers. Negative Number
s do not affect the current number since they are always lower than the current number.
1
when the key generator is used, and to modifications that happen due to a record being stored with a key value specified in the call to store the record.2^53
(9007199254740992
) any attempts to use the key generator to generate a new key will result in a ConstraintError
. It is still possible to insert records into the object store by specifying an explicit key, however the only way to use a key generator again for the object store is to delete the object store and create a new one.
Note
As long as key generators are used in a normal fashion this will not be a problem. If you generate a new key 1000 times per second day and night, you won't run into this limit for over 285000 years.
clear()
function, does not affect the current number of the object store's key generator.A practical result of this is that the first key generated for an object store is always 1
(unless a higher numeric key is inserted first) and the key generated for an object store is always a positive integer higher than the highest numeric key in the store. The same key is never generated twice for the same object store unless a transaction is rolled back.
Example 5
Each object store gets its own key generator:
Example
store1 = db.createObjectStore("store1", { autoIncrement: true }); store1.put("a"); // Will get key 1 store2 = db.createObjectStore("store2", { autoIncrement: true }); store2.put("a"); // Will get key 1 store1.put("b"); // Will get key 2 store2.put("b"); // Will get key 2
If an insertion fails due to constraint violations or IO error, the key generator is not updated.
Example
transaction.onerror = function(e) { e.preventDefault() }; store = db.createObjectStore("store1", { autoIncrement: true }); index = store.createIndex("index1", "ix", { unique: true }); store.put({ ix: "a"}); // Will get key 1 store.put({ ix: "a"}); // Will fail store.put({ ix: "b"}); // Will get key 2
Removing items from an objectStore never affects the key generator. Including when .clear() is called.
Example
store = db.createObjectStore("store1", { autoIncrement: true }); store.put("a"); // Will get key 1 store.delete(1); store.put("b"); // Will get key 2 store.clear(); store.put("c"); // Will get key 3 store.delete(IDBKeyRange.lowerBound(0)); store.put("d"); // Will get key 4
Inserting an item with an explicit key affects the key generator if, and only if, the key is numeric and higher than the last generated key.
Example
store = db.createObjectStore("store1", { autoIncrement: true }); store.put("a"); // Will get key 1 store.put("b", 3); // Will use key 3 store.put("c"); // Will get key 4 store.put("d", -10); // Will use key -10 store.put("e"); // Will get key 5 store.put("f", 6.00001); // Will use key 6.0001 store.put("g"); // Will get key 7 store.put("f", 8.9999); // Will use key 8.9999 store.put("g"); // Will get key 9 store.put("h", "foo"); // Will use key "foo" store.put("i"); // Will get key 10 store.put("j", [1000]); // Will use key [1000] store.put("k"); // Will get key 11 // All of these would behave the same if the objectStore used a keyPath and the explicit key was passed inline in the object
Aborting a transaction rolls back any increases to the key generator which happened during the transaction. This is to make all rollbacks consistent since rollbacks that happen due to crash never has a chance to commit the increased key generator value.
Example
db.createObjectStore("store", { autoIncrement: true }); trans1 = db.transaction(["store"], "readwrite"); store_t1 = trans1.objectStore("store"); store_t1.put("a"); // Will get key 1 store_t1.put("b"); // Will get key 2 trans1.abort(); trans2 = db.transaction(["store"], "readwrite"); store_t2 = trans2.objectStore("store"); store_t2.put("c"); // Will get key 1 store_t2.put("d"); // Will get key 23.2 APIs
The 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 through the properties of the IDBRequest
instance.
IDBRequest
Interface
The IDBRequest
interface provides means to access results of asynchronous requests to databases and database objects using event handler attributes [HTML5].
Example 6
In the following example, we open a database asynchronously. Various event handlers are registered for responding to various situations.
Example
var request = indexedDB.open('AddressBook', 15); request.onsuccess = function(evt) {...}; request.onerror = function(evt) {...};
interface IDBRequest : EventTarget { readonly attribute any result; readonly attribute DOMError error; readonly attribute (IDBObjectStore
orIDBIndex
orIDBCursor
)? source; readonly attributeIDBTransaction
transaction; readonly attributeIDBRequestReadyState
readyState; attribute EventHandler onsuccess; attribute EventHandler onerror; };
error
of type DOMError, readonly
DOMException
of type InvalidStateError
.
onerror
of type EventHandler,
error
event.
onsuccess
of type EventHandler,
success
event.
readyState
of type IDBRequestReadyState
, readonly
"pending"
, otherwise returns "done"
.
result
of type any, readonly
undefined
when the request resulted in an error. When the done flag is false, getting this property MUST throw a DOMException
of type InvalidStateError
.
source
of type (IDBObjectStore or IDBIndex or IDBCursor), readonly , nullable
null
when there is no source set.
transaction
of type IDBTransaction
, readonly
IDBFactory.open
.
When a request is made, a new request is returned with its done flag set to false. If a request completes successfully, the done flag is set to true, the result is set to the result of the request, and an event with type success
is fired at the request.
If an error occurs while performing the operation, the done flag is set to true, the error attribute is set to a DOMError
type that matches the error, and an event with type error
is fired at the request.
The open
and deleteDatabase
functions on
uses a separate interface for its requests in order to make use of the IDBFactory
blocked
event and upgradeneeded
event easier.
interface IDBOpenDBRequest : IDBRequest
{
attribute EventHandler onblocked;
attribute EventHandler onupgradeneeded;
};
onblocked
of type EventHandler,
blocked
event.
onupgradeneeded
of type EventHandler,
upgradeneeded
event.
The task source for these tasks is the database access task source.
3.2.2 Event interfacesThis specification fires events with the following custom interfaces:
[Constructor(DOMString type, optional IDBVersionChangeEventInit eventInitDict)] interface IDBVersionChangeEvent : Event { readonly attribute unsigned long long oldVersion; readonly attribute unsigned long long? newVersion; };
newVersion
of type unsigned long long, readonly , nullable
"versionchange"
transaction.
oldVersion
of type unsigned long long, readonly
Events are constructed as defined in Constructing events, in [DOM4].
3.2.3 Opening a databaseWindow 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;
};
indexedDB
of type IDBFactory
, readonly
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 at a time.
interface IDBFactory {IDBOpenDBRequest
open (DOMString name, [EnforceRange] optional unsigned long long version);IDBOpenDBRequest
deleteDatabase (DOMString name); short cmp (any first, any second); };
cmp
If either first or second is not a valid key, the implementation MUST throw a DOMException
of type DataError
.
Otherwise, this method MUST compare two keys. The method returns 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.
Parameter Type Nullable Optional Description firstany
✘ ✘ The first key to compare. second any
✘ ✘ The second key to compare.
Return type: short
deleteDatabase
When invoked, this method MUST create a request and return it. The created request must implement the IDBOpenDBRequest
interface and have its source set to null. The method then queues up an operation to run 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 error attribute of the request to a DOMError
whose name
is the same as the error returned, and dispatch an event at the request. The event must use the Event
interface and have its type
set to "error"
. The event does bubble but is not cancelable. The propagation path of the event is just the request.
If the steps above are successful, the implementation MUST set the result of the request to undefined
and fire a success event at the request. The event MUST implement the IDBVersionChangeEvent
interface and have oldVersion
set to database version and have the newVersion
property set to null.
DOMString
✘ ✘ The name for the database
open
If the value of version is 0
(zero), the implementation MUST throw a TypeError
.
Otherwise, this method MUST create a request and return it. The created request MUST implement the IDBOpenDBRequest
interface and have its source set to null
. The method then queues up an operation to run the steps for opening a database. Let origin be the origin of the IDBEnvironment
used to access this IDBFactory
, name and version be the name and version parameters passed to this function, and request be the newly created request. If the version parameter is not specified, let version be undefined
.
Note
If version is not specified and a database with that name already exists, a connection will be opened without changing the version. If version is not specified and no database with that name exists, a new database will be created with version equal to 1
.
If an error is returned from the steps above, the implementation MUST set the error attribute of the request to a DOMError
whose name
is the same as the error returned, and dispatch an event at the request. The event must use the Event
interface and have its type
set to "error"
. The event does bubble but is not cancelable. The propagation path of the event is just the request.
If the steps above are successful, the implementation MUST set the result
to the connection created by the steps above and dispatch an event at request. The event must use the Event
interface and have its type
set to "success"
. The event does not bubble and is not cancelable. The propagation path of the event is just the request. If the steps above resulted in a "versionchange"
transaction being run, then firing the "success"
event MUST be done after the “versionchange”
transaction completes.
Note
The last requirement is to ensure that in case another version upgrade is about to happen, the success event is fired on the connection first so that the page gets a chance to register a listener for the versionchange
event.
DOMString
✘ ✘ The name for the database version unsigned long long
✘ ✔ The version for the database
A database object can be used to manipulate the objects of that database. It is also the only way to obtain a transaction for that database.
interface IDBDatabase : EventTarget { readonly attribute DOMString name; readonly attribute unsigned long long version; readonly attribute DOMStringList objectStoreNames;IDBObjectStore
createObjectStore (DOMString name, optionalIDBObjectStoreParameters
optionalParameters); void deleteObjectStore (DOMString name);IDBTransaction
transaction ((DOMString or sequence<DOMString>) storeNames, optionalIDBTransactionMode
mode = "readonly"); void close (); attribute EventHandler onabort; attribute EventHandler onerror; attribute EventHandler onversionchange; };
name
of type DOMString, readonly
IDBDatabase
instance.
objectStoreNames
of type DOMStringList, readonly
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 value of this attribute stays constant for the lifetime of the IDBDatabase
instance, except during a "versionchange"
transaction if createObjectStore
or deleteObjectStore
is called on this IDBDatabase
instance itself.
onabort
of type EventHandler,
abort
event.
onerror
of type EventHandler,
error
event.
onversionchange
of type EventHandler,
versionchange
event.
version
of type unsigned long long, readonly
IDBDatabase
instance was created. When a IDBDatabase
instance is created, this is always the number passed as the version argument passed to the open
call used to create the IDBDatabase
instance. This value remains constant for the lifetime of the IDBDatabase
object. If the connection is closed, this attribute represents a snapshot of the version that the database had when the connection was closed. Even if another connection is later used to modify the version, that attribute on closed instances are not changed.
close
No parameters.
Return type: void
createObjectStore
This method creates and returns a new object store with the given name in the connected database. Note that this method must only be called from within a "versionchange"
transaction.
If this database is not running a "versionchange"
transaction, or if this function is called on a IDBDatabase
object other than that transaction's connection, the implementation MUST throw a DOMException
of type InvalidStateError
. If the "versionchange"
transaction is not active, the implementation MUST throw a DOMException
of type TransactionInactiveError
. If an object store with the name name already exists in this database, the implementation MUST throw a DOMException
of type ConstraintError
.
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 not a valid key path, the implementation MUST throw a DOMException
of type SyntaxError
.
If the optionalParameters argument is specified, and autoIncrement
is set to true, then set autoIncrement to true. If autoIncrement is true and keyPath is an empty DOMString
or any sequence<DOMString>
, the implementation MUST throw a DOMException
of type InvalidAccessError
.
Otherwise the implementation MUST create a new object store in the connected database and return an IDBObjectStore
object representing it. Set the created object store's name to name. If autoIncrement is true, then the created object store uses a key generator. If keyPath is defined, set the created object store's key path to the value of keyPath.
This method synchronously modifies the IDBDatabase.objectStoreNames
property. However it only changes the IDBDatabase.objectStoreNames
property on the IDBDatabase
instance on which it was called.
In some implementations it is possible for the implementation to run into problems after queuing up an operation to create 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 an 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 using the appropriate error as error parameter. For example if creating the object store failed due to quota reasons, QuotaError
MUST be used as error.
deleteObjectStore
This method destroys the object store with the given name in the connected database. Note that this method must only be called from within a "versionchange"
transaction.
If this database is not running a "versionchange"
transaction, or if this function is called on a IDBDatabase
object other than that transactions connection, the implementation MUST throw a DOMException
of type InvalidStateError
. If the "versionchange"
transaction is not active, the implementation MUST throw a DOMException
of type TransactionInactiveError
.
If there is no object store with name name, compared in a case-sensitive manner, in the connected database, the implementation MUST throw a DOMException
of type NotFoundError
.
Otherwise, this method destroys the object store with the name name in the connected database.
This method synchronously modifies the IDBDatabase.objectStoreNames
property. However it only changes the IDBDatabase.objectStoreNames
property on the IDBDatabase
instance on which it was called.
DOMString
✘ ✘ The name of an existing object store
Return type: void
transaction
If the value for the mode parameter is not "readonly"
or "readwrite"
, the implementation MUST throw a TypeError
. If this method is called on IDBDatabase
object for which a "versionchange"
transaction is still running, the implementation MUST throw a DOMException
of type InvalidStateError
. If this method is called on a IDBDatabase
instance where the closePending flag is set, the implementation MUST throw a DOMException
of type InvalidStateError
. If any of the names in storeNames do not exist in this database, the implementation MUST throw a DOMException
of type NotFoundError
. If storeNames is an empty list, the implementation MUST throw a DOMException
of type InvalidAccessError
.
Otherwise, this method MUST execute the steps for creating a transaction in an asychronous fashion. The storeNames and mode arguments are forwarded to the algorithm as-is. The connection argument is set to the IDBDatabase
that the transaction()
method was called on.
The method returns an IDBTransaction
object representing the transaction returned by the steps above.
(DOMString or sequence<DOMString>)
✘ ✘ The names of object stores in the scope of the new transaction mode IDBTransactionMode
= "readonly"
✘ ✔ The mode for isolating access to data inside the given object stores. If this parameter is not provided, the default access mode is "readonly"
.
interface IDBObjectStore { readonly attribute DOMString name; readonly attribute any keyPath; readonly attribute DOMStringList indexNames; readonly attributeIDBTransaction
transaction; readonly attribute boolean autoIncrement;IDBRequest
put (any value, optional any key);IDBRequest
add (any value, optional any key);IDBRequest
delete (any key);IDBRequest
get (any key);IDBRequest
clear ();IDBRequest
openCursor (optional any range, optionalIDBCursorDirection
direction = "next");IDBIndex
createIndex (DOMString name, (DOMString or sequence<DOMString>) keyPath, optionalIDBIndexParameters
optionalParameters);IDBIndex
index (DOMString name); void deleteIndex (DOMString indexName);IDBRequest
count (optional any key); };
autoIncrement
of type boolean, readonly
indexNames
of type DOMStringList, readonly
On getting, provide a list of the names of indexes on objects in this object store. The list MUST be sorted in ascending order using the algorithm defined by step 4 of section 11.8.5, The Abstract Relational Comparison Algorithm of the ECMAScript Language Specification [ECMA-262].
Once the closePending flag is set on the connection, this attribute MUST return a snapshot of the list of names of the indexes taken at the time when the close
method was called. Even if other connections are later used to change the set of indexes that exist in the object store. In other words, the value of this attribute stays constant for the lifetime of the IDBObjectStore
instance, except during a "versionchange"
transaction if createIndex
or deleteIndex
is called on this IDBObjectStore
instance itself.
keyPath
of type any, readonly
On getting, returns a value representing the key path of this object store, or null
if none. If the key path is a DOMString
, the value will be a DOMString
equal to the key path. If the key path is a sequence<DOMString>
, the value will be a new Array
, populated by appending String
s equal to each DOMString
in the sequence.
The returned value is not the same instance that was used when the object store was created. However, if this attribute returns an object (specifically an Array
), it returns the same object instance every time it is inspected. Changing the properties of the object has no effect on the object store.
name
of type DOMString, readonly
transaction
of type IDBTransaction
, readonly
add
If the transaction this IDBObjectStore
belongs to has its mode set to "readonly"
, the implementation MUST throw a DOMException
of type ReadOnlyError
. If the transaction this IDBObjectStore
belongs to is not active, the implementation MUST throw a DOMException
of type TransactionInactiveError
. If the object store has been deleted, the implementation MUST throw a DOMException
of type InvalidStateError
. If any of the following conditions are true, the implementation MUST throw a DOMException
of type DataError
:
Otherwise, this method creates a structured clone of the value parameter. If the structure clone algorithm throws an exception, that exception is rethrown. Otherwise, run the steps for asynchronously executing a request and return 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.
Note
To determine if a transaction has completed successfully, listen to the transaction’s complete
event rather than the IDBObjectStore.add
request’s success
event, because the transaction may still fail after the success
event fires.
any
✘ ✘ The value to be stored in the record key any
✘ ✔ The key used to identify the record
clear
If the transaction this IDBObjectStore
belongs to has its mode set to "readonly"
, the implementation MUST throw a DOMException
of type ReadOnlyError
. If the transaction this IDBObjectStore
belongs to is not active, the implementation MUST throw a DOMException
of type TransactionInactiveError
. If the object store has been deleted, the implementation MUST throw a DOMException
of type InvalidStateError
.
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.
count
If the transaction this IDBObjectStore
belongs to is not active, the implementation MUST throw a DOMException
of type TransactionInactiveError
. If the object store has been deleted, the implementation MUST throw a DOMException
of type InvalidStateError
. If the optional key parameter is not a valid key or a key range, the implementation MUST throw a DOMException
of type DataError
.
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 iterating a cursor as operation, using the created cursor as cursor. If provided, use the key parameter as key, otherwise, use undefined as key. If the result of the algorithm is null return 0
(zero) as the result for the request. Otherwise, use the return cursor to determine the total number of objects that share the key or key range and return that value as the result for the request.
any
✘ ✔ Key identifying the record to be retrieved. This can also be an IDBKeyRange
.
createIndex
This method creates and returns a new index with the given name in the object store. Note that this method must only be called from within a "versionchange"
transaction.
If this object store's database is not running a "versionchange"
transaction, the implementation MUST throw a DOMException
of type InvalidStateError
. If the transaction this IDBObjectStore
belongs to is not active, the implementation MUST throw a DOMException
of type TransactionInactiveError
. If the object store has been deleted, the implementation MUST throw a DOMException
of type InvalidStateError
. If an index with the name name already exists in this object store, the implementation MUST throw a DOMException
of type ConstraintError
. If keyPath is not a valid key path, the implementation MUST throw a DOMException
of type SyntaxError
. If keyPath is a sequence<DOMString>
and the multiEntry property in the optionalParameters is true, the implementation MUST throw a DOMException
of type InvalidAccessError
.
Otherwise, the implementation MUST create a new index in the object store and return an IDBIndex
object representing it. Set the created index's name to name and key path to keyPath. Set the created index's unique and multiEntry flags to the values of the unique and multiEntry properties in the optionalParameters argument.
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 an IDBIndex
object. Instead the implementation must queue up an operation to abort the "versionchange"
transaction which was used for the createIndex call.
This method synchronously modifies the IDBObjectStore.indexNames
property. However it only changes the IDBObjectStore.indexNames
property on the IDBObjectStore
instance on which it was called. Although this method does not return a IDBRequest
object, the index creation itself is processed as an asynchronous request within the "versionchange"
transaction.
In some implementations it is 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 queued up to be 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 an 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 using the appropriate error as error parameter. For example if creating the index failed due to quota reasons, QuotaError
MUST be used as error and if the index can't be created due to unique constraints, ConstraintError
MUST be used as error.
Example 7
The asynchronous creation of indexes is observable in the following example:
Example
var request1 = objectStore.put({name: "betty"}, 1); var request2 = objectStore.put({name: "betty"}, 2); var index = objectStore.createIndex("by_name", "name", {unique: true});
At the point where createIndex
called, neither of the requests have executed. When the second request executes, a duplicate name is created. Since the index creation is considered an asynchronous request, the index's uniqueness constraint does not cause the second request to fail. Instead, the transaction will be aborted when the index is created and the constraint fails.
DOMString
✘ ✘ The name of a new index keyPath (DOMString or sequence<DOMString>)
✘ ✘ The key path used by the new index. optionalParameters IDBIndexParameters
✘ ✔ The options object whose attributes are optional parameters to this function. unique
specifies whether the index's unique flag is set. multiEntry
specifies whether the index's multiEntry flag is set.
delete
If the transaction this IDBObjectStore
belongs to has its mode set to "readonly"
, the implementation MUST throw a DOMException
of type ReadOnlyError
. If the transaction this IDBObjectStore
belongs to is not active, the implementation MUST throw a DOMException
of type TransactionInactiveError
. If the object store has been deleted, the implementation MUST throw a DOMException
of type InvalidStateError
. If key is not a valid key or a key range, the implementation MUST throw a DOMException
of type DataError
.
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 records from an object store as operation, using this IDBObjectStore
as store and the key parameter as key.
Note
Unlike other methods which take keys or key ranges, this method does not allow null to be passed as key. This is to reduce the risk that a small bug would clear a whole object store.
Parameter Type Nullable Optional Description keyany
✘ ✘ Key identifying the record to be deleted
deleteIndex
This method destroys the index with the given name in the object store. Note that this method must only be called from within a "versionchange"
transaction.
If this object store's database is not running a "versionchange"
transaction, the implementation MUST throw a DOMException
of type InvalidStateError
. If the transaction this IDBObjectStore
belongs to is not active, the implementation MUST throw a DOMException
of type TransactionInactiveError
. If the object store has been deleted, the implementation MUST throw a DOMException
of type InvalidStateError
. If there is no index with the name name, compared in a case-sensitive manner, in the object store, the implementation MUST throw a DOMException
of type NotFoundError
.
Otherwise, this method destroys the index with the name name in the object store.
This method synchronously modifies the IDBObjectStore.indexNames
property. However it only changes the IDBObjectStore.indexNames
property on the IDBObjectStore
instance on which it was called. Although this method does not return a IDBRequest
object, the index destruction itself is processed as an asynchronous request within the "versionchange"
transaction.
DOMString
✘ ✘ The name of an existing index
Return type: void
get
If the transaction this IDBObjectStore
belongs to is not active, the implementation MUST throw a DOMException
of type TransactionInactiveError
. If the object store has been deleted, the implementation MUST throw a DOMException
of type InvalidStateError
. If key is not a valid key or a key range, the implementation MUST throw a DOMException
of type DataError
.
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.
Note
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.
any
✘ ✘ Key identifying the record to be retrieved. This can also be an IDBKeyRange
in which case the function retreives the first existing value in that range.
index
IDBIndex
representing an index that is part of the 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 IDBTransaction
instances use different IDBIndex
instances to represent the same index.
If there is no index with the given name, compared in a case-sensitive manner, in the object store, the implementation MUST throw a DOMException
of type NotFoundError
. If the object store has been deleted, the implementation MUST throw a DOMException
of type InvalidStateError
.
DOMString
✘ ✘ The name of an existing index
openCursor
If the transaction this IDBObjectStore
belongs to is not active, the implementation MUST throw a DOMException
of type TransactionInactiveError
. If the object store has been deleted, the implementation MUST throw a DOMException
of type InvalidStateError
. If key is not a valid key or a key range, the implementation MUST throw a DOMException
of type DataError
.
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 got value 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.
put
If the transaction this IDBObjectStore
belongs to has its mode set to "readonly"
, the implementation MUST throw a DOMException
of type ReadOnlyError
. If the transaction this IDBObjectStore
belongs to is not active, the implementation MUST throw a DOMException
of type TransactionInactiveError
. If the object store has been deleted, the implementation MUST throw a DOMException
of type InvalidStateError
. If any of the following conditions are true, the implementation MUST throw a DOMException
of type DataError
:
Otherwise, this method creates a structured clone of the value parameter. If the structured clone algorithm throws an exception, that exception is rethrown. Otherwise, run the steps for asynchronously executing a request and return 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.
any
✘ ✘ The value to be stored in the record key any
✘ ✔ The key used to identify the record
Index objects implement the following interface:
interface IDBIndex { readonly attribute DOMString name; readonly attributeIDBObjectStore
objectStore; readonly attribute any keyPath; readonly attribute boolean multiEntry; readonly attribute boolean unique;IDBRequest
openCursor (optional any range, optionalIDBCursorDirection
direction = "next");IDBRequest
openKeyCursor (optional any range, optionalIDBCursorDirection
direction = "next");IDBRequest
get (any key);IDBRequest
getKey (any key);IDBRequest
count (optional any key); };
keyPath
of type any, readonly
On getting, returns a value representing the key path of this index. If the key path is a DOMString
, the value will be a DOMString
equal to the key path. If the key path is a sequence<DOMString>
, the value will be a new Array
, populated by appending String
s equal to each DOMString
in the sequence.
The returned value is not the same instance that was used when the index was created. However, if this attribute returns an object (specifically an Array
), it returns the same object instance every time it is inspected. Changing the properties of the object has no effect on the index.
multiEntry
of type boolean, readonly
name
of type DOMString, readonly
objectStore
of type IDBObjectStore
, readonly
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
.
unique
of type boolean, readonly
count
If the transaction this IDBIndex
belongs to is not active, the implementation MUST throw a DOMException
of type TransactionInactiveError
. If the index or the index's object store has been deleted, the implementation MUST throw a DOMException
of type InvalidStateError
. If the optional key parameter is not a valid key or a key range, the implementation MUST throw a DOMException
of type DataError
.
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 IDBIndex
as source and the steps for iterating a cursor as operation, using the created cursor as cursor. If provided, use the key parameter as key, otherwise, use undefined as key. If the result of the algorithm is null return 0
(zero) as the result for the request. Otherwise, use the return cursor to determine the total number of objects that share the key or key range and return that value as the result for the request.
any
✘ ✔ Key identifying the record to be retrieved. This can also be an IDBKeyRange
.
get
If the transaction this IDBIndex
belongs to is not active, the implementation MUST throw a DOMException
of type TransactionInactiveError
. If the index or the index's object store has been deleted, the implementation MUST throw a DOMException
of type InvalidStateError
. If the key parameter is not a valid key or a key range, the implementation MUST throw a DOMException
of type DataError
.
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 referenced value from an index as operation, using this IDBIndex
as index and the key parameter as key.
Note
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.
any
✘ ✘ Key identifying the record to be retrieved. This can also be an IDBKeyRange
in which case the function retreives the first existing value in that range.
getKey
Gets the key of the record from the referenced object store entry.
If the transaction this IDBIndex
belongs to is not active, the implementation MUST throw a DOMException
of type TransactionInactiveError
. If the index or the index's object store has been deleted, the implementation MUST throw a DOMException
of type InvalidStateError
. If the key parameter is not a valid key or a key range, the implementation MUST throw a DOMException
of type DataError
.
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 index as operation, using this IDBIndex
as index and the key parameter as key.
any
✘ ✘ Key identifying the record to be retrieved. This can also be an IDBKeyRange
in which case the function retreives the first existing value in that range.
openCursor
If the transaction this IDBIndex
belongs to is not active, the implementation MUST throw a DOMException
of type TransactionInactiveError
. If the index or the index's object store has been deleted, the implementation MUST throw a DOMException
of type InvalidStateError
. If the range parameter is specified but is not a valid key or a key range, the implementation MUST throw a DOMException
of type DataError
.
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 got value 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
openKeyCursor
If the transaction this IDBIndex
belongs to is not active, the implementation MUST throw a DOMException
of type TransactionInactiveError
. If the index or the index's object store has been deleted, the implementation MUST throw a DOMException
of type InvalidStateError
. If the range parameter is specified but is not a valid key or a key range, the implementation MUST throw a DOMException
of type DataError
.
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 got value 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
Cursor objects implement the following interface:
interface IDBCursor { readonly attribute (IDBObjectStore
orIDBIndex
) source; readonly attributeIDBCursorDirection
direction; readonly attribute any key; readonly attribute any primaryKey;IDBRequest
update (any value); void advance ([EnforceRange] unsigned long count); void continue (optional any key);IDBRequest
delete (); };
direction
of type IDBCursorDirection
, readonly
key
of type any, readonly
Array
), it returns the same object instance every time it is inspected, until the cursor's key is changed. 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.
primaryKey
of type any, readonly
Array
), it returns the same object instance every time it is inspected, until the cursor's effective key is changed. 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.
source
of type (IDBObjectStore or IDBIndex), readonly
IDBObjectStore
or IDBIndex
which this cursor is iterating. This attribute never returns null or throws an exception, even if the cursor is currently being iterated, has iterated past its end, or its transaction is not active.
advance
If the value for count is 0
(zero), the implementation MUST throw a TypeError
. If the transaction this IDBCursor
belongs to is not active, the implementation MUST throw a DOMException
of type TransactionInactiveError
. If the cursor's source or effective object store has been deleted, the implementation MUST throw a DOMException
of type InvalidStateError
. If this cursor's got value flag is false, indicating that the cursor is being iterated or has iterated past its end, the implementation MUST throw a DOMException
of type InvalidStateError
.
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. The operation runs the steps for iterating a cursor count number of times with null as key and this cursor as cursor.
Before this method returns, unless an exception was thrown, it sets the got value flag on the cursor to false.
Note
Calling this method more than once before new cursor data has been loaded is not allowed. For example, calling advance()
twice from the same onsuccess handler results in an DOMException
of type InvalidStateError
being thrown on the second call because the cursor's got value has been set to false.
unsigned long
✘ ✘ The number of advances forward the cursor should make.
Return type: void
continue
If the transaction this IDBCursor
belongs to is not active, the implementation MUST throw a DOMException
of type TransactionInactiveError
. If the cursor's source or effective object store has been deleted, the implementation MUST throw a DOMException
of type InvalidStateError
. If this cursor's got value flag is false, indicating that the cursor is being iterated or has iterated past its end, the implementation MUST throw a DOMException
of type InvalidStateError
. If the key parameter is specified and fulfills any of these conditions, the implementation MUST throw a DOMException
of type DataError
:
"next"
or "nextunique"
."prev"
or "prevunique"
.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.
Note
Calling this method more than once before new cursor data has been loaded is not allowed. For example, calling continue()
twice from the same onsuccess handler results in a DOMException
of type InvalidStateError
being thrown on the second call because the cursor's got value has been set to false.
any
✘ ✔ The next key to position this cursor at
Return type: void
delete
If the transaction this IDBCursor
belongs to has its mode set to "readonly"
, the implementation MUST throw a DOMException
of type ReadOnlyError
. If the transaction this IDBCursor
belongs to is not active, the implementation MUST throw a DOMException
of type TransactionInactiveError
. If the cursor's source or effective object store has been deleted, the implementation MUST throw a DOMException
of type InvalidStateError
. If this cursor's got value flag is false, indicating that the cursor is being iterated or has iterated past its end, or if this cursor does not implement the IDBCursorWithValue
interface, the implementation MUST throw a DOMException
of type InvalidStateError
.
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 records from an object store as operation, using this cursor's effective object store and effective key as store and key respectively.
No parameters.
update
If the transaction this IDBCursor
belongs to has its mode set to "readonly"
, the implementation MUST throw a DOMException
of type ReadOnlyError
. If the transaction this IDBCursor
belongs to is not active, the implementation MUST throw a DOMException
of type TransactionInactiveError
. If the cursor's source or effective object store has been deleted, the implementation MUST throw a DOMException
of type InvalidStateError
. If this cursor's got value flag is false, indicating that the cursor is being iterated or has iterated past its end, or if this cursor does not implement the IDBCursorWithValue
interface, the implementation MUST throw a DOMException
of type InvalidStateError
. 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, the implementation MUST throw a DOMException
of type DataError
.
Otherwise, this method creates a structured clone of the value parameter. If the structured clone algorithm throws an exception, that exception is rethrown. Otherwise, run the steps for asynchronously executing a request and return 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.
any
✘ ✘ The new value to store at the current position.
interface IDBCursorWithValue : IDBCursor
{
readonly attribute any value;
};
value
of type any, readonly
Transaction objects implement the following interface:
interface IDBTransaction : EventTarget { readonly attributeIDBTransactionMode
mode; readonly attributeIDBDatabase
db; readonly attribute DOMError error;IDBObjectStore
objectStore (DOMString name); void abort (); attribute EventHandler onabort; attribute EventHandler oncomplete; attribute EventHandler onerror; };
db
of type IDBDatabase
, readonly
error
of type DOMError, readonly
abort
function, this property returns null
. If this transaction was aborted due to a failed request, this property returns the same DOMError
as the request which caused this transaction to be aborted. If this transaction was aborted due to an error when committing the transaction, and not due to a failed request, this property returns a DOMError
which contains the reason for the transaction failure (e.g. QuotaExceededError
or UnknownError
).
mode
of type IDBTransactionMode
, readonly
onabort
of type EventHandler,
abort
event.
oncomplete
of type EventHandler,
complete
event.
Note
To determine if a transaction has completed successfully, listen to the transaction’s complete
event rather than the success
event of a particular request, because the transaction may still fail after the success
event fires.
onerror
of type EventHandler,
error
event.
abort
If this transaction is finished, the implementation MUST throw a DOMException
of type InvalidStateError
.
Otherwise, this method sets the transaction's active flag to false and aborts the transaction by running the steps for aborting a transaction with the error parameter set to null
.
No parameters.
Return type: void
objectStore
IDBObjectStore
representing an object store that is part of 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.
If the requested object store is not in this transaction's scope, the implementation MUST throw a DOMException
of type NotFoundError
. If the transaction has finished, the implementation MUST throw a DOMException
of type InvalidStateError
.
DOMString
✘ ✘ The requested object store
The steps for opening a database are defined in the following steps. The algorithm in these steps takes four arguments: the origin which requested the database to be opened, a database name, a database version, and a request.
"versionchange"
transaction.Note
If several connections with the same origin and name are waiting due to the above conditions, and those connections have a higher version than the database's current version, then once any of those connections can proceed to the next step in this algorithm it will immediately start a "versionchange"
transaction. This prevents the other connections from proceeding until that "versionchange"
transaction is finished.
0
as version, and with no object stores. Let db be the new database.undefined
, then let version be 1
if db was created in the previous step, or the current version of db otherwise.DOMError
of type VersionError."versionchange"
transaction using connection, version and request."versionchange"
transaction in the previous step was aborted, or if connection is closed, return a DOMError
of type AbortError and abort these steps. In either of these cases, ensure that connection is closed by running the steps for closing a database connection before these steps are aborted.When the user agent is to create a transaction it MUST run the following steps. This algorithm takes three arguments: a connection, a mode, and the list storeNames naming the object stores to be included in the scope of the transaction.
sequence<DOMString>
then let scope be the set of unique strings in the sequence. Otherwise, storeNames must be a DOMString
; let scope be a set containing one string equal to storeNames. If any of the strings in scope identifies an object store which doesn't exist, throw a DOMException
of type NotFoundError
. If scope is an empty set throw a DOMException
of type InvalidAccessError
.DOMException
of type InvalidStateError
.When taking the steps for committing a transaction the implementation MUST execute the following algorithm. This algorithm takes one argument, the transaction to commit.
QuotaExceededError
or UnknownError
.Event
interface and have its type
set to "complete"
. The event does not bubble and is not cancelable. The propagation path for the event is transaction's connection and then transaction.
Note
Even if an exception is thrown from one of the event handlers of this event, the transaction is still committed since writing the database changes happens before the event takes places. Only after the transaction has been successfully written is the "complete"
event fired.
When taking the steps for aborting a transaction the implementation MUST execute the following algorithm. This algorithm takes two arguments: the transaction to abort, and an error name.
"versionchange"
transactions this includes changes to the set of object stores and indexes, as well as the change to the version. Also run the steps for aborting a "versionchange"
transaction which reverts changes to all IDBDatabase
and IDBObjectStore
instances.null
, create a DOMError
object and set its name
to error. Set transaction's error
property to this newly created DOMError
.undefined
and set the request's error attribute to a DOMError
with a type of AbortError.Event
interface and have its type
set to "error"
. The event bubbles and is cancelable. The propagation path for the event is transaction's connection, then transaction and finally the request. There is no default action for the event.Note
This does not always result in any error
events being fired. For example if a transaction is aborted due to an error while committing the transaction, or if it was the last remaining request that failed.
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.When taking the steps for asynchronously executing a request the implementation MUST run the following algorithm. The algorithm takes a source object and an 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
DOMException
of type TransactionInactiveError
.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 queue up the execution of the remaining steps in this algorithm.
Note
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.
undefined
. Finally fire a success event at request.undefined
and set the error attribute on the request to a DOMError
with the same error type as the operation that failed. Finally fire an error event at request.
Note
This only reverts the changes done by this request, not any other changes made by the transaction.
"versionchange"
transaction steps
The steps for running a "versionchange"
transaction are as follows. This algorithm takes three arguments: a connection object which is used to update the database, a new version to be set for the database, and a request.
IDBDatabase
objects, except connection, connected to the same database as connection.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 oldVersion
property set to db's version and have the newVersion
property set to version. This event MUST NOT bubble or be cancelable. The propagation path for the event is just the IDBDatabase
object itself.
Note
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.
If any of the connections in openDatabases are still not closed, queue up a blocked
event for the request. The event MUST use the IDBVersionChangeEvent
interface and have the oldVersion
property set to db's version and have the newVersion
property set to version. This event MUST NOT bubble or be cancelable. The propagation path for the event is just request.
"versionchange"
and connection used as connection. The scope of the transaction includes every object store in connection. Set its active flag to false. Let transaction represent this transaction.result
property of request to connection.transaction
property of request to transaction.upgradeneeded
event targeted at request. The event MUST use the IDBVersionChangeEvent
interface and have the oldVersion
property set to old version and have the newVersion
property set to version. The done flag on the request is set to true.AbortError
."versionchange"
transaction is aborted the IDBDatabase
instance which represents connection will remain unchanged. I.e., its name
, version
, and objectStoreNames
properties will remain the value they were before the transaction was aborted. The default attributes for the IDBDatabase
are:transaction
property to null
. This MUST be done in the same task as the task firing the complete
or abort
event, but after those events has been fired."versionchange"
transaction
The steps for aborting a "versionchange"
transaction are as follows.
IDBDatabase.name
is not modified at all. Even if the transaction is used to create a new database, and thus there is no on-disk database, IDBDatabase.name
remains as it was.IDBDatabase.version
to the version the on-disk database had before the transaction was started. If the "versionchange"
transaction was started because the database was newly created, revert IDBDatabase.version
to version 0; if the transaction was started in response to a version upgrade, revert to the version it had before the transaction was started. Note that the only time that the IDBDatabase.version
property ever changes value is during a "versionchange"
transaction.IDBDatabase.objectStoreNames
to the list of names that it had before the transaction was started. If the "versionchange"
transaction was started because the database was newly created, revert it to an empty list. If the "versionchange"
transaction was started in response to a version upgrade, revert to the list of object store names it had before the transaction was started.IDBObjectStore.indexNames
(for each object store) to the list of names that IDBObjectStore.indexNames
had before the transaction was started. For any object store that was created by the transaction, revert the list to an empty list. For any object store that existed before the transaction was started, revert to the list of index names it had before the transaction was started. For any object store that was deleted during the transaction, revert the list of names to the list it had before the transaction was started, potentially a non-empty list.The steps for closing a database connection are as follows. These steps take one argument, a connection object.
closePending
flag of connection to true.Note
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 closePending flag first and throw an exception if it is true.
The steps for deleting a database are as follows. The algorithm in these steps takes three arguments: the origin that requested the database to be deleted, a database name, and a request.
IDBDatabase
objects connected to db.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 oldVersion
property set to db's version and have the newVersion
property set to null
. This event MUST NOT bubble or be cancelable.
Note
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.
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 oldVersion
property set to db's version and have the newVersion
property set to null
. This event MUST NOT bubble or be cancelable.
To fire a success event at a request, the implementation MUST run the following steps:
Event
interface and have its type
set to "success"
. The event does not bubble and is not cancelable. The propagation path for the event is the transaction's connection, then transaction and finally request.AbortError
as error.To fire an error event at a request, the implementation MUST run the following steps:
Event
interface and have its type
set to "error"
. The event bubbles and is cancelable. The propagation path for the event is the transaction's connection, then transaction and finally request. The event's default action is to abort the transaction by running the steps for aborting a transaction using transaction as transaction and the name
of request's error
property as error. However the default action is not taken if any of the event handlers threw an exception.AbortError
as error. This is done even if the error event is not canceled.
Note
This means that if an error event is fired and any of the event handlers throw an exception, the error
property on the transaction is set to an AbortError
rather than whatever DOMError
the error
property on the request was set to. Even if preventDefault
is never called.
The steps to assign a key to a value using a key path are as follows:
Object
object or an Array
object (see structured clone algorithm [HTML5]), then throw a DOMException
of type DataError
.Object
.Note
The steps leading here ensure that remainingKeyPath is a single identifier name (that is, a string without periods) by this step. The steps also ensure that object is an Object
or an Array
, and not a Date
, RegExp
, Blob
, or other nonsupported type.
Note
The intent is that these steps are only executed if evaluating the key path did not yield a value. In other words, before you run these steps, first evaluate the key path against value, and only if that does not yield a value (where undefined
does count as a value) do you generate a key and use these steps to modify value to contain the generated key.
Note
The key path used here is always a DOMString
and never an sequence<DOMString>
since it is not possible to create a object store whose multiEntry flag is true and whose key path is an sequence<DOMString>
.
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.
3.4.1 Object Store Storage OperationThe steps for storing a record into an object store are as follows. The algorithm run by these steps takes four arguments: an object store store, a value, an optional key, and a no-overwrite flag.
2^53
(9007199254740992
) any attempt to use the key generator to generate a new key fails with a ConstraintError
.Number
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.ConstraintError
. Abort this algorithm without taking any further steps.Array
, and if index key is not a valid key, take no further actions for this index.Array
, remove any elements from index key that are not valid keys and remove any duplicate elements from index key such that only one instance of the duplicate value remains.
Note
For example, the following value of index key [10, 20, null, 30, 20]
is converted to [10, 20, 30]
.
Note
After this step index key is or contains only valid keys.
Array
, and if index already contains a record with key equal to index key, and index has its unique flag set to true, then this operation failed with a ConstraintError
. Abort this algorithm without taking any further steps.Array
, and if index already contains a record with key equal to any of the values in index key, and index has its unique flag set to true, then this operation failed with a ConstraintError
. Abort this algorithm without taking any further steps.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.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
Note that it is legal for the Array
to have length 0, in this case no records are added to the index.
Note
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, Array
s are not recursively "unpacked" to produce multiple rows. Only the outer-most Array
is.
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.
undefined
.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.
undefined
.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.
undefined
.The steps for deleting records from an object store are as follows. The algorithm run by these steps takes two parameters: an object store store and a key.
undefined
.The steps for clearing an object store are as follows. The algorithm run by these steps takes one parameter: an object store store.
undefined
.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.
Note
records is always sorted in ascending key order. In the case of source being an index, records is secondarily sorted in ascending value order (where the value in an index is the key of the record in the referenced object store).
If direction is "next"
, let found record be the first record in records which satisfy all of the following requirements:
If direction is "nextunique"
, let found record be the first record in records which satisfy all of the following requirements:
If direction is "prev"
, let found record be the last record in records which satisfy all of the following requirements:
If direction is "prevunique"
, let temp record be the last record in records which satisfy all of the following requirements:
If temp record is defined, let found record be the first record in records whose key is equal to temp record's key.
undefined
. If source is an index, set cursor's object store position to undefined
. If cursor implements IDBCursorWithValue
then set cursor's value to undefined
. The result of this algorithm is null
. Abort these steps.Set cursor's position to found record's key. If source is an index, set cursor's object store position to found record's value.
Set cursor's key to found record's key.
If cursor implements IDBCursorWithValue
then set cursor's value to a structured clone of found record referenced value.
This section is non-normative.
4.1 User trackingA 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:
iframe
s.
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.
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.
User agents MAY require the user to authorize access to databases before a site can use the feature.
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.
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.
4.2 Cookie resurrectionIf the user interface for persistent storage presents data in the persistent storage features described in this specification separately from data in HTTP session cookies, then users are likely to delete data in one and not the other. This would allow sites to use the two features as redundant backup for each other, defeating a user's attempts to protect his privacy.
4.3 Sensitivity of dataUser agents should treat persistently stored data as potentially sensitive; it is 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.
This section is non-normative.
5.1 DNS spoofing attacksBecause 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.
5.2 Cross-directory attacksDifferent 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.
Note
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.
5.3 Implementation risksThe 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. RequirementsRequirements will be written with an aim to verify that these were actually met by the API specified in this document.
B. Revision HistoryThe following is an informative summary of the changes since the last publication of this specification. A complete revision history of the Editor's Drafts of this specification can be found here.
C. AcknowledgementsSpecial thanks and great appreciation to Nikunj Mehta, the original author of this specification, who was employed by Oracle Corp when he wrote the early drafts.
Garret Swart was extremely influential in the design of this specification.
Special thanks to Chris Anderson, Pablo Castro, Kristof Degrave, Jake Drew, Ben Dilts, João Eiras: Alec Flett, Dana Florescu, David Grogan, Israel Hilerio, Kyle Huey, Laxminarayan G Kamath A, Anne van Kesteren, Tobie Langel, Kang-Hao Lu, Andrea Marchesini, Glenn Maynard, Ms2ger, Odin Omdal, Danillo Paiva, Olli Pettay, Simon Pieters, Yonathan Randolph, Arun Ranganathan, Margo Seltzer, Maciej Stachowiak, Ben Turner, Hans Wennborg, Shawn Wilsher, Boris Zbarsky Zhiqiang Zhang, and Kris Zyp, all of whose feedback and suggestions have led to improvements to this specification.
D. References D.1 Normative referencesRetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.3