Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete a database in WebSQL programmatically?

I am new to Web SQL database and I use it to save data in a local database in a web page.

 I can create a database by

var db = openDatabase('database', '1.0', 'my database', 2 * 1024 * 1024);

 and I can create a table by doing this

db.transaction(function (tx) {
  tx.executeSql('CREATE TABLE IF NOT EXISTS mytable (blah,blah)');
});

 I can delete the table by

db.transaction(function (tx) {
  tx.executeSql('DROP TABLE mytable');
});

 but is there a way to delete the database programmatically?

like image 853
Derek 朕會功夫 Avatar asked Aug 24 '11 22:08

Derek 朕會功夫


People also ask

Is WebSQL deprecated?

WebSQL in third-party contexts is now deprecated. Removal is expected in Chrome 97. The Web SQL Database standard was first proposed in April 2009 and abandoned in November 2010. Gecko never implemented this feature and WebKit deprecated this feature in 2019.

Should I use WebSQL?

WebSQL is still deprecated and in fact being removed from iOS Safari. Web Workers are not necessarily a panacea. I'd recommend using IndexedDB for large data, and LocalStorage for small amounts of data that you need synchronous access to.

What is WebSQL used for?

Web SQL is a web page API for storing or managing the data in databases that can be queried using a variant of SQL like creating databases, opening the transaction, creating tables, inserting values to tables, deleting values, and reading data.


7 Answers

Using PersistenceJS there is a persistence.reset API which will wipe the database clean. PersistenceJS Site

For developing / testing purposes, you can view content and delete webSQL, IndexedDB, cookies, etc by searching for your domain name at this URL in Chrome:

chrome://settings/cookies

There, you can delete all the storage for a domain or just certain local storage entities. Yes, the URL implies just 'cookies', but the interface at this URL includes all types of offline storage.

It would be great I think if the Chrome developer tools interface had the ability to right-click and delete a data storage entity in the Resources tab along with inspecting the content. But for now, all I know of is the settings/cookies URL.

like image 172
i_a Avatar answered Oct 06 '22 06:10

i_a


Spec says:

4.1 Databases

Each origin has an associated set of databases. Each database has a name and a current version. There is no way to enumerate or delete the databases available for an origin from this API.

like image 45
serg Avatar answered Oct 06 '22 05:10

serg


I am developing a phonegap+jquery-mobile+KO app with offline storage using web sql via persistencejs, and jasmine js for BDD.

I'm working on some sort of "database cleaner" to be executed after each spec. When I was searching on how to drop a web sql database I read the reply https://stackoverflow.com/a/10929725/667598 (in this thread/question), and went to see what's in that directory (Mac OS X).

cd ~/Library/Application\ Support/Google/Chrome/Default/databases

