1 |
dpavlin |
24 |
#!/usr/bin/perl -w |
2 |
|
|
|
3 |
|
|
# Helper script to produce alter tables for inherited tables and |
4 |
dpavlin |
25 |
# indexes from source shema like this: |
5 |
|
|
# |
6 |
|
|
# ./mkindex schema.sql | psql database_name |
7 |
dpavlin |
24 |
|
8 |
|
|
use strict; |
9 |
dpavlin |
25 |
use Data::Dumper; |
10 |
dpavlin |
24 |
|
11 |
|
|
my $out; |
12 |
|
|
|
13 |
|
|
my ($table, $inherit); |
14 |
|
|
|
15 |
dpavlin |
25 |
print "begin;\n"; |
16 |
|
|
|
17 |
dpavlin |
24 |
while (<>) { |
18 |
|
|
chomp; |
19 |
|
|
|
20 |
|
|
if (/create\s+table\s+(\S+)/i) { |
21 |
|
|
$table = $1; |
22 |
|
|
} |
23 |
|
|
|
24 |
|
|
next unless ($table); |
25 |
|
|
|
26 |
|
|
if (/primary\s+key\s*\(\s*(\S+)\s*\)/i ) { |
27 |
|
|
$out->{table_pk}->{$table} = $1; |
28 |
|
|
} |
29 |
|
|
if (/^\s*(\S+)\s*.+?--\s*((?:unique\s+)*index)/i) { |
30 |
|
|
$out->{index}->{$2}->{$table} = $1; |
31 |
|
|
} |
32 |
|
|
|
33 |
|
|
if (/\s*inherits\s*\(\s*(\S+)\s*\)/) { |
34 |
|
|
$out->{inherits}->{$table} = $1; |
35 |
|
|
} |
36 |
|
|
|
37 |
dpavlin |
25 |
if (s/^\s*(\S+)(.+?)references\s+(\S+)\s*\((\S+)\)/$1$2/i) { |
38 |
|
|
@{ $out->{references}->{$table}->{$1} } = ( $3, $4 ); |
39 |
|
|
} |
40 |
|
|
|
41 |
|
|
print "$_\n"; |
42 |
|
|
print STDERR "# $_\n"; |
43 |
|
|
|
44 |
dpavlin |
24 |
} |
45 |
|
|
|
46 |
dpavlin |
25 |
print STDERR Dumper($out); |
47 |
dpavlin |
24 |
|
48 |
|
|
foreach my $table (keys %{ $out->{inherits} }) { |
49 |
|
|
my $parent = $out->{inherits}->{$table} || die; |
50 |
|
|
my $pk = $out->{table_pk}->{$parent} || die; |
51 |
|
|
my $seq = $parent . '_' . $pk . '_seq'; |
52 |
|
|
print qq{alter table $table alter column $pk set default nextval('$seq');\n}; |
53 |
|
|
} |
54 |
|
|
|
55 |
|
|
foreach my $type (keys %{ $out->{index} }) { |
56 |
|
|
foreach my $table (keys %{ $out->{index}->{$type} }) { |
57 |
|
|
my $f = $out->{index}->{$type}->{$table} || die; |
58 |
|
|
my $i = $table . '_' . $f . '_ind'; |
59 |
|
|
print qq{create $type $i on $table($f);\n}; |
60 |
|
|
} |
61 |
|
|
} |
62 |
|
|
|
63 |
dpavlin |
25 |
foreach my $table (keys %{ $out->{references} }) { |
64 |
|
|
foreach my $field (keys %{ $out->{references}->{$table} }) { |
65 |
|
|
my $fk = $out->{references}->{$table}->{$field} || die; |
66 |
|
|
my $func = $table . '_' . $field . '_fkey'; |
67 |
|
|
print qq{ |
68 |
|
|
create or replace function $func() returns TRIGGER AS |
69 |
|
|
\$\$ |
70 |
|
|
DECLARE |
71 |
|
|
BEGIN |
72 |
|
|
IF NEW.$field IN (select $fk->[1] from $fk->[0]) THEN |
73 |
|
|
RETURN NEW; |
74 |
|
|
ELSE |
75 |
|
|
RAISE EXCEPTION 'insert or update on table "%" violates foreign key constraint for "$table" table', TG_RELNAME; |
76 |
|
|
END IF; |
77 |
|
|
END; |
78 |
|
|
\$\$ language 'plpgsql'; |
79 |
|
|
}; |
80 |
|
|
} |
81 |
|
|
} |
82 |
|
|
|
83 |
|
|
print "commit;\n"; |