1 package SQL::Translator::Producer::ClassDBI;
3 # -------------------------------------------------------------------
4 # Copyright (C) 2002-2009 SQLFairy Authors
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.
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.
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
19 # -------------------------------------------------------------------
22 use vars qw[ $VERSION $DEBUG ];
24 $DEBUG = 1 unless defined $DEBUG;
26 use SQL::Translator::Schema::Constants;
27 use SQL::Translator::Utils qw(debug header_comment);
30 my %CDBI_auto_pkgs = (
36 # -------------------------------------------------------------------
39 local $DEBUG = $t->debug;
40 my $no_comments = $t->no_comments;
41 my $schema = $t->schema;
42 my $args = $t->producer_args;
45 if ( my $fmt = $args->{'format_pkg_name'} ) {
46 $t->format_package_name( $fmt );
49 if ( my $fmt = $args->{'format_fk_name'} ) {
50 $t->format_fk_name( $fmt );
53 my $db_user = $args->{'db_user'} || '';
54 my $db_pass = $args->{'db_password'} || '';
55 my $main_pkg_name = $args->{'package_name'} ||
56 # $args->{'main_pkg_name'} || # keep this? undocumented
57 $t->format_package_name('DBI');
58 my $header = header_comment( __PACKAGE__, "# " );
59 my $parser_type = ( split /::/, $t->parser_type )[-1];
60 my $from = $CDBI_auto_pkgs{$parser_type} || '';
61 my $dsn = $args->{'dsn'} || sprintf( 'dbi:%s:_',
62 $CDBI_auto_pkgs{ $parser_type }
63 ? $CDBI_auto_pkgs{ $parser_type } : $parser_type
65 my $sep = '# ' . '-' x 67;
69 # Identify "link tables" (have only PK and FK fields).
73 for my $table ( $schema->get_tables ) {
74 debug("PKG: Table = ", $table->name, "\n");
76 for my $field ( $table->get_fields ) {
77 unless ( $field->is_primary_key or $field->is_foreign_key ) {
85 foreach my $left ( $table->get_fields ) {
86 next unless $left->is_foreign_key;
87 my $lfk = $left->foreign_key_reference or next;
88 my $lr_table = $schema->get_table( $lfk->reference_table )
90 my $lr_field_name = ( $lfk->reference_fields )[0];
91 my $lr_field = $lr_table->get_field($lr_field_name);
92 next unless $lr_field->is_primary_key;
94 foreach my $right ( $table->get_fields ) {
95 next if $left->name eq $right->name;
97 my $rfk = $right->foreign_key_reference or next;
98 my $rr_table = $schema->get_table( $rfk->reference_table )
100 my $rr_field_name = ( $rfk->reference_fields )[0];
101 my $rr_field = $rr_table->get_field($rr_field_name);
102 next unless $rr_field->is_primary_key;
104 $linkable{ $lr_table->name }{ $rr_table->name } = $table;
105 $linkable{ $rr_table->name }{ $lr_table->name } = $table;
106 $linktable{ $table->name } = $table;
112 # Iterate over all tables
114 my ( %packages, $order );
115 for my $table ( $schema->get_tables ) {
116 my $table_name = $table->name or next;
118 my $table_pkg_name = join '::', $main_pkg_name, $t->format_package_name($table_name);
119 $packages{ $table_pkg_name } = {
121 pkg_name => $table_pkg_name,
122 base => $main_pkg_name,
123 table => $table_name,
127 # Primary key may have a differenct accessor method name
129 # if ( my $constraint = $table->primary_key ) {
130 # my $field = ( $constraint->fields )[0];
131 # $packages{ $table_pkg_name }{'_columns_primary'} = $field;
133 # if ( my $pk_xform = $t->format_pk_name ) {
134 # my $pk_name = $pk_xform->( $table_pkg_name, $field );
136 # $packages{$table_pkg_name}{'pk_accessor'} =
137 # "#\n# Primary key accessor\n#\n"
138 # . "sub $pk_name {\n shift->$field\n}\n\n";
143 foreach my $field ( $table->get_fields ) {
144 if ( !$field->is_foreign_key and !$field->is_primary_key ) {
145 push @{ $packages{$table_pkg_name}{'_columns_essential'} },
149 elsif ( !$field->is_primary_key ) {
150 push @{ $packages{$table_pkg_name}{'_columns_others'} },
157 foreach my $link ( keys %{ $linkable{$table_name} } ) {
160 if ( my $fk_xform = $t->format_fk_name ) {
162 # ADD CALLBACK FOR PLURALIZATION MANGLING HERE
163 $linkmethodname = $fk_xform->(
164 $linkable{ $table_name }{ $link }->name,
165 ( $schema->get_table( $link )->primary_key->fields )[0]
170 # ADD CALLBACK FOR PLURALIZATION MANGLING HERE
172 $linkable{ $table_name }{ $link }->name . '_'
173 . ( $schema->get_table( $link )->primary_key->fields )[0]
179 foreach my $field ( $linkable{$table_name}{$link}->get_fields )
181 next unless $field->is_foreign_key;
184 $field->foreign_key_reference->reference_table eq
187 $field->foreign_key_reference->reference_table eq $link
191 ( $field->foreign_key_reference->reference_fields )[0]
192 if $field->foreign_key_reference->reference_table eq
195 push @rk_fields, $field->name
196 if $field->foreign_key_reference->reference_table eq
201 # If one possible traversal via link table.
203 if ( scalar(@rk_fields) == 1 and scalar(@lk_fields) == 1 ) {
204 foreach my $rk_field (@rk_fields) {
205 push @{ $packages{$table_pkg_name}{'has_many'}{$link} },
208 . " { my \$self = shift; "
210 . ( $schema->get_table($link)->primary_key->fields )
213 . $linkable{$table_name}{$link}->name . "_"
219 # Else there is more than one way to traverse it.
220 # ack! Let's treat these types of link tables as
221 # a many-to-one (easier)
223 # NOTE: we need to rethink the link method name,
224 # as the cardinality has shifted on us.
227 elsif ( scalar(@rk_fields) == 1 ) {
228 foreach my $rk_field (@rk_fields) {
230 # ADD CALLBACK FOR PLURALIZATION MANGLING HERE
232 push @{ $packages{$table_pkg_name}{'has_many'}{$link} },
234 . $linkable{$table_name}{$link}->name
235 . "s { my \$self = shift; return \$self->"
236 . $linkable{$table_name}{$link}->name . "_"
241 elsif ( scalar(@lk_fields) == 1 ) {
243 # These will be taken care of on the other end...
248 # Many many many. Need multiple iterations here,
249 # data structure revision to handle N FK sources.
250 # This code has not been tested and likely doesn't
253 foreach my $rk_field (@rk_fields) {
254 # ADD CALLBACK FOR PLURALIZATION MANGLING HERE
255 push @{ $packages{$table_pkg_name}{'has_many'}{$link} },
257 . $linkable{$table_name}{$link}->name . "_"
259 . "s { my \$self = shift; return \$self->"
260 . $linkable{$table_name}{$link}->name . "_"
269 # Use foreign keys to set up "has_a/has_many" relationships.
271 foreach my $field ( $table->get_fields ) {
272 if ( $field->is_foreign_key ) {
273 my $table_name = $table->name;
274 my $field_name = $field->name;
275 # my $fk_method = $t->format_fk_name( $table_name, $field_name );
276 my $fk_method = join('::', $table_pkg_name,
277 $t->format_fk_name( $table_name, $field_name )
279 my $fk = $field->foreign_key_reference;
280 my $ref_table = $fk->reference_table;
281 my $ref_pkg = $t->format_package_name($ref_table);
282 my $ref_field = ( $fk->reference_fields )[0];
283 # my $fk_method = join('::',
284 # $table_pkg_name, $t->format_fk_name( $ref_table )
287 push @{ $packages{$table_pkg_name}{'has_a'} },
288 "$table_pkg_name->has_a(\n"
289 . " $field_name => '$ref_pkg'\n);\n\n"
290 . "sub $fk_method {\n"
291 . " return shift->$field_name\n}\n\n"
294 # if there weren't M-M relationships via the has_many
295 # being set up here, create nice pluralized method alias
296 # rather for user as alt. to ugly tablename_fieldname name
298 # if ( !$packages{$ref_pkg}{'has_many'}{$table_name} ) {
300 # # ADD CALLBACK FOR PLURALIZATION MANGLING HERE
302 # push @{ $packages{$ref_pkg}{'has_many'}{$table_name} },
303 # "sub ${table_name}s {\n " .
304 # "return shift->$table_name\_$field_name\n}\n\n";
310 push @{ $packages{$ref_pkg}{'has_many'}{$table_name} },
311 "$ref_pkg->has_many(\n '${table_name}_${field_name}', "
312 . "'$table_pkg_name' => '$field_name'\n);\n\n";
319 # Now build up text of package.
321 my $base_pkg = sprintf( 'Class::DBI%s', $from ? "::$from" : '' );
322 push @create, join ( "\n",
323 "package $main_pkg_name;\n",
326 "use base '$base_pkg';\n",
327 "$main_pkg_name->set_db('Main', '$dsn', '$db_user', '$db_pass');\n\n",
331 sort { $packages{ $a }{'order'} <=> $packages{ $b }{'order'} }
334 my $pkg = $packages{$pkg_name} or next;
335 next unless $pkg->{'pkg_name'};
337 push @create, join ( "\n",
339 "package " . $pkg->{'pkg_name'} . ";",
340 "use base '" . $pkg->{'base'} . "';",
341 "use Class::DBI::Pager;\n\n",
345 push @create, join('',
353 my $table = $schema->get_table( $pkg->{'table'} );
354 my @field_names = map { $_->name } $table->get_fields;
356 push @create, join("\n",
357 $pkg_name."->table('".$pkg->{'table'}."');\n",
358 $pkg_name."->columns(All => qw/".
359 join(' ', @field_names)."/);\n\n",
365 if ( my $pk = $pkg->{'pk_accessor'} ) {
369 if ( my @has_a = @{ $pkg->{'has_a'} || [] } ) {
370 push @create, $_ for @has_a;
373 foreach my $has_many_key ( keys %{ $pkg->{'has_many'} } ) {
374 if ( my @has_many = @{ $pkg->{'has_many'}{$has_many_key} || [] } ) {
375 push @create, $_ for @has_many;
380 push @create, "1;\n";
389 # -------------------------------------------------------------------
395 SQL::Translator::Producer::ClassDBI - create Class::DBI classes from schema
399 Use this producer as you would any other from SQL::Translator. See
400 L<SQL::Translator> for details.
402 This package uses SQL::Translator's formatting methods
403 format_package_name(), format_pk_name(), format_fk_name(), and
404 format_table_name() as it creates classes, one per table in the schema
405 provided. An additional base class is also created for database connectivity
406 configuration. See L<Class::DBI> for details on how this works.
410 Allen Day E<lt>allenday@ucla.eduE<gt>,
411 Ying Zhang E<lt>zyolive@yahoo.comE<gt>,
412 Ken Youens-Clark E<lt>kclark@cpan.orgE<gt>.