1 package SQL::Translator::Producer::Diagram;
5 SQL::Translator::Producer::Diagram - ER diagram producer for SQL::Translator
9 Use via SQL::Translator:
13 my $t = SQL::Translator->new(
17 # All args are optional
18 out_file => 'schema.png',# if not provided will go to STDOUT
19 output_type => 'png', # is default or 'jpeg'
20 title => 'My Schema', # default is filename
21 font_size => 'medium', # is default or 'small,' 'large'
22 imap_file => '', # filename to write image map coords
23 imap_url => '', # base URL for image map
24 gutter => 30 # is default, px distance b/w cols
25 num_columns => 5, # the number of columns
26 no_lines => 1, # do not draw lines to show FKs
27 add_color => 1, # give it some color
28 show_fk_only => 1, # show only fields used in FKs
29 join_pk_only => 1, # use only primary keys to figure PKs
30 natural_join => 1, # intuit FKs if not defined
31 skip_fields => [...], # list* of field names to exclude
32 skip_tables => [...], # list* of table names to exclude
33 skip_tables_like => [...], # list* of regexen to exclude tables
35 ) or die SQL::Translator->error;
38 * "list" can be either an array-ref or a comma-separated string
45 use SQL::Translator::Schema::Constants;
46 use SQL::Translator::Utils qw(debug);
48 use vars qw[ $VERSION $DEBUG ];
50 $DEBUG = 0 unless defined $DEBUG;
52 use constant VALID_FONT_SIZE => {
59 use constant VALID_IMAGE_TYPE => {
66 my $schema = $t->schema;
67 my $args = $t->producer_args;
68 local $DEBUG = $t->debug;
69 debug("Schema =\n", Dumper( $schema ));
70 debug("Producer args =\n", Dumper( $args ));
72 my $out_file = $args->{'out_file'} || '';
73 my $output_type = $args->{'output_type'} || 'png';
74 my $title = $args->{'title'} || $t->filename;
75 my $font_size = $args->{'font_size'} || 'medium';
76 my $imap_file = $args->{'imap_file'} || '';
77 my $imap_url = $args->{'imap_url'} || '';
78 my $gutter = $args->{'gutter'} || 30; # distance b/w columns
79 my $num_columns = $args->{'num_columns'} || $args->{'no_columns'} || '';
80 my $no_lines = $args->{'no_lines'};
81 my $add_color = $args->{'add_color'};
82 my $show_fk_only = $args->{'show_fk_only'};
83 my $join_pk_only = $args->{'join_pk_only'};
84 my $natural_join = $args->{'natural_join'} || $join_pk_only;
85 my %skip_field = map { $_, 1 } (
86 ref $args->{'skip_fields'} eq 'ARRAY'
87 ? @{ $args->{'skip_fields'} }
88 : split ( /\s*,\s*/, $args->{'skip_fields'} )
91 my %skip_table = map { $_, 1 } (
92 ref $args->{'skip_tables'} eq 'ARRAY'
93 ? @{ $args->{'skip_tables'} }
94 : split ( /\s*,\s*/, $args->{'skip_tables'} )
97 my @skip_tables_like = map { qr/$_/ } (
98 ref $args->{'skip_tables_like'} eq 'ARRAY'
99 ? @{ $args->{'skip_tables_like'} }
100 : split ( /\s*,\s*/, $args->{'skip_tables_like'} )
104 if ( $natural_join ) {
105 $schema->make_natural_joins(
106 join_pk_only => $join_pk_only,
107 skip_fields => $args->{'skip_fields'},
110 my $g = $schema->as_graph_pm;
111 my $d = Graph::Traversal::DFS->new( $g, next_alphabetic => 1 );
114 @table_names = $d->dfs;
117 @table_names = map { $_->name } $schema->get_tables;
120 die "Invalid image type '$output_type'"
121 unless VALID_IMAGE_TYPE->{ $output_type };
122 die "Invalid font size '$font_size'"
123 unless VALID_FONT_SIZE->{ $font_size };
129 = $font_size eq 'small' ? gdTinyFont
130 : $font_size eq 'medium' ? gdSmallFont
131 : $font_size eq 'large' ? gdLargeFont
134 my $num_tables = scalar @table_names;
135 $num_columns = 0 unless $num_columns =~ /^\d+$/;
136 $num_columns ||= sprintf( "%.0f", sqrt( $num_tables ) + .5 );
138 my $no_per_col = sprintf( "%.0f", $num_tables/$num_columns + .5 );
141 my ( $max_x, $max_y ); # the furthest x and y used
142 my $orig_y = 40; # used to reset y for each column
143 my ( $x, $y ) = (30,$orig_y); # where to start
144 my $cur_col = 1; # the current column
145 my $no_this_col = 0; # number of tables in current column
146 my $this_col_x = $x; # current column's x
147 my %nj_registry; # for locations of fields for natural joins
148 my @fk_registry; # for locations of fields for foreign keys
149 my %table_x; # for max x of each table
150 my $field_no; # counter to give distinct no. to each field
151 my %coords; # holds fields coordinates
152 my @imap_coords; # for making clickable image map
156 for my $table_name ( @table_names ) {
157 my $table = $schema->get_table( $table_name );
159 if ( @skip_tables_like or keys %skip_table ) {
160 next TABLE if $skip_table{ $table_name };
161 for my $regex ( @skip_tables_like ) {
162 next TABLE if $table_name =~ $regex;
168 [ 'string', $font, $this_col_x, $y, $table_name, 'black' ];
169 $y += $font->height + 2;
170 my $below_table_name = $y;
173 $this_col_x + ($font->width * length($table_name));
175 debug("Processing table '$table_name'");
177 my @fields = $table->get_fields;
178 debug("Fields = ", join(', ', map { $_->name } @fields));
180 my ( @fld_desc, $max_name, $max_desc );
181 for my $f ( @fields ) {
182 my $name = $f->name or next;
183 my $is_pk = $f->is_primary_key;
188 # Decide if we should skip this field.
190 if ( $show_fk_only ) {
191 next unless $is_pk || $f->is_foreign_key;
196 $legend{'Primary key'} = '[PK]';
199 if ( $f->is_unique ) {
201 $legend{'Unique constraint'} = '[U]';
204 if ( $f->is_foreign_key ) {
206 $legend{'Foreign Key'} = '[FK]';
211 $attr .= '[' . join(', ', @attr) . ']';
214 my $desc = $f->data_type;
215 $desc .= '('.$f->size.')' if $f->size &&
216 $f->data_type =~ /^(VAR)?CHAR2?$/i;
218 my $nlen = length $name;
219 my $dlen = length $desc;
220 $max_name = $nlen if $nlen > $max_name;
221 $max_desc = $dlen if $dlen > $max_desc;
222 push @fld_desc, [ $name, $desc, $f->{'name'}, $is_pk, $attr ];
227 for my $fld_desc ( @fld_desc ) {
228 my ( $name, $desc, $orig_name, $is_pk, $attr ) = @$fld_desc;
229 my $diff1 = $max_name - length $name;
230 my $diff2 = $max_desc - length $desc;
231 $name .= ' ' x $diff1;
232 $desc .= ' ' x $diff2;
233 $desc = $name . $desc . $attr;
235 push @shapes, [ 'string', $font, $this_col_x, $y, $desc, 'black' ];
236 $y += $font->height + 2;
237 my $length = $this_col_x + ( $font->width * length( $desc ) );
238 $this_max_x = $length if $length > $this_max_x;
240 my $constraints = $table->{'fields'}{ $orig_name }{'constraints'};
242 if ( $natural_join && !$skip_field{ $orig_name } ) {
243 push @{ $nj_registry{ $orig_name } }, $table_name;
246 my $y_link = $y - $font->height/2;
247 $coords{ $table_name }{ $orig_name }{'coords'} = {
248 left => [ $this_col_x - 6, $y_link ],
249 right => [ $length + 2 , $y_link ],
250 table => $table_name,
251 field_no => ++$field_no,
253 fld_name => $orig_name,
257 $imap_url."#$table_name-$orig_name",
258 $this_col_x, $y - $font->height, $length, $y_link,
262 unless ( $natural_join ) {
263 for my $c ( $table->get_constraints ) {
264 next unless $c->type eq FOREIGN_KEY;
265 my $fk_table = $c->reference_table or next;
267 for my $field_name ( $c->fields ) {
268 for my $fk_field ( $c->reference_fields ) {
269 next unless defined $schema->get_table( $fk_table );
271 [ $fk_table , $fk_field ],
272 [ $table_name, $field_name ],
280 $table_x{ $table_name } = $this_max_x + 5;
281 push @shapes, [ 'line', $this_col_x - 5, $below_table_name,
282 $this_max_x, $below_table_name, 'black' ];
283 my @bounds = ( $this_col_x - 5, $top - 5, $this_max_x, $y + 5 );
287 $bounds[0], $bounds[1],
288 $this_max_x, $below_table_name,
291 unshift @shapes, [ 'filledRectangle', @bounds, 'white' ];
295 $imap_url."#$table_name",
296 $bounds[0], $bounds[1], $this_max_x, $below_table_name,
299 push @shapes, [ 'rectangle', @bounds, 'black' ];
300 $max_x = $this_max_x if $this_max_x > $max_x;
303 if ( ++$no_this_col == $no_per_col ) {# if we've filled up this column
304 $cur_col++; # up the column number
305 $no_this_col = 0; # reset the number of tables
306 $max_x += $gutter; # push the x over for next column
307 $this_col_x = $max_x; # remember the max x for this col
308 $max_y = $y if $y > $max_y; # note the max y
309 $y = $orig_y; # reset the y for next column
318 unless ( $no_lines ) {
319 my @position_bunches;
321 if ( $natural_join ) {
322 for my $field_name ( keys %nj_registry ) {
325 @{ $nj_registry{ $field_name } || [] } or next;
326 next if scalar @table_names == 1;
328 for my $table_name ( @table_names ) {
330 $coords{ $table_name }{ $field_name }{'coords'};
333 push @position_bunches, [ @positions ];
337 for my $pair ( @fk_registry ) {
338 push @position_bunches, [
339 $coords{$pair->[0][0]}{ $pair->[0][1] }{'coords'},
340 $coords{$pair->[1][0]}{ $pair->[1][1] }{'coords'},
345 my $is_directed = $natural_join ? 0 : 1;
347 for my $bunch ( @position_bunches ) {
348 my @positions = @$bunch;
350 for my $i ( 0 .. $#positions ) {
351 my $pos1 = $positions[ $i ];
352 my ( $ax, $ay ) = @{ $pos1->{'left'} || [] } or next;
353 my ( $bx, $by ) = @{ $pos1->{'right'} || [] } or next;
354 my $table1 = $pos1->{'table'};
355 my $fno1 = $pos1->{'field_no'};
356 my $is_pk = $pos1->{'is_pk'};
357 next if $join_pk_only and !$is_pk;
359 for my $j ( 0 .. $#positions ) {
360 my $pos2 = $positions[ $j ];
361 my ( $cx, $cy ) = @{ $pos2->{'left'} || [] } or next;
362 my ( $dx, $dy ) = @{ $pos2->{'right'} || [] } or next;
363 my $table2 = $pos2->{'table'};
364 my $fno2 = $pos2->{'field_no'};
365 next if $table1 eq $table2;
366 next if $done{ $fno1 }{ $fno2 };
367 next if $fno1 == $fno2;
371 abs ( $ax - $cx ) + abs ( $ay - $cy ),
372 [ $ax, $ay, $cx, $cy ],
376 abs ( $ax - $dx ) + abs ( $ay - $dy ),
377 [ $ax, $ay, $dx, $dy ],
381 abs ( $bx - $cx ) + abs ( $by - $cy ),
382 [ $bx, $by, $cx, $cy ],
386 abs ( $bx - $dx ) + abs ( $by - $dy ),
387 [ $bx, $by, $dx, $dy ],
388 [ 'right', 'right' ],
390 @distances = sort { $a->[0] <=> $b->[0] } @distances;
391 my $shortest = $distances[0];
392 my ( $x1, $y1, $x2, $y2 ) = @{ $shortest->[1] };
393 my ( $side1, $side2 ) = @{ $shortest->[2] };
396 my $col1_right = $table_x{ $table1 };
397 my $col2_right = $table_x{ $table2 };
401 while ( $horz_taken{ $x1 + $diff } ) {
402 $diff = $side1 eq 'left' ? $diff - 2 : $diff + 2;
404 $horz_taken{ $x1 + $diff } = 1;
407 if ( $side1 eq 'left' ) {
408 $start = $x1 - $offset + $diff;
411 $start = $col1_right + $diff;
414 if ( $side2 eq 'left' ) {
415 $end = $x2 - $offset + $diff;
418 $end = $col2_right + $diff;
422 [ 'line', $x1, $y1, $start, $y1, 'cadetblue' ];
424 [ 'line', $start, $y1, $end, $y2, 'cadetblue' ];
426 [ 'line', $end, $y2, $x2, $y2, 'cadetblue' ];
428 if ( $is_directed ) {
430 $side1 eq 'right' && $side2 eq 'left'
432 $side1 eq 'left' && $side2 eq 'left'
435 'line', $x2 - 3, $y2 - 3, $x2, $y2, 'cadetblue'
438 'line', $x2 - 3, $y2 + 3, $x2, $y2, 'cadetblue'
441 'line', $x2 - 3, $y2 - 3, $x2 - 3, $y2 +3,
447 'line', $x2 + 3, $y2 - 3, $x2, $y2, 'cadetblue'
450 'line', $x2 + 3, $y2 + 3, $x2, $y2, 'cadetblue'
453 'line', $x2 + 3, $y2 - 3, $x2 + 3, $y2 +3,
459 $done{ $fno1 }{ $fno2 } = 1;
460 $done{ $fno2 }{ $fno1 } = 1;
467 # Add the title, legend and signature.
469 my $large_font = gdLargeFont;
470 my $title_len = $large_font->width * length $title;
472 'string', $large_font, $max_x/2 - $title_len/2, 10, $title, 'black'
478 'string', $font, $x, $max_y - $font->height - 4, 'Legend', 'black'
480 $max_y += $font->height + 4;
483 for my $len ( map { length $_ } values %legend ) {
484 $longest = $len if $len > $longest;
488 while ( my ( $key, $shape ) = each %legend ) {
489 my $space = $longest - length $shape;
491 'string', $font, $x, $max_y - $font->height - 4,
492 join( '', $shape, ' ' x $space, $key ), 'black'
495 $max_y += $font->height + 4;
499 my $sig = 'Created by SQL::Translator ' . $t->version;
500 my $sig_len = $font->width * length $sig;
502 'string', $font, $max_x - $sig_len, $max_y - $font->height - 4,
509 my $gd = GD::Image->new( $max_x + 30, $max_y );
510 unless ( $gd->can( $output_type ) ) {
511 die "GD can't create images of type '$output_type'\n";
513 my %colors = map { $_->[0], $gd->colorAllocate( @{$_->[1]} ) } (
514 [ white => [ 255, 255, 255 ] ],
515 [ beige => [ 245, 245, 220 ] ],
516 [ black => [ 0, 0, 0 ] ],
517 [ lightblue => [ 173, 216, 230 ] ],
518 [ cadetblue => [ 95, 158, 160 ] ],
519 [ lightgoldenrodyellow => [ 250, 250, 210 ] ],
520 [ khaki => [ 240, 230, 140 ] ],
521 [ red => [ 255, 0, 0 ] ],
523 $gd->interlaced( 'true' );
524 my $background_color = $add_color ? 'lightgoldenrodyellow' : 'white';
525 $gd->fill( 0, 0, $colors{ $background_color } );
526 for my $shape ( @shapes ) {
527 my $method = shift @$shape;
528 my $color = pop @$shape;
529 $gd->$method( @$shape, $colors{ $color } );
535 debug("imap file = '$imap_file'");
536 if ( $imap_file && @imap_coords ) {
537 open my $fh, '>', $imap_file or die "Can't write '$imap_file': $!\n";
538 print $fh qq[<html><body><img src="" usemap="#imap" border="0">\n].
539 qq[<map name="imap">\n];
540 for my $rec ( @imap_coords ) {
541 my $href = shift @$rec;
542 print $fh q[<area coords="].join(',', @$rec).qq[" href="$href">\n];
544 print $fh qq[</body></html>];
552 open my $fh, '>', $out_file or die "Can't write '$out_file': $!\n";
554 print $fh $gd->$output_type;
558 return $gd->$output_type;
564 # -------------------------------------------------------------------
570 Ken Youens-Clark E<lt>kclark@cpan.orgE<gt>.