81 lines
2.9 KiB
TypeScript
81 lines
2.9 KiB
TypeScript
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 });
|
|
}
|
|
}
|