1 package SQL::Translator::Producer::Diagram;
3 # -------------------------------------------------------------------
4 # $Id: Diagram.pm,v 1.12 2004-08-30 19:04:59 kycl4rk Exp $
5 # -------------------------------------------------------------------
6 # Copyright (C) 2002-4 SQLFairy Authors
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 # -------------------------------------------------------------------
25 SQL::Translator::Producer::Diagram - ER diagram producer for SQL::Translator
29 Use via SQL::Translator:
33 my $t = SQL::Translator->new( producer => 'Diagram', '...' );
41 use SQL::Translator::Schema::Constants;
42 use SQL::Translator::Utils qw(debug);
44 use vars qw[ $VERSION $DEBUG ];
45 $VERSION = sprintf "%d.%02d", q$Revision: 1.12 $ =~ /(\d+)\.(\d+)/;
46 $DEBUG = 0 unless defined $DEBUG;
48 use constant VALID_FONT_SIZE => {
55 use constant VALID_IMAGE_TYPE => {
62 my $schema = $t->schema;
63 my $args = $t->producer_args;
64 local $DEBUG = $t->debug;
65 debug("Schema =\n", Dumper( $schema ));
66 debug("Producer args =\n", Dumper( $args ));
68 my $out_file = $args->{'out_file'} || '';
69 my $output_type = $args->{'output_type'} || 'png';
70 my $title = $args->{'title'} || $t->filename;
71 my $font_size = $args->{'font_size'} || 'medium';
72 my $imap_file = $args->{'imap_file'} || '';
73 my $imap_url = $args->{'imap_url'} || '';
74 my $gutter = $args->{'gutter'} || 30; # distance b/w columns
75 my $no_columns = $args->{'no_columns'};
76 my $no_lines = $args->{'no_lines'};
77 my $add_color = $args->{'add_color'};
78 my $show_fk_only = $args->{'show_fk_only'};
79 my $join_pk_only = $args->{'join_pk_only'};
80 my $natural_join = $args->{'natural_join'} || $join_pk_only;
81 my $skip_fields = $args->{'skip_fields'};
82 my %skip = map { s/^\s+|\s+$//g; $_,1 } split (/,/, $skip_fields);
84 $schema->make_natural_joins(
85 join_pk_only => $join_pk_only,
86 skip_fields => $args->{'skip_fields'},
89 die "Invalid image type '$output_type'"
90 unless VALID_IMAGE_TYPE ->{ $output_type };
91 die "Invalid font size '$font_size'"
92 unless VALID_FONT_SIZE->{ $font_size };
98 $font_size eq 'small' ? gdTinyFont :
99 $font_size eq 'medium' ? gdSmallFont :
100 $font_size eq 'large' ? gdLargeFont : gdGiantFont;
101 my @tables = $schema->get_tables;
102 my $no_tables = scalar @tables;
103 $no_columns = 0 unless $no_columns =~ /^\d+$/;
104 $no_columns ||= sprintf( "%.0f", sqrt( $no_tables ) + .5 );
106 my $no_per_col = sprintf( "%.0f", $no_tables/$no_columns + .5 );
109 my ( $max_x, $max_y ); # the furthest x and y used
110 my $orig_y = 40; # used to reset y for each column
111 my ( $x, $y ) = (30,$orig_y); # where to start
112 my $cur_col = 1; # the current column
113 my $no_this_col = 0; # number of tables in current column
114 my $this_col_x = $x; # current column's x
115 my %nj_registry; # for locations of fields for natural joins
116 my @fk_registry; # for locations of fields for foreign keys
117 my %table_x; # for max x of each table
118 my $field_no; # counter to give distinct no. to each field
119 my %coords; # holds fields coordinates
120 my @imap_coords; # for making clickable image map
123 for my $table ( @tables ) {
124 my $table_name = $table->name;
127 [ 'string', $font, $this_col_x, $y, $table_name, 'black' ];
128 $y += $font->height + 2;
129 my $below_table_name = $y;
132 $this_col_x + ($font->width * length($table_name));
134 debug("Processing table '$table_name'");
136 my @fields = $table->get_fields;
137 debug("Fields = ", join(', ', map { $_->name } @fields));
139 my ( @fld_desc, $max_name, $max_desc );
140 for my $f ( @fields ) {
141 my $name = $f->name or next;
142 my $is_pk = $f->is_primary_key;
147 # Decide if we should skip this field.
149 if ( $show_fk_only ) {
150 next unless $is_pk || $f->is_foreign_key;
155 $legend{'Primary key'} = '[PK]';
158 if ( $f->is_unique ) {
160 $legend{'Unique constraint'} = '[U]';
163 if ( $f->is_foreign_key ) {
165 $legend{'Foreign Key'} = '[FK]';
170 $attr .= '[' . join(', ', @attr) . ']';
173 my $desc = $f->data_type;
174 $desc .= '('.$f->size.')' if $f->size &&
175 $f->data_type =~ /^(VAR)?CHAR2?$/i;
177 my $nlen = length $name;
178 my $dlen = length $desc;
179 $max_name = $nlen if $nlen > $max_name;
180 $max_desc = $dlen if $dlen > $max_desc;
181 push @fld_desc, [ $name, $desc, $f->{'name'}, $is_pk, $attr ];
186 for my $fld_desc ( @fld_desc ) {
187 my ( $name, $desc, $orig_name, $is_pk, $attr ) = @$fld_desc;
188 my $diff1 = $max_name - length $name;
189 my $diff2 = $max_desc - length $desc;
190 $name .= ' ' x $diff1;
191 $desc .= ' ' x $diff2;
192 $desc = $name . $desc . $attr;
194 push @shapes, [ 'string', $font, $this_col_x, $y, $desc, 'black' ];
195 $y += $font->height + 2;
196 my $length = $this_col_x + ( $font->width * length( $desc ) );
197 $this_max_x = $length if $length > $this_max_x;
199 my $constraints = $table->{'fields'}{ $orig_name }{'constraints'};
201 if ( $natural_join && !$skip{ $orig_name } ) {
202 push @{ $nj_registry{ $orig_name } }, $table_name;
205 my $y_link = $y - $font->height/2;
206 $coords{ $table_name }{ $orig_name }{'coords'} = {
207 left => [ $this_col_x - 6, $y_link ],
208 right => [ $length + 2 , $y_link ],
209 table => $table_name,
210 field_no => ++$field_no,
212 fld_name => $orig_name,
216 $imap_url."#$table_name-$orig_name",
217 $this_col_x, $y - $font->height, $length, $y_link,
221 unless ( $natural_join ) {
222 for my $c ( $table->get_constraints ) {
223 next unless $c->type eq FOREIGN_KEY;
224 my $fk_table = $c->reference_table or next;
226 for my $field_name ( $c->fields ) {
227 for my $fk_field ( $c->reference_fields ) {
228 next unless defined $schema->get_table( $fk_table );
230 [ $fk_table , $fk_field ],
231 [ $table_name, $field_name ],
239 $table_x{ $table_name } = $this_max_x + 5;
240 push @shapes, [ 'line', $this_col_x - 5, $below_table_name,
241 $this_max_x, $below_table_name, 'black' ];
242 my @bounds = ( $this_col_x - 5, $top - 5, $this_max_x, $y + 5 );
246 $bounds[0], $bounds[1],
247 $this_max_x, $below_table_name,
250 unshift @shapes, [ 'filledRectangle', @bounds, 'white' ];
254 $imap_url."#$table_name",
255 $bounds[0], $bounds[1], $this_max_x, $below_table_name,
258 push @shapes, [ 'rectangle', @bounds, 'black' ];
259 $max_x = $this_max_x if $this_max_x > $max_x;
262 if ( ++$no_this_col == $no_per_col ) {# if we've filled up this column
263 $cur_col++; # up the column number
264 $no_this_col = 0; # reset the number of tables
265 $max_x += $gutter; # push the x over for next column
266 $this_col_x = $max_x; # remember the max x for this col
267 $max_y = $y if $y > $max_y; # note the max y
268 $y = $orig_y; # reset the y for next column
277 unless ( $no_lines ) {
278 my @position_bunches;
280 if ( $natural_join ) {
281 for my $field_name ( keys %nj_registry ) {
284 @{ $nj_registry{ $field_name } || [] } or next;
285 next if scalar @table_names == 1;
287 for my $table_name ( @table_names ) {
289 $coords{ $table_name }{ $field_name }{'coords'};
292 push @position_bunches, [ @positions ];
296 for my $pair ( @fk_registry ) {
297 push @position_bunches, [
298 $coords{$pair->[0][0]}{ $pair->[0][1] }{'coords'},
299 $coords{$pair->[1][0]}{ $pair->[1][1] }{'coords'},
304 my $is_directed = $natural_join ? 0 : 1;
306 for my $bunch ( @position_bunches ) {
307 my @positions = @$bunch;
309 for my $i ( 0 .. $#positions ) {
310 my $pos1 = $positions[ $i ];
311 my ( $ax, $ay ) = @{ $pos1->{'left'} || [] } or next;
312 my ( $bx, $by ) = @{ $pos1->{'right'} || [] } or next;
313 my $table1 = $pos1->{'table'};
314 my $fno1 = $pos1->{'field_no'};
315 my $is_pk = $pos1->{'is_pk'};
316 next if $join_pk_only and !$is_pk;
318 for my $j ( 0 .. $#positions ) {
319 my $pos2 = $positions[ $j ];
320 my ( $cx, $cy ) = @{ $pos2->{'left'} || [] } or next;
321 my ( $dx, $dy ) = @{ $pos2->{'right'} || [] } or next;
322 my $table2 = $pos2->{'table'};
323 my $fno2 = $pos2->{'field_no'};
324 next if $table1 eq $table2;
325 next if $done{ $fno1 }{ $fno2 };
326 next if $fno1 == $fno2;
330 abs ( $ax - $cx ) + abs ( $ay - $cy ),
331 [ $ax, $ay, $cx, $cy ],
335 abs ( $ax - $dx ) + abs ( $ay - $dy ),
336 [ $ax, $ay, $dx, $dy ],
340 abs ( $bx - $cx ) + abs ( $by - $cy ),
341 [ $bx, $by, $cx, $cy ],
345 abs ( $bx - $dx ) + abs ( $by - $dy ),
346 [ $bx, $by, $dx, $dy ],
347 [ 'right', 'right' ],
349 @distances = sort { $a->[0] <=> $b->[0] } @distances;
350 my $shortest = $distances[0];
351 my ( $x1, $y1, $x2, $y2 ) = @{ $shortest->[1] };
352 my ( $side1, $side2 ) = @{ $shortest->[2] };
355 my $col1_right = $table_x{ $table1 };
356 my $col2_right = $table_x{ $table2 };
360 while ( $horz_taken{ $x1 + $diff } ) {
361 $diff = $side1 eq 'left' ? $diff - 2 : $diff + 2;
363 $horz_taken{ $x1 + $diff } = 1;
366 if ( $side1 eq 'left' ) {
367 $start = $x1 - $offset + $diff;
370 $start = $col1_right + $diff;
373 if ( $side2 eq 'left' ) {
374 $end = $x2 - $offset + $diff;
377 $end = $col2_right + $diff;
381 [ 'line', $x1, $y1, $start, $y1, 'cadetblue' ];
383 [ 'line', $start, $y1, $end, $y2, 'cadetblue' ];
385 [ 'line', $end, $y2, $x2, $y2, 'cadetblue' ];
387 if ( $is_directed ) {
389 $side1 eq 'right' && $side2 eq 'left'
391 $side1 eq 'left' && $side2 eq 'left'
394 'line', $x2 - 3, $y2 - 3, $x2, $y2, 'cadetblue'
397 'line', $x2 - 3, $y2 + 3, $x2, $y2, 'cadetblue'
400 'line', $x2 - 3, $y2 - 3, $x2 - 3, $y2 +3,
406 'line', $x2 + 3, $y2 - 3, $x2, $y2, 'cadetblue'
409 'line', $x2 + 3, $y2 + 3, $x2, $y2, 'cadetblue'
412 'line', $x2 + 3, $y2 - 3, $x2 + 3, $y2 +3,
418 $done{ $fno1 }{ $fno2 } = 1;
419 $done{ $fno2 }{ $fno1 } = 1;
426 # Add the title, legend and signature.
428 my $large_font = gdLargeFont;
429 my $title_len = $large_font->width * length $title;
431 'string', $large_font, $max_x/2 - $title_len/2, 10, $title, 'black'
437 'string', $font, $x, $max_y - $font->height - 4, 'Legend', 'black'
439 $max_y += $font->height + 4;
442 for my $len ( map { length $_ } values %legend ) {
443 $longest = $len if $len > $longest;
447 while ( my ( $key, $shape ) = each %legend ) {
448 my $space = $longest - length $shape;
450 'string', $font, $x, $max_y - $font->height - 4,
451 join( '', $shape, ' ' x $space, $key ), 'black'
454 $max_y += $font->height + 4;
458 my $sig = 'Created by SQL::Translator ' . $t->version;
459 my $sig_len = $font->width * length $sig;
461 'string', $font, $max_x - $sig_len, $max_y - $font->height - 4,
468 my $gd = GD::Image->new( $max_x + 30, $max_y );
469 unless ( $gd->can( $output_type ) ) {
470 die "GD can't create images of type '$output_type'\n";
472 my %colors = map { $_->[0], $gd->colorAllocate( @{$_->[1]} ) } (
473 [ white => [ 255, 255, 255 ] ],
474 [ beige => [ 245, 245, 220 ] ],
475 [ black => [ 0, 0, 0 ] ],
476 [ lightblue => [ 173, 216, 230 ] ],
477 [ cadetblue => [ 95, 158, 160 ] ],
478 [ lightgoldenrodyellow => [ 250, 250, 210 ] ],
479 [ khaki => [ 240, 230, 140 ] ],
480 [ red => [ 255, 0, 0 ] ],
482 $gd->interlaced( 'true' );
483 my $background_color = $add_color ? 'lightgoldenrodyellow' : 'white';
484 $gd->fill( 0, 0, $colors{ $background_color } );
485 for my $shape ( @shapes ) {
486 my $method = shift @$shape;
487 my $color = pop @$shape;
488 $gd->$method( @$shape, $colors{ $color } );
494 debug("imap file = '$imap_file'");
495 if ( $imap_file && @imap_coords ) {
496 open my $fh, ">$imap_file" or die "Can't write '$imap_file': $!\n";
497 print $fh qq[<html><body><img src="" usemap="#imap" border="0">\n].
498 qq[<map name="imap">\n];
499 for my $rec ( @imap_coords ) {
500 my $href = shift @$rec;
501 print $fh q[<area coords="].join(',', @$rec).qq[" href="$href">\n];
503 print $fh qq[</body></html>];
511 open my $fh, ">$out_file" or die "Can't write '$out_file': $!\n";
512 print $fh $gd->$output_type;
516 return $gd->$output_type;
522 # -------------------------------------------------------------------
528 Ken Y. Clark E<lt>kclark@cpan.orgE<gt>.