-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathWebSqlStorage.js
98 lines (94 loc) · 2.73 KB
/
WebSqlStorage.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/*
Copyright (c) 2004-2011, The Dojo Foundation All Rights Reserved.
Available via Academic Free License >= 2.1 OR the modified BSD license.
see: http://dojotoolkit.org/license for details
*/
var WebSqlStorage;
(function () {
WebSqlStorage = function(dbSize) {
this.db = openDatabase('lsjs db', '1.0', 'lsjs database', dbSize * 1024 * 1024);
this.db.transaction(function(tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS lsjs(id TEXT PRIMARY KEY ASC, entry TEXT)');
});
};
WebSqlStorage.prototype = {
clear: function() {
this.db.transaction(function(tx) {
tx.executeSql('DROP TABLE IF EXISTS lsjs');
});
},
isSupported: function() {
return !!window.openDatabase;
},
remove: function(key, handler, errorHandler) {
this.db.transaction(function(tx) {
tx.executeSql('DELETE FROM lsjs WHERE id=?', [key], function(tx){
if (handler) {
handler();
}
}, function(tx, e){
if (errorHandler) {
errorHandler(e);
} else {
console.log("Failed to remove value in local storage ["+key+"] : "+e);
}
});
});
},
get: function(key, handler, errorHandler) {
this.db.transaction(function(tx) {
tx.executeSql('SELECT entry FROM lsjs WHERE id=?', [key], function(tx, results){
if (results.rows.length > 0) {
var value = JSON.parse(results.rows.item(0).entry);
handler(value);
} else {
if (errorHandler) {
errorHandler("Failed to get value in local storage ["+key+"]");
} else {
console.log("Failed to get value in local storage ["+key+"] : "+e);
}
}
}, function(tx, e){
if (errorHandler) {
errorHandler(e);
} else {
console.log("Failed to get value in local storage ["+key+"] : "+e);
}
});
});
},
set: function(key, entry, handler, errorHandler) {
var entryValue = JSON.stringify(entry);
var scope = this;
this.get(key, function(){
scope.db.transaction(function(tx) {
tx.executeSql('UPDATE lsjs set entry=? where id=?', [entryValue, key], function(tx){
if (handler) {
handler(true);
}
}, function(tx, e){
if (errorHandler) {
errorHandler(e);
} else {
console.log("Failed to set value in local storage ["+key+"] : "+e);
}
});
});
}, function(){
scope.db.transaction(function(tx) {
tx.executeSql('INSERT into lsjs (id, entry) VALUES (?, ?)', [key, entryValue], function(tx){
if (handler) {
handler(true);
}
}, function(tx, e){
if (errorHandler) {
errorHandler(e);
} else {
console.log("Failed to set value in local storage ["+key+"] : "+e);
}
});
});
});
}
};
}());