I'm playing with the node-sqlite3 package and ran into a strange situation. This simple script has a simple logic: find if a table exists, if it does empty it, if not - create it.
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('guy.sqlite'); //':memory:'
var tableExists = false;
db.serialize(function() {
db.get("SELECT name FROM sqlite_master WHERE type='table' AND name='lorem'", function(error, row) {
tableExists = (row != undefined);
console.log("xxxxx " +tableExists);
});
console.log("yyyyy " +tableExists);
if (tableExists) {
console.log("table exists. cleaning existing records");
db.run("DELETE FROM lorem", function(error) {
if (error)
console.log(error);
});
}
else {
console.log("creating table")
db.run("CREATE TABLE lorem (info TEXT)", function(error) {
if (error.message.indexOf("already exists") != -1) {
console.log(error);
}
});
}
});
db.close();
But the result I get is:
yyyyy false
creating table
xxxxx true
{ stack: [Getter/Setter],
arguments: undefined,
type: undefined,
message: 'SQLITE_ERROR: table lorem already exists',
errno: 1,
code: 'SQLITE_ERROR' }
According to the serialize command documentation, these queries are supposed to run sequentially. Yet clearly the evaluation of tableExists (marked with 'yyy') occurs before a value is set (marked with 'xxx'), causing an attempt to recreate an existing table.
I can handle the error, but I was wondering what's causing this and how to avoid such behavior in the future.
As always, thanks for your time.
Guy