import noDatabaseDbHandler from "../utils/noDatabaseDbHandler"; import varDatabaseDbHandler from "../utils/varDatabaseDbHandler"; import createTable from "../utils/createTable"; import updateTable from "../utils/updateTable"; import { DSQL_DatabaseSchemaType } from "../../types"; 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"; type Param = { userId?: number | string | null; targetDatabase?: string; dbSchemaData?: DSQL_DatabaseSchemaType[]; targetTable?: string; dbId?: string | number; }; /** * # Create database from Schema Function * @requires DSQL_DB_CONN - Gobal Variable for Datasquirel Database */ export default async function createDbFromSchema({ userId, targetDatabase, dbSchemaData, targetTable, dbId, }: Param): Promise { 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: DSQL_DatabaseSchemaType = dbSchema[i]; const { dbFullName, tables, dbSlug, childrenDatabases } = database; if (!dbFullName) continue; if (targetDatabase && dbFullName != targetDatabase) { continue; } console.log(`Handling database => ${dbFullName}`); const dbCheck: any = await noDatabaseDbHandler( `SELECT SCHEMA_NAME AS dbFullName FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '${dbFullName}'` ); if (!dbCheck?.[0]?.dbFullName) { const newDatabase = await noDatabaseDbHandler( `CREATE DATABASE IF NOT EXISTS \`${dbFullName}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_bin` ); } const allTables: any = 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: any = 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 && tableCheck[0]?.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?.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?.[0]) { handleIndexescreateDbFromSchema({ dbFullName, indexes, tableName, }); } } } /** * @description Check all children databases */ if (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?.id) { await createDbFromSchema({ userId, dbId: targetDatabase?.id, }); } } } } return true; } catch (error: any) { console.log(`createDbFromSchema ERROR => ${error.message}`); return false; } }