The background,

As the capabilities of the browser continue to increase, more and more sites are considering storing large amounts of data on the client side, which can reduce the amount of data retrieved from the server and bring it directly from the local.

Existing browser data storage schemes are not suitable for storing large amounts of data: cookies are less than 4KB in size, and each request is sent back to the server; LocalStorage is between 2.5MB and 10MB (depending on the browser), does not provide search, and cannot create custom indexes. So a new solution was needed, and this was the context in which IndexedDB was born.

Cookie, localStorage, sessionStorage three kinds of localStorage;

  • Cookie: A simple text file stored in a client, associated with a particular Web document, that holds information about the time the client accesses the Web document and is available to the client when it accesses the Web document again.
  • LocalStorage: Used to store the data of the entire website for a long time. The saved data does not expire until manual deletion. Property is read-only.
  • SessionStorage: The sessionStorage interface is similar to that of localStorage, but the life cycle of storing data is different from that of localStorage. Session literally means “Session”. It can only save some data in the current session, refresh the page data still exists. But when the page is closed, the data in sessionStorage will be cleared.

Ii. Basic features of IndexDB

  1. Key-value pair storage. IndexedDB uses an object Store internally to store data. All types of data can be stored directly, including JavaScript objects. In the object warehouse, data is stored as “key-value pairs”, and each data record has a corresponding primary key. The primary key is unique and cannot be duplicated, otherwise an error will be thrown.
  2. Asynchronous. IndexedDB does not lock the browser and users can still perform other operations, in contrast to LocalStorage, where operations are synchronous. Asynchronous design is designed to prevent massive data reads and writes from slowing down the performance of a web page.
  3. Support transactions. IndexedDB supports transaction, which means that if one of a series of steps fails, the entire transaction is cancelled and the database is rolled back to the state before the transaction occurred, without overwriting only a portion of the data.
  4. Homologous restriction. IndexedDB is subject to the same origin restriction, with each database corresponding to the domain name that created it. Web pages can only access databases under their own domain names, but not cross-domain databases.
  5. Large storage space. IndexedDB has much more storage space than LocalStorage, usually no less than 250MB or even no upper limit.
  6. Binary storage is supported. IndexedDB can store not only strings but also binary data (ArrayBuffer objects and Blob objects).

Basic concepts of IndexDB

1. IDBDatabase object

A database is a container for a series of related data. Each domain name (strictly speaking, protocol + domain name + port) can create as many databases as you want.

IndexedDB databases have an idea of versions. Only one version of the database can exist at a time. If you want to change the database structure (adding or deleting tables, indexes, or primary keys), you can only do this by upgrading the database version.

2. Object Stores: Each database contains several object stores. It is similar to a table in a relational database.

3. Data Records: Object repositories hold data records. Each record is similar to a row in a relational database, but has two parts: the primary key and the data body. The primary key used to create the default index must be different or an error will be reported. The primary key can be an attribute in the data record or can be specified as an increasing integer number.

4. Index: In order to speed up the retrieval of data, you can build indexes for different attributes in the object warehouse.

1. Transactions: data records are read, written, deleted and modified through transactions. The transaction object provides three events, error, Abort, and complete, to listen for the result of the operation

Four, common operations

1. IDBRequest object

The IDBRequest object represents an open database connection and is returned by the indexeddb.open () and indexeddb.deleteDatabase () methods. All database operations are done through this object.

Properties:

  • Idbrequest. readyState: Pending indicates that the operation is in progress, and done indicates that the operation is completing.
  • Idbrequest. result: Returns the result of the request. Reading this property is an error if the request fails and the result is unavailable.
  • Idbrequest. error: An error object is returned when the request fails.
  • Idbrequest. source: Returns the source of the request (such as an index object or ObjectStore).
  • Idbrequest.transaction: Returns the transaction currently in progress for the request, or null if no transaction is involved.
  • Idbrequest. onSUCCESS: Specifies a listening function for the SUCCESS event.
  • Idbrequest. onerror: Specifies a listener function for error events.

2, IDBDatabase

After successfully opening the data, you can retrieve an IDBDatabase object from the Result property of the IDBOpenDBRequest object, which represents the connected database. All subsequent operations to the database are done through this object.

Properties:

  • Idbdatabase. name: indicates the database name.
  • Idbdatabase. version: indicates the integer database version. This property is an empty string when the database is first created.
  • IDBDatabase. ObjectStoreNames: DOMStringList object (the set of strings), containing the current data of the names of all the object store.
  • Idbdatabase. onabort: Specifies the listener for the abort event (transaction abort).
  • Idbdatabase. onCLOSE: Specifies a listening function for the close event (unexpected database shutdown).
  • Idbdatabase. onERROR: Specifies a listener for error events (database access failures).
  • IDBDatabase. Onversionchange: database version changes triggered when (upgradeneeded events, or call with indexedDB. DeleteDatabase ()).

