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