Remove copyright headers from individual scripts
[dbsrgits/SQL-Translator.git] / lib / SQL / Translator / Producer / Diagram.pm
CommitLineData
37503827 1package SQL::Translator::Producer::Diagram;
2
e966b2b0 3=head1 NAME
4
5SQL::Translator::Producer::Diagram - ER diagram producer for SQL::Translator
6
7=head1 SYNOPSIS
8
9Use via SQL::Translator:
10
11 use SQL::Translator;
12
9d4a26be 13 my $t = SQL::Translator->new(
14 from => 'MySQL',
15 to => 'GraphViz',
16 producer_args => {
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
34 }
35 ) or die SQL::Translator->error;
e966b2b0 36 $t->translate;
37
9d4a26be 38* "list" can be either an array-ref or a comma-separated string
39
e966b2b0 40=cut
41
37503827 42use strict;
43use GD;
44use Data::Dumper;
761fa621 45use SQL::Translator::Schema::Constants;
37503827 46use SQL::Translator::Utils qw(debug);
47
da06ac74 48use vars qw[ $VERSION $DEBUG ];
11ad2df9 49$VERSION = '1.59';
37503827 50$DEBUG = 0 unless defined $DEBUG;
51
52use constant VALID_FONT_SIZE => {
53 small => 1,
54 medium => 1,
55 large => 1,
56 huge => 1,
57};
58
59use constant VALID_IMAGE_TYPE => {
60 png => 1,
61 jpeg => 1,
62};
63
64sub produce {
761fa621 65 my $t = shift;
66 my $schema = $t->schema;
37503827 67 my $args = $t->producer_args;
68 local $DEBUG = $t->debug;
761fa621 69 debug("Schema =\n", Dumper( $schema ));
37503827 70 debug("Producer args =\n", Dumper( $args ));
71
6a20798b 72 my $out_file = $args->{'out_file'} || '';
9d4a26be 73 my $output_type = $args->{'output_type'} || 'png';
6a20798b 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'} || '';
01a182ab 78 my $gutter = $args->{'gutter'} || 30; # distance b/w columns
9d4a26be 79 my $num_columns = $args->{'num_columns'} || $args->{'no_columns'} || '';
37503827 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;
9d4a26be 85 my %skip_field = map { $_, 1 } (
86 ref $args->{'skip_fields'} eq 'ARRAY'
87 ? @{ $args->{'skip_fields'} }
88 : split ( /\s*,\s*/, $args->{'skip_fields'} )
89 );
90
91 my %skip_table = map { $_, 1 } (
92 ref $args->{'skip_tables'} eq 'ARRAY'
93 ? @{ $args->{'skip_tables'} }
94 : split ( /\s*,\s*/, $args->{'skip_tables'} )
95 );
96
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'} )
101 );
761fa621 102
dcac44eb 103 my @table_names;
104 if ( $natural_join ) {
105 $schema->make_natural_joins(
106 join_pk_only => $join_pk_only,
107 skip_fields => $args->{'skip_fields'},
108 );
109
110 my $g = $schema->as_graph_pm;
111 my $d = Graph::Traversal::DFS->new( $g, next_alphabetic => 1 );
112 $d->preorder;
113
114 @table_names = $d->dfs;
115 }
116 else {
117 @table_names = map { $_->name } $schema->get_tables;
118 }
37503827 119
7652721a 120 die "Invalid image type '$output_type'"
9d4a26be 121 unless VALID_IMAGE_TYPE->{ $output_type };
37503827 122 die "Invalid font size '$font_size'"
123 unless VALID_FONT_SIZE->{ $font_size };
124
125 #
126 # Layout the image.
127 #
dcac44eb 128 my $font
129 = $font_size eq 'small' ? gdTinyFont
130 : $font_size eq 'medium' ? gdSmallFont
131 : $font_size eq 'large' ? gdLargeFont
132 : gdGiantFont;
133
9d4a26be 134 my $num_tables = scalar @table_names;
135 $num_columns = 0 unless $num_columns =~ /^\d+$/;
136 $num_columns ||= sprintf( "%.0f", sqrt( $num_tables ) + .5 );
137 $num_columns ||= .5;
138 my $no_per_col = sprintf( "%.0f", $num_tables/$num_columns + .5 );
37503827 139
140 my @shapes;
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
37503827 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
761fa621 151 my %coords; # holds fields coordinates
6a20798b 152 my @imap_coords; # for making clickable image map
37503827 153 my %legend;
154
9d4a26be 155 TABLE:
dcac44eb 156 for my $table_name ( @table_names ) {
157 my $table = $schema->get_table( $table_name );
9d4a26be 158
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;
163 }
164 }
165
dcac44eb 166 my $top = $y;
37503827 167 push @shapes,
168 [ 'string', $font, $this_col_x, $y, $table_name, 'black' ];
37503827 169 $y += $font->height + 2;
170 my $below_table_name = $y;
171 $y += 2;
172 my $this_max_x =
173 $this_col_x + ($font->width * length($table_name));
174
175 debug("Processing table '$table_name'");
176
761fa621 177 my @fields = $table->get_fields;
178 debug("Fields = ", join(', ', map { $_->name } @fields));
37503827 179
60dcc980 180 my ( @fld_desc, $max_name, $max_desc );
37503827 181 for my $f ( @fields ) {
761fa621 182 my $name = $f->name or next;
183 my $is_pk = $f->is_primary_key;
37503827 184
60dcc980 185 my @attr;
186
37503827 187 #
188 # Decide if we should skip this field.
189 #
190 if ( $show_fk_only ) {
761fa621 191 next unless $is_pk || $f->is_foreign_key;
37503827 192 }
193
194 if ( $is_pk ) {
60dcc980 195 push @attr, 'PK';
196 $legend{'Primary key'} = '[PK]';
37503827 197 }
cd9ccb3e 198
199 if ( $f->is_unique ) {
60dcc980 200 push @attr, 'U';
37503827 201 $legend{'Unique constraint'} = '[U]';
202 }
203
60dcc980 204 if ( $f->is_foreign_key ) {
205 push @attr, 'FK';
206 $legend{'Foreign Key'} = '[FK]';
207 }
208
209 my $attr = '';
210 if ( @attr ) {
211 $attr .= '[' . join(', ', @attr) . ']';
212 }
213
761fa621 214 my $desc = $f->data_type;
60dcc980 215 $desc .= '('.$f->size.')' if $f->size &&
216 $f->data_type =~ /^(VAR)?CHAR2?$/i;
37503827 217
218 my $nlen = length $name;
60dcc980 219 my $dlen = length $desc;
37503827 220 $max_name = $nlen if $nlen > $max_name;
60dcc980 221 $max_desc = $dlen if $dlen > $max_desc;
222 push @fld_desc, [ $name, $desc, $f->{'name'}, $is_pk, $attr ];
37503827 223 }
224
60dcc980 225 $max_name += 2;
226 $max_desc += 2;
37503827 227 for my $fld_desc ( @fld_desc ) {
60dcc980 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;
37503827 234
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;
239
240 my $constraints = $table->{'fields'}{ $orig_name }{'constraints'};
241
9d4a26be 242 if ( $natural_join && !$skip_field{ $orig_name } ) {
37503827 243 push @{ $nj_registry{ $orig_name } }, $table_name;
244 }
37503827 245
246 my $y_link = $y - $font->height/2;
761fa621 247 $coords{ $table_name }{ $orig_name }{'coords'} = {
37503827 248 left => [ $this_col_x - 6, $y_link ],
249 right => [ $length + 2 , $y_link ],
250 table => $table_name,
251 field_no => ++$field_no,
252 is_pk => $is_pk,
253 fld_name => $orig_name,
254 };
6a20798b 255
256 push @imap_coords, [
257 $imap_url."#$table_name-$orig_name",
258 $this_col_x, $y - $font->height, $length, $y_link,
259 ];
37503827 260 }
261
761fa621 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;
266
267 for my $field_name ( $c->fields ) {
268 for my $fk_field ( $c->reference_fields ) {
269 next unless defined $schema->get_table( $fk_table );
270 push @fk_registry, [
761fa621 271 [ $fk_table , $fk_field ],
761a28bb 272 [ $table_name, $field_name ],
761fa621 273 ];
274 }
275 }
276 }
277 }
278
37503827 279 $this_max_x += 5;
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 );
284 if ( $add_color ) {
285 unshift @shapes, [
286 'filledRectangle',
287 $bounds[0], $bounds[1],
288 $this_max_x, $below_table_name,
289 'khaki'
290 ];
291 unshift @shapes, [ 'filledRectangle', @bounds, 'white' ];
292 }
6a20798b 293
294 push @imap_coords, [
295 $imap_url."#$table_name",
296 $bounds[0], $bounds[1], $this_max_x, $below_table_name,
297 ];
298
37503827 299 push @shapes, [ 'rectangle', @bounds, 'black' ];
300 $max_x = $this_max_x if $this_max_x > $max_x;
301 $y += 25;
302
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
310 }
311 }
312
313 #
314 # Connect the lines.
315 #
316 my %horz_taken;
317 my %done;
318 unless ( $no_lines ) {
319 my @position_bunches;
320
321 if ( $natural_join ) {
322 for my $field_name ( keys %nj_registry ) {
323 my @positions;
324 my @table_names =
325 @{ $nj_registry{ $field_name } || [] } or next;
326 next if scalar @table_names == 1;
327
328 for my $table_name ( @table_names ) {
329 push @positions,
761fa621 330 $coords{ $table_name }{ $field_name }{'coords'};
37503827 331 }
332
333 push @position_bunches, [ @positions ];
334 }
335 }
336 else {
337 for my $pair ( @fk_registry ) {
338 push @position_bunches, [
761fa621 339 $coords{$pair->[0][0]}{ $pair->[0][1] }{'coords'},
340 $coords{$pair->[1][0]}{ $pair->[1][1] }{'coords'},
37503827 341 ];
342 }
343 }
344
345 my $is_directed = $natural_join ? 0 : 1;
346
347 for my $bunch ( @position_bunches ) {
348 my @positions = @$bunch;
349
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;
358
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;
368
369 my @distances = ();
370 push @distances, [
371 abs ( $ax - $cx ) + abs ( $ay - $cy ),
372 [ $ax, $ay, $cx, $cy ],
373 [ 'left', 'left' ]
374 ];
375 push @distances, [
376 abs ( $ax - $dx ) + abs ( $ay - $dy ),
377 [ $ax, $ay, $dx, $dy ],
378 [ 'left', 'right' ],
379 ];
380 push @distances, [
381 abs ( $bx - $cx ) + abs ( $by - $cy ),
382 [ $bx, $by, $cx, $cy ],
383 [ 'right', 'left' ],
384 ];
385 push @distances, [
386 abs ( $bx - $dx ) + abs ( $by - $dy ),
387 [ $bx, $by, $dx, $dy ],
388 [ 'right', 'right' ],
389 ];
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] };
394 my ( $start, $end );
395 my $offset = 9;
396 my $col1_right = $table_x{ $table1 };
397 my $col2_right = $table_x{ $table2 };
398
399 my $diff = 0;
400 if ( $x1 == $x2 ) {
401 while ( $horz_taken{ $x1 + $diff } ) {
402 $diff = $side1 eq 'left' ? $diff - 2 : $diff + 2;
403 }
404 $horz_taken{ $x1 + $diff } = 1;
405 }
406
407 if ( $side1 eq 'left' ) {
408 $start = $x1 - $offset + $diff;
409 }
410 else {
411 $start = $col1_right + $diff;
412 }
413
414 if ( $side2 eq 'left' ) {
415 $end = $x2 - $offset + $diff;
416 }
417 else {
418 $end = $col2_right + $diff;
419 }
420
421 push @shapes,
422 [ 'line', $x1, $y1, $start, $y1, 'cadetblue' ];
423 push @shapes,
424 [ 'line', $start, $y1, $end, $y2, 'cadetblue' ];
425 push @shapes,
426 [ 'line', $end, $y2, $x2, $y2, 'cadetblue' ];
427
428 if ( $is_directed ) {
429 if (
430 $side1 eq 'right' && $side2 eq 'left'
431 ||
432 $side1 eq 'left' && $side2 eq 'left'
433 ) {
434 push @shapes, [
435 'line', $x2 - 3, $y2 - 3, $x2, $y2, 'cadetblue'
436 ];
437 push @shapes, [
438 'line', $x2 - 3, $y2 + 3, $x2, $y2, 'cadetblue'
439 ];
440 push @shapes, [
441 'line', $x2 - 3, $y2 - 3, $x2 - 3, $y2 +3,
442 'cadetblue'
443 ];
444 }
445 else {
446 push @shapes, [
447 'line', $x2 + 3, $y2 - 3, $x2, $y2, 'cadetblue'
448 ];
449 push @shapes, [
450 'line', $x2 + 3, $y2 + 3, $x2, $y2, 'cadetblue'
451 ];
452 push @shapes, [
453 'line', $x2 + 3, $y2 - 3, $x2 + 3, $y2 +3,
454 'cadetblue'
455 ];
456 }
457 }
458
459 $done{ $fno1 }{ $fno2 } = 1;
460 $done{ $fno2 }{ $fno1 } = 1;
461 }
462 }
463 }
464 }
465
466 #
467 # Add the title, legend and signature.
468 #
469 my $large_font = gdLargeFont;
470 my $title_len = $large_font->width * length $title;
471 push @shapes, [
472 'string', $large_font, $max_x/2 - $title_len/2, 10, $title, 'black'
473 ];
474
475 if ( %legend ) {
476 $max_y += 5;
477 push @shapes, [
478 'string', $font, $x, $max_y - $font->height - 4, 'Legend', 'black'
479 ];
480 $max_y += $font->height + 4;
481
482 my $longest;
483 for my $len ( map { length $_ } values %legend ) {
484 $longest = $len if $len > $longest;
485 }
486 $longest += 2;
487
488 while ( my ( $key, $shape ) = each %legend ) {
489 my $space = $longest - length $shape;
490 push @shapes, [
491 'string', $font, $x, $max_y - $font->height - 4,
492 join( '', $shape, ' ' x $space, $key ), 'black'
493 ];
494
495 $max_y += $font->height + 4;
496 }
497 }
498
60dcc980 499 my $sig = 'Created by SQL::Translator ' . $t->version;
37503827 500 my $sig_len = $font->width * length $sig;
501 push @shapes, [
502 'string', $font, $max_x - $sig_len, $max_y - $font->height - 4,
503 $sig, 'black'
504 ];
505
506 #
507 # Render the image.
508 #
509 my $gd = GD::Image->new( $max_x + 30, $max_y );
7652721a 510 unless ( $gd->can( $output_type ) ) {
511 die "GD can't create images of type '$output_type'\n";
37503827 512 }
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 ] ],
522 );
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 } );
530 }
531
532 #
6a20798b 533 # Make image map.
534 #
535 debug("imap file = '$imap_file'");
536 if ( $imap_file && @imap_coords ) {
d4924f25 537 open my $fh, '>', $imap_file or die "Can't write '$imap_file': $!\n";
6a20798b 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];
543 }
544 print $fh qq[</body></html>];
545 close $fh;
546 }
547
548 #
37503827 549 # Print the image.
550 #
551 if ( $out_file ) {
d4924f25 552 open my $fh, '>', $out_file or die "Can't write '$out_file': $!\n";
54c61e72 553 binmode $fh;
7652721a 554 print $fh $gd->$output_type;
37503827 555 close $fh;
556 }
557 else {
7652721a 558 return $gd->$output_type;
37503827 559 }
560}
561
5621;
563
977651a5 564# -------------------------------------------------------------------
565
37503827 566=pod
567
37503827 568=head1 AUTHOR
569
d4924f25 570Ken Youens-Clark E<lt>kclark@cpan.orgE<gt>.
37503827 571
572=cut