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