This commit is contained in:
Benjamin Toby
2025-01-10 20:35:05 +01:00
parent 9192dae0b5
commit a3561da53d
286 changed files with 13862 additions and 42590 deletions
@@ -0,0 +1,7 @@
/**
* Convert Camel Joined Text to Camel Spaced Text
* ==============================================================================
* @description this function takes a camel cased text without spaces, and returns
* a camel-case-spaced text
*/
export default function camelJoinedtoCamelSpace(text: string): string | null;
@@ -0,0 +1,44 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = camelJoinedtoCamelSpace;
/**
* Convert Camel Joined Text to Camel Spaced Text
* ==============================================================================
* @description this function takes a camel cased text without spaces, and returns
* a camel-case-spaced text
*/
function camelJoinedtoCamelSpace(text) {
if (!(text === null || text === void 0 ? void 0 : text.match(/./))) {
return "";
}
if (text === null || text === void 0 ? void 0 : text.match(/ /)) {
return text;
}
if (text) {
let textArray = text.split("");
let capIndexes = [];
for (let i = 0; i < textArray.length; i++) {
const char = textArray[i];
if (i === 0)
continue;
if (char.match(/[A-Z]/)) {
capIndexes.push(i);
}
}
let textChunks = [
`${textArray[0].toUpperCase()}${text.substring(1, capIndexes[0])}`,
];
for (let j = 0; j < capIndexes.length; j++) {
const capIndex = capIndexes[j];
if (capIndex === 0)
continue;
const startIndex = capIndex + 1;
const endIndex = capIndexes[j + 1];
textChunks.push(`${textArray[capIndex].toUpperCase()}${text.substring(startIndex, endIndex)}`);
}
return textChunks.join(" ");
}
else {
return null;
}
}
+20
View File
@@ -0,0 +1,20 @@
import { DSQL_DatabaseSchemaType, DSQL_TableSchemaType } from "../../types";
type Param = {
dbFullName: string;
tableName: string;
tableInfoArray: any[];
dbSchema?: DSQL_DatabaseSchemaType[];
tableSchema?: DSQL_TableSchemaType;
recordedDbEntry?: any;
clone?: boolean;
};
/**
* # Create Table Functions
*/
export default function createTable({ dbFullName, tableName, tableInfoArray, dbSchema, clone, tableSchema, recordedDbEntry, }: Param): Promise<any>;
export {};
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
+141
View File
@@ -0,0 +1,141 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = createTable;
const varDatabaseDbHandler_1 = __importDefault(require("./varDatabaseDbHandler"));
const generateColumnDescription_1 = __importDefault(require("./generateColumnDescription"));
const supplementTable_1 = __importDefault(require("./supplementTable"));
const dbHandler_1 = __importDefault(require("./dbHandler"));
/**
* # Create Table Functions
*/
function createTable(_a) {
return __awaiter(this, arguments, void 0, function* ({ dbFullName, tableName, tableInfoArray, dbSchema, clone, tableSchema, recordedDbEntry, }) {
/**
* Format tableInfoArray
*
* @description Format tableInfoArray
*/
const finalTable = (0, supplementTable_1.default)({ tableInfoArray: tableInfoArray });
/**
* Grab Schema
*
* @description Grab Schema
*/
const createTableQueryArray = [];
createTableQueryArray.push(`CREATE TABLE IF NOT EXISTS \`${tableName}\` (`);
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
try {
if (!recordedDbEntry) {
throw new Error("Recorded Db entry not found!");
}
const existingTable = yield (0, varDatabaseDbHandler_1.default)({
database: "datasquirel",
queryString: `SELECT * FROM user_database_tables WHERE db_id = ? AND table_slug = ?`,
queryValuesArray: [recordedDbEntry.id, tableSchema === null || tableSchema === void 0 ? void 0 : tableSchema.tableName],
});
/** @type {import("../../types").MYSQL_user_database_tables_table_def} */
const table = existingTable === null || existingTable === void 0 ? void 0 : existingTable[0];
if (!(table === null || table === void 0 ? void 0 : table.id)) {
const newTableEntry = yield (0, dbHandler_1.default)({
query: `INSERT INTO user_database_tables SET ?`,
values: {
user_id: recordedDbEntry.user_id,
db_id: recordedDbEntry.id,
db_slug: recordedDbEntry.db_slug,
table_name: tableSchema === null || tableSchema === void 0 ? void 0 : tableSchema.tableFullName,
table_slug: tableSchema === null || tableSchema === void 0 ? void 0 : tableSchema.tableName,
child_table: (tableSchema === null || tableSchema === void 0 ? void 0 : tableSchema.childTable) ? "1" : null,
child_table_parent_database: (tableSchema === null || tableSchema === void 0 ? void 0 : tableSchema.childTableDbFullName) || null,
child_table_parent_table: (tableSchema === null || tableSchema === void 0 ? void 0 : tableSchema.childTableName) || null,
date_created: Date(),
date_created_code: Date.now(),
date_updated: Date(),
date_updated_code: Date.now(),
},
database: "datasquirel",
});
}
}
catch (error) { }
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
let primaryKeySet = false;
/** @type {import("../../types").DSQL_FieldSchemaType[]} */
let foreignKeys = [];
////////////////////////////////////////
for (let i = 0; i < finalTable.length; i++) {
const column = finalTable[i];
const { fieldName, dataType, nullValue, primaryKey, autoIncrement, defaultValue, defaultValueLiteral, foreignKey, updatedField, onUpdate, onUpdateLiteral, onDelete, onDeleteLiteral, defaultField, encrypted, json, newTempField, notNullValue, originName, plainText, pattern, patternFlags, richText, } = column;
if (foreignKey) {
foreignKeys.push(Object.assign({}, column));
}
let { fieldEntryText, newPrimaryKeySet } = (0, generateColumnDescription_1.default)({
columnData: column,
primaryKeySet: primaryKeySet,
});
primaryKeySet = newPrimaryKeySet;
////////////////////////////////////////
const comma = (() => {
if (foreignKeys[0])
return ",";
if (i === finalTable.length - 1)
return "";
return ",";
})();
createTableQueryArray.push(" " + fieldEntryText + comma);
////////////////////////////////////////
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
if (foreignKeys[0]) {
foreignKeys.forEach((foreighKey, index, array) => {
var _a, _b, _c, _d, _e;
const fieldName = foreighKey.fieldName;
const destinationTableName = (_a = foreighKey.foreignKey) === null || _a === void 0 ? void 0 : _a.destinationTableName;
const destinationTableColumnName = (_b = foreighKey.foreignKey) === null || _b === void 0 ? void 0 : _b.destinationTableColumnName;
const cascadeDelete = (_c = foreighKey.foreignKey) === null || _c === void 0 ? void 0 : _c.cascadeDelete;
const cascadeUpdate = (_d = foreighKey.foreignKey) === null || _d === void 0 ? void 0 : _d.cascadeUpdate;
const foreignKeyName = (_e = foreighKey.foreignKey) === null || _e === void 0 ? void 0 : _e.foreignKeyName;
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(`) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;`);
const createTableQuery = createTableQueryArray.join("\n");
////////////////////////////////////////
const newTable = yield (0, varDatabaseDbHandler_1.default)({
queryString: createTableQuery,
database: dbFullName,
});
return newTable;
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
});
}
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
+10
View File
@@ -0,0 +1,10 @@
type Param = {
query: string;
values?: string[] | object;
database?: string;
};
/**
* # Main DB Handler Function
*/
export default function dbHandler({ query, values, database, }: Param): Promise<any[] | object | null>;
export {};
+100
View File
@@ -0,0 +1,100 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = dbHandler;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const serverless_mysql_1 = __importDefault(require("serverless-mysql"));
const grabDbSSL_1 = __importDefault(require("../../utils/backend/grabDbSSL"));
let connection = (0, serverless_mysql_1.default)({
config: {
host: process.env.DSQL_DB_HOST,
user: process.env.DSQL_DB_USERNAME,
password: process.env.DSQL_DB_PASSWORD,
database: process.env.DSQL_DB_NAME,
charset: "utf8mb4",
ssl: (0, grabDbSSL_1.default)(),
},
});
/**
* # Main DB Handler Function
*/
function dbHandler(_a) {
return __awaiter(this, arguments, void 0, function* ({ query, values, database, }) {
/**
* Switch Database
*
* @description If a database is provided, switch to it
*/
let isDbCorrect = true;
if (database) {
connection = (0, serverless_mysql_1.default)({
config: {
host: process.env.DSQL_DB_HOST,
user: process.env.DSQL_DB_USERNAME,
password: process.env.DSQL_DB_PASSWORD,
database: database,
charset: "utf8mb4",
ssl: (0, grabDbSSL_1.default)(),
},
});
}
if (!isDbCorrect) {
console.log("Shell Db Handler ERROR in switching Database! Operation Failed!");
return null;
}
/**
* Declare variables
*
* @description Declare "results" variable
*/
let results;
/**
* Fetch from db
*
* @description Fetch data from db if no cache
*/
try {
if (query && values) {
results = yield connection.query(query, values);
}
else {
results = yield connection.query(query);
}
/** ********************* Clean up */
yield connection.end();
}
catch ( /** @type {any} */error) {
if (process.env.FIRST_RUN) {
return null;
}
console.log("ERROR in dbHandler =>", error.message);
console.log(error);
console.log(connection.config());
fs_1.default.appendFileSync(path_1.default.resolve(__dirname, "../.tmp/dbErrorLogs.txt"), JSON.stringify(error, null, 4) + "\n" + Date() + "\n\n\n", "utf8");
results = null;
}
/**
* Return results
*
* @description Return results add to cache if "req" param is passed
*/
if (results) {
return JSON.parse(JSON.stringify(results));
}
else {
return null;
}
});
}
@@ -0,0 +1,13 @@
type Param = {
columnData: import("../../types").DSQL_FieldSchemaType;
primaryKeySet?: boolean;
};
type Return = {
fieldEntryText: string;
newPrimaryKeySet: boolean;
};
/**
* # Generate Table Column Description
*/
export default function generateColumnDescription({ columnData, primaryKeySet, }: Param): Return;
export {};
@@ -0,0 +1,55 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = generateColumnDescription;
/**
* # Generate Table Column Description
*/
function generateColumnDescription({ columnData, primaryKeySet, }) {
/**
* Format tableInfoArray
*
* @description Format tableInfoArray
*/
const { fieldName, dataType, nullValue, primaryKey, autoIncrement, defaultValue, defaultValueLiteral, onUpdateLiteral, notNullValue, } = columnData;
let fieldEntryText = "";
fieldEntryText += `\`${fieldName}\` ${dataType}`;
////////////////////////////////////////
if (nullValue) {
fieldEntryText += " DEFAULT NULL";
}
else if (defaultValueLiteral) {
fieldEntryText += ` DEFAULT ${defaultValueLiteral}`;
}
else if (defaultValue) {
if (String(defaultValue).match(/uuid\(\)/i)) {
fieldEntryText += ` DEFAULT UUID()`;
}
else {
fieldEntryText += ` DEFAULT '${defaultValue}'`;
}
}
else if (notNullValue) {
fieldEntryText += ` NOT NULL`;
}
////////////////////////////////////////
if (onUpdateLiteral) {
fieldEntryText += ` ON UPDATE ${onUpdateLiteral}`;
}
////////////////////////////////////////
if (primaryKey && !primaryKeySet) {
fieldEntryText += " PRIMARY KEY";
primaryKeySet = true;
}
////////////////////////////////////////
if (autoIncrement) {
fieldEntryText += " AUTO_INCREMENT";
primaryKeySet = true;
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
return {
fieldEntryText,
newPrimaryKeySet: primaryKeySet || false,
};
}
@@ -0,0 +1,4 @@
/**
* # Create database from Schema Function
*/
export default function noDatabaseDbHandler(queryString: string): Promise<any>;
+55
View File
@@ -0,0 +1,55 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = noDatabaseDbHandler;
const dbHandler_1 = __importDefault(require("./dbHandler"));
/**
* # Create database from Schema Function
*/
function noDatabaseDbHandler(queryString) {
return __awaiter(this, void 0, void 0, function* () {
/**
* Declare variables
*
* @description Declare "results" variable
*/
let results;
/**
* Fetch from db
*
* @description Fetch data from db if no cache
*/
try {
/** ********************* Run Query */
results = yield (0, dbHandler_1.default)({ query: queryString });
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
}
catch (error) {
console.log("ERROR in noDatabaseDbHandler =>", error.message);
}
/**
* Return results
*
* @description Return results add to cache if "req" param is passed
*/
if (results) {
return results;
}
else {
return null;
}
});
}
+4
View File
@@ -0,0 +1,4 @@
/**
* # Sulg To Camel Case
*/
export default function slugToCamelTitle(text: string): string | null;
+19
View File
@@ -0,0 +1,19 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = slugToCamelTitle;
/**
* # Sulg To Camel Case
*/
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());
});
let parsedAddress = camelArray.join(" ");
return parsedAddress;
}
else {
return null;
}
}
+14
View File
@@ -0,0 +1,14 @@
import { DSQL_FieldSchemaType } from "../../types";
type Param = {
tableInfoArray: DSQL_FieldSchemaType[];
};
/**
* # Supplement Table
*/
export default function supplementTable({ tableInfoArray }: Param): DSQL_FieldSchemaType[];
export {};
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
+39
View File
@@ -0,0 +1,39 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = supplementTable;
/**
* # Supplement Table
*/
function supplementTable({ tableInfoArray }) {
/**
* Format tableInfoArray
*
* @description Format tableInfoArray
*/
let finalTableArray = tableInfoArray;
const defaultFields = require("../../../package-shared/data/defaultFields.json");
////////////////////////////////////////
let primaryKeyExists = finalTableArray.filter((_field) => _field.primaryKey);
////////////////////////////////////////
defaultFields.forEach((field) => {
let fieldExists = finalTableArray.filter((_field) => _field.fieldName === field.fieldName);
if (fieldExists && fieldExists[0]) {
return;
}
else if (field.fieldName === "id" && !primaryKeyExists[0]) {
finalTableArray.unshift(field);
}
else {
finalTableArray.push(field);
}
});
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
return finalTableArray;
}
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
+19
View File
@@ -0,0 +1,19 @@
type Param = {
dbFullName: string;
tableName: string;
tableSchema: import("../../types").DSQL_TableSchemaType;
tableNameFull?: string;
tableInfoArray: import("../../types").DSQL_FieldSchemaType[];
userId?: number | string | null;
dbSchema: import("../../types").DSQL_DatabaseSchemaType[];
tableIndexes?: import("../../types").DSQL_IndexSchemaType[];
clone?: boolean;
tableIndex?: number;
childDb?: boolean;
recordedDbEntry?: any;
};
/**
* # Update table function
*/
export default function updateTable({ dbFullName, tableName, tableInfoArray, userId, dbSchema, tableIndexes, tableSchema, clone, childDb, tableIndex, tableNameFull, recordedDbEntry, }: Param): Promise<any>;
export {};
+417
View File
@@ -0,0 +1,417 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = updateTable;
const fs_1 = __importDefault(require("fs"));
const varDatabaseDbHandler_1 = __importDefault(require("./varDatabaseDbHandler"));
const defaultFieldsRegexp = /^id$|^uuid$|^date_created$|^date_created_code$|^date_created_timestamp$|^date_updated$|^date_updated_code$|^date_updated_timestamp$/;
const generateColumnDescription_1 = __importDefault(require("./generateColumnDescription"));
const dbHandler_1 = __importDefault(require("./dbHandler"));
/**
* # Update table function
*/
function updateTable(_a) {
return __awaiter(this, arguments, void 0, function* ({ dbFullName, tableName, tableInfoArray, userId, dbSchema, tableIndexes, tableSchema, clone, childDb, tableIndex, tableNameFull, recordedDbEntry, }) {
/**
* Initialize
* ==========================================
* @description Initial setup
*/
var _b;
/** @type {any[]} */
let errorLogs = [];
/**
* @description Initialize table info array. This value will be
* changing depending on if a field is renamed or not.
*/
let upToDateTableFieldsArray = tableInfoArray;
/**
* Handle Table updates
*
* @description Try to undate table, catch error if anything goes wrong
*/
try {
/**
* @type {string[]}
* @description Table update query string array
*/
const updateTableQueryArray = [];
/**
* @type {string[]}
* @description Constriants query string array
*/
const constraintsQueryArray = [];
/**
* @description Push the query initial value
*/
updateTableQueryArray.push(`ALTER TABLE \`${tableName}\``);
if (childDb) {
try {
if (!recordedDbEntry) {
throw new Error("Recorded Db entry not found!");
}
const existingTable = yield (0, varDatabaseDbHandler_1.default)({
database: "datasquirel",
queryString: `SELECT * FROM user_database_tables WHERE db_id = ? AND table_slug = ?`,
queryValuesArray: [recordedDbEntry.id, tableName],
});
/** @type {import("../../types").MYSQL_user_database_tables_table_def} */
const table = existingTable === null || existingTable === void 0 ? void 0 : existingTable[0];
if (!(table === null || table === void 0 ? void 0 : table.id)) {
const newTableEntry = yield (0, dbHandler_1.default)({
query: `INSERT INTO user_database_tables SET ?`,
values: {
user_id: recordedDbEntry.user_id,
db_id: recordedDbEntry.id,
db_slug: recordedDbEntry.db_slug,
table_name: tableNameFull,
table_slug: tableName,
child_table: (tableSchema === null || tableSchema === void 0 ? void 0 : tableSchema.childTable) ? "1" : null,
child_table_parent_database: (tableSchema === null || tableSchema === void 0 ? void 0 : tableSchema.childTableDbFullName) || null,
child_table_parent_table: tableSchema.childTableName || null,
date_created: Date(),
date_created_code: Date.now(),
date_updated: Date(),
date_updated_code: Date.now(),
},
database: "datasquirel",
});
}
}
catch (error) { }
}
/**
* @type {import("../../types").DSQL_MYSQL_SHOW_INDEXES_Type[]}
* @description All indexes from MYSQL db
*/ // @ts-ignore
const allExistingIndexes = yield (0, varDatabaseDbHandler_1.default)({
queryString: `SHOW INDEXES FROM \`${tableName}\``,
database: dbFullName,
});
/**
* @type {import("../../types").DSQL_MYSQL_SHOW_COLUMNS_Type[]}
* @description All columns from MYSQL db
*/ // @ts-ignore
const allExistingColumns = yield (0, varDatabaseDbHandler_1.default)({
queryString: `SHOW COLUMNS FROM \`${tableName}\``,
database: dbFullName,
});
////////////////////////////////////////
/**
* @type {string[]}
* @description Updated column names Array
*/
const updatedColumnsArray = [];
/**
* @description Iterate through every existing column
*/
for (let e = 0; e < allExistingColumns.length; e++) {
const { Field } = allExistingColumns[e];
if (Field.match(defaultFieldsRegexp))
continue;
/**
* @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);
if (existingEntry && existingEntry[0]) {
/**
* @description Check if Field name has been updated
*/
if (existingEntry[0].updatedField &&
existingEntry[0].fieldName) {
updatedColumnsArray.push(existingEntry[0].fieldName);
const renameColumn = yield (0, varDatabaseDbHandler_1.default)({
queryString: `ALTER TABLE ${tableName} RENAME COLUMN \`${existingEntry[0].originName}\` TO \`${existingEntry[0].fieldName}\``,
database: dbFullName,
});
console.log(`Column Renamed from "${existingEntry[0].originName}" to "${existingEntry[0].fieldName}"`);
/**
* Update Db Schema
* ===================================================
* @description Update Db Schema after renaming column
*/
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);
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;
fs_1.default.writeFileSync(`${String(process.env.DSQL_USER_DB_SCHEMA_PATH)}/user-${userId}/main.json`, JSON.stringify(userSchemaData), "utf8");
}
catch ( /** @type {any} */error) {
console.log("Update table error =>", error.message);
}
////////////////////////////////////////
}
////////////////////////////////////////
continue;
////////////////////////////////////////
}
else {
yield (0, varDatabaseDbHandler_1.default)({
queryString: `ALTER TABLE ${tableName} DROP COLUMN \`${Field}\``,
database: dbFullName,
});
}
}
/**
* Handle MYSQL Table Indexes
* ===================================================
* @description Iterate through each table index(if available)
* and perform operations
*/
for (let f = 0; f < allExistingIndexes.length; f++) {
const { Key_name, Index_comment } = allExistingIndexes[f];
/**
* @description Check if this index was specifically created
* by datasquirel
*/
if (Index_comment === null || Index_comment === void 0 ? void 0 : Index_comment.match(/schema_index/)) {
try {
const existingKeyInSchema = tableIndexes === null || tableIndexes === void 0 ? void 0 : tableIndexes.filter((indexObject) => indexObject.alias === Key_name);
if (!(existingKeyInSchema === null || existingKeyInSchema === void 0 ? void 0 : 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
* present in the datasquirel DB schema
*/
yield (0, varDatabaseDbHandler_1.default)({
queryString: `ALTER TABLE ${tableName} DROP INDEX \`${Key_name}\``,
database: dbFullName,
});
}
}
}
/**
* Handle DATASQUIREL Table Indexes
* ===================================================
* @description Iterate through each datasquirel schema
* table index(if available), and perform operations
*/
if (tableIndexes && tableIndexes[0]) {
for (let g = 0; g < tableIndexes.length; g++) {
const { indexType, indexName, indexTableFields, alias } = tableIndexes[g];
if (!(alias === null || alias === void 0 ? void 0 : 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
*/
yield (0, varDatabaseDbHandler_1.default)({
queryString: `CREATE${(indexType === null || indexType === void 0 ? void 0 : indexType.match(/fullText/i)) ? " FULLTEXT" : ""} INDEX \`${alias}\` ON ${tableName}(${indexTableFields === null || indexTableFields === void 0 ? void 0 : indexTableFields.map((nm) => nm.value).map((nm) => `\`${nm}\``).join(",")}) COMMENT 'schema_index'`,
database: dbFullName,
});
}
}
}
/**
* Handle MYSQL Foreign Keys
* ===================================================
* @description Iterate through each datasquirel schema
* table index(if available), and perform operations
*/
/**
* @description All MSQL Foreign Keys
* @type {import("../../types").DSQL_MYSQL_FOREIGN_KEYS_Type[] | null}
*/ // @ts-ignore
const allForeignKeys = yield (0, varDatabaseDbHandler_1.default)({
queryString: `SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE CONSTRAINT_SCHEMA = '${dbFullName}' AND TABLE_NAME='${tableName}' AND CONSTRAINT_TYPE='FOREIGN KEY'`,
database: dbFullName,
});
if (allForeignKeys) {
for (let c = 0; c < allForeignKeys.length; c++) {
const { CONSTRAINT_NAME } = allForeignKeys[c];
/**
* @description Skip if Key is the PRIMARY Key
*/
if (CONSTRAINT_NAME.match(/PRIMARY/))
continue;
/**
* @description Drop all foreign Keys to avoid MYSQL errors when adding/updating
* Foreign keys
*/
const dropForeignKey = yield (0, varDatabaseDbHandler_1.default)({
queryString: `ALTER TABLE ${tableName} DROP FOREIGN KEY \`${CONSTRAINT_NAME}\``,
database: dbFullName,
});
}
}
/**
* Handle DATASQUIREL schema fields for current table
* ===================================================
* @description Iterate through each field object and
* perform operations
*/
for (let i = 0; i < upToDateTableFieldsArray.length; i++) {
const column = upToDateTableFieldsArray[i];
const prevColumn = upToDateTableFieldsArray[i - 1];
const nextColumn = upToDateTableFieldsArray[i + 1];
const { fieldName, dataType, nullValue, primaryKey, autoIncrement, defaultValue, defaultValueLiteral, foreignKey, updatedField, } = column;
////////////////////////////////////////
/**
* @description Skip default fields
*/
if (fieldName === null || fieldName === void 0 ? void 0 : fieldName.match(/^id$|^date_/))
continue;
/**
* @description Skip columns that have been updated recently
*/
// if (updatedColumnsArray.includes(fieldName)) continue;
////////////////////////////////////////
let updateText = "";
////////////////////////////////////////
/** @type {any} */
let existingColumnIndex;
/**
* @description Existing MYSQL field object
*/
let existingColumn = allExistingColumns && allExistingColumns[0]
? allExistingColumns.filter((_column, _index) => {
if (_column.Field === fieldName) {
existingColumnIndex = _index;
return true;
}
})
: null;
/**
* @description Construct SQL text snippet for this field
*/
let { fieldEntryText } = (0, generateColumnDescription_1.default)({
columnData: column,
});
/**
* @description Modify Column(Field) if it already exists
* in MYSQL database
*/
if (existingColumn && ((_b = existingColumn[0]) === null || _b === void 0 ? void 0 : _b.Field)) {
const { Field, Type, Null, Key, Default, Extra } = existingColumn[0];
let isColumnReordered = i < existingColumnIndex;
if (Field === fieldName &&
!isColumnReordered &&
(dataType === null || dataType === void 0 ? void 0 : dataType.toUpperCase()) === Type.toUpperCase()) {
updateText += `MODIFY COLUMN ${fieldEntryText}`;
// continue;
}
else {
if (userId) {
updateText += `MODIFY COLUMN ${fieldEntryText}${isColumnReordered
? (prevColumn === null || prevColumn === void 0 ? void 0 : prevColumn.fieldName)
? " AFTER `" + prevColumn.fieldName + "`"
: (nextColumn === null || nextColumn === void 0 ? void 0 : nextColumn.fieldName)
? " BEFORE `" + nextColumn.fieldName + "`"
: ""
: ""}`;
}
else {
updateText += `MODIFY COLUMN ${fieldEntryText}`;
}
}
}
else if (prevColumn && prevColumn.fieldName) {
/**
* @description Add new Column AFTER previous column, if
* previous column exists
*/
updateText += `ADD COLUMN ${fieldEntryText} AFTER \`${prevColumn.fieldName}\``;
}
else if (nextColumn && nextColumn.fieldName) {
/**
* @description Add new Column BEFORE next column, if
* next column exists
*/
updateText += `ADD COLUMN ${fieldEntryText} BEFORE \`${nextColumn.fieldName}\``;
}
else {
/**
* @description Append new column to the end of existing columns
*/
updateText += `ADD COLUMN ${fieldEntryText}`;
}
////////////////////////////////////////
/**
* @description Pust SQL code snippet to updateTableQueryArray Array
* Add a comma(,) to separate from the next snippet
*/
updateTableQueryArray.push(updateText + ",");
/**
* @description Handle foreing keys if available, and if there is no
* "clone" boolean = true
*/
if (!clone && 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 finalQueryString = `ALTER TABLE \`${tableName}\` ${foreinKeyText}`;
const addForeignKey = yield (0, varDatabaseDbHandler_1.default)({
database: dbFullName,
queryString: finalQueryString,
});
if (!(addForeignKey === null || addForeignKey === void 0 ? void 0 : addForeignKey.serverStatus)) {
errorLogs.push(addForeignKey);
}
}
////////////////////////////////////////
}
/**
* @description Construct final SQL query by combning all SQL snippets in
* updateTableQueryArray Arry, and trimming the final comma(,)
*/
const updateTableQuery = updateTableQueryArray
.join(" ")
.replace(/,$/, "");
////////////////////////////////////////
/**
* @description Check if SQL snippets array has more than 1 entries
* This is because 1 entry means "ALTER TABLE table_name" only, without any
* Alter directives like "ADD COLUMN" or "MODIFY COLUMN"
*/
if (updateTableQueryArray.length > 1) {
const updateTable = yield (0, varDatabaseDbHandler_1.default)({
queryString: updateTableQuery,
database: dbFullName,
});
return updateTable;
}
else {
/**
* @description If only 1 SQL snippet is left in updateTableQueryArray, this
* means that no updates have been made to the table
*/
return "No Changes Made to Table";
}
}
catch ( /** @type {any} */error) {
console.log('Error in "updateTable" shell function =>', error.message);
return "Error in Updating Table";
}
});
}
@@ -0,0 +1,12 @@
import { DSQL_TableSchemaType } from "../../types";
type Param = {
queryString: string;
queryValuesArray?: string[];
database?: string;
tableSchema?: DSQL_TableSchemaType;
};
/**
* # DB handler for specific database
*/
export default function varDatabaseDbHandler({ queryString, queryValuesArray, database, tableSchema, }: Param): Promise<any>;
export {};
+64
View File
@@ -0,0 +1,64 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = varDatabaseDbHandler;
const dbHandler_1 = __importDefault(require("./dbHandler"));
/**
* # DB handler for specific database
*/
function varDatabaseDbHandler(_a) {
return __awaiter(this, arguments, void 0, function* ({ queryString, queryValuesArray, database, tableSchema, }) {
/**
* Declare variables
*
* @description Declare "results" variable
*/
let results;
/**
* Fetch from db
*
* @description Fetch data from db if no cache
*/
try {
if (queryString &&
queryValuesArray &&
Array.isArray(queryValuesArray) &&
queryValuesArray[0]) {
results = yield (0, dbHandler_1.default)({
query: queryString,
values: queryValuesArray,
database,
});
}
else {
results = yield (0, dbHandler_1.default)({
query: queryString,
database,
});
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
}
catch ( /** @type {any} */error) {
console.log("Shell Vardb Error =>", error.message);
}
/**
* Return results
*
* @description Return results add to cache if "req" param is passed
*/
return results;
});
}