1 package SQL::Translator::Producer::Diagram;
3 # -------------------------------------------------------------------
4 # $Id: Diagram.pm,v 1.2 2003-04-24 19:40:52 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::Utils qw(debug);
28 use vars qw[ $VERSION $DEBUG ];
29 $VERSION = sprintf "%d.%02d", q$Revision: 1.2 $ =~ /(\d+)\.(\d+)/;
30 $DEBUG = 0 unless defined $DEBUG;
32 use constant VALID_FONT_SIZE => {
39 use constant VALID_IMAGE_TYPE => {
46 my $args = $t->producer_args;
47 local $DEBUG = $t->debug;
48 debug("Data =\n", Dumper( $data ));
49 debug("Producer args =\n", Dumper( $args ));
51 my $out_file = $args->{'out_file'} || '';
52 my $image_type = $args->{'image_type'} || 'png';
53 my $title = $args->{'title'} || $t->filename;
54 my $font_size = $args->{'font_size'} || 'medium';
55 my $no_columns = $args->{'no_columns'};
56 my $no_lines = $args->{'no_lines'};
57 my $add_color = $args->{'add_color'};
58 my $show_fk_only = $args->{'show_fk_only'};
59 my $join_pk_only = $args->{'join_pk_only'};
60 my $natural_join = $args->{'natural_join'} || $join_pk_only;
61 my $skip_fields = $args->{'skip_fields'};
62 my %skip = map { $_, 1 } split ( /,/, $skip_fields );
64 die "Invalid image type '$image_type'"
65 unless VALID_IMAGE_TYPE ->{ $image_type };
66 die "Invalid font size '$font_size'"
67 unless VALID_FONT_SIZE->{ $font_size };
73 $font_size eq 'small' ? gdTinyFont :
74 $font_size eq 'medium' ? gdSmallFont :
75 $font_size eq 'large' ? gdLargeFont : gdGiantFont;
76 my $no_tables = scalar keys %$data;
77 $no_columns = 0 unless $no_columns =~ /^\d+$/;
78 $no_columns ||= sprintf( "%.0f", sqrt( $no_tables ) + .5 );
80 my $no_per_col = sprintf( "%.0f", $no_tables/$no_columns + .5 );
83 my ( $max_x, $max_y ); # the furthest x and y used
84 my $orig_y = 40; # used to reset y for each column
85 my ( $x, $y ) = (30,$orig_y); # where to start
86 my $cur_col = 1; # the current column
87 my $no_this_col = 0; # number of tables in current column
88 my $this_col_x = $x; # current column's x
89 my $gutter = 30; # distance b/w columns
90 my %nj_registry; # for locations of fields for natural joins
91 my @fk_registry; # for locations of fields for foreign keys
92 my %table_x; # for max x of each table
93 my $field_no; # counter to give distinct no. to each field
97 # If necessary, pre-process fields to find foreign keys.
99 if ( $show_fk_only && $natural_join ) {
100 my ( %common_keys, %pk );
101 for my $table ( values %$data ) {
103 @{ $table->{'indices'} || [] },
104 @{ $table->{'constraints'} || [] },
106 my @fields = @{ $index->{'fields'} || [] } or next;
107 if ( $index->{'type'} eq 'primary_key' ) {
108 $pk{ $_ } = 1 for @fields;
112 for my $field ( values %{ $table->{'fields'} } ) {
113 push @{ $common_keys{ $field->{'name'} } },
114 $table->{'table_name'};
118 for my $field ( keys %common_keys ) {
119 my @tables = @{ $common_keys{ $field } };
120 next unless scalar @tables > 1;
121 for my $table ( @tables ) {
122 next if $join_pk_only and !defined $pk{ $field };
123 $data->{ $table }{'fields'}{ $field }{'is_fk'} = 1;
128 for my $table ( values %$data ) {
129 for my $field ( values %{ $table->{'fields'} } ) {
131 grep { $_->{'type'} eq 'foreign_key' }
132 @{ $field->{'constraints'} }
134 my $ref_table = $constraint->{'reference_table'} or next;
135 my @ref_fields = @{$constraint->{'reference_fields'} || []};
137 unless ( @ref_fields ) {
139 values %{ $data->{ $ref_table }{'fields'} }
142 grep { $_->{'type'} eq 'primary_key' }
143 @{ $field->{'constraints'} }
145 push @ref_fields, @{ $pk->{'fields'} };
149 $constraint->{'reference_fields'} = [ @ref_fields ];
153 @{ $constraint->{'reference_fields'} }
155 $data->{$ref_table}{'fields'}{$ref_field}{'is_fk'} = 1;
165 sort { $a->[0] <=> $b->[0] }
166 map { [ $_->{'order'}, $_ ] }
169 my $table_name = $table->{'table_name'};
172 [ 'string', $font, $this_col_x, $y, $table_name, 'black' ];
174 $y += $font->height + 2;
175 my $below_table_name = $y;
178 $this_col_x + ($font->width * length($table_name));
180 debug("Processing table '$table_name'");
184 sort { $a->[0] <=> $b->[0] }
185 map { [ $_->{'order'}, $_ ] }
186 values %{ $table->{'fields'} };
188 debug("Fields = ", join(', ', map { $_->{'name'} } @fields));
192 @{ $table->{'indices'} || [] },
193 @{ $table->{'constraints'} || [] },
195 my @fields = @{ $index->{'fields'} || [] } or next;
196 if ( $index->{'type'} eq 'primary_key' ) {
197 $pk{ $_ } = 1 for @fields;
199 elsif ( $index->{'type'} eq 'unique' ) {
200 $unique{ $_ } = 1 for @fields;
204 debug("PK = ", join(', ', sort keys %pk)) if %pk;
205 debug("Unique = ", join(', ', sort keys %unique)) if %unique;
207 my ( @fld_desc, $max_name );
208 for my $f ( @fields ) {
209 my $name = $f->{'name'} or next;
210 my $is_pk = $pk{ $name };
211 my $is_unique = $unique{ $name };
214 # Decide if we should skip this field.
216 if ( $show_fk_only ) {
217 if ( $natural_join ) {
218 next unless $is_pk || $f->{'is_fk'};
221 next unless $is_pk || $f->{'is_fk'} ||
222 grep { $_->{'type'} eq 'foreign_key' }
223 @{ $f->{'constraints'} }
230 $legend{'Primary key'} = '*';
232 elsif ( $is_unique ) {
234 $legend{'Unique constraint'} = '[U]';
237 my $size = @{ $f->{'size'} || [] }
238 ? '(' . join( ',', @{ $f->{'size'} } ) . ')'
240 my $desc = join( ' ', map { $_ || () } $f->{'data_type'}, $size );
242 my $nlen = length $name;
243 $max_name = $nlen if $nlen > $max_name;
244 push @fld_desc, [ $name, $desc, $f->{'name'}, $is_pk ];
248 for my $fld_desc ( @fld_desc ) {
249 my ( $name, $desc, $orig_name, $is_pk ) = @$fld_desc;
250 my $diff = $max_name - length $name;
251 $name .= ' ' x $diff;
252 $desc = $name . $desc;
254 push @shapes, [ 'string', $font, $this_col_x, $y, $desc, 'black' ];
255 $y += $font->height + 2;
256 my $length = $this_col_x + ( $font->width * length( $desc ) );
257 $this_max_x = $length if $length > $this_max_x;
259 my $constraints = $table->{'fields'}{ $orig_name }{'constraints'};
261 if ( $natural_join && !$skip{ $orig_name } ) {
262 push @{ $nj_registry{ $orig_name } }, $table_name;
264 elsif ( @{ $constraints || [] } ) {
265 for my $constraint ( @$constraints ) {
266 next unless $constraint->{'type'} eq 'foreign_key';
268 @{ $constraint->{'reference_fields'} || [] }
270 my $fk_table = $constraint->{'reference_table'};
271 next unless defined $data->{ $fk_table };
273 [ $table_name, $orig_name ],
274 [ $fk_table , $fk_field ],
280 my $y_link = $y - $font->height/2;
281 $table->{'fields'}{ $orig_name }{'coords'} = {
282 left => [ $this_col_x - 6, $y_link ],
283 right => [ $length + 2 , $y_link ],
284 table => $table_name,
285 field_no => ++$field_no,
287 fld_name => $orig_name,
292 $table_x{ $table_name } = $this_max_x + 5;
293 push @shapes, [ 'line', $this_col_x - 5, $below_table_name,
294 $this_max_x, $below_table_name, 'black' ];
295 my @bounds = ( $this_col_x - 5, $top - 5, $this_max_x, $y + 5 );
299 $bounds[0], $bounds[1],
300 $this_max_x, $below_table_name,
303 unshift @shapes, [ 'filledRectangle', @bounds, 'white' ];
305 push @shapes, [ 'rectangle', @bounds, 'black' ];
306 $max_x = $this_max_x if $this_max_x > $max_x;
309 if ( ++$no_this_col == $no_per_col ) {# if we've filled up this column
310 $cur_col++; # up the column number
311 $no_this_col = 0; # reset the number of tables
312 $max_x += $gutter; # push the x over for next column
313 $this_col_x = $max_x; # remember the max x for this col
314 $max_y = $y if $y > $max_y; # note the max y
315 $y = $orig_y; # reset the y for next column
324 unless ( $no_lines ) {
325 my @position_bunches;
327 if ( $natural_join ) {
328 for my $field_name ( keys %nj_registry ) {
331 @{ $nj_registry{ $field_name } || [] } or next;
332 next if scalar @table_names == 1;
334 for my $table_name ( @table_names ) {
336 $data->{$table_name}{'fields'}{ $field_name }{'coords'};
339 push @position_bunches, [ @positions ];
343 for my $pair ( @fk_registry ) {
344 push @position_bunches, [
345 $data->{$pair->[0][0]}{'fields'}{ $pair->[0][1] }{'coords'},
346 $data->{$pair->[1][0]}{'fields'}{ $pair->[1][1] }{'coords'},
351 my $is_directed = $natural_join ? 0 : 1;
353 for my $bunch ( @position_bunches ) {
354 my @positions = @$bunch;
356 for my $i ( 0 .. $#positions ) {
357 my $pos1 = $positions[ $i ];
358 my ( $ax, $ay ) = @{ $pos1->{'left'} || [] } or next;
359 my ( $bx, $by ) = @{ $pos1->{'right'} || [] } or next;
360 my $table1 = $pos1->{'table'};
361 my $fno1 = $pos1->{'field_no'};
362 my $is_pk = $pos1->{'is_pk'};
363 next if $join_pk_only and !$is_pk;
365 for my $j ( 0 .. $#positions ) {
366 my $pos2 = $positions[ $j ];
367 my ( $cx, $cy ) = @{ $pos2->{'left'} || [] } or next;
368 my ( $dx, $dy ) = @{ $pos2->{'right'} || [] } or next;
369 my $table2 = $pos2->{'table'};
370 my $fno2 = $pos2->{'field_no'};
371 next if $table1 eq $table2;
372 next if $done{ $fno1 }{ $fno2 };
373 next if $fno1 == $fno2;
377 abs ( $ax - $cx ) + abs ( $ay - $cy ),
378 [ $ax, $ay, $cx, $cy ],
382 abs ( $ax - $dx ) + abs ( $ay - $dy ),
383 [ $ax, $ay, $dx, $dy ],
387 abs ( $bx - $cx ) + abs ( $by - $cy ),
388 [ $bx, $by, $cx, $cy ],
392 abs ( $bx - $dx ) + abs ( $by - $dy ),
393 [ $bx, $by, $dx, $dy ],
394 [ 'right', 'right' ],
396 @distances = sort { $a->[0] <=> $b->[0] } @distances;
397 my $shortest = $distances[0];
398 my ( $x1, $y1, $x2, $y2 ) = @{ $shortest->[1] };
399 my ( $side1, $side2 ) = @{ $shortest->[2] };
402 my $col1_right = $table_x{ $table1 };
403 my $col2_right = $table_x{ $table2 };
407 while ( $horz_taken{ $x1 + $diff } ) {
408 $diff = $side1 eq 'left' ? $diff - 2 : $diff + 2;
410 $horz_taken{ $x1 + $diff } = 1;
413 if ( $side1 eq 'left' ) {
414 $start = $x1 - $offset + $diff;
417 $start = $col1_right + $diff;
420 if ( $side2 eq 'left' ) {
421 $end = $x2 - $offset + $diff;
424 $end = $col2_right + $diff;
428 [ 'line', $x1, $y1, $start, $y1, 'cadetblue' ];
430 [ 'line', $start, $y1, $end, $y2, 'cadetblue' ];
432 [ 'line', $end, $y2, $x2, $y2, 'cadetblue' ];
434 if ( $is_directed ) {
436 $side1 eq 'right' && $side2 eq 'left'
438 $side1 eq 'left' && $side2 eq 'left'
441 'line', $x2 - 3, $y2 - 3, $x2, $y2, 'cadetblue'
444 'line', $x2 - 3, $y2 + 3, $x2, $y2, 'cadetblue'
447 'line', $x2 - 3, $y2 - 3, $x2 - 3, $y2 +3,
453 'line', $x2 + 3, $y2 - 3, $x2, $y2, 'cadetblue'
456 'line', $x2 + 3, $y2 + 3, $x2, $y2, 'cadetblue'
459 'line', $x2 + 3, $y2 - 3, $x2 + 3, $y2 +3,
465 $done{ $fno1 }{ $fno2 } = 1;
466 $done{ $fno2 }{ $fno1 } = 1;
473 # Add the title, legend and signature.
475 my $large_font = gdLargeFont;
476 my $title_len = $large_font->width * length $title;
478 'string', $large_font, $max_x/2 - $title_len/2, 10, $title, 'black'
484 'string', $font, $x, $max_y - $font->height - 4, 'Legend', 'black'
486 $max_y += $font->height + 4;
489 for my $len ( map { length $_ } values %legend ) {
490 $longest = $len if $len > $longest;
494 while ( my ( $key, $shape ) = each %legend ) {
495 my $space = $longest - length $shape;
497 'string', $font, $x, $max_y - $font->height - 4,
498 join( '', $shape, ' ' x $space, $key ), 'black'
501 $max_y += $font->height + 4;
505 my $sig = __PACKAGE__." $VERSION";
506 my $sig_len = $font->width * length $sig;
508 'string', $font, $max_x - $sig_len, $max_y - $font->height - 4,
515 my $gd = GD::Image->new( $max_x + 30, $max_y );
516 unless ( $gd->can( $image_type ) ) {
517 die "GD can't create images of type '$image_type'\n";
519 my %colors = map { $_->[0], $gd->colorAllocate( @{$_->[1]} ) } (
520 [ white => [ 255, 255, 255 ] ],
521 [ beige => [ 245, 245, 220 ] ],
522 [ black => [ 0, 0, 0 ] ],
523 [ lightblue => [ 173, 216, 230 ] ],
524 [ cadetblue => [ 95, 158, 160 ] ],
525 [ lightgoldenrodyellow => [ 250, 250, 210 ] ],
526 [ khaki => [ 240, 230, 140 ] ],
527 [ red => [ 255, 0, 0 ] ],
529 $gd->interlaced( 'true' );
530 my $background_color = $add_color ? 'lightgoldenrodyellow' : 'white';
531 $gd->fill( 0, 0, $colors{ $background_color } );
532 for my $shape ( @shapes ) {
533 my $method = shift @$shape;
534 my $color = pop @$shape;
535 $gd->$method( @$shape, $colors{ $color } );
542 open my $fh, ">$out_file" or die "Can't write '$out_file': $!\n";
543 print $fh $gd->$image_type;
547 return $gd->$image_type;
557 SQL::Translator::Producer::Diagram - ER diagram producer for SQL::Translator
561 Ken Y. Clark E<lt>kclark@cpan.orgE<gt>