Skip to content

Instantly share code, notes, and snippets.

@davidsheldon
Created July 17, 2009 15:09
Show Gist options
  • Select an option

  • Save davidsheldon/149097 to your computer and use it in GitHub Desktop.

Select an option

Save davidsheldon/149097 to your computer and use it in GitHub Desktop.
If you have a column with a foreign key constraint, and no index, then whenever anything is deleted from the target table it has to do a table scan. This will show you columns that might cause this error. pg_dump -s databaseName | findMissingFKIndexes.pl
#!/usr/bin/perl
my $DEBUG=0;
my %indexes = ();
my %keys = ();
my $last = "";
while(<>) {
if (/^CREATE INDEX.*ON (\S+) USING btree \((\S+)(,.*)?\)/) {
print "INDEX $1 $2\n" if $DEBUG;
$indexes{"$1 $2"} = 1;
}
if (/ADD CONSTRAINT \S+ PRIMARY KEY \((\S+)(,.*)?\)/) {
my $column = $1;
$last =~ /TABLE ONLY (\S+)/;
print "PK $1 $column\n" if $DEBUG;
$indexes{"$1 $column"} = 1;
}
if (/ADD CONSTRAINT \S+ FOREIGN KEY \((\S+)\)/) {
my $column = $1;
$last =~ /TABLE ONLY (\S+)/;
print "FK $1 $column\n" if $DEBUG;
$keys{"$1 $column"} = 1;
}
$last = $_;
}
for my $fk (keys %keys) {
print "MISSING: $fk\n" unless $indexes{$fk};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment