PersistentObjectStore.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. .pragma library
  2. function getDatabase() {
  3. return openDatabaseSync("SettingsDB", "1.0", "Settings", 5000);
  4. }
  5. function initialize() {
  6. var db = getDatabase();
  7. db.transaction(
  8. function(tx) {
  9. // Create the settings table if it doesn't already exist
  10. // If the table exists, this is skipped
  11. tx.executeSql('CREATE TABLE IF NOT EXISTS settings(settingsName TEXT, keyName TEXT, value TEXT)');
  12. tx.executeSql('CREATE INDEX IF NOT EXISTS settingsName ON settings (settingsName);');
  13. tx.executeSql('CREATE UNIQUE INDEX IF NOT EXISTS fullKeyName ON settings (settingsName, keyName);');
  14. }
  15. );
  16. console.log('DB initialized');
  17. }
  18. function save(obj) {
  19. var db = getDatabase();
  20. db.transaction(
  21. function (tx) {
  22. // Clean all fields of this settings object first, so the DB is always clean from unused fields
  23. tx.executeSql('DELETE FROM settings WHERE settingsName=?;', [obj.objectName]);
  24. // Save all fields
  25. for (var fieldName in obj) {
  26. var value = JSON.stringify(obj[fieldName]);
  27. if (typeof value === 'undefined' || fieldName === 'objectName') {
  28. continue;
  29. }
  30. tx.executeSql('INSERT INTO settings (settingsName, keyName, value) VALUES (?, ?, ?);', [obj.objectName, fieldName, value]);
  31. console.log("Saved: " + obj.objectName + "." + fieldName + " => " + value);
  32. }
  33. }
  34. );
  35. }
  36. function load(obj) {
  37. var db = getDatabase();
  38. db.transaction(
  39. function (tx) {
  40. // Load fields
  41. for (var fieldName in obj) {
  42. var rs = tx.executeSql('SELECT value FROM settings WHERE settingsName=? AND keyName=?;', [obj.objectName, fieldName]);
  43. if (rs.rows.length > 0) {
  44. obj[fieldName] = JSON.parse(rs.rows.item(0).value);
  45. console.log("Loaded: " + obj.objectName + "." + fieldName + ". New value: " + obj[fieldName]);
  46. } else {
  47. console.log("Not loaded: " + obj.objectName + "." + fieldName + ". Current value:" + obj[fieldName]);
  48. }
  49. }
  50. }
  51. );
  52. }