· 9 years ago · Dec 26, 2016, 02:58 PM
1import {Injectable} from "@angular/core";
2import {Platform} from "ionic-angular";
3
4const DB_NAME: string = '__ionic';
5const win: any = window;
6
7@Injectable()
8export class Sql {
9 private _db: any;
10
11 constructor(public platform: Platform) {
12 this.platform.ready().then(() => {
13 if (this.platform.is('cordova') && win.sqlitePlugin) {
14 this._db = win.sqlitePlugin.openDatabase({
15 name: DB_NAME,
16 location: 2,
17 createFromLocation: 0
18 });
19 console.log(this._db);
20 } else {
21 console.warn('Storage: SQLite plugin not installed, falling back to WebSQL. Make sure to install cordova-sqlite-storage in production!');
22 this._db = win.openDatabase(DB_NAME, '1.0', 'database', 5 * 1024 * 1024);
23 }
24 this._tryInit();
25 })
26 }
27
28 // Initialize the DB with our required tables
29 _tryInit() {
30 this.query('CREATE TABLE IF NOT EXISTS kv (key text primary key, value text)').catch(err => {
31 console.error('Storage: Unable to create initial storage tables', err.tx, err.err);
32 });
33 }
34
35 /**
36 * Perform an arbitrary SQL operation on the database. Use this method
37 * to have full control over the underlying database through SQL operations
38 * like SELECT, INSERT, and UPDATE.
39 *
40 * @param {string} query the query to run
41 * @param {array} params the additional params to use for query placeholders
42 * @return {Promise} that resolves or rejects with an object of the form { tx: Transaction, res: Result (or err)}
43 */
44 query(query: string, params: any[] = []): Promise<any> {
45 return new Promise((resolve, reject) => {
46 try {
47 this._db.transaction((tx: any) => {
48 tx.executeSql(query, params,
49 (tx: any, res: any) => resolve({ tx: tx, res: res }),
50 (tx: any, err: any) => reject({ tx: tx, err: err }));
51 },
52 (err: any) => reject({ err: err }));
53 } catch (err) {
54 reject({ err: err });
55 }
56 });
57 }
58
59 /**
60 * Get the value in the database identified by the given key.
61 * @param {string} key the key
62 * @return {Promise} that resolves or rejects with an object of the form { tx: Transaction, res: Result (or err)}
63 */
64 get(key: string): Promise<any> {
65 return this.query('select key, value from kv where key = ? limit 1', [key]).then(data => {
66 if (data.res.rows.length > 0) {
67 return data.res.rows.item(0).value;
68 }
69 });
70 }
71
72 /**
73 * Set the value in the database for the given key. Existing values will be overwritten.
74 * @param {string} key the key
75 * @param {string} value The value (as a string)
76 * @return {Promise} that resolves or rejects with an object of the form { tx: Transaction, res: Result (or err)}
77 */
78 set(key: string, value: string): Promise<any> {
79 return this.query('insert or replace into kv(key, value) values (?, ?)', [key, value]);
80 }
81
82 /**
83 * Remove the value in the database for the given key.
84 * @param {string} key the key
85 * @return {Promise} that resolves or rejects with an object of the form { tx: Transaction, res: Result (or err)}
86 */
87 remove(key: string): Promise<any> {
88 return this.query('delete from kv where key = ?', [key]);
89 }
90
91 /**
92 * Clear all keys/values of your database.
93 * @return {Promise} that resolves or rejects with an object of the form { tx: Transaction, res: Result (or err)}
94 */
95 clear(): Promise<any> {
96 return this.query('delete from kv');
97 }
98}