While developing my Cordova hybrid application, I have grown very accustomed to testing my application in a regular desktop browser, and this has worked out very well so far.
Now I'd like to add sqlite functionality to my application. I see that there is a plugin for cordova, but I am curious, how can I write a fallback so that if cordova is not being used, I can use sqlite naturally without using the cordova plugin? Ideally, I'd like it to be abstracted so that the native sqlite object behaves exactly like the plugin, so I can do all of my testing in a regular browser to minimize the number of times I have to install my app to an actual device - the build time for android is very long, so I'd like to avoid it as much as possible.
Thanks!
You can use a simple wrapper which uses WebSQL for the browser and SQLite for the device. Just use different Database object. WebSQL and SQLite API is close to identical. You only need different initialization for browser and device.
Here is my example code(ES6):
var runiOS = false;
var DB;
// Check browser or device
var onDeviceReady = new Promise(function(resolve, reject) {
if (document.URL.match(/^https?:/i)) {
console.log("Running in a browser...");
resolve();
} else {
console.log("Running in an app...");
runiOS = true;
document.addEventListener("deviceready", resolve, false);
}
});
// Run application
onDeviceReady.then(function() {
// Init WebSQL on browser or SQLite on device
if (runiOS) {
DB = window.sqlitePlugin.openDatabase({ name: 'my.db', location: 'default' }, function (db) {}, function (error) { console.log('Open database ERROR: ' + JSON.stringify(error)); });
console.log('DB: SQLite');
}
else {
DB = window.openDatabase('my', "0.1", "My list", 200000);
console.log('DB: WebSQL');
}
// ...
db.transaction(function(tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS DemoTable (name, score)');
tx.executeSql('INSERT INTO DemoTable VALUES (?,?)', ['Alice', 101]);
tx.executeSql('INSERT INTO DemoTable VALUES (?,?)', ['Betty', 202]);
}, function(error) {
console.log('Transaction ERROR: ' + error.message);
}, function() {
console.log('Populated database OK');
});
db.transaction(function(tx) {
tx.executeSql('SELECT count(*) AS mycount FROM DemoTable', [], function(tx, rs) {
console.log('Record count (expected to be 2): ' + rs.rows.item(0).mycount);
}, function(tx, error) {
console.log('SELECT error: ' + error.message);
});
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With