Sometimes its the little things..
[qzeecontrol] / qml / QZeeControl / settingsstorage.js
1 /*
2  * The following code is taken from:
3  * http://www.developer.nokia.com/Community/Wiki/How-to_create_a_persistent_settings_database_in_Qt_Quick_%28QML%29
4  * At the time of writing (2011-11-12) there were no copyright or licensing notes in place at the above web site.
5  * Hence, the following code is treated as public domain and has been simply copied and pasted here as is.
6  * Note: the application name and the name and size of the database had been changed to reflect Simplictionary.
7  * The version number is intended to describe the "storage format".
8  * Thanks to the original author (Slocan) for sharing this code.
9  */
10
11 //storage.js
12 // First, let's create a short helper function to get the database connection
13 function getDatabase() {
14      return openDatabaseSync("QZeeControl", "1.0", "SettingsStorageDatabase", 4000);
15 }
16
17 // At the start of the application, we can initialize the tables we need if they haven't been created yet
18 function initialize() {
19     var db = getDatabase();
20     db.transaction(
21         function(tx) {
22             // Create the settings table if it doesn't already exist
23             // If the table exists, this is skipped
24             tx.executeSql('CREATE TABLE IF NOT EXISTS settings(setting TEXT UNIQUE, value TEXT)');
25           });
26 }
27
28 // This function is used to write a setting into the database
29 function setSetting(setting, value) {
30    // setting: string representing the setting name (eg: “username”)
31    // value: string representing the value of the setting (eg: “myUsername”)
32    var db = getDatabase();
33    var res = "";
34    db.transaction(function(tx) {
35         var rs = tx.executeSql('INSERT OR REPLACE INTO settings VALUES (?,?);', [setting,value]);
36               //console.log(rs.rowsAffected)
37               if (rs.rowsAffected > 0) {
38                 res = "OK";
39               } else {
40                 res = "Error";
41               }
42         }
43   );
44   // The function returns “OK” if it was successful, or “Error” if it wasn't
45   return res;
46 }
47 // This function is used to retrieve a setting from the database
48 function getSetting(setting) {
49    var db = getDatabase();
50    var res="";
51    db.transaction(function(tx) {
52      var rs = tx.executeSql('SELECT value FROM settings WHERE setting=?;', [setting]);
53      if (rs.rows.length > 0) {
54           res = rs.rows.item(0).value;
55      } else {
56          res = "Unknown";
57      }
58   })
59   // The function returns “Unknown” if the setting was not found in the database
60   // For more advanced projects, this should probably be handled through error codes
61   return res
62 }