Indexeddb: Database in your browser

With the continuous enhancement of browser functions, more and more websites are considering storing large amounts of data on the client. This consideration is to obtain data directly from the local, reducing the network resources consumed by obtaining data from the server.

The original browser data storage solutions are not suitable for storing large amounts of data. The size of the cookie does not exceed 4KB, and each request will be sent to the server; the size of WebStorage (LocalStorage, SessionStorage) is between 2.5MB and 10MB (various browsers are different, generally can be considered as about 5MB), and does not provide search Function, it is also not possible to create a custom index. Therefore IndexedDB was born, a new browser storage solution provided by H5.

What IndexedDB

In layman’s terms, IndexedDB is provided by the browser A local database can be created and manipulated by web scripts. IndexedDB allows to store a large amount of data, while providing an excuse for searching and creating indexes. These are things that Cookie and WebStorage do not have. As far as the database is concerned, IndexedDB is not a relational database (SQL query statements are not supported), and is closer to a NoSQL database.

Indexed has the following characteristics:

1. Key-value pair storage. IndexedDB internally uses Object Store to store data. All types of data can be stored directly, including JavaScript objects. In the object warehouse, data is stored in the form of key-value pairs, and each data record has a corresponding primary key, and this primary key is unique, and an error will be thrown once it is repeated.

2. Asynchronous. When IndexedDB is operated, the browser will not be locked (the thread will not hang), and the user can still perform other operations. This is in contrast to LocalStorage, which operates synchronously (threads will hang). The asynchronous design is to prevent the read and write of large amounts of data from slowing down the performance of the web page.

3. Support affairs. IndexedDB supports transactions (Transaction). This means that as long as one step in a series of operations fails, the entire transaction will be cancelled, and the database will be rolled back to the state before the transaction occurred. There is no situation where only part of the data is overwritten.

4. Same-origin policy. IndexedDB is restricted by the browser’s same-origin policy, and each database corresponds to the domain name that created it. Web pages can only access databases under their own domain names, and cannot access cross-domain databases.

5. Large storage space. The storage space of IndexedDB is much larger than that of WebStorage, generally not less than 250MB, and there is even no upper limit.

6. Supports binary storage. IndexedDB can store not only strings, but also binary data (ArrayBuffer and Blob objects).

Some main concepts in Indexed

IndexedDB is a complex The API involves many concepts. It abstracts different entities into object interfaces. Learning this API is actually learning the various object interfaces it provides.

< /tr>

Database IDBDatabase object
Object Warehouse IDBObjectStore object
Index IDBIndex object
Transaction IDBTransaction object
Operation request IDBRequest object
Pointer IDBCursor object
Primary key collection IDBKeyRange object

Here are some main concepts:

1. Database. A database is a container for a series of related data. Any number of databases can be created for each domain name. In addition, there is a concept of version in the IndexedDB database, and only one version of the database can exist at the same time. If you want to modify the structure of the database (add tables or delete tables, indexes, and primary keys), you can only do so by upgrading the database version.

2. Object warehouse. Each database contains several object warehouses, which are similar to tables in relational databases.

3. Data logging. The object warehouse stores data records. Each record is similar to a row in a relational database, but only has two parts: the primary key and the data body. The primary key is used to create the default index and must be different, otherwise an error will be reported. The primary key can be an attribute in the real data record, or it can be specified as an incremental integer number. The data body can be any data type and is not limited to objects.

4. Index. In order to speed up data indexing, different attributes can be indexed in the object warehouse.

5. Affairs. The reading, writing, and deletion of data records must be completed through transactions. The transaction object provides three events of error, abort and complete to monitor the result of the operation.

Common operations of IndexedDB

Here are the common operations of IndexedDB database Simple example.

1. Open the database

The first step to use IndexedDB is to open the database, use indexed.open ()method.

var request = window.indexedDB.open(databaseName, version);

< /div>

This method accepts two parameters. The first parameter is a string, which represents the database name. If the specified database does not exist, a new database will be created. The second parameter is an integer, which represents the version of the database. If omitted, the existing database version will be opened. When creating a new database, the default version is 1.

This method will return an IDBRequest object. This object can handle the operation result of opening the database through onerror, onsuccess and onupgradeneeded events.

The onerror event indicates a failure to open the database.

request.onerror = function (event) {

console.log(
‘Database opening error’);
};

The onsuccess event indicates that the database is successfully opened.

request.onsuccess = function (event) {

var db = request.result;
console.log(
‘Database opened successfully’, db);
};

onupgradeneeded event, if the specified version number is greater than the actual version number of the database, a database upgrade event will occur.

request.onupgradeneeded = function (event) {

var db = event.target.result;
}

2. New database

