From 81e6f51cd0e020bb47d75b1fc484903efe0856b5 Mon Sep 17 00:00:00 2001 From: fcarraUniSa Date: Tue, 17 Feb 2026 00:38:40 +0100 Subject: [PATCH] Update db.js --- backend/db.js | 61 +++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 54 insertions(+), 7 deletions(-) diff --git a/backend/db.js b/backend/db.js index ae0dea3..73dc080 100644 --- a/backend/db.js +++ b/backend/db.js @@ -1,19 +1,29 @@ - import mysql from 'mysql2/promise'; import dotenv from 'dotenv'; +import fs from 'fs'; +import path from 'path'; +import { fileURLToPath } from 'url'; dotenv.config(); -const pool = mysql.createPool({ +// Fix per __dirname in ES Modules +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); + +// Configurazione DB con gestione esplicita della porta e casting a numero +const dbConfig = { host: process.env.DB_HOST || 'db', - port: process.env.DB_PORT || 3306, + port: Number(process.env.DB_PORT) || 3306, // Importante: converte la stringa ENV in numero user: process.env.DB_USER || 'omni_user', password: process.env.DB_PASSWORD || 'omni_pass', database: process.env.DB_NAME || 'omnisupport', waitForConnections: true, connectionLimit: 10, - queueLimit: 0 -}); + queueLimit: 0, + multipleStatements: true // Necessario per eseguire schema.sql che contiene più query +}; + +const pool = mysql.createPool(dbConfig); export const query = async (sql, params) => { try { @@ -30,10 +40,47 @@ export const checkConnection = async () => { const connection = await pool.getConnection(); await connection.ping(); connection.release(); - console.log('✅ Connected to MySQL Database'); + // Log che conferma l'host e la porta utilizzati (utile per debug esterni) + console.log(`✅ Connected to MySQL Database at ${dbConfig.host}:${dbConfig.port}`); return true; } catch (error) { - console.error('❌ Database connection failed:', error.message); + console.error(`❌ Database connection failed (${dbConfig.host}:${dbConfig.port}):`, error.message); return false; } }; + +export const initDb = async () => { + try { + console.log(`🔌 Attempting connection to database at ${dbConfig.host}:${dbConfig.port}...`); + + // Verifica che la connessione sia attiva prima di provare a inizializzare + const isConnected = await checkConnection(); + if (!isConnected) { + console.error("❌ Skipping initialization due to connection failure."); + return; + } + + // Controlla se la tabella 'agents' esiste già + // Se esiste, assumiamo che il DB sia già popolato e non facciamo nulla per evitare sovrascritture + const [rows] = await pool.query("SHOW TABLES LIKE 'agents'"); + + if (Array.isArray(rows) && rows.length > 0) { + console.log('ℹ️ Database tables already exist. Skipping initialization.'); + return; + } + + console.log('⚠️ Database empty or uninitialized. Running schema.sql...'); + + const schemaPath = path.join(__dirname, 'schema.sql'); + const schemaSql = fs.readFileSync(schemaPath, 'utf8'); + + // Eseguiamo lo script SQL completo + await pool.query(schemaSql); + + console.log('✅ Database initialized successfully with schema and seed data.'); + console.log('👤 Superadmin created: fcarra79@gmail.com'); + + } catch (error) { + console.error('❌ Failed to initialize database:', error); + } +};