- isQueue table option adds queue columns and a (status, available_at) index; BunSQLite.queue exposes add, claim, complete, fail and release_stale with atomic claims - Set busy_timeout on connections so workers in separate processes wait instead of failing with SQLITE_BUSY - Quote table and column names with backticks in generated SQL, so reserved words (to, order, group) work and unknown columns error instead of matching as string literals - Tests for queue ops, multi-process claims and reserved-word names Co-Authored-By: Claude Opus 5.5 <[email protected]>
57 lines
1.8 KiB
JavaScript
57 lines
1.8 KiB
JavaScript
import { sqlIdent, sqlName } from "./sql-safe";
|
|
/**
|
|
* # SQL Insert Generator
|
|
*/
|
|
export default function sqlInsertGenerator({ tableName, data, dbFullName, }) {
|
|
const finalDbName = dbFullName
|
|
? `${sqlName(dbFullName, "database name")}.`
|
|
: "";
|
|
if (Array.isArray(data) && data?.[0]) {
|
|
let insertKeys = [];
|
|
data.forEach((dt) => {
|
|
const kys = Object.keys(dt);
|
|
kys.forEach((ky) => {
|
|
if (!insertKeys.includes(ky)) {
|
|
insertKeys.push(sqlIdent(ky, "column name"));
|
|
}
|
|
});
|
|
});
|
|
let queryBatches = [];
|
|
let queryValues = [];
|
|
data.forEach((item) => {
|
|
queryBatches.push(`(${insertKeys
|
|
.map((ky) => {
|
|
const value = item[ky];
|
|
if (typeof value == "function") {
|
|
const fnValue = value();
|
|
queryValues.push(fnValue.value ?? null);
|
|
return fnValue.placeholder;
|
|
}
|
|
queryValues.push(sqlValue(value));
|
|
return "?";
|
|
})
|
|
.join(",")})`);
|
|
});
|
|
let query = `INSERT INTO ${finalDbName}${sqlName(tableName, "table name")} (${insertKeys.map((ky) => sqlName(ky)).join(",")}) VALUES ${queryBatches.join(",")}`;
|
|
return {
|
|
query: query,
|
|
values: queryValues,
|
|
};
|
|
}
|
|
else {
|
|
return undefined;
|
|
}
|
|
}
|
|
/**
|
|
* # Normalize a JS value for binding
|
|
* @description Keeps `0`, `""` and `false` (as `0`) instead of turning them
|
|
* into `NULL`
|
|
*/
|
|
export function sqlValue(value) {
|
|
if (value === undefined || value === null)
|
|
return null;
|
|
if (typeof value == "boolean")
|
|
return value ? 1 : 0;
|
|
return value;
|
|
}
|