This commit is contained in:
Benjamin Toby
2025-07-05 14:59:30 +01:00
parent 6e334c2525
commit 7e8bb37c09
526 changed files with 17560 additions and 11386 deletions
+3 -1
View File
@@ -1,10 +1,12 @@
import { ServerlessMysql } from "serverless-mysql";
import { DSQLErrorObject } from "../../types";
export type ConnDBHandlerQueryObject = {
query: string;
values?: (string | number | undefined)[];
};
type Return<ReturnType = any> = ReturnType | null | {
error: string;
error?: string;
errors?: DSQLErrorObject[];
};
/**
* # Run Query From MySQL Connection
+73 -79
View File
@@ -1,25 +1,10 @@
"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 = connDbHandler;
const debug_log_1 = __importDefault(require("../logging/debug-log"));
import debugLog from "../logging/debug-log";
/**
* # Run Query From MySQL Connection
* @description Run a query from a pre-existing MySQL/Mariadb Connection
* setup with `serverless-mysql` npm module
*/
function connDbHandler(
export default async function connDbHandler(
/**
* ServerlessMySQL Connection Object
*/
@@ -32,74 +17,83 @@ query,
* Array of Values to Sanitize and Inject
*/
values, debug) {
return __awaiter(this, void 0, void 0, function* () {
var _a, _b;
try {
if (!conn)
throw new Error("No Connection Found!");
if (!query)
throw new Error("Query String Required!");
if (typeof query == "string") {
const res = yield conn.query(trimQuery(query), values);
if (debug) {
(0, debug_log_1.default)({
log: res,
addTime: true,
label: "res",
});
}
return JSON.parse(JSON.stringify(res));
}
else if (typeof query == "object") {
const resArray = [];
for (let i = 0; i < query.length; i++) {
try {
const queryObj = query[i];
const queryObjRes = yield conn.query(trimQuery(queryObj.query), queryObj.values);
if (debug) {
(0, debug_log_1.default)({
log: queryObjRes,
addTime: true,
label: "queryObjRes",
});
}
resArray.push(JSON.parse(JSON.stringify(queryObjRes)));
}
catch (error) {
(_a = global.ERROR_CALLBACK) === null || _a === void 0 ? void 0 : _a.call(global, `Connection DB Handler Query Error`, error);
resArray.push(null);
}
}
if (debug) {
(0, debug_log_1.default)({
log: resArray,
addTime: true,
label: "resArray",
});
}
return resArray;
}
else {
return null;
}
}
catch (error) {
(_b = global.ERROR_CALLBACK) === null || _b === void 0 ? void 0 : _b.call(global, `Connection DB Handler Error`, error);
var _a, _b;
try {
if (!conn)
throw new Error("No Connection Found!");
if (!query)
throw new Error("Query String Required!");
let queryErrorArray = [];
if (typeof query == "string") {
const res = await conn.query(trimQuery(query), values);
if (debug) {
(0, debug_log_1.default)({
log: `Connection DB Handler Error: ${error.message}`,
debugLog({
log: res,
addTime: true,
label: "Error",
label: "res",
});
}
return {
error: `Connection DB Handler Error: ${error.message}`,
};
return JSON.parse(JSON.stringify(res));
}
finally {
conn === null || conn === void 0 ? void 0 : conn.end();
else if (typeof query == "object") {
const resArray = [];
for (let i = 0; i < query.length; i++) {
let currentQueryError = {};
try {
const queryObj = query[i];
currentQueryError.sql = queryObj.query;
currentQueryError.sqlValues = queryObj.values;
const queryObjRes = await conn.query(trimQuery(queryObj.query), queryObj.values);
if (debug) {
debugLog({
log: queryObjRes,
addTime: true,
label: "queryObjRes",
});
}
resArray.push(JSON.parse(JSON.stringify(queryObjRes)));
}
catch (error) {
(_a = global.ERROR_CALLBACK) === null || _a === void 0 ? void 0 : _a.call(global, `Connection DB Handler Query Error`, error);
resArray.push(null);
currentQueryError["error"] = error.message;
queryErrorArray.push(currentQueryError);
}
}
if (debug) {
debugLog({
log: resArray,
addTime: true,
label: "resArray",
});
}
if (queryErrorArray[0]) {
return {
errors: queryErrorArray,
};
}
return resArray;
}
});
else {
return null;
}
}
catch (error) {
(_b = global.ERROR_CALLBACK) === null || _b === void 0 ? void 0 : _b.call(global, `Connection DB Handler Error`, error);
if (debug) {
debugLog({
log: `Connection DB Handler Error: ${error.message}`,
addTime: true,
label: "Error",
});
}
return {
error: `Connection DB Handler Error: ${error.message}`,
};
}
finally {
conn === null || conn === void 0 ? void 0 : conn.end();
}
}
function trimQuery(query) {
return query.replace(/\n/gm, "").replace(/ {2,}/g, "").trim();
@@ -0,0 +1 @@
export default function dataTypeConstructor(dataType: string, limit?: number, decimal?: number): string;
@@ -0,0 +1,20 @@
import dataTypeParser, { DataTypesWithNumbers } from "./data-type-parser";
export default function dataTypeConstructor(dataType, limit, decimal) {
let finalType = dataTypeParser(dataType).type;
if (!DataTypesWithNumbers.includes(finalType)) {
return finalType;
}
if (finalType == "VARCHAR") {
return (finalType += `(${limit || 250})`);
}
if (finalType == "DECIMAL" ||
finalType == "FLOAT" ||
finalType == "DOUBLE") {
return (finalType += `(${limit || 10},${decimal || 2})`);
}
if (limit && !decimal)
finalType += `(${limit})`;
if (limit && decimal)
finalType += `(${limit},${decimal})`;
return finalType;
}
@@ -0,0 +1,10 @@
import DataTypes from "../../../data/data-types";
export declare const DataTypesWithNumbers: (typeof DataTypes)[number]["name"][];
export declare const DataTypesWithTwoNumbers: (typeof DataTypes)[number]["name"][];
type Return = {
type: (typeof DataTypes)[number]["name"];
limit?: number;
decimal?: number;
};
export default function dataTypeParser(dataType?: string): Return;
export {};
+40
View File
@@ -0,0 +1,40 @@
import numberfy from "../../numberfy";
export const DataTypesWithNumbers = [
"DECIMAL",
"DOUBLE",
"FLOAT",
"VARCHAR",
];
export const DataTypesWithTwoNumbers = [
"DECIMAL",
"DOUBLE",
"FLOAT",
];
export default function dataTypeParser(dataType) {
if (!dataType) {
return {
type: "VARCHAR",
limit: 250,
};
}
const dataTypeArray = dataType.split("(");
const type = dataTypeArray[0];
const number = dataTypeArray[1];
if (!DataTypesWithNumbers.includes(type)) {
return {
type,
};
}
if (number === null || number === void 0 ? void 0 : number.match(/,/)) {
const numberArr = number.split(",");
return {
type,
limit: numberfy(numberArr[0]),
decimal: numberArr[1] ? numberfy(numberArr[1]) : undefined,
};
}
return {
type,
limit: number ? numberfy(number) : undefined,
};
}
@@ -0,0 +1,11 @@
import { DSQL_ChildrenDatabaseObject, DSQL_ChildrenTablesType, DSQL_DatabaseSchemaType } from "../../../types";
type Params = {
dbs?: DSQL_DatabaseSchemaType[];
dbSchema?: DSQL_DatabaseSchemaType;
childDbSchema?: DSQL_ChildrenDatabaseObject;
childTableSchema?: DSQL_ChildrenTablesType;
dbSlug?: string;
dbFullName?: string;
};
export default function grabTargetDatabaseSchemaIndex({ dbs, dbFullName, dbSlug, dbSchema, childDbSchema, childTableSchema, }: Params): number | undefined;
export {};
@@ -0,0 +1,10 @@
export default function grabTargetDatabaseSchemaIndex({ dbs, dbFullName, dbSlug, dbSchema, childDbSchema, childTableSchema, }) {
if (!dbs)
return undefined;
const targetDbIndex = dbs.findIndex((db) => (dbSlug && dbSlug == db.dbSlug) ||
(dbFullName && dbFullName == db.dbFullName) ||
(dbSchema && dbSchema.dbSlug && dbSchema.dbSlug == db.dbSlug));
if (targetDbIndex < 0)
return undefined;
return targetDbIndex;
}
@@ -0,0 +1,9 @@
import { DSQL_ChildrenTablesType, DSQL_TableSchemaType } from "../../../types";
type Params = {
tables?: DSQL_TableSchemaType[];
tableSchema?: DSQL_TableSchemaType;
childTableSchema?: DSQL_ChildrenTablesType;
tableName?: string;
};
export default function grabTargetTableSchemaIndex({ tables, tableName, tableSchema, childTableSchema, }: Params): number | undefined;
export {};
@@ -0,0 +1,11 @@
export default function grabTargetTableSchemaIndex({ tables, tableName, tableSchema, childTableSchema, }) {
if (!tables)
return undefined;
const targetTableIndex = tables.findIndex((tbl) => (tableName && tableName == tbl.tableName) ||
(tableSchema &&
tableSchema.tableName &&
tableSchema.tableName == tbl.tableName));
if (targetTableIndex < 0)
return undefined;
return targetTableIndex;
}
@@ -0,0 +1,7 @@
import { DSQL_TableSchemaType } from "../../../types";
type Params = {
tables: DSQL_TableSchemaType[];
tableName?: string;
};
export default function grabTargetTableSchema({ tables, tableName, }: Params): DSQL_TableSchemaType | undefined;
export {};
@@ -0,0 +1,4 @@
export default function grabTargetTableSchema({ tables, tableName, }) {
const targetTable = tables.find((tbl) => tableName && tableName == tbl.tableName);
return targetTable;
}
@@ -0,0 +1,2 @@
import { DSQL_FieldSchemaType, TextFieldTypesArray } from "../../../types";
export default function grabTextFieldType(field: DSQL_FieldSchemaType, nullReturn?: boolean): (typeof TextFieldTypesArray)[number]["value"] | undefined;
@@ -0,0 +1,19 @@
export default function grabTextFieldType(field, nullReturn) {
if (field.richText)
return "richText";
if (field.json)
return "json";
if (field.yaml)
return "yaml";
if (field.html)
return "html";
if (field.css)
return "css";
if (field.javascript)
return "javascript";
if (field.shell)
return "shell";
if (nullReturn)
return undefined;
return "plain";
}
@@ -0,0 +1,7 @@
import { DSQL_DatabaseSchemaType } from "../../../types";
type Params = {
currentDbSchema: DSQL_DatabaseSchemaType;
userId: string | number;
};
export default function ({ currentDbSchema, userId }: Params): DSQL_DatabaseSchemaType;
export {};
@@ -0,0 +1,88 @@
import { grabPrimaryRequiredDbSchema, writeUpdatedDbSchema, } from "../../../shell/createDbFromSchema/grab-required-database-schemas";
import _ from "lodash";
import uniqueByKey from "../../unique-by-key";
export default function ({ currentDbSchema, userId }) {
var _a, _b, _c;
const newCurrentDbSchema = _.cloneDeep(currentDbSchema);
if (newCurrentDbSchema.childrenDatabases) {
for (let ch = 0; ch < newCurrentDbSchema.childrenDatabases.length; ch++) {
const dbChildDb = newCurrentDbSchema.childrenDatabases[ch];
if (!dbChildDb.dbId) {
newCurrentDbSchema.childrenDatabases.splice(ch, 1, {});
continue;
}
const targetChildDatabase = grabPrimaryRequiredDbSchema({
dbId: dbChildDb.dbId,
userId,
});
/**
* Delete child database from array if said database
* doesn't exist
*/
if ((targetChildDatabase === null || targetChildDatabase === void 0 ? void 0 : targetChildDatabase.id) && targetChildDatabase.childDatabase) {
targetChildDatabase.tables = [...newCurrentDbSchema.tables];
writeUpdatedDbSchema({
dbSchema: targetChildDatabase,
userId,
});
}
else {
(_a = newCurrentDbSchema.childrenDatabases) === null || _a === void 0 ? void 0 : _a.splice(ch, 1, {});
}
}
newCurrentDbSchema.childrenDatabases =
uniqueByKey(newCurrentDbSchema.childrenDatabases.filter((db) => Boolean(db.dbId)), "dbId");
}
/**
* Handle scenario where this database is a child of another
*/
if (currentDbSchema.childDatabase && currentDbSchema.childDatabaseDbId) {
const targetParentDatabase = grabPrimaryRequiredDbSchema({
dbId: currentDbSchema.childDatabaseDbId,
userId,
});
if (!targetParentDatabase) {
return newCurrentDbSchema;
}
/**
* Delete child Database key/values from current database if
* the parent database doesn't esit
*/
if (!(targetParentDatabase === null || targetParentDatabase === void 0 ? void 0 : targetParentDatabase.id)) {
delete newCurrentDbSchema.childDatabase;
delete newCurrentDbSchema.childDatabaseDbId;
return newCurrentDbSchema;
}
/**
* New Child Database Object to be appended
*/
const newChildDatabaseObject = {
dbId: currentDbSchema.id,
};
/**
* Add a new Children array in the target Database if this is the
* first child to be added to said database. Else append to array
* if it exists
*/
if ((targetParentDatabase === null || targetParentDatabase === void 0 ? void 0 : targetParentDatabase.id) &&
!((_b = targetParentDatabase.childrenDatabases) === null || _b === void 0 ? void 0 : _b[0])) {
targetParentDatabase.childrenDatabases = [newChildDatabaseObject];
}
else if ((targetParentDatabase === null || targetParentDatabase === void 0 ? void 0 : targetParentDatabase.id) &&
((_c = targetParentDatabase.childrenDatabases) === null || _c === void 0 ? void 0 : _c[0])) {
const existingChildDb = targetParentDatabase.childrenDatabases.find((db) => db.dbId == currentDbSchema.id);
if (!(existingChildDb === null || existingChildDb === void 0 ? void 0 : existingChildDb.dbId)) {
targetParentDatabase.childrenDatabases.push(newChildDatabaseObject);
}
targetParentDatabase.childrenDatabases = uniqueByKey(targetParentDatabase.childrenDatabases, "dbId");
}
/**
* Update tables for child database, which is the current database
*/
if (targetParentDatabase === null || targetParentDatabase === void 0 ? void 0 : targetParentDatabase.id) {
newCurrentDbSchema.tables = targetParentDatabase.tables;
writeUpdatedDbSchema({ dbSchema: targetParentDatabase, userId });
}
}
return newCurrentDbSchema;
}
@@ -0,0 +1,9 @@
import { DSQL_DatabaseSchemaType, DSQL_TableSchemaType } from "../../../types";
type Params = {
currentDbSchema: DSQL_DatabaseSchemaType;
currentTableSchema: DSQL_TableSchemaType;
currentTableSchemaIndex: number;
userId: string | number;
};
export default function ({ currentDbSchema, currentTableSchema, currentTableSchemaIndex, userId, }: Params): DSQL_DatabaseSchemaType;
export {};
@@ -0,0 +1,133 @@
import { grabPrimaryRequiredDbSchema, writeUpdatedDbSchema, } from "../../../shell/createDbFromSchema/grab-required-database-schemas";
import _ from "lodash";
import uniqueByKey from "../../unique-by-key";
export default function ({ currentDbSchema, currentTableSchema, currentTableSchemaIndex, userId, }) {
var _a, _b, _c, _d, _e, _f, _g;
if (!currentDbSchema.dbFullName) {
throw new Error(`Resolve Children tables ERROR => currentDbSchema.dbFullName not found!`);
}
const newCurrentDbSchema = _.cloneDeep(currentDbSchema);
if (newCurrentDbSchema.tables[currentTableSchemaIndex].childrenTables) {
for (let ch = 0; ch <
newCurrentDbSchema.tables[currentTableSchemaIndex].childrenTables
.length; ch++) {
const childTable = newCurrentDbSchema.tables[currentTableSchemaIndex]
.childrenTables[ch];
if (!childTable.dbId || !childTable.tableId) {
(_a = newCurrentDbSchema.tables[currentTableSchemaIndex].childrenTables) === null || _a === void 0 ? void 0 : _a.splice(ch, 1, {});
continue;
}
const targetChildTableParentDatabase = grabPrimaryRequiredDbSchema({
dbId: childTable.dbId,
userId,
});
/**
* Delete child table from array if the parent database
* of said child table has been deleted or doesn't exist
*/
if (!(targetChildTableParentDatabase === null || targetChildTableParentDatabase === void 0 ? void 0 : targetChildTableParentDatabase.dbFullName)) {
(_b = newCurrentDbSchema.tables[currentTableSchemaIndex].childrenTables) === null || _b === void 0 ? void 0 : _b.splice(ch, 1, {});
}
else {
/**
* Delete child table from array if the parent database
* exists but the target tabled has been deleted or doesn't
* exist
*/
const targetChildTableParentDatabaseTableIndex = targetChildTableParentDatabase.tables.findIndex((tbl) => tbl.id == childTable.tableId);
const targetChildTableParentDatabaseTable = targetChildTableParentDatabase.tables[targetChildTableParentDatabaseTableIndex];
if (targetChildTableParentDatabaseTable === null || targetChildTableParentDatabaseTable === void 0 ? void 0 : targetChildTableParentDatabaseTable.childTable) {
targetChildTableParentDatabase.tables[targetChildTableParentDatabaseTableIndex].fields = [...currentTableSchema.fields];
targetChildTableParentDatabase.tables[targetChildTableParentDatabaseTableIndex].indexes = [...(currentTableSchema.indexes || [])];
writeUpdatedDbSchema({
dbSchema: targetChildTableParentDatabase,
userId,
});
}
else {
(_c = newCurrentDbSchema.tables[currentTableSchemaIndex].childrenTables) === null || _c === void 0 ? void 0 : _c.splice(ch, 1, {});
}
}
}
if ((_d = newCurrentDbSchema.tables[currentTableSchemaIndex]
.childrenTables) === null || _d === void 0 ? void 0 : _d[0]) {
newCurrentDbSchema.tables[currentTableSchemaIndex].childrenTables =
uniqueByKey(newCurrentDbSchema.tables[currentTableSchemaIndex].childrenTables.filter((tbl) => Boolean(tbl.dbId) && Boolean(tbl.tableId)), "dbId");
}
else {
delete newCurrentDbSchema.tables[currentTableSchemaIndex]
.childrenTables;
}
}
/**
* Handle scenario where this table is a child of another
*/
if (currentTableSchema.childTable &&
currentTableSchema.childTableDbId &&
currentTableSchema.childTableDbId) {
const targetParentDatabase = grabPrimaryRequiredDbSchema({
dbId: currentTableSchema.childTableDbId,
userId,
});
const targetParentDatabaseTableIndex = targetParentDatabase === null || targetParentDatabase === void 0 ? void 0 : targetParentDatabase.tables.findIndex((tbl) => tbl.id == currentTableSchema.childTableId);
const targetParentDatabaseTable = typeof targetParentDatabaseTableIndex == "number"
? targetParentDatabaseTableIndex < 0
? undefined
: targetParentDatabase === null || targetParentDatabase === void 0 ? void 0 : targetParentDatabase.tables[targetParentDatabaseTableIndex]
: undefined;
/**
* Delete child Table key/values from current database if
* the parent database doesn't esit
*/
if (!(targetParentDatabase === null || targetParentDatabase === void 0 ? void 0 : targetParentDatabase.dbFullName) ||
!(targetParentDatabaseTable === null || targetParentDatabaseTable === void 0 ? void 0 : targetParentDatabaseTable.tableName)) {
delete newCurrentDbSchema.tables[currentTableSchemaIndex]
.childTable;
delete newCurrentDbSchema.tables[currentTableSchemaIndex]
.childTableDbId;
delete newCurrentDbSchema.tables[currentTableSchemaIndex]
.childTableId;
delete newCurrentDbSchema.tables[currentTableSchemaIndex]
.childTableDbId;
return newCurrentDbSchema;
}
/**
* New Child Database Table Object to be appended
*/
const newChildDatabaseTableObject = {
tableId: currentTableSchema.id,
dbId: newCurrentDbSchema.id,
};
/**
* Add a new Children array in the target table schema if this is the
* first child to be added to said table schema. Else append to array
* if it exists
*/
if (typeof targetParentDatabaseTableIndex == "number" &&
!((_e = targetParentDatabaseTable.childrenTables) === null || _e === void 0 ? void 0 : _e[0])) {
targetParentDatabase.tables[targetParentDatabaseTableIndex].childrenTables = [newChildDatabaseTableObject];
}
else if (typeof targetParentDatabaseTableIndex == "number" &&
((_f = targetParentDatabaseTable.childrenTables) === null || _f === void 0 ? void 0 : _f[0])) {
const existingChildDbTable = targetParentDatabaseTable.childrenTables.find((tbl) => tbl.dbId == newCurrentDbSchema.id &&
tbl.tableId == currentTableSchema.id);
if (!(existingChildDbTable === null || existingChildDbTable === void 0 ? void 0 : existingChildDbTable.tableId)) {
(_g = targetParentDatabase.tables[targetParentDatabaseTableIndex].childrenTables) === null || _g === void 0 ? void 0 : _g.push(newChildDatabaseTableObject);
}
targetParentDatabase.tables[targetParentDatabaseTableIndex].childrenTables = uniqueByKey(targetParentDatabase.tables[targetParentDatabaseTableIndex]
.childrenTables || [], ["dbId", "tableId"]);
}
/**
* Update fields and indexes for child table, which is the
* current table
*/
if (targetParentDatabaseTable === null || targetParentDatabaseTable === void 0 ? void 0 : targetParentDatabaseTable.tableName) {
newCurrentDbSchema.tables[currentTableSchemaIndex].fields =
targetParentDatabaseTable.fields;
newCurrentDbSchema.tables[currentTableSchemaIndex].indexes =
targetParentDatabaseTable.indexes;
writeUpdatedDbSchema({ dbSchema: targetParentDatabase, userId });
}
}
return newCurrentDbSchema;
}
@@ -0,0 +1,7 @@
import { DSQL_DatabaseSchemaType } from "../../../types";
type Params = {
dbSchema: DSQL_DatabaseSchemaType;
userId: string | number;
};
export default function resolveSchemaChildren({ dbSchema, userId }: Params): DSQL_DatabaseSchemaType;
export {};
@@ -0,0 +1,20 @@
import _ from "lodash";
import resolveSchemaChildrenHandleChildrenDatabases from "./resolve-schema-children-handle-children-databases";
import resolveSchemaChildrenHandleChildrenTables from "./resolve-schema-children-handle-children-tables";
export default function resolveSchemaChildren({ dbSchema, userId }) {
let newDbSchema = _.cloneDeep(dbSchema);
newDbSchema = resolveSchemaChildrenHandleChildrenDatabases({
currentDbSchema: newDbSchema,
userId,
});
for (let t = 0; t < newDbSchema.tables.length; t++) {
const tableSchema = newDbSchema.tables[t];
newDbSchema = resolveSchemaChildrenHandleChildrenTables({
currentDbSchema: newDbSchema,
currentTableSchema: tableSchema,
currentTableSchemaIndex: t,
userId,
});
}
return newDbSchema;
}
@@ -0,0 +1,7 @@
import { DSQL_DatabaseSchemaType } from "../../../types";
type Params = {
dbSchema: DSQL_DatabaseSchemaType;
userId: string | number;
};
export default function resolveSchemaForeignKeys({ dbSchema, userId }: Params): DSQL_DatabaseSchemaType;
export {};
@@ -0,0 +1,27 @@
import _ from "lodash";
export default function resolveSchemaForeignKeys({ dbSchema, userId }) {
var _a;
let newDbSchema = _.cloneDeep(dbSchema);
for (let t = 0; t < newDbSchema.tables.length; t++) {
const tableSchema = newDbSchema.tables[t];
for (let f = 0; f < tableSchema.fields.length; f++) {
const fieldSchema = tableSchema.fields[f];
if ((_a = fieldSchema.foreignKey) === null || _a === void 0 ? void 0 : _a.destinationTableColumnName) {
const fkDestinationTableIndex = newDbSchema.tables.findIndex((tbl) => {
var _a;
return tbl.tableName ==
((_a = fieldSchema.foreignKey) === null || _a === void 0 ? void 0 : _a.destinationTableName);
});
/**
* Delete current Foreign Key if related table doesn't exist
* or has been deleted
*/
if (fkDestinationTableIndex < 0) {
delete newDbSchema.tables[t].fields[f].foreignKey;
continue;
}
}
}
}
return newDbSchema;
}
@@ -0,0 +1,10 @@
import { DSQL_DatabaseSchemaType } from "../../../types";
type Params = {
userId: string | number;
dbId?: string | number;
};
export default function resolveUsersSchemaIDs({ userId, dbId }: Params): false | undefined;
export declare function resolveUserDatabaseSchemaIDs({ dbSchema, }: {
dbSchema: DSQL_DatabaseSchemaType;
}): DSQL_DatabaseSchemaType;
export {};
@@ -0,0 +1,54 @@
import fs from "fs";
import grabDirNames from "../../backend/names/grab-dir-names";
import _n from "../../numberfy";
import path from "path";
import _ from "lodash";
import EJSON from "../../ejson";
import { writeUpdatedDbSchema } from "../../../shell/createDbFromSchema/grab-required-database-schemas";
export default function resolveUsersSchemaIDs({ userId, dbId }) {
const { targetUserPrivateDir, tempDirName } = grabDirNames({ userId });
if (!targetUserPrivateDir)
return false;
const schemaDirFilesFolders = fs.readdirSync(targetUserPrivateDir);
for (let i = 0; i < schemaDirFilesFolders.length; i++) {
const fileOrFolderName = schemaDirFilesFolders[i];
if (!fileOrFolderName.match(/^\d+.json/))
continue;
const fileDbId = _n(fileOrFolderName.split(".").shift());
if (!fileDbId)
continue;
if (dbId && _n(dbId) !== fileDbId) {
continue;
}
const schemaFullPath = path.join(targetUserPrivateDir, fileOrFolderName);
if (!fs.existsSync(schemaFullPath))
continue;
const dbSchema = EJSON.parse(fs.readFileSync(schemaFullPath, "utf-8"));
if (!dbSchema)
continue;
let newDbSchema = resolveUserDatabaseSchemaIDs({ dbSchema });
writeUpdatedDbSchema({ dbSchema: newDbSchema, userId });
}
}
export function resolveUserDatabaseSchemaIDs({ dbSchema, }) {
let newDbSchema = _.cloneDeep(dbSchema);
if (!newDbSchema.id)
newDbSchema.id = dbSchema.id;
newDbSchema.tables.forEach((tbl, index) => {
var _a;
if (!tbl.id) {
newDbSchema.tables[index].id = index + 1;
}
tbl.fields.forEach((fld, flIndx) => {
if (!fld.id) {
newDbSchema.tables[index].fields[flIndx].id = flIndx + 1;
}
});
(_a = tbl.indexes) === null || _a === void 0 ? void 0 : _a.forEach((indx, indIndx) => {
if (!indx.id && newDbSchema.tables[index].indexes) {
newDbSchema.tables[index].indexes[indIndx].id = indIndx + 1;
}
});
});
return newDbSchema;
}
@@ -0,0 +1,2 @@
import { DSQL_FieldSchemaType, TextFieldTypesArray } from "../../../types";
export default function setTextFieldType(field: DSQL_FieldSchemaType, type?: (typeof TextFieldTypesArray)[number]["value"]): DSQL_FieldSchemaType;
@@ -0,0 +1,30 @@
import _ from "lodash";
export default function setTextFieldType(field, type) {
const newField = _.cloneDeep(field);
delete newField.css;
delete newField.richText;
delete newField.json;
delete newField.shell;
delete newField.html;
delete newField.javascript;
delete newField.yaml;
delete newField.code;
delete newField.defaultValueLiteral;
if (type == "css")
return Object.assign(Object.assign({}, newField), { css: true });
if (type == "richText")
return Object.assign(Object.assign({}, newField), { richText: true });
if (type == "json")
return Object.assign(Object.assign({}, newField), { json: true });
if (type == "shell")
return Object.assign(Object.assign({}, newField), { shell: true });
if (type == "html")
return Object.assign(Object.assign({}, newField), { html: true });
if (type == "yaml")
return Object.assign(Object.assign({}, newField), { yaml: true });
if (type == "javascript")
return Object.assign(Object.assign({}, newField), { javascript: true });
if (type == "code")
return Object.assign(Object.assign({}, newField), { code: true });
return Object.assign({}, newField);
}