This commit is contained in:
Benjamin Toby
2024-11-06 07:26:23 +01:00
parent d81f38809b
commit 190598aa3f
42 changed files with 3766 additions and 298 deletions
+3 -3
View File
@@ -3,9 +3,9 @@
* No imports found for this Module
==== MODULE TRACE END ==== */
// @ts-check
const runQuery = require("../../package-shared/functions/backend/db/runQuery");
const runQuery = require("./utils/runQuery");
// @ts-check
/**
* @typedef {Object} LocalGetReturn
@@ -39,7 +39,6 @@ async function localGet({ options, dbSchema }) {
/** @type {string | undefined | any } */
const tableName = options?.tableName ? options.tableName : undefined;
const dbFullName = process.env.DSQL_DB_NAME || "";
/**
@@ -71,6 +70,7 @@ async function localGet({ options, dbSchema }) {
queryValuesArray: queryValues,
dbSchema,
tableName,
local: true,
});
if (error) throw error;
+2 -1
View File
@@ -1,6 +1,6 @@
// @ts-check
const runQuery = require("./utils/runQuery");
const runQuery = require("../../package-shared/functions/backend/db/runQuery");
/**
* Make a get request to Datasquirel API
@@ -52,6 +52,7 @@ async function localPost({ options, dbSchema }) {
dbSchema: dbSchema,
queryValuesArray: queryValues,
tableName,
local: true,
});
if (error) throw error;
-184
View File
@@ -1,184 +0,0 @@
// @ts-check
/**
* Imports: Handle imports
*/
const encrypt = require("../../../functions/encrypt");
const dbHandler = require("../../engine/utils/dbHandler");
const updateDb = require("./updateDbEntry");
const updateDbEntry = require("./updateDbEntry");
/**
* Add a db Entry Function
* ==============================================================================
* @description Description
* @async
*
* @param {object} params - An object containing the function parameters.
* "Read only" or "Full Access"? Defaults to "Read Only"
* @param {string} params.dbFullName - Database full name
* @param {string} params.tableName - Table name
* @param {*} params.data - Data to add
* @param {import("../../../package-shared/types").DSQL_TableSchemaType} [params.tableSchema] - Table schema
* @param {string} [params.duplicateColumnName] - Duplicate column name
* @param {string} [params.duplicateColumnValue] - Duplicate column value
* @param {boolean} [params.update] - Update this row if it exists
* @param {string} params.encryptionKey - Update this row if it exists
* @param {string} params.encryptionSalt - Update this row if it exists
*
* @returns {Promise<*>}
*/
async function addDbEntry({
dbFullName,
tableName,
data,
tableSchema,
duplicateColumnName,
duplicateColumnValue,
update,
encryptionKey,
encryptionSalt,
}) {
/**
* Initialize variables
*/
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
/**
* Handle function logic
*/
if (duplicateColumnName && typeof duplicateColumnName === "string") {
const duplicateValue = await dbHandler({
database: dbFullName,
query: `SELECT * FROM \`${tableName}\` WHERE \`${duplicateColumnName}\`=?`,
values: [duplicateColumnValue || ""],
});
if (duplicateValue && duplicateValue[0] && !update) {
return null;
} else if (duplicateValue && duplicateValue[0] && update) {
return await updateDbEntry({
dbFullName,
tableName,
data,
tableSchema,
identifierColumnName: duplicateColumnName,
identifierValue: duplicateColumnValue || "",
encryptionKey,
encryptionSalt,
});
}
}
/**
* Declare variables
*
* @description Declare "results" variable
*/
const dataKeys = Object.keys(data);
let insertKeysArray = [];
let insertValuesArray = [];
for (let i = 0; i < dataKeys.length; i++) {
try {
const dataKey = dataKeys[i];
let value = data[dataKey];
const targetFieldSchemaArray = tableSchema
? tableSchema?.fields?.filter(
(field) => field.fieldName == dataKey
)
: null;
const targetFieldSchema =
targetFieldSchemaArray && targetFieldSchemaArray[0]
? targetFieldSchemaArray[0]
: null;
if (!value) continue;
if (targetFieldSchema?.encrypted) {
value = encrypt({ data: value, encryptionKey, encryptionSalt });
console.log("DSQL: Encrypted value =>", value);
}
if (targetFieldSchema?.pattern) {
const pattern = new RegExp(
targetFieldSchema.pattern,
targetFieldSchema.patternFlags || ""
);
if (!value?.toString()?.match(pattern)) {
console.log("DSQL: Pattern not matched =>", value);
value = "";
}
}
if (typeof value === "string" && !value.match(/./i)) {
value = {
toSqlString: function () {
return "NULL";
},
};
}
insertKeysArray.push("`" + dataKey + "`");
if (typeof value === "object") {
value = JSON.stringify(value);
}
insertValuesArray.push(value);
} catch (/** @type {*} */ error) {
console.log("DSQL: Error in parsing data keys =>", error.message);
continue;
}
}
////////////////////////////////////////
insertKeysArray.push("`date_created`");
insertValuesArray.push(Date());
insertKeysArray.push("`date_created_code`");
insertValuesArray.push(Date.now());
////////////////////////////////////////
insertKeysArray.push("`date_updated`");
insertValuesArray.push(Date());
insertKeysArray.push("`date_updated_code`");
insertValuesArray.push(Date.now());
////////////////////////////////////////
const query = `INSERT INTO \`${tableName}\` (${insertKeysArray.join(
","
)}) VALUES (${insertValuesArray.map(() => "?").join(",")})`;
const queryValuesArray = insertValuesArray;
const newInsert = await dbHandler({
database: dbFullName,
query: query,
values: queryValuesArray,
});
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
/**
* Return statement
*/
return newInsert;
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
module.exports = addDbEntry;
-83
View File
@@ -1,83 +0,0 @@
// @ts-check
const dbHandler = require("../../engine/utils/dbHandler");
/**
* Imports: Handle imports
*/
/**
* Delete DB Entry Function
* ==============================================================================
* @description Description
* @async
*
* @param {object} params - An object containing the function parameters.
* @param {string} [params.dbContext] - What is the database context? "Master"
* or "Dsql User". Defaults to "Master"
* @param {("Read Only" | "Full Access")} [params.paradigm] - What is the paradigm for "Dsql User"?
* "Read only" or "Full Access"? Defaults to "Read Only"
* @param {string} params.dbFullName - Database full name
* @param {string} params.tableName - Table name
* @param {import("../../../package-shared/types").DSQL_TableSchemaType} [params.tableSchema] - Table schema
* @param {string} params.identifierColumnName - Update row identifier column name
* @param {string|number} params.identifierValue - Update row identifier column value
*
* @returns {Promise<object|null>}
*/
async function deleteDbEntry({
dbContext,
paradigm,
dbFullName,
tableName,
identifierColumnName,
identifierValue,
}) {
try {
/**
* Check if data is valid
*/
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
/**
* Execution
*
* @description
*/
const query = `DELETE FROM ${tableName} WHERE \`${identifierColumnName}\`=?`;
const deletedEntry = await dbHandler({
query: query,
database: dbFullName,
values: [identifierValue],
});
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
/**
* Return statement
*/
return deletedEntry;
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
} catch (error) {
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
return null;
}
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
module.exports = deleteDbEntry;
-189
View File
@@ -1,189 +0,0 @@
/** # MODULE TRACE
======================================================================
* Detected 4 files that call this module. The files are listed below:
======================================================================
* `require` Statement Found in [get.js](d:\GitHub\dsql\engine\query\get.js)
* `require` Statement Found in [post.js](d:\GitHub\dsql\engine\query\post.js)
* `require` Statement Found in [add-user.js](d:\GitHub\dsql\engine\user\add-user.js)
* `require` Statement Found in [update-user.js](d:\GitHub\dsql\engine\user\update-user.js)
==== MODULE TRACE END ==== */
// @ts-check
const fs = require("fs");
const addDbEntry = require("./addDbEntry");
const updateDbEntry = require("./updateDbEntry");
const deleteDbEntry = require("./deleteDbEntry");
const varDatabaseDbHandler = require("../../engine/utils/varDatabaseDbHandler");
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/**
* Run DSQL users queries
* ==============================================================================
* @param {object} params - An object containing the function parameters.
* @param {string} params.dbFullName - Database full name. Eg. "datasquire_user_2_test"
* @param {*} params.query - Query string or object
* @param {boolean} [params.readOnly] - Is this operation read only?
* @param {import("../../../package-shared/types").DSQL_DatabaseSchemaType} [params.dbSchema] - Database schema
* @param {string[]} [params.queryValuesArray] - An optional array of query values if "?" is used in the query string
* @param {string} [params.tableName] - Table Name
*
* @return {Promise<{result: *, error?: *}>}
*/
async function runQuery({
dbFullName,
query,
readOnly,
dbSchema,
queryValuesArray,
tableName,
}) {
/**
* Declare variables
*
* @description Declare "results" variable
*/
const encryptionKey = process.env.DSQL_ENCRYPTION_KEY || "";
const encryptionSalt = process.env.DSQL_ENCRYPTION_SALT || "";
let result, error, tableSchema;
if (dbSchema) {
try {
const table = tableName
? tableName
: typeof query == "string"
? null
: query
? query?.table
: null;
if (!table) throw new Error("No table name provided");
tableSchema = dbSchema.tables.filter(
(tb) => tb?.tableName === table
)[0];
} catch (_err) {}
}
/**
* Declare variables
*
* @description Declare "results" variable
*/
try {
if (typeof query === "string") {
result = await varDatabaseDbHandler({
queryString: query,
queryValuesArray,
database: dbFullName,
tableSchema,
});
} else if (typeof query === "object") {
/**
* Declare variables
*
* @description Declare "results" variable
*/
const {
data,
action,
table,
identifierColumnName,
identifierValue,
update,
duplicateColumnName,
duplicateColumnValue,
} = query;
switch (action.toLowerCase()) {
case "insert":
result = await addDbEntry({
dbFullName: dbFullName,
tableName: table,
data: data,
update,
duplicateColumnName,
duplicateColumnValue,
tableSchema,
encryptionKey,
encryptionSalt,
});
if (!result?.insertId) {
error = new Error("Couldn't insert data");
}
break;
case "update":
result = await updateDbEntry({
dbContext: "Dsql User",
paradigm: "Full Access",
dbFullName: dbFullName,
tableName: table,
data: data,
identifierColumnName,
identifierValue,
tableSchema,
encryptionKey,
encryptionSalt,
});
break;
case "delete":
result = await deleteDbEntry({
dbContext: "Dsql User",
paradigm: "Full Access",
dbFullName: dbFullName,
tableName: table,
identifierColumnName,
identifierValue,
tableSchema,
});
break;
default:
console.log("Unhandled Query");
console.log("Query Recieved =>", query);
result = {
result: null,
error: "Unhandled Query",
};
break;
}
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
} catch (/** @type {*} */ error) {
console.log("Error in Running Query =>", error.message);
console.log("Query Recieved =>", query);
result = {
result: null,
error: "Error in running Query => " + error.message,
};
error = error.message;
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
return { result, error };
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
}
module.exports = runQuery;
-180
View File
@@ -1,180 +0,0 @@
// @ts-check
const encrypt = require("../../../functions/encrypt");
const dbHandler = require("../../engine/utils/dbHandler");
/**
* Imports: Handle imports
*/
/**
* Update DB Function
* ==============================================================================
* @description Description
* @async
*
* @param {object} params - An object containing the function parameters.
* @param {("Master" | "Dsql User")} [params.dbContext] - What is the database context? "Master"
* or "Dsql User". Defaults to "Master"
* @param {("Read Only" | "Full Access")} [params.paradigm] - What is the paradigm for "Dsql User"?
* "Read only" or "Full Access"? Defaults to "Read Only"
* @param {string} params.dbFullName - Database full name
* @param {string} params.tableName - Table name
* @param {*} params.data - Data to add
* @param {import("../../../package-shared/types").DSQL_TableSchemaType} [params.tableSchema] - Table schema
* @param {string} params.identifierColumnName - Update row identifier column name
* @param {string | number} params.identifierValue - Update row identifier column value
* @param {string} params.encryptionKey - Encryption key
* @param {string} params.encryptionSalt - Encryption salt
*
* @returns {Promise<object|null>}
*/
async function updateDbEntry({
dbContext,
paradigm,
dbFullName,
tableName,
data,
tableSchema,
identifierColumnName,
identifierValue,
encryptionKey,
encryptionSalt,
}) {
/**
* Check if data is valid
*/
if (!data || !Object.keys(data).length) return null;
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
/**
* Declare variables
*
* @description Declare "results" variable
*/
const dataKeys = Object.keys(data);
let updateKeyValueArray = [];
let updateValues = [];
/**
* Declare variables
*
* @description Declare "results" variable
*/
for (let i = 0; i < dataKeys.length; i++) {
try {
const dataKey = dataKeys[i];
let value = data[dataKey];
const targetFieldSchemaArray = tableSchema
? tableSchema?.fields?.filter(
(field) => field.fieldName === dataKey
)
: null;
const targetFieldSchema =
targetFieldSchemaArray && targetFieldSchemaArray[0]
? targetFieldSchemaArray[0]
: null;
if (typeof value == "undefined") continue;
if (
typeof value !== "string" &&
typeof value !== "number" &&
!value
)
continue;
if (targetFieldSchema?.encrypted) {
value = encrypt({ data: value, encryptionKey, encryptionSalt });
}
if (typeof value === "object") {
value = JSON.stringify(value);
}
if (typeof value === "string" && value.match(/^null$/i)) {
value = {
toSqlString: function () {
return "NULL";
},
};
}
if (targetFieldSchema?.pattern) {
const pattern = new RegExp(
targetFieldSchema.pattern,
targetFieldSchema.patternFlags || ""
);
if (!value?.toString()?.match(pattern)) {
console.log("DSQL: Pattern not matched =>", value);
value = "";
}
}
if (typeof value === "string" && !value.match(/./i)) {
value = {
toSqlString: function () {
return "NULL";
},
};
}
if (!value && typeof value == "number" && value != 0) continue;
updateKeyValueArray.push(`\`${dataKey}\`=?`);
updateValues.push(value);
////////////////////////////////////////
////////////////////////////////////////
} catch (/** @type {*} */ error) {
////////////////////////////////////////
////////////////////////////////////////
console.log(
"DSQL: Error in parsing data keys in update function =>",
error.message
);
continue;
}
}
////////////////////////////////////////
////////////////////////////////////////
updateKeyValueArray.push(`date_updated='${Date()}'`);
updateKeyValueArray.push(`date_updated_code='${Date.now()}'`);
////////////////////////////////////////
////////////////////////////////////////
const query = `UPDATE ${tableName} SET ${updateKeyValueArray.join(
","
)} WHERE \`${identifierColumnName}\`=?`;
updateValues.push(identifierValue);
const updatedEntry = await dbHandler({
database: dbFullName,
query: query,
values: updateValues,
});
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
/**
* Return statement
*/
return updatedEntry;
}
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
module.exports = updateDbEntry;