3.1 Constructs
An indexed database is made of records holding simple values
and hierarchical objects. Each record consists of a key and a value.
3.1.1 Keys
In order to efficiently retrieve records
stored in an indexed database, a user agent needs to organize each
record according to its key. Conforming user agents
must support the use of the following values as keys: IDL data types
DOMString
, long
, and float
[WEBIDL]; the Date
JavaScript object [ECMA-262]; as well as the value null
.
For purposes of comparison, all DOMString
values are evaluated as greater than
long
, float
, and Date
values; Date
values are evaluated as greater than long
and float
values; and long
and float
values are evaluated by their numeric
value with no need to separate them by type. Moreover, null
always evaluates
less than any other key value that is a non-null value. For the particular case
of floating point numbers, the value NaN is not allowed.
Only data types with natural ordering can be used as keys.
The ECMAScript undefined
must not be used as a key.
3.1.2 Values
Values can be any data type supported by the structured clone algorithm
[HTML5]. This includes simple types such as DOMString
and Date
as well as Object
and Array
instances.
A database can derive a key from the contents of
the value being stored. In such a case, only Object
instances may be stored as values. Only the direct enumerable
properties of a stored Object
instance should be
used to derive a key value.
3.1.3 Object Store
An object store is a persistent storage mechanism that
holds key-value pairs, also called records
or stored objects. An object store's
records are sorted by keys to enable fast
insertion and look up as well as ordered retrieval.
Every object store has a
name. Within a database,
each object store must have a valid
and unique name.
If an object store uses keys generated from a monotonically
increasing sequence, it must have a key generator that
produces unique keys for records in that
object store. Alternatively, if an application provides keys,
they may either be identified as a part of the value being stored,
also called in-line keys, or be identified separately,
also called out-of-line keys. No two
records in an object store may be
identified by the same key. An object store must have a
key path if it uses
in-line keys. The key path must be the name
of an enumerated property of all stored objects in that
object store.
The IDBObjectStore
and IDBObjectStoreSync
interfaces provide access to the metadata of an object store.
3.1.5 Database
Each origin has an associated set of
databases. A database comprises
one or more object stores.
Each database has a valid
name and a human readable
description. A valid name is any
string including the empty string. An exact match of names means
that their UTF-8 encodings are identical.
If an implementation does not support all sets of strings, it may
implement support for arbitrary strings by mapping
database names (e.g. using a hashing algorithm) to the supported
set of names.
Each database also has a current version.
Each
database has one version at a time; a
database
can't exist in multiple versions at once.
The act of opening a database creates a database
connection. There may be multiple
connections to a given database
at any given time. An operation that is attempting to read a
given piece of data in a database is called a
reader and one that is attempting to write a piece of
data is called a writer.
Readers and writers should only operate through
transactions. A connection may have
any number of active transactions.
IDBDatabase
and IDBDatabaseSync
interfaces represent connections to a database.
3.1.6 Key Range
An individual record can be retrieved from an
object store using either the record's key or the key
applicable for some index that
references that object store.
Multiple records can be fetched using a key range. A
key range is a continuous interval over some data type
used for keys.
A key range may be left-bounded or right-bounded if there is
a value that is, respectively, smaller than or larger than all its
elements. A key range is said to be bounded if it is both
left- and right-bounded and unbounded otherwise. A
valid key range must be
either half-bounded or bounded. A key range may be open,
i.e., not including its endpoints or closed, i.e., including
its endpoints. A key range may consist of a single value.
The IDBKeyRange
interface defines a
key range.
interface IDBKeyRange {
const unsigned short SINGLE = 0;
const unsigned short LEFT_OPEN = 1;
const unsigned short RIGHT_OPEN = 2;
const unsigned short LEFT_BOUND = 4;
const unsigned short RIGHT_BOUND = 8;
readonly attribute any left;
readonly attribute any right;
readonly attribute unsigned short flags;
IDBKeyRange
only (in any value);
IDBKeyRange
leftBound (in any bound, in optional boolean open);
IDBKeyRange
rightBound (in any bound, in optional boolean open);
IDBKeyRange
bound (in any left, in any right, in optional boolean openLeft, in optional boolean openRight);
};
Attributes
flags
of type unsigned short, readonly- Flags for bounding values
No exceptions.
left
of type any, readonly- This value is the left-bound of the key range.
No exceptions.
right
of type any, readonly- This value is the right-bound of the key range.
No exceptions.
Methods
bound
-
Create a new left- and right-bound key range.
Parameter | Type | Nullable | Optional | Description |
---|
left | any | ✘ | ✘ | The left-bound value |
right | any | ✘ | ✘ | The right-bound value |
openLeft | boolean | ✘ | ✔ | Is the left-bound value included in the key range. |
openRight | boolean | ✘ | ✔ | Is the right-bound value included in the key range. |
No exceptions.
leftBound
-
Create a new left-bound key range.
Parameter | Type | Nullable | Optional | Description |
---|
bound | any | ✘ | ✘ | The left bound value |
open | boolean | ✘ | ✔ | Is the left-bound value included in the key range. |
No exceptions.
only
-
Create a new single-valued key range.
Parameter | Type | Nullable | Optional | Description |
---|
value | any | ✘ | ✘ | The only value |
No exceptions.
rightBound
-
Create a new right-bound key range.
Parameter | Type | Nullable | Optional | Description |
---|
bound | any | ✘ | ✘ | The right bound value |
open | boolean | ✘ | ✔ | Is the right-bound value included in the key range. |
No exceptions.
3.1.7 Cursor
Cursors are a transient mechanism used to
iterate over multiple records in a database. The storage operations
are performed on the underlying index or an
object store.
A cursor comprises a range of records in
either an index or an object store. A
cursor maintains a position over
this series, which moves in a direction that is either
monotonically increasing or decreasing order of the record keys.
Cursor objects implement the IDBCursor
or the IDBCursorSync
interfaces.
3.1.8 Transaction
A transaction is defined on a database. A
transaction's scope is either
static or dynamic and it may include a subset of the object stores of the transaction's
database. If the scope is static, then it may
be global, meaning that it includes every existing and
to be created object stores of the database. There may
be multiple transactions active in a database
as long as their scopes do not overlap or the overlapping
objects are locked in modes that are not mutually exclusive.
TODO: decide what happens when dynamic transactions need to lock a database
object that is already exclusively locked by another transaction.
Concurrent access to the object stores in a transaction
may be isolated in one of three modes. These are:
READ_ONLY
READ_WRITE
SNAPSHOT_READ
VERSION_CHANGE
Any number of readers may concurrently access
all object stores. A writer is not allowed
if there is any reader concurrently accessing the
object stores, unless the reader is detached, i.e.,
looking at a snapshot view of the data that does not change once
created.
Transactions offer some protection from
application and system failures. A transaction may be used to
store multiple data records or to conditionally modify certain data
records. A transaction represents an atomic and durable set
of data access and mutation operations.
Transactions are expected to be short
lived. A transaction may be programmatically aborted.
Conforming user agents must automatically:
-
commit a transaction at the end of the scope in
which it was created unless there is an active operation being
performed using that transaction, in which case, the transaction is
automatically committed when that operation is completed.
-
abort a transaction at the end of the scope in which it was
created, if an exception is propagated to that scope.
Static transaction objects implement the
IDBTransaction
or the
IDBTransactionSync
interfaces.
Dynamic transaction objects implement the
IDBDynamicTransaction
or the
IDBDynamicTransactionSync
interfaces.
Define dynamic transactions if we agree they should be part of this specification.
3.1.9 The IDBDatabaseException
Interface
exception IDBDatabaseException {
const unsigned short UNKNOWN_ERR = 0;
const unsigned short NON_TRANSIENT_ERR = 1;
const unsigned short NOT_FOUND_ERR = 2;
const unsigned short CONSTRAINT_ERR = 3;
const unsigned short DATA_ERR = 4;
const unsigned short NOT_ALLOWED_ERR = 5;
const unsigned short SERIAL_ERR = 11;
const unsigned short RECOVERABLE_ERR = 21;
const unsigned short TRANSIENT_ERR = 31;
const unsigned short TIMEOUT_ERR = 32;
const unsigned short DEADLOCK_ERR = 33;
attribute unsigned short code;
attribute DOMString message;
};
Fields
code
of type attribute unsigned short-
Return the most appropriate error code.
message
of type attribute DOMString-
Return an error message describing the exception raised.
The message should be localized to the user's language.
Constants
CONSTRAINT_ERR
of type unsigned short- A mutation operation in the transaction failed due to a
because a constraint was not satisfied. For example, an
object such as an object store or index already
exists and a new one was being attempted to be created.
DATA_ERR
of type unsigned short- Data provided to an operation does not meet requirements.
DEADLOCK_ERR
of type unsigned short- The current transaction was automatically rolled back
by the database because of deadlock or other transaction
serialization failures.
NON_TRANSIENT_ERR
of type unsigned short- This error occurred because an operation was not allowed on
an object. A retry of the same operation would fail unless the
cause of the error is corrected.
NOT_ALLOWED_ERR
of type unsigned short- A mutation operation was attempted on a database that
did not allow mutations.
NOT_FOUND_ERR
of type unsigned short- The operation failed because the requested database
object could not be found. For example, an object store
did not exist but was being opened.
RECOVERABLE_ERR
of type unsigned short- The operation failed because the database was prevented
from taking an action. The operation might be able to succeed
if the application performs some recovery steps and retries
the entire transaction. For example, there was not enough
remaining storage space, or the storage quota was reached
and the user declined to give more space to the database.
SERIAL_ERR
of type unsigned short- The operation failed because of the size of the data set
being returned or because there was a problem in serializing or
deserializing the object being processed.
TIMEOUT_ERR
of type unsigned short- A lock for the transaction could not be obtained in a
reasonable time.
TRANSIENT_ERR
of type unsigned short- The operation failed because of some temporary problems.
The failed operation might be able to succeed when the
operation is retried without any intervention by
application-level functionality.
UNKNOWN_ERR
of type unsigned short- The operation failed for reasons unrelated to the database
itself and not covered by any other error code.
3.2 Asynchronous APIs
The asynchronous API methods return without blocking the calling thread.
All asynchronous operations return an IDBRequest
instance,
which can be used to access the results of the operation as they become available.
3.2.1 Event interfaces
Events are fired during asynchronous access as database
objects are created and data is consumed from these objects.
As requests are made to database objects, the user
agent loads information about them into memory and when the required
object handle is available, it alerts the application through the
firing of events. The events are as follows:
The IDBEvent
interface extends
the Event
interface defined in [DOM-LEVEL-3-EVENTS].
[NoInterfaceObject]
interface IDBEvent : Event {
readonly attribute any source;
};
Attributes
source
of type any, readonly- Returns the asynchronous request object that fired this event.
No exceptions.
[NoInterfaceObject]
interface IDBSuccessEvent : IDBEvent
{
readonly attribute any result;
};
Attributes
result
of type any, readonly- Returns the result of the successful completion of an asynchronous request
on the
source
.No exceptions.
[NoInterfaceObject]
interface IDBTransactionEvent : IDBSuccessEvent
{
readonly attribute IDBTransaction
transaction;
};
Attributes
transaction
of type IDBTransaction
, readonly- Returns the transaction used for the request
on the
source
.No exceptions.
[NoInterfaceObject]
interface IDBErrorEvent : IDBEvent
{
readonly attribute unsigned short code;
readonly attribute DOMString message;
};
Attributes
code
of type unsigned short, readonly- Returns the most appropriate error code from carrying out the asynchronous request
on the
source
. The
valid values of this error code are defined on the exception
IDBDatabaseException
.No exceptions.
message
of type DOMString, readonly- Returns the describing the reason for the error. The message should be localized
to the user's language.
No exceptions.
[NoInterfaceObject]
interface IDBVersionChangeEvent : IDBEvent
{
readonly attribute DOMString version;
};
3.2.2 The IDBRequest
Interface
The IDBRequest
interface provides means to access results of
asynchronous requests to databases and database
objects using event handler attributes [DOM-LEVEL-3-EVENTS].
In the following example, we open a database asynchronously. Various
event handlers are registered for responding to various situations.
ECMAScript
var request = indexedDB.open('AddressBook', 'Address Book');
request.onsuccess = function(evt) {...};
request.onerror = function(evt) {...};
[NoInterfaceObject]
interface IDBRequest : EventTarget {
void abort ();
const unsigned short LOADING = 1;
const unsigned short DONE = 2;
readonly attribute unsigned short readyState;
attribute Function onsuccess;
attribute Function onerror;
};
Attributes
onerror
of type Function- The event handler for the error event
No exceptions.
onsuccess
of type Function- The event handler for the success event
No exceptions.
readyState
of type unsigned short, readonly- Every request starts in the
LOADING
state.
When either the request completes, fails or aborts successfully, the state changes to
DONE
.No exceptions.
Methods
abort
- This method has no effect if the
readyState
is DONE
.
If made on a read request, the implementation discontinues the in-flight request
even if the implementation has already read the data, and is ready to fire a
success event. The error event
is always fired if abort()
is called, and the success event is suppressed.
The readyState
moves to DONE
.
If the request aborts successfully, the
error
is set
to UNKNOWN_ERR
.No parameters.
No exceptions.
Constants
DONE
of type unsigned short- This state indicates that a result to a previous request is available in
the
result
attribute. LOADING
of type unsigned short- This state indicates that a request has been started but its results is not
yet available.
When a request is made, the
readyState
changes to
LOADING
.
If a request completes successfully, the
readyState
changes to DONE
,
the result of the request is included as the
result
of
a new IDBSuccessEvent
event, and queue a task to fire that event with the name success
,
with no namespace, which does not bubble, is not cancelable at each
Window
object.
If an error occurs while performing the operation, the
readyState
changes to DONE
,
the error code and message are included in a new IDBDatabaseError
event, and queue a task to fire that event with the name
error
, with no namespace, which does not bubble, is
not cancelable at each Window
object.
The task source for these tasks is the
database access task source.
The following are the event handlers (and their corresponding
event handler event types) that must be supported, as IDL
attributes, by objects implementing the IDBRequest
interface:
The following are the event handlers (and their corresponding
event handler event types) that must be supported, as IDL
attributes, by objects implementing the IDBTransaction
interface:
Event handler |
Event handler event type |
oncomplete |
complete |
onabort |
abort |
ontimeout |
timeout |
3.2.3 Opening a database
Window
and
Worker
objects
must implement the IDBEnvironment
interface.
Window implements IDBEnvironment
;
Worker implements IDBEnvironment
;
[NoInterfaceObject]
interface IDBEnvironment {
readonly attribute IDBFactory
indexedDB;
};
Attributes
indexedDB
of type IDBFactory
, readonly- This attribute provides applications a mechanism for accessing
capabilities of indexed databases.
No exceptions.
Every method for making asynchronous requests returns an
IDBRequest
object that communicates back to the requesting
application through events.
This design means that any number of requests can be active on any database
or object handle at a time.
[NoInterfaceObject]
interface IDBFactory {
readonly attribute DOMStringList databases;
IDBRequest
open (in DOMString name, in DOMString description) raises (IDBDatabaseException
);
};
Attributes
databases
of type DOMStringList, readonly-
This value is the list of the names of databases available in the global scope object.
No exceptions.
Methods
open
-
This method returns immediately and runs the
following steps in a different thread.
If an error occurs while the database connection
is being opened, then an
error event is fired on this method's
returned object with its
code
set
to UNKNOWN_ERR
and a suitable
message
.
-
Let origin be the origin of the active document
from which the method was invoked.
-
Perform the steps for opening a database, with
origin, the name parameter and
description parameter, and call its result as
result.
-
If the steps were aborted with an error code, then set this
request's
error
with that
code and abort these steps.
-
Create a
IDBDatabase
object for result
and call it db.
-
Fire a success event on this
method's returned object using the
IDBSuccessEvent
interface with its
result
set to db.
3.2.5 Object Store
Object store objects implement the following
interface:
[NoInterfaceObject]
interface IDBObjectStore {
readonly attribute DOMString name;
readonly attribute DOMString keyPath;
readonly attribute DOMStringList indexNames;
IDBRequest
put (in any value, in optional any key) raises (IDBDatabaseException
);
IDBRequest
add (in any value, in optional any key) raises (IDBDatabaseException
);
IDBRequest
remove (in any key) raises (IDBDatabaseException
);
IDBRequest
get (in any key) raises (IDBDatabaseException
);
IDBRequest
openCursor (in optional IDBKeyRange
range, in optional unsigned short direction) raises (IDBDatabaseException
);
IDBIndex
createIndex (in DOMString name, in DOMString keyPath, in optional boolean unique) raises (IDBDatabaseException
);
IDBIndex
index (in DOMString name) raises (IDBDatabaseException
);
void removeIndex (in DOMString indexName) raises (IDBDatabaseException
);
};
Attributes
indexNames
of type DOMStringList, readonly-
On getting, provide a list of the names of indexes on
objects in this object store.
No exceptions.
keyPath
of type DOMString, readonly-
On getting, provide the key path
of this object store. If this attribute is
null
,
the application must provide a key value for each modification operation.
No exceptions.
name
of type DOMString, readonly-
On getting, provide the name of this
object store.
No exceptions.
Methods
add
-
This method returns immediately and stores the given value in this
object store by following the
steps for storing a record into an object store with the
no-overwrite flag set. If the record can be successfully
stored in the object store, then a
success event is fired on this
method's returned object using the
IDBTransactionEvent
interface with its
result
set to
the key for the stored record and
transaction
set to the transaction in which this object store is
opened. If a record exists in this object store for
the key key parameter, then an
error event is fired on this method's
returned object with its
code
set to
CONSTRAINT_ERR
Parameter | Type | Nullable | Optional | Description |
---|
value | any | ✘ | ✘ | The value to be stored in the record |
key | any | ✘ | ✔ | The key used to identify the record, which defaults
to null |
createIndex
-
This creates and returns a new index with the given name and parameters in the
connected database. Note that this method must only
be called from a VERSION_CHANGE
transaction callback.
get
-
This method returns immediately and retrieves the value from this
object store for the record corresponding to the given key
by following the
steps for retrieving a record from an object store.
If the operation is successful, then the
result
of this object's request
is set to the retrieved value. If a record did not exist in this
object store for the key key parameter, then an
error event is fired on this method's
returned object with its
code
set to
NOT_FOUND_ERR
and a suitable
message
. If the record can be successfully
retrieved from the object store, then a
success event is fired on this
method's returned object using the
IDBTransactionEvent
interface with its
result
set to
the value of the retrieved record and transaction
set to the transaction in which this object store is
opened.
Parameter | Type | Nullable | Optional | Description |
---|
key | any | ✘ | ✘ | Key identifying the record to be retrieved |
index
-
This method returns immediately and opens the index with the
given name in the connected database.
openCursor
-
This method returns immediately and creates a cursor over the
records of this object store. The range of this
cursor matches the key range specified as the
range parameter, or if that parameter is not specified or
null
, then the range includes all the records.
If there is even a single record that matches the key range, then a
success event is fired on this method's
returned object with its
result
set to the
IDBCursor
object for that cursor. If no
records match the key range, then an
success event is fired on this method's
returned object with its
result
set to null
.
put
-
This method returns immediately and stores the given value in this
object store by following the
steps for storing a record into an object store. If the
record can be successfully stored in the object store, then
a success event is fired on this
method's returned object using the
IDBTransactionEvent
interface with its
result
set to
the key for the stored record and
transaction
set to the transaction in which this object store is
opened.
Parameter | Type | Nullable | Optional | Description |
---|
value | any | ✘ | ✘ | The value to be stored in the record |
key | any | ✘ | ✔ | The key used to identify the record, which defaults
to null |
remove
-
This method returns immediately and removes the record from
this object store by following the
steps for deleting a record from an object store
corresponding to the given key. If a record did not exist
in this object store for the key parameter,
then an error event is fired on this
method's returned object with its
code
set to
NOT_FOUND_ERR
and a suitable
message
. If the record can be successfully
removed from the object store, then a
success event is fired on this
method's returned object using the
IDBTransactionEvent
interface with its
result
set to
the value of the removed record and transaction
set to the transaction in which this object store is
opened.
Parameter | Type | Nullable | Optional | Description |
---|
key | any | ✘ | ✘ | Key identifying the record to be removed |
removeIndex
-
This method destroys the index with the given name in the
connected database. Note that this
method must only be called from a VERSION_CHANGE
transaction callback.
3.2.6 Index
Index objects implement the following interface:
[NoInterfaceObject]
interface IDBIndex {
readonly attribute DOMString name;
readonly attribute DOMString storeName;
readonly attribute DOMString keyPath;
readonly attribute boolean unique;
IDBCursor
openObjectCursor (in optional IDBKeyRange
range, in optional unsigned short direction) raises (IDBDatabaseException
);
IDBRequest
openCursor (in optional IDBKeyRange
range, in optional unsigned short direction) raises (IDBDatabaseException
);
IDBRequest
getObject (in any key) raises (IDBDatabaseException
);
IDBRequest
get (in any key) raises (IDBDatabaseException
);
};
Methods
get
-
This method returns immediately and retrieves the value from this index
for the record corresponding to the given key parameter by
following the steps for retrieving a value from an index.
If the operation is successful, then the
result
of this object's request
is set to the retrieved value. If a record did not exist in this
index for the key key parameter, then an
error event is fired on this method's
returned object with its
code
set to
NOT_FOUND_ERR
and a suitable
message
.
Parameter | Type | Nullable | Optional | Description |
---|
key | any | ✘ | ✘ | Key identifying the record to be retrieved |
getObject
-
This method returns immediately and retrieves the value from this index's
referenced object store for the record corresponding to the given
key by following the steps for retrieving a record from an index.
If the operation is successful, then the
result
of this object's request
is set to the retrieved value. If a record did not exist in this
index for the key key parameter, then an
error event is fired on this method's
returned object with its
code
set to
NOT_FOUND_ERR
and a suitable
message
.
Parameter | Type | Nullable | Optional | Description |
---|
key | any | ✘ | ✘ | Key identifying the record to be retrieved |
openCursor
-
This method returns immediately and creates a cursor over the
records of this index. The range of this cursor
matches the key range specified as the range parameter, or
if that parameter is not specified or
null
, then the
range includes all the records.
If there is even a single record that matches the key range, then a
success event is fired on this method's
returned object with its
result
set to the
IDBCursor
object for that cursor. If no
records match the key range, then an
error event is fired on this method's
returned object with its
code
set to
NOT_FOUND_ERR
and a suitable
message
.
openObjectCursor
-
This method returns immediately and creates a cursor over the
records of this index's referenced object store
as arranged by this index. The range of this cursor
matches the key range specified as the range parameter, or
if that parameter is not specified or
null
, then the
range includes all the records.
If there is even a single record that matches the key range, then a
success event is fired on this method's
returned object with its
result
set to the
IDBCursor
object for that cursor. If no
records match the key range, then an
error event is fired on this method's
returned object with its
code
set to
NOT_FOUND_ERR
and a suitable
message
.
3.2.7 Cursor
Cursor objects implement the following interface:
[NoInterfaceObject]
interface IDBCursor {
const unsigned short NEXT = 0;
const unsigned short NEXT_NO_DUPLICATE = 1;
const unsigned short PREV = 2;
const unsigned short PREV_NO_DUPLICATE = 3;
readonly attribute unsigned short direction;
readonly attribute any key;
readonly attribute any value;
readonly attribute unsigned long long count;
IDBRequest
update (in any value) raises (IDBDatabaseException
);
boolean continue (in optional any key);
IDBRequest
remove () raises (IDBDatabaseException
);
};
Attributes
count
of type unsigned long long, readonly-
On getting, provide the approximate number of objects in the cursor.
No exceptions.
direction
of type unsigned short, readonly-
On getting, provide the traversal direction of the cursor.
No exceptions.
key
of type any, readonly- The key for the record at the cursor's position.
No exceptions.
value
of type any, readonly- The value for the record at the cursor's position.
No exceptions.
Methods
continue
-
This method returns immediately and advances the cursor to the next
position along its direction to the item whose key matches the
optional parameter. If no such parameter is provided, advance to the
immediate next position. If the cursor has reached the end of its
range, then an
success event is fired on this method's
returned object with its
result
set to null
.
Parameter | Type | Nullable | Optional | Description |
---|
key | any | ✘ | ✔ | The next key to position this cursor at |
No exceptions.
remove
-
This method returns immediately and deletes the object at the
cursor's position. The cursor's
position is not changed. Any attempts to retrieve the cursor's
current value will return null
.
No parameters.
update
-
This method returns immediately and sets the value for the record at the
cursor's position.
Parameter | Type | Nullable | Optional | Description |
---|
value | any | ✘ | ✘ | |
Constants
NEXT
of type unsigned short-
indicates that this cursor should yield all records, including
duplicates and its direction is monotonically increasing
order of keys.
NEXT_NO_DUPLICATE
of type unsigned short-
indicates that this cursor should yield all records, not including
duplicates and its direction is monotonically increasing
order of keys. For every key with duplicate values, only the first
record is yielded.
PREV
of type unsigned short-
indicates that cursor should yield all records, including
duplicates and its direction is monotonically decreasing
order of keys.
PREV_NO_DUPLICATE
of type unsigned short-
indicates that this cursor should yield all records, not including
duplicates and its direction is monotonically decreasing
order of keys. For every key with duplicate values, only the first
record is yielded.
3.3 Synchronous APIs
3.3.1 Opening a database
Worker
objects must implement the
IDBEnvironmentSync
interface.
WorkerUtils implements IDBEnvironmentSync
;
[NoInterfaceObject]
interface IDBEnvironmentSync {
readonly attribute IDBFactorySync
indexedDBSync;
};
Attributes
indexedDBSync
of type IDBFactorySync
, readonly- This attribute provides applications a mechanism for accessing
capabilities of indexed databases.
No exceptions.
[NoInterfaceObject]
interface IDBFactorySync {
IDBDatabaseSync
open (in DOMString name, in DOMString description) raises (IDBDatabaseException
);
};
Methods
open
-
The synchronous API for databases blocks the calling thread until a
IDBDatabaseSync
object is ready to return.
When this method is invoked, the user agent must run the
following steps:
-
Let origin be the origin of the scripts in the worker.
-
Perform the steps for opening a database, with origin,
the name parameter and description parameter, and
call its result as result.
-
If the steps were aborted with an error code, then throw a newly constructed
IDBDatabaseException
exception with the code of that error and abort these steps.
-
Create a
IDBDatabaseSync
object using result
and call it db.
-
Return db.
3.3.3 Object Store
In the following example, we set up an object store to use the
key path id. This
object store is also designed to use a key generator.
ECMAScript
var db = indexedDB.open('AddressBook', 'Address Book');
if (db.version !== '1') {
var olddb = indexedDB.open('AddressBook', 'Address Book');
olddb.createObjectStore('Contact', 'id', true);
olddb.setVersion('1');
}
Using this database, we can store records in the Contact
object store.
ECMAScript
var store = db.openObjectStore('Contact');
var lincoln = {name: 'Lincoln', number: '7012'};
var contact = store.put(lincoln);
// contact.id === 1
A stored value can be retrieved using the same key used by the
first put operation.
ECMAScript
var contact = store.get(1);
// contact.name === 'Lincoln'
A second put operation will overwrite the record stored by the first
put operation.
ECMAScript
var abraham = {id: 1, name: 'Abraham', number: '2107'};
store.put(abraham);
Now when the object store is read with the same key, the result
is different compared to the object read earlier.
ECMAScript
var contact = store.get(1);
// contact.id === 1 && contact.name === 'Abraham';
Additionally, all the records of an object store
matching a certain key range can be retrieved in key order.
ECMAScript
var range = new IDBKeyRange.bound(2, 4);
var cursor = store.openCursor(range);
// each value is a contact and each key is the id for that
// contact whose id is between 2 and 4, both inclusive
cursor.continue();
[NoInterfaceObject]
interface IDBObjectStoreSync {
const unsigned short READ_WRITE = 0;
const unsigned short READ_ONLY = 1;
const unsigned short SNAPSHOT_READ = 2;
readonly attribute unsigned short mode;
readonly attribute DOMString name;
readonly attribute DOMString keyPath;
readonly attribute DOMStringList indexNames;
any put (in any value, in optional any key) raises (IDBDatabaseException
);
any add (in any value, in optional any key) raises (IDBDatabaseException
);
void remove (in any key) raises (IDBDatabaseException
);
any get (in any key) raises (IDBDatabaseException
);
IDBIndexSync
createIndex (in DOMString name, in DOMString keyPath, in optional boolean unique);
IDBIndexSync
openIndex (in DOMString name) raises (IDBDatabaseException
);
void removeIndex (in DOMString indexName) raises (IDBDatabaseException
);
IDBCursorSync
openCursor (in optional IDBKeyRange
range, in optional unsigned short direction) raises (IDBDatabaseException
);
};
Attributes
indexNames
of type DOMStringList, readonly-
On getting, provide a list of the names of indexes on
objects in this object store.
No exceptions.
keyPath
of type DOMString, readonly-
On getting, provide the key path
of this object store. If this attribute is
null
,
the application must provide a key value for each modification operation.
No exceptions.
mode
of type unsigned short, readonly- On getting, provide the mode for isolating access to data
inside this object store.
No exceptions.
name
of type DOMString, readonly-
On getting, provide the name of this
object store.
No exceptions.
3.3.4 Index
An index can be created for retrieving records other than
by using record keys. Continuing the earlier example, an auto-populated
index could be maintained on the name property of objects
in the Contact object store.
ECMAScript
var db = indexedDB.open('AddressBook', 'Address Book');
if (db.version === '1') {
var olddb = indexedDB.open('AddressBook', 'Address Book');
olddb.createObjectStore('Contact', 'id', true);
olddb.createIndex('ContactName', 'Contact', 'name', false);
olddb.setVersion('2');
}
For example, the id of an object with the name
property value 'Lincoln' can be retrieved using the
ContactName index.
ECMAScript
var index = db.openIndex('ContactName');
var id = index.get('Lincoln');
// id === 1
Additionally, all the records of an object store matching
a certain range index keys can be retrieved in key order. When
objects are retrieved from the Contact object store,
they are arranged by the value of the id attribute. On the
other hand, when objects are retrieved using the ContactName
index, they are arranged by the value of the name
property.
ECMAScript
var range = new IDBKeyRange
.bound('L', 'M');
var cursor = index.openCursor(range);
// each value is a contact and each key is the name for that
// contact whose name's first letter is either L or M
cursor.continue();
If, on the other hand, we only want the names but not the Contact
objects for a given range, then we can use a different mechanism for that.
ECMAScript
var range = new IDBKeyRange
.bound('L', 'M');
var cursor = index.openObjectCursor(range);
// each value is a contact and each key is the name for that
// contact whose name's first letter is either L or M
cursor.continue();
[NoInterfaceObject]
interface IDBIndexSync {
readonly attribute DOMString name;
readonly attribute DOMString storeName;
readonly attribute DOMString keyPath;
readonly attribute boolean unique;
void openObjectCursor (in optional IDBKeyRange
range, in optional unsigned short direction) raises (IDBDatabaseException
);
void openCursor (in optional IDBKeyRange
range, in optional unsigned short direction) raises (IDBDatabaseException
);
any put (in any value, in optional any key);
any add (in any value, in optional any key) raises (IDBDatabaseException
);
any getObject (in any key) raises (IDBDatabaseException
);
any get (in any key) raises (IDBDatabaseException
);
void remove (in any key) raises (IDBDatabaseException
);
};
Methods
add
-
Store the given value in this index by following
the steps for storing a record into an index and the no-overwrite flag set. The
returned object from this method is the key for the stored record.
Parameter | Type | Nullable | Optional | Description |
---|
value | any | ✘ | ✘ | The value to be stored in the record |
key | any | ✘ | ✔ | The key used to identify the record |
get
-
Retrieve the value from this index for the record
corresponding to the given key by following the
steps for retrieving a value from an index.
The value returned from this method is the retrieved value.
Parameter | Type | Nullable | Optional | Description |
---|
key | any | ✘ | ✘ | Key identifying the record to be retrieved |
getObject
-
Retrieve the value from this index's referenced
object store for the record corresponding to the given key
by following the steps for retrieving a record from an index.
The value returned from this method is the retrieved value.
Parameter | Type | Nullable | Optional | Description |
---|
key | any | ✘ | ✘ | Key identifying the record to be retrieved |
openCursor
-
Create a cursor over the records of this
index. The range of this cursor matches
the key range specified as the range parameter, or
if that parameter is not specified or
null
, then the
range includes all the records.
openObjectCursor
-
Create a cursor over the records of this
index's referenced object store as arranged by
this index. The range of this cursor matches
the key range specified as the range parameter, or
if that parameter is not specified or
null
, then the
range includes all the records.
put
-
Store the given value in this index by following
the steps for storing a record into an index. The
returned object from this method is the key for the stored record.
Parameter | Type | Nullable | Optional | Description |
---|
value | any | ✘ | ✘ | The value to be stored in the record |
key | any | ✘ | ✔ | The key used to identify the record |
No exceptions.
remove
-
Remove the records from this index by following
the steps for deleting a record from an index
corresponding to the given key.
Parameter | Type | Nullable | Optional | Description |
---|
key | any | ✘ | ✘ | Key identifying the record to be removed |
3.3.5 Cursor
Using the synchronous API, an application can process all the records
in the cursor's range. No two values provided by the
user agent to callbacks processing data in this cursor can be
identical.
By default, a cursor walks over objects starting at the
first record and ending at the last record including
all the duplicates encountered along the way. If the
cursor callback returns true, then the iteration is
stopped.
ECMAScript
var objects = ...
var cursor = objects.openCursor();
// act on each object and continue the cursor to its end
cursor.continue();
To start at the last record and end in the first record, the cursor
should be created with the direction parameter PREV
.
ECMAScript
var objects = ...
var cursor = objects.openCursor(IDBCursor
.PREV);
// act on each object and continue the cursor to its end
cursor.continue();
To start at a certain key and end in the last record, i.e.,
for a lower-bounded cursor, while skipping duplicates,
the cursor should be created with both the required
start key and the direction parameter.
ECMAScript
var objects = ...
var range = IDBKeyRange
.leftBound(key);
objects.openCursor(range, IDBCursor
.NEXT_NO_DUPLICATE);
// act on each object and continue the cursor to its end
cursor.continue();
It is also possible to create a bounded cursor, i.e., with
application-specified starting and ending points, the
cursor should be created with both the required keys.
If the range is inclusive of both keys, then additional
flags are required. In the following example, all keys
with values in the inclusive range (start
,
end
) are returned with all their duplicates,
from the beginning of the range to its end.
ECMAScript
var objects = ...
var range = IDBKeyRange
.bound(start, end);
objects.openCursor(range);
// act on each object and continue the cursor to its end
cursor.continue();
[NoInterfaceObject]
interface IDBCursorSync {
const unsigned short NEXT = 0;
const unsigned short NEXT_NO_DUPLICATE = 1;
const unsigned short PREV = 2;
const unsigned short PREV_NO_DUPLICATE = 3;
readonly attribute unsigned short direction;
readonly attribute any key;
attribute any value setraises (IDBDatabaseException
);
readonly attribute unsigned long long count;
boolean continue (in optional any key);
void remove () raises (IDBDatabaseException
);
};
Attributes
count
of type unsigned long long, readonly-
On getting, provide the approximate number of objects in the cursor.
No exceptions.
direction
of type unsigned short, readonly-
On getting, provide the traversal direction of the cursor.
No exceptions.
key
of type any, readonly- The key for the record at the cursor's position.
No exceptions.
value
of type any- The value for the record at the cursor's position.
Methods
continue
-
Advance the cursor to the next position along its direction
to the item whose key matches the optional parameter. If no such
parameter is provided, advance to the immediate next position. If
the cursor has reached the end of its range, then this
method returns false, otherwise it returns true.
Parameter | Type | Nullable | Optional | Description |
---|
key | any | ✘ | ✔ | The next key to position this cursor at |
No exceptions.
remove
-
Delete the object at the cursor's position. The cursor's
position is not changed. Any attempts to retrieve the cursor's
current value will return null
.
No parameters.
Constants
NEXT
of type unsigned short-
indicates that this cursor should yield all records, including
duplicates and its direction is monotonically increasing
order of keys.
NEXT_NO_DUPLICATE
of type unsigned short-
indicates that this cursor should yield all records, not including
duplicates and its direction is monotonically increasing
order of keys. For every key with duplicate values, only the first
record is yielded.
PREV
of type unsigned short-
indicates that cursor should yield all records, including
duplicates and its direction is monotonically decreasing
order of keys.
PREV_NO_DUPLICATE
of type unsigned short-
indicates that this cursor should yield all records, not including
duplicates and its direction is monotonically decreasing
order of keys. For every key with duplicate values, only the first
record is yielded.