Node JS - mysql - querying inside of a callback of a query - javascript

I was wondering if it's possible to query the database inside of a callback of another query. So for example,
connection.connect();
connection.query(query, [param1, param2], function(err, rows, fields) {
// do something
connection.query(new_query, function(err, rows, fields) {
// do something else
});
});
connection.end();
I am getting a Error: Cannot enqueue Query after invoking quit. error on line 4 of this code. So I was wondering if this is possible at all.

Explanation of your problem:
js is executed line by line. In order, that would be:
connection.connect()
connection.query( params...) (async i/o, placing callbacks)
connection.end()
Then, when a the query to the database is finished, the callback in 2. is executed, but the 3. was executed before, ending connection. So in that point in callback, you cant make another query, because the connection is closed.
Solution:
connection.end() should be inside the last nested query
Fixed code:
connection.connect();
connection.query(query, [param1, param2], function(err, rows, fields) {
// do something
connection.query(new_query, function(err, rows, fields) {
// do something else
connection.end();
});
});

Yes, you can issue queries in callback. You're getting the error because the connection.end call is NOT in a callback. Where you have it now, it will be called before the first callback fires.

i try to use for connection.release();
pool.getconnection(function(err,connection){
if(!err)
{
connection.release();//after this perform query operation
connection.query(query, [param1, param2], function(err, rows, fields) {
// do something
connection.query(new_query, function(err, rows, fields) {
// do something else
});
});
}
})

Related

nodejs/pg, callback parameters

I am fairly new to node.js, and haven't done much of javascripts. Tried to search my problem, but couldn't find specific answer related to it.
So, while I was working on attaching the PostgreSQL to my app, I followed a snippet from some example on web, and it seems like working pretty well.
Anyways I wanted to understand how it works, I had a problem understanding specific part of the following code:
module.exports = {
query: function(text, values, cb) {
pool.connect(function(err, client, done) {
if(err) {
return console.error('error fetching client from pool', err);
}
console.log(client);
client.query(text, values, function(err, result) {
done();
cb(err, result);
})
});
}
}
and the specific part is:
pool.connect(function(err, client, done) { ... }
What I understood is connect function takes callback function with err, client, and done as parameter, however I couldn't understand from where the function(err, client, done) is passed to connect function as parameter. By where, I mean an object or a caller that call connect function.
I had suspected that it would be handled internally, but I wanted to know clearly.
Bydefault all callback function, the first parameter must be an error and second will be a result of ur callback function.
Done is similar to callback keyword, which says, your task is over and give response back from where the function has called, its just like return statement in normal function
example:
function callbackDemo(arg1, arg2, callback) {
if (condition)
callback(null, "Success");
else
callback("error");
}
callbackDemo(1, 2, function(err, result){
if(!err)
console(result);
else
console.log(err);
});

NodeJS, doesn't close mysql connection

I actually use this MYSQL Client and when I close a connection is actually never closes , so I can see in the status.
router.get('/test', function (req, res, next) {
var conn = mysql.createConnection(config);
conn.connect();
conn.query('select * from invoices ', function (err, result) {
if (err) {
throw err;
}
res.status(200).json({result: result});
conn.end();// || conn.destroy();
});
});
Move conn.end() out of the query callback - as described in node-mysql's documentation:
Every method you invoke on a connection is queued and executed in sequence.
Closing the connection is done using end() which makes sure all remaining queries are executed before sending a quit packet to the mysql server.
connection.connect();
connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) {
if (err) throw err;
console.log('The solution is: ', rows[0].solution);
});
connection.end();
Also you can use pool.
Check this link.
Connections can be pooled to ease sharing a single connection, or
managing multiple connections.
When you are done with a connection, just call connection.release()
and the connection will return to the pool, ready to be used again by
someone else.
pool.end(function (err) {
// all connections in the pool have ended
});

How do I call MySql procedures from Node JS

I want to call a stored procedure from MySql node:
How do I call it? The documentation says:
You can call stored procedures from your queries as with any other mysql driver. If the stored procedure produces several result sets, they are exposed to you the same way as the results for multiple statement queries
I tried searching for it on internet but got very old results which do not work anymore.
I tried:
connection.query('procedure_name()', {84,Bhuwan}, function(err, result) {
connection.destroy();
if (err)
throw err;
callback(err, result);
});
But I am getting error.
Can anyone provide a proper syntax for it??
You have to use 'call' command and if you have parameters to pass to the query, you need to add '?' marks. Check the code.
connection.query("call procedure_name(?,?)", [param1, param2], function (err, result) {
if (err) {
console.log("err:", err);
} else {
console.log("results:", result);
}
});

getting TypeError: Cannot call method 'releaseConnection' of null in mysql node.js

i am using mysql felix node.js module.
i am using its pool connection.
i have many queries in my server side (written in node) that are written like this:
this.courtsAmount = function(date, callback){
pool.getConnection(function(err, connection) {
connection.query('SELECT MAX(id) AS result from courts where date="' + date + '"', function(err, rows, fields){
connection.release();
if (err) throw err;
if (rows[0].result)
callback(rows[0].result);
else
callback(0);
});
});
};
for some reason i keep getting this error (from all sorts of functions that are written like this):
Type Error: Cannot call method 'releaseConnection' of null
which is pointing to the 'connection.release()' line.
i really don't understand what is the problem here, as i understand from the API inside the function of pool.getConnection i am supposed to have full access to the connection. maybe it is an issue of something to have to do with timeout of the connection? i believe it is not the case because this error happens while i am actually going through my site.
another question:
do i have to deal with the option that connections will timeout if i use the pool?
and if the answer is yes, how should i do it?
thanks.
I'd recommend adding error checking before attempting to use the connection instance. I've updated your code (see my comments inline):
this.courtsAmount = function(date, callback) {
pool.getConnection(function(err, connection) {
if (err) throw err; // <-- 'connection' might be null, so add an error check here
connection.query('SELECT MAX(id) AS result from courts where date="' + date + '"', function(err, rows, fields) {
if (err) throw err; // <-- moved this line up to check for an error first
connection.release(); // <-- moved this line down so error checking happens first
if (rows[0].result)
callback(rows[0].result);
else
callback(0);
});
});
};
Also, if the date instance is coming from an untrusted source, then your code is vulnerable to SQL injection. You might consider switching to mysql2 and using a prepared statement.

Node.js - Break out of callback function and return true/false in the parent functon

I'm using the Node Express framework to build an API and I run into a problem regarding the Basic Auth functionality. I need to run an SQL query to retrieve information about a user and validate their credentials. The issue occurs after the query has been completed. The SQL data is sent into a callback function as shown below. I want to do all the validation inside that callback but I want to break out of the SQL callback and return true/false from the express.basicAuth() function. I have tried setting a global variable and then accessing it outside of the SQL callback but sometimes the query might not have finished by the time that it gets the block that accesses that global variable. Thanks in advance for your help.
var auth = express.basicAuth(function(user, pass) {
// Query to select information regarding the requested user
/* Query here to find the requested user's data */
client.query(query, function (err, rows, fields) {
if (err) throw err;
GLOBAL.sql = rows;
/* I want to break out of this query callback function and return true from this auth variable */
});
// Sometimes the query isn't completed when it gets to this stage
console.log(JSON.stringify(GLOBAL.sql));
});
express.basicAuth also supports asynchronous operation:
var auth = express.basicAuth(function(user, pass, next) {
...
client.query(query, function (err, rows, fields) {
if (err)
next(err);
else
if (/* authentication successful */)
next(null, user); // <-- sets 'req.remoteUser' to the username
else
next(null, false);
});
});

Categories

Resources