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