1 package SQL::Translator::Producer::Diagram;
3 # -------------------------------------------------------------------
4 # $Id: Diagram.pm,v 1.7 2003-08-27 03:44:08 kycl4rk Exp $
5 # -------------------------------------------------------------------
6 # Copyright (C) 2003 Ken Y. Clark <kclark@cpan.org>
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.
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.
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
21 # -------------------------------------------------------------------
26 use SQL::Translator::Schema::Constants;
27 use SQL::Translator::Utils qw(debug);
29 use vars qw[ $VERSION $DEBUG ];
30 $VERSION = sprintf "%d.%02d", q$Revision: 1.7 $ =~ /(\d+)\.(\d+)/;
31 $DEBUG = 0 unless defined $DEBUG;
33 use constant VALID_FONT_SIZE => {
40 use constant VALID_IMAGE_TYPE => {
47 my $schema = $t->schema;
48 my $args = $t->producer_args;
49 local $DEBUG = $t->debug;
50 debug("Schema =\n", Dumper( $schema ));
51 debug("Producer args =\n", Dumper( $args ));
53 my $out_file = $args->{'out_file'} || '';
54 my $output_type = $args->{'output_type'} || 'png';
55 my $title = $args->{'title'} || $t->filename;
56 my $font_size = $args->{'font_size'} || 'medium';
57 my $imap_file = $args->{'imap_file'} || '';
58 my $imap_url = $args->{'imap_url'} || '';
59 my $no_columns = $args->{'no_columns'};
60 my $no_lines = $args->{'no_lines'};
61 my $add_color = $args->{'add_color'};
62 my $show_fk_only = $args->{'show_fk_only'};
63 my $join_pk_only = $args->{'join_pk_only'};
64 my $natural_join = $args->{'natural_join'} || $join_pk_only;
65 my $skip_fields = $args->{'skip_fields'};
66 my %skip = map { s/^\s+|\s+$//g; $_,1 } split (/,/, $skip_fields);
68 $schema->make_natural_joins(
69 join_pk_only => $join_pk_only,
70 skip_fields => $args->{'skip_fields'},
73 die "Invalid image type '$output_type'"
74 unless VALID_IMAGE_TYPE ->{ $output_type };
75 die "Invalid font size '$font_size'"
76 unless VALID_FONT_SIZE->{ $font_size };
82 $font_size eq 'small' ? gdTinyFont :
83 $font_size eq 'medium' ? gdSmallFont :
84 $font_size eq 'large' ? gdLargeFont : gdGiantFont;
85 my @tables = $schema->get_tables;
86 my $no_tables = scalar @tables;
87 $no_columns = 0 unless $no_columns =~ /^\d+$/;
88 $no_columns ||= sprintf( "%.0f", sqrt( $no_tables ) + .5 );
90 my $no_per_col = sprintf( "%.0f", $no_tables/$no_columns + .5 );
93 my ( $max_x, $max_y ); # the furthest x and y used
94 my $orig_y = 40; # used to reset y for each column
95 my ( $x, $y ) = (30,$orig_y); # where to start
96 my $cur_col = 1; # the current column
97 my $no_this_col = 0; # number of tables in current column
98 my $this_col_x = $x; # current column's x
99 my $gutter = 30; # distance b/w columns
100 my %nj_registry; # for locations of fields for natural joins
101 my @fk_registry; # for locations of fields for foreign keys
102 my %table_x; # for max x of each table
103 my $field_no; # counter to give distinct no. to each field
104 my %coords; # holds fields coordinates
105 my @imap_coords; # for making clickable image map
108 for my $table ( @tables ) {
109 my $table_name = $table->name;
112 [ 'string', $font, $this_col_x, $y, $table_name, 'black' ];
113 $y += $font->height + 2;
114 my $below_table_name = $y;
117 $this_col_x + ($font->width * length($table_name));
119 debug("Processing table '$table_name'");
121 my @fields = $table->get_fields;
122 debug("Fields = ", join(', ', map { $_->name } @fields));
124 my ( @fld_desc, $max_name );
125 for my $f ( @fields ) {
126 my $name = $f->name or next;
127 my $is_pk = $f->is_primary_key;
130 # Decide if we should skip this field.
132 if ( $show_fk_only ) {
133 next unless $is_pk || $f->is_foreign_key;
138 $legend{'Primary key'} = '*';
141 if ( $f->is_unique ) {
143 $legend{'Unique constraint'} = '[U]';
146 my $desc = $f->data_type;
147 $desc .= '('.$f->size.')' if $f->size;
149 my $nlen = length $name;
150 $max_name = $nlen if $nlen > $max_name;
151 push @fld_desc, [ $name, $desc, $f->{'name'}, $is_pk ];
155 for my $fld_desc ( @fld_desc ) {
156 my ( $name, $desc, $orig_name, $is_pk ) = @$fld_desc;
157 my $diff = $max_name - length $name;
158 $name .= ' ' x $diff;
159 $desc = $name . $desc;
161 push @shapes, [ 'string', $font, $this_col_x, $y, $desc, 'black' ];
162 $y += $font->height + 2;
163 my $length = $this_col_x + ( $font->width * length( $desc ) );
164 $this_max_x = $length if $length > $this_max_x;
166 my $constraints = $table->{'fields'}{ $orig_name }{'constraints'};
168 if ( $natural_join && !$skip{ $orig_name } ) {
169 push @{ $nj_registry{ $orig_name } }, $table_name;
172 my $y_link = $y - $font->height/2;
173 $coords{ $table_name }{ $orig_name }{'coords'} = {
174 left => [ $this_col_x - 6, $y_link ],
175 right => [ $length + 2 , $y_link ],
176 table => $table_name,
177 field_no => ++$field_no,
179 fld_name => $orig_name,
183 $imap_url."#$table_name-$orig_name",
184 $this_col_x, $y - $font->height, $length, $y_link,
188 unless ( $natural_join ) {
189 for my $c ( $table->get_constraints ) {
190 next unless $c->type eq FOREIGN_KEY;
191 my $fk_table = $c->reference_table or next;
193 for my $field_name ( $c->fields ) {
194 for my $fk_field ( $c->reference_fields ) {
195 next unless defined $schema->get_table( $fk_table );
197 [ $fk_table , $fk_field ],
198 [ $table_name, $field_name ],
206 $table_x{ $table_name } = $this_max_x + 5;
207 push @shapes, [ 'line', $this_col_x - 5, $below_table_name,
208 $this_max_x, $below_table_name, 'black' ];
209 my @bounds = ( $this_col_x - 5, $top - 5, $this_max_x, $y + 5 );
213 $bounds[0], $bounds[1],
214 $this_max_x, $below_table_name,
217 unshift @shapes, [ 'filledRectangle', @bounds, 'white' ];
221 $imap_url."#$table_name",
222 $bounds[0], $bounds[1], $this_max_x, $below_table_name,
225 push @shapes, [ 'rectangle', @bounds, 'black' ];
226 $max_x = $this_max_x if $this_max_x > $max_x;
229 if ( ++$no_this_col == $no_per_col ) {# if we've filled up this column
230 $cur_col++; # up the column number
231 $no_this_col = 0; # reset the number of tables
232 $max_x += $gutter; # push the x over for next column
233 $this_col_x = $max_x; # remember the max x for this col
234 $max_y = $y if $y > $max_y; # note the max y
235 $y = $orig_y; # reset the y for next column
244 unless ( $no_lines ) {
245 my @position_bunches;
247 if ( $natural_join ) {
248 for my $field_name ( keys %nj_registry ) {
251 @{ $nj_registry{ $field_name } || [] } or next;
252 next if scalar @table_names == 1;
254 for my $table_name ( @table_names ) {
256 $coords{ $table_name }{ $field_name }{'coords'};
259 push @position_bunches, [ @positions ];
263 for my $pair ( @fk_registry ) {
264 push @position_bunches, [
265 $coords{$pair->[0][0]}{ $pair->[0][1] }{'coords'},
266 $coords{$pair->[1][0]}{ $pair->[1][1] }{'coords'},
271 my $is_directed = $natural_join ? 0 : 1;
273 for my $bunch ( @position_bunches ) {
274 my @positions = @$bunch;
276 for my $i ( 0 .. $#positions ) {
277 my $pos1 = $positions[ $i ];
278 my ( $ax, $ay ) = @{ $pos1->{'left'} || [] } or next;
279 my ( $bx, $by ) = @{ $pos1->{'right'} || [] } or next;
280 my $table1 = $pos1->{'table'};
281 my $fno1 = $pos1->{'field_no'};
282 my $is_pk = $pos1->{'is_pk'};
283 next if $join_pk_only and !$is_pk;
285 for my $j ( 0 .. $#positions ) {
286 my $pos2 = $positions[ $j ];
287 my ( $cx, $cy ) = @{ $pos2->{'left'} || [] } or next;
288 my ( $dx, $dy ) = @{ $pos2->{'right'} || [] } or next;
289 my $table2 = $pos2->{'table'};
290 my $fno2 = $pos2->{'field_no'};
291 next if $table1 eq $table2;
292 next if $done{ $fno1 }{ $fno2 };
293 next if $fno1 == $fno2;
297 abs ( $ax - $cx ) + abs ( $ay - $cy ),
298 [ $ax, $ay, $cx, $cy ],
302 abs ( $ax - $dx ) + abs ( $ay - $dy ),
303 [ $ax, $ay, $dx, $dy ],
307 abs ( $bx - $cx ) + abs ( $by - $cy ),
308 [ $bx, $by, $cx, $cy ],
312 abs ( $bx - $dx ) + abs ( $by - $dy ),
313 [ $bx, $by, $dx, $dy ],
314 [ 'right', 'right' ],
316 @distances = sort { $a->[0] <=> $b->[0] } @distances;
317 my $shortest = $distances[0];
318 my ( $x1, $y1, $x2, $y2 ) = @{ $shortest->[1] };
319 my ( $side1, $side2 ) = @{ $shortest->[2] };
322 my $col1_right = $table_x{ $table1 };
323 my $col2_right = $table_x{ $table2 };
327 while ( $horz_taken{ $x1 + $diff } ) {
328 $diff = $side1 eq 'left' ? $diff - 2 : $diff + 2;
330 $horz_taken{ $x1 + $diff } = 1;
333 if ( $side1 eq 'left' ) {
334 $start = $x1 - $offset + $diff;
337 $start = $col1_right + $diff;
340 if ( $side2 eq 'left' ) {
341 $end = $x2 - $offset + $diff;
344 $end = $col2_right + $diff;
348 [ 'line', $x1, $y1, $start, $y1, 'cadetblue' ];
350 [ 'line', $start, $y1, $end, $y2, 'cadetblue' ];
352 [ 'line', $end, $y2, $x2, $y2, 'cadetblue' ];
354 if ( $is_directed ) {
356 $side1 eq 'right' && $side2 eq 'left'
358 $side1 eq 'left' && $side2 eq 'left'
361 'line', $x2 - 3, $y2 - 3, $x2, $y2, 'cadetblue'
364 'line', $x2 - 3, $y2 + 3, $x2, $y2, 'cadetblue'
367 'line', $x2 - 3, $y2 - 3, $x2 - 3, $y2 +3,
373 'line', $x2 + 3, $y2 - 3, $x2, $y2, 'cadetblue'
376 'line', $x2 + 3, $y2 + 3, $x2, $y2, 'cadetblue'
379 'line', $x2 + 3, $y2 - 3, $x2 + 3, $y2 +3,
385 $done{ $fno1 }{ $fno2 } = 1;
386 $done{ $fno2 }{ $fno1 } = 1;
393 # Add the title, legend and signature.
395 my $large_font = gdLargeFont;
396 my $title_len = $large_font->width * length $title;
398 'string', $large_font, $max_x/2 - $title_len/2, 10, $title, 'black'
404 'string', $font, $x, $max_y - $font->height - 4, 'Legend', 'black'
406 $max_y += $font->height + 4;
409 for my $len ( map { length $_ } values %legend ) {
410 $longest = $len if $len > $longest;
414 while ( my ( $key, $shape ) = each %legend ) {
415 my $space = $longest - length $shape;
417 'string', $font, $x, $max_y - $font->height - 4,
418 join( '', $shape, ' ' x $space, $key ), 'black'
421 $max_y += $font->height + 4;
425 my $sig = __PACKAGE__." $VERSION";
426 my $sig_len = $font->width * length $sig;
428 'string', $font, $max_x - $sig_len, $max_y - $font->height - 4,
435 my $gd = GD::Image->new( $max_x + 30, $max_y );
436 unless ( $gd->can( $output_type ) ) {
437 die "GD can't create images of type '$output_type'\n";
439 my %colors = map { $_->[0], $gd->colorAllocate( @{$_->[1]} ) } (
440 [ white => [ 255, 255, 255 ] ],
441 [ beige => [ 245, 245, 220 ] ],
442 [ black => [ 0, 0, 0 ] ],
443 [ lightblue => [ 173, 216, 230 ] ],
444 [ cadetblue => [ 95, 158, 160 ] ],
445 [ lightgoldenrodyellow => [ 250, 250, 210 ] ],
446 [ khaki => [ 240, 230, 140 ] ],
447 [ red => [ 255, 0, 0 ] ],
449 $gd->interlaced( 'true' );
450 my $background_color = $add_color ? 'lightgoldenrodyellow' : 'white';
451 $gd->fill( 0, 0, $colors{ $background_color } );
452 for my $shape ( @shapes ) {
453 my $method = shift @$shape;
454 my $color = pop @$shape;
455 $gd->$method( @$shape, $colors{ $color } );
461 debug("imap file = '$imap_file'");
462 if ( $imap_file && @imap_coords ) {
463 open my $fh, ">$imap_file" or die "Can't write '$imap_file': $!\n";
464 print $fh qq[<html><body><img src="" usemap="#imap" border="0">\n].
465 qq[<map name="imap">\n];
466 for my $rec ( @imap_coords ) {
467 my $href = shift @$rec;
468 print $fh q[<area coords="].join(',', @$rec).qq[" href="$href">\n];
470 print $fh qq[</body></html>];
478 open my $fh, ">$out_file" or die "Can't write '$out_file': $!\n";
479 print $fh $gd->$output_type;
483 return $gd->$output_type;
493 SQL::Translator::Producer::Diagram - ER diagram producer for SQL::Translator
497 Ken Y. Clark E<lt>kclark@cpan.orgE<gt>