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