Updating backend
- Added database self check - Added more @me handlers - Fixed issues
This commit is contained in:
@@ -1,4 +1,6 @@
|
||||
import mysql from 'mysql2';
|
||||
import dbconf from '../database.json';
|
||||
import { log } from './logManager';
|
||||
|
||||
const connection = mysql.createConnection({
|
||||
host: process.env.DATABASE_HOST,
|
||||
@@ -23,4 +25,58 @@ function createPool(host, user, password, db) {
|
||||
return newPool;
|
||||
}
|
||||
|
||||
export { connection, pool, createPool };
|
||||
function databaseSelfTest() {
|
||||
log('Database self-test');
|
||||
dbconf.tables.forEach(table => {
|
||||
let query = `CREATE TABLE IF NOT EXISTS ${table.name} (`;
|
||||
table.columns.forEach((column, index) => {
|
||||
query += `${column.name} ${column.type}`;
|
||||
if (column.primary_key) query += ' PRIMARY KEY';
|
||||
if (column.constraints && column.constraints.length > 0) query += ` ${column.constraints.join(' ')}`;
|
||||
if (column.index) query += `, INDEX ${column.name}_idx (${column.name})`;
|
||||
if (index < table.columns.length - 1) query += ', ';
|
||||
});
|
||||
if (table.constraints && table.constraints.length > 0) {
|
||||
table.constraints.forEach(constraint => {
|
||||
setTimeout(() => { // do not remove or it breaks /sarcasm
|
||||
if (constraint.primary_key) query += `, PRIMARY KEY (${constraint.columns.join(', ')})`;
|
||||
if (constraint.foreign_key) query += `, CONSTRAINT ${constraint.name} FOREIGN KEY (${constraint.column}) REFERENCES ${constraint.reference} ON DELETE ${constraint.on_delete} ON UPDATE ${constraint.on_update}`;
|
||||
if (constraint.index) query += `, INDEX ${constraint.name} (${constraint.columns.join(', ')})`;
|
||||
}, 500);
|
||||
});
|
||||
}
|
||||
query += ') ENGINE=InnoDB;';
|
||||
pool.query(query)
|
||||
.then(() => log(`Table ${table.name} validated`))
|
||||
.catch(err => console.log(`Error creating table ${table.name}: ${err}`));
|
||||
|
||||
if (table.data) {
|
||||
pool.query(`SELECT * FROM ${table.name}`)
|
||||
.then(([rows]) => {
|
||||
if (rows.length === 0) {
|
||||
table.data.forEach(row => {
|
||||
let insertQuery = `INSERT INTO ${table.name} (`;
|
||||
let values = 'VALUES (';
|
||||
Object.keys(row).forEach((key, index) => {
|
||||
insertQuery += key;
|
||||
values += `'${row[key]}'`;
|
||||
if (index < Object.keys(row).length - 1) {
|
||||
insertQuery += ', ';
|
||||
values += ', ';
|
||||
}
|
||||
});
|
||||
insertQuery += ') ' + values + ');';
|
||||
pool.query(insertQuery)
|
||||
.then(() => log(`Row inserted in table ${table.name}`))
|
||||
.catch(err => log(`Error inserting row in table ${table.name}: ${err}`));
|
||||
});
|
||||
}
|
||||
})
|
||||
.catch(err => log(`Error checking if table ${table.name} is empty: ${err}`));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
databaseSelfTest();
|
||||
|
||||
export { connection, pool, createPool, databaseSelfTest };
|
||||
|
||||
Reference in New Issue
Block a user