gitignoring
[dbsrgits/SQL-Translator.git] / lib / SQL / Translator / Producer / Diagram.pm
CommitLineData
37503827 1package SQL::Translator::Producer::Diagram;
2
44659089 3# -------------------------------------------------------------------
4# Copyright (C) 2002-2009 SQLFairy Authors
5#
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.
9#
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.
14#
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
18# 02111-1307 USA
19# -------------------------------------------------------------------
20
e966b2b0 21=head1 NAME
22
23SQL::Translator::Producer::Diagram - ER diagram producer for SQL::Translator
24
25=head1 SYNOPSIS
26
27Use via SQL::Translator:
28
29 use SQL::Translator;
30
9d4a26be 31 my $t = SQL::Translator->new(
32 from => 'MySQL',
33 to => 'GraphViz',
34 producer_args => {
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
52 }
53 ) or die SQL::Translator->error;
e966b2b0 54 $t->translate;
55
9d4a26be 56* "list" can be either an array-ref or a comma-separated string
57
e966b2b0 58=cut
59
37503827 60use strict;
61use GD;
62use Data::Dumper;
761fa621 63use SQL::Translator::Schema::Constants;
37503827 64use SQL::Translator::Utils qw(debug);
65
da06ac74 66use vars qw[ $VERSION $DEBUG ];
11ad2df9 67$VERSION = '1.59';
37503827 68$DEBUG = 0 unless defined $DEBUG;
69
70use constant VALID_FONT_SIZE => {
71 small => 1,
72 medium => 1,
73 large => 1,
74 huge => 1,
75};
76
77use constant VALID_IMAGE_TYPE => {
78 png => 1,
79 jpeg => 1,
80};
81
82sub produce {
761fa621 83 my $t = shift;
84 my $schema = $t->schema;
37503827 85 my $args = $t->producer_args;
86 local $DEBUG = $t->debug;
761fa621 87 debug("Schema =\n", Dumper( $schema ));
37503827 88 debug("Producer args =\n", Dumper( $args ));
89
6a20798b 90 my $out_file = $args->{'out_file'} || '';
9d4a26be 91 my $output_type = $args->{'output_type'} || 'png';
6a20798b 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'} || '';
01a182ab 96 my $gutter = $args->{'gutter'} || 30; # distance b/w columns
9d4a26be 97 my $num_columns = $args->{'num_columns'} || $args->{'no_columns'} || '';
37503827 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;
9d4a26be 103 my %skip_field = map { $_, 1 } (
104 ref $args->{'skip_fields'} eq 'ARRAY'
105 ? @{ $args->{'skip_fields'} }
106 : split ( /\s*,\s*/, $args->{'skip_fields'} )
107 );
108
109 my %skip_table = map { $_, 1 } (
110 ref $args->{'skip_tables'} eq 'ARRAY'
111 ? @{ $args->{'skip_tables'} }
112 : split ( /\s*,\s*/, $args->{'skip_tables'} )
113 );
114
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'} )
119 );
761fa621 120
dcac44eb 121 my @table_names;
122 if ( $natural_join ) {
123 $schema->make_natural_joins(
124 join_pk_only => $join_pk_only,
125 skip_fields => $args->{'skip_fields'},
126 );
127
128 my $g = $schema->as_graph_pm;
129 my $d = Graph::Traversal::DFS->new( $g, next_alphabetic => 1 );
130 $d->preorder;
131
132 @table_names = $d->dfs;
133 }
134 else {
135 @table_names = map { $_->name } $schema->get_tables;
136 }
37503827 137
7652721a 138 die "Invalid image type '$output_type'"
9d4a26be 139 unless VALID_IMAGE_TYPE->{ $output_type };
37503827 140 die "Invalid font size '$font_size'"
141 unless VALID_FONT_SIZE->{ $font_size };
142
143 #
144 # Layout the image.
145 #
dcac44eb 146 my $font
147 = $font_size eq 'small' ? gdTinyFont
148 : $font_size eq 'medium' ? gdSmallFont
149 : $font_size eq 'large' ? gdLargeFont
150 : gdGiantFont;
151
9d4a26be 152 my $num_tables = scalar @table_names;
153 $num_columns = 0 unless $num_columns =~ /^\d+$/;
154 $num_columns ||= sprintf( "%.0f", sqrt( $num_tables ) + .5 );
155 $num_columns ||= .5;
156 my $no_per_col = sprintf( "%.0f", $num_tables/$num_columns + .5 );
37503827 157
158 my @shapes;
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
37503827 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
761fa621 169 my %coords; # holds fields coordinates
6a20798b 170 my @imap_coords; # for making clickable image map
37503827 171 my %legend;
172
9d4a26be 173 TABLE:
dcac44eb 174 for my $table_name ( @table_names ) {
175 my $table = $schema->get_table( $table_name );
9d4a26be 176
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;
181 }
182 }
183
dcac44eb 184 my $top = $y;
37503827 185 push @shapes,
186 [ 'string', $font, $this_col_x, $y, $table_name, 'black' ];
37503827 187 $y += $font->height + 2;
188 my $below_table_name = $y;
189 $y += 2;
190 my $this_max_x =
191 $this_col_x + ($font->width * length($table_name));
192
193 debug("Processing table '$table_name'");
194
761fa621 195 my @fields = $table->get_fields;
196 debug("Fields = ", join(', ', map { $_->name } @fields));
37503827 197
60dcc980 198 my ( @fld_desc, $max_name, $max_desc );
37503827 199 for my $f ( @fields ) {
761fa621 200 my $name = $f->name or next;
201 my $is_pk = $f->is_primary_key;
37503827 202
60dcc980 203 my @attr;
204
37503827 205 #
206 # Decide if we should skip this field.
207 #
208 if ( $show_fk_only ) {
761fa621 209 next unless $is_pk || $f->is_foreign_key;
37503827 210 }
211
212 if ( $is_pk ) {
60dcc980 213 push @attr, 'PK';
214 $legend{'Primary key'} = '[PK]';
37503827 215 }
cd9ccb3e 216
217 if ( $f->is_unique ) {
60dcc980 218 push @attr, 'U';
37503827 219 $legend{'Unique constraint'} = '[U]';
220 }
221
60dcc980 222 if ( $f->is_foreign_key ) {
223 push @attr, 'FK';
224 $legend{'Foreign Key'} = '[FK]';
225 }
226
227 my $attr = '';
228 if ( @attr ) {
229 $attr .= '[' . join(', ', @attr) . ']';
230 }
231
761fa621 232 my $desc = $f->data_type;
60dcc980 233 $desc .= '('.$f->size.')' if $f->size &&
234 $f->data_type =~ /^(VAR)?CHAR2?$/i;
37503827 235
236 my $nlen = length $name;
60dcc980 237 my $dlen = length $desc;
37503827 238 $max_name = $nlen if $nlen > $max_name;
60dcc980 239 $max_desc = $dlen if $dlen > $max_desc;
240 push @fld_desc, [ $name, $desc, $f->{'name'}, $is_pk, $attr ];
37503827 241 }
242
60dcc980 243 $max_name += 2;
244 $max_desc += 2;
37503827 245 for my $fld_desc ( @fld_desc ) {
60dcc980 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;
37503827 252
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;
257
258 my $constraints = $table->{'fields'}{ $orig_name }{'constraints'};
259
9d4a26be 260 if ( $natural_join && !$skip_field{ $orig_name } ) {
37503827 261 push @{ $nj_registry{ $orig_name } }, $table_name;
262 }
37503827 263
264 my $y_link = $y - $font->height/2;
761fa621 265 $coords{ $table_name }{ $orig_name }{'coords'} = {
37503827 266 left => [ $this_col_x - 6, $y_link ],
267 right => [ $length + 2 , $y_link ],
268 table => $table_name,
269 field_no => ++$field_no,
270 is_pk => $is_pk,
271 fld_name => $orig_name,
272 };
6a20798b 273
274 push @imap_coords, [
275 $imap_url."#$table_name-$orig_name",
276 $this_col_x, $y - $font->height, $length, $y_link,
277 ];
37503827 278 }
279
761fa621 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;
284
285 for my $field_name ( $c->fields ) {
286 for my $fk_field ( $c->reference_fields ) {
287 next unless defined $schema->get_table( $fk_table );
288 push @fk_registry, [
761fa621 289 [ $fk_table , $fk_field ],
761a28bb 290 [ $table_name, $field_name ],
761fa621 291 ];
292 }
293 }
294 }
295 }
296
37503827 297 $this_max_x += 5;
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 );
302 if ( $add_color ) {
303 unshift @shapes, [
304 'filledRectangle',
305 $bounds[0], $bounds[1],
306 $this_max_x, $below_table_name,
307 'khaki'
308 ];
309 unshift @shapes, [ 'filledRectangle', @bounds, 'white' ];
310 }
6a20798b 311
312 push @imap_coords, [
313 $imap_url."#$table_name",
314 $bounds[0], $bounds[1], $this_max_x, $below_table_name,
315 ];
316
37503827 317 push @shapes, [ 'rectangle', @bounds, 'black' ];
318 $max_x = $this_max_x if $this_max_x > $max_x;
319 $y += 25;
320
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
328 }
329 }
330
331 #
332 # Connect the lines.
333 #
334 my %horz_taken;
335 my %done;
336 unless ( $no_lines ) {
337 my @position_bunches;
338
339 if ( $natural_join ) {
340 for my $field_name ( keys %nj_registry ) {
341 my @positions;
342 my @table_names =
343 @{ $nj_registry{ $field_name } || [] } or next;
344 next if scalar @table_names == 1;
345
346 for my $table_name ( @table_names ) {
347 push @positions,
761fa621 348 $coords{ $table_name }{ $field_name }{'coords'};
37503827 349 }
350
351 push @position_bunches, [ @positions ];
352 }
353 }
354 else {
355 for my $pair ( @fk_registry ) {
356 push @position_bunches, [
761fa621 357 $coords{$pair->[0][0]}{ $pair->[0][1] }{'coords'},
358 $coords{$pair->[1][0]}{ $pair->[1][1] }{'coords'},
37503827 359 ];
360 }
361 }
362
363 my $is_directed = $natural_join ? 0 : 1;
364
365 for my $bunch ( @position_bunches ) {
366 my @positions = @$bunch;
367
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;
376
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;
386
387 my @distances = ();
388 push @distances, [
389 abs ( $ax - $cx ) + abs ( $ay - $cy ),
390 [ $ax, $ay, $cx, $cy ],
391 [ 'left', 'left' ]
392 ];
393 push @distances, [
394 abs ( $ax - $dx ) + abs ( $ay - $dy ),
395 [ $ax, $ay, $dx, $dy ],
396 [ 'left', 'right' ],
397 ];
398 push @distances, [
399 abs ( $bx - $cx ) + abs ( $by - $cy ),
400 [ $bx, $by, $cx, $cy ],
401 [ 'right', 'left' ],
402 ];
403 push @distances, [
404 abs ( $bx - $dx ) + abs ( $by - $dy ),
405 [ $bx, $by, $dx, $dy ],
406 [ 'right', 'right' ],
407 ];
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] };
412 my ( $start, $end );
413 my $offset = 9;
414 my $col1_right = $table_x{ $table1 };
415 my $col2_right = $table_x{ $table2 };
416
417 my $diff = 0;
418 if ( $x1 == $x2 ) {
419 while ( $horz_taken{ $x1 + $diff } ) {
420 $diff = $side1 eq 'left' ? $diff - 2 : $diff + 2;
421 }
422 $horz_taken{ $x1 + $diff } = 1;
423 }
424
425 if ( $side1 eq 'left' ) {
426 $start = $x1 - $offset + $diff;
427 }
428 else {
429 $start = $col1_right + $diff;
430 }
431
432 if ( $side2 eq 'left' ) {
433 $end = $x2 - $offset + $diff;
434 }
435 else {
436 $end = $col2_right + $diff;
437 }
438
439 push @shapes,
440 [ 'line', $x1, $y1, $start, $y1, 'cadetblue' ];
441 push @shapes,
442 [ 'line', $start, $y1, $end, $y2, 'cadetblue' ];
443 push @shapes,
444 [ 'line', $end, $y2, $x2, $y2, 'cadetblue' ];
445
446 if ( $is_directed ) {
447 if (
448 $side1 eq 'right' && $side2 eq 'left'
449 ||
450 $side1 eq 'left' && $side2 eq 'left'
451 ) {
452 push @shapes, [
453 'line', $x2 - 3, $y2 - 3, $x2, $y2, 'cadetblue'
454 ];
455 push @shapes, [
456 'line', $x2 - 3, $y2 + 3, $x2, $y2, 'cadetblue'
457 ];
458 push @shapes, [
459 'line', $x2 - 3, $y2 - 3, $x2 - 3, $y2 +3,
460 'cadetblue'
461 ];
462 }
463 else {
464 push @shapes, [
465 'line', $x2 + 3, $y2 - 3, $x2, $y2, 'cadetblue'
466 ];
467 push @shapes, [
468 'line', $x2 + 3, $y2 + 3, $x2, $y2, 'cadetblue'
469 ];
470 push @shapes, [
471 'line', $x2 + 3, $y2 - 3, $x2 + 3, $y2 +3,
472 'cadetblue'
473 ];
474 }
475 }
476
477 $done{ $fno1 }{ $fno2 } = 1;
478 $done{ $fno2 }{ $fno1 } = 1;
479 }
480 }
481 }
482 }
483
484 #
485 # Add the title, legend and signature.
486 #
487 my $large_font = gdLargeFont;
488 my $title_len = $large_font->width * length $title;
489 push @shapes, [
490 'string', $large_font, $max_x/2 - $title_len/2, 10, $title, 'black'
491 ];
492
493 if ( %legend ) {
494 $max_y += 5;
495 push @shapes, [
496 'string', $font, $x, $max_y - $font->height - 4, 'Legend', 'black'
497 ];
498 $max_y += $font->height + 4;
499
500 my $longest;
501 for my $len ( map { length $_ } values %legend ) {
502 $longest = $len if $len > $longest;
503 }
504 $longest += 2;
505
506 while ( my ( $key, $shape ) = each %legend ) {
507 my $space = $longest - length $shape;
508 push @shapes, [
509 'string', $font, $x, $max_y - $font->height - 4,
510 join( '', $shape, ' ' x $space, $key ), 'black'
511 ];
512
513 $max_y += $font->height + 4;
514 }
515 }
516
60dcc980 517 my $sig = 'Created by SQL::Translator ' . $t->version;
37503827 518 my $sig_len = $font->width * length $sig;
519 push @shapes, [
520 'string', $font, $max_x - $sig_len, $max_y - $font->height - 4,
521 $sig, 'black'
522 ];
523
524 #
525 # Render the image.
526 #
527 my $gd = GD::Image->new( $max_x + 30, $max_y );
7652721a 528 unless ( $gd->can( $output_type ) ) {
529 die "GD can't create images of type '$output_type'\n";
37503827 530 }
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 ] ],
540 );
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 } );
548 }
549
550 #
6a20798b 551 # Make image map.
552 #
553 debug("imap file = '$imap_file'");
554 if ( $imap_file && @imap_coords ) {
d4924f25 555 open my $fh, '>', $imap_file or die "Can't write '$imap_file': $!\n";
6a20798b 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];
561 }
562 print $fh qq[</body></html>];
563 close $fh;
564 }
565
566 #
37503827 567 # Print the image.
568 #
569 if ( $out_file ) {
d4924f25 570 open my $fh, '>', $out_file or die "Can't write '$out_file': $!\n";
54c61e72 571 binmode $fh;
7652721a 572 print $fh $gd->$output_type;
37503827 573 close $fh;
574 }
575 else {
7652721a 576 return $gd->$output_type;
37503827 577 }
578}
579
5801;
581
977651a5 582# -------------------------------------------------------------------
583
37503827 584=pod
585
37503827 586=head1 AUTHOR
587
d4924f25 588Ken Youens-Clark E<lt>kclark@cpan.orgE<gt>.
37503827 589
590=cut