Files
omnisupport-ai/backend/db.js
fcarraUniSa 81e6f51cd0 Update db.js
2026-02-17 00:38:40 +01:00

87 lines
2.8 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import mysql from 'mysql2/promise';
import dotenv from 'dotenv';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
dotenv.config();
// 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: 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,
multipleStatements: true // Necessario per eseguire schema.sql che contiene più query
};
const pool = mysql.createPool(dbConfig);
export const query = async (sql, params) => {
try {
const [results] = await pool.execute(sql, params);
return results;
} catch (error) {
console.error('Database query error:', error);
throw error;
}
};
export const checkConnection = async () => {
try {
const connection = await pool.getConnection();
await connection.ping();
connection.release();
// 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 (${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);
}
};