Updates
This commit is contained in:
@@ -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 {
|
||||
|
||||
Reference in New Issue
Block a user