Methods:

  • Idbdatabase.close () : closes the database connection until all transactions are complete.
  • IDBDatabase. CreateObjectStore () : create stored objects of data warehouse, similar to a traditional relational database tables, return a IDBObjectStore object. This method can only be called in the versionchange event listener function.
  • IDBDatabase. DeleteObjectStore () : delete the specified object repository. This method can only be called in the versionchange event listener function.
  • Idbdatabase.transaction () : Returns an IDBTransaction transaction object.

3. IDBObjectStore object

The IDBObjectStore object corresponds to an object Store. IDBDatabase. CreateObjectStore () method returns a IDBObjectStore object.

Transaction () of the IDBDatabase object returns a transaction object whose objectStore() method returns the IDBObjectStore object, so you can use the following chained notation.

** Attribute: **

  • IDBObjectStore. IndexNames: returns an array of similar objects (DOMStringList), warehouse all index contains the current object.
  • Idbobjectstore. keyPath: Returns the primary key of the current object store.
  • Idbobjectstore. name: Returns the name of the current object store.
  • IDBObjectStore. Transaction: warehouse belonging to a transaction object returns the current object.
  • IDBObjectStore. AutoIncrement: Boolean, indicates whether the primary key is automatically incremented.

Methods:

  • Idbobjectstore.add () is used to add data to the object repository, returning an IDBRequest object. This method is only used to add data, and an error is reported if the primary key is the same, so you must use the PUT () method to update data.
  • The idBobjectStore.put () method updates the data record corresponding to a primary key and inserts a new record if the corresponding key value does not exist. This method returns an IDBRequest object.
  • Idbobjectstore.clear () deletes all records from the current object store. This method returns an IDBRequest object.
  • The idBobjectStore.delete () method is used to delete records for the specified primary key. This method returns an IDBRequest object.
  • The idBobjectStore.count () method is used to count the number of records. This method returns an IDBRequest object.
  • Idbobjectstore.getkey () is used to get the primary key. This method returns an IDBRequest object.
  • Idbobjectstore.get () is used to get the data record corresponding to the primary key. This method returns an IDBRequest object.
  • Idbobjectstore.getall () is used to get records from the object store. This method returns an IDBRequest object.
  • IDBObjectStore. GetAllKeys () is used to obtain all eligible primary key. This method returns an IDBRequest object.
  • The idBobjectStore.index () method returns the index object IDBIndex with the specified name.
  • IDBObjectStore. CreateIndex () method is used to create an index of the current database. This method can only be called from inside the VersionChange listener.
  • IDBObjectStore. DeleteIndex () method is used to delete the specified index. This method can only be called from inside the VersionChange listener.
  • IDBObjectStore. OpenCursor () is used to obtain a pointer to the object. Pointer objects can be used to iterate over data. This object is also asynchronous and has its own Success and error events for which you can specify listener functions.
  • IDBObjectStore. OpenKeyCursor () is used to obtain a pointer to the primary key object.

4. IDBTransaction object

The IDBTransaction object is used to operate database transactions asynchronously, and all read and write operations are performed through this object. The idbDatabase.Transaction () method returns an IDBTransaction object.

Properties:

  • Idbtransaction. db: returns IDBDatabase, the database object where the current transaction resides.
  • Idbtransaction. error: Returns an error for the current transaction. This method returns NULL if the transaction did not end, successfully ended, or was manually terminated.
  • Idbtransaction. mode: returns the mode of the current transaction. The default value is readonly (readonly) and the other value is readwrite.
  • IDBTransaction. ObjectStoreNames: returns a similar array object DOMStringList, members was the name of the object of the current transaction involves the warehouse.
  • Idbtransaction. onABORT: Specifies the listener function for the ABORT event (transaction interruption).
  • IDBTransaction. The oncomplete: specify the complete event (transaction success) surveillance function.
  • Idbtransaction. onERROR: Specifies a listener for error events (transaction failures).

Methods:

  • Idbtransaction.abort () : Terminates the current transaction and rolls back all changes that have been made.
  • IDBTransaction. ObjectStore (name) : returns the object of the specified name IDBObjectStore warehouse.

5. IDBIndex object

The idBobjectStore.index () method retrieves the IDBIndex object.

The IDBIndex object represents the index of the database, through which records in the database can be retrieved. The primary key of a data record is indexed by default. The IDBIndex object is mainly used to obtain an object through indexes other than the primary key.

IDBIndex is a persistent key-value pair store. The index is automatically updated whenever a data record is inserted, updated, or deleted from the referenced object library.

Properties:

  • Idbindex. name: indicates the name of the index.
  • Idbindex. objectStore: objectStore where the index resides.
  • IDBIndex. KeyPath: primary key of the index.
  • Idbindex. multiEntry: Boolean value for arrays with keyPath. If true, each member of the array will have one entry, otherwise each array will have only one entry.
  • Idbindex. unique: Boolean value indicating whether the same primary key is allowed when creating an index.
  • The IDBIndex object has the following methods, all of which are asynchronous and immediately return an IDBRequest object.
  • Idbindex.count () : Used to get the number of records. It can take a primary key or an IDBKeyRange object as an argument, in which case only the number of records that match the primary key is returned, otherwise the number of all records is returned.
  • Idbindex. get(key) : Used to obtain data records that match the specified primary key.
  • Idbindex. getKey(key) : Used to obtain the specified primary key.
  • Idbindex. getAll() : Used to retrieve all data records. It can take two optional arguments, the first to specify the primary key and the second to specify the number of records to return. If these two parameters are omitted, all records are returned. There is a performance impact because the browser must generate all objects upon successful retrieval. If the data set is large, the IDBCursor object is recommended.
  • Idbindex.getallkeys () : This method is similar to idbindex.getall () except that all primary keys are retrieved.
  • IDBIndex. OpenCursor () : Gets an IDBCursor object that walks over all the entries in the index.
  • Idbindex.openkeycursor () : This method is similar to idbindex.opencursor () except that the primary key of all entries is traversed.

Methods:

  • Idbindex.count () : Used to get the number of records. It can take a primary key or an IDBKeyRange object as an argument, in which case only the number of records that match the primary key is returned, otherwise the number of all records is returned.
  • Idbindex. get(key) : Used to obtain data records that match the specified primary key.
  • Idbindex. getKey(key) : Used to obtain the specified primary key.
  • Idbindex. getAll() : Used to retrieve all data records. It can take two optional arguments, the first to specify the primary key and the second to specify the number of records to return. If these two parameters are omitted, all records are returned. There is a performance impact because the browser must generate all objects upon successful retrieval. If the data set is large, the IDBCursor object is recommended.
  • Idbindex.getallkeys () : This method is similar to idbindex.getall () except that all primary keys are retrieved.
  • IDBIndex. OpenCursor () : Gets an IDBCursor object that walks over all the entries in the index.
  • Idbindex.openkeycursor () : This method is similar to idbindex.opencursor () except that the primary key of all entries is traversed.

6. IDBCursor object

IDBCursor object usually by IDBObjectStore. OpenCursor () method. IDBCursor objects represent pointer objects that are used to traverse records in a data warehouse (IDBObjectStore) or index (IDBIndex).

Properties:

  • Idbcursor. source: Returns the object repository or index being traversed.
  • Idbcursor. direction: indicates the direction of pointer traversal. There are four possible values: Next (iterating backwards from the beginning), NextUnique (iterating backwards from the beginning, repeating values only once), prev (iterating forwards from the tail), and prevUnique (iterating forwards from the tail, repeating values only once). This property by IDBObjectStore. OpenCursor () method of the second parameter specifies, once the specified cannot be changed.
  • Idbcursor. key: Returns the primary key of the current record.
  • Idbcursor. value: Returns the data value of the current record.
  • Idbcursor. primaryKey: returns the primaryKey of the current record. For a data warehouse (objectStore), this property is equivalent to idbcursor.key; For indexes, idbcursor. key returns the position value of the index, and this property returns the primary key of the data record.

Methods:

  • Idbcursor. advance(n) : Moves the cursor forward n positions.
  • Idbcursor.continue () : Moves the pointer forward one position. It can take a primary key as an argument and jump to that primary key.
  • IDBCursor. ContinuePrimaryKey () : this method requires two parameters, the first is the key, the second is the primaryKey, pointer to conform to the position of the two parameters.
  • Idbcursor.delete () : Used to delete records at the current location, returning an IDBRequest object. This method does not change the position of the pointer.
  • Idbcursor.update () : Used to update the record of the current position, returning an IDBRequest object. Its argument is the new value to write to the database.

7. IDBKeyRange object

The IDBKeyRange object represents a set of primary keys in the Object Store. Based on this set of primary keys, you can retrieve a set of records in a data warehouse or index.

The IDBKeyRange can contain only one value, or it can specify upper and lower limits. It has four static methods that specify the range of primary keys.

  • Idbkeyrange.lowerbound () : specifies the lowerBound.
  • Idbkeyrange.upperbound () : specifies the upperBound.
  • Idbkeyrange.bound () : specifies both upper and lower bounds.
  • Idbkeyrange.only () : specifies that only one value is included.

Refer to the link: www.ruanyifeng.com/blog/2018/0… www.jianshu.com/p/bb116c7a7… Wangdoc.com/javascript/…