"use strict"; (() => { var exports = {}; exports.id = 2873; exports.ids = [2873]; exports.modules = { /***/ 6517: /***/ ((module) => { module.exports = require("lodash"); /***/ }), /***/ 2261: /***/ ((module) => { module.exports = require("serverless-mysql"); /***/ }), /***/ 4300: /***/ ((module) => { module.exports = require("buffer"); /***/ }), /***/ 2081: /***/ ((module) => { module.exports = require("child_process"); /***/ }), /***/ 6113: /***/ ((module) => { module.exports = require("crypto"); /***/ }), /***/ 7147: /***/ ((module) => { module.exports = require("fs"); /***/ }), /***/ 3685: /***/ ((module) => { module.exports = require("http"); /***/ }), /***/ 1017: /***/ ((module) => { module.exports = require("path"); /***/ }), /***/ 188: /***/ ((__unused_webpack_module, __webpack_exports__, __webpack_require__) => { // ESM COMPAT FLAG __webpack_require__.r(__webpack_exports__); // EXPORTS __webpack_require__.d(__webpack_exports__, { "default": () => (/* binding */ handler) }); // EXTERNAL MODULE: ./package-shared/utils/backend/global-db/DB_HANDLER.js var DB_HANDLER = __webpack_require__(2224); var DB_HANDLER_default = /*#__PURE__*/__webpack_require__.n(DB_HANDLER); // EXTERNAL MODULE: ./functions/backend/grabDelegatedUserFromCookie.js var grabDelegatedUserFromCookie = __webpack_require__(1352); var grabDelegatedUserFromCookie_default = /*#__PURE__*/__webpack_require__.n(grabDelegatedUserFromCookie); // EXTERNAL MODULE: ./functions/backend/serverError.js var serverError = __webpack_require__(2163); var serverError_default = /*#__PURE__*/__webpack_require__.n(serverError); // EXTERNAL MODULE: ./functions/backend/userAuth.js var userAuth = __webpack_require__(6825); var userAuth_default = /*#__PURE__*/__webpack_require__.n(userAuth); // EXTERNAL MODULE: ./functions/backend/grabUserSchemaData.js var grabUserSchemaData = __webpack_require__(8164); // EXTERNAL MODULE: external "fs" var external_fs_ = __webpack_require__(7147); var external_fs_default = /*#__PURE__*/__webpack_require__.n(external_fs_); // EXTERNAL MODULE: external "lodash" var external_lodash_ = __webpack_require__(6517); var external_lodash_default = /*#__PURE__*/__webpack_require__.n(external_lodash_); ;// CONCATENATED MODULE: ./functions/backend/cleanUpSchemaData.js // @ts-check /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** * @typedef {object} updateSchemaDataReturn */ /** * @param {object} params * @param {DSQL_DatabaseSchemaType[]} params.dbSchemaData - Existing Schema * @param {string} params.dbFullName - Target Database full name * @param {DSQL_TableSchemaType} params.table - New Table Schema Data * @param {number} params.userId * * @return {DSQL_DatabaseSchemaType[] | null} */ function cleanUpSchemaData({ dbSchemaData , dbFullName , table , userId , }) { try { let newDbSchemaData = _.cloneDeep(dbSchemaData); //////////////////////////////////////// //////////////////////////////////////// //////////////////////////////////////// /** * Check For Expired Child Tables * * @description Check For Expired Child Tables */ newDbSchemaData.forEach((db, index)=>{ db.tables.forEach((tableObject, _index)=>{ if (tableObject.childrenTables) { tableObject.childrenTables.forEach((childTable, __index)=>{ try { const childDbTest = newDbSchemaData.filter((_db)=>_db.dbFullName === childTable.dbNameFull); if (!childDbTest?.[0]) { tableObject.childrenTables?.splice(__index, 1); return; } const childTableObjectTest = db.tables.filter((_table)=>_table.tableName === childTable.tableName); if (!childTableObjectTest || !childTableObjectTest[0]) { tableObject.childrenTables?.splice(__index, 1); return; } } catch (/** @type {any} */ error) {} }); } }); }); //////////////////////////////////////// //////////////////////////////////////// //////////////////////////////////////// /** * Start process * ========================================================= * @description Analyze existing schema data and parse/update */ const dbIndex = newDbSchemaData.findIndex((db)=>db.dbFullName === dbFullName); const targetDb = newDbSchemaData[dbIndex]; const targetTableIndex = targetDb.tables.findIndex((_table)=>_table.tableName === table.tableName); const targetTable = targetDb.tables[targetTableIndex]; if (targetTable.childrenTables) { targetTable.childrenTables.forEach((childTable, index)=>{ try { const childDbTest = newDbSchemaData.filter((db)=>db.dbFullName === childTable.dbNameFull); if (!childDbTest || !childDbTest[0]) { targetTable.childrenTables?.splice(index, 1); return; } const childDb = childDbTest[0]; //////////////////////////////////////// //////////////////////////////////////// //////////////////////////////////////// const childTableObjectTest = childDb.tables.filter((tb)=>tb.tableName === childTable.tableName); if (!childTableObjectTest || !childTableObjectTest[0]) { targetTable.childrenTables?.splice(index, 1); return; } const childTableObject = childTableObjectTest[0]; //////////////////////////////////////// //////////////////////////////////////// //////////////////////////////////////// const originChildTableFieldsClone = _.cloneDeep(targetTable.fields); // const originChildTableFields = [...targetTable.fields]; const originChildTableIndexesClone = _.cloneDeep(targetTable.indexes); // const originChildTableIndexes = [...targetTable.indexes]; childTableObject.fields = originChildTableFieldsClone; childTableObject.indexes = originChildTableIndexesClone; childTableObject.fields.forEach((childFieldObject, index)=>{ const targetParentField = targetTable.fields[index]; if (targetParentField?.foreignKey) { const foreignKeyTable = childDb.tables.filter((tbl)=>tbl.tableName === targetParentField.foreignKey?.destinationTableName); if (foreignKeyTable && foreignKeyTable[0]) { const foreignKeyField = foreignKeyTable[0].fields.filter((fld)=>fld.fieldName === targetParentField?.foreignKey?.destinationTableColumnName); if (foreignKeyField && foreignKeyField[0]) { childFieldObject.foreignKey = { ...targetParentField.foreignKey }; childFieldObject.foreignKey.foreignKeyName = childFieldObject.foreignKey.foreignKeyName?.replace(/dsql_\d+_[^_]+_/, `dsql_${userId}_${childDb.dbSlug}_`); childFieldObject.dataType = foreignKeyField[0].dataType; } else { delete childFieldObject.foreignKey; } } else { delete childFieldObject.foreignKey; } } else { delete childFieldObject.foreignKey; } }); } catch (/** @type {any} */ error) { targetTable.childrenTables?.splice(index, 1); } }); } if (targetDb.childrenDatabases) { targetDb.childrenDatabases.forEach((childDb, index)=>{ try { const { dbFullName } = childDb; const targetChildDb = newDbSchemaData.filter((db)=>db.dbFullName === dbFullName)[0]; if (!targetChildDb || !targetChildDb.tables) { targetDb.childrenDatabases?.splice(index, 1); return; } targetChildDb.tables = targetDb.tables; } catch (/** @type {any} */ error) {} }); } return newDbSchemaData; } catch (error) { return null; } } //////////////////////////////////////// //////////////////////////////////////// //////////////////////////////////////// ;// CONCATENATED MODULE: ./functions/backend/updateSchemaData.js // @ts-check /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** * @typedef {object} updateSchemaDataReturn */ /** * @param {object} params * @param {import("@/package-shared/types").DSQL_DatabaseSchemaType[]} params.dbSchemaData - Existing Schema * @param {import("@/package-shared/types").DSQL_DatabaseSchemaType[]} params.schema - New Schema (Partial) * @param {string} params.dbFullName - Target Database full name * @param {import("./grabDelegatedUserFromCookie").grabDelegatedUserFromCookieReturn | null} params.delegatedUser * @param {import("@/package-shared/types").DSQL_TableSchemaType} params.table - New Table Schema Data * @param {number} params.userId * * @returns {boolean} */ function updateSchemaData({ dbSchemaData , delegatedUser , dbFullName , schema , table , userId , }) { const userSchemaMainFilePath = `./jsonData/dbSchemas/users/user-${userId}/main.json`; try { if (!dbSchemaData) throw new Error("Database schema not found!"); let newDbSchemaData = external_lodash_default().cloneDeep(dbSchemaData); let targetDatabase = newDbSchemaData.find((db)=>db.dbFullName == dbFullName); if (!targetDatabase) throw new Error("Old Database schema not found!"); let targetDatabaseIndex = newDbSchemaData.findIndex((db)=>db.dbFullName == dbFullName); if (targetDatabaseIndex < 0) throw new Error("Target Database index not found!"); const newSchemaDatabase = schema.find((db)=>db.dbFullName === dbFullName); if (!newSchemaDatabase) throw new Error("New Database schema not found!"); if (delegatedUser?.delegated) { const createTablePriviledge = Boolean(delegatedUser.priviledges?.match(/create.?table/i)); const editTablePriviledge = Boolean(delegatedUser.priviledges?.match(/edit.?table/i)); if (!editTablePriviledge) { throw new Error("Unauthorized!"); } //////////////////////////////////////// //////////////////////////////////////// //////////////////////////////////////// } const schemaTable = newSchemaDatabase.tables.find((tbl)=>tbl.tableName == table.tableName); if (!schemaTable) throw new Error("Table schema not found!"); const targetTableIndex = targetDatabase.tables.findIndex((tbl)=>tbl.tableName == table.tableName); if (schemaTable) { newDbSchemaData[targetDatabaseIndex].tables[targetTableIndex] = schemaTable; } //////////////////////////////////////// //////////////////////////////////////// //////////////////////////////////////// const childrenDatabases = targetDatabase?.childrenDatabases; childrenDatabases?.forEach((chDb)=>{ const chDbIndex = newDbSchemaData.findIndex((db)=>db.dbFullName === chDb.dbFullName); if (newDbSchemaData[chDbIndex] && targetDatabase) { newDbSchemaData[chDbIndex].tables = targetDatabase.tables.map((tbl)=>{ const newTbl = external_lodash_default().cloneDeep(tbl); delete newTbl.childrenTables; return newTbl; }); } }); //////////////////////////////////////// //////////////////////////////////////// //////////////////////////////////////// const childrenTables = newDbSchemaData?.[targetDatabaseIndex]?.tables?.[targetTableIndex]?.childrenTables; if (childrenTables) { childrenTables.forEach((childTbl)=>{ const childTblDbindex = newDbSchemaData.findIndex((db)=>db.dbFullName == childTbl.dbNameFull); const childTblDbTblIndex = newDbSchemaData[childTblDbindex]?.tables?.findIndex((tbl)=>tbl.tableName === childTbl.tableName); const childTblDbTbl = newDbSchemaData[childTblDbindex]?.tables[childTblDbTblIndex]; if (childTblDbTbl) { newDbSchemaData[childTblDbindex].tables[childTblDbTblIndex].fields = external_lodash_default().cloneDeep(schemaTable.fields); newDbSchemaData[childTblDbindex].tables[childTblDbTblIndex].indexes = external_lodash_default().cloneDeep(schemaTable.indexes); } }); } //////////////////////////////////////// //////////////////////////////////////// //////////////////////////////////////// external_fs_default().writeFileSync(`${userSchemaMainFilePath}`, JSON.stringify(newDbSchemaData), "utf8"); //////////////////////////////////////// //////////////////////////////////////// //////////////////////////////////////// return true; } catch (/** @type {any} */ error) { console.log("updateSchemaData.js ERROR: ", error.message); return false; } } //////////////////////////////////////// //////////////////////////////////////// //////////////////////////////////////// ;// CONCATENATED MODULE: ./pages/api/updateDbSchemaDataForUser.js // @ts-check /** * ============================================================================== * Imports * ============================================================================== */ const fs = __webpack_require__(7147); const path = __webpack_require__(1017); const { execSync } = __webpack_require__(2081); /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** ****************************************************************************** */ /** * API handler * ============================================================================== * @type {import("next").NextApiHandler} */ async function handler(req, res) { /** * Check method * * @description Check request method and return if invalid */ if (req.method !== "POST") return res.json({ msg: "Failed!" }); /** * User auth * * @description Authenticate user */ const user = await userAuth_default()(req, res, true); if (!user) { return res.json({ success: false, msg: "Unauthorized" }); } /** * User auth * * @description Authenticate user */ /** @type {import("@/package-shared/types").DSQL_DatabaseSchemaType[]} */ const schema = req.body.schema; const database = req.body.database; /** @type {import("@/package-shared/types").DSQL_TableSchemaType} */ const table = req.body.table; const delegated = req.body.delegated; /** * Send Response * * @description Send a boolean response */ try { /** * Check if user has rights to this table * * @description Check if user has rights to this table */ const delegatedUser = await grabDelegatedUserFromCookie_default()({ request: req, user: user, databaseSlug: database, query: req.query }); const userId = delegatedUser?.rootUserId ? delegatedUser.rootUserId : user.id; const dbFullName = `datasquirel_user_${userId}_${database}`.replace(/[^a-z\_0-9]/g, ""); /** * Check if user has rights to this table * * @description Check if user has rights to this table */ let confirm; if (delegatedUser?.delegated) { const checkDelegatedUser = await DB_HANDLER_default()(`SELECT * FROM user_users WHERE invited_user_id=? AND user_id=? AND user_priviledge LIKE '%Edit Tables%'`, [ user.id, delegatedUser.rootUserId ]); if (checkDelegatedUser && checkDelegatedUser[0]) confirm = true; } else { confirm = true; } if (!confirm) { return res.json({ success: false, msg: "Unauthorized" }); } /** * Create new user folder and file * * @description Create new user folder and file */ const dbSchemaData = (0,grabUserSchemaData["default"])({ userId: userId }); if (!dbSchemaData) throw new Error("Database schema not found!"); const updateDbSchema = updateSchemaData({ dbFullName, dbSchemaData, delegatedUser, schema, table, userId }); if (!updateDbSchema) { throw new Error("Update Failed!"); } //////////////////////////////////////// const targetPath = path.join(process.cwd(), "/shell"); const dbShellUpdate = execSync(`node createDbFromSchema.js --user ${userId} --database ${dbFullName}`, { cwd: targetPath }); //////////////////////////////////////// res.json({ success: true }); //////////////////////////////////////// } catch (/** @type {any} */ error) { //////////////////////////////////////// console.log("updateDbSchemaDataForUser ERROR:", error.message); serverError_default()({ component: "/api/updateDbSchemaDataForUser/main-catch-error", message: error.message, user: user }); res.json({ success: false, msg: error.message }); //////////////////////////////////////// } } /***/ }) }; ; // load runtime var __webpack_require__ = require("../../webpack-api-runtime.js"); __webpack_require__.C(exports); var __webpack_exec__ = (moduleId) => (__webpack_require__(__webpack_require__.s = moduleId)) var __webpack_exports__ = __webpack_require__.X(0, [5425,2224,2163,6825,1352,8164], () => (__webpack_exec__(188))); module.exports = __webpack_exports__; })();