create referencial integrity which works with inheritance
authorDobrica Pavlinusic <dpavlin@rot13.org>
Sat, 23 Jul 2005 18:21:01 +0000 (18:21 +0000)
committerDobrica Pavlinusic <dpavlin@rot13.org>
Sat, 23 Jul 2005 18:21:01 +0000 (18:21 +0000)
git-svn-id: svn+ssh://mjesec/home/dpavlin/svn/webpac2/trunk@25 07558da8-63fa-0310-ba24-9fe276d99e06

sql/mkindex.pl

index 8872492..52f5fe2 100755 (executable)
@@ -1,15 +1,19 @@
 #!/usr/bin/perl -w
 
 # Helper script to produce alter tables for inherited tables and
-# indexes from source shema
+# indexes from source shema like this:
+#
+# ./mkindex schema.sql | psql database_name
 
 use strict;
-#use Data::Dumper;
+use Data::Dumper;
 
 my $out;
 
 my ($table, $inherit);
 
+print "begin;\n";
+
 while (<>) {
        chomp;
 
@@ -30,9 +34,16 @@ while (<>) {
                $out->{inherits}->{$table} = $1;
        }
 
+       if (s/^\s*(\S+)(.+?)references\s+(\S+)\s*\((\S+)\)/$1$2/i) {
+               @{ $out->{references}->{$table}->{$1} } = ( $3, $4 );
+       }
+
+       print "$_\n";
+       print STDERR "# $_\n";
+
 }
 
-#print STDERR Dumper($out);
+print STDERR Dumper($out);
 
 foreach my $table (keys %{ $out->{inherits} }) {
        my $parent = $out->{inherits}->{$table} || die;
@@ -49,4 +60,24 @@ foreach my $type (keys %{ $out->{index} }) {
        }
 }
 
-       
+foreach my $table (keys %{ $out->{references} }) {
+       foreach my $field (keys %{ $out->{references}->{$table} }) {
+               my $fk = $out->{references}->{$table}->{$field} || die;
+               my $func = $table . '_' . $field . '_fkey';
+               print qq{
+create or replace function $func() returns TRIGGER AS
+\$\$
+DECLARE
+BEGIN
+IF NEW.$field IN (select $fk->[1] from $fk->[0]) THEN
+       RETURN NEW;
+ELSE
+       RAISE EXCEPTION 'insert or update on table "%" violates foreign key constraint for "$table" table', TG_RELNAME;
+END IF;
+END;
+\$\$ language 'plpgsql';
+};
+       }
+}
+
+print "commit;\n";