This commit is contained in:
Benjamin Toby
2023-09-21 15:00:04 +01:00
parent 70ee0a2c0a
commit 44b013147e
77 changed files with 8511 additions and 8495 deletions
+101 -101
View File
@@ -1,101 +1,101 @@
/** # MODULE TRACE
======================================================================
* No imports found for this Module
==== MODULE TRACE END ==== */
// @ts-check
const runQuery = require("./utils/runQuery");
/**
* @typedef {Object} LocalGetReturn
* @property {boolean} success - Did the function run successfully?
* @property {*} [payload] - GET request results
* @property {string} [msg] - Message
* @property {string} [error] - Error Message
*/
/**
* @typedef {Object} LocalQueryObject
* @property {string} query - Table Name
* @property {string} [tableName] - Table Name
* @property {string[]} [queryValues] - GET request results
*/
/**
* Make a get request to Datasquirel API
* ==============================================================================
* @async
*
* @param {Object} params - Single object passed
* @param {LocalQueryObject} params.options - SQL Query
* @param {import("../../types/database-schema.td").DSQL_DatabaseSchemaType} [params.dbSchema] - Name of the table to query
*
* @returns { Promise<LocalGetReturn> } - Return Object
*/
async function localGet({ options, dbSchema }) {
try {
const { query, queryValues } = options;
/** @type {string | undefined | any } */
const tableName = options?.tableName ? options.tableName : undefined;
const dbFullName = process.env.DSQL_DB_NAME || "";
/**
* Input Validation
*
* @description Input Validation
*/
if (typeof query == "string" && (query.match(/^alter|^delete|information_schema|databases|^create/i) || !query.match(/^select/i))) {
return { success: false, msg: "Wrong Input" };
}
/**
* Create new user folder and file
*
* @description Create new user folder and file
*/
let results;
try {
let { result, error } = await runQuery({
dbFullName: dbFullName,
query: query,
queryValuesArray: queryValues,
dbSchema,
tableName,
});
if (error) throw error;
if (!result) throw new Error("No Result received for query => " + query);
if (result?.error) throw new Error(result.error);
results = result;
return { success: true, payload: results };
////////////////////////////////////////
} catch (/** @type {*} */ error) {
////////////////////////////////////////
console.log("Error in local get Request =>", error.message);
return {
success: false,
payload: null,
error: error.message,
};
}
////////////////////////////////////////
} catch (/** @type {*} */ error) {
////////////////////////////////////////
console.log("Error in local get Request =>", error.message);
return { success: false, msg: "Something went wrong!" };
////////////////////////////////////////
}
}
module.exports = localGet;
/** # MODULE TRACE
======================================================================
* No imports found for this Module
==== MODULE TRACE END ==== */
// @ts-check
const runQuery = require("./utils/runQuery");
/**
* @typedef {Object} LocalGetReturn
* @property {boolean} success - Did the function run successfully?
* @property {*} [payload] - GET request results
* @property {string} [msg] - Message
* @property {string} [error] - Error Message
*/
/**
* @typedef {Object} LocalQueryObject
* @property {string} query - Table Name
* @property {string} [tableName] - Table Name
* @property {string[]} [queryValues] - GET request results
*/
/**
* Make a get request to Datasquirel API
* ==============================================================================
* @async
*
* @param {Object} params - Single object passed
* @param {LocalQueryObject} params.options - SQL Query
* @param {import("../../types/database-schema.td").DSQL_DatabaseSchemaType} [params.dbSchema] - Name of the table to query
*
* @returns { Promise<LocalGetReturn> } - Return Object
*/
async function localGet({ options, dbSchema }) {
try {
const { query, queryValues } = options;
/** @type {string | undefined | any } */
const tableName = options?.tableName ? options.tableName : undefined;
const dbFullName = process.env.DSQL_DB_NAME || "";
/**
* Input Validation
*
* @description Input Validation
*/
if (typeof query == "string" && (query.match(/^alter|^delete|information_schema|databases|^create/i) || !query.match(/^select/i))) {
return { success: false, msg: "Wrong Input" };
}
/**
* Create new user folder and file
*
* @description Create new user folder and file
*/
let results;
try {
let { result, error } = await runQuery({
dbFullName: dbFullName,
query: query,
queryValuesArray: queryValues,
dbSchema,
tableName,
});
if (error) throw error;
if (!result) throw new Error("No Result received for query => " + query);
if (result?.error) throw new Error(result.error);
results = result;
return { success: true, payload: results };
////////////////////////////////////////
} catch (/** @type {*} */ error) {
////////////////////////////////////////
console.log("Error in local get Request =>", error.message);
return {
success: false,
payload: null,
error: error.message,
};
}
////////////////////////////////////////
} catch (/** @type {*} */ error) {
////////////////////////////////////////
console.log("Error in local get Request =>", error.message);
return { success: false, msg: "Something went wrong!" };
////////////////////////////////////////
}
}
module.exports = localGet;
+100 -100
View File
@@ -1,100 +1,100 @@
// @ts-check
const runQuery = require("./utils/runQuery");
/**
* @typedef {Object} LocalPostReturn
* @property {boolean} success - Did the function run successfully?
* @property {*} [payload] - GET request results
* @property {string} [msg] - Message
* @property {string} [error] - Error Message
*/
/**
* @typedef {Object} LocalPostQueryObject
* @property {string | import("../../utils/post").PostDataPayload} query - Table Name
* @property {string} [tableName] - Table Name
* @property {string[]} [queryValues] - GET request results
*/
/**
* Make a get request to Datasquirel API
* ==============================================================================
* @async
*
* @param {Object} params - Single object passed
* @param {LocalPostQueryObject} params.options - SQL Query
* @param {import("../../types/database-schema.td").DSQL_DatabaseSchemaType} [params.dbSchema] - Name of the table to query
*
* @returns { Promise<LocalPostReturn> } - Return Object
*/
async function localPost({ options, dbSchema }) {
try {
/**
* Grab Body
*/
const { query, tableName, queryValues } = options;
const dbFullName = process.env.DSQL_DB_NAME || "";
/**
* Input Validation
*
* @description Input Validation
*/
if (typeof query === "string" && query?.match(/^create |^alter |^drop /i)) {
return { success: false, msg: "Wrong Input" };
}
if (typeof query === "object" && query?.action?.match(/^create |^alter |^drop /i)) {
return { success: false, msg: "Wrong Input" };
}
/**
* Create new user folder and file
*
* @description Create new user folder and file
*/
try {
let { result, error } = await runQuery({
dbFullName: dbFullName,
query: query,
dbSchema: dbSchema,
queryValuesArray: queryValues,
tableName,
});
if (error) throw error;
return {
success: true,
payload: result,
error: error,
};
////////////////////////////////////////
} catch (/** @type {*} */ error) {
////////////////////////////////////////
return {
success: false,
payload: null,
error: error.message,
};
}
////////////////////////////////////////
} catch (/** @type {*} */ error) {
////////////////////////////////////////
console.log("Error in local post Request =>", error.message);
return {
success: false,
payload: null,
msg: "Something went wrong!",
};
////////////////////////////////////////
}
}
module.exports = localPost;
// @ts-check
const runQuery = require("./utils/runQuery");
/**
* @typedef {Object} LocalPostReturn
* @property {boolean} success - Did the function run successfully?
* @property {*} [payload] - GET request results
* @property {string} [msg] - Message
* @property {string} [error] - Error Message
*/
/**
* @typedef {Object} LocalPostQueryObject
* @property {string | import("../../utils/post").PostDataPayload} query - Table Name
* @property {string} [tableName] - Table Name
* @property {string[]} [queryValues] - GET request results
*/
/**
* Make a get request to Datasquirel API
* ==============================================================================
* @async
*
* @param {Object} params - Single object passed
* @param {LocalPostQueryObject} params.options - SQL Query
* @param {import("../../types/database-schema.td").DSQL_DatabaseSchemaType} [params.dbSchema] - Name of the table to query
*
* @returns { Promise<LocalPostReturn> } - Return Object
*/
async function localPost({ options, dbSchema }) {
try {
/**
* Grab Body
*/
const { query, tableName, queryValues } = options;
const dbFullName = process.env.DSQL_DB_NAME || "";
/**
* Input Validation
*
* @description Input Validation
*/
if (typeof query === "string" && query?.match(/^create |^alter |^drop /i)) {
return { success: false, msg: "Wrong Input" };
}
if (typeof query === "object" && query?.action?.match(/^create |^alter |^drop /i)) {
return { success: false, msg: "Wrong Input" };
}
/**
* Create new user folder and file
*
* @description Create new user folder and file
*/
try {
let { result, error } = await runQuery({
dbFullName: dbFullName,
query: query,
dbSchema: dbSchema,
queryValuesArray: queryValues,
tableName,
});
if (error) throw error;
return {
success: true,
payload: result,
error: error,
};
////////////////////////////////////////
} catch (/** @type {*} */ error) {
////////////////////////////////////////
return {
success: false,
payload: null,
error: error.message,
};
}
////////////////////////////////////////
} catch (/** @type {*} */ error) {
////////////////////////////////////////
console.log("Error in local post Request =>", error.message);
return {
success: false,
payload: null,
msg: "Something went wrong!",
};
////////////////////////////////////////
}
}
module.exports = localPost;
+143 -143
View File
@@ -1,143 +1,143 @@
// @ts-check
/**
* Imports
*/
const https = require("https");
const path = require("path");
const fs = require("fs");
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/**
* @typedef {Object} PostReturn
* @property {boolean} success - Did the function run successfully?
* @property {*} [payload] - The Y Coordinate
* @property {string} [error] - The Y Coordinate
*/
/**
* # Update API Schema From Local DB
*
* @async
*
* @returns { Promise<PostReturn> } - Return Object
*/
async function updateApiSchemaFromLocalDb() {
try {
/**
* Initialize
*/
const dbSchemaPath = path.resolve(process.cwd(), "dsql.schema.json");
const key = process.env.DSQL_KEY || "";
const dbSchema = JSON.parse(fs.readFileSync(dbSchemaPath, "utf8"));
/**
* Make https request
*
* @description make a request to datasquirel.com
*/
const httpResponse = await new Promise((resolve, reject) => {
const reqPayloadString = JSON.stringify({
schema: dbSchema,
}).replace(/\n|\r|\n\r/gm, "");
try {
JSON.parse(reqPayloadString);
} catch (error) {
console.log(error);
console.log(reqPayloadString);
return {
success: false,
payload: null,
error: "Query object is invalid. Please Check query data values",
};
}
const reqPayload = reqPayloadString;
const httpsRequest = https.request(
{
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": Buffer.from(reqPayload).length,
Authorization: key,
},
port: 443,
hostname: "datasquirel.com",
path: `/api/query/update-schema-from-single-database`,
},
/**
* Callback Function
*
* @description https request callback
*/
(response) => {
var str = "";
response.on("data", function (chunk) {
str += chunk;
});
response.on("end", function () {
try {
resolve(JSON.parse(str));
} catch (error) {
console.log(error);
console.log("Fetched Payload =>", str);
resolve({
success: false,
payload: null,
error: error,
});
}
});
response.on("error", (err) => {
resolve({
success: false,
payload: null,
error: err.message,
});
});
}
);
httpsRequest.write(reqPayload);
httpsRequest.on("error", (error) => {
console.log("HTTPS request ERROR =>", error);
});
httpsRequest.end();
});
/** ********************************************** */
/** ********************************************** */
/** ********************************************** */
return httpResponse;
} catch (/** @type {*} */ error) {
return {
success: false,
payload: null,
error: error.message,
};
}
}
/** ********************************************** */
/** ********************************************** */
/** ********************************************** */
module.exports = updateApiSchemaFromLocalDb;
// @ts-check
/**
* Imports
*/
const https = require("https");
const path = require("path");
const fs = require("fs");
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/** ****************************************************************************** */
/**
* @typedef {Object} PostReturn
* @property {boolean} success - Did the function run successfully?
* @property {*} [payload] - The Y Coordinate
* @property {string} [error] - The Y Coordinate
*/
/**
* # Update API Schema From Local DB
*
* @async
*
* @returns { Promise<PostReturn> } - Return Object
*/
async function updateApiSchemaFromLocalDb() {
try {
/**
* Initialize
*/
const dbSchemaPath = path.resolve(process.cwd(), "dsql.schema.json");
const key = process.env.DSQL_KEY || "";
const dbSchema = JSON.parse(fs.readFileSync(dbSchemaPath, "utf8"));
/**
* Make https request
*
* @description make a request to datasquirel.com
*/
const httpResponse = await new Promise((resolve, reject) => {
const reqPayloadString = JSON.stringify({
schema: dbSchema,
}).replace(/\n|\r|\n\r/gm, "");
try {
JSON.parse(reqPayloadString);
} catch (error) {
console.log(error);
console.log(reqPayloadString);
return {
success: false,
payload: null,
error: "Query object is invalid. Please Check query data values",
};
}
const reqPayload = reqPayloadString;
const httpsRequest = https.request(
{
method: "POST",
headers: {
"Content-Type": "application/json",
"Content-Length": Buffer.from(reqPayload).length,
Authorization: key,
},
port: 443,
hostname: "datasquirel.com",
path: `/api/query/update-schema-from-single-database`,
},
/**
* Callback Function
*
* @description https request callback
*/
(response) => {
var str = "";
response.on("data", function (chunk) {
str += chunk;
});
response.on("end", function () {
try {
resolve(JSON.parse(str));
} catch (error) {
console.log(error);
console.log("Fetched Payload =>", str);
resolve({
success: false,
payload: null,
error: error,
});
}
});
response.on("error", (err) => {
resolve({
success: false,
payload: null,
error: err.message,
});
});
}
);
httpsRequest.write(reqPayload);
httpsRequest.on("error", (error) => {
console.log("HTTPS request ERROR =>", error);
});
httpsRequest.end();
});
/** ********************************************** */
/** ********************************************** */
/** ********************************************** */
return httpResponse;
} catch (/** @type {*} */ error) {
return {
success: false,
payload: null,
error: error.message,
};
}
}
/** ********************************************** */
/** ********************************************** */
/** ********************************************** */
module.exports = updateApiSchemaFromLocalDb;
+162 -162
View File
@@ -1,162 +1,162 @@
// @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("../../../types/database-schema.td").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;
// @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("../../../types/database-schema.td").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;
+76 -76
View File
@@ -1,76 +1,76 @@
// @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("../../../types/database-schema.td").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;
// @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("../../../types/database-schema.td").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;
+165 -165
View File
@@ -1,165 +1,165 @@
/** # 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("../../../types/database-schema.td").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;
/** # 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("../../../types/database-schema.td").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;
+149 -149
View File
@@ -1,149 +1,149 @@
// @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("../../../types/database-schema.td").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;
// @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("../../../types/database-schema.td").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;