This commit is contained in:
2026-07-14 08:12:13 +01:00
parent b5e4724e03
commit 3b5fba4063
26 changed files with 1097 additions and 321 deletions
+86
View File
@@ -0,0 +1,86 @@
import _ from "lodash";
import type {
BUN_MARIADB_DatabaseSchemaType,
BUN_MARIADB_TableSchemaType,
CreateDBSchemaParams,
} from "../../types";
export default async function orderDBSchema({
db_schema,
}: CreateDBSchemaParams): Promise<BUN_MARIADB_DatabaseSchemaType> {
let new_db_schema = _.cloneDeep(db_schema);
const tables = new_db_schema.tables;
let new_tables_set = new Set<BUN_MARIADB_TableSchemaType>();
let new_tables_start_set = new Set<BUN_MARIADB_TableSchemaType>();
let new_tables_end_set = new Set<BUN_MARIADB_TableSchemaType>();
function setParentTable(table: BUN_MARIADB_TableSchemaType) {
const fields = table.fields;
let does_table_have_foreign_keys = false;
for (let f = 0; f < fields.length; f++) {
const field = fields[f];
if (!field) continue;
const dst_table_name = field.foreignKey?.destinationTableName;
if (dst_table_name) {
const fk_table = tables.find(
(tb) => tb.tableName == dst_table_name,
);
if (
fk_table &&
!new_tables_start_set.has(fk_table) &&
!new_tables_end_set.has(fk_table)
) {
setParentTable(fk_table);
}
new_tables_end_set.add(table);
if (fk_table) {
new_tables_start_set.add(fk_table);
}
does_table_have_foreign_keys = true;
}
}
return { does_table_have_foreign_keys };
}
for (let i = 0; i < tables.length; i++) {
const table = tables[i];
if (!table) {
continue;
}
let { does_table_have_foreign_keys } = setParentTable(table);
if (does_table_have_foreign_keys) {
new_tables_end_set.add(table);
} else {
new_tables_start_set.add(table);
}
}
const parsed_tables = [
...Array.from(new_tables_start_set),
...Array.from(new_tables_end_set),
];
for (let nt = 0; nt < parsed_tables.length; nt++) {
const new_table = parsed_tables[nt];
if (new_table) {
new_tables_set.add(new_table);
}
}
new_db_schema.tables = Array.from(new_tables_set);
return new_db_schema;
}