Updates
This commit is contained in:
+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