From 65496fcae0e8699f825f726cc84c958a40ec6747 Mon Sep 17 00:00:00 2001 From: git Date: Wed, 25 Jun 2025 12:53:42 +0100 Subject: [PATCH] Fixed potential bug by improving code. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit collapsing your logic into a single atomic “upsert” statement: --- main.js | 28 +++++++++++++--------------- 1 file changed, 13 insertions(+), 15 deletions(-) diff --git a/main.js b/main.js index a87c11b..53c90f0 100644 --- a/main.js +++ b/main.js @@ -22,27 +22,25 @@ function getDbPassword() { } // Insert data into MariaDB async function updateMariaDB(record) { - if (!['A', 'PTR', 'SRV', 'TXT'].includes(record.Type)) return; + if (!['A','PTR','SRV','TXT'].includes(record.Type)) return; const host = DB_USER; 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 { - // Step 1: Check if a row exists - const [rows] = await dbPool.execute(`SELECT Data FROM ${DB_TABLE} WHERE Host = ? AND Type = ? AND Name = ?;`,[host, Type, Name]); - - if (rows.length === 0) { - // No existing row → INSERT - await dbPool.execute(`INSERT INTO ${DB_TABLE} (Host, Type, Name, Data) VALUES (?, ?, ?, ?);`,[host, Type, Name, dataStr]); - } else if (rows[0].Data !== dataStr) { - // Row exists but Data is different → UPDATE - 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 - + // INSERT new row, or if (Host,Type,Name) already exists, just update Data + const sql = ` + INSERT INTO ${DB_TABLE} (Host, Type, Name, Data) + VALUES (?, ?, ?, ?) + ON DUPLICATE KEY UPDATE + Data = VALUES(Data) + `; + await dbPool.execute(sql, [host, Type, Name, dataStr]); } catch (err) { - console.error("DB Update Error:", err); + console.error("DB Upsert Error:", err); } }