datasquirel/package-shared/functions/dsql/sql/sql-insert-generator.ts
2025-01-10 20:10:28 +01:00

67 lines
1.8 KiB
TypeScript

// @ts-check
interface SQLInsertGenReturn {
query: string;
values: string[];
}
/**
* # SQL Insert Generator
*/
export default function sqlInsertGenerator({
tableName,
data,
}: {
data: any[];
tableName: string;
}): SQLInsertGenReturn | undefined {
try {
if (Array.isArray(data) && data?.[0]) {
/** @type {string[]} */
let insertKeys: string[] = [];
data.forEach((dt) => {
const kys = Object.keys(dt);
kys.forEach((ky) => {
if (!insertKeys.includes(ky)) {
insertKeys.push(ky);
}
});
});
/** @type {string[]} */
let queryBatches: string[] = [];
/** @type {string[]} */
let queryValues: string[] = [];
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: any) {
console.log(`SQL insert gen ERROR: ${error.message}`);
return undefined;
}
}