Ran through perltidy, broke long lines, changed logic on setting of
[dbsrgits/SQL-Translator.git] / lib / SQL / Translator / Producer / ClassDBI.pm
1 package SQL::Translator::Producer::ClassDBI;
2
3 # -------------------------------------------------------------------
4 # $Id: ClassDBI.pm,v 1.30 2003-08-12 23:21:54 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.30 $ =~ /(\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 Data::Dumper;
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 = $t->format_package_name('DBI');
50     my $header        = header_comment( __PACKAGE__, "# " );
51     my $parser_type   = ( split /::/, $t->parser_type )[-1];
52     my $from          = $CDBI_auto_pkgs{$parser_type} || '';
53     my $dsn           = $args->{'dsn'} || sprintf( 'dbi:%s:_',
54         $CDBI_auto_pkgs{$parser_type}
55         ? $CDBI_auto_pkgs{$parser_type}
56         : $parser_type );
57     my $sep = '# ' . '-' x 67;
58
59     #
60     # Identify "link tables" (have only PK and FK fields).
61     #
62     my %linkable;
63     my %linktable;
64     foreach my $table ( $schema->get_tables ) {
65         my $is_link = 1;
66         foreach my $field ( $table->get_fields ) {
67             unless ( $field->is_primary_key or $field->is_foreign_key ) {
68                 $is_link = 0;
69                 last;
70             }
71         }
72
73         next unless $is_link;
74
75         foreach my $left ( $table->get_fields ) {
76             next unless $left->is_foreign_key;
77             my $lfk = $left->foreign_key_reference or next;
78             my $lr_table = $schema->get_table( $lfk->reference_table )
79               or next;
80             my $lr_field_name = ( $lfk->reference_fields )[0];
81             my $lr_field      = $lr_table->get_field($lr_field_name);
82             next unless $lr_field->is_primary_key;
83
84             foreach my $right ( $table->get_fields ) {
85                 next if $left->name eq $right->name;
86
87                 my $rfk = $right->foreign_key_reference or next;
88                 my $rr_table = $schema->get_table( $rfk->reference_table )
89                   or next;
90                 my $rr_field_name = ( $rfk->reference_fields )[0];
91                 my $rr_field      = $rr_table->get_field($rr_field_name);
92                 next unless $rr_field->is_primary_key;
93
94                 $linkable{ $lr_table->name }{ $rr_table->name } = $table;
95                 $linkable{ $rr_table->name }{ $lr_table->name } = $table;
96                 $linktable{ $table->name } = $table;
97             }
98         }
99     }
100
101     #
102     # Iterate over all tables
103     #
104     my ( %packages, $order );
105     for my $table ( $schema->get_tables ) {
106         my $table_name = $table->name or next;
107
108         my $table_pkg_name = $t->format_package_name($table_name);
109         $packages{$table_pkg_name} = {
110             order    => ++$order,
111             pkg_name => $table_pkg_name,
112             base     => $main_pkg_name,
113             table    => $table_name,
114         };
115
116         #
117         # Primary key may have a differenct accessor method name
118         #
119         if ( my $constraint = $table->primary_key ) {
120             my $field = ( $constraint->fields )[0];
121             $packages{ $table_pkg_name }{'_columns_primary'} = $field;
122
123             if ( my $pk_xform = $t->format_pk_name ) {
124                 my $pk_name = $pk_xform->( $table_pkg_name, $field );
125
126                 $packages{$table_pkg_name}{'pk_accessor'} =
127                   "#\n# Primary key accessor\n#\n"
128                   . "sub $pk_name {\n    shift->$field\n}\n\n";
129             }
130         }
131
132         my $is_data = 0;
133         foreach my $field ( $table->get_fields ) {
134             if ( !$field->is_foreign_key and !$field->is_primary_key ) {
135                 push @{ $packages{$table_pkg_name}{'_columns_essential'} },
136                   $field->name;
137                 $is_data++;
138             }
139             elsif ( !$field->is_primary_key ) {
140                 push @{ $packages{$table_pkg_name}{'_columns_others'} },
141                   $field->name;
142             }
143         }
144
145         my %linked;
146         if ($is_data) {
147             foreach my $link ( keys %{ $linkable{$table_name} } ) {
148                 my $linkmethodname;
149
150                 if ( my $fk_xform = $t->format_fk_name ) {
151
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                 # if one possible traversal via link table
189                 if ( scalar(@rk_fields) == 1 and scalar(@lk_fields) == 1 ) {
190                     foreach my $rk_field (@rk_fields) {
191                         push @{ $packages{$table_pkg_name}{'has_many'}{$link} },
192                           "sub "
193                           . $linkmethodname
194                           . " { my \$self = shift; "
195                           . "return map \$_->"
196                           . ( $schema->get_table($link)->primary_key->fields )
197                           [0]
198                           . ", \$self->"
199                           . $linkable{$table_name}{$link}->name . "_"
200                           . $rk_field
201                           . " }\n\n";
202                     }
203
204                     # else there is more than one way to traverse it.
205                     # ack!  let's treat these types of link tables as
206                     # a many-to-one (easier)
207                     #
208                     # NOTE: we need to rethink the link method name,
209                     # as the cardinality has shifted on us.
210                 }
211                 elsif ( scalar(@rk_fields) == 1 ) {
212                     foreach my $rk_field (@rk_fields) {
213
214                         # ADD CALLBACK FOR PLURALIZATION MANGLING HERE
215                         push @{ $packages{$table_pkg_name}{'has_many'}{$link} },
216                           "sub "
217                           . $linkable{$table_name}{$link}->name
218                           . "s { my \$self = shift; return \$self->"
219                           . $linkable{$table_name}{$link}->name . "_"
220                           . $rk_field
221                           . "(\@_) }\n\n";
222                     }
223                 }
224                 elsif ( scalar(@lk_fields) == 1 ) {
225                     # these will be taken care of on the other end...
226                 }
227                 else {
228                     # many many many.  need multiple iterations here,
229                     # data structure revision to handle N FK sources.
230                     # This code has not been tested and likely doesn't
231                     # work here
232                     foreach my $rk_field (@rk_fields) {
233
234                         # ADD CALLBACK FOR PLURALIZATION MANGLING HERE
235                         push @{ $packages{$table_pkg_name}{'has_many'}{$link} },
236                           "sub "
237                           . $linkable{$table_name}{$link}->name . "_"
238                           . $rk_field
239                           . "s { my \$self = shift; return \$self->"
240                           . $linkable{$table_name}{$link}->name . "_"
241                           . $rk_field
242                           . "(\@_) }\n\n";
243                     }
244                 }
245             }
246         }
247
248         #
249         # Use foreign keys to set up "has_a/has_many" relationships.
250         #
251         foreach my $field ( $table->get_fields ) {
252             if ( $field->is_foreign_key ) {
253                 my $table_name = $table->name;
254                 my $field_name = $field->name;
255                 my $fk_method  = $t->format_fk_name( $table_name, $field_name );
256                 my $fk         = $field->foreign_key_reference;
257                 my $ref_table  = $fk->reference_table;
258                 my $ref_pkg    = $t->format_package_name($ref_table);
259                 my $ref_field  = ( $fk->reference_fields )[0];
260
261                 push @{ $packages{$table_pkg_name}{'has_a'} },
262                   "$table_pkg_name->has_a(\n"
263                   . "    $field_name => '$ref_pkg'\n);\n\n"
264                   . "sub $fk_method {\n"
265                   . "    return shift->$field_name\n}\n\n";
266
267                 #
268                 # If this table "has a" to the other, then it follows 
269                 # that the other table "has many" of this one, right?
270                 #
271                 # No... there is the possibility of 1-1 cardinality
272
273                 # if there weren't M-M relationships via the has_many
274                 # being set up here, create nice pluralized method alias
275                 # rather for user as alt. to ugly tablename_fieldname name
276                 if ( !$packages{$ref_pkg}{'has_many'}{$table_name} ) {
277
278                     # ADD CALLBACK FOR PLURALIZATION MANGLING HERE
279                     push @{ $packages{$ref_pkg}{'has_many'}{$table_name} },
280 "sub ${table_name}s {\n    return shift->$table_name\_$field_name\n}\n\n";
281
282                     #else ugly
283                 }
284                 else {
285                 }
286
287                 push @{ $packages{$ref_pkg}{'has_many'}{$table_name} },
288                   "$ref_pkg->has_many(\n    '${table_name}_${field_name}', "
289                   . "'$table_pkg_name' => '$field_name'\n);\n\n";
290
291             }
292         }
293     }
294
295     #
296     # Now build up text of package.
297     #
298     my $base_pkg = sprintf( 'Class::DBI%s', $from ? "::$from" : '' );
299     $create .= join ( "\n",
300         "package $main_pkg_name;\n",
301         $header,
302         "use strict;",
303         "use base '$base_pkg';\n",
304         "$main_pkg_name->set_db('Main', '$dsn', '$db_user', '$db_pass');\n\n",
305     );
306
307     for my $pkg_name (
308         sort { $packages{ $a }{'order'} <=> $packages{ $b }{'order'} }
309         keys %packages
310     ) {
311         my $pkg = $packages{ $pkg_name };
312
313         $create .= join ( "\n",
314             $sep,
315             "package " . $pkg->{'pkg_name'} . ";",
316             "use base '" . $pkg->{'base'} . "';",
317             "use Class::DBI::Pager;\n\n",
318         );
319
320         #if ( $from ) {
321         #    $create .= 
322         #        $pkg->{'pkg_name'}."->set_up_table('".$pkg->{'table'}."');\n\n";
323         #}
324         #else {
325         #    my $table       = $schema->get_table( $pkg->{'table'} );
326         #    my @field_names = map { $_->name } $table->get_fields;
327         #
328         #    $create .= join("\n",
329         #        $pkg_name."->table('".$pkg->{'table'}."');\n",
330         #        $pkg_name."->columns(All => qw/".
331         #        join(' ', @field_names)."/);\n\n",
332         #    );
333         #}
334
335         # the approach here is to do lazy loading on the expensive
336         # columns (expensive defined as those columns which require
337         # construction of a referenced object) fields which are
338         # strictly data (ie, not references) are treated as essential
339         # b/c they don't require much time to set up.
340
341         $create .= $pkg_name . "->table('" . $pkg->{'table'} . "');\n";
342
343         # set up primary key field
344         if ( $pkg->{'_columns_primary'} ) {
345             $create .= $pkg_name
346               . "->columns(Primary   => qw/"
347               . $pkg->{'_columns_primary'} . "/);\n";
348         }
349         else {
350             die "Class::DBI isn't going to like that you don't have".
351                 " a primary key field for table " . $pkg->{'table'} .
352                 " in package '$pkg_name'";
353         }
354
355         # set up non-FK fields to be populated at construction
356         if ( $pkg->{'_columns_essential'} ) {
357             $create .= $pkg_name
358               . "->columns(Essential => qw/"
359               . join ( ' ', @{ $pkg->{'_columns_essential'} } ) . "/);\n";
360         }
361
362         # set up FK fields for lazy loading on request
363         if ( $pkg->{'_columns_others'} ) {
364             $create .= $pkg_name
365               . "->columns(Others    => qw/"
366               . join ( ' ', @{ $pkg->{'_columns_others'} } ) . "/);\n";
367         }
368
369         $create .= "\n";
370
371         if ( my $pk = $pkg->{'pk_accessor'} ) {
372             $create .= $pk;
373         }
374
375         if ( my @has_a = @{ $pkg->{'has_a'} || [] } ) {
376             $create .= $_ for @has_a;
377         }
378
379         foreach my $has_many_key ( keys %{ $pkg->{'has_many'} } ) {
380             if ( my @has_many = @{ $pkg->{'has_many'}{$has_many_key} || [] } ) {
381                 $create .= $_ for @has_many;
382             }
383         }
384     }
385
386     $create .= "1;\n";
387
388     return $create;
389 }
390
391 1;
392
393 # -------------------------------------------------------------------
394
395 =pod
396
397 =head1 NAME
398
399 SQL::Translator::Producer::ClassDBI - create Class::DBI classes from schema
400
401 =head1 SYNOPSIS
402
403 Use this producer as you would any other from SQL::Translator.  See
404 L<SQL::Translator> for details.
405
406 This package utilizes SQL::Translator's formatting methods
407 format_package_name(), format_pk_name(), format_fk_name(), and
408 format_table_name() as it creates classes, one per table in the schema
409 provided.  An additional base class is also created for database connectivity
410 configuration.  See L<Class::DBI> for details on how this works.
411
412 =head1 AUTHORS
413
414 Allen Day E<lt>allenday@ucla.eduE<gt>
415 Ying Zhang E<lt>zyolive@yahoo.comE<gt>,
416 Ken Y. Clark E<lt>kclark@cpan.org<gt>.