datasquirel/package-shared/shell/createDbFromSchema/handle-unique-constraints.ts
2026-02-19 04:52:04 +01:00

50 lines
1.6 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) {
/**
* # 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 });
}
}