Actually there was an empty test for it as well :)
[dbsrgits/SQL-Translator.git] / lib / SQL / Translator / Producer / Diagram.pm
CommitLineData
37503827 1package SQL::Translator::Producer::Diagram;
2
3# -------------------------------------------------------------------
d4f84dd1 4# $Id: Diagram.pm 1440 2009-01-17 16:31:57Z jawnsy $
37503827 5# -------------------------------------------------------------------
478f608d 6# Copyright (C) 2002-2009 SQLFairy Authors
37503827 7#
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.
11#
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.
16#
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
20# 02111-1307 USA
21# -------------------------------------------------------------------
22
e966b2b0 23=head1 NAME
24
25SQL::Translator::Producer::Diagram - ER diagram producer for SQL::Translator
26
27=head1 SYNOPSIS
28
29Use via SQL::Translator:
30
31 use SQL::Translator;
32
9f61e9f2 33 my $t = SQL::Translator->new( producer => 'Diagram', '...' );
e966b2b0 34 $t->translate;
35
e966b2b0 36=cut
37
37503827 38use strict;
39use GD;
40use Data::Dumper;
761fa621 41use SQL::Translator::Schema::Constants;
37503827 42use SQL::Translator::Utils qw(debug);
43
478f608d 44use vars qw[ $DEBUG ];
37503827 45$DEBUG = 0 unless defined $DEBUG;
46
47use constant VALID_FONT_SIZE => {
48 small => 1,
49 medium => 1,
50 large => 1,
51 huge => 1,
52};
53
54use constant VALID_IMAGE_TYPE => {
55 png => 1,
56 jpeg => 1,
57};
58
59sub produce {
761fa621 60 my $t = shift;
61 my $schema = $t->schema;
37503827 62 my $args = $t->producer_args;
63 local $DEBUG = $t->debug;
761fa621 64 debug("Schema =\n", Dumper( $schema ));
37503827 65 debug("Producer args =\n", Dumper( $args ));
66
6a20798b 67 my $out_file = $args->{'out_file'} || '';
7652721a 68 my $output_type = $args->{'output_type'} || 'png';
6a20798b 69 my $title = $args->{'title'} || $t->filename;
70 my $font_size = $args->{'font_size'} || 'medium';
71 my $imap_file = $args->{'imap_file'} || '';
72 my $imap_url = $args->{'imap_url'} || '';
01a182ab 73 my $gutter = $args->{'gutter'} || 30; # distance b/w columns
37503827 74 my $no_columns = $args->{'no_columns'};
75 my $no_lines = $args->{'no_lines'};
76 my $add_color = $args->{'add_color'};
77 my $show_fk_only = $args->{'show_fk_only'};
78 my $join_pk_only = $args->{'join_pk_only'};
79 my $natural_join = $args->{'natural_join'} || $join_pk_only;
80 my $skip_fields = $args->{'skip_fields'};
761fa621 81 my %skip = map { s/^\s+|\s+$//g; $_,1 } split (/,/, $skip_fields);
82
dcac44eb 83# my @tables = $schema->get_tables;
84 my @table_names;
85 if ( $natural_join ) {
86 $schema->make_natural_joins(
87 join_pk_only => $join_pk_only,
88 skip_fields => $args->{'skip_fields'},
89 );
90
91 my $g = $schema->as_graph_pm;
92 my $d = Graph::Traversal::DFS->new( $g, next_alphabetic => 1 );
93 $d->preorder;
94
95 @table_names = $d->dfs;
96 }
97 else {
98 @table_names = map { $_->name } $schema->get_tables;
99 }
37503827 100
7652721a 101 die "Invalid image type '$output_type'"
102 unless VALID_IMAGE_TYPE ->{ $output_type };
37503827 103 die "Invalid font size '$font_size'"
104 unless VALID_FONT_SIZE->{ $font_size };
105
106 #
107 # Layout the image.
108 #
dcac44eb 109 my $font
110 = $font_size eq 'small' ? gdTinyFont
111 : $font_size eq 'medium' ? gdSmallFont
112 : $font_size eq 'large' ? gdLargeFont
113 : gdGiantFont;
114
115 my $no_tables = scalar @table_names;
550022e5 116 $no_columns = 0 unless $no_columns =~ /^\d+$/;
37503827 117 $no_columns ||= sprintf( "%.0f", sqrt( $no_tables ) + .5 );
118 $no_columns ||= .5;
119 my $no_per_col = sprintf( "%.0f", $no_tables/$no_columns + .5 );
120
121 my @shapes;
122 my ( $max_x, $max_y ); # the furthest x and y used
123 my $orig_y = 40; # used to reset y for each column
124 my ( $x, $y ) = (30,$orig_y); # where to start
125 my $cur_col = 1; # the current column
126 my $no_this_col = 0; # number of tables in current column
127 my $this_col_x = $x; # current column's x
37503827 128 my %nj_registry; # for locations of fields for natural joins
129 my @fk_registry; # for locations of fields for foreign keys
130 my %table_x; # for max x of each table
131 my $field_no; # counter to give distinct no. to each field
761fa621 132 my %coords; # holds fields coordinates
6a20798b 133 my @imap_coords; # for making clickable image map
37503827 134 my %legend;
135
dcac44eb 136 for my $table_name ( @table_names ) {
137 my $table = $schema->get_table( $table_name );
138 my $top = $y;
37503827 139 push @shapes,
140 [ 'string', $font, $this_col_x, $y, $table_name, 'black' ];
37503827 141 $y += $font->height + 2;
142 my $below_table_name = $y;
143 $y += 2;
144 my $this_max_x =
145 $this_col_x + ($font->width * length($table_name));
146
147 debug("Processing table '$table_name'");
148
761fa621 149 my @fields = $table->get_fields;
150 debug("Fields = ", join(', ', map { $_->name } @fields));
37503827 151
60dcc980 152 my ( @fld_desc, $max_name, $max_desc );
37503827 153 for my $f ( @fields ) {
761fa621 154 my $name = $f->name or next;
155 my $is_pk = $f->is_primary_key;
37503827 156
60dcc980 157 my @attr;
158
37503827 159 #
160 # Decide if we should skip this field.
161 #
162 if ( $show_fk_only ) {
761fa621 163 next unless $is_pk || $f->is_foreign_key;
37503827 164 }
165
166 if ( $is_pk ) {
60dcc980 167 push @attr, 'PK';
168 $legend{'Primary key'} = '[PK]';
37503827 169 }
cd9ccb3e 170
171 if ( $f->is_unique ) {
60dcc980 172 push @attr, 'U';
37503827 173 $legend{'Unique constraint'} = '[U]';
174 }
175
60dcc980 176 if ( $f->is_foreign_key ) {
177 push @attr, 'FK';
178 $legend{'Foreign Key'} = '[FK]';
179 }
180
181 my $attr = '';
182 if ( @attr ) {
183 $attr .= '[' . join(', ', @attr) . ']';
184 }
185
761fa621 186 my $desc = $f->data_type;
60dcc980 187 $desc .= '('.$f->size.')' if $f->size &&
188 $f->data_type =~ /^(VAR)?CHAR2?$/i;
37503827 189
190 my $nlen = length $name;
60dcc980 191 my $dlen = length $desc;
37503827 192 $max_name = $nlen if $nlen > $max_name;
60dcc980 193 $max_desc = $dlen if $dlen > $max_desc;
194 push @fld_desc, [ $name, $desc, $f->{'name'}, $is_pk, $attr ];
37503827 195 }
196
60dcc980 197 $max_name += 2;
198 $max_desc += 2;
37503827 199 for my $fld_desc ( @fld_desc ) {
60dcc980 200 my ( $name, $desc, $orig_name, $is_pk, $attr ) = @$fld_desc;
201 my $diff1 = $max_name - length $name;
202 my $diff2 = $max_desc - length $desc;
203 $name .= ' ' x $diff1;
204 $desc .= ' ' x $diff2;
205 $desc = $name . $desc . $attr;
37503827 206
207 push @shapes, [ 'string', $font, $this_col_x, $y, $desc, 'black' ];
208 $y += $font->height + 2;
209 my $length = $this_col_x + ( $font->width * length( $desc ) );
210 $this_max_x = $length if $length > $this_max_x;
211
212 my $constraints = $table->{'fields'}{ $orig_name }{'constraints'};
213
214 if ( $natural_join && !$skip{ $orig_name } ) {
215 push @{ $nj_registry{ $orig_name } }, $table_name;
216 }
37503827 217
218 my $y_link = $y - $font->height/2;
761fa621 219 $coords{ $table_name }{ $orig_name }{'coords'} = {
37503827 220 left => [ $this_col_x - 6, $y_link ],
221 right => [ $length + 2 , $y_link ],
222 table => $table_name,
223 field_no => ++$field_no,
224 is_pk => $is_pk,
225 fld_name => $orig_name,
226 };
6a20798b 227
228 push @imap_coords, [
229 $imap_url."#$table_name-$orig_name",
230 $this_col_x, $y - $font->height, $length, $y_link,
231 ];
37503827 232 }
233
761fa621 234 unless ( $natural_join ) {
235 for my $c ( $table->get_constraints ) {
236 next unless $c->type eq FOREIGN_KEY;
237 my $fk_table = $c->reference_table or next;
238
239 for my $field_name ( $c->fields ) {
240 for my $fk_field ( $c->reference_fields ) {
241 next unless defined $schema->get_table( $fk_table );
242 push @fk_registry, [
761fa621 243 [ $fk_table , $fk_field ],
761a28bb 244 [ $table_name, $field_name ],
761fa621 245 ];
246 }
247 }
248 }
249 }
250
37503827 251 $this_max_x += 5;
252 $table_x{ $table_name } = $this_max_x + 5;
253 push @shapes, [ 'line', $this_col_x - 5, $below_table_name,
254 $this_max_x, $below_table_name, 'black' ];
255 my @bounds = ( $this_col_x - 5, $top - 5, $this_max_x, $y + 5 );
256 if ( $add_color ) {
257 unshift @shapes, [
258 'filledRectangle',
259 $bounds[0], $bounds[1],
260 $this_max_x, $below_table_name,
261 'khaki'
262 ];
263 unshift @shapes, [ 'filledRectangle', @bounds, 'white' ];
264 }
6a20798b 265
266 push @imap_coords, [
267 $imap_url."#$table_name",
268 $bounds[0], $bounds[1], $this_max_x, $below_table_name,
269 ];
270
37503827 271 push @shapes, [ 'rectangle', @bounds, 'black' ];
272 $max_x = $this_max_x if $this_max_x > $max_x;
273 $y += 25;
274
275 if ( ++$no_this_col == $no_per_col ) {# if we've filled up this column
276 $cur_col++; # up the column number
277 $no_this_col = 0; # reset the number of tables
278 $max_x += $gutter; # push the x over for next column
279 $this_col_x = $max_x; # remember the max x for this col
280 $max_y = $y if $y > $max_y; # note the max y
281 $y = $orig_y; # reset the y for next column
282 }
283 }
284
285 #
286 # Connect the lines.
287 #
288 my %horz_taken;
289 my %done;
290 unless ( $no_lines ) {
291 my @position_bunches;
292
293 if ( $natural_join ) {
294 for my $field_name ( keys %nj_registry ) {
295 my @positions;
296 my @table_names =
297 @{ $nj_registry{ $field_name } || [] } or next;
298 next if scalar @table_names == 1;
299
300 for my $table_name ( @table_names ) {
301 push @positions,
761fa621 302 $coords{ $table_name }{ $field_name }{'coords'};
37503827 303 }
304
305 push @position_bunches, [ @positions ];
306 }
307 }
308 else {
309 for my $pair ( @fk_registry ) {
310 push @position_bunches, [
761fa621 311 $coords{$pair->[0][0]}{ $pair->[0][1] }{'coords'},
312 $coords{$pair->[1][0]}{ $pair->[1][1] }{'coords'},
37503827 313 ];
314 }
315 }
316
317 my $is_directed = $natural_join ? 0 : 1;
318
319 for my $bunch ( @position_bunches ) {
320 my @positions = @$bunch;
321
322 for my $i ( 0 .. $#positions ) {
323 my $pos1 = $positions[ $i ];
324 my ( $ax, $ay ) = @{ $pos1->{'left'} || [] } or next;
325 my ( $bx, $by ) = @{ $pos1->{'right'} || [] } or next;
326 my $table1 = $pos1->{'table'};
327 my $fno1 = $pos1->{'field_no'};
328 my $is_pk = $pos1->{'is_pk'};
329 next if $join_pk_only and !$is_pk;
330
331 for my $j ( 0 .. $#positions ) {
332 my $pos2 = $positions[ $j ];
333 my ( $cx, $cy ) = @{ $pos2->{'left'} || [] } or next;
334 my ( $dx, $dy ) = @{ $pos2->{'right'} || [] } or next;
335 my $table2 = $pos2->{'table'};
336 my $fno2 = $pos2->{'field_no'};
337 next if $table1 eq $table2;
338 next if $done{ $fno1 }{ $fno2 };
339 next if $fno1 == $fno2;
340
341 my @distances = ();
342 push @distances, [
343 abs ( $ax - $cx ) + abs ( $ay - $cy ),
344 [ $ax, $ay, $cx, $cy ],
345 [ 'left', 'left' ]
346 ];
347 push @distances, [
348 abs ( $ax - $dx ) + abs ( $ay - $dy ),
349 [ $ax, $ay, $dx, $dy ],
350 [ 'left', 'right' ],
351 ];
352 push @distances, [
353 abs ( $bx - $cx ) + abs ( $by - $cy ),
354 [ $bx, $by, $cx, $cy ],
355 [ 'right', 'left' ],
356 ];
357 push @distances, [
358 abs ( $bx - $dx ) + abs ( $by - $dy ),
359 [ $bx, $by, $dx, $dy ],
360 [ 'right', 'right' ],
361 ];
362 @distances = sort { $a->[0] <=> $b->[0] } @distances;
363 my $shortest = $distances[0];
364 my ( $x1, $y1, $x2, $y2 ) = @{ $shortest->[1] };
365 my ( $side1, $side2 ) = @{ $shortest->[2] };
366 my ( $start, $end );
367 my $offset = 9;
368 my $col1_right = $table_x{ $table1 };
369 my $col2_right = $table_x{ $table2 };
370
371 my $diff = 0;
372 if ( $x1 == $x2 ) {
373 while ( $horz_taken{ $x1 + $diff } ) {
374 $diff = $side1 eq 'left' ? $diff - 2 : $diff + 2;
375 }
376 $horz_taken{ $x1 + $diff } = 1;
377 }
378
379 if ( $side1 eq 'left' ) {
380 $start = $x1 - $offset + $diff;
381 }
382 else {
383 $start = $col1_right + $diff;
384 }
385
386 if ( $side2 eq 'left' ) {
387 $end = $x2 - $offset + $diff;
388 }
389 else {
390 $end = $col2_right + $diff;
391 }
392
393 push @shapes,
394 [ 'line', $x1, $y1, $start, $y1, 'cadetblue' ];
395 push @shapes,
396 [ 'line', $start, $y1, $end, $y2, 'cadetblue' ];
397 push @shapes,
398 [ 'line', $end, $y2, $x2, $y2, 'cadetblue' ];
399
400 if ( $is_directed ) {
401 if (
402 $side1 eq 'right' && $side2 eq 'left'
403 ||
404 $side1 eq 'left' && $side2 eq 'left'
405 ) {
406 push @shapes, [
407 'line', $x2 - 3, $y2 - 3, $x2, $y2, 'cadetblue'
408 ];
409 push @shapes, [
410 'line', $x2 - 3, $y2 + 3, $x2, $y2, 'cadetblue'
411 ];
412 push @shapes, [
413 'line', $x2 - 3, $y2 - 3, $x2 - 3, $y2 +3,
414 'cadetblue'
415 ];
416 }
417 else {
418 push @shapes, [
419 'line', $x2 + 3, $y2 - 3, $x2, $y2, 'cadetblue'
420 ];
421 push @shapes, [
422 'line', $x2 + 3, $y2 + 3, $x2, $y2, 'cadetblue'
423 ];
424 push @shapes, [
425 'line', $x2 + 3, $y2 - 3, $x2 + 3, $y2 +3,
426 'cadetblue'
427 ];
428 }
429 }
430
431 $done{ $fno1 }{ $fno2 } = 1;
432 $done{ $fno2 }{ $fno1 } = 1;
433 }
434 }
435 }
436 }
437
438 #
439 # Add the title, legend and signature.
440 #
441 my $large_font = gdLargeFont;
442 my $title_len = $large_font->width * length $title;
443 push @shapes, [
444 'string', $large_font, $max_x/2 - $title_len/2, 10, $title, 'black'
445 ];
446
447 if ( %legend ) {
448 $max_y += 5;
449 push @shapes, [
450 'string', $font, $x, $max_y - $font->height - 4, 'Legend', 'black'
451 ];
452 $max_y += $font->height + 4;
453
454 my $longest;
455 for my $len ( map { length $_ } values %legend ) {
456 $longest = $len if $len > $longest;
457 }
458 $longest += 2;
459
460 while ( my ( $key, $shape ) = each %legend ) {
461 my $space = $longest - length $shape;
462 push @shapes, [
463 'string', $font, $x, $max_y - $font->height - 4,
464 join( '', $shape, ' ' x $space, $key ), 'black'
465 ];
466
467 $max_y += $font->height + 4;
468 }
469 }
470
60dcc980 471 my $sig = 'Created by SQL::Translator ' . $t->version;
37503827 472 my $sig_len = $font->width * length $sig;
473 push @shapes, [
474 'string', $font, $max_x - $sig_len, $max_y - $font->height - 4,
475 $sig, 'black'
476 ];
477
478 #
479 # Render the image.
480 #
481 my $gd = GD::Image->new( $max_x + 30, $max_y );
7652721a 482 unless ( $gd->can( $output_type ) ) {
483 die "GD can't create images of type '$output_type'\n";
37503827 484 }
485 my %colors = map { $_->[0], $gd->colorAllocate( @{$_->[1]} ) } (
486 [ white => [ 255, 255, 255 ] ],
487 [ beige => [ 245, 245, 220 ] ],
488 [ black => [ 0, 0, 0 ] ],
489 [ lightblue => [ 173, 216, 230 ] ],
490 [ cadetblue => [ 95, 158, 160 ] ],
491 [ lightgoldenrodyellow => [ 250, 250, 210 ] ],
492 [ khaki => [ 240, 230, 140 ] ],
493 [ red => [ 255, 0, 0 ] ],
494 );
495 $gd->interlaced( 'true' );
496 my $background_color = $add_color ? 'lightgoldenrodyellow' : 'white';
497 $gd->fill( 0, 0, $colors{ $background_color } );
498 for my $shape ( @shapes ) {
499 my $method = shift @$shape;
500 my $color = pop @$shape;
501 $gd->$method( @$shape, $colors{ $color } );
502 }
503
504 #
6a20798b 505 # Make image map.
506 #
507 debug("imap file = '$imap_file'");
508 if ( $imap_file && @imap_coords ) {
509 open my $fh, ">$imap_file" or die "Can't write '$imap_file': $!\n";
510 print $fh qq[<html><body><img src="" usemap="#imap" border="0">\n].
511 qq[<map name="imap">\n];
512 for my $rec ( @imap_coords ) {
513 my $href = shift @$rec;
514 print $fh q[<area coords="].join(',', @$rec).qq[" href="$href">\n];
515 }
516 print $fh qq[</body></html>];
517 close $fh;
518 }
519
520 #
37503827 521 # Print the image.
522 #
523 if ( $out_file ) {
524 open my $fh, ">$out_file" or die "Can't write '$out_file': $!\n";
7652721a 525 print $fh $gd->$output_type;
37503827 526 close $fh;
527 }
528 else {
7652721a 529 return $gd->$output_type;
37503827 530 }
531}
532
5331;
534
977651a5 535# -------------------------------------------------------------------
536
37503827 537=pod
538
37503827 539=head1 AUTHOR
540
e966b2b0 541Ken Y. Clark E<lt>kclark@cpan.orgE<gt>.
37503827 542
543=cut