Add default returning record on db insert and update
This commit is contained in:
Vendored
+31
-3
@@ -1,8 +1,9 @@
|
||||
import dbHandler from "../db-handler";
|
||||
import sqlInsertGenerator from "../../utils/sql-insert-generator";
|
||||
import grabDuplicateSafeInsertSql from "../grab-duplicate-safe-insert-sql";
|
||||
export default async function DbInsert({ table, data, update_on_duplicate, config, }) {
|
||||
export default async function DbInsert({ table, data, update_on_duplicate, returning = true, config, }) {
|
||||
let sqlObj = null;
|
||||
const useReturning = returning;
|
||||
try {
|
||||
const finalData = data.map((d) => ({
|
||||
created_at: Date.now(),
|
||||
@@ -15,9 +16,19 @@ export default async function DbInsert({ table, data, update_on_duplicate, confi
|
||||
data: finalData,
|
||||
}) || null;
|
||||
let sql = sqlObj?.query || "";
|
||||
if (!sql) {
|
||||
return {
|
||||
success: false,
|
||||
msg: "No insert data provided",
|
||||
debug: { sqlObj },
|
||||
};
|
||||
}
|
||||
if (update_on_duplicate && data[0]) {
|
||||
sql = await grabDuplicateSafeInsertSql({ data, table, sql });
|
||||
}
|
||||
if (useReturning) {
|
||||
sql += " RETURNING *";
|
||||
}
|
||||
(sqlObj || {}).query = sql;
|
||||
const res = dbHandler({
|
||||
query: sql,
|
||||
@@ -27,9 +38,26 @@ export default async function DbInsert({ table, data, update_on_duplicate, confi
|
||||
if (!res.success) {
|
||||
return { ...res, debug: { sqlObj } };
|
||||
}
|
||||
if (!useReturning) {
|
||||
return {
|
||||
success: Boolean(res.postInsertReturn?.insertId),
|
||||
postInsertReturn: res.postInsertReturn,
|
||||
debug: {
|
||||
sqlObj,
|
||||
},
|
||||
};
|
||||
}
|
||||
const rows = res.payload || [];
|
||||
return {
|
||||
success: Boolean(res.postInsertReturn?.insertId),
|
||||
postInsertReturn: res.postInsertReturn,
|
||||
success: rows.length > 0,
|
||||
payload: rows,
|
||||
singleRes: rows[0] ?? null,
|
||||
postInsertReturn: {
|
||||
affectedRows: rows.length,
|
||||
insertId: rows.length
|
||||
? Number(rows[rows.length - 1]?.id)
|
||||
: undefined,
|
||||
},
|
||||
debug: {
|
||||
sqlObj,
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user