Updates
This commit is contained in:
+1
@@ -0,0 +1 @@
|
||||
export {};
|
||||
Vendored
+56
@@ -0,0 +1,56 @@
|
||||
"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 });
|
||||
require("dotenv").config({ path: "./../.env" });
|
||||
const serverless_mysql_1 = __importDefault(require("serverless-mysql"));
|
||||
const grabDbSSL_1 = __importDefault(require("../utils/backend/grabDbSSL"));
|
||||
const connection = (0, serverless_mysql_1.default)({
|
||||
config: {
|
||||
host: process.env.DSQL_DB_HOST,
|
||||
user: process.env.DSQL_DB_USERNAME,
|
||||
password: process.env.DSQL_DB_PASSWORD,
|
||||
database: process.env.DSQL_DB_NAME,
|
||||
charset: "utf8mb4",
|
||||
ssl: (0, grabDbSSL_1.default)(),
|
||||
},
|
||||
});
|
||||
/**
|
||||
* # Main DB Handler Function
|
||||
* @async
|
||||
*
|
||||
* @param {object} params
|
||||
* @param {string} params.query
|
||||
* @param {string[] | object} [params.values]
|
||||
* @param {string} [params.database]
|
||||
*
|
||||
* @returns {Promise<object|null>}
|
||||
*/
|
||||
(() => __awaiter(void 0, void 0, void 0, function* () {
|
||||
/**
|
||||
* Switch Database
|
||||
*
|
||||
* @description If a database is provided, switch to it
|
||||
*/
|
||||
try {
|
||||
const result = yield connection.query("SELECT id,first_name,last_name FROM users LIMIT 3");
|
||||
console.log("Connection Query Success =>", result);
|
||||
}
|
||||
catch (error) {
|
||||
console.log("Connection query ERROR =>", error.message);
|
||||
}
|
||||
finally {
|
||||
connection.end();
|
||||
process.exit();
|
||||
}
|
||||
}))();
|
||||
@@ -0,0 +1,10 @@
|
||||
type Param = {
|
||||
userId?: number | string | null;
|
||||
targetDatabase?: string;
|
||||
dbSchemaData?: import("../types").DSQL_DatabaseSchemaType[];
|
||||
};
|
||||
/**
|
||||
* # Create database from Schema Function
|
||||
*/
|
||||
export default function createDbFromSchema({ userId, targetDatabase, dbSchemaData, }: Param): Promise<void>;
|
||||
export {};
|
||||
+245
@@ -0,0 +1,245 @@
|
||||
"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 = createDbFromSchema;
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
require("dotenv").config({ path: "./../.env" });
|
||||
const noDatabaseDbHandler_1 = __importDefault(require("./utils/noDatabaseDbHandler"));
|
||||
const varDatabaseDbHandler_1 = __importDefault(require("./utils/varDatabaseDbHandler"));
|
||||
const createTable_1 = __importDefault(require("./utils/createTable"));
|
||||
const updateTable_1 = __importDefault(require("./utils/updateTable"));
|
||||
const dbHandler_1 = __importDefault(require("./utils/dbHandler"));
|
||||
const ejson_1 = __importDefault(require("../utils/ejson"));
|
||||
const execFlag = process.argv.find((arg) => arg === "--exec");
|
||||
/**
|
||||
* # Create database from Schema Function
|
||||
*/
|
||||
function createDbFromSchema(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ userId, targetDatabase, dbSchemaData, }) {
|
||||
var _b, _c;
|
||||
const schemaPath = userId
|
||||
? path_1.default.join(String(process.env.DSQL_USER_DB_SCHEMA_PATH), `/user-${userId}/main.json`)
|
||||
: path_1.default.resolve(__dirname, "../../jsonData/dbSchemas/main.json");
|
||||
const dbSchema = dbSchemaData ||
|
||||
ejson_1.default.parse(fs_1.default.readFileSync(schemaPath, "utf8"));
|
||||
if (!dbSchema) {
|
||||
console.log("Schema Not Found!");
|
||||
return;
|
||||
}
|
||||
// await createDatabasesFromSchema(dbSchema);
|
||||
for (let i = 0; i < dbSchema.length; i++) {
|
||||
/** @type {import("../types").DSQL_DatabaseSchemaType} */
|
||||
const database = dbSchema[i];
|
||||
const { dbFullName, tables, dbName, dbSlug, childrenDatabases } = database;
|
||||
if (targetDatabase && dbFullName != targetDatabase) {
|
||||
continue;
|
||||
}
|
||||
/** @type {any} */
|
||||
const dbCheck = yield (0, noDatabaseDbHandler_1.default)(`SELECT SCHEMA_NAME AS dbFullName FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '${dbFullName}'`);
|
||||
if (dbCheck && ((_b = dbCheck[0]) === null || _b === void 0 ? void 0 : _b.dbFullName)) {
|
||||
// Database Exists
|
||||
}
|
||||
else {
|
||||
const newDatabase = yield (0, noDatabaseDbHandler_1.default)(`CREATE DATABASE IF NOT EXISTS \`${dbFullName}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_bin`);
|
||||
}
|
||||
/**
|
||||
* Select all tables
|
||||
* @type {any}
|
||||
* @description Select All tables in target database
|
||||
*/
|
||||
const allTables = yield (0, noDatabaseDbHandler_1.default)(`SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA='${dbFullName}'`);
|
||||
// let tableDropped;
|
||||
for (let tb = 0; tb < allTables.length; tb++) {
|
||||
const { TABLE_NAME } = allTables[tb];
|
||||
/**
|
||||
* @description Check if TABLE_NAME is part of the tables contained
|
||||
* in the user schema JSON. If it's not, the table is either deleted
|
||||
* or the table name has been recently changed
|
||||
*/
|
||||
if (!tables.filter((_table) => _table.tableName === TABLE_NAME)[0]) {
|
||||
const oldTableFilteredArray = tables.filter((_table) => _table.tableNameOld &&
|
||||
_table.tableNameOld === TABLE_NAME);
|
||||
/**
|
||||
* @description Check if this table has been recently renamed. Rename
|
||||
* table id true. Drop table if false
|
||||
*/
|
||||
if (oldTableFilteredArray && oldTableFilteredArray[0]) {
|
||||
console.log("Renaming Table");
|
||||
yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: `RENAME TABLE \`${oldTableFilteredArray[0].tableNameOld}\` TO \`${oldTableFilteredArray[0].tableName}\``,
|
||||
database: dbFullName,
|
||||
});
|
||||
}
|
||||
else {
|
||||
console.log(`Dropping Table from ${dbFullName}`);
|
||||
yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: `DROP TABLE \`${TABLE_NAME}\``,
|
||||
database: dbFullName,
|
||||
});
|
||||
const deleteTableEntry = yield (0, dbHandler_1.default)({
|
||||
query: `DELETE FROM user_database_tables WHERE user_id = ? AND db_slug = ? AND table_slug = ?`,
|
||||
values: [userId, dbSlug, TABLE_NAME],
|
||||
database: "datasquirel",
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
const recordedDbEntryArray = userId
|
||||
? yield (0, varDatabaseDbHandler_1.default)({
|
||||
database: "datasquirel",
|
||||
queryString: `SELECT * FROM user_databases WHERE db_full_name = ?`,
|
||||
queryValuesArray: [dbFullName],
|
||||
})
|
||||
: undefined;
|
||||
const recordedDbEntry = recordedDbEntryArray === null || recordedDbEntryArray === void 0 ? void 0 : recordedDbEntryArray[0];
|
||||
/**
|
||||
* @description Iterate through each table and perform table actions
|
||||
*/
|
||||
for (let t = 0; t < tables.length; t++) {
|
||||
const table = tables[t];
|
||||
const { tableName, fields, indexes } = table;
|
||||
/**
|
||||
* @description Check if table exists
|
||||
* @type {any}
|
||||
*/
|
||||
const tableCheck = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: `
|
||||
SELECT EXISTS (
|
||||
SELECT
|
||||
TABLE_NAME
|
||||
FROM
|
||||
information_schema.TABLES
|
||||
WHERE
|
||||
TABLE_SCHEMA = ? AND
|
||||
TABLE_NAME = ?
|
||||
) AS tableExists`,
|
||||
queryValuesArray: [dbFullName, table.tableName],
|
||||
database: dbFullName,
|
||||
});
|
||||
////////////////////////////////////////
|
||||
if (tableCheck && ((_c = tableCheck[0]) === null || _c === void 0 ? void 0 : _c.tableExists) > 0) {
|
||||
/**
|
||||
* @description Update table if table exists
|
||||
*/
|
||||
const updateExistingTable = yield (0, updateTable_1.default)({
|
||||
dbFullName: dbFullName,
|
||||
tableName: tableName,
|
||||
tableNameFull: table.tableFullName,
|
||||
tableInfoArray: fields,
|
||||
userId,
|
||||
dbSchema,
|
||||
tableIndexes: indexes,
|
||||
tableIndex: t,
|
||||
childDb: database.childDatabase || undefined,
|
||||
recordedDbEntry,
|
||||
tableSchema: table,
|
||||
});
|
||||
if (table.childrenTables && table.childrenTables[0]) {
|
||||
for (let ch = 0; ch < table.childrenTables.length; ch++) {
|
||||
const childTable = table.childrenTables[ch];
|
||||
const updateExistingChildTable = yield (0, updateTable_1.default)({
|
||||
dbFullName: childTable.dbNameFull,
|
||||
tableName: childTable.tableName,
|
||||
tableNameFull: childTable.tableNameFull,
|
||||
tableInfoArray: fields,
|
||||
userId,
|
||||
dbSchema,
|
||||
tableIndexes: indexes,
|
||||
clone: true,
|
||||
childDb: database.childDatabase || undefined,
|
||||
recordedDbEntry,
|
||||
tableSchema: table,
|
||||
});
|
||||
}
|
||||
}
|
||||
////////////////////////////////////////
|
||||
}
|
||||
else {
|
||||
////////////////////////////////////////
|
||||
/**
|
||||
* @description Create new Table if table doesnt exist
|
||||
*/
|
||||
const createNewTable = yield (0, createTable_1.default)({
|
||||
tableName: tableName,
|
||||
tableInfoArray: fields,
|
||||
dbFullName: dbFullName,
|
||||
dbSchema,
|
||||
tableSchema: table,
|
||||
recordedDbEntry,
|
||||
});
|
||||
if (indexes && indexes[0]) {
|
||||
/**
|
||||
* Handle DATASQUIREL Table Indexes
|
||||
* ===================================================
|
||||
* @description Iterate through each datasquirel schema
|
||||
* table index(if available), and perform operations
|
||||
*/
|
||||
if (indexes && indexes[0]) {
|
||||
for (let g = 0; g < indexes.length; g++) {
|
||||
const { indexType, indexName, indexTableFields, alias, } = indexes[g];
|
||||
if (!(alias === null || alias === void 0 ? void 0 : alias.match(/./)))
|
||||
continue;
|
||||
/**
|
||||
* @description Check for existing Index in MYSQL db
|
||||
*/
|
||||
try {
|
||||
/**
|
||||
* @type {import("../types").DSQL_MYSQL_SHOW_INDEXES_Type[]}
|
||||
* @description All indexes from MYSQL db
|
||||
*/ // @ts-ignore
|
||||
const allExistingIndexes = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: `SHOW INDEXES FROM \`${tableName}\``,
|
||||
database: dbFullName,
|
||||
});
|
||||
const existingKeyInDb = allExistingIndexes.filter((indexObject) => indexObject.Key_name === alias);
|
||||
if (!existingKeyInDb[0])
|
||||
throw new Error("This Index Does not Exist");
|
||||
}
|
||||
catch (error) {
|
||||
/**
|
||||
* @description Create new index if determined that it
|
||||
* doesn't exist in MYSQL db
|
||||
*/
|
||||
yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: `CREATE${(indexType === null || indexType === void 0 ? void 0 : indexType.match(/fullText/i))
|
||||
? " FULLTEXT"
|
||||
: ""} INDEX \`${alias}\` ON ${tableName}(${indexTableFields === null || indexTableFields === void 0 ? void 0 : indexTableFields.map((nm) => nm.value).map((nm) => `\`${nm}\``).join(",")}) COMMENT 'schema_index'`,
|
||||
database: dbFullName,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
* @description Check all children databases
|
||||
*/
|
||||
if (childrenDatabases === null || childrenDatabases === void 0 ? void 0 : childrenDatabases[0]) {
|
||||
for (let ch = 0; ch < childrenDatabases.length; ch++) {
|
||||
const childDb = childrenDatabases[ch];
|
||||
const { dbFullName } = childDb;
|
||||
yield createDbFromSchema({
|
||||
userId,
|
||||
targetDatabase: dbFullName,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
if (execFlag) {
|
||||
createDbFromSchema({});
|
||||
}
|
||||
+1
@@ -0,0 +1 @@
|
||||
export {};
|
||||
Vendored
+15
@@ -0,0 +1,15 @@
|
||||
"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());
|
||||
});
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
function deploy() {
|
||||
return __awaiter(this, void 0, void 0, function* () { });
|
||||
}
|
||||
deploy();
|
||||
@@ -0,0 +1 @@
|
||||
export {};
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
"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 });
|
||||
require("dotenv").config({ path: "./../.env" });
|
||||
const varDatabaseDbHandler_1 = __importDefault(require("../functions/backend/varDatabaseDbHandler"));
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/**
|
||||
* Grab Schema
|
||||
*
|
||||
* @description Grab Schema
|
||||
*/
|
||||
(0, varDatabaseDbHandler_1.default)({
|
||||
queryString: `SELECT user_database_tables.*,user_databases.db_full_name FROM user_database_tables JOIN user_databases ON user_database_tables.db_id=user_databases.id`,
|
||||
database: "datasquirel",
|
||||
}).then((tables) => __awaiter(void 0, void 0, void 0, function* () {
|
||||
for (let i = 0; i < tables.length; i++) {
|
||||
const table = tables[i];
|
||||
const { id, user_id, db_id, db_full_name, table_name, table_slug, table_description, } = table;
|
||||
const tableInfo = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: `SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='${db_full_name}' AND TABLE_NAME='${table_slug}'`,
|
||||
database: db_full_name,
|
||||
});
|
||||
const updateDbCharset = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: `ALTER DATABASE ${db_full_name} CHARACTER SET = utf8mb4 COLLATE = utf8mb4_bin;`,
|
||||
database: db_full_name,
|
||||
});
|
||||
const updateEncoding = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: `ALTER TABLE \`${table_slug}\` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_bin`,
|
||||
database: db_full_name,
|
||||
});
|
||||
}
|
||||
process.exit();
|
||||
}));
|
||||
@@ -0,0 +1 @@
|
||||
export {};
|
||||
@@ -0,0 +1,10 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const jsonFile = path_1.default.resolve(__dirname, "../../jsonData/userPriviledges.json");
|
||||
const base64File = Buffer.from(fs_1.default.readFileSync(jsonFile, "utf8")).toString("base64");
|
||||
console.log(base64File);
|
||||
@@ -0,0 +1 @@
|
||||
export {};
|
||||
@@ -0,0 +1,52 @@
|
||||
"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 });
|
||||
require("dotenv").config({ path: "./../.env" });
|
||||
const serverError_1 = __importDefault(require("../functions/backend/serverError"));
|
||||
const noDatabaseDbHandler_1 = __importDefault(require("./utils/noDatabaseDbHandler"));
|
||||
/**
|
||||
* # Create Database From Schema
|
||||
*/
|
||||
function grantFullPrivileges(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ userId }) {
|
||||
/**
|
||||
* Grab Schema
|
||||
*
|
||||
* @description Grab Schema
|
||||
*/
|
||||
try {
|
||||
const defaultMariadbUserHost = process.env.DSQL_DB_HOST || "127.0.0.1";
|
||||
const allDatabases = yield (0, noDatabaseDbHandler_1.default)(`SHOW DATABASES`);
|
||||
const datasquirelUserDatabases = allDatabases.filter((/** @type {any} */ database) => database.Database.match(/datasquirel_user_/));
|
||||
for (let i = 0; i < datasquirelUserDatabases.length; i++) {
|
||||
const datasquirelUserDatabase = datasquirelUserDatabases[i];
|
||||
const { Database } = datasquirelUserDatabase;
|
||||
const grantDbPriviledges = yield (0, noDatabaseDbHandler_1.default)(`GRANT ALL PRIVILEGES ON ${Database}.* TO '${process.env.DSQL_DB_FULL_ACCESS_USERNAME}'@'%' WITH GRANT OPTION`);
|
||||
const grantRead = yield (0, noDatabaseDbHandler_1.default)(`GRANT SELECT ON ${Database}.* TO '${process.env.DSQL_DB_READ_ONLY_USERNAME}'@'%'`);
|
||||
}
|
||||
const flushPriviledged = yield (0, noDatabaseDbHandler_1.default)(`FLUSH PRIVILEGES`);
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
(0, serverError_1.default)({
|
||||
component: "shell/grantDbPriviledges/main-catch-error",
|
||||
message: error.message,
|
||||
user: { id: userId },
|
||||
});
|
||||
}
|
||||
process.exit();
|
||||
});
|
||||
}
|
||||
const userArg = process.argv[process.argv.indexOf("--user")];
|
||||
const externalUser = process.argv[process.argv.indexOf("--user") + 1];
|
||||
grantFullPrivileges({ userId: userArg ? externalUser : null });
|
||||
+1
@@ -0,0 +1 @@
|
||||
export {};
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const child_process_1 = require("child_process");
|
||||
require("dotenv").config({ path: "./../.env" });
|
||||
const sourceFile = process.argv.indexOf("--src") >= 0
|
||||
? process.argv[process.argv.indexOf("--src") + 1]
|
||||
: null;
|
||||
const destinationFile = process.argv.indexOf("--dst") >= 0
|
||||
? process.argv[process.argv.indexOf("--dst") + 1]
|
||||
: null;
|
||||
console.log("Running Less compiler ...");
|
||||
const sourceFiles = sourceFile === null || sourceFile === void 0 ? void 0 : sourceFile.split(",");
|
||||
const dstFiles = destinationFile === null || destinationFile === void 0 ? void 0 : destinationFile.split(",");
|
||||
if (!sourceFiles || !dstFiles) {
|
||||
throw new Error("No Source or Destination Files!");
|
||||
}
|
||||
for (let i = 0; i < sourceFiles.length; i++) {
|
||||
const srcFolder = sourceFiles[i];
|
||||
const dstFile = dstFiles[i];
|
||||
fs_1.default.watch(srcFolder, { recursive: true }, (evtType, prev) => {
|
||||
if ((prev === null || prev === void 0 ? void 0 : prev.match(/\(/)) || (prev === null || prev === void 0 ? void 0 : prev.match(/\.js$/i))) {
|
||||
return;
|
||||
}
|
||||
let finalSrcPath = `${srcFolder}/main.less`;
|
||||
let finalDstPath = dstFile;
|
||||
if (prev === null || prev === void 0 ? void 0 : prev.match(/\[/)) {
|
||||
const paths = prev.split("/");
|
||||
const targetPathFull = paths[paths.length - 1];
|
||||
const targetPath = targetPathFull
|
||||
.replace(/\[|\]/g, "")
|
||||
.replace(/\.less/, "");
|
||||
const destinationFileParentFolder = dstFile.replace(/\/[^\/]+\.css$/, "");
|
||||
const targetDstFilePath = `${destinationFileParentFolder}/${targetPath}.css`;
|
||||
finalSrcPath = `${srcFolder}/${targetPathFull}`;
|
||||
finalDstPath = targetDstFilePath;
|
||||
}
|
||||
(0, child_process_1.exec)(`lessc ${finalSrcPath} ${(finalDstPath === null || finalDstPath === void 0 ? void 0 : finalDstPath.match(/\.css$/))
|
||||
? finalDstPath
|
||||
: finalDstPath.replace(/\/$/, "") + "/_main.css"}`, (error, stdout, stderr) => {
|
||||
if (error) {
|
||||
console.log("ERROR =>", error.message);
|
||||
if (!(evtType === null || evtType === void 0 ? void 0 : evtType.match(/change/i)) && (prev === null || prev === void 0 ? void 0 : prev.match(/\[/))) {
|
||||
fs_1.default.unlinkSync(finalDstPath);
|
||||
}
|
||||
return;
|
||||
}
|
||||
console.log("Less Compilation \x1b[32msuccessful\x1b[0m!");
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
export interface GrantType {
|
||||
database: string;
|
||||
table: string;
|
||||
privileges: string[];
|
||||
}
|
||||
type Param = {
|
||||
username: string;
|
||||
host: string;
|
||||
grants: GrantType[];
|
||||
userId: string;
|
||||
};
|
||||
/**
|
||||
* # Handle Grants for Users
|
||||
*/
|
||||
export default function handleGrants({ username, host, grants, userId, }: Param): Promise<boolean>;
|
||||
export {};
|
||||
@@ -0,0 +1,77 @@
|
||||
"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 = handleGrants;
|
||||
const noDatabaseDbHandler_1 = __importDefault(require("../utils/noDatabaseDbHandler"));
|
||||
/**
|
||||
* # Handle Grants for Users
|
||||
*/
|
||||
function handleGrants(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ username, host, grants, userId, }) {
|
||||
var _b;
|
||||
let success = false;
|
||||
console.log(`Handling Grants for User =>`, username, host);
|
||||
if (!username) {
|
||||
console.log(`No username provided.`);
|
||||
return success;
|
||||
}
|
||||
if (!host) {
|
||||
console.log(`No Host provided. \x1b[35m\`--host\`\x1b[0m flag is required`);
|
||||
return success;
|
||||
}
|
||||
if (!grants) {
|
||||
console.log(`No grants Array provided.`);
|
||||
return success;
|
||||
}
|
||||
try {
|
||||
const existingUser = yield (0, noDatabaseDbHandler_1.default)(`SELECT * FROM mysql.user WHERE User = '${username}' AND Host = '${host}'`);
|
||||
const isUserExisting = Boolean((_b = existingUser === null || existingUser === void 0 ? void 0 : existingUser[0]) === null || _b === void 0 ? void 0 : _b.User);
|
||||
if (isUserExisting) {
|
||||
const userGrants = yield (0, noDatabaseDbHandler_1.default)(`SHOW GRANTS FOR '${username}'@'${host}'`);
|
||||
for (let i = 0; i < userGrants.length; i++) {
|
||||
const grantObject = userGrants[i];
|
||||
const grant = grantObject === null || grantObject === void 0 ? void 0 : grantObject[Object.keys(grantObject)[0]];
|
||||
if (grant === null || grant === void 0 ? void 0 : grant.match(/GRANT .* PRIVILEGES ON .* TO/)) {
|
||||
const revokeGrantText = grant
|
||||
.replace(/GRANT/, "REVOKE")
|
||||
.replace(/ TO /, " FROM ");
|
||||
const revokePrivilege = yield (0, noDatabaseDbHandler_1.default)(revokeGrantText);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* @type {GrantType[]}
|
||||
*/
|
||||
const grantsArray = grants;
|
||||
for (let i = 0; i < grantsArray.length; i++) {
|
||||
const grantObject = grantsArray[i];
|
||||
const { database, table, privileges } = grantObject;
|
||||
const tableText = table == "*" ? "*" : `\`${table}\``;
|
||||
const databaseText = database == "*"
|
||||
? `\`${process.env.DSQL_USER_DB_PREFIX}${userId}_%\``
|
||||
: `\`${database}\``;
|
||||
const privilegesText = privileges.includes("ALL")
|
||||
? "ALL PRIVILEGES"
|
||||
: privileges.join(", ");
|
||||
const grantText = `GRANT ${privilegesText} ON ${databaseText}.${tableText} TO '${username}'@'${host}'`;
|
||||
const grantPriviledge = yield (0, noDatabaseDbHandler_1.default)(grantText);
|
||||
}
|
||||
}
|
||||
success = true;
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
console.log(`Error in adding SQL user =>`, error.message);
|
||||
}
|
||||
return success;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
type Param = {
|
||||
userId?: number | string;
|
||||
mariadbUserHost?: string;
|
||||
mariadbUser?: string;
|
||||
sqlUserID?: string | number;
|
||||
};
|
||||
/**
|
||||
* # Refresh Mariadb User Grants
|
||||
*/
|
||||
export default function refreshUsersAndGrants({ userId, mariadbUserHost, mariadbUser, sqlUserID, }: Param): Promise<void>;
|
||||
export {};
|
||||
@@ -0,0 +1,195 @@
|
||||
"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 = refreshUsersAndGrants;
|
||||
const path_1 = __importDefault(require("path"));
|
||||
require("dotenv").config({ path: path_1.default.resolve(__dirname, "../../../.env") });
|
||||
const generate_password_1 = __importDefault(require("generate-password"));
|
||||
const noDatabaseDbHandler_1 = __importDefault(require("../utils/noDatabaseDbHandler"));
|
||||
const dbHandler_1 = __importDefault(require("../utils/dbHandler"));
|
||||
const handleGrants_1 = __importDefault(require("./handleGrants"));
|
||||
const encrypt_1 = __importDefault(require("../../functions/dsql/encrypt"));
|
||||
const decrypt_1 = __importDefault(require("../../functions/dsql/decrypt"));
|
||||
const defaultMariadbUserHost = process.env.DSQL_DB_HOST || "127.0.0.1";
|
||||
/**
|
||||
* # Refresh Mariadb User Grants
|
||||
*/
|
||||
function refreshUsersAndGrants(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ userId, mariadbUserHost, mariadbUser, sqlUserID, }) {
|
||||
var _b, _c, _d, _e;
|
||||
/**
|
||||
* @description Users
|
||||
* @type {*[] | null}
|
||||
*/ // @ts-ignore
|
||||
const users = yield (0, dbHandler_1.default)({
|
||||
query: `SELECT * FROM users`,
|
||||
});
|
||||
if (!(users === null || users === void 0 ? void 0 : users[0])) {
|
||||
process.exit();
|
||||
}
|
||||
for (let i = 0; i < users.length; i++) {
|
||||
const user = users[i];
|
||||
if (!user)
|
||||
continue;
|
||||
if (userId && user.id != userId)
|
||||
continue;
|
||||
try {
|
||||
const { mariadb_user, mariadb_host, mariadb_pass, id } = user;
|
||||
const existingUser = yield (0, noDatabaseDbHandler_1.default)(`SELECT * FROM mysql.user WHERE User = '${mariadb_user}' AND Host = '${mariadb_host}'`);
|
||||
const existingMariaDBUserArray = userId && sqlUserID
|
||||
? yield (0, dbHandler_1.default)({
|
||||
query: `SELECT * FROM mariadb_users WHERE id = ? AND user_id = ?`,
|
||||
values: [sqlUserID, userId],
|
||||
})
|
||||
: null;
|
||||
/**
|
||||
* @type {import("../../types").MYSQL_mariadb_users_table_def | undefined}
|
||||
*/
|
||||
const activeMariadbUserObject = Array.isArray(existingMariaDBUserArray)
|
||||
? existingMariaDBUserArray === null || existingMariaDBUserArray === void 0 ? void 0 : existingMariaDBUserArray[0]
|
||||
: undefined;
|
||||
const isPrimary = activeMariadbUserObject
|
||||
? ((_b = String(activeMariadbUserObject.primary)) === null || _b === void 0 ? void 0 : _b.match(/1/))
|
||||
? true
|
||||
: false
|
||||
: false;
|
||||
const isUserExisting = Boolean((_c = existingUser === null || existingUser === void 0 ? void 0 : existingUser[0]) === null || _c === void 0 ? void 0 : _c.User);
|
||||
const isThisPrimaryHost = Boolean(mariadbUserHost == defaultMariadbUserHost);
|
||||
const dslUsername = `dsql_user_${id}`;
|
||||
const dsqlPassword = (activeMariadbUserObject === null || activeMariadbUserObject === void 0 ? void 0 : activeMariadbUserObject.password)
|
||||
? activeMariadbUserObject.password
|
||||
: isUserExisting
|
||||
? mariadb_pass
|
||||
: generate_password_1.default.generate({
|
||||
length: 16,
|
||||
numbers: true,
|
||||
symbols: true,
|
||||
uppercase: true,
|
||||
exclude: "*#.'`\"",
|
||||
});
|
||||
const encryptedPassword = (activeMariadbUserObject === null || activeMariadbUserObject === void 0 ? void 0 : activeMariadbUserObject.password)
|
||||
? activeMariadbUserObject.password
|
||||
: isUserExisting
|
||||
? mariadb_pass
|
||||
: (0, encrypt_1.default)({
|
||||
data: dsqlPassword,
|
||||
encryptionKey: process.env.DSQL_ENCRYPTION_PASSWORD,
|
||||
encryptionSalt: process.env.DSQL_ENCRYPTION_SALT,
|
||||
});
|
||||
if (!isUserExisting &&
|
||||
!sqlUserID &&
|
||||
!isPrimary &&
|
||||
!mariadbUserHost &&
|
||||
!mariadbUser) {
|
||||
const createNewUser = yield (0, noDatabaseDbHandler_1.default)(`CREATE USER IF NOT EXISTS '${dslUsername}'@'${defaultMariadbUserHost}' IDENTIFIED BY '${dsqlPassword}'`);
|
||||
console.log("createNewUser", createNewUser);
|
||||
console.log(`User ${user.id}: ${user.first_name} ${user.last_name} SQL credentials successfully updated.`);
|
||||
const updateUser = yield (0, dbHandler_1.default)({
|
||||
query: `UPDATE users SET mariadb_user = ?, mariadb_host = ?, mariadb_pass = ? WHERE id = ?`,
|
||||
values: [
|
||||
dslUsername,
|
||||
defaultMariadbUserHost,
|
||||
encryptedPassword,
|
||||
user.id,
|
||||
],
|
||||
});
|
||||
}
|
||||
if (isPrimary) {
|
||||
const finalHost = mariadbUserHost
|
||||
? mariadbUserHost
|
||||
: mariadb_host;
|
||||
const updateUser = yield (0, dbHandler_1.default)({
|
||||
query: `UPDATE users SET mariadb_user = ?, mariadb_host = ?, mariadb_pass = ? WHERE id = ?`,
|
||||
values: [
|
||||
dslUsername,
|
||||
finalHost,
|
||||
encryptedPassword,
|
||||
user.id,
|
||||
],
|
||||
});
|
||||
}
|
||||
//////////////////////////////////////////////
|
||||
//////////////////////////////////////////////
|
||||
//////////////////////////////////////////////
|
||||
/**
|
||||
* @description Handle mariadb_users table
|
||||
*/
|
||||
const existingMariadbPrimaryUser = yield (0, dbHandler_1.default)({
|
||||
query: `SELECT * FROM mariadb_users WHERE user_id = ? AND \`primary\` = 1`,
|
||||
values: [id],
|
||||
});
|
||||
const isPrimaryUserExisting = Boolean(Array.isArray(existingMariadbPrimaryUser) &&
|
||||
((_d = existingMariadbPrimaryUser === null || existingMariadbPrimaryUser === void 0 ? void 0 : existingMariadbPrimaryUser[0]) === null || _d === void 0 ? void 0 : _d.user_id));
|
||||
const primaryUserGrants = [
|
||||
{
|
||||
database: "*",
|
||||
table: "*",
|
||||
privileges: ["ALL"],
|
||||
},
|
||||
];
|
||||
if (!isPrimaryUserExisting) {
|
||||
const insertPrimaryMariadbUser = yield (0, dbHandler_1.default)({
|
||||
query: `INSERT INTO mariadb_users (user_id, username, password, \`primary\`, grants) VALUES (?, ?, ?, ?, ?)`,
|
||||
values: [
|
||||
id,
|
||||
dslUsername,
|
||||
encryptedPassword,
|
||||
"1",
|
||||
JSON.stringify(primaryUserGrants),
|
||||
],
|
||||
});
|
||||
}
|
||||
//////////////////////////////////////////////
|
||||
const existingExtraMariadbUsers = yield (0, dbHandler_1.default)({
|
||||
query: `SELECT * FROM mariadb_users WHERE user_id = ? AND \`primary\` != '1'`,
|
||||
values: [id],
|
||||
});
|
||||
if (Array.isArray(existingExtraMariadbUsers)) {
|
||||
for (let i = 0; i < existingExtraMariadbUsers.length; i++) {
|
||||
const mariadbUser = existingExtraMariadbUsers[i];
|
||||
const { user_id, username, host, password, primary, grants, } = mariadbUser;
|
||||
if (mariadbUser && username != mariadbUser)
|
||||
continue;
|
||||
if (mariadbUserHost && host != mariadbUserHost)
|
||||
continue;
|
||||
const decrptedPassword = (0, decrypt_1.default)({
|
||||
encryptedString: password,
|
||||
encryptionKey: process.env.DSQL_ENCRYPTION_PASSWORD,
|
||||
encryptionSalt: process.env.DSQL_ENCRYPTION_SALT,
|
||||
});
|
||||
const existingExtraMariadbUser = yield (0, noDatabaseDbHandler_1.default)(`SELECT * FROM mysql.user WHERE User = '${username}' AND Host = '${host}'`);
|
||||
const isExtraMariadbUserExisting = Boolean((_e = existingExtraMariadbUser === null || existingExtraMariadbUser === void 0 ? void 0 : existingExtraMariadbUser[0]) === null || _e === void 0 ? void 0 : _e.User);
|
||||
if (!isExtraMariadbUserExisting) {
|
||||
yield (0, noDatabaseDbHandler_1.default)(`CREATE USER IF NOT EXISTS '${username}'@'${host}' IDENTIFIED BY '${decrptedPassword}'`);
|
||||
}
|
||||
const isGrantHandled = yield (0, handleGrants_1.default)({
|
||||
username,
|
||||
host,
|
||||
grants: grants && typeof grants == "string"
|
||||
? JSON.parse(grants)
|
||||
: [],
|
||||
userId: String(userId),
|
||||
});
|
||||
if (!isGrantHandled) {
|
||||
console.log(`Error in handling grants for user ${username}@${host}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (error) {
|
||||
console.log(`Error in adding SQL user =>`, error.message);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export {};
|
||||
@@ -0,0 +1,70 @@
|
||||
"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 });
|
||||
require("dotenv").config({ path: "../../.env" });
|
||||
const generate_password_1 = __importDefault(require("generate-password"));
|
||||
const noDatabaseDbHandler_1 = __importDefault(require("../utils/noDatabaseDbHandler"));
|
||||
const dbHandler_1 = __importDefault(require("../utils/dbHandler"));
|
||||
const encrypt_1 = __importDefault(require("../../functions/dsql/encrypt"));
|
||||
/**
|
||||
* # Reset SQL Passwords
|
||||
*/
|
||||
function resetSQLCredentialsPasswords() {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
const users = (yield (0, dbHandler_1.default)({
|
||||
query: `SELECT * FROM users`,
|
||||
}));
|
||||
if (!users) {
|
||||
process.exit();
|
||||
}
|
||||
for (let i = 0; i < users.length; i++) {
|
||||
const user = users[i];
|
||||
if (!user)
|
||||
continue;
|
||||
try {
|
||||
const maridbUsers = (yield (0, dbHandler_1.default)({
|
||||
query: `SELECT * FROM mysql.user WHERE User = 'dsql_user_${user.id}'`,
|
||||
}));
|
||||
for (let j = 0; j < maridbUsers.length; j++) {
|
||||
const { User, Host } = maridbUsers[j];
|
||||
const password = generate_password_1.default.generate({
|
||||
length: 16,
|
||||
numbers: true,
|
||||
symbols: true,
|
||||
uppercase: true,
|
||||
exclude: "*#.'`\"",
|
||||
});
|
||||
const encryptedPassword = (0, encrypt_1.default)({
|
||||
data: password,
|
||||
encryptionKey: process.env.DSQL_ENCRYPTION_PASSWORD,
|
||||
encryptionSalt: process.env.DSQL_ENCRYPTION_SALT,
|
||||
});
|
||||
yield (0, noDatabaseDbHandler_1.default)(`SET PASSWORD FOR '${User}'@'${Host}' = PASSWORD('${password}')`);
|
||||
if (user.mariadb_user == User && user.mariadb_host == Host) {
|
||||
const updateUser = yield (0, dbHandler_1.default)({
|
||||
query: `UPDATE users SET mariadb_pass = ? WHERE id = ?`,
|
||||
values: [encryptedPassword, user.id],
|
||||
});
|
||||
}
|
||||
console.log(`User ${user.id}: ${user.first_name} ${user.last_name} Password Updated successfully added.`);
|
||||
}
|
||||
}
|
||||
catch (error) {
|
||||
console.log(`Error Updating User ${user.id} Password =>`, error.message);
|
||||
}
|
||||
}
|
||||
process.exit();
|
||||
});
|
||||
}
|
||||
resetSQLCredentialsPasswords();
|
||||
@@ -0,0 +1 @@
|
||||
export {};
|
||||
@@ -0,0 +1,142 @@
|
||||
"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 });
|
||||
const path_1 = __importDefault(require("path"));
|
||||
require("dotenv").config({ path: "../../../.env" });
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const child_process_1 = require("child_process");
|
||||
const ejson_1 = __importDefault(require("../../../utils/ejson"));
|
||||
const DB_HANDLER_1 = __importDefault(require("../../../utils/backend/global-db/DB_HANDLER"));
|
||||
const addDbEntry_1 = __importDefault(require("../../../functions/backend/db/addDbEntry"));
|
||||
const addMariadbUser_1 = __importDefault(require("../../../functions/backend/addMariadbUser"));
|
||||
const updateDbEntry_1 = __importDefault(require("../../../functions/backend/db/updateDbEntry"));
|
||||
const hashPassword_1 = __importDefault(require("../../../functions/dsql/hashPassword"));
|
||||
const tmpDir = process.argv[process.argv.length - 1];
|
||||
/**
|
||||
* # Create New User
|
||||
*/
|
||||
function createUser() {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
/**
|
||||
* Validate Form
|
||||
*
|
||||
* @description Check if request body is valid
|
||||
*/
|
||||
try {
|
||||
const isTmpDir = Boolean(tmpDir === null || tmpDir === void 0 ? void 0 : tmpDir.match(/\.json$/));
|
||||
const targetPath = isTmpDir
|
||||
? path_1.default.resolve(process.cwd(), tmpDir)
|
||||
: path_1.default.resolve(__dirname, "./new-user.json");
|
||||
const userObj = ejson_1.default.parse(fs_1.default.readFileSync(targetPath, "utf-8"));
|
||||
if (typeof userObj !== "object" || Array.isArray(userObj))
|
||||
throw new Error("User Object Invalid!");
|
||||
const ROOT_DIR = path_1.default.resolve(__dirname, "../../../");
|
||||
/**
|
||||
* Validate Form
|
||||
*
|
||||
* @description Check if request body is valid
|
||||
*/
|
||||
const first_name = userObj.first_name;
|
||||
const last_name = userObj.last_name;
|
||||
const email = userObj.email;
|
||||
const password = userObj.password;
|
||||
const username = userObj.username;
|
||||
if (!(email === null || email === void 0 ? void 0 : email.match(/.*@.*\..*/)))
|
||||
return false;
|
||||
if (!(first_name === null || first_name === void 0 ? void 0 : first_name.match(/^[a-zA-Z]+$/)) ||
|
||||
!(last_name === null || last_name === void 0 ? void 0 : last_name.match(/^[a-zA-Z]+$/)))
|
||||
return false;
|
||||
if (password === null || password === void 0 ? void 0 : password.match(/ /))
|
||||
return false;
|
||||
if (username === null || username === void 0 ? void 0 : username.match(/ /))
|
||||
return false;
|
||||
let hashedPassword = (0, hashPassword_1.default)({
|
||||
encryptionKey: process.env.DSQL_ENCRYPTION_PASSWORD || "",
|
||||
password: password,
|
||||
});
|
||||
let existingUser = yield (0, DB_HANDLER_1.default)(`SELECT * FROM users WHERE email='${email}'`);
|
||||
if (existingUser === null || existingUser === void 0 ? void 0 : existingUser[0]) {
|
||||
console.log("User Exists");
|
||||
return false;
|
||||
}
|
||||
const newUser = yield (0, addDbEntry_1.default)({
|
||||
dbFullName: "datasquirel",
|
||||
tableName: "users",
|
||||
data: Object.assign(Object.assign({}, userObj), { password: hashedPassword }),
|
||||
});
|
||||
if (!(newUser === null || newUser === void 0 ? void 0 : newUser.insertId))
|
||||
return false;
|
||||
/**
|
||||
* Add a Mariadb User for this User
|
||||
*/
|
||||
yield (0, addMariadbUser_1.default)({ userId: newUser.insertId });
|
||||
const STATIC_ROOT = process.env.DSQL_STATIC_SERVER_DIR;
|
||||
if (!STATIC_ROOT) {
|
||||
console.log("Static File ENV not Found!");
|
||||
throw new Error("No Static Path");
|
||||
}
|
||||
/**
|
||||
* Create new user folder and file
|
||||
*
|
||||
* @description Create new user folder and file
|
||||
*/
|
||||
let newUserSchemaFolderPath = `${process.env.DSQL_USER_DB_SCHEMA_PATH}/user-${newUser.insertId}`;
|
||||
let newUserMediaFolderPath = path_1.default.join(STATIC_ROOT, `images/user-images/user-${newUser.insertId}`);
|
||||
fs_1.default.mkdirSync(newUserSchemaFolderPath, { recursive: true });
|
||||
fs_1.default.mkdirSync(newUserMediaFolderPath, { recursive: true });
|
||||
fs_1.default.writeFileSync(`${newUserSchemaFolderPath}/main.json`, JSON.stringify([]), "utf8");
|
||||
const imageBasePath = path_1.default.join(STATIC_ROOT, `images/user-images/user-${newUser.insertId}`);
|
||||
if (!fs_1.default.existsSync(imageBasePath)) {
|
||||
fs_1.default.mkdirSync(imageBasePath, { recursive: true });
|
||||
}
|
||||
let imagePath = path_1.default.join(STATIC_ROOT, `images/user-images/user-${newUser.insertId}/user-${newUser.insertId}-profile.jpg`);
|
||||
let imageThumbnailPath = path_1.default.join(STATIC_ROOT, `images/user-images/user-${newUser.insertId}/user-${newUser.insertId}-profile-thumbnail.jpg`);
|
||||
let prodImageUrl = imagePath.replace(STATIC_ROOT, process.env.DSQL_STATIC_HOST || "");
|
||||
let prodImageThumbnailUrl = imageThumbnailPath.replace(STATIC_ROOT, process.env.DSQL_STATIC_HOST || "");
|
||||
fs_1.default.copyFileSync(path_1.default.join(ROOT_DIR, "/public/images/user-preset.png"), imagePath);
|
||||
fs_1.default.copyFileSync(path_1.default.join(ROOT_DIR, "/public/images/user-preset-thumbnail.png"), imageThumbnailPath);
|
||||
(0, child_process_1.execSync)(`chmod 644 ${imagePath} ${imageThumbnailPath}`);
|
||||
const updateImages = yield (0, updateDbEntry_1.default)({
|
||||
dbFullName: "datasquirel",
|
||||
tableName: "users",
|
||||
identifierColumnName: "id",
|
||||
identifierValue: newUser.insertId,
|
||||
data: {
|
||||
image: prodImageUrl,
|
||||
image_thumbnail: prodImageThumbnailUrl,
|
||||
},
|
||||
});
|
||||
if (isTmpDir) {
|
||||
try {
|
||||
fs_1.default.unlinkSync(path_1.default.resolve(process.cwd(), tmpDir));
|
||||
}
|
||||
catch (error) { }
|
||||
}
|
||||
return true;
|
||||
}
|
||||
catch (error) {
|
||||
console.log(`Error in creating user => ${error.message}`);
|
||||
return false;
|
||||
}
|
||||
});
|
||||
}
|
||||
createUser().then((res) => {
|
||||
if (res) {
|
||||
console.log("User Creation Success!!!");
|
||||
}
|
||||
else {
|
||||
console.log("User Creation Failed!");
|
||||
}
|
||||
process.exit();
|
||||
});
|
||||
@@ -0,0 +1 @@
|
||||
export {};
|
||||
@@ -0,0 +1,81 @@
|
||||
"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 });
|
||||
const path_1 = __importDefault(require("path"));
|
||||
require("dotenv").config({ path: "../../../.env" });
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const ejson_1 = __importDefault(require("../../../utils/ejson"));
|
||||
const hashPassword_1 = __importDefault(require("../../../functions/dsql/hashPassword"));
|
||||
const updateDbEntry_1 = __importDefault(require("../../../functions/backend/db/updateDbEntry"));
|
||||
const tmpDir = process.argv[process.argv.length - 1];
|
||||
/**
|
||||
* # Create New User
|
||||
*/
|
||||
function createUser() {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
/**
|
||||
* Validate Form
|
||||
*
|
||||
* @description Check if request body is valid
|
||||
*/
|
||||
try {
|
||||
const isTmpDir = Boolean(tmpDir === null || tmpDir === void 0 ? void 0 : tmpDir.match(/\.json$/));
|
||||
const targetPath = isTmpDir
|
||||
? path_1.default.resolve(process.cwd(), tmpDir)
|
||||
: path_1.default.resolve(__dirname, "./update-user.json");
|
||||
const updateUserObj = ejson_1.default.parse(fs_1.default.readFileSync(targetPath, "utf-8"));
|
||||
if (typeof updateUserObj !== "object" || Array.isArray(updateUserObj))
|
||||
throw new Error("Update User Object Invalid!");
|
||||
let hashedPassword = updateUserObj.password
|
||||
? (0, hashPassword_1.default)({
|
||||
encryptionKey: process.env.DSQL_ENCRYPTION_PASSWORD || "",
|
||||
password: updateUserObj.password,
|
||||
})
|
||||
: undefined;
|
||||
let updatePayload = Object.assign({}, updateUserObj);
|
||||
if (hashedPassword) {
|
||||
updatePayload["password"] = hashedPassword;
|
||||
}
|
||||
const newUser = yield (0, updateDbEntry_1.default)({
|
||||
dbFullName: "datasquirel",
|
||||
tableName: "users",
|
||||
data: Object.assign(Object.assign({}, updatePayload), { id: undefined }),
|
||||
identifierColumnName: "id",
|
||||
identifierValue: updatePayload.id,
|
||||
});
|
||||
if (!(newUser === null || newUser === void 0 ? void 0 : newUser.affectedRows))
|
||||
return false;
|
||||
if (isTmpDir) {
|
||||
try {
|
||||
fs_1.default.unlinkSync(path_1.default.resolve(process.cwd(), tmpDir));
|
||||
}
|
||||
catch (error) { }
|
||||
}
|
||||
return true;
|
||||
}
|
||||
catch (error) {
|
||||
console.log(`Error in creating user => ${error.message}`);
|
||||
return false;
|
||||
}
|
||||
});
|
||||
}
|
||||
createUser().then((res) => {
|
||||
if (res) {
|
||||
console.log("User Update Success!!!");
|
||||
}
|
||||
else {
|
||||
console.log("User Update Failed!");
|
||||
}
|
||||
process.exit();
|
||||
});
|
||||
+1
@@ -0,0 +1 @@
|
||||
export {};
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const imageBase64 = fs_1.default.readFileSync("./../public/images/unique-tokens-icon.png", "base64");
|
||||
@@ -0,0 +1 @@
|
||||
export {};
|
||||
@@ -0,0 +1,86 @@
|
||||
"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 });
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
require("dotenv").config({ path: "./../.env" });
|
||||
const varDatabaseDbHandler_1 = __importDefault(require("../functions/backend/varDatabaseDbHandler"));
|
||||
const DB_HANDLER_1 = __importDefault(require("../utils/backend/global-db/DB_HANDLER"));
|
||||
const userId = process.argv.indexOf("--userId") >= 0
|
||||
? process.argv[process.argv.indexOf("--userId") + 1]
|
||||
: null;
|
||||
/**
|
||||
* Grab Schema
|
||||
*
|
||||
* @description Grab Schema
|
||||
*/
|
||||
function recoverMainJsonFromDb() {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
if (!userId) {
|
||||
console.log("No user Id provided");
|
||||
return;
|
||||
}
|
||||
const databases = yield (0, DB_HANDLER_1.default)(`SELECT * FROM user_databases WHERE user_id='${userId}'`);
|
||||
const dbWrite = [];
|
||||
for (let i = 0; i < databases.length; i++) {
|
||||
const { id, db_name, db_slug, db_full_name, db_image, db_description } = databases[i];
|
||||
const dbObject = {
|
||||
dbName: db_name,
|
||||
dbSlug: db_slug,
|
||||
dbFullName: db_full_name,
|
||||
dbDescription: db_description,
|
||||
dbImage: db_image,
|
||||
tables: [],
|
||||
};
|
||||
const tables = yield (0, DB_HANDLER_1.default)(`SELECT * FROM user_database_tables WHERE user_id='${userId}' AND db_id='${id}'`);
|
||||
for (let j = 0; j < tables.length; j++) {
|
||||
const { table_name, table_slug, table_description } = tables[j];
|
||||
const tableObject = {
|
||||
tableName: table_slug,
|
||||
tableFullName: table_name,
|
||||
fields: [],
|
||||
indexes: [],
|
||||
};
|
||||
const tableFields = yield (0, varDatabaseDbHandler_1.default)({
|
||||
database: db_full_name,
|
||||
queryString: `SHOW COLUMNS FROM ${table_slug}`,
|
||||
});
|
||||
for (let k = 0; k < tableFields.length; k++) {
|
||||
const { Field, Type, Null, Default, Key } = tableFields[k];
|
||||
const fieldObject = {
|
||||
fieldName: Field,
|
||||
dataType: Type.toUpperCase(),
|
||||
};
|
||||
if ((Default === null || Default === void 0 ? void 0 : Default.match(/./)) && !(Default === null || Default === void 0 ? void 0 : Default.match(/timestamp/i)))
|
||||
fieldObject["defaultValue"] = Default;
|
||||
if (Key === null || Key === void 0 ? void 0 : Key.match(/pri/i)) {
|
||||
fieldObject["primaryKey"] = true;
|
||||
fieldObject["autoIncrement"] = true;
|
||||
}
|
||||
if (Default === null || Default === void 0 ? void 0 : Default.match(/timestamp/i))
|
||||
fieldObject["defaultValueLiteral"] = Default;
|
||||
if (Null === null || Null === void 0 ? void 0 : Null.match(/yes/i))
|
||||
fieldObject["nullValue"] = true;
|
||||
if (Null === null || Null === void 0 ? void 0 : Null.match(/no/i))
|
||||
fieldObject["notNullValue"] = true;
|
||||
tableObject.fields.push(fieldObject);
|
||||
}
|
||||
dbObject.tables.push(tableObject);
|
||||
}
|
||||
dbWrite.push(dbObject);
|
||||
}
|
||||
fs_1.default.writeFileSync(`${String(process.env.DSQL_USER_DB_SCHEMA_PATH)}/user-${userId}/main.json`, JSON.stringify(dbWrite, null, 4), "utf-8");
|
||||
process.exit();
|
||||
});
|
||||
}
|
||||
recoverMainJsonFromDb();
|
||||
@@ -0,0 +1 @@
|
||||
export {};
|
||||
@@ -0,0 +1,72 @@
|
||||
"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 });
|
||||
require("dotenv").config({ path: "./../.env" });
|
||||
const generate_password_1 = __importDefault(require("generate-password"));
|
||||
const noDatabaseDbHandler_1 = __importDefault(require("./utils/noDatabaseDbHandler"));
|
||||
const dbHandler_1 = __importDefault(require("./utils/dbHandler"));
|
||||
const encrypt_1 = __importDefault(require("../functions/dsql/encrypt"));
|
||||
/**
|
||||
* Create database from Schema Function
|
||||
* ==============================================================================
|
||||
* @param {object} params - Single object params
|
||||
* @param {number|string|null} params.userId - User ID or null
|
||||
*/
|
||||
function resetSQLCredentials() {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
const users = (yield (0, dbHandler_1.default)({
|
||||
query: `SELECT * FROM users`,
|
||||
}));
|
||||
if (!users) {
|
||||
process.exit();
|
||||
}
|
||||
for (let i = 0; i < users.length; i++) {
|
||||
const user = users[i];
|
||||
if (!user)
|
||||
continue;
|
||||
const defaultMariadbUserHost = process.env.DSQL_DB_HOST || "127.0.0.1";
|
||||
try {
|
||||
const username = `dsql_user_${user.id}`;
|
||||
const password = generate_password_1.default.generate({
|
||||
length: 16,
|
||||
numbers: true,
|
||||
symbols: true,
|
||||
uppercase: true,
|
||||
exclude: "*#.'`\"",
|
||||
});
|
||||
const encryptedPassword = (0, encrypt_1.default)({ data: password });
|
||||
yield (0, noDatabaseDbHandler_1.default)(`DROP USER IF EXISTS '${username}'@'%'`);
|
||||
yield (0, noDatabaseDbHandler_1.default)(`DROP USER IF EXISTS '${username}'@'${defaultMariadbUserHost}'`);
|
||||
yield (0, noDatabaseDbHandler_1.default)(`CREATE USER IF NOT EXISTS '${username}'@'${defaultMariadbUserHost}' IDENTIFIED BY '${password}'`);
|
||||
yield (0, noDatabaseDbHandler_1.default)(`GRANT ALL PRIVILEGES ON \`datasquirel_user_${user.id}_%\`.* TO '${username}'@'${defaultMariadbUserHost}'`);
|
||||
yield (0, noDatabaseDbHandler_1.default)(`FLUSH PRIVILEGES`);
|
||||
const updateUser = yield (0, dbHandler_1.default)({
|
||||
query: `UPDATE users SET mariadb_user = ?, mariadb_host = ?, mariadb_pass = ? WHERE id = ?`,
|
||||
values: [
|
||||
username,
|
||||
defaultMariadbUserHost,
|
||||
encryptedPassword,
|
||||
user.id,
|
||||
],
|
||||
});
|
||||
console.log(`User ${user.id}: ${user.first_name} ${user.last_name} SQL credentials successfully added.`);
|
||||
}
|
||||
catch (error) {
|
||||
console.log(`Error in adding SQL user =>`, error.message);
|
||||
}
|
||||
}
|
||||
process.exit();
|
||||
});
|
||||
}
|
||||
resetSQLCredentials();
|
||||
@@ -0,0 +1 @@
|
||||
export {};
|
||||
@@ -0,0 +1,60 @@
|
||||
"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 });
|
||||
require("dotenv").config({ path: "./../.env" });
|
||||
const generate_password_1 = __importDefault(require("generate-password"));
|
||||
const noDatabaseDbHandler_1 = __importDefault(require("./utils/noDatabaseDbHandler"));
|
||||
const dbHandler_1 = __importDefault(require("./utils/dbHandler"));
|
||||
const encrypt_1 = __importDefault(require("../functions/dsql/encrypt"));
|
||||
/**
|
||||
* # Create database from Schema Function
|
||||
*/
|
||||
function resetSQLCredentialsPasswords() {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
const users = (yield (0, dbHandler_1.default)({
|
||||
query: `SELECT * FROM users`,
|
||||
}));
|
||||
if (!users) {
|
||||
process.exit();
|
||||
}
|
||||
for (let i = 0; i < users.length; i++) {
|
||||
const user = users[i];
|
||||
if (!user)
|
||||
continue;
|
||||
const defaultMariadbUserHost = process.env.DSQL_DB_HOST || "127.0.0.1";
|
||||
try {
|
||||
const username = `dsql_user_${user.id}`;
|
||||
const password = generate_password_1.default.generate({
|
||||
length: 16,
|
||||
numbers: true,
|
||||
symbols: true,
|
||||
uppercase: true,
|
||||
exclude: "*#.'`\"",
|
||||
});
|
||||
const encryptedPassword = (0, encrypt_1.default)({ data: password });
|
||||
yield (0, noDatabaseDbHandler_1.default)(`SET PASSWORD FOR '${username}'@'${defaultMariadbUserHost}' = PASSWORD('${password}')`);
|
||||
const updateUser = yield (0, dbHandler_1.default)({
|
||||
query: `UPDATE users SET mariadb_pass = ? WHERE id = ?`,
|
||||
values: [encryptedPassword, user.id],
|
||||
});
|
||||
console.log(`User ${user.id}: ${user.first_name} ${user.last_name} Password Updated successfully added.`);
|
||||
}
|
||||
catch (error) {
|
||||
console.log(`Error Updating User ${user.id} Password =>`, error.message);
|
||||
}
|
||||
}
|
||||
process.exit();
|
||||
});
|
||||
}
|
||||
resetSQLCredentialsPasswords();
|
||||
@@ -0,0 +1 @@
|
||||
export {};
|
||||
@@ -0,0 +1,40 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const rootDir = path_1.default.resolve(__dirname, "../../../");
|
||||
const ignorePattern = /\/\.git\/|\/\.next\/|\/\.dist\/|node_modules|\/\.local_dist\/|\/\.tmp\/|\/types\/|\.config\.js|\/public\//;
|
||||
function transformJsToTs(dir) {
|
||||
var _a;
|
||||
const dirContent = fs_1.default.readdirSync(dir);
|
||||
for (let i = 0; i < dirContent.length; i++) {
|
||||
const fileFolder = dirContent[i];
|
||||
const fullFileFolderPath = path_1.default.join(dir, fileFolder);
|
||||
const stat = fs_1.default.statSync(fullFileFolderPath);
|
||||
if (stat.isDirectory()) {
|
||||
transformJsToTs(fullFileFolderPath);
|
||||
continue;
|
||||
}
|
||||
if (ignorePattern.test(fullFileFolderPath))
|
||||
continue;
|
||||
if (fullFileFolderPath.match(/\.jsx?$/)) {
|
||||
const extension = (_a = fullFileFolderPath.match(/\.jsx?$/)) === null || _a === void 0 ? void 0 : _a[0];
|
||||
if (!extension)
|
||||
continue;
|
||||
const newExtension = extension.replace("js", "ts");
|
||||
const newFilePath = fullFileFolderPath.replace(/\.jsx?$/, newExtension);
|
||||
console.log(fullFileFolderPath);
|
||||
console.log(extension, "=>", newExtension);
|
||||
console.log(newFilePath);
|
||||
console.log("\n/////////////////////////////////////////");
|
||||
console.log("/////////////////////////////////////////\n");
|
||||
fs_1.default.copyFileSync(fullFileFolderPath, newFilePath);
|
||||
fs_1.default.unlinkSync(fullFileFolderPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
console.log("rootDir", rootDir);
|
||||
transformJsToTs(rootDir);
|
||||
@@ -0,0 +1 @@
|
||||
export {};
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
"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 });
|
||||
require("dotenv").config({ path: "./../.env" });
|
||||
const generate_password_1 = __importDefault(require("generate-password"));
|
||||
const noDatabaseDbHandler_1 = __importDefault(require("./utils/noDatabaseDbHandler"));
|
||||
const dbHandler_1 = __importDefault(require("./utils/dbHandler"));
|
||||
const encrypt_1 = __importDefault(require("../functions/dsql/encrypt"));
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/**
|
||||
* # Set SQL Credentials
|
||||
*/
|
||||
function setSQLCredentials() {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
const users = (yield (0, dbHandler_1.default)({
|
||||
query: `SELECT * FROM users`,
|
||||
}));
|
||||
if (!users) {
|
||||
process.exit();
|
||||
}
|
||||
for (let i = 0; i < users.length; i++) {
|
||||
const user = users[i];
|
||||
if (!user)
|
||||
continue;
|
||||
if (user.mariadb_user && user.mariadb_pass) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
const username = `dsql_user_${user.id}`;
|
||||
const password = generate_password_1.default.generate({
|
||||
length: 16,
|
||||
numbers: true,
|
||||
symbols: true,
|
||||
uppercase: true,
|
||||
exclude: "*#.'`\"",
|
||||
});
|
||||
const encryptedPassword = (0, encrypt_1.default)({ data: password });
|
||||
yield (0, noDatabaseDbHandler_1.default)(`CREATE USER IF NOT EXISTS '${username}'@'127.0.0.1' IDENTIFIED BY '${password}'`);
|
||||
yield (0, noDatabaseDbHandler_1.default)(`GRANT ALL PRIVILEGES ON \`datasquirel\\_user\\_${user.id}\\_%\`.* TO '${username}'@'127.0.0.1'`);
|
||||
yield (0, noDatabaseDbHandler_1.default)(`FLUSH PRIVILEGES`);
|
||||
const updateUser = yield (0, dbHandler_1.default)({
|
||||
query: `UPDATE users SET mariadb_user = ?, mariadb_host = '127.0.0.1' mariadb_pass = ? WHERE id = ?`,
|
||||
values: [username, encryptedPassword, user.id],
|
||||
});
|
||||
console.log(`User ${user.id}: ${user.first_name} ${user.last_name} SQL credentials successfully added.`);
|
||||
}
|
||||
catch (error) {
|
||||
console.log(`Error in adding SQL user =>`, error.message);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
setSQLCredentials();
|
||||
@@ -0,0 +1 @@
|
||||
export {};
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const child_process_1 = require("child_process");
|
||||
require("dotenv").config({ path: "./../.env" });
|
||||
const sourceFile = process.argv.indexOf("--src") >= 0
|
||||
? process.argv[process.argv.indexOf("--src") + 1]
|
||||
: null;
|
||||
const destinationFile = process.argv.indexOf("--dst") >= 0
|
||||
? process.argv[process.argv.indexOf("--dst") + 1]
|
||||
: null;
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
console.log("Running Tailwind CSS compiler ...");
|
||||
fs_1.default.watch("./../", (curr, prev) => {
|
||||
(0, child_process_1.exec)(`npx tailwindcss -i ./tailwind/main.css -o ./styles/tailwind.css`, (error, stdout, stderr) => {
|
||||
if (error) {
|
||||
console.log("ERROR =>", error.message);
|
||||
return;
|
||||
}
|
||||
console.log("Tailwind CSS Compilation \x1b[32msuccessful\x1b[0m!");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1 @@
|
||||
export {};
|
||||
@@ -0,0 +1,57 @@
|
||||
"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 });
|
||||
require("dotenv").config({ path: "./.env" });
|
||||
const grabDbSSL_1 = __importDefault(require("../utils/backend/grabDbSSL"));
|
||||
const serverless_mysql_1 = __importDefault(require("serverless-mysql"));
|
||||
const connection = (0, serverless_mysql_1.default)({
|
||||
config: {
|
||||
host: process.env.DSQL_DB_HOST,
|
||||
user: process.env.DB_USER,
|
||||
password: process.env.DB_PASS,
|
||||
// database: process.env.DSQL_DB_NAME,
|
||||
charset: "utf8mb4",
|
||||
ssl: (0, grabDbSSL_1.default)(),
|
||||
},
|
||||
});
|
||||
/**
|
||||
* # Main DB Handler Function
|
||||
* @async
|
||||
*
|
||||
* @param {object} params
|
||||
* @param {string} params.query
|
||||
* @param {string[] | object} [params.values]
|
||||
* @param {string} [params.database]
|
||||
*
|
||||
* @returns {Promise<object|null>}
|
||||
*/
|
||||
(() => __awaiter(void 0, void 0, void 0, function* () {
|
||||
/**
|
||||
* Switch Database
|
||||
*
|
||||
* @description If a database is provided, switch to it
|
||||
*/
|
||||
try {
|
||||
const result = yield connection.query("SHOW DATABASES");
|
||||
const parsedResults = JSON.parse(JSON.stringify(result));
|
||||
console.log("parsedResults =>", parsedResults);
|
||||
}
|
||||
catch (error) {
|
||||
console.log("Connection query ERROR =>", error.message);
|
||||
}
|
||||
finally {
|
||||
connection.end();
|
||||
process.exit();
|
||||
}
|
||||
}))();
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/**
|
||||
* # Test SQL Escape
|
||||
*/
|
||||
export default function testSQLEscape(): Promise<void>;
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
"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 = testSQLEscape;
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
require("dotenv").config({ path: "./../.env" });
|
||||
const generate_password_1 = __importDefault(require("generate-password"));
|
||||
const noDatabaseDbHandler_1 = __importDefault(require("./utils/noDatabaseDbHandler"));
|
||||
const dbHandler_1 = __importDefault(require("./utils/dbHandler"));
|
||||
const encrypt_1 = __importDefault(require("../functions/dsql/encrypt"));
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/**
|
||||
* # Test SQL Escape
|
||||
*/
|
||||
function testSQLEscape() {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
const users = (yield (0, dbHandler_1.default)({
|
||||
query: `SELECT * FROM users`,
|
||||
}));
|
||||
if (!users) {
|
||||
process.exit();
|
||||
}
|
||||
for (let i = 0; i < users.length; i++) {
|
||||
const user = users[i];
|
||||
if (!user)
|
||||
continue;
|
||||
const defaultMariadbUserHost = process.env.DSQL_DB_HOST || "127.0.0.1";
|
||||
try {
|
||||
const username = `dsql_user_${user.id}`;
|
||||
const password = generate_password_1.default.generate({
|
||||
length: 16,
|
||||
numbers: true,
|
||||
symbols: true,
|
||||
uppercase: true,
|
||||
exclude: "*#.'`\"",
|
||||
});
|
||||
const encryptedPassword = (0, encrypt_1.default)({ data: password });
|
||||
yield (0, noDatabaseDbHandler_1.default)(`DROP USER '${username}'@'${defaultMariadbUserHost}'`);
|
||||
yield (0, noDatabaseDbHandler_1.default)(`CREATE USER IF NOT EXISTS '${username}'@'${defaultMariadbUserHost}' IDENTIFIED BY '${password}'`);
|
||||
yield (0, noDatabaseDbHandler_1.default)(`GRANT ALL PRIVILEGES ON \`datasquirel\\_user\\_${user.id}\\_%\`.* TO '${username}'@'${defaultMariadbUserHost}'`);
|
||||
yield (0, noDatabaseDbHandler_1.default)(`FLUSH PRIVILEGES`);
|
||||
const updateUser = yield (0, dbHandler_1.default)({
|
||||
query: `UPDATE users SET mariadb_user = ?, mariadb_host = ? mariadb_pass = ? WHERE id = ?`,
|
||||
values: [
|
||||
username,
|
||||
defaultMariadbUserHost,
|
||||
encryptedPassword,
|
||||
user.id,
|
||||
],
|
||||
});
|
||||
console.log(`User ${user.id}: ${user.first_name} ${user.last_name} SQL credentials successfully added.`);
|
||||
}
|
||||
catch (error) {
|
||||
console.log(`Error in adding SQL user =>`, error.message);
|
||||
}
|
||||
}
|
||||
process.exit();
|
||||
});
|
||||
}
|
||||
testSQLEscape();
|
||||
@@ -0,0 +1 @@
|
||||
export {};
|
||||
@@ -0,0 +1,56 @@
|
||||
"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 });
|
||||
const DB_HANDLER_1 = __importDefault(require("../utils/backend/global-db/DB_HANDLER"));
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
require("dotenv").config({ path: "./../.env" });
|
||||
function updateChildrenTablesOnDb() {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
/**
|
||||
* Grab Schema
|
||||
*
|
||||
* @description Grab Schema
|
||||
*/
|
||||
try {
|
||||
const rootDir = String(process.env.DSQL_USER_DB_SCHEMA_PATH);
|
||||
const userFolders = fs_1.default.readdirSync(rootDir);
|
||||
for (let i = 0; i < userFolders.length; i++) {
|
||||
const folder = userFolders[i];
|
||||
const userId = folder.replace(/user-/, "");
|
||||
const databases = JSON.parse(fs_1.default.readFileSync(`${rootDir}/${folder}/main.json`, "utf-8"));
|
||||
for (let j = 0; j < databases.length; j++) {
|
||||
const db = databases[j];
|
||||
const dbTables = db.tables;
|
||||
for (let k = 0; k < dbTables.length; k++) {
|
||||
const table = dbTables[k];
|
||||
if (table === null || table === void 0 ? void 0 : table.childTable) {
|
||||
const originTableName = table.childTableName;
|
||||
const originDbName = table.childTableDbFullName;
|
||||
const WHERE_CLAUSE = `WHERE user_id='${userId}' AND db_slug='${db.dbSlug}' AND table_slug='${table.tableName}'`;
|
||||
const existingTableInDb = yield (0, DB_HANDLER_1.default)(`SELECT * FROM user_database_tables ${WHERE_CLAUSE}`);
|
||||
if (existingTableInDb && existingTableInDb[0]) {
|
||||
const updateChildrenTablesInfo = yield (0, DB_HANDLER_1.default)(`UPDATE user_database_tables SET child_table='1',child_table_parent_database='${originDbName}',child_table_parent_table='${originTableName}' WHERE id='${existingTableInDb[0].id}'`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (error) {
|
||||
console.log(error);
|
||||
}
|
||||
process.exit();
|
||||
});
|
||||
}
|
||||
updateChildrenTablesOnDb();
|
||||
@@ -0,0 +1 @@
|
||||
export {};
|
||||
@@ -0,0 +1,44 @@
|
||||
"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 });
|
||||
require("dotenv").config({ path: "./../.env" });
|
||||
const varDatabaseDbHandler_1 = __importDefault(require("../functions/backend/varDatabaseDbHandler"));
|
||||
/**
|
||||
* Grab Schema
|
||||
*
|
||||
* @description Grab Schema
|
||||
*/
|
||||
(0, varDatabaseDbHandler_1.default)({
|
||||
queryString: `SELECT user_database_tables.*,user_databases.db_full_name FROM user_database_tables JOIN user_databases ON user_database_tables.db_id=user_databases.id`,
|
||||
database: "datasquirel",
|
||||
}).then((tables) => __awaiter(void 0, void 0, void 0, function* () {
|
||||
for (let i = 0; i < tables.length; i++) {
|
||||
const table = tables[i];
|
||||
const { id, user_id, db_id, db_full_name, table_name, table_slug, table_description, } = table;
|
||||
const tableInfo = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: `SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='${db_full_name}' AND TABLE_NAME='${table_slug}'`,
|
||||
database: db_full_name,
|
||||
});
|
||||
const updateCreationDateTimestamp = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: `ALTER TABLE \`${table_slug}\` MODIFY COLUMN date_created_timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP`,
|
||||
database: db_full_name,
|
||||
});
|
||||
const updateDateTimestamp = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: `ALTER TABLE \`${table_slug}\` MODIFY COLUMN date_updated_timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP`,
|
||||
database: db_full_name,
|
||||
});
|
||||
console.log("Date Updated Column updated");
|
||||
}
|
||||
process.exit();
|
||||
}));
|
||||
@@ -0,0 +1 @@
|
||||
export {};
|
||||
@@ -0,0 +1,52 @@
|
||||
"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 });
|
||||
require("dotenv").config({ path: "./../.env" });
|
||||
const serverError_1 = __importDefault(require("../functions/backend/serverError"));
|
||||
const varDatabaseDbHandler_1 = __importDefault(require("./utils/varDatabaseDbHandler"));
|
||||
const DB_HANDLER_1 = __importDefault(require("../utils/backend/global-db/DB_HANDLER"));
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/**
|
||||
* Grab Schema
|
||||
*
|
||||
* @description Grab Schema
|
||||
*/
|
||||
(0, varDatabaseDbHandler_1.default)({
|
||||
queryString: `SELECT DISTINCT db_id FROM user_database_tables`,
|
||||
database: "datasquirel",
|
||||
}).then((tables) => __awaiter(void 0, void 0, void 0, function* () {
|
||||
// console.log(tables);
|
||||
// process.exit();
|
||||
for (let i = 0; i < tables.length; i++) {
|
||||
const table = tables[i];
|
||||
try {
|
||||
const { db_id } = table;
|
||||
const dbSlug = yield (0, DB_HANDLER_1.default)(`SELECT db_slug FROM user_databases WHERE id='${db_id}'`);
|
||||
const updateTableSlug = yield (0, DB_HANDLER_1.default)(`UPDATE user_database_tables SET db_slug='${dbSlug[0].db_slug}' WHERE db_id='${db_id}'`);
|
||||
}
|
||||
catch (error) {
|
||||
(0, serverError_1.default)({
|
||||
component: "shell/updateDbSlugsForTableRecords/main-catch-error",
|
||||
message: error.message,
|
||||
user: {},
|
||||
});
|
||||
}
|
||||
}
|
||||
process.exit();
|
||||
}));
|
||||
@@ -0,0 +1 @@
|
||||
export {};
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
"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 });
|
||||
require("dotenv").config({ path: "./../.env" });
|
||||
const grabDbSSL_1 = __importDefault(require("../utils/backend/grabDbSSL"));
|
||||
const serverless_mysql_1 = __importDefault(require("serverless-mysql"));
|
||||
const connection = (0, serverless_mysql_1.default)({
|
||||
config: {
|
||||
host: process.env.DSQL_DB_HOST,
|
||||
user: process.env.DSQL_DB_USERNAME,
|
||||
password: process.env.DSQL_DB_PASSWORD,
|
||||
database: process.env.DSQL_DB_NAME,
|
||||
charset: "utf8mb4",
|
||||
ssl: (0, grabDbSSL_1.default)(),
|
||||
},
|
||||
});
|
||||
/**
|
||||
* # Main DB Handler Function
|
||||
* @async
|
||||
*
|
||||
* @param {object} params
|
||||
* @param {string} params.query
|
||||
* @param {string[] | object} [params.values]
|
||||
* @param {string} [params.database]
|
||||
*
|
||||
* @returns {Promise<object|null>}
|
||||
*/
|
||||
(() => __awaiter(void 0, void 0, void 0, function* () {
|
||||
var _a;
|
||||
/**
|
||||
* Switch Database
|
||||
*
|
||||
* @description If a database is provided, switch to it
|
||||
*/
|
||||
try {
|
||||
const result = yield connection.query("SELECT user,host,ssl_type FROM mysql.user");
|
||||
const parsedResults = JSON.parse(JSON.stringify(result));
|
||||
for (let i = 0; i < parsedResults.length; i++) {
|
||||
const user = parsedResults[i];
|
||||
if (user.User !== process.env.DSQL_DB_READ_ONLY_USERNAME ||
|
||||
user.User !== process.env.DSQL_DB_FULL_ACCESS_USERNAME ||
|
||||
!((_a = user.User) === null || _a === void 0 ? void 0 : _a.match(/dsql_user_.*/i))) {
|
||||
continue;
|
||||
}
|
||||
const { User, Host, ssl_type } = user;
|
||||
if (ssl_type === "ANY") {
|
||||
continue;
|
||||
}
|
||||
const addUserSSL = yield connection.query(`ALTER USER '${User}'@'${Host}'`);
|
||||
console.log(`addUserSSL => ${User}@${Host}`, addUserSSL);
|
||||
}
|
||||
}
|
||||
catch (error) {
|
||||
console.log("Connection query ERROR =>", error.message);
|
||||
}
|
||||
finally {
|
||||
connection.end();
|
||||
process.exit();
|
||||
}
|
||||
}))();
|
||||
@@ -0,0 +1,7 @@
|
||||
/**
|
||||
* Convert Camel Joined Text to Camel Spaced Text
|
||||
* ==============================================================================
|
||||
* @description this function takes a camel cased text without spaces, and returns
|
||||
* a camel-case-spaced text
|
||||
*/
|
||||
export default function camelJoinedtoCamelSpace(text: string): string | null;
|
||||
@@ -0,0 +1,44 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = camelJoinedtoCamelSpace;
|
||||
/**
|
||||
* Convert Camel Joined Text to Camel Spaced Text
|
||||
* ==============================================================================
|
||||
* @description this function takes a camel cased text without spaces, and returns
|
||||
* a camel-case-spaced text
|
||||
*/
|
||||
function camelJoinedtoCamelSpace(text) {
|
||||
if (!(text === null || text === void 0 ? void 0 : text.match(/./))) {
|
||||
return "";
|
||||
}
|
||||
if (text === null || text === void 0 ? void 0 : text.match(/ /)) {
|
||||
return text;
|
||||
}
|
||||
if (text) {
|
||||
let textArray = text.split("");
|
||||
let capIndexes = [];
|
||||
for (let i = 0; i < textArray.length; i++) {
|
||||
const char = textArray[i];
|
||||
if (i === 0)
|
||||
continue;
|
||||
if (char.match(/[A-Z]/)) {
|
||||
capIndexes.push(i);
|
||||
}
|
||||
}
|
||||
let textChunks = [
|
||||
`${textArray[0].toUpperCase()}${text.substring(1, capIndexes[0])}`,
|
||||
];
|
||||
for (let j = 0; j < capIndexes.length; j++) {
|
||||
const capIndex = capIndexes[j];
|
||||
if (capIndex === 0)
|
||||
continue;
|
||||
const startIndex = capIndex + 1;
|
||||
const endIndex = capIndexes[j + 1];
|
||||
textChunks.push(`${textArray[capIndex].toUpperCase()}${text.substring(startIndex, endIndex)}`);
|
||||
}
|
||||
return textChunks.join(" ");
|
||||
}
|
||||
else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { DSQL_DatabaseSchemaType, DSQL_TableSchemaType } from "../../types";
|
||||
type Param = {
|
||||
dbFullName: string;
|
||||
tableName: string;
|
||||
tableInfoArray: any[];
|
||||
dbSchema?: DSQL_DatabaseSchemaType[];
|
||||
tableSchema?: DSQL_TableSchemaType;
|
||||
recordedDbEntry?: any;
|
||||
clone?: boolean;
|
||||
};
|
||||
/**
|
||||
* # Create Table Functions
|
||||
*/
|
||||
export default function createTable({ dbFullName, tableName, tableInfoArray, dbSchema, clone, tableSchema, recordedDbEntry, }: Param): Promise<any>;
|
||||
export {};
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
+141
@@ -0,0 +1,141 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = createTable;
|
||||
const varDatabaseDbHandler_1 = __importDefault(require("./varDatabaseDbHandler"));
|
||||
const generateColumnDescription_1 = __importDefault(require("./generateColumnDescription"));
|
||||
const supplementTable_1 = __importDefault(require("./supplementTable"));
|
||||
const dbHandler_1 = __importDefault(require("./dbHandler"));
|
||||
/**
|
||||
* # Create Table Functions
|
||||
*/
|
||||
function createTable(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ dbFullName, tableName, tableInfoArray, dbSchema, clone, tableSchema, recordedDbEntry, }) {
|
||||
/**
|
||||
* Format tableInfoArray
|
||||
*
|
||||
* @description Format tableInfoArray
|
||||
*/
|
||||
const finalTable = (0, supplementTable_1.default)({ tableInfoArray: tableInfoArray });
|
||||
/**
|
||||
* Grab Schema
|
||||
*
|
||||
* @description Grab Schema
|
||||
*/
|
||||
const createTableQueryArray = [];
|
||||
createTableQueryArray.push(`CREATE TABLE IF NOT EXISTS \`${tableName}\` (`);
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
try {
|
||||
if (!recordedDbEntry) {
|
||||
throw new Error("Recorded Db entry not found!");
|
||||
}
|
||||
const existingTable = yield (0, varDatabaseDbHandler_1.default)({
|
||||
database: "datasquirel",
|
||||
queryString: `SELECT * FROM user_database_tables WHERE db_id = ? AND table_slug = ?`,
|
||||
queryValuesArray: [recordedDbEntry.id, tableSchema === null || tableSchema === void 0 ? void 0 : tableSchema.tableName],
|
||||
});
|
||||
/** @type {import("../../types").MYSQL_user_database_tables_table_def} */
|
||||
const table = existingTable === null || existingTable === void 0 ? void 0 : existingTable[0];
|
||||
if (!(table === null || table === void 0 ? void 0 : table.id)) {
|
||||
const newTableEntry = yield (0, dbHandler_1.default)({
|
||||
query: `INSERT INTO user_database_tables SET ?`,
|
||||
values: {
|
||||
user_id: recordedDbEntry.user_id,
|
||||
db_id: recordedDbEntry.id,
|
||||
db_slug: recordedDbEntry.db_slug,
|
||||
table_name: tableSchema === null || tableSchema === void 0 ? void 0 : tableSchema.tableFullName,
|
||||
table_slug: tableSchema === null || tableSchema === void 0 ? void 0 : tableSchema.tableName,
|
||||
child_table: (tableSchema === null || tableSchema === void 0 ? void 0 : tableSchema.childTable) ? "1" : null,
|
||||
child_table_parent_database: (tableSchema === null || tableSchema === void 0 ? void 0 : tableSchema.childTableDbFullName) || null,
|
||||
child_table_parent_table: (tableSchema === null || tableSchema === void 0 ? void 0 : tableSchema.childTableName) || null,
|
||||
date_created: Date(),
|
||||
date_created_code: Date.now(),
|
||||
date_updated: Date(),
|
||||
date_updated_code: Date.now(),
|
||||
},
|
||||
database: "datasquirel",
|
||||
});
|
||||
}
|
||||
}
|
||||
catch (error) { }
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
let primaryKeySet = false;
|
||||
/** @type {import("../../types").DSQL_FieldSchemaType[]} */
|
||||
let foreignKeys = [];
|
||||
////////////////////////////////////////
|
||||
for (let i = 0; i < finalTable.length; i++) {
|
||||
const column = finalTable[i];
|
||||
const { fieldName, dataType, nullValue, primaryKey, autoIncrement, defaultValue, defaultValueLiteral, foreignKey, updatedField, onUpdate, onUpdateLiteral, onDelete, onDeleteLiteral, defaultField, encrypted, json, newTempField, notNullValue, originName, plainText, pattern, patternFlags, richText, } = column;
|
||||
if (foreignKey) {
|
||||
foreignKeys.push(Object.assign({}, column));
|
||||
}
|
||||
let { fieldEntryText, newPrimaryKeySet } = (0, generateColumnDescription_1.default)({
|
||||
columnData: column,
|
||||
primaryKeySet: primaryKeySet,
|
||||
});
|
||||
primaryKeySet = newPrimaryKeySet;
|
||||
////////////////////////////////////////
|
||||
const comma = (() => {
|
||||
if (foreignKeys[0])
|
||||
return ",";
|
||||
if (i === finalTable.length - 1)
|
||||
return "";
|
||||
return ",";
|
||||
})();
|
||||
createTableQueryArray.push(" " + fieldEntryText + comma);
|
||||
////////////////////////////////////////
|
||||
}
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
if (foreignKeys[0]) {
|
||||
foreignKeys.forEach((foreighKey, index, array) => {
|
||||
var _a, _b, _c, _d, _e;
|
||||
const fieldName = foreighKey.fieldName;
|
||||
const destinationTableName = (_a = foreighKey.foreignKey) === null || _a === void 0 ? void 0 : _a.destinationTableName;
|
||||
const destinationTableColumnName = (_b = foreighKey.foreignKey) === null || _b === void 0 ? void 0 : _b.destinationTableColumnName;
|
||||
const cascadeDelete = (_c = foreighKey.foreignKey) === null || _c === void 0 ? void 0 : _c.cascadeDelete;
|
||||
const cascadeUpdate = (_d = foreighKey.foreignKey) === null || _d === void 0 ? void 0 : _d.cascadeUpdate;
|
||||
const foreignKeyName = (_e = foreighKey.foreignKey) === null || _e === void 0 ? void 0 : _e.foreignKeyName;
|
||||
const comma = (() => {
|
||||
if (index === foreignKeys.length - 1)
|
||||
return "";
|
||||
return ",";
|
||||
})();
|
||||
createTableQueryArray.push(` CONSTRAINT \`${foreignKeyName}\` FOREIGN KEY (\`${fieldName}\`) REFERENCES \`${destinationTableName}\`(${destinationTableColumnName})${cascadeDelete ? " ON DELETE CASCADE" : ""}${cascadeUpdate ? " ON UPDATE CASCADE" : ""}${comma}`);
|
||||
});
|
||||
}
|
||||
////////////////////////////////////////
|
||||
createTableQueryArray.push(`) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;`);
|
||||
const createTableQuery = createTableQueryArray.join("\n");
|
||||
////////////////////////////////////////
|
||||
const newTable = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: createTableQuery,
|
||||
database: dbFullName,
|
||||
});
|
||||
return newTable;
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
});
|
||||
}
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
type Param = {
|
||||
query: string;
|
||||
values?: string[] | object;
|
||||
database?: string;
|
||||
};
|
||||
/**
|
||||
* # Main DB Handler Function
|
||||
*/
|
||||
export default function dbHandler({ query, values, database, }: Param): Promise<any[] | object | null>;
|
||||
export {};
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = dbHandler;
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const serverless_mysql_1 = __importDefault(require("serverless-mysql"));
|
||||
const grabDbSSL_1 = __importDefault(require("../../utils/backend/grabDbSSL"));
|
||||
let connection = (0, serverless_mysql_1.default)({
|
||||
config: {
|
||||
host: process.env.DSQL_DB_HOST,
|
||||
user: process.env.DSQL_DB_USERNAME,
|
||||
password: process.env.DSQL_DB_PASSWORD,
|
||||
database: process.env.DSQL_DB_NAME,
|
||||
charset: "utf8mb4",
|
||||
ssl: (0, grabDbSSL_1.default)(),
|
||||
},
|
||||
});
|
||||
/**
|
||||
* # Main DB Handler Function
|
||||
*/
|
||||
function dbHandler(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ query, values, database, }) {
|
||||
/**
|
||||
* Switch Database
|
||||
*
|
||||
* @description If a database is provided, switch to it
|
||||
*/
|
||||
let isDbCorrect = true;
|
||||
if (database) {
|
||||
connection = (0, serverless_mysql_1.default)({
|
||||
config: {
|
||||
host: process.env.DSQL_DB_HOST,
|
||||
user: process.env.DSQL_DB_USERNAME,
|
||||
password: process.env.DSQL_DB_PASSWORD,
|
||||
database: database,
|
||||
charset: "utf8mb4",
|
||||
ssl: (0, grabDbSSL_1.default)(),
|
||||
},
|
||||
});
|
||||
}
|
||||
if (!isDbCorrect) {
|
||||
console.log("Shell Db Handler ERROR in switching Database! Operation Failed!");
|
||||
return null;
|
||||
}
|
||||
/**
|
||||
* Declare variables
|
||||
*
|
||||
* @description Declare "results" variable
|
||||
*/
|
||||
let results;
|
||||
/**
|
||||
* Fetch from db
|
||||
*
|
||||
* @description Fetch data from db if no cache
|
||||
*/
|
||||
try {
|
||||
if (query && values) {
|
||||
results = yield connection.query(query, values);
|
||||
}
|
||||
else {
|
||||
results = yield connection.query(query);
|
||||
}
|
||||
/** ********************* Clean up */
|
||||
yield connection.end();
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
if (process.env.FIRST_RUN) {
|
||||
return null;
|
||||
}
|
||||
console.log("ERROR in dbHandler =>", error.message);
|
||||
console.log(error);
|
||||
console.log(connection.config());
|
||||
fs_1.default.appendFileSync(path_1.default.resolve(__dirname, "../.tmp/dbErrorLogs.txt"), JSON.stringify(error, null, 4) + "\n" + Date() + "\n\n\n", "utf8");
|
||||
results = null;
|
||||
}
|
||||
/**
|
||||
* Return results
|
||||
*
|
||||
* @description Return results add to cache if "req" param is passed
|
||||
*/
|
||||
if (results) {
|
||||
return JSON.parse(JSON.stringify(results));
|
||||
}
|
||||
else {
|
||||
return null;
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
type Param = {
|
||||
columnData: import("../../types").DSQL_FieldSchemaType;
|
||||
primaryKeySet?: boolean;
|
||||
};
|
||||
type Return = {
|
||||
fieldEntryText: string;
|
||||
newPrimaryKeySet: boolean;
|
||||
};
|
||||
/**
|
||||
* # Generate Table Column Description
|
||||
*/
|
||||
export default function generateColumnDescription({ columnData, primaryKeySet, }: Param): Return;
|
||||
export {};
|
||||
@@ -0,0 +1,55 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = generateColumnDescription;
|
||||
/**
|
||||
* # Generate Table Column Description
|
||||
*/
|
||||
function generateColumnDescription({ columnData, primaryKeySet, }) {
|
||||
/**
|
||||
* Format tableInfoArray
|
||||
*
|
||||
* @description Format tableInfoArray
|
||||
*/
|
||||
const { fieldName, dataType, nullValue, primaryKey, autoIncrement, defaultValue, defaultValueLiteral, onUpdateLiteral, notNullValue, } = columnData;
|
||||
let fieldEntryText = "";
|
||||
fieldEntryText += `\`${fieldName}\` ${dataType}`;
|
||||
////////////////////////////////////////
|
||||
if (nullValue) {
|
||||
fieldEntryText += " DEFAULT NULL";
|
||||
}
|
||||
else if (defaultValueLiteral) {
|
||||
fieldEntryText += ` DEFAULT ${defaultValueLiteral}`;
|
||||
}
|
||||
else if (defaultValue) {
|
||||
if (String(defaultValue).match(/uuid\(\)/i)) {
|
||||
fieldEntryText += ` DEFAULT UUID()`;
|
||||
}
|
||||
else {
|
||||
fieldEntryText += ` DEFAULT '${defaultValue}'`;
|
||||
}
|
||||
}
|
||||
else if (notNullValue) {
|
||||
fieldEntryText += ` NOT NULL`;
|
||||
}
|
||||
////////////////////////////////////////
|
||||
if (onUpdateLiteral) {
|
||||
fieldEntryText += ` ON UPDATE ${onUpdateLiteral}`;
|
||||
}
|
||||
////////////////////////////////////////
|
||||
if (primaryKey && !primaryKeySet) {
|
||||
fieldEntryText += " PRIMARY KEY";
|
||||
primaryKeySet = true;
|
||||
}
|
||||
////////////////////////////////////////
|
||||
if (autoIncrement) {
|
||||
fieldEntryText += " AUTO_INCREMENT";
|
||||
primaryKeySet = true;
|
||||
}
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
return {
|
||||
fieldEntryText,
|
||||
newPrimaryKeySet: primaryKeySet || false,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
/**
|
||||
* # Create database from Schema Function
|
||||
*/
|
||||
export default function noDatabaseDbHandler(queryString: string): Promise<any>;
|
||||
@@ -0,0 +1,55 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = noDatabaseDbHandler;
|
||||
const dbHandler_1 = __importDefault(require("./dbHandler"));
|
||||
/**
|
||||
* # Create database from Schema Function
|
||||
*/
|
||||
function noDatabaseDbHandler(queryString) {
|
||||
return __awaiter(this, void 0, void 0, function* () {
|
||||
/**
|
||||
* Declare variables
|
||||
*
|
||||
* @description Declare "results" variable
|
||||
*/
|
||||
let results;
|
||||
/**
|
||||
* Fetch from db
|
||||
*
|
||||
* @description Fetch data from db if no cache
|
||||
*/
|
||||
try {
|
||||
/** ********************* Run Query */
|
||||
results = yield (0, dbHandler_1.default)({ query: queryString });
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
}
|
||||
catch (error) {
|
||||
console.log("ERROR in noDatabaseDbHandler =>", error.message);
|
||||
}
|
||||
/**
|
||||
* Return results
|
||||
*
|
||||
* @description Return results add to cache if "req" param is passed
|
||||
*/
|
||||
if (results) {
|
||||
return results;
|
||||
}
|
||||
else {
|
||||
return null;
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
/**
|
||||
* # Sulg To Camel Case
|
||||
*/
|
||||
export default function slugToCamelTitle(text: string): string | null;
|
||||
@@ -0,0 +1,19 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = slugToCamelTitle;
|
||||
/**
|
||||
* # Sulg To Camel Case
|
||||
*/
|
||||
function slugToCamelTitle(text) {
|
||||
if (text) {
|
||||
let addArray = text.split("-").filter((item) => item !== "");
|
||||
let camelArray = addArray.map((item) => {
|
||||
return (item.substr(0, 1).toUpperCase() + item.substr(1).toLowerCase());
|
||||
});
|
||||
let parsedAddress = camelArray.join(" ");
|
||||
return parsedAddress;
|
||||
}
|
||||
else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { DSQL_FieldSchemaType } from "../../types";
|
||||
type Param = {
|
||||
tableInfoArray: DSQL_FieldSchemaType[];
|
||||
};
|
||||
/**
|
||||
* # Supplement Table
|
||||
*/
|
||||
export default function supplementTable({ tableInfoArray }: Param): DSQL_FieldSchemaType[];
|
||||
export {};
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
@@ -0,0 +1,39 @@
|
||||
"use strict";
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = supplementTable;
|
||||
/**
|
||||
* # Supplement Table
|
||||
*/
|
||||
function supplementTable({ tableInfoArray }) {
|
||||
/**
|
||||
* Format tableInfoArray
|
||||
*
|
||||
* @description Format tableInfoArray
|
||||
*/
|
||||
let finalTableArray = tableInfoArray;
|
||||
const defaultFields = require("../../../package-shared/data/defaultFields.json");
|
||||
////////////////////////////////////////
|
||||
let primaryKeyExists = finalTableArray.filter((_field) => _field.primaryKey);
|
||||
////////////////////////////////////////
|
||||
defaultFields.forEach((field) => {
|
||||
let fieldExists = finalTableArray.filter((_field) => _field.fieldName === field.fieldName);
|
||||
if (fieldExists && fieldExists[0]) {
|
||||
return;
|
||||
}
|
||||
else if (field.fieldName === "id" && !primaryKeyExists[0]) {
|
||||
finalTableArray.unshift(field);
|
||||
}
|
||||
else {
|
||||
finalTableArray.push(field);
|
||||
}
|
||||
});
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
return finalTableArray;
|
||||
}
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
@@ -0,0 +1,19 @@
|
||||
type Param = {
|
||||
dbFullName: string;
|
||||
tableName: string;
|
||||
tableSchema: import("../../types").DSQL_TableSchemaType;
|
||||
tableNameFull?: string;
|
||||
tableInfoArray: import("../../types").DSQL_FieldSchemaType[];
|
||||
userId?: number | string | null;
|
||||
dbSchema: import("../../types").DSQL_DatabaseSchemaType[];
|
||||
tableIndexes?: import("../../types").DSQL_IndexSchemaType[];
|
||||
clone?: boolean;
|
||||
tableIndex?: number;
|
||||
childDb?: boolean;
|
||||
recordedDbEntry?: any;
|
||||
};
|
||||
/**
|
||||
* # Update table function
|
||||
*/
|
||||
export default function updateTable({ dbFullName, tableName, tableInfoArray, userId, dbSchema, tableIndexes, tableSchema, clone, childDb, tableIndex, tableNameFull, recordedDbEntry, }: Param): Promise<any>;
|
||||
export {};
|
||||
+417
@@ -0,0 +1,417 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = updateTable;
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const varDatabaseDbHandler_1 = __importDefault(require("./varDatabaseDbHandler"));
|
||||
const defaultFieldsRegexp = /^id$|^uuid$|^date_created$|^date_created_code$|^date_created_timestamp$|^date_updated$|^date_updated_code$|^date_updated_timestamp$/;
|
||||
const generateColumnDescription_1 = __importDefault(require("./generateColumnDescription"));
|
||||
const dbHandler_1 = __importDefault(require("./dbHandler"));
|
||||
/**
|
||||
* # Update table function
|
||||
*/
|
||||
function updateTable(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ dbFullName, tableName, tableInfoArray, userId, dbSchema, tableIndexes, tableSchema, clone, childDb, tableIndex, tableNameFull, recordedDbEntry, }) {
|
||||
/**
|
||||
* Initialize
|
||||
* ==========================================
|
||||
* @description Initial setup
|
||||
*/
|
||||
var _b;
|
||||
/** @type {any[]} */
|
||||
let errorLogs = [];
|
||||
/**
|
||||
* @description Initialize table info array. This value will be
|
||||
* changing depending on if a field is renamed or not.
|
||||
*/
|
||||
let upToDateTableFieldsArray = tableInfoArray;
|
||||
/**
|
||||
* Handle Table updates
|
||||
*
|
||||
* @description Try to undate table, catch error if anything goes wrong
|
||||
*/
|
||||
try {
|
||||
/**
|
||||
* @type {string[]}
|
||||
* @description Table update query string array
|
||||
*/
|
||||
const updateTableQueryArray = [];
|
||||
/**
|
||||
* @type {string[]}
|
||||
* @description Constriants query string array
|
||||
*/
|
||||
const constraintsQueryArray = [];
|
||||
/**
|
||||
* @description Push the query initial value
|
||||
*/
|
||||
updateTableQueryArray.push(`ALTER TABLE \`${tableName}\``);
|
||||
if (childDb) {
|
||||
try {
|
||||
if (!recordedDbEntry) {
|
||||
throw new Error("Recorded Db entry not found!");
|
||||
}
|
||||
const existingTable = yield (0, varDatabaseDbHandler_1.default)({
|
||||
database: "datasquirel",
|
||||
queryString: `SELECT * FROM user_database_tables WHERE db_id = ? AND table_slug = ?`,
|
||||
queryValuesArray: [recordedDbEntry.id, tableName],
|
||||
});
|
||||
/** @type {import("../../types").MYSQL_user_database_tables_table_def} */
|
||||
const table = existingTable === null || existingTable === void 0 ? void 0 : existingTable[0];
|
||||
if (!(table === null || table === void 0 ? void 0 : table.id)) {
|
||||
const newTableEntry = yield (0, dbHandler_1.default)({
|
||||
query: `INSERT INTO user_database_tables SET ?`,
|
||||
values: {
|
||||
user_id: recordedDbEntry.user_id,
|
||||
db_id: recordedDbEntry.id,
|
||||
db_slug: recordedDbEntry.db_slug,
|
||||
table_name: tableNameFull,
|
||||
table_slug: tableName,
|
||||
child_table: (tableSchema === null || tableSchema === void 0 ? void 0 : tableSchema.childTable) ? "1" : null,
|
||||
child_table_parent_database: (tableSchema === null || tableSchema === void 0 ? void 0 : tableSchema.childTableDbFullName) || null,
|
||||
child_table_parent_table: tableSchema.childTableName || null,
|
||||
date_created: Date(),
|
||||
date_created_code: Date.now(),
|
||||
date_updated: Date(),
|
||||
date_updated_code: Date.now(),
|
||||
},
|
||||
database: "datasquirel",
|
||||
});
|
||||
}
|
||||
}
|
||||
catch (error) { }
|
||||
}
|
||||
/**
|
||||
* @type {import("../../types").DSQL_MYSQL_SHOW_INDEXES_Type[]}
|
||||
* @description All indexes from MYSQL db
|
||||
*/ // @ts-ignore
|
||||
const allExistingIndexes = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: `SHOW INDEXES FROM \`${tableName}\``,
|
||||
database: dbFullName,
|
||||
});
|
||||
/**
|
||||
* @type {import("../../types").DSQL_MYSQL_SHOW_COLUMNS_Type[]}
|
||||
* @description All columns from MYSQL db
|
||||
*/ // @ts-ignore
|
||||
const allExistingColumns = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: `SHOW COLUMNS FROM \`${tableName}\``,
|
||||
database: dbFullName,
|
||||
});
|
||||
////////////////////////////////////////
|
||||
/**
|
||||
* @type {string[]}
|
||||
* @description Updated column names Array
|
||||
*/
|
||||
const updatedColumnsArray = [];
|
||||
/**
|
||||
* @description Iterate through every existing column
|
||||
*/
|
||||
for (let e = 0; e < allExistingColumns.length; e++) {
|
||||
const { Field } = allExistingColumns[e];
|
||||
if (Field.match(defaultFieldsRegexp))
|
||||
continue;
|
||||
/**
|
||||
* @description This finds out whether the fieldName corresponds with the MSQL Field name
|
||||
* if the fildName doesn't match any MYSQL Field name, the field is deleted.
|
||||
*/
|
||||
let existingEntry = upToDateTableFieldsArray.filter((column) => column.fieldName === Field || column.originName === Field);
|
||||
if (existingEntry && existingEntry[0]) {
|
||||
/**
|
||||
* @description Check if Field name has been updated
|
||||
*/
|
||||
if (existingEntry[0].updatedField &&
|
||||
existingEntry[0].fieldName) {
|
||||
updatedColumnsArray.push(existingEntry[0].fieldName);
|
||||
const renameColumn = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: `ALTER TABLE ${tableName} RENAME COLUMN \`${existingEntry[0].originName}\` TO \`${existingEntry[0].fieldName}\``,
|
||||
database: dbFullName,
|
||||
});
|
||||
console.log(`Column Renamed from "${existingEntry[0].originName}" to "${existingEntry[0].fieldName}"`);
|
||||
/**
|
||||
* Update Db Schema
|
||||
* ===================================================
|
||||
* @description Update Db Schema after renaming column
|
||||
*/
|
||||
try {
|
||||
const userSchemaData = dbSchema;
|
||||
const targetDbIndex = userSchemaData.findIndex((db) => db.dbFullName === dbFullName);
|
||||
const targetTableIndex = userSchemaData[targetDbIndex].tables.findIndex((table) => table.tableName === tableName);
|
||||
const targetFieldIndex = userSchemaData[targetDbIndex].tables[targetTableIndex].fields.findIndex((field) => field.fieldName === existingEntry[0].fieldName);
|
||||
delete userSchemaData[targetDbIndex].tables[targetTableIndex].fields[targetFieldIndex]["originName"];
|
||||
delete userSchemaData[targetDbIndex].tables[targetTableIndex].fields[targetFieldIndex]["updatedField"];
|
||||
/**
|
||||
* @description Set New Table Fields Array
|
||||
*/
|
||||
upToDateTableFieldsArray =
|
||||
userSchemaData[targetDbIndex].tables[targetTableIndex].fields;
|
||||
fs_1.default.writeFileSync(`${String(process.env.DSQL_USER_DB_SCHEMA_PATH)}/user-${userId}/main.json`, JSON.stringify(userSchemaData), "utf8");
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
console.log("Update table error =>", error.message);
|
||||
}
|
||||
////////////////////////////////////////
|
||||
}
|
||||
////////////////////////////////////////
|
||||
continue;
|
||||
////////////////////////////////////////
|
||||
}
|
||||
else {
|
||||
yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: `ALTER TABLE ${tableName} DROP COLUMN \`${Field}\``,
|
||||
database: dbFullName,
|
||||
});
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Handle MYSQL Table Indexes
|
||||
* ===================================================
|
||||
* @description Iterate through each table index(if available)
|
||||
* and perform operations
|
||||
*/
|
||||
for (let f = 0; f < allExistingIndexes.length; f++) {
|
||||
const { Key_name, Index_comment } = allExistingIndexes[f];
|
||||
/**
|
||||
* @description Check if this index was specifically created
|
||||
* by datasquirel
|
||||
*/
|
||||
if (Index_comment === null || Index_comment === void 0 ? void 0 : Index_comment.match(/schema_index/)) {
|
||||
try {
|
||||
const existingKeyInSchema = tableIndexes === null || tableIndexes === void 0 ? void 0 : tableIndexes.filter((indexObject) => indexObject.alias === Key_name);
|
||||
if (!(existingKeyInSchema === null || existingKeyInSchema === void 0 ? void 0 : existingKeyInSchema[0]))
|
||||
throw new Error(`This Index(${Key_name}) Has been Deleted!`);
|
||||
}
|
||||
catch (error) {
|
||||
/**
|
||||
* @description Drop Index: This happens when the MYSQL index is not
|
||||
* present in the datasquirel DB schema
|
||||
*/
|
||||
yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: `ALTER TABLE ${tableName} DROP INDEX \`${Key_name}\``,
|
||||
database: dbFullName,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Handle DATASQUIREL Table Indexes
|
||||
* ===================================================
|
||||
* @description Iterate through each datasquirel schema
|
||||
* table index(if available), and perform operations
|
||||
*/
|
||||
if (tableIndexes && tableIndexes[0]) {
|
||||
for (let g = 0; g < tableIndexes.length; g++) {
|
||||
const { indexType, indexName, indexTableFields, alias } = tableIndexes[g];
|
||||
if (!(alias === null || alias === void 0 ? void 0 : alias.match(/./)))
|
||||
continue;
|
||||
/**
|
||||
* @description Check for existing Index in MYSQL db
|
||||
*/
|
||||
try {
|
||||
const existingKeyInDb = allExistingIndexes.filter((indexObject) => indexObject.Key_name === alias);
|
||||
if (!existingKeyInDb[0])
|
||||
throw new Error("This Index Does not Exist");
|
||||
}
|
||||
catch (error) {
|
||||
/**
|
||||
* @description Create new index if determined that it
|
||||
* doesn't exist in MYSQL db
|
||||
*/
|
||||
yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: `CREATE${(indexType === null || indexType === void 0 ? void 0 : indexType.match(/fullText/i)) ? " FULLTEXT" : ""} INDEX \`${alias}\` ON ${tableName}(${indexTableFields === null || indexTableFields === void 0 ? void 0 : indexTableFields.map((nm) => nm.value).map((nm) => `\`${nm}\``).join(",")}) COMMENT 'schema_index'`,
|
||||
database: dbFullName,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Handle MYSQL Foreign Keys
|
||||
* ===================================================
|
||||
* @description Iterate through each datasquirel schema
|
||||
* table index(if available), and perform operations
|
||||
*/
|
||||
/**
|
||||
* @description All MSQL Foreign Keys
|
||||
* @type {import("../../types").DSQL_MYSQL_FOREIGN_KEYS_Type[] | null}
|
||||
*/ // @ts-ignore
|
||||
const allForeignKeys = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: `SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE CONSTRAINT_SCHEMA = '${dbFullName}' AND TABLE_NAME='${tableName}' AND CONSTRAINT_TYPE='FOREIGN KEY'`,
|
||||
database: dbFullName,
|
||||
});
|
||||
if (allForeignKeys) {
|
||||
for (let c = 0; c < allForeignKeys.length; c++) {
|
||||
const { CONSTRAINT_NAME } = allForeignKeys[c];
|
||||
/**
|
||||
* @description Skip if Key is the PRIMARY Key
|
||||
*/
|
||||
if (CONSTRAINT_NAME.match(/PRIMARY/))
|
||||
continue;
|
||||
/**
|
||||
* @description Drop all foreign Keys to avoid MYSQL errors when adding/updating
|
||||
* Foreign keys
|
||||
*/
|
||||
const dropForeignKey = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: `ALTER TABLE ${tableName} DROP FOREIGN KEY \`${CONSTRAINT_NAME}\``,
|
||||
database: dbFullName,
|
||||
});
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Handle DATASQUIREL schema fields for current table
|
||||
* ===================================================
|
||||
* @description Iterate through each field object and
|
||||
* perform operations
|
||||
*/
|
||||
for (let i = 0; i < upToDateTableFieldsArray.length; i++) {
|
||||
const column = upToDateTableFieldsArray[i];
|
||||
const prevColumn = upToDateTableFieldsArray[i - 1];
|
||||
const nextColumn = upToDateTableFieldsArray[i + 1];
|
||||
const { fieldName, dataType, nullValue, primaryKey, autoIncrement, defaultValue, defaultValueLiteral, foreignKey, updatedField, } = column;
|
||||
////////////////////////////////////////
|
||||
/**
|
||||
* @description Skip default fields
|
||||
*/
|
||||
if (fieldName === null || fieldName === void 0 ? void 0 : fieldName.match(/^id$|^date_/))
|
||||
continue;
|
||||
/**
|
||||
* @description Skip columns that have been updated recently
|
||||
*/
|
||||
// if (updatedColumnsArray.includes(fieldName)) continue;
|
||||
////////////////////////////////////////
|
||||
let updateText = "";
|
||||
////////////////////////////////////////
|
||||
/** @type {any} */
|
||||
let existingColumnIndex;
|
||||
/**
|
||||
* @description Existing MYSQL field object
|
||||
*/
|
||||
let existingColumn = allExistingColumns && allExistingColumns[0]
|
||||
? allExistingColumns.filter((_column, _index) => {
|
||||
if (_column.Field === fieldName) {
|
||||
existingColumnIndex = _index;
|
||||
return true;
|
||||
}
|
||||
})
|
||||
: null;
|
||||
/**
|
||||
* @description Construct SQL text snippet for this field
|
||||
*/
|
||||
let { fieldEntryText } = (0, generateColumnDescription_1.default)({
|
||||
columnData: column,
|
||||
});
|
||||
/**
|
||||
* @description Modify Column(Field) if it already exists
|
||||
* in MYSQL database
|
||||
*/
|
||||
if (existingColumn && ((_b = existingColumn[0]) === null || _b === void 0 ? void 0 : _b.Field)) {
|
||||
const { Field, Type, Null, Key, Default, Extra } = existingColumn[0];
|
||||
let isColumnReordered = i < existingColumnIndex;
|
||||
if (Field === fieldName &&
|
||||
!isColumnReordered &&
|
||||
(dataType === null || dataType === void 0 ? void 0 : dataType.toUpperCase()) === Type.toUpperCase()) {
|
||||
updateText += `MODIFY COLUMN ${fieldEntryText}`;
|
||||
// continue;
|
||||
}
|
||||
else {
|
||||
if (userId) {
|
||||
updateText += `MODIFY COLUMN ${fieldEntryText}${isColumnReordered
|
||||
? (prevColumn === null || prevColumn === void 0 ? void 0 : prevColumn.fieldName)
|
||||
? " AFTER `" + prevColumn.fieldName + "`"
|
||||
: (nextColumn === null || nextColumn === void 0 ? void 0 : nextColumn.fieldName)
|
||||
? " BEFORE `" + nextColumn.fieldName + "`"
|
||||
: ""
|
||||
: ""}`;
|
||||
}
|
||||
else {
|
||||
updateText += `MODIFY COLUMN ${fieldEntryText}`;
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (prevColumn && prevColumn.fieldName) {
|
||||
/**
|
||||
* @description Add new Column AFTER previous column, if
|
||||
* previous column exists
|
||||
*/
|
||||
updateText += `ADD COLUMN ${fieldEntryText} AFTER \`${prevColumn.fieldName}\``;
|
||||
}
|
||||
else if (nextColumn && nextColumn.fieldName) {
|
||||
/**
|
||||
* @description Add new Column BEFORE next column, if
|
||||
* next column exists
|
||||
*/
|
||||
updateText += `ADD COLUMN ${fieldEntryText} BEFORE \`${nextColumn.fieldName}\``;
|
||||
}
|
||||
else {
|
||||
/**
|
||||
* @description Append new column to the end of existing columns
|
||||
*/
|
||||
updateText += `ADD COLUMN ${fieldEntryText}`;
|
||||
}
|
||||
////////////////////////////////////////
|
||||
/**
|
||||
* @description Pust SQL code snippet to updateTableQueryArray Array
|
||||
* Add a comma(,) to separate from the next snippet
|
||||
*/
|
||||
updateTableQueryArray.push(updateText + ",");
|
||||
/**
|
||||
* @description Handle foreing keys if available, and if there is no
|
||||
* "clone" boolean = true
|
||||
*/
|
||||
if (!clone && foreignKey) {
|
||||
const { destinationTableName, destinationTableColumnName, cascadeDelete, cascadeUpdate, foreignKeyName, } = foreignKey;
|
||||
const foreinKeyText = `ADD CONSTRAINT \`${foreignKeyName}\` FOREIGN KEY (\`${fieldName}\`) REFERENCES \`${destinationTableName}\`(\`${destinationTableColumnName}\`)${cascadeDelete ? " ON DELETE CASCADE" : ""}${cascadeUpdate ? " ON UPDATE CASCADE" : ""}`;
|
||||
// const foreinKeyText = `ADD CONSTRAINT \`${foreignKeyName}\` FOREIGN KEY (${fieldName}) REFERENCES ${destinationTableName}(${destinationTableColumnName})${cascadeDelete ? " ON DELETE CASCADE" : ""}${cascadeUpdate ? " ON UPDATE CASCADE" : ""}` + ",";
|
||||
const finalQueryString = `ALTER TABLE \`${tableName}\` ${foreinKeyText}`;
|
||||
const addForeignKey = yield (0, varDatabaseDbHandler_1.default)({
|
||||
database: dbFullName,
|
||||
queryString: finalQueryString,
|
||||
});
|
||||
if (!(addForeignKey === null || addForeignKey === void 0 ? void 0 : addForeignKey.serverStatus)) {
|
||||
errorLogs.push(addForeignKey);
|
||||
}
|
||||
}
|
||||
////////////////////////////////////////
|
||||
}
|
||||
/**
|
||||
* @description Construct final SQL query by combning all SQL snippets in
|
||||
* updateTableQueryArray Arry, and trimming the final comma(,)
|
||||
*/
|
||||
const updateTableQuery = updateTableQueryArray
|
||||
.join(" ")
|
||||
.replace(/,$/, "");
|
||||
////////////////////////////////////////
|
||||
/**
|
||||
* @description Check if SQL snippets array has more than 1 entries
|
||||
* This is because 1 entry means "ALTER TABLE table_name" only, without any
|
||||
* Alter directives like "ADD COLUMN" or "MODIFY COLUMN"
|
||||
*/
|
||||
if (updateTableQueryArray.length > 1) {
|
||||
const updateTable = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: updateTableQuery,
|
||||
database: dbFullName,
|
||||
});
|
||||
return updateTable;
|
||||
}
|
||||
else {
|
||||
/**
|
||||
* @description If only 1 SQL snippet is left in updateTableQueryArray, this
|
||||
* means that no updates have been made to the table
|
||||
*/
|
||||
return "No Changes Made to Table";
|
||||
}
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
console.log('Error in "updateTable" shell function =>', error.message);
|
||||
return "Error in Updating Table";
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { DSQL_TableSchemaType } from "../../types";
|
||||
type Param = {
|
||||
queryString: string;
|
||||
queryValuesArray?: string[];
|
||||
database?: string;
|
||||
tableSchema?: DSQL_TableSchemaType;
|
||||
};
|
||||
/**
|
||||
* # DB handler for specific database
|
||||
*/
|
||||
export default function varDatabaseDbHandler({ queryString, queryValuesArray, database, tableSchema, }: Param): Promise<any>;
|
||||
export {};
|
||||
@@ -0,0 +1,64 @@
|
||||
"use strict";
|
||||
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
||||
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
||||
return new (P || (P = Promise))(function (resolve, reject) {
|
||||
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
||||
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
||||
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
||||
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
||||
});
|
||||
};
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = varDatabaseDbHandler;
|
||||
const dbHandler_1 = __importDefault(require("./dbHandler"));
|
||||
/**
|
||||
* # DB handler for specific database
|
||||
*/
|
||||
function varDatabaseDbHandler(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ queryString, queryValuesArray, database, tableSchema, }) {
|
||||
/**
|
||||
* Declare variables
|
||||
*
|
||||
* @description Declare "results" variable
|
||||
*/
|
||||
let results;
|
||||
/**
|
||||
* Fetch from db
|
||||
*
|
||||
* @description Fetch data from db if no cache
|
||||
*/
|
||||
try {
|
||||
if (queryString &&
|
||||
queryValuesArray &&
|
||||
Array.isArray(queryValuesArray) &&
|
||||
queryValuesArray[0]) {
|
||||
results = yield (0, dbHandler_1.default)({
|
||||
query: queryString,
|
||||
values: queryValuesArray,
|
||||
database,
|
||||
});
|
||||
}
|
||||
else {
|
||||
results = yield (0, dbHandler_1.default)({
|
||||
query: queryString,
|
||||
database,
|
||||
});
|
||||
}
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
}
|
||||
catch ( /** @type {any} */error) {
|
||||
console.log("Shell Vardb Error =>", error.message);
|
||||
}
|
||||
/**
|
||||
* Return results
|
||||
*
|
||||
* @description Return results add to cache if "req" param is passed
|
||||
*/
|
||||
return results;
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user