1 package SQL::Translator::Producer::Diagram;
3 # -------------------------------------------------------------------
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$ =~ /(\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 # my @tables = $schema->get_tables;
86 if ( $natural_join ) {
87 $schema->make_natural_joins(
88 join_pk_only => $join_pk_only,
89 skip_fields => $args->{'skip_fields'},
92 my $g = $schema->as_graph_pm;
93 my $d = Graph::Traversal::DFS->new( $g, next_alphabetic => 1 );
96 @table_names = $d->dfs;
99 @table_names = map { $_->name } $schema->get_tables;
102 die "Invalid image type '$output_type'"
103 unless VALID_IMAGE_TYPE ->{ $output_type };
104 die "Invalid font size '$font_size'"
105 unless VALID_FONT_SIZE->{ $font_size };
111 = $font_size eq 'small' ? gdTinyFont
112 : $font_size eq 'medium' ? gdSmallFont
113 : $font_size eq 'large' ? gdLargeFont
116 my $no_tables = scalar @table_names;
117 $no_columns = 0 unless $no_columns =~ /^\d+$/;
118 $no_columns ||= sprintf( "%.0f", sqrt( $no_tables ) + .5 );
120 my $no_per_col = sprintf( "%.0f", $no_tables/$no_columns + .5 );
123 my ( $max_x, $max_y ); # the furthest x and y used
124 my $orig_y = 40; # used to reset y for each column
125 my ( $x, $y ) = (30,$orig_y); # where to start
126 my $cur_col = 1; # the current column
127 my $no_this_col = 0; # number of tables in current column
128 my $this_col_x = $x; # current column's x
129 my %nj_registry; # for locations of fields for natural joins
130 my @fk_registry; # for locations of fields for foreign keys
131 my %table_x; # for max x of each table
132 my $field_no; # counter to give distinct no. to each field
133 my %coords; # holds fields coordinates
134 my @imap_coords; # for making clickable image map
137 for my $table_name ( @table_names ) {
138 my $table = $schema->get_table( $table_name );
141 [ 'string', $font, $this_col_x, $y, $table_name, 'black' ];
142 $y += $font->height + 2;
143 my $below_table_name = $y;
146 $this_col_x + ($font->width * length($table_name));
148 debug("Processing table '$table_name'");
150 my @fields = $table->get_fields;
151 debug("Fields = ", join(', ', map { $_->name } @fields));
153 my ( @fld_desc, $max_name, $max_desc );
154 for my $f ( @fields ) {
155 my $name = $f->name or next;
156 my $is_pk = $f->is_primary_key;
161 # Decide if we should skip this field.
163 if ( $show_fk_only ) {
164 next unless $is_pk || $f->is_foreign_key;
169 $legend{'Primary key'} = '[PK]';
172 if ( $f->is_unique ) {
174 $legend{'Unique constraint'} = '[U]';
177 if ( $f->is_foreign_key ) {
179 $legend{'Foreign Key'} = '[FK]';
184 $attr .= '[' . join(', ', @attr) . ']';
187 my $desc = $f->data_type;
188 $desc .= '('.$f->size.')' if $f->size &&
189 $f->data_type =~ /^(VAR)?CHAR2?$/i;
191 my $nlen = length $name;
192 my $dlen = length $desc;
193 $max_name = $nlen if $nlen > $max_name;
194 $max_desc = $dlen if $dlen > $max_desc;
195 push @fld_desc, [ $name, $desc, $f->{'name'}, $is_pk, $attr ];
200 for my $fld_desc ( @fld_desc ) {
201 my ( $name, $desc, $orig_name, $is_pk, $attr ) = @$fld_desc;
202 my $diff1 = $max_name - length $name;
203 my $diff2 = $max_desc - length $desc;
204 $name .= ' ' x $diff1;
205 $desc .= ' ' x $diff2;
206 $desc = $name . $desc . $attr;
208 push @shapes, [ 'string', $font, $this_col_x, $y, $desc, 'black' ];
209 $y += $font->height + 2;
210 my $length = $this_col_x + ( $font->width * length( $desc ) );
211 $this_max_x = $length if $length > $this_max_x;
213 my $constraints = $table->{'fields'}{ $orig_name }{'constraints'};
215 if ( $natural_join && !$skip{ $orig_name } ) {
216 push @{ $nj_registry{ $orig_name } }, $table_name;
219 my $y_link = $y - $font->height/2;
220 $coords{ $table_name }{ $orig_name }{'coords'} = {
221 left => [ $this_col_x - 6, $y_link ],
222 right => [ $length + 2 , $y_link ],
223 table => $table_name,
224 field_no => ++$field_no,
226 fld_name => $orig_name,
230 $imap_url."#$table_name-$orig_name",
231 $this_col_x, $y - $font->height, $length, $y_link,
235 unless ( $natural_join ) {
236 for my $c ( $table->get_constraints ) {
237 next unless $c->type eq FOREIGN_KEY;
238 my $fk_table = $c->reference_table or next;
240 for my $field_name ( $c->fields ) {
241 for my $fk_field ( $c->reference_fields ) {
242 next unless defined $schema->get_table( $fk_table );
244 [ $fk_table , $fk_field ],
245 [ $table_name, $field_name ],
253 $table_x{ $table_name } = $this_max_x + 5;
254 push @shapes, [ 'line', $this_col_x - 5, $below_table_name,
255 $this_max_x, $below_table_name, 'black' ];
256 my @bounds = ( $this_col_x - 5, $top - 5, $this_max_x, $y + 5 );
260 $bounds[0], $bounds[1],
261 $this_max_x, $below_table_name,
264 unshift @shapes, [ 'filledRectangle', @bounds, 'white' ];
268 $imap_url."#$table_name",
269 $bounds[0], $bounds[1], $this_max_x, $below_table_name,
272 push @shapes, [ 'rectangle', @bounds, 'black' ];
273 $max_x = $this_max_x if $this_max_x > $max_x;
276 if ( ++$no_this_col == $no_per_col ) {# if we've filled up this column
277 $cur_col++; # up the column number
278 $no_this_col = 0; # reset the number of tables
279 $max_x += $gutter; # push the x over for next column
280 $this_col_x = $max_x; # remember the max x for this col
281 $max_y = $y if $y > $max_y; # note the max y
282 $y = $orig_y; # reset the y for next column
291 unless ( $no_lines ) {
292 my @position_bunches;
294 if ( $natural_join ) {
295 for my $field_name ( keys %nj_registry ) {
298 @{ $nj_registry{ $field_name } || [] } or next;
299 next if scalar @table_names == 1;
301 for my $table_name ( @table_names ) {
303 $coords{ $table_name }{ $field_name }{'coords'};
306 push @position_bunches, [ @positions ];
310 for my $pair ( @fk_registry ) {
311 push @position_bunches, [
312 $coords{$pair->[0][0]}{ $pair->[0][1] }{'coords'},
313 $coords{$pair->[1][0]}{ $pair->[1][1] }{'coords'},
318 my $is_directed = $natural_join ? 0 : 1;
320 for my $bunch ( @position_bunches ) {
321 my @positions = @$bunch;
323 for my $i ( 0 .. $#positions ) {
324 my $pos1 = $positions[ $i ];
325 my ( $ax, $ay ) = @{ $pos1->{'left'} || [] } or next;
326 my ( $bx, $by ) = @{ $pos1->{'right'} || [] } or next;
327 my $table1 = $pos1->{'table'};
328 my $fno1 = $pos1->{'field_no'};
329 my $is_pk = $pos1->{'is_pk'};
330 next if $join_pk_only and !$is_pk;
332 for my $j ( 0 .. $#positions ) {
333 my $pos2 = $positions[ $j ];
334 my ( $cx, $cy ) = @{ $pos2->{'left'} || [] } or next;
335 my ( $dx, $dy ) = @{ $pos2->{'right'} || [] } or next;
336 my $table2 = $pos2->{'table'};
337 my $fno2 = $pos2->{'field_no'};
338 next if $table1 eq $table2;
339 next if $done{ $fno1 }{ $fno2 };
340 next if $fno1 == $fno2;
344 abs ( $ax - $cx ) + abs ( $ay - $cy ),
345 [ $ax, $ay, $cx, $cy ],
349 abs ( $ax - $dx ) + abs ( $ay - $dy ),
350 [ $ax, $ay, $dx, $dy ],
354 abs ( $bx - $cx ) + abs ( $by - $cy ),
355 [ $bx, $by, $cx, $cy ],
359 abs ( $bx - $dx ) + abs ( $by - $dy ),
360 [ $bx, $by, $dx, $dy ],
361 [ 'right', 'right' ],
363 @distances = sort { $a->[0] <=> $b->[0] } @distances;
364 my $shortest = $distances[0];
365 my ( $x1, $y1, $x2, $y2 ) = @{ $shortest->[1] };
366 my ( $side1, $side2 ) = @{ $shortest->[2] };
369 my $col1_right = $table_x{ $table1 };
370 my $col2_right = $table_x{ $table2 };
374 while ( $horz_taken{ $x1 + $diff } ) {
375 $diff = $side1 eq 'left' ? $diff - 2 : $diff + 2;
377 $horz_taken{ $x1 + $diff } = 1;
380 if ( $side1 eq 'left' ) {
381 $start = $x1 - $offset + $diff;
384 $start = $col1_right + $diff;
387 if ( $side2 eq 'left' ) {
388 $end = $x2 - $offset + $diff;
391 $end = $col2_right + $diff;
395 [ 'line', $x1, $y1, $start, $y1, 'cadetblue' ];
397 [ 'line', $start, $y1, $end, $y2, 'cadetblue' ];
399 [ 'line', $end, $y2, $x2, $y2, 'cadetblue' ];
401 if ( $is_directed ) {
403 $side1 eq 'right' && $side2 eq 'left'
405 $side1 eq 'left' && $side2 eq 'left'
408 'line', $x2 - 3, $y2 - 3, $x2, $y2, 'cadetblue'
411 'line', $x2 - 3, $y2 + 3, $x2, $y2, 'cadetblue'
414 'line', $x2 - 3, $y2 - 3, $x2 - 3, $y2 +3,
420 'line', $x2 + 3, $y2 - 3, $x2, $y2, 'cadetblue'
423 'line', $x2 + 3, $y2 + 3, $x2, $y2, 'cadetblue'
426 'line', $x2 + 3, $y2 - 3, $x2 + 3, $y2 +3,
432 $done{ $fno1 }{ $fno2 } = 1;
433 $done{ $fno2 }{ $fno1 } = 1;
440 # Add the title, legend and signature.
442 my $large_font = gdLargeFont;
443 my $title_len = $large_font->width * length $title;
445 'string', $large_font, $max_x/2 - $title_len/2, 10, $title, 'black'
451 'string', $font, $x, $max_y - $font->height - 4, 'Legend', 'black'
453 $max_y += $font->height + 4;
456 for my $len ( map { length $_ } values %legend ) {
457 $longest = $len if $len > $longest;
461 while ( my ( $key, $shape ) = each %legend ) {
462 my $space = $longest - length $shape;
464 'string', $font, $x, $max_y - $font->height - 4,
465 join( '', $shape, ' ' x $space, $key ), 'black'
468 $max_y += $font->height + 4;
472 my $sig = 'Created by SQL::Translator ' . $t->version;
473 my $sig_len = $font->width * length $sig;
475 'string', $font, $max_x - $sig_len, $max_y - $font->height - 4,
482 my $gd = GD::Image->new( $max_x + 30, $max_y );
483 unless ( $gd->can( $output_type ) ) {
484 die "GD can't create images of type '$output_type'\n";
486 my %colors = map { $_->[0], $gd->colorAllocate( @{$_->[1]} ) } (
487 [ white => [ 255, 255, 255 ] ],
488 [ beige => [ 245, 245, 220 ] ],
489 [ black => [ 0, 0, 0 ] ],
490 [ lightblue => [ 173, 216, 230 ] ],
491 [ cadetblue => [ 95, 158, 160 ] ],
492 [ lightgoldenrodyellow => [ 250, 250, 210 ] ],
493 [ khaki => [ 240, 230, 140 ] ],
494 [ red => [ 255, 0, 0 ] ],
496 $gd->interlaced( 'true' );
497 my $background_color = $add_color ? 'lightgoldenrodyellow' : 'white';
498 $gd->fill( 0, 0, $colors{ $background_color } );
499 for my $shape ( @shapes ) {
500 my $method = shift @$shape;
501 my $color = pop @$shape;
502 $gd->$method( @$shape, $colors{ $color } );
508 debug("imap file = '$imap_file'");
509 if ( $imap_file && @imap_coords ) {
510 open my $fh, ">$imap_file" or die "Can't write '$imap_file': $!\n";
511 print $fh qq[<html><body><img src="" usemap="#imap" border="0">\n].
512 qq[<map name="imap">\n];
513 for my $rec ( @imap_coords ) {
514 my $href = shift @$rec;
515 print $fh q[<area coords="].join(',', @$rec).qq[" href="$href">\n];
517 print $fh qq[</body></html>];
525 open my $fh, ">$out_file" or die "Can't write '$out_file': $!\n";
526 print $fh $gd->$output_type;
530 return $gd->$output_type;
536 # -------------------------------------------------------------------
542 Ken Y. Clark E<lt>kclark@cpan.orgE<gt>.