Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Revision 1038264 of IDBTransaction

  • Revision slug: Web/API/IDBTransaction
  • Revision title: IDBTransaction
  • Revision id: 1038264
  • Created:
  • Creator: i80and
  • Is current revision? No
  • Comment If the mode constants are deprecated, the leading example should use string constants.

Revision Content

{{APIRef("IndexedDB")}}

The IDBTransaction interface of the IndexedDB API provides a static, asynchronous transaction on a database using event handler attributes. All reading and writing of data is done within transactions. You actually use {{domxref("IDBDatabase")}} to start transactions and {{domxref("IDBTransaction")}} to set the mode of the transaction (e.g. is it readonly or readwrite), and access an {{domxref("IDBObjectStore")}} to make a request. You can also use it to abort transactions.

Note that as of Firefox 40, IndexedDB transactions have relaxed durability guarantees to increase performance (see {{Bug("1112702")}}.) Previously in a readwrite transaction {{domxref("IDBTransaction.oncomplete")}} was fired only when all data was guaranteed to have been flushed to disk. In Firefox 40+ the complete event is fired after the OS has been told to write the data but potentially before that data has actually been flushed to disk. The complete event may thus be delivered quicker than before, however, there exists a small chance that the entire transaction will be lost if the OS crashes or there is a loss of system power before the data is flushed to disk. Since such catastrophic events are rare most consumers should not need to concern themselves further.

