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