这篇翻译不完整。请帮忙从英语翻译这篇文章

IDBTransacation接口由IndexedDB API提供,异步事务使用数据库中的事件对象属性。所有的读取和写入数据均在事务中完成。由IDBDatabase发起事务,通过IDBTransaction 来设置事务的模式(例如:是否只读readonly或读写readwrite),以及通过IDBObjectStore来发起一个请求。同时你也可以使用它来中止事务。

Note that as of Firefox 40, IndexedDB transactions have relaxed durability guarantees to increase performance (see bug 1112702.) Previously in a readwrite transaction 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 IDBDatabase.transaction.

注意,事务在被创建的时候就已经开始,并非在发起第一个请求(IDBRequest)的时候。例如下面的例子:

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

在代码执行后,object store 应该包含值 "2", 因为 trans2 应该在 trans1 之后执行。

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

  • Abort due to bad requests, e.g. trying to add() the same key twice, or put() with the same index key with a uniqueness constraint. This causes an error on the request, which can bubble up to an error on the transaction, which aborts the transaction. Can be prevented by using preventDefault() on the error event on the request.
  • Explicit abort() call from script
  • Uncaught exception in request's success/error handler
  • I/O error (actual failure to write to disk, e.g. disk detached, or other OS/hardware failure)
  • Quota exceeded
  • User agent crash

 

Note: 此特性在 Web Worker 中可用。

属性

IDBTransaction.db 只读
当前事务所属的数据库连接。
IDBTransaction.error 只读
Returns a DOMException indicating the type of error that occured 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 IDBTransaction.abort function.
IDBTransaction.mode 只读
用于隔离事务作用域内的object store中数据访问的模式。下方的常量章节给出了所有可用的值。默认值是 readonly.
IDBTransaction.objectStoreNames 只读
Returns a DOMStringList of the names of IDBObjectStore objects.

Event handlers

IDBTransaction.onabort 只读
The event handler for the abort event, fired when the transaction is aborted. This can happen due to:
  • bad requests, e.g. trying to add() the same key twice, or put() with the same index key with a uniqueness constraint and there is no error handler on the request to call preventDefault() on the event,
  • an explicit abort() call from script
  • uncaught exception in request's success/error handler,
  • an I/O error (actual failure to write to disk, e.g. disk detached, or other OS/hardware failure), or
  • quota exceeded.
IDBTransaction.oncomplete 只读
The event handler for the complete event, thrown when the transaction completes successfully.
IDBTransaction.onerror 只读
The event handler for the error event, thrown when the transaction fails to complete.

方法

EventTarget继承

IDBTransaction.abort
放弃本次连接的transaction的所有修改,如果当前的transaction处于回滚完毕或完成状态,则会抛出一个错误事件。
IDBTransaction.objectStore
返回表示作为此事务作用域一部分的object store的 IDBObjectStore 对象。

模式常量

已废弃 Gecko 25 (Firefox 25 / Thunderbird 25 / SeaMonkey 2.22)
This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it.

这些常量将不再可用——它们在Gecko 25中被移除。 你应该直接使用字符串常量来作为替代。 (bug 888598)

Transactions 可使用以下三种模式中的一种:

常量 描述
READ_ONLY

"readonly"

(0 in Chrome)

允许读取数据,不改变。

READ_WRITE

"readwrite"

(1 in Chrome)

允许读取和写入现有数据存储,数据被改变。
VERSION_CHANGE

"versionchange"

(2 in Chrome)

允许执行任何操作,包括删除和创建对象存储和索引。
此模式是用于开始使用IDBDatabasesetVersion()方法更新版本号事务。 这种模式的事务无法与其它事务并发运行。
这种模式下的事务被称为“升级事务”。

即使目前这些常量已经被废弃,但如果你需要使用它,则需要提供向下兼容方案(in Chrome the change was made in version 21)。你应当防止出现对象不存在的情况:

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
Indexed Database API
IDBTransaction
Recommendation  

Browser compatibility

We're converting our compatibility data into a machine-readable JSON format. This compatibility table still uses the old format, because we haven't yet converted the data it contains. Find out how you can help!

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari (WebKit)
Basic support 23webkit
24
10 moz
16.0 (16.0)
10, partial 15 7.1
Feature Android Firefox Mobile (Gecko) Firefox OS IE Phone Opera Mobile Safari Mobile
Basic support 4.4 22.0 (22.0) 1.0.1 10 22 未实现

Known browser issues

Older versions of Google Chrome serialise 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 read-only transactions are completed. For the status, see bug 64076.

See also

文档标签和贡献者

此页面的贡献者: lightrabbit, dawangraoming, teoli, looch
最后编辑者: lightrabbit,