<commit_before>// CVICU App: connection to MySQL database

// Node packages
var app = require('express')();
var db = require('mysql');
var bodyParser = require('body-parser');
var multer = require('multer');

// Configure app
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.use(multer({dest:'./uploads/'}).single('singleInputFileName'));

// Database information
var connectionInfo = {
    host : "localhost",
    user : "root",
    password : "<PASSWORD>",
    port : 3306
};

// Complication object
var Complication = function(table, columns) {
    this.tableName = table;
    this.columnNames = columns;
};

// Getting an array of all tables in the database
var connection = db.createConnection(connectionInfo);
connection.connect(function(err) {
    if (err) {
        console.error("Error connecting: " + err.stack);
        return;
    }
    console.log('Connected as id ' + connection.threadId);
});

var tables = [];
var query = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'cvicu';";
connection.query(query, function(err, results) {
    if (err) {
        console.error("Error in accessing schema: " + err.stack);
        return;
    } else {
        for (var i = 0; i < results.length; i++) {
            tables.push(results[i]["TABLE_NAME"]);
        }
        console.log(tables);

        // Generating Complication objects from all MySQL tables
        var complicationTables = {};
        var query = "SELECT `COLUMN_NAME` FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_SCHEMA` = 'cvicu' AND `TABLE_NAME` = ?;";
        // for (table in tables) {
        //     console.log(table);
        //     var columns = [];
        //     connection.query(query, table, function(err, results) {
        //         if (err) {
        //             console.error("Error in accessing tables: " + err.stack);
        //             return;
        //         } else {
        //             for (var i = 1; i < results.length; i++) {
        //                 columns.push(results[i]["COLUMN_NAME"]);
        //             }
        //             complicationTables[table] = new Complication(table, columns);
        //             console.log(columns);
        //             //TODO : FIGURE OUT WHY COLUMNS ARE EMPTY
        //         }
        //     });
        // }
        for (var j = 0; j < tables.length; j++) {
            var columns = [];
            connection.query(query, tables[j], function(err, results) {
                if (err) {
                    console.error("Error in accessing tables: " + err.stack);
                    return;
                } else {
                    for (var k = 0; k < results.length; k++) {
                        columns.push(results[k]["COLUMN_NAME"]);
                    }
                    complicationTables[tables[j]] = new Complication(tables[j], columns);
                }
                console.log(complicationTables);
            });
        }
    }
});
console.log("YEE");
// connection.end();

// TODO: Only need one connection.connect / end ?

// Complications maps and table to iterate
var arrhythmia = new Complication("arrhythmialog", ["FIN", "Type", "Therapy", "StopDate", "date", "date_1"]);

var cpr = new Complication("cprlog", ["FIN", "startDate", "endDate", "outcome", "Hypothermia", "date"]);

var dsc = new Complication("dsclog", ["FIN", "Plan", "date", "date_1"]);

var complicationTables = {
    arrhythmialog : arrhythmia,
    cprlog : cpr,
    dsclog : dsc
};

// Helper Functions
function isEmpty(obj) { // check if object is empty
    return !Object.keys(obj).length;
}

