This commit is contained in:
2026-02-11 06:56:43 +01:00
parent 80df059135
commit a90706de5d
7 changed files with 90 additions and 39 deletions
@@ -1,10 +1,21 @@
// @ts-check
interface SQLInsertGenReturn {
query: string;
values: string[];
}
type DataFn = () => {
placeholder: string;
value: string | number | Float32Array<ArrayBuffer>;
};
type DataType = { [k: string]: string | number | DataFn | undefined | null };
type Params = {
data: DataType[];
tableName: string;
dbFullName?: string;
};
/**
* # SQL Insert Generator
*/
@@ -12,11 +23,7 @@ export default function sqlInsertGenerator({
tableName,
data,
dbFullName,
}: {
data: any[];
tableName: string;
dbFullName?: string;
}): SQLInsertGenReturn | undefined {
}: Params): SQLInsertGenReturn | undefined {
const finalDbName = dbFullName ? `${dbFullName}.` : "";
try {
@@ -32,27 +39,42 @@ export default function sqlInsertGenerator({
});
});
/** @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 "?";
const value = item[ky];
const finalValue =
typeof value == "string" ||
typeof value == "number"
? String(value)
: value
? String(value().value)
: null;
if (!finalValue) {
return undefined;
}
queryValues.push(finalValue);
const placeholder =
typeof value == "function"
? value().placeholder
: "?";
return placeholder;
})
.join(",")})`
.filter((k) => Boolean(k))
.join(",")})`,
);
});
let query = `INSERT INTO ${finalDbName}${tableName} (${insertKeys.join(
","
",",
)}) VALUES ${queryBatches.join(",")}`;
return {