Inside you will see a Databases.db SQLite3 database, and directories for each origin. These directories are named with the pattern protocol_host_somenumber (I don't know what that number is). So for example, in my case, since my apps are just files I open in Google Chrome with the file:/// … protocol, I can see a file__0 directory. And for twitter and I can also see a http_twitter.com_0 and a https_twitter.com_0.

Inside this directories all file names are just numbers. For example inside file__0 I found a file named 8 and another named 9. In my case, these files are websql database. I don't know if there also Indexed DB databases in chrome's Default/databases dir.

With this names it is a little hard to guess what database is what. You can open the database and you'll have to infer the app or site via its tables and data.

Luckily, the Databases.db I mentioned before is a mapping between those files named with numbers and the databases.

You can open the Databases.db and any other web sql file with the sqlite3 command

sqlite3 Databases.db

Obviously, once inside the sqlite3 shell, is handy to have some SQL knowledge. Anyway, it is also always handy some help, which is available via the command

.help

With the command .tables you can list tables in the database. Inside this Databases.db we can find the tables Databases and meta. The important one is Databases, so with a

select * from Databases;

we can see the mapping between the databases and their files. For example

7|http_jquerymobile.com_0|testdb|html5 test db|200000

8|file__0|elfaro_dev|Base de datos de ElFaro para desarrollo|734003200

The first column is the id of the table which is the number used for db file names, the second is the origin (the directory) the other columns are the db name, the db description and the estimated size used when creating the db from the Javascript API.

So to actually delete a database what I did was to delete it from this table, for example:

delete from Databases where id = 8

And then delete the actual file from the filesystem (outside sqlite3 shell)

rm file__0/8

And that's it.

PS: I know this is a too long answer for a simple subject but I just needed to flush this from my system and back it up somewhere like SO or a blog.

like image 37
hisa_py Avatar answered Oct 06 '22 05:10

hisa_py


The developer options

There is no way to enumerate or delete the databases programmatically (yet).
Chrome developers can navigate to chrome://settings/cookies search and delete any database Opera developers can navigate to opera://settings/cookies

The only way to truly delete a database (and everything else)

A new Spec says this might be possible in the feature with both response header and javascript. The disadvantages is that you can't control what is being deleted, So you would need to create a backup first of everything else unless you want to clear everything

2.1.3. The storage parameter

The storage parameter indicates that the server wishes to remove locally stored data associated with the origin of a particular response’s url. This includes storage mechansims such as (localStorage, sessionStorage, [INDEXEDDB], [WEBDATABASE], etc), as well as tangentially related mechainsm such as service worker registrations.

Js:

navigator.storage.clear({
    types: [ "storage" ],
    includeSubdomains: true // false by default
});

Response header:

res.header("Clear-Site-Data", "storage; includeSubdomains");

But this is not avalible to any browser yet...

Best solution for clients (not the developers)

/* This will fetch all tables from sqlite_master
 * except some few we can't delete.
 * It will then drop (delete) all tables.
 * as a final touch, it is going to change the database
 * version to "", which is the same thing you would get if
 * you would check if it the database were just created
 *
 * @param name [string] - the database to delete
 * @param cb [function] - the callback when it's done
 */
function dropDatabase(name, cb){
    // empty string means: I do not care what version, desc, size the db is
    var db = openDatabase(name, "", "", "");

    function error(tx, err){
        console.log(err);
    }

    db.transaction(ts => {
        // query all tabels from sqlite_master that we have created and can modify
        var query = "SELECT * FROM sqlite_master WHERE name NOT LIKE 'sqlite\\_%' escape '\\' AND name NOT LIKE '\\_%' escape '\\'";
        var args = [];
        var success = (tx, result) => {
            var rows, i, n, name;

            rows = result.rows;
            n = i = rows.length;

            // invokes cb once it’s called n times
            function after(){
                if (--n < 0) {
                    // Change the database version back to empty string
                    // (same as when we compear new database creations)
                    db.changeVersion(db.version, "", function(){}, error, cb);
                }
            }

            while(i--){
                // drop all tabels and calls after() each time
                name = JSON.stringify(rows.item(i).name);
                tx.executeSql('DROP TABLE ' + name, [], after, error);
            }

            // call it just 1 more extra time incase we didn't get any tabels
            after();
        };

        ts.executeSql(query, args, success, error);
    });

}

Usage

dropDatabase("database", function(){
    console.log("done")
});
like image 44
Endless Avatar answered Oct 06 '22 07:10

Endless


The localdatabase files are stored in your Windows user settings under Application Data > Google > Chrome > User Data > Default > databases.

So manually deleting them is theoretically possible. This is only useful while testing / developing on your own computer, since when another user opens your app/site, it is unlikely to have file system access.

However, even though you can find the files and delete them, the data sticks around. I've tried it with Chrome both open and closed and all chrome processes ended, and yet the browser inspector keeps showing me my old database with all the unwanted fields and data in it.

like image 41
Wytze Avatar answered Oct 06 '22 07:10

Wytze


This is answered in HTML5 database storage (SQL lite) - few questions.

To summarize:

  • Currently no way to drop a WebSQL database.
  • Probably use Indexed DB or localStorage instead.
like image 28
Boris Smus Avatar answered Oct 06 '22 06:10

Boris Smus


In my library implementation, I just delete all tables. Which, indeed, delete the database. List of tables are select * from sqlite_master.

like image 34
Kyaw Tun Avatar answered Oct 06 '22 06:10

Kyaw Tun