Mysql select clause in Node.js - javascript

hello i wannna create sql caluse using this function
function selectFrom(reqContents, callback) {
connection.query('SELECT ?? FROM ?? WHERE ?', [ reqContents.attribute,
reqContents.table, reqContents.GET ], function(err, tuple, result) {
if (err) {
console.log(err);
} else {
callback(tuple);
}
});
}
First parameter(reqContents) is array and i have to use this function. But when i wrote multiple where conditions(below example), this query can't operate well.
Example :
reqContents.GET = {
id : user1,
passwd : 1
}

Here is a function I wrote to take the .GET params from reqContents and generate the where clause from its key, values
function buildQuery(params){
// Join the attributes to be in the form of att1,att2,att3
params.attribute = params.attribute.join(",");
// Generate WHERE clause conditions with AND between them
params.GET = (function generateWhere(keyValues){
var str = "";
for(var key in keyValues) {
str += key + " = " + (isNaN(keyValues[key])? '"'+keyValues[key]+'"': keyValues[key]);
if(Object.keys(keyValues).indexOf(key) != Object.keys(keyValues).length-1)
str+= " AND ";
};
return str;
})(params.GET);
return params;
}
This is what you need to do:
function selectFrom(reqContents, callback) {
reqContents = buildQuery(reqContents);
connection.query('SELECT ?? FROM ?? WHERE ?', [ reqContents.attribute,
reqContents.table, reqContents.GET ], function(err, tuple, result) {
if (err) {
console.log(err);
} else {
callback(tuple);
}
});

Related

Nested SQL queries in function in node.js

First of all, i'm new in JS. I have a function that possibly can use multiple requests to get the final data. How can i do this in the right way? In this example participants won't pushed to the dialogs array because it's in async call.
function getDialogs(token, callback) {
//getting user id
con.query("SELECT user_id FROM users_tokens WHERE user_token = '" + token + "'", function(error, results) {
if (error) {
throw error;
}
var userId = results[0].user_id;
//getting all conversation
con.query("SELECT cc.id as conversation_id, cc.type FROM chat_conversations cc INNER JOIN chat_participants cp ON cc.id = cp.conversation_id WHERE cp.user_id = " + userId + " GROUP BY cc.id", function (error, results) {
if (error) {
throw error;
}
var dialogs = [];
for (let i = 0; i < results.length; i++) {
var dialog = {id: results[i].conversation_id};
//getting chat participants
con.query("SELECT user_id FROM chat_participants WHERE conversation_id = " + results[i].conversation_id + " AND user_id != " + userId, function (error, results) {
var participants = [];
for (let j = 0; j< results.length; j++) {
participants.push(results[j].user_id);
}
dialogs[participants] = participants;
});
dialogs.push(dialog);
}
callback(dialogs);
});
});
}
Technically you can use a single request like this
SELECT user_id FROM chat_participants WHERE conversation_id IN (
SELECT
cc.id as conversation_id,
cc.type
FROM
chat_conversations cc
INNER JOIN chat_participants cp ON cc.id = cp.conversation_id
WHERE
cp.user_id IN (
SELECT
user_id
FROM
users_tokens
WHERE
user_token = "TOKEN"
)
GROUP BY
cc.id
)
but there are a few problems with this approach as well.
First of all, it seems like you are only using the user_id of your first row, so please use LIMIT 1 in such cases.
Second of all, it seems like user_id won't ever have a duplicate, so make it a primary key.
Third of all, don't concat your token, node mysql supports having placeholders using ? in your query, like this:
con.query("SELECT * FROM ? WHERE user_id = ?", ["table_name", "userid"])
Fourth of all, promisify your requests so you don't have a callback hell, do something like:
function promiseRequest(query, placeholders) {
return new Promise((res, rej) => {
con.query(query, placeholders, (err, data) => {
if (err) rej(err);
res(data);
});
});
}

how to call an array which is in a function from the another function in javascript?

This is the async function:
async function getpackages(conn, childId, callback) {
var childId = childId;
var request6 = new sql.Request(conn);
var packageQuery = "select OrderId,ChildID from dbo.tbl_Scheduler where NoOfMealsLeft>0 and ChildId=" + childId;
await request6.query(packageQuery, function (err, packagelist) {
if (!err && packagelist.recordsets.length > 0) {
console.log("Error:" + err + "Result:" + util.inspect(packagelist.recordsets[0]));
var orderdetail_ = [];
for (i = 0; i < packagelist.recordsets[0].length; i++) {
orderdetail_.push(packagelist.recordsets[0][i].OrderId);
}
console.log("-->" + orderdetail_);
callback(null, packagelist.recordsets[0]);
} else if (packagelist.recordsets.length < 1) {
callback("Not a valid id input", null);
}
});
};
I need to call the orderdetails_ array in the query. The array contains four data and I need to iterate over 4 data one by one, using the or in the SQL query.
module.exports.newscheduledmeal = function (req, res, next, callback) {
let entered_date = req.query.date;
let childId = req.query.id;
let current_date = new Date().toISOString().slice(0, 10);
if (entered_date < current_date) {
return callback('Please enter date more than or equal to current date.', null);
} else
var conn = new sql.ConnectionPool(dbConfig);
try {
conn.connect().then(function () {
var request = new sql.Request(conn);
getpackages(conn, childId, function (err, orderid) {
if (err) {
callback(err, null);
} else
var PackageidQuery = "select PackageId from dbo.tbl_Order where OrderId=";
request.query(PackageidQuery, function (err, packagelist) {
if (!err) {
conn.close();
callback(null, packagelist.recordsets);
} else {
conn.close();
callback("Error", null);
}
});
});
});
} catch (err) {
console.log("Exception occured:" + err);
conn.close();
callback(err, null);
}
};
I want to get the details of the array which is in getpackages to be used in the module section and specifically in the SQL query section.

How to run code only after query has finished?

I have the following code:
var userFound = false;
let sql = `SELECT box_id, cubby_id, comport, deliveredToUser
FROM recipients
WHERE package_password = ?`;
connection.query(sql, [req.session.sessionUserPackagePassword],
function(err, rows, fields) {
if (!err) {
for (var i = 0; i < rows.length; i++) {
// Make the comparaison case insensitive
if ((rows[i].deliveredToUser).toLowerCase() == `no`) {
userFound = true;
console.log(userFound);
var comport = rows[i].comport;
var command = "open" + rows[i].cubby_id;
var commandClose = "close" + rows[i].cubby_id;
var commandStatus = "status" + rows[i].cubby_id;
console.log(command);
console.log(comport);
var options = {
scriptPath: 'python/scripts',
// pass arguments to the script here
args: [command, comport, commandClose, commandStatus]
};
PythonShell.run('controlLock.py', options, function(err, results) {
if (err) {
res.render('errorConnection', {});
}
console.log('results: %j', results);
});
}
}
console.log(userFound);
// If the query fails to execute
} else {
console.log('Error while performing Query.');
res.render('errorConnection', {});
}
});
connection.end();
if (!userFound) {
//
res.render('pickup/errorAlreadyDelivered', {});
connection.end();
}
I would want this part at the end to be run only once the query has finished:
if (!userFound) {
//
res.render('pickup/errorAlreadyDelivered', {});
connection.end();
}
console.log("connection ended " + userFound);
I placed a console.log outside of the query and at the bottom and despite the query value changing to true it prints out false first, and comes out first because the console.log didn't wait until the query has finish to be able to store the value.

Unable to export variables in async node js files to other nodejs files [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 5 years ago.
I am trying to export variable output to another node js file. But due to async task of fs read function, I am unable to export output variable.
I am unable to understand where I am making mistake.
I am just getting output as undefined.
Could anyone let me know the mistake.
var parseString = require('xml2js').parseString;
var xml = '';
var fs = require('fs');
var async = require('async');
var exports = module.exports = {};
var output;
var out;
async.series([
function (callback) {
fs.readFile('./sample.xml', 'utf8', function(err, data) {
parseString(data, function(err, result) {
xml = result;
var partyNames = xml["TXLife"]["TXLifeRequest"][0]["OLifE"][0]["Party"];
for (var i = 0;i < partyNames.length;i++) {
var firstName, lastName, sex, dob, zip, riskScore, scriptCheckScore, questCheckScore;
if (partyNames[i]["PartyTypeCode"][0]["_"] == "Person" && partyNames[i]["Person"][0]["LastName"] == "JAYME") {
if (partyNames[i]["Person"][0].hasOwnProperty("FirstName")) {
firstName = partyNames[i]["Person"][0]["FirstName"];
}
if (partyNames[i]["Person"][0].hasOwnProperty("LastName")) {
lastName = partyNames[i]["Person"][0]["LastName"];
}
if (partyNames[i]["Person"][0].hasOwnProperty("BirthDate")) {
dob = partyNames[i]["Person"][0]["BirthDate"];
}
if (partyNames[i]["Person"][0].hasOwnProperty("Gender") && partyNames[i]["Person"][0]["Gender"][0].hasOwnProperty("_")) {
sex = partyNames[i]["Person"][0]["Gender"][0]["_"]
}
if (partyNames[i].hasOwnProperty("Address") && partyNames[i]["Address"][0].hasOwnProperty("Zip")) {
zip = partyNames[i]["Address"][0]["Zip"][0];
}
if (partyNames[i].hasOwnProperty("Risk") && partyNames[i]["Risk"][0].hasOwnProperty("OLifEExtension") &&
partyNames[i]["Risk"][0]["OLifEExtension"][5].hasOwnProperty("RiskScoring") && partyNames[i]["Risk"][0]["OLifEExtension"][5]["RiskScoring"][0].hasOwnProperty("RiskScore")) {
riskScore = partyNames[i]["Risk"][0]["OLifEExtension"][5]["RiskScoring"][0]["RiskScore"][0]["QuantitativeScore"][0];
scriptCheckScore = partyNames[i]["Risk"][0]["OLifEExtension"][5]["RiskScoring"][0]["RiskScore"][1]["QuantitativeScore"][0];
questCheckScore = partyNames[i]["Risk"][0]["OLifEExtension"][5]["RiskScoring"][0]["RiskScore"][2]["QuantitativeScore"][0]
console.log("Risk score ",riskScore);
console.log("Script check score ",scriptCheckScore);
console.log("questCheckScore ",questCheckScore);
}
output = firstName + " " + lastName + " " + dob + " " + sex + " " + zip;
callback(null, output);
}
}
})
});
},
function (callback){
out = output;
//module.exports.out = output;
console.log("second");
callback(null, out);
}
],
function(err, result) {
console.log("result", result);
exports.out = result;
}
);
From Module A you will want to invoke a function in Module B (let's call it getFileContent) that takes a callback function - maybe something like this:
var getFileContent(callback) {
:
// async operation to get content
callback(null, results); // assuming no error
:
}
Now in Module A, invoke this - something like this:
var B = require('B'); // whatever module B reference is
B.getFileContent(function(err, result) {
if (err) {
:
} else {
// do something with result
}
});
You are exporting nothing right now because you're calling a function asynchronously, so you should be exporting your function instead of an empty object. For example:
In your main file
var awesomeExports = require('seriesFile');
awesomeExports((err, value) => {
if(err) //Do something with error.
//Do something with value.
})
In your async.series file
//All your includes.
module.exports = (err, callback) => {
async.series([
//Your async.series functions in the array.
],
function(err, result) {
callback(err, result);
}
);
}

How to make object while in for loop using node-mysql?

I have "for" loop in a function and I want to make 1 object instead of many to save draw calls. Is there any way I could do that ? On my tests I have find out that I can't make var outside connection.query which would contain data from what query. So I can't even use global variable which is contained in that query. I am new on this so any help would be great.
External file included in app.js
load_sent_mail: function(person_id, callback, socket) {
pool.getConnection(function(err, connection) {
connection.query('SELECT * FROM `mail` WHERE mail_sender = ' + person_id + '', function(err, mail_data) {
if (!err) {
for (var key in mail_data) {
var items_to_get_info = [];
if (mail_data[key].mail_spot_1 != 0) items_to_get_info.push(mail_data[key].mail_spot_1);
if (mail_data[key].mail_spot_2 != 0) items_to_get_info.push(mail_data[key].mail_spot_2);
if (mail_data[key].mail_spot_3 != 0) items_to_get_info.push(mail_data[key].mail_spot_3);
if (mail_data[key].mail_spot_4 != 0) items_to_get_info.push(mail_data[key].mail_spot_4);
if (items_to_get_info.length) {
connection.query('SELECT `person_items`.`id`, `items`.`item_image`, `items`.`item_place` FROM `person_items` INNER JOIN `items` ON `person_items`.`item_id` = `items`.`item_id` WHERE `person_items`.`id`IN (' + items_to_get_info.join(",") + ')', function(err, items_in_mail) {
if (!err) {
callback(null, items_in_mail);
} else {
console.log(err)
}
});
} {
//0 items
}
}
}
})
connection.release();
});
}
app.js
mail.load_sent_mail(person_id,function(err,items_in_mail){
socket.emit('incoming_mail', items_in_mail);
});
If I understand your question correctly, does this solve your problem:
load_sent_mail: function(person_id, callback, socket) {
pool.getConnection(function(err, connection) {
connection.query('SELECT * FROM `mail` WHERE mail_sender = ' + person_id + '', function(err, mail_data) {
if (!err) {
// Move this line before the loop
var items_to_get_info = [];
for (var key in mail_data) {
if (mail_data[key].mail_spot_1 != 0) items_to_get_info.push(mail_data[key].mail_spot_1);
if (mail_data[key].mail_spot_2 != 0) items_to_get_info.push(mail_data[key].mail_spot_2);
if (mail_data[key].mail_spot_3 != 0) items_to_get_info.push(mail_data[key].mail_spot_3);
if (mail_data[key].mail_spot_4 != 0) items_to_get_info.push(mail_data[key].mail_spot_4);
}
// Move this line after the loop
if (items_to_get_info.length) {
connection.query('SELECT `person_items`.`id`, `items`.`item_image`, `items`.`item_place` FROM `person_items` INNER JOIN `items` ON `person_items`.`item_id` = `items`.`item_id` WHERE `person_items`.`id`IN (' + items_to_get_info.join(",") + ')', function(err, items_in_mail) {
if (!err) {
callback(null, items_in_mail);
} else {
console.log(err)
}
});
}
}
})
connection.release();
});
}
I think I lost a bracket somewhere, but I hope you get the idea!

Categories

Resources