import dbHandler from "../db-handler"; import _ from "lodash"; import type { BunMariaDBConfig, DBResponseObject, ServerQueryParam, } from "../../types"; import sqlGenerator from "../../utils/sql-generator"; import { quoteIdentifier } from "../../utils/sql-identifier"; type Params< Schema extends { [k: string]: any } = { [k: string]: any }, Table extends string = string, > = { table: Table; query?: ServerQueryParam; targetId?: number | string; config?: BunMariaDBConfig; }; export default async function DbDelete< Schema extends { [k: string]: any } = { [k: string]: any }, Table extends string = string, >({ table, query, targetId, config, }: Params): Promise { let sqlObj: ReturnType | null = null; try { const finalQuery = query || {}; sqlObj = sqlGenerator({ tableName: table, genObject: finalQuery, targetId, }); const whereClause = sqlObj.where; if (!whereClause) { return { success: false, msg: `No WHERE clause`, debug: { sqlObj, }, }; } let sql = `DELETE FROM ${quoteIdentifier(table)} ${whereClause}`; sql += ` RETURNING *`; sqlObj.string = sql; sqlObj.values = sqlObj.whereValues; const res = await dbHandler({ query: sql, values: sqlObj.values as any, config, }); if (!res.success) { return { msg: "Database delete failed", ...res, success: false, debug: { sqlObj, }, }; } return { ..._.omit(res, ["payload"]), success: Boolean(res.insert_return?.last_insert_id), debug: { sqlObj, }, }; } catch (error: any) { return { success: false, error: error.message, debug: { sqlObj, }, }; } }