#!/usr/perl/bin/perl -w # Reads in tables in random order, and sorts out the foreign key references # by using a topological sort. use strict; use Graph; { my $graph = Graph->new; my %table_text; my $table; while (<>) { if (/CREATE\s+TABLE\s+(\w+)/i) { $table = $1; } push @{ $table_text{$table} }, $_ if (defined($table)); if (/references\s+(\w+)/i) { my $table_ref = $1; if (! ($table_ref eq $table) ) { $graph->add_edge($table_ref, $table); } } } my @ts = $graph->topological_sort; foreach my $table_name (@ts) { my @table_rows = @{ $table_text{$table_name} }; foreach (@table_rows) { print "$_"; } } } # end of main 1; __END__