app.post('/', function(req, res) {
    var request = req.body;


    // Checking FIN patient MRN number
    if (request["targetAction"] == "checkFIN") {
        var connection = db.createConnection(connectionInfo);
        connection.connect();

        var fin = request["FIN"];
        var table = request["Table"];
        var query = "SELECT * from ?? WHERE FIN = ?;";

        connection.query("USE cvicu;");
        connection.query(query, [table, fin], function(err, results) {
            if (err) {
                console.error("Error in FIN query: " + err.stack);
                return;
            } else if (isEmpty(results)) {
                // No such user exists
                console.log("FIN and complication not found!");
                res.write("NO");
                res.end();
            } else {
                // User found
                console.log("FIN and complication found!");
                res.write(results[results.length - 1]["date"]);
                res.end();
            }
        });
        connection.end();
    }


    // All queries requesting logs
    if (request["targetAction"] == "requestLogs") {
        var toClient = [];
        var connection = db.createConnection(connectionInfo);
        connection.connect();

        for (comp in complicationTables) {
            var query = "SELECT date FROM ?? WHERE FIN = ?;";
            connection.query("USE cvicu;");
            connection.query(query, [comp, request["FIN"]], function(err, results) {
                if (err) {
                    console.error("Error in requesting " + comp + ": " + err.stack);
                    return;
                } else if (!isEmpty(results)) {
                    var lastLog = {
                        table : comp,
                        date : results[results.length - 1]["date"]
                    };
                } else {
                    var lastLog = {
                        table : "null"
                    };
                }
            });
            toClient.push(lastLog);
        }
        //TODO: Figure out why logs are nested within each other (mistake?). Also, how do we get the particular complication from the connection before query? Use multiple dictionaries to make modular code?
    }


    // All queries inserting into logs
    if (request["targetAction"] == "addLog") {
        // Create connection and get table name
        var connection = db.createConnection(connectionInfo);
        connection.connect();
        var thisComplication = request["Table"];

        console.log ("Start: adding to " + thisComplication);

        // Create an object patientLog that represents a row of values in the SQL table
        var patientLog = {};
        var columnNames = complicationTables[thisComplication]["columnNames"];
        for (column in columnNames) {
            patientLog[column] = request[column];
        }

        // Generate query
        var query = "INSERT INTO ?? SET ?;";
        connection.query("USE cvicu");
        connection.query(query, [thisComplication, patientLog], function(err, results) {
            if (err) {
                console.error("Error in " + thisComplication + " insertion: " + err.stack);
                var toClient = {
                    BackMsg : "add back",
                    Result : "false"
                };
                toClient = JSON.stringify(toClient);
                res.write(toClient);
                res.end();
                return;
            } else {
                var toClient = {
                    BackMsg : "add back",
                    Result : "true"
                };
                toClient = JSON.stringify(toClient);
                res.write(toClient);
                res.end();
            }
        });
        connection.end();
        console.log("End: adding to " + thisComplication);
    }
});

app.listen(3000, function() {
    console.log('Server running at port 3000.');
});
<commit_msg>removed previous for loop that gave the empty results. somehow this asynchronous thing is still weird<commit_after>// CVICU App: connection to MySQL database

// Node packages
var app = require('express')();
var db = require('mysql');
var bodyParser = require('body-parser');
var multer = require('multer');

// Configure app
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));
app.use(multer({dest:'./uploads/'}).single('singleInputFileName'));

// Database information
var connectionInfo = {
    host : "localhost",
    user : "root",
    password : "<PASSWORD>",
    port : 3306
};

// Complication object
var Complication = function(table, columns) {
    this.tableName = table;
    this.columnNames = columns;
};

// Getting an array of all tables in the database
var connection = db.createConnection(connectionInfo);
connection.connect(function(err) {
    if (err) {
        console.error("Error connecting: " + err.stack);
        return;
    }
    console.log('Connected as id ' + connection.threadId);
});

var tables = [];
var query = "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'cvicu';";
connection.query(query, function(err, results) {
    if (err) {
        console.error("Error in accessing schema: " + err.stack);
        return;
    } else {
        for (var i = 0; i < results.length; i++) {
            tables.push(results[i]["TABLE_NAME"]);
        }
        console.log(tables);

        // Generating Complication objects from all MySQL tables
        var complicationTables = {};
        var query = "SELECT `COLUMN_NAME` FROM `INFORMATION_SCHEMA`.`COLUMNS` WHERE `TABLE_SCHEMA` = 'cvicu' AND `TABLE_NAME` = ?;";
        
        for (var j = 0; j < tables.length; j++) {
            var columns = [];
            connection.query(query, tables[j], function(err, results) {
                if (err) {
                    console.error("Error in accessing tables: " + err.stack);
                    return;
                } else {
                    for (var k = 0; k < results.length; k++) {
                        columns.push(results[k]["COLUMN_NAME"]);
                    }
                    complicationTables[tables[j]] = new Complication(tables[j], columns);
                }
                // console.log(complicationTables);
            });
        }
    }
});
console.log("YEE");
// connection.end();

