mladenp
11/27/2014 - 1:25 PM

SQLite wrapper for phonegap

SQLite wrapper for phonegap

.factory('DB', function ($q, $http, DB_CONFIG) {
    var self = this;
    self.db = null;

    /*self.db_open = function () {
        self.db =  window.sqlitePlugin.openDatabase({name: DB_CONFIG.name, bgType: 1});
    };*/

    self.db_open =function(){
        var def = $q.defer();
        try{
            if(window.sqlitePlugin){
                self.db = window.sqlitePlugin.openDatabase({name: DB_CONFIG.name},function(){
                    def.resolve(true);
                });
            } else {
                def.reject();
            }
        }catch(e){
            def.reject(e);
        }
        return def.promise;
    };

    self.init = function () {
        angular.forEach(DB_CONFIG.tables, function (table) {
            var columns = [];
            angular.forEach(table.columns, function (column) {
                columns.push(column.name + ' ' + column.type);
            });

            var query = 'CREATE TABLE IF NOT EXISTS ' + table.name + ' (' + columns.join(',') + ')';
            self.query(query);
            //console.log('Table ' + table.name + ' initialized');
        });
    };

    self.drop_all = function () {
        angular.forEach(DB_CONFIG.tables, function (table) {
            var query = 'DROP TABLE ' + table.name;
            self.query(query);
        });
    };

    self.query = function (query, bindings) {
        bindings = typeof bindings !== 'undefined' ? bindings : [];
        var deferred = $q.defer();

        self.db.transaction(function (transaction) {
            transaction.executeSql(query, bindings, function (transaction, result) {
                deferred.resolve(result);
            }, function (transaction, error) {
                deferred.reject(error);
            });
        });

        return deferred.promise;
    };

    self.fetchAll = function (result) {
        var output = [];
        for (var i = 0; i < result.rows.length; i++) {
            output.push(result.rows.item(i));
        }
        return output;
    };
    self.fetch = function (result) {
        return result.rows.item(0);
    };
    self.latestUpdate = function (table) {
        return self.query('SELECT MAX(updated) FROM '+table).then(function (result) {
            return self.fetch(result);
        });
    };

    return self;
})