Mitch
Mitch

Reputation: 21

Are SQL Statements Executed in Sequential Order via PhoneGap's Web SQL Database?

The PhoneGap Web SQL Database documentation at http://docs.phonegap.com/en/3.1.0/cordova_storage_storage.md.html#SQLTransaction lists the following JavaScript code fragment:

function populateDB(tx) {
    tx.executeSql('DROP TABLE IF EXISTS DEMO');
    tx.executeSql('CREATE TABLE IF NOT EXISTS DEMO (id unique, data)');
    tx.executeSql('INSERT INTO DEMO (id, data) VALUES (1, "First row")');
    tx.executeSql('INSERT INTO DEMO (id, data) VALUES (2, "Second row")');
}

Am I guaranteed that the four SQL statements in the above code fragment will execute sequentially (i.e., the DROP TABLE command will definitely execute first, followed by the CREATE TABLE statement second, etc)? There are lots of postings about the asynchronous nature of the PhoneGap Web SQL Database API, but I can't find any postings about the sequential nature of the PhoneGap Web SQL Database API. As you might imagine, it doesn't make any sense for the CREATE TABLE statement to execute if the DROP TABLE statement didn't first finish executing.

Upvotes: 2

Views: 639

Answers (3)

Astra Bear
Astra Bear

Reputation: 2738

I have had the same issue. I wrote a function to make it easier to avoid callback hell. I am sure there are probably similar things out there but here is mine. I tested it with 100,000 lines, no problem

function runSqlSeries(tx, sqls, parameterss, fnum, callback) {
    if (typeof sqls === 'string') {
        sqls = [sqls];
    }
    var totalNumber = sqls.length;
    var sqlIndex = fnum;
    if (parameterss && sqls.length == 1 && parameterss.length > 1) {
        //ie one sql statement run many times
        totalNumber = parameterss.length;
        sqlIndex = 0;
    }
    if (fnum >= totalNumber) {
        callback(true, "success - ran " + fnum + " sql statements");
        return;
    }
    var successFn = function() {
        astracore.runSqlSeries(tx, sqls, parameterss, fnum + 1, callback);
    }
    var errorFn = function(tx, error) {
        callback(false, "Error running function " + fnum + " " + error.message);
    }
    var parameters = [];
    if (parameterss) {
        parameters = parameterss[fnum];
    }

    tx.executeSql(sqls[sqlIndex], parameters, successFn, errorFn);
};

Upvotes: 0

Kyaw Tun
Kyaw Tun

Reputation: 13141

Unfortunately, it is not guaranteed. Websql spec don't say that request must be execute on order it placed, whereas IndexedDB API does. But most implementation respect request ordering, but few don't.

The proper way is listen to request success callback and use tx from the callback to guarantee sequential execution.

Upvotes: 1

Purus
Purus

Reputation: 5799

Yes. The lines are executed in sequential order unless you have have some conditional branching.. like if-else-then.

For the above snippet, it will execute sequentially.. guaranteed.

Upvotes: 0

Related Questions