datasquirel/package-shared/utils/db/schema/resolve-users-schema-ids.ts
Benjamin Toby 7e8bb37c09 Updates
2025-07-05 14:59:30 +01:00

79 lines
2.3 KiB
TypeScript

import fs from "fs";
import grabDirNames from "../../backend/names/grab-dir-names";
import _n from "../../numberfy";
import path from "path";
import { DSQL_DatabaseSchemaType } from "../../../types";
import _ from "lodash";
import EJSON from "../../ejson";
import { writeUpdatedDbSchema } from "../../../shell/createDbFromSchema/grab-required-database-schemas";
type Params = {
userId: string | number;
dbId?: string | number;
};
export default function resolveUsersSchemaIDs({ userId, dbId }: Params) {
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")
) as DSQL_DatabaseSchemaType | undefined;
if (!dbSchema) continue;
let newDbSchema = resolveUserDatabaseSchemaIDs({ dbSchema });
writeUpdatedDbSchema({ dbSchema: newDbSchema, userId });
}
}
export function resolveUserDatabaseSchemaIDs({
dbSchema,
}: {
dbSchema: DSQL_DatabaseSchemaType;
}) {
let newDbSchema = _.cloneDeep(dbSchema);
if (!newDbSchema.id) newDbSchema.id = dbSchema.id;
newDbSchema.tables.forEach((tbl, index) => {
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;
}
});
tbl.indexes?.forEach((indx, indIndx) => {
if (!indx.id && newDbSchema.tables[index].indexes) {
newDbSchema.tables[index].indexes[indIndx].id = indIndx + 1;
}
});
});
return newDbSchema;
}