This commit is contained in:
Benjamin Toby
2024-12-06 11:31:24 +01:00
parent 6df20790f4
commit 8ca2779741
153 changed files with 6621 additions and 3899 deletions
+59
View File
@@ -0,0 +1,59 @@
// @ts-check
/**
* 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
*
* @param {string} text - text string without spaces
*
* @returns {string | null}
*/
module.exports = function camelJoinedtoCamelSpace(text) {
if (!text?.match(/./)) {
return "";
}
if (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;
}
};
+212
View File
@@ -0,0 +1,212 @@
// @ts-check
const varDatabaseDbHandler = require("./varDatabaseDbHandler");
const generateColumnDescription = require("./generateColumnDescription");
const supplementTable = require("./supplementTable");
const dbHandler = require("./dbHandler");
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/**
*
* @param {object} params
* @param {string} params.dbFullName
* @param {string} params.tableName
* @param {any[]} params.tableInfoArray
* @param {import("../../types").DSQL_DatabaseSchemaType[]} [params.dbSchema]
* @param {import("../../types").DSQL_TableSchemaType} [params.tableSchema]
* @param {any} [params.recordedDbEntry]
* @param {boolean} [params.clone] - Is this a newly cloned table?
* @returns
*/
module.exports = async function createTable({
dbFullName,
tableName,
tableInfoArray,
dbSchema,
clone,
tableSchema,
recordedDbEntry,
}) {
/**
* Format tableInfoArray
*
* @description Format tableInfoArray
*/
const finalTable = supplementTable({ 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 = await varDatabaseDbHandler({
database: "datasquirel",
queryString: `SELECT * FROM user_database_tables WHERE db_id = ? AND table_slug = ?`,
queryValuesArray: [recordedDbEntry.id, tableSchema?.tableName],
});
/** @type {import("../../types").MYSQL_user_database_tables_table_def} */
const table = existingTable?.[0];
if (!table?.id) {
const newTableEntry = await dbHandler({
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?.tableFullName,
table_slug: tableSchema?.tableName,
child_table: tableSchema?.childTable ? "1" : null,
child_table_parent_database:
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) {}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
let primaryKeySet = false;
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({
fieldName: fieldName,
...foreignKey,
});
}
let { fieldEntryText, newPrimaryKeySet } = generateColumnDescription({
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) => {
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(
`) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;`
);
const createTableQuery = createTableQueryArray.join("\n");
////////////////////////////////////////
const newTable = await varDatabaseDbHandler({
queryString: createTableQuery,
database: dbFullName,
});
return newTable;
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
};
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
+118
View File
@@ -0,0 +1,118 @@
// @ts-check
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
const fs = require("fs");
const path = require("path");
const mysql = require("serverless-mysql");
const grabDbSSL = require("../../utils/backend/grabDbSSL");
let connection = mysql({
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: grabDbSSL(),
},
});
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////
/**
* # Main DB Handler Function
* @async
*
* @param {object} params
* @param {string} params.query
* @param {string[] | object} [params.values]
* @param {string} [params.database]
*
* @returns {Promise<any[] | object | null>}
*/
module.exports = async function dbHandler({ query, values, database }) {
/**
* Switch Database
*
* @description If a database is provided, switch to it
*/
let isDbCorrect = true;
if (database) {
connection = mysql({
config: {
host: process.env.DSQL_DB_HOST,
user: process.env.DSQL_DB_USERNAME,
password: process.env.DSQL_DB_PASSWORD,
database: database,
charset: "utf8mb4",
ssl: grabDbSSL(),
},
});
}
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 = await connection.query(query, values);
} else {
results = await connection.query(query);
}
/** ********************* Clean up */
await 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.appendFileSync(
path.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;
}
};
+108
View File
@@ -0,0 +1,108 @@
// @ts-check
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/**
* Generate SQL text for Field
* ==============================================================================
* @param {object} params - Single object params
* @param {import("../../types").DSQL_FieldSchemaType} params.columnData - Field object
* @param {boolean} [params.primaryKeySet] - Table Name(slug)
*
* @returns {{ fieldEntryText: string, newPrimaryKeySet: boolean }}
*/
module.exports = function generateColumnDescription({
columnData,
primaryKeySet,
}) {
/**
* Format tableInfoArray
*
* @description Format tableInfoArray
*/
const {
fieldName,
dataType,
nullValue,
primaryKey,
autoIncrement,
defaultValue,
defaultValueLiteral,
foreignKey,
updatedField,
onUpdate,
onUpdateLiteral,
onDelete,
onDeleteLiteral,
defaultField,
encrypted,
json,
newTempField,
notNullValue,
originName,
plainText,
pattern,
patternFlags,
richText,
} = columnData;
let fieldEntryText = "";
fieldEntryText += `\`${fieldName}\` ${dataType}`;
////////////////////////////////////////
// if (String(fieldEntryText).match(/ UUID$/)) {
// fieldEntryText += ` DEFAULT UUID()`;
// } else
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 };
};
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
+45
View File
@@ -0,0 +1,45 @@
// @ts-check
const dbHandler = require("./dbHandler");
/**
* Create database from Schema Function
* ==============================================================================
* @param {string} queryString - Query String
* @returns {Promise<any>}
*/
module.exports = async function noDatabaseDbHandler(queryString) {
/**
* Declare variables
*
* @description Declare "results" variable
*/
let results;
/**
* Fetch from db
*
* @description Fetch data from db if no cache
*/
try {
/** ********************* Run Query */
results = await dbHandler({ query: queryString });
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
} catch (/** @type {any} */ 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;
}
};
+18
View File
@@ -0,0 +1,18 @@
// @ts-check
module.exports = function slugToCamelTitle(/** @type {String} */ 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;
}
};
+58
View File
@@ -0,0 +1,58 @@
// @ts-check
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/**
*
* @param {object} param0
* @param {import("../../types").DSQL_FieldSchemaType[]} param0.tableInfoArray
* @returns
*/
module.exports = 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;
};
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
File diff suppressed because it is too large Load Diff
+71
View File
@@ -0,0 +1,71 @@
// @ts-check
const fs = require("fs");
const dbHandler = require("./dbHandler");
/**
* 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").DSQL_TableSchemaType} [params.tableSchema] - Table schema
* @returns {Promise<any>}
*/
module.exports = async function varDatabaseDbHandler({
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 = await dbHandler({
query: queryString,
values: queryValuesArray,
database,
});
} else {
results = await dbHandler({
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;
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
};