68 lines
2.3 KiB
TypeScript
68 lines
2.3 KiB
TypeScript
import varDatabaseDbHandler from "../utils/varDatabaseDbHandler";
|
|
import {
|
|
DSQL_IndexSchemaType,
|
|
DSQL_MYSQL_SHOW_INDEXES_Type,
|
|
} from "../../types";
|
|
import grabDSQLSchemaIndexComment from "../utils/grab-dsql-schema-index-comment";
|
|
|
|
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: DSQL_MYSQL_SHOW_INDEXES_Type[] =
|
|
await varDatabaseDbHandler({
|
|
queryString: `SHOW INDEXES FROM \`${dbFullName}\`.\`${tableName}\``,
|
|
});
|
|
|
|
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 varDatabaseDbHandler({ queryString });
|
|
}
|
|
}
|
|
|
|
const allExistingIndexesAfterUpdate: DSQL_MYSQL_SHOW_INDEXES_Type[] =
|
|
await varDatabaseDbHandler({
|
|
queryString: `SHOW INDEXES FROM \`${dbFullName}\`.\`${tableName}\``,
|
|
});
|
|
}
|