docs.rodeo

MDN Web Docs mirror

IDBTransaction

{{APIRef("IndexedDB")}}  {{AvailableInWorkers}} 

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 use {{domxref("IDBDatabase")}}  to start transactions, IDBTransaction to set the mode of the transaction (e.g. is it readonly or readwrite), and you access an {{domxref("IDBObjectStore")}}  to make a request. You can also use an IDBTransaction object to abort transactions.

{{InheritanceDiagram}} 

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

const trans1 = db.transaction("foo", "readwrite");
const trans2 = db.transaction("foo", "readwrite");
const objectStore2 = trans2.objectStore("foo");
const objectStore1 = trans1.objectStore("foo");
objectStore2.put("2", "key");
objectStore1.put("1", "key");

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

A transaction alternates between active and inactive states between event loop tasks. It’s active in the task when it was created, and in each task of the requests’ success or error event handlers. It’s inactive in all other tasks, in which case placing requests will fail. If no new requests are placed when the transaction is active, and there are no other outstanding requests, the transaction will automatically commit.

Transaction failures

Transactions can fail for a fixed number of reasons, all of which (except the user agent crash) will trigger an abort callback:

Firefox durability guarantees

Note that as of Firefox 40, IndexedDB transactions have relaxed durability guarantees to increase performance (see Firefox bug 1112702.) Previously in a readwrite transaction, a {{domxref("IDBTransaction.complete_event","complete")}}  event 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")}} .

Instance properties

Instance methods

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

Events

Listen to these events using addEventListener() or by assigning an event listener to the oneventname property of this interface.

Mode constants

{{Deprecated_Header}} 

[!WARNING] These constants are no longer available — they were removed in Gecko 25. You should use the string constants directly instead. (Firefox 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. Transactions of this mode cannot run concurrently with other transactions. Transactions in this mode are known as "upgrade 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:

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

Examples

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).

const note = document.getElementById("notifications");

// an instance of a db object for us to store the IDB data in
let db;

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

DBOpenRequest.onsuccess = (event) => {
  note.appendChild(document.createElement("li")).textContent =
    "Database initialized.";

  // store the result of opening the database in the db
  // variable. This is used a lot below
  db = DBOpenRequest.result;

  // Add the data to the database
  addData();
};

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

  // open a read/write db transaction, ready to add data
  const transaction = db.transaction(["toDoList"], "readwrite");

  // report on the success of opening the transaction
  transaction.oncomplete = (event) => {
    note.appendChild(document.createElement("li")).textContent =
      "Transaction completed: database modification finished.";
  };

  transaction.onerror = (event) => {
    note.appendChild(document.createElement("li")).textContent =
      "Transaction not opened due to error. Duplicate items not allowed.";
  };

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

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

  objectStoreRequest.onsuccess = (event) => {
    // report the success of the request (this does not mean the item
    // has been stored successfully in the DB - for that you need transaction.oncomplete)
    note.appendChild(document.createElement("li")).textContent =
      "Request successful.";
  };
}

Specifications

{{Specifications}} 

Browser compatibility

{{Compat}} 

See also

In this article

View on MDN