Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import {Injectable} from "@angular/core";
- import {SQLite} from "ionic-native";
- const DB_NAME: string = '__rimsapp';
- const win: any = window;
- @Injectable()
- export class Sql {
- private _db: any;
- constructor() {
- if (win.sqlitePlugin) {
- let db = new SQLite();
- this._db = db.openDatabase({
- name: DB_NAME,
- location: 'default'
- });
- } 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(DB_NAME, '1.0', 'database', 5 * 1024 * 1024);
- }
- this._tryInit();
- }
- // 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: any[] = []): Promise<any> {
- return new Promise((resolve, reject) => {
- try {
- this._db.transaction((tx: any) => {
- tx.executeSql(query, params,
- (tx: any, res: any) => resolve({tx: tx, res: res}),
- (tx: any, err: any) => reject({tx: tx, err: err}));
- },
- (err: any) => 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;
- private dbConnections: {[dbName:string]:any} = {};
- private hasSQLite: boolean = false;
- constructor(private storage: Storage) {
- //noinspection TypeScriptUnresolvedVariable
- if (!!win.sqlitePlugin)
- this.hasSQLite = true;
- this.initDb();
- }
- private initDb(db: string = 'firebaseDataStore') {
- if (this.hasSQLite) {
- let dbInit = new SQLite();
- this.dbConnections[db] = dbInit.openDatabase({
- name: db,
- location: 'default'
- });
- } else {
- this.dbConnections[db] = win.openDatabase(db, '1.0', 'database', 5 * 1024 * 1024);
- }
- this.query(db, '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);
- });
- }
- public getJSON(key: string, db:string = 'firebaseDataStore'): Promise<any> {
- return this.get(key, db).then(value => {
- try {
- return JSON.parse(value);
- } catch (e) {
- console.warn('Storage getJson(): unable to parse value for key', key, ' as JSON');
- throw e; // rethrowing exception so it can be handled with .catch()
- }
- });
- }
- public setJSON(key: string, data: any, db: string = 'firebaseDataStore') {
- try {
- return this.set(key, JSON.stringify(data), db);
- } catch (e) {
- return Promise.reject(e);
- }
- }
- /**
- * Get the value in the database identified by the given key.
- * @param {string} key the key
- * @param {string} db the database to target
- * @return {Promise} that resolves or rejects with an object of the form { tx: Transaction, res: Result (or err)}
- */
- public get(key: string, db: string = 'firebaseDataStore'): Promise<any> {
- return this.query(db, '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, db:string = 'firebaseDataStore'): Promise<any> {
- return this.query(db, 'insert or replace into kv(key, value) values (?, ?)', [key, value]);
- }
- // public getJSON(key: string, db: string = 'firebaseDataStore'): Promise<any> {
- // return new Promise<any>((resolve, reject) => {
- // this.storage.get(key).then(val => resolve(JSON.parse(val)), err => reject(err));
- // });
- // }
- public getDataSet(keyPrefix: string, db: string = 'firebaseDataStore'): Promise<any[]> {
- return new Promise<any[]>((resolve, reject) => {
- resolve(null);
- this.query(db, "SELECT * FROM kv WHERE key LIKE '" + keyPrefix + "%';").then(resultSet => {
- resolve(resultSet);
- }, err => reject(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} [db] the database to target
- * @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(db: string = 'firebaseDataStore', query: string, params: any[] = []): Promise<any> {
- return new Promise((resolve, reject) => {
- try {
- if(!this.dbConnections[db])
- this.initDb(db);
- this.dbConnections[db].transaction((tx: any) => {
- tx.executeSql(query, params,
- (tx: any, res: any) => resolve({tx: tx, res: res}),
- (tx: any, err: any) => reject({tx: tx, err: err}));
- },
- (err: any) => reject({err: err}));
- } catch (err) {
- reject({err: err});
- }
- });
- }
- /**
- * 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, db:string = 'firebaseDataStore'): Promise<any> {
- return this.query(db, '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(db:string = 'firebaseDataStore'): Promise<any> {
- return this.query(db, 'delete from kv');
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement