7e682940df60bc19c451a9006d1708786b9f518f
[dbsrgits/SQL-Translator.git] / lib / SQL / Translator / Producer / ClassDBI.pm
1 package SQL::Translator::Producer::ClassDBI;
2
3 # -------------------------------------------------------------------
4 # Copyright (C) 2002-2009 SQLFairy Authors
5 #
6 # This program is free software; you can redistribute it and/or
7 # modify it under the terms of the GNU General Public License as
8 # published by the Free Software Foundation; version 2.
9 #
10 # This program is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 # General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program; if not, write to the Free Software
17 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
18 # 02111-1307  USA
19 # -------------------------------------------------------------------
20
21 use strict;
22 use vars qw[ $VERSION $DEBUG ];
23 $VERSION = '1.59';
24 $DEBUG = 1 unless defined $DEBUG;
25
26 use SQL::Translator::Schema::Constants;
27 use SQL::Translator::Utils qw(debug header_comment);
28 use Data::Dumper;
29
30 my %CDBI_auto_pkgs = (
31     MySQL      => 'mysql',
32     PostgreSQL => 'Pg',
33     Oracle     => 'Oracle',
34 );
35
36 sub produce {
37     my $t             = shift;
38     local $DEBUG      = $t->debug;
39     my $no_comments   = $t->no_comments;
40     my $schema        = $t->schema;
41     my $args          = $t->producer_args;
42     my @create;
43
44     if ( my $fmt = $args->{'format_pkg_name'} ) {
45         $t->format_package_name( $fmt );
46     }
47
48     if ( my $fmt = $args->{'format_fk_name'} ) {
49         $t->format_fk_name( $fmt );
50     }
51
52     my $db_user       = $args->{'db_user'} || '';
53     my $db_pass       = $args->{'db_password'} || '';
54     my $main_pkg_name = $args->{'package_name'} ||
55                         # $args->{'main_pkg_name'} || # keep this? undocumented
56                         $t->format_package_name('DBI');
57     my $header        = header_comment( __PACKAGE__, "# " );
58     my $parser_type   = ( split /::/, $t->parser_type )[-1];
59     my $from          = $CDBI_auto_pkgs{$parser_type} || '';
60     my $dsn           = $args->{'dsn'} || sprintf( 'dbi:%s:_',
61         $CDBI_auto_pkgs{ $parser_type }
62         ? $CDBI_auto_pkgs{ $parser_type } : $parser_type
63     );
64     my $sep           = '# ' . '-' x 67;
65
66
67     #
68     # Identify "link tables" (have only PK and FK fields).
69     #
70     my %linkable;
71     my %linktable;
72     for my $table ( $schema->get_tables ) {
73         debug("PKG: Table = ", $table->name, "\n");
74         my $is_link = 1;
75         for my $field ( $table->get_fields ) {
76             unless ( $field->is_primary_key or $field->is_foreign_key ) {
77                 $is_link = 0;
78                 last;
79             }
80         }
81
82         next unless $is_link;
83
84         foreach my $left ( $table->get_fields ) {
85             next unless $left->is_foreign_key;
86             my $lfk = $left->foreign_key_reference or next;
87             my $lr_table = $schema->get_table( $lfk->reference_table )
88               or next;
89             my $lr_field_name = ( $lfk->reference_fields )[0];
90             my $lr_field      = $lr_table->get_field($lr_field_name);
91             next unless $lr_field->is_primary_key;
92
93             foreach my $right ( $table->get_fields ) {
94                 next if $left->name eq $right->name;
95
96                 my $rfk = $right->foreign_key_reference or next;
97                 my $rr_table = $schema->get_table( $rfk->reference_table )
98                   or next;
99                 my $rr_field_name = ( $rfk->reference_fields )[0];
100                 my $rr_field      = $rr_table->get_field($rr_field_name);
101                 next unless $rr_field->is_primary_key;
102
103                 $linkable{ $lr_table->name }{ $rr_table->name } = $table;
104                 $linkable{ $rr_table->name }{ $lr_table->name } = $table;
105                 $linktable{ $table->name } = $table;
106             }
107         }
108     }
109
110     #
111     # Iterate over all tables
112     #
113     my ( %packages, $order );
114     for my $table ( $schema->get_tables ) {
115         my $table_name = $table->name or next;
116
117         my $table_pkg_name = join '::', $main_pkg_name, $t->format_package_name($table_name);
118         $packages{ $table_pkg_name } = {
119             order    => ++$order,
120             pkg_name => $table_pkg_name,
121             base     => $main_pkg_name,
122             table    => $table_name,
123         };
124
125         #
126         # Primary key may have a differenct accessor method name
127         #
128 #        if ( my $constraint = $table->primary_key ) {
129 #            my $field = ( $constraint->fields )[0];
130 #            $packages{ $table_pkg_name }{'_columns_primary'} = $field;
131 #
132 #            if ( my $pk_xform = $t->format_pk_name ) {
133 #                my $pk_name = $pk_xform->( $table_pkg_name, $field );
134 #
135 #                $packages{$table_pkg_name}{'pk_accessor'} =
136 #                  "#\n# Primary key accessor\n#\n"
137 #                  . "sub $pk_name {\n    shift->$field\n}\n\n";
138 #            }
139 #        }
140
141         my $is_data = 0;
142         foreach my $field ( $table->get_fields ) {
143             if ( !$field->is_foreign_key and !$field->is_primary_key ) {
144                 push @{ $packages{$table_pkg_name}{'_columns_essential'} },
145                   $field->name;
146                 $is_data++;
147             }
148             elsif ( !$field->is_primary_key ) {
149                 push @{ $packages{$table_pkg_name}{'_columns_others'} },
150                   $field->name;
151             }
152         }
153
154         my %linked;
155         if ($is_data) {
156             foreach my $link ( keys %{ $linkable{$table_name} } ) {
157                 my $linkmethodname;
158
159                 if ( my $fk_xform = $t->format_fk_name ) {
160
161                     # ADD CALLBACK FOR PLURALIZATION MANGLING HERE
162                     $linkmethodname = $fk_xform->(
163                         $linkable{ $table_name }{ $link }->name,
164                         ( $schema->get_table( $link )->primary_key->fields )[0]
165                       )
166                       . 's';
167                 }
168                 else {
169                     # ADD CALLBACK FOR PLURALIZATION MANGLING HERE
170                     $linkmethodname =
171                       $linkable{ $table_name }{ $link }->name . '_'
172                       . ( $schema->get_table( $link )->primary_key->fields )[0]
173                       . 's';
174                 }
175
176                 my @rk_fields = ();
177                 my @lk_fields = ();
178                 foreach my $field ( $linkable{$table_name}{$link}->get_fields )
179                 {
180                     next unless $field->is_foreign_key;
181
182                     next unless (
183                         $field->foreign_key_reference->reference_table eq
184                            $table_name
185                         ||
186                         $field->foreign_key_reference->reference_table eq $link
187                     );
188
189                     push @lk_fields,
190                       ( $field->foreign_key_reference->reference_fields )[0]
191                       if $field->foreign_key_reference->reference_table eq
192                       $link;
193
194                     push @rk_fields, $field->name
195                       if $field->foreign_key_reference->reference_table eq
196                       $table_name;
197                 }
198
199                 #
200                 # If one possible traversal via link table.
201                 #
202                 if ( scalar(@rk_fields) == 1 and scalar(@lk_fields) == 1 ) {
203                     foreach my $rk_field (@rk_fields) {
204                         push @{ $packages{$table_pkg_name}{'has_many'}{$link} },
205                           "sub "
206                           . $linkmethodname
207                           . " { my \$self = shift; "
208                           . "return map \$_->"
209                           . ( $schema->get_table($link)->primary_key->fields )
210                           [0]
211                           . ", \$self->"
212                           . $linkable{$table_name}{$link}->name . "_"
213                           . $rk_field
214                           . " }\n\n";
215                     }
216
217                     #
218                     # Else there is more than one way to traverse it.
219                     # ack!  Let's treat these types of link tables as
220                     # a many-to-one (easier)
221                     #
222                     # NOTE: we need to rethink the link method name,
223                     # as the cardinality has shifted on us.
224                     #
225                 }
226                 elsif ( scalar(@rk_fields) == 1 ) {
227                     foreach my $rk_field (@rk_fields) {
228                         #
229                         # ADD CALLBACK FOR PLURALIZATION MANGLING HERE
230                         #
231                         push @{ $packages{$table_pkg_name}{'has_many'}{$link} },
232                           "sub "
233                           . $linkable{$table_name}{$link}->name
234                           . "s { my \$self = shift; return \$self->"
235                           . $linkable{$table_name}{$link}->name . "_"
236                           . $rk_field
237                           . "(\@_) }\n\n";
238                     }
239                 }
240                 elsif ( scalar(@lk_fields) == 1 ) {
241                     #
242                     # These will be taken care of on the other end...
243                     #
244                 }
245                 else {
246                     #
247                     # Many many many.  Need multiple iterations here,
248                     # data structure revision to handle N FK sources.
249                     # This code has not been tested and likely doesn't
250                     # work here.
251                     #
252                     foreach my $rk_field (@rk_fields) {
253                         # ADD CALLBACK FOR PLURALIZATION MANGLING HERE
254                         push @{ $packages{$table_pkg_name}{'has_many'}{$link} },
255                           "sub "
256                           . $linkable{$table_name}{$link}->name . "_"
257                           . $rk_field
258                           . "s { my \$self = shift; return \$self->"
259                           . $linkable{$table_name}{$link}->name . "_"
260                           . $rk_field
261                           . "(\@_) }\n\n";
262                     }
263                 }
264             }
265         }
266
267         #
268         # Use foreign keys to set up "has_a/has_many" relationships.
269         #
270         foreach my $field ( $table->get_fields ) {
271             if ( $field->is_foreign_key ) {
272                 my $table_name = $table->name;
273                 my $field_name = $field->name;
274 #                my $fk_method  = $t->format_fk_name( $table_name, $field_name );
275                 my $fk_method  = join('::', $table_pkg_name,
276                     $t->format_fk_name( $table_name, $field_name )
277                 );
278                 my $fk         = $field->foreign_key_reference;
279                 my $ref_table  = $fk->reference_table;
280                 my $ref_pkg    = $t->format_package_name($ref_table);
281                 my $ref_field  = ( $fk->reference_fields )[0];
282 #                my $fk_method  = join('::',
283 #                    $table_pkg_name, $t->format_fk_name( $ref_table )
284 #                );
285
286                 push @{ $packages{$table_pkg_name}{'has_a'} },
287                   "$table_pkg_name->has_a(\n"
288                   . "    $field_name => '$ref_pkg'\n);\n\n"
289                   . "sub $fk_method {\n"
290                   . "    return shift->$field_name\n}\n\n"
291                 ;
292
293                 # if there weren't M-M relationships via the has_many
294                 # being set up here, create nice pluralized method alias
295                 # rather for user as alt. to ugly tablename_fieldname name
296                 #
297 #                if ( !$packages{$ref_pkg}{'has_many'}{$table_name} ) {
298 #                    #
299 #                    # ADD CALLBACK FOR PLURALIZATION MANGLING HERE
300 #                    #
301 #                    push @{ $packages{$ref_pkg}{'has_many'}{$table_name} },
302 #                        "sub ${table_name}s {\n    " .
303 #                        "return shift->$table_name\_$field_name\n}\n\n";
304 #                    # else ugly
305 #                }
306 #                else {
307 #                }
308
309                 push @{ $packages{$ref_pkg}{'has_many'}{$table_name} },
310                   "$ref_pkg->has_many(\n    '${table_name}_${field_name}', "
311                   . "'$table_pkg_name' => '$field_name'\n);\n\n";
312
313             }
314         }
315     }
316
317     #
318     # Now build up text of package.
319     #
320     my $base_pkg = sprintf( 'Class::DBI%s', $from ? "::$from" : '' );
321     push @create, join ( "\n",
322         "package $main_pkg_name;\n",
323         $header,
324         "use strict;",
325         "use base '$base_pkg';\n",
326         "$main_pkg_name->set_db('Main', '$dsn', '$db_user', '$db_pass');\n\n",
327     );
328
329     for my $pkg_name (
330         sort { $packages{ $a }{'order'} <=> $packages{ $b }{'order'} }
331         keys %packages
332     ) {
333         my $pkg = $packages{$pkg_name} or next;
334         next unless $pkg->{'pkg_name'};
335
336         push @create, join ( "\n",
337             $sep,
338             "package " . $pkg->{'pkg_name'} . ";",
339             "use base '" . $pkg->{'base'} . "';",
340             "use Class::DBI::Pager;\n\n",
341         );
342
343                 if ( $from ) {
344                     push @create, join('',
345                         $pkg->{'pkg_name'},
346                         "->set_up_table('",
347                         $pkg->{'table'},
348                         "');\n\n"
349                     );
350                 }
351                 else {
352                     my $table       = $schema->get_table( $pkg->{'table'} );
353                     my @field_names = map { $_->name } $table->get_fields;
354
355                     push @create, join("\n",
356                         $pkg_name."->table('".$pkg->{'table'}."');\n",
357                         $pkg_name."->columns(All => qw/".
358                         join(' ', @field_names)."/);\n\n",
359                     );
360                 }
361
362         push @create, "\n";
363
364         if ( my $pk = $pkg->{'pk_accessor'} ) {
365             push @create, $pk;
366         }
367
368         if ( my @has_a = @{ $pkg->{'has_a'} || [] } ) {
369             push @create, $_ for @has_a;
370         }
371
372         foreach my $has_many_key ( keys %{ $pkg->{'has_many'} } ) {
373             if ( my @has_many = @{ $pkg->{'has_many'}{$has_many_key} || [] } ) {
374                 push @create, $_ for @has_many;
375             }
376         }
377     }
378
379     push @create, "1;\n";
380
381     return wantarray
382         ? @create
383         : join('', @create);
384 }
385
386 1;
387
388 =pod
389
390 =head1 NAME
391
392 SQL::Translator::Producer::ClassDBI - create Class::DBI classes from schema
393
394 =head1 SYNOPSIS
395
396 Use this producer as you would any other from SQL::Translator.  See
397 L<SQL::Translator> for details.
398
399 This package uses SQL::Translator's formatting methods
400 format_package_name(), format_pk_name(), format_fk_name(), and
401 format_table_name() as it creates classes, one per table in the schema
402 provided.  An additional base class is also created for database connectivity
403 configuration.  See L<Class::DBI> for details on how this works.
404
405 =head1 AUTHORS
406
407 Allen Day E<lt>allenday@ucla.eduE<gt>,
408 Ying Zhang E<lt>zyolive@yahoo.comE<gt>,
409 Ken Youens-Clark E<lt>kclark@cpan.orgE<gt>.