UNPKG

@derherrgammler/sqlimporter

Version:

A npm Module to execute .sql files with Nodejs.

70 lines (65 loc) 2.25 kB
"use strict"; //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Dependencies //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ var fs = require("fs"); var path = require("path"); var mysql = require("mysql"); var bluebird = require("bluebird"); var connConfig; var promiseWhile = bluebird.method(function (condition, action) { if (!condition()) { return; } return action().then(promiseWhile.bind(null, condition, action)); }); //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Function //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ function config (oConfig) { connConfig = { "connectionLimit" : 10, "host" : oConfig.host, "user" : oConfig.user, "password" : oConfig.password }; return this; }; function importFile (sPath) { // console.log(connConfig) var connection = mysql.createPool(connConfig); // console.log(connection); var sFile = path.join(__dirname + "/../../.." + sPath); var sSQLFile = fs.readFileSync(sFile, 'utf8'); var sSQLFile = sSQLFile.replace(/(\r\n|\n|\r)/gm, ""); var sSQLFile = sSQLFile.replace(/(\/\*([\s\S]*?)\*\/)|(\/\/(.*)$)/gm, ""); var sSQLFile = sSQLFile.replace(/\s+/g, ' ').trim(); var aSQLFile = sSQLFile.split(";"); var iStatements = aSQLFile.length - 1; var n = 0; promiseWhile(function() { return n < iStatements; }, function () { return new Promise(function (fFill, fFail) { console.log("STATEMENT " + n + ": " + " ]----------[ " + aSQLFile[n]); connection.query(aSQLFile[n], function (oErr, rows) { if (!oErr) { n += 1; fFill(); } else { console.log(oErr); fFail("\nError occured!\nCheck Statement: " + aSQLFile[n] + "\nIt's the " + (n + 1) + ". Statement in your File."); } }); }) }) .then(function () { connection.end(); return; }); }; exports.config = config; exports.importFile = function (sFilePath) { importFile(sFilePath); return this; };