views:

367

answers:

2

Instead of doing an each loop on a JSON file containing a list of SQL statments and passing them one at a time, is it possible with Safari client side storage to simply wrap the data in "BEGIN TRANSACTION" / "COMMIT TRANSACTION" and pass that to the database system in a single call? Looping 1,000+ statements takes too much time.

Currently iterating one transaction at a time:

$j.getJSON("update1.json",
  function(data){
    $j.each(data, function(i,item){
      testDB.transaction(
          function (transaction) {
              transaction.executeSql(data[i], [], nullDataHandler, errorHandler);
          }
      );
   });
});

Trying to figure out how to make just one call:

$j.getJSON("update1.json",
  function(data){
      testDB.transaction(
          function (transaction) {
              transaction.executeSql(data, [], nullDataHandler, errorHandler);
          }
      );
});

Has anybody tried this yet and succeeded?

A: 

I haven't ever messed with HTML5 database storage (have with local/sessionStorage though) and I would assume that it's possible to run one huge string of statements. Use data.join(separator here) to get the string representation of the data array.

Eli Grey
Thank you for your answer. It seems it won't accept more then one statement at a time, even when separated with ';'.
SKFox
It is a little database, meant for simple operations. If you want a full-blown database send the data to a server. If you want off-line operation, in a single-threaded javascript app then the built-in db works fine.
James Black
A: 

Every example I could find in the documentation seems to show only one SQL statement per executeSql command. I would just suggest showing an "ajax spinner" loading graphic and execute your SQL in a loop. You can keep it all within the transaction, but the loop would still need to be there:

$j.getJSON("update1.json",
    function(data){
       testDB.transaction(
           function (transaction) {
               for(var i = 0; i < data.length; i++){
                   transaction.executeSql(data[i], [], nullDataHandler, errorHandler);
               }
           }
       );
    }
);

Moving the loop inside the transaction and using the for i = should help get a little more speed out of your loop. $.each is good for less than a 1000 iterations, after that the native for(var = i... will probably be faster.

Note Using my code, if any of your SQL statements throw errors, the entire transaction will fail. If that is not your intention, you will need to keep the loop outside the transaction.

Doug Neiner
Correcting your Note. executeSql supports providing callback for errors, in your example it is errorHandler. If this handler returns true the transaction will fails, if false it will continue (or may be the other way around).
Michael