Updates
This commit is contained in:
@@ -1,57 +0,0 @@
|
||||
// @ts-check
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
require("dotenv").config({ path: "./../.env" });
|
||||
const mysql = require("serverless-mysql");
|
||||
const grabDbSSL = require("../utils/backend/grabDbSSL");
|
||||
|
||||
const connection = mysql({
|
||||
config: {
|
||||
host: process.env.DSQL_DB_HOST,
|
||||
user: process.env.DSQL_DB_USERNAME,
|
||||
password: process.env.DSQL_DB_PASSWORD,
|
||||
database: process.env.DSQL_DB_NAME,
|
||||
charset: "utf8mb4",
|
||||
ssl: grabDbSSL(),
|
||||
},
|
||||
});
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* # Main DB Handler Function
|
||||
* @async
|
||||
*
|
||||
* @param {object} params
|
||||
* @param {string} params.query
|
||||
* @param {string[] | object} [params.values]
|
||||
* @param {string} [params.database]
|
||||
*
|
||||
* @returns {Promise<object|null>}
|
||||
*/
|
||||
(async () => {
|
||||
/**
|
||||
* Switch Database
|
||||
*
|
||||
* @description If a database is provided, switch to it
|
||||
*/
|
||||
try {
|
||||
const result = await connection.query(
|
||||
"SELECT id,first_name,last_name FROM users LIMIT 3"
|
||||
);
|
||||
console.log("Connection Query Success =>", result);
|
||||
} catch (/** @type {any} */ error) {
|
||||
console.log("Connection query ERROR =>", error.message);
|
||||
} finally {
|
||||
connection.end();
|
||||
process.exit();
|
||||
}
|
||||
})();
|
||||
Executable
+30
@@ -0,0 +1,30 @@
|
||||
require("dotenv").config({ path: "./../.env" });
|
||||
import mysql from "serverless-mysql";
|
||||
import grabDbSSL from "../utils/backend/grabDbSSL";
|
||||
|
||||
/**
|
||||
* # 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>}
|
||||
*/
|
||||
(async () => {
|
||||
const connection = global.DSQL_DB_CONN;
|
||||
|
||||
try {
|
||||
const result = await connection.query(
|
||||
"SELECT id,first_name,last_name FROM users LIMIT 3"
|
||||
);
|
||||
console.log("Connection Query Success =>", result);
|
||||
} catch (error: any) {
|
||||
console.log("Connection query ERROR =>", error.message);
|
||||
} finally {
|
||||
connection.end();
|
||||
process.exit();
|
||||
}
|
||||
})();
|
||||
+49
-53
@@ -1,28 +1,37 @@
|
||||
// @ts-check
|
||||
import path from "path";
|
||||
import fs from "fs";
|
||||
|
||||
const path = require("path");
|
||||
const fs = require("fs");
|
||||
import noDatabaseDbHandler from "./utils/noDatabaseDbHandler";
|
||||
import varDatabaseDbHandler from "./utils/varDatabaseDbHandler";
|
||||
import createTable from "./utils/createTable";
|
||||
import updateTable from "./utils/updateTable";
|
||||
import dbHandler from "./utils/dbHandler";
|
||||
import EJSON from "../utils/ejson";
|
||||
import { DSQL_DatabaseSchemaType } from "../types";
|
||||
|
||||
require("dotenv").config({ path: "./../.env" });
|
||||
|
||||
const noDatabaseDbHandler = require("./utils/noDatabaseDbHandler");
|
||||
const varDatabaseDbHandler = require("./utils/varDatabaseDbHandler");
|
||||
const createTable = require("./utils/createTable");
|
||||
const updateTable = require("./utils/updateTable");
|
||||
const dbHandler = require("./utils/dbHandler");
|
||||
const EJSON = require("../utils/ejson");
|
||||
|
||||
const execFlag = process.argv.find((arg) => arg === "--exec");
|
||||
type Param = {
|
||||
userId?: number | string | null;
|
||||
targetDatabase?: string;
|
||||
dbSchemaData?: import("../types").DSQL_DatabaseSchemaType[];
|
||||
};
|
||||
|
||||
/**
|
||||
* Create database from Schema Function
|
||||
* =============================================
|
||||
* @param {object} params - Single object params
|
||||
* @param {number|string|null} [params.userId] - User ID or null
|
||||
* @param {string} [params.targetDatabase] - User Database full name
|
||||
* @param {import("../types").DSQL_DatabaseSchemaType[]} [params.dbSchemaData]
|
||||
* # Create database from Schema Function
|
||||
* @requires DSQL_DB_CONN - Gobal Variable for Datasquirel Database
|
||||
*/
|
||||
async function createDbFromSchema({ userId, targetDatabase, dbSchemaData }) {
|
||||
export default async function createDbFromSchema({
|
||||
userId,
|
||||
targetDatabase,
|
||||
dbSchemaData,
|
||||
}: Param) {
|
||||
console.log("///////////////////////////////");
|
||||
console.log("///////////////////////////////");
|
||||
console.log("Rebuilding Database ...");
|
||||
console.log("process.env.DSQL_DB_HOST", process.env.DSQL_DB_HOST);
|
||||
console.log("process.env.DSQL_DB_USERNAME", process.env.DSQL_DB_USERNAME);
|
||||
console.log("process.env.DSQL_DB_PASSWORD", process.env.DSQL_DB_PASSWORD);
|
||||
console.log("process.env.DSQL_DB_NAME", process.env.DSQL_DB_NAME);
|
||||
|
||||
const schemaPath = userId
|
||||
? path.join(
|
||||
String(process.env.DSQL_USER_DB_SCHEMA_PATH),
|
||||
@@ -30,12 +39,11 @@ async function createDbFromSchema({ userId, targetDatabase, dbSchemaData }) {
|
||||
)
|
||||
: path.resolve(__dirname, "../../jsonData/dbSchemas/main.json");
|
||||
|
||||
/** @type {import("../types").DSQL_DatabaseSchemaType[] | undefined} */
|
||||
const dbSchema =
|
||||
const dbSchema: DSQL_DatabaseSchemaType[] | undefined =
|
||||
dbSchemaData ||
|
||||
/** @type {import("../types").DSQL_DatabaseSchemaType[] | undefined} */ (
|
||||
EJSON.parse(fs.readFileSync(schemaPath, "utf8"))
|
||||
);
|
||||
(EJSON.parse(fs.readFileSync(schemaPath, "utf8")) as
|
||||
| DSQL_DatabaseSchemaType[]
|
||||
| undefined);
|
||||
|
||||
if (!dbSchema) {
|
||||
console.log("Schema Not Found!");
|
||||
@@ -45,8 +53,8 @@ async function createDbFromSchema({ userId, targetDatabase, dbSchemaData }) {
|
||||
// await createDatabasesFromSchema(dbSchema);
|
||||
|
||||
for (let i = 0; i < dbSchema.length; i++) {
|
||||
/** @type {import("../types").DSQL_DatabaseSchemaType} */
|
||||
const database = dbSchema[i];
|
||||
const database: DSQL_DatabaseSchemaType = dbSchema[i];
|
||||
|
||||
const { dbFullName, tables, dbName, dbSlug, childrenDatabases } =
|
||||
database;
|
||||
|
||||
@@ -55,13 +63,11 @@ async function createDbFromSchema({ userId, targetDatabase, dbSchemaData }) {
|
||||
}
|
||||
|
||||
/** @type {any} */
|
||||
const dbCheck = await noDatabaseDbHandler(
|
||||
const dbCheck: any = await noDatabaseDbHandler(
|
||||
`SELECT SCHEMA_NAME AS dbFullName FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '${dbFullName}'`
|
||||
);
|
||||
|
||||
if (dbCheck && dbCheck[0]?.dbFullName) {
|
||||
// Database Exists
|
||||
} else {
|
||||
if (!dbCheck?.[0]?.dbFullName) {
|
||||
const newDatabase = await noDatabaseDbHandler(
|
||||
`CREATE DATABASE IF NOT EXISTS \`${dbFullName}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_bin`
|
||||
);
|
||||
@@ -72,7 +78,7 @@ async function createDbFromSchema({ userId, targetDatabase, dbSchemaData }) {
|
||||
* @type {any}
|
||||
* @description Select All tables in target database
|
||||
*/
|
||||
const allTables = await noDatabaseDbHandler(
|
||||
const allTables: any = await noDatabaseDbHandler(
|
||||
`SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA='${dbFullName}'`
|
||||
);
|
||||
|
||||
@@ -102,20 +108,17 @@ async function createDbFromSchema({ userId, targetDatabase, dbSchemaData }) {
|
||||
if (oldTableFilteredArray && oldTableFilteredArray[0]) {
|
||||
console.log("Renaming Table");
|
||||
await varDatabaseDbHandler({
|
||||
queryString: `RENAME TABLE \`${oldTableFilteredArray[0].tableNameOld}\` TO \`${oldTableFilteredArray[0].tableName}\``,
|
||||
database: dbFullName,
|
||||
queryString: `RENAME TABLE \`${dbFullName}\`.\`${oldTableFilteredArray[0].tableNameOld}\` TO \`${oldTableFilteredArray[0].tableName}\``,
|
||||
});
|
||||
} else {
|
||||
console.log(`Dropping Table from ${dbFullName}`);
|
||||
await varDatabaseDbHandler({
|
||||
queryString: `DROP TABLE \`${TABLE_NAME}\``,
|
||||
database: dbFullName,
|
||||
queryString: `DROP TABLE \`${dbFullName}\`.\`${TABLE_NAME}\``,
|
||||
});
|
||||
|
||||
const deleteTableEntry = await dbHandler({
|
||||
query: `DELETE FROM user_database_tables WHERE user_id = ? AND db_slug = ? AND table_slug = ?`,
|
||||
query: `DELETE FROM datasquirel.user_database_tables WHERE user_id = ? AND db_slug = ? AND table_slug = ?`,
|
||||
values: [userId, dbSlug, TABLE_NAME],
|
||||
database: "datasquirel",
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -123,8 +126,7 @@ async function createDbFromSchema({ userId, targetDatabase, dbSchemaData }) {
|
||||
|
||||
const recordedDbEntryArray = userId
|
||||
? await varDatabaseDbHandler({
|
||||
database: "datasquirel",
|
||||
queryString: `SELECT * FROM user_databases WHERE db_full_name = ?`,
|
||||
queryString: `SELECT * FROM datasquirel.user_databases WHERE db_full_name = ?`,
|
||||
queryValuesArray: [dbFullName],
|
||||
})
|
||||
: undefined;
|
||||
@@ -143,7 +145,7 @@ async function createDbFromSchema({ userId, targetDatabase, dbSchemaData }) {
|
||||
* @description Check if table exists
|
||||
* @type {any}
|
||||
*/
|
||||
const tableCheck = await varDatabaseDbHandler({
|
||||
const tableCheck: any = await varDatabaseDbHandler({
|
||||
queryString: `
|
||||
SELECT EXISTS (
|
||||
SELECT
|
||||
@@ -155,7 +157,6 @@ async function createDbFromSchema({ userId, targetDatabase, dbSchemaData }) {
|
||||
TABLE_NAME = ?
|
||||
) AS tableExists`,
|
||||
queryValuesArray: [dbFullName, table.tableName],
|
||||
database: dbFullName,
|
||||
});
|
||||
|
||||
////////////////////////////////////////
|
||||
@@ -209,7 +210,6 @@ async function createDbFromSchema({ userId, targetDatabase, dbSchemaData }) {
|
||||
tableName: tableName,
|
||||
tableInfoArray: fields,
|
||||
dbFullName: dbFullName,
|
||||
dbSchema,
|
||||
tableSchema: table,
|
||||
recordedDbEntry,
|
||||
});
|
||||
@@ -240,10 +240,9 @@ async function createDbFromSchema({ userId, targetDatabase, dbSchemaData }) {
|
||||
* @type {import("../types").DSQL_MYSQL_SHOW_INDEXES_Type[]}
|
||||
* @description All indexes from MYSQL db
|
||||
*/ // @ts-ignore
|
||||
const allExistingIndexes =
|
||||
const allExistingIndexes: import("../types").DSQL_MYSQL_SHOW_INDEXES_Type[] =
|
||||
await varDatabaseDbHandler({
|
||||
queryString: `SHOW INDEXES FROM \`${tableName}\``,
|
||||
database: dbFullName,
|
||||
queryString: `SHOW INDEXES FROM \`${dbFullName}\`.\`${tableName}\``,
|
||||
});
|
||||
|
||||
const existingKeyInDb =
|
||||
@@ -265,11 +264,10 @@ async function createDbFromSchema({ userId, targetDatabase, dbSchemaData }) {
|
||||
indexType?.match(/fullText/i)
|
||||
? " FULLTEXT"
|
||||
: ""
|
||||
} INDEX \`${alias}\` ON ${tableName}(${indexTableFields
|
||||
} INDEX \`${alias}\` ON \`${dbFullName}\`.\`${tableName}\`(${indexTableFields
|
||||
?.map((nm) => nm.value)
|
||||
.map((nm) => `\`${nm}\``)
|
||||
.join(",")}) COMMENT 'schema_index'`,
|
||||
database: dbFullName,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -293,10 +291,8 @@ async function createDbFromSchema({ userId, targetDatabase, dbSchemaData }) {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = createDbFromSchema;
|
||||
|
||||
if (execFlag) {
|
||||
createDbFromSchema({});
|
||||
console.log("Database Successfully Rebuilt!");
|
||||
console.log("///////////////////////////////");
|
||||
console.log("///////////////////////////////");
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
// @ts-check
|
||||
|
||||
const fs = require("fs");
|
||||
|
||||
async function deploy() {}
|
||||
|
||||
deploy();
|
||||
Executable
+5
@@ -0,0 +1,5 @@
|
||||
import fs from "fs";
|
||||
|
||||
async function deploy() {}
|
||||
|
||||
deploy();
|
||||
+2
-13
@@ -1,10 +1,6 @@
|
||||
// @ts-check
|
||||
|
||||
require("dotenv").config({ path: "./../.env" });
|
||||
|
||||
////////////////////////////////////////
|
||||
|
||||
const varDatabaseDbHandler = require("../functions/backend/varDatabaseDbHandler");
|
||||
import varDatabaseDbHandler from "../functions/backend/varDatabaseDbHandler";
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
@@ -36,23 +32,16 @@ varDatabaseDbHandler({
|
||||
|
||||
const tableInfo = await varDatabaseDbHandler({
|
||||
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 = await varDatabaseDbHandler({
|
||||
queryString: `ALTER DATABASE ${db_full_name} CHARACTER SET = utf8mb4 COLLATE = utf8mb4_bin;`,
|
||||
database: db_full_name,
|
||||
});
|
||||
|
||||
const updateEncoding = await varDatabaseDbHandler({
|
||||
queryString: `ALTER TABLE \`${table_slug}\` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_bin`,
|
||||
database: db_full_name,
|
||||
queryString: `ALTER TABLE \`${db_full_name}\`.\`${table_slug}\` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_bin`,
|
||||
});
|
||||
}
|
||||
|
||||
process.exit();
|
||||
});
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
+2
-4
@@ -1,7 +1,5 @@
|
||||
// @ts-check
|
||||
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
|
||||
const jsonFile = path.resolve(__dirname, "../../jsonData/userPriviledges.json");
|
||||
const base64File = Buffer.from(fs.readFileSync(jsonFile, "utf8")).toString(
|
||||
@@ -1,79 +0,0 @@
|
||||
// @ts-check
|
||||
|
||||
require("dotenv").config({ path: "./../.env" });
|
||||
|
||||
const serverError = require("../functions/backend/serverError");
|
||||
const noDatabaseDbHandler = require("./utils/noDatabaseDbHandler");
|
||||
////////////////////////////////////////
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
/**
|
||||
* # Create Database From Schema
|
||||
* @param {object} param0
|
||||
* @param {string | null} param0.userId
|
||||
*/
|
||||
async function createDbFromSchema({ userId }) {
|
||||
/**
|
||||
* Grab Schema
|
||||
*
|
||||
* @description Grab Schema
|
||||
*/
|
||||
try {
|
||||
const defaultMariadbUserHost = process.env.DSQL_DB_HOST || "127.0.0.1";
|
||||
|
||||
const allDatabases = await noDatabaseDbHandler(`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 = await noDatabaseDbHandler(
|
||||
`GRANT ALL PRIVILEGES ON ${Database}.* TO '${process.env.DSQL_DB_FULL_ACCESS_USERNAME}'@'%' WITH GRANT OPTION`
|
||||
);
|
||||
|
||||
const grantRead = await noDatabaseDbHandler(
|
||||
`GRANT SELECT ON ${Database}.* TO '${process.env.DSQL_DB_READ_ONLY_USERNAME}'@'%'`
|
||||
);
|
||||
}
|
||||
|
||||
const flushPriviledged = await noDatabaseDbHandler(`FLUSH PRIVILEGES`);
|
||||
} catch (/** @type {any} */ error) {
|
||||
serverError({
|
||||
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];
|
||||
|
||||
createDbFromSchema({ userId: userArg ? externalUser : null });
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
require("dotenv").config({ path: "./../.env" });
|
||||
import serverError from "../functions/backend/serverError";
|
||||
import noDatabaseDbHandler from "./utils/noDatabaseDbHandler";
|
||||
|
||||
/**
|
||||
* # Create Database From Schema
|
||||
*/
|
||||
async function grantFullPrivileges({ userId }: { userId: string | null }) {
|
||||
/**
|
||||
* Grab Schema
|
||||
*
|
||||
* @description Grab Schema
|
||||
*/
|
||||
try {
|
||||
const defaultMariadbUserHost = process.env.DSQL_DB_HOST || "127.0.0.1";
|
||||
|
||||
const allDatabases = await noDatabaseDbHandler(`SHOW DATABASES`);
|
||||
|
||||
const datasquirelUserDatabases = allDatabases.filter(
|
||||
(/** @type {any} */ database: any) =>
|
||||
database.Database.match(/datasquirel_user_/)
|
||||
);
|
||||
|
||||
for (let i = 0; i < datasquirelUserDatabases.length; i++) {
|
||||
const datasquirelUserDatabase = datasquirelUserDatabases[i];
|
||||
const { Database } = datasquirelUserDatabase;
|
||||
|
||||
const grantDbPriviledges = await noDatabaseDbHandler(
|
||||
`GRANT ALL PRIVILEGES ON ${Database}.* TO '${process.env.DSQL_DB_FULL_ACCESS_USERNAME}'@'%' WITH GRANT OPTION`
|
||||
);
|
||||
|
||||
const grantRead = await noDatabaseDbHandler(
|
||||
`GRANT SELECT ON ${Database}.* TO '${process.env.DSQL_DB_READ_ONLY_USERNAME}'@'%'`
|
||||
);
|
||||
}
|
||||
|
||||
const flushPriviledged = await noDatabaseDbHandler(`FLUSH PRIVILEGES`);
|
||||
} catch (/** @type {any} */ error: any) {
|
||||
serverError({
|
||||
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 });
|
||||
+10
-14
@@ -1,5 +1,5 @@
|
||||
const fs = require("fs");
|
||||
const { exec } = require("child_process");
|
||||
import fs from "fs";
|
||||
import { exec } from "child_process";
|
||||
|
||||
require("dotenv").config({ path: "./../.env" });
|
||||
|
||||
@@ -12,24 +12,21 @@ const destinationFile =
|
||||
? process.argv[process.argv.indexOf("--dst") + 1]
|
||||
: null;
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
console.log("Running Less compiler ...");
|
||||
|
||||
const sourceFiles = sourceFile.split(",");
|
||||
const dstFiles = destinationFile.split(",");
|
||||
const sourceFiles = sourceFile?.split(",");
|
||||
const dstFiles = 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.watch(srcFolder, { recursive: true }, (evtType, prev) => {
|
||||
if (prev?.match(/\(/) || prev?.match(/\.js$/i)) {
|
||||
if (prev?.match(/\(/) || prev?.match(/\.(j|t)s$/i)) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -61,11 +58,10 @@ for (let i = 0; i < sourceFiles.length; i++) {
|
||||
: finalDstPath.replace(/\/$/, "") + "/_main.css"
|
||||
}`,
|
||||
(error, stdout, stderr) => {
|
||||
/** @type {Error} */
|
||||
if (error) {
|
||||
console.log("ERROR =>", error.message);
|
||||
|
||||
if (!evtType?.match(/change/i) && prev.match(/\[/)) {
|
||||
if (!evtType?.match(/change/i) && prev?.match(/\[/)) {
|
||||
fs.unlinkSync(finalDstPath);
|
||||
}
|
||||
|
||||
+22
-23
@@ -1,26 +1,27 @@
|
||||
// @ts-check
|
||||
import noDatabaseDbHandler from "../utils/noDatabaseDbHandler";
|
||||
|
||||
const noDatabaseDbHandler = require("../utils/noDatabaseDbHandler");
|
||||
export interface GrantType {
|
||||
database: string;
|
||||
table: string;
|
||||
privileges: string[];
|
||||
}
|
||||
|
||||
type Param = {
|
||||
username?: string;
|
||||
host?: string;
|
||||
grants?: GrantType[];
|
||||
userId: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* @typedef {object} GrantType
|
||||
* @property {string} database - Database Name
|
||||
* @property {string} table - Table Name
|
||||
* @property {string[]} privileges - Privileges
|
||||
* # Handle Grants for Users
|
||||
*/
|
||||
|
||||
/**
|
||||
* Handle Grants for Users
|
||||
* ================================================
|
||||
* @param {object} params - Single object params
|
||||
* @param {string} params.username - Username
|
||||
* @param {string} params.host - Host
|
||||
* @param {GrantType[]} params.grants - Grants
|
||||
* @param {string} params.userId
|
||||
*
|
||||
* @returns {Promise<boolean>} success
|
||||
*/
|
||||
async function handleGrants({ username, host, grants, userId }) {
|
||||
export default async function handleGrants({
|
||||
username,
|
||||
host,
|
||||
grants,
|
||||
userId,
|
||||
}: Param): Promise<boolean> {
|
||||
let success = false;
|
||||
|
||||
console.log(`Handling Grants for User =>`, username, host);
|
||||
@@ -72,7 +73,7 @@ async function handleGrants({ username, host, grants, userId }) {
|
||||
/**
|
||||
* @type {GrantType[]}
|
||||
*/
|
||||
const grantsArray = grants;
|
||||
const grantsArray: GrantType[] = grants;
|
||||
|
||||
for (let i = 0; i < grantsArray.length; i++) {
|
||||
const grantObject = grantsArray[i];
|
||||
@@ -95,11 +96,9 @@ async function handleGrants({ username, host, grants, userId }) {
|
||||
}
|
||||
|
||||
success = true;
|
||||
} catch (/** @type {any} */ error) {
|
||||
} catch (/** @type {any} */ error: any) {
|
||||
console.log(`Error in adding SQL user =>`, error.message);
|
||||
}
|
||||
|
||||
return success;
|
||||
}
|
||||
|
||||
module.exports = handleGrants;
|
||||
+74
-87
@@ -1,52 +1,53 @@
|
||||
// @ts-check
|
||||
|
||||
const path = require("path");
|
||||
import path from "path";
|
||||
require("dotenv").config({ path: path.resolve(__dirname, "../../../.env") });
|
||||
|
||||
const generator = require("generate-password");
|
||||
const noDatabaseDbHandler = require("../utils/noDatabaseDbHandler");
|
||||
const dbHandler = require("../utils/dbHandler");
|
||||
const handleGrants = require("./handleGrants");
|
||||
const encrypt = require("../../functions/dsql/encrypt");
|
||||
const decrypt = require("../../functions/dsql/decrypt");
|
||||
import generator from "generate-password";
|
||||
import noDatabaseDbHandler from "../utils/noDatabaseDbHandler";
|
||||
import dbHandler from "../utils/dbHandler";
|
||||
import handleGrants, { GrantType } from "./handleGrants";
|
||||
import encrypt from "../../functions/dsql/encrypt";
|
||||
import decrypt from "../../functions/dsql/decrypt";
|
||||
import { MYSQL_mariadb_users_table_def } from "../../types";
|
||||
|
||||
const defaultMariadbUserHost = process.env.DSQL_DB_HOST || "127.0.0.1";
|
||||
|
||||
type Param = {
|
||||
userId?: number | string;
|
||||
mariadbUserHost?: string;
|
||||
mariadbUsername?: string;
|
||||
sqlUserID?: string | number;
|
||||
};
|
||||
|
||||
/**
|
||||
* Refresh Mariadb User Grants
|
||||
* ===================================================
|
||||
* @param {object} params
|
||||
* @param {number | string} [params.userId]
|
||||
* @param {string} [params.mariadbUserHost]
|
||||
* @param {string} [params.mariadbUser]
|
||||
* @param {string | number} [params.sqlUserID]
|
||||
* # Refresh Mariadb User Grants
|
||||
*/
|
||||
async function refreshUsersAndGrants({
|
||||
export default async function refreshUsersAndGrants({
|
||||
userId,
|
||||
mariadbUserHost,
|
||||
mariadbUser,
|
||||
mariadbUsername,
|
||||
sqlUserID,
|
||||
}) {
|
||||
/**
|
||||
* @description Users
|
||||
* @type {*[] | null}
|
||||
*/ // @ts-ignore
|
||||
const users = await dbHandler({
|
||||
query: `SELECT * FROM users`,
|
||||
});
|
||||
}: Param) {
|
||||
const mariadbUsers = (await dbHandler({
|
||||
query: `SELECT * FROM mariadb_users`,
|
||||
})) as any[] | null;
|
||||
|
||||
if (!users?.[0]) {
|
||||
process.exit();
|
||||
if (!mariadbUsers?.[0]) {
|
||||
return;
|
||||
}
|
||||
|
||||
for (let i = 0; i < users.length; i++) {
|
||||
const user = users[i];
|
||||
const isRootUser = userId
|
||||
? userId == Number(process.env.DSQL_SU_USER_ID)
|
||||
: false;
|
||||
|
||||
if (!user) continue;
|
||||
if (userId && user.id != userId) continue;
|
||||
for (let i = 0; i < mariadbUsers.length; i++) {
|
||||
const mariadbUser = mariadbUsers[i];
|
||||
|
||||
if (!mariadbUser) continue;
|
||||
if (userId && mariadbUser.user_id != userId) continue;
|
||||
|
||||
try {
|
||||
const { mariadb_user, mariadb_host, mariadb_pass, id } = user;
|
||||
const { mariadb_user, mariadb_host, mariadb_pass, user_id } =
|
||||
mariadbUser;
|
||||
const existingUser = await noDatabaseDbHandler(
|
||||
`SELECT * FROM mysql.user WHERE User = '${mariadb_user}' AND Host = '${mariadb_host}'`
|
||||
);
|
||||
@@ -59,12 +60,9 @@ async function refreshUsersAndGrants({
|
||||
})
|
||||
: null;
|
||||
|
||||
/**
|
||||
* @type {import("../../types").MYSQL_mariadb_users_table_def | undefined}
|
||||
*/
|
||||
const activeMariadbUserObject = Array.isArray(
|
||||
existingMariaDBUserArray
|
||||
)
|
||||
const activeMariadbUserObject:
|
||||
| import("../../types").MYSQL_mariadb_users_table_def
|
||||
| undefined = Array.isArray(existingMariaDBUserArray)
|
||||
? existingMariaDBUserArray?.[0]
|
||||
: undefined;
|
||||
|
||||
@@ -80,7 +78,10 @@ async function refreshUsersAndGrants({
|
||||
mariadbUserHost == defaultMariadbUserHost
|
||||
);
|
||||
|
||||
const dslUsername = `dsql_user_${id}`;
|
||||
const dslUsername = isRootUser
|
||||
? mariadbUsername
|
||||
: `dsql_user_${user_id}`;
|
||||
|
||||
const dsqlPassword = activeMariadbUserObject?.password
|
||||
? activeMariadbUserObject.password
|
||||
: isUserExisting
|
||||
@@ -102,12 +103,13 @@ async function refreshUsersAndGrants({
|
||||
encryptionKey: process.env.DSQL_ENCRYPTION_PASSWORD,
|
||||
encryptionSalt: process.env.DSQL_ENCRYPTION_SALT,
|
||||
});
|
||||
|
||||
if (
|
||||
!isUserExisting &&
|
||||
!sqlUserID &&
|
||||
!isPrimary &&
|
||||
!mariadbUserHost &&
|
||||
!mariadbUser
|
||||
!mariadbUsername
|
||||
) {
|
||||
const createNewUser = await noDatabaseDbHandler(
|
||||
`CREATE USER IF NOT EXISTS '${dslUsername}'@'${defaultMariadbUserHost}' IDENTIFIED BY '${dsqlPassword}'`
|
||||
@@ -116,7 +118,7 @@ async function refreshUsersAndGrants({
|
||||
console.log("createNewUser", createNewUser);
|
||||
|
||||
console.log(
|
||||
`User ${user.id}: ${user.first_name} ${user.last_name} SQL credentials successfully updated.`
|
||||
`User ${mariadbUser.id}: ${mariadbUser.first_name} ${mariadbUser.last_name} SQL credentials successfully updated.`
|
||||
);
|
||||
|
||||
const updateUser = await dbHandler({
|
||||
@@ -125,9 +127,13 @@ async function refreshUsersAndGrants({
|
||||
dslUsername,
|
||||
defaultMariadbUserHost,
|
||||
encryptedPassword,
|
||||
user.id,
|
||||
mariadbUser.id,
|
||||
],
|
||||
});
|
||||
} else if (!isUserExisting && mariadbUserHost) {
|
||||
const createNewUser = await noDatabaseDbHandler(
|
||||
`CREATE USER IF NOT EXISTS '${dslUsername}'@'${mariadbUserHost}' IDENTIFIED BY '${dsqlPassword}'`
|
||||
);
|
||||
}
|
||||
|
||||
if (isPrimary) {
|
||||
@@ -141,7 +147,7 @@ async function refreshUsersAndGrants({
|
||||
dslUsername,
|
||||
finalHost,
|
||||
encryptedPassword,
|
||||
user.id,
|
||||
mariadbUser.id,
|
||||
],
|
||||
});
|
||||
}
|
||||
@@ -155,7 +161,7 @@ async function refreshUsersAndGrants({
|
||||
*/
|
||||
const existingMariadbPrimaryUser = await dbHandler({
|
||||
query: `SELECT * FROM mariadb_users WHERE user_id = ? AND \`primary\` = 1`,
|
||||
values: [id],
|
||||
values: [user_id],
|
||||
});
|
||||
|
||||
const isPrimaryUserExisting = Boolean(
|
||||
@@ -163,8 +169,7 @@ async function refreshUsersAndGrants({
|
||||
existingMariadbPrimaryUser?.[0]?.user_id
|
||||
);
|
||||
|
||||
/** @type {import("./handleGrants").GrantType[]} */
|
||||
const primaryUserGrants = [
|
||||
const primaryUserGrants: GrantType[] = [
|
||||
{
|
||||
database: "*",
|
||||
table: "*",
|
||||
@@ -176,7 +181,7 @@ async function refreshUsersAndGrants({
|
||||
const insertPrimaryMariadbUser = await dbHandler({
|
||||
query: `INSERT INTO mariadb_users (user_id, username, password, \`primary\`, grants) VALUES (?, ?, ?, ?, ?)`,
|
||||
values: [
|
||||
id,
|
||||
user_id,
|
||||
dslUsername,
|
||||
encryptedPassword,
|
||||
"1",
|
||||
@@ -189,32 +194,31 @@ async function refreshUsersAndGrants({
|
||||
|
||||
const existingExtraMariadbUsers = await dbHandler({
|
||||
query: `SELECT * FROM mariadb_users WHERE user_id = ? AND \`primary\` != '1'`,
|
||||
values: [id],
|
||||
values: [user_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;
|
||||
const _mariadbUser = existingExtraMariadbUsers[
|
||||
i
|
||||
] as MYSQL_mariadb_users_table_def;
|
||||
|
||||
if (mariadbUser && username != mariadbUser) continue;
|
||||
if (mariadbUserHost && host != mariadbUserHost) continue;
|
||||
if (
|
||||
_mariadbUser &&
|
||||
_mariadbUser.username != mariadbUsername
|
||||
)
|
||||
continue;
|
||||
if (mariadbUserHost && _mariadbUser.host != mariadbUserHost)
|
||||
continue;
|
||||
|
||||
const decrptedPassword = decrypt({
|
||||
encryptedString: password,
|
||||
encryptedString: _mariadbUser.password || "",
|
||||
encryptionKey: process.env.DSQL_ENCRYPTION_PASSWORD,
|
||||
encryptionSalt: process.env.DSQL_ENCRYPTION_SALT,
|
||||
});
|
||||
|
||||
const existingExtraMariadbUser = await noDatabaseDbHandler(
|
||||
`SELECT * FROM mysql.user WHERE User = '${username}' AND Host = '${host}'`
|
||||
`SELECT * FROM mysql.user WHERE User='${_mariadbUser.username}' AND Host='${_mariadbUser.host}'`
|
||||
);
|
||||
|
||||
const isExtraMariadbUserExisting = Boolean(
|
||||
@@ -223,47 +227,30 @@ async function refreshUsersAndGrants({
|
||||
|
||||
if (!isExtraMariadbUserExisting) {
|
||||
await noDatabaseDbHandler(
|
||||
`CREATE USER IF NOT EXISTS '${username}'@'${host}' IDENTIFIED BY '${decrptedPassword}'`
|
||||
`CREATE USER IF NOT EXISTS '${_mariadbUser.username}'@'${_mariadbUser.host}' IDENTIFIED BY '${decrptedPassword}'`
|
||||
);
|
||||
}
|
||||
|
||||
const isGrantHandled = await handleGrants({
|
||||
username,
|
||||
host,
|
||||
username: _mariadbUser.username,
|
||||
host: _mariadbUser.host,
|
||||
grants:
|
||||
grants && typeof grants == "string"
|
||||
? JSON.parse(grants)
|
||||
_mariadbUser.grants &&
|
||||
typeof _mariadbUser.grants == "string"
|
||||
? JSON.parse(_mariadbUser.grants)
|
||||
: [],
|
||||
userId: String(userId),
|
||||
});
|
||||
|
||||
if (!isGrantHandled) {
|
||||
console.log(
|
||||
`Error in handling grants for user ${username}@${host}`
|
||||
`Error in handling grants for user ${_mariadbUser.username}@${_mariadbUser.host}`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////
|
||||
//////////////////////////////////////////////
|
||||
//////////////////////////////////////////////
|
||||
} catch (/** @type {any} */ error) {
|
||||
} catch (error: any) {
|
||||
console.log(`Error in adding SQL user =>`, error.message);
|
||||
}
|
||||
}
|
||||
|
||||
process.exit();
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
}
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
module.exports = refreshUsersAndGrants;
|
||||
@@ -1,105 +0,0 @@
|
||||
// @ts-check
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
require("dotenv").config({ path: "../../.env" });
|
||||
const generator = require("generate-password");
|
||||
const noDatabaseDbHandler = require("../utils/noDatabaseDbHandler");
|
||||
const dbHandler = require("../utils/dbHandler");
|
||||
const encrypt = 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
|
||||
*/
|
||||
async function resetSQLCredentialsPasswords() {
|
||||
/**
|
||||
* @description Users
|
||||
* @type {*[] | null}
|
||||
*/ // @ts-ignore
|
||||
const users = await dbHandler({
|
||||
query: `SELECT * FROM users`,
|
||||
});
|
||||
|
||||
if (!users) {
|
||||
process.exit();
|
||||
}
|
||||
|
||||
for (let i = 0; i < users.length; i++) {
|
||||
const user = users[i];
|
||||
|
||||
if (!user) continue;
|
||||
|
||||
try {
|
||||
/**
|
||||
* @type {any[]}
|
||||
*/ // @ts-ignore
|
||||
const maridbUsers = await dbHandler({
|
||||
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 = generator.generate({
|
||||
length: 16,
|
||||
numbers: true,
|
||||
symbols: true,
|
||||
uppercase: true,
|
||||
exclude: "*#.'`\"",
|
||||
});
|
||||
|
||||
const encryptedPassword = encrypt({
|
||||
data: password,
|
||||
encryptionKey: process.env.DSQL_ENCRYPTION_PASSWORD,
|
||||
encryptionSalt: process.env.DSQL_ENCRYPTION_SALT,
|
||||
});
|
||||
|
||||
await noDatabaseDbHandler(
|
||||
`SET PASSWORD FOR '${User}'@'${Host}' = PASSWORD('${password}')`
|
||||
);
|
||||
|
||||
if (user.mariadb_user == User && user.mariadb_host == Host) {
|
||||
const updateUser = await dbHandler({
|
||||
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 (/** @type {any} */ error) {
|
||||
console.log(
|
||||
`Error Updating User ${user.id} Password =>`,
|
||||
error.message
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
process.exit();
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
}
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
resetSQLCredentialsPasswords();
|
||||
@@ -0,0 +1,72 @@
|
||||
require("dotenv").config({ path: "../../.env" });
|
||||
import generator from "generate-password";
|
||||
import noDatabaseDbHandler from "../utils/noDatabaseDbHandler";
|
||||
import dbHandler from "../utils/dbHandler";
|
||||
import encrypt from "../../functions/dsql/encrypt";
|
||||
|
||||
/**
|
||||
* # Reset SQL Passwords
|
||||
*/
|
||||
async function resetSQLCredentialsPasswords() {
|
||||
const users = (await dbHandler({
|
||||
query: `SELECT * FROM users`,
|
||||
})) as any[];
|
||||
|
||||
if (!users) {
|
||||
process.exit();
|
||||
}
|
||||
|
||||
for (let i = 0; i < users.length; i++) {
|
||||
const user = users[i];
|
||||
|
||||
if (!user) continue;
|
||||
|
||||
try {
|
||||
const maridbUsers = (await dbHandler({
|
||||
query: `SELECT * FROM mysql.user WHERE User = 'dsql_user_${user.id}'`,
|
||||
})) as any[];
|
||||
|
||||
for (let j = 0; j < maridbUsers.length; j++) {
|
||||
const { User, Host } = maridbUsers[j];
|
||||
|
||||
const password = generator.generate({
|
||||
length: 16,
|
||||
numbers: true,
|
||||
symbols: true,
|
||||
uppercase: true,
|
||||
exclude: "*#.'`\"",
|
||||
});
|
||||
|
||||
const encryptedPassword = encrypt({
|
||||
data: password,
|
||||
encryptionKey: process.env.DSQL_ENCRYPTION_PASSWORD,
|
||||
encryptionSalt: process.env.DSQL_ENCRYPTION_SALT,
|
||||
});
|
||||
|
||||
await noDatabaseDbHandler(
|
||||
`SET PASSWORD FOR '${User}'@'${Host}' = PASSWORD('${password}')`
|
||||
);
|
||||
|
||||
if (user.mariadb_user == User && user.mariadb_host == Host) {
|
||||
const updateUser = await dbHandler({
|
||||
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: any) {
|
||||
console.log(
|
||||
`Error Updating User ${user.id} Password =>`,
|
||||
error.message
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
process.exit();
|
||||
}
|
||||
|
||||
resetSQLCredentialsPasswords();
|
||||
+10
-12
@@ -1,15 +1,13 @@
|
||||
// @ts-check
|
||||
|
||||
const path = require("path");
|
||||
import path from "path";
|
||||
require("dotenv").config({ path: "../../../.env" });
|
||||
const fs = require("fs");
|
||||
const { execSync } = require("child_process");
|
||||
const EJSON = require("../../../utils/ejson");
|
||||
const DB_HANDLER = require("../../../utils/backend/global-db/DB_HANDLER");
|
||||
const addDbEntry = require("../../../functions/backend/db/addDbEntry");
|
||||
const addMariadbUser = require("../../../functions/backend/addMariadbUser");
|
||||
const updateDbEntry = require("../../../functions/backend/db/updateDbEntry");
|
||||
const hashPassword = require("../../../functions/dsql/hashPassword");
|
||||
import fs from "fs";
|
||||
import { execSync } from "child_process";
|
||||
import EJSON from "../../../utils/ejson";
|
||||
import DB_HANDLER from "../../../utils/backend/global-db/DB_HANDLER";
|
||||
import addDbEntry from "../../../functions/backend/db/addDbEntry";
|
||||
import addMariadbUser from "../../../functions/backend/addMariadbUser";
|
||||
import updateDbEntry from "../../../functions/backend/db/updateDbEntry";
|
||||
import hashPassword from "../../../functions/dsql/hashPassword";
|
||||
|
||||
const tmpDir = process.argv[process.argv.length - 1];
|
||||
|
||||
@@ -169,7 +167,7 @@ async function createUser() {
|
||||
}
|
||||
|
||||
return true;
|
||||
} catch (/** @type {any} */ error) {
|
||||
} catch (error: any) {
|
||||
console.log(`Error in creating user => ${error.message}`);
|
||||
return false;
|
||||
}
|
||||
+7
-10
@@ -1,11 +1,9 @@
|
||||
// @ts-check
|
||||
|
||||
const path = require("path");
|
||||
import path from "path";
|
||||
require("dotenv").config({ path: "../../../.env" });
|
||||
const fs = require("fs");
|
||||
const EJSON = require("../../../utils/ejson");
|
||||
const hashPassword = require("../../../functions/dsql/hashPassword");
|
||||
const updateDbEntry = require("../../../functions/backend/db/updateDbEntry");
|
||||
import fs from "fs";
|
||||
import EJSON from "../../../utils/ejson";
|
||||
import hashPassword from "../../../functions/dsql/hashPassword";
|
||||
import updateDbEntry from "../../../functions/backend/db/updateDbEntry";
|
||||
|
||||
const tmpDir = process.argv[process.argv.length - 1];
|
||||
|
||||
@@ -40,8 +38,7 @@ async function createUser() {
|
||||
updatePayload["password"] = hashedPassword;
|
||||
}
|
||||
|
||||
/** @type {any} */
|
||||
const newUser = await updateDbEntry({
|
||||
const newUser: any = await updateDbEntry({
|
||||
dbFullName: "datasquirel",
|
||||
tableName: "users",
|
||||
data: { ...updatePayload, id: undefined },
|
||||
@@ -58,7 +55,7 @@ async function createUser() {
|
||||
}
|
||||
|
||||
return true;
|
||||
} catch (/** @type {any} */ error) {
|
||||
} catch (error: any) {
|
||||
console.log(`Error in creating user => ${error.message}`);
|
||||
return false;
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
// @ts-check
|
||||
|
||||
const fs = require("fs");
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
/**
|
||||
* Grab Schema
|
||||
*
|
||||
* @description Grab Schema
|
||||
*/
|
||||
const imageBase64 = fs.readFileSync(
|
||||
"./../public/images/unique-tokens-icon.png",
|
||||
"base64"
|
||||
);
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
Executable
+6
@@ -0,0 +1,6 @@
|
||||
import fs from "fs";
|
||||
|
||||
const imageBase64 = fs.readFileSync(
|
||||
"./../public/images/unique-tokens-icon.png",
|
||||
"base64"
|
||||
);
|
||||
+7
-28
@@ -1,27 +1,13 @@
|
||||
// @ts-check
|
||||
|
||||
const fs = require("fs");
|
||||
import fs from "fs";
|
||||
require("dotenv").config({ path: "./../.env" });
|
||||
|
||||
////////////////////////////////////////
|
||||
|
||||
const varDatabaseDbHandler = require("../functions/backend/varDatabaseDbHandler");
|
||||
const DB_HANDLER = require("../utils/backend/global-db/DB_HANDLER");
|
||||
|
||||
/** ****************************************************************************** */
|
||||
import varDatabaseDbHandler from "../functions/backend/varDatabaseDbHandler";
|
||||
import DB_HANDLER from "../utils/backend/global-db/DB_HANDLER";
|
||||
|
||||
const userId =
|
||||
process.argv.indexOf("--userId") >= 0
|
||||
? process.argv[process.argv.indexOf("--userId") + 1]
|
||||
: null;
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
/**
|
||||
* Grab Schema
|
||||
*
|
||||
@@ -43,8 +29,7 @@ async function recoverMainJsonFromDb() {
|
||||
const { id, db_name, db_slug, db_full_name, db_image, db_description } =
|
||||
databases[i];
|
||||
|
||||
/** @type {any} */
|
||||
const dbObject = {
|
||||
const dbObject: any = {
|
||||
dbName: db_name,
|
||||
dbSlug: db_slug,
|
||||
dbFullName: db_full_name,
|
||||
@@ -60,8 +45,7 @@ async function recoverMainJsonFromDb() {
|
||||
for (let j = 0; j < tables.length; j++) {
|
||||
const { table_name, table_slug, table_description } = tables[j];
|
||||
|
||||
/** @type {any} */
|
||||
const tableObject = {
|
||||
const tableObject: any = {
|
||||
tableName: table_slug,
|
||||
tableFullName: table_name,
|
||||
fields: [],
|
||||
@@ -70,14 +54,13 @@ async function recoverMainJsonFromDb() {
|
||||
|
||||
const tableFields = await varDatabaseDbHandler({
|
||||
database: db_full_name,
|
||||
queryString: `SHOW COLUMNS FROM ${table_slug}`,
|
||||
queryString: `SHOW COLUMNS FROM ${db_full_name}.${table_slug}`,
|
||||
});
|
||||
|
||||
for (let k = 0; k < tableFields.length; k++) {
|
||||
const { Field, Type, Null, Default, Key } = tableFields[k];
|
||||
|
||||
/** @type {any} */
|
||||
const fieldObject = {
|
||||
const fieldObject: any = {
|
||||
fieldName: Field,
|
||||
dataType: Type.toUpperCase(),
|
||||
};
|
||||
@@ -113,8 +96,4 @@ async function recoverMainJsonFromDb() {
|
||||
process.exit();
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
recoverMainJsonFromDb();
|
||||
+7
-34
@@ -1,21 +1,8 @@
|
||||
// @ts-check
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
require("dotenv").config({ path: "./../.env" });
|
||||
const generator = require("generate-password");
|
||||
const noDatabaseDbHandler = require("./utils/noDatabaseDbHandler");
|
||||
const dbHandler = require("./utils/dbHandler");
|
||||
const encrypt = require("../functions/dsql/encrypt");
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
import generator from "generate-password";
|
||||
import noDatabaseDbHandler from "./utils/noDatabaseDbHandler";
|
||||
import dbHandler from "./utils/dbHandler";
|
||||
import encrypt from "../functions/dsql/encrypt";
|
||||
|
||||
/**
|
||||
* Create database from Schema Function
|
||||
@@ -24,13 +11,9 @@ const encrypt = require("../functions/dsql/encrypt");
|
||||
* @param {number|string|null} params.userId - User ID or null
|
||||
*/
|
||||
async function resetSQLCredentials() {
|
||||
/**
|
||||
* @description Users
|
||||
* @type {*[] | null}
|
||||
*/ // @ts-ignore
|
||||
const users = await dbHandler({
|
||||
const users = (await dbHandler({
|
||||
query: `SELECT * FROM users`,
|
||||
});
|
||||
})) as any[];
|
||||
|
||||
if (!users) {
|
||||
process.exit();
|
||||
@@ -82,22 +65,12 @@ async function resetSQLCredentials() {
|
||||
console.log(
|
||||
`User ${user.id}: ${user.first_name} ${user.last_name} SQL credentials successfully added.`
|
||||
);
|
||||
} catch (/** @type {any} */ error) {
|
||||
} catch (error: any) {
|
||||
console.log(`Error in adding SQL user =>`, error.message);
|
||||
}
|
||||
}
|
||||
|
||||
process.exit();
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
}
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
resetSQLCredentials();
|
||||
@@ -1,90 +0,0 @@
|
||||
// @ts-check
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
require("dotenv").config({ path: "./../.env" });
|
||||
const generator = require("generate-password");
|
||||
const noDatabaseDbHandler = require("./utils/noDatabaseDbHandler");
|
||||
const dbHandler = require("./utils/dbHandler");
|
||||
const encrypt = 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
|
||||
*/
|
||||
async function resetSQLCredentialsPasswords() {
|
||||
/**
|
||||
* @description Users
|
||||
* @type {*[] | null}
|
||||
*/ // @ts-ignore
|
||||
const users = await dbHandler({
|
||||
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 = generator.generate({
|
||||
length: 16,
|
||||
numbers: true,
|
||||
symbols: true,
|
||||
uppercase: true,
|
||||
exclude: "*#.'`\"",
|
||||
});
|
||||
const encryptedPassword = encrypt({ data: password });
|
||||
|
||||
await noDatabaseDbHandler(
|
||||
`SET PASSWORD FOR '${username}'@'${defaultMariadbUserHost}' = PASSWORD('${password}')`
|
||||
);
|
||||
|
||||
const updateUser = await dbHandler({
|
||||
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 (/** @type {any} */ error) {
|
||||
console.log(
|
||||
`Error Updating User ${user.id} Password =>`,
|
||||
error.message
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
process.exit();
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
}
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
resetSQLCredentialsPasswords();
|
||||
@@ -0,0 +1,60 @@
|
||||
require("dotenv").config({ path: "./../.env" });
|
||||
import generator from "generate-password";
|
||||
import noDatabaseDbHandler from "./utils/noDatabaseDbHandler";
|
||||
import dbHandler from "./utils/dbHandler";
|
||||
import encrypt from "../functions/dsql/encrypt";
|
||||
|
||||
/**
|
||||
* # Create database from Schema Function
|
||||
*/
|
||||
async function resetSQLCredentialsPasswords() {
|
||||
const users = (await dbHandler({
|
||||
query: `SELECT * FROM users`,
|
||||
})) as any[];
|
||||
|
||||
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 = generator.generate({
|
||||
length: 16,
|
||||
numbers: true,
|
||||
symbols: true,
|
||||
uppercase: true,
|
||||
exclude: "*#.'`\"",
|
||||
});
|
||||
const encryptedPassword = encrypt({ data: password });
|
||||
|
||||
await noDatabaseDbHandler(
|
||||
`SET PASSWORD FOR '${username}'@'${defaultMariadbUserHost}' = PASSWORD('${password}')`
|
||||
);
|
||||
|
||||
const updateUser = await dbHandler({
|
||||
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: any) {
|
||||
console.log(
|
||||
`Error Updating User ${user.id} Password =>`,
|
||||
error.message
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
process.exit();
|
||||
}
|
||||
|
||||
resetSQLCredentialsPasswords();
|
||||
@@ -0,0 +1,46 @@
|
||||
import path from "path";
|
||||
import fs from "fs";
|
||||
|
||||
const rootDir = path.resolve(__dirname, "../../../");
|
||||
const ignorePattern =
|
||||
/\/\.git\/|\/\.next\/|\/\.dist\/|node_modules|\/\.local_dist\/|\/\.tmp\/|\/types\/|\.config\.js|\/public\//;
|
||||
|
||||
function transformJsToTs(dir: string) {
|
||||
const dirContent = fs.readdirSync(dir);
|
||||
|
||||
for (let i = 0; i < dirContent.length; i++) {
|
||||
const fileFolder = dirContent[i];
|
||||
const fullFileFolderPath = path.join(dir, fileFolder);
|
||||
const stat = fs.statSync(fullFileFolderPath);
|
||||
|
||||
if (stat.isDirectory()) {
|
||||
transformJsToTs(fullFileFolderPath);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (ignorePattern.test(fullFileFolderPath)) continue;
|
||||
|
||||
if (fullFileFolderPath.match(/\.jsx?$/)) {
|
||||
const extension = fullFileFolderPath.match(/\.jsx?$/)?.[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.copyFileSync(fullFileFolderPath, newFilePath);
|
||||
fs.unlinkSync(fullFileFolderPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
console.log("rootDir", rootDir);
|
||||
|
||||
transformJsToTs(rootDir);
|
||||
+8
-33
@@ -1,14 +1,8 @@
|
||||
// @ts-check
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
require("dotenv").config({ path: "./../.env" });
|
||||
const generator = require("generate-password");
|
||||
const noDatabaseDbHandler = require("./utils/noDatabaseDbHandler");
|
||||
const dbHandler = require("./utils/dbHandler");
|
||||
const encrypt = require("../functions/dsql/encrypt");
|
||||
import generator from "generate-password";
|
||||
import noDatabaseDbHandler from "./utils/noDatabaseDbHandler";
|
||||
import dbHandler from "./utils/dbHandler";
|
||||
import encrypt from "../functions/dsql/encrypt";
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
@@ -18,19 +12,12 @@ const encrypt = 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
|
||||
* # Set SQL Credentials
|
||||
*/
|
||||
async function setSQLCredentials() {
|
||||
/**
|
||||
* @description Users
|
||||
* @type {*[] | null}
|
||||
*/ // @ts-ignore
|
||||
const users = await dbHandler({
|
||||
const users = (await dbHandler({
|
||||
query: `SELECT * FROM users`,
|
||||
});
|
||||
})) as any[] | null;
|
||||
|
||||
if (!users) {
|
||||
process.exit();
|
||||
@@ -72,22 +59,10 @@ async function setSQLCredentials() {
|
||||
console.log(
|
||||
`User ${user.id}: ${user.first_name} ${user.last_name} SQL credentials successfully added.`
|
||||
);
|
||||
} catch (/** @type {any} */ error) {
|
||||
} catch (error: any) {
|
||||
console.log(`Error in adding SQL user =>`, error.message);
|
||||
}
|
||||
}
|
||||
|
||||
process.exit();
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
}
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
setSQLCredentials();
|
||||
@@ -1,29 +0,0 @@
|
||||
// @ts-check
|
||||
|
||||
const fs = require("fs");
|
||||
const { exec } = 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.watch("./../", (curr, prev) => {
|
||||
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!");
|
||||
});
|
||||
});
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
import fs from "fs";
|
||||
import { exec } from "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.watch("./../", (curr, prev) => {
|
||||
exec(
|
||||
`bunx 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!");
|
||||
}
|
||||
);
|
||||
});
|
||||
+3
-16
@@ -1,12 +1,6 @@
|
||||
// @ts-check
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
require("dotenv").config({ path: "./.env" });
|
||||
const grabDbSSL = require("../utils/backend/grabDbSSL");
|
||||
const mysql = require("serverless-mysql");
|
||||
import grabDbSSL from "../utils/backend/grabDbSSL";
|
||||
import mysql from "serverless-mysql";
|
||||
|
||||
const connection = mysql({
|
||||
config: {
|
||||
@@ -19,13 +13,6 @@ const connection = mysql({
|
||||
},
|
||||
});
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* # Main DB Handler Function
|
||||
* @async
|
||||
@@ -49,7 +36,7 @@ const connection = mysql({
|
||||
const parsedResults = JSON.parse(JSON.stringify(result));
|
||||
|
||||
console.log("parsedResults =>", parsedResults);
|
||||
} catch (/** @type {any} */ error) {
|
||||
} catch (error: any) {
|
||||
console.log("Connection query ERROR =>", error.message);
|
||||
} finally {
|
||||
connection.end();
|
||||
@@ -1,221 +0,0 @@
|
||||
require("dotenv").config({ path: "./../.env" });
|
||||
|
||||
const dbEngine = require("@moduletrace/datasquirel/engine");
|
||||
const http = require("http");
|
||||
|
||||
const datasquirel = require("@moduletrace/datasquirel");
|
||||
|
||||
`curl http://www.dataden.tech`;
|
||||
|
||||
datasquirel
|
||||
.get({
|
||||
db: "test",
|
||||
key: process.env.DATASQUIREL_READ_ONLY_KEY,
|
||||
query: "SELECT title, slug, body FROM blog_posts",
|
||||
})
|
||||
.then((response) => {
|
||||
console.log(response);
|
||||
});
|
||||
|
||||
// dbEngine.db
|
||||
// .query({
|
||||
// dbFullName: "datasquirel",
|
||||
// dbHost: process.env.DSQL_DB_HOST,
|
||||
// dbPassword: process.env.DSQL_DB_PASSWORD,
|
||||
// dbUsername: process.env.DSQL_DB_USERNAME,
|
||||
// query: "SHOW TABLES",
|
||||
// })
|
||||
// .then((res) => {
|
||||
// console.log("res =>", res);
|
||||
// });
|
||||
|
||||
// run({
|
||||
// key: "bc057a2cd57922e085739c89b4985e5e676b655d7cc0ba7604659cad0a08c252040120c06597a5d22959a502a44bd816",
|
||||
// db: "showmerebates",
|
||||
// query: "SELECT * FROM test_table",
|
||||
// }).then((res) => {
|
||||
// console.log("res =>", res);
|
||||
// });
|
||||
|
||||
post({
|
||||
key: "3115fce7ea7772eda75f8f0e55a1414c5c018b4920f4bc99a2d4d7000bac203c15a7036fd3d7ef55ae67a002d4c757895b5c58ff82079a04ba6d42d23d4353256985090959a58a9af8e03cb277fc7895413e6f28ae11b1cc15329c7f94cdcf9a795f54d6e1d319adc287dc147143e62d",
|
||||
database: "showmerebates",
|
||||
query: {
|
||||
action: "delete",
|
||||
table: "test_table",
|
||||
identifierColumnName: "id",
|
||||
identifierValue: 6,
|
||||
},
|
||||
}).then((res) => {
|
||||
console.log("res =>", res);
|
||||
});
|
||||
|
||||
async function run({ key, db, query }) {
|
||||
const httpResponse = await new Promise((resolve, reject) => {
|
||||
http.request(
|
||||
{
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Authorization: key,
|
||||
},
|
||||
hostname: "localhost",
|
||||
port: 7070,
|
||||
path: `/api/query/get?db=${db}&query=${query
|
||||
.replace(/\n|\r|\n\r/g, "")
|
||||
.replace(/ {2,}/g, " ")
|
||||
.replace(/ /g, "+")}`,
|
||||
},
|
||||
|
||||
/**
|
||||
* Callback Function
|
||||
*
|
||||
* @description https request callback
|
||||
*/
|
||||
(response) => {
|
||||
var str = "";
|
||||
|
||||
response.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
|
||||
response.on("end", function () {
|
||||
resolve(JSON.parse(str));
|
||||
});
|
||||
|
||||
response.on("error", (err) => {
|
||||
reject(err);
|
||||
});
|
||||
}
|
||||
).end();
|
||||
});
|
||||
|
||||
return httpResponse;
|
||||
}
|
||||
|
||||
/**
|
||||
* @typedef {Object} PostReturn
|
||||
* @property {boolean} success - Did the function run successfully?
|
||||
* @property {(Object[]|string)} [payload=[]] - The Y Coordinate
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {object} PostDataPayload
|
||||
* @property {string} action - "insert" | "update" | "delete"
|
||||
* @property {string} table - Table name(slug) eg "blog_posts"
|
||||
* @property {string} identifierColumnName - Table identifier field name => eg. "id" OR "email"
|
||||
* @property {string} identifierValue - Corresponding value of the selected field name => This
|
||||
* checks identifies a the target row for "update" or "delete". Not needed for "insert"
|
||||
* @property {object} data - Table insert payload object => This must have keys that match
|
||||
* table fields
|
||||
* @property {string?} duplicateColumnName - Duplicate column name to check for
|
||||
* @property {string?} duplicateColumnValue - Duplicate column value to match. If no "update" param
|
||||
* provided, function will return null
|
||||
* @property {boolean?} update - Should the "insert" action update the existing entry if indeed
|
||||
* the entry with "duplicateColumnValue" exists?
|
||||
*/
|
||||
|
||||
/**
|
||||
* Post request
|
||||
* ==============================================================================
|
||||
* @async
|
||||
*
|
||||
* @param {Object} params - Single object passed
|
||||
* @param {string} params.key - FULL ACCESS API Key
|
||||
* @param {string} params.database - Database Name
|
||||
* @param {PostDataPayload} params.query - SQL query String or Request Object
|
||||
*
|
||||
* @returns { Promise<PostReturn> } - Return Object
|
||||
*/
|
||||
async function post({ key, query, database }) {
|
||||
/**
|
||||
* Make https request
|
||||
*
|
||||
* @description make a request to datasquirel.com
|
||||
*/
|
||||
const httpResponse = await new Promise((resolve, reject) => {
|
||||
const reqPayloadString = JSON.stringify({
|
||||
query,
|
||||
database,
|
||||
}).replace(/\n|\r|\n\r/gm, "");
|
||||
|
||||
try {
|
||||
JSON.parse(reqPayloadString);
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
console.log(reqPayloadString);
|
||||
|
||||
return {
|
||||
success: false,
|
||||
payload: null,
|
||||
error: "Query object is invalid. Please Check query data values",
|
||||
};
|
||||
}
|
||||
|
||||
const reqPayload = reqPayloadString;
|
||||
|
||||
const httpsRequest = http.request(
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Content-Length": Buffer.from(reqPayload).length,
|
||||
Authorization: key,
|
||||
},
|
||||
hostname: "localhost",
|
||||
port: 7070,
|
||||
path: `/api/query/post`,
|
||||
},
|
||||
|
||||
/**
|
||||
* Callback Function
|
||||
*
|
||||
* @description https request callback
|
||||
*/
|
||||
(response) => {
|
||||
var str = "";
|
||||
|
||||
response.on("data", function (chunk) {
|
||||
str += chunk;
|
||||
});
|
||||
|
||||
response.on("end", function () {
|
||||
try {
|
||||
resolve(JSON.parse(str));
|
||||
} catch (error) {
|
||||
console.log(error.message);
|
||||
console.log("Fetched Payload =>", str);
|
||||
|
||||
resolve({
|
||||
success: false,
|
||||
payload: null,
|
||||
error: error.message,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
response.on("error", (err) => {
|
||||
resolve({
|
||||
success: false,
|
||||
payload: null,
|
||||
error: err.message,
|
||||
});
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
httpsRequest.write(reqPayload);
|
||||
|
||||
httpsRequest.on("error", (error) => {
|
||||
console.log("HTTPS request ERROR =>", error.message);
|
||||
});
|
||||
|
||||
httpsRequest.end();
|
||||
});
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
return httpResponse;
|
||||
}
|
||||
+9
-26
@@ -5,10 +5,10 @@
|
||||
////////////////////////////////////////
|
||||
|
||||
require("dotenv").config({ path: "./../.env" });
|
||||
const generator = require("generate-password");
|
||||
const noDatabaseDbHandler = require("./utils/noDatabaseDbHandler");
|
||||
const dbHandler = require("./utils/dbHandler");
|
||||
const encrypt = require("../functions/dsql/encrypt");
|
||||
import generator from "generate-password";
|
||||
import noDatabaseDbHandler from "./utils/noDatabaseDbHandler";
|
||||
import dbHandler from "./utils/dbHandler";
|
||||
import encrypt from "../functions/dsql/encrypt";
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
@@ -18,19 +18,12 @@ const encrypt = 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
|
||||
* # Test SQL Escape
|
||||
*/
|
||||
async function testSQLEscape() {
|
||||
/**
|
||||
* @description Users
|
||||
* @type {*[] | null}
|
||||
*/ // @ts-ignore
|
||||
const users = await dbHandler({
|
||||
export default async function testSQLEscape() {
|
||||
const users = (await dbHandler({
|
||||
query: `SELECT * FROM users`,
|
||||
});
|
||||
})) as any[];
|
||||
|
||||
if (!users) {
|
||||
process.exit();
|
||||
@@ -81,22 +74,12 @@ async function testSQLEscape() {
|
||||
console.log(
|
||||
`User ${user.id}: ${user.first_name} ${user.last_name} SQL credentials successfully added.`
|
||||
);
|
||||
} catch (/** @type {any} */ error) {
|
||||
} catch (error: any) {
|
||||
console.log(`Error in adding SQL user =>`, error.message);
|
||||
}
|
||||
}
|
||||
|
||||
process.exit();
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
}
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
testSQLEscape();
|
||||
+2
-28
@@ -1,16 +1,7 @@
|
||||
// @ts-check
|
||||
|
||||
const DB_HANDLER = require("../utils/backend/global-db/DB_HANDLER");
|
||||
const fs = require("fs");
|
||||
import DB_HANDLER from "../utils/backend/global-db/DB_HANDLER";
|
||||
import fs from "fs";
|
||||
require("dotenv").config({ path: "./../.env" });
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
async function updateChildrenTablesOnDb() {
|
||||
/**
|
||||
* Grab Schema
|
||||
@@ -57,24 +48,7 @@ async function updateChildrenTablesOnDb() {
|
||||
console.log(error);
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
process.exit();
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
}
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
// const userArg = process.argv[process.argv.indexOf("--user")];
|
||||
// const externalUser = process.argv[process.argv.indexOf("--user") + 1];
|
||||
|
||||
updateChildrenTablesOnDb();
|
||||
@@ -1,60 +0,0 @@
|
||||
// @ts-check
|
||||
|
||||
require("dotenv").config({ path: "./../.env" });
|
||||
|
||||
////////////////////////////////////////
|
||||
|
||||
const varDatabaseDbHandler = require("../functions/backend/varDatabaseDbHandler");
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
/**
|
||||
* Grab Schema
|
||||
*
|
||||
* @description Grab Schema
|
||||
*/
|
||||
varDatabaseDbHandler({
|
||||
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(async (tables) => {
|
||||
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 = await varDatabaseDbHandler({
|
||||
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 = await varDatabaseDbHandler({
|
||||
queryString: `ALTER TABLE \`${table_slug}\` MODIFY COLUMN date_created_timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP`,
|
||||
database: db_full_name,
|
||||
});
|
||||
|
||||
const updateDateTimestamp = await varDatabaseDbHandler({
|
||||
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();
|
||||
});
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
require("dotenv").config({ path: "./../.env" });
|
||||
import varDatabaseDbHandler from "../functions/backend/varDatabaseDbHandler";
|
||||
|
||||
/**
|
||||
* Grab Schema
|
||||
*
|
||||
* @description Grab Schema
|
||||
*/
|
||||
varDatabaseDbHandler({
|
||||
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(async (tables) => {
|
||||
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 = await varDatabaseDbHandler({
|
||||
queryString: `SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='${db_full_name}' AND TABLE_NAME='${table_slug}'`,
|
||||
});
|
||||
|
||||
const updateCreationDateTimestamp = await varDatabaseDbHandler({
|
||||
queryString: `ALTER TABLE \`${db_full_name}\`.\`${table_slug}\` MODIFY COLUMN date_created_timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP`,
|
||||
});
|
||||
|
||||
const updateDateTimestamp = await varDatabaseDbHandler({
|
||||
queryString: `ALTER TABLE \`${db_full_name}\`.\`${table_slug}\` MODIFY COLUMN date_updated_timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP`,
|
||||
});
|
||||
|
||||
console.log("Date Updated Column updated");
|
||||
}
|
||||
|
||||
process.exit();
|
||||
});
|
||||
+5
-12
@@ -1,10 +1,8 @@
|
||||
// @ts-check
|
||||
|
||||
require("dotenv").config({ path: "./../.env" });
|
||||
|
||||
const serverError = require("../functions/backend/serverError");
|
||||
const varDatabaseDbHandler = require("./utils/varDatabaseDbHandler");
|
||||
const DB_HANDLER = require("../utils/backend/global-db/DB_HANDLER");
|
||||
import serverError from "../functions/backend/serverError";
|
||||
import varDatabaseDbHandler from "./utils/varDatabaseDbHandler";
|
||||
import DB_HANDLER from "../utils/backend/global-db/DB_HANDLER";
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
@@ -19,8 +17,7 @@ const DB_HANDLER = require("../utils/backend/global-db/DB_HANDLER");
|
||||
* @description Grab Schema
|
||||
*/
|
||||
varDatabaseDbHandler({
|
||||
queryString: `SELECT DISTINCT db_id FROM user_database_tables`,
|
||||
database: "datasquirel",
|
||||
queryString: `SELECT DISTINCT db_id FROM datasquirel.user_database_tables`,
|
||||
}).then(async (tables) => {
|
||||
// console.log(tables);
|
||||
// process.exit();
|
||||
@@ -38,7 +35,7 @@ varDatabaseDbHandler({
|
||||
const updateTableSlug = await DB_HANDLER(
|
||||
`UPDATE user_database_tables SET db_slug='${dbSlug[0].db_slug}' WHERE db_id='${db_id}'`
|
||||
);
|
||||
} catch (/** @type {any} */ error) {
|
||||
} catch (error: any) {
|
||||
serverError({
|
||||
component:
|
||||
"shell/updateDbSlugsForTableRecords/main-catch-error",
|
||||
@@ -50,7 +47,3 @@ varDatabaseDbHandler({
|
||||
|
||||
process.exit();
|
||||
});
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
+5
-21
@@ -1,19 +1,6 @@
|
||||
// @ts-check
|
||||
|
||||
require("dotenv").config({ path: "./../.env" });
|
||||
const grabDbSSL = require("../utils/backend/grabDbSSL");
|
||||
const mysql = require("serverless-mysql");
|
||||
|
||||
const connection = mysql({
|
||||
config: {
|
||||
host: process.env.DSQL_DB_HOST,
|
||||
user: process.env.DSQL_DB_USERNAME,
|
||||
password: process.env.DSQL_DB_PASSWORD,
|
||||
database: process.env.DSQL_DB_NAME,
|
||||
charset: "utf8mb4",
|
||||
ssl: grabDbSSL(),
|
||||
},
|
||||
});
|
||||
import grabDbSSL from "../utils/backend/grabDbSSL";
|
||||
import mysql from "serverless-mysql";
|
||||
|
||||
/**
|
||||
* # Main DB Handler Function
|
||||
@@ -27,11 +14,8 @@ const connection = mysql({
|
||||
* @returns {Promise<object|null>}
|
||||
*/
|
||||
(async () => {
|
||||
/**
|
||||
* Switch Database
|
||||
*
|
||||
* @description If a database is provided, switch to it
|
||||
*/
|
||||
const connection = global.DSQL_DB_CONN;
|
||||
|
||||
try {
|
||||
const result = await connection.query(
|
||||
"SELECT user,host,ssl_type FROM mysql.user"
|
||||
@@ -61,7 +45,7 @@ const connection = mysql({
|
||||
|
||||
console.log(`addUserSSL => ${User}@${Host}`, addUserSSL);
|
||||
}
|
||||
} catch (/** @type {any} */ error) {
|
||||
} catch (error: any) {
|
||||
console.log("Connection query ERROR =>", error.message);
|
||||
} finally {
|
||||
connection.end();
|
||||
+2
-8
@@ -1,16 +1,10 @@
|
||||
// @ts-check
|
||||
|
||||
/**
|
||||
* Convert Camel Joined Text to Camel Spaced Text
|
||||
* ==============================================================================
|
||||
* @description this function takes a camel cased text without spaces, and returns
|
||||
* a camel-case-spaced text
|
||||
*
|
||||
* @param {string} text - text string without spaces
|
||||
*
|
||||
* @returns {string | null}
|
||||
*/
|
||||
module.exports = function camelJoinedtoCamelSpace(text) {
|
||||
export default function camelJoinedtoCamelSpace(text: string): string | null {
|
||||
if (!text?.match(/./)) {
|
||||
return "";
|
||||
}
|
||||
@@ -56,4 +50,4 @@ module.exports = function camelJoinedtoCamelSpace(text) {
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
}
|
||||
+24
-49
@@ -1,38 +1,27 @@
|
||||
// @ts-check
|
||||
import varDatabaseDbHandler from "./varDatabaseDbHandler";
|
||||
import generateColumnDescription from "./generateColumnDescription";
|
||||
import supplementTable from "./supplementTable";
|
||||
import dbHandler from "./dbHandler";
|
||||
import { DSQL_DatabaseSchemaType, DSQL_TableSchemaType } from "../../types";
|
||||
|
||||
const varDatabaseDbHandler = require("./varDatabaseDbHandler");
|
||||
const generateColumnDescription = require("./generateColumnDescription");
|
||||
const supplementTable = require("./supplementTable");
|
||||
const dbHandler = require("./dbHandler");
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
type Param = {
|
||||
dbFullName: string;
|
||||
tableName: string;
|
||||
tableInfoArray: any[];
|
||||
tableSchema?: DSQL_TableSchemaType;
|
||||
recordedDbEntry?: any;
|
||||
};
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {object} params
|
||||
* @param {string} params.dbFullName
|
||||
* @param {string} params.tableName
|
||||
* @param {any[]} params.tableInfoArray
|
||||
* @param {import("../../types").DSQL_DatabaseSchemaType[]} [params.dbSchema]
|
||||
* @param {import("../../types").DSQL_TableSchemaType} [params.tableSchema]
|
||||
* @param {any} [params.recordedDbEntry]
|
||||
* @param {boolean} [params.clone] - Is this a newly cloned table?
|
||||
* @returns
|
||||
* # Create Table Functions
|
||||
*/
|
||||
module.exports = async function createTable({
|
||||
export default async function createTable({
|
||||
dbFullName,
|
||||
tableName,
|
||||
tableInfoArray,
|
||||
dbSchema,
|
||||
clone,
|
||||
tableSchema,
|
||||
recordedDbEntry,
|
||||
}) {
|
||||
}: Param) {
|
||||
/**
|
||||
* Format tableInfoArray
|
||||
*
|
||||
@@ -47,7 +36,9 @@ module.exports = async function createTable({
|
||||
*/
|
||||
const createTableQueryArray = [];
|
||||
|
||||
createTableQueryArray.push(`CREATE TABLE IF NOT EXISTS \`${tableName}\` (`);
|
||||
createTableQueryArray.push(
|
||||
`CREATE TABLE IF NOT EXISTS \`${dbFullName}\`.\`${tableName}\` (`
|
||||
);
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
@@ -59,17 +50,17 @@ module.exports = async function createTable({
|
||||
}
|
||||
|
||||
const existingTable = await varDatabaseDbHandler({
|
||||
database: "datasquirel",
|
||||
queryString: `SELECT * FROM user_database_tables WHERE db_id = ? AND table_slug = ?`,
|
||||
queryString: `SELECT * FROM datasquirel.user_database_tables WHERE db_id = ? AND table_slug = ?`,
|
||||
queryValuesArray: [recordedDbEntry.id, tableSchema?.tableName],
|
||||
});
|
||||
|
||||
/** @type {import("../../types").MYSQL_user_database_tables_table_def} */
|
||||
const table = existingTable?.[0];
|
||||
const table: import("../../types").MYSQL_user_database_tables_table_def =
|
||||
existingTable?.[0];
|
||||
|
||||
if (!table?.id) {
|
||||
const newTableEntry = await dbHandler({
|
||||
query: `INSERT INTO user_database_tables SET ?`,
|
||||
query: `INSERT INTO datasquirel.user_database_tables SET ?`,
|
||||
values: {
|
||||
user_id: recordedDbEntry.user_id,
|
||||
db_id: recordedDbEntry.id,
|
||||
@@ -86,7 +77,6 @@ module.exports = async function createTable({
|
||||
date_updated: Date(),
|
||||
date_updated_code: Date.now(),
|
||||
},
|
||||
database: "datasquirel",
|
||||
});
|
||||
}
|
||||
} catch (error) {}
|
||||
@@ -98,7 +88,7 @@ module.exports = async function createTable({
|
||||
let primaryKeySet = false;
|
||||
|
||||
/** @type {import("../../types").DSQL_FieldSchemaType[]} */
|
||||
let foreignKeys = [];
|
||||
let foreignKeys: import("../../types").DSQL_FieldSchemaType[] = [];
|
||||
|
||||
////////////////////////////////////////
|
||||
|
||||
@@ -156,10 +146,6 @@ module.exports = async function createTable({
|
||||
////////////////////////////////////////
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
if (foreignKeys[0]) {
|
||||
foreignKeys.forEach((foreighKey, index, array) => {
|
||||
const fieldName = foreighKey.fieldName;
|
||||
@@ -196,18 +182,7 @@ module.exports = async function createTable({
|
||||
|
||||
const newTable = await varDatabaseDbHandler({
|
||||
queryString: createTableQuery,
|
||||
database: dbFullName,
|
||||
});
|
||||
|
||||
return newTable;
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
};
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
}
|
||||
@@ -1,118 +0,0 @@
|
||||
// @ts-check
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
|
||||
const mysql = require("serverless-mysql");
|
||||
const grabDbSSL = require("../../utils/backend/grabDbSSL");
|
||||
|
||||
let connection = mysql({
|
||||
config: {
|
||||
host: process.env.DSQL_DB_HOST,
|
||||
user: process.env.DSQL_DB_USERNAME,
|
||||
password: process.env.DSQL_DB_PASSWORD,
|
||||
database: process.env.DSQL_DB_NAME,
|
||||
charset: "utf8mb4",
|
||||
ssl: grabDbSSL(),
|
||||
},
|
||||
});
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* # Main DB Handler Function
|
||||
* @async
|
||||
*
|
||||
* @param {object} params
|
||||
* @param {string} params.query
|
||||
* @param {string[] | object} [params.values]
|
||||
* @param {string} [params.database]
|
||||
*
|
||||
* @returns {Promise<any[] | object | null>}
|
||||
*/
|
||||
module.exports = async function dbHandler({ query, values, database }) {
|
||||
/**
|
||||
* Switch Database
|
||||
*
|
||||
* @description If a database is provided, switch to it
|
||||
*/
|
||||
let isDbCorrect = true;
|
||||
|
||||
if (database) {
|
||||
connection = mysql({
|
||||
config: {
|
||||
host: process.env.DSQL_DB_HOST,
|
||||
user: process.env.DSQL_DB_USERNAME,
|
||||
password: process.env.DSQL_DB_PASSWORD,
|
||||
database: database,
|
||||
charset: "utf8mb4",
|
||||
ssl: grabDbSSL(),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
if (!isDbCorrect) {
|
||||
console.log(
|
||||
"Shell Db Handler ERROR in switching Database! Operation Failed!"
|
||||
);
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Declare variables
|
||||
*
|
||||
* @description Declare "results" variable
|
||||
*/
|
||||
let results;
|
||||
|
||||
/**
|
||||
* Fetch from db
|
||||
*
|
||||
* @description Fetch data from db if no cache
|
||||
*/
|
||||
try {
|
||||
if (query && values) {
|
||||
results = await connection.query(query, values);
|
||||
} else {
|
||||
results = await connection.query(query);
|
||||
}
|
||||
|
||||
/** ********************* Clean up */
|
||||
await connection.end();
|
||||
} catch (/** @type {any} */ error) {
|
||||
if (process.env.FIRST_RUN) {
|
||||
return null;
|
||||
}
|
||||
|
||||
console.log("ERROR in dbHandler =>", error.message);
|
||||
console.log(error);
|
||||
console.log(connection.config());
|
||||
|
||||
fs.appendFileSync(
|
||||
path.resolve(__dirname, "../.tmp/dbErrorLogs.txt"),
|
||||
JSON.stringify(error, null, 4) + "\n" + Date() + "\n\n\n",
|
||||
"utf8"
|
||||
);
|
||||
results = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return results
|
||||
*
|
||||
* @description Return results add to cache if "req" param is passed
|
||||
*/
|
||||
if (results) {
|
||||
return JSON.parse(JSON.stringify(results));
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
|
||||
import mysql from "serverless-mysql";
|
||||
import grabDbSSL from "../../utils/backend/grabDbSSL";
|
||||
|
||||
type Param = {
|
||||
query: string;
|
||||
values?: string[] | object;
|
||||
};
|
||||
|
||||
/**
|
||||
* # Main DB Handler Function
|
||||
* @requires DSQL_DB_CONN - Gobal Variable for Datasquirel Database
|
||||
*/
|
||||
export default async function dbHandler({
|
||||
query,
|
||||
values,
|
||||
}: Param): Promise<any[] | object | null> {
|
||||
let connection = global.DSQL_DB_CONN;
|
||||
|
||||
let results;
|
||||
|
||||
try {
|
||||
if (query && values) {
|
||||
results = await connection.query(query, values);
|
||||
} else {
|
||||
results = await connection.query(query);
|
||||
}
|
||||
} catch (/** @type {any} */ error: any) {
|
||||
if (process.env.FIRST_RUN) {
|
||||
return null;
|
||||
}
|
||||
|
||||
console.log("ERROR in dbHandler =>", error.message);
|
||||
console.log(error);
|
||||
console.log(connection.config());
|
||||
|
||||
fs.appendFileSync(
|
||||
path.resolve(__dirname, "../.tmp/dbErrorLogs.txt"),
|
||||
JSON.stringify(error, null, 4) + "\n" + Date() + "\n\n\n",
|
||||
"utf8"
|
||||
);
|
||||
results = null;
|
||||
} finally {
|
||||
await connection?.end();
|
||||
}
|
||||
|
||||
if (results) {
|
||||
return JSON.parse(JSON.stringify(results));
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -1,108 +0,0 @@
|
||||
// @ts-check
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
|
||||
/**
|
||||
* Generate SQL text for Field
|
||||
* ==============================================================================
|
||||
* @param {object} params - Single object params
|
||||
* @param {import("../../types").DSQL_FieldSchemaType} params.columnData - Field object
|
||||
* @param {boolean} [params.primaryKeySet] - Table Name(slug)
|
||||
*
|
||||
* @returns {{ fieldEntryText: string, newPrimaryKeySet: boolean }}
|
||||
*/
|
||||
module.exports = function generateColumnDescription({
|
||||
columnData,
|
||||
primaryKeySet,
|
||||
}) {
|
||||
/**
|
||||
* Format tableInfoArray
|
||||
*
|
||||
* @description Format tableInfoArray
|
||||
*/
|
||||
const {
|
||||
fieldName,
|
||||
dataType,
|
||||
nullValue,
|
||||
primaryKey,
|
||||
autoIncrement,
|
||||
defaultValue,
|
||||
defaultValueLiteral,
|
||||
foreignKey,
|
||||
updatedField,
|
||||
onUpdate,
|
||||
onUpdateLiteral,
|
||||
onDelete,
|
||||
onDeleteLiteral,
|
||||
defaultField,
|
||||
encrypted,
|
||||
json,
|
||||
newTempField,
|
||||
notNullValue,
|
||||
originName,
|
||||
plainText,
|
||||
pattern,
|
||||
patternFlags,
|
||||
richText,
|
||||
} = columnData;
|
||||
|
||||
let fieldEntryText = "";
|
||||
|
||||
fieldEntryText += `\`${fieldName}\` ${dataType}`;
|
||||
|
||||
////////////////////////////////////////
|
||||
|
||||
// if (String(fieldEntryText).match(/ UUID$/)) {
|
||||
// fieldEntryText += ` DEFAULT UUID()`;
|
||||
// } else
|
||||
if (nullValue) {
|
||||
fieldEntryText += " DEFAULT NULL";
|
||||
} else if (defaultValueLiteral) {
|
||||
fieldEntryText += ` DEFAULT ${defaultValueLiteral}`;
|
||||
} else if (defaultValue) {
|
||||
if (String(defaultValue).match(/uuid\(\)/i)) {
|
||||
fieldEntryText += ` DEFAULT UUID()`;
|
||||
} else {
|
||||
fieldEntryText += ` DEFAULT '${defaultValue}'`;
|
||||
}
|
||||
} else if (notNullValue) {
|
||||
fieldEntryText += ` NOT NULL`;
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
|
||||
if (onUpdateLiteral) {
|
||||
fieldEntryText += ` ON UPDATE ${onUpdateLiteral}`;
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
|
||||
if (primaryKey && !primaryKeySet) {
|
||||
fieldEntryText += " PRIMARY KEY";
|
||||
primaryKeySet = true;
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
|
||||
if (autoIncrement) {
|
||||
fieldEntryText += " AUTO_INCREMENT";
|
||||
primaryKeySet = true;
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
return { fieldEntryText, newPrimaryKeySet: primaryKeySet || false };
|
||||
};
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
@@ -0,0 +1,83 @@
|
||||
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 {
|
||||
/**
|
||||
* 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,
|
||||
};
|
||||
}
|
||||
@@ -1,45 +0,0 @@
|
||||
// @ts-check
|
||||
|
||||
const dbHandler = require("./dbHandler");
|
||||
|
||||
/**
|
||||
* Create database from Schema Function
|
||||
* ==============================================================================
|
||||
* @param {string} queryString - Query String
|
||||
* @returns {Promise<any>}
|
||||
*/
|
||||
module.exports = async function noDatabaseDbHandler(queryString) {
|
||||
/**
|
||||
* Declare variables
|
||||
*
|
||||
* @description Declare "results" variable
|
||||
*/
|
||||
let results;
|
||||
|
||||
/**
|
||||
* Fetch from db
|
||||
*
|
||||
* @description Fetch data from db if no cache
|
||||
*/
|
||||
try {
|
||||
/** ********************* Run Query */
|
||||
results = await dbHandler({ query: queryString });
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
} catch (/** @type {any} */ error) {
|
||||
console.log("ERROR in noDatabaseDbHandler =>", error.message);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return results
|
||||
*
|
||||
* @description Return results add to cache if "req" param is passed
|
||||
*/
|
||||
if (results) {
|
||||
return results;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,19 @@
|
||||
import dbHandler from "./dbHandler";
|
||||
|
||||
export default async function noDatabaseDbHandler(
|
||||
queryString: string
|
||||
): Promise<any> {
|
||||
let results;
|
||||
|
||||
try {
|
||||
results = await dbHandler({ query: queryString });
|
||||
} catch (error: any) {
|
||||
console.log("ERROR in noDatabaseDbHandler =>", error.message);
|
||||
}
|
||||
|
||||
if (results) {
|
||||
return results;
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+5
-4
@@ -1,6 +1,7 @@
|
||||
// @ts-check
|
||||
|
||||
module.exports = function slugToCamelTitle(/** @type {String} */ text) {
|
||||
/**
|
||||
* # Sulg To Camel Case
|
||||
*/
|
||||
export default function slugToCamelTitle(text: string) {
|
||||
if (text) {
|
||||
let addArray = text.split("-").filter((item) => item !== "");
|
||||
let camelArray = addArray.map((item) => {
|
||||
@@ -15,4 +16,4 @@ module.exports = function slugToCamelTitle(/** @type {String} */ text) {
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
}
|
||||
+8
-14
@@ -1,19 +1,13 @@
|
||||
// @ts-check
|
||||
import { DSQL_FieldSchemaType } from "../../types";
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
type Param = {
|
||||
tableInfoArray: DSQL_FieldSchemaType[];
|
||||
};
|
||||
|
||||
/**
|
||||
*
|
||||
* @param {object} param0
|
||||
* @param {import("../../types").DSQL_FieldSchemaType[]} param0.tableInfoArray
|
||||
* @returns
|
||||
* # Supplement Table
|
||||
*/
|
||||
module.exports = function supplementTable({ tableInfoArray }) {
|
||||
export default function supplementTable({ tableInfoArray }: Param) {
|
||||
/**
|
||||
* Format tableInfoArray
|
||||
*
|
||||
@@ -30,7 +24,7 @@ module.exports = function supplementTable({ tableInfoArray }) {
|
||||
|
||||
////////////////////////////////////////
|
||||
|
||||
defaultFields.forEach((field) => {
|
||||
defaultFields.forEach((field: any) => {
|
||||
let fieldExists = finalTableArray.filter(
|
||||
(_field) => _field.fieldName === field.fieldName
|
||||
);
|
||||
@@ -49,7 +43,7 @@ module.exports = function supplementTable({ tableInfoArray }) {
|
||||
////////////////////////////////////////
|
||||
|
||||
return finalTableArray;
|
||||
};
|
||||
}
|
||||
|
||||
/** ****************************************************************************** */
|
||||
/** ****************************************************************************** */
|
||||
+54
-112
@@ -1,46 +1,31 @@
|
||||
// @ts-check
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
///////////////////////// - Update Table Function - ////////////////////////////
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
const fs = require("fs");
|
||||
const varDatabaseDbHandler = require("./varDatabaseDbHandler");
|
||||
import fs from "fs";
|
||||
import varDatabaseDbHandler from "./varDatabaseDbHandler";
|
||||
|
||||
const defaultFieldsRegexp =
|
||||
/^id$|^uuid$|^date_created$|^date_created_code$|^date_created_timestamp$|^date_updated$|^date_updated_code$|^date_updated_timestamp$/;
|
||||
|
||||
const generateColumnDescription = require("./generateColumnDescription");
|
||||
const dbHandler = require("./dbHandler");
|
||||
import generateColumnDescription from "./generateColumnDescription";
|
||||
import dbHandler from "./dbHandler";
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
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
|
||||
* ==============================================================================
|
||||
* @param {object} params - Single object params
|
||||
* @param {string} params.dbFullName - Database full name => "datasquirel_user_4394_db_name"
|
||||
* @param {string} params.tableName - Table Name(slug)
|
||||
* @param {import("../../types").DSQL_TableSchemaType} params.tableSchema - Table Name(slug)
|
||||
* @param {string} [params.tableNameFull] - Table Name(slug)
|
||||
* @param {import("../../types").DSQL_FieldSchemaType[]} params.tableInfoArray - Table Info Array
|
||||
* @param {number | string | null} [params.userId] - User ID
|
||||
* @param {import("../../types").DSQL_DatabaseSchemaType[]} params.dbSchema - Single post
|
||||
* @param {import("../../types").DSQL_IndexSchemaType[]} [params.tableIndexes] - Table Indexes
|
||||
* @param {boolean} [params.clone] - Is this a newly cloned table?
|
||||
* @param {number} [params.tableIndex] - The number index of the table in the dbSchema array
|
||||
* @param {boolean} [params.childDb] - The number index of the table in the dbSchema array
|
||||
* @param {any} [params.recordedDbEntry] - The database object as recorded in `user_databases` table
|
||||
* # Update table function
|
||||
*/
|
||||
module.exports = async function updateTable({
|
||||
export default async function updateTable({
|
||||
dbFullName,
|
||||
tableName,
|
||||
tableInfoArray,
|
||||
@@ -53,7 +38,7 @@ module.exports = async function updateTable({
|
||||
tableIndex,
|
||||
tableNameFull,
|
||||
recordedDbEntry,
|
||||
}) {
|
||||
}: Param) {
|
||||
/**
|
||||
* Initialize
|
||||
* ==========================================
|
||||
@@ -61,7 +46,7 @@ module.exports = async function updateTable({
|
||||
*/
|
||||
|
||||
/** @type {any[]} */
|
||||
let errorLogs = [];
|
||||
let errorLogs: any[] = [];
|
||||
|
||||
/**
|
||||
* @description Initialize table info array. This value will be
|
||||
@@ -79,22 +64,20 @@ module.exports = async function updateTable({
|
||||
* @type {string[]}
|
||||
* @description Table update query string array
|
||||
*/
|
||||
const updateTableQueryArray = [];
|
||||
const updateTableQueryArray: string[] = [];
|
||||
|
||||
/**
|
||||
* @type {string[]}
|
||||
* @description Constriants query string array
|
||||
*/
|
||||
const constraintsQueryArray = [];
|
||||
const constraintsQueryArray: string[] = [];
|
||||
|
||||
/**
|
||||
* @description Push the query initial value
|
||||
*/
|
||||
updateTableQueryArray.push(`ALTER TABLE \`${tableName}\``);
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
updateTableQueryArray.push(
|
||||
`ALTER TABLE \`${dbFullName}\`.\`${tableName}\``
|
||||
);
|
||||
|
||||
if (childDb) {
|
||||
try {
|
||||
@@ -103,17 +86,17 @@ module.exports = async function updateTable({
|
||||
}
|
||||
|
||||
const existingTable = await varDatabaseDbHandler({
|
||||
database: "datasquirel",
|
||||
queryString: `SELECT * FROM user_database_tables WHERE db_id = ? AND table_slug = ?`,
|
||||
queryString: `SELECT * FROM datasquirel.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?.[0];
|
||||
const table: import("../../types").MYSQL_user_database_tables_table_def =
|
||||
existingTable?.[0];
|
||||
|
||||
if (!table?.id) {
|
||||
const newTableEntry = await dbHandler({
|
||||
query: `INSERT INTO user_database_tables SET ?`,
|
||||
query: `INSERT INTO datasquirel.user_database_tables SET ?`,
|
||||
values: {
|
||||
user_id: recordedDbEntry.user_id,
|
||||
db_id: recordedDbEntry.id,
|
||||
@@ -130,33 +113,28 @@ module.exports = async function updateTable({
|
||||
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 = await varDatabaseDbHandler({
|
||||
queryString: `SHOW INDEXES FROM \`${tableName}\``,
|
||||
database: dbFullName,
|
||||
});
|
||||
const allExistingIndexes: import("../../types").DSQL_MYSQL_SHOW_INDEXES_Type[] =
|
||||
await varDatabaseDbHandler({
|
||||
queryString: `SHOW INDEXES FROM \`${dbFullName}\`.\`${tableName}\``,
|
||||
});
|
||||
|
||||
/**
|
||||
* @type {import("../../types").DSQL_MYSQL_SHOW_COLUMNS_Type[]}
|
||||
* @description All columns from MYSQL db
|
||||
*/ // @ts-ignore
|
||||
const allExistingColumns = await varDatabaseDbHandler({
|
||||
queryString: `SHOW COLUMNS FROM \`${tableName}\``,
|
||||
database: dbFullName,
|
||||
});
|
||||
const allExistingColumns: import("../../types").DSQL_MYSQL_SHOW_COLUMNS_Type[] =
|
||||
await varDatabaseDbHandler({
|
||||
queryString: `SHOW COLUMNS FROM \`${dbFullName}\`.\`${tableName}\``,
|
||||
});
|
||||
|
||||
////////////////////////////////////////
|
||||
|
||||
@@ -164,11 +142,7 @@ module.exports = async function updateTable({
|
||||
* @type {string[]}
|
||||
* @description Updated column names Array
|
||||
*/
|
||||
const updatedColumnsArray = [];
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
const updatedColumnsArray: string[] = [];
|
||||
|
||||
/**
|
||||
* @description Iterate through every existing column
|
||||
@@ -198,8 +172,7 @@ module.exports = async function updateTable({
|
||||
updatedColumnsArray.push(existingEntry[0].fieldName);
|
||||
|
||||
const renameColumn = await varDatabaseDbHandler({
|
||||
queryString: `ALTER TABLE ${tableName} RENAME COLUMN \`${existingEntry[0].originName}\` TO \`${existingEntry[0].fieldName}\``,
|
||||
database: dbFullName,
|
||||
queryString: `ALTER TABLE \`${dbFullName}\`.\`${tableName}\` RENAME COLUMN \`${existingEntry[0].originName}\` TO \`${existingEntry[0].fieldName}\``,
|
||||
});
|
||||
|
||||
console.log(
|
||||
@@ -251,7 +224,7 @@ module.exports = async function updateTable({
|
||||
JSON.stringify(userSchemaData),
|
||||
"utf8"
|
||||
);
|
||||
} catch (/** @type {any} */ error) {
|
||||
} catch (/** @type {any} */ error: any) {
|
||||
console.log("Update table error =>", error.message);
|
||||
}
|
||||
|
||||
@@ -265,16 +238,11 @@ module.exports = async function updateTable({
|
||||
////////////////////////////////////////
|
||||
} else {
|
||||
await varDatabaseDbHandler({
|
||||
queryString: `ALTER TABLE ${tableName} DROP COLUMN \`${Field}\``,
|
||||
database: dbFullName,
|
||||
queryString: `ALTER TABLE \`${dbFullName}\`.\`${tableName}\` DROP COLUMN \`${Field}\``,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* Handle MYSQL Table Indexes
|
||||
* ===================================================
|
||||
@@ -303,8 +271,7 @@ module.exports = async function updateTable({
|
||||
* present in the datasquirel DB schema
|
||||
*/
|
||||
await varDatabaseDbHandler({
|
||||
queryString: `ALTER TABLE ${tableName} DROP INDEX \`${Key_name}\``,
|
||||
database: dbFullName,
|
||||
queryString: `ALTER TABLE \`${dbFullName}\`.\`${tableName}\` DROP INDEX \`${Key_name}\``,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -340,20 +307,15 @@ module.exports = async function updateTable({
|
||||
await varDatabaseDbHandler({
|
||||
queryString: `CREATE${
|
||||
indexType?.match(/fullText/i) ? " FULLTEXT" : ""
|
||||
} INDEX \`${alias}\` ON ${tableName}(${indexTableFields
|
||||
} INDEX \`${alias}\` ON \`${dbFullName}\`.\`${tableName}\`(${indexTableFields
|
||||
?.map((nm) => nm.value)
|
||||
.map((nm) => `\`${nm}\``)
|
||||
.join(",")}) COMMENT 'schema_index'`,
|
||||
database: dbFullName,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* Handle MYSQL Foreign Keys
|
||||
* ===================================================
|
||||
@@ -364,10 +326,11 @@ module.exports = async function updateTable({
|
||||
/**
|
||||
* @description All MSQL Foreign Keys
|
||||
* @type {import("../../types").DSQL_MYSQL_FOREIGN_KEYS_Type[] | null}
|
||||
*/ // @ts-ignore
|
||||
const allForeignKeys = await varDatabaseDbHandler({
|
||||
*/
|
||||
const allForeignKeys:
|
||||
| import("../../types").DSQL_MYSQL_FOREIGN_KEYS_Type[]
|
||||
| null = await varDatabaseDbHandler({
|
||||
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) {
|
||||
@@ -384,16 +347,11 @@ module.exports = async function updateTable({
|
||||
* Foreign keys
|
||||
*/
|
||||
const dropForeignKey = await varDatabaseDbHandler({
|
||||
queryString: `ALTER TABLE ${tableName} DROP FOREIGN KEY \`${CONSTRAINT_NAME}\``,
|
||||
database: dbFullName,
|
||||
queryString: `ALTER TABLE \`${dbFullName}\`.\`${tableName}\` DROP FOREIGN KEY \`${CONSTRAINT_NAME}\``,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* Handle DATASQUIREL schema fields for current table
|
||||
* ===================================================
|
||||
@@ -435,7 +393,7 @@ module.exports = async function updateTable({
|
||||
////////////////////////////////////////
|
||||
|
||||
/** @type {any} */
|
||||
let existingColumnIndex;
|
||||
let existingColumnIndex: any;
|
||||
|
||||
/**
|
||||
* @description Existing MYSQL field object
|
||||
@@ -516,10 +474,6 @@ module.exports = async function updateTable({
|
||||
*/
|
||||
updateTableQueryArray.push(updateText + ",");
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
|
||||
/**
|
||||
* @description Handle foreing keys if available, and if there is no
|
||||
* "clone" boolean = true
|
||||
@@ -538,10 +492,9 @@ module.exports = async function updateTable({
|
||||
}${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 finalQueryString = `ALTER TABLE \`${dbFullName}\`.\`${tableName}\` ${foreinKeyText}`;
|
||||
|
||||
const addForeignKey = await varDatabaseDbHandler({
|
||||
database: dbFullName,
|
||||
queryString: finalQueryString,
|
||||
});
|
||||
|
||||
@@ -571,7 +524,6 @@ module.exports = async function updateTable({
|
||||
if (updateTableQueryArray.length > 1) {
|
||||
const updateTable = await varDatabaseDbHandler({
|
||||
queryString: updateTableQuery,
|
||||
database: dbFullName,
|
||||
});
|
||||
|
||||
return updateTable;
|
||||
@@ -582,19 +534,9 @@ module.exports = async function updateTable({
|
||||
*/
|
||||
return "No Changes Made to Table";
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
} catch (/** @type {any} */ error) {
|
||||
} catch (/** @type {any} */ error: any) {
|
||||
console.log('Error in "updateTable" shell function =>', error.message);
|
||||
|
||||
return "Error in Updating Table";
|
||||
}
|
||||
};
|
||||
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
////////////////////////////////////////////////////////////////////////////////
|
||||
}
|
||||
+11
-24
@@ -1,25 +1,18 @@
|
||||
// @ts-check
|
||||
import dbHandler from "./dbHandler";
|
||||
import { DSQL_TableSchemaType } from "../../types";
|
||||
|
||||
const fs = require("fs");
|
||||
const dbHandler = require("./dbHandler");
|
||||
type Param = {
|
||||
queryString: string;
|
||||
queryValuesArray?: string[];
|
||||
};
|
||||
|
||||
/**
|
||||
* DB handler for specific database
|
||||
* ==============================================================================
|
||||
* @async
|
||||
* @param {object} params - Single object params
|
||||
* @param {string} params.queryString - SQL string
|
||||
* @param {string[]} [params.queryValuesArray] - Values Array
|
||||
* @param {string} [params.database] - Database name
|
||||
* @param {import("../../types").DSQL_TableSchemaType} [params.tableSchema] - Table schema
|
||||
* @returns {Promise<any>}
|
||||
* # DB handler for specific database
|
||||
*/
|
||||
module.exports = async function varDatabaseDbHandler({
|
||||
export default async function varDatabaseDbHandler({
|
||||
queryString,
|
||||
queryValuesArray,
|
||||
database,
|
||||
tableSchema,
|
||||
}) {
|
||||
}: Param): Promise<any> {
|
||||
/**
|
||||
* Declare variables
|
||||
*
|
||||
@@ -42,19 +35,17 @@ module.exports = async function varDatabaseDbHandler({
|
||||
results = await dbHandler({
|
||||
query: queryString,
|
||||
values: queryValuesArray,
|
||||
database,
|
||||
});
|
||||
} else {
|
||||
results = await dbHandler({
|
||||
query: queryString,
|
||||
database,
|
||||
});
|
||||
}
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
} catch (/** @type {any} */ error) {
|
||||
} catch (/** @type {any} */ error: any) {
|
||||
console.log("Shell Vardb Error =>", error.message);
|
||||
}
|
||||
|
||||
@@ -64,8 +55,4 @@ module.exports = async function varDatabaseDbHandler({
|
||||
* @description Return results add to cache if "req" param is passed
|
||||
*/
|
||||
return results;
|
||||
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
////////////////////////////////////////
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user