datasquirel/dist/package-shared/shell/createDbFromSchema.js
Benjamin Toby 186cc76ffb Updates
2025-01-12 18:19:20 +01:00

265 lines
14 KiB
JavaScript

"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = createDbFromSchema;
const path_1 = __importDefault(require("path"));
const fs_1 = __importDefault(require("fs"));
const noDatabaseDbHandler_1 = __importDefault(require("./utils/noDatabaseDbHandler"));
const varDatabaseDbHandler_1 = __importDefault(require("./utils/varDatabaseDbHandler"));
const createTable_1 = __importDefault(require("./utils/createTable"));
const updateTable_1 = __importDefault(require("./utils/updateTable"));
const dbHandler_1 = __importDefault(require("./utils/dbHandler"));
const ejson_1 = __importDefault(require("../utils/ejson"));
const util_1 = require("util");
/**
* # Create database from Schema Function
*/
function createDbFromSchema(_a) {
return __awaiter(this, arguments, void 0, function* ({ userId, targetDatabase, dbSchemaData, }) {
var _b, _c;
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_1.default.join(String(process.env.DSQL_USER_DB_SCHEMA_PATH), `/user-${userId}/main.json`)
: path_1.default.resolve(__dirname, "../../jsonData/dbSchemas/main.json");
const dbSchema = dbSchemaData ||
ejson_1.default.parse(fs_1.default.readFileSync(schemaPath, "utf8"));
if (!dbSchema) {
console.log("Schema Not Found!");
return;
}
// await createDatabasesFromSchema(dbSchema);
for (let i = 0; i < dbSchema.length; i++) {
/** @type {import("../types").DSQL_DatabaseSchemaType} */
const database = dbSchema[i];
const { dbFullName, tables, dbName, dbSlug, childrenDatabases } = database;
if (targetDatabase && dbFullName != targetDatabase) {
continue;
}
console.log("Checking Database ...");
/** @type {any} */
const dbCheck = yield (0, noDatabaseDbHandler_1.default)(`SELECT SCHEMA_NAME AS dbFullName FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '${dbFullName}'`);
console.log("DB Checked Success!");
if (dbCheck && ((_b = dbCheck[0]) === null || _b === void 0 ? void 0 : _b.dbFullName)) {
// Database Exists
}
else {
const newDatabase = yield (0, noDatabaseDbHandler_1.default)(`CREATE DATABASE IF NOT EXISTS \`${dbFullName}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_bin`);
}
/**
* Select all tables
* @type {any}
* @description Select All tables in target database
*/
const allTables = yield (0, noDatabaseDbHandler_1.default)(`SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA='${dbFullName}'`);
// let tableDropped;
for (let tb = 0; tb < allTables.length; tb++) {
const { TABLE_NAME } = allTables[tb];
/**
* @description Check if TABLE_NAME is part of the tables contained
* in the user schema JSON. If it's not, the table is either deleted
* or the table name has been recently changed
*/
if (!tables.filter((_table) => _table.tableName === TABLE_NAME)[0]) {
const oldTableFilteredArray = tables.filter((_table) => _table.tableNameOld &&
_table.tableNameOld === TABLE_NAME);
/**
* @description Check if this table has been recently renamed. Rename
* table id true. Drop table if false
*/
if (oldTableFilteredArray && oldTableFilteredArray[0]) {
console.log("Renaming Table");
yield (0, varDatabaseDbHandler_1.default)({
queryString: `RENAME TABLE \`${oldTableFilteredArray[0].tableNameOld}\` TO \`${oldTableFilteredArray[0].tableName}\``,
database: dbFullName,
});
}
else {
console.log(`Dropping Table from ${dbFullName}`);
yield (0, varDatabaseDbHandler_1.default)({
queryString: `DROP TABLE \`${TABLE_NAME}\``,
database: dbFullName,
});
const deleteTableEntry = yield (0, dbHandler_1.default)({
query: `DELETE FROM user_database_tables WHERE user_id = ? AND db_slug = ? AND table_slug = ?`,
values: [userId, dbSlug, TABLE_NAME],
database: "datasquirel",
});
}
}
}
const recordedDbEntryArray = userId
? yield (0, varDatabaseDbHandler_1.default)({
database: "datasquirel",
queryString: `SELECT * FROM user_databases WHERE db_full_name = ?`,
queryValuesArray: [dbFullName],
})
: undefined;
const recordedDbEntry = recordedDbEntryArray === null || recordedDbEntryArray === void 0 ? void 0 : recordedDbEntryArray[0];
/**
* @description Iterate through each table and perform table actions
*/
for (let t = 0; t < tables.length; t++) {
const table = tables[t];
const { tableName, fields, indexes } = table;
/**
* @description Check if table exists
* @type {any}
*/
const tableCheck = yield (0, varDatabaseDbHandler_1.default)({
queryString: `
SELECT EXISTS (
SELECT
TABLE_NAME
FROM
information_schema.TABLES
WHERE
TABLE_SCHEMA = ? AND
TABLE_NAME = ?
) AS tableExists`,
queryValuesArray: [dbFullName, table.tableName],
database: dbFullName,
});
////////////////////////////////////////
if (tableCheck && ((_c = tableCheck[0]) === null || _c === void 0 ? void 0 : _c.tableExists) > 0) {
/**
* @description Update table if table exists
*/
const updateExistingTable = yield (0, updateTable_1.default)({
dbFullName: dbFullName,
tableName: tableName,
tableNameFull: table.tableFullName,
tableInfoArray: fields,
userId,
dbSchema,
tableIndexes: indexes,
tableIndex: t,
childDb: database.childDatabase || undefined,
recordedDbEntry,
tableSchema: table,
});
if (table.childrenTables && table.childrenTables[0]) {
for (let ch = 0; ch < table.childrenTables.length; ch++) {
const childTable = table.childrenTables[ch];
const updateExistingChildTable = yield (0, updateTable_1.default)({
dbFullName: childTable.dbNameFull,
tableName: childTable.tableName,
tableNameFull: childTable.tableNameFull,
tableInfoArray: fields,
userId,
dbSchema,
tableIndexes: indexes,
clone: true,
childDb: database.childDatabase || undefined,
recordedDbEntry,
tableSchema: table,
});
}
}
////////////////////////////////////////
}
else {
////////////////////////////////////////
/**
* @description Create new Table if table doesnt exist
*/
const createNewTable = yield (0, createTable_1.default)({
tableName: tableName,
tableInfoArray: fields,
dbFullName: dbFullName,
dbSchema,
tableSchema: table,
recordedDbEntry,
});
if (indexes && indexes[0]) {
/**
* Handle DATASQUIREL Table Indexes
* ===================================================
* @description Iterate through each datasquirel schema
* table index(if available), and perform operations
*/
if (indexes && indexes[0]) {
for (let g = 0; g < indexes.length; g++) {
const { indexType, indexName, indexTableFields, alias, } = indexes[g];
if (!(alias === null || alias === void 0 ? void 0 : alias.match(/./)))
continue;
/**
* @description Check for existing Index in MYSQL db
*/
try {
/**
* @type {import("../types").DSQL_MYSQL_SHOW_INDEXES_Type[]}
* @description All indexes from MYSQL db
*/ // @ts-ignore
const allExistingIndexes = yield (0, varDatabaseDbHandler_1.default)({
queryString: `SHOW INDEXES FROM \`${tableName}\``,
database: dbFullName,
});
const existingKeyInDb = allExistingIndexes.filter((indexObject) => indexObject.Key_name === alias);
if (!existingKeyInDb[0])
throw new Error("This Index Does not Exist");
}
catch (error) {
/**
* @description Create new index if determined that it
* doesn't exist in MYSQL db
*/
yield (0, varDatabaseDbHandler_1.default)({
queryString: `CREATE${(indexType === null || indexType === void 0 ? void 0 : indexType.match(/fullText/i))
? " FULLTEXT"
: ""} INDEX \`${alias}\` ON ${tableName}(${indexTableFields === null || indexTableFields === void 0 ? void 0 : indexTableFields.map((nm) => nm.value).map((nm) => `\`${nm}\``).join(",")}) COMMENT 'schema_index'`,
database: dbFullName,
});
}
}
}
}
}
}
/**
* @description Check all children databases
*/
if (childrenDatabases === null || childrenDatabases === void 0 ? void 0 : childrenDatabases[0]) {
for (let ch = 0; ch < childrenDatabases.length; ch++) {
const childDb = childrenDatabases[ch];
const { dbFullName } = childDb;
yield createDbFromSchema({
userId,
targetDatabase: dbFullName,
});
}
}
}
console.log("Database Successfully Rebuilt!");
console.log("///////////////////////////////");
console.log("///////////////////////////////");
});
}
const { values } = (0, util_1.parseArgs)({
args: process.argv,
options: {
exec: { type: "boolean" },
},
strict: true,
allowPositionals: true,
});
if (values.exec) {
createDbFromSchema({});
}