import { DSQL_FieldSchemaType, DSQL_MYSQL_SHOW_COLUMNS_Type, } from "../../types"; import dbHandler from "../../functions/backend/dbHandler"; import defaultFieldsRegexp from "../../functions/dsql/default-fields-regexp"; import generateColumnDescription from "./generateColumnDescription"; type Param = { dbFullName: string; tableName: string; fields: DSQL_FieldSchemaType[]; clone?: boolean; allExistingColumns: DSQL_MYSQL_SHOW_COLUMNS_Type[]; }; /** * Handle DATASQUIREL schema fields for current table * =================================================== * @description Iterate through each field object and * perform operations */ export default async function handleDSQLSchemaFields({ dbFullName, tableName, fields, allExistingColumns, }: Param) { let sql = `ALTER TABLE \`${dbFullName}\`.\`${tableName}\``; for (let i = 0; i < fields.length; i++) { const column = fields[i]; // const prevColumn = fields[i - 1]; // const nextColumn = fields[i + 1]; const { fieldName, dataType, foreignKey } = column; if (!fieldName) continue; if (defaultFieldsRegexp.test(fieldName)) continue; let updateText = ""; const existingColumnIndex = allExistingColumns?.findIndex( (_column, _index) => _column.Field === fieldName ); const existingColumn = existingColumnIndex >= 0 ? allExistingColumns[existingColumnIndex] : undefined; let { fieldEntryText } = generateColumnDescription({ columnData: column, }); /** * @description Modify Column(Field) if it already exists * in MYSQL database */ if (existingColumn?.Field) { const { Field, Type } = existingColumn; updateText += ` MODIFY COLUMN ${fieldEntryText}`; } else { /** * @description Append new column to the end of existing columns */ updateText += ` ADD COLUMN ${fieldEntryText}`; } /** * @description Pust SQL code snippet to updateTableQueryArray Array * Add a comma(,) to separate from the next snippet */ if (updateText.match(/./)) { sql += " " + updateText + ","; } } const finalSQL = sql.replace(/\,$/, ""); const updateTable = await dbHandler({ query: finalSQL, }); }