Fixed potential bug by improving code.

collapsing your logic into a single atomic “upsert” statement:
This commit is contained in:
git 2025-06-25 12:53:42 +01:00
parent 5a2e11655c
commit 65496fcae0

26
main.js
View File

@ -26,23 +26,21 @@ async function updateMariaDB(record) {
const host = DB_USER; const host = DB_USER;
const { Type, Name } = record; const { Type, Name } = record;
const dataStr = typeof record.Data === 'object' ? JSON.stringify(record.Data) : record.Data; const dataStr = typeof record.Data === 'object'
? JSON.stringify(record.Data)
: record.Data;
try { try {
// Step 1: Check if a row exists // INSERT new row, or if (Host,Type,Name) already exists, just update Data
const [rows] = await dbPool.execute(`SELECT Data FROM ${DB_TABLE} WHERE Host = ? AND Type = ? AND Name = ?;`,[host, Type, Name]); const sql = `
INSERT INTO ${DB_TABLE} (Host, Type, Name, Data)
if (rows.length === 0) { VALUES (?, ?, ?, ?)
// No existing row → INSERT ON DUPLICATE KEY UPDATE
await dbPool.execute(`INSERT INTO ${DB_TABLE} (Host, Type, Name, Data) VALUES (?, ?, ?, ?);`,[host, Type, Name, dataStr]); Data = VALUES(Data)
} else if (rows[0].Data !== dataStr) { `;
// Row exists but Data is different → UPDATE await dbPool.execute(sql, [host, Type, Name, dataStr]);
await dbPool.execute(`UPDATE ${DB_TABLE} SET Data = ? WHERE Host = ? AND Type = ? AND Name = ?;`,[dataStr, host, Type, Name]);
}
// else: existing data is the same → do nothing
} catch (err) { } catch (err) {
console.error("DB Update Error:", err); console.error("DB Upsert Error:", err);
} }
} }