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 # -------------------------------------------------------------------
40 local $DEBUG = $t->debug;
41 my $no_comments = $t->no_comments;
42 my $schema = $t->schema;
43 my $args = $t->producer_args;
44 if ( my $fmt = $args->{'format_pkg_name'} ) {
45 $t->format_package_name( $fmt );
47 if ( my $fmt = $args->{'format_fk_name'} ) {
48 $t->format_fk_name( $fmt );
50 my $db_user = $args->{'db_user'} || '';
51 my $db_pass = $args->{'db_password'} || '';
52 my $main_pkg_name = $args->{'package_name'} ||
53 # $args->{'main_pkg_name'} || # keep this? undocumented
54 $t->format_package_name('DBI');
55 my $header = header_comment( __PACKAGE__, "# " );
56 my $parser_type = ( split /::/, $t->parser_type )[-1];
57 my $from = $CDBI_auto_pkgs{$parser_type} || '';
58 my $dsn = $args->{'dsn'} || sprintf( 'dbi:%s:_',
59 $CDBI_auto_pkgs{ $parser_type }
60 ? $CDBI_auto_pkgs{ $parser_type } : $parser_type
62 my $sep = '# ' . '-' x 67;
66 # Identify "link tables" (have only PK and FK fields).
70 for my $table ( $schema->get_tables ) {
71 debug("PKG: Table = ", $table->name, "\n");
73 for my $field ( $table->get_fields ) {
74 unless ( $field->is_primary_key or $field->is_foreign_key ) {
82 foreach my $left ( $table->get_fields ) {
83 next unless $left->is_foreign_key;
84 my $lfk = $left->foreign_key_reference or next;
85 my $lr_table = $schema->get_table( $lfk->reference_table )
87 my $lr_field_name = ( $lfk->reference_fields )[0];
88 my $lr_field = $lr_table->get_field($lr_field_name);
89 next unless $lr_field->is_primary_key;
91 foreach my $right ( $table->get_fields ) {
92 next if $left->name eq $right->name;
94 my $rfk = $right->foreign_key_reference or next;
95 my $rr_table = $schema->get_table( $rfk->reference_table )
97 my $rr_field_name = ( $rfk->reference_fields )[0];
98 my $rr_field = $rr_table->get_field($rr_field_name);
99 next unless $rr_field->is_primary_key;
101 $linkable{ $lr_table->name }{ $rr_table->name } = $table;
102 $linkable{ $rr_table->name }{ $lr_table->name } = $table;
103 $linktable{ $table->name } = $table;
109 # Iterate over all tables
111 my ( %packages, $order );
112 for my $table ( $schema->get_tables ) {
113 my $table_name = $table->name or next;
115 my $table_pkg_name = join '::', $main_pkg_name, $t->format_package_name($table_name);
116 $packages{ $table_pkg_name } = {
118 pkg_name => $table_pkg_name,
119 base => $main_pkg_name,
120 table => $table_name,
124 # Primary key may have a differenct accessor method name
126 # if ( my $constraint = $table->primary_key ) {
127 # my $field = ( $constraint->fields )[0];
128 # $packages{ $table_pkg_name }{'_columns_primary'} = $field;
130 # if ( my $pk_xform = $t->format_pk_name ) {
131 # my $pk_name = $pk_xform->( $table_pkg_name, $field );
133 # $packages{$table_pkg_name}{'pk_accessor'} =
134 # "#\n# Primary key accessor\n#\n"
135 # . "sub $pk_name {\n shift->$field\n}\n\n";
140 foreach my $field ( $table->get_fields ) {
141 if ( !$field->is_foreign_key and !$field->is_primary_key ) {
142 push @{ $packages{$table_pkg_name}{'_columns_essential'} },
146 elsif ( !$field->is_primary_key ) {
147 push @{ $packages{$table_pkg_name}{'_columns_others'} },
154 foreach my $link ( keys %{ $linkable{$table_name} } ) {
157 if ( my $fk_xform = $t->format_fk_name ) {
159 # ADD CALLBACK FOR PLURALIZATION MANGLING HERE
160 $linkmethodname = $fk_xform->(
161 $linkable{ $table_name }{ $link }->name,
162 ( $schema->get_table( $link )->primary_key->fields )[0]
167 # ADD CALLBACK FOR PLURALIZATION MANGLING HERE
169 $linkable{ $table_name }{ $link }->name . '_'
170 . ( $schema->get_table( $link )->primary_key->fields )[0]
176 foreach my $field ( $linkable{$table_name}{$link}->get_fields )
178 next unless $field->is_foreign_key;
181 $field->foreign_key_reference->reference_table eq
184 $field->foreign_key_reference->reference_table eq $link
188 ( $field->foreign_key_reference->reference_fields )[0]
189 if $field->foreign_key_reference->reference_table eq
192 push @rk_fields, $field->name
193 if $field->foreign_key_reference->reference_table eq
198 # If one possible traversal via link table.
200 if ( scalar(@rk_fields) == 1 and scalar(@lk_fields) == 1 ) {
201 foreach my $rk_field (@rk_fields) {
202 push @{ $packages{$table_pkg_name}{'has_many'}{$link} },
205 . " { my \$self = shift; "
207 . ( $schema->get_table($link)->primary_key->fields )
210 . $linkable{$table_name}{$link}->name . "_"
216 # Else there is more than one way to traverse it.
217 # ack! Let's treat these types of link tables as
218 # a many-to-one (easier)
220 # NOTE: we need to rethink the link method name,
221 # as the cardinality has shifted on us.
224 elsif ( scalar(@rk_fields) == 1 ) {
225 foreach my $rk_field (@rk_fields) {
227 # ADD CALLBACK FOR PLURALIZATION MANGLING HERE
229 push @{ $packages{$table_pkg_name}{'has_many'}{$link} },
231 . $linkable{$table_name}{$link}->name
232 . "s { my \$self = shift; return \$self->"
233 . $linkable{$table_name}{$link}->name . "_"
238 elsif ( scalar(@lk_fields) == 1 ) {
240 # These will be taken care of on the other end...
245 # Many many many. Need multiple iterations here,
246 # data structure revision to handle N FK sources.
247 # This code has not been tested and likely doesn't
250 foreach my $rk_field (@rk_fields) {
251 # ADD CALLBACK FOR PLURALIZATION MANGLING HERE
252 push @{ $packages{$table_pkg_name}{'has_many'}{$link} },
254 . $linkable{$table_name}{$link}->name . "_"
256 . "s { my \$self = shift; return \$self->"
257 . $linkable{$table_name}{$link}->name . "_"
266 # Use foreign keys to set up "has_a/has_many" relationships.
268 foreach my $field ( $table->get_fields ) {
269 if ( $field->is_foreign_key ) {
270 my $table_name = $table->name;
271 my $field_name = $field->name;
272 # my $fk_method = $t->format_fk_name( $table_name, $field_name );
273 my $fk_method = join('::', $table_pkg_name,
274 $t->format_fk_name( $table_name, $field_name )
276 my $fk = $field->foreign_key_reference;
277 my $ref_table = $fk->reference_table;
278 my $ref_pkg = $t->format_package_name($ref_table);
279 my $ref_field = ( $fk->reference_fields )[0];
280 # my $fk_method = join('::',
281 # $table_pkg_name, $t->format_fk_name( $ref_table )
284 push @{ $packages{$table_pkg_name}{'has_a'} },
285 "$table_pkg_name->has_a(\n"
286 . " $field_name => '$ref_pkg'\n);\n\n"
287 . "sub $fk_method {\n"
288 . " return shift->$field_name\n}\n\n"
291 # if there weren't M-M relationships via the has_many
292 # being set up here, create nice pluralized method alias
293 # rather for user as alt. to ugly tablename_fieldname name
295 # if ( !$packages{$ref_pkg}{'has_many'}{$table_name} ) {
297 # # ADD CALLBACK FOR PLURALIZATION MANGLING HERE
299 # push @{ $packages{$ref_pkg}{'has_many'}{$table_name} },
300 # "sub ${table_name}s {\n " .
301 # "return shift->$table_name\_$field_name\n}\n\n";
307 push @{ $packages{$ref_pkg}{'has_many'}{$table_name} },
308 "$ref_pkg->has_many(\n '${table_name}_${field_name}', "
309 . "'$table_pkg_name' => '$field_name'\n);\n\n";
316 # Now build up text of package.
318 my $base_pkg = sprintf( 'Class::DBI%s', $from ? "::$from" : '' );
319 $create .= join ( "\n",
320 "package $main_pkg_name;\n",
323 "use base '$base_pkg';\n",
324 "$main_pkg_name->set_db('Main', '$dsn', '$db_user', '$db_pass');\n\n",
328 sort { $packages{ $a }{'order'} <=> $packages{ $b }{'order'} }
331 my $pkg = $packages{$pkg_name} or next;
332 next unless $pkg->{'pkg_name'};
334 $create .= join ( "\n",
336 "package " . $pkg->{'pkg_name'} . ";",
337 "use base '" . $pkg->{'base'} . "';",
338 "use Class::DBI::Pager;\n\n",
343 $pkg->{'pkg_name'}."->set_up_table('".$pkg->{'table'}."');\n\n";
346 my $table = $schema->get_table( $pkg->{'table'} );
347 my @field_names = map { $_->name } $table->get_fields;
349 $create .= join("\n",
350 $pkg_name."->table('".$pkg->{'table'}."');\n",
351 $pkg_name."->columns(All => qw/".
352 join(' ', @field_names)."/);\n\n",
358 if ( my $pk = $pkg->{'pk_accessor'} ) {
362 if ( my @has_a = @{ $pkg->{'has_a'} || [] } ) {
363 $create .= $_ for @has_a;
366 foreach my $has_many_key ( keys %{ $pkg->{'has_many'} } ) {
367 if ( my @has_many = @{ $pkg->{'has_many'}{$has_many_key} || [] } ) {
368 $create .= $_ for @has_many;
380 # -------------------------------------------------------------------
386 SQL::Translator::Producer::ClassDBI - create Class::DBI classes from schema
390 Use this producer as you would any other from SQL::Translator. See
391 L<SQL::Translator> for details.
393 This package utilizes SQL::Translator's formatting methods
394 format_package_name(), format_pk_name(), format_fk_name(), and
395 format_table_name() as it creates classes, one per table in the schema
396 provided. An additional base class is also created for database connectivity
397 configuration. See L<Class::DBI> for details on how this works.
401 Allen Day E<lt>allenday@ucla.eduE<gt>,
402 Ying Zhang E<lt>zyolive@yahoo.comE<gt>,
403 Ken Y. Clark E<lt>kclark@cpan.orgE<gt>.