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