Indexeddb 简明教程
IndexedDB - Transactions
事务是一组操作,这些操作要么全部成功,要么全部失败。例如,如果我们通过 UPI 向商家付款,但交易被拒绝,那该笔钱必须退回发送者的帐户。事务维持这种完整性。
A transaction is a group of operations, that should either all succeed, or all fail. For example, if we pay from UPI to a merchant and the transaction declines then the money must fall back to the senders' account. A transaction maintains this integrity.
以下是如何开启事务的语法:
Following is the syntax for opening a transaction −
db.transaction(store[, type]);
此处的存储是我们要在其中执行事务的对象存储。事务的类型有两种:
The store here is the object store where we want to do the transaction. The type of the transaction is of 2 types −
-
read-only − can only read, by default it is given.
-
read-write − we can only read and write the data but we cannot create, remove or alter it from object stores.
Transaction life cycle
事务是对象存储之间执行任何操作的连接。每个事务都有一个状态,该状态可以是:
The transaction is a connection between object stores to perform any operations. Each transaction has a state which can be −
-
active − When a transaction is first created. or when a request is associated with a transaction. New requests can be made against the transaction when it is in this state.
-
inactive − A transaction is in this state after control returns to the event after its creation. No requests can be made against the transaction when it is in this state.
-
committing − Once all the requests associated with a transaction are completed then it attempts to commit. During the commit state, no new requests can be made.
-
finished − After a transaction is committed or aborted then it is in the finished state. During the finished state, no new requests can be made.
The lifetime of a transaction
会形成一个具有范围和模式的事务。当事务生成后,其状态最初是激活的。
A transaction with a scope and a mode is formed. A transaction’s state is originally active when it is generated.
-
To begin the transaction, the implementation must queue a task.
-
A success or, error event will be fired when each request connected with a transaction is handled. The transaction state is set to active when the event is sent, allowing subsequent requests to be made against the transaction. The transaction’s status is set to inactive once the event dispatch is completed.
-
A transaction can be canceled at any point before it is completed, even if it isn’t currently active or hasn’t begun.
-
When all requests made against the database are successful, the implementation must attempt to commit the transaction.
-
When a transaction is committed or aborted its state is set to finish.
Transaction scheduling
当事务可以启动时,有一些限制。
When a transaction can be started, there are some limitations.
-
When there is no read or write transactions that: a. were established before transactions tx b. have an overlapping scope with tx c. are not in a final state, a read-only transaction tx can commence.
-
A read/write-only transaction tx can begin when there are no other transactions that − were formed before tx,have an overlapping scope with tx, orare not in a completed state.
Upgrade transactions
模式为 " versionchange " 的事务是升级事务。
A transaction with the mode "versionchange" is an upgrade transaction.
对象存储和数据库中的索引可以使用升级操作进行创建、重命名和删除。
Object stores and indexes in a database can be created, renamed, and deleted using upgrade operations.
如果给出的版本大于当前版本,则在打开与数据库的连接后完成运行升级事务的步骤时自动生成升级事务。在 upgradeneeded 事件处理程序中,此事务将处于活动状态。
If a version greater than the current version is given, an upgrade transaction is automatically produced when completing the steps to run an upgrade transaction after a connection to a database is opened. Within the upgradeneeded event handler, this transaction will be active.
Committing a transaction
必须完成以下步骤才能提交事务 -
The following steps must be completed to commit a transaction −
-
The transaction state is first set to committing.
-
Wait until all of the transaction requests on the list have been processed.
-
Abort the transaction if an error occurs.
-
If the transaction is an upgrade transaction, set the database upgrade transaction’s transactions connections to NULL.
-
Change the transaction state to complete.
-
fire the transaction’s entire event
-
If a transaction is an upgrade transaction, set the request’s transaction to null and make the request that is associated with the transaction.
Syntax
transaction.commit()
尝试提交事务。将允许所有挂起请求完成,但不会接受任何新请求。
Attempts to commit the transaction. All pending requests will be allowed to complete, but no new requests will be accepted.
如果挂起的请求失败,则事务将中止。成功请求的成功事件仍将触发,但在事件处理程序中抛出异常不会中止事务,调用 preventDefault() 不会阻止事务中止。
The transaction will abort if a pending request fails. The success events for successful requests will still fire, but throwing an exception in an event handler will not abort the transaction calling preventDefault() will not prevent the transaction from aborting.
Event Handlers
各种事件处理程序属性如下所示
Various event handler attributes are as follows
attribute EventHandler onabort;
attribute EventHandler oncomplete;
attribute EventHandler onerror;
Transactions Example
下面给出了一个简单的 JavaScript 程序来演示事务的使用 -
A simple JavaScript program to demonstrate the usage of a transaction is given below −
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<script>
const request = indexedDB.open("botdatabase",1);
request.onupgradeneeded = function(){
const db = request.result;
const store = db.createObjectStore("bots",{ keyPath: "id"});
}
request.onsuccess = function(){
document.write("database opened successfully");
const db = request.result;
const transaction=db.transaction("bots","readwrite");
const store = transaction.objectStore("bots");
store.add({id: 1, name: "jason",branch: "IT"});
store.add({id: 2, name: "praneeth",branch: "CSE"});
store.add({id: 3, name: "palli",branch: "EEE"});
store.add({id: 4, name: "abdul",branch: "IT"});
store.put({id: 4, name: "deevana",branch: "CSE"});
transaction.oncomplete = function(){
document.write("transaction complete");
db.close;
};
}
</script>
</body>
</html>
Output
database opened successfully
transaction complete
在这里创建事务,只有在创建事务时才能将数据添加到对象存储中,最终在事务完成后,我们关闭数据库。
Here a transaction is created, only when a transaction is created can we add data into the object store and finally after the transaction is complete we close the database.
Example
以下示例演示了一个事务属性 oncomplete 的用法 -
The following example shows the usage of a transaction attribute oncomplete −
function student(db, names) {
let transaction = db.transaction(['names'], 'readwrite');
let store = transaction.objectStore('names');
for (let i = 0; i < messages.length; i++) {
store.add({text: names[i]});
}
transaction.oncomplete = function()
{document.write('transaction complete')};
}
Abort transactions
要中止事务,请按照以下步骤操作 -
To abort a transaction, follow these steps −
-
All transaction-related modifications to the database are undone.
-
Changes in object stores, indexes, and versions are likewise reverted during upgrade transactions.
-
Complete the transaction state.
-
Set transactions error to error if the error is not null.
-
Set the request processed flag to true for each request in the transactions request list.
-
Set the requests done flag to true and the results to define.
-
If the transaction is an upgrade transaction, set the upgrade transaction associated with the transaction’s connection to null.
-
Create an abort at transaction event with the bubbles attribute set to true.
-
If the transaction is an upgrade transaction, assume that request is the transaction’s open request.