1 package SQL::Translator::Producer::Diagram;
3 # -------------------------------------------------------------------
4 # $Id: Diagram.pm,v 1.10 2004-02-11 21:30:19 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( parser => 'MySQL', '...' );
39 use SQL::Translator::MySQL 'parse';
41 my $t = SQL::Translator->new( filename => '...' );;
50 use SQL::Translator::Schema::Constants;
51 use SQL::Translator::Utils qw(debug);
53 use vars qw[ $VERSION $DEBUG ];
54 $VERSION = sprintf "%d.%02d", q$Revision: 1.10 $ =~ /(\d+)\.(\d+)/;
55 $DEBUG = 0 unless defined $DEBUG;
57 use constant VALID_FONT_SIZE => {
64 use constant VALID_IMAGE_TYPE => {
71 my $schema = $t->schema;
72 my $args = $t->producer_args;
73 local $DEBUG = $t->debug;
74 debug("Schema =\n", Dumper( $schema ));
75 debug("Producer args =\n", Dumper( $args ));
77 my $out_file = $args->{'out_file'} || '';
78 my $output_type = $args->{'output_type'} || 'png';
79 my $title = $args->{'title'} || $t->filename;
80 my $font_size = $args->{'font_size'} || 'medium';
81 my $imap_file = $args->{'imap_file'} || '';
82 my $imap_url = $args->{'imap_url'} || '';
83 my $no_columns = $args->{'no_columns'};
84 my $no_lines = $args->{'no_lines'};
85 my $add_color = $args->{'add_color'};
86 my $show_fk_only = $args->{'show_fk_only'};
87 my $join_pk_only = $args->{'join_pk_only'};
88 my $natural_join = $args->{'natural_join'} || $join_pk_only;
89 my $skip_fields = $args->{'skip_fields'};
90 my %skip = map { s/^\s+|\s+$//g; $_,1 } split (/,/, $skip_fields);
92 $schema->make_natural_joins(
93 join_pk_only => $join_pk_only,
94 skip_fields => $args->{'skip_fields'},
97 die "Invalid image type '$output_type'"
98 unless VALID_IMAGE_TYPE ->{ $output_type };
99 die "Invalid font size '$font_size'"
100 unless VALID_FONT_SIZE->{ $font_size };
106 $font_size eq 'small' ? gdTinyFont :
107 $font_size eq 'medium' ? gdSmallFont :
108 $font_size eq 'large' ? gdLargeFont : gdGiantFont;
109 my @tables = $schema->get_tables;
110 my $no_tables = scalar @tables;
111 $no_columns = 0 unless $no_columns =~ /^\d+$/;
112 $no_columns ||= sprintf( "%.0f", sqrt( $no_tables ) + .5 );
114 my $no_per_col = sprintf( "%.0f", $no_tables/$no_columns + .5 );
117 my ( $max_x, $max_y ); # the furthest x and y used
118 my $orig_y = 40; # used to reset y for each column
119 my ( $x, $y ) = (30,$orig_y); # where to start
120 my $cur_col = 1; # the current column
121 my $no_this_col = 0; # number of tables in current column
122 my $this_col_x = $x; # current column's x
123 my $gutter = 30; # distance b/w columns
124 my %nj_registry; # for locations of fields for natural joins
125 my @fk_registry; # for locations of fields for foreign keys
126 my %table_x; # for max x of each table
127 my $field_no; # counter to give distinct no. to each field
128 my %coords; # holds fields coordinates
129 my @imap_coords; # for making clickable image map
132 for my $table ( @tables ) {
133 my $table_name = $table->name;
136 [ 'string', $font, $this_col_x, $y, $table_name, 'black' ];
137 $y += $font->height + 2;
138 my $below_table_name = $y;
141 $this_col_x + ($font->width * length($table_name));
143 debug("Processing table '$table_name'");
145 my @fields = $table->get_fields;
146 debug("Fields = ", join(', ', map { $_->name } @fields));
148 my ( @fld_desc, $max_name, $max_desc );
149 for my $f ( @fields ) {
150 my $name = $f->name or next;
151 my $is_pk = $f->is_primary_key;
156 # Decide if we should skip this field.
158 if ( $show_fk_only ) {
159 next unless $is_pk || $f->is_foreign_key;
164 $legend{'Primary key'} = '[PK]';
167 if ( $f->is_unique ) {
169 $legend{'Unique constraint'} = '[U]';
172 if ( $f->is_foreign_key ) {
174 $legend{'Foreign Key'} = '[FK]';
179 $attr .= '[' . join(', ', @attr) . ']';
182 my $desc = $f->data_type;
183 $desc .= '('.$f->size.')' if $f->size &&
184 $f->data_type =~ /^(VAR)?CHAR2?$/i;
186 my $nlen = length $name;
187 my $dlen = length $desc;
188 $max_name = $nlen if $nlen > $max_name;
189 $max_desc = $dlen if $dlen > $max_desc;
190 push @fld_desc, [ $name, $desc, $f->{'name'}, $is_pk, $attr ];
195 for my $fld_desc ( @fld_desc ) {
196 my ( $name, $desc, $orig_name, $is_pk, $attr ) = @$fld_desc;
197 my $diff1 = $max_name - length $name;
198 my $diff2 = $max_desc - length $desc;
199 $name .= ' ' x $diff1;
200 $desc .= ' ' x $diff2;
201 $desc = $name . $desc . $attr;
203 push @shapes, [ 'string', $font, $this_col_x, $y, $desc, 'black' ];
204 $y += $font->height + 2;
205 my $length = $this_col_x + ( $font->width * length( $desc ) );
206 $this_max_x = $length if $length > $this_max_x;
208 my $constraints = $table->{'fields'}{ $orig_name }{'constraints'};
210 if ( $natural_join && !$skip{ $orig_name } ) {
211 push @{ $nj_registry{ $orig_name } }, $table_name;
214 my $y_link = $y - $font->height/2;
215 $coords{ $table_name }{ $orig_name }{'coords'} = {
216 left => [ $this_col_x - 6, $y_link ],
217 right => [ $length + 2 , $y_link ],
218 table => $table_name,
219 field_no => ++$field_no,
221 fld_name => $orig_name,
225 $imap_url."#$table_name-$orig_name",
226 $this_col_x, $y - $font->height, $length, $y_link,
230 unless ( $natural_join ) {
231 for my $c ( $table->get_constraints ) {
232 next unless $c->type eq FOREIGN_KEY;
233 my $fk_table = $c->reference_table or next;
235 for my $field_name ( $c->fields ) {
236 for my $fk_field ( $c->reference_fields ) {
237 next unless defined $schema->get_table( $fk_table );
239 [ $fk_table , $fk_field ],
240 [ $table_name, $field_name ],
248 $table_x{ $table_name } = $this_max_x + 5;
249 push @shapes, [ 'line', $this_col_x - 5, $below_table_name,
250 $this_max_x, $below_table_name, 'black' ];
251 my @bounds = ( $this_col_x - 5, $top - 5, $this_max_x, $y + 5 );
255 $bounds[0], $bounds[1],
256 $this_max_x, $below_table_name,
259 unshift @shapes, [ 'filledRectangle', @bounds, 'white' ];
263 $imap_url."#$table_name",
264 $bounds[0], $bounds[1], $this_max_x, $below_table_name,
267 push @shapes, [ 'rectangle', @bounds, 'black' ];
268 $max_x = $this_max_x if $this_max_x > $max_x;
271 if ( ++$no_this_col == $no_per_col ) {# if we've filled up this column
272 $cur_col++; # up the column number
273 $no_this_col = 0; # reset the number of tables
274 $max_x += $gutter; # push the x over for next column
275 $this_col_x = $max_x; # remember the max x for this col
276 $max_y = $y if $y > $max_y; # note the max y
277 $y = $orig_y; # reset the y for next column
286 unless ( $no_lines ) {
287 my @position_bunches;
289 if ( $natural_join ) {
290 for my $field_name ( keys %nj_registry ) {
293 @{ $nj_registry{ $field_name } || [] } or next;
294 next if scalar @table_names == 1;
296 for my $table_name ( @table_names ) {
298 $coords{ $table_name }{ $field_name }{'coords'};
301 push @position_bunches, [ @positions ];
305 for my $pair ( @fk_registry ) {
306 push @position_bunches, [
307 $coords{$pair->[0][0]}{ $pair->[0][1] }{'coords'},
308 $coords{$pair->[1][0]}{ $pair->[1][1] }{'coords'},
313 my $is_directed = $natural_join ? 0 : 1;
315 for my $bunch ( @position_bunches ) {
316 my @positions = @$bunch;
318 for my $i ( 0 .. $#positions ) {
319 my $pos1 = $positions[ $i ];
320 my ( $ax, $ay ) = @{ $pos1->{'left'} || [] } or next;
321 my ( $bx, $by ) = @{ $pos1->{'right'} || [] } or next;
322 my $table1 = $pos1->{'table'};
323 my $fno1 = $pos1->{'field_no'};
324 my $is_pk = $pos1->{'is_pk'};
325 next if $join_pk_only and !$is_pk;
327 for my $j ( 0 .. $#positions ) {
328 my $pos2 = $positions[ $j ];
329 my ( $cx, $cy ) = @{ $pos2->{'left'} || [] } or next;
330 my ( $dx, $dy ) = @{ $pos2->{'right'} || [] } or next;
331 my $table2 = $pos2->{'table'};
332 my $fno2 = $pos2->{'field_no'};
333 next if $table1 eq $table2;
334 next if $done{ $fno1 }{ $fno2 };
335 next if $fno1 == $fno2;
339 abs ( $ax - $cx ) + abs ( $ay - $cy ),
340 [ $ax, $ay, $cx, $cy ],
344 abs ( $ax - $dx ) + abs ( $ay - $dy ),
345 [ $ax, $ay, $dx, $dy ],
349 abs ( $bx - $cx ) + abs ( $by - $cy ),
350 [ $bx, $by, $cx, $cy ],
354 abs ( $bx - $dx ) + abs ( $by - $dy ),
355 [ $bx, $by, $dx, $dy ],
356 [ 'right', 'right' ],
358 @distances = sort { $a->[0] <=> $b->[0] } @distances;
359 my $shortest = $distances[0];
360 my ( $x1, $y1, $x2, $y2 ) = @{ $shortest->[1] };
361 my ( $side1, $side2 ) = @{ $shortest->[2] };
364 my $col1_right = $table_x{ $table1 };
365 my $col2_right = $table_x{ $table2 };
369 while ( $horz_taken{ $x1 + $diff } ) {
370 $diff = $side1 eq 'left' ? $diff - 2 : $diff + 2;
372 $horz_taken{ $x1 + $diff } = 1;
375 if ( $side1 eq 'left' ) {
376 $start = $x1 - $offset + $diff;
379 $start = $col1_right + $diff;
382 if ( $side2 eq 'left' ) {
383 $end = $x2 - $offset + $diff;
386 $end = $col2_right + $diff;
390 [ 'line', $x1, $y1, $start, $y1, 'cadetblue' ];
392 [ 'line', $start, $y1, $end, $y2, 'cadetblue' ];
394 [ 'line', $end, $y2, $x2, $y2, 'cadetblue' ];
396 if ( $is_directed ) {
398 $side1 eq 'right' && $side2 eq 'left'
400 $side1 eq 'left' && $side2 eq 'left'
403 'line', $x2 - 3, $y2 - 3, $x2, $y2, 'cadetblue'
406 'line', $x2 - 3, $y2 + 3, $x2, $y2, 'cadetblue'
409 'line', $x2 - 3, $y2 - 3, $x2 - 3, $y2 +3,
415 'line', $x2 + 3, $y2 - 3, $x2, $y2, 'cadetblue'
418 'line', $x2 + 3, $y2 + 3, $x2, $y2, 'cadetblue'
421 'line', $x2 + 3, $y2 - 3, $x2 + 3, $y2 +3,
427 $done{ $fno1 }{ $fno2 } = 1;
428 $done{ $fno2 }{ $fno1 } = 1;
435 # Add the title, legend and signature.
437 my $large_font = gdLargeFont;
438 my $title_len = $large_font->width * length $title;
440 'string', $large_font, $max_x/2 - $title_len/2, 10, $title, 'black'
446 'string', $font, $x, $max_y - $font->height - 4, 'Legend', 'black'
448 $max_y += $font->height + 4;
451 for my $len ( map { length $_ } values %legend ) {
452 $longest = $len if $len > $longest;
456 while ( my ( $key, $shape ) = each %legend ) {
457 my $space = $longest - length $shape;
459 'string', $font, $x, $max_y - $font->height - 4,
460 join( '', $shape, ' ' x $space, $key ), 'black'
463 $max_y += $font->height + 4;
467 my $sig = 'Created by SQL::Translator ' . $t->version;
468 my $sig_len = $font->width * length $sig;
470 'string', $font, $max_x - $sig_len, $max_y - $font->height - 4,
477 my $gd = GD::Image->new( $max_x + 30, $max_y );
478 unless ( $gd->can( $output_type ) ) {
479 die "GD can't create images of type '$output_type'\n";
481 my %colors = map { $_->[0], $gd->colorAllocate( @{$_->[1]} ) } (
482 [ white => [ 255, 255, 255 ] ],
483 [ beige => [ 245, 245, 220 ] ],
484 [ black => [ 0, 0, 0 ] ],
485 [ lightblue => [ 173, 216, 230 ] ],
486 [ cadetblue => [ 95, 158, 160 ] ],
487 [ lightgoldenrodyellow => [ 250, 250, 210 ] ],
488 [ khaki => [ 240, 230, 140 ] ],
489 [ red => [ 255, 0, 0 ] ],
491 $gd->interlaced( 'true' );
492 my $background_color = $add_color ? 'lightgoldenrodyellow' : 'white';
493 $gd->fill( 0, 0, $colors{ $background_color } );
494 for my $shape ( @shapes ) {
495 my $method = shift @$shape;
496 my $color = pop @$shape;
497 $gd->$method( @$shape, $colors{ $color } );
503 debug("imap file = '$imap_file'");
504 if ( $imap_file && @imap_coords ) {
505 open my $fh, ">$imap_file" or die "Can't write '$imap_file': $!\n";
506 print $fh qq[<html><body><img src="" usemap="#imap" border="0">\n].
507 qq[<map name="imap">\n];
508 for my $rec ( @imap_coords ) {
509 my $href = shift @$rec;
510 print $fh q[<area coords="].join(',', @$rec).qq[" href="$href">\n];
512 print $fh qq[</body></html>];
520 open my $fh, ">$out_file" or die "Can't write '$out_file': $!\n";
521 print $fh $gd->$output_type;
525 return $gd->$output_type;
531 # -------------------------------------------------------------------
537 Ken Y. Clark E<lt>kclark@cpan.orgE<gt>.