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 = (
38 local $DEBUG = $t->debug;
39 my $no_comments = $t->no_comments;
40 my $schema = $t->schema;
41 my $args = $t->producer_args;
44 if ( my $fmt = $args->{'format_pkg_name'} ) {
45 $t->format_package_name( $fmt );
48 if ( my $fmt = $args->{'format_fk_name'} ) {
49 $t->format_fk_name( $fmt );
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
64 my $sep = '# ' . '-' x 67;
68 # Identify "link tables" (have only PK and FK fields).
72 for my $table ( $schema->get_tables ) {
73 debug("PKG: Table = ", $table->name, "\n");
75 for my $field ( $table->get_fields ) {
76 unless ( $field->is_primary_key or $field->is_foreign_key ) {
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 )
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;
93 foreach my $right ( $table->get_fields ) {
94 next if $left->name eq $right->name;
96 my $rfk = $right->foreign_key_reference or next;
97 my $rr_table = $schema->get_table( $rfk->reference_table )
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;
103 $linkable{ $lr_table->name }{ $rr_table->name } = $table;
104 $linkable{ $rr_table->name }{ $lr_table->name } = $table;
105 $linktable{ $table->name } = $table;
111 # Iterate over all tables
113 my ( %packages, $order );
114 for my $table ( $schema->get_tables ) {
115 my $table_name = $table->name or next;
117 my $table_pkg_name = join '::', $main_pkg_name, $t->format_package_name($table_name);
118 $packages{ $table_pkg_name } = {
120 pkg_name => $table_pkg_name,
121 base => $main_pkg_name,
122 table => $table_name,
126 # Primary key may have a differenct accessor method name
128 # if ( my $constraint = $table->primary_key ) {
129 # my $field = ( $constraint->fields )[0];
130 # $packages{ $table_pkg_name }{'_columns_primary'} = $field;
132 # if ( my $pk_xform = $t->format_pk_name ) {
133 # my $pk_name = $pk_xform->( $table_pkg_name, $field );
135 # $packages{$table_pkg_name}{'pk_accessor'} =
136 # "#\n# Primary key accessor\n#\n"
137 # . "sub $pk_name {\n shift->$field\n}\n\n";
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'} },
148 elsif ( !$field->is_primary_key ) {
149 push @{ $packages{$table_pkg_name}{'_columns_others'} },
156 foreach my $link ( keys %{ $linkable{$table_name} } ) {
159 if ( my $fk_xform = $t->format_fk_name ) {
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]
169 # ADD CALLBACK FOR PLURALIZATION MANGLING HERE
171 $linkable{ $table_name }{ $link }->name . '_'
172 . ( $schema->get_table( $link )->primary_key->fields )[0]
178 foreach my $field ( $linkable{$table_name}{$link}->get_fields )
180 next unless $field->is_foreign_key;
183 $field->foreign_key_reference->reference_table eq
186 $field->foreign_key_reference->reference_table eq $link
190 ( $field->foreign_key_reference->reference_fields )[0]
191 if $field->foreign_key_reference->reference_table eq
194 push @rk_fields, $field->name
195 if $field->foreign_key_reference->reference_table eq
200 # If one possible traversal via link table.
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} },
207 . " { my \$self = shift; "
209 . ( $schema->get_table($link)->primary_key->fields )
212 . $linkable{$table_name}{$link}->name . "_"
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)
222 # NOTE: we need to rethink the link method name,
223 # as the cardinality has shifted on us.
226 elsif ( scalar(@rk_fields) == 1 ) {
227 foreach my $rk_field (@rk_fields) {
229 # ADD CALLBACK FOR PLURALIZATION MANGLING HERE
231 push @{ $packages{$table_pkg_name}{'has_many'}{$link} },
233 . $linkable{$table_name}{$link}->name
234 . "s { my \$self = shift; return \$self->"
235 . $linkable{$table_name}{$link}->name . "_"
240 elsif ( scalar(@lk_fields) == 1 ) {
242 # These will be taken care of on the other end...
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
252 foreach my $rk_field (@rk_fields) {
253 # ADD CALLBACK FOR PLURALIZATION MANGLING HERE
254 push @{ $packages{$table_pkg_name}{'has_many'}{$link} },
256 . $linkable{$table_name}{$link}->name . "_"
258 . "s { my \$self = shift; return \$self->"
259 . $linkable{$table_name}{$link}->name . "_"
268 # Use foreign keys to set up "has_a/has_many" relationships.
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 )
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 )
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"
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
297 # if ( !$packages{$ref_pkg}{'has_many'}{$table_name} ) {
299 # # ADD CALLBACK FOR PLURALIZATION MANGLING HERE
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";
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";
318 # Now build up text of package.
320 my $base_pkg = sprintf( 'Class::DBI%s', $from ? "::$from" : '' );
321 push @create, join ( "\n",
322 "package $main_pkg_name;\n",
325 "use base '$base_pkg';\n",
326 "$main_pkg_name->set_db('Main', '$dsn', '$db_user', '$db_pass');\n\n",
330 sort { $packages{ $a }{'order'} <=> $packages{ $b }{'order'} }
333 my $pkg = $packages{$pkg_name} or next;
334 next unless $pkg->{'pkg_name'};
336 push @create, join ( "\n",
338 "package " . $pkg->{'pkg_name'} . ";",
339 "use base '" . $pkg->{'base'} . "';",
340 "use Class::DBI::Pager;\n\n",
344 push @create, join('',
352 my $table = $schema->get_table( $pkg->{'table'} );
353 my @field_names = map { $_->name } $table->get_fields;
355 push @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 push @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 push @create, $_ for @has_many;
379 push @create, "1;\n";
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 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.
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>.