12

Pretty-printing recordsets from the mssql node package

 3 years ago
source link: https://stevedrivendevelopment.com/2016/08/19/pretty-printing-recordsets-from-the-mssql-node-package/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Pretty-printing recordsets from the mssql node package

I’ve been using the node mssql package in node scripts, and it’s great but it doesn’t have a pretty-printer for recordsets; console.dir() will print something out but you get some nasty-looking JSON formatted output.

This function is just a reusable printer for recordsets returned from sql.Request().query() or sql.Request().batch().methods.

Pass in the recordset and a function which prints the line, eg;

printTable(recordset, console.log);

And you get something more famililar with a SQL Server Management Studio feel;

-- SELECT id, name from table
id   name
===========
6    p1
7    p2
8    p3

Here’s the function:

// pretty-print a table returned from mssql node package 
// https://www.npmjs.com/package/mssql
var printTable = function(recordset, printLine) {

 var padEnd = function (str, paddingValue) {
   while(str.length < paddingValue) {
     str = str + " ";
   }
   return str;
 };

 var print = function(value) {
   return (value == undefined || value == null) ? "(null)" : value.toString(); 
 }

 var maxWidth = {};

 for(var c in recordset.columns) {
   maxWidth[c] = c.length;
 }

 var l = recordset.length;
 for(var r = 0; r < l; r++) {
   var row = recordset[r];
   for(var c in recordset.columns) {
     var col = recordset.columns[c];
     row[c] = print(row[c]);
     maxWidth[c] = Math.max(maxWidth[c], row[c].length);
   }
 }

 var head = "";
 for(var c in recordset.columns) {
   var head = head + padEnd(c, maxWidth[c]) + " ";
 }

 printLine(head);

 var sep = Array(head.length).join("=");
 
 printLine(sep);

 for(var r = 0; r < l; r++) {
   var row = recordset[r];
   var printedRow = "";
   for(var c in recordset.columns) {
     printedRow = printedRow + padEnd(row[c], maxWidth[c]) + " ";
   }
   printLine(printedRow);
 }
};

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK