Adding new GraphViz producer.
[dbsrgits/SQL-Translator.git] / lib / SQL / Translator / Producer / GraphViz.pm
1 package SQL::Translator::Producer::GraphViz;
2
3 # -------------------------------------------------------------------
4 # $Id: GraphViz.pm,v 1.1 2003-04-24 16:15:13 kycl4rk Exp $
5 # -------------------------------------------------------------------
6 # Copyright (C) 2003 Ken Y. Clark <kclark@cpan.org>
7 #
8 # This program is free software; you can redistribute it and/or
9 # modify it under the terms of the GNU General Public License as
10 # published by the Free Software Foundation; version 2.
11 #
12 # This program is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 # General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with this program; if not, write to the Free Software
19 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
20 # 02111-1307  USA
21 # -------------------------------------------------------------------
22
23 use strict;
24 use GraphViz;
25 use Data::Dumper;
26 use SQL::Translator::Utils qw(debug);
27
28 use vars qw[ $VERSION $DEBUG ];
29 $VERSION = sprintf "%d.%02d", q$Revision: 1.1 $ =~ /(\d+)\.(\d+)/;
30 $DEBUG   = 0 unless defined $DEBUG;
31
32 use constant VALID_LAYOUT => {
33     dot   => 1, 
34     neato => 1, 
35     twopi => 1,
36 };
37
38 use constant VALID_NODE_SHAPE => {
39     record        => 1, 
40     plaintext     => 1, 
41     ellipse       => 1, 
42     circle        => 1, 
43     egg           => 1, 
44     triangle      => 1, 
45     box           => 1, 
46     diamond       => 1, 
47     trapezium     => 1, 
48     parallelogram => 1, 
49     house         => 1, 
50     hexagon       => 1, 
51     octagon       => 1, 
52 };
53
54 use constant VALID_OUTPUT => {
55     canon => 1, 
56     text  => 1, 
57     ps    => 1, 
58     hpgl  => 1,
59     pcl   => 1, 
60     mif   => 1, 
61     pic   => 1, 
62     gd    => 1, 
63     gd2   => 1, 
64     gif   => 1, 
65     jpeg  => 1,
66     png   => 1, 
67     wbmp  => 1, 
68     cmap  => 1, 
69     ismap => 1, 
70     imap  => 1, 
71     vrml  => 1,
72     vtx   => 1, 
73     mp    => 1, 
74     fig   => 1, 
75     svg   => 1, 
76     plain => 1,
77 };
78
79 sub produce {
80     my ($t, $data) = @_;
81     my $args       = $t->producer_args;
82     local $DEBUG   = $t->debug;
83     debug("Data =\n", Dumper( $data ));
84     debug("Producer args =\n", Dumper( $args ));
85
86     my $out_file        = $args->{'out_file'};
87     my $layout          = $args->{'layout'};
88     my $node_shape      = $args->{'node_shape'};
89     my $output_type     = $args->{'output_type'};
90     my $add_color       = $args->{'add_color'};
91     my $natural_join    = $args->{'natural_join'};
92     my $join_pk_only    = $args->{'join_pk_only'};
93     my $skip_fields     = $args->{'skip_fields'};
94     my %skip            = map { s/^\s+|\s+$//g; $_, 1 }
95                           split ( /,/, $skip_fields );
96     $natural_join     ||= $join_pk_only;
97
98     die "Invalid layout '$layout'" unless VALID_LAYOUT->{ $layout };
99     die "Invalid output type: '$output_type'"
100         unless VALID_OUTPUT->{ $output_type };
101     die "Invalid node shape'$node_shape'" 
102         unless VALID_NODE_SHAPE->{ $node_shape };
103
104     #
105     # Create GraphViz and see if we can produce the output type.
106     #
107     my $gv            =  GraphViz->new(
108         directed      => $natural_join ? 0 : 1,
109         layout        => $layout,
110         no_overlap    => 1,
111         bgcolor       => $add_color ? 'lightgoldenrodyellow' : 'white',
112         node          => { 
113             shape     => $node_shape, 
114             style     => 'filled', 
115             fillcolor => 'white' 
116         },
117     ) or die "Can't create GraphViz object\n";
118
119     my %nj_registry; # for locations of fields for natural joins
120     my @fk_registry; # for locations of fields for foreign keys
121
122     #
123     # If necessary, pre-process fields to find foreign keys.
124     #
125     if ( $natural_join ) {
126         my ( %common_keys, %pk );
127         for my $table ( values %$data ) {
128             for my $index ( 
129                 @{ $table->{'indices'}     || [] },
130                 @{ $table->{'constraints'} || [] },
131             ) {
132                 my @fields = @{ $index->{'fields'} || [] } or next;
133                 if ( $index->{'type'} eq 'primary_key' ) {
134                     $pk{ $_ } = 1 for @fields;
135                 }
136             }
137
138             for my $field ( values %{ $table->{'fields'} } ) {
139                 push @{ $common_keys{ $field->{'name'} } }, 
140                     $table->{'table_name'};
141             }
142         }
143
144         for my $field ( keys %common_keys ) {
145             my @tables = @{ $common_keys{ $field } };
146             next unless scalar @tables > 1;
147             for my $table ( @tables ) {
148                 next if $join_pk_only and !defined $pk{ $field };
149                 $data->{ $table }{'fields'}{ $field }{'is_fk'} = 1;
150             }
151         }
152     }
153     else {
154         for my $table ( values %$data ) {
155             for my $field ( values %{ $table->{'fields'} } ) {
156                 for my $constraint ( 
157                     grep { $_->{'type'} eq 'foreign_key' }
158                     @{ $field->{'constraints'} }
159                 ) {
160                     my $ref_table  = $constraint->{'reference_table'} or next;
161                     my @ref_fields = @{ $constraint->{'reference_fields'}||[] };
162
163                     unless ( @ref_fields ) {
164                         for my $field ( 
165                             values %{ $data->{ $ref_table }{'fields'} } 
166                         ) {
167                             for my $pk (
168                                 grep { $_->{'type'} eq 'primary_key' }
169                                 @{ $field->{'constraints'} }
170                             ) {
171                                 push @ref_fields, @{ $pk->{'fields'} };
172                             }
173                         }
174
175                         $constraint->{'reference_fields'} = [ @ref_fields ];
176                     }
177
178                     for my $ref_field (@{$constraint->{'reference_fields'}}) {
179                         $data->{$ref_table}{'fields'}{$ref_field}{'is_fk'} = 1;
180                     }
181                 }
182             }
183         }
184     }
185
186     for my $table (
187         map  { $_->[1] }
188         sort { $a->[0] <=> $b->[0] }
189         map  { [ $_->{'order'}, $_ ] }
190         values %$data 
191     ) {
192         my $table_name = $table->{'table_name'};
193         $gv->add_node( $table_name );
194
195         debug("Processing table '$table_name'");
196
197         my @fields = 
198             map  { $_->[1] }
199             sort { $a->[0] <=> $b->[0] }
200             map  { [ $_->{'order'}, $_ ] }
201             values %{ $table->{'fields'} };
202
203         debug("Fields = ", join(', ', map { $_->{'name'} } @fields));
204
205         my ( %pk, %unique );
206         for my $index ( 
207             @{ $table->{'indices'}     || [] },
208             @{ $table->{'constraints'} || [] },
209         ) {
210             my @fields = @{ $index->{'fields'} || [] } or next;
211             if ( $index->{'type'} eq 'primary_key' ) {
212                 $pk{ $_ } = 1 for @fields;
213             }
214             elsif ( $index->{'type'} eq 'unique' ) {
215                 $unique{ $_ } = 1 for @fields;
216             }
217         }
218
219         debug("Primary keys = ", join(', ', sort keys %pk));
220         debug("Unique = ", join(', ', sort keys %unique));
221
222         for my $f ( @fields ) {
223             my $name      = $f->{'name'} or next;
224             my $is_pk     = $pk{ $name };
225             my $is_unique = $unique{ $name };
226
227             #
228             # Decide if we should skip this field.
229             #
230             if ( $natural_join ) {
231                 next unless $is_pk || $f->{'is_fk'};
232             }
233             else {
234                 next unless $is_pk ||
235                     grep { $_->{'type'} eq 'foreign_key' }
236                     @{ $f->{'constraints'} }
237                 ;
238             }
239
240             my $constraints = $f->{'constraints'};
241
242             if ( $natural_join && !$skip{ $name } ) {
243                 push @{ $nj_registry{ $name } }, $table_name;
244             }
245             elsif ( @{ $constraints || [] } ) {
246                 for my $constraint ( @$constraints ) {
247                     next unless $constraint->{'type'} eq 'foreign_key';
248                     for my $fk_field ( 
249                         @{ $constraint->{'reference_fields'} || [] }
250                     ) {
251                         my $fk_table = $constraint->{'reference_table'};
252                         next unless defined $data->{ $fk_table };
253                         push @fk_registry, [ $table_name, $fk_table ];
254                     }
255                 }
256             }
257         }
258     }
259
260     #
261     # Make the connections.
262     #
263     my @table_bunches;
264     if ( $natural_join ) {
265         for my $field_name ( keys %nj_registry ) {
266             my @table_names = @{ $nj_registry{ $field_name } || [] } or next;
267             next if scalar @table_names == 1;
268             push @table_bunches, [ @table_names ];
269         }
270     }
271     else {
272         @table_bunches = @fk_registry;
273     }
274
275     my %done;
276     for my $bunch ( @table_bunches ) {
277         my @tables = @$bunch;
278
279         for my $i ( 0 .. $#tables ) {
280             my $table1 = $tables[ $i ];
281             for my $j ( 0 .. $#tables ) {
282                 my $table2 = $tables[ $j ];
283                 next if $table1 eq $table2;
284                 next if $done{ $table1 }{ $table2 };
285                 $gv->add_edge( $table1, $table2 );
286                 $done{ $table1 }{ $table2 } = 1;
287                 $done{ $table2 }{ $table1 } = 1;
288             }
289         }
290     }
291
292     #
293     # Print the image.
294     #
295     my $output_method = "as_$output_type";
296     if ( $out_file ) {
297         open my $fh, ">$out_file" or die "Can't write '$out_file': $!\n";
298         print $fh $gv->$output_method;
299         close $fh;
300     }
301     else {
302         return $gv->$output_method;
303     }
304 }
305
306 1;
307
308 =pod
309
310 =head1 NAME
311
312 SQL::Translator::Producer::GraphViz - GraphViz producer for SQL::Translator
313
314 =head1 AUTHOR
315
316 Ken Y. Clark E<lt>kclark@cpan.orgE<gt>
317
318 =cut