216 lines
10 KiB
JavaScript
216 lines
10 KiB
JavaScript
import noDatabaseDbHandler from "../utils/noDatabaseDbHandler";
|
|
import varDatabaseDbHandler from "../utils/varDatabaseDbHandler";
|
|
import createTable from "../utils/createTable";
|
|
import updateTable from "../utils/updateTable";
|
|
import grabDirNames from "../../utils/backend/names/grab-dir-names";
|
|
import checkDbRecordCreateDbSchema from "./check-db-record";
|
|
import handleIndexescreateDbFromSchema from "./handle-indexes";
|
|
import grabRequiredDatabaseSchemas, { grabPrimaryRequiredDbSchema, } from "./grab-required-database-schemas";
|
|
import dbHandler from "../../functions/backend/dbHandler";
|
|
/**
|
|
* # Create database from Schema Function
|
|
* @requires DSQL_DB_CONN - Gobal Variable for Datasquirel Database
|
|
*/
|
|
export default async function createDbFromSchema({ userId, targetDatabase, dbSchemaData, targetTable, dbId, }) {
|
|
var _a, _b;
|
|
try {
|
|
const { userSchemaMainJSONFilePath } = grabDirNames({
|
|
userId,
|
|
});
|
|
let dbSchema = dbSchemaData
|
|
? dbSchemaData
|
|
: dbId
|
|
? grabRequiredDatabaseSchemas({
|
|
dbId,
|
|
userId,
|
|
})
|
|
: undefined;
|
|
if (!dbSchema) {
|
|
console.log("Schema Not Found!");
|
|
return false;
|
|
}
|
|
const isMain = !userSchemaMainJSONFilePath;
|
|
for (let i = 0; i < dbSchema.length; i++) {
|
|
const database = dbSchema[i];
|
|
const { dbFullName, tables, dbSlug, childrenDatabases } = database;
|
|
if (!dbFullName)
|
|
continue;
|
|
if (targetDatabase && dbFullName != targetDatabase) {
|
|
continue;
|
|
}
|
|
console.log(`Handling database => ${dbFullName}`);
|
|
const dbCheck = await noDatabaseDbHandler(`SELECT SCHEMA_NAME AS dbFullName FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '${dbFullName}'`);
|
|
if (!((_a = dbCheck === null || dbCheck === void 0 ? void 0 : dbCheck[0]) === null || _a === void 0 ? void 0 : _a.dbFullName)) {
|
|
const newDatabase = await noDatabaseDbHandler(`CREATE DATABASE IF NOT EXISTS \`${dbFullName}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_bin`);
|
|
}
|
|
const allTables = await noDatabaseDbHandler(`SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA='${dbFullName}'`);
|
|
let recordedDbEntry = await checkDbRecordCreateDbSchema({
|
|
dbSchema: database,
|
|
userId,
|
|
isMain,
|
|
});
|
|
for (let tb = 0; tb < allTables.length; tb++) {
|
|
const { TABLE_NAME } = allTables[tb];
|
|
const targetTableSchema = tables.find((_table) => _table.tableName === TABLE_NAME);
|
|
/**
|
|
* @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 (!targetTableSchema) {
|
|
console.log(`Dropping Table ${TABLE_NAME} from ${dbFullName}`);
|
|
await varDatabaseDbHandler({
|
|
queryString: `DROP TABLE \`${dbFullName}\`.\`${TABLE_NAME}\``,
|
|
});
|
|
const deleteTableEntry = await dbHandler({
|
|
query: `DELETE FROM datasquirel.user_database_tables WHERE user_id = ? AND db_slug = ? AND table_slug = ?`,
|
|
values: [userId, dbSlug, TABLE_NAME],
|
|
});
|
|
// const oldTable = tables.find(
|
|
// (_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 (oldTable) {
|
|
// console.log("Renaming Table");
|
|
// await varDatabaseDbHandler({
|
|
// queryString: `RENAME TABLE \`${dbFullName}\`.\`${oldTable.tableNameOld}\` TO \`${oldTable.tableName}\``,
|
|
// });
|
|
// } else {
|
|
// console.log(
|
|
// `Dropping Table ${TABLE_NAME} from ${dbFullName}`
|
|
// );
|
|
// await varDatabaseDbHandler({
|
|
// queryString: `DROP TABLE \`${dbFullName}\`.\`${TABLE_NAME}\``,
|
|
// });
|
|
// const deleteTableEntry = await dbHandler({
|
|
// query: `DELETE FROM datasquirel.user_database_tables WHERE user_id = ? AND db_slug = ? AND table_slug = ?`,
|
|
// values: [userId, dbSlug, TABLE_NAME],
|
|
// });
|
|
// }
|
|
}
|
|
}
|
|
/**
|
|
* @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;
|
|
if (targetTable && tableName !== targetTable)
|
|
continue;
|
|
console.log(`Handling table => ${tableName}`);
|
|
/**
|
|
* @description Check if table exists
|
|
* @type {any}
|
|
*/
|
|
const tableCheck = await varDatabaseDbHandler({
|
|
queryString: `
|
|
SELECT EXISTS (
|
|
SELECT
|
|
TABLE_NAME
|
|
FROM
|
|
information_schema.TABLES
|
|
WHERE
|
|
TABLE_SCHEMA = ? AND
|
|
TABLE_NAME = ?
|
|
) AS tableExists`,
|
|
queryValuesArray: [dbFullName, table.tableName],
|
|
});
|
|
if (tableCheck && ((_b = tableCheck[0]) === null || _b === void 0 ? void 0 : _b.tableExists) > 0) {
|
|
/**
|
|
* @description Update table if table exists
|
|
*/
|
|
const updateExistingTable = await updateTable({
|
|
dbFullName: dbFullName,
|
|
tableName: tableName,
|
|
tableFields: fields,
|
|
userId,
|
|
dbSchema: database,
|
|
tableIndexes: indexes,
|
|
recordedDbEntry,
|
|
tableSchema: table,
|
|
isMain,
|
|
});
|
|
if (table.childrenTables && table.childrenTables[0]) {
|
|
for (let ch = 0; ch < table.childrenTables.length; ch++) {
|
|
const childTable = table.childrenTables[ch];
|
|
const childTableParentDbSchema = grabPrimaryRequiredDbSchema({
|
|
dbId: childTable.dbId,
|
|
userId,
|
|
});
|
|
if (!(childTableParentDbSchema === null || childTableParentDbSchema === void 0 ? void 0 : childTableParentDbSchema.dbFullName))
|
|
continue;
|
|
const childTableSchema = childTableParentDbSchema.tables.find((tbl) => tbl.id == childTable.tableId);
|
|
if (!childTableSchema)
|
|
continue;
|
|
const updateExistingChildTable = await updateTable({
|
|
dbFullName: childTableParentDbSchema.dbFullName,
|
|
tableName: childTableSchema.tableName,
|
|
tableFields: childTableSchema.fields,
|
|
userId,
|
|
dbSchema: childTableParentDbSchema,
|
|
tableIndexes: childTableSchema.indexes,
|
|
clone: true,
|
|
recordedDbEntry,
|
|
tableSchema: table,
|
|
isMain,
|
|
});
|
|
}
|
|
}
|
|
}
|
|
else {
|
|
/**
|
|
* @description Create new Table if table doesnt exist
|
|
*/
|
|
const createNewTable = await createTable({
|
|
tableName: tableName,
|
|
tableInfoArray: fields,
|
|
dbFullName: dbFullName,
|
|
tableSchema: table,
|
|
recordedDbEntry,
|
|
isMain,
|
|
});
|
|
/**
|
|
* Handle DATASQUIREL Table Indexes
|
|
* ===================================================
|
|
* @description Iterate through each datasquirel schema
|
|
* table index(if available), and perform operations
|
|
*/
|
|
if (indexes === null || indexes === void 0 ? void 0 : indexes[0]) {
|
|
handleIndexescreateDbFromSchema({
|
|
dbFullName,
|
|
indexes,
|
|
tableName,
|
|
});
|
|
}
|
|
}
|
|
}
|
|
/**
|
|
* @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 { dbId } = childDb;
|
|
const targetDatabase = dbSchema.find((dbSch) => dbSch.childDatabaseDbId == dbId);
|
|
if (targetDatabase === null || targetDatabase === void 0 ? void 0 : targetDatabase.id) {
|
|
await createDbFromSchema({
|
|
userId,
|
|
dbId: targetDatabase === null || targetDatabase === void 0 ? void 0 : targetDatabase.id,
|
|
});
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
catch (error) {
|
|
console.log(`createDbFromSchema ERROR => ${error.message}`);
|
|
return false;
|
|
}
|
|
}
|