Efforts to re-enable Allen's many-to-many linktable code. I have no idea
[dbsrgits/SQL-Translator.git] / lib / SQL / Translator / Producer / ClassDBI.pm
1 package SQL::Translator::Producer::ClassDBI;
2
3 # -------------------------------------------------------------------
4 # $Id: ClassDBI.pm,v 1.25 2003-06-27 02:59:25 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.25 $ =~ /(\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     local $DEBUG      = $t->debug;
43     my $no_comments   = $t->no_comments;
44     my $schema        = $t->schema;
45     my $args          = $t->producer_args;
46     my $db_user       = $args->{'db_user'} || '';
47     my $db_pass       = $args->{'db_pass'} || '';
48     my $main_pkg_name = $t->format_package_name('DBI');
49     my $header        = header_comment(__PACKAGE__, "# ");
50     my $parser_type   = ( split /::/, $t->parser_type )[-1];
51     my $from          = $CDBI_auto_pkgs{ $parser_type } || '';
52     my $dsn           = $args->{'dsn'} || sprintf( 'dbi:%s:_',
53                             $CDBI_auto_pkgs{ $parser_type }
54                             ? $CDBI_auto_pkgs{ $parser_type } : $parser_type
55                         );
56     my $sep           = '# ' . '-' x 67;
57
58     #
59     # Identify "link tables" (have only PK and FK fields).
60     #
61     my %linkable;
62     my %linktable;
63     foreach my $table ( $schema->get_tables ) {
64         my $is_link = 1;
65         foreach my $field ( $table->get_fields ) {
66             unless ( $field->is_primary_key or $field->is_foreign_key ) {
67                 $is_link = 0; 
68                 last;
69             }
70         }
71
72         next unless $is_link;
73       
74         foreach my $left ( $table->get_fields ) {
75             next unless $left->is_foreign_key;
76             my $lfk           = $left->foreign_key_reference or next;
77             my $lr_table      = $schema->get_table( $lfk->reference_table )
78                                  or next;
79             my $lr_field_name = ($lfk->reference_fields)[0];
80             my $lr_field      = $lr_table->get_field($lr_field_name);
81             next unless $lr_field->is_primary_key;
82
83             foreach my $right ( $table->get_fields ) {
84                 next if $left->name eq $right->name;
85         
86                 my $rfk      = $right->foreign_key_reference or next;
87                 my $rr_table = $schema->get_table( $rfk->reference_table )
88                                or next;
89                 my $rr_field_name = ($rfk->reference_fields)[0];
90                 my $rr_field      = $rr_table->get_field($rr_field_name);
91                 next unless $rr_field->is_primary_key;
92         
93                 $linkable{ $lr_table }{ $rr_table } = $table;
94                 $linkable{ $rr_table }{ $lr_table } = $table;
95                 $linktable{ $table->name } = $table;
96             }
97         }
98     }
99     
100     #
101     # Iterate over all tables
102     #
103     my ( %packages, $order );
104     for my $table ( $schema->get_tables ) {
105         my $table_name = $table->name or next;
106
107         my $table_pkg_name = $t->format_package_name($table_name);
108         $packages{ $table_pkg_name } = {
109             order     => ++$order,
110             pkg_name  => $table_pkg_name,
111             base      => $main_pkg_name,
112             table     => $table_name,
113         };
114
115         #
116         # Primary key may have a differenct accessor method name
117         #
118         if ( my $pk_xform = $t->format_pk_name ) {
119             if ( my $constraint = $table->primary_key ) {
120                 my $field          = ($constraint->fields)[0];
121                 my $pk_name        = $pk_xform->($table_pkg_name, $field);
122                 
123                 $packages{ $table_pkg_name }{'pk_accessor'} = 
124                     "#\n# Primary key accessor\n#\n".
125                     "sub $pk_name {\n    shift->$field\n}\n\n"
126                 ;
127             }
128         }
129         
130         #
131         # Use foreign keys to set up "has_a/has_many" relationships.
132         #
133         my $is_data = 0;
134         foreach my $field ( $table->get_fields ) {
135             $is_data++ if !$field->is_foreign_key and !$field->is_primary_key;
136             if ( $field->is_foreign_key ) {
137                 my $table_name = $table->name;
138                 my $field_name = $field->name;
139                 my $fk_method  = $t->format_fk_name($table_name, $field_name);
140                 my $fk         = $field->foreign_key_reference;
141                 my $ref_table  = $fk->reference_table;
142                 my $ref_pkg    = $t->format_package_name($ref_table);
143                 my $ref_field  = ($fk->reference_fields)[0];
144
145                 push @{ $packages{ $table_pkg_name }{'has_a'} },
146                     "$table_pkg_name->has_a(\n".
147                     "    $field_name => '$ref_pkg'\n);\n\n".
148                     "sub $fk_method {\n".
149                     "    return shift->$field_name\n}\n\n"
150                 ;
151
152                 #
153                 # If this table "has a" to the other, then it follows 
154                 # that the other table "has many" of this one, right?
155                 #
156                 push @{ $packages{ $ref_pkg }{'has_many'} },
157                     "$ref_pkg->has_many(\n    '${table_name}_${field_name}', ".
158                     "'$table_pkg_name' => '$field_name'\n);\n\n"
159                 ;
160             }
161         }
162
163         my %linked;
164         if ( $is_data ) {
165             foreach my $link ( keys %{ $linkable{ $table_name } } ) {
166                 my $linkmethodname = 
167                     "_".$t->format_fk_name($table->name,$link)."_refs"
168                 ;
169
170                 push @{ $packages{ $table_name }{'has_many'} },
171                     "$table_pkg_name->has_many(\n    ".
172                         "'$linkmethodname', ".
173                         $t->format_package_name(
174                             $linkable{ $table->name }{ $link }->name
175                         )."','".
176                        ($schema->get_table($link)->primary_key->fields)[0].
177                     "');\n\n"
178                 ;
179
180                 #
181                 # I'm not sure what to do with this code. - ky
182                 #
183
184 #                $create .= "sub ". $t->format_fk_name($table,$link).
185 #                    # HARDCODED 's' HERE.  
186 #                    # ADD CALLBACK FOR PLURALIZATION MANGLING
187 #                    "s {\n    my \$self = shift; return map \$_->".$link.
188 #                    ", \$self->".$linkmethodname.";\n}\n\n"
189 #                ;
190             }
191         }
192     }
193
194     #
195     # Now build up text of package.
196     #
197     my $base_pkg = sprintf( 'Class::DBI%s', $from ? "::$from" : '' );
198     my $create = join("\n",
199         "package $main_pkg_name;\n",
200         $header,
201         "use strict;",
202         "use base '$base_pkg';\n",
203         "$main_pkg_name->set_db('Main', '$dsn', '$db_user', '$db_pass');\n\n",
204     ); 
205
206     for my $pkg_name ( 
207         sort { $packages{ $a }{'order'} <=> $packages{ $b }{'order'} }
208         keys %packages
209     ) {
210         my $pkg = $packages{ $pkg_name };
211
212         $create .= join("\n",
213             $sep,
214             "package ".$pkg->{'pkg_name'}.";",
215             "use base '".$pkg->{'base'}."';",
216             "use Class::DBI::Pager;\n\n",
217         );    
218
219         if ( $from ) {
220             $create .= 
221                 $pkg->{'pkg_name'}."->set_up_table('".$pkg->{'table'}."');\n\n";
222         }
223         else {
224             my $table       = $schema->get_table( $pkg->{'table'} );
225             my @field_names = map { $_->name } $table->get_fields;
226
227             $create .= join("\n",
228                 $pkg_name."->table('".$pkg->{'table'}."');\n",
229                 $pkg_name."->columns(All => qw/".
230                 join(' ', @field_names)."/);\n\n",
231             );
232         }
233
234         if ( my $pk = $pkg->{'pk_accessor'} ) {
235             $create .= $pk;
236         }
237
238         if ( my @has_a = @{ $pkg->{'has_a'} || [] } ) {
239             $create .= $_ for @has_a;
240         }
241
242         if ( my @has_many = @{ $pkg->{'has_many'} || [] } ) {
243             $create .= $_ for @has_many;
244         }
245     }
246
247     $create .= "1;\n";
248
249     return $create;
250 }
251
252 1;
253
254 # -------------------------------------------------------------------
255
256 =pod
257
258 =head1 NAME
259
260 SQL::Translator::Producer::ClassDBI - create Class::DBI classes from schema
261
262 =head1 SYNOPSIS
263
264 Use this producer as you would any other from SQL::Translator.  See
265 L<SQL::Translator> for details.
266
267 This package utilizes SQL::Translator's formatting methods
268 format_package_name(), format_pk_name(), format_fk_name(), and
269 format_table_name() as it creates classes, one per table in the schema
270 provided.  An additional base class is also created for database connectivity
271 configuration.  See L<Class::DBI> for details on how this works.
272
273 =head1 AUTHORS
274
275 Allen Day E<lt>allenday@ucla.eduE<gt>
276 Ying Zhang E<lt>zyolive@yahoo.comE<gt>,
277 Ken Y. Clark E<lt>kclark@cpan.org<gt>.