// TODO: Only need one connection.connect / end ?

// Complications maps and table to iterate
var arrhythmia = new Complication("arrhythmialog", ["FIN", "Type", "Therapy", "StopDate", "date", "date_1"]);

var cpr = new Complication("cprlog", ["FIN", "startDate", "endDate", "outcome", "Hypothermia", "date"]);

var dsc = new Complication("dsclog", ["FIN", "Plan", "date", "date_1"]);

var complicationTables = {
    arrhythmialog : arrhythmia,
    cprlog : cpr,
    dsclog : dsc
};

// Helper Functions
function isEmpty(obj) { // check if object is empty
    return !Object.keys(obj).length;
}

app.post('/', function(req, res) {
    var request = req.body;


    // Checking FIN patient MRN number
    if (request["targetAction"] == "checkFIN") {
        var connection = db.createConnection(connectionInfo);
        connection.connect();

        var fin = request["FIN"];
        var table = request["Table"];
        var query = "SELECT * from ?? WHERE FIN = ?;";

        connection.query("USE cvicu;");
        connection.query(query, [table, fin], function(err, results) {
            if (err) {
                console.error("Error in FIN query: " + err.stack);
                return;
            } else if (isEmpty(results)) {
                // No such user exists
                console.log("FIN and complication not found!");
                res.write("NO");
                res.end();
            } else {
                // User found
                console.log("FIN and complication found!");
                res.write(results[results.length - 1]["date"]);
                res.end();
            }
        });
        connection.end();
    }


    // All queries requesting logs
    if (request["targetAction"] == "requestLogs") {
        var toClient = [];
        var connection = db.createConnection(connectionInfo);
        connection.connect();

        for (comp in complicationTables) {
            var query = "SELECT date FROM ?? WHERE FIN = ?;";
            connection.query("USE cvicu;");
            connection.query(query, [comp, request["FIN"]], function(err, results) {
                if (err) {
                    console.error("Error in requesting " + comp + ": " + err.stack);
                    return;
                } else if (!isEmpty(results)) {
                    var lastLog = {
                        table : comp,
                        date : results[results.length - 1]["date"]
                    };
                } else {
                    var lastLog = {
                        table : "null"
                    };
                }
            });
            toClient.push(lastLog);
        }
        //TODO: Figure out why logs are nested within each other (mistake?). Also, how do we get the particular complication from the connection before query? Use multiple dictionaries to make modular code?
    }


    // All queries inserting into logs
    if (request["targetAction"] == "addLog") {
        // Create connection and get table name
        var connection = db.createConnection(connectionInfo);
        connection.connect();
        var thisComplication = request["Table"];

        console.log ("Start: adding to " + thisComplication);

        // Create an object patientLog that represents a row of values in the SQL table
        var patientLog = {};
        var columnNames = complicationTables[thisComplication]["columnNames"];
        for (column in columnNames) {
            patientLog[column] = request[column];
        }

        // Generate query
        var query = "INSERT INTO ?? SET ?;";
        connection.query("USE cvicu");
        connection.query(query, [thisComplication, patientLog], function(err, results) {
            if (err) {
                console.error("Error in " + thisComplication + " insertion: " + err.stack);
                var toClient = {
                    BackMsg : "add back",
                    Result : "false"
                };
                toClient = JSON.stringify(toClient);
                res.write(toClient);
                res.end();
                return;
            } else {
                var toClient = {
                    BackMsg : "add back",
                    Result : "true"
                };
                toClient = JSON.stringify(toClient);
                res.write(toClient);
                res.end();
            }
        });
        connection.end();
        console.log("End: adding to " + thisComplication);
    }
});

app.listen(3000, function() {
    console.log('Server running at port 3000.');
});

{'fraction_non_alphanumeric': 0.13127015713991627, 'fraction_numerical': 0.0026761819803746653, 'mean_word_length': 1.8118850086822305, 'pattern_counts': {'":': 2, '<': 12, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3054132', 'n_tokens_mistral': 4002, 'n_tokens_neox': 3782, 'n_words': 1021}