Francisco H. Francisco H. - 9 days ago 5
Javascript Question

"handleError is not a function" error running sql.js

I'm trying to implement a REST environment in which, on the client side, client data is stored in a SQLite database.

I have accomplished this before on Cordova using Cordova-sqlite-storage, but I'm unable to accomplish the same using its vanilla-JS counterpart, sql.js

The problem I have is that the

Database()
function isn't returning anything, so I can't do any kind of query.

This is my test file (test.html):



<html>
<head>
<script src="https://rawgit.com/kripken/sql.js/master/js/sql.js"></script>
</head>
<body>
<script>
var sql = window.SQL;
var db = sql.Database(); // Is returning undefined ?

sqlstr = "CREATE TABLE hello (a int, b char);";
sqlstr += "INSERT INTO hello VALUES (0, 'hello');"
sqlstr += "INSERT INTO hello VALUES (1, 'world');"
db.run(sqlstr); // Run the query without returning anything

var res = db.exec("SELECT * FROM hello");

console.log(res);
</script>
</body>
</html>





This returns the following error:


TypeError: this.handleError is not a function

sql.js

Line 466


If I create
this.handleError()
by myself, the error changes to:


TypeError: db is undefined

test.html

Line 13


Any ideas on how to solve this problem? I have looked all over the place, but documentation seems to be scarce.

Answer

sql.Database() needs to be called as a constructor (e.g. db = new sql.Database();). Note the new, as in the Usage example.

var sql = window.SQL;
var db = new sql.Database();

sqlstr = "CREATE TABLE hello (a int, b char);";
sqlstr += "INSERT INTO hello VALUES (0, 'hello');"
sqlstr += "INSERT INTO hello VALUES (1, 'world');"
db.run(sqlstr);

var res = db.exec("SELECT * FROM hello");

console.log(res);
<script src="https://rawgit.com/kripken/sql.js/master/js/sql.js" type="text/javascript"></script>