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(
35 # All args are optional
36 out_file => 'schema.png',# if not provided will go to STDOUT
37 output_type => 'png', # is default or 'jpeg'
38 title => 'My Schema', # default is filename
39 font_size => 'medium', # is default or 'small,' 'large'
40 imap_file => '', # filename to write image map coords
41 imap_url => '', # base URL for image map
42 gutter => 30 # is default, px distance b/w cols
43 num_columns => 5, # the number of columns
44 no_lines => 1, # do not draw lines to show FKs
45 add_color => 1, # give it some color
46 show_fk_only => 1, # show only fields used in FKs
47 join_pk_only => 1, # use only primary keys to figure PKs
48 natural_join => 1, # intuit FKs if not defined
49 skip_fields => [...], # list* of field names to exclude
50 skip_tables => [...], # list* of table names to exclude
51 skip_tables_like => [...], # list* of regexen to exclude tables
53 ) or die SQL::Translator->error;
56 * "list" can be either an array-ref or a comma-separated string
63 use SQL::Translator::Schema::Constants;
64 use SQL::Translator::Utils qw(debug);
66 use vars qw[ $VERSION $DEBUG ];
68 $DEBUG = 0 unless defined $DEBUG;
70 use constant VALID_FONT_SIZE => {
77 use constant VALID_IMAGE_TYPE => {
84 my $schema = $t->schema;
85 my $args = $t->producer_args;
86 local $DEBUG = $t->debug;
87 debug("Schema =\n", Dumper( $schema ));
88 debug("Producer args =\n", Dumper( $args ));
90 my $out_file = $args->{'out_file'} || '';
91 my $output_type = $args->{'output_type'} || 'png';
92 my $title = $args->{'title'} || $t->filename;
93 my $font_size = $args->{'font_size'} || 'medium';
94 my $imap_file = $args->{'imap_file'} || '';
95 my $imap_url = $args->{'imap_url'} || '';
96 my $gutter = $args->{'gutter'} || 30; # distance b/w columns
97 my $num_columns = $args->{'num_columns'} || $args->{'no_columns'} || '';
98 my $no_lines = $args->{'no_lines'};
99 my $add_color = $args->{'add_color'};
100 my $show_fk_only = $args->{'show_fk_only'};
101 my $join_pk_only = $args->{'join_pk_only'};
102 my $natural_join = $args->{'natural_join'} || $join_pk_only;
103 my %skip_field = map { $_, 1 } (
104 ref $args->{'skip_fields'} eq 'ARRAY'
105 ? @{ $args->{'skip_fields'} }
106 : split ( /\s*,\s*/, $args->{'skip_fields'} )
109 my %skip_table = map { $_, 1 } (
110 ref $args->{'skip_tables'} eq 'ARRAY'
111 ? @{ $args->{'skip_tables'} }
112 : split ( /\s*,\s*/, $args->{'skip_tables'} )
115 my @skip_tables_like = map { qr/$_/ } (
116 ref $args->{'skip_tables_like'} eq 'ARRAY'
117 ? @{ $args->{'skip_tables_like'} }
118 : split ( /\s*,\s*/, $args->{'skip_tables_like'} )
122 if ( $natural_join ) {
123 $schema->make_natural_joins(
124 join_pk_only => $join_pk_only,
125 skip_fields => $args->{'skip_fields'},
128 my $g = $schema->as_graph_pm;
129 my $d = Graph::Traversal::DFS->new( $g, next_alphabetic => 1 );
132 @table_names = $d->dfs;
135 @table_names = map { $_->name } $schema->get_tables;
138 die "Invalid image type '$output_type'"
139 unless VALID_IMAGE_TYPE->{ $output_type };
140 die "Invalid font size '$font_size'"
141 unless VALID_FONT_SIZE->{ $font_size };
147 = $font_size eq 'small' ? gdTinyFont
148 : $font_size eq 'medium' ? gdSmallFont
149 : $font_size eq 'large' ? gdLargeFont
152 my $num_tables = scalar @table_names;
153 $num_columns = 0 unless $num_columns =~ /^\d+$/;
154 $num_columns ||= sprintf( "%.0f", sqrt( $num_tables ) + .5 );
156 my $no_per_col = sprintf( "%.0f", $num_tables/$num_columns + .5 );
159 my ( $max_x, $max_y ); # the furthest x and y used
160 my $orig_y = 40; # used to reset y for each column
161 my ( $x, $y ) = (30,$orig_y); # where to start
162 my $cur_col = 1; # the current column
163 my $no_this_col = 0; # number of tables in current column
164 my $this_col_x = $x; # current column's x
165 my %nj_registry; # for locations of fields for natural joins
166 my @fk_registry; # for locations of fields for foreign keys
167 my %table_x; # for max x of each table
168 my $field_no; # counter to give distinct no. to each field
169 my %coords; # holds fields coordinates
170 my @imap_coords; # for making clickable image map
174 for my $table_name ( @table_names ) {
175 my $table = $schema->get_table( $table_name );
177 if ( @skip_tables_like or keys %skip_table ) {
178 next TABLE if $skip_table{ $table_name };
179 for my $regex ( @skip_tables_like ) {
180 next TABLE if $table_name =~ $regex;
186 [ 'string', $font, $this_col_x, $y, $table_name, 'black' ];
187 $y += $font->height + 2;
188 my $below_table_name = $y;
191 $this_col_x + ($font->width * length($table_name));
193 debug("Processing table '$table_name'");
195 my @fields = $table->get_fields;
196 debug("Fields = ", join(', ', map { $_->name } @fields));
198 my ( @fld_desc, $max_name, $max_desc );
199 for my $f ( @fields ) {
200 my $name = $f->name or next;
201 my $is_pk = $f->is_primary_key;
206 # Decide if we should skip this field.
208 if ( $show_fk_only ) {
209 next unless $is_pk || $f->is_foreign_key;
214 $legend{'Primary key'} = '[PK]';
217 if ( $f->is_unique ) {
219 $legend{'Unique constraint'} = '[U]';
222 if ( $f->is_foreign_key ) {
224 $legend{'Foreign Key'} = '[FK]';
229 $attr .= '[' . join(', ', @attr) . ']';
232 my $desc = $f->data_type;
233 $desc .= '('.$f->size.')' if $f->size &&
234 $f->data_type =~ /^(VAR)?CHAR2?$/i;
236 my $nlen = length $name;
237 my $dlen = length $desc;
238 $max_name = $nlen if $nlen > $max_name;
239 $max_desc = $dlen if $dlen > $max_desc;
240 push @fld_desc, [ $name, $desc, $f->{'name'}, $is_pk, $attr ];
245 for my $fld_desc ( @fld_desc ) {
246 my ( $name, $desc, $orig_name, $is_pk, $attr ) = @$fld_desc;
247 my $diff1 = $max_name - length $name;
248 my $diff2 = $max_desc - length $desc;
249 $name .= ' ' x $diff1;
250 $desc .= ' ' x $diff2;
251 $desc = $name . $desc . $attr;
253 push @shapes, [ 'string', $font, $this_col_x, $y, $desc, 'black' ];
254 $y += $font->height + 2;
255 my $length = $this_col_x + ( $font->width * length( $desc ) );
256 $this_max_x = $length if $length > $this_max_x;
258 my $constraints = $table->{'fields'}{ $orig_name }{'constraints'};
260 if ( $natural_join && !$skip_field{ $orig_name } ) {
261 push @{ $nj_registry{ $orig_name } }, $table_name;
264 my $y_link = $y - $font->height/2;
265 $coords{ $table_name }{ $orig_name }{'coords'} = {
266 left => [ $this_col_x - 6, $y_link ],
267 right => [ $length + 2 , $y_link ],
268 table => $table_name,
269 field_no => ++$field_no,
271 fld_name => $orig_name,
275 $imap_url."#$table_name-$orig_name",
276 $this_col_x, $y - $font->height, $length, $y_link,
280 unless ( $natural_join ) {
281 for my $c ( $table->get_constraints ) {
282 next unless $c->type eq FOREIGN_KEY;
283 my $fk_table = $c->reference_table or next;
285 for my $field_name ( $c->fields ) {
286 for my $fk_field ( $c->reference_fields ) {
287 next unless defined $schema->get_table( $fk_table );
289 [ $fk_table , $fk_field ],
290 [ $table_name, $field_name ],
298 $table_x{ $table_name } = $this_max_x + 5;
299 push @shapes, [ 'line', $this_col_x - 5, $below_table_name,
300 $this_max_x, $below_table_name, 'black' ];
301 my @bounds = ( $this_col_x - 5, $top - 5, $this_max_x, $y + 5 );
305 $bounds[0], $bounds[1],
306 $this_max_x, $below_table_name,
309 unshift @shapes, [ 'filledRectangle', @bounds, 'white' ];
313 $imap_url."#$table_name",
314 $bounds[0], $bounds[1], $this_max_x, $below_table_name,
317 push @shapes, [ 'rectangle', @bounds, 'black' ];
318 $max_x = $this_max_x if $this_max_x > $max_x;
321 if ( ++$no_this_col == $no_per_col ) {# if we've filled up this column
322 $cur_col++; # up the column number
323 $no_this_col = 0; # reset the number of tables
324 $max_x += $gutter; # push the x over for next column
325 $this_col_x = $max_x; # remember the max x for this col
326 $max_y = $y if $y > $max_y; # note the max y
327 $y = $orig_y; # reset the y for next column
336 unless ( $no_lines ) {
337 my @position_bunches;
339 if ( $natural_join ) {
340 for my $field_name ( keys %nj_registry ) {
343 @{ $nj_registry{ $field_name } || [] } or next;
344 next if scalar @table_names == 1;
346 for my $table_name ( @table_names ) {
348 $coords{ $table_name }{ $field_name }{'coords'};
351 push @position_bunches, [ @positions ];
355 for my $pair ( @fk_registry ) {
356 push @position_bunches, [
357 $coords{$pair->[0][0]}{ $pair->[0][1] }{'coords'},
358 $coords{$pair->[1][0]}{ $pair->[1][1] }{'coords'},
363 my $is_directed = $natural_join ? 0 : 1;
365 for my $bunch ( @position_bunches ) {
366 my @positions = @$bunch;
368 for my $i ( 0 .. $#positions ) {
369 my $pos1 = $positions[ $i ];
370 my ( $ax, $ay ) = @{ $pos1->{'left'} || [] } or next;
371 my ( $bx, $by ) = @{ $pos1->{'right'} || [] } or next;
372 my $table1 = $pos1->{'table'};
373 my $fno1 = $pos1->{'field_no'};
374 my $is_pk = $pos1->{'is_pk'};
375 next if $join_pk_only and !$is_pk;
377 for my $j ( 0 .. $#positions ) {
378 my $pos2 = $positions[ $j ];
379 my ( $cx, $cy ) = @{ $pos2->{'left'} || [] } or next;
380 my ( $dx, $dy ) = @{ $pos2->{'right'} || [] } or next;
381 my $table2 = $pos2->{'table'};
382 my $fno2 = $pos2->{'field_no'};
383 next if $table1 eq $table2;
384 next if $done{ $fno1 }{ $fno2 };
385 next if $fno1 == $fno2;
389 abs ( $ax - $cx ) + abs ( $ay - $cy ),
390 [ $ax, $ay, $cx, $cy ],
394 abs ( $ax - $dx ) + abs ( $ay - $dy ),
395 [ $ax, $ay, $dx, $dy ],
399 abs ( $bx - $cx ) + abs ( $by - $cy ),
400 [ $bx, $by, $cx, $cy ],
404 abs ( $bx - $dx ) + abs ( $by - $dy ),
405 [ $bx, $by, $dx, $dy ],
406 [ 'right', 'right' ],
408 @distances = sort { $a->[0] <=> $b->[0] } @distances;
409 my $shortest = $distances[0];
410 my ( $x1, $y1, $x2, $y2 ) = @{ $shortest->[1] };
411 my ( $side1, $side2 ) = @{ $shortest->[2] };
414 my $col1_right = $table_x{ $table1 };
415 my $col2_right = $table_x{ $table2 };
419 while ( $horz_taken{ $x1 + $diff } ) {
420 $diff = $side1 eq 'left' ? $diff - 2 : $diff + 2;
422 $horz_taken{ $x1 + $diff } = 1;
425 if ( $side1 eq 'left' ) {
426 $start = $x1 - $offset + $diff;
429 $start = $col1_right + $diff;
432 if ( $side2 eq 'left' ) {
433 $end = $x2 - $offset + $diff;
436 $end = $col2_right + $diff;
440 [ 'line', $x1, $y1, $start, $y1, 'cadetblue' ];
442 [ 'line', $start, $y1, $end, $y2, 'cadetblue' ];
444 [ 'line', $end, $y2, $x2, $y2, 'cadetblue' ];
446 if ( $is_directed ) {
448 $side1 eq 'right' && $side2 eq 'left'
450 $side1 eq 'left' && $side2 eq 'left'
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 'line', $x2 + 3, $y2 - 3, $x2, $y2, 'cadetblue'
468 'line', $x2 + 3, $y2 + 3, $x2, $y2, 'cadetblue'
471 'line', $x2 + 3, $y2 - 3, $x2 + 3, $y2 +3,
477 $done{ $fno1 }{ $fno2 } = 1;
478 $done{ $fno2 }{ $fno1 } = 1;
485 # Add the title, legend and signature.
487 my $large_font = gdLargeFont;
488 my $title_len = $large_font->width * length $title;
490 'string', $large_font, $max_x/2 - $title_len/2, 10, $title, 'black'
496 'string', $font, $x, $max_y - $font->height - 4, 'Legend', 'black'
498 $max_y += $font->height + 4;
501 for my $len ( map { length $_ } values %legend ) {
502 $longest = $len if $len > $longest;
506 while ( my ( $key, $shape ) = each %legend ) {
507 my $space = $longest - length $shape;
509 'string', $font, $x, $max_y - $font->height - 4,
510 join( '', $shape, ' ' x $space, $key ), 'black'
513 $max_y += $font->height + 4;
517 my $sig = 'Created by SQL::Translator ' . $t->version;
518 my $sig_len = $font->width * length $sig;
520 'string', $font, $max_x - $sig_len, $max_y - $font->height - 4,
527 my $gd = GD::Image->new( $max_x + 30, $max_y );
528 unless ( $gd->can( $output_type ) ) {
529 die "GD can't create images of type '$output_type'\n";
531 my %colors = map { $_->[0], $gd->colorAllocate( @{$_->[1]} ) } (
532 [ white => [ 255, 255, 255 ] ],
533 [ beige => [ 245, 245, 220 ] ],
534 [ black => [ 0, 0, 0 ] ],
535 [ lightblue => [ 173, 216, 230 ] ],
536 [ cadetblue => [ 95, 158, 160 ] ],
537 [ lightgoldenrodyellow => [ 250, 250, 210 ] ],
538 [ khaki => [ 240, 230, 140 ] ],
539 [ red => [ 255, 0, 0 ] ],
541 $gd->interlaced( 'true' );
542 my $background_color = $add_color ? 'lightgoldenrodyellow' : 'white';
543 $gd->fill( 0, 0, $colors{ $background_color } );
544 for my $shape ( @shapes ) {
545 my $method = shift @$shape;
546 my $color = pop @$shape;
547 $gd->$method( @$shape, $colors{ $color } );
553 debug("imap file = '$imap_file'");
554 if ( $imap_file && @imap_coords ) {
555 open my $fh, '>', $imap_file or die "Can't write '$imap_file': $!\n";
556 print $fh qq[<html><body><img src="" usemap="#imap" border="0">\n].
557 qq[<map name="imap">\n];
558 for my $rec ( @imap_coords ) {
559 my $href = shift @$rec;
560 print $fh q[<area coords="].join(',', @$rec).qq[" href="$href">\n];
562 print $fh qq[</body></html>];
570 open my $fh, '>', $out_file or die "Can't write '$out_file': $!\n";
572 print $fh $gd->$output_type;
576 return $gd->$output_type;
582 # -------------------------------------------------------------------
588 Ken Youens-Clark E<lt>kclark@cpan.orgE<gt>.