1 package SQL::Translator::Producer::ClassDBI;
3 # -------------------------------------------------------------------
4 # $Id: ClassDBI.pm,v 1.41 2005-06-08 15:33:59 kycl4rk Exp $
5 # -------------------------------------------------------------------
6 # Copyright (C) 2002-4 SQLFairy Authors
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.
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.
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
21 # -------------------------------------------------------------------
24 use vars qw[ $VERSION $DEBUG ];
25 $VERSION = sprintf "%d.%02d", q$Revision: 1.41 $ =~ /(\d+)\.(\d+)/;
26 $DEBUG = 1 unless defined $DEBUG;
28 use SQL::Translator::Schema::Constants;
29 use SQL::Translator::Utils qw(debug header_comment);
32 my %CDBI_auto_pkgs = (
38 # -------------------------------------------------------------------
42 local $DEBUG = $t->debug;
43 my $no_comments = $t->no_comments;
44 my $schema = $t->schema;
45 my $args = $t->producer_args;
46 if ( my $fmt = $args->{'format_pkg_name'} ) {
47 $t->format_package_name( $fmt );
49 if ( my $fmt = $args->{'format_fk_name'} ) {
50 $t->format_fk_name( $fmt );
52 my $db_user = $args->{'db_user'} || '';
53 my $db_pass = $args->{'db_pass'} || '';
54 my $main_pkg_name = $args->{'main_pkg_name'} ||
55 $t->format_package_name('DBI');
56 my $header = header_comment( __PACKAGE__, "# " );
57 my $parser_type = ( split /::/, $t->parser_type )[-1];
58 my $from = $CDBI_auto_pkgs{$parser_type} || '';
59 my $dsn = $args->{'dsn'} || sprintf( 'dbi:%s:_',
60 $CDBI_auto_pkgs{ $parser_type }
61 ? $CDBI_auto_pkgs{ $parser_type } : $parser_type
63 my $sep = '# ' . '-' x 67;
67 # Identify "link tables" (have only PK and FK fields).
71 for my $table ( $schema->get_tables ) {
72 debug("PKG: Table = ", $table->name, "\n");
74 for my $field ( $table->get_fields ) {
75 unless ( $field->is_primary_key or $field->is_foreign_key ) {
83 foreach my $left ( $table->get_fields ) {
84 next unless $left->is_foreign_key;
85 my $lfk = $left->foreign_key_reference or next;
86 my $lr_table = $schema->get_table( $lfk->reference_table )
88 my $lr_field_name = ( $lfk->reference_fields )[0];
89 my $lr_field = $lr_table->get_field($lr_field_name);
90 next unless $lr_field->is_primary_key;
92 foreach my $right ( $table->get_fields ) {
93 next if $left->name eq $right->name;
95 my $rfk = $right->foreign_key_reference or next;
96 my $rr_table = $schema->get_table( $rfk->reference_table )
98 my $rr_field_name = ( $rfk->reference_fields )[0];
99 my $rr_field = $rr_table->get_field($rr_field_name);
100 next unless $rr_field->is_primary_key;
102 $linkable{ $lr_table->name }{ $rr_table->name } = $table;
103 $linkable{ $rr_table->name }{ $lr_table->name } = $table;
104 $linktable{ $table->name } = $table;
110 # Iterate over all tables
112 my ( %packages, $order );
113 for my $table ( $schema->get_tables ) {
114 my $table_name = $table->name or next;
116 # my $table_pkg_name = $t->format_package_name($table_name);
117 my $table_pkg_name = join( '::',
118 $main_pkg_name, $t->format_package_name($table_name)
120 $packages{ $table_pkg_name } = {
122 pkg_name => $table_pkg_name,
123 base => $main_pkg_name,
124 table => $table_name,
128 # Primary key may have a differenct accessor method name
130 # if ( my $constraint = $table->primary_key ) {
131 # my $field = ( $constraint->fields )[0];
132 # $packages{ $table_pkg_name }{'_columns_primary'} = $field;
134 # if ( my $pk_xform = $t->format_pk_name ) {
135 # my $pk_name = $pk_xform->( $table_pkg_name, $field );
137 # $packages{$table_pkg_name}{'pk_accessor'} =
138 # "#\n# Primary key accessor\n#\n"
139 # . "sub $pk_name {\n shift->$field\n}\n\n";
144 foreach my $field ( $table->get_fields ) {
145 if ( !$field->is_foreign_key and !$field->is_primary_key ) {
146 push @{ $packages{$table_pkg_name}{'_columns_essential'} },
150 elsif ( !$field->is_primary_key ) {
151 push @{ $packages{$table_pkg_name}{'_columns_others'} },
158 foreach my $link ( keys %{ $linkable{$table_name} } ) {
161 if ( my $fk_xform = $t->format_fk_name ) {
163 # ADD CALLBACK FOR PLURALIZATION MANGLING HERE
164 $linkmethodname = $fk_xform->(
165 $linkable{ $table_name }{ $link }->name,
166 ( $schema->get_table( $link )->primary_key->fields )[0]
171 # ADD CALLBACK FOR PLURALIZATION MANGLING HERE
173 $linkable{ $table_name }{ $link }->name . '_'
174 . ( $schema->get_table( $link )->primary_key->fields )[0]
180 foreach my $field ( $linkable{$table_name}{$link}->get_fields )
182 next unless $field->is_foreign_key;
185 $field->foreign_key_reference->reference_table eq
188 $field->foreign_key_reference->reference_table eq $link
192 ( $field->foreign_key_reference->reference_fields )[0]
193 if $field->foreign_key_reference->reference_table eq
196 push @rk_fields, $field->name
197 if $field->foreign_key_reference->reference_table eq
202 # If one possible traversal via link table.
204 if ( scalar(@rk_fields) == 1 and scalar(@lk_fields) == 1 ) {
205 foreach my $rk_field (@rk_fields) {
206 push @{ $packages{$table_pkg_name}{'has_many'}{$link} },
209 . " { my \$self = shift; "
211 . ( $schema->get_table($link)->primary_key->fields )
214 . $linkable{$table_name}{$link}->name . "_"
220 # Else there is more than one way to traverse it.
221 # ack! Let's treat these types of link tables as
222 # a many-to-one (easier)
224 # NOTE: we need to rethink the link method name,
225 # as the cardinality has shifted on us.
228 elsif ( scalar(@rk_fields) == 1 ) {
229 foreach my $rk_field (@rk_fields) {
231 # ADD CALLBACK FOR PLURALIZATION MANGLING HERE
233 push @{ $packages{$table_pkg_name}{'has_many'}{$link} },
235 . $linkable{$table_name}{$link}->name
236 . "s { my \$self = shift; return \$self->"
237 . $linkable{$table_name}{$link}->name . "_"
242 elsif ( scalar(@lk_fields) == 1 ) {
244 # These will be taken care of on the other end...
249 # Many many many. Need multiple iterations here,
250 # data structure revision to handle N FK sources.
251 # This code has not been tested and likely doesn't
254 foreach my $rk_field (@rk_fields) {
255 # ADD CALLBACK FOR PLURALIZATION MANGLING HERE
256 push @{ $packages{$table_pkg_name}{'has_many'}{$link} },
258 . $linkable{$table_name}{$link}->name . "_"
260 . "s { my \$self = shift; return \$self->"
261 . $linkable{$table_name}{$link}->name . "_"
270 # Use foreign keys to set up "has_a/has_many" relationships.
272 foreach my $field ( $table->get_fields ) {
273 if ( $field->is_foreign_key ) {
274 my $table_name = $table->name;
275 my $field_name = $field->name;
276 # my $fk_method = $t->format_fk_name( $table_name, $field_name );
277 my $fk_method = join('::', $table_pkg_name,
278 $t->format_fk_name( $table_name, $field_name )
280 my $fk = $field->foreign_key_reference;
281 my $ref_table = $fk->reference_table;
282 my $ref_pkg = join('::',
283 $main_pkg_name, $t->format_package_name($ref_table)
285 my $ref_field = ( $fk->reference_fields )[0];
286 # my $fk_method = join('::',
287 # $table_pkg_name, $t->format_fk_name( $ref_table )
290 push @{ $packages{$table_pkg_name}{'has_a'} },
291 "$table_pkg_name->has_a(\n"
292 . " $field_name => '$ref_pkg'\n);\n\n"
293 . "sub $fk_method {\n"
294 . " return shift->$field_name\n}\n\n"
297 # if there weren't M-M relationships via the has_many
298 # being set up here, create nice pluralized method alias
299 # rather for user as alt. to ugly tablename_fieldname name
301 # if ( !$packages{$ref_pkg}{'has_many'}{$table_name} ) {
303 # # ADD CALLBACK FOR PLURALIZATION MANGLING HERE
305 # push @{ $packages{$ref_pkg}{'has_many'}{$table_name} },
306 # "sub ${table_name}s {\n " .
307 # "return shift->$table_name\_$field_name\n}\n\n";
313 push @{ $packages{$ref_pkg}{'has_many'}{$table_name} },
314 "$ref_pkg->has_many(\n '${table_name}_${field_name}', "
315 . "'$table_pkg_name' => '$field_name'\n);\n\n";
322 # Now build up text of package.
324 my $base_pkg = sprintf( 'Class::DBI%s', $from ? "::$from" : '' );
325 $create .= join ( "\n",
326 "package $main_pkg_name;\n",
329 "use base '$base_pkg';\n",
330 "$main_pkg_name->set_db('Main', '$dsn', '$db_user', '$db_pass');\n\n",
334 sort { $packages{ $a }{'order'} <=> $packages{ $b }{'order'} }
337 my $pkg = $packages{$pkg_name} or next;
338 next unless $pkg->{'pkg_name'};
340 $create .= join ( "\n",
342 "package " . $pkg->{'pkg_name'} . ";",
343 "use base '" . $pkg->{'base'} . "';",
344 "use Class::DBI::Pager;\n\n",
349 $pkg->{'pkg_name'}."->set_up_table('".$pkg->{'table'}."');\n\n";
352 my $table = $schema->get_table( $pkg->{'table'} );
353 my @field_names = map { $_->name } $table->get_fields;
355 $create .= join("\n",
356 $pkg_name."->table('".$pkg->{'table'}."');\n",
357 $pkg_name."->columns(All => qw/".
358 join(' ', @field_names)."/);\n\n",
364 if ( my $pk = $pkg->{'pk_accessor'} ) {
368 if ( my @has_a = @{ $pkg->{'has_a'} || [] } ) {
369 $create .= $_ for @has_a;
372 foreach my $has_many_key ( keys %{ $pkg->{'has_many'} } ) {
373 if ( my @has_many = @{ $pkg->{'has_many'}{$has_many_key} || [] } ) {
374 $create .= $_ for @has_many;
386 # -------------------------------------------------------------------
392 SQL::Translator::Producer::ClassDBI - create Class::DBI classes from schema
396 Use this producer as you would any other from SQL::Translator. See
397 L<SQL::Translator> for details.
399 This package utilizes 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.
407 Allen Day E<lt>allenday@ucla.eduE<gt>,
408 Ying Zhang E<lt>zyolive@yahoo.comE<gt>,
409 Ken Y. Clark E<lt>kclark@cpan.orgE<gt>.