1 package SQL::Translator::Producer::Diagram;
3 # -------------------------------------------------------------------
4 # Copyright (C) 2002-2009 SQLFairy Authors
6 # This program is free software; you can redistribute it and/or
7 # modify it under the terms of the GNU General Public License as
8 # published by the Free Software Foundation; version 2.
10 # This program is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 # General Public License for more details.
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
19 # -------------------------------------------------------------------
23 SQL::Translator::Producer::Diagram - ER diagram producer for SQL::Translator
27 Use via SQL::Translator:
31 my $t = SQL::Translator->new( producer => 'Diagram', '...' );
39 use SQL::Translator::Schema::Constants;
40 use SQL::Translator::Utils qw(debug);
42 use vars qw[ $VERSION $DEBUG ];
44 $DEBUG = 0 unless defined $DEBUG;
46 use constant VALID_FONT_SIZE => {
53 use constant VALID_IMAGE_TYPE => {
60 my $schema = $t->schema;
61 my $args = $t->producer_args;
62 local $DEBUG = $t->debug;
63 debug("Schema =\n", Dumper( $schema ));
64 debug("Producer args =\n", Dumper( $args ));
66 my $out_file = $args->{'out_file'} || '';
67 my $output_type = $args->{'output_type'} || 'png';
68 my $title = $args->{'title'} || $t->filename;
69 my $font_size = $args->{'font_size'} || 'medium';
70 my $imap_file = $args->{'imap_file'} || '';
71 my $imap_url = $args->{'imap_url'} || '';
72 my $gutter = $args->{'gutter'} || 30; # distance b/w columns
73 my $no_columns = $args->{'no_columns'};
74 my $no_lines = $args->{'no_lines'};
75 my $add_color = $args->{'add_color'};
76 my $show_fk_only = $args->{'show_fk_only'};
77 my $join_pk_only = $args->{'join_pk_only'};
78 my $natural_join = $args->{'natural_join'} || $join_pk_only;
79 my $skip_fields = $args->{'skip_fields'};
80 my %skip = map { s/^\s+|\s+$//g; $_,1 } split (/,/, $skip_fields);
82 # my @tables = $schema->get_tables;
84 if ( $natural_join ) {
85 $schema->make_natural_joins(
86 join_pk_only => $join_pk_only,
87 skip_fields => $args->{'skip_fields'},
90 my $g = $schema->as_graph_pm;
91 my $d = Graph::Traversal::DFS->new( $g, next_alphabetic => 1 );
94 @table_names = $d->dfs;
97 @table_names = map { $_->name } $schema->get_tables;
100 die "Invalid image type '$output_type'"
101 unless VALID_IMAGE_TYPE ->{ $output_type };
102 die "Invalid font size '$font_size'"
103 unless VALID_FONT_SIZE->{ $font_size };
109 = $font_size eq 'small' ? gdTinyFont
110 : $font_size eq 'medium' ? gdSmallFont
111 : $font_size eq 'large' ? gdLargeFont
114 my $no_tables = scalar @table_names;
115 $no_columns = 0 unless $no_columns =~ /^\d+$/;
116 $no_columns ||= sprintf( "%.0f", sqrt( $no_tables ) + .5 );
118 my $no_per_col = sprintf( "%.0f", $no_tables/$no_columns + .5 );
121 my ( $max_x, $max_y ); # the furthest x and y used
122 my $orig_y = 40; # used to reset y for each column
123 my ( $x, $y ) = (30,$orig_y); # where to start
124 my $cur_col = 1; # the current column
125 my $no_this_col = 0; # number of tables in current column
126 my $this_col_x = $x; # current column's x
127 my %nj_registry; # for locations of fields for natural joins
128 my @fk_registry; # for locations of fields for foreign keys
129 my %table_x; # for max x of each table
130 my $field_no; # counter to give distinct no. to each field
131 my %coords; # holds fields coordinates
132 my @imap_coords; # for making clickable image map
135 for my $table_name ( @table_names ) {
136 my $table = $schema->get_table( $table_name );
139 [ 'string', $font, $this_col_x, $y, $table_name, 'black' ];
140 $y += $font->height + 2;
141 my $below_table_name = $y;
144 $this_col_x + ($font->width * length($table_name));
146 debug("Processing table '$table_name'");
148 my @fields = $table->get_fields;
149 debug("Fields = ", join(', ', map { $_->name } @fields));
151 my ( @fld_desc, $max_name, $max_desc );
152 for my $f ( @fields ) {
153 my $name = $f->name or next;
154 my $is_pk = $f->is_primary_key;
159 # Decide if we should skip this field.
161 if ( $show_fk_only ) {
162 next unless $is_pk || $f->is_foreign_key;
167 $legend{'Primary key'} = '[PK]';
170 if ( $f->is_unique ) {
172 $legend{'Unique constraint'} = '[U]';
175 if ( $f->is_foreign_key ) {
177 $legend{'Foreign Key'} = '[FK]';
182 $attr .= '[' . join(', ', @attr) . ']';
185 my $desc = $f->data_type;
186 $desc .= '('.$f->size.')' if $f->size &&
187 $f->data_type =~ /^(VAR)?CHAR2?$/i;
189 my $nlen = length $name;
190 my $dlen = length $desc;
191 $max_name = $nlen if $nlen > $max_name;
192 $max_desc = $dlen if $dlen > $max_desc;
193 push @fld_desc, [ $name, $desc, $f->{'name'}, $is_pk, $attr ];
198 for my $fld_desc ( @fld_desc ) {
199 my ( $name, $desc, $orig_name, $is_pk, $attr ) = @$fld_desc;
200 my $diff1 = $max_name - length $name;
201 my $diff2 = $max_desc - length $desc;
202 $name .= ' ' x $diff1;
203 $desc .= ' ' x $diff2;
204 $desc = $name . $desc . $attr;
206 push @shapes, [ 'string', $font, $this_col_x, $y, $desc, 'black' ];
207 $y += $font->height + 2;
208 my $length = $this_col_x + ( $font->width * length( $desc ) );
209 $this_max_x = $length if $length > $this_max_x;
211 my $constraints = $table->{'fields'}{ $orig_name }{'constraints'};
213 if ( $natural_join && !$skip{ $orig_name } ) {
214 push @{ $nj_registry{ $orig_name } }, $table_name;
217 my $y_link = $y - $font->height/2;
218 $coords{ $table_name }{ $orig_name }{'coords'} = {
219 left => [ $this_col_x - 6, $y_link ],
220 right => [ $length + 2 , $y_link ],
221 table => $table_name,
222 field_no => ++$field_no,
224 fld_name => $orig_name,
228 $imap_url."#$table_name-$orig_name",
229 $this_col_x, $y - $font->height, $length, $y_link,
233 unless ( $natural_join ) {
234 for my $c ( $table->get_constraints ) {
235 next unless $c->type eq FOREIGN_KEY;
236 my $fk_table = $c->reference_table or next;
238 for my $field_name ( $c->fields ) {
239 for my $fk_field ( $c->reference_fields ) {
240 next unless defined $schema->get_table( $fk_table );
242 [ $fk_table , $fk_field ],
243 [ $table_name, $field_name ],
251 $table_x{ $table_name } = $this_max_x + 5;
252 push @shapes, [ 'line', $this_col_x - 5, $below_table_name,
253 $this_max_x, $below_table_name, 'black' ];
254 my @bounds = ( $this_col_x - 5, $top - 5, $this_max_x, $y + 5 );
258 $bounds[0], $bounds[1],
259 $this_max_x, $below_table_name,
262 unshift @shapes, [ 'filledRectangle', @bounds, 'white' ];
266 $imap_url."#$table_name",
267 $bounds[0], $bounds[1], $this_max_x, $below_table_name,
270 push @shapes, [ 'rectangle', @bounds, 'black' ];
271 $max_x = $this_max_x if $this_max_x > $max_x;
274 if ( ++$no_this_col == $no_per_col ) {# if we've filled up this column
275 $cur_col++; # up the column number
276 $no_this_col = 0; # reset the number of tables
277 $max_x += $gutter; # push the x over for next column
278 $this_col_x = $max_x; # remember the max x for this col
279 $max_y = $y if $y > $max_y; # note the max y
280 $y = $orig_y; # reset the y for next column
289 unless ( $no_lines ) {
290 my @position_bunches;
292 if ( $natural_join ) {
293 for my $field_name ( keys %nj_registry ) {
296 @{ $nj_registry{ $field_name } || [] } or next;
297 next if scalar @table_names == 1;
299 for my $table_name ( @table_names ) {
301 $coords{ $table_name }{ $field_name }{'coords'};
304 push @position_bunches, [ @positions ];
308 for my $pair ( @fk_registry ) {
309 push @position_bunches, [
310 $coords{$pair->[0][0]}{ $pair->[0][1] }{'coords'},
311 $coords{$pair->[1][0]}{ $pair->[1][1] }{'coords'},
316 my $is_directed = $natural_join ? 0 : 1;
318 for my $bunch ( @position_bunches ) {
319 my @positions = @$bunch;
321 for my $i ( 0 .. $#positions ) {
322 my $pos1 = $positions[ $i ];
323 my ( $ax, $ay ) = @{ $pos1->{'left'} || [] } or next;
324 my ( $bx, $by ) = @{ $pos1->{'right'} || [] } or next;
325 my $table1 = $pos1->{'table'};
326 my $fno1 = $pos1->{'field_no'};
327 my $is_pk = $pos1->{'is_pk'};
328 next if $join_pk_only and !$is_pk;
330 for my $j ( 0 .. $#positions ) {
331 my $pos2 = $positions[ $j ];
332 my ( $cx, $cy ) = @{ $pos2->{'left'} || [] } or next;
333 my ( $dx, $dy ) = @{ $pos2->{'right'} || [] } or next;
334 my $table2 = $pos2->{'table'};
335 my $fno2 = $pos2->{'field_no'};
336 next if $table1 eq $table2;
337 next if $done{ $fno1 }{ $fno2 };
338 next if $fno1 == $fno2;
342 abs ( $ax - $cx ) + abs ( $ay - $cy ),
343 [ $ax, $ay, $cx, $cy ],
347 abs ( $ax - $dx ) + abs ( $ay - $dy ),
348 [ $ax, $ay, $dx, $dy ],
352 abs ( $bx - $cx ) + abs ( $by - $cy ),
353 [ $bx, $by, $cx, $cy ],
357 abs ( $bx - $dx ) + abs ( $by - $dy ),
358 [ $bx, $by, $dx, $dy ],
359 [ 'right', 'right' ],
361 @distances = sort { $a->[0] <=> $b->[0] } @distances;
362 my $shortest = $distances[0];
363 my ( $x1, $y1, $x2, $y2 ) = @{ $shortest->[1] };
364 my ( $side1, $side2 ) = @{ $shortest->[2] };
367 my $col1_right = $table_x{ $table1 };
368 my $col2_right = $table_x{ $table2 };
372 while ( $horz_taken{ $x1 + $diff } ) {
373 $diff = $side1 eq 'left' ? $diff - 2 : $diff + 2;
375 $horz_taken{ $x1 + $diff } = 1;
378 if ( $side1 eq 'left' ) {
379 $start = $x1 - $offset + $diff;
382 $start = $col1_right + $diff;
385 if ( $side2 eq 'left' ) {
386 $end = $x2 - $offset + $diff;
389 $end = $col2_right + $diff;
393 [ 'line', $x1, $y1, $start, $y1, 'cadetblue' ];
395 [ 'line', $start, $y1, $end, $y2, 'cadetblue' ];
397 [ 'line', $end, $y2, $x2, $y2, 'cadetblue' ];
399 if ( $is_directed ) {
401 $side1 eq 'right' && $side2 eq 'left'
403 $side1 eq 'left' && $side2 eq 'left'
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 'line', $x2 + 3, $y2 - 3, $x2, $y2, 'cadetblue'
421 'line', $x2 + 3, $y2 + 3, $x2, $y2, 'cadetblue'
424 'line', $x2 + 3, $y2 - 3, $x2 + 3, $y2 +3,
430 $done{ $fno1 }{ $fno2 } = 1;
431 $done{ $fno2 }{ $fno1 } = 1;
438 # Add the title, legend and signature.
440 my $large_font = gdLargeFont;
441 my $title_len = $large_font->width * length $title;
443 'string', $large_font, $max_x/2 - $title_len/2, 10, $title, 'black'
449 'string', $font, $x, $max_y - $font->height - 4, 'Legend', 'black'
451 $max_y += $font->height + 4;
454 for my $len ( map { length $_ } values %legend ) {
455 $longest = $len if $len > $longest;
459 while ( my ( $key, $shape ) = each %legend ) {
460 my $space = $longest - length $shape;
462 'string', $font, $x, $max_y - $font->height - 4,
463 join( '', $shape, ' ' x $space, $key ), 'black'
466 $max_y += $font->height + 4;
470 my $sig = 'Created by SQL::Translator ' . $t->version;
471 my $sig_len = $font->width * length $sig;
473 'string', $font, $max_x - $sig_len, $max_y - $font->height - 4,
480 my $gd = GD::Image->new( $max_x + 30, $max_y );
481 unless ( $gd->can( $output_type ) ) {
482 die "GD can't create images of type '$output_type'\n";
484 my %colors = map { $_->[0], $gd->colorAllocate( @{$_->[1]} ) } (
485 [ white => [ 255, 255, 255 ] ],
486 [ beige => [ 245, 245, 220 ] ],
487 [ black => [ 0, 0, 0 ] ],
488 [ lightblue => [ 173, 216, 230 ] ],
489 [ cadetblue => [ 95, 158, 160 ] ],
490 [ lightgoldenrodyellow => [ 250, 250, 210 ] ],
491 [ khaki => [ 240, 230, 140 ] ],
492 [ red => [ 255, 0, 0 ] ],
494 $gd->interlaced( 'true' );
495 my $background_color = $add_color ? 'lightgoldenrodyellow' : 'white';
496 $gd->fill( 0, 0, $colors{ $background_color } );
497 for my $shape ( @shapes ) {
498 my $method = shift @$shape;
499 my $color = pop @$shape;
500 $gd->$method( @$shape, $colors{ $color } );
506 debug("imap file = '$imap_file'");
507 if ( $imap_file && @imap_coords ) {
508 open my $fh, '>', $imap_file or die "Can't write '$imap_file': $!\n";
509 print $fh qq[<html><body><img src="" usemap="#imap" border="0">\n].
510 qq[<map name="imap">\n];
511 for my $rec ( @imap_coords ) {
512 my $href = shift @$rec;
513 print $fh q[<area coords="].join(',', @$rec).qq[" href="$href">\n];
515 print $fh qq[</body></html>];
523 open my $fh, '>', $out_file or die "Can't write '$out_file': $!\n";
524 print $fh $gd->$output_type;
528 return $gd->$output_type;
534 # -------------------------------------------------------------------
540 Ken Youens-Clark E<lt>kclark@cpan.orgE<gt>.