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,40 @@
type Param = {
dbContext?: "Master" | "Dsql User";
paradigm?: "Read Only" | "Full Access";
dbFullName?: string;
tableName: string;
data: any;
tableSchema?: import("../../../types").DSQL_TableSchemaType;
duplicateColumnName?: string;
duplicateColumnValue?: string;
update?: boolean;
encryptionKey?: string;
encryptionSalt?: string;
useLocal?: boolean;
};
/**
* Add a db Entry 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 {any} params.data - Data to add
* @param {import("../../../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
* @param {boolean} [params.useLocal]
*
* @returns {Promise<any>}
*/
export default function addDbEntry({ dbContext, paradigm, dbFullName, tableName, data, tableSchema, duplicateColumnName, duplicateColumnValue, update, encryptionKey, encryptionSalt, useLocal, }: Param): Promise<any>;
export {};
+209
View File
@@ -0,0 +1,209 @@
"use strict";
// @ts-check
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 = addDbEntry;
const sanitize_html_1 = __importDefault(require("sanitize-html"));
const sanitizeHtmlOptions_1 = __importDefault(require("../html/sanitizeHtmlOptions"));
const updateDbEntry_1 = __importDefault(require("./updateDbEntry"));
const DB_HANDLER_1 = __importDefault(require("../../../utils/backend/global-db/DB_HANDLER"));
const DSQL_USER_DB_HANDLER_1 = __importDefault(require("../../../utils/backend/global-db/DSQL_USER_DB_HANDLER"));
const encrypt_1 = __importDefault(require("../../dsql/encrypt"));
const LOCAL_DB_HANDLER_1 = __importDefault(require("../../../utils/backend/global-db/LOCAL_DB_HANDLER"));
/**
* Add a db Entry 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 {any} params.data - Data to add
* @param {import("../../../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
* @param {boolean} [params.useLocal]
*
* @returns {Promise<any>}
*/
function addDbEntry(_a) {
return __awaiter(this, arguments, void 0, function* ({ dbContext, paradigm, dbFullName, tableName, data, tableSchema, duplicateColumnName, duplicateColumnValue, update, encryptionKey, encryptionSalt, useLocal, }) {
var _b, _c;
/**
* Initialize variables
*/
const isMaster = useLocal
? true
: (dbContext === null || dbContext === void 0 ? void 0 : dbContext.match(/dsql.user/i))
? false
: dbFullName && !dbFullName.match(/^datasquirel$/)
? false
: true;
/** @type { any } */
const dbHandler = useLocal
? LOCAL_DB_HANDLER_1.default
: isMaster
? DB_HANDLER_1.default
: DSQL_USER_DB_HANDLER_1.default;
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
if (data === null || data === void 0 ? void 0 : data["date_created_timestamp"])
delete data["date_created_timestamp"];
if (data === null || data === void 0 ? void 0 : data["date_updated_timestamp"])
delete data["date_updated_timestamp"];
if (data === null || data === void 0 ? void 0 : data["date_updated"])
delete data["date_updated"];
if (data === null || data === void 0 ? void 0 : data["date_updated_code"])
delete data["date_updated_code"];
if (data === null || data === void 0 ? void 0 : data["date_created"])
delete data["date_created"];
if (data === null || data === void 0 ? void 0 : data["date_created_code"])
delete data["date_created_code"];
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
/**
* Handle function logic
*/
if (duplicateColumnName && typeof duplicateColumnName === "string") {
const duplicateValue = isMaster
? yield dbHandler(`SELECT * FROM \`${tableName}\` WHERE \`${duplicateColumnName}\`=?`, [duplicateColumnValue])
: yield dbHandler({
paradigm: "Read Only",
database: dbFullName,
queryString: `SELECT * FROM \`${tableName}\` WHERE \`${duplicateColumnName}\`=?`,
queryValues: [duplicateColumnValue],
});
if ((duplicateValue === null || duplicateValue === void 0 ? void 0 : duplicateValue[0]) && !update) {
return null;
}
else if (duplicateValue && duplicateValue[0] && update) {
return yield (0, updateDbEntry_1.default)({
dbContext,
paradigm,
dbFullName,
tableName,
data,
tableSchema,
encryptionKey,
encryptionSalt,
identifierColumnName: duplicateColumnName,
identifierValue: duplicateColumnValue || "",
});
}
}
/**
* 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];
// @ts-ignore
let value = data === null || data === void 0 ? void 0 : data[dataKey];
const targetFieldSchemaArray = tableSchema
? (_b = tableSchema === null || tableSchema === void 0 ? void 0 : tableSchema.fields) === null || _b === void 0 ? void 0 : _b.filter((field) => field.fieldName == dataKey)
: null;
const targetFieldSchema = targetFieldSchemaArray && targetFieldSchemaArray[0]
? targetFieldSchemaArray[0]
: null;
if (value == null || value == undefined)
continue;
if (((_c = targetFieldSchema === null || targetFieldSchema === void 0 ? void 0 : targetFieldSchema.dataType) === null || _c === void 0 ? void 0 : _c.match(/int$/i)) &&
typeof value == "string" &&
!(value === null || value === void 0 ? void 0 : value.match(/./)))
continue;
if (targetFieldSchema === null || targetFieldSchema === void 0 ? void 0 : targetFieldSchema.encrypted) {
value = (0, encrypt_1.default)({
data: value,
encryptionKey,
encryptionSalt,
});
console.log("DSQL: Encrypted value =>", value);
}
const htmlRegex = /<[^>]+>/g;
if ((targetFieldSchema === null || targetFieldSchema === void 0 ? void 0 : targetFieldSchema.richText) || String(value).match(htmlRegex)) {
value = (0, sanitize_html_1.default)(value, sanitizeHtmlOptions_1.default);
}
if (targetFieldSchema === null || targetFieldSchema === void 0 ? void 0 : targetFieldSchema.pattern) {
const pattern = new RegExp(targetFieldSchema.pattern, targetFieldSchema.patternFlags || "");
if (!pattern.test(value)) {
console.log("DSQL: Pattern not matched =>", value);
value = "";
}
}
insertKeysArray.push("`" + dataKey + "`");
if (typeof value === "object") {
value = JSON.stringify(value);
}
if (typeof value == "number") {
insertValuesArray.push(String(value));
}
else {
insertValuesArray.push(value);
}
}
catch ( /** @type {any} */error) {
console.log("DSQL: Error in parsing data keys =>", error.message);
continue;
}
}
////////////////////////////////////////
if (!(data === null || data === void 0 ? void 0 : data["date_created"])) {
insertKeysArray.push("`date_created`");
insertValuesArray.push(Date());
}
if (!(data === null || data === void 0 ? void 0 : data["date_created_code"])) {
insertKeysArray.push("`date_created_code`");
insertValuesArray.push(Date.now());
}
////////////////////////////////////////
if (!(data === null || data === void 0 ? void 0 : data["date_updated"])) {
insertKeysArray.push("`date_updated`");
insertValuesArray.push(Date());
}
if (!(data === null || data === void 0 ? void 0 : data["date_updated_code"])) {
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 = isMaster
? yield dbHandler(query, queryValuesArray)
: yield dbHandler({
paradigm,
database: dbFullName,
queryString: query,
queryValues: queryValuesArray,
});
/**
* Return statement
*/
return newInsert;
});
}
@@ -0,0 +1,16 @@
type Param = {
dbContext?: string;
paradigm?: "Read Only" | "Full Access";
dbFullName: string;
tableName: string;
tableSchema?: import("../../../types").DSQL_TableSchemaType;
identifierColumnName: string;
identifierValue: string | number;
useLocal?: boolean;
};
/**
* # Delete DB Entry Function
* @description
*/
export default function deleteDbEntry({ dbContext, paradigm, dbFullName, tableName, identifierColumnName, identifierValue, useLocal, }: Param): Promise<object | null>;
export {};
@@ -0,0 +1,62 @@
"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 = deleteDbEntry;
const DB_HANDLER_1 = __importDefault(require("../../../utils/backend/global-db/DB_HANDLER"));
const DSQL_USER_DB_HANDLER_1 = __importDefault(require("../../../utils/backend/global-db/DSQL_USER_DB_HANDLER"));
const LOCAL_DB_HANDLER_1 = __importDefault(require("../../../utils/backend/global-db/LOCAL_DB_HANDLER"));
/**
* # Delete DB Entry Function
* @description
*/
function deleteDbEntry(_a) {
return __awaiter(this, arguments, void 0, function* ({ dbContext, paradigm, dbFullName, tableName, identifierColumnName, identifierValue, useLocal, }) {
try {
const isMaster = useLocal
? true
: (dbContext === null || dbContext === void 0 ? void 0 : dbContext.match(/dsql.user/i))
? false
: dbFullName && !dbFullName.match(/^datasquirel$/)
? false
: true;
/** @type { (a1:any, a2?:any) => any } */
const dbHandler = useLocal
? LOCAL_DB_HANDLER_1.default
: isMaster
? DB_HANDLER_1.default
: DSQL_USER_DB_HANDLER_1.default;
/**
* Execution
*
* @description
*/
const query = `DELETE FROM ${tableName} WHERE \`${identifierColumnName}\`=?`;
const deletedEntry = isMaster
? yield dbHandler(query, [identifierValue])
: yield dbHandler({
paradigm,
queryString: query,
database: dbFullName,
queryValues: [identifierValue],
});
/**
* Return statement
*/
return deletedEntry;
}
catch (error) {
return null;
}
});
}
@@ -0,0 +1,5 @@
/**
* # Path Traversal Check
* @returns {string}
*/
export default function pathTraversalCheck(text: string | number): string;
@@ -0,0 +1,10 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = pathTraversalCheck;
/**
* # Path Traversal Check
* @returns {string}
*/
function pathTraversalCheck(text) {
return text.toString().replace(/\//g, "");
}
+14
View File
@@ -0,0 +1,14 @@
type Param = {
dbFullName: string;
query: string | any;
readOnly?: boolean;
local?: boolean;
dbSchema?: import("../../../types").DSQL_DatabaseSchemaType;
queryValuesArray?: (string | number)[];
tableName?: string;
};
/**
* # Run DSQL users queries
*/
export default function runQuery({ dbFullName, query, readOnly, dbSchema, queryValuesArray, tableName, local, }: Param): Promise<any>;
export {};
+155
View File
@@ -0,0 +1,155 @@
"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 = runQuery;
const fullAccessDbHandler_1 = __importDefault(require("../fullAccessDbHandler"));
const varReadOnlyDatabaseDbHandler_1 = __importDefault(require("../varReadOnlyDatabaseDbHandler"));
const serverError_1 = __importDefault(require("../serverError"));
const addDbEntry_1 = __importDefault(require("./addDbEntry"));
const updateDbEntry_1 = __importDefault(require("./updateDbEntry"));
const deleteDbEntry_1 = __importDefault(require("./deleteDbEntry"));
const trim_sql_1 = __importDefault(require("../../../utils/trim-sql"));
/**
* # Run DSQL users queries
*/
function runQuery(_a) {
return __awaiter(this, arguments, void 0, function* ({ dbFullName, query, readOnly, dbSchema, queryValuesArray, tableName, local, }) {
/**
* Declare variables
*
* @description Declare "results" variable
*/
let result;
let error;
let tableSchema;
if (dbSchema) {
try {
const table = tableName
? tableName
: typeof query == "string"
? null
: query
? query === null || query === void 0 ? void 0 : query.table
: null;
if (!table)
throw new Error("No table name provided");
tableSchema = dbSchema.tables.filter((tb) => (tb === null || tb === void 0 ? void 0 : tb.tableName) === table)[0];
}
catch (_err) {
// console.log("ERROR getting tableSchema: ", _err.message);
}
}
/**
* Declare variables
*
* @description Declare "results" variable
*/
try {
if (typeof query === "string") {
const formattedQuery = (0, trim_sql_1.default)(query);
/**
* Input Validation
*
* @description Input Validation
*/
if (readOnly &&
formattedQuery.match(/^alter|^delete|information_schema|^create/i)) {
throw new Error("Wrong Input!");
}
if (readOnly) {
result = yield (0, varReadOnlyDatabaseDbHandler_1.default)({
queryString: formattedQuery,
queryValuesArray: queryValuesArray === null || queryValuesArray === void 0 ? void 0 : queryValuesArray.map((vl) => String(vl)),
database: dbFullName,
tableSchema,
useLocal: local,
});
}
else {
result = yield (0, fullAccessDbHandler_1.default)({
queryString: formattedQuery,
queryValuesArray: queryValuesArray === null || queryValuesArray === void 0 ? void 0 : queryValuesArray.map((vl) => String(vl)),
database: dbFullName,
tableSchema,
local,
});
}
}
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 = yield (0, addDbEntry_1.default)({
dbContext: local ? "Master" : "Dsql User",
paradigm: "Full Access",
dbFullName: dbFullName,
tableName: table,
data: data,
update,
duplicateColumnName,
duplicateColumnValue,
tableSchema,
useLocal: local,
});
if (!(result === null || result === void 0 ? void 0 : result.insertId)) {
error = new Error("Couldn't insert data");
}
break;
case "update":
result = yield (0, updateDbEntry_1.default)({
dbContext: local ? "Master" : "Dsql User",
paradigm: "Full Access",
dbFullName: dbFullName,
tableName: table,
data: data,
identifierColumnName,
identifierValue,
tableSchema,
useLocal: local,
});
break;
case "delete":
result = yield (0, deleteDbEntry_1.default)({
dbContext: local ? "Master" : "Dsql User",
paradigm: "Full Access",
dbFullName: dbFullName,
tableName: table,
identifierColumnName,
identifierValue,
tableSchema,
useLocal: local,
});
break;
default:
result = null;
break;
}
}
}
catch ( /** @type {any} */error) {
(0, serverError_1.default)({
component: "functions/backend/runQuery",
message: error.message,
});
result = null;
error = error.message;
}
return { result, error };
});
}
@@ -0,0 +1,8 @@
/**
* Sanitize SQL function
* ==============================================================================
* @description this function takes in a text(or number) and returns a sanitized
* text, usually without spaces
*/
declare function sanitizeSql(text: any, spaces: boolean, regex?: RegExp | null): any;
export default sanitizeSql;
+111
View File
@@ -0,0 +1,111 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const lodash_1 = __importDefault(require("lodash"));
/**
* Sanitize SQL function
* ==============================================================================
* @description this function takes in a text(or number) and returns a sanitized
* text, usually without spaces
*/
function sanitizeSql(text, spaces, regex) {
var _a;
if (!text)
return "";
if (typeof text == "number" || typeof text == "boolean")
return text;
if (typeof text == "string" && !((_a = text === null || text === void 0 ? void 0 : text.toString()) === null || _a === void 0 ? void 0 : _a.match(/./)))
return "";
if (typeof text == "object" && !Array.isArray(text)) {
const newObject = sanitizeObjects(text, spaces);
return newObject;
}
else if (typeof text == "object" && Array.isArray(text)) {
const newArray = sanitizeArrays(text, spaces);
return newArray;
}
let finalText = text;
if (regex) {
finalText = text.toString().replace(regex, "");
}
if (spaces) {
}
else {
finalText = text
.toString()
.replace(/\n|\r|\n\r|\r\n/g, "")
.replace(/ /g, "");
}
const escapeRegex = /select |insert |drop |delete |alter |create |exec | union | or | like | concat|LOAD_FILE|ASCII| COLLATE | HAVING | information_schema|DECLARE |\#|WAITFOR |delay |BENCHMARK |\/\*.*\*\//gi;
finalText = finalText
.replace(/(?<!\\)\'/g, "\\'")
.replace(/(?<!\\)\`/g, "\\`")
.replace(/\/\*\*\//g, "")
.replace(escapeRegex, "\\$&");
return finalText;
}
/**
* Sanitize Objects Function
* ==============================================================================
* @description Sanitize objects in the form { key: "value" }
*
* @param {any} object - Database Full Name
* @param {boolean} [spaces] - Allow spaces
*
* @returns {object}
*/
function sanitizeObjects(object, spaces) {
/** @type {any} */
let objectUpdated = Object.assign({}, object);
const keys = Object.keys(objectUpdated);
keys.forEach((key) => {
const value = objectUpdated[key];
if (!value) {
delete objectUpdated[key];
return;
}
if (typeof value == "string" || typeof value == "number") {
objectUpdated[key] = sanitizeSql(value, spaces);
}
else if (typeof value == "object" && !Array.isArray(value)) {
objectUpdated[key] = sanitizeObjects(value, spaces);
}
else if (typeof value == "object" && Array.isArray(value)) {
objectUpdated[key] = sanitizeArrays(value, spaces);
}
});
return objectUpdated;
}
/**
* Sanitize Objects Function
* ==============================================================================
* @description Sanitize objects in the form { key: "value" }
*
* @param {any[]} array - Database Full Name
* @param {boolean} [spaces] - Allow spaces
*
* @returns {string[]|number[]|object[]}
*/
function sanitizeArrays(array, spaces) {
let arrayUpdated = lodash_1.default.cloneDeep(array);
arrayUpdated.forEach((item, index) => {
const value = item;
if (!value) {
arrayUpdated.splice(index, 1);
return;
}
if (typeof item == "string" || typeof item == "number") {
arrayUpdated[index] = sanitizeSql(value, spaces);
}
else if (typeof item == "object" && !Array.isArray(value)) {
arrayUpdated[index] = sanitizeObjects(value, spaces);
}
else if (typeof item == "object" && Array.isArray(value)) {
arrayUpdated[index] = sanitizeArrays(item, spaces);
}
});
return arrayUpdated;
}
exports.default = sanitizeSql;
@@ -0,0 +1,19 @@
type Param = {
dbContext?: "Master" | "Dsql User";
paradigm?: "Read Only" | "Full Access";
dbFullName?: string;
tableName: string;
encryptionKey?: string;
encryptionSalt?: string;
data: any;
tableSchema?: import("../../../types").DSQL_TableSchemaType;
identifierColumnName: string;
identifierValue: string | number;
useLocal?: boolean;
};
/**
* # Update DB Function
* @description
*/
export default function updateDbEntry({ dbContext, paradigm, dbFullName, tableName, data, tableSchema, identifierColumnName, identifierValue, encryptionKey, encryptionSalt, useLocal, }: Param): Promise<object | null>;
export {};
@@ -0,0 +1,144 @@
"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 = updateDbEntry;
const sanitize_html_1 = __importDefault(require("sanitize-html"));
const sanitizeHtmlOptions_1 = __importDefault(require("../html/sanitizeHtmlOptions"));
const DB_HANDLER_1 = __importDefault(require("../../../utils/backend/global-db/DB_HANDLER"));
const DSQL_USER_DB_HANDLER_1 = __importDefault(require("../../../utils/backend/global-db/DSQL_USER_DB_HANDLER"));
const encrypt_1 = __importDefault(require("../../dsql/encrypt"));
const LOCAL_DB_HANDLER_1 = __importDefault(require("../../../utils/backend/global-db/LOCAL_DB_HANDLER"));
/**
* # Update DB Function
* @description
*/
function updateDbEntry(_a) {
return __awaiter(this, arguments, void 0, function* ({ dbContext, paradigm, dbFullName, tableName, data, tableSchema, identifierColumnName, identifierValue, encryptionKey, encryptionSalt, useLocal, }) {
var _b;
/**
* Check if data is valid
*/
if (!data || !Object.keys(data).length)
return null;
const isMaster = useLocal
? true
: (dbContext === null || dbContext === void 0 ? void 0 : dbContext.match(/dsql.user/i))
? false
: dbFullName && !dbFullName.match(/^datasquirel$/)
? false
: true;
/** @type {(a1:any, a2?:any)=> any } */
const dbHandler = useLocal
? LOCAL_DB_HANDLER_1.default
: isMaster
? DB_HANDLER_1.default
: DSQL_USER_DB_HANDLER_1.default;
////////////////////////////////////////
////////////////////////////////////////
////////////////////////////////////////
/**
* Declare variables
*
* @description Declare "results" variable
*/
const dataKeys = Object.keys(data);
let updateKeyValueArray = [];
let updateValues = [];
for (let i = 0; i < dataKeys.length; i++) {
try {
const dataKey = dataKeys[i];
// @ts-ignore
let value = data[dataKey];
const targetFieldSchemaArray = tableSchema
? (_b = tableSchema === null || tableSchema === void 0 ? void 0 : tableSchema.fields) === null || _b === void 0 ? void 0 : _b.filter((field) => field.fieldName === dataKey)
: null;
const targetFieldSchema = targetFieldSchemaArray && targetFieldSchemaArray[0]
? targetFieldSchemaArray[0]
: null;
if (value == null || value == undefined)
continue;
const htmlRegex = /<[^>]+>/g;
if ((targetFieldSchema === null || targetFieldSchema === void 0 ? void 0 : targetFieldSchema.richText) || String(value).match(htmlRegex)) {
value = (0, sanitize_html_1.default)(value, sanitizeHtmlOptions_1.default);
}
if (targetFieldSchema === null || targetFieldSchema === void 0 ? void 0 : targetFieldSchema.encrypted) {
value = (0, encrypt_1.default)({
data: value,
encryptionKey,
encryptionSalt,
});
}
if (typeof value === "object") {
value = JSON.stringify(value);
}
if (targetFieldSchema === null || targetFieldSchema === void 0 ? void 0 : targetFieldSchema.pattern) {
const pattern = new RegExp(targetFieldSchema.pattern, targetFieldSchema.patternFlags || "");
if (!pattern.test(value)) {
console.log("DSQL: Pattern not matched =>", value);
value = "";
}
}
if (typeof value === "string" && value.match(/^null$/i)) {
value = {
toSqlString: function () {
return "NULL";
},
};
}
if (typeof value === "string" && !value.match(/./i)) {
value = {
toSqlString: function () {
return "NULL";
},
};
}
updateKeyValueArray.push(`\`${dataKey}\`=?`);
if (typeof value == "number") {
updateValues.push(String(value));
}
else {
updateValues.push(value);
}
////////////////////////////////////////
////////////////////////////////////////
}
catch ( /** @type {any} */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 = isMaster
? yield dbHandler(query, updateValues)
: yield dbHandler({
paradigm,
database: dbFullName,
queryString: query,
queryValues: updateValues,
});
/**
* Return statement
*/
return updatedEntry;
});
}