1 package SQL::Translator::Producer::Diagram;
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>
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.
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.
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
21 # -------------------------------------------------------------------
26 use SQL::Translator::Schema::Constants;
27 use SQL::Translator::Utils qw(debug);
29 use vars qw[ $VERSION $DEBUG ];
30 $VERSION = sprintf "%d.%02d", q$Revision: 1.3 $ =~ /(\d+)\.(\d+)/;
31 $DEBUG = 0 unless defined $DEBUG;
33 use constant VALID_FONT_SIZE => {
40 use constant VALID_IMAGE_TYPE => {
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 ));
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);
66 $schema->make_natural_joins(
67 join_pk_only => $join_pk_only,
68 skip_fields => $args->{'skip_fields'},
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 };
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 );
88 my $no_per_col = sprintf( "%.0f", $no_tables/$no_columns + .5 );
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
105 for my $table ( @tables ) {
106 my $table_name = $table->name;
109 [ 'string', $font, $this_col_x, $y, $table_name, 'black' ];
111 $y += $font->height + 2;
112 my $below_table_name = $y;
115 $this_col_x + ($font->width * length($table_name));
117 debug("Processing table '$table_name'");
119 my @fields = $table->get_fields;
120 debug("Fields = ", join(', ', map { $_->name } @fields));
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;
128 # Decide if we should skip this field.
130 if ( $show_fk_only ) {
131 next unless $is_pk || $f->is_foreign_key;
136 $legend{'Primary key'} = '*';
138 elsif ( $f->is_unique ) {
140 $legend{'Unique constraint'} = '[U]';
143 my $desc = $f->data_type;
144 $desc .= '('.$f->size.')' if $f->size;
146 my $nlen = length $name;
147 $max_name = $nlen if $nlen > $max_name;
148 push @fld_desc, [ $name, $desc, $f->{'name'}, $is_pk ];
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;
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;
163 my $constraints = $table->{'fields'}{ $orig_name }{'constraints'};
165 if ( $natural_join && !$skip{ $orig_name } ) {
166 push @{ $nj_registry{ $orig_name } }, $table_name;
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,
176 fld_name => $orig_name,
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;
185 for my $field_name ( $c->fields ) {
186 for my $fk_field ( $c->reference_fields ) {
187 next unless defined $schema->get_table( $fk_table );
189 [ $table_name, $field_name ],
190 [ $fk_table , $fk_field ],
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 );
205 $bounds[0], $bounds[1],
206 $this_max_x, $below_table_name,
209 unshift @shapes, [ 'filledRectangle', @bounds, 'white' ];
211 push @shapes, [ 'rectangle', @bounds, 'black' ];
212 $max_x = $this_max_x if $this_max_x > $max_x;
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
230 unless ( $no_lines ) {
231 my @position_bunches;
233 if ( $natural_join ) {
234 for my $field_name ( keys %nj_registry ) {
237 @{ $nj_registry{ $field_name } || [] } or next;
238 next if scalar @table_names == 1;
240 for my $table_name ( @table_names ) {
242 $coords{ $table_name }{ $field_name }{'coords'};
245 push @position_bunches, [ @positions ];
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'},
257 my $is_directed = $natural_join ? 0 : 1;
259 for my $bunch ( @position_bunches ) {
260 my @positions = @$bunch;
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;
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;
283 abs ( $ax - $cx ) + abs ( $ay - $cy ),
284 [ $ax, $ay, $cx, $cy ],
288 abs ( $ax - $dx ) + abs ( $ay - $dy ),
289 [ $ax, $ay, $dx, $dy ],
293 abs ( $bx - $cx ) + abs ( $by - $cy ),
294 [ $bx, $by, $cx, $cy ],
298 abs ( $bx - $dx ) + abs ( $by - $dy ),
299 [ $bx, $by, $dx, $dy ],
300 [ 'right', 'right' ],
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] };
308 my $col1_right = $table_x{ $table1 };
309 my $col2_right = $table_x{ $table2 };
313 while ( $horz_taken{ $x1 + $diff } ) {
314 $diff = $side1 eq 'left' ? $diff - 2 : $diff + 2;
316 $horz_taken{ $x1 + $diff } = 1;
319 if ( $side1 eq 'left' ) {
320 $start = $x1 - $offset + $diff;
323 $start = $col1_right + $diff;
326 if ( $side2 eq 'left' ) {
327 $end = $x2 - $offset + $diff;
330 $end = $col2_right + $diff;
334 [ 'line', $x1, $y1, $start, $y1, 'cadetblue' ];
336 [ 'line', $start, $y1, $end, $y2, 'cadetblue' ];
338 [ 'line', $end, $y2, $x2, $y2, 'cadetblue' ];
340 if ( $is_directed ) {
342 $side1 eq 'right' && $side2 eq 'left'
344 $side1 eq 'left' && $side2 eq 'left'
347 'line', $x2 - 3, $y2 - 3, $x2, $y2, 'cadetblue'
350 'line', $x2 - 3, $y2 + 3, $x2, $y2, 'cadetblue'
353 'line', $x2 - 3, $y2 - 3, $x2 - 3, $y2 +3,
359 'line', $x2 + 3, $y2 - 3, $x2, $y2, 'cadetblue'
362 'line', $x2 + 3, $y2 + 3, $x2, $y2, 'cadetblue'
365 'line', $x2 + 3, $y2 - 3, $x2 + 3, $y2 +3,
371 $done{ $fno1 }{ $fno2 } = 1;
372 $done{ $fno2 }{ $fno1 } = 1;
379 # Add the title, legend and signature.
381 my $large_font = gdLargeFont;
382 my $title_len = $large_font->width * length $title;
384 'string', $large_font, $max_x/2 - $title_len/2, 10, $title, 'black'
390 'string', $font, $x, $max_y - $font->height - 4, 'Legend', 'black'
392 $max_y += $font->height + 4;
395 for my $len ( map { length $_ } values %legend ) {
396 $longest = $len if $len > $longest;
400 while ( my ( $key, $shape ) = each %legend ) {
401 my $space = $longest - length $shape;
403 'string', $font, $x, $max_y - $font->height - 4,
404 join( '', $shape, ' ' x $space, $key ), 'black'
407 $max_y += $font->height + 4;
411 my $sig = __PACKAGE__." $VERSION";
412 my $sig_len = $font->width * length $sig;
414 'string', $font, $max_x - $sig_len, $max_y - $font->height - 4,
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";
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 ] ],
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 } );
448 open my $fh, ">$out_file" or die "Can't write '$out_file': $!\n";
449 print $fh $gd->$image_type;
453 return $gd->$image_type;
463 SQL::Translator::Producer::Diagram - ER diagram producer for SQL::Translator
467 Ken Y. Clark E<lt>kclark@cpan.orgE<gt>