Try to create HTML5 table in WebOS but failed - javascript

I try to create HTML5 table in WebOS using following JavaScript, but the table is not created.
However i can't see any further detail in the log other than the first Mojo.log "Try to create database".
2011-01-25T15:48:50.251507Z [43854] qemux86 user.notice LunaSysMgr: {LunaSysMgrJS}: com.palm.phonegap: Info: Try to create database, palmInitFramework347:2527
Do you have any idea?
Thanks..
var db;
function openDb(){
var shortName = 'mcrm';
var version = '1.0';
var displayName = 'mCRM'
var maxSize = 65536;
db = openDatabase(shortName, version, displayName, maxSize);
try {
db.transaction(
function(transaction) {
Mojo.Log.info("Try to create database");
transaction.executeSql(
'CREATE TABLE IF NOT EXISTS bookmarks'
+ ' (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, '
+ ' resource_id INTEGER NOT NULL '
+ ' resource_type TEXT NOT NULL '
+ ' url TEXT NOT NULL );',
function() {
Mojo.Log.info("DATABASE CREATED");
},
errorHandler
);
}
);
Mojo.Log.info("Is it no error?");
}
function errorHandler(transaction, error) {
Mojo.Log.info("ooopss. Error was ", error.message , " ;Error code:", error.code);
return true;
}

the cause of log file is not giving err message i.e. missing one argument of executeSql
the cause of the error i.e. missing comma at CREATE TABLE statement

Related

Unable to CREATE SQLite tables using JavaScript in for loop

I have a cross platform app developed using AngularJS, JS, Phonegap/Cordova, Monaca and Onsen UI.
I have implemented a SQLite Database in the app to store various data to ensure that the app can be used offline. I have done a few simple tests and this is all working as intended.
I now try to create all the tables I will need in the app (28 in total) in my apps first views onDeviceReady() function. For this I create an array of objects that I will pass one by one to the SQLite CREATE statement as below.
Setting up the table values
// Form values
var formValues = [{
tablename: "table_1",
id: "id_1",
desc: "desc_1",
dataType: "TEXT"
}, {
tablename: "table_2",
id: "id_2",
desc: "desc_2",
dataType: "TEXT"
}, {
...
...
...
...
}, {
tablename: "table_28",
id: "id_28",
desc: "desc_28",
dataType: "TEXT"
}];
Creating the tables
function onDeviceReady() {
for (var i = 0; i < formValues.length; i++) {
var createFormValues = 'CREATE TABLE IF NOT EXISTS ' + formValues[i].tablename + ' (' + formValues[i].id + ' INTEGER, ' + formValues[i].desc + ' ' + formValues[i].dataType + ')';
alert("SQL: " + createFormValues +
"\n\nForm: " + formValues +
"\nName: " + formValues[i].tablename +
"\nID: " + formValues[i].id +
"\nDesc: " + formValues[i].desc +
"\nType: " + formValues[i].dataType);
db.transaction(function (tx) { tx.executeSql(createFormValues); });
}
};
When I run the above code, the alert shows that all the information including the SQL statement is OK. However, when I query each table following the for() loop, it says no tables are created EXCEPT the last table.
I then try the following which DOES create all the tables but is obviously less efficient and manageable.
Calling a function
createFormTables("table_1", "id_1", "desc_1", "TEXT");
createFormTables("table_2", "id_2", "desc_2", "TEXT");
createFormTables("...", "...", "...", "...");
createFormTables("table_28", "id_28", "desc_28", "TEXT");
Executing the function
createFormTables: function (tableName, id, description, dataType) {
var sql = 'CREATE TABLE IF NOT EXISTS ' + tableName + ' (' + id + ' INTEGER, ' + description + ' ' + dataType + ')';
alert("Create Form Field SQL: " + sql);
db.transaction(function (tx) { tx.executeSql(sql); });
},
I know that the SQLite statements are executed asynchronously but I dont understand why that would create the tables in the second example and not the first? How do I create the tables using the first example? I can set a $timeout to execute each INSERT statement but this seems unnecessary and will cause delays.
I would use the JavaScript "Object" aproach to avoid conflict when calling function 'createFormTables' with something like:
var QuerySet = function(){
//OPTIONAL: I use JQuery Deferred to catch when an async event has finished
this.defRes = new $.Deferred();
this.defResProm = this.defRes.promise();
};
QuerySet.prototype.createFormTables= function(inputData){
//do your stuff and manage when this.defRes is resolved and results it sends back (if a result is needed)
this.sqlToExecute = "// YOUR SQL QUERY";
var self=this;
$.when(
(new SqlResult(this.sqlToExecute)).execSqlCustomDeferred(), //read below for SqlResult() explanations
self
).done(function(sqlRes,self){
self.defRes.resolve();
});
return this.defResProm;
};
Then in the code:
creatFromTables[i] = (new QuerySet()).createFormTables(inputData);
createFromTables[i].defRes.done(function(res){//do stuff with the result});
Don't need to use $.Deferred() but I think it could be useful if you want to know when all the tables have been created.
And here is sqlResult that is used to call the transaction on the DB itself:
var SqlResult = function(sqlToExecute,bracketValues){
//console.log("SqlResult("+sqlToExecute+','+bracketValues+') starts');
this.sqlToExecute = sqlToExecute;
this.bracketValues =bracketValues;
};
SqlResult.prototype.execSqlCustomDeferred = function(){
var execSqlCustomDeferredRes = $.Deferred();
var execSqlCustomDeferredResProm = execSqlCustomDeferredRes.promise();
//console.log("SqlResult.execSqlCustomDeferred sqlToExecute is: "+this.sqlToExecute);
var sqlToExecuteForTx = this.sqlToExecute;
var bracketValuesForTx = this.bracketValues;
DbManagement.db.transaction(function(tx){
console.log("SqlResult.execSqlCustomDeferred in TX sqlToExecute is: "+sqlToExecuteForTx);
if(bracketValuesForTx!=null){
console.log("SqlResult.execSqlCustomDeferred bracket value is: "+ArrayManagement.arrayToString(bracketValuesForTx));
}
tx.executeSql(sqlToExecuteForTx,bracketValuesForTx,success,error);
function success(tx,rs){
//console.log('before execSqlCustomDeferredRes resolve ' + execSqlCustomDeferredRes.state());
execSqlCustomDeferredRes.resolve(rs);
//console.log('before execSqlCustomDeferredRes resolve after ' + execSqlCustomDeferredRes.state());
}
function error(tx,error){
console.log('execSqlCustomDeferred error ' + error.message);
execSqlCustomDeferredRes.reject(error);
}
});
return execSqlCustomDeferredResProm;
};

UserCannotBeAlteredWithoutSessionError when updating PFUser on Parse from Heroku node.js app

I'm trying to update a PFUser in my Parse database from a node.js app running on Heroku. I'm calling the Parse cloud function from an iOS app.
Here's the part of the code I use to update the user on parse as well as creating the user on Stripe (the Stripe part works fine):
Parse.Cloud.define("createCustomerWithCreditCardToken", function(request, response) {
var userId = request.user.id;
var sourceId = request.params.creditCardToken;
var customerId;
var userSessionToken = request.user.getSessionToken();
console.log('userId: ' + userId + ' source: ' + sourceId + ' userSessionToken: ' + userSessionToken);
stripe.customers.create({
source: sourceId,
description: userId
}, function(error, customer) {
if (error !== null) {
response.error('error creating customer: ' + error);
}else {
var userQuery = new Parse.Query('User');
userQuery.equalTo('objectId', userId);
userQuery.first({sessionToken: userSessionToken}).then(function(user) {
console.log('user from parse query: ' + user.get("username"));
user.set("stripeCustomerId", customer.id);
user.save(null, {
success: function(parseCustomer) {
console.log('customer saved to parse: ' + parseCustomer);
},
error: function(error, parseCustomer) {
console.log('customer save failed: ' + JSON.stringify(error, null, 2) + ' with error: ' + JSON.stringify(parseCustomer,null, 2));
}
});
});
customerId = customer.id;
console.log('customerId: '+ customerId);
// response.success(customer);
response.success('Customer: ' + JSON.stringify(customer, null, 2) + 'error: ' + error);
}
});
});
I get the following error log output when I run this:
error log output
error: { "code": 206, "message": "Parse::UserCannotBeAlteredWithoutSessionError" }
In this post the current user concept in a node.js app context is discussed by a Parse engineer.
Also in Cloud Code, the concept of a method that returns the current
user makes sense, as it does in JavaScript on a web page, because
there’s only one active request and only one user. However in a
context like node.js, there can’t be a global current user, which
requires explicit passing of the session token.
Essentially he advises to do this:
Parse.Cloud.define('findBacon', function(req, res) {
var token = req.user.getSessionToken();
var query = new Parse.Query('Bacon');
// Pass the session token to the query
query.find({ sessionToken: token }).then( ... );
});
I have also tried using {useMasterKey:true} instead of {sessionToken:userSessionToken} which produces the same error.
I might just be missing some obvious detail, but I just can't seem to find it. Any ideas on how to solve this are greatly appreciated.
Turns out there's a third way of handling credentials:
Parse.Cloud.useMasterKey();
I placed this line in the beginning of the entire method, that did it for me. I'm not sure of the implications of giving the whole function these credentials though.
I'm not sure when you would use the other options either.
If someone comes across this and would like to elaborate, I'll be happy to give the right answer to a good explanation of when to grant which credentials.

better approach to access datatabase and creating models in cross platform apps

for example , i have been using following approach in my cross platform apps to accessing sqlite database as follows
To access database i have made a saperate .js for UserProfile table
function DBUserProfile()
{
this.selectUserName = function(userId, callback)
{
try
{
//Get Data
localDB.transaction(function selectUserProfileData(tx)
{
var objDBDatabaseSchema = new DBDatabaseSchema();
var sqlCommand = 'SELECT username FROM '
+ objDBDatabaseSchema.UserProfileMetaData.USER_PROFILE_TABLE_NAME
+' WHERE engineer_id='
+ '="' + userId + '"';
objDBDatabaseSchema = null;
tx.executeSql(sqlCommand,[],function selectUserNameResult(tx, results)
{
if (results.rows.length > 0 )
{
var userId = results.rows.item(0).username ;
callback(userId);
}
else
{
var userId = "";
callback(userId);
}
}, errorDB);
}, errorDB);
}
catch (e)
{
// TODO: handle exception
console.log("DBUserProfile - selectUserName " + e);
}
};
}
and this is how i use them in a pages
var objDBUserProfile = new DBUserProfile();
objDBUserProfile.selectUserName("3443" , function(id){
//
});
but the above approach is pretty time consuming i have been end up creating lot of models and db files to access tables and lot of new objects , so does anyone has a better approach in jquery to cut down the development time. any suggestions are welcome

How to get the context of a Web Sql error?

I start deploying an offline application on iPhones, but it's still under heavy developpment.
I have a simple error handler for my query :
db.transaction(tx) {
tx.executeSql("SELECT * FROM TABLE",[], successHandler, errorHandler);
});
function errorHandler(transaction, error) {
alert("Error : " + error.message);
}
When I test myself the application, and get an error, I manage to find what was the query generating the error. But when it's my users (distant users, of course), it's very difficult, as the error messages are not specific.
Is there a way to add context info to my error messages, for example the sql query, or a comment parameter ?
You could use a pattern like this:
db.transaction(tx) {
doQuery(tx, "SELECT * FROM TABLE",[],theSuccessHandler)
});
function doQuery(tx, query, values, successHandler) {
tx.executeSql(query, values, successHandler, errorHandler);
function errorHandler(transaction, error) {
alert("Error : " + error.message + " in " + query);
}
}
I ehanced Myrne answer to add query parameters and a free context string :
function doQuery(tx, query, values, successHandler, context)
{
tx.executeSql(query, values, successHandler, errorHandler);
function errorHandler(transaction, error)
{
var text_context = context != undefined && context != "" ? "(" + context + ") " : "";
alert("Error "+text_context+": " + error.message + " in " + query + " (params : "+values.join(", ")+")");
}
}
This will return this kind of error :
Error (function update_commande) : could not prepare statement (1 no such column: field3) in UPDATE table SET field2 = ?, field3 = ? WHERE field1 = ? (params : 1.63, 1449, 606)

html5sql - Can't seem to connect to my DB

I'm using html5sql.com for doing html5 DB stuff :o)
- Really a great module...
However, I got stuck!
At my index.html/index.js I create my database and tables in it.
try {
html5sql.openDatabase("com.dynamicvenues.fairkeyMobile.db","Questionnaire",3*1024*1024);
html5sql.process(
[
"CREATE TABLE IF NOT EXISTS Questionnaire (uid INTEGER, json TEXT, hash TEXT);",
"CREATE TABLE IF NOT EXISTS Answers (id INTEGER PRIMARY KEY, visitor_id TEXT, json TEXT);"
],
function(){
console.log("Success Creating Tables");
},
function(error, statement){
console.error("Error: " + error.message + " when processing " + statement);
}
)
} catch(error) {
alert("Database create failed: "+error.message);
}
And further in the same page I populate one table with data:
jQuery.get(serverHttp+"json.php?exhibitorID="+exhibitorID, function(data){
var html = $(data).map(function() {
return $(this).html();
});
var jsonStr = html[0];
var exhibitorID = html[1];
var hashStr = html[2];
var SQL = "INSERT INTO Questionnaire (uid, json, hash) VALUES ("+exhibitorID+",'"+jsonStr+"','"+hashStr+"')";
try {
html5sql.process(SQL,
function(){
console.log('Inserted 1 row!');
},
function(){
console.error("Error: " + error.message + " when processing " + statement);
}
)
} catch(error) {
alert("Query failed: "+error);
}
Now, in a different page called questionnaire.html/questionnaire.js I'm trying to retrieve the data I stored in the table Questionnaire.
html5sql.process(
["SELECT * FROM Questionnaire;"],
function(transaction, results, rowsArray){
for(var i = 0; i < rowsArray.length; i++){
var uid = rowsArray[i].uid;
var json = rowsArray[i].json;
var hash = rowsArray[i].hash;
console.log("Retrieved rows: "+uid+" - "+json+" "+hash);
}
console.log("Done selecting data");
},
function(error, statement){
console.error(error.message+" Occured while processing: "+statement);
}
);
What am I doing wrong???
Regards,
Daniel
Solved! Inserted: html5sql.openDatabase("com.dynamicvenues.fairkeyMobile.db","Questionnaire",3*102‌​4*1024); Before html5sql.process() at questionnaire.js

Categories

Resources