Sunday, October 2, 2011

Indexed DB: Creating, opening and deleting a database

In my last post I provided some more information about the structure of the Indexed DB database. Today, I will dive into code and tell you how to create, open and delete a database. There are some small differences between the browsers, but I will handle that at the specific parts of code.

The code I will show will be the Asynchronous implementation of the API. In my previous post I have said no browser does implement the synchronous API, but I was wrong. The IE 10 Preview 3 also implements the Synchronous implementation, but you should only use it in combination with web workers, because it freezes the UI if you don’t.

Initializing the Indexed DB API

First things first: the Indexed DB API is still in draft, so this means the unified Indexed DB property on the window element isn’t implemented yet. Every browser uses his on prefix to use the API, but we can assign this to the Indexed DB property. This gives us a way to us the Indexed DB on the same way.

Initializing the Firefox implementation

if (window.mozIndexedDB) {
            window.indexedDB = window.mozIndexedDB;
            window.IDBKeyRange = window.IDBKeyRange;
            window.IDBTransaction = window.IDBTransaction;
}

Initializing the Chrome implementation

if (window.webkitIndexedDB) {
            window.indexedDB = window.webkitIndexedDB;
            window.IDBKeyRange = window.webkitIDBKeyRange;
            window.IDBTransaction = window.webkitIDBTransaction;
}

Initializing the IE 10 Preview 3 implementation (You’ll need to be running the Windows 8 Developer Preview to run this)

if (window.msIndexedDB) {
            window.indexedDB = window.msIndexedDB;
}

Initializing the IE prototype implementation

if (navigator.appName == 'Microsoft Internet Explorer') {
            window.indexedDB = new ActiveXObject("SQLCE.Factory.4.0");
            window.indexedDBSync = new ActiveXObject("SQLCE.FactorySync.4.0");

            if (window.JSON) {
                window.indexedDB.json = window.JSON;
                window.indexedDBSync.json = window.JSON;
            } else {
                var jsonObject = {
                    parse: function (txt) {
                        if (txt === "[]") return [];
                        if (txt === "{}") return {};
                        throw { message: "Unrecognized JSON to parse: " + txt };
                    }
                };
                window.indexedDB.json = jsonObject;
                window.indexedDBSync.json = jsonObject;

            }

            // Add some interface-level constants and methods.
            window.IDBDatabaseException = {
                UNKNOWN_ERR: 0,
                NON_TRANSIENT_ERR: 1,
                NOT_FOUND_ERR: 2,
                CONSTRAINT_ERR: 3,
                DATA_ERR: 4,
                NOT_ALLOWED_ERR: 5,
                SERIAL_ERR: 11,
                RECOVERABLE_ERR: 21,
                TRANSIENT_ERR: 31,
                TIMEOUT_ERR: 32,
                DEADLOCK_ERR: 33
            };

            window.IDBKeyRange = {
                SINGLE: 0,
                LEFT_OPEN: 1,
                RIGHT_OPEN: 2,
                LEFT_BOUND: 4,
                RIGHT_BOUND: 8
            };

            window.IDBRequest = {
                INITIAL: 0,
                LOADING: 1,
                DONE: 2
            };

            window.IDBTransaction = {
                READ_ONLY: 0,
                READ_WRITE: 1,
                VERSION_CHANGE: 2
            };

            window.IDBKeyRange.only = function (value) {
                return window.indexedDB.range.only(value);
            };

            window.IDBKeyRange.leftBound = function (bound, open) {
                return window.indexedDB.range.leftBound(bound, open);
            };

            window.IDBKeyRange.rightBound = function (bound, open) {
                return window.indexedDB.range.rightBound(bound, open);
            };

            window.IDBKeyRange.bound = function (left, right, openLeft, openRight) {
                return window.indexedDB.range.bound(left, right, openLeft, openRight);
            };
}

Creating and opening a database

Once we have our Indexed DB initialized, we can start the real thing. Creating a database. There is no specific method to create a new database, but when we call the open method, a database will be created if it doesn’t exists. After that a connection to the database will be opened. To open or create a database, the only thing you need is a name.

var dbreq = window.indexedDB.open(“database name”);

dbreq.onsuccess = function (event) {
        var dbConnection;
        // IE prototype Implementation
        if (event.result) {
                dbConnection = event.result;
        }
        //IE 10 Preview 3, Firefox & Chrome implementation
        else {
                dbConnection = dbreq.result;
        }
}

dbreq.onerror = function (event) {
       // Log or show the error message
}

Calling the open method, will return an IDBRequest object. On this object we can attach an onerror function and an onsuccess function. The onerror event will provide handling the error returned by the open function, here you can provide logging or error handling. In the onsuccess event, the database connection will be opened. We can now start using the database connection.

As you can see in code, IE prototype implementation is handling this on an other way then IE 10 Preview 3, Firefox and Chrome. In the IE prototype implementation we get the result (the database connection) out the parameter that is passed trough with the onsuccess function. For IE 10 Preview 3, Firefox and Chrome, we get the result from the IDBRequest object. This is the implementation that was defined by the W3C.

Deleting a database

Deleting the database will happen almost the same way as opening a database. You provide the name of the database you want to delete, and the database will get deleted. The error event will only be called when something goes wrong. Providing a database name that doesn’t exists, will not result in an error and the onsuccess function will get called.

var dbreq = window.indexedDB.deleteDatabase(“database name”);
        dbreq.onsuccess = function (event) {
             // Database deleted
        }
        dbreq.onerror = function (event) {
            // Log or show the error message
        }

Now we can create, open and delete a database. In one of my next posts, I will show you how you can create/change your database structure.

25 comments:

  1. Great Information and post! It is very informative and suggestible for the user of solar energy, May I think it can be beneficial in coming days...
    Web App Developers

    ReplyDelete
  2. Hi Kristof,
    I would like to follow your code, but I got an error in FF 15:

    TypeError: window.indexedDB is undefined.

    My code is:


    if (window.mozIndexedDB) {

    window.indexedDB = window.mozIndexedDB;
    window.IDBKeyRange = window.IDBKeyRange;
    window.IDBTransaction = window.IDBTransaction;
    }

    var dbreq = window.indexedDB.open("blabla");


    I don't understand whats the problem is. Do I need to activate indexeddb?

    ReplyDelete
    Replies
    1. Hi,

      It should work, It is possible that FF will ask you for permissions to use the indexeddb. Once you give permission it should work.

      Have you tried looking if something is present in the window.mozIndexedDB object?

      greetings,

      Kristof

      Delete
  3. Hey Kristof,
    thanks for your answer. Where do I have to grant the permission in FF15? window.mozIndexedDB is null.
    Thanks, Michael

    ReplyDelete
    Replies
    1. You need to give permission when you navigate the first time to your page where you use indexeddb. If you allowed that, and you still got issues, then it is possible that you are using indexeddb inside an iframe. And that isn't allowed

      greetings

      Kristof

      Delete
  4. Hi Kristof,
    I got it... I have to execute the html file with the indexeddb code via http protocol. Executing the file from the file system doesn't work. I needed the Apache httpd. Now it works fine. Thanks for your good tutorial!!!!
    Michael

    ReplyDelete
  5. This Database is very useful for creating any web its full of informative and writer share with us we are thankful for the writer. uk dissertation || do my dissertation for me || buy uk dissertation online


    ReplyDelete
  6. This awesome article as well as a step by step tutorial for creating database, deleting database. check out dissertationwritinguk for latest information and top rated services regarding dissertations. You can also get dissertation writing help too.

    ReplyDelete
  7. Wonderful blog post. I really appreciate the quality of your work here. Thanks so much for sharing such valuable information with the rest of the world.Dissertation Writing Service | dissertation writing help

    ReplyDelete
  8. Superb one! I have never read such a nice article; topic and the comments are good. I have learned many things from all your post and this one was the best post for me. I really enjoyed reading it and craving more tips from you… thank you for such an engaging article.

    Professional Degree I Logo Design

    ReplyDelete
  9. I am so thrilled and your blog is so astonishing.stay up the high-quality work and recognition for distribution this article.... Order Coursework


    ReplyDelete
  10. I am very agitated that I have discovered your post because I have been penetrating for some information on this for about two hours. You have helped me a lot undeniably and by reading this article. I have found much new and valuable information about this subject. I was guessing if you could write a little more on this subject? I’d be grateful if you could involved a little bit more.
    Thanks for sharing it.
    Online Writing Service

    ReplyDelete
  11. Thanks for sharing great content. Keep showing your potential. Hopefully waiting for more good post.

    ReplyDelete
  12. I Have Been wondering about this issue, so thanks for posting.
    vigrx plus

    ReplyDelete
  13. We offer excellent academic assistance to students through our highly qualified custom thesis proposal service and experienced team of writers.

    ReplyDelete
  14. This is really very informative blog which I have found luckily while searching something similar on the net.
    UK Dissertation Writers

    ReplyDelete
  15. This is incredibly spellbinding idea that you have share on the internet. Just keep posting your glorious thoughts so may enjoy your reading.
    Cheap Dissertation Writing Services

    ReplyDelete
  16. I was just looking for the best dissertation writing services and found your blog luckily. I am really imprsssed by the way you have expressed your ideas and will keep visiting the website again.
    Best Dissertation Writing Services UK

    ReplyDelete
  17. This comment has been removed by a blog administrator.

    ReplyDelete
  18. This comment has been removed by a blog administrator.

    ReplyDelete
  19. This comment has been removed by a blog administrator.

    ReplyDelete
  20. This comment has been removed by a blog administrator.

    ReplyDelete
  21. This comment has been removed by a blog administrator.

    ReplyDelete
  22. " Nootropics or smart drugs, are being used around the world by students, entrepreneurs, small business owners, athletes, poker players and housewives. http://www.noocube-review.com/"

    ReplyDelete
  23. Male Extra pills are famous on the market. But you have to know some side effects and results. My prof review will help you. http://www.maleextrareviewguide.com

    ReplyDelete