datasquirel/package-shared/shell/createDbFromSchema/handle-indexes.ts
2026-01-03 05:34:24 +01:00

82 lines
2.8 KiB
TypeScript

import {
DSQL_IndexSchemaType,
DSQL_MYSQL_SHOW_INDEXES_Type,
} 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;
dbFullName: string;
indexes: DSQL_IndexSchemaType[];
};
/**
* Handle DATASQUIREL Table Indexes
* ===================================================
* @description Iterate through each datasquirel schema
* table index(if available), and perform operations
*/
export default async function handleIndexescreateDbFromSchema({
dbFullName,
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}\` 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;
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}'`;
const addIndex = await dbHandler({ query: queryString });
}
}