New The database is the same operation as opening the database. If the specified database does not exist, a new database will be created. The difference is that opening a database triggers the onsuccess event, while creating a new database triggers the onupgradeneeded event, because the version is created from scratch at this time.

Usually the first thing after creating a new database is to create a new object warehouse (new table).

var db;

request.onupgradeneeded
= function(event) {
db
= event.target.result;
var objectStore = db.createObjectStore('yanggb', {keyPath:'id'});
}

In the above code, after the database is successfully created, a table called yanggb will be added, and the primary key is id.

A better way is to first judge whether the following table exists, and then add it if it does not exist.

var db;

request.onupgradeneeded
= function(event) {
db
= event.target.result;
var objectStore;
if (!db.objectStoreNames.contains('yanggb')) {
objectStore
= db.createObjectStore(‘yanggb’, {keyPath: ‘id’});
}
}

The primary key (key) is an attribute that is indexed by default. If the data record does not have an attribute suitable for the primary key, you can also let IndexedDB automatically generate the primary key. The following code specifies that the primary key is an increasing integer.

var objectStore = db.createObjectStore('yanggb', {autoIncrement: true});

After creating a new object warehouse, you can create an index in the next step.

var db;

request.onupgradeneeded
= function(event) {
db
= event.target.result;
var objectStore;
if (!db.objectStoreNames.contains('yanggb')) {
objectStore
= db.createObjectStore(‘yanggb’, {keyPath: ‘id’});
objectStore.createIndex(
'index_book','book', {unique: false});
objectStore.createIndex(
'index_email','email', {unique: true});
}
}

The three parameters of IDBObject.createIndex() are the index name, the attribute where the index is located, and the configuration object (indicating whether the attribute can contain duplicate value).

3. New data

New data refers to writing data to the object warehouse Recording needs to be done through the transaction object.

function addRecord() {

var request = db.transaction(['yanggb'],'readwrite')
.objectStore(
‘yanggb‘)
.add({id:
1, book: ‘eleven kinds of loneliness’, email: ‘[email protected]‘});

request.onsuccess
= function (event) {
console.log(
‘Data written successfully!’);
};

request.onerror
= function (event) {
console.log(
‘Failed to write data!’);
}
}

In the above code, writing data requires a new transaction. You must specify the table name and operation mode (read-only read or read-write readwrite) when creating a new one. After creating a new transaction, you can get the IDBObjectStore object through the IDBTransaction.objectStore(name) method, and then write a row of records to the table through the add() method of the table object.

This write operation is an asynchronous operation. By monitoring the success event and error event of the connection object, you can know whether the write is successful or perform corresponding follow-up operations.

4. Reading data

Reading data is also done through transaction objects.

function getRecord() {

var transaction = db.transaction([‘yanggb‘]);
var objectStore = transaction.objectStore(‘yanggb‘);
var request = objectStore.get(1);

request.onerror
= function(event) {
console.log(
‘Transaction failed’);
};

request.onsuccess
= function(event) {
if (request.result) {
console.log(
‘book: ‘+ request.result.book);
console.log(
‘email: ‘+ request.result.email);
}
else {
console.log(
‘No data record obtained!’);
}
};
}

The IDBObjectStore.get() method is used to read data and receives a parameter, which is the value of the primary key.

5. Traverse data

If you want to traverse all data records in the data warehouse, you need to use pointers Object IDBCursor.

function getRecords() {

var objectStore = db.transaction('yanggb').objectStore('yanggb');

objectStore.openCursor().onsuccess
= function (event) {
var cursor = event.target.result;

if (cursor) {
console.log(
‘id: ‘+ cursor.key);
console.log(
‘book: ‘+ cursor.value.book);
console.log(
‘email: ‘+ cursor.value.email);
cursor.
continue();
}
else {
console.log(
‘There is no more data!’);
}
};
}

Here, the operation of obtaining data records is completed in the onsuccess monitoring event in the IDBCursor object.

6. Update the data

Update the data to use the put() method of the IDBObjectStore object.

function updateRecord() {

var request = db.transaction(['yanggb'],'readwrite')
.objectStore(
‘yanggb‘)
.put({id:
1, book: ‘yanggb chasing the kite’, email: ‘[emailprotected]‘});

request.onsuccess
= function (event) {
console.log(
‘Data update successfully!’);
};

request.onerror
= function (event) {
console.log(
‘Data update failed’);
}
}

In the above code, the IDBObject.put() method will automatically update the record whose primary key is 1.

7. Deleting data

To delete data, use the delete() method of the IDBObjectStore object.

function remove() {

var request = db.transaction(['yanggb'],'readwrite')
.objectStore(
‘yanggb‘)
.
delete(1);

request.onsuccess
= function (event) {
console.log(
‘Data deleted successfully’);
};
}

