Fetching multiple mysql queries in one go using QueryQueue

20 Oct, 2017 01:10 PM
 query
 mysql
 nodejs
There are times when we need to query mysql database with multiple queries and then process the results together. I am achieving this here using the QueryQueue module built by me. It is available as a npm package.

To start with let us query a hypothetical employee <-> department schema. I am not going into the details of the scheme as it is very straight forward.

Doing it with plain mysql module



var mysql = require("mysql");

var con = mysql.createConnection({
       host: "localhost",
       user: "root",
       password: "root",
       database: 'itunes_connect' 
});

con.query("SELECT NAME FROM EMPLOYEE WHERE DEPT = ?", ["COMPUTER SCIENCE"], function (err, employees) {
       if (err) {
              console.log(err);
              return;
       }
       con.query("SELECT NAME FROM DEPARTMENT", [], function (err, departments) {
              if (err) {
                     console.log(err);
                     return;
              }
              console.log(employees);
              console.log(departments);
       });
});


Now doing it the QueryQueue way


npm install queryqueue --save

var QueryQueue = require('queryqueue');

QueryQueue.config({
       host: "localhost",
       user: "root",
       password: "root",
       database: 'itunes_connect' 
});

var runner = QueryQueue.Runner(function (result) {
       console.log(result.employees);
       console.log(result.departments);
});

runner.add('employees', "SELECT NAME FROM EMPLOYEE WHERE DEPT = ?", ["COMPUTER SCIENCE"]);
runner.add('departments', "SELECT NAME FROM DEPARTMENT");
runner.start();


A brief explanation



QueryQueue.config - takes database parameters that mysql takes to create connection. This can be done one time in app.js or something similar.

QueryQueue.Runner - takes a callback that is executed once all the queries are completed. The parameter to the callback has the result of each query.

QueryQueue.add - takes a key to which the result is assigned, the query itself and bind parameters if any (optional).

QueryQueue.start - Start the runner and execute all the queries.

NPM package is at - 
https://www.npmjs.com/package/queryqueue

Adios!