Refactor types
This commit is contained in:
@@ -22,7 +22,7 @@ const updateApiSchemaFromLocalDb = require("../query/update-api-schema-from-loca
|
||||
* ==============================================================================
|
||||
*
|
||||
* @param {object} params - Single object passed
|
||||
* @param {import("../../types/database-schema.td").DSQL_DatabaseSchemaType} params.dbSchema - Database Schema Object
|
||||
* @param {import("@/package-shared/types/database-schema.td").DSQL_DatabaseSchemaType | undefined} params.dbSchema - Database Schema Object
|
||||
*
|
||||
* @returns {Promise<*>} new user auth object payload
|
||||
*/
|
||||
@@ -33,7 +33,7 @@ module.exports = async function addUsersTableToDb({ dbSchema }) {
|
||||
* @description Initialize
|
||||
*/
|
||||
const database = process.env.DSQL_DB_NAME || "";
|
||||
/** @type {import("../../types/database-schema.td").DSQL_TableSchemaType} */
|
||||
/** @type {import("@/package-shared/types/database-schema.td").DSQL_TableSchemaType} */
|
||||
const userPreset = require("./data/presets/users.json");
|
||||
|
||||
try {
|
||||
@@ -42,15 +42,22 @@ module.exports = async function addUsersTableToDb({ dbSchema }) {
|
||||
*
|
||||
* @description Fetch user from db
|
||||
*/
|
||||
const userSchemaMainFilePath = path.resolve(process.cwd(), "dsql.schema.json");
|
||||
const userSchemaMainFilePath = path.resolve(
|
||||
process.cwd(),
|
||||
"dsql.schema.json"
|
||||
);
|
||||
let targetDatabase = dbSchema;
|
||||
|
||||
let existingTableIndex = targetDatabase.tables.findIndex((table, index) => {
|
||||
if (table.tableName === "users") {
|
||||
existingTableIndex = index;
|
||||
return true;
|
||||
if (!targetDatabase) throw new Error("Target database not found!");
|
||||
|
||||
let existingTableIndex = targetDatabase.tables.findIndex(
|
||||
(table, index) => {
|
||||
if (table.tableName === "users") {
|
||||
existingTableIndex = index;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
});
|
||||
);
|
||||
|
||||
if (existingTableIndex >= 0) {
|
||||
targetDatabase.tables[existingTableIndex] = userPreset;
|
||||
@@ -58,7 +65,11 @@ module.exports = async function addUsersTableToDb({ dbSchema }) {
|
||||
targetDatabase.tables.push(userPreset);
|
||||
}
|
||||
|
||||
fs.writeFileSync(`${userSchemaMainFilePath}`, JSON.stringify(dbSchema, null, 4), "utf8");
|
||||
fs.writeFileSync(
|
||||
`${userSchemaMainFilePath}`,
|
||||
JSON.stringify(dbSchema, null, 4),
|
||||
"utf8"
|
||||
);
|
||||
|
||||
////////////////////////////////////////
|
||||
|
||||
|
||||
@@ -27,7 +27,7 @@ const updateTable = require("./utils/updateTable");
|
||||
* runs the "dsql create" command. `NOTE`: there must be a "dsql.schema.json" file
|
||||
* in the root of the project for this function to work
|
||||
*
|
||||
* @param {import("../../types/database-schema.td").DSQL_DatabaseSchemaType[]} dbSchema - An array of database schema objects
|
||||
* @param {import("@/package-shared/types/database-schema.td").DSQL_DatabaseSchemaType | undefined} dbSchema - An array of database schema objects
|
||||
*/
|
||||
async function createDbFromSchema(dbSchema) {
|
||||
try {
|
||||
@@ -42,8 +42,13 @@ async function createDbFromSchema(dbSchema) {
|
||||
}
|
||||
|
||||
for (let i = 0; i < dbSchema.length; i++) {
|
||||
/** @type {import("../../types/database-schema.td").DSQL_DatabaseSchemaType} */
|
||||
/** @type {import("@/package-shared/types/database-schema.td").DSQL_DatabaseSchemaType | undefined} */
|
||||
const database = dbSchema[i];
|
||||
|
||||
if (!database) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const { dbFullName, tables } = database;
|
||||
|
||||
////////////////////////////////////////
|
||||
@@ -51,12 +56,16 @@ async function createDbFromSchema(dbSchema) {
|
||||
////////////////////////////////////////
|
||||
|
||||
/** @type {{ dbFullName: string }[] | null} */
|
||||
const dbCheck = await noDatabaseDbHandler({ query: `SELECT SCHEMA_NAME AS dbFullName FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '${dbFullName}'` });
|
||||
const dbCheck = await noDatabaseDbHandler({
|
||||
query: `SELECT SCHEMA_NAME AS dbFullName FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '${dbFullName}'`,
|
||||
});
|
||||
|
||||
if (dbCheck && dbCheck[0]?.dbFullName) {
|
||||
// Database Exists
|
||||
} else {
|
||||
const newDatabase = await noDatabaseDbHandler({ query: `CREATE DATABASE IF NOT EXISTS \`${dbFullName}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_bin` });
|
||||
const newDatabase = await noDatabaseDbHandler({
|
||||
query: `CREATE DATABASE IF NOT EXISTS \`${dbFullName}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_bin`,
|
||||
});
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
@@ -68,7 +77,9 @@ async function createDbFromSchema(dbSchema) {
|
||||
* @type {{ TABLE_NAME: string }[] | null}
|
||||
* @description Select All tables in target database
|
||||
*/
|
||||
const allTables = await noDatabaseDbHandler({ query: `SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA='${dbFullName}'` });
|
||||
const allTables = await noDatabaseDbHandler({
|
||||
query: `SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA='${dbFullName}'`,
|
||||
});
|
||||
|
||||
let tableDropped;
|
||||
|
||||
@@ -85,8 +96,16 @@ async function createDbFromSchema(dbSchema) {
|
||||
* in the user schema JSON. If it's not, the table is either deleted
|
||||
* or the table name has been recently changed
|
||||
*/
|
||||
if (!tables.filter((_table) => _table.tableName === TABLE_NAME)[0]) {
|
||||
const oldTableFilteredArray = tables.filter((_table) => _table.tableNameOld && _table.tableNameOld === TABLE_NAME);
|
||||
if (
|
||||
!tables.filter(
|
||||
(_table) => _table.tableName === TABLE_NAME
|
||||
)[0]
|
||||
) {
|
||||
const oldTableFilteredArray = tables.filter(
|
||||
(_table) =>
|
||||
_table.tableNameOld &&
|
||||
_table.tableNameOld === TABLE_NAME
|
||||
);
|
||||
|
||||
/**
|
||||
* @description Check if this table has been recently renamed. Rename
|
||||
@@ -159,7 +178,11 @@ async function createDbFromSchema(dbSchema) {
|
||||
});
|
||||
|
||||
if (table.childrenTables && table.childrenTables[0]) {
|
||||
for (let ch = 0; ch < table.childrenTables.length; ch++) {
|
||||
for (
|
||||
let ch = 0;
|
||||
ch < table.childrenTables.length;
|
||||
ch++
|
||||
) {
|
||||
const childTable = table.childrenTables[ch];
|
||||
|
||||
const updateExistingChildTable = await updateTable({
|
||||
@@ -199,7 +222,12 @@ async function createDbFromSchema(dbSchema) {
|
||||
*/
|
||||
if (indexes && indexes[0]) {
|
||||
for (let g = 0; g < indexes.length; g++) {
|
||||
const { indexType, indexName, indexTableFields, alias } = indexes[g];
|
||||
const {
|
||||
indexType,
|
||||
indexName,
|
||||
indexTableFields,
|
||||
alias,
|
||||
} = indexes[g];
|
||||
|
||||
if (!alias?.match(/./)) continue;
|
||||
|
||||
@@ -207,27 +235,42 @@ async function createDbFromSchema(dbSchema) {
|
||||
* @type {any[] | null}
|
||||
* @description All indexes from MYSQL db
|
||||
*/
|
||||
const allExistingIndexes = await varDatabaseDbHandler({
|
||||
queryString: `SHOW INDEXES FROM \`${tableName}\``,
|
||||
database: dbFullName,
|
||||
});
|
||||
const allExistingIndexes =
|
||||
await varDatabaseDbHandler({
|
||||
queryString: `SHOW INDEXES FROM \`${tableName}\``,
|
||||
database: dbFullName,
|
||||
});
|
||||
|
||||
/**
|
||||
* @description Check for existing Index in MYSQL db
|
||||
*/
|
||||
try {
|
||||
const existingKeyInDb = allExistingIndexes ? allExistingIndexes.filter((indexObject) => indexObject.Key_name === alias) : null;
|
||||
if (!existingKeyInDb?.[0]) throw new Error("This Index Does not Exist");
|
||||
const existingKeyInDb = allExistingIndexes
|
||||
? allExistingIndexes.filter(
|
||||
(indexObject) =>
|
||||
indexObject.Key_name === alias
|
||||
)
|
||||
: null;
|
||||
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
|
||||
*/
|
||||
await varDatabaseDbHandler({
|
||||
queryString: `CREATE${indexType.match(/fullText/i) ? " FULLTEXT" : ""} INDEX \`${alias}\` ON ${tableName}(${indexTableFields
|
||||
queryString: `CREATE${
|
||||
indexType.match(/fullText/i)
|
||||
? " FULLTEXT"
|
||||
: ""
|
||||
} INDEX \`${alias}\` ON ${tableName}(${indexTableFields
|
||||
.map((nm) => nm.value)
|
||||
.map((nm) => `\`${nm}\``)
|
||||
.join(",")}) COMMENT 'schema_index'`,
|
||||
.join(
|
||||
","
|
||||
)}) COMMENT 'schema_index'`,
|
||||
database: dbFullName,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -10,7 +10,23 @@ const supplementTable = require("./supplementTable");
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
module.exports = async function createTable({ dbFullName, tableName, tableInfoArray, varDatabaseDbHandler, dbSchema }) {
|
||||
/**
|
||||
*
|
||||
* @param {object} param0
|
||||
* @param {string} param0.dbFullName
|
||||
* @param {string} param0.tableName
|
||||
* @param {any[]} param0.tableInfoArray
|
||||
* @param {(params: import("./varDatabaseDbHandler").VarDbHandlerParam)=>any} param0.varDatabaseDbHandler
|
||||
* @param {import("@/package-shared/types/database-schema.td").DSQL_DatabaseSchemaType} [param0.dbSchema]
|
||||
* @returns
|
||||
*/
|
||||
module.exports = async function createTable({
|
||||
dbFullName,
|
||||
tableName,
|
||||
tableInfoArray,
|
||||
varDatabaseDbHandler,
|
||||
dbSchema,
|
||||
}) {
|
||||
/**
|
||||
* Format tableInfoArray
|
||||
*
|
||||
@@ -36,7 +52,7 @@ module.exports = async function createTable({ dbFullName, tableName, tableInfoAr
|
||||
|
||||
for (let i = 0; i < finalTable.length; i++) {
|
||||
const column = finalTable[i];
|
||||
const { fieldName, dataType, nullValue, primaryKey, autoIncrement, defaultValue, defaultValueLiteral, foreignKey, updatedField } = column;
|
||||
const { fieldName, foreignKey } = column;
|
||||
|
||||
if (foreignKey) {
|
||||
foreignKeys.push({
|
||||
@@ -45,7 +61,10 @@ module.exports = async function createTable({ dbFullName, tableName, tableInfoAr
|
||||
});
|
||||
}
|
||||
|
||||
let { fieldEntryText, newPrimaryKeySet } = generateColumnDescription({ columnData: column, primaryKeySet: primaryKeySet });
|
||||
let { fieldEntryText, newPrimaryKeySet } = generateColumnDescription({
|
||||
columnData: column,
|
||||
primaryKeySet: primaryKeySet,
|
||||
});
|
||||
|
||||
primaryKeySet = newPrimaryKeySet;
|
||||
|
||||
@@ -74,20 +93,33 @@ module.exports = async function createTable({ dbFullName, tableName, tableInfoAr
|
||||
|
||||
if (foreignKeys[0]) {
|
||||
foreignKeys.forEach((foreighKey, index, array) => {
|
||||
const { fieldName, destinationTableName, destinationTableColumnName, cascadeDelete, cascadeUpdate, foreignKeyName } = foreighKey;
|
||||
const {
|
||||
fieldName,
|
||||
destinationTableName,
|
||||
destinationTableColumnName,
|
||||
cascadeDelete,
|
||||
cascadeUpdate,
|
||||
foreignKeyName,
|
||||
} = foreighKey;
|
||||
|
||||
const comma = (() => {
|
||||
if (index === foreignKeys.length - 1) return "";
|
||||
return ",";
|
||||
})();
|
||||
|
||||
createTableQueryArray.push(` CONSTRAINT \`${foreignKeyName}\` FOREIGN KEY (\`${fieldName}\`) REFERENCES \`${destinationTableName}\`(${destinationTableColumnName})${cascadeDelete ? " ON DELETE CASCADE" : ""}${cascadeUpdate ? " ON UPDATE CASCADE" : ""}${comma}`);
|
||||
createTableQueryArray.push(
|
||||
` CONSTRAINT \`${foreignKeyName}\` FOREIGN KEY (\`${fieldName}\`) REFERENCES \`${destinationTableName}\`(${destinationTableColumnName})${
|
||||
cascadeDelete ? " ON DELETE CASCADE" : ""
|
||||
}${cascadeUpdate ? " ON UPDATE CASCADE" : ""}${comma}`
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
|
||||
createTableQueryArray.push(`) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;`);
|
||||
createTableQueryArray.push(
|
||||
`) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;`
|
||||
);
|
||||
|
||||
const createTableQuery = createTableQueryArray.join("\n");
|
||||
|
||||
|
||||
@@ -65,7 +65,7 @@ const connection = mysql.createConnection({
|
||||
* @param {object} params - Single Param object containing params
|
||||
* @param {string} params.query - Query String
|
||||
* @param {(string | number)[]} [params.values] - Values
|
||||
* @param {import("../../../types/database-schema.td").DSQL_DatabaseSchemaType} [params.dbSchema] - Database Schema
|
||||
* @param {import("../../../package-shared/types/database-schema.td").DSQL_DatabaseSchemaType} [params.dbSchema] - Database Schema
|
||||
* @param {string} [params.database] - Target Database
|
||||
* @param {string} [params.tableName] - Target Table Name
|
||||
*
|
||||
|
||||
@@ -11,18 +11,30 @@
|
||||
* Generate SQL text for Field
|
||||
* ==============================================================================
|
||||
* @param {object} params - Single object params
|
||||
* @param {import("../../../types/database-schema.td").DSQL_FieldSchemaType} params.columnData - Field object
|
||||
* @param {import("@/package-shared/types/database-schema.td").DSQL_FieldSchemaType} params.columnData - Field object
|
||||
* @param {boolean} [params.primaryKeySet] - Table Name(slug)
|
||||
*
|
||||
* @returns {{fieldEntryText: string, newPrimaryKeySet: boolean}}
|
||||
*/
|
||||
module.exports = function generateColumnDescription({ columnData, primaryKeySet }) {
|
||||
module.exports = function generateColumnDescription({
|
||||
columnData,
|
||||
primaryKeySet,
|
||||
}) {
|
||||
/**
|
||||
* Format tableInfoArray
|
||||
*
|
||||
* @description Format tableInfoArray
|
||||
*/
|
||||
const { fieldName, dataType, nullValue, primaryKey, autoIncrement, defaultValue, defaultValueLiteral, notNullValue } = columnData;
|
||||
const {
|
||||
fieldName,
|
||||
dataType,
|
||||
nullValue,
|
||||
primaryKey,
|
||||
autoIncrement,
|
||||
defaultValue,
|
||||
defaultValueLiteral,
|
||||
notNullValue,
|
||||
} = columnData;
|
||||
|
||||
let fieldEntryText = "";
|
||||
|
||||
|
||||
@@ -27,7 +27,7 @@ const connection = mysql.createConnection({
|
||||
* @param {string} params.query - Query String
|
||||
* @param {string[]} [params.values] - Values
|
||||
*
|
||||
* @returns {Promise<object[] | null>}
|
||||
* @returns {Promise<any[] | null>}
|
||||
*/
|
||||
module.exports = async function noDatabaseDbHandler({ query, values }) {
|
||||
/**
|
||||
|
||||
@@ -14,10 +14,13 @@ const defaultFieldsRegexp = require("./defaultFieldsRegexp");
|
||||
* @param {object} params - Single object params
|
||||
* @param {*[]} params.unparsedResults - Array of data objects containing Fields(keys)
|
||||
* and corresponding values of the fields(values)
|
||||
* @param {import("../../../types/database-schema.td").DSQL_TableSchemaType} [params.tableSchema] - Table schema
|
||||
* @param {import("../../../package-shared/types/database-schema.td").DSQL_TableSchemaType} [params.tableSchema] - Table schema
|
||||
* @returns {Promise<object[]|null>}
|
||||
*/
|
||||
module.exports = async function parseDbResults({ unparsedResults, tableSchema }) {
|
||||
module.exports = async function parseDbResults({
|
||||
unparsedResults,
|
||||
tableSchema,
|
||||
}) {
|
||||
/**
|
||||
* Declare variables
|
||||
*
|
||||
@@ -56,7 +59,11 @@ module.exports = async function parseDbResults({ unparsedResults, tableSchema })
|
||||
}
|
||||
|
||||
if (resultFieldSchema?.encrypted && value?.match(/./)) {
|
||||
result[resultFieldName] = decrypt({ encryptedString: value, encryptionKey, encryptionSalt });
|
||||
result[resultFieldName] = decrypt({
|
||||
encryptedString: value,
|
||||
encryptionKey,
|
||||
encryptionSalt,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,10 +1,17 @@
|
||||
// @ts-check
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {string} text
|
||||
* @returns
|
||||
*/
|
||||
module.exports = function slugToCamelTitle(text) {
|
||||
if (text) {
|
||||
let addArray = text.split("-").filter((item) => item !== "");
|
||||
let camelArray = addArray.map((item) => {
|
||||
return item.substr(0, 1).toUpperCase() + item.substr(1).toLowerCase();
|
||||
return (
|
||||
item.substr(0, 1).toUpperCase() + item.substr(1).toLowerCase()
|
||||
);
|
||||
});
|
||||
|
||||
let parsedAddress = camelArray.join(" ");
|
||||
|
||||
@@ -7,6 +7,12 @@
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {object} param0
|
||||
* @param {import("@/package-shared/types/database-schema.td").DSQL_FieldSchemaType[]} param0.tableInfoArray
|
||||
* @returns
|
||||
*/
|
||||
module.exports = function supplementTable({ tableInfoArray }) {
|
||||
/**
|
||||
* Format tableInfoArray
|
||||
@@ -18,12 +24,16 @@ module.exports = function supplementTable({ tableInfoArray }) {
|
||||
|
||||
////////////////////////////////////////
|
||||
|
||||
let primaryKeyExists = finalTableArray.filter((_field) => _field.primaryKey);
|
||||
let primaryKeyExists = finalTableArray.filter(
|
||||
(_field) => _field.primaryKey
|
||||
);
|
||||
|
||||
////////////////////////////////////////
|
||||
|
||||
defaultFields.forEach((field) => {
|
||||
let fieldExists = finalTableArray.filter((_field) => _field.fieldName === field.fieldName);
|
||||
let fieldExists = finalTableArray.filter(
|
||||
(_field) => _field.fieldName === field.fieldName
|
||||
);
|
||||
|
||||
if (fieldExists && fieldExists[0]) {
|
||||
return;
|
||||
|
||||
@@ -10,7 +10,8 @@
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
|
||||
const defaultFieldsRegexp = /^id$|^date_created$|^date_created_code$|^date_created_timestamp$|^date_updated$|^date_updated_code$|^date_updated_timestamp$/;
|
||||
const defaultFieldsRegexp =
|
||||
/^id$|^date_created$|^date_created_code$|^date_created_timestamp$|^date_updated$|^date_updated_code$|^date_updated_timestamp$/;
|
||||
|
||||
const generateColumnDescription = require("./generateColumnDescription");
|
||||
const varDatabaseDbHandler = require("./varDatabaseDbHandler");
|
||||
@@ -30,15 +31,23 @@ const schemaPath = path.resolve(process.cwd(), "dsql.schema.json");
|
||||
* @param {object} params - Single object params
|
||||
* @param {string} params.dbFullName - Database full name => "datasquirel_user_4394_db_name"
|
||||
* @param {string} params.tableName - Table Name(slug)
|
||||
* @param {import("../../../types/database-schema.td").DSQL_FieldSchemaType[]} params.tableInfoArray - Table Info Array
|
||||
* @param {import("../../../types/database-schema.td").DSQL_DatabaseSchemaType[]} params.dbSchema - Single post
|
||||
* @param {import("../../../types/database-schema.td").DSQL_IndexSchemaType[]} [params.tableIndexes] - Table Indexes
|
||||
* @param {import("@/package-shared/types/database-schema.td").DSQL_FieldSchemaType[]} params.tableInfoArray - Table Info Array
|
||||
* @param {import("@/package-shared/types/database-schema.td").DSQL_DatabaseSchemaType[]} params.dbSchema - Single post
|
||||
* @param {import("@/package-shared/types/database-schema.td").DSQL_IndexSchemaType[]} [params.tableIndexes] - Table Indexes
|
||||
* @param {boolean} [params.clone] - Is this a newly cloned table?
|
||||
* @param {number} [params.tableIndex] - The number index of the table in the dbSchema array
|
||||
*
|
||||
* @returns {Promise<string|object[]|null>}
|
||||
*/
|
||||
module.exports = async function updateTable({ dbFullName, tableName, tableInfoArray, dbSchema, tableIndexes, clone, tableIndex }) {
|
||||
module.exports = async function updateTable({
|
||||
dbFullName,
|
||||
tableName,
|
||||
tableInfoArray,
|
||||
dbSchema,
|
||||
tableIndexes,
|
||||
clone,
|
||||
tableIndex,
|
||||
}) {
|
||||
/**
|
||||
* Initialize
|
||||
* ==========================================
|
||||
@@ -79,7 +88,7 @@ module.exports = async function updateTable({ dbFullName, tableName, tableInfoAr
|
||||
////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* @type {*}
|
||||
* @type {DSQL_MYSQL_SHOW_INDEXES_Type[]}
|
||||
* @description All indexes from MYSQL db
|
||||
*/
|
||||
const allExistingIndexes = await varDatabaseDbHandler({
|
||||
@@ -88,7 +97,7 @@ module.exports = async function updateTable({ dbFullName, tableName, tableInfoAr
|
||||
});
|
||||
|
||||
/**
|
||||
* @type {*}
|
||||
* @type {DSQL_MYSQL_SHOW_COLUMNS_Type[]}
|
||||
* @description All columns from MYSQL db
|
||||
*/
|
||||
const allExistingColumns = await varDatabaseDbHandler({
|
||||
@@ -121,7 +130,11 @@ module.exports = async function updateTable({ dbFullName, tableName, tableInfoAr
|
||||
* @description This finds out whether the fieldName corresponds with the MSQL Field name
|
||||
* if the fildName doesn't match any MYSQL Field name, the field is deleted.
|
||||
*/
|
||||
let existingEntry = upToDateTableFieldsArray.filter((column) => column.fieldName === Field || column.originName === Field);
|
||||
let existingEntry = upToDateTableFieldsArray.filter(
|
||||
(column) =>
|
||||
column.fieldName === Field ||
|
||||
column.originName === Field
|
||||
);
|
||||
|
||||
if (existingEntry && existingEntry[0]) {
|
||||
/**
|
||||
@@ -135,7 +148,9 @@ module.exports = async function updateTable({ dbFullName, tableName, tableInfoAr
|
||||
database: dbFullName,
|
||||
});
|
||||
|
||||
console.log(`Column Renamed from "${existingEntry[0].originName}" to "${existingEntry[0].fieldName}"`);
|
||||
console.log(
|
||||
`Column Renamed from "${existingEntry[0].originName}" to "${existingEntry[0].fieldName}"`
|
||||
);
|
||||
|
||||
/**
|
||||
* Update Db Schema
|
||||
@@ -145,21 +160,47 @@ module.exports = async function updateTable({ dbFullName, tableName, tableInfoAr
|
||||
try {
|
||||
const userSchemaData = dbSchema;
|
||||
|
||||
const targetDbIndex = userSchemaData.findIndex((db) => db.dbFullName === dbFullName);
|
||||
const targetTableIndex = userSchemaData[targetDbIndex].tables.findIndex((table) => table.tableName === tableName);
|
||||
const targetFieldIndex = userSchemaData[targetDbIndex].tables[targetTableIndex].fields.findIndex((field) => field.fieldName === existingEntry[0].fieldName);
|
||||
const targetDbIndex = userSchemaData.findIndex(
|
||||
(db) => db.dbFullName === dbFullName
|
||||
);
|
||||
const targetTableIndex = userSchemaData[
|
||||
targetDbIndex
|
||||
].tables.findIndex(
|
||||
(table) => table.tableName === tableName
|
||||
);
|
||||
const targetFieldIndex = userSchemaData[
|
||||
targetDbIndex
|
||||
].tables[targetTableIndex].fields.findIndex(
|
||||
(field) =>
|
||||
field.fieldName ===
|
||||
existingEntry[0].fieldName
|
||||
);
|
||||
|
||||
delete userSchemaData[targetDbIndex].tables[targetTableIndex].fields[targetFieldIndex]["originName"];
|
||||
delete userSchemaData[targetDbIndex].tables[targetTableIndex].fields[targetFieldIndex]["updatedField"];
|
||||
delete userSchemaData[targetDbIndex].tables[
|
||||
targetTableIndex
|
||||
].fields[targetFieldIndex]["originName"];
|
||||
delete userSchemaData[targetDbIndex].tables[
|
||||
targetTableIndex
|
||||
].fields[targetFieldIndex]["updatedField"];
|
||||
|
||||
/**
|
||||
* @description Set New Table Fields Array
|
||||
*/
|
||||
upToDateTableFieldsArray = userSchemaData[targetDbIndex].tables[targetTableIndex].fields;
|
||||
upToDateTableFieldsArray =
|
||||
userSchemaData[targetDbIndex].tables[
|
||||
targetTableIndex
|
||||
].fields;
|
||||
|
||||
fs.writeFileSync(schemaPath, JSON.stringify(userSchemaData), "utf8");
|
||||
fs.writeFileSync(
|
||||
schemaPath,
|
||||
JSON.stringify(userSchemaData),
|
||||
"utf8"
|
||||
);
|
||||
} catch (/** @type {*} */ error) {
|
||||
console.log("Error in updating Table =>", error.message);
|
||||
console.log(
|
||||
"Error in updating Table =>",
|
||||
error.message
|
||||
);
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
@@ -199,8 +240,16 @@ module.exports = async function updateTable({ dbFullName, tableName, tableInfoAr
|
||||
*/
|
||||
if (Index_comment?.match(/schema_index/)) {
|
||||
try {
|
||||
const existingKeyInSchema = tableIndexes ? tableIndexes.filter((indexObject) => indexObject.alias === Key_name) : null;
|
||||
if (!existingKeyInSchema?.[0]) throw new Error(`This Index(${Key_name}) Has been Deleted!`);
|
||||
const existingKeyInSchema = tableIndexes
|
||||
? tableIndexes.filter(
|
||||
(indexObject) =>
|
||||
indexObject.alias === Key_name
|
||||
)
|
||||
: null;
|
||||
if (!existingKeyInSchema?.[0])
|
||||
throw new Error(
|
||||
`This Index(${Key_name}) Has been Deleted!`
|
||||
);
|
||||
} catch (error) {
|
||||
/**
|
||||
* @description Drop Index: This happens when the MYSQL index is not
|
||||
@@ -222,7 +271,8 @@ module.exports = async function updateTable({ dbFullName, tableName, tableInfoAr
|
||||
*/
|
||||
if (tableIndexes && tableIndexes[0]) {
|
||||
for (let g = 0; g < tableIndexes.length; g++) {
|
||||
const { indexType, indexName, indexTableFields, alias } = tableIndexes[g];
|
||||
const { indexType, indexName, indexTableFields, alias } =
|
||||
tableIndexes[g];
|
||||
|
||||
if (!alias?.match(/./)) continue;
|
||||
|
||||
@@ -230,15 +280,21 @@ module.exports = async function updateTable({ dbFullName, tableName, tableInfoAr
|
||||
* @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");
|
||||
const existingKeyInDb = allExistingIndexes?.filter(
|
||||
(/** @type {any} */ 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
|
||||
*/
|
||||
await varDatabaseDbHandler({
|
||||
queryString: `CREATE${indexType.match(/fullText/i) ? " FULLTEXT" : ""} INDEX \`${alias}\` ON ${tableName}(${indexTableFields
|
||||
queryString: `CREATE${
|
||||
indexType.match(/fullText/i) ? " FULLTEXT" : ""
|
||||
} INDEX \`${alias}\` ON ${tableName}(${indexTableFields
|
||||
.map((nm) => nm.value)
|
||||
.map((nm) => `\`${nm}\``)
|
||||
.join(",")}) COMMENT 'schema_index'`,
|
||||
@@ -302,7 +358,17 @@ module.exports = async function updateTable({ dbFullName, tableName, tableInfoAr
|
||||
const prevColumn = upToDateTableFieldsArray[i - 1];
|
||||
const nextColumn = upToDateTableFieldsArray[i + 1];
|
||||
|
||||
const { fieldName, dataType, nullValue, primaryKey, autoIncrement, defaultValue, defaultValueLiteral, foreignKey, updatedField } = column;
|
||||
const {
|
||||
fieldName,
|
||||
dataType,
|
||||
nullValue,
|
||||
primaryKey,
|
||||
autoIncrement,
|
||||
defaultValue,
|
||||
defaultValueLiteral,
|
||||
foreignKey,
|
||||
updatedField,
|
||||
} = column;
|
||||
|
||||
////////////////////////////////////////
|
||||
|
||||
@@ -339,22 +405,37 @@ module.exports = async function updateTable({ dbFullName, tableName, tableInfoAr
|
||||
/**
|
||||
* @description Construct SQL text snippet for this field
|
||||
*/
|
||||
let { fieldEntryText } = generateColumnDescription({ columnData: column });
|
||||
let { fieldEntryText } = generateColumnDescription({
|
||||
columnData: column,
|
||||
});
|
||||
|
||||
/**
|
||||
* @description Modify Column(Field) if it already exists
|
||||
* in MYSQL database
|
||||
*/
|
||||
if (existingColumn && existingColumn[0]?.Field) {
|
||||
const { Field, Type, Null, Key, Default, Extra } = existingColumn[0];
|
||||
const { Field, Type, Null, Key, Default, Extra } =
|
||||
existingColumn[0];
|
||||
|
||||
let isColumnReordered = existingColumnIndex ? i < existingColumnIndex : false;
|
||||
let isColumnReordered = existingColumnIndex
|
||||
? i < existingColumnIndex
|
||||
: false;
|
||||
|
||||
if (Field === fieldName && !isColumnReordered && dataType.toUpperCase() === Type.toUpperCase()) {
|
||||
if (
|
||||
Field === fieldName &&
|
||||
!isColumnReordered &&
|
||||
dataType.toUpperCase() === Type.toUpperCase()
|
||||
) {
|
||||
updateText += `MODIFY COLUMN ${fieldEntryText}`;
|
||||
// continue;
|
||||
} else {
|
||||
updateText += `MODIFY COLUMN ${fieldEntryText}${isColumnReordered ? (prevColumn?.fieldName ? " AFTER `" + prevColumn.fieldName + "`" : " AFTER `id`") : ""}`;
|
||||
updateText += `MODIFY COLUMN ${fieldEntryText}${
|
||||
isColumnReordered
|
||||
? prevColumn?.fieldName
|
||||
? " AFTER `" + prevColumn.fieldName + "`"
|
||||
: " AFTER `id`"
|
||||
: ""
|
||||
}`;
|
||||
// if (userId) {
|
||||
// } else {
|
||||
// updateText += `MODIFY COLUMN ${fieldEntryText}`;
|
||||
@@ -396,9 +477,17 @@ module.exports = async function updateTable({ dbFullName, tableName, tableInfoAr
|
||||
* "clone" boolean = true
|
||||
*/
|
||||
if (!clone && foreignKey) {
|
||||
const { destinationTableName, destinationTableColumnName, cascadeDelete, cascadeUpdate, foreignKeyName } = foreignKey;
|
||||
const {
|
||||
destinationTableName,
|
||||
destinationTableColumnName,
|
||||
cascadeDelete,
|
||||
cascadeUpdate,
|
||||
foreignKeyName,
|
||||
} = foreignKey;
|
||||
|
||||
const foreinKeyText = `ADD CONSTRAINT \`${foreignKeyName}\` FOREIGN KEY (${fieldName}) REFERENCES ${destinationTableName}(${destinationTableColumnName})${cascadeDelete ? " ON DELETE CASCADE" : ""}${cascadeUpdate ? " ON UPDATE CASCADE" : ""}`;
|
||||
const foreinKeyText = `ADD CONSTRAINT \`${foreignKeyName}\` FOREIGN KEY (${fieldName}) REFERENCES ${destinationTableName}(${destinationTableColumnName})${
|
||||
cascadeDelete ? " ON DELETE CASCADE" : ""
|
||||
}${cascadeUpdate ? " ON UPDATE CASCADE" : ""}`;
|
||||
// const foreinKeyText = `ADD CONSTRAINT \`${foreignKeyName}\` FOREIGN KEY (${fieldName}) REFERENCES ${destinationTableName}(${destinationTableColumnName})${cascadeDelete ? " ON DELETE CASCADE" : ""}${cascadeUpdate ? " ON UPDATE CASCADE" : ""}` + ",";
|
||||
|
||||
const finalQueryString = `ALTER TABLE \`${tableName}\` ${foreinKeyText}`;
|
||||
@@ -416,7 +505,9 @@ module.exports = async function updateTable({ dbFullName, tableName, tableInfoAr
|
||||
* @description Construct final SQL query by combning all SQL snippets in
|
||||
* updateTableQueryArray Arry, and trimming the final comma(,)
|
||||
*/
|
||||
const updateTableQuery = updateTableQueryArray.join(" ").replace(/,$/, "");
|
||||
const updateTableQuery = updateTableQueryArray
|
||||
.join(" ")
|
||||
.replace(/,$/, "");
|
||||
|
||||
////////////////////////////////////////
|
||||
|
||||
|
||||
@@ -19,18 +19,27 @@ const fs = require("fs");
|
||||
const parseDbResults = require("./parseDbResults");
|
||||
const dbHandler = require("./dbHandler");
|
||||
|
||||
/**
|
||||
* @typedef {object} VarDbHandlerParam
|
||||
* @property {string} queryString - SQL string
|
||||
* @property {string[]} [queryValuesArray] - Values Array
|
||||
* @property {string} database - Database name
|
||||
* @property {import("@/package-shared/types/database-schema.td").DSQL_TableSchemaType} [tableSchema] - Table schema
|
||||
*/
|
||||
|
||||
/**
|
||||
* DB handler for specific database
|
||||
* ==============================================================================
|
||||
* @async
|
||||
* @param {object} params - Single object params
|
||||
* @param {string} params.queryString - SQL string
|
||||
* @param {string[]} [params.queryValuesArray] - Values Array
|
||||
* @param {string} params.database - Database name
|
||||
* @param {import("../../../types/database-schema.td").DSQL_TableSchemaType} [params.tableSchema] - Table schema
|
||||
* @returns {Promise<*>}
|
||||
* @param {VarDbHandlerParam} params
|
||||
* @returns {Promise<any>}
|
||||
*/
|
||||
module.exports = async function varDatabaseDbHandler({ queryString, queryValuesArray, database, tableSchema }) {
|
||||
module.exports = async function varDatabaseDbHandler({
|
||||
queryString,
|
||||
queryValuesArray,
|
||||
database,
|
||||
tableSchema,
|
||||
}) {
|
||||
/**
|
||||
* Create Connection
|
||||
*
|
||||
@@ -54,17 +63,32 @@ module.exports = async function varDatabaseDbHandler({ queryString, queryValuesA
|
||||
* @description Fetch data from db if no cache
|
||||
*/
|
||||
try {
|
||||
if (queryString && Array.isArray(queryValuesArray) && queryValuesArray[0]) {
|
||||
results = await dbHandler({ query: queryString, values: queryValuesArray, database: database });
|
||||
if (
|
||||
queryString &&
|
||||
Array.isArray(queryValuesArray) &&
|
||||
queryValuesArray[0]
|
||||
) {
|
||||
results = await dbHandler({
|
||||
query: queryString,
|
||||
values: queryValuesArray,
|
||||
database: database,
|
||||
});
|
||||
} else if (queryString && !Array.isArray(queryValuesArray)) {
|
||||
results = await dbHandler({ query: queryString, database: database });
|
||||
results = await dbHandler({
|
||||
query: queryString,
|
||||
database: database,
|
||||
});
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
} catch (error) {
|
||||
console.log("\x1b[31mvarDatabaseDbHandler ERROR\x1b[0m =>", database, error);
|
||||
console.log(
|
||||
"\x1b[31mvarDatabaseDbHandler ERROR\x1b[0m =>",
|
||||
database,
|
||||
error
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -76,10 +100,17 @@ module.exports = async function varDatabaseDbHandler({ queryString, queryValuesA
|
||||
try {
|
||||
const unparsedResults = results;
|
||||
// deepcode ignore reDOS: <please specify a reason of ignoring this>
|
||||
const parsedResults = await parseDbResults({ unparsedResults: unparsedResults, tableSchema: tableSchema });
|
||||
const parsedResults = await parseDbResults({
|
||||
unparsedResults: unparsedResults,
|
||||
tableSchema: tableSchema,
|
||||
});
|
||||
return parsedResults;
|
||||
} catch (error) {
|
||||
console.log("\x1b[31mvarDatabaseDbHandler ERROR\x1b[0m =>", database, error);
|
||||
console.log(
|
||||
"\x1b[31mvarDatabaseDbHandler ERROR\x1b[0m =>",
|
||||
database,
|
||||
error
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user