Ahh, SQLite, the plugin that everyone wants. The SQLite plugin for Cordova is a very popular plugin that allows devs to bypass browser-based storage by creating a full SQLite DB. But the plugin can be intimidating, especially for those who’ve never dealt with database queries before. Thankfully, we can use PouchDB as an abstraction. Check it out!

Here’s some of the code I used to set up PouchDB:

.service('DBService', function($q) { var items; var db; var self = this; this.initDB = function() { return db = new PouchDB('simpleDB', { adapter: 'websql' }); }; this.getDB = function() { if (!items) { return $q.when( db.allDocs({ include_docs: true })) .then(function(docs) { items = docs.rows.map(function(row) { row.doc.Date = new Date(row.doc.Date); return row.doc; }); // Listen for changes on the database. db.changes({ live: true, since: 'now', include_docs: true }) .on('change', function(change) { self.onDatabaseChange(change) }); return items; }); } else { return $q.when(); }; }; this.onDatabaseChange = function(change) { var index = self.findIndex(items, change.id); var item = items[index]; items.splice(index, 0, change.doc) // insert } this.findIndex = function(array, id) { var low = 0, high = array.length, mid; while (low < high) { mid = (low + high) >>> 1; array[mid]._id < id ? low = mid + 1 : high = mid } return low; } this.storeData = function(data) { return $q.when(db.post({ 'title': data })) }; return this })

Conclusion

While you could still use SQLite without PouchDB, the built-in adapter makes the process much easier. You can write to your data store like you would an regular JavaScript object, knowing that it will translate over to a SQL data store. Hopefully, this screencast will simplify the process of using the SQLite plugin in your app! Thanks for watching.