prepared statement node sqlite3 and Like keyword - javascript

Im trying to create a function that lets me search and order a list using Node and SQLite3. Im not quite sure what I am doing wrong, but when I include the sort parameter the code stops working and I get "Error: SQLITE_ERROR: Near "?": syntax error".
This is the code.
exports.search = function(name, sort, sortAscDesc, cb) {
var sqlQuery = "SELECT * FROM Crimestat";
if (name != undefined) {
name = "%" + name + "%";
sqlQuery += " WHERE municipacility LIKE ?";
}
if (sort != undefined) {
if (sortAscDesc != undefined) {
sqlQuery += " ORDER BY ? ?";
} else {
sqlQuery += " ORDER BY ASC";
}
}
console.log("sql query " + sqlQuery)
db.all(sqlQuery, name, sort, sortAscDesc, function(err, row) {
if (row == undefined) {
console.log("error " + err)
cb(false);
} else {
cb(row);
}
});
Thank you in advance

Related

While loop is not working in document db stored procedure

I have a bellow code in my stored procedure , but azure is throwing an exception
"maximum allotted time limit exceed" whenever I have while loop with true condition. Unless and until unique validation performed I don't wanna proceed further execution.
if (field.validations.unique != undefined && field.validations.unique) {
var gotResponse = false;
var query = "select * from root r where r." + field.name + "='" + record[field.name] + "' AND r.obj_type = '" + record.obj_type + "'";
var isAccepted = collection.queryDocuments(collectionLink, query, {}, function (err, existingDocs, responseOptions) {
if (existingDocs.length > 0 && existingDocs[0].id != record.id) {
if (!record.error['unique'])
record.error['unique'] = [];
record.error['unique'].push(field.name);
}
gotResponse = true;
});
while(true){
if(gotResponse ) break;
}
}

javascript league api combinedTick callback

async run(message, args) {
LolApi.init('censored', 'na');
LolApi.setRateLimit(10, 500);
var input = '';
args = args.toLowerCase();
LolApi.Summoner.getByName(args, function (err, summoner) {
if (!err) {
Name = summoner[args].name;
Name = Name.toLowerCase();
Id = summoner[Name].id;
Level = summoner[Name].summonerLevel;
input += "Name: " + summoner[Name].name + '\n' +
"Level: " + Level + "\n";
console.log(input);
//message.reply(input);
process.nextTick(LolApi.getLeagueData);
}
else {
message.reply('Error fam.');
}
});
setTimeout(function(){console.log('Waiting...')},2000);
LolApi.getLeagueData(Id,'NA', function (err, summoner) {
if (!err) {
Tier = summoner[Id][0].tier;
Division = summoner[Id][0].entries[0].division;
input += "Tier: " + Tier + '\n' +
"Division: " + Division;
message.reply(input);
} else {
console.log(Name);
console.log(err);
message.reply('Error Fam' + Id + "test");
}
});
}
When i run this code up get an error 404 running the second part. It gives me an saying combinedTickCallback but im not sure what this means because i am a noob. I use node.js if that helps with anything

Node sqlite3 when to close db

I cannot figure out when to close a db in node-sqlite3, or really how to use the package in general. It seems if I run this, I get "no such table:rooms". Eventually after running it enough times, I might manage to make the table.
var sqlite3 = require('sqlite3').verbose();
class RoomManager{
constructor(options){
this.db = this._createDb();
this.table = "rooms";
this._createTable();
this.addRoom({
name : 'test3'
}).getRooms()
this.deleteRoom({
name : 'test3'
}).getRooms();
return this;
}
_createDb() {
return new sqlite3.Database('chat');
}
_createTable(){
this.db.run("CREATE TABLE IF NOT EXISTS " + this.table + " (name TEXT, size INT)");
return this;
}
addRoom(options){
this.db.run("INSERT INTO " + this.table + " (name, size) VALUES ($name, $size)", {
$name : options.name,
$size : options.size || 1000
});
return this;
}
getRooms(){
this.db.all("SELECT rowid, name, size FROM " + this.table, function(err, rows) {
rows.forEach(function (row) {
console.log(row.rowid + ": " + row.name + " - " + row.size);
});
});
return this;
}
getRoom(options){
if(options.name){
this.db.get("SELECT * FROM " + this.table + " WHERE name = $name", {
$name : options.name
}, function(err, row){
return row;
});
}
}
deleteRoom(options){
this.db.run("DELETE FROM " + this.table + " WHERE name = $name", {
$name : options.name
});
return this;
}
}
module.exports = RoomManager;
Your problem that Node is asynchronous. So, you must wait end of command by callback function. e.g.
this.db.run(query, params, function(err) {
if (err)
return console.log(err);
// do next query here
})
Sqlite module can control flow by db.serialize. Imho it's useless in common cases. Better use async module or promises for it.

Unit testing a function and simulating an event emitter response

I am currently writing some tests against the code shown below in node.js using mocha. I want to simulate the response from the event emitter 'check_user'. I have sinon.js but I can't get my mind in the right place to work out the best way to simulate the response.
Anyone able to offer some advice on how to go about this?
TgCustomCommand.contact = new Command("contact", "Will send you a users contact card to add to your contact list. Usage is .contact nick", function (input, callback) {
var payload = input;
//Switch our contact to payload.to as this is what our checkuser function looks at
//Check the command over
if (payload.command_args === false) {
payload.response = 'msg ' + payload.to + ' ' + this.description;
return callback(null, payload);
} else {
payload.return = payload.to;
payload.to = payload.command_args; //Set up ready for nick check
//Check the nick exists
emitter.emit('check_user', payload, function (err, result) {
if (err) return callback(err, null);
payload = input; //Reset our payload so we have correct payload.to
//Check how many users we returned
if (result.length === 0) { //Not in our contact list
payload.response = 'msg ' + payload.return + ' I do not have that person in my contact list!';
return callback(null, payload);
} else if (result.length === 1) {
payload.to = result[0].Nick;
payload.response = "send_contact " + payload.return + ' ' + result[0].Phone + ' ' + result[0].Nick + " _";
return callback(null, payload);
}
else {
//loop through our object and create a list of those returned
payload.response = "msg " + payload.return + " I know multiple people with a similar nick: ";
for (var i = 0; i < result.length; i++) {
log.debug(result[i].Nick);
payload.response = payload.response + result[i].Nick + " ";
}
return callback(null, payload);
}
});
}
;
});

i'm developing a phonegap application but it cannot connect the database i attached the following program?

** i'm developing a phonegap application but it cannot connect the database i attached the following program? my code is below:**
function onDeviceReady() {
var mobno = document.getElementById("mobno").value;
var cust = document.getElementById("cust").value;
db = window.openDatabase("RegistrationDB", "1.0", "Registration", 200000);
if (dbCreated)
else
db.transaction(populateDB, transaction_error, populateDB_success);
}
function populateDB(tx) {
tx.executeSql('DROP TABLE IF EXISTS Registration');
var sql = "CREATE TABLE IF NOT EXISTS Registration ( "
+ "mobno INTEGER(50), " + "custname VARCHAR(50))";
tx.executeSql(sql);
var mobno = document.getElementById("mobno").value;
var cust = document.getElementById("cust").value;
tx.executeSql("INSERT INTO Registration (mobno,custname) VALUES ('"+ mobno +"','"+ cust +"')");
}
function transaction_error(tx, error) {
alert("Database Error: " + error);
}
function populateDB_success() {
dbCreated = true;
// where you want to move
alert("Successfully inserted");
window.location="file:///android_asset/www/login.html";
}
If you would like to use the Cordova SqlLite plugin you have to install it:
cordova plugin add https://github.com/brodysoft/Cordova-SQLitePlugin
next you can create the db in device ready:
function onDeviceReady() {
var db = window.sqlitePlugin.openDatabase("Database", "1.0", "Demo", -1);
db.transaction(function(tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS test_table (id integer primary key, data text, data_num integer)');
tx.executeSql("INSERT INTO test_table (data, data_num) VALUES (?,?)", ["test", 100], function(tx, res) {
console.log("insertId: " + res.insertId + " -- probably 1");
console.log("rowsAffected: " + res.rowsAffected + " -- should be 1");
tx.executeSql("select count(id) as cnt from test_table;", [], function(tx, res) {
console.log("res.rows.length: " + res.rows.length + " -- should be 1");
console.log("res.rows.item(0).cnt: " + res.rows.item(0).cnt + " -- should be 1");
});
}, function(e) {
console.log("ERROR: " + e.message);
});
});
}

Categories