This commit is contained in:
2026-01-03 05:34:24 +01:00
parent f0d44092e5
commit 290dfe303c
49 changed files with 1497 additions and 1016 deletions
@@ -13,8 +13,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = handleIndexescreateDbFromSchema;
const grab_dsql_schema_index_comment_1 = __importDefault(require("../utils/grab-dsql-schema-index-comment"));
const dbHandler_1 = __importDefault(require("../../functions/backend/dbHandler"));
const app_data_1 = __importDefault(require("../../data/app-data"));
/**
* Handle DATASQUIREL Table Indexes
* ===================================================
@@ -23,36 +23,47 @@ const dbHandler_1 = __importDefault(require("../../functions/backend/dbHandler")
*/
function handleIndexescreateDbFromSchema(_a) {
return __awaiter(this, arguments, void 0, function* ({ dbFullName, tableName, indexes, }) {
/**
* Handle MYSQL Table Indexes
* ===================================================
* @description Iterate through each table index(if available)
* and perform operations
*/
const allExistingIndexes = (yield (0, dbHandler_1.default)({
query: `SHOW INDEXES FROM \`${dbFullName}\`.\`${tableName}\``,
query: `SHOW INDEXES FROM \`${dbFullName}\`.\`${tableName}\` WHERE Index_comment LIKE '%${app_data_1.default["IndexComment"]}%'`,
}));
if (allExistingIndexes) {
for (let f = 0; f < allExistingIndexes.length; f++) {
const { Key_name } = allExistingIndexes[f];
try {
const existingKeyInSchema = indexes === null || indexes === void 0 ? void 0 : indexes.find((indexObject) => indexObject.alias === Key_name);
if (!existingKeyInSchema)
throw new Error(`This Index(${Key_name}) Has been Deleted!`);
}
catch (error) {
/**
* @description Drop Index: This happens when the MYSQL index is not
* present in the datasquirel DB schema
*/
yield (0, dbHandler_1.default)({
query: `ALTER TABLE \`${dbFullName}\`.\`${tableName}\` DROP INDEX \`${Key_name}\``,
});
}
}
}
/**
* # Re-Add New Indexes
*/
for (let g = 0; g < indexes.length; g++) {
const { indexType, indexName, indexTableFields, alias } = indexes[g];
if (!(alias === null || alias === void 0 ? void 0 : alias.match(/./)))
continue;
/**
* @description Check for existing Index in MYSQL db
*/
try {
const existingKeyInDb = allExistingIndexes.filter((indexObject) => indexObject.Key_name === alias);
if (!existingKeyInDb[0])
throw new Error("This Index Does not Exist");
}
catch (error) {
/**
* @description Create new index if determined that it
* doesn't exist in MYSQL db
*/
const queryString = `CREATE${indexType == "full_text"
? " FULLTEXT"
: indexType == "vector"
? " VECTOR"
: ""} INDEX \`${alias}\` ON \`${dbFullName}\`.\`${tableName}\`(${indexTableFields === null || indexTableFields === void 0 ? void 0 : indexTableFields.map((nm) => nm.value).map((nm) => `\`${nm}\``).join(",")}) COMMENT '${(0, grab_dsql_schema_index_comment_1.default)()} ${indexName}'`;
const addIndex = yield (0, dbHandler_1.default)({ query: queryString });
}
const queryString = `CREATE${indexType == "full_text"
? " FULLTEXT"
: indexType == "vector"
? " VECTOR"
: ""} INDEX \`${alias}\` ON \`${dbFullName}\`.\`${tableName}\`(${indexTableFields === null || indexTableFields === void 0 ? void 0 : indexTableFields.map((nm) => nm.value).map((nm) => `\`${nm}\``).join(",")}) COMMENT '${app_data_1.default["IndexComment"]} ${indexName}'`;
const addIndex = yield (0, dbHandler_1.default)({ query: queryString });
}
const allExistingIndexesAfterUpdate = (yield (0, dbHandler_1.default)({
query: `SHOW INDEXES FROM \`${dbFullName}\`.\`${tableName}\``,
}));
});
}
@@ -0,0 +1,14 @@
import { DSQL_UniqueConstraintSchemaType } from "../../types";
type Param = {
tableName: string;
dbFullName: string;
tableUniqueConstraints: DSQL_UniqueConstraintSchemaType[];
};
/**
* Handle DATASQUIREL Table Unique Constraints
* ===================================================
* @description Iterate through each datasquirel schema
* table unique constraint(if available), and perform operations
*/
export default function handleUniqueConstraintsCreateDbFromSchema({ dbFullName, tableName, tableUniqueConstraints, }: Param): Promise<void>;
export {};
@@ -0,0 +1,69 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = handleUniqueConstraintsCreateDbFromSchema;
const dbHandler_1 = __importDefault(require("../../functions/backend/dbHandler"));
const app_data_1 = __importDefault(require("../../data/app-data"));
/**
* Handle DATASQUIREL Table Unique Constraints
* ===================================================
* @description Iterate through each datasquirel schema
* table unique constraint(if available), and perform operations
*/
function handleUniqueConstraintsCreateDbFromSchema(_a) {
return __awaiter(this, arguments, void 0, function* ({ dbFullName, tableName, tableUniqueConstraints, }) {
/**
* # Delete All Existing Unique Constraints
*/
// const allExistingUniqueConstraints = (await dbHandler({
// query: `SHOW INDEXES FROM \`${dbFullName}\`.\`${tableName}\` WHERE Index_comment LIKE '%${AppData["UniqueConstraintComment"]}%'`,
// })) as DSQL_MYSQL_SHOW_INDEXES_Type[] | null;
// if (allExistingUniqueConstraints?.[0]) {
// for (let f = 0; f < allExistingUniqueConstraints.length; f++) {
// const { Key_name } = allExistingUniqueConstraints[f];
// try {
// const existingKeyInSchema = tableUniqueConstraints?.find(
// (indexObject) => indexObject.alias === Key_name
// );
// if (!existingKeyInSchema)
// throw new Error(
// `This Index(${Key_name}) Has been Deleted!`
// );
// } catch (error) {
// /**
// * @description Drop Index: This happens when the MYSQL index is not
// * present in the datasquirel DB schema
// */
// await dbHandler({
// query: `ALTER TABLE \`${dbFullName}\`.\`${tableName}\` DROP INDEX \`${Key_name}\``,
// });
// }
// }
// }
/**
* # Re-Add New Constraints
*/
for (let g = 0; g < tableUniqueConstraints.length; g++) {
const { constraintName, alias, constraintTableFields } = tableUniqueConstraints[g];
if (!(alias === null || alias === void 0 ? void 0 : alias.match(/./)))
continue;
/**
* @description Create new index if determined that it
* doesn't exist in MYSQL db
*/
const queryString = `CREATE UNIQUE INDEX \`${alias}\` ON \`${dbFullName}\`.\`${tableName}\`(${constraintTableFields === null || constraintTableFields === void 0 ? void 0 : constraintTableFields.map((nm) => nm.value).map((nm) => `\`${nm}\``).join(",")}) COMMENT '${app_data_1.default["UniqueConstraintComment"]} ${constraintName}'`;
const addIndex = yield (0, dbHandler_1.default)({ query: queryString });
}
});
}
+6 -2
View File
@@ -104,7 +104,7 @@ function createDbFromSchema(_a) {
*/
for (let t = 0; t < tables.length; t++) {
const table = tables[t];
const { tableName, fields, indexes } = table;
const { tableName, fields, indexes, uniqueConstraints } = table;
if (targetTable && tableName !== targetTable)
continue;
console.log(`Handling table => ${tableName}`);
@@ -139,6 +139,7 @@ function createDbFromSchema(_a) {
recordedDbEntry,
tableSchema: table,
isMain,
tableUniqueConstraints: uniqueConstraints,
});
if (table.childrenTables && table.childrenTables[0]) {
for (let ch = 0; ch < table.childrenTables.length; ch++) {
@@ -159,6 +160,7 @@ function createDbFromSchema(_a) {
userId,
dbSchema: childTableParentDbSchema,
tableIndexes: childTableSchema.indexes,
tableUniqueConstraints: childTableSchema.uniqueConstraints,
clone: true,
recordedDbEntry,
tableSchema: table,
@@ -173,11 +175,13 @@ function createDbFromSchema(_a) {
*/
const createNewTable = yield (0, createTable_1.default)({
tableName: tableName,
tableInfoArray: fields,
fields,
dbFullName: dbFullName,
tableSchema: table,
recordedDbEntry,
isMain,
indexes,
uniqueConstraints,
});
/**
* Handle DATASQUIREL Table Indexes
+5 -3
View File
@@ -1,15 +1,17 @@
import { DSQL_FieldSchemaType, DSQL_TableSchemaType } from "../../types";
import { DSQL_FieldSchemaType, DSQL_IndexSchemaType, DSQL_TableSchemaType, DSQL_UniqueConstraintSchemaType } from "../../types";
import { DSQL_DATASQUIREL_USER_DATABASES } from "../../types/dsql";
type Param = {
dbFullName: string;
tableName: string;
tableInfoArray: DSQL_FieldSchemaType[];
fields: DSQL_FieldSchemaType[];
tableSchema?: DSQL_TableSchemaType;
recordedDbEntry?: DSQL_DATASQUIREL_USER_DATABASES;
isMain?: boolean;
indexes?: DSQL_IndexSchemaType[];
uniqueConstraints?: DSQL_UniqueConstraintSchemaType[];
};
/**
* # Create Table Functions
*/
export default function createTable({ dbFullName, tableName, tableInfoArray, tableSchema, recordedDbEntry, isMain, }: Param): Promise<number | undefined>;
export default function createTable({ dbFullName, tableName, fields: passedFields, tableSchema, recordedDbEntry, isMain, indexes, uniqueConstraints, }: Param): Promise<number | undefined>;
export {};
+43 -18
View File
@@ -18,12 +18,14 @@ const supplementTable_1 = __importDefault(require("./supplementTable"));
const handle_table_foreign_key_1 = __importDefault(require("./handle-table-foreign-key"));
const create_table_handle_table_record_1 = __importDefault(require("./create-table-handle-table-record"));
const dbHandler_1 = __importDefault(require("../../functions/backend/dbHandler"));
const handle_indexes_1 = __importDefault(require("../createDbFromSchema/handle-indexes"));
const handle_unique_constraints_1 = __importDefault(require("../createDbFromSchema/handle-unique-constraints"));
/**
* # Create Table Functions
*/
function createTable(_a) {
return __awaiter(this, arguments, void 0, function* ({ dbFullName, tableName, tableInfoArray, tableSchema, recordedDbEntry, isMain, }) {
const finalTable = (0, supplementTable_1.default)({ tableInfoArray: tableInfoArray });
return __awaiter(this, arguments, void 0, function* ({ dbFullName, tableName, fields: passedFields, tableSchema, recordedDbEntry, isMain, indexes, uniqueConstraints, }) {
const fields = (0, supplementTable_1.default)({ tableInfoArray: passedFields });
let tableId = yield (0, create_table_handle_table_record_1.default)({
recordedDbEntry,
tableSchema,
@@ -34,15 +36,15 @@ function createTable(_a) {
const createTableQueryArray = [];
createTableQueryArray.push(`CREATE TABLE IF NOT EXISTS \`${dbFullName}\`.\`${tableName}\` (`);
let primaryKeySet = false;
for (let i = 0; i < finalTable.length; i++) {
const column = finalTable[i];
for (let i = 0; i < fields.length; i++) {
const column = fields[i];
let { fieldEntryText, newPrimaryKeySet } = (0, generateColumnDescription_1.default)({
columnData: column,
primaryKeySet: primaryKeySet,
});
primaryKeySet = newPrimaryKeySet;
const comma = (() => {
if (i === finalTable.length - 1)
if (i === fields.length - 1)
return "";
return ",";
})();
@@ -53,19 +55,42 @@ function createTable(_a) {
const newTable = yield (0, dbHandler_1.default)({
query: createTableQuery,
});
for (let i = 0; i < finalTable.length; i++) {
const column = finalTable[i];
const { foreignKey, fieldName } = column;
if (!fieldName)
continue;
if (foreignKey) {
yield (0, handle_table_foreign_key_1.default)({
dbFullName,
foreignKey,
tableName,
fieldName,
});
}
/**
* Handle MYSQL Foreign Keys
* ===================================================
* @description Iterate through each datasquirel schema
* table index(if available), and perform operations
*/
yield (0, handle_table_foreign_key_1.default)({
dbFullName,
fields,
tableName,
});
/**
* Handle DATASQUIREL Table Indexes
* ===================================================
* @description Iterate through each datasquirel schema
* table index(if available), and perform operations
*/
if (indexes === null || indexes === void 0 ? void 0 : indexes[0]) {
(0, handle_indexes_1.default)({
dbFullName,
indexes,
tableName,
});
}
/**
* Handle DATASQUIREL Table Unique Indexes
* ===================================================
* @description Iterate through each datasquirel schema
* table unique constraint(if available), and perform operations
*/
if (uniqueConstraints === null || uniqueConstraints === void 0 ? void 0 : uniqueConstraints[0]) {
(0, handle_unique_constraints_1.default)({
dbFullName,
tableUniqueConstraints: uniqueConstraints,
tableName,
});
}
return tableId;
});
@@ -1,9 +0,0 @@
type Param = {
dbFullName: string;
tableName: string;
};
/**
* # Drop All Foreign Keys
*/
export default function dropAllForeignKeys({ dbFullName, tableName, }: Param): Promise<void>;
export {};
@@ -1,52 +0,0 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = dropAllForeignKeys;
const grab_sql_key_name_1 = __importDefault(require("../../utils/grab-sql-key-name"));
const dbHandler_1 = __importDefault(require("../../functions/backend/dbHandler"));
/**
* # Drop All Foreign Keys
*/
function dropAllForeignKeys(_a) {
return __awaiter(this, arguments, void 0, function* ({ dbFullName, tableName, }) {
try {
// const rows = await varDatabaseDbHandler({
// queryString: `SELECT CONSTRAINT_NAME FROM information_schema.REFERENTIAL_CONSTRAINTS WHERE TABLE_NAME = '${tableName}' AND CONSTRAINT_SCHEMA = '${dbFullName}'`,
// });
// console.log("rows", rows);
// console.log("dbFullName", dbFullName);
// console.log("tableName", tableName);
// for (const row of rows) {
// await varDatabaseDbHandler({
// queryString: `ALTER TABLE \`${dbFullName}\`.\`${tableName}\` DROP FOREIGN KEY \`${row.CONSTRAINT_NAME}\`
// `,
// });
// }
const foreignKeys = (yield (0, dbHandler_1.default)({
query: `SHOW INDEXES FROM \`${dbFullName}\`.\`${tableName}\` WHERE Key_name LIKE '${(0, grab_sql_key_name_1.default)({ type: "foreign_key" })}%'`,
}));
for (const fk of foreignKeys) {
if (fk.Key_name.match(new RegExp((0, grab_sql_key_name_1.default)({ type: "foreign_key" })))) {
yield (0, dbHandler_1.default)({
query: `ALTER TABLE \`${dbFullName}\`.\`${tableName}\` DROP INDEX \`${fk.Key_name}\`
`,
});
}
}
}
catch (error) {
console.log(`dropAllForeignKeys ERROR => ${error.message}`);
}
});
}
@@ -0,0 +1,16 @@
import { DSQL_FieldSchemaType, DSQL_MYSQL_SHOW_COLUMNS_Type } from "../../types";
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 function handleDSQLSchemaFields({ dbFullName, tableName, fields, allExistingColumns, }: Param): Promise<void>;
export {};
@@ -0,0 +1,72 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = handleDSQLSchemaFields;
const dbHandler_1 = __importDefault(require("../../functions/backend/dbHandler"));
const default_fields_regexp_1 = __importDefault(require("../../functions/dsql/default-fields-regexp"));
const generateColumnDescription_1 = __importDefault(require("./generateColumnDescription"));
/**
* Handle DATASQUIREL schema fields for current table
* ===================================================
* @description Iterate through each field object and
* perform operations
*/
function handleDSQLSchemaFields(_a) {
return __awaiter(this, arguments, void 0, function* ({ dbFullName, tableName, fields, allExistingColumns, }) {
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 (default_fields_regexp_1.default.test(fieldName))
continue;
let updateText = "";
const existingColumnIndex = allExistingColumns === null || allExistingColumns === void 0 ? void 0 : allExistingColumns.findIndex((_column, _index) => _column.Field === fieldName);
const existingColumn = existingColumnIndex >= 0
? allExistingColumns[existingColumnIndex]
: undefined;
let { fieldEntryText } = (0, generateColumnDescription_1.default)({
columnData: column,
});
/**
* @description Modify Column(Field) if it already exists
* in MYSQL database
*/
if (existingColumn === null || existingColumn === void 0 ? void 0 : 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 = yield (0, dbHandler_1.default)({
query: finalSQL,
});
});
}
@@ -0,0 +1,18 @@
import { DSQL_DatabaseSchemaType, DSQL_FieldSchemaType, DSQL_MYSQL_SHOW_COLUMNS_Type } from "../../types";
type Param = {
dbFullName: string;
tableName: string;
fields: DSQL_FieldSchemaType[];
dbSchema: DSQL_DatabaseSchemaType;
userId?: number | string | null;
};
/**
* Handle MYSQL Columns (Fields)
* ===================================================
* @description Now handle all fields/columns
*/
export default function handleMariaDBExistingColumns({ dbFullName, tableName, fields, dbSchema, userId, }: Param): Promise<{
upToDateTableFieldsArray: DSQL_FieldSchemaType[];
allExistingColumns: DSQL_MYSQL_SHOW_COLUMNS_Type[];
}>;
export {};
@@ -0,0 +1,94 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = handleMariaDBExistingColumns;
const dbHandler_1 = __importDefault(require("../../functions/backend/dbHandler"));
const default_fields_regexp_1 = __importDefault(require("../../functions/dsql/default-fields-regexp"));
const grab_required_database_schemas_1 = require("../createDbFromSchema/grab-required-database-schemas");
const lodash_1 = __importDefault(require("lodash"));
/**
* Handle MYSQL Columns (Fields)
* ===================================================
* @description Now handle all fields/columns
*/
function handleMariaDBExistingColumns(_a) {
return __awaiter(this, arguments, void 0, function* ({ dbFullName, tableName, fields, dbSchema, userId, }) {
let upToDateTableFieldsArray = lodash_1.default.cloneDeep(fields);
let allExistingColumns = (yield (0, dbHandler_1.default)({
query: `SHOW COLUMNS FROM \`${dbFullName}\`.\`${tableName}\``,
}));
/**
* @description Iterate through every existing column
*/
for (let e = 0; e < allExistingColumns.length; e++) {
const { Field } = allExistingColumns[e];
if (Field.match(default_fields_regexp_1.default))
continue;
/**
* @description This finds out whether the fieldName corresponds with the MSQL Field name
* if the fildName doesn't match any MYSQL Field name, the field is deleted.
*/
let existingEntry = upToDateTableFieldsArray.find((column) => column.fieldName === Field || column.originName === Field);
if (!existingEntry) {
yield (0, dbHandler_1.default)({
query: `ALTER TABLE \`${dbFullName}\`.\`${tableName}\` DROP COLUMN \`${Field}\``,
});
continue;
}
if (existingEntry) {
/**
* @description Check if Field name has been updated
*/
if (existingEntry.updatedField && existingEntry.fieldName) {
yield (0, dbHandler_1.default)({
query: `ALTER TABLE \`${dbFullName}\`.\`${tableName}\` RENAME COLUMN \`${existingEntry.originName}\` TO \`${existingEntry.fieldName}\``,
});
console.log(`Column Renamed from "${existingEntry.originName}" to "${existingEntry.fieldName}"`);
/**
* Update Db Schema
* ===================================================
* @description Update Db Schema after renaming column
*/
try {
const updatedSchemaData = lodash_1.default.cloneDeep(dbSchema);
const targetTableIndex = updatedSchemaData.tables.findIndex((table) => table.tableName === tableName);
const targetFieldIndex = updatedSchemaData.tables[targetTableIndex].fields.findIndex((field) => field.fieldName === existingEntry.fieldName);
delete updatedSchemaData.tables[targetTableIndex].fields[targetFieldIndex]["originName"];
delete updatedSchemaData.tables[targetTableIndex].fields[targetFieldIndex]["updatedField"];
/**
* @description Set New Table Fields Array
*/
upToDateTableFieldsArray =
updatedSchemaData.tables[targetTableIndex].fields;
if (userId) {
(0, grab_required_database_schemas_1.writeUpdatedDbSchema)({
dbSchema: updatedSchemaData,
userId,
});
}
allExistingColumns = (yield (0, dbHandler_1.default)({
query: `SHOW COLUMNS FROM \`${dbFullName}\`.\`${tableName}\``,
}));
}
catch (error) {
console.log("Update table error =>", error.message);
}
////////////////////////////////////////
}
continue;
}
}
return { upToDateTableFieldsArray, allExistingColumns };
});
}
@@ -1,13 +1,15 @@
import { DSQL_ForeignKeyType } from "../../types";
import { DSQL_FieldSchemaType } from "../../types";
type Param = {
dbFullName: string;
tableName: string;
foreignKey: DSQL_ForeignKeyType;
fieldName: string;
errorLogs?: any[];
fields: DSQL_FieldSchemaType[];
clone?: boolean;
};
/**
* # Update table function
* Handle MYSQL Foreign Keys
* ===================================================
* @description Iterate through each datasquirel schema
* table index(if available), and perform operations
*/
export default function handleTableForeignKey({ dbFullName, tableName, foreignKey, errorLogs, fieldName, }: Param): Promise<void>;
export default function handleTableForeignKey({ dbFullName, tableName, fields, clone, }: Param): Promise<void>;
export {};
+26 -19
View File
@@ -15,27 +15,34 @@ Object.defineProperty(exports, "__esModule", { value: true });
exports.default = handleTableForeignKey;
const dbHandler_1 = __importDefault(require("../../functions/backend/dbHandler"));
/**
* # Update table function
* Handle MYSQL Foreign Keys
* ===================================================
* @description Iterate through each datasquirel schema
* table index(if available), and perform operations
*/
function handleTableForeignKey(_a) {
return __awaiter(this, arguments, void 0, function* ({ dbFullName, tableName, foreignKey, errorLogs, fieldName, }) {
const { destinationTableName, destinationTableColumnName, cascadeDelete, cascadeUpdate, foreignKeyName, } = foreignKey;
let finalQueryString = `ALTER TABLE \`${dbFullName}\`.\`${tableName}\``;
finalQueryString += ` ADD CONSTRAINT \`${foreignKeyName}\` FOREIGN KEY (\`${fieldName}\`)`;
finalQueryString += ` REFERENCES \`${destinationTableName}\`(\`${destinationTableColumnName}\`)`;
if (cascadeDelete)
finalQueryString += ` ON DELETE CASCADE`;
if (cascadeUpdate)
finalQueryString += ` ON UPDATE CASCADE`;
// let foreinKeyText = `ADD CONSTRAINT \`${foreignKeyName}\` FOREIGN KEY (\`${destinationTableColumnType}\`) REFERENCES \`${destinationTableName}\`(\`${destinationTableColumnName}\`)${
// cascadeDelete ? " ON DELETE CASCADE" : ""
// }${cascadeUpdate ? " ON UPDATE CASCADE" : ""}`;
// let finalQueryString = `ALTER TABLE \`${dbFullName}\`.\`${tableName}\` ${foreinKeyText}`;
const addForeignKey = (yield (0, dbHandler_1.default)({
query: finalQueryString,
}));
if (!(addForeignKey === null || addForeignKey === void 0 ? void 0 : addForeignKey.serverStatus)) {
errorLogs === null || errorLogs === void 0 ? void 0 : errorLogs.push(addForeignKey);
return __awaiter(this, arguments, void 0, function* ({ dbFullName, tableName, fields, clone, }) {
let addFkSQL = `ALTER TABLE \`${dbFullName}\`.\`${tableName}\``;
for (let i = 0; i < fields.length; i++) {
const { fieldName, foreignKey } = fields[i];
if (!clone && foreignKey && fieldName) {
const { destinationTableName, destinationTableColumnName, cascadeDelete, cascadeUpdate, foreignKeyName, } = foreignKey;
addFkSQL += ` ADD CONSTRAINT \`${foreignKeyName}\` FOREIGN KEY (\`${fieldName}\`)`;
addFkSQL += ` REFERENCES \`${destinationTableName}\`(\`${destinationTableColumnName}\`)`;
if (cascadeDelete)
addFkSQL += ` ON DELETE CASCADE`;
if (cascadeUpdate)
addFkSQL += ` ON UPDATE CASCADE`;
addFkSQL += `,`;
}
}
const finalAddFKSQL = addFkSQL.endsWith(",")
? addFkSQL.replace(/\,$/, "")
: undefined;
if (finalAddFKSQL) {
const addForeignKey = (yield (0, dbHandler_1.default)({
query: finalAddFKSQL,
}));
}
});
}
+17
View File
@@ -0,0 +1,17 @@
import { DSQL_DatabaseSchemaType, DSQL_TableSchemaType } from "../../types";
import { DSQL_DATASQUIREL_USER_DATABASES } from "../../types/dsql";
type Params = {
dbFullName: string;
tableName: string;
tableSchema: DSQL_TableSchemaType;
dbSchema: DSQL_DatabaseSchemaType;
recordedDbEntry?: DSQL_DATASQUIREL_USER_DATABASES;
isMain?: boolean;
};
/**
* # Update table function
*/
export default function updateTableInit({ dbFullName, tableName, tableSchema, recordedDbEntry, isMain, }: Params): Promise<{
tableID: number | undefined;
}>;
export {};
+136
View File
@@ -0,0 +1,136 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = updateTableInit;
const create_table_handle_table_record_1 = __importDefault(require("./create-table-handle-table-record"));
const dbHandler_1 = __importDefault(require("../../functions/backend/dbHandler"));
/**
* # Update table function
*/
function updateTableInit(_a) {
return __awaiter(this, arguments, void 0, function* ({ dbFullName, tableName, tableSchema, recordedDbEntry, isMain, }) {
/**
* @description Grab Table Record
*/
if (!recordedDbEntry && !isMain) {
throw new Error("Recorded Db entry not found!");
}
let tableID = yield (0, create_table_handle_table_record_1.default)({
recordedDbEntry,
tableSchema,
update: true,
isMain,
});
if (!tableID && !isMain) {
throw new Error("Recorded Table entry not found!");
}
/**
* Handle Table Default Collation
*
* @description Update Column Collation
*/
if (tableSchema.collation) {
try {
const existingCollation = (yield (0, dbHandler_1.default)({
query: `SHOW TABLE STATUS LIKE '${tableName}'`,
config: { database: dbFullName },
}));
const existingCollationStr = existingCollation === null || existingCollation === void 0 ? void 0 : existingCollation[0].Collation;
if (existingCollationStr !== tableSchema.collation) {
yield (0, dbHandler_1.default)({
query: `ALTER TABLE \`${dbFullName}\`.\`${tableName}\` CONVERT TO CHARACTER SET utf8mb4 COLLATE ${tableSchema.collation}`,
});
}
}
catch (error) { }
}
/**
* Drop All Foreign Keys
* ===================================================
* @description Find all existing foreign keys and drop
* them
*/
const allForeignKeys = (yield (0, dbHandler_1.default)({
query: `SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE CONSTRAINT_SCHEMA = '${dbFullName}' AND TABLE_NAME='${tableName}' AND CONSTRAINT_TYPE='FOREIGN KEY'`,
}));
if (allForeignKeys === null || allForeignKeys === void 0 ? void 0 : allForeignKeys[0]) {
let dropFkSQL = `ALTER TABLE \`${dbFullName}\`.\`${tableName}\``;
for (let c = 0; c < allForeignKeys.length; c++) {
const { CONSTRAINT_NAME } = allForeignKeys[c];
if (CONSTRAINT_NAME.match(/PRIMARY/))
continue;
dropFkSQL += ` DROP FOREIGN KEY \`${CONSTRAINT_NAME}\`,`;
}
const finalSQL = dropFkSQL.endsWith(",")
? dropFkSQL.replace(/\,$/, "")
: undefined;
if (finalSQL) {
yield (0, dbHandler_1.default)({
query: finalSQL,
});
}
}
/**
* Drop All Unique Constraints
* ===================================================
* @description Find all existing unique field constraints
* and remove them
*/
const allUniqueConstraints = (yield (0, dbHandler_1.default)({
query: `SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE CONSTRAINT_SCHEMA = '${dbFullName}' AND TABLE_NAME='${tableName}' AND CONSTRAINT_TYPE='UNIQUE'`,
}));
if (allUniqueConstraints === null || allUniqueConstraints === void 0 ? void 0 : allUniqueConstraints[0]) {
let dropIndxSQL = `ALTER TABLE \`${dbFullName}\`.\`${tableName}\``;
for (let c = 0; c < allUniqueConstraints.length; c++) {
const { CONSTRAINT_NAME } = allUniqueConstraints[c];
dropIndxSQL += ` DROP INDEX ${CONSTRAINT_NAME},`;
}
const finalDropIndxSQL = dropIndxSQL.endsWith(",")
? dropIndxSQL.replace(/\,$/, "")
: undefined;
if (finalDropIndxSQL) {
yield (0, dbHandler_1.default)({
query: finalDropIndxSQL,
});
}
}
/**
* Drop All Indexes
* ===================================================
* @description Find all existing foreign keys and drop
* them
*/
const allMariadbIndexes = (yield (0, dbHandler_1.default)({
query: `SHOW INDEXES FROM \`${dbFullName}\`.\`${tableName}\``,
}));
if (allMariadbIndexes === null || allMariadbIndexes === void 0 ? void 0 : allMariadbIndexes[0]) {
let dropIndxs = `ALTER TABLE \`${dbFullName}\`.\`${tableName}\``;
for (let c = 0; c < allMariadbIndexes.length; c++) {
const { Key_name } = allMariadbIndexes[c];
if (Key_name.match(/PRIMARY/))
continue;
dropIndxs += ` DROP INDEX \`${Key_name}\`,`;
}
const finalDropIndxs = dropIndxs.endsWith(",")
? dropIndxs.replace(/\,$/, "")
: undefined;
if (finalDropIndxs) {
const dropFkRes = yield (0, dbHandler_1.default)({
query: finalDropIndxs,
});
}
}
return { tableID };
});
}
+3 -2
View File
@@ -1,4 +1,4 @@
import { DSQL_DatabaseSchemaType, DSQL_FieldSchemaType, DSQL_IndexSchemaType, DSQL_TableSchemaType } from "../../types";
import { DSQL_DatabaseSchemaType, DSQL_FieldSchemaType, DSQL_IndexSchemaType, DSQL_TableSchemaType, DSQL_UniqueConstraintSchemaType } from "../../types";
import { DSQL_DATASQUIREL_USER_DATABASES } from "../../types/dsql";
type Param = {
dbFullName: string;
@@ -8,6 +8,7 @@ type Param = {
userId?: number | string | null;
dbSchema: DSQL_DatabaseSchemaType;
tableIndexes?: DSQL_IndexSchemaType[];
tableUniqueConstraints?: DSQL_UniqueConstraintSchemaType[];
clone?: boolean;
recordedDbEntry?: DSQL_DATASQUIREL_USER_DATABASES;
isMain?: boolean;
@@ -15,5 +16,5 @@ type Param = {
/**
* # Update table function
*/
export default function updateTable({ dbFullName, tableName, tableFields, userId, dbSchema, tableIndexes, tableSchema, clone, recordedDbEntry, isMain, }: Param): Promise<number | undefined>;
export default function updateTable({ dbFullName, tableName, tableFields, userId, dbSchema, tableIndexes, tableSchema, clone, recordedDbEntry, isMain, tableUniqueConstraints, }: Param): Promise<number | undefined>;
export {};
+48 -297
View File
@@ -13,117 +13,72 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = updateTable;
const generateColumnDescription_1 = __importDefault(require("./generateColumnDescription"));
const handle_table_foreign_key_1 = __importDefault(require("./handle-table-foreign-key"));
const drop_all_foreign_keys_1 = __importDefault(require("./drop-all-foreign-keys"));
const create_table_handle_table_record_1 = __importDefault(require("./create-table-handle-table-record"));
const default_fields_regexp_1 = __importDefault(require("../../functions/dsql/default-fields-regexp"));
const handle_indexes_1 = __importDefault(require("../createDbFromSchema/handle-indexes"));
const lodash_1 = __importDefault(require("lodash"));
const grab_required_database_schemas_1 = require("../createDbFromSchema/grab-required-database-schemas");
const normalize_text_1 = __importDefault(require("../../utils/normalize-text"));
const dbHandler_1 = __importDefault(require("../../functions/backend/dbHandler"));
const handle_unique_constraints_1 = __importDefault(require("../createDbFromSchema/handle-unique-constraints"));
const handle_table_foreign_key_1 = __importDefault(require("./handle-table-foreign-key"));
const handle_dsql_schema_fields_1 = __importDefault(require("./handle-dsql-schema-fields"));
const handle_mariadb_existing_columns_1 = __importDefault(require("./handle-mariadb-existing-columns"));
const update_table_init_1 = __importDefault(require("./update-table-init"));
/**
* # Update table function
*/
function updateTable(_a) {
return __awaiter(this, arguments, void 0, function* ({ dbFullName, tableName, tableFields, userId, dbSchema, tableIndexes, tableSchema, clone, recordedDbEntry, isMain, }) {
/**
* Initialize
* ==========================================
* @description Initial setup
*/
let errorLogs = [];
/**
* @description Initialize table info array. This value will be
* changing depending on if a field is renamed or not.
*/
let upToDateTableFieldsArray = lodash_1.default.cloneDeep(tableFields);
/**
* @type {string[]}
* @description Table update query string array
*/
const updateTableQueryArray = [];
/**
* @description Push the query initial value
*/
updateTableQueryArray.push(`ALTER TABLE \`${dbFullName}\`.\`${tableName}\``);
return __awaiter(this, arguments, void 0, function* ({ dbFullName, tableName, tableFields, userId, dbSchema, tableIndexes, tableSchema, clone, recordedDbEntry, isMain, tableUniqueConstraints, }) {
/**
* @description Grab Table Record
*/
if (!recordedDbEntry && !isMain) {
throw new Error("Recorded Db entry not found!");
}
let tableID = yield (0, create_table_handle_table_record_1.default)({
recordedDbEntry,
const { tableID } = yield (0, update_table_init_1.default)({
dbFullName,
dbSchema,
tableName,
tableSchema,
update: true,
isMain,
recordedDbEntry,
});
if (!tableID && !isMain) {
throw new Error("Recorded Table entry not found!");
}
/**
* Handle Table Default Collation
*
* @description Update Column Collation
*/
if (tableSchema.collation) {
try {
const existingCollation = (yield (0, dbHandler_1.default)({
query: `SHOW TABLE STATUS LIKE '${tableName}'`,
config: { database: dbFullName },
}));
const existingCollationStr = existingCollation === null || existingCollation === void 0 ? void 0 : existingCollation[0].Collation;
if (existingCollationStr !== tableSchema.collation) {
yield (0, dbHandler_1.default)({
query: `ALTER TABLE \`${dbFullName}\`.\`${tableName}\` CONVERT TO CHARACTER SET utf8mb4 COLLATE ${tableSchema.collation}`,
});
}
}
catch (error) { }
}
/**
* Handle Table updates
*
* @description Try to undate table, catch error if anything goes wrong
*/
try {
const { allExistingColumns, upToDateTableFieldsArray } = yield (0, handle_mariadb_existing_columns_1.default)({
dbFullName,
dbSchema,
fields: tableFields,
tableName,
userId,
});
/**
* Handle MYSQL Table Indexes
* Handle DATASQUIREL schema fields for current table
* ===================================================
* @description Iterate through each table index(if available)
* and perform operations
* @description Iterate through each field object and
* perform operations
*/
const allExistingIndexes = (yield (0, dbHandler_1.default)({
query: `SHOW INDEXES FROM \`${dbFullName}\`.\`${tableName}\` WHERE Index_comment LIKE '%schema_index%'`,
}));
if (allExistingIndexes) {
for (let f = 0; f < allExistingIndexes.length; f++) {
const { Key_name } = allExistingIndexes[f];
try {
const existingKeyInSchema = tableIndexes === null || tableIndexes === void 0 ? void 0 : tableIndexes.find((indexObject) => indexObject.alias === Key_name);
if (!existingKeyInSchema)
throw new Error(`This Index(${Key_name}) Has been Deleted!`);
}
catch (error) {
/**
* @description Drop Index: This happens when the MYSQL index is not
* present in the datasquirel DB schema
*/
yield (0, dbHandler_1.default)({
query: `ALTER TABLE \`${dbFullName}\`.\`${tableName}\` DROP INDEX \`${Key_name}\``,
});
}
}
}
yield (0, handle_dsql_schema_fields_1.default)({
dbFullName,
tableName,
fields: upToDateTableFieldsArray,
allExistingColumns,
});
/**
* Handle MYSQL Foreign Keys
* ===================================================
* @description Iterate through each datasquirel schema
* table index(if available), and perform operations
*/
yield (0, handle_table_foreign_key_1.default)({
dbFullName,
fields: upToDateTableFieldsArray,
tableName,
clone,
});
/**
* Handle DATASQUIREL Table Indexes
* ===================================================
* @description Iterate through each datasquirel schema
* table index(if available), and perform operations
*/
if (tableIndexes && tableIndexes[0]) {
if (tableIndexes === null || tableIndexes === void 0 ? void 0 : tableIndexes[0]) {
(0, handle_indexes_1.default)({
dbFullName,
indexes: tableIndexes,
@@ -131,226 +86,22 @@ function updateTable(_a) {
});
}
/**
* Handle MYSQL Foreign Keys
* Handle DATASQUIREL Table Unique Indexes
* ===================================================
* @description Iterate through each datasquirel schema
* table index(if available), and perform operations
* table unique constraint(if available), and perform operations
*/
const allForeignKeys = (yield (0, dbHandler_1.default)({
query: `SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE CONSTRAINT_SCHEMA = '${dbFullName}' AND TABLE_NAME='${tableName}' AND CONSTRAINT_TYPE='FOREIGN KEY'`,
}));
if (allForeignKeys) {
for (let c = 0; c < allForeignKeys.length; c++) {
const { CONSTRAINT_NAME } = allForeignKeys[c];
/**
* @description Skip if Key is the PRIMARY Key
*/
if (CONSTRAINT_NAME.match(/PRIMARY/))
continue;
/**
* @description Drop all foreign Keys to avoid MYSQL errors when adding/updating
* Foreign keys
*/
yield (0, dbHandler_1.default)({
query: `ALTER TABLE \`${dbFullName}\`.\`${tableName}\` DROP FOREIGN KEY \`${CONSTRAINT_NAME}\``,
});
}
}
/**
* Handle MYSQL Unique Fields
* ===================================================
* @description Find all existing unique field constraints
* and remove them
*/
const allUniqueConstraints = (yield (0, dbHandler_1.default)({
query: (0, normalize_text_1.default)(`SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS \
WHERE CONSTRAINT_SCHEMA = '${dbFullName}' AND TABLE_NAME='${tableName}' AND \
CONSTRAINT_TYPE='UNIQUE'`),
}));
if (allUniqueConstraints) {
for (let c = 0; c < allUniqueConstraints.length; c++) {
const { CONSTRAINT_NAME } = allUniqueConstraints[c];
yield (0, dbHandler_1.default)({
query: `ALTER TABLE \`${dbFullName}\`.\`${tableName}\` DROP INDEX \`${CONSTRAINT_NAME}\``,
});
}
}
/**
* Handle MYSQL Columns (Fields)
* ===================================================
* @description Now handle all fields/columns
*/
let allExistingColumns = (yield (0, dbHandler_1.default)({
query: `SHOW COLUMNS FROM \`${dbFullName}\`.\`${tableName}\``,
}));
/**
* @type {string[]}
* @description Updated column names Array
*/
const updatedColumnsArray = [];
/**
* @description Iterate through every existing column
*/
for (let e = 0; e < allExistingColumns.length; e++) {
const { Field } = allExistingColumns[e];
if (Field.match(default_fields_regexp_1.default))
continue;
/**
* @description This finds out whether the fieldName corresponds with the MSQL Field name
* if the fildName doesn't match any MYSQL Field name, the field is deleted.
*/
let existingEntry = upToDateTableFieldsArray.find((column) => column.fieldName === Field || column.originName === Field);
if (existingEntry) {
/**
* @description Check if Field name has been updated
*/
if (existingEntry.updatedField && existingEntry.fieldName) {
updatedColumnsArray.push(existingEntry.fieldName);
yield (0, dbHandler_1.default)({
query: `ALTER TABLE \`${dbFullName}\`.\`${tableName}\` RENAME COLUMN \`${existingEntry.originName}\` TO \`${existingEntry.fieldName}\``,
});
console.log(`Column Renamed from "${existingEntry.originName}" to "${existingEntry.fieldName}"`);
/**
* Update Db Schema
* ===================================================
* @description Update Db Schema after renaming column
*/
try {
const updatedSchemaData = lodash_1.default.cloneDeep(dbSchema);
const targetTableIndex = updatedSchemaData.tables.findIndex((table) => table.tableName === tableName);
const targetFieldIndex = updatedSchemaData.tables[targetTableIndex].fields.findIndex((field) => field.fieldName === existingEntry.fieldName);
delete updatedSchemaData.tables[targetTableIndex]
.fields[targetFieldIndex]["originName"];
delete updatedSchemaData.tables[targetTableIndex]
.fields[targetFieldIndex]["updatedField"];
/**
* @description Set New Table Fields Array
*/
upToDateTableFieldsArray =
updatedSchemaData.tables[targetTableIndex].fields;
if (userId) {
(0, grab_required_database_schemas_1.writeUpdatedDbSchema)({
dbSchema: updatedSchemaData,
userId,
});
}
allExistingColumns = (yield (0, dbHandler_1.default)({
query: `SHOW COLUMNS FROM \`${dbFullName}\`.\`${tableName}\``,
}));
}
catch (error) {
console.log("Update table error =>", error.message);
}
////////////////////////////////////////
}
////////////////////////////////////////
continue;
////////////////////////////////////////
}
else {
yield (0, dbHandler_1.default)({
query: `ALTER TABLE \`${dbFullName}\`.\`${tableName}\` DROP COLUMN \`${Field}\``,
});
}
}
/**
* Handle DATASQUIREL schema fields for current table
* ===================================================
* @description Iterate through each field object and
* perform operations
*/
for (let i = 0; i < upToDateTableFieldsArray.length; i++) {
const column = upToDateTableFieldsArray[i];
// const prevColumn = upToDateTableFieldsArray[i - 1];
// const nextColumn = upToDateTableFieldsArray[i + 1];
const { fieldName, dataType, foreignKey } = column;
if (!fieldName)
continue;
if (default_fields_regexp_1.default.test(fieldName))
continue;
let updateText = "";
const existingColumnIndex = allExistingColumns === null || allExistingColumns === void 0 ? void 0 : allExistingColumns.findIndex((_column, _index) => _column.Field === fieldName);
const existingColumn = existingColumnIndex >= 0
? allExistingColumns[existingColumnIndex]
: undefined;
let { fieldEntryText } = (0, generateColumnDescription_1.default)({
columnData: column,
if (tableUniqueConstraints === null || tableUniqueConstraints === void 0 ? void 0 : tableUniqueConstraints[0]) {
(0, handle_unique_constraints_1.default)({
dbFullName,
tableUniqueConstraints,
tableName,
});
/**
* @description Modify Column(Field) if it already exists
* in MYSQL database
*/
if (existingColumn === null || existingColumn === void 0 ? void 0 : existingColumn.Field) {
const { Field, Type } = existingColumn;
updateText += `MODIFY COLUMN ${fieldEntryText}`;
// if (
// Field === fieldName &&
// dataType?.toUpperCase() === Type.toUpperCase()
// ) {
// } else {
// 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(/./)) {
updateTableQueryArray.push(updateText + ",");
}
}
/**
* @description Construct final SQL query by combning all SQL snippets in
* updateTableQueryArray Arry, and trimming the final comma(,)
*/
const updateTableQuery = updateTableQueryArray
.filter((q) => Boolean(q.match(/./)))
.join(" ")
.replace(/,$/, "");
////////////////////////////////////////
/**
* @description Check if SQL snippets array has more than 1 entries
* This is because 1 entry means "ALTER TABLE table_name" only, without any
* Alter directives like "ADD COLUMN" or "MODIFY COLUMN"
*/
if (updateTableQueryArray.length > 1) {
const updateTable = yield (0, dbHandler_1.default)({
query: updateTableQuery,
});
/**
* # Handle Foreign Keys
*/
yield (0, drop_all_foreign_keys_1.default)({ dbFullName, tableName });
for (let i = 0; i < upToDateTableFieldsArray.length; i++) {
const { fieldName, foreignKey } = upToDateTableFieldsArray[i];
if (!clone && foreignKey && fieldName) {
yield (0, handle_table_foreign_key_1.default)({
dbFullName,
errorLogs,
foreignKey,
fieldName,
tableName,
});
}
}
}
else {
/**
* @description If only 1 SQL snippet is left in updateTableQueryArray, this
* means that no updates have been made to the table
*/
}
return tableID;
}
catch (error) {
console.log('Error in "updateTable" shell function =>', error.message);
return tableID;
}
return tableID;
});
}