import _ from "lodash"; export default async function orderDBSchema({ db_schema, }) { let new_db_schema = _.cloneDeep(db_schema); const tables = new_db_schema.tables; let new_tables_set = new Set(); let new_tables_start_set = new Set(); let new_tables_end_set = new Set(); function setParentTable(table) { 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; }