I currently have a transaction that attempts to insert data into a table. If the data is already in the table a constraint failed error is raised and a select is run to get the ID.
t2.executeSql('INSERT INTO books (book) VALUES (?);',
[record],
function (t2, r) { // SQL_successfulCallback
record = r.insertId;
},
function (t2, err) { // SQL_errorCallback
if (err.message !== 'constraint failed') { // insert failed because of other
// reason - fail transaction
console.log('Insert SQL error ' + err.code + ' - ' + err.message + '.');
return true;
} else { // insert failed because data was already in the table
t2.executeSql('SELECT bookID FROM books WHERE book=?',
[record],
function (t, r) { // SQL_successfulCallback
record = r.rows.item(0).classificationID;
},
function (t, err) { // SQL_errorCallback
console.log('Lookup SQL error ' + err.code + ' - ' + err.message + '.');
return true;
}
);
return false;
}
}
);
I want to speed the transaction up so I thought I would see if the data was in the table first. If it isn’t then insert it…
t2.executeSql('SELECT bookID FROM books WHERE book=?',
[record],
function (t2, r) { // SQL_successfulCallback
if (r.rows.length !== 0) {
record = r.rows.item(0).bookID;
} else {
t2.executeSql('INSERT INTO books (book) VALUES (?);',
[record],
function(t2, r){ // SQL_successfulCallbac
record = r.insertId;
},
function (t2, err) { // SQL_errorCallback
if (err.message !== 'constraint failed') { // insert failed because of other
// reason - fail transaction
console.log('Insert SQL error ' + err.code + ' - ' + err.message + '.');
return true;
} else { // insert failed because data was already in the table
return false;
}
}
);
}
},
function (t, err) { // SQL_errorCallback
console.log('Lookup SQL error ' + err.code + ' - ' + err.message + '.');
return true;
}
);
…but it doesn’t work. This transaction runs all the selects then does the inserts. How can I make the second method work?
I’m assuming the transaction is queuing the request. So your queue will look like this
Select 1
Select 2
Select 3
Then when you commit your transaction looks like this after the first call.
Select 2
Select 3
Insert 1
Insert 2
Insert 3
This is happening because the the functions to call the inserts are exected after the select is ran and this doesn’t happen until the transaction commits but the selects have already be registered.
In order to get it to be
select1
insert1
select2
insert2
I would create a separate transaction for each select statement.