var mysql      = require('mysql-native');
var db = mysql.createTCPClient();
db.auth('classicmodels', 'classicmodels', 'Nr4VCCub6NuG8Vzd');

function escapeHtml(unsafe) {
  return unsafe
      .replace(/&(?!amp;)/g, "&")
      .replace(/<(?!lt;)/g, "&lt;")
      .replace(/>(?!gt;)/g, "&gt;")
      .replace(/"(?!quot;)/g, "&quot;")
      .replace(/'(?!#039;)/g, "&#039;");
}


var pipe = process.stdout;

function oneStep(next) {
        pipe.write("<h1>Kunden</h1>\n");
        pipe.write("<table>\n");
        pipe.write("<tr><th>Kunde</th><th>Stadt</th><th>Land</th></tr>\n");
        var customers = db.query("SELECT customerName, city, country FROM customers ORDER BY customerName");
        customers.addListener('row', function(customer) {
                var name = escapeHtml(customer.customerName);
                var city = escapeHtml(customer.city);
                var country = escapeHtml(customer.country);

                pipe.write("<tr><td>"+name+"</td><td>"+city+"</td><td>"+country+"</td></tr>\n");
        });
        customers.addListener('end', function() {
                pipe.write("</table>");

                pipe.write("<h1>Produkte</h1>\n");
                pipe.write("<table>\n");
                pipe.write("<tr><th>Code</th><th>Name</th><th>Anbieter</th></tr>\n");
                var products = db.query("SELECT productCode, productName, productVendor FROM products ORDER BY productCode");
                products.addListener('row', function(product) {
                        var code = escapeHtml(product.productCode);
                        var name = escapeHtml(product.productName);
                        var vendor = escapeHtml(product.productVendor);

                        pipe.write("<tr><td>"+code+"</td><td>"+name+"</td><td>"+vendor+"</td></tr>\n");
                });
                products.addListener('end', function() {
                        pipe.write("</table>\n");
                        // fertig
                        next();
                });
        });
}

var count = 1000;

function nextStep() {
        if(count) {
                count--;
                oneStep(nextStep);
        } else {
                db.close();
                // nach 1000 Iterationen beenden
        }
}
// Kette von 1000 Aufrufen starten
nextStep();