import varDatabaseDbHandler from "./varDatabaseDbHandler"; import numberfy from "../../utils/numberfy"; import updateDbEntry from "../../functions/backend/db/updateDbEntry"; import addDbEntry from "../../functions/backend/db/addDbEntry"; import slugToNormalText from "../../utils/slug-to-normal-text"; import _ from "lodash"; /** * # Handle Table Record Update and Insert */ export default async function ({ tableSchema, recordedDbEntry, update, isMain, }) { var _a; if (isMain) return undefined; let tableId; const targetDatabase = "datasquirel"; const targetTableName = "user_database_tables"; if (!(tableSchema === null || tableSchema === void 0 ? void 0 : tableSchema.tableName)) { return undefined; } const newTableSchema = _.cloneDeep(tableSchema); try { if (!recordedDbEntry) { throw new Error("Recorded Db entry not found!"); } // const existingTableName = newTableSchema.tableNameOld // ? newTableSchema.tableNameOld // : newTableSchema.tableName; const newTableEntry = { user_id: recordedDbEntry.user_id, db_id: recordedDbEntry.id, db_slug: recordedDbEntry.db_slug, table_name: slugToNormalText(newTableSchema.tableName), table_slug: newTableSchema.tableName, child_table: newTableSchema.childTable ? 1 : 0, child_table_parent_database_schema_id: newTableSchema.childTableDbId ? numberfy(newTableSchema.childTableDbId) : 0, child_table_parent_table_schema_id: newTableSchema.childTableId ? numberfy(newTableSchema.childTableId) : 0, table_schema_id: newTableSchema.id ? numberfy(newTableSchema.id) : 0, active_data: newTableSchema.updateData ? 1 : 0, }; const existingTable = await varDatabaseDbHandler({ queryString: `SELECT * FROM ${targetDatabase}.${targetTableName} WHERE db_id = ? AND table_slug = ?`, queryValuesArray: [ String(recordedDbEntry.id), String(newTableSchema.tableName), ], }); const table = existingTable === null || existingTable === void 0 ? void 0 : existingTable[0]; if (table === null || table === void 0 ? void 0 : table.id) { tableId = table.id; if (update) { await updateDbEntry({ data: newTableEntry, identifierColumnName: "id", identifierValue: table.id, tableName: targetTableName, dbFullName: targetDatabase, }); } } else { const newTableEntryRes = await addDbEntry({ data: newTableEntry, tableName: targetTableName, dbFullName: targetDatabase, }); if ((_a = newTableEntryRes === null || newTableEntryRes === void 0 ? void 0 : newTableEntryRes.payload) === null || _a === void 0 ? void 0 : _a.insertId) { tableId = newTableEntryRes.payload.insertId; } } if (newTableSchema.tableNameOld) { } return tableId; } catch (error) { return undefined; } }