Roll Back compile version
This commit is contained in:
+68
-51
@@ -1,62 +1,79 @@
|
||||
import varDatabaseDbHandler from "../utils/varDatabaseDbHandler";
|
||||
import numberfy from "../../utils/numberfy";
|
||||
import addDbEntry from "../../functions/backend/db/addDbEntry";
|
||||
import updateDbEntry from "../../functions/backend/db/updateDbEntry";
|
||||
"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 = checkDbRecordCreateDbSchema;
|
||||
const varDatabaseDbHandler_1 = __importDefault(require("../utils/varDatabaseDbHandler"));
|
||||
const numberfy_1 = __importDefault(require("../../utils/numberfy"));
|
||||
const addDbEntry_1 = __importDefault(require("../../functions/backend/db/addDbEntry"));
|
||||
const updateDbEntry_1 = __importDefault(require("../../functions/backend/db/updateDbEntry"));
|
||||
/**
|
||||
* # Create database from Schema Function
|
||||
* @requires DSQL_DB_CONN - Gobal Variable for Datasquirel Database
|
||||
*/
|
||||
export default async function checkDbRecordCreateDbSchema({ userId, dbSchema, isMain, }) {
|
||||
var _a, _b;
|
||||
if (isMain)
|
||||
return undefined;
|
||||
try {
|
||||
const { dbFullName, dbName, dbSlug, dbDescription, dbImage, childDatabase, childDatabaseDbId, id, } = dbSchema;
|
||||
let recordedDbEntryArray = userId
|
||||
? await varDatabaseDbHandler({
|
||||
queryString: `SELECT * FROM datasquirel.user_databases WHERE db_full_name = ?`,
|
||||
queryValuesArray: [dbFullName || "NULL"],
|
||||
})
|
||||
: undefined;
|
||||
let recordedDbEntry = recordedDbEntryArray === null || recordedDbEntryArray === void 0 ? void 0 : recordedDbEntryArray[0];
|
||||
const newDbEntryObj = {
|
||||
user_id: numberfy(userId),
|
||||
db_name: dbName,
|
||||
db_slug: dbSlug,
|
||||
db_full_name: dbFullName,
|
||||
db_description: dbDescription,
|
||||
db_image: dbImage,
|
||||
active_clone: childDatabase ? 1 : undefined,
|
||||
db_schema_id: numberfy(id),
|
||||
active_clone_parent_db_id: numberfy(childDatabaseDbId),
|
||||
};
|
||||
if (!(recordedDbEntry === null || recordedDbEntry === void 0 ? void 0 : recordedDbEntry.id) && userId) {
|
||||
const newDbEntry = await addDbEntry({
|
||||
data: newDbEntryObj,
|
||||
tableName: "user_databases",
|
||||
forceLocal: true,
|
||||
});
|
||||
if ((_a = newDbEntry.payload) === null || _a === void 0 ? void 0 : _a.insertId) {
|
||||
recordedDbEntryArray = await varDatabaseDbHandler({
|
||||
function checkDbRecordCreateDbSchema(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ userId, dbSchema, isMain, }) {
|
||||
var _b, _c;
|
||||
if (isMain)
|
||||
return undefined;
|
||||
try {
|
||||
const { dbFullName, dbName, dbSlug, dbDescription, dbImage, childDatabase, childDatabaseDbId, id, } = dbSchema;
|
||||
let recordedDbEntryArray = userId
|
||||
? yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: `SELECT * FROM datasquirel.user_databases WHERE db_full_name = ?`,
|
||||
queryValuesArray: [dbFullName || "NULL"],
|
||||
})
|
||||
: undefined;
|
||||
let recordedDbEntry = recordedDbEntryArray === null || recordedDbEntryArray === void 0 ? void 0 : recordedDbEntryArray[0];
|
||||
const newDbEntryObj = {
|
||||
user_id: (0, numberfy_1.default)(userId),
|
||||
db_name: dbName,
|
||||
db_slug: dbSlug,
|
||||
db_full_name: dbFullName,
|
||||
db_description: dbDescription,
|
||||
db_image: dbImage,
|
||||
active_clone: childDatabase ? 1 : undefined,
|
||||
db_schema_id: (0, numberfy_1.default)(id),
|
||||
active_clone_parent_db_id: (0, numberfy_1.default)(childDatabaseDbId),
|
||||
};
|
||||
if (!(recordedDbEntry === null || recordedDbEntry === void 0 ? void 0 : recordedDbEntry.id) && userId) {
|
||||
const newDbEntry = yield (0, addDbEntry_1.default)({
|
||||
data: newDbEntryObj,
|
||||
tableName: "user_databases",
|
||||
forceLocal: true,
|
||||
});
|
||||
recordedDbEntry = recordedDbEntryArray === null || recordedDbEntryArray === void 0 ? void 0 : recordedDbEntryArray[0];
|
||||
if ((_b = newDbEntry.payload) === null || _b === void 0 ? void 0 : _b.insertId) {
|
||||
recordedDbEntryArray = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: `SELECT * FROM datasquirel.user_databases WHERE db_full_name = ?`,
|
||||
queryValuesArray: [dbFullName || "NULL"],
|
||||
});
|
||||
recordedDbEntry = recordedDbEntryArray === null || recordedDbEntryArray === void 0 ? void 0 : recordedDbEntryArray[0];
|
||||
}
|
||||
}
|
||||
else if (recordedDbEntry === null || recordedDbEntry === void 0 ? void 0 : recordedDbEntry.id) {
|
||||
yield (0, updateDbEntry_1.default)({
|
||||
data: newDbEntryObj,
|
||||
tableName: "user_databases",
|
||||
forceLocal: true,
|
||||
identifierColumnName: "id",
|
||||
identifierValue: String(recordedDbEntry.id),
|
||||
});
|
||||
}
|
||||
return recordedDbEntry;
|
||||
}
|
||||
else if (recordedDbEntry === null || recordedDbEntry === void 0 ? void 0 : recordedDbEntry.id) {
|
||||
await updateDbEntry({
|
||||
data: newDbEntryObj,
|
||||
tableName: "user_databases",
|
||||
forceLocal: true,
|
||||
identifierColumnName: "id",
|
||||
identifierValue: String(recordedDbEntry.id),
|
||||
});
|
||||
catch (error) {
|
||||
(_c = global.ERROR_CALLBACK) === null || _c === void 0 ? void 0 : _c.call(global, `Error Checking DB Record on Creating Schema`, error);
|
||||
return undefined;
|
||||
}
|
||||
return recordedDbEntry;
|
||||
}
|
||||
catch (error) {
|
||||
(_b = global.ERROR_CALLBACK) === null || _b === void 0 ? void 0 : _b.call(global, `Error Checking DB Record on Creating Schema`, error);
|
||||
return undefined;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,75 +1,92 @@
|
||||
import varDatabaseDbHandler from "../utils/varDatabaseDbHandler";
|
||||
import sqlGenerator from "../../functions/dsql/sql/sql-generator";
|
||||
import numberfy from "../../utils/numberfy";
|
||||
import addDbEntry from "../../functions/backend/db/addDbEntry";
|
||||
"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 = checkTableRecordCreateDbSchema;
|
||||
const varDatabaseDbHandler_1 = __importDefault(require("../utils/varDatabaseDbHandler"));
|
||||
const sql_generator_1 = __importDefault(require("../../functions/dsql/sql/sql-generator"));
|
||||
const numberfy_1 = __importDefault(require("../../utils/numberfy"));
|
||||
const addDbEntry_1 = __importDefault(require("../../functions/backend/db/addDbEntry"));
|
||||
/**
|
||||
* # Create database from Schema Function
|
||||
* @requires DSQL_DB_CONN - Gobal Variable for Datasquirel Database
|
||||
*/
|
||||
export default async function checkTableRecordCreateDbSchema({ userId, tableSchema, dbSchema, dbRecord, dbFullName, }) {
|
||||
var _a, _b;
|
||||
if (!tableSchema)
|
||||
return undefined;
|
||||
try {
|
||||
const queryObj = sqlGenerator({
|
||||
tableName: "user_database_tables",
|
||||
genObject: {
|
||||
query: {
|
||||
db_id: {
|
||||
value: String(dbRecord === null || dbRecord === void 0 ? void 0 : dbRecord.id),
|
||||
},
|
||||
table_slug: {
|
||||
value: tableSchema.tableName,
|
||||
},
|
||||
user_id: {
|
||||
value: String(userId),
|
||||
function checkTableRecordCreateDbSchema(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ userId, tableSchema, dbSchema, dbRecord, dbFullName, }) {
|
||||
var _b, _c;
|
||||
if (!tableSchema)
|
||||
return undefined;
|
||||
try {
|
||||
const queryObj = (0, sql_generator_1.default)({
|
||||
tableName: "user_database_tables",
|
||||
genObject: {
|
||||
query: {
|
||||
db_id: {
|
||||
value: String(dbRecord === null || dbRecord === void 0 ? void 0 : dbRecord.id),
|
||||
},
|
||||
table_slug: {
|
||||
value: tableSchema.tableName,
|
||||
},
|
||||
user_id: {
|
||||
value: String(userId),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
dbFullName: "datasquirel",
|
||||
});
|
||||
let recordedTableEntryArray = userId
|
||||
? await varDatabaseDbHandler({
|
||||
queryString: (queryObj === null || queryObj === void 0 ? void 0 : queryObj.string) || "",
|
||||
queryValuesArray: queryObj === null || queryObj === void 0 ? void 0 : queryObj.values,
|
||||
})
|
||||
: undefined;
|
||||
let recordedTableEntry = recordedTableEntryArray === null || recordedTableEntryArray === void 0 ? void 0 : recordedTableEntryArray[0];
|
||||
if (!(recordedTableEntry === null || recordedTableEntry === void 0 ? void 0 : recordedTableEntry.id) && userId) {
|
||||
const newTableInsertObject = {
|
||||
user_id: numberfy(userId),
|
||||
db_id: dbRecord === null || dbRecord === void 0 ? void 0 : dbRecord.id,
|
||||
db_slug: dbRecord === null || dbRecord === void 0 ? void 0 : dbRecord.db_slug,
|
||||
table_slug: tableSchema.tableName,
|
||||
};
|
||||
if ((tableSchema === null || tableSchema === void 0 ? void 0 : tableSchema.childTable) && tableSchema.childTableId) {
|
||||
const parentDb = dbSchema.find((db) => db.id == tableSchema.childTableDbId);
|
||||
const parentDbTable = parentDb === null || parentDb === void 0 ? void 0 : parentDb.tables.find((tbl) => tbl.id == tableSchema.childTableId);
|
||||
if (parentDb && parentDbTable) {
|
||||
newTableInsertObject["child_table"] = 1;
|
||||
newTableInsertObject["child_table_parent_database_schema_id"] = numberfy(parentDb.id);
|
||||
newTableInsertObject["child_table_parent_table_schema_id"] =
|
||||
numberfy(parentDbTable.id);
|
||||
}
|
||||
}
|
||||
const newTableRecordEntry = await addDbEntry({
|
||||
data: newTableInsertObject,
|
||||
tableName: "user_database_tables",
|
||||
dbContext: "Master",
|
||||
forceLocal: true,
|
||||
dbFullName: "datasquirel",
|
||||
});
|
||||
if ((_a = newTableRecordEntry.payload) === null || _a === void 0 ? void 0 : _a.insertId) {
|
||||
recordedTableEntryArray = await varDatabaseDbHandler({
|
||||
let recordedTableEntryArray = userId
|
||||
? yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: (queryObj === null || queryObj === void 0 ? void 0 : queryObj.string) || "",
|
||||
queryValuesArray: queryObj === null || queryObj === void 0 ? void 0 : queryObj.values,
|
||||
})
|
||||
: undefined;
|
||||
let recordedTableEntry = recordedTableEntryArray === null || recordedTableEntryArray === void 0 ? void 0 : recordedTableEntryArray[0];
|
||||
if (!(recordedTableEntry === null || recordedTableEntry === void 0 ? void 0 : recordedTableEntry.id) && userId) {
|
||||
const newTableInsertObject = {
|
||||
user_id: (0, numberfy_1.default)(userId),
|
||||
db_id: dbRecord === null || dbRecord === void 0 ? void 0 : dbRecord.id,
|
||||
db_slug: dbRecord === null || dbRecord === void 0 ? void 0 : dbRecord.db_slug,
|
||||
table_slug: tableSchema.tableName,
|
||||
};
|
||||
if ((tableSchema === null || tableSchema === void 0 ? void 0 : tableSchema.childTable) && tableSchema.childTableId) {
|
||||
const parentDb = dbSchema.find((db) => db.id == tableSchema.childTableDbId);
|
||||
const parentDbTable = parentDb === null || parentDb === void 0 ? void 0 : parentDb.tables.find((tbl) => tbl.id == tableSchema.childTableId);
|
||||
if (parentDb && parentDbTable) {
|
||||
newTableInsertObject["child_table"] = 1;
|
||||
newTableInsertObject["child_table_parent_database_schema_id"] = (0, numberfy_1.default)(parentDb.id);
|
||||
newTableInsertObject["child_table_parent_table_schema_id"] =
|
||||
(0, numberfy_1.default)(parentDbTable.id);
|
||||
}
|
||||
}
|
||||
const newTableRecordEntry = yield (0, addDbEntry_1.default)({
|
||||
data: newTableInsertObject,
|
||||
tableName: "user_database_tables",
|
||||
dbContext: "Master",
|
||||
forceLocal: true,
|
||||
});
|
||||
recordedTableEntry = recordedTableEntryArray === null || recordedTableEntryArray === void 0 ? void 0 : recordedTableEntryArray[0];
|
||||
if ((_b = newTableRecordEntry.payload) === null || _b === void 0 ? void 0 : _b.insertId) {
|
||||
recordedTableEntryArray = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: (queryObj === null || queryObj === void 0 ? void 0 : queryObj.string) || "",
|
||||
queryValuesArray: queryObj === null || queryObj === void 0 ? void 0 : queryObj.values,
|
||||
});
|
||||
recordedTableEntry = recordedTableEntryArray === null || recordedTableEntryArray === void 0 ? void 0 : recordedTableEntryArray[0];
|
||||
}
|
||||
}
|
||||
return recordedTableEntry;
|
||||
}
|
||||
return recordedTableEntry;
|
||||
}
|
||||
catch (error) {
|
||||
(_b = global.ERROR_CALLBACK) === null || _b === void 0 ? void 0 : _b.call(global, `Error Checking Table Record on Creating Schema`, error);
|
||||
return undefined;
|
||||
}
|
||||
catch (error) {
|
||||
(_c = global.ERROR_CALLBACK) === null || _c === void 0 ? void 0 : _c.call(global, `Error Checking Table Record on Creating Schema`, error);
|
||||
return undefined;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
+49
-37
@@ -1,10 +1,22 @@
|
||||
import fs from "fs";
|
||||
import path from "path";
|
||||
import grabDirNames from "../../utils/backend/names/grab-dir-names";
|
||||
import EJSON from "../../utils/ejson";
|
||||
import numberfy from "../../utils/numberfy";
|
||||
import uniqueByKey from "../../utils/unique-by-key";
|
||||
export default function grabRequiredDatabaseSchemas(params) {
|
||||
"use strict";
|
||||
var __importDefault = (this && this.__importDefault) || function (mod) {
|
||||
return (mod && mod.__esModule) ? mod : { "default": mod };
|
||||
};
|
||||
Object.defineProperty(exports, "__esModule", { value: true });
|
||||
exports.default = grabRequiredDatabaseSchemas;
|
||||
exports.grabPrimaryRequiredDbSchema = grabPrimaryRequiredDbSchema;
|
||||
exports.findDbNameInSchemaDir = findDbNameInSchemaDir;
|
||||
exports.writeUpdatedDbSchema = writeUpdatedDbSchema;
|
||||
exports.deleteDbSchema = deleteDbSchema;
|
||||
exports.findTargetDbSchemaFromMainSchema = findTargetDbSchemaFromMainSchema;
|
||||
exports.grabLatestDbSchemaID = grabLatestDbSchemaID;
|
||||
const fs_1 = __importDefault(require("fs"));
|
||||
const path_1 = __importDefault(require("path"));
|
||||
const grab_dir_names_1 = __importDefault(require("../../utils/backend/names/grab-dir-names"));
|
||||
const ejson_1 = __importDefault(require("../../utils/ejson"));
|
||||
const numberfy_1 = __importDefault(require("../../utils/numberfy"));
|
||||
const unique_by_key_1 = __importDefault(require("../../utils/unique-by-key"));
|
||||
function grabRequiredDatabaseSchemas(params) {
|
||||
const primaryDbSchema = grabPrimaryRequiredDbSchema(params);
|
||||
if (!primaryDbSchema)
|
||||
return undefined;
|
||||
@@ -35,9 +47,9 @@ export default function grabRequiredDatabaseSchemas(params) {
|
||||
continue;
|
||||
relatedDatabases.push(childTableDbSchema);
|
||||
}
|
||||
return uniqueByKey([primaryDbSchema, ...relatedDatabases], "dbFullName");
|
||||
return (0, unique_by_key_1.default)([primaryDbSchema, ...relatedDatabases], "dbFullName");
|
||||
}
|
||||
export function grabPrimaryRequiredDbSchema({ userId, dbId, dbSlug }) {
|
||||
function grabPrimaryRequiredDbSchema({ userId, dbId, dbSlug }) {
|
||||
let finalDbId = dbId;
|
||||
if (!finalDbId && userId && dbSlug) {
|
||||
const searchedDb = findDbNameInSchemaDir({ dbName: dbSlug, userId });
|
||||
@@ -48,7 +60,7 @@ export function grabPrimaryRequiredDbSchema({ userId, dbId, dbSlug }) {
|
||||
if (!finalDbId) {
|
||||
return undefined;
|
||||
}
|
||||
const { targetUserPrivateDir, oldSchemasDir } = grabDirNames({
|
||||
const { targetUserPrivateDir, oldSchemasDir } = (0, grab_dir_names_1.default)({
|
||||
userId,
|
||||
});
|
||||
const finalSchemaDir = targetUserPrivateDir || oldSchemasDir;
|
||||
@@ -57,13 +69,13 @@ export function grabPrimaryRequiredDbSchema({ userId, dbId, dbSlug }) {
|
||||
return undefined;
|
||||
}
|
||||
if (finalDbId) {
|
||||
const dbIdSchema = path.resolve(finalSchemaDir, `${finalDbId}.json`);
|
||||
if (fs.existsSync(dbIdSchema)) {
|
||||
const dbIdSchemaObject = EJSON.parse(fs.readFileSync(dbIdSchema, "utf-8"));
|
||||
const dbIdSchema = path_1.default.resolve(finalSchemaDir, `${finalDbId}.json`);
|
||||
if (fs_1.default.existsSync(dbIdSchema)) {
|
||||
const dbIdSchemaObject = ejson_1.default.parse(fs_1.default.readFileSync(dbIdSchema, "utf-8"));
|
||||
return dbIdSchemaObject;
|
||||
}
|
||||
}
|
||||
const dbSchemasFiles = fs.readdirSync(finalSchemaDir);
|
||||
const dbSchemasFiles = fs_1.default.readdirSync(finalSchemaDir);
|
||||
let targetDbSchema;
|
||||
try {
|
||||
for (let i = 0; i < dbSchemasFiles.length; i++) {
|
||||
@@ -72,8 +84,8 @@ export function grabPrimaryRequiredDbSchema({ userId, dbId, dbSlug }) {
|
||||
continue;
|
||||
if (!fileOrPath.match(/^\d+.json/))
|
||||
continue;
|
||||
const targetFileJSONPath = path.join(finalSchemaDir, fileOrPath);
|
||||
const targetSchema = EJSON.parse(fs.readFileSync(targetFileJSONPath, "utf-8"));
|
||||
const targetFileJSONPath = path_1.default.join(finalSchemaDir, fileOrPath);
|
||||
const targetSchema = ejson_1.default.parse(fs_1.default.readFileSync(targetFileJSONPath, "utf-8"));
|
||||
if (targetSchema && finalDbId && (targetSchema === null || targetSchema === void 0 ? void 0 : targetSchema.id) == finalDbId) {
|
||||
targetDbSchema = targetSchema;
|
||||
}
|
||||
@@ -101,7 +113,7 @@ export function grabPrimaryRequiredDbSchema({ userId, dbId, dbSlug }) {
|
||||
console.log(`userId`, userId);
|
||||
return undefined;
|
||||
}
|
||||
export function findDbNameInSchemaDir({ userId, dbName, }) {
|
||||
function findDbNameInSchemaDir({ userId, dbName, }) {
|
||||
if (!userId) {
|
||||
console.log(`userId not provided!`);
|
||||
return undefined;
|
||||
@@ -110,14 +122,14 @@ export function findDbNameInSchemaDir({ userId, dbName, }) {
|
||||
console.log(`dbName not provided!`);
|
||||
return undefined;
|
||||
}
|
||||
const { targetUserPrivateDir } = grabDirNames({
|
||||
const { targetUserPrivateDir } = (0, grab_dir_names_1.default)({
|
||||
userId,
|
||||
});
|
||||
if (!targetUserPrivateDir) {
|
||||
console.log(`targetUserPrivateDir not found!`);
|
||||
return undefined;
|
||||
}
|
||||
const dbSchemasFiles = fs.readdirSync(targetUserPrivateDir);
|
||||
const dbSchemasFiles = fs_1.default.readdirSync(targetUserPrivateDir);
|
||||
let targetDbSchema;
|
||||
try {
|
||||
for (let i = 0; i < dbSchemasFiles.length; i++) {
|
||||
@@ -126,8 +138,8 @@ export function findDbNameInSchemaDir({ userId, dbName, }) {
|
||||
continue;
|
||||
if (!fileOrPath.match(/^\d+.json/))
|
||||
continue;
|
||||
const targetFileJSONPath = path.join(targetUserPrivateDir, fileOrPath);
|
||||
const targetSchema = EJSON.parse(fs.readFileSync(targetFileJSONPath, "utf-8"));
|
||||
const targetFileJSONPath = path_1.default.join(targetUserPrivateDir, fileOrPath);
|
||||
const targetSchema = ejson_1.default.parse(fs_1.default.readFileSync(targetFileJSONPath, "utf-8"));
|
||||
if (!targetSchema)
|
||||
continue;
|
||||
if (targetSchema.dbFullName == dbName ||
|
||||
@@ -140,8 +152,8 @@ export function findDbNameInSchemaDir({ userId, dbName, }) {
|
||||
catch (error) { }
|
||||
return targetDbSchema;
|
||||
}
|
||||
export function writeUpdatedDbSchema({ dbSchema, userId, }) {
|
||||
const { targetUserPrivateDir } = grabDirNames({
|
||||
function writeUpdatedDbSchema({ dbSchema, userId, }) {
|
||||
const { targetUserPrivateDir } = (0, grab_dir_names_1.default)({
|
||||
userId,
|
||||
});
|
||||
if (!targetUserPrivateDir) {
|
||||
@@ -149,19 +161,19 @@ export function writeUpdatedDbSchema({ dbSchema, userId, }) {
|
||||
return {};
|
||||
}
|
||||
if (dbSchema.id) {
|
||||
const dbIdSchemaPath = path.join(targetUserPrivateDir, `${dbSchema.id}.json`);
|
||||
fs.writeFileSync(dbIdSchemaPath, EJSON.stringify(dbSchema) || "[]");
|
||||
const dbIdSchemaPath = path_1.default.join(targetUserPrivateDir, `${dbSchema.id}.json`);
|
||||
fs_1.default.writeFileSync(dbIdSchemaPath, ejson_1.default.stringify(dbSchema) || "[]");
|
||||
return { success: true };
|
||||
}
|
||||
else {
|
||||
const nextID = grabLatestDbSchemaID(targetUserPrivateDir);
|
||||
dbSchema.id = nextID;
|
||||
fs.writeFileSync(path.join(targetUserPrivateDir, `${nextID}.json`), EJSON.stringify(dbSchema) || "[]");
|
||||
fs_1.default.writeFileSync(path_1.default.join(targetUserPrivateDir, `${nextID}.json`), ejson_1.default.stringify(dbSchema) || "[]");
|
||||
return { success: true, dbSchemaId: nextID };
|
||||
}
|
||||
}
|
||||
export function deleteDbSchema({ dbSchema, userId }) {
|
||||
const { targetUserPrivateDir, userSchemaMainJSONFilePath } = grabDirNames({
|
||||
function deleteDbSchema({ dbSchema, userId }) {
|
||||
const { targetUserPrivateDir, userSchemaMainJSONFilePath } = (0, grab_dir_names_1.default)({
|
||||
userId,
|
||||
});
|
||||
if (!targetUserPrivateDir)
|
||||
@@ -170,15 +182,15 @@ export function deleteDbSchema({ dbSchema, userId }) {
|
||||
dbId: dbSchema.id,
|
||||
userId,
|
||||
});
|
||||
const schemaFile = path.join(targetUserPrivateDir, `${targetDbSchema === null || targetDbSchema === void 0 ? void 0 : targetDbSchema.id}.json`);
|
||||
const schemaFile = path_1.default.join(targetUserPrivateDir, `${targetDbSchema === null || targetDbSchema === void 0 ? void 0 : targetDbSchema.id}.json`);
|
||||
try {
|
||||
fs.unlinkSync(schemaFile);
|
||||
fs_1.default.unlinkSync(schemaFile);
|
||||
}
|
||||
catch (error) { }
|
||||
if (userSchemaMainJSONFilePath &&
|
||||
fs.existsSync(userSchemaMainJSONFilePath)) {
|
||||
fs_1.default.existsSync(userSchemaMainJSONFilePath)) {
|
||||
try {
|
||||
let allDbSchemas = EJSON.parse(fs.readFileSync(userSchemaMainJSONFilePath, "utf-8"));
|
||||
let allDbSchemas = ejson_1.default.parse(fs_1.default.readFileSync(userSchemaMainJSONFilePath, "utf-8"));
|
||||
if (allDbSchemas === null || allDbSchemas === void 0 ? void 0 : allDbSchemas[0]) {
|
||||
for (let i = 0; i < allDbSchemas.length; i++) {
|
||||
const dbSch = allDbSchemas[i];
|
||||
@@ -187,18 +199,18 @@ export function deleteDbSchema({ dbSchema, userId }) {
|
||||
allDbSchemas.splice(i, 1);
|
||||
}
|
||||
}
|
||||
fs.writeFileSync(userSchemaMainJSONFilePath, EJSON.stringify(allDbSchemas) || "[]");
|
||||
fs_1.default.writeFileSync(userSchemaMainJSONFilePath, ejson_1.default.stringify(allDbSchemas) || "[]");
|
||||
}
|
||||
}
|
||||
catch (error) { }
|
||||
}
|
||||
}
|
||||
export function findTargetDbSchemaFromMainSchema(schemas, dbFullName, dbId) {
|
||||
function findTargetDbSchemaFromMainSchema(schemas, dbFullName, dbId) {
|
||||
const targetDbSchema = schemas.find((sch) => sch.dbFullName == dbFullName || (dbId && sch.id == dbId));
|
||||
return targetDbSchema;
|
||||
}
|
||||
export function grabLatestDbSchemaID(userSchemaDir) {
|
||||
const dbSchemasFiles = fs.readdirSync(userSchemaDir);
|
||||
function grabLatestDbSchemaID(userSchemaDir) {
|
||||
const dbSchemasFiles = fs_1.default.readdirSync(userSchemaDir);
|
||||
const dbNumbers = dbSchemasFiles
|
||||
.filter((dbSch) => {
|
||||
if (!dbSch.endsWith(`.json`))
|
||||
@@ -207,7 +219,7 @@ export function grabLatestDbSchemaID(userSchemaDir) {
|
||||
return true;
|
||||
return false;
|
||||
})
|
||||
.map((dbSch) => numberfy(dbSch.replace(/[^0-9]/g, "")));
|
||||
.map((dbSch) => (0, numberfy_1.default)(dbSch.replace(/[^0-9]/g, "")));
|
||||
if (dbNumbers[0])
|
||||
return ((dbNumbers
|
||||
.sort((a, b) => {
|
||||
|
||||
+43
-26
@@ -1,37 +1,54 @@
|
||||
import varDatabaseDbHandler from "../utils/varDatabaseDbHandler";
|
||||
import grabDSQLSchemaIndexComment from "../utils/grab-dsql-schema-index-comment";
|
||||
"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 = handleIndexescreateDbFromSchema;
|
||||
const varDatabaseDbHandler_1 = __importDefault(require("../utils/varDatabaseDbHandler"));
|
||||
const grab_dsql_schema_index_comment_1 = __importDefault(require("../utils/grab-dsql-schema-index-comment"));
|
||||
/**
|
||||
* Handle DATASQUIREL Table Indexes
|
||||
* ===================================================
|
||||
* @description Iterate through each datasquirel schema
|
||||
* table index(if available), and perform operations
|
||||
*/
|
||||
export default async function handleIndexescreateDbFromSchema({ dbFullName, tableName, indexes, }) {
|
||||
const allExistingIndexes = await varDatabaseDbHandler({
|
||||
queryString: `SHOW INDEXES FROM \`${dbFullName}\`.\`${tableName}\``,
|
||||
});
|
||||
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 {
|
||||
const existingKeyInDb = allExistingIndexes.filter((indexObject) => indexObject.Key_name === alias);
|
||||
if (!existingKeyInDb[0])
|
||||
throw new Error("This Index Does not Exist");
|
||||
}
|
||||
catch (error) {
|
||||
function handleIndexescreateDbFromSchema(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ dbFullName, tableName, indexes, }) {
|
||||
const allExistingIndexes = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: `SHOW INDEXES FROM \`${dbFullName}\`.\`${tableName}\``,
|
||||
});
|
||||
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 Create new index if determined that it
|
||||
* doesn't exist in MYSQL db
|
||||
* @description Check for existing Index in MYSQL db
|
||||
*/
|
||||
const queryString = `CREATE${indexType == "full_text" ? " FULLTEXT" : ""} INDEX \`${alias}\` ON \`${dbFullName}\`.\`${tableName}\`(${indexTableFields === null || indexTableFields === void 0 ? void 0 : indexTableFields.map((nm) => nm.value).map((nm) => `\`${nm}\``).join(",")}) COMMENT '${grabDSQLSchemaIndexComment()} ${indexName}'`;
|
||||
const addIndex = await varDatabaseDbHandler({ queryString });
|
||||
try {
|
||||
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
|
||||
*/
|
||||
const queryString = `CREATE${indexType == "full_text" ? " FULLTEXT" : ""} INDEX \`${alias}\` ON \`${dbFullName}\`.\`${tableName}\`(${indexTableFields === null || indexTableFields === void 0 ? void 0 : indexTableFields.map((nm) => nm.value).map((nm) => `\`${nm}\``).join(",")}) COMMENT '${(0, grab_dsql_schema_index_comment_1.default)()} ${indexName}'`;
|
||||
const addIndex = yield (0, varDatabaseDbHandler_1.default)({ queryString });
|
||||
}
|
||||
}
|
||||
}
|
||||
const allExistingIndexesAfterUpdate = await varDatabaseDbHandler({
|
||||
queryString: `SHOW INDEXES FROM \`${dbFullName}\`.\`${tableName}\``,
|
||||
const allExistingIndexesAfterUpdate = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: `SHOW INDEXES FROM \`${dbFullName}\`.\`${tableName}\``,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
+236
-186
@@ -1,114 +1,163 @@
|
||||
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";
|
||||
"use strict";
|
||||
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
var desc = Object.getOwnPropertyDescriptor(m, k);
|
||||
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
||||
desc = { enumerable: true, get: function() { return m[k]; } };
|
||||
}
|
||||
Object.defineProperty(o, k2, desc);
|
||||
}) : (function(o, m, k, k2) {
|
||||
if (k2 === undefined) k2 = k;
|
||||
o[k2] = m[k];
|
||||
}));
|
||||
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
||||
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
||||
}) : function(o, v) {
|
||||
o["default"] = v;
|
||||
});
|
||||
var __importStar = (this && this.__importStar) || (function () {
|
||||
var ownKeys = function(o) {
|
||||
ownKeys = Object.getOwnPropertyNames || function (o) {
|
||||
var ar = [];
|
||||
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
||||
return ar;
|
||||
};
|
||||
return ownKeys(o);
|
||||
};
|
||||
return function (mod) {
|
||||
if (mod && mod.__esModule) return mod;
|
||||
var result = {};
|
||||
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
||||
__setModuleDefault(result, mod);
|
||||
return result;
|
||||
};
|
||||
})();
|
||||
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 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 grab_dir_names_1 = __importDefault(require("../../utils/backend/names/grab-dir-names"));
|
||||
const check_db_record_1 = __importDefault(require("./check-db-record"));
|
||||
const handle_indexes_1 = __importDefault(require("./handle-indexes"));
|
||||
const grab_required_database_schemas_1 = __importStar(require("./grab-required-database-schemas"));
|
||||
const dbHandler_1 = __importDefault(require("../../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,
|
||||
function createDbFromSchema(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ userId, targetDatabase, dbSchemaData, targetTable, dbId, }) {
|
||||
var _b, _c;
|
||||
try {
|
||||
const { userSchemaMainJSONFilePath } = (0, grab_dir_names_1.default)({
|
||||
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],
|
||||
// });
|
||||
// }
|
||||
}
|
||||
let dbSchema = dbSchemaData
|
||||
? dbSchemaData
|
||||
: dbId
|
||||
? (0, grab_required_database_schemas_1.default)({
|
||||
dbId,
|
||||
userId,
|
||||
})
|
||||
: undefined;
|
||||
if (!dbSchema) {
|
||||
console.log("Schema Not Found!");
|
||||
return false;
|
||||
}
|
||||
/**
|
||||
* @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)
|
||||
const isMain = !userSchemaMainJSONFilePath;
|
||||
for (let i = 0; i < dbSchema.length; i++) {
|
||||
const database = dbSchema[i];
|
||||
const { dbFullName, tables, dbSlug, childrenDatabases } = database;
|
||||
if (!dbFullName)
|
||||
continue;
|
||||
console.log(`Handling table => ${tableName}`);
|
||||
if (targetDatabase && dbFullName != targetDatabase) {
|
||||
continue;
|
||||
}
|
||||
console.log(`Handling database => ${dbFullName}`);
|
||||
const dbCheck = yield (0, noDatabaseDbHandler_1.default)(`SELECT SCHEMA_NAME AS dbFullName FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '${dbFullName}'`);
|
||||
if (!((_b = dbCheck === null || dbCheck === void 0 ? void 0 : dbCheck[0]) === null || _b === void 0 ? void 0 : _b.dbFullName)) {
|
||||
const newDatabase = yield (0, noDatabaseDbHandler_1.default)(`CREATE DATABASE IF NOT EXISTS \`${dbFullName}\` CHARACTER SET utf8mb4 COLLATE utf8mb4_bin`);
|
||||
}
|
||||
const allTables = yield (0, noDatabaseDbHandler_1.default)(`SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA='${dbFullName}'`);
|
||||
let recordedDbEntry = yield (0, check_db_record_1.default)({
|
||||
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}`);
|
||||
yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: `DROP TABLE \`${dbFullName}\`.\`${TABLE_NAME}\``,
|
||||
});
|
||||
const deleteTableEntry = yield (0, dbHandler_1.default)({
|
||||
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 Check if table exists
|
||||
* @type {any}
|
||||
* @description Iterate through each table and perform table actions
|
||||
*/
|
||||
const tableCheck = await varDatabaseDbHandler({
|
||||
queryString: `
|
||||
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 = yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: `
|
||||
SELECT EXISTS (
|
||||
SELECT
|
||||
TABLE_NAME
|
||||
@@ -118,98 +167,99 @@ export default async function createDbFromSchema({ userId, targetDatabase, dbSch
|
||||
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,
|
||||
queryValuesArray: [dbFullName, table.tableName],
|
||||
});
|
||||
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,
|
||||
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,
|
||||
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 = (0, grab_required_database_schemas_1.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 = yield (0, updateTable_1.default)({
|
||||
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 = yield (0, createTable_1.default)({
|
||||
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]) {
|
||||
(0, handle_indexes_1.default)({
|
||||
dbFullName,
|
||||
indexes,
|
||||
tableName,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
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,
|
||||
});
|
||||
/**
|
||||
* @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) {
|
||||
yield createDbFromSchema({
|
||||
userId,
|
||||
dbId: targetDatabase === null || targetDatabase === void 0 ? void 0 : targetDatabase.id,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
catch (error) {
|
||||
console.log(`createDbFromSchema ERROR => ${error.message}`);
|
||||
return false;
|
||||
}
|
||||
catch (error) {
|
||||
console.log(`createDbFromSchema ERROR => ${error.message}`);
|
||||
return false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user