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