Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can SQL.js (SQLite JavaScript implementation) write to disk immediately, automaticallly?

I'm prototyping an idea I've got for a Chrome extension (and a packaged app variant of that extension) for which a small, lightweight SQL database, like SQLite, would be ideal. However, Chrome Apps cannot use Web SQL.

I've been experimenting with SQL.js, a JavaScript implementation of SQLite, but it seems that I need to manually write the entire database out to disk anytime I want to save. That means that every SQL write (e.g., UPDATE, INSERT, DELETE) needs to be followed by manually writing the entire database to disk, if I want to persist my changes past the current session. Correct? Am I missing something?

Is this the only option I've got with SQL.js (or any other JavaScript implementation of SQLite)? It would be much easier if the data was automatically written out to disk whenever the data changes.

And even better would be if the SQLite implementation was intelligent enough to only update the portion of the datafile that actually changed. So if you've got a 20 meg database, and you do an update that flips a bit flag from 0 to 1, it could just change that one bit, instead of having to write out the entire 20 megs to disk.

I'm aware of IndexedDB as an alternative, and I'm investigating it separately. This question is about my SQL.js/SQLite options. I want to be really sure I understand if and how SQLite could be made to work.

There does appear to be a Cordova-specific plugin that offers SQLite support, but that won't work (at least, not without customization) in Chrome Extensions & Apps.

like image 270
Josh Avatar asked Nov 01 '22 18:11

Josh


1 Answers

You can try Alasql JavaScript SQL library. It has Local Storage and IndexedDB adapters, where you can store data.

Current Local Storage adapter can work in AUTOCOMMIT mode, when Alasql writes every changes immediately to localStorage (see Local Storage Adapter source code).

alasql('CREATE LOCALSTORAGE DATABASE MyBase; SET AUTOCOMMIT ON; \
        INSERT INTO MyBase.cite VALUES ("Paris","France")");

If you need more specific requirements, it is easy to rewrite this adapter to your needs.

like image 54
agershun Avatar answered Nov 04 '22 06:11

agershun