diff --git a/connection-db.js b/connection-db.js new file mode 100644 index 0000000000000000000000000000000000000000..6470d95c03883f59809818c86732163f071275ce --- /dev/null +++ b/connection-db.js @@ -0,0 +1,109 @@ +var mysql = require('promise-mysql'); + +const config = require('./config'); + + + +function query(req) { + return mysql.createConnection( + config.mysql + ).then(connection => { + return Promise.all([ + connection.query(req), + connection + ]) + }).then(([rep, connection]) => { + connection.end(); + return rep; + }).catch(error => { + //logs out the error + console.error(error); + }); +} + + +Promise.all([ + query(`CREATE TABLE IF NOT EXISTS channel( + chatId INT PRIMARY KEY NOT NULL, + username TEXT, + state TEXT, + token TEXT, + refresh TEXT, + expiration TEXT, + schedule TEXT +)`), + + query(`CREATE TABLE IF NOT EXISTS groups( + chatId INT NOT NULL, + grp INT, + primary key (chatId, grp) +)`) +]).then(_ => { + + console.log('[mariadb] connected to database') + +}) + + + +function getChanByChatId(chatId) { + return query(` + SELECT * + FROM channel + WHERE chatId = ${chatId} + `).then(rep => rep[0]); +} + +function createChan(data) { + return query(` + INSERT INTO channel + VALUES (${data.chatId}, "${data.username}", "${data.state}", "${data.token}", "${data.refresh}", "${data.expiration}", "${data.schedule}") + `) +} + +function deleteChanByChatId(chatId) { + return query(`DELETE FROM channel WHERE chatId = ${chatId}`); +} + +function modifyChan(data) { + return query(` + UPDATE channel + SET username = "${data.username}", + state = "${data.state}", + token = "${data.token}", + refresh = "${data.refresh}", + expiration = "${data.expiration}", + schedule = "${data.schedule}" + WHERE chatId = ${data.chatId} + `).then(_ => { + return getChanByChatId(data.chatId) + }) +} + +function getChanByState(state) { + return query(` + SELECT * + FROM channel + WHERE state = "${state}" + `).then(rep => rep[0]); +} + +function addGroup(chatId, groupId) { + return query(` + INSERT INTO groups + VALUES (${chatId}, ${groupId}) + `); +} + +function getGroups(chatId) { + return query(` + SELECT grp + FROM groups + WHERE chatId = ${chatId} + `).then(rep => { + return rep.map(element => element.grp); + }) +} + + +module.exports = { query, getChanByChatId, createChan, deleteChanByChatId, modifyChan, getChanByState, addGroup, getGroups }; \ No newline at end of file