Update db.js
This commit is contained in:
@@ -1,19 +1,29 @@
|
|||||||
|
|
||||||
import mysql from 'mysql2/promise';
|
import mysql from 'mysql2/promise';
|
||||||
import dotenv from 'dotenv';
|
import dotenv from 'dotenv';
|
||||||
|
import fs from 'fs';
|
||||||
|
import path from 'path';
|
||||||
|
import { fileURLToPath } from 'url';
|
||||||
|
|
||||||
dotenv.config();
|
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',
|
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',
|
user: process.env.DB_USER || 'omni_user',
|
||||||
password: process.env.DB_PASSWORD || 'omni_pass',
|
password: process.env.DB_PASSWORD || 'omni_pass',
|
||||||
database: process.env.DB_NAME || 'omnisupport',
|
database: process.env.DB_NAME || 'omnisupport',
|
||||||
waitForConnections: true,
|
waitForConnections: true,
|
||||||
connectionLimit: 10,
|
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) => {
|
export const query = async (sql, params) => {
|
||||||
try {
|
try {
|
||||||
@@ -30,10 +40,47 @@ export const checkConnection = async () => {
|
|||||||
const connection = await pool.getConnection();
|
const connection = await pool.getConnection();
|
||||||
await connection.ping();
|
await connection.ping();
|
||||||
connection.release();
|
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;
|
return true;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('❌ Database connection failed:', error.message);
|
console.error(`❌ Database connection failed (${dbConfig.host}:${dbConfig.port}):`, error.message);
|
||||||
return false;
|
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);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user