From f5e89799fcc08be0b7c7bd5c05e871040dd4610b Mon Sep 17 00:00:00 2001 From: Benjamin Toby Date: Tue, 12 Nov 2024 12:00:07 +0100 Subject: [PATCH] Updates --- functions/sql/sql-insert-generator.js | 67 +++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100644 functions/sql/sql-insert-generator.js diff --git a/functions/sql/sql-insert-generator.js b/functions/sql/sql-insert-generator.js new file mode 100644 index 0000000..421005a --- /dev/null +++ b/functions/sql/sql-insert-generator.js @@ -0,0 +1,67 @@ +// @ts-check + +/** + * @typedef {object} SQLINsertGenReturn + * @property {string} query + * @property {string[]} values + */ + +/** + * @param {object} param0 + * @param {any[]} param0.data + * @param {string} param0.tableName + * + * @return {SQLINsertGenReturn | undefined} + */ +function sqlInsertGenerator({ tableName, data }) { + try { + if (Array.isArray(data) && data?.[0]) { + /** @type {string[]} */ + let insertKeys = []; + + data.forEach((dt) => { + const kys = Object.keys(dt); + kys.forEach((ky) => { + if (!insertKeys.includes(ky)) { + insertKeys.push(ky); + } + }); + }); + + /** @type {string[]} */ + let queryBatches = []; + /** @type {string[]} */ + let queryValues = []; + + data.forEach((item) => { + queryBatches.push( + `(${insertKeys + .map((ky) => { + queryValues.push( + item[ky]?.toString()?.match(/./) + ? item[ky] + : null + ); + return "?"; + }) + .join(",")})` + ); + }); + let query = `INSERT INTO ${tableName} (${insertKeys.join( + "," + )}) VALUES ${queryBatches.join(",")}`; + + return { + query: query, + values: queryValues, + }; + } else { + return undefined; + } + } catch (/** @type {any} */ error) { + console.log(`SQL insert gen ERROR: ${error.message}`); + return undefined; + } +} + +module.exports = sqlInsertGenerator;