The IDBObjectStore.delete() method is used to delete data and accepts a parameter whose value is the value of the primary key.

8. Use index

The meaning of index is that you can quickly get data records through any field. If you don’t build an index, you can only search for the primary key (value from the primary key) by default. The book field has been indexed when creating the above table, so the corresponding data record can be found through the book field.

function searchRecordByIndexOfBook() {

var transaction = db.transaction(['yanggb'],'readonly');
var store = transaction.objectStore(‘yanggb‘);
var index = store.index(‘book‘);
var request = index.get('yanggb chasing the kite') ;

request.onsuccess
= function (e) {
var result = e.target.result;
if (result) {
console.log(
‘Find the corresponding data!’);
}
else {
console.log(
‘No corresponding data found!’);
}
}
}

If you want to learn more, you can check the API on the official website: https://developer.mozilla.org/en-US/docs/ Web/API/IndexedDB_API.

“Don’t frown if I sing enough.”

var request = window.indexedDB.open(databaseName, version);

request.onerror = function  (event) {

console.log(
‘Database opening error’);
};

request.onsuccess = function (event) {

var db = request.result;
console.log(
‘Database opened successfully’, db);
};

request.onupgradeneeded = function (event) {

var db = event.target.result;
}

var db;

request.onupgradeneeded
= function(event) {
db
= event.target.result;
var objectStore = db.createObjectStore('yanggb', {keyPath:'id'});
}

var db;

request.onupgradeneeded
= function(event) {
db
= event.target.result;
var objectStore;
if (!db.objectStoreNames.contains('yanggb')) {
objectStore
= db.createObjectStore(‘yanggb’, {keyPath: ‘id’});
}
}

var objectStore = db.createObjectStore('yanggb', {autoIncrement: true});

var  db;

request.onupgradeneeded
= function(event) {
db
= event.target.result;
var objectStore;
if (!db.objectStoreNames.contains('yanggb')) {
objectStore
= db.createObjectStore(‘yanggb’, {keyPath: ‘id’});
objectStore.createIndex(
'index_book','book', {unique: false});
objectStore.createIndex(
'index_email','email', {unique: true});
}
}

function addRecord() {

var request = db.transaction(['yanggb'],'readwrite')
.objectStore(
‘yanggb‘)
.add({id:
1, book: ‘eleven kinds of loneliness’, email: ‘[email protected]‘});

request.onsuccess
= function (event) {
console.log(
‘Data written successfully!’);
};

request.onerror
= function (event) {
console.log(
‘Failed to write data!’);
}
}

function getRecord() {

var transaction = db.transaction([‘yanggb‘]);
var objectStore = transaction.objectStore(‘yanggb‘);
var request = objectStore.get(1);

request.onerror
= function(event) {
console.log(
‘Transaction failed’);
};

request.onsuccess
= function(event) {
if (request.result) {
console.log(
‘book: ‘+ request.result.book);
console.log(
‘email: ‘+ request.result.email);
}
else {
console.log(
‘No data record obtained!’);
}
};
}

function getRecords() {

var objectStore = db.transaction('yanggb').objectStore('yanggb');

objectStore.openCursor().onsuccess
= function (event) {
var cursor = event.target.result;

if (cursor) {
console.log(
‘id: ‘+ cursor.key);
console.log(
‘book: ‘+ cursor.value.book);
console.log(
‘email: ‘+ cursor.value.email);
cursor.
continue();
}
else {
console.log(
‘There is no more data!’);
}
};
}

function updateRecord() {

var request = db.transaction(['yanggb'],'readwrite')
.objectStore(
‘yanggb‘)
.put({id:
1, book: ‘yanggb chasing the kite’, email: ‘[emailprotected]‘});

request.onsuccess
= function (event) {
console.log(
‘Data update successfully!’);
};

request.onerror
= function (event) {
console.log(
‘Data update failed’);
}
}

function remove() {

var request = db.transaction(['yanggb'],'readwrite')
.objectStore(
‘yanggb‘)
.
delete(1);

request.onsuccess
= function (event) {
console.log(
‘Data deleted successfully’);
};
}

function searchRecordByIndexOfBook() {

var transaction = db.transaction(['yanggb'],'readonly');
var store = transaction.objectStore(‘yanggb‘);
var index = store.index(‘book‘);
var request = index.get('yanggb chasing the kite') ;

request.onsuccess
= function (e) {
var result = e.target.result;
if (result) {
console.log(
‘Find the corresponding data!’);
}
else {
console.log(
‘No corresponding data found!’);
}
}
}

Leave a Comment

Your email address will not be published.