Updates
This commit is contained in:
@@ -3,10 +3,11 @@ import { DSQL_DATASQUIREL_USER_DATABASES } from "../../types/dsql";
|
||||
type Param = {
|
||||
userId?: number | string | null;
|
||||
dbSchema: DSQL_DatabaseSchemaType;
|
||||
isMain?: boolean;
|
||||
};
|
||||
/**
|
||||
* # Create database from Schema Function
|
||||
* @requires DSQL_DB_CONN - Gobal Variable for Datasquirel Database
|
||||
*/
|
||||
export default function checkDbRecordCreateDbSchema({ userId, dbSchema, }: Param): Promise<DSQL_DATASQUIREL_USER_DATABASES | undefined>;
|
||||
export default function checkDbRecordCreateDbSchema({ userId, dbSchema, isMain, }: Param): Promise<DSQL_DATASQUIREL_USER_DATABASES | undefined>;
|
||||
export {};
|
||||
|
||||
+52
-56
@@ -1,66 +1,62 @@
|
||||
"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"));
|
||||
import varDatabaseDbHandler from "../utils/varDatabaseDbHandler";
|
||||
import numberfy from "../../utils/numberfy";
|
||||
import addDbEntry from "../../functions/backend/db/addDbEntry";
|
||||
import updateDbEntry from "../../functions/backend/db/updateDbEntry";
|
||||
/**
|
||||
* # Create database from Schema Function
|
||||
* @requires DSQL_DB_CONN - Gobal Variable for Datasquirel Database
|
||||
*/
|
||||
function checkDbRecordCreateDbSchema(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ userId, dbSchema, }) {
|
||||
var _b;
|
||||
try {
|
||||
const { dbFullName, dbName, dbSlug, dbDescription, dbImage, childDatabase, childDatabaseDbFullName, } = dbSchema;
|
||||
let recordedDbEntryArray = userId
|
||||
? yield (0, varDatabaseDbHandler_1.default)({
|
||||
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({
|
||||
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];
|
||||
if (!(recordedDbEntry === null || recordedDbEntry === void 0 ? void 0 : recordedDbEntry.id) && userId) {
|
||||
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,
|
||||
active_clone_parent_db: childDatabaseDbFullName,
|
||||
};
|
||||
const newDbEntry = (yield (0, addDbEntry_1.default)({
|
||||
data: newDbEntryObj,
|
||||
tableName: "user_databases",
|
||||
forceLocal: true,
|
||||
}));
|
||||
if (newDbEntry.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];
|
||||
}
|
||||
});
|
||||
recordedDbEntry = recordedDbEntryArray === null || recordedDbEntryArray === void 0 ? void 0 : recordedDbEntryArray[0];
|
||||
}
|
||||
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;
|
||||
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),
|
||||
});
|
||||
}
|
||||
});
|
||||
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,94 +1,75 @@
|
||||
"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"));
|
||||
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";
|
||||
/**
|
||||
* # Create database from Schema Function
|
||||
* @requires DSQL_DB_CONN - Gobal Variable for Datasquirel Database
|
||||
*/
|
||||
function checkTableRecordCreateDbSchema(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ userId, tableSchema, dbSchema, dbRecord, dbFullName, }) {
|
||||
var _b;
|
||||
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),
|
||||
},
|
||||
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),
|
||||
},
|
||||
},
|
||||
dbFullName: "datasquirel",
|
||||
});
|
||||
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_name: tableSchema.tableFullName,
|
||||
table_slug: tableSchema.tableName,
|
||||
};
|
||||
if ((tableSchema === null || tableSchema === void 0 ? void 0 : tableSchema.childTable) && tableSchema.childTableName) {
|
||||
const parentDb = dbSchema.find((db) => db.dbFullName == tableSchema.childTableDbFullName);
|
||||
const parentDbTable = parentDb === null || parentDb === void 0 ? void 0 : parentDb.tables.find((tbl) => tbl.tableName == tableSchema.childTableName);
|
||||
if (parentDb && parentDbTable) {
|
||||
newTableInsertObject["child_table"] = 1;
|
||||
newTableInsertObject["child_table_parent_database"] =
|
||||
parentDb.dbFullName;
|
||||
newTableInsertObject["child_table_parent_table"] =
|
||||
parentDbTable.tableName;
|
||||
}
|
||||
}
|
||||
const newTableRecordEntry = (yield (0, addDbEntry_1.default)({
|
||||
data: newTableInsertObject,
|
||||
tableName: "user_database_tables",
|
||||
dbContext: "Master",
|
||||
forceLocal: true,
|
||||
}));
|
||||
if (newTableRecordEntry.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];
|
||||
},
|
||||
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);
|
||||
}
|
||||
}
|
||||
return recordedTableEntry;
|
||||
const newTableRecordEntry = await addDbEntry({
|
||||
data: newTableInsertObject,
|
||||
tableName: "user_database_tables",
|
||||
dbContext: "Master",
|
||||
forceLocal: true,
|
||||
});
|
||||
if ((_a = newTableRecordEntry.payload) === null || _a === void 0 ? void 0 : _a.insertId) {
|
||||
recordedTableEntryArray = await varDatabaseDbHandler({
|
||||
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];
|
||||
}
|
||||
}
|
||||
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;
|
||||
}
|
||||
});
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
import { DSQL_DatabaseSchemaType } from "../../types";
|
||||
type Params = {
|
||||
userId?: string | number | null;
|
||||
dbId?: string | number;
|
||||
dbSlug?: string;
|
||||
};
|
||||
export default function grabRequiredDatabaseSchemas(params: Params): DSQL_DatabaseSchemaType[] | undefined;
|
||||
export declare function grabPrimaryRequiredDbSchema({ userId, dbId, dbSlug }: Params): DSQL_DatabaseSchemaType | undefined;
|
||||
export declare function findDbNameInSchemaDir({ userId, dbName, }: {
|
||||
userId?: string | number;
|
||||
dbName?: string;
|
||||
}): DSQL_DatabaseSchemaType | undefined;
|
||||
type UpdateDbSchemaParam = {
|
||||
dbSchema: DSQL_DatabaseSchemaType;
|
||||
userId?: string | number | null;
|
||||
};
|
||||
export declare function writeUpdatedDbSchema({ dbSchema, userId, }: UpdateDbSchemaParam): {
|
||||
success?: boolean;
|
||||
dbSchemaId?: string | number;
|
||||
};
|
||||
export declare function deleteDbSchema({ dbSchema, userId }: UpdateDbSchemaParam): void;
|
||||
export declare function findTargetDbSchemaFromMainSchema(schemas: DSQL_DatabaseSchemaType[], dbFullName?: string, dbId?: string | number): DSQL_DatabaseSchemaType | undefined;
|
||||
export declare function grabLatestDbSchemaID(userSchemaDir: string): number;
|
||||
export {};
|
||||
+218
@@ -0,0 +1,218 @@
|
||||
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) {
|
||||
const primaryDbSchema = grabPrimaryRequiredDbSchema(params);
|
||||
if (!primaryDbSchema)
|
||||
return undefined;
|
||||
let relatedDatabases = [];
|
||||
const childrenDatabases = primaryDbSchema.childrenDatabases || [];
|
||||
const childrenTables = primaryDbSchema.tables
|
||||
.map((tbl) => {
|
||||
return tbl.childrenTables || [];
|
||||
})
|
||||
.flat() || [];
|
||||
for (let i = 0; i < childrenDatabases.length; i++) {
|
||||
const childDb = childrenDatabases[i];
|
||||
const childDbSchema = grabPrimaryRequiredDbSchema({
|
||||
userId: params.userId,
|
||||
dbId: childDb.dbId,
|
||||
});
|
||||
if (!(childDbSchema === null || childDbSchema === void 0 ? void 0 : childDbSchema.dbSlug))
|
||||
continue;
|
||||
relatedDatabases.push(childDbSchema);
|
||||
}
|
||||
for (let i = 0; i < childrenTables.length; i++) {
|
||||
const childTbl = childrenTables[i];
|
||||
const childTableDbSchema = grabPrimaryRequiredDbSchema({
|
||||
userId: params.userId,
|
||||
dbId: childTbl.dbId,
|
||||
});
|
||||
if (!(childTableDbSchema === null || childTableDbSchema === void 0 ? void 0 : childTableDbSchema.dbSlug))
|
||||
continue;
|
||||
relatedDatabases.push(childTableDbSchema);
|
||||
}
|
||||
return uniqueByKey([primaryDbSchema, ...relatedDatabases], "dbFullName");
|
||||
}
|
||||
export function grabPrimaryRequiredDbSchema({ userId, dbId, dbSlug }) {
|
||||
let finalDbId = dbId;
|
||||
if (!finalDbId && userId && dbSlug) {
|
||||
const searchedDb = findDbNameInSchemaDir({ dbName: dbSlug, userId });
|
||||
if (searchedDb === null || searchedDb === void 0 ? void 0 : searchedDb.id) {
|
||||
finalDbId = searchedDb.id;
|
||||
}
|
||||
}
|
||||
if (!finalDbId) {
|
||||
return undefined;
|
||||
}
|
||||
const { targetUserPrivateDir, oldSchemasDir } = grabDirNames({
|
||||
userId,
|
||||
});
|
||||
const finalSchemaDir = targetUserPrivateDir || oldSchemasDir;
|
||||
if (!finalSchemaDir) {
|
||||
console.log(`finalSchemaDir not found!`);
|
||||
return undefined;
|
||||
}
|
||||
if (finalDbId) {
|
||||
const dbIdSchema = path.resolve(finalSchemaDir, `${finalDbId}.json`);
|
||||
if (fs.existsSync(dbIdSchema)) {
|
||||
const dbIdSchemaObject = EJSON.parse(fs.readFileSync(dbIdSchema, "utf-8"));
|
||||
return dbIdSchemaObject;
|
||||
}
|
||||
}
|
||||
const dbSchemasFiles = fs.readdirSync(finalSchemaDir);
|
||||
let targetDbSchema;
|
||||
try {
|
||||
for (let i = 0; i < dbSchemasFiles.length; i++) {
|
||||
const fileOrPath = dbSchemasFiles[i];
|
||||
if (!fileOrPath.endsWith(`.json`))
|
||||
continue;
|
||||
if (!fileOrPath.match(/^\d+.json/))
|
||||
continue;
|
||||
const targetFileJSONPath = path.join(finalSchemaDir, fileOrPath);
|
||||
const targetSchema = EJSON.parse(fs.readFileSync(targetFileJSONPath, "utf-8"));
|
||||
if (targetSchema && finalDbId && (targetSchema === null || targetSchema === void 0 ? void 0 : targetSchema.id) == finalDbId) {
|
||||
targetDbSchema = targetSchema;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (error) { }
|
||||
if (targetDbSchema) {
|
||||
return targetDbSchema;
|
||||
}
|
||||
// else if ( dbFullName) {
|
||||
// let existingSchemaInMainJSON = findTargetDbSchemaFromMainSchema(
|
||||
// dbFullName
|
||||
// );
|
||||
// const nextID = grabLatestDbSchemaID(finalSchemaDir);
|
||||
// if (existingSchemaInMainJSON) {
|
||||
// existingSchemaInMainJSON.id = nextID;
|
||||
// fs.writeFileSync(
|
||||
// path.join(finalSchemaDir, `${nextID}.json`),
|
||||
// EJSON.stringify(existingSchemaInMainJSON) || "[]"
|
||||
// );
|
||||
// return existingSchemaInMainJSON;
|
||||
// }
|
||||
// }
|
||||
console.log(`userSchemaDir not found!`);
|
||||
console.log(`userId`, userId);
|
||||
return undefined;
|
||||
}
|
||||
export function findDbNameInSchemaDir({ userId, dbName, }) {
|
||||
if (!userId) {
|
||||
console.log(`userId not provided!`);
|
||||
return undefined;
|
||||
}
|
||||
if (!dbName) {
|
||||
console.log(`dbName not provided!`);
|
||||
return undefined;
|
||||
}
|
||||
const { targetUserPrivateDir } = grabDirNames({
|
||||
userId,
|
||||
});
|
||||
if (!targetUserPrivateDir) {
|
||||
console.log(`targetUserPrivateDir not found!`);
|
||||
return undefined;
|
||||
}
|
||||
const dbSchemasFiles = fs.readdirSync(targetUserPrivateDir);
|
||||
let targetDbSchema;
|
||||
try {
|
||||
for (let i = 0; i < dbSchemasFiles.length; i++) {
|
||||
const fileOrPath = dbSchemasFiles[i];
|
||||
if (!fileOrPath.endsWith(`.json`))
|
||||
continue;
|
||||
if (!fileOrPath.match(/^\d+.json/))
|
||||
continue;
|
||||
const targetFileJSONPath = path.join(targetUserPrivateDir, fileOrPath);
|
||||
const targetSchema = EJSON.parse(fs.readFileSync(targetFileJSONPath, "utf-8"));
|
||||
if (!targetSchema)
|
||||
continue;
|
||||
if (targetSchema.dbFullName == dbName ||
|
||||
targetSchema.dbSlug == dbName) {
|
||||
targetDbSchema = targetSchema;
|
||||
return targetSchema;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (error) { }
|
||||
return targetDbSchema;
|
||||
}
|
||||
export function writeUpdatedDbSchema({ dbSchema, userId, }) {
|
||||
const { targetUserPrivateDir } = grabDirNames({
|
||||
userId,
|
||||
});
|
||||
if (!targetUserPrivateDir) {
|
||||
console.log(`user ${userId} has no targetUserPrivateDir`);
|
||||
return {};
|
||||
}
|
||||
if (dbSchema.id) {
|
||||
const dbIdSchemaPath = path.join(targetUserPrivateDir, `${dbSchema.id}.json`);
|
||||
fs.writeFileSync(dbIdSchemaPath, EJSON.stringify(dbSchema) || "[]");
|
||||
return { success: true };
|
||||
}
|
||||
else {
|
||||
const nextID = grabLatestDbSchemaID(targetUserPrivateDir);
|
||||
dbSchema.id = nextID;
|
||||
fs.writeFileSync(path.join(targetUserPrivateDir, `${nextID}.json`), EJSON.stringify(dbSchema) || "[]");
|
||||
return { success: true, dbSchemaId: nextID };
|
||||
}
|
||||
}
|
||||
export function deleteDbSchema({ dbSchema, userId }) {
|
||||
const { targetUserPrivateDir, userSchemaMainJSONFilePath } = grabDirNames({
|
||||
userId,
|
||||
});
|
||||
if (!targetUserPrivateDir)
|
||||
return;
|
||||
const targetDbSchema = grabPrimaryRequiredDbSchema({
|
||||
dbId: dbSchema.id,
|
||||
userId,
|
||||
});
|
||||
const schemaFile = path.join(targetUserPrivateDir, `${targetDbSchema === null || targetDbSchema === void 0 ? void 0 : targetDbSchema.id}.json`);
|
||||
try {
|
||||
fs.unlinkSync(schemaFile);
|
||||
}
|
||||
catch (error) { }
|
||||
if (userSchemaMainJSONFilePath &&
|
||||
fs.existsSync(userSchemaMainJSONFilePath)) {
|
||||
try {
|
||||
let allDbSchemas = EJSON.parse(fs.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];
|
||||
if (dbSch.dbFullName == dbSchema.dbFullName ||
|
||||
dbSch.id == dbSchema.id) {
|
||||
allDbSchemas.splice(i, 1);
|
||||
}
|
||||
}
|
||||
fs.writeFileSync(userSchemaMainJSONFilePath, EJSON.stringify(allDbSchemas) || "[]");
|
||||
}
|
||||
}
|
||||
catch (error) { }
|
||||
}
|
||||
}
|
||||
export 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);
|
||||
const dbNumbers = dbSchemasFiles
|
||||
.filter((dbSch) => {
|
||||
if (!dbSch.endsWith(`.json`))
|
||||
return false;
|
||||
if (dbSch.match(/^\d+\.json/))
|
||||
return true;
|
||||
return false;
|
||||
})
|
||||
.map((dbSch) => numberfy(dbSch.replace(/[^0-9]/g, "")));
|
||||
if (dbNumbers[0])
|
||||
return ((dbNumbers
|
||||
.sort((a, b) => {
|
||||
return a - b;
|
||||
})
|
||||
.pop() || 0) + 1);
|
||||
return 1;
|
||||
}
|
||||
+28
-48
@@ -1,57 +1,37 @@
|
||||
"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"));
|
||||
import varDatabaseDbHandler from "../utils/varDatabaseDbHandler";
|
||||
import grabDSQLSchemaIndexComment from "../utils/grab-dsql-schema-index-comment";
|
||||
/**
|
||||
* Handle DATASQUIREL Table Indexes
|
||||
* ===================================================
|
||||
* @description Iterate through each datasquirel schema
|
||||
* table index(if available), and perform operations
|
||||
*/
|
||||
function handleIndexescreateDbFromSchema(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ dbFullName, tableName, indexes, }) {
|
||||
var _b;
|
||||
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 \`${dbFullName}\`.\`${tableName}\``,
|
||||
});
|
||||
const existingKeyInDb = allExistingIndexes.filter((indexObject) => indexObject.Key_name === alias);
|
||||
if (!existingKeyInDb[0])
|
||||
throw new Error("This Index Does not Exist");
|
||||
}
|
||||
catch (error) {
|
||||
(_b = global.ERROR_CALLBACK) === null || _b === void 0 ? void 0 : _b.call(global, `Error Handling Indexes on Creating Schema`, 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 \`${dbFullName}\`.\`${tableName}\`(${indexTableFields === null || indexTableFields === void 0 ? void 0 : indexTableFields.map((nm) => nm.value).map((nm) => `\`${nm}\``).join(",")}) COMMENT 'schema_index'`,
|
||||
});
|
||||
}
|
||||
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) {
|
||||
/**
|
||||
* @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 '${grabDSQLSchemaIndexComment()} ${indexName}'`;
|
||||
const addIndex = await varDatabaseDbHandler({ queryString });
|
||||
}
|
||||
}
|
||||
const allExistingIndexesAfterUpdate = await varDatabaseDbHandler({
|
||||
queryString: `SHOW INDEXES FROM \`${dbFullName}\`.\`${tableName}\``,
|
||||
});
|
||||
}
|
||||
|
||||
+5
-2
@@ -1,11 +1,14 @@
|
||||
import { DSQL_DatabaseSchemaType } from "../../types";
|
||||
type Param = {
|
||||
userId?: number | string | null;
|
||||
targetDatabase?: string;
|
||||
dbSchemaData?: import("../../types").DSQL_DatabaseSchemaType[];
|
||||
dbSchemaData?: DSQL_DatabaseSchemaType[];
|
||||
targetTable?: string;
|
||||
dbId?: string | number;
|
||||
};
|
||||
/**
|
||||
* # Create database from Schema Function
|
||||
* @requires DSQL_DB_CONN - Gobal Variable for Datasquirel Database
|
||||
*/
|
||||
export default function createDbFromSchema({ userId, targetDatabase, dbSchemaData, }: Param): Promise<boolean>;
|
||||
export default function createDbFromSchema({ userId, targetDatabase, dbSchemaData, targetTable, dbId, }: Param): Promise<boolean>;
|
||||
export {};
|
||||
|
||||
+111
-100
@@ -1,46 +1,35 @@
|
||||
"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 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 grab_dir_names_1 = __importDefault(require("../../utils/backend/names/grab-dir-names"));
|
||||
const check_db_record_1 = __importDefault(require("./check-db-record"));
|
||||
const check_table_record_1 = __importDefault(require("./check-table-record"));
|
||||
const handle_indexes_1 = __importDefault(require("./handle-indexes"));
|
||||
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
|
||||
*/
|
||||
function createDbFromSchema(_a) {
|
||||
return __awaiter(this, arguments, void 0, function* ({ userId, targetDatabase, dbSchemaData, }) {
|
||||
var _b, _c;
|
||||
const { userSchemaMainJSONFilePath, mainShemaJSONFilePath } = (0, grab_dir_names_1.default)({
|
||||
export default async function createDbFromSchema({ userId, targetDatabase, dbSchemaData, targetTable, dbId, }) {
|
||||
var _a, _b;
|
||||
try {
|
||||
const { userSchemaMainJSONFilePath } = grabDirNames({
|
||||
userId,
|
||||
});
|
||||
const schemaPath = userSchemaMainJSONFilePath || mainShemaJSONFilePath;
|
||||
const dbSchema = dbSchemaData ||
|
||||
ejson_1.default.parse(fs_1.default.readFileSync(schemaPath, "utf8"));
|
||||
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;
|
||||
@@ -49,14 +38,16 @@ function createDbFromSchema(_a) {
|
||||
if (targetDatabase && dbFullName != targetDatabase) {
|
||||
continue;
|
||||
}
|
||||
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`);
|
||||
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 = 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)({
|
||||
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];
|
||||
@@ -67,28 +58,40 @@ function createDbFromSchema(_a) {
|
||||
* or the table name has been recently changed
|
||||
*/
|
||||
if (!targetTableSchema) {
|
||||
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");
|
||||
yield (0, varDatabaseDbHandler_1.default)({
|
||||
queryString: `RENAME TABLE \`${dbFullName}\`.\`${oldTable.tableNameOld}\` TO \`${oldTable.tableName}\``,
|
||||
});
|
||||
}
|
||||
else {
|
||||
console.log(`Dropping Table 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],
|
||||
});
|
||||
}
|
||||
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],
|
||||
// });
|
||||
// }
|
||||
}
|
||||
}
|
||||
/**
|
||||
@@ -97,56 +100,64 @@ function createDbFromSchema(_a) {
|
||||
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)({
|
||||
const tableCheck = await varDatabaseDbHandler({
|
||||
queryString: `
|
||||
SELECT EXISTS (
|
||||
SELECT
|
||||
TABLE_NAME
|
||||
FROM
|
||||
information_schema.TABLES
|
||||
WHERE
|
||||
TABLE_SCHEMA = ? AND
|
||||
TABLE_NAME = ?
|
||||
SELECT EXISTS (
|
||||
SELECT
|
||||
TABLE_NAME
|
||||
FROM
|
||||
information_schema.TABLES
|
||||
WHERE
|
||||
TABLE_SCHEMA = ? AND
|
||||
TABLE_NAME = ?
|
||||
) AS tableExists`,
|
||||
queryValuesArray: [dbFullName, table.tableName],
|
||||
});
|
||||
////////////////////////////////////////
|
||||
if (tableCheck && ((_c = tableCheck[0]) === null || _c === void 0 ? void 0 : _c.tableExists) > 0) {
|
||||
if (tableCheck && ((_b = tableCheck[0]) === null || _b === void 0 ? void 0 : _b.tableExists) > 0) {
|
||||
/**
|
||||
* @description Update table if table exists
|
||||
*/
|
||||
const updateExistingTable = yield (0, updateTable_1.default)({
|
||||
const updateExistingTable = await updateTable({
|
||||
dbFullName: dbFullName,
|
||||
tableName: tableName,
|
||||
tableNameFull: table.tableFullName,
|
||||
tableInfoArray: fields,
|
||||
tableFields: fields,
|
||||
userId,
|
||||
dbSchema,
|
||||
dbSchema: database,
|
||||
tableIndexes: indexes,
|
||||
tableIndex: t,
|
||||
childDb: database.childDatabase || undefined,
|
||||
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 updateExistingChildTable = yield (0, updateTable_1.default)({
|
||||
dbFullName: childTable.dbNameFull,
|
||||
tableName: childTable.tableName,
|
||||
tableNameFull: childTable.tableNameFull,
|
||||
tableInfoArray: fields,
|
||||
const childTableParentDbSchema = grabPrimaryRequiredDbSchema({
|
||||
dbId: childTable.dbId,
|
||||
userId,
|
||||
dbSchema,
|
||||
tableIndexes: indexes,
|
||||
});
|
||||
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,
|
||||
childDb: database.childDatabase || undefined,
|
||||
recordedDbEntry,
|
||||
tableSchema: table,
|
||||
isMain,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -155,12 +166,13 @@ function createDbFromSchema(_a) {
|
||||
/**
|
||||
* @description Create new Table if table doesnt exist
|
||||
*/
|
||||
const createNewTable = yield (0, createTable_1.default)({
|
||||
const createNewTable = await createTable({
|
||||
tableName: tableName,
|
||||
tableInfoArray: fields,
|
||||
dbFullName: dbFullName,
|
||||
tableSchema: table,
|
||||
recordedDbEntry,
|
||||
isMain,
|
||||
});
|
||||
/**
|
||||
* Handle DATASQUIREL Table Indexes
|
||||
@@ -169,20 +181,13 @@ function createDbFromSchema(_a) {
|
||||
* table index(if available), and perform operations
|
||||
*/
|
||||
if (indexes === null || indexes === void 0 ? void 0 : indexes[0]) {
|
||||
(0, handle_indexes_1.default)({
|
||||
handleIndexescreateDbFromSchema({
|
||||
dbFullName,
|
||||
indexes,
|
||||
tableName,
|
||||
});
|
||||
}
|
||||
}
|
||||
const tableRecord = yield (0, check_table_record_1.default)({
|
||||
dbFullName,
|
||||
dbSchema,
|
||||
tableSchema: table,
|
||||
dbRecord: recordedDbEntry,
|
||||
userId,
|
||||
});
|
||||
}
|
||||
/**
|
||||
* @description Check all children databases
|
||||
@@ -191,14 +196,20 @@ function createDbFromSchema(_a) {
|
||||
for (let ch = 0; ch < childrenDatabases.length; ch++) {
|
||||
const childDb = childrenDatabases[ch];
|
||||
const { dbId } = childDb;
|
||||
const targetDatabase = dbSchema.find((dbSch) => dbSch.id == dbId);
|
||||
yield createDbFromSchema({
|
||||
userId,
|
||||
targetDatabase: targetDatabase === null || targetDatabase === void 0 ? void 0 : targetDatabase.dbFullName,
|
||||
});
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user