Skip to content

Instantly share code, notes, and snippets.

@r37r0m0d3l
Forked from jeefy/phonegap_orm.js
Created October 15, 2013 20:34
Show Gist options
  • Save r37r0m0d3l/6998237 to your computer and use it in GitHub Desktop.
Save r37r0m0d3l/6998237 to your computer and use it in GitHub Desktop.
/*
I wasn't happy with PhoneGap's Storage API and made it cleaner (in my eyes anyway)
Example:
db.query("someTable", ['id', 'column1', 'column2'], false, function(tx, results){ .. });
db.query("someTable", ['*'], {'column1':'val', 'column2':'val'}, function(tx, results){ .. });
db.save("someTable", IterableObject, function(){ ... });
Doing more testing and validation later, but getting it out there now. :)
*/
var db = {
initialize: function(name, version, display, size, tables, appObj){
this.db = window.openDatabase(name, version, display, size);
this.name = name;
this.version = version;
this.display = display;
this.size = size;
this.tables = tables;
this.create(tables, appObj);
return this;
},
create: function(tables, appObj){
this.db.transaction(
function(tx){ //Transaction
for(i in tables){
tx.executeSql(tables[i]);
}
}, function(err){ //Error
console.log(err.message);
}, function(){
appObj.receivedEvent('setupready');
}
);
return this;
},
query: function(table, values, where, callback){
where = (typeof where !== 'undefined' ? where : false);
var sql = 'select ';
for(i in values){
sql += values[i] + ', ';
}
sql = sql.substring(0, sql.length-2) + ' from ' + table;
if(where){
sql+= ' where ';
for(i in where){
sql += i + '=\'' + where[i] + '\' and ';
}
sql = sql.substring(0, sql.length - 5);
}
sql += ';';
this.db.transaction(
function(tx){
tx.executeSql(sql, [], callback);
}, function(err){
console.log('Error: ' + err.message);
}
);
},
save: function(table, data, callback){
if("id" in data){
this._update(table, data, callback);
} else {
this._insert(table, data, callback);
}
},
remove: function(table, id, callback){
var sql = 'delete from ' + table + ' where id=\''+id+'\';';
this.db.transaction(
function(tx){
tx.executeSql(sql, [], callback);
}, function(err){
console.log(err);
}
);
},
_insert: function(table, data, callback){
var keys = "";
var vals = "";
for(i in data){
keys += i + ', ';
values += '\'' + data[i] + '\', ';
}
var sql = 'insert into ' + table + '(' + keys.substring(0, keys.length-2) + ') values('; + values.substring(0, values.length-2) + ');';
this.db.transaction(
function(tx){
tx.executeSql(sql, [], callback);
}, function(err){
console.log(err);
}
);
},
_update: function(table, data, callback){
var sql = 'update ' + table + ' set ';
for(i in data){
if(i != "id"){
sql += i + '=\'' + data[i] + '\', ';
}
}
sql = sql.substring(0, sql.length-2) + ' where id=\''+data['id']+'\';';
this.db.transaction(
function(tx){
tx.executeSql(sql, [], callback);
}, function(err){
console.log(err);
}
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment