this version is a good base, seems to work ok

This commit is contained in:
Mike 2012-04-08 10:19:39 -04:00
parent 22c392ff02
commit baa87f9e08
2 changed files with 164 additions and 257 deletions

View File

@ -1,141 +1,82 @@
(function() { (function() {
var callbacks, cbref, counter, getOptions, root; var root;
root = this;
root = this; root.SQLitePlugin = (function() {
callbacks = {};
counter = 0;
cbref = function(hash) {
var f;
f = "cb" + (counter += 1);
callbacks[f] = hash;
return f;
};
getOptions = function(opts, success, error) {
var cb, has_cbs;
cb = {};
has_cbs = false;
if (typeof success === "function") {
has_cbs = true;
cb.success = success;
}
if (typeof error === "function") {
has_cbs = true;
cb.error = error;
}
if (has_cbs) opts.callback = cbref(cb);
return opts;
};
root.SQLitePlugin = (function() {
console.log("root.SQLitePlugin"); console.log("root.SQLitePlugin");
SQLitePlugin.prototype.openDBs = {}; SQLitePlugin.prototype.openDBs = {};
function SQLitePlugin(dbPath, openSuccess, openError) { function SQLitePlugin(dbPath, openSuccess, openError)
console.log("SQLitePlugin"); {
this.dbPath = dbPath; console.log("SQLitePlugin");
this.openSuccess = openSuccess; this.dbPath = dbPath;
this.openError = openError; this.openSuccess = openSuccess;
if (!dbPath) { this.openError = openError;
throw new Error("Cannot create a SQLitePlugin instance without a dbPath"); if (!dbPath) {
} throw new Error("Cannot create a SQLitePlugin instance without a dbPath");
this.openSuccess || (this.openSuccess = function() { }
console.log("DB opened: " + dbPath); this.openSuccess || (this.openSuccess = function() {
}); console.log("DB opened: " + dbPath);
this.openError || (this.openError = function(e) { });
console.log(e.message); this.openError || (this.openError = function(e) {
}); console.log(e.message);
this.open(this.openSuccess, this.openError); });
this.open(this.openSuccess, this.openError);
} }
SQLitePlugin.handleCallback = function(ref, type, obj) { SQLitePlugin.prototype.transaction = function(fn, error, success)
console.log("SQLitePlugin.prototype.handleCallback"); {
var _ref; console.log("SQLitePlugin.prototype.transaction");
if ((_ref = callbacks[ref]) != null) { var t;
if (typeof _ref[type] === "function") _ref[type](obj); t = new root.SQLitePluginTransaction(this.dbPath);
} fn(t);
callbacks[ref] = null; return t.complete(success, error);
delete callbacks[ref];
};
SQLitePlugin.prototype.executeSql = function(sql, values, success, error) {
console.log("SQLitePlugin.prototype.executeSql");
var opts;
if (!sql) throw new Error("Cannot executeSql without a query");
opts = getOptions({
query: [sql].concat(values || []),
path: this.dbPath
}, success, error);
// PhoneGap.exec("SQLitePlugin.backgroundExecuteSql", opts);
PhoneGap.exec(null, null, "SQLitePlugin", "backgroundExecuteSql", opts);
};
SQLitePlugin.prototype.transaction = function(fn, error, success) {
console.log("SQLitePlugin.prototype.transaction");
var t;
t = new root.SQLitePluginTransaction(this.dbPath);
fn(t);
return t.complete(success, error);
}; };
SQLitePlugin.prototype.open = function(success, error) { SQLitePlugin.prototype.open = function(success, error)
console.log("SQLitePlugin.prototype.open"); {
var opts; console.log("SQLitePlugin.prototype.open");
if (!(this.dbPath in this.openDBs)) { var opts;
this.openDBs[this.dbPath] = true; if (!(this.dbPath in this.openDBs)) {
opts = getOptions({ this.openDBs[this.dbPath] = true;
path: this.dbPath PhoneGap.exec(success, error, "SQLitePlugin", "open", [this.dbPath]);
}, success, error); }
//PhoneGap.exec("SQLitePlugin.open", opts);
/*
* db The name of the database
version The version
display_name The display name
size The size in bytes
*
*/
PhoneGap.exec(success, error, "SQLitePlugin", "open", [this.dbPath]);
}
}; };
SQLitePlugin.prototype.close = function(success, error) { SQLitePlugin.prototype.close = function(success, error)
{
console.log("SQLitePlugin.prototype.close"); console.log("SQLitePlugin.prototype.close");
var opts; var opts;
if (this.dbPath in this.openDBs) { if (this.dbPath in this.openDBs) {
delete this.openDBs[this.dbPath]; delete this.openDBs[this.dbPath];
opts = getOptions({ PhoneGap.exec(null, null, "SQLitePlugin", "close", [this.dbPath]);
path: this.dbPath }
}, success, error);
//PhoneGap.exec("SQLitePlugin.close", opts);
PhoneGap.exec(null, null, "SQLitePlugin", "close", opts);
}
}; };
return SQLitePlugin; return SQLitePlugin;
})(); })();
get_unique_id = function() get_unique_id = function()
{
var id = new Date().getTime();
var id2 = new Date().getTime();
while(id === id2)
{ {
id2 = new Date().getTime(); var id = new Date().getTime();
var id2 = new Date().getTime();
while(id === id2)
{
id2 = new Date().getTime();
}
return id2+'000';
} }
return id2+'000'; transaction_queue = [];
} transaction_callback_queue = new Object();
transaction_queue = []; root.SQLitePluginTransaction = (function() {
transaction_callback_queue = new Object(); console.log("root.SQLitePluginTransaction");
root.SQLitePluginTransaction = (function() { function SQLitePluginTransaction(dbPath)
console.log("root.SQLitePluginTransaction"); {
function SQLitePluginTransaction(dbPath) {
console.log("root.SQLitePluginTransaction.SQLitePluginTransaction"); console.log("root.SQLitePluginTransaction.SQLitePluginTransaction");
this.dbPath = dbPath; this.dbPath = dbPath;
this.executes = []; this.executes = [];
this.trans_id = get_unique_id(); this.trans_id = get_unique_id();
console.log("root.SQLitePluginTransaction - this.trans_id:"+this.trans_id); console.log("root.SQLitePluginTransaction - this.trans_id:"+this.trans_id);
transaction_queue[this.trans_id] = []; transaction_queue[this.trans_id] = [];
} transaction_callback_queue[this.trans_id] = new Object();
}
SQLitePluginTransaction.queryCompleteCallback = function(transId, queryId, result) SQLitePluginTransaction.queryCompleteCallback = function(transId, queryId, result)
{ {
var query = null; var query = null;
@ -149,27 +90,61 @@
} }
if(query) if(query)
console.log("SQLitePluginTransaction.completeCallback---query:"+query['query']); console.log("SQLitePluginTransaction.completeCallback---query:"+query['query']);
else if(query && query['callback'])
console.log("SQLitePluginTransaction.completeCallback---JSON.stringify(transaction_queue):"+JSON.stringify(transaction_queue[transId]));
if(query['callback'])
query['callback'](result) query['callback'](result)
} }
SQLitePluginTransaction.queryErrorCallback = function(transId, queryId, result)
{
var query = null;
for (var x in transaction_queue[transId])
{
if(transaction_queue[transId][x]['query_id'] == queryId)
{
query = transaction_queue[transId][x];
break;
}
}
if(query)
console.log("SQLitePluginTransaction.queryErrorCallback---query:"+query['query']);
if(query && query['err_callback'])
query['err_callback'](result)
}
SQLitePluginTransaction.txCompleteCallback = function(transId) SQLitePluginTransaction.txCompleteCallback = function(transId)
{ {
if(typeof transId != 'undefined') if(typeof transId != 'undefined')
{ {
console.log("SQLitePluginTransaction.txCompleteCallback---transId:"+transId); console.log("SQLitePluginTransaction.txCompleteCallback---transId:"+transId);
if(transId && transaction_callback_queue[transId]) if(transId && transaction_callback_queue[transId]['success'])
transaction_callback_queue[transId](); transaction_callback_queue[transId]['success']();
delete transaction_queue[transId];
delete transaction_callback_queue[transId];
} }
else else
console.log("SQLitePluginTransaction.txCompleteCallback---transId = NULL"); console.log("SQLitePluginTransaction.txCompleteCallback---transId = NULL");
} }
SQLitePluginTransaction.txErrorCallback = function(transId, error)
{
if(typeof transId != 'undefined')
{
console.log("SQLitePluginTransaction.txErrorCallback---transId:"+transId);
if(transId && transaction_callback_queue[transId]['error'])
transaction_callback_queue[transId]['error'](error);
delete transaction_queue[transId];
delete transaction_callback_queue[transId];
}
else
console.log("SQLitePluginTransaction.txErrorCallback---transId = NULL");
}
SQLitePluginTransaction.prototype.add_to_transaction = function(trans_id, query, params, callback, err_callback) SQLitePluginTransaction.prototype.add_to_transaction = function(trans_id, query, params, callback, err_callback)
{ {
var new_query = new Object();; var new_query = new Object();;
new_query['trans_id'] = trans_id; new_query['trans_id'] = trans_id;
new_query['query_id'] = get_unique_id(); if(callback)
new_query['query_id'] = get_unique_id();
else
new_query['query_id'] = "";
new_query['query'] = query; new_query['query'] = query;
new_query['params'] = params; new_query['params'] = params;
new_query['callback'] = callback; new_query['callback'] = callback;
@ -179,67 +154,69 @@
transaction_queue[trans_id].push(new_query); transaction_queue[trans_id].push(new_query);
} }
SQLitePluginTransaction.prototype.executeSql = function(sql, values, success, error) { SQLitePluginTransaction.prototype.executeSql = function(sql, values, success, error) {
console.log("SQLitePluginTransaction.prototype.executeSql"); console.log("SQLitePluginTransaction.prototype.executeSql");
var errorcb, successcb, txself; var errorcb, successcb, txself;
txself = this; txself = this;
successcb = null; successcb = null;
if (success) { if (success)
successcb = function(execres) { {
console.log("executeSql callback:"+JSON.stringify(execres)); console.log("success not null:"+sql);
var res, saveres; successcb = function(execres)
saveres = execres; {
res = { console.log("executeSql callback:"+JSON.stringify(execres));
rows: { var res, saveres;
item: function(i) { saveres = execres;
return saveres[i]; res = {
}, rows: {
length: saveres.length item: function(i) {
}, return saveres[i];
rowsAffected: saveres.rowsAffected, },
insertId: saveres.insertId || null length: saveres.length
}; },
return success(txself, res); rowsAffected: saveres.rowsAffected,
}; insertId: saveres.insertId || null
} };
errorcb = null; return success(txself, res);
if (error) { };
errorcb = function(res) { }
return error(txself, res); else
}; console.log("success NULL:"+sql);
}
errorcb = null;
if (error) {
errorcb = function(res) {
return error(txself, res);
};
}
this.add_to_transaction(this.trans_id, sql, values, successcb, errorcb); this.add_to_transaction(this.trans_id, sql, values, successcb, errorcb);
console.log("executeSql - add_to_transaction"+sql); console.log("executeSql - add_to_transaction"+sql);
}; };
SQLitePluginTransaction.prototype.complete = function(success, error) {
SQLitePluginTransaction.prototype.complete = function(success, error) {
console.log("SQLitePluginTransaction.prototype.complete"); console.log("SQLitePluginTransaction.prototype.complete");
var begin_opts, commit_opts, errorcb, executes, opts, successcb, txself; var begin_opts, commit_opts, errorcb, executes, opts, successcb, txself;
if (this.__completed) throw new Error("Transaction already run"); if (this.__completed) throw new Error("Transaction already run");
this.__completed = true; this.__completed = true;
txself = this; txself = this;
successcb = function() {}; successcb = function() {};
if (success) { if (success) {
successcb = function() { successcb = function() {
return success(txself); return success(txself);
}; };
} }
errorcb = function(res) { errorcb = function(res) {};
}; if (error) {
if (error) { errorcb = function(res) {
errorcb = function(res) { return error(txself, res);
return error(txself, res); };
}; }
} console.log("complete - this.transaction_queue"+JSON.stringify(transaction_queue[this.trans_id]));
console.log("complete - this.transaction_queue"+JSON.stringify(transaction_queue[this.trans_id])); transaction_callback_queue[this.trans_id]['success'] = successcb;
transaction_callback_queue[this.trans_id] = successcb; transaction_callback_queue[this.trans_id]['error'] = errorcb;
PhoneGap.exec(null, null, "SQLitePlugin", "executeSqlBatch", transaction_queue[this.trans_id]); PhoneGap.exec(null, null, "SQLitePlugin", "executeSqlBatch", transaction_queue[this.trans_id]);
}; };
return SQLitePluginTransaction; return SQLitePluginTransaction;
})(); })();
}).call(this); }).call(this);

View File

@ -17,21 +17,12 @@ import android.database.sqlite.*;
import android.util.Log; import android.util.Log;
/**
* This class implements the HTML5 database support for Android 1.X devices. It
* is not used for Android 2.X, since HTML5 database is built in to the browser.
*/
public class SQLitePlugin extends Plugin { public class SQLitePlugin extends Plugin {
// Data Definition Language // Data Definition Language
private static final String ALTER = "alter";
private static final String CREATE = "create";
private static final String DROP = "drop";
private static final String TRUNCATE = "truncate";
SQLiteDatabase myDb = null; // Database object SQLiteDatabase myDb = null; // Database object
String path = null; // Database path String path = null; // Database path
String dbName = null; // Database name String dbName = null; // Database name
/** /**
* Constructor. * Constructor.
@ -102,20 +93,6 @@ public class SQLitePlugin extends Plugin {
else else
Log.v("error", "null trans_id"); Log.v("error", "null trans_id");
} }
else if (action.equals("executeSql")) {
String[] s = null;
if (args.isNull(1)) {
s = new String[0];
} else {
JSONArray a = args.getJSONArray(1);
int len = a.length();
s = new String[len];
for (int i = 0; i < len; i++) {
s[i] = a.getString(i);
}
}
this.executeSql(args.getString(0), s, args.getString(2));
}
return new PluginResult(status, result); return new PluginResult(status, result);
} catch (JSONException e) { } catch (JSONException e) {
return new PluginResult(PluginResult.Status.JSON_EXCEPTION); return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
@ -195,36 +172,6 @@ public class SQLitePlugin extends Plugin {
this.myDb = SQLiteDatabase.openOrCreateDatabase(this.dbName, null); this.myDb = SQLiteDatabase.openOrCreateDatabase(this.dbName, null);
} }
/**
* Execute SQL statement.
*
* @param query
* The SQL query
* @param params
* Parameters for the query
* @param tx_id
* Transaction id
*/
public void executeSql(String query, String[] params, String tx_id) {
try {
if (isDDL(query)) {
this.myDb.execSQL(query);
this.sendJavascript("dddb.completeQuery('" + tx_id + "', '');");
}
else {
Cursor myCursor = this.myDb.rawQuery(query, params);
//this.processResults(myCursor, tx_id);
myCursor.close();
}
}
catch (SQLiteException ex) {
ex.printStackTrace();
System.out.println("SQLitePlugin.executeSql(): Error=" + ex.getMessage());
// Send error message back to JavaScript
this.sendJavascript("dddb.fail('" + ex.getMessage() + "','" + tx_id + "');");
}
}
public void executeSqlBatch(String[] queryarr, String[][] paramsarr, String[] queryIDs, String tx_id) { public void executeSqlBatch(String[] queryarr, String[][] paramsarr, String[] queryIDs, String tx_id) {
try { try {
this.myDb.beginTransaction(); this.myDb.beginTransaction();
@ -237,17 +184,16 @@ public class SQLitePlugin extends Plugin {
params = paramsarr[i]; params = paramsarr[i];
query_id = queryIDs[i]; query_id = queryIDs[i];
Cursor myCursor = this.myDb.rawQuery(query, params); Cursor myCursor = this.myDb.rawQuery(query, params);
this.processResults(myCursor, query_id, tx_id); if(query_id != "")
this.processResults(myCursor, query_id, tx_id);
myCursor.close(); myCursor.close();
} }
this.myDb.setTransactionSuccessful(); this.myDb.setTransactionSuccessful();
} }
catch (SQLiteException ex) { catch (SQLiteException ex) {
ex.printStackTrace(); ex.printStackTrace();
System.out.println("SQLitePlugin.executeSql(): Error=" + ex.getMessage()); Log.v("executeSqlBatch", "SQLitePlugin.executeSql(): Error=" + ex.getMessage());
this.sendJavascript("SQLitePluginTransaction.txErrorCallback('" + tx_id + "', '"+ex.getMessage()+"');");
// Send error message back to JavaScript
//this.sendJavascript("dddb.fail('" + ex.getMessage() + "','" + tx_id + "');");
} }
finally { finally {
this.myDb.endTransaction(); this.myDb.endTransaction();
@ -256,20 +202,6 @@ public class SQLitePlugin extends Plugin {
} }
} }
/**
* Checks to see the the query is a Data Definintion command
*
* @param query to be executed
* @return true if it is a DDL command, false otherwise
*/
private boolean isDDL(String query) {
String cmd = query.toLowerCase();
if (cmd.startsWith(DROP) || cmd.startsWith(CREATE) || cmd.startsWith(ALTER) || cmd.startsWith(TRUNCATE)) {
return true;
}
return false;
}
/** /**
* Process query results. * Process query results.
* *
@ -309,9 +241,7 @@ public class SQLitePlugin extends Plugin {
result = fullresult.toString(); result = fullresult.toString();
} }
// Let JavaScript know that there are no more rows
this.sendJavascript(" SQLitePluginTransaction.queryCompleteCallback('" + tx_id + "','" + query_id + "', " + result + ");"); this.sendJavascript(" SQLitePluginTransaction.queryCompleteCallback('" + tx_id + "','" + query_id + "', " + result + ");");
} }
} }