Applied changes submitted by Paul Makepeace <sourceforge.net@paulm.com>.
[dbsrgits/SQL-Translator.git] / lib / SQL / Translator / Producer / ClassDBI.pm
CommitLineData
f42e7027 1package SQL::Translator::Producer::ClassDBI;
2
3# -------------------------------------------------------------------
4330d04e 4# $Id: ClassDBI.pm,v 1.44 2005-11-17 21:55:41 mwz444 Exp $
f42e7027 5# -------------------------------------------------------------------
977651a5 6# Copyright (C) 2002-4 SQLFairy Authors
f42e7027 7#
8# This program is free software; you can redistribute it and/or
9# modify it under the terms of the GNU General Public License as
10# published by the Free Software Foundation; version 2.
11#
12# This program is distributed in the hope that it will be useful, but
13# WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15# General Public License for more details.
16#
17# You should have received a copy of the GNU General Public License
18# along with this program; if not, write to the Free Software
19# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
20# 02111-1307 USA
21# -------------------------------------------------------------------
22
23use strict;
24use vars qw[ $VERSION $DEBUG ];
4330d04e 25$VERSION = sprintf "%d.%02d", q$Revision: 1.44 $ =~ /(\d+)\.(\d+)/;
41a7b982 26$DEBUG = 1 unless defined $DEBUG;
f42e7027 27
6c45056f 28use SQL::Translator::Schema::Constants;
73892176 29use SQL::Translator::Utils qw(debug header_comment);
71046f4b 30use Data::Dumper;
f42e7027 31
bf4629e7 32my %CDBI_auto_pkgs = (
71046f4b 33 MySQL => 'mysql',
34 PostgreSQL => 'Pg',
35 Oracle => 'Oracle',
bf4629e7 36);
37
38# -------------------------------------------------------------------
f42e7027 39sub produce {
41a7b982 40 my $t = shift;
41 my $create = undef;
42 local $DEBUG = $t->debug;
390292d3 43 my $no_comments = $t->no_comments;
44 my $schema = $t->schema;
45 my $args = $t->producer_args;
73892176 46 if ( my $fmt = $args->{'format_pkg_name'} ) {
47 $t->format_package_name( $fmt );
48 }
49 if ( my $fmt = $args->{'format_fk_name'} ) {
50 $t->format_fk_name( $fmt );
51 }
bf4629e7 52 my $db_user = $args->{'db_user'} || '';
4330d04e 53 my $db_pass = $args->{'db_password'} || '';
54 my $main_pkg_name = $args->{'package_name'} ||
55 # $args->{'main_pkg_name'} || # keep this? undocumented
41a7b982 56 $t->format_package_name('DBI');
57 my $header = header_comment( __PACKAGE__, "# " );
390292d3 58 my $parser_type = ( split /::/, $t->parser_type )[-1];
41a7b982 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 );
71046f4b 64 my $sep = '# ' . '-' x 67;
fe77d758 65
73892176 66
fe77d758 67 #
68 # Identify "link tables" (have only PK and FK fields).
69 #
70 my %linkable;
71 my %linktable;
73892176 72 for my $table ( $schema->get_tables ) {
73 debug("PKG: Table = ", $table->name, "\n");
fe77d758 74 my $is_link = 1;
73892176 75 for my $field ( $table->get_fields ) {
fe77d758 76 unless ( $field->is_primary_key or $field->is_foreign_key ) {
41a7b982 77 $is_link = 0;
fe77d758 78 last;
79 }
80 }
81
82 next unless $is_link;
41a7b982 83
fe77d758 84 foreach my $left ( $table->get_fields ) {
85 next unless $left->is_foreign_key;
41a7b982 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];
fe77d758 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;
41a7b982 95
96 my $rfk = $right->foreign_key_reference or next;
fe77d758 97 my $rr_table = $schema->get_table( $rfk->reference_table )
41a7b982 98 or next;
99 my $rr_field_name = ( $rfk->reference_fields )[0];
fe77d758 100 my $rr_field = $rr_table->get_field($rr_field_name);
101 next unless $rr_field->is_primary_key;
41a7b982 102
c703e51d 103 $linkable{ $lr_table->name }{ $rr_table->name } = $table;
104 $linkable{ $rr_table->name }{ $lr_table->name } = $table;
fe77d758 105 $linktable{ $table->name } = $table;
106 }
107 }
108 }
c703e51d 109
6c45056f 110 #
71046f4b 111 # Iterate over all tables
6c45056f 112 #
bf4629e7 113 my ( %packages, $order );
6c45056f 114 for my $table ( $schema->get_tables ) {
115 my $table_name = $table->name or next;
6c45056f 116
4330d04e 117 my $table_pkg_name = join '::', $main_pkg_name, $t->format_package_name($table_name);
73892176 118 $packages{ $table_pkg_name } = {
41a7b982 119 order => ++$order,
120 pkg_name => $table_pkg_name,
121 base => $main_pkg_name,
122 table => $table_name,
bf4629e7 123 };
6c45056f 124
6c45056f 125 #
bf4629e7 126 # Primary key may have a differenct accessor method name
6c45056f 127 #
73892176 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# }
d79af833 140
141 my $is_data = 0;
142 foreach my $field ( $table->get_fields ) {
41a7b982 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 }
d79af833 152 }
153
41a7b982 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 }
d79af833 266
6c45056f 267 #
bf4629e7 268 # Use foreign keys to set up "has_a/has_many" relationships.
6c45056f 269 #
270 foreach my $field ( $table->get_fields ) {
271 if ( $field->is_foreign_key ) {
bf4629e7 272 my $table_name = $table->name;
6c45056f 273 my $field_name = $field->name;
73892176 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 );
6c45056f 278 my $fk = $field->foreign_key_reference;
279 my $ref_table = $fk->reference_table;
f7cde540 280 my $ref_pkg = $t->format_package_name($ref_table);
41a7b982 281 my $ref_field = ( $fk->reference_fields )[0];
73892176 282# my $fk_method = join('::',
283# $table_pkg_name, $t->format_fk_name( $ref_table )
284# );
6c45056f 285
41a7b982 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"
73892176 290 . " return shift->$field_name\n}\n\n"
291 ;
52fbac6a 292
41a7b982 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 #
73892176 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# }
41a7b982 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";
71046f4b 312
fe77d758 313 }
41a7b982 314 }
315 }
6c45056f 316
fe77d758 317 #
318 # Now build up text of package.
319 #
bf4629e7 320 my $base_pkg = sprintf( 'Class::DBI%s', $from ? "::$from" : '' );
41a7b982 321 $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 (
bf4629e7 330 sort { $packages{ $a }{'order'} <=> $packages{ $b }{'order'} }
331 keys %packages
332 ) {
8b183a02 333 my $pkg = $packages{$pkg_name} or next;
334 next unless $pkg->{'pkg_name'};
bf4629e7 335
41a7b982 336 $create .= join ( "\n",
bf4629e7 337 $sep,
41a7b982 338 "package " . $pkg->{'pkg_name'} . ";",
339 "use base '" . $pkg->{'base'} . "';",
bf4629e7 340 "use Class::DBI::Pager;\n\n",
41a7b982 341 );
342
9c6eb8e3 343 if ( $from ) {
344 $create .=
345 $pkg->{'pkg_name'}."->set_up_table('".$pkg->{'table'}."');\n\n";
346 }
347 else {
348 my $table = $schema->get_table( $pkg->{'table'} );
349 my @field_names = map { $_->name } $table->get_fields;
420f63c7 350
9c6eb8e3 351 $create .= join("\n",
352 $pkg_name."->table('".$pkg->{'table'}."');\n",
353 $pkg_name."->columns(All => qw/".
354 join(' ', @field_names)."/);\n\n",
355 );
356 }
b789c790 357
41a7b982 358 $create .= "\n";
b789c790 359
bf4629e7 360 if ( my $pk = $pkg->{'pk_accessor'} ) {
361 $create .= $pk;
362 }
df602cfb 363
bf4629e7 364 if ( my @has_a = @{ $pkg->{'has_a'} || [] } ) {
365 $create .= $_ for @has_a;
366 }
367
41a7b982 368 foreach my $has_many_key ( keys %{ $pkg->{'has_many'} } ) {
369 if ( my @has_many = @{ $pkg->{'has_many'}{$has_many_key} || [] } ) {
370 $create .= $_ for @has_many;
371 }
372 }
6c45056f 373 }
df602cfb 374
bf4629e7 375 $create .= "1;\n";
376
377 return $create;
f42e7027 378}
379
3801;
381
bf4629e7 382# -------------------------------------------------------------------
383
384=pod
f42e7027 385
386=head1 NAME
387
bf4629e7 388SQL::Translator::Producer::ClassDBI - create Class::DBI classes from schema
f42e7027 389
390=head1 SYNOPSIS
391
1eee27d3 392Use this producer as you would any other from SQL::Translator. See
393L<SQL::Translator> for details.
f42e7027 394
1eee27d3 395This package utilizes SQL::Translator's formatting methods
396format_package_name(), format_pk_name(), format_fk_name(), and
397format_table_name() as it creates classes, one per table in the schema
398provided. An additional base class is also created for database connectivity
399configuration. See L<Class::DBI> for details on how this works.
f42e7027 400
6c45056f 401=head1 AUTHORS
f42e7027 402
7c2e6f47 403Allen Day E<lt>allenday@ucla.eduE<gt>,
5f054727 404Ying Zhang E<lt>zyolive@yahoo.comE<gt>,
799df8f9 405Ken Y. Clark E<lt>kclark@cpan.orgE<gt>.