require('dotenv').config(); const mysql = require('mysql'); const utils = require('./utils'); const { nodeObject } = require("./recordHelper"); const { DebugBuilder } = require("../utilities/debugBuilder"); const { BufferToJson } = require("../utilities/utils"); const log = new DebugBuilder("server", "mysSQLHandler"); const connection = mysql.createPool({ host: process.env.NODE_DB_HOST, user: process.env.NODE_DB_USER, password: process.env.NODE_DB_PASS, database: process.env.NODE_DB_NAME }); const nodesTable = `${process.env.NODE_DB_NAME}.nodes`; /** * Return a node object from a single SQL row * * @param {object} row The row to convert to a node object * @returns {nodeObject} The converted node object to be used downstream */ function returnNodeObjectFromRow(row) { return new nodeObject({ _id: row.id, _name: row.name, _ip: row.ip, _port: row.port, _location: row.location, _nearbySystems: BufferToJson(row.nearbySystems), _online: row.online }); } /** * Wrapper to convert an array of rows to an array of nodeObjects * * @param {array} rows The array of SQL results to be converted into node objects * @returns {array} An array of node objects */ function returnNodeObjectFromRows(rows) { var i = 0; for (var row of rows){ log.DEBUG("Row: ", row); rows[i] = returnNodeObjectFromRow(row); i += 1; } log.DEBUG("Converted Objects from Rows: ", rows); return rows; } /** Get all nodes the server knows about regardless of status * @param {*} callback Callback function */ exports.getAllNodes = (callback) => { const sqlQuery = `SELECT * FROM ${nodesTable}` runSQL(sqlQuery, (rows) => { if(!rows || rows.length == 0) callback(undefined); return callback(returnNodeObjectFromRows(rows)); }) } /** * Get all Nodes synchronously **May not be working** * * @returns */ exports.getAllNodesSync = async () => { const sqlQuery = `SELECT * FROM ${nodesTable}` var returnObjects = []; const rows = await runSQL(sqlQuery); console.log("Rows: ", rows); return returnNodeObjectFromRows(rows); } /** Get all nodes that have the online status set true (are online) * @param callback Callback function */ exports.getOnlineNodes = (callback) => { const sqlQuery = `SELECT * FROM ${nodesTable} WHERE online = 1;` runSQL(sqlQuery, (rows) => { return callback(returnNodeObjectFromRows(rows)); }) } /** Get info on a node based on ID * @param nodeId The ID of the node * @param callback Callback function */ exports.getNodeInfoFromId = (nodeId, callback) => { const sqlQuery = `SELECT * FROM ${nodesTable} WHERE id = ${nodeId}` runSQL(sqlQuery, (rows) => { // Call back the first (and theoretically only) row // Specify 0 so downstream functions don't have to worry about it return callback(returnNodeObjectFromRow(rows[0])); }) } /** Add a new node to the DB * @param nodeObject Node information object * @param callback Callback function */ exports.addNewNode = (nodeObject, callback) => { if (!nodeObject.name) throw new Error("No name provided"); const name = nodeObject.name, ip = nodeObject.ip, port = nodeObject.port, location = nodeObject.location, nearbySystems = utils.JsonToBuffer(nodeObject.nearbySystems), online = nodeObject.online; const sqlQuery = `INSERT INTO ${nodesTable} (name, ip, port, location, nearbySystems, online) VALUES ('${name}', '${ip}', ${port}, '${location}', '${nearbySystems}', ${online})`; runSQL(sqlQuery, (rows) => { return callback(returnNodeObjectFromRows(rows)); }) } /** Update the known info on a node * @param nodeObject Node information object * @param callback Callback function */ exports.updateNodeInfo = (nodeObject, callback) => { if(!nodeObject.id) throw new Error("Attempted to updated node without providing ID", nodeObject); const name = nodeObject.name, ip = nodeObject.ip, port = nodeObject.port, location = nodeObject.location, online = nodeObject.online; let queryParams = [], nearbySystems = nodeObject.nearbySystems; if (name) queryParams.push(`name = '${name}'`); if (ip) queryParams.push(`ip = '${ip}'`); if (port) queryParams.push(`port = ${port}`); if (location) queryParams.push(`location = '${location}'`); if (nearbySystems) { nearbySystems = utils.JsonToBuffer(nearbySystems) queryParams.push(`nearbySystems = '${nearbySystems}'`); } if (typeof online === "boolean" || typeof online === "number") { if (online || online === 1) queryParams.push(`online = 1`); else queryParams.push(`online = 0`); } let sqlQuery = `UPDATE ${nodesTable} SET` if (!queryParams || queryParams.length === 0) return callback(undefined); if (queryParams.length === 1) { sqlQuery = `${sqlQuery} ${queryParams[0]}` } else { let i = 0; for (const param of queryParams) { if (i === queryParams.length-1) { sqlQuery = `${sqlQuery} ${param}` i += 1; } else { sqlQuery = `${sqlQuery} ${param},` i += 1; } } } sqlQuery = `${sqlQuery} WHERE id = ${nodeObject.id};` runSQL(sqlQuery, (rows) => { if (rows.affectedRows === 1) return callback(true); else return callback(returnNodeObjectFromRows(rows)); }) } // Function to run and handle SQL errors function runSQL(sqlQuery, callback, error = (err) => { console.log(err); throw err; }) { return connection.query(sqlQuery, (err, rows) => { if (err) return error(err); //console.log('The rows are:', rows); return callback(rows); }) } exports.closeConnection = () => { connection.end() }