take out duplicate docs
[dbsrgits/SQL-Translator.git] / lib / SQL / Translator / Producer / ClassDBI.pm
CommitLineData
f42e7027 1package SQL::Translator::Producer::ClassDBI;
2
44659089 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
f42e7027 21use strict;
da06ac74 22use vars qw[ $VERSION $DEBUG ];
11ad2df9 23$VERSION = '1.59';
41a7b982 24$DEBUG = 1 unless defined $DEBUG;
f42e7027 25
6c45056f 26use SQL::Translator::Schema::Constants;
73892176 27use SQL::Translator::Utils qw(debug header_comment);
71046f4b 28use Data::Dumper;
f42e7027 29
bf4629e7 30my %CDBI_auto_pkgs = (
71046f4b 31 MySQL => 'mysql',
32 PostgreSQL => 'Pg',
33 Oracle => 'Oracle',
bf4629e7 34);
35
f42e7027 36sub produce {
4d1e8cb4 37 my $t = shift;
38 local $DEBUG = $t->debug;
390292d3 39 my $no_comments = $t->no_comments;
40 my $schema = $t->schema;
41 my $args = $t->producer_args;
4d1e8cb4 42 my @create;
43
73892176 44 if ( my $fmt = $args->{'format_pkg_name'} ) {
45 $t->format_package_name( $fmt );
46 }
4d1e8cb4 47
73892176 48 if ( my $fmt = $args->{'format_fk_name'} ) {
49 $t->format_fk_name( $fmt );
50 }
4d1e8cb4 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} || '';
ea93df61 60 my $dsn = $args->{'dsn'} || sprintf( 'dbi:%s:_',
61 $CDBI_auto_pkgs{ $parser_type }
62 ? $CDBI_auto_pkgs{ $parser_type } : $parser_type
41a7b982 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
ea93df61 182 next unless (
41a7b982 183 $field->foreign_key_reference->reference_table eq
184 $table_name
ea93df61 185 ||
186 $field->foreign_key_reference->reference_table eq $link
41a7b982 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 );
ea93df61 275 my $fk_method = join('::', $table_pkg_name,
73892176 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" : '' );
4d1e8cb4 321 push @create, join ( "\n",
41a7b982 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
4d1e8cb4 336 push @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 ) {
4d1e8cb4 344 push @create, join('',
345 $pkg->{'pkg_name'},
346 "->set_up_table('",
347 $pkg->{'table'},
348 "');\n\n"
349 );
9c6eb8e3 350 }
351 else {
352 my $table = $schema->get_table( $pkg->{'table'} );
353 my @field_names = map { $_->name } $table->get_fields;
ea93df61 354
4d1e8cb4 355 push @create, join("\n",
9c6eb8e3 356 $pkg_name."->table('".$pkg->{'table'}."');\n",
357 $pkg_name."->columns(All => qw/".
358 join(' ', @field_names)."/);\n\n",
359 );
360 }
b789c790 361
4d1e8cb4 362 push @create, "\n";
b789c790 363
bf4629e7 364 if ( my $pk = $pkg->{'pk_accessor'} ) {
4d1e8cb4 365 push @create, $pk;
bf4629e7 366 }
df602cfb 367
bf4629e7 368 if ( my @has_a = @{ $pkg->{'has_a'} || [] } ) {
4d1e8cb4 369 push @create, $_ for @has_a;
bf4629e7 370 }
371
41a7b982 372 foreach my $has_many_key ( keys %{ $pkg->{'has_many'} } ) {
373 if ( my @has_many = @{ $pkg->{'has_many'}{$has_many_key} || [] } ) {
4d1e8cb4 374 push @create, $_ for @has_many;
41a7b982 375 }
376 }
6c45056f 377 }
df602cfb 378
4d1e8cb4 379 push @create, "1;\n";
bf4629e7 380
4d1e8cb4 381 return wantarray
382 ? @create
383 : join('', @create);
f42e7027 384}
385
3861;
387
bf4629e7 388=pod
f42e7027 389
390=head1 NAME
391
bf4629e7 392SQL::Translator::Producer::ClassDBI - create Class::DBI classes from schema
f42e7027 393
394=head1 SYNOPSIS
395
1eee27d3 396Use this producer as you would any other from SQL::Translator. See
397L<SQL::Translator> for details.
f42e7027 398
4d1e8cb4 399This package uses SQL::Translator's formatting methods
1eee27d3 400format_package_name(), format_pk_name(), format_fk_name(), and
401format_table_name() as it creates classes, one per table in the schema
402provided. An additional base class is also created for database connectivity
403configuration. See L<Class::DBI> for details on how this works.
f42e7027 404
6c45056f 405=head1 AUTHORS
f42e7027 406
7c2e6f47 407Allen Day E<lt>allenday@ucla.eduE<gt>,
5f054727 408Ying Zhang E<lt>zyolive@yahoo.comE<gt>,
4d1e8cb4 409Ken Youens-Clark E<lt>kclark@cpan.orgE<gt>.