1 package SQL::Translator::Producer::Turnkey;
3 # -------------------------------------------------------------------
4 # $Id: Turnkey.pm,v 1.1 2003-08-28 08:51:09 boconnor Exp $
5 # -------------------------------------------------------------------
6 # Copyright (C) 2003 Allen Day <allenday@ucla.edu>,
7 # Ying Zhang <zyolive@yahoo.com>
9 # This program is free software; you can redistribute it and/or
10 # modify it under the terms of the GNU General Public License as
11 # published by the Free Software Foundation; version 2.
13 # This program is distributed in the hope that it will be useful, but
14 # WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 # General Public License for more details.
18 # You should have received a copy of the GNU General Public License
19 # along with this program; if not, write to the Free Software
20 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
22 # -------------------------------------------------------------------
25 use vars qw[ $VERSION $DEBUG ];
26 $VERSION = sprintf "%d.%02d", q$Revision: 1.1 $ =~ /(\d+)\.(\d+)/;
27 $DEBUG = 1 unless defined $DEBUG;
29 use SQL::Translator::Schema::Constants;
30 use SQL::Translator::Utils qw(header_comment);
34 my %CDBI_auto_pkgs = (
40 # -------------------------------------------------------------------
44 local $DEBUG = $t->debug;
45 my $no_comments = $t->no_comments;
46 my $schema = $t->schema;
47 my $args = $t->producer_args;
48 my $db_user = $args->{'db_user'} || '';
49 my $db_pass = $args->{'db_pass'} || '';
50 my $main_pkg_name = $args->{'main_pkg_name'} ||
51 $t->format_package_name('DBI');
52 my $header = header_comment(__PACKAGE__, "# ");
53 my $parser_type = ( split /::/, $t->parser_type )[-1];
54 my $from = $CDBI_auto_pkgs{ $parser_type } || '';
55 my $dsn = $args->{'dsn'} || sprintf( 'dbi:%s:_',
56 $CDBI_auto_pkgs{ $parser_type }
57 ? $CDBI_auto_pkgs{ $parser_type } : $parser_type
59 my $sep = '# ' . '-' x 67;
62 # Identify "link tables" (have only PK and FK fields).
66 foreach my $table ( $schema->get_tables ) {
68 foreach my $field ( $table->get_fields ) {
69 unless ( $field->is_primary_key or $field->is_foreign_key ) {
77 foreach my $left ( $table->get_fields ) {
78 next unless $left->is_foreign_key;
79 my $lfk = $left->foreign_key_reference or next;
80 my $lr_table = $schema->get_table( $lfk->reference_table )
82 my $lr_field_name = ($lfk->reference_fields)[0];
83 my $lr_field = $lr_table->get_field($lr_field_name);
84 next unless $lr_field->is_primary_key;
86 foreach my $right ( $table->get_fields ) {
87 next if $left->name eq $right->name;
89 my $rfk = $right->foreign_key_reference or next;
90 my $rr_table = $schema->get_table( $rfk->reference_table )
92 my $rr_field_name = ($rfk->reference_fields)[0];
93 my $rr_field = $rr_table->get_field($rr_field_name);
94 next unless $rr_field->is_primary_key;
96 $linkable{ $lr_table->name }{ $rr_table->name } = $table;
97 $linkable{ $rr_table->name }{ $lr_table->name } = $table;
98 $linktable{ $table->name } = $table;
104 # Iterate over all tables
106 my ( %packages, $order );
107 for my $table ( $schema->get_tables ) {
108 my $table_name = $table->name or next;
110 my $table_pkg_name = $t->format_package_name($table_name);
111 $packages{ $table_pkg_name } = {
113 pkg_name => $table_pkg_name,
114 base => $main_pkg_name,
115 table => $table_name,
119 # Primary key may have a differenct accessor method name
121 if ( my $constraint = $table->primary_key ) {
122 my $field = ($constraint->fields)[0];
123 $packages{ $table_pkg_name }{'columns_primary'} = $field;
125 if ( my $pk_xform = $t->format_pk_name ) {
126 my $pk_name = $pk_xform->( $table_pkg_name, $field );
128 $packages{ $table_pkg_name }{'pk_accessor'} =
129 "#\n# Primary key accessor\n#\n".
130 "sub $pk_name {\n shift->$field\n}\n\n";
136 foreach my $field ( $table->get_fields ) {
137 if ( !$field->is_foreign_key and !$field->is_primary_key ) {
138 push @{ $packages{ $table_pkg_name }{'columns_essential'} }, $field->name;
140 } elsif ( !$field->is_primary_key ) {
141 push @{ $packages{ $table_pkg_name }{'columns_others'} }, $field->name;
147 foreach my $link ( keys %{ $linkable{ $table_name } } ) {
150 if ( my $fk_xform = $t->format_fk_name ) {
151 # ADD CALLBACK FOR PLURALIZATION MANGLING HERE
152 $linkmethodname = $fk_xform->($linkable{$table_name}{$link}->name,
153 ($schema->get_table($link)->primary_key->fields)[0]).'s';
155 # ADD CALLBACK FOR PLURALIZATION MANGLING HERE
156 $linkmethodname = $linkable{$table_name}{$link}->name.'_'.
157 ($schema->get_table($link)->primary_key->fields)[0].'s';
162 foreach my $field ($linkable{$table_name}{$link}->get_fields) {
163 next unless $field->is_foreign_key;
166 $field->foreign_key_reference->reference_table eq $table_name
168 $field->foreign_key_reference->reference_table eq $link
170 push @lk_fields, ($field->foreign_key_reference->reference_fields)[0]
171 if $field->foreign_key_reference->reference_table eq $link;
172 push @rk_fields, $field->name
173 if $field->foreign_key_reference->reference_table eq $table_name;
176 #if one possible traversal via link table
177 if (scalar(@rk_fields) == 1 and scalar(@lk_fields) == 1) {
178 foreach my $rk_field (@rk_fields) {
179 #push @{ $packages{ $table_pkg_name }{'has_many'}{ $link } },
180 push @{ $packages{ $table_pkg_name }{'has_many'}{$link}{'link_one_one'} },
181 "sub ".$linkmethodname." { my \$self = shift; ".
183 ($schema->get_table($link)->primary_key->fields)[0].
184 ", \$self->".$linkable{$table_name}{$link}->name.
185 "_".$rk_field." }\n\n";
186 #push @{ $packages{ $table_pkg_name }{'has_many'}{ $link }{'one_one'} },
187 # {link_method_name => $linkmethodname, primary_key_field => ($schema->get_table($link)->primary_key->fields)[0],
188 # table_name => $linkable{$table_name}{$link}->name, rk_field => $rk_field};
190 #else there is more than one way to traverse it. ack!
191 #let's treat these types of link tables as a many-to-one (easier)
193 #NOTE: we need to rethink the link method name, as the cardinality
195 } elsif (scalar(@rk_fields) == 1) {
196 foreach my $rk_field (@rk_fields) {
197 # ADD CALLBACK FOR PLURALIZATION MANGLING HERE
198 #push @{ $packages{ $table_pkg_name }{'has_many'}{ $link } },
199 push @{ $packages{ $table_pkg_name }{'has_many'}{ $link }{'link_many_one'} },
200 "sub " . $linkable{$table_name}{$link}->name .
201 "s { my \$self = shift; return \$self->" .
202 $linkable{$table_name}{$link}->name . "_" .
203 $rk_field . "(\@_) }\n\n";
204 #push @{ $packages{ $table_pkg_name }{'has_many'}{ $link }{'many_one'} },
206 # table_name => $linkable{$table_name}{$link}->name, rk_field => $rk_field
209 } elsif (scalar(@lk_fields) == 1) {
210 #these will be taken care of on the other end...
212 #many many many. need multiple iterations here, data structure revision
213 #to handle N FK sources. This code has not been tested and likely doesn't
215 foreach my $rk_field (@rk_fields) {
216 # ADD CALLBACK FOR PLURALIZATION MANGLING HERE
217 #push @{ $packages{ $table_pkg_name }{'has_many'}{ $link } },
218 push @{ $packages{ $table_pkg_name }{'has_many'}{ $link }{'link_many_many'} },
219 "sub " . $linkable{$table_name}{$link}->name . "_" . $rk_field .
220 "s { my \$self = shift; return \$self->" .
221 $linkable{$table_name}{$link}->name . "_" .
222 $rk_field . "(\@_) }\n\n";
223 #push @{ $packages{ $table_pkg_name }{'has_many'}{ $link }{'many_many'} },
225 # table_name => $linkable{$table_name}{$link}->name, rk_field => $rk_field
234 # Use foreign keys to set up "has_a/has_many" relationships.
236 foreach my $field ( $table->get_fields ) {
237 if ( $field->is_foreign_key ) {
238 my $table_name = $table->name;
239 my $field_name = $field->name;
240 my $fk_method = $t->format_fk_name($table_name, $field_name);
241 my $fk = $field->foreign_key_reference;
242 my $ref_table = $fk->reference_table;
243 my $ref_pkg = $t->format_package_name($ref_table);
244 my $ref_field = ($fk->reference_fields)[0];
246 push @{ $packages{ $table_pkg_name }{'has_a'} },
247 "$table_pkg_name->has_a(\n".
248 " $field_name => '$ref_pkg'\n);\n\n".
249 "sub $fk_method {\n".
250 " return shift->$field_name\n}\n\n"
255 # If this table "has a" to the other, then it follows
256 # that the other table "has many" of this one, right?
258 # No... there is the possibility of 1-1 cardinality
260 #if there weren't M-M relationships via the has_many
261 #being set up here, create nice pluralized method alias
262 #rather for user as alt. to ugly tablename_fieldname name
263 if(! $packages{ $ref_pkg }{ 'has_many' }{ $table_name } ){
264 # ADD CALLBACK FOR PLURALIZATION MANGLING HERE
265 #push @{ $packages{ $ref_pkg }{'has_many'}{ $table_name } },
266 # "sub $table_name\s {\n return shift->$table_name\_$field_name\n}\n\n";
267 push @{ $packages{ $ref_pkg }{'has_many'}{ $table_name }{'fk_pluralized'} },
268 { table_name => $table_name, field_name => $field_name };
274 #push @{ $packages{ $ref_pkg }{'has_many'}{ $table_name } },
275 # "$ref_pkg->has_many(\n '${table_name}_${field_name}', ".
276 # "'$table_pkg_name' => '$field_name'\n);\n\n";
277 push @{ $packages{ $ref_pkg }{'has_many'}{ $table_name }{pluralized} },
278 { ref_pkg => $ref_pkg, table_pkg_name => $table_pkg_name, table_name => $table_name, field_name => $field_name };
284 $metadata{"packages"} = \%packages;
285 $metadata{"linkable"} = \%linkable;
286 return(translateForm($t, \%metadata));
289 ###########################################
290 # Here documents for the tt2 templates #
291 ###########################################
293 my $turnkey_atom_tt2 = <<'EOF';
294 [% ###### DOCUMENT START ###### %]
296 [% FOREACH package = linkable %]
298 ##############################################
300 package Durian::Atom::[% package.key FILTER ucfirst %];
302 [% pname = package.key FILTER ucfirst%]
303 [% pkey = "Durian::Model::${pname}" %]
305 use base qw(Durian::Atom);
314 my $dbobject = shift;
315 # Assumption here that if it's not rendering on it's own dbobject
316 # then it's a list. This will be updated when AtomLists are implemented -boconnor
317 if(ref($dbobject) eq 'Durian::Model::[% package.key FILTER ucfirst %]') {
318 return(_render_record($dbobject));
320 else { return(_render_list($dbobject)); }
324 my $dbobject = shift;
328 [% FOREACH field = packages.$pkey.columns_essential %]
329 $field_hash->{[% field %]} = $dbobject->[% field %]();
331 $row->{data} = $field_hash;
332 $row->{id} = $dbobject->id();
338 my $dbobject = shift;
340 my @objects = $dbobject->[% package.key %]s;
341 foreach my $object (@objects)
345 [% FOREACH field = packages.$pkey.columns_essential %]
346 $field_hash->{[% field %]} = $object->[% field %]();
348 $row->{data} = $field_hash;
349 $row->{id} = $object->id();
364 my $turnkey_dbi_tt2 = <<EOF;
365 [% ####### MACRO START ###### %]
367 [% MACRO printPackage(package) BLOCK %]
368 # --------------------------------------------
369 package [% package.pkg_name %];
370 use base '[% package.base %]';
371 use Class::DBI::Pager;
373 [% package.pkg_name %]->set_up_table('[% package.table %]');
374 [% package.pkg_name %]->columns(Primary => qw/[% printList(package.columns_primary) %]/);
375 [% package.pkg_name %]->columns(Essential => qw/[% printList(package.columns_essential) %]/);
377 [% printPKAccessors(package.columns_primary, package.table) %]
378 [% printHasMany(package.has_many, package.table) %]
379 [% printHasA(package.has_a, package.pkg_name) %]
383 [% MACRO printPKAccessors(array, name) BLOCK %]
385 # Primary key accessor
387 [% FOREACH item = array %]
394 [% MACRO printHasMany(hash, name) BLOCK %]
398 [% FOREACH group = hash %][% FOREACH item = group.value %][% FOREACH arr = item.value %]
399 # Key: [% group.key %]
400 # Relationship: [% item.key %]
401 [% IF item.key == 'fk_pluralized' %]
402 sub [% arr.table_name -%]s {
403 return shift->[% arr.table_name %]_[% arr.field_name %]
405 [% ELSIF item.key == 'pluralized' %]
406 [% arr.ref_pkg %]->has_many('[% arr.table_name %]_[% arr.field_name %]', '[% arr.table_pkg_name %]' => '[% arr.field_name %]');
407 [% ELSIF item.key == 'link_one_one' %]
408 [% FOREACH line = item.value %]
411 [% ELSIF item.key == 'link_many_one' %]
412 [% FOREACH line = item.value %]
415 [% ELSIF item.key == 'link_many_many' %]
416 [% FOREACH line = item.value %]
421 [% END %][% END %][% END %][% END %]
423 [% MACRO printHasA(hash, pkg_name) BLOCK %]
428 [% FOREACH item = hash %][% item %]
431 [% MACRO printList(array) BLOCK %][% FOREACH item = array %][% item %] [% END %][% END %]
434 [% ###### DOCUMENT START ###### %]
436 package Durian::Model::DBI;
438 # Created by SQL::Translator::Producer::ClassDBI
439 # Template used AutoDBI.tt2
442 use base qw(Class::DBI::Pg);
444 Durian::Model::DBI->set_db('Main', '[% db_str %]', '[% db_user %]', '[% db_pass %]');
446 [% FOREACH package = packages %]
447 [% printPackage(package.value) %]
451 my $turnkey_xml_tt2 = <<EOF;
452 <?xml version="1.0" encoding="UTF-8"?>
453 <!DOCTYPE Durian SYSTEM "Durian.dtd">
456 <!-- The basic layout is fixed -->
457 <container bgcolor="#FFFFFF" cellpadding="0" cellspacing="0" height="90%" orientation="vertical" type="root" width="100%" xlink:label="RootContainer">
458 <container cellpadding="3" cellspacing="0" orientation="horizontal" type="container" height="100%" width="100%" xlink:label="MiddleContainer">
459 <container align="center" cellpadding="2" cellspacing="0" class="leftbar" orientation="vertical" type="minor" width="0%" xlink:label="MidLeftContainer"/>
460 <container cellpadding="0" cellspacing="0" orientation="vertical" width="100%" type="major" xlink:label="MainContainer"/>
464 <!-- Atom Classes -->
465 [% FOREACH package = linkable %]
466 <atom class="Durian::Atom::[% package.key FILTER ucfirst %]" name="[% package.key FILTER ucfirst %]" xlink:label="[% package.key FILTER ucfirst %]Atom"/>
469 <!-- Atom Bindings -->
471 [% FOREACH focus_atom = linkable %]
472 [% FOREACH link_atom = focus_atom.value %]
473 <atomatombinding xlink:from="#[% focus_atom.key FILTER ucfirst %]Atom" xlink:to="#[% link_atom.key FILTER ucfirst %]Atom" xlink:label="[% focus_atom.key FILTER ucfirst %]Atom2[% link_atom.key FILTER ucfirst %]Atom"/>
478 <atomcontainerbindings>
479 [% FOREACH focus_atom = linkable %]
480 <atomcontainerbindingslayout xlink:label="Durian::Model::[% focus_atom.key FILTER ucfirst %]">
481 [% FOREACH link_atom = focus_atom.value %]
482 <atomcontainerbinding xlink:from="#MidLeftContainer" xlink:label="MidLeftContainer2[% link_atom.key FILTER ucfirst %]Atom" xlink:to="#[% link_atom.key FILTER ucfirst %]Atom"/>
484 <atomcontainerbinding xlink:from="#MainContainer" xlink:label="MainContainer2[% focus_atom.key FILTER ucfirst %]Atom" xlink:to="#[% focus_atom.key FILTER ucfirst %]Atom"/>
485 </atomcontainerbindingslayout>
487 </atomcontainerbindings>
490 <uribinding uri="/" class="Durian::Util::Frontpage"/>
494 [% FOREACH focus_atom = linkable %]
495 <classbinding class="Durian::Model::[% focus_atom.key FILTER ucfirst %]" plugin="#[% focus_atom.key FILTER ucfirst %]Atom" rank="0"/>
502 my $turnkey_template_tt2 = <<'EOF';
504 [% MACRO renderpanel(panel,dbobject) BLOCK %]
505 <!-- begin panel: [% panel.label %] -->
506 <table border="0" width="[% panel.width %]" height="[% panel.height %]" bgcolor="[% panel.bgcolor %]" valign="top" cellpadding="[% panel.cellpadding %]" cellspacing="[% panel.cellspacing %]" align="[% panel.align %]" valign="[% panel.valign %]">
508 [% FOREACH p = panel.containers %]
509 [% IF p.can_render(panel) %]
510 <td valign="top" class="[% p.class %]" align="[% panel.align %]" height="[% p.height || 1 %]" width="[% p.width %]">
511 [% IF p.type == 'Container' %]
512 [% renderpanel(p,dbobject) %]
514 <table cellpadding="0" cellspacing="0" align="left" height="100%" width="100%">
516 <tr bgcolor="#4444FF" height="1">
517 <td><font color="#FFFFFF">[% p.name %][% IF panel.type == 'major' %]: [% dbobject.name %][% END %]</font></td>
518 <td align="right" width="0"><!--<nobr><img src="/images/v.gif"/><img src="/images/^.gif"/>[% IF p.delible == 'yes' %]<img src="/images/x.gif"/>[% END %]</nobr>--></td>
521 <tr><td colspan="2" bgcolor="#FFFFFF">
522 <!-- begin atom: [% p.label %] -->
523 <table cellpadding="0" cellspacing="0" align="left" height="100%" width="100%"><!-- [% ref(atom) %] [% ref(dbobject) %] -->
524 [% renderatom(p,dbobject) %] <!-- used to be renderplugin(p,panel) -->
529 [% IF panel.orientation == 'vertical' %]
536 <!-- end panel: [% panel.label %] -->
538 [% MACRO renderatom(atom, dbobject) SWITCH atom.name %]
539 [- FOREACH package = linkable -]
540 [% CASE '[- package.key FILTER ucfirst -]' %]
541 [% render[- package.key FILTER ucfirst -]Atom(atom.render(dbobject)) %]
544 [% renderlist(atom.render(dbobject)) %]
546 [- FOREACH package = linkable -]
547 [% MACRO render[- package.key FILTER ucfirst -]Atom(lstArr) BLOCK %]
548 [% FOREACH record = lstArr %]
549 [% fields = record.data %]
550 [- pname = package.key FILTER ucfirst -]
551 [- pkey = "Durian::Model::${pname}" -]
552 [- FOREACH field = packages.$pkey.columns_essential -]
553 <tr><td><b>[- field -]</b></td><td>[% fields.[- field -] %]</td></tr>
556 <tr><td><a href="?id=[% id %];class=Durian::Model::[- package.key FILTER ucfirst -]">Link</a></td><td></td></tr>
560 [% MACRO renderlist(lstArr) BLOCK %]
561 [% FOREACH item = lstArr %]
571 my $args = $t->producer_args;
572 my $tt2 = $args->{'template'};
574 if ($tt2 eq 'atom') { $tt2Ref = \$turnkey_atom_tt2; }
575 if ($tt2 eq 'dbi') { $tt2Ref = \$turnkey_dbi_tt2; }
576 if ($tt2 eq 'xml') { $tt2Ref = \$turnkey_xml_tt2; }
577 if ($tt2 eq 'template') { $tt2Ref = \$turnkey_template_tt2; }
580 packages => $output->{packages},
581 linkable => $output->{linkable},
582 linktable => $output->{linktable},
583 db_str => $args->{db_str},
584 db_user => $args->{db_user},
585 db_pass => $args->{db_pass},
588 EVAL_PERL => 1, # evaluate Perl code blocks
591 # create Template object
592 my $template = Template->new($config);
595 # specify input filename, or file handle, text reference, etc.
596 # process input template, substituting variables
597 $template->process($tt2Ref, $vars, \$result) || die $template->error();
603 # -------------------------------------------------------------------
609 SQL::Translator::Producer::ClassDBI - create Class::DBI classes from schema
613 Use this producer as you would any other from SQL::Translator. See
614 L<SQL::Translator> for details.
616 This package utilizes SQL::Translator's formatting methods
617 format_package_name(), format_pk_name(), format_fk_name(), and
618 format_table_name() as it creates classes, one per table in the schema
619 provided. An additional base class is also created for database connectivity
620 configuration. See L<Class::DBI> for details on how this works.
624 Allen Day E<lt>allenday@ucla.eduE<gt>
625 Ying Zhang E<lt>zyolive@yahoo.comE<gt>,
626 Ken Y. Clark E<lt>kclark@cpan.orgE<gt>,
627 Brian O'Connor E<lt>brian.oconnor@excite.comE<gt>.