More cosmetic changes to make comments pretty, added ability to set
[dbsrgits/SQL-Translator.git] / lib / SQL / Translator / Producer / ClassDBI.pm
1 package SQL::Translator::Producer::ClassDBI;
2
3 # -------------------------------------------------------------------
4 # $Id: ClassDBI.pm,v 1.31 2003-08-13 17:13:53 kycl4rk Exp $
5 # -------------------------------------------------------------------
6 # Copyright (C) 2003 Allen Day <allenday@ucla.edu>,
7 #                    Ying Zhang <zyolive@yahoo.com>
8 #
9 # This program is free software; you can redistribute it and/or
10 # modify it under the terms of the GNU General Public License as
11 # published by the Free Software Foundation; version 2.
12 #
13 # This program is distributed in the hope that it will be useful, but
14 # WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16 # General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with this program; if not, write to the Free Software
20 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
21 # 02111-1307  USA
22 # -------------------------------------------------------------------
23
24 use strict;
25 use vars qw[ $VERSION $DEBUG ];
26 $VERSION = sprintf "%d.%02d", q$Revision: 1.31 $ =~ /(\d+)\.(\d+)/;
27 $DEBUG = 1 unless defined $DEBUG;
28
29 use SQL::Translator::Schema::Constants;
30 use SQL::Translator::Utils qw(header_comment);
31 use Text::Autoformat;
32
33 my %CDBI_auto_pkgs = (
34     MySQL          => 'mysql',
35     PostgreSQL     => 'Pg',
36     Oracle         => 'Oracle',
37 );
38
39 # -------------------------------------------------------------------
40 sub produce {
41     my $t      = shift;
42     my $create = undef;
43     local $DEBUG = $t->debug;
44     my $no_comments   = $t->no_comments;
45     my $schema        = $t->schema;
46     my $args          = $t->producer_args;
47     my $db_user       = $args->{'db_user'} || '';
48     my $db_pass       = $args->{'db_pass'} || '';
49     my $main_pkg_name = $args->{'main_pkg_name'} || 
50                         $t->format_package_name('DBI');
51     my $header        = header_comment( __PACKAGE__, "# " );
52     my $parser_type   = ( split /::/, $t->parser_type )[-1];
53     my $from          = $CDBI_auto_pkgs{$parser_type} || '';
54     my $dsn           = $args->{'dsn'} || sprintf( 'dbi:%s:_',
55         $CDBI_auto_pkgs{$parser_type}
56         ? $CDBI_auto_pkgs{$parser_type}
57         : $parser_type );
58     my $sep = '# ' . '-' x 67;
59
60     #
61     # Identify "link tables" (have only PK and FK fields).
62     #
63     my %linkable;
64     my %linktable;
65     foreach my $table ( $schema->get_tables ) {
66         my $is_link = 1;
67         foreach my $field ( $table->get_fields ) {
68             unless ( $field->is_primary_key or $field->is_foreign_key ) {
69                 $is_link = 0;
70                 last;
71             }
72         }
73
74         next unless $is_link;
75
76         foreach my $left ( $table->get_fields ) {
77             next unless $left->is_foreign_key;
78             my $lfk = $left->foreign_key_reference or next;
79             my $lr_table = $schema->get_table( $lfk->reference_table )
80               or next;
81             my $lr_field_name = ( $lfk->reference_fields )[0];
82             my $lr_field      = $lr_table->get_field($lr_field_name);
83             next unless $lr_field->is_primary_key;
84
85             foreach my $right ( $table->get_fields ) {
86                 next if $left->name eq $right->name;
87
88                 my $rfk = $right->foreign_key_reference or next;
89                 my $rr_table = $schema->get_table( $rfk->reference_table )
90                   or next;
91                 my $rr_field_name = ( $rfk->reference_fields )[0];
92                 my $rr_field      = $rr_table->get_field($rr_field_name);
93                 next unless $rr_field->is_primary_key;
94
95                 $linkable{ $lr_table->name }{ $rr_table->name } = $table;
96                 $linkable{ $rr_table->name }{ $lr_table->name } = $table;
97                 $linktable{ $table->name } = $table;
98             }
99         }
100     }
101
102     #
103     # Iterate over all tables.
104     #
105     my ( %packages, $order );
106     for my $table ( $schema->get_tables ) {
107         my $table_name = $table->name or next;
108
109         my $table_pkg_name = $t->format_package_name($table_name);
110         $packages{$table_pkg_name} = {
111             order    => ++$order,
112             pkg_name => $table_pkg_name,
113             base     => $main_pkg_name,
114             table    => $table_name,
115         };
116
117         #
118         # Primary key may have a differenct accessor method name
119         #
120         if ( my $constraint = $table->primary_key ) {
121             my $field = ( $constraint->fields )[0];
122             $packages{ $table_pkg_name }{'_columns_primary'} = $field;
123
124             if ( my $pk_xform = $t->format_pk_name ) {
125                 my $pk_name = $pk_xform->( $table_pkg_name, $field );
126
127                 $packages{$table_pkg_name}{'pk_accessor'} =
128                   "#\n# Primary key accessor\n#\n"
129                   . "sub $pk_name {\n    shift->$field\n}\n\n";
130             }
131         }
132
133         my $is_data = 0;
134         foreach my $field ( $table->get_fields ) {
135             if ( !$field->is_foreign_key and !$field->is_primary_key ) {
136                 push @{ $packages{$table_pkg_name}{'_columns_essential'} },
137                   $field->name;
138                 $is_data++;
139             }
140             elsif ( !$field->is_primary_key ) {
141                 push @{ $packages{$table_pkg_name}{'_columns_others'} },
142                   $field->name;
143             }
144         }
145
146         my %linked;
147         if ($is_data) {
148             foreach my $link ( keys %{ $linkable{$table_name} } ) {
149                 my $linkmethodname;
150
151                 if ( my $fk_xform = $t->format_fk_name ) {
152                     # ADD CALLBACK FOR PLURALIZATION MANGLING HERE
153                     $linkmethodname = $fk_xform->(
154                         $linkable{$table_name}{$link}->name,
155                         ( $schema->get_table($link)->primary_key->fields )[0]
156                       )
157                       . 's';
158                 }
159                 else {
160
161                     # ADD CALLBACK FOR PLURALIZATION MANGLING HERE
162                     $linkmethodname =
163                       $linkable{$table_name}{$link}->name . '_'
164                       . ( $schema->get_table($link)->primary_key->fields )[0]
165                       . 's';
166                 }
167
168                 my @rk_fields = ();
169                 my @lk_fields = ();
170                 foreach my $field ( $linkable{$table_name}{$link}->get_fields )
171                 {
172                     next unless $field->is_foreign_key;
173
174                     next
175                       unless ( $field->foreign_key_reference->reference_table eq
176                            $table_name
177                         || $field->foreign_key_reference->reference_table eq
178                         $link );
179                     push @lk_fields,
180                       ( $field->foreign_key_reference->reference_fields )[0]
181                       if $field->foreign_key_reference->reference_table eq
182                       $link;
183                     push @rk_fields, $field->name
184                       if $field->foreign_key_reference->reference_table eq
185                       $table_name;
186                 }
187
188                 #
189                 # If one possible traversal via link table.
190                 #
191                 if ( scalar(@rk_fields) == 1 and scalar(@lk_fields) == 1 ) {
192                     foreach my $rk_field (@rk_fields) {
193                         push @{ $packages{$table_pkg_name}{'has_many'}{$link} },
194                           "sub "
195                           . $linkmethodname
196                           . " { my \$self = shift; "
197                           . "return map \$_->"
198                           . ( $schema->get_table($link)->primary_key->fields )
199                           [0]
200                           . ", \$self->"
201                           . $linkable{$table_name}{$link}->name . "_"
202                           . $rk_field
203                           . " }\n\n";
204                     }
205
206                     #
207                     # Else there is more than one way to traverse it.
208                     # ack!  Let's treat these types of link tables as
209                     # a many-to-one (easier).
210                     #
211                     # NOTE: We need to rethink the link method name,
212                     # as the cardinality has shifted on us.
213                     #
214                 }
215                 elsif ( scalar(@rk_fields) == 1 ) {
216                     foreach my $rk_field (@rk_fields) {
217
218                         # ADD CALLBACK FOR PLURALIZATION MANGLING HERE
219                         push @{ $packages{$table_pkg_name}{'has_many'}{$link} },
220                           "sub "
221                           . $linkable{$table_name}{$link}->name
222                           . "s { my \$self = shift; return \$self->"
223                           . $linkable{$table_name}{$link}->name . "_"
224                           . $rk_field
225                           . "(\@_) }\n\n";
226                     }
227                 }
228                 elsif ( scalar(@lk_fields) == 1 ) {
229                     # These will be taken care of on the other end...
230                 }
231                 else {
232                     #
233                     # Many many many.  Need multiple iterations here,
234                     # data structure revision to handle N FK sources.
235                     # This code has not been tested and likely doesn't
236                     # work here.
237                     #
238                     foreach my $rk_field (@rk_fields) {
239
240                         # ADD CALLBACK FOR PLURALIZATION MANGLING HERE
241                         push @{ $packages{$table_pkg_name}{'has_many'}{$link} },
242                           "sub "
243                           . $linkable{$table_name}{$link}->name . "_"
244                           . $rk_field
245                           . "s { my \$self = shift; return \$self->"
246                           . $linkable{$table_name}{$link}->name . "_"
247                           . $rk_field
248                           . "(\@_) }\n\n";
249                     }
250                 }
251             }
252         }
253
254         #
255         # Use foreign keys to set up "has_a/has_many" relationships.
256         #
257         foreach my $field ( $table->get_fields ) {
258             if ( $field->is_foreign_key ) {
259                 my $table_name = $table->name;
260                 my $field_name = $field->name;
261                 my $fk_method  = $t->format_fk_name( $table_name, $field_name )
262                                  || $field_name;
263                 my $fk         = $field->foreign_key_reference;
264                 my $ref_table  = $fk->reference_table;
265                 my $ref_pkg    = $t->format_package_name($ref_table);
266                 my $ref_field  = ( $fk->reference_fields )[0];
267
268                 push @{ $packages{$table_pkg_name}{'has_a'} },
269                     "$table_pkg_name->has_a(\n"
270                     . "    $field_name => '$ref_pkg'\n);\n\n"
271                     . "sub $fk_method {\n"
272                     . "    return shift->$field_name\n}\n\n"
273                 ;
274
275                 #
276                 # If this table "has a" to the other, then it follows 
277                 # that the other table "has many" of this one, right?
278                 #
279                 # No... there is the possibility of 1-1 cardinality
280                 #
281                 # If there weren't M-M relationships via the has_many
282                 # being set up here, create nice pluralized method alias
283                 # rather for user as alt. to ugly tablename_fieldname name.
284                 #
285                 if ( !$packages{$ref_pkg}{'has_many'}{$table_name} ) {
286
287                     # ADD CALLBACK FOR PLURALIZATION MANGLING HERE
288                     push @{ $packages{$ref_pkg}{'has_many'}{$table_name} },
289                         "sub ${table_name}s {\n    ".
290                         "return shift->$table_name\_$field_name\n}\n\n"
291                     ;
292                 }
293                 else {
294                     ; # nothing? why is this here? -ky
295                 }
296
297                 push @{ $packages{$ref_pkg}{'has_many'}{$table_name} },
298                     "$ref_pkg->has_many(\n    '${table_name}_${field_name}',\n"
299                     . "    '$table_pkg_name' => '$field_name'\n);\n\n"
300                 ;
301             }
302         }
303     }
304
305     #
306     # Now build up text of package.
307     #
308     my $base_pkg = sprintf( 'Class::DBI%s', $from ? "::$from" : '' );
309     $create .= join ( "\n",
310         "package $main_pkg_name;\n",
311         $header,
312         "use strict;",
313         "use base '$base_pkg';\n",
314         "$main_pkg_name->set_db('Main', '$dsn', '$db_user', '$db_pass');\n\n",
315     );
316
317     for my $pkg_name (
318         sort { $packages{ $a }{'order'} <=> $packages{ $b }{'order'} }
319         keys %packages
320     ) {
321         my $pkg = $packages{ $pkg_name };
322
323         $create .= join ( "\n",
324             $sep,
325             "package " . $pkg->{'pkg_name'} . ";",
326             "use base '" . $pkg->{'base'} . "';",
327             "use Class::DBI::Pager;\n\n",
328         );
329
330         #
331         # The approach here is to do lazy loading on the expensive
332         # columns (expensive defined as those columns which require
333         # construction of a referenced object) fields which are
334         # strictly data (ie, not references) are treated as essential
335         # b/c they don't require much time to set up.
336         #
337         $create .= $pkg_name . "->table('" . $pkg->{'table'} . "');\n\n";
338
339         # set up primary key field
340         if ( $pkg->{'_columns_primary'} ) {
341             $create .= $pkg_name
342                 . "->columns(\n    Primary   => qw/"
343                 . $pkg->{'_columns_primary'} . "/\n);\n\n";
344         }
345         else {
346             die "Class::DBI isn't going to like that you don't have".
347                 " a primary key field for table " . $pkg->{'table'} .
348                 " in package '$pkg_name'";
349         }
350
351         #
352         # Set up non-FK fields to be populated at construction.
353         #
354         if ( $pkg->{'_columns_essential'} ) {
355             $create .= $pkg_name
356                 . "->columns(\n"
357                 . autoformat( '    Essential => qw/' .
358                     join ( ' ', @{ $pkg->{'_columns_essential'} } ) . '/'
359                 ) . ");\n\n"
360             ;
361         }
362
363         #
364         # Set up FK fields for lazy loading on request.
365         #
366         if ( $pkg->{'_columns_others'} ) {
367             $create .= $pkg_name
368                 . "->columns(\n"
369                 . autoformat( '    Others    => qw/' .
370                     join ( ' ', @{ $pkg->{'_columns_others'} } ) . '/'
371                 ) . ");\n\n"
372             ;
373         }
374
375         if ( my $pk = $pkg->{'pk_accessor'} ) {
376             $create .= $pk;
377         }
378
379         if ( my @has_a = @{ $pkg->{'has_a'} || [] } ) {
380             $create .= $_ for @has_a;
381         }
382
383         foreach my $has_many_key ( keys %{ $pkg->{'has_many'} } ) {
384             if ( my @has_many = @{ $pkg->{'has_many'}{$has_many_key} || [] } ) {
385                 $create .= $_ for @has_many;
386             }
387         }
388     }
389
390     $create .= "1;\n";
391
392     return $create;
393 }
394
395 1;
396
397 # -------------------------------------------------------------------
398
399 =pod
400
401 =head1 NAME
402
403 SQL::Translator::Producer::ClassDBI - create Class::DBI classes from schema
404
405 =head1 SYNOPSIS
406
407 Use this producer as you would any other from SQL::Translator.  See
408 L<SQL::Translator> for details.
409
410 This package utilizes SQL::Translator's formatting methods
411 format_package_name(), format_pk_name(), format_fk_name(), and
412 format_table_name() as it creates classes, one per table in the schema
413 provided.  An additional base class is also created for database connectivity
414 configuration.  See L<Class::DBI> for details on how this works.
415
416 =head1 AUTHORS
417
418 Allen Day E<lt>allenday@ucla.eduE<gt>
419 Ying Zhang E<lt>zyolive@yahoo.comE<gt>,
420 Ken Y. Clark E<lt>kclark@cpan.org<gt>.