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