99 lines
2.1 KiB
JavaScript
99 lines
2.1 KiB
JavaScript
const { Sequelize } = require('sequelize');
|
|
const config = require('./config.json');
|
|
|
|
/**
|
|
* MySQL Connection Configuration via senaai.tech
|
|
* Direct connection to MySQL server (port 11001)
|
|
*/
|
|
const dbConfig = config.database;
|
|
|
|
const sequelize = new Sequelize(
|
|
dbConfig.database,
|
|
dbConfig.username,
|
|
dbConfig.password,
|
|
{
|
|
host: dbConfig.host,
|
|
port: dbConfig.port,
|
|
dialect: dbConfig.dialect,
|
|
dialectOptions: {
|
|
connectTimeout: 60000, // 60 seconds for slow networks
|
|
},
|
|
|
|
// Connection Pool Configuration
|
|
pool: dbConfig.pool,
|
|
|
|
// Logging
|
|
logging: dbConfig.logging,
|
|
|
|
// Query options
|
|
define: {
|
|
timestamps: true,
|
|
underscored: true,
|
|
freezeTableName: true,
|
|
},
|
|
|
|
// Timezone
|
|
timezone: dbConfig.timezone,
|
|
|
|
// Retry configuration
|
|
retry: {
|
|
max: 3,
|
|
timeout: 3000,
|
|
},
|
|
}
|
|
);
|
|
|
|
/**
|
|
* Test database connection
|
|
*/
|
|
const testConnection = async () => {
|
|
try {
|
|
await sequelize.authenticate();
|
|
console.log(`✅ MySQL connection established successfully to ${dbConfig.host}:${dbConfig.port}`);
|
|
return true;
|
|
} catch (error) {
|
|
console.error('❌ Unable to connect to MySQL:', error.message);
|
|
return false;
|
|
}
|
|
};
|
|
|
|
/**
|
|
* Initialize database models
|
|
*/
|
|
const initializeDatabase = async () => {
|
|
try {
|
|
// Test connection first
|
|
const isConnected = await testConnection();
|
|
if (!isConnected) {
|
|
throw new Error('Failed to connect to database');
|
|
}
|
|
|
|
// Note: Auto-sync disabled in production for safety
|
|
console.log('✅ Database connection ready');
|
|
|
|
return sequelize;
|
|
} catch (error) {
|
|
console.error('❌ Database initialization failed:', error.message);
|
|
throw error;
|
|
}
|
|
};
|
|
|
|
/**
|
|
* Close database connection
|
|
*/
|
|
const closeConnection = async () => {
|
|
try {
|
|
await sequelize.close();
|
|
console.log('✅ Database connection closed');
|
|
} catch (error) {
|
|
console.error('❌ Error closing database connection:', error.message);
|
|
}
|
|
};
|
|
|
|
module.exports = {
|
|
sequelize,
|
|
testConnection,
|
|
initializeDatabase,
|
|
closeConnection,
|
|
};
|