51 lines
1.7 KiB
JavaScript
51 lines
1.7 KiB
JavaScript
"use strict";
|
|
// @ts-check
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.default = sqlInsertGenerator;
|
|
/**
|
|
* # SQL Insert Generator
|
|
*/
|
|
function sqlInsertGenerator({ tableName, data, dbFullName, }) {
|
|
const finalDbName = dbFullName ? `${dbFullName}.` : "";
|
|
try {
|
|
if (Array.isArray(data) && (data === null || data === void 0 ? void 0 : data[0])) {
|
|
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) => {
|
|
var _a, _b;
|
|
queryValues.push(((_b = (_a = item[ky]) === null || _a === void 0 ? void 0 : _a.toString()) === null || _b === void 0 ? void 0 : _b.match(/./))
|
|
? item[ky]
|
|
: null);
|
|
return "?";
|
|
})
|
|
.join(",")})`);
|
|
});
|
|
let query = `INSERT INTO ${finalDbName}${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;
|
|
}
|
|
}
|