-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathsql.ts
More file actions
209 lines (184 loc) · 6.43 KB
/
sql.ts
File metadata and controls
209 lines (184 loc) · 6.43 KB
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
const DB_NAME: string = '__ionicstorage';
const win: any = window;
/**
* SqlStorage uses SQLite or WebSQL (development only!) to store data in a
* persistent SQL store on the filesystem.
*
* This is the preferred storage engine, as data will be stored in appropriate
* app storage, unlike Local Storage which is treated differently by the OS.
*
* For convenience, the engine supports key/value storage for simple get/set and blob
* storage. The full SQL engine is exposed underneath through the `query` method.
*
* @usage
```js
* let storage = new SqlStorage(options);
* storage.set('name', 'Max');
* storage.get('name').then((name) => {
* });
*
* // Sql storage also exposes the full engine underneath
* storage.query('insert into projects(name, data) values("Cool Project", "blah")');
* storage.query('select * from projects').then((resp) => {})
* ```
*
* The `SqlStorage` service supports these options:
* {
* name: the name of the database (__ionicstorage by default)
* backupFlag: // where to store the file, default is BACKUP_LOCAL which DOES NOT store to iCloud. Other options: BACKUP_LIBRARY, BACKUP_DOCUMENTS
* existingDatabase: whether to load this as an existing database (default is false)
* }
*
*/
/** Utility functions
* TODO: MOVE THESE TO A UTIL CLASS LATER
*/
export const isFunction = (val: any) => typeof val === 'function';
export const isObject = (val: any) => typeof val === 'object';
export const isArray = Array.isArray;
export class SqlStorage {
static BACKUP_LOCAL = 2;
static BACKUP_LIBRARY = 1;
static BACKUP_DOCUMENTS = 0;
private _db: any;
constructor(options = {}) {
let dbOptions = this.defaults(options, {
name: DB_NAME,
backupFlag: SqlStorage.BACKUP_LOCAL,
existingDatabase: false
});
if (win.sqlitePlugin) {
let location = this._getBackupLocation(dbOptions.backupFlag);
this._db = win.sqlitePlugin.openDatabase(this.assign({
name: dbOptions.name,
location: location,
createFromLocation: dbOptions.existingDatabase ? 1 : 0
}, dbOptions));
} else {
console.warn('Storage: SQLite plugin not installed, falling back to WebSQL. Make sure to install cordova-sqlite-storage in production!');
this._db = win.openDatabase(dbOptions.name, '1.0', 'database', 5 * 1024 * 1024);
}
this._tryInit();
}
_getBackupLocation(dbFlag: number): number {
switch (dbFlag) {
case SqlStorage.BACKUP_LOCAL:
return 2;
case SqlStorage.BACKUP_LIBRARY:
return 1;
case SqlStorage.BACKUP_DOCUMENTS:
return 0;
default:
throw Error('Invalid backup flag: ' + dbFlag);
}
}
// Initialize the DB with our required tables
_tryInit() {
this.query('CREATE TABLE IF NOT EXISTS kv (key text primary key, value text)').catch(err => {
console.error('Storage: Unable to create initial storage tables', err.tx, err.err);
});
}
/**
* Perform an arbitrary SQL operation on the database. Use this method
* to have full control over the underlying database through SQL operations
* like SELECT, INSERT, and UPDATE.
*
* @param {string} query the query to run
* @param {array} params the additional params to use for query placeholders
* @return {Promise} that resolves or rejects with an object of the form { tx: Transaction, res: Result (or err)}
*/
query(query: string, params = []): Promise<any> {
return new Promise((resolve, reject) => {
try {
this._db.transaction((tx) => {
tx.executeSql(query, params,
(tx, res) => resolve({ tx: tx, res: res }),
(tx, err) => reject({ tx: tx, err: err }));
},
(err) => reject({ err: err }));
} catch (err) {
reject({ err: err });
}
});
}
/**
* Get the value in the database identified by the given key.
* @param {string} key the key
* @return {Promise} that resolves or rejects with an object of the form { tx: Transaction, res: Result (or err)}
*/
get(key: string): Promise<any> {
return this.query('select key, value from kv where key = ? limit 1', [key]).then(data => {
if (data.res.rows.length > 0) {
return data.res.rows.item(0).value;
}
});
}
/**
* Set the value in the database for the given key. Existing values will be overwritten.
* @param {string} key the key
* @param {string} value The value (as a string)
* @return {Promise} that resolves or rejects with an object of the form { tx: Transaction, res: Result (or err)}
*/
set(key: string, value: string): Promise<any> {
return this.query('insert or replace into kv(key, value) values (?, ?)', [key, value]);
}
/**
* Remove the value in the database for the given key.
* @param {string} key the key
* @return {Promise} that resolves or rejects with an object of the form { tx: Transaction, res: Result (or err)}
*/
remove(key: string): Promise<any> {
return this.query('delete from kv where key = ?', [key]);
}
/**
* Clear all keys/values of your database.
* @return {Promise} that resolves or rejects with an object of the form { tx: Transaction, res: Result (or err)}
*/
clear(): Promise<any> {
return this.query('delete from kv');
}
assign(...args: any[]): any {
if (typeof Object.assign !== 'function') {
// use the old-school shallow extend method
return this._baseExtend(args[0], [].slice.call(args, 1), false);
}
// use the built in ES6 Object.assign method
return Object.assign.apply(null, args);
}
/**
* Apply default arguments if they don't exist in
* the first object.
* @param the destination to apply defaults to.
*/
defaults(dest: any, ...args: any[]) {
for (var i = arguments.length - 1; i >= 1; i--) {
var source = arguments[i];
if (source) {
for (var key in source) {
if (source.hasOwnProperty(key) && !dest.hasOwnProperty(key)) {
dest[key] = source[key];
}
}
}
}
return dest;
}
_baseExtend(dst: any, objs: any, deep: boolean) {
for (var i = 0, ii = objs.length; i < ii; ++i) {
var obj = objs[i];
if (!obj || !isObject(obj) && !isFunction(obj)) continue;
var keys = Object.keys(obj);
for (var j = 0, jj = keys.length; j < jj; j++) {
var key = keys[j];
var src = obj[key];
if (deep && isObject(src)) {
if (!isObject(dst[key])) dst[key] = isArray(src) ? [] : {};
this._baseExtend(dst[key], [src], true);
} else {
dst[key] = src;
}
}
}
return dst;
}
}