use of org.libj.util.RefDigraph in project jaxdb by jaxdb.
the class DDLx method topologicalSort.
private static Schema topologicalSort(final Schema schema) {
final List<$Table> tables = new ArrayList<>(schema.getTable());
schema.getTable().clear();
tables.sort(tableNameComparator);
final RefDigraph<$Table, String> digraph = new RefDigraph<>(table -> table.getName$().text().toLowerCase());
for (final $Table table : tables) {
digraph.add(table);
if (table.getColumn() != null)
for (final $Column column : table.getColumn()) if (column.getForeignKey() != null)
digraph.add(table, column.getForeignKey().getReferences$().text().toLowerCase());
if (table.getConstraints() != null && table.getConstraints().getForeignKey() != null)
for (final $ForeignKeyComposite foreignKey : table.getConstraints().getForeignKey()) digraph.add(table, foreignKey.getReferences$().text().toLowerCase());
}
if (digraph.hasCycle())
throw new IllegalStateException("Cycle exists in relational model: " + CollectionUtil.toString(digraph.getCycle(), " -> "));
final List<$Table> topologialOrder = digraph.getTopologicalOrder();
final ListIterator<$Table> topological = topologialOrder.listIterator(digraph.size());
while (topological.hasPrevious()) schema.getTable().add(topological.previous());
return schema;
}
Aggregations