If you must ensure durability for some reason (e.g. you're storing critical data that cannot be recomputed later) you can force a transaction to flush to disk before delivering the complete event by creating a transaction using the experimental (non-standard) readwriteflush mode (see {{domxref("IDBDatabase.transaction")}}.

Note that transactions are started when the transaction is created, not when the first request is placed; for example consider this:

var trans1 = db.transaction("foo", "readwrite");
var trans2 = db.transaction("foo", "readwrite");
trans2.put("2", "key");
trans1.put("1", "key");

After the code is executed the object store should contain the value "2", since trans2 should run after trans1.

{{AvailableInWorkers}}

Methods

Inherits from: {{domxref("EventTarget")}}

{{domxref("IDBTransaction.abort")}}
Rolls back all the changes to objects in the database associated with this transaction. If this transaction has been aborted or completed, then this method throws an error event.
{{domxref("IDBTransaction.objectStore")}}
Returns an {{domxref("IDBObjectStore")}} object representing an object store that is part of the scope of this transaction.

Properties

{{domxref("IDBTransaction.db")}} {{readonlyInline}}
The database connection with which this transaction is associated.
{{domxref("IDBTransaction.mode")}} {{readonlyInline}}
The mode for isolating access to data in the object stores that are in the scope of the transaction. For possible values, see the Constants section below. The default value is readonly.
{{domxref("IDBTransaction.objectStoreNames")}} {{readonlyinline}}
Returns a {{domxref("DOMStringList")}} of the names of {{domxref("IDBObjectStore")}} objects.
{{domxref("IDBTransaction.error")}} {{readonlyInline}}
Returns one of several types of error when there is an unsuccessful transaction. This property is null if the transaction is not finished, is finished and successfully committed, or was aborted with {{domxref("IDBTransaction.abort")}} function.

Event handlers

{{domxref("IDBTransaction.onabort")}} {{readonlyInline}}
The event handler for the abort event, fired when the transaction is aborted.
{{domxref("IDBTransaction.oncomplete")}} {{readonlyInline}}
The event handler for the complete event, thrown when the transaction completes successfully.
{{domxref("IDBTransaction.onerror")}} {{readonlyInline}}
The event handler for the error event, thrown when the transaction fails to complete.

Mode constants

{{ deprecated_header(13) }}

These constants are no longer available — they were removed in Gecko 25. You should use the string constants directly instead. ({{ bug(888598) }})

Transactions can have one of three modes:

Constant Value Description
READ_ONLY

"readonly"

(0 in Chrome)

Allows data to be read but not changed.

READ_WRITE

"readwrite"

(1 in Chrome)

Allows reading and writing of data in existing data stores to be changed.
VERSION_CHANGE

"versionchange"

(2 in Chrome)

Allows any operation to be performed, including ones that delete and create object stores and indexes. This mode is for updating the version number of transactions that were started using the setVersion() method of IDBDatabase objects. Transactions of this mode cannot run concurrently with other transactions.

Even if these constants are now deprecated, you can still use them to provide backward compatibility if required (in Chrome the change was made in version 21). You should code defensively in case the object is not available anymore:

var myIDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || { READ_WRITE: "readwrite" };

Example

In the following code snippet, we open a read/write transaction on our database and add some data to an object store. Note also the functions attached to transaction event handlers to report on the outcome of the transaction opening in the event of success or failure. For a full working example, see our To-do Notifications app (view example live.)

// Let us open our database
var DBOpenRequest = window.indexedDB.open("toDoList", 4);

DBOpenRequest.onsuccess = function(event) {
  note.innerHTML += '<li>Database initialised.</li>';
    
  // store the result of opening the database in the db variable. This is used a lot below
  db = DBOpenRequest.result;
    
  // Run the addData() function to add the data to the database
  addData();
};

function addData() {
  // Create a new object ready for being inserted into the IDB
  var newItem = [ { taskTitle: "Walk dog", hours: 19, minutes: 30, day: 24, month: "December", year: 2013, notified: "no" } ];

  // open a read/write db transaction, ready for adding the data
  var transaction = db.transaction(["toDoList"], "readwrite");

  // report on the success of opening the transaction
  transaction.oncomplete = function(event) {
    note.innerHTML += '<li>Transaction completed: database modification finished.</li>';
  };


  transaction.onerror = function(event) {
  note.innerHTML += '<li>Transaction not opened due to error. Duplicate items not allowed.</li>';
  };

  // create an object store on the transaction
  var objectStore = transaction.objectStore("toDoList");

  // add our newItem object to the object store
  var objectStoreRequest = objectStore.add(newItem[0]);

  objectStoreRequest.onsuccess = function(event) {
    // report the success of our new item going into the database
    note.innerHTML += '<li>New item added to database.</li>';
  };
};

Specifications

Specification Status Comment
{{SpecName('IndexedDB', '#transaction', 'IDBTransaction')}} {{Spec2('IndexedDB')}} Initial definition

Browser compatibility

{{CompatibilityTable}}
Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Basic support 23{{property_prefix("webkit")}}
24[1]
10 {{property_prefix("moz")}}
{{CompatGeckoDesktop("16.0")}}
10, partial 15 7.1
Available in workers {{CompatVersionUnknown}} {{CompatGeckoMobile("37.0")}} {{CompatUnknown}} {{CompatVersionUnknown}} {{CompatUnknown}}
objectStoreNames property {{CompatChrome(48.0)}} {{CompatNo}} {{CompatNo}} {{CompatNo}} {{CompatNo}}
Feature Android Android Webview Firefox Mobile (Gecko) Firefox OS IE Phone Opera Mobile Safari Mobile Chrome for Android
Basic support 4.4 {{CompatVersionUnknown}} {{CompatGeckoMobile("22.0")}} 1.0.1 10 22 8 {{CompatVersionUnknown}}
Available in workers {{CompatVersionUnknown}} {{CompatVersionUnknown}} {{CompatGeckoMobile("37.0")}} {{CompatVersionUnknown}} {{CompatUnknown}} {{CompatVersionUnknown}} {{CompatUnknown}} {{CompatVersionUnknown}}
objectStoreNames property {{CompatNo}} {{CompatChrome(48.0)}} {{CompatNo}} {{CompatNo}} {{CompatNo}} {{CompatNo}} {{CompatNo}} {{CompatChrome(48.0)}}
  • [1] Older versions of Chrome serialize all transactions. So even if you have only read-only transactions and no read-write transaction, your transactions are executed one at a time. Any subsequent transactions are not executed until all read-only transactions are completed. For the status, see bug 64076.

See also

  • Using IndexedDB
  • Starting transactions: {{domxref("IDBDatabase")}}
  • Using transactions: {{domxref("IDBTransaction")}}
  • Setting a range of keys: {{domxref("IDBKeyRange")}}
  • Retrieving and making changes to your data: {{domxref("IDBObjectStore")}}
  • Using cursors: {{domxref("IDBCursor")}}
  • Reference example: To-do Notifications (view example live.)

Revision Source

<p>{{APIRef("IndexedDB")}}</p>

<div>
<p>The <strong><code>IDBTransaction</code></strong> interface of the <a href="/en-US/docs/IndexedDB">IndexedDB API</a> provides a static, asynchronous transaction on a database using event handler attributes. All reading and writing of data is done within transactions. You actually use {{domxref("IDBDatabase")}} to start transactions and {{domxref("IDBTransaction")}} to set the mode of the transaction (e.g. is it readonly or readwrite), and access an {{domxref("IDBObjectStore")}} to make a request. You can also use it to abort transactions.</p>
</div>

<p>Note that as of Firefox 40, IndexedDB transactions have relaxed durability guarantees to increase performance (see {{Bug("1112702")}}.) Previously in a <code>readwrite</code> transaction {{domxref("IDBTransaction.oncomplete")}} was fired only when all data was guaranteed to have been flushed to disk. In Firefox 40+ the <code>complete</code> event is fired after the OS has been told to write the data but potentially before that data has actually been flushed to disk. The <code>complete</code> event may thus be delivered quicker than before, however, there exists a small chance that the entire transaction will be lost if the OS crashes or there is a loss of system power before the data is flushed to disk. Since such catastrophic events are rare most consumers should not need to concern themselves further.</p>

<p>If you must ensure durability for some reason (e.g. you're storing critical data that cannot be recomputed later) you can force a transaction to flush to disk before delivering the <code>complete</code> event by creating a transaction using the experimental (non-standard) <code>readwriteflush</code> mode (see {{domxref("IDBDatabase.transaction")}}.</p>

<p>Note that transactions are started when the transaction is created, not when the first request is placed; for example consider this:</p>

<pre class="brush: js" id="comment_text_0">
var trans1 = db.transaction("foo", "readwrite");
var trans2 = db.transaction("foo", "readwrite");
trans2.put("2", "key");
trans1.put("1", "key");
</pre>

<p>After the code is executed the object store should contain the value "2", since <code>trans2</code> should run after <code>trans1</code>.</p>

<p>{{AvailableInWorkers}}</p>

<h2 id="Methods">Methods</h2>

<p>Inherits from: {{domxref("EventTarget")}}</p>

<dl>
 <dt>{{domxref("IDBTransaction.abort")}}</dt>
 <dd>Rolls back all the changes to objects in the database associated with this transaction. If this transaction has been aborted or completed, then this method throws an error event.</dd>
 <dt>{{domxref("IDBTransaction.objectStore")}}</dt>
 <dd>Returns an {{domxref("IDBObjectStore")}} object representing an <span class="internalDFN">object store</span> that is part of the <span class="internalDFN">scope</span> of this <span class="internalDFN">transaction</span>.</dd>
</dl>

<h2 id="Properties">Properties</h2>

<dl>
 <dt>{{domxref("IDBTransaction.db")}} {{readonlyInline}}</dt>
 <dd>The database connection with which this transaction is associated.</dd>
 <dt>{{domxref("IDBTransaction.mode")}} {{readonlyInline}}</dt>
 <dd>The mode for isolating access to data in the object stores that are in the scope of the transaction. For possible values, see the Constants section below. The default value is <code><a href="#const_read_only">readonly</a></code>.</dd>
 <dt>{{domxref("IDBTransaction.objectStoreNames")}} {{readonlyinline}}</dt>
 <dd>Returns a {{domxref("DOMStringList")}} of the names of {{domxref("IDBObjectStore")}} objects.</dd>
 <dt>{{domxref("IDBTransaction.error")}} {{readonlyInline}}</dt>
 <dd>Returns one of several types of error when there is an unsuccessful transaction. This property is <code>null</code> if the transaction is not finished, is finished and successfully committed, or was aborted with {{domxref("IDBTransaction.abort")}} function.</dd>
</dl>

<h3 id="Event_handlers">Event handlers</h3>

<dl>
 <dt>{{domxref("IDBTransaction.onabort")}} {{readonlyInline}}</dt>
 <dd>The event handler for the <code>abort</code> event, fired when the transaction is aborted.</dd>
 <dt>{{domxref("IDBTransaction.oncomplete")}} {{readonlyInline}}</dt>
 <dd>The event handler for the <code>complete</code> event, thrown when the transaction completes successfully.</dd>
 <dt>{{domxref("IDBTransaction.onerror")}} {{readonlyInline}}</dt>
 <dd>The event handler for the <code>error</code> event, thrown when the transaction fails to complete.</dd>
</dl>

<h2 id="Mode_constants">Mode constants</h2>

<div>
<div>{{ deprecated_header(13) }}</div>

<div class="warning">
<p>These constants are no longer available — they were removed in Gecko 25. You should use the string constants directly instead. ({{ bug(888598) }})</p>
</div>
</div>

<p>Transactions can have one of three modes:</p>

<table class="standard-table">
 <thead>
  <tr>
   <th scope="col">Constant</th>
   <th scope="col">Value</th>
   <th scope="col">Description</th>
  </tr>
 </thead>
 <tbody>
  <tr>
   <td><code><a>READ_ONLY</a></code></td>
   <td>
    <p>"readonly"</p>

    <p>(0 in Chrome)</p>
   </td>
   <td>
    <p>Allows data to be read but not changed.</p>
   </td>
  </tr>
  <tr>
   <td><code><a>READ_WRITE</a></code></td>
   <td>
    <p>"readwrite"</p>

    <p>(1 in Chrome)</p>
   </td>
   <td>Allows reading and writing of data in existing data stores to be changed.</td>
  </tr>
  <tr>
   <td><code><a>VERSION_CHANGE</a></code></td>
   <td>
    <p>"versionchange"</p>

    <p>(2 in Chrome)</p>
   </td>
   <td>Allows any operation to be performed, including ones that delete and create object stores and indexes. This mode is for updating the version number of transactions that were started using the <a href="/en-US/docs/IndexedDB/IDBDatabase#setVersion"><code>setVersion()</code></a> method of <a href="/en-US/docs/IndexedDB/IDBDatabase">IDBDatabase</a> objects. Transactions of this mode cannot run concurrently with other transactions.</td>
  </tr>
 </tbody>
</table>

<p>Even if these constants are now deprecated, you can still use them to provide backward compatibility if required (in Chrome <a href="https://peter.sh/2012/05/tab-sizing-string-values-for-indexeddb-and-chrome-21/">the change was made in version 21</a>). You should code defensively in case the object is not available anymore:</p>

<pre class="brush:js;">
var myIDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || { READ_WRITE: "readwrite" };</pre>

<h2 id="Example">Example</h2>

<p>In the following code snippet, we open a read/write transaction on our database and add some data to an object store. Note also the functions attached to transaction event handlers to report on the outcome of the transaction opening in the event of success or failure. For a full working example, see our <a href="https://github.com/mdn/to-do-notifications/">To-do Notifications</a> app (<a href="https://mdn.github.io/to-do-notifications/">view example live</a>.)</p>

<pre class="brush: js">
// Let us open our database
var DBOpenRequest = window.indexedDB.open("toDoList", 4);

DBOpenRequest.onsuccess = function(event) {
  note.innerHTML += '&lt;li&gt;Database initialised.&lt;/li&gt;';
    
  // store the result of opening the database in the db variable. This is used a lot below
  db = DBOpenRequest.result;
    
  // Run the addData() function to add the data to the database
  addData();
};

function addData() {
  // Create a new object ready for being inserted into the IDB
  var newItem = [ { taskTitle: "Walk dog", hours: 19, minutes: 30, day: 24, month: "December", year: 2013, notified: "no" } ];

  // open a read/write db transaction, ready for adding the data
  var transaction = db.transaction(["toDoList"], "readwrite");

  // report on the success of opening the transaction
  transaction.oncomplete = function(event) {
    note.innerHTML += '&lt;li&gt;Transaction completed: database modification finished.&lt;/li&gt;';
  };


  transaction.onerror = function(event) {
  note.innerHTML += '&lt;li&gt;Transaction not opened due to error. Duplicate items not allowed.&lt;/li&gt;';
  };

  // create an object store on the transaction
  var objectStore = transaction.objectStore("toDoList");

  // add our newItem object to the object store
  var objectStoreRequest = objectStore.add(newItem[0]);

  objectStoreRequest.onsuccess = function(event) {
    // report the success of our new item going into the database
    note.innerHTML += '&lt;li&gt;New item added to database.&lt;/li&gt;';
  };
};</pre>

<h2 id="Specifications">Specifications</h2>

<table class="standard-table">
 <tbody>
  <tr>
   <th scope="col">Specification</th>
   <th scope="col">Status</th>
   <th scope="col">Comment</th>
  </tr>
  <tr>
   <td>{{SpecName('IndexedDB', '#transaction', 'IDBTransaction')}}</td>
   <td>{{Spec2('IndexedDB')}}</td>
   <td>Initial definition</td>
  </tr>
 </tbody>
</table>

<h2 id="Browser_compatibility" name="Browser_compatibility">Browser compatibility</h2>

<div>{{CompatibilityTable}}</div>

<div id="compat-desktop">
<table class="compat-table">
 <tbody>
  <tr>
   <th>Feature</th>
   <th>Chrome</th>
   <th>Firefox (Gecko)</th>
   <th>Internet Explorer</th>
   <th>Opera</th>
   <th>Safari (WebKit)</th>
  </tr>
  <tr>
   <td>Basic support</td>
   <td>23{{property_prefix("webkit")}}<br />
    24[1]</td>
   <td>10 {{property_prefix("moz")}}<br />
    {{CompatGeckoDesktop("16.0")}}</td>
   <td>10, partial</td>
   <td>15</td>
   <td>7.1</td>
  </tr>
  <tr>
   <td>Available in workers</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatGeckoMobile("37.0")}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatUnknown}}</td>
  </tr>
  <tr>
   <td><code>objectStoreNames</code> property</td>
   <td>{{CompatChrome(48.0)}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatNo}}</td>
  </tr>
 </tbody>
</table>
</div>

<div id="compat-mobile">
<table class="compat-table">
 <tbody>
  <tr>
   <th>Feature</th>
   <th>Android</th>
   <th>Android Webview</th>
   <th>Firefox Mobile (Gecko)</th>
   <th>Firefox OS</th>
   <th>IE Phone</th>
   <th>Opera Mobile</th>
   <th>Safari Mobile</th>
   <th>Chrome for Android</th>
  </tr>
  <tr>
   <td>Basic support</td>
   <td>4.4</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatGeckoMobile("22.0")}}</td>
   <td>1.0.1</td>
   <td>10</td>
   <td>22</td>
   <td>8</td>
   <td>{{CompatVersionUnknown}}</td>
  </tr>
  <tr>
   <td>Available in workers</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatGeckoMobile("37.0")}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
  </tr>
  <tr>
   <td><code>objectStoreNames</code> property</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatChrome(48.0)}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatChrome(48.0)}}</td>
  </tr>
 </tbody>
</table>
</div>

<ul>
 <li>[1] Older versions of Chrome serialize all transactions. So even if you have only read-only transactions and no read-write transaction, your transactions are executed one at a time. Any subsequent transactions are not executed until all read-only transactions are completed. For the status, see <a href="https://crbug/64076">bug 64076</a>.</li>
</ul>

<h2 id="See_also">See also</h2>

<ul>
 <li><a href="/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB">Using IndexedDB</a></li>
 <li>Starting transactions: {{domxref("IDBDatabase")}}</li>
 <li>Using transactions: {{domxref("IDBTransaction")}}</li>
 <li>Setting a range of keys: {{domxref("IDBKeyRange")}}</li>
 <li>Retrieving and making changes to your data: {{domxref("IDBObjectStore")}}</li>
 <li>Using cursors: {{domxref("IDBCursor")}}</li>
 <li>Reference example: <a class="external" href="https://github.com/mdn/to-do-notifications/tree/gh-pages">To-do Notifications</a> (<a class="external" href="https://mdn.github.io/to-do-notifications/">view example live</a>.)</li>
</ul>
Revert to this revision