//npm install mysql var mysql = await import('mysql'); const db = function ({host, port, user, password, database}) { var t= this; var con = mysql.createConnection({ host: host, port: port, user: user, password: password, database: database, multipleStatements: true }); var connected = false; t.connect = function(){ return new Promise((res,rej)=>{ con.connect(function(err) { if (err) { rej(err); }else{ connected = true; res(); }; }); }); }; t.isconnected = function(){ return connected; }; t.check = function(structure){ return new Promise((res,rej)=>{ if(!connected) return false; var sqlcode1 = ""; var sqlcode2 = ""; //ALTER TABLE `cars` ADD IF NOT EXISTS `test` INT NOT NULL; var sqlcode3 = ""; //ALTER TABLE `cars` CHANGE `test` `test` TEXT NOT NULL; var tablenames = Object.keys(structure); for (var i = 0; i < tablenames.length; i++) { let tablename = tablenames[i]; let table = structure[tablename]; let attributes = Object.keys(table); if(attributes.length>1){ sqlcode1 += `CREATE TABLE IF NOT EXISTS ${con.escapeId(tablename)} (`; for (var j = 0; j < attributes.length; j++) { var attributename = attributes[j]; var attribute = table[attributename]; sqlcode1+=`${con.escapeId(attributename)} ${attribute.type||"text"}`; sqlcode2+=`ALTER TABLE ${con.escapeId(tablename)} ADD IF NOT EXISTS ${con.escapeId(attributename)} ${attribute.type||"text"}`; sqlcode3+=`ALTER TABLE ${con.escapeId(tablename)} CHANGE ${con.escapeId(attributename)} ${con.escapeId(attributename)} ${attribute.type||"text"}`; if(!!attribute.A_I){ sqlcode1+=` AUTO_INCREMENT PRIMARY KEY`; sqlcode2+=` AUTO_INCREMENT PRIMARY KEY`; sqlcode3+=` AUTO_INCREMENT`; }else if(!!attribute.default){ sqlcode1+=` DEFAULT ${con.escape(attribute.default)}`; sqlcode2+=` DEFAULT ${con.escape(attribute.default)}`; sqlcode3+=` DEFAULT ${con.escape(attribute.default)}`; } sqlcode1+=", "; sqlcode2+="; "; sqlcode3+="; "; } sqlcode1 = sqlcode1.slice(0,-2); sqlcode1+=`); `; } } con.query(sqlcode1+sqlcode2+sqlcode3,[],function(err,result){ if(err){ rej(err); }else{ res(); } }); }); }; t.query = function(sql,insert = []){ return new Promise((res,rej)=>{ if(!connected) return rej("Not Connected to DB!"); con.query(sql,insert,function(err,result){ if(!err){ res(result); }else{ rej(err); } }); }); }; t.disconnect = function(){ connected = false; return new Promise((res,rej)=>{ con.end((err)=>{ if(err){ rej(); }else{ res(); } }); }); }; } export default db; //CREATE TABLE customers (id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), address VARCHAR(255))