datasquirel/package-shared/shell/createDbFromSchema/check-db-record.ts
Benjamin Toby 7e8bb37c09 Updates
2025-07-05 14:59:30 +01:00

93 lines
3.2 KiB
TypeScript

import varDatabaseDbHandler from "../utils/varDatabaseDbHandler";
import { DSQL_DatabaseSchemaType, PostInsertReturn } from "../../types";
import { DSQL_DATASQUIREL_USER_DATABASES } from "../../types/dsql";
import numberfy from "../../utils/numberfy";
import addDbEntry from "../../functions/backend/db/addDbEntry";
import updateDbEntry from "../../functions/backend/db/updateDbEntry";
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 async function checkDbRecordCreateDbSchema({
userId,
dbSchema,
isMain,
}: Param): Promise<DSQL_DATASQUIREL_USER_DATABASES | undefined> {
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: DSQL_DATASQUIREL_USER_DATABASES | undefined =
recordedDbEntryArray?.[0];
const newDbEntryObj: DSQL_DATASQUIREL_USER_DATABASES = {
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?.id && userId) {
const newDbEntry =
await addDbEntry<DSQL_DATASQUIREL_USER_DATABASES>({
data: newDbEntryObj,
tableName: "user_databases",
forceLocal: true,
});
if (newDbEntry.payload?.insertId) {
recordedDbEntryArray = await varDatabaseDbHandler({
queryString: `SELECT * FROM datasquirel.user_databases WHERE db_full_name = ?`,
queryValuesArray: [dbFullName || "NULL"],
});
recordedDbEntry = recordedDbEntryArray?.[0];
}
} else if (recordedDbEntry?.id) {
await updateDbEntry<DSQL_DATASQUIREL_USER_DATABASES>({
data: newDbEntryObj,
tableName: "user_databases",
forceLocal: true,
identifierColumnName: "id",
identifierValue: String(recordedDbEntry.id),
});
}
return recordedDbEntry;
} catch (error) {
global.ERROR_CALLBACK?.(
`Error Checking DB Record on Creating Schema`,
error as Error
);
return undefined;
}
}