1. Introduction

User agents need to store large numbers of objects locally in order to satisfy off-line data requirements of Web applications. [WEBSTORAGE] is useful for storing pairs of keys and their corresponding values. However, it does not provide in-order retrieval of keys, efficient searching over values, or storage of duplicate values for a key.

This specification provides a concrete API to perform advanced key-value data management that is at the heart of most sophisticated query processors. It does so by using transactional databases to store keys and their corresponding values (one or more per key), and providing a means of traversing keys in a deterministic order. This is often implemented through the use of persistent B-tree data structures that are considered efficient for insertion and deletion as well as in-order traversal of very large numbers of data records.

In the following example, the API is used to access a “library” database that holds books stored by their “isbn” attribute. Additionally, an index is maintained on the “title” attribute of the objects stored in the object store. This index can be used to look up books by title, and enforces a uniqueness constraint. Another index is maintained on the “author” attribute of the objects, and can be used to look up books by author.

A connection to the database is opened. If the “library” database did not already exist, it is created and an event handler creates the object store and indexes. Finally, the opened connection is saved for use in subsequent examples.

  1. var request = indexedDB.open("library");
  2.  
  3. request.onupgradeneeded = function() {
  4. // The database did not previously exist, so create object stores and indexes.
  5. var db = request.result;
  6. var store = db.createObjectStore("books", {keyPath: "isbn"});
  7. var titleIndex = store.createIndex("by_title", "title", {unique: true});
  8. var authorIndex = store.createIndex("by_author", "author");
  9.  
  10. // Populate with initial data.
  11. store.put({title: "Quarry Memories", author: "Fred", isbn: 123456});
  12. store.put({title: "Water Buffaloes", author: "Fred", isbn: 234567});
  13. store.put({title: "Bedrock Nights", author: "Barney", isbn: 345678});
  14. };
  15.  
  16. request.onsuccess = function() {
  17. db = request.result;
  18. };

The following example populates the database using a transaction.

  1. var tx = db.transaction("books", "readwrite");
  2. var store = tx.objectStore("books");
  3.  
  4. store.put({title: "Quarry Memories", author: "Fred", isbn: 123456});
  5. store.put({title: "Water Buffaloes", author: "Fred", isbn: 234567});
  6. store.put({title: "Bedrock Nights", author: "Barney", isbn: 345678});
  7.  
  8. tx.oncomplete = function() {
  9. // All requests have succeeded and the transaction has committed.
  10. };

The following example looks up a single book in the database by title using an index.

  1. var tx = db.transaction("books", "readonly");
  2. var store = tx.objectStore("books");
  3. var index = store.index("by_title");
  4.  
  5. var request = index.get("Bedrock Nights");
  6. request.onsuccess = function() {
  7. var matching = request.result;
  8. if (matching !== undefined) {
  9. // A match was found.
  10. report(matching.isbn, matching.title, matching.author);
  11. } else {
  12. // No match was found.
  13. report(null);
  14. }
  15. };

The following example looks up all books in the database by author using an index and a cursor.

  1. var tx = db.transaction("books", "readonly");
  2. var store = tx.objectStore("books");
  3. var index = store.index("by_author");
  4.  
  5. var request = index.openCursor(IDBKeyRange.only("Fred"));
  6. request.onsuccess = function() {
  7. var cursor = request.result;
  8. if (cursor) {
  9. // Called for each matching record.
  10. report(cursor.value.isbn, cursor.value.title, cursor.value.author);
  11. cursor.continue();
  12. } else {
  13. // No more matching records.
  14. report(null);
  15. }
  16. };

The following example shows how errors could be handled when a request fails.

  1. var tx = db.transaction("books", "readwrite");
  2. var store = tx.objectStore("books");
  3. var request = store.put({title: "Water Buffaloes", author: "Slate", isbn: 987654});
  4. request.onerror = function(event) {
  5. // The uniqueness constraint of the "by_title" index failed.
  6. report(request.error);
  7. // Could call event.preventDefault() to prevent the transaction from aborting.
  8. };
  9. tx.onabort = function() {
  10. // Otherwise the transaction will automatically abort due the failed request.
  11. report(tx.error);
  12. };

The database connection can be closed when it is no longer needed.

  1. db.close();

In the future, the database might have grown to contain other object stores and indexes. The following example shows one way to handle migrating from an older version of the database.

  1. var request = indexedDB.open("library", 3); // Request version 3.
  2.  
  3. request.onupgradeneeded = function(event) {
  4. var db = request.result;
  5. if (event.oldVersion < 1) {
  6. // Version 1 is the first version of the database.
  7. var store = db.createObjectStore("books", {keyPath: "isbn"});
  8. var titleIndex = store.createIndex("by_title", "title", {unique: true});
  9. var authorIndex = store.createIndex("by_author", "author");
  10. }
  11. if (event.oldVersion < 2) {
  12. // Version 2 introduces a new index of books by year.
  13. var bookStore = request.transaction.objectStore("books");
  14. var yearIndex = bookStore.createIndex("by_year", "year");
  15. }
  16. if (event.oldVersion < 3) {
  17. // Version 3 introduces a new object store for magazines with two indexes.
  18. var magazines = db.createObjectStore("magazines");
  19. var publisherIndex = magazines.createIndex("by_publisher", "publisher");
  20. var frequencyIndex = magazines.createIndex("by_frequency", "frequency");
  21. }
  22. };
  23.  
  24. request.onsuccess = function() {
  25. db = request.result; // db.version will be 3.
  26. };

A single database can be used by multiple clients (pages and workers) simultaneously — transactions ensure they don’t clash while reading and writing. If a new client wants to upgrade the database (via the “[upgradeneeded](#request-upgradeneeded)“ event), it cannot do so until all other clients close their connection to the current version of the database.

To avoid blocking a new client from upgrading, clients can listen for the version change event. This fires when another client is wanting to upgrade the database. To allow this to continue, react to the “versionchange“ event by doing something that ultimately closes this client’s connection to the database.

One way of doing this is to reload the page:

  1. db.onversionchange = function() {
  2. // First, save any unsaved data:
  3. saveUnsavedData().then(function() {
  4. // If the document isn’t being actively used, it could be appropriate to reload
  5. // the page without the user’s interaction.
  6. if (!document.hasFocus()) {
  7. location.reload();
  8. // Reloading will close the database, and also reload with the new JavaScript
  9. // and database definitions.
  10. } else {
  11. // If the document has focus, it can be too disruptive to reload the page.
  12. // Maybe ask the user to do it manually:
  13. displayMessage("Please reload this page for the latest version.");
  14. }
  15. });
  16. };
  17.  
  18. function saveUnsavedData() {
  19. // How you do this depends on your app.
  20. }
  21.  
  22. function displayMessage() {
  23. // Show a non-modal message to the user.
  24. }

Another way is to call the connection‘s [close()](#dom-idbdatabase-close) method. However, you need to make sure your app is aware of this, as subsequent attempts to access the database will fail.

  1. db.onversionchange = function() {
  2. saveUnsavedData().then(function() {
  3. db.close();
  4. stopUsingTheDatabase();
  5. });
  6. };
  7.  
  8. function stopUsingTheDatabase() {
  9. // Put the app into a state where it no longer uses the database.
  10. }

The new client (the one attempting the upgrade) can use the "blocked" event to detect if other clients are preventing the upgrade from happening. The "blocked" event fires if other clients still hold a connection to the database after their "versionchange" events have fired.

  1. var request = indexedDB.open("library", 4); // Request version 4.
  2. var blockedTimeout;
  3.  
  4. request.onblocked = function() {
  5. // Give the other clients time to save data asynchronously.
  6. blockedTimeout = setTimeout(function() {
  7. displayMessage("Upgrade blocked - Please close other tabs displaying this site.");
  8. }, 1000);
  9. };
  10.  
  11. request.onupgradeneeded = function(event) {
  12. clearTimeout(blockedTimeout);
  13. hideMessage();
  14. // ...
  15. };
  16.  
  17. function hideMessage() {
  18. // Hide a previously displayed message.
  19. }

The user will only see the above message if another client fails to disconnect from the database. Ideally the user will never see this.