datasquirel/package-shared/shell/createDbFromSchema/handle-indexes.ts
Benjamin Toby c37d105dee Updates
2025-07-09 20:30:45 +01:00

66 lines
2.2 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";
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) {
const allExistingIndexes = (await dbHandler({
query: `SHOW INDEXES FROM \`${dbFullName}\`.\`${tableName}\``,
})) as DSQL_MYSQL_SHOW_INDEXES_Type[];
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
);
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" : ""
} INDEX \`${alias}\` ON \`${dbFullName}\`.\`${tableName}\`(${indexTableFields
?.map((nm) => nm.value)
.map((nm) => `\`${nm}\``)
.join(
","
)}) COMMENT '${grabDSQLSchemaIndexComment()} ${indexName}'`;
const addIndex = await dbHandler({ query: queryString });
}
}
const allExistingIndexesAfterUpdate = (await dbHandler({
query: `SHOW INDEXES FROM \`${dbFullName}\`.\`${tableName}\``,
})) as DSQL_MYSQL_SHOW_INDEXES_Type[];
}