Ajout du support de MYSQL
This commit is contained in:
90
autopost/db.js
Normal file
90
autopost/db.js
Normal file
@@ -0,0 +1,90 @@
|
||||
// db.js
|
||||
const config = require('./config');
|
||||
|
||||
let db, mysqlPool, sqlite3;
|
||||
const dbtype = config.dbtype;
|
||||
|
||||
if (dbtype === 'mysql') {
|
||||
const mysql = require('mysql2/promise');
|
||||
mysqlPool = mysql.createPool({
|
||||
host: config.DB_HOST,
|
||||
port: config.DB_PORT,
|
||||
user: config.DB_USER,
|
||||
password: config.DB_PASSWORD,
|
||||
database: config.DB_DATABASE,
|
||||
waitForConnections: true,
|
||||
connectionLimit: 10,
|
||||
});
|
||||
|
||||
db = {
|
||||
async query(sql, params = []) {
|
||||
return await mysqlPool.query(sql, params);
|
||||
},
|
||||
async close() {
|
||||
await mysqlPool.end();
|
||||
}
|
||||
};
|
||||
async function testConnection() {
|
||||
try {
|
||||
const conn = await mysqlPool.getConnection();
|
||||
await conn.ping();
|
||||
conn.release();
|
||||
console.log('[DATABASE] Connexion MySQL OK');
|
||||
} catch (err) {
|
||||
console.error('[DATABASE] Échec connexion MySQL:', err.message);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
db.testConnection = testConnection;
|
||||
} else {
|
||||
// SQLite
|
||||
sqlite3 = require('sqlite3').verbose();
|
||||
db = {
|
||||
async query(sql, params = []) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const lowered = sql.trim().toLowerCase();
|
||||
let base = new sqlite3.Database(config.dbFile, lowered.startsWith('select') ? sqlite3.OPEN_READONLY : sqlite3.OPEN_READWRITE);
|
||||
if (lowered.startsWith('select') && lowered.includes('count(')) {
|
||||
base.get(sql, params, (err, row) => {
|
||||
base.close();
|
||||
if (err) return reject(err);
|
||||
resolve([[row]]);
|
||||
});
|
||||
} else if (lowered.startsWith('select')) {
|
||||
base.all(sql, params, (err, rows) => {
|
||||
base.close();
|
||||
if (err) return reject(err);
|
||||
resolve([rows]);
|
||||
});
|
||||
} else {
|
||||
base.run(sql, params, function(err) {
|
||||
base.close();
|
||||
if (err) return reject(err);
|
||||
resolve([{ affectedRows: this.changes }]);
|
||||
});
|
||||
}
|
||||
});
|
||||
},
|
||||
async close() {}
|
||||
};
|
||||
async function testConnection() {
|
||||
try {
|
||||
let base = new sqlite3.Database(config.dbFile);
|
||||
base.get('SELECT 1', [], (err, row) => {
|
||||
base.close();
|
||||
if (err) {
|
||||
console.error('[DATABASE] Échec connexion SQLite:', err.message);
|
||||
process.exit(1);
|
||||
} else {
|
||||
console.log('[DATABASE] Connexion SQLite OK');
|
||||
}
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('[DATABASE] Échec connexion SQLite:', err.message);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
db.testConnection = testConnection;
|
||||
}
|
||||
|
||||
module.exports = db;
|
||||
Reference in New Issue
Block a user