Updates
This commit is contained in:
@@ -4,6 +4,7 @@ import {
|
||||
} from "../../types";
|
||||
import grabDSQLSchemaIndexComment from "../utils/grab-dsql-schema-index-comment";
|
||||
import dbHandler from "../../functions/backend/dbHandler";
|
||||
import AppData from "../../data/app-data";
|
||||
|
||||
type Param = {
|
||||
tableName: string;
|
||||
@@ -22,48 +23,59 @@ export default async function handleIndexescreateDbFromSchema({
|
||||
tableName,
|
||||
indexes,
|
||||
}: Param) {
|
||||
/**
|
||||
* Handle MYSQL Table Indexes
|
||||
* ===================================================
|
||||
* @description Iterate through each table index(if available)
|
||||
* and perform operations
|
||||
*/
|
||||
const allExistingIndexes = (await dbHandler({
|
||||
query: `SHOW INDEXES FROM \`${dbFullName}\`.\`${tableName}\``,
|
||||
})) as DSQL_MYSQL_SHOW_INDEXES_Type[];
|
||||
query: `SHOW INDEXES FROM \`${dbFullName}\`.\`${tableName}\` WHERE Index_comment LIKE '%${AppData["IndexComment"]}%'`,
|
||||
})) as DSQL_MYSQL_SHOW_INDEXES_Type[] | null;
|
||||
|
||||
if (allExistingIndexes) {
|
||||
for (let f = 0; f < allExistingIndexes.length; f++) {
|
||||
const { Key_name } = allExistingIndexes[f];
|
||||
|
||||
try {
|
||||
const existingKeyInSchema = 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
|
||||
*/
|
||||
await dbHandler({
|
||||
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?.match(/./)) continue;
|
||||
|
||||
/**
|
||||
* @description Check for existing Index in MYSQL db
|
||||
*/
|
||||
try {
|
||||
const existingKeyInDb = allExistingIndexes.filter(
|
||||
(indexObject) => indexObject.Key_name === alias
|
||||
);
|
||||
const queryString = `CREATE${
|
||||
indexType == "full_text"
|
||||
? " FULLTEXT"
|
||||
: indexType == "vector"
|
||||
? " VECTOR"
|
||||
: ""
|
||||
} INDEX \`${alias}\` ON \`${dbFullName}\`.\`${tableName}\`(${indexTableFields
|
||||
?.map((nm) => nm.value)
|
||||
.map((nm) => `\`${nm}\``)
|
||||
.join(",")}) COMMENT '${AppData["IndexComment"]} ${indexName}'`;
|
||||
|
||||
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
|
||||
?.map((nm) => nm.value)
|
||||
.map((nm) => `\`${nm}\``)
|
||||
.join(
|
||||
","
|
||||
)}) COMMENT '${grabDSQLSchemaIndexComment()} ${indexName}'`;
|
||||
|
||||
const addIndex = await dbHandler({ query: queryString });
|
||||
}
|
||||
const addIndex = await dbHandler({ query: queryString });
|
||||
}
|
||||
|
||||
const allExistingIndexesAfterUpdate = (await dbHandler({
|
||||
query: `SHOW INDEXES FROM \`${dbFullName}\`.\`${tableName}\``,
|
||||
})) as DSQL_MYSQL_SHOW_INDEXES_Type[];
|
||||
}
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
import {
|
||||
DSQL_MYSQL_FOREIGN_KEYS_Type,
|
||||
DSQL_MYSQL_SHOW_INDEXES_Type,
|
||||
DSQL_UniqueConstraintSchemaType,
|
||||
} from "../../types";
|
||||
import dbHandler from "../../functions/backend/dbHandler";
|
||||
import AppData from "../../data/app-data";
|
||||
import normalizeText from "../../utils/normalize-text";
|
||||
|
||||
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 async function handleUniqueConstraintsCreateDbFromSchema({
|
||||
dbFullName,
|
||||
tableName,
|
||||
tableUniqueConstraints,
|
||||
}: Param) {
|
||||
/**
|
||||
* # 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?.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
|
||||
?.map((nm) => nm.value)
|
||||
.map((nm) => `\`${nm}\``)
|
||||
.join(",")}) COMMENT '${
|
||||
AppData["UniqueConstraintComment"]
|
||||
} ${constraintName}'`;
|
||||
|
||||
const addIndex = await dbHandler({ query: queryString });
|
||||
}
|
||||
}
|
||||
@@ -131,7 +131,7 @@ export default async function createDbFromSchema({
|
||||
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;
|
||||
|
||||
@@ -169,6 +169,7 @@ export default async function createDbFromSchema({
|
||||
recordedDbEntry,
|
||||
tableSchema: table,
|
||||
isMain,
|
||||
tableUniqueConstraints: uniqueConstraints,
|
||||
});
|
||||
|
||||
if (table.childrenTables && table.childrenTables[0]) {
|
||||
@@ -201,6 +202,8 @@ export default async function createDbFromSchema({
|
||||
userId,
|
||||
dbSchema: childTableParentDbSchema,
|
||||
tableIndexes: childTableSchema.indexes,
|
||||
tableUniqueConstraints:
|
||||
childTableSchema.uniqueConstraints,
|
||||
clone: true,
|
||||
recordedDbEntry,
|
||||
tableSchema: table,
|
||||
@@ -214,11 +217,13 @@ export default async function createDbFromSchema({
|
||||
*/
|
||||
const createNewTable = await createTable({
|
||||
tableName: tableName,
|
||||
tableInfoArray: fields,
|
||||
fields,
|
||||
dbFullName: dbFullName,
|
||||
tableSchema: table,
|
||||
recordedDbEntry,
|
||||
isMain,
|
||||
indexes,
|
||||
uniqueConstraints,
|
||||
});
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,18 +1,27 @@
|
||||
import generateColumnDescription from "./generateColumnDescription";
|
||||
import supplementTable from "./supplementTable";
|
||||
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";
|
||||
import handleTableForeignKey from "./handle-table-foreign-key";
|
||||
import createTableHandleTableRecord from "./create-table-handle-table-record";
|
||||
import dbHandler from "../../functions/backend/dbHandler";
|
||||
import handleIndexescreateDbFromSchema from "../createDbFromSchema/handle-indexes";
|
||||
import handleUniqueConstraintsCreateDbFromSchema from "../createDbFromSchema/handle-unique-constraints";
|
||||
|
||||
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[];
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -21,12 +30,14 @@ type Param = {
|
||||
export default async function createTable({
|
||||
dbFullName,
|
||||
tableName,
|
||||
tableInfoArray,
|
||||
fields: passedFields,
|
||||
tableSchema,
|
||||
recordedDbEntry,
|
||||
isMain,
|
||||
indexes,
|
||||
uniqueConstraints,
|
||||
}: Param) {
|
||||
const finalTable = supplementTable({ tableInfoArray: tableInfoArray });
|
||||
const fields = supplementTable({ tableInfoArray: passedFields });
|
||||
|
||||
let tableId = await createTableHandleTableRecord({
|
||||
recordedDbEntry,
|
||||
@@ -44,8 +55,8 @@ export default async function createTable({
|
||||
|
||||
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 } = generateColumnDescription({
|
||||
columnData: column,
|
||||
@@ -55,7 +66,7 @@ export default async function createTable({
|
||||
primaryKeySet = newPrimaryKeySet;
|
||||
|
||||
const comma = (() => {
|
||||
if (i === finalTable.length - 1) return "";
|
||||
if (i === fields.length - 1) return "";
|
||||
return ",";
|
||||
})();
|
||||
|
||||
@@ -74,20 +85,44 @@ export default async function createTable({
|
||||
query: createTableQuery,
|
||||
});
|
||||
|
||||
for (let i = 0; i < finalTable.length; i++) {
|
||||
const column = finalTable[i];
|
||||
const { foreignKey, fieldName } = column;
|
||||
/**
|
||||
* Handle MYSQL Foreign Keys
|
||||
* ===================================================
|
||||
* @description Iterate through each datasquirel schema
|
||||
* table index(if available), and perform operations
|
||||
*/
|
||||
await handleTableForeignKey({
|
||||
dbFullName,
|
||||
fields,
|
||||
tableName,
|
||||
});
|
||||
|
||||
if (!fieldName) continue;
|
||||
/**
|
||||
* Handle DATASQUIREL Table Indexes
|
||||
* ===================================================
|
||||
* @description Iterate through each datasquirel schema
|
||||
* table index(if available), and perform operations
|
||||
*/
|
||||
if (indexes?.[0]) {
|
||||
handleIndexescreateDbFromSchema({
|
||||
dbFullName,
|
||||
indexes,
|
||||
tableName,
|
||||
});
|
||||
}
|
||||
|
||||
if (foreignKey) {
|
||||
await handleTableForeignKey({
|
||||
dbFullName,
|
||||
foreignKey,
|
||||
tableName,
|
||||
fieldName,
|
||||
});
|
||||
}
|
||||
/**
|
||||
* Handle DATASQUIREL Table Unique Indexes
|
||||
* ===================================================
|
||||
* @description Iterate through each datasquirel schema
|
||||
* table unique constraint(if available), and perform operations
|
||||
*/
|
||||
if (uniqueConstraints?.[0]) {
|
||||
handleUniqueConstraintsCreateDbFromSchema({
|
||||
dbFullName,
|
||||
tableUniqueConstraints: uniqueConstraints,
|
||||
tableName,
|
||||
});
|
||||
}
|
||||
|
||||
return tableId;
|
||||
|
||||
@@ -1,53 +0,0 @@
|
||||
import grabSQLKeyName from "../../utils/grab-sql-key-name";
|
||||
import dbHandler from "../../functions/backend/dbHandler";
|
||||
|
||||
type Param = {
|
||||
dbFullName: string;
|
||||
tableName: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* # Drop All Foreign Keys
|
||||
*/
|
||||
export default async function dropAllForeignKeys({
|
||||
dbFullName,
|
||||
tableName,
|
||||
}: Param) {
|
||||
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 = (await dbHandler({
|
||||
query: `SHOW INDEXES FROM \`${dbFullName}\`.\`${tableName}\` WHERE Key_name LIKE '${grabSQLKeyName(
|
||||
{ type: "foreign_key" }
|
||||
)}%'`,
|
||||
})) as any;
|
||||
|
||||
for (const fk of foreignKeys) {
|
||||
if (
|
||||
fk.Key_name.match(
|
||||
new RegExp(grabSQLKeyName({ type: "foreign_key" }))
|
||||
)
|
||||
) {
|
||||
await dbHandler({
|
||||
query: `ALTER TABLE \`${dbFullName}\`.\`${tableName}\` DROP INDEX \`${fk.Key_name}\`
|
||||
`,
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (error: any) {
|
||||
console.log(`dropAllForeignKeys ERROR => ${error.message}`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
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,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
import {
|
||||
DSQL_DatabaseSchemaType,
|
||||
DSQL_FieldSchemaType,
|
||||
DSQL_MYSQL_SHOW_COLUMNS_Type,
|
||||
} from "../../types";
|
||||
import dbHandler from "../../functions/backend/dbHandler";
|
||||
import defaultFieldsRegexp from "../../functions/dsql/default-fields-regexp";
|
||||
import { writeUpdatedDbSchema } from "../createDbFromSchema/grab-required-database-schemas";
|
||||
import _ from "lodash";
|
||||
|
||||
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 async function handleMariaDBExistingColumns({
|
||||
dbFullName,
|
||||
tableName,
|
||||
fields,
|
||||
dbSchema,
|
||||
userId,
|
||||
}: Param) {
|
||||
let upToDateTableFieldsArray = _.cloneDeep(fields);
|
||||
|
||||
let allExistingColumns: DSQL_MYSQL_SHOW_COLUMNS_Type[] = (await dbHandler({
|
||||
query: `SHOW COLUMNS FROM \`${dbFullName}\`.\`${tableName}\``,
|
||||
})) as DSQL_MYSQL_SHOW_COLUMNS_Type[];
|
||||
|
||||
/**
|
||||
* @description Iterate through every existing column
|
||||
*/
|
||||
for (let e = 0; e < allExistingColumns.length; e++) {
|
||||
const { Field } = allExistingColumns[e];
|
||||
|
||||
if (Field.match(defaultFieldsRegexp)) 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) {
|
||||
await dbHandler({
|
||||
query: `ALTER TABLE \`${dbFullName}\`.\`${tableName}\` DROP COLUMN \`${Field}\``,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
if (existingEntry) {
|
||||
/**
|
||||
* @description Check if Field name has been updated
|
||||
*/
|
||||
if (existingEntry.updatedField && existingEntry.fieldName) {
|
||||
await dbHandler({
|
||||
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 = _.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) {
|
||||
writeUpdatedDbSchema({
|
||||
dbSchema: updatedSchemaData,
|
||||
userId,
|
||||
});
|
||||
}
|
||||
|
||||
allExistingColumns = (await dbHandler({
|
||||
query: `SHOW COLUMNS FROM \`${dbFullName}\`.\`${tableName}\``,
|
||||
})) as DSQL_MYSQL_SHOW_COLUMNS_Type[];
|
||||
} catch (error: any) {
|
||||
console.log("Update table error =>", error.message);
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
return { upToDateTableFieldsArray, allExistingColumns };
|
||||
}
|
||||
@@ -1,51 +1,60 @@
|
||||
import { DSQL_ForeignKeyType } from "../../types";
|
||||
import {
|
||||
DSQL_FieldSchemaType,
|
||||
DSQL_ForeignKeyType,
|
||||
DSQL_MYSQL_FOREIGN_KEYS_Type,
|
||||
} from "../../types";
|
||||
import dbHandler from "../../functions/backend/dbHandler";
|
||||
|
||||
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 async function handleTableForeignKey({
|
||||
dbFullName,
|
||||
tableName,
|
||||
foreignKey,
|
||||
errorLogs,
|
||||
fieldName,
|
||||
fields,
|
||||
clone,
|
||||
}: Param) {
|
||||
const {
|
||||
destinationTableName,
|
||||
destinationTableColumnName,
|
||||
cascadeDelete,
|
||||
cascadeUpdate,
|
||||
foreignKeyName,
|
||||
} = foreignKey;
|
||||
let addFkSQL = `ALTER TABLE \`${dbFullName}\`.\`${tableName}\``;
|
||||
|
||||
let finalQueryString = `ALTER TABLE \`${dbFullName}\`.\`${tableName}\``;
|
||||
for (let i = 0; i < fields.length; i++) {
|
||||
const { fieldName, foreignKey } = fields[i];
|
||||
|
||||
finalQueryString += ` ADD CONSTRAINT \`${foreignKeyName}\` FOREIGN KEY (\`${fieldName}\`)`;
|
||||
finalQueryString += ` REFERENCES \`${destinationTableName}\`(\`${destinationTableColumnName}\`)`;
|
||||
if (!clone && foreignKey && fieldName) {
|
||||
const {
|
||||
destinationTableName,
|
||||
destinationTableColumnName,
|
||||
cascadeDelete,
|
||||
cascadeUpdate,
|
||||
foreignKeyName,
|
||||
} = foreignKey;
|
||||
|
||||
if (cascadeDelete) finalQueryString += ` ON DELETE CASCADE`;
|
||||
if (cascadeUpdate) finalQueryString += ` ON UPDATE CASCADE`;
|
||||
addFkSQL += ` ADD CONSTRAINT \`${foreignKeyName}\` FOREIGN KEY (\`${fieldName}\`)`;
|
||||
addFkSQL += ` REFERENCES \`${destinationTableName}\`(\`${destinationTableColumnName}\`)`;
|
||||
|
||||
// let foreinKeyText = `ADD CONSTRAINT \`${foreignKeyName}\` FOREIGN KEY (\`${destinationTableColumnType}\`) REFERENCES \`${destinationTableName}\`(\`${destinationTableColumnName}\`)${
|
||||
// cascadeDelete ? " ON DELETE CASCADE" : ""
|
||||
// }${cascadeUpdate ? " ON UPDATE CASCADE" : ""}`;
|
||||
if (cascadeDelete) addFkSQL += ` ON DELETE CASCADE`;
|
||||
if (cascadeUpdate) addFkSQL += ` ON UPDATE CASCADE`;
|
||||
|
||||
// let finalQueryString = `ALTER TABLE \`${dbFullName}\`.\`${tableName}\` ${foreinKeyText}`;
|
||||
addFkSQL += `,`;
|
||||
}
|
||||
}
|
||||
|
||||
const addForeignKey = (await dbHandler({
|
||||
query: finalQueryString,
|
||||
})) as any;
|
||||
const finalAddFKSQL = addFkSQL.endsWith(",")
|
||||
? addFkSQL.replace(/\,$/, "")
|
||||
: undefined;
|
||||
|
||||
if (!addForeignKey?.serverStatus) {
|
||||
errorLogs?.push(addForeignKey);
|
||||
if (finalAddFKSQL) {
|
||||
const addForeignKey = (await dbHandler({
|
||||
query: finalAddFKSQL,
|
||||
})) as any;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
import {
|
||||
DSQL_DatabaseSchemaType,
|
||||
DSQL_MARIADB_SHOW_INDEXES_TYPE,
|
||||
DSQL_MYSQL_FOREIGN_KEYS_Type,
|
||||
DSQL_TableSchemaType,
|
||||
} from "../../types";
|
||||
import createTableHandleTableRecord from "./create-table-handle-table-record";
|
||||
import { DSQL_DATASQUIREL_USER_DATABASES } from "../../types/dsql";
|
||||
import _ from "lodash";
|
||||
import dbHandler from "../../functions/backend/dbHandler";
|
||||
|
||||
type Params = {
|
||||
dbFullName: string;
|
||||
tableName: string;
|
||||
tableSchema: DSQL_TableSchemaType;
|
||||
dbSchema: DSQL_DatabaseSchemaType;
|
||||
recordedDbEntry?: DSQL_DATASQUIREL_USER_DATABASES;
|
||||
isMain?: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* # Update table function
|
||||
*/
|
||||
export default async function updateTableInit({
|
||||
dbFullName,
|
||||
tableName,
|
||||
tableSchema,
|
||||
recordedDbEntry,
|
||||
isMain,
|
||||
}: Params) {
|
||||
/**
|
||||
* @description Grab Table Record
|
||||
*/
|
||||
if (!recordedDbEntry && !isMain) {
|
||||
throw new Error("Recorded Db entry not found!");
|
||||
}
|
||||
|
||||
let tableID = await createTableHandleTableRecord({
|
||||
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 = (await dbHandler({
|
||||
query: `SHOW TABLE STATUS LIKE '${tableName}'`,
|
||||
config: { database: dbFullName },
|
||||
})) as any[];
|
||||
|
||||
const existingCollationStr = existingCollation?.[0].Collation;
|
||||
|
||||
if (existingCollationStr !== tableSchema.collation) {
|
||||
await dbHandler({
|
||||
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 = (await dbHandler({
|
||||
query: `SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE CONSTRAINT_SCHEMA = '${dbFullName}' AND TABLE_NAME='${tableName}' AND CONSTRAINT_TYPE='FOREIGN KEY'`,
|
||||
})) as DSQL_MYSQL_FOREIGN_KEYS_Type[] | null;
|
||||
|
||||
if (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) {
|
||||
await dbHandler({
|
||||
query: finalSQL,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Drop All Unique Constraints
|
||||
* ===================================================
|
||||
* @description Find all existing unique field constraints
|
||||
* and remove them
|
||||
*/
|
||||
const allUniqueConstraints = (await dbHandler({
|
||||
query: `SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE CONSTRAINT_SCHEMA = '${dbFullName}' AND TABLE_NAME='${tableName}' AND CONSTRAINT_TYPE='UNIQUE'`,
|
||||
})) as DSQL_MYSQL_FOREIGN_KEYS_Type[] | null;
|
||||
|
||||
if (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) {
|
||||
await dbHandler({
|
||||
query: finalDropIndxSQL,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Drop All Indexes
|
||||
* ===================================================
|
||||
* @description Find all existing foreign keys and drop
|
||||
* them
|
||||
*/
|
||||
const allMariadbIndexes = (await dbHandler({
|
||||
query: `SHOW INDEXES FROM \`${dbFullName}\`.\`${tableName}\``,
|
||||
})) as DSQL_MARIADB_SHOW_INDEXES_TYPE[] | null;
|
||||
|
||||
if (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 = await dbHandler({
|
||||
query: finalDropIndxs,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return { tableID };
|
||||
}
|
||||
@@ -1,23 +1,18 @@
|
||||
import generateColumnDescription from "./generateColumnDescription";
|
||||
import {
|
||||
DSQL_DatabaseSchemaType,
|
||||
DSQL_FieldSchemaType,
|
||||
DSQL_IndexSchemaType,
|
||||
DSQL_MYSQL_FOREIGN_KEYS_Type,
|
||||
DSQL_MYSQL_SHOW_COLUMNS_Type,
|
||||
DSQL_MYSQL_SHOW_INDEXES_Type,
|
||||
DSQL_TableSchemaType,
|
||||
DSQL_UniqueConstraintSchemaType,
|
||||
} from "../../types";
|
||||
import handleTableForeignKey from "./handle-table-foreign-key";
|
||||
import dropAllForeignKeys from "./drop-all-foreign-keys";
|
||||
import createTableHandleTableRecord from "./create-table-handle-table-record";
|
||||
import { DSQL_DATASQUIREL_USER_DATABASES } from "../../types/dsql";
|
||||
import defaultFieldsRegexp from "../../functions/dsql/default-fields-regexp";
|
||||
import handleIndexescreateDbFromSchema from "../createDbFromSchema/handle-indexes";
|
||||
import _ from "lodash";
|
||||
import { writeUpdatedDbSchema } from "../createDbFromSchema/grab-required-database-schemas";
|
||||
import normalizeText from "../../utils/normalize-text";
|
||||
import dbHandler from "../../functions/backend/dbHandler";
|
||||
import handleUniqueConstraintsCreateDbFromSchema from "../createDbFromSchema/handle-unique-constraints";
|
||||
import handleTableForeignKey from "./handle-table-foreign-key";
|
||||
import handleDSQLSchemaFields from "./handle-dsql-schema-fields";
|
||||
import handleMariaDBExistingColumns from "./handle-mariadb-existing-columns";
|
||||
import updateTableInit from "./update-table-init";
|
||||
|
||||
type Param = {
|
||||
dbFullName: string;
|
||||
@@ -27,6 +22,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;
|
||||
@@ -46,113 +42,60 @@ export default async function updateTable({
|
||||
clone,
|
||||
recordedDbEntry,
|
||||
isMain,
|
||||
tableUniqueConstraints,
|
||||
}: Param): Promise<number | undefined> {
|
||||
/**
|
||||
* Initialize
|
||||
* ==========================================
|
||||
* @description Initial setup
|
||||
*/
|
||||
|
||||
let errorLogs: any[] = [];
|
||||
|
||||
/**
|
||||
* @description Initialize table info array. This value will be
|
||||
* changing depending on if a field is renamed or not.
|
||||
*/
|
||||
let upToDateTableFieldsArray = _.cloneDeep(tableFields);
|
||||
|
||||
/**
|
||||
* @type {string[]}
|
||||
* @description Table update query string array
|
||||
*/
|
||||
const updateTableQueryArray: string[] = [];
|
||||
|
||||
/**
|
||||
* @description Push the query initial value
|
||||
*/
|
||||
updateTableQueryArray.push(
|
||||
`ALTER TABLE \`${dbFullName}\`.\`${tableName}\``
|
||||
);
|
||||
|
||||
/**
|
||||
* @description Grab Table Record
|
||||
*/
|
||||
if (!recordedDbEntry && !isMain) {
|
||||
throw new Error("Recorded Db entry not found!");
|
||||
}
|
||||
|
||||
let tableID = await createTableHandleTableRecord({
|
||||
recordedDbEntry,
|
||||
const { tableID } = await updateTableInit({
|
||||
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 = (await dbHandler({
|
||||
query: `SHOW TABLE STATUS LIKE '${tableName}'`,
|
||||
config: { database: dbFullName },
|
||||
})) as any[];
|
||||
|
||||
const existingCollationStr = existingCollation?.[0].Collation;
|
||||
|
||||
if (existingCollationStr !== tableSchema.collation) {
|
||||
await dbHandler({
|
||||
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 } =
|
||||
await handleMariaDBExistingColumns({
|
||||
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 = (await dbHandler({
|
||||
query: `SHOW INDEXES FROM \`${dbFullName}\`.\`${tableName}\` WHERE Index_comment LIKE '%schema_index%'`,
|
||||
})) as DSQL_MYSQL_SHOW_INDEXES_Type[] | null;
|
||||
await handleDSQLSchemaFields({
|
||||
dbFullName,
|
||||
tableName,
|
||||
fields: upToDateTableFieldsArray,
|
||||
allExistingColumns,
|
||||
});
|
||||
|
||||
if (allExistingIndexes) {
|
||||
for (let f = 0; f < allExistingIndexes.length; f++) {
|
||||
const { Key_name } = allExistingIndexes[f];
|
||||
|
||||
try {
|
||||
const existingKeyInSchema = 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
|
||||
*/
|
||||
await dbHandler({
|
||||
query: `ALTER TABLE \`${dbFullName}\`.\`${tableName}\` DROP INDEX \`${Key_name}\``,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Handle MYSQL Foreign Keys
|
||||
* ===================================================
|
||||
* @description Iterate through each datasquirel schema
|
||||
* table index(if available), and perform operations
|
||||
*/
|
||||
await handleTableForeignKey({
|
||||
dbFullName,
|
||||
fields: upToDateTableFieldsArray,
|
||||
tableName,
|
||||
clone,
|
||||
});
|
||||
|
||||
/**
|
||||
* Handle DATASQUIREL Table Indexes
|
||||
@@ -160,7 +103,7 @@ export default async function updateTable({
|
||||
* @description Iterate through each datasquirel schema
|
||||
* table index(if available), and perform operations
|
||||
*/
|
||||
if (tableIndexes && tableIndexes[0]) {
|
||||
if (tableIndexes?.[0]) {
|
||||
handleIndexescreateDbFromSchema({
|
||||
dbFullName,
|
||||
indexes: tableIndexes,
|
||||
@@ -169,274 +112,21 @@ export default async function updateTable({
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 = (await dbHandler({
|
||||
query: `SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE CONSTRAINT_SCHEMA = '${dbFullName}' AND TABLE_NAME='${tableName}' AND CONSTRAINT_TYPE='FOREIGN KEY'`,
|
||||
})) as DSQL_MYSQL_FOREIGN_KEYS_Type[] | null;
|
||||
|
||||
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
|
||||
*/
|
||||
await dbHandler({
|
||||
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 = (await dbHandler({
|
||||
query: normalizeText(`SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS \
|
||||
WHERE CONSTRAINT_SCHEMA = '${dbFullName}' AND TABLE_NAME='${tableName}' AND \
|
||||
CONSTRAINT_TYPE='UNIQUE'`),
|
||||
})) as DSQL_MYSQL_FOREIGN_KEYS_Type[] | null;
|
||||
|
||||
if (allUniqueConstraints) {
|
||||
for (let c = 0; c < allUniqueConstraints.length; c++) {
|
||||
const { CONSTRAINT_NAME } = allUniqueConstraints[c];
|
||||
await dbHandler({
|
||||
query: `ALTER TABLE \`${dbFullName}\`.\`${tableName}\` DROP INDEX \`${CONSTRAINT_NAME}\``,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle MYSQL Columns (Fields)
|
||||
* ===================================================
|
||||
* @description Now handle all fields/columns
|
||||
*/
|
||||
let allExistingColumns: DSQL_MYSQL_SHOW_COLUMNS_Type[] =
|
||||
(await dbHandler({
|
||||
query: `SHOW COLUMNS FROM \`${dbFullName}\`.\`${tableName}\``,
|
||||
})) as DSQL_MYSQL_SHOW_COLUMNS_Type[];
|
||||
|
||||
/**
|
||||
* @type {string[]}
|
||||
* @description Updated column names Array
|
||||
*/
|
||||
const updatedColumnsArray: string[] = [];
|
||||
|
||||
/**
|
||||
* @description Iterate through every existing column
|
||||
*/
|
||||
for (let e = 0; e < allExistingColumns.length; e++) {
|
||||
const { Field } = allExistingColumns[e];
|
||||
|
||||
if (Field.match(defaultFieldsRegexp)) 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);
|
||||
|
||||
await dbHandler({
|
||||
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 = _.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) {
|
||||
writeUpdatedDbSchema({
|
||||
dbSchema: updatedSchemaData,
|
||||
userId,
|
||||
});
|
||||
}
|
||||
|
||||
allExistingColumns = (await dbHandler({
|
||||
query: `SHOW COLUMNS FROM \`${dbFullName}\`.\`${tableName}\``,
|
||||
})) as DSQL_MYSQL_SHOW_COLUMNS_Type[];
|
||||
} catch (error: any) {
|
||||
console.log("Update table error =>", error.message);
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
|
||||
continue;
|
||||
|
||||
////////////////////////////////////////
|
||||
} else {
|
||||
await dbHandler({
|
||||
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 (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,
|
||||
if (tableUniqueConstraints?.[0]) {
|
||||
handleUniqueConstraintsCreateDbFromSchema({
|
||||
dbFullName,
|
||||
tableUniqueConstraints,
|
||||
tableName,
|
||||
});
|
||||
|
||||
/**
|
||||
* @description Modify Column(Field) if it already exists
|
||||
* in MYSQL database
|
||||
*/
|
||||
if (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 = await dbHandler({
|
||||
query: updateTableQuery,
|
||||
});
|
||||
|
||||
/**
|
||||
* # Handle Foreign Keys
|
||||
*/
|
||||
await dropAllForeignKeys({ dbFullName, tableName });
|
||||
|
||||
for (let i = 0; i < upToDateTableFieldsArray.length; i++) {
|
||||
const { fieldName, foreignKey } = upToDateTableFieldsArray[i];
|
||||
if (!clone && foreignKey && fieldName) {
|
||||
await handleTableForeignKey({
|
||||
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: any) {
|
||||
console.log('Error in "updateTable" shell function =>', error.message);
|
||||
|
||||
return tableID;
|
||||
}
|
||||
|
||||
return tableID;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user