[Bio] / Sprout / ERDB.pm Repository:
ViewVC logotype

Diff of /Sprout/ERDB.pm

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1.20, Sun Sep 11 17:02:33 2005 UTC revision 1.45, Tue Jun 6 05:05:15 2006 UTC
# Line 9  Line 9 
9      use DBObject;      use DBObject;
10      use Stats;      use Stats;
11      use Time::HiRes qw(gettimeofday);      use Time::HiRes qw(gettimeofday);
12        use Digest::MD5 qw(md5_base64);
13      use FIG;      use FIG;
14    
15  =head1 Entity-Relationship Database Package  =head1 Entity-Relationship Database Package
# Line 109  Line 110 
110  compatability with certain database packages), but the only values supported are  compatability with certain database packages), but the only values supported are
111  0 and 1.  0 and 1.
112    
113    =item id-string
114    
115    variable-length string, maximum 25 characters
116    
117  =item key-string  =item key-string
118    
119  variable-length string, maximum 40 characters  variable-length string, maximum 40 characters
# Line 125  Line 130 
130    
131  variable-length string, maximum 255 characters  variable-length string, maximum 255 characters
132    
133    =item hash-string
134    
135    variable-length string, maximum 22 characters
136    
137  =back  =back
138    
139    The hash-string data type has a special meaning. The actual key passed into the loader will
140    be a string, but it will be digested into a 22-character MD5 code to save space. Although the
141    MD5 algorithm is not perfect, it is extremely unlikely two strings will have the same
142    digest. Therefore, it is presumed the keys will be unique. When the database is actually
143    in use, the hashed keys will be presented rather than the original values. For this reason,
144    they should not be used for entities where the key is meaningful.
145    
146  =head3 Global Tags  =head3 Global Tags
147    
148  The entire database definition must be inside a B<Database> tag. The display name of  The entire database definition must be inside a B<Database> tag. The display name of
# Line 309  Line 325 
325                    text =>    { sqlType => 'TEXT',               maxLen => 1000000000,   avgLen => 500, dataGen => "StringGen(IntGen(80,1000))" },                    text =>    { sqlType => 'TEXT',               maxLen => 1000000000,   avgLen => 500, dataGen => "StringGen(IntGen(80,1000))" },
326                    date =>    { sqlType => 'BIGINT',             maxLen => 80,           avgLen =>   8, dataGen => "DateGen(-7, 7, IntGen(0,1400))" },                    date =>    { sqlType => 'BIGINT',             maxLen => 80,           avgLen =>   8, dataGen => "DateGen(-7, 7, IntGen(0,1400))" },
327                    float =>   { sqlType => 'DOUBLE PRECISION',   maxLen => 40,           avgLen =>   8, dataGen => "FloatGen(0.0, 100.0)" },                    float =>   { sqlType => 'DOUBLE PRECISION',   maxLen => 40,           avgLen =>   8, dataGen => "FloatGen(0.0, 100.0)" },
328                    boolean => { sqlType => 'SMALLINT',           maxLen => 1,            avgLen =>   2, dataGen => "IntGen(0, 1)" },                    boolean => { sqlType => 'SMALLINT',           maxLen => 1,            avgLen =>   1, dataGen => "IntGen(0, 1)" },
329                     'hash-string' =>
330                                 { sqlType => 'VARCHAR(22)',        maxLen => 22,           avgLen =>  22, dataGen => "SringGen(22)" },
331                     'id-string' =>
332                                 { sqlType => 'VARCHAR(25)',        maxLen => 25,           avgLen =>  25, dataGen => "SringGen(22)" },
333                   'key-string' =>                   'key-string' =>
334                               { sqlType => 'VARCHAR(40)',        maxLen => 40,           avgLen =>  10, dataGen => "StringGen(IntGen(10,40))" },                               { sqlType => 'VARCHAR(40)',        maxLen => 40,           avgLen =>  10, dataGen => "StringGen(IntGen(10,40))" },
335                   'name-string' =>                   'name-string' =>
# Line 402  Line 422 
422      # Write the HTML heading stuff.      # Write the HTML heading stuff.
423      print HTMLOUT "<html>\n<head>\n<title>$title</title>\n";      print HTMLOUT "<html>\n<head>\n<title>$title</title>\n";
424      print HTMLOUT "</head>\n<body>\n";      print HTMLOUT "</head>\n<body>\n";
425        # Write the documentation.
426        print HTMLOUT $self->DisplayMetaData();
427        # Close the document.
428        print HTMLOUT "</body>\n</html>\n";
429        # Close the file.
430        close HTMLOUT;
431    }
432    
433    =head3 DisplayMetaData
434    
435    C<< my $html = $erdb->DisplayMetaData(); >>
436    
437    Return an HTML description of the database. This description can be used to help users create
438    the data to be loaded into the relations and form queries. The output is raw includable HTML
439    without any HEAD or BODY tags.
440    
441    =over 4
442    
443    =item filename
444    
445    The name of the output file.
446    
447    =back
448    
449    =cut
450    
451    sub DisplayMetaData {
452        # Get the parameters.
453        my ($self) = @_;
454        # Get the metadata and the title string.
455        my $metadata = $self->{_metaData};
456        # Get the title string.
457        my $title = $metadata->{Title};
458        # Get the entity and relationship lists.
459        my $entityList = $metadata->{Entities};
460        my $relationshipList = $metadata->{Relationships};
461        # Declare the return variable.
462        my $retVal = "";
463        # Open the output file.
464        Trace("Building MetaData table of contents.") if T(4);
465      # Here we do the table of contents. It starts as an unordered list of section names. Each      # Here we do the table of contents. It starts as an unordered list of section names. Each
466      # section contains an ordered list of entity or relationship subsections.      # section contains an ordered list of entity or relationship subsections.
467      print HTMLOUT "<ul>\n<li><a href=\"#EntitiesSection\">Entities</a>\n<ol>\n";      $retVal .= "<ul>\n<li><a href=\"#EntitiesSection\">Entities</a>\n<ol>\n";
468      # Loop through the Entities, displaying a list item for each.      # Loop through the Entities, displaying a list item for each.
469      foreach my $key (sort keys %{$entityList}) {      foreach my $key (sort keys %{$entityList}) {
470          # Display this item.          # Display this item.
471          print HTMLOUT "<li><a href=\"#$key\">$key</a></li>\n";          $retVal .= "<li><a href=\"#$key\">$key</a></li>\n";
472      }      }
473      # Close off the entity section and start the relationship section.      # Close off the entity section and start the relationship section.
474      print HTMLOUT "</ol></li>\n<li><a href=\"#RelationshipsSection\">Relationships</a>\n<ol>\n";      $retVal .= "</ol></li>\n<li><a href=\"#RelationshipsSection\">Relationships</a>\n<ol>\n";
475      # Loop through the Relationships.      # Loop through the Relationships.
476      foreach my $key (sort keys %{$relationshipList}) {      foreach my $key (sort keys %{$relationshipList}) {
477          # Display this item.          # Display this item.
478          my $relationshipTitle = _ComputeRelationshipSentence($key, $relationshipList->{$key});          my $relationshipTitle = _ComputeRelationshipSentence($key, $relationshipList->{$key});
479          print HTMLOUT "<li><a href=\"#$key\">$relationshipTitle</a></li>\n";          $retVal .= "<li><a href=\"#$key\">$relationshipTitle</a></li>\n";
480      }      }
481      # Close off the relationship section and list the join table section.      # Close off the relationship section and list the join table section.
482      print HTMLOUT "</ol></li>\n<li><a href=\"#JoinTable\">Join Table</a></li>\n";      $retVal .= "</ol></li>\n<li><a href=\"#JoinTable\">Join Table</a></li>\n";
483      # Close off the table of contents itself.      # Close off the table of contents itself.
484      print HTMLOUT "</ul>\n";      $retVal .=  "</ul>\n";
485      # Now we start with the actual data. Denote we're starting the entity section.      # Now we start with the actual data. Denote we're starting the entity section.
486      print HTMLOUT "<a name=\"EntitiesSection\"></a><h2>Entities</h2>\n";      $retVal .= "<a name=\"EntitiesSection\"></a><h2>Entities</h2>\n";
487      # Loop through the entities.      # Loop through the entities.
488      for my $key (sort keys %{$entityList}) {      for my $key (sort keys %{$entityList}) {
489          Trace("Building MetaData entry for $key entity.") if T(4);          Trace("Building MetaData entry for $key entity.") if T(4);
490          # Create the entity header. It contains a bookmark and the entity name.          # Create the entity header. It contains a bookmark and the entity name.
491          print HTMLOUT "<a name=\"$key\"></a><h3>$key</h3>\n";          $retVal .= "<a name=\"$key\"></a><h3>$key</h3>\n";
492          # Get the entity data.          # Get the entity data.
493          my $entityData = $entityList->{$key};          my $entityData = $entityList->{$key};
494          # If there's descriptive text, display it.          # If there's descriptive text, display it.
495          if (my $notes = $entityData->{Notes}) {          if (my $notes = $entityData->{Notes}) {
496              print HTMLOUT "<p>" . _HTMLNote($notes->{content}) . "</p>\n";              $retVal .= "<p>" . _HTMLNote($notes->{content}) . "</p>\n";
497          }          }
498          # Now we want a list of the entity's relationships. First, we set up the relationship subsection.          # Now we want a list of the entity's relationships. First, we set up the relationship subsection.
499          print HTMLOUT "<h4>Relationships for <b>$key</b></h4>\n<ul>\n";          $retVal .= "<h4>Relationships for <b>$key</b></h4>\n<ul>\n";
500          # Loop through the relationships.          # Loop through the relationships.
501          for my $relationship (sort keys %{$relationshipList}) {          for my $relationship (sort keys %{$relationshipList}) {
502              # Get the relationship data.              # Get the relationship data.
# Line 446  Line 506 
506                  # Get the relationship sentence and append the arity.                  # Get the relationship sentence and append the arity.
507                  my $relationshipDescription = _ComputeRelationshipSentence($relationship, $relationshipStructure);                  my $relationshipDescription = _ComputeRelationshipSentence($relationship, $relationshipStructure);
508                  # Display the relationship data.                  # Display the relationship data.
509                  print HTMLOUT "<li><a href=\"#$relationship\">$relationshipDescription</a></li>\n";                  $retVal .= "<li><a href=\"#$relationship\">$relationshipDescription</a></li>\n";
510              }              }
511          }          }
512          # Close off the relationship list.          # Close off the relationship list.
513          print HTMLOUT "</ul>\n";          $retVal .= "</ul>\n";
514          # Get the entity's relations.          # Get the entity's relations.
515          my $relationList = $entityData->{Relations};          my $relationList = $entityData->{Relations};
516          # Create a header for the relation subsection.          # Create a header for the relation subsection.
517          print HTMLOUT "<h4>Relations for <b>$key</b></h4>\n";          $retVal .= "<h4>Relations for <b>$key</b></h4>\n";
518          # Loop through the relations, displaying them.          # Loop through the relations, displaying them.
519          for my $relation (sort keys %{$relationList}) {          for my $relation (sort keys %{$relationList}) {
520              my $htmlString = _ShowRelationTable($relation, $relationList->{$relation});              my $htmlString = _ShowRelationTable($relation, $relationList->{$relation});
521              print HTMLOUT $htmlString;              $retVal .= $htmlString;
522          }          }
523      }      }
524      # Denote we're starting the relationship section.      # Denote we're starting the relationship section.
525      print HTMLOUT "<a name=\"RelationshipsSection\"></a><h2>Relationships</h2>\n";      $retVal .= "<a name=\"RelationshipsSection\"></a><h2>Relationships</h2>\n";
526      # Loop through the relationships.      # Loop through the relationships.
527      for my $key (sort keys %{$relationshipList}) {      for my $key (sort keys %{$relationshipList}) {
528          Trace("Building MetaData entry for $key relationship.") if T(4);          Trace("Building MetaData entry for $key relationship.") if T(4);
# Line 470  Line 530 
530          my $relationshipStructure = $relationshipList->{$key};          my $relationshipStructure = $relationshipList->{$key};
531          # Create the relationship header.          # Create the relationship header.
532          my $headerText = _ComputeRelationshipHeading($key, $relationshipStructure);          my $headerText = _ComputeRelationshipHeading($key, $relationshipStructure);
533          print HTMLOUT "<h3><a name=\"$key\"></a>$headerText</h3>\n";          $retVal .= "<h3><a name=\"$key\"></a>$headerText</h3>\n";
534          # Get the entity names.          # Get the entity names.
535          my $fromEntity = $relationshipStructure->{from};          my $fromEntity = $relationshipStructure->{from};
536          my $toEntity = $relationshipStructure->{to};          my $toEntity = $relationshipStructure->{to};
# Line 480  Line 540 
540          # since both sentences will say the same thing.          # since both sentences will say the same thing.
541          my $arity = $relationshipStructure->{arity};          my $arity = $relationshipStructure->{arity};
542          if ($arity eq "11") {          if ($arity eq "11") {
543              print HTMLOUT "<p>Each <b>$fromEntity</b> relates to at most one <b>$toEntity</b>.\n";              $retVal .= "<p>Each <b>$fromEntity</b> relates to at most one <b>$toEntity</b>.\n";
544          } else {          } else {
545              print HTMLOUT "<p>Each <b>$fromEntity</b> relates to multiple <b>$toEntity</b>s.\n";              $retVal .= "<p>Each <b>$fromEntity</b> relates to multiple <b>$toEntity</b>s.\n";
546              if ($arity eq "MM" && $fromEntity ne $toEntity) {              if ($arity eq "MM" && $fromEntity ne $toEntity) {
547                  print HTMLOUT "Each <b>$toEntity</b> relates to multiple <b>$fromEntity</b>s.\n";                  $retVal .= "Each <b>$toEntity</b> relates to multiple <b>$fromEntity</b>s.\n";
548              }              }
549          }          }
550          print HTMLOUT "</p>\n";          $retVal .= "</p>\n";
551          # If there are notes on this relationship, display them.          # If there are notes on this relationship, display them.
552          if (my $notes = $relationshipStructure->{Notes}) {          if (my $notes = $relationshipStructure->{Notes}) {
553              print HTMLOUT "<p>" . _HTMLNote($notes->{content}) . "</p>\n";              $retVal .= "<p>" . _HTMLNote($notes->{content}) . "</p>\n";
554          }          }
555          # Generate the relationship's relation table.          # Generate the relationship's relation table.
556          my $htmlString = _ShowRelationTable($key, $relationshipStructure->{Relations}->{$key});          my $htmlString = _ShowRelationTable($key, $relationshipStructure->{Relations}->{$key});
557          print HTMLOUT $htmlString;          $retVal .= $htmlString;
558      }      }
559      Trace("Building MetaData join table.") if T(4);      Trace("Building MetaData join table.") if T(4);
560      # Denote we're starting the join table.      # Denote we're starting the join table.
561      print HTMLOUT "<a name=\"JoinTable\"></a><h3>Join Table</h3>\n";      $retVal .= "<a name=\"JoinTable\"></a><h3>Join Table</h3>\n";
562      # Create a table header.      # Create a table header.
563      print HTMLOUT _OpenTable("Join Table", "Source", "Target", "Join Condition");      $retVal .= _OpenTable("Join Table", "Source", "Target", "Join Condition");
564      # Loop through the joins.      # Loop through the joins.
565      my $joinTable = $metadata->{Joins};      my $joinTable = $metadata->{Joins};
566      my @joinKeys = keys %{$joinTable};      my @joinKeys = keys %{$joinTable};
# Line 508  Line 568 
568          # Separate out the source, the target, and the join clause.          # Separate out the source, the target, and the join clause.
569          $joinKey =~ m!^([^/]+)/(.+)$!;          $joinKey =~ m!^([^/]+)/(.+)$!;
570          my ($sourceRelation, $targetRelation) = ($1, $2);          my ($sourceRelation, $targetRelation) = ($1, $2);
571          Trace("Join with key $joinKey is from $sourceRelation to $targetRelation.") if T(4);          Trace("Join with key $joinKey is from $sourceRelation to $targetRelation.") if T(Joins => 4);
572          my $source = $self->ComputeObjectSentence($sourceRelation);          my $source = $self->ComputeObjectSentence($sourceRelation);
573          my $target = $self->ComputeObjectSentence($targetRelation);          my $target = $self->ComputeObjectSentence($targetRelation);
574          my $clause = $joinTable->{$joinKey};          my $clause = $joinTable->{$joinKey};
575          # Display them in a table row.          # Display them in a table row.
576          print HTMLOUT "<tr><td>$source</td><td>$target</td><td>$clause</td></tr>\n";          $retVal .= "<tr><td>$source</td><td>$target</td><td>$clause</td></tr>\n";
577      }      }
578      # Close the table.      # Close the table.
579      print HTMLOUT _CloseTable();      $retVal .= _CloseTable();
580      # Close the document.      Trace("Built MetaData HTML.") if T(3);
581      print HTMLOUT "</body>\n</html>\n";      # Return the HTML.
582      # Close the file.      return $retVal;
     close HTMLOUT;  
     Trace("Built MetaData web page.") if T(3);  
583  }  }
584    
585  =head3 DumpMetaData  =head3 DumpMetaData
# Line 553  Line 611 
611  sub CreateTables {  sub CreateTables {
612      # Get the parameters.      # Get the parameters.
613      my ($self) = @_;      my ($self) = @_;
614      my $metadata = $self->{_metaData};      # Get the relation names.
615      my $dbh = $self->{_dbh};      my @relNames = $self->GetTableNames();
616      # Loop through the entities.      # Loop through the relations.
617      my $entityHash = $metadata->{Entities};      for my $relationName (@relNames) {
     for my $entityName (keys %{$entityHash}) {  
         my $entityData = $entityHash->{$entityName};  
         # Tell the user what we're doing.  
         Trace("Creating relations for entity $entityName.") if T(1);  
         # Loop through the entity's relations.  
         for my $relationName (keys %{$entityData->{Relations}}) {  
618              # Create a table for this relation.              # Create a table for this relation.
619              $self->CreateTable($relationName);              $self->CreateTable($relationName);
620              Trace("Relation $relationName created.") if T(1);          Trace("Relation $relationName created.") if T(2);
         }  
     }  
     # Loop through the relationships.  
     my $relationshipTable = $metadata->{Relationships};  
     for my $relationshipName (keys %{$metadata->{Relationships}}) {  
         # Create a table for this relationship.  
         Trace("Creating relationship $relationshipName.") if T(1);  
         $self->CreateTable($relationshipName);  
621      }      }
622  }  }
623    
# Line 646  Line 690 
690      }      }
691  }  }
692    
693    =head3 VerifyFields
694    
695    C<< my $count = $erdb->VerifyFields($relName, \@fieldList); >>
696    
697    Run through the list of proposed field values, insuring that all the character fields are
698    below the maximum length. If any fields are too long, they will be truncated in place.
699    
700    =over 4
701    
702    =item relName
703    
704    Name of the relation for which the specified fields are destined.
705    
706    =item fieldList
707    
708    Reference to a list, in order, of the fields to be put into the relation.
709    
710    =item RETURN
711    
712    Returns the number of fields truncated.
713    
714    =back
715    
716    =cut
717    
718    sub VerifyFields {
719        # Get the parameters.
720        my ($self, $relName, $fieldList) = @_;
721        # Initialize the return value.
722        my $retVal = 0;
723        # Get the relation definition.
724        my $relData = $self->_FindRelation($relName);
725        # Get the list of field descriptors.
726        my $fieldTypes = $relData->{Fields};
727        my $fieldCount = scalar @{$fieldTypes};
728        # Loop through the two lists.
729        for (my $i = 0; $i < $fieldCount; $i++) {
730            # Get the type of the current field.
731            my $fieldType = $fieldTypes->[$i]->{type};
732            # If it's a character field, verify the length.
733            if ($fieldType =~ /string/) {
734                my $maxLen = $TypeTable{$fieldType}->{maxLen};
735                my $oldString = $fieldList->[$i];
736                if (length($oldString) > $maxLen) {
737                    # Here it's too big, so we truncate it.
738                    Trace("Truncating field $i in relation $relName to $maxLen characters from \"$oldString\".") if T(1);
739                    $fieldList->[$i] = substr $oldString, 0, $maxLen;
740                    $retVal++;
741                }
742            }
743        }
744        # Return the truncation count.
745        return $retVal;
746    }
747    
748    =head3 DigestFields
749    
750    C<< $erdb->DigestFields($relName, $fieldList); >>
751    
752    Digest the strings in the field list that correspond to data type C<hash-string> in the
753    specified relation.
754    
755    =over 4
756    
757    =item relName
758    
759    Name of the relation to which the fields belong.
760    
761    =item fieldList
762    
763    List of field contents to be loaded into the relation.
764    
765    =back
766    
767    =cut
768    #: Return Type ;
769    sub DigestFields {
770        # Get the parameters.
771        my ($self, $relName, $fieldList) = @_;
772        # Get the relation definition.
773        my $relData = $self->_FindRelation($relName);
774        # Get the list of field descriptors.
775        my $fieldTypes = $relData->{Fields};
776        my $fieldCount = scalar @{$fieldTypes};
777        # Loop through the two lists.
778        for (my $i = 0; $i < $fieldCount; $i++) {
779            # Get the type of the current field.
780            my $fieldType = $fieldTypes->[$i]->{type};
781            # If it's a hash string, digest it in place.
782            if ($fieldType eq 'hash-string') {
783                $fieldList->[$i] = md5_base64($fieldList->[$i]);
784            }
785        }
786    }
787    
788  =head3 CreateIndex  =head3 CreateIndex
789    
790  C<< $erdb->CreateIndex($relationName); >>  C<< $erdb->CreateIndex($relationName); >>
# Line 674  Line 813 
813          # Get the index's uniqueness flag.          # Get the index's uniqueness flag.
814          my $unique = (exists $indexData->{Unique} ? $indexData->{Unique} : 'false');          my $unique = (exists $indexData->{Unique} ? $indexData->{Unique} : 'false');
815          # Create the index.          # Create the index.
816          $dbh->create_index(idx => $indexName, tbl => $relationName, flds => $flds, unique => $unique);          my $rv = $dbh->create_index(idx => $indexName, tbl => $relationName,
817                                        flds => $flds, unique => $unique);
818            if ($rv) {
819          Trace("Index created: $indexName for $relationName ($flds)") if T(1);          Trace("Index created: $indexName for $relationName ($flds)") if T(1);
820            } else {
821                Confess("Error creating index $indexName for $relationName using ($flds): " . $dbh->error_message());
822            }
823      }      }
824  }  }
825    
# Line 724  Line 868 
868      $directoryName =~ s!/\\$!!;      $directoryName =~ s!/\\$!!;
869      # Declare the return variable.      # Declare the return variable.
870      my $retVal = Stats->new();      my $retVal = Stats->new();
871      # Get the metadata structure.      # Get the relation names.
872      my $metaData = $self->{_metaData};      my @relNames = $self->GetTableNames();
873      # Loop through the entities.      for my $relationName (@relNames) {
     for my $entity (values %{$metaData->{Entities}}) {  
         # Loop through the entity's relations.  
         for my $relationName (keys %{$entity->{Relations}}) {  
874              # Try to load this relation.              # Try to load this relation.
875              my $result = $self->_LoadRelation($directoryName, $relationName, $rebuild);              my $result = $self->_LoadRelation($directoryName, $relationName, $rebuild);
876              # Accumulate the statistics.              # Accumulate the statistics.
877              $retVal->Accumulate($result);              $retVal->Accumulate($result);
878          }          }
     }  
     # Loop through the relationships.  
     for my $relationshipName (keys %{$metaData->{Relationships}}) {  
         # Try to load this relationship's relation.  
         my $result = $self->_LoadRelation($directoryName, $relationshipName, $rebuild);  
         # Accumulate the statistics.  
         $retVal->Accumulate($result);  
     }  
879      # Add the duration of the load to the statistical object.      # Add the duration of the load to the statistical object.
880      $retVal->Add('duration', gettimeofday - $startTime);      $retVal->Add('duration', gettimeofday - $startTime);
881      # Return the accumulated statistics.      # Return the accumulated statistics.
882      return $retVal;      return $retVal;
883  }  }
884    
885    
886  =head3 GetTableNames  =head3 GetTableNames
887    
888  C<< my @names = $erdb->GetTableNames; >>  C<< my @names = $erdb->GetTableNames; >>
# Line 812  Line 946 
946    
947  =head3 Get  =head3 Get
948    
949  C<< my $query = $erdb->Get(\@objectNames, $filterClause, $param1, $param2, ..., $paramN); >>  C<< my $query = $erdb->Get(\@objectNames, $filterClause, \@params); >>
950    
951  This method returns a query object for entities of a specified type using a specified filter.  This method returns a query object for entities of a specified type using a specified filter.
952  The filter is a standard WHERE/ORDER BY clause with question marks as parameter markers and each  The filter is a standard WHERE/ORDER BY clause with question marks as parameter markers and each
# Line 820  Line 954 
954  following call requests all B<Genome> objects for the genus specified in the variable  following call requests all B<Genome> objects for the genus specified in the variable
955  $genus.  $genus.
956    
957  C<< $query = $erdb->Get(['Genome'], "Genome(genus) = ?", $genus); >>  C<< $query = $erdb->Get(['Genome'], "Genome(genus) = ?", [$genus]); >>
958    
959  The WHERE clause contains a single question mark, so there is a single additional  The WHERE clause contains a single question mark, so there is a single additional
960  parameter representing the parameter value. It would also be possible to code  parameter representing the parameter value. It would also be possible to code
# Line 837  Line 971 
971  It is possible to specify multiple entity and relationship names in order to retrieve more than  It is possible to specify multiple entity and relationship names in order to retrieve more than
972  one object's data at the same time, which allows highly complex joined queries. For example,  one object's data at the same time, which allows highly complex joined queries. For example,
973    
974  C<< $query = $erdb->Get(['Genome', 'ComesFrom', 'Source'], "Genome(genus) = ?", $genus); >>  C<< $query = $erdb->Get(['Genome', 'ComesFrom', 'Source'], "Genome(genus) = ?", [$genus]); >>
975    
976  If multiple names are specified, then the query processor will automatically determine a  If multiple names are specified, then the query processor will automatically determine a
977  join path between the entities and relationships. The algorithm used is very simplistic.  join path between the entities and relationships. The algorithm used is very simplistic.
978  In particular, you can't specify any entity or relationship more than once, and if a  In particular, if a relationship is recursive, the path is determined by the order in which
979  relationship is recursive, the path is determined by the order in which the entity  the entity and the relationship appear. For example, consider a recursive relationship
980  and the relationship appear. For example, consider a recursive relationship B<IsParentOf>  B<IsParentOf> which relates B<People> objects to other B<People> objects. If the join path is
 which relates B<People> objects to other B<People> objects. If the join path is  
981  coded as C<['People', 'IsParentOf']>, then the people returned will be parents. If, however,  coded as C<['People', 'IsParentOf']>, then the people returned will be parents. If, however,
982  the join path is C<['IsParentOf', 'People']>, then the people returned will be children.  the join path is C<['IsParentOf', 'People']>, then the people returned will be children.
983    
984    If an entity or relationship is mentioned twice, the name for the second occurrence will
985    be suffixed with C<2>, the third occurrence will be suffixed with C<3>, and so forth. So,
986    for example, if we have C<['Feature', 'HasContig', 'Contig', 'HasContig']>, then the
987    B<to-link> field of the first B<HasContig> is specified as C<HasContig(to-link)>, while
988    the B<to-link> field of the second B<HasContig> is specified as C<HasContig2(to-link)>.
989    
990  =over 4  =over 4
991    
992  =item objectNames  =item objectNames
# Line 870  Line 1009 
1009    
1010  C<< "Genome(genus) = ? ORDER BY Genome(species)" >>  C<< "Genome(genus) = ? ORDER BY Genome(species)" >>
1011    
1012    Note that the case is important. Only an uppercase "ORDER BY" with a single space will
1013    be processed. The idea is to make it less likely to find the verb by accident.
1014    
1015  The rules for field references in a sort order are the same as those for field references in the  The rules for field references in a sort order are the same as those for field references in the
1016  filter clause in general; however, odd things may happen if a sort field is from a secondary  filter clause in general; however, odd things may happen if a sort field is from a secondary
1017  relation.  relation.
1018    
1019  =item param1, param2, ..., paramN  Finally, you can limit the number of rows returned by adding a LIMIT clause. The LIMIT must
1020    be the last thing in the filter clause, and it contains only the word "LIMIT" followed by
1021    a positive number. So, for example
1022    
1023    C<< "Genome(genus) = ? ORDER BY Genome(species) LIMIT 10" >>
1024    
1025    will only return the first ten genomes for the specified genus. The ORDER BY clause is not
1026    required. For example, to just get the first 10 genomes in the B<Genome> table, you could
1027    use
1028    
1029  Parameter values to be substituted into the filter clause.  C<< "LIMIT 10" >>
1030    
1031    =item params
1032    
1033    Reference to a list of parameter values to be substituted into the filter clause.
1034    
1035  =item RETURN  =item RETURN
1036    
# Line 888  Line 1042 
1042    
1043  sub Get {  sub Get {
1044      # Get the parameters.      # Get the parameters.
1045      my ($self, $objectNames, $filterClause, @params) = @_;      my ($self, $objectNames, $filterClause, $params) = @_;
1046      # Construct the SELECT statement. The general pattern is      # Process the SQL stuff.
1047      #      my ($suffix, $mappedNameListRef, $mappedNameHashRef) =
1048      # SELECT name1.*, name2.*, ... nameN.* FROM name1, name2, ... nameN          $self->_SetupSQL($objectNames, $filterClause);
1049      #      # Create the query.
1050      my $dbh = $self->{_dbh};      my $command = "SELECT DISTINCT " . join(".*, ", @{$mappedNameListRef}) .
1051      my $command = "SELECT DISTINCT " . join('.*, ', @{$objectNames}) . ".* FROM " .          ".* $suffix";
1052                  join(', ', @{$objectNames});      my $sth = $self->_GetStatementHandle($command, $params);
1053      # Check for a filter clause.      # Now we create the relation map, which enables DBQuery to determine the order, name
1054      if ($filterClause) {      # and mapped name for each object in the query.
1055          # Here we have one, so we convert its field names and add it to the query. First,      my @relationMap = ();
1056          # We create a copy of the filter string we can work with.      for my $mappedName (@{$mappedNameListRef}) {
1057          my $filterString = $filterClause;          push @relationMap, [$mappedName, $mappedNameHashRef->{$mappedName}];
         # Next, we sort the object names by length. This helps protect us from finding  
         # object names inside other object names when we're doing our search and replace.  
         my @sortedNames = sort { length($b) - length($a) } @{$objectNames};  
         # We will also keep a list of conditions to add to the WHERE clause in order to link  
         # entities and relationships as well as primary relations to secondary ones.  
         my @joinWhere = ();  
         # The final preparatory step is to create a hash table of relation names. The  
         # table begins with the relation names already in the SELECT command.  
         my %fromNames = ();  
         for my $objectName (@sortedNames) {  
             $fromNames{$objectName} = 1;  
1058          }          }
1059          # We are ready to begin. We loop through the object names, replacing each      # Return the statement object.
1060          # object name's field references by the corresponding SQL field reference.      my $retVal = DBQuery::_new($self, $sth, \@relationMap);
1061          # Along the way, if we find a secondary relation, we will need to add it      return $retVal;
         # to the FROM clause.  
         for my $objectName (@sortedNames) {  
             # Get the length of the object name plus 2. This is the value we add to the  
             # size of the field name to determine the size of the field reference as a  
             # whole.  
             my $nameLength = 2 + length $objectName;  
             # Get the object's field list.  
             my $fieldList = $self->_GetFieldTable($objectName);  
             # Find the field references for this object.  
             while ($filterString =~ m/$objectName\(([^)]*)\)/g) {  
                 # At this point, $1 contains the field name, and the current position  
                 # is set immediately after the final parenthesis. We pull out the name of  
                 # the field and the position and length of the field reference as a whole.  
                 my $fieldName = $1;  
                 my $len = $nameLength + length $fieldName;  
                 my $pos = pos($filterString) - $len;  
                 # Insure the field exists.  
                 if (!exists $fieldList->{$fieldName}) {  
                     Confess("Field $fieldName not found for object $objectName.");  
                 } else {  
                     # Get the field's relation.  
                     my $relationName = $fieldList->{$fieldName}->{relation};  
                     # Insure the relation is in the FROM clause.  
                     if (!exists $fromNames{$relationName}) {  
                         # Add the relation to the FROM clause.  
                         $command .= ", $relationName";  
                         # Create its join sub-clause.  
                         push @joinWhere, "$objectName.id = $relationName.id";  
                         # Denote we have it available for future fields.  
                         $fromNames{$relationName} = 1;  
1062                      }                      }
1063                      # Form an SQL field reference from the relation name and the field name.  
1064                      my $sqlReference = "$relationName." . _FixName($fieldName);  =head3 GetFlat
1065                      # Put it into the filter string in place of the old value.  
1066                      substr($filterString, $pos, $len) = $sqlReference;  C<< my @list = $erdb->GetFlat(\@objectNames, $filterClause, \@parameterList, $field); >>
1067                      # Reposition the search.  
1068                      pos $filterString = $pos + length $sqlReference;  This is a variation of L</GetAll> that asks for only a single field per record and
1069    returns a single flattened list.
1070    
1071    =over 4
1072    
1073    =item objectNames
1074    
1075    List containing the names of the entity and relationship objects to be retrieved.
1076    
1077    =item filterClause
1078    
1079    WHERE/ORDER BY clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can
1080    be parameterized with parameter markers (C<?>). Each field used must be specified in the standard form
1081    B<I<objectName>(I<fieldName>)>. Any parameters specified in the filter clause should be added to the
1082    parameter list as additional parameters. The fields in a filter clause can come from primary
1083    entity relations, relationship relations, or secondary entity relations; however, all of the
1084    entities and relationships involved must be included in the list of object names.
1085    
1086    =item parameterList
1087    
1088    List of the parameters to be substituted in for the parameters marks in the filter clause.
1089    
1090    =item field
1091    
1092    Name of the field to be used to get the elements of the list returned.
1093    
1094    =item RETURN
1095    
1096    Returns a list of values.
1097    
1098    =back
1099    
1100    =cut
1101    #: Return Type @;
1102    sub GetFlat {
1103        # Get the parameters.
1104        my ($self, $objectNames, $filterClause, $parameterList, $field) = @_;
1105        # Construct the query.
1106        my $query = $self->Get($objectNames, $filterClause, $parameterList);
1107        # Create the result list.
1108        my @retVal = ();
1109        # Loop through the records, adding the field values found to the result list.
1110        while (my $row = $query->Fetch()) {
1111            push @retVal, $row->Value($field);
1112                  }                  }
1113        # Return the list created.
1114        return @retVal;
1115              }              }
1116    
1117    =head3 Delete
1118    
1119    C<< my $stats = $erdb->Delete($entityName, $objectID); >>
1120    
1121    Delete an entity instance from the database. The instance is deleted along with all entity and
1122    relationship instances dependent on it. The idea of dependence here is recursive. An object is
1123    always dependent on itself. An object is dependent if it is a 1-to-many or many-to-many
1124    relationship connected to a dependent entity or the "to" entity connected to a 1-to-many
1125    dependent relationship.
1126    
1127    =over 4
1128    
1129    =item entityName
1130    
1131    Name of the entity type for the instance being deleted.
1132    
1133    =item objectID
1134    
1135    ID of the entity instance to be deleted. If the ID contains a wild card character (C<%>),
1136    then it is presumed to by a LIKE pattern.
1137    
1138    =item testFlag
1139    
1140    If TRUE, the delete statements will be traced without being executed.
1141    
1142    =item RETURN
1143    
1144    Returns a statistics object indicating how many records of each particular table were
1145    deleted.
1146    
1147    =back
1148    
1149    =cut
1150    #: Return Type $%;
1151    sub Delete {
1152        # Get the parameters.
1153        my ($self, $entityName, $objectID, $testFlag) = @_;
1154        # Declare the return variable.
1155        my $retVal = Stats->new();
1156        # Get the DBKernel object.
1157        my $db = $self->{_dbh};
1158        # We're going to generate all the paths branching out from the starting entity. One of
1159        # the things we have to be careful about is preventing loops. We'll use a hash to
1160        # determine if we've hit a loop.
1161        my %alreadyFound = ();
1162        # These next lists will serve as our result stack. We start by pushing object lists onto
1163        # the stack, and then popping them off to do the deletes. This means the deletes will
1164        # start with the longer paths before getting to the shorter ones. That, in turn, makes
1165        # sure we don't delete records that might be needed to forge relationships back to the
1166        # original item. We have two lists-- one for TO-relationships, and one for
1167        # FROM-relationships and entities.
1168        my @fromPathList = ();
1169        my @toPathList = ();
1170        # This final hash is used to remember what work still needs to be done. We push paths
1171        # onto the list, then pop them off to extend the paths. We prime it with the starting
1172        # point. Note that we will work hard to insure that the last item on a path in the
1173        # TODO list is always an entity.
1174        my @todoList = ([$entityName]);
1175        while (@todoList) {
1176            # Get the current path.
1177            my $current = pop @todoList;
1178            # Copy it into a list.
1179            my @stackedPath = @{$current};
1180            # Pull off the last item on the path. It will always be an entity.
1181            my $entityName = pop @stackedPath;
1182            # Add it to the alreadyFound list.
1183            $alreadyFound{$entityName} = 1;
1184            # Get the entity data.
1185            my $entityData = $self->_GetStructure($entityName);
1186            # The first task is to loop through the entity's relation. A DELETE command will
1187            # be needed for each of them.
1188            my $relations = $entityData->{Relations};
1189            for my $relation (keys %{$relations}) {
1190                my @augmentedList = (@stackedPath, $relation);
1191                push @fromPathList, \@augmentedList;
1192          }          }
1193          # The next step is to join the objects together. We only need to do this if there          # Now we need to look for relationships connected to this entity.
1194          # is more than one object in the object list. We start with the first object and          my $relationshipList = $self->{_metaData}->{Relationships};
1195          # run through the objects after it. Note also that we make a safety copy of the          for my $relationshipName (keys %{$relationshipList}) {
1196          # list before running through it.              my $relationship = $relationshipList->{$relationshipName};
1197          my @objectList = @{$objectNames};              # Check the FROM field. We're only interested if it's us.
1198          my $lastObject = shift @objectList;              if ($relationship->{from} eq $entityName) {
1199          # Get the join table.                  # Add the path to this relationship.
1200          my $joinTable = $self->{_metaData}->{Joins};                  my @augmentedList = (@stackedPath, $entityName, $relationshipName);
1201          # Loop through the object list.                  push @fromPathList, \@augmentedList;
1202          for my $thisObject (@objectList) {                  # Check the arity. If it's MM we're done. If it's 1M
1203              # Look for a join.                  # and the target hasn't been seen yet, we want to
1204              my $joinKey = "$lastObject/$thisObject";                  # stack the entity for future processing.
1205              if (!exists $joinTable->{$joinKey}) {                  if ($relationship->{arity} eq '1M') {
1206                  # Here there's no join, so we throw an error.                      my $toEntity = $relationship->{to};
1207                  Confess("No join exists to connect from $lastObject to $thisObject.");                      if (! exists $alreadyFound{$toEntity}) {
1208                            # Here we have a new entity that's dependent on
1209                            # the current entity, so we need to stack it.
1210                            my @stackList = (@augmentedList, $toEntity);
1211                            push @fromPathList, \@stackList;
1212              } else {              } else {
1213                  # Get the join clause and add it to the WHERE list.                          Trace("$toEntity ignored because it occurred previously.") if T(4);
                 push @joinWhere, $joinTable->{$joinKey};  
                 # Save this object as the last object for the next iteration.  
                 $lastObject = $thisObject;  
1214              }              }
1215          }          }
         # Now we need to handle the whole ORDER BY thing. We'll put the order by clause  
         # in the following variable.  
         my $orderClause = "";  
         # Locate the ORDER BY verb (if any).  
         if ($filterString =~ m/^(.*)ORDER BY/g) {  
             # Here we have an ORDER BY verb. Split it off of the filter string.  
             my $pos = pos $filterString;  
             $orderClause = substr($filterString, $pos);  
             $filterString = $1;  
1216          }          }
1217          # Add the filter and the join clauses (if any) to the SELECT command.              # Now check the TO field. In this case only the relationship needs
1218          if ($filterString) {              # deletion.
1219              push @joinWhere, "($filterString)";              if ($relationship->{to} eq $entityName) {
1220                    my @augmentedList = (@stackedPath, $entityName, $relationshipName);
1221                    push @toPathList, \@augmentedList;
1222          }          }
         if (@joinWhere) {  
             $command .= " WHERE " . join(' AND ', @joinWhere);  
1223          }          }
         # Add the sort clause (if any) to the SELECT command.  
         if ($orderClause) {  
             $command .= " ORDER BY $orderClause";  
1224          }          }
1225        # Create the first qualifier for the WHERE clause. This selects the
1226        # keys of the primary entity records to be deleted. When we're deleting
1227        # from a dependent table, we construct a join page from the first qualifier
1228        # to the table containing the dependent records to delete.
1229        my $qualifier = ($objectID =~ /%/ ? "LIKE ?" : "= ?");
1230        # We need to make two passes. The first is through the to-list, and
1231        # the second through the from-list. The from-list is second because
1232        # the to-list may need to pass through some of the entities the
1233        # from-list would delete.
1234        my %stackList = ( from_link => \@fromPathList, to_link => \@toPathList );
1235        # Now it's time to do the deletes. We do it in two passes.
1236        for my $keyName ('to_link', 'from_link') {
1237            # Get the list for this key.
1238            my @pathList = @{$stackList{$keyName}};
1239            Trace(scalar(@pathList) . " entries in path list for $keyName.") if T(3);
1240            # Loop through this list.
1241            while (my $path = pop @pathList) {
1242                # Get the table whose rows are to be deleted.
1243                my @pathTables = @{$path};
1244                # Start the DELETE statement. We need to call DBKernel because the
1245                # syntax of a DELETE-USING varies among DBMSs.
1246                my $target = $pathTables[$#pathTables];
1247                my $stmt = $db->SetUsing(@pathTables);
1248                # Now start the WHERE. The first thing is the ID field from the starting table. That
1249                # starting table will either be the entity relation or one of the entity's
1250                # sub-relations.
1251                $stmt .= " WHERE $pathTables[0].id $qualifier";
1252                # Now we run through the remaining entities in the path, connecting them up.
1253                for (my $i = 1; $i <= $#pathTables; $i += 2) {
1254                    # Connect the current relationship to the preceding entity.
1255                    my ($entity, $rel) = @pathTables[$i-1,$i];
1256                    # The style of connection depends on the direction of the relationship.
1257                    $stmt .= " AND $entity.id = $rel.$keyName";
1258                    if ($i + 1 <= $#pathTables) {
1259                        # Here there's a next entity, so connect that to the relationship's
1260                        # to-link.
1261                        my $entity2 = $pathTables[$i+1];
1262                        $stmt .= " AND $rel.to_link = $entity2.id";
1263                    }
1264                }
1265                # Now we have our desired DELETE statement.
1266                if ($testFlag) {
1267                    # Here the user wants to trace without executing.
1268                    Trace($stmt) if T(0);
1269                } else {
1270                    # Here we can delete. Note that the SQL method dies with a confessing
1271                    # if an error occurs, so we just go ahead and do it.
1272                    Trace("Executing delete from $target using '$objectID'.") if T(3);
1273                    my $rv = $db->SQL($stmt, 0, $objectID);
1274                    # Accumulate the statistics for this delete. The only rows deleted
1275                    # are from the target table, so we use its name to record the
1276                    # statistic.
1277                    $retVal->Add($target, $rv);
1278      }      }
1279      Trace("SQL query: $command") if T(3);          }
1280      Trace("PARMS: '" . (join "', '", @params) . "'") if (T(4) && (@params > 0));      }
1281      my $sth = $dbh->prepare_command($command);      # Return the result.
     # Execute it with the parameters bound in.  
     $sth->execute(@params) || Confess("SELECT error" . $sth->errstr());  
     # Return the statement object.  
     my $retVal = DBQuery::_new($self, $sth, @{$objectNames});  
1282      return $retVal;      return $retVal;
1283  }  }
1284    
1285  =head3 GetList  =head3 GetList
1286    
1287  C<< my @dbObjects = $erdb->GetList(\@objectNames, $filterClause, $param1, $param2, ..., $paramN); >>  C<< my @dbObjects = $erdb->GetList(\@objectNames, $filterClause, \@params); >>
1288    
1289  Return a list of object descriptors for the specified objects as determined by the  Return a list of object descriptors for the specified objects as determined by the
1290  specified filter clause.  specified filter clause.
# Line 1040  Line 1312 
1312  with an ORDER BY clause. For example, the following filter string gets all genomes for a  with an ORDER BY clause. For example, the following filter string gets all genomes for a
1313  particular genus and sorts them by species name.  particular genus and sorts them by species name.
1314    
1315  C<< "Genome(genus) = ? ORDER BY Genome(species)" >>  C<< "Genome(genus) = ? ORDER BY Genome(species)" >>
1316    
1317    The rules for field references in a sort order are the same as those for field references in the
1318    filter clause in general; however, odd things may happen if a sort field is from a secondary
1319    relation.
1320    
1321    =item params
1322    
1323    Reference to a list of parameter values to be substituted into the filter clause.
1324    
1325    =item RETURN
1326    
1327    Returns a list of B<DBObject>s that satisfy the query conditions.
1328    
1329    =back
1330    
1331    =cut
1332    #: Return Type @%
1333    sub GetList {
1334        # Get the parameters.
1335        my ($self, $objectNames, $filterClause, $params) = @_;
1336        # Declare the return variable.
1337        my @retVal = ();
1338        # Perform the query.
1339        my $query = $self->Get($objectNames, $filterClause, $params);
1340        # Loop through the results.
1341        while (my $object = $query->Fetch) {
1342            push @retVal, $object;
1343        }
1344        # Return the result.
1345        return @retVal;
1346    }
1347    
1348    =head3 GetCount
1349    
1350    C<< my $count = $erdb->GetCount(\@objectNames, $filter, \@params); >>
1351    
1352    Return the number of rows found by a specified query. This method would
1353    normally be used to count the records in a single table. For example, in a
1354    genetics database
1355    
1356        my $count = $erdb->GetCount(['Genome'], 'Genome(genus-species) LIKE ?', ['homo %']);
1357    
1358    would return the number of genomes for the genus I<homo>. It is conceivable, however,
1359    to use it to return records based on a join. For example,
1360    
1361        my $count = $erdb->GetCount(['Feature', 'Genome'], 'Genome(genus-species) LIKE ?',
1362                                    ['homo %']);
1363    
1364    would return the number of features for genomes in the genus I<homo>. Note that
1365    only the rows from the first table are counted. If the above command were
1366    
1367        my $count = $erdb->GetCount(['Genome', 'Feature'], 'Genome(genus-species) LIKE ?',
1368                                    ['homo %']);
1369    
1370    it would return the number of genomes, not the number of genome/feature pairs.
1371    
1372    =over 4
1373    
1374    =item objectNames
1375    
1376    Reference to a list of the objects (entities and relationships) included in the
1377    query.
1378    
1379  The rules for field references in a sort order are the same as those for field references in the  =item filter
1380  filter clause in general; however, odd things may happen if a sort field is from a secondary  
1381  relation.  A filter clause for restricting the query. The rules are the same as for the L</Get>
1382    method.
1383    
1384  =item param1, param2, ..., paramN  =item params
1385    
1386  Parameter values to be substituted into the filter clause.  Reference to a list of the parameter values to be substituted for the parameter marks
1387    in the filter.
1388    
1389  =item RETURN  =item RETURN
1390    
1391  Returns a list of B<DBObject>s that satisfy the query conditions.  Returns a count of the number of records in the first table that would satisfy
1392    the query.
1393    
1394  =back  =back
1395    
1396  =cut  =cut
1397  #: Return Type @%  
1398  sub GetList {  sub GetCount {
1399      # Get the parameters.      # Get the parameters.
1400      my ($self, $objectNames, $filterClause, @params) = @_;      my ($self, $objectNames, $filter, $params) = @_;
1401      # Declare the return variable.      # Declare the return variable.
1402      my @retVal = ();      my $retVal;
1403      # Perform the query.      # Create the SQL command suffix to get the desired records.
1404      my $query = $self->Get($objectNames, $filterClause, @params);      my ($suffix, $mappedNameListRef, $mappedNameHashRef) = $self->_SetupSQL($objectNames,
1405      # Loop through the results.                                                                              $filter);
1406      while (my $object = $query->Fetch) {      # Prefix it with text telling it we want a record count.
1407          push @retVal, $object;      my $firstObject = $mappedNameListRef->[0];
1408        my $command = "SELECT COUNT($firstObject.id) $suffix";
1409        # Prepare and execute the command.
1410        my $sth = $self->_GetStatementHandle($command, $params);
1411        # Get the count value.
1412        ($retVal) = $sth->fetchrow_array();
1413        # Check for a problem.
1414        if (! defined($retVal)) {
1415            if ($sth->err) {
1416                # Here we had an SQL error.
1417                Confess("Error retrieving row count: " . $sth->errstr());
1418            } else {
1419                # Here we have no result.
1420                Confess("No result attempting to retrieve row count.");
1421            }
1422      }      }
1423      # Return the result.      # Return the result.
1424      return @retVal;      return $retVal;
1425  }  }
1426    
1427  =head3 ComputeObjectSentence  =head3 ComputeObjectSentence
# Line 1312  Line 1663 
1663    
1664  =item RETURN  =item RETURN
1665    
1666  Returns a statistical object containing the number of records read and a list of  Returns a statistical object containing a list of the error messages.
 the error messages.  
1667    
1668  =back  =back
1669    
# Line 1327  Line 1677 
1677      Trace("Loading table $relationName from $fileName") if T(2);      Trace("Loading table $relationName from $fileName") if T(2);
1678      # Get the database handle.      # Get the database handle.
1679      my $dbh = $self->{_dbh};      my $dbh = $self->{_dbh};
1680        # Get the input file size.
1681        my $fileSize = -s $fileName;
1682      # Get the relation data.      # Get the relation data.
1683      my $relation = $self->_FindRelation($relationName);      my $relation = $self->_FindRelation($relationName);
1684      # Check the truncation flag.      # Check the truncation flag.
# Line 1337  Line 1689 
1689          # leave extra room. We postulate a minimum row count of 1000 to          # leave extra room. We postulate a minimum row count of 1000 to
1690          # prevent problems with incoming empty load files.          # prevent problems with incoming empty load files.
1691          my $rowSize = $self->EstimateRowSize($relationName);          my $rowSize = $self->EstimateRowSize($relationName);
         my $fileSize = -s $fileName;  
1692          my $estimate = FIG::max($fileSize * 1.5 / $rowSize, 1000);          my $estimate = FIG::max($fileSize * 1.5 / $rowSize, 1000);
1693          # Re-create the table without its index.          # Re-create the table without its index.
1694          $self->CreateTable($relationName, 0, $estimate);          $self->CreateTable($relationName, 0, $estimate);
# Line 1361  Line 1712 
1712          $retVal->AddMessage("Table load failed for $relationName using $fileName.");          $retVal->AddMessage("Table load failed for $relationName using $fileName.");
1713          Trace("Table load failed for $relationName.") if T(1);          Trace("Table load failed for $relationName.") if T(1);
1714      } else {      } else {
1715          # Here we successfully loaded the table. Trace the number of records loaded.          # Here we successfully loaded the table.
1716          Trace("$retVal->{records} records read for $relationName.") if T(2);          $retVal->Add("tables");
1717            my $size = -s $fileName;
1718            Trace("$size bytes loaded into $relationName.") if T(2);
1719          # If we're rebuilding, we need to create the table indexes.          # If we're rebuilding, we need to create the table indexes.
1720          if ($truncateFlag && ! $dbh->{_preIndex}) {          if ($truncateFlag && ! $dbh->{_preIndex}) {
1721              eval {              eval {
# Line 1373  Line 1726 
1726              }              }
1727          }          }
1728      }      }
     # Commit the database changes.  
     $dbh->commit_tran;  
1729      # Analyze the table to improve performance.      # Analyze the table to improve performance.
1730      $dbh->vacuum_it($relationName);      $dbh->vacuum_it($relationName);
1731      # Return the statistics.      # Return the statistics.
# Line 1468  Line 1819 
1819      # Get the parameters.      # Get the parameters.
1820      my ($self, $entityType, $ID) = @_;      my ($self, $entityType, $ID) = @_;
1821      # Create a query.      # Create a query.
1822      my $query = $self->Get([$entityType], "$entityType(id) = ?", $ID);      my $query = $self->Get([$entityType], "$entityType(id) = ?", [$ID]);
1823      # Get the first (and only) object.      # Get the first (and only) object.
1824      my $retVal = $query->Fetch();      my $retVal = $query->Fetch();
1825      # Return the result.      # Return the result.
# Line 1581  Line 1932 
1932      # list is a scalar we convert it into a singleton list.      # list is a scalar we convert it into a singleton list.
1933      my @parmList = ();      my @parmList = ();
1934      if (ref $parameterList eq "ARRAY") {      if (ref $parameterList eq "ARRAY") {
1935            Trace("GetAll parm list is an array.") if T(4);
1936          @parmList = @{$parameterList};          @parmList = @{$parameterList};
1937      } else {      } else {
1938            Trace("GetAll parm list is a scalar: $parameterList.") if T(4);
1939          push @parmList, $parameterList;          push @parmList, $parameterList;
1940      }      }
     # Create the query.  
     my $query = $self->Get($objectNames, $filterClause, @parmList);  
     # Set up a counter of the number of records read.  
     my $fetched = 0;  
1941      # Insure the counter has a value.      # Insure the counter has a value.
1942      if (!defined $count) {      if (!defined $count) {
1943          $count = 0;          $count = 0;
1944      }      }
1945        # Add the row limit to the filter clause.
1946        if ($count > 0) {
1947            $filterClause .= " LIMIT $count";
1948        }
1949        # Create the query.
1950        my $query = $self->Get($objectNames, $filterClause, \@parmList);
1951        # Set up a counter of the number of records read.
1952        my $fetched = 0;
1953      # Loop through the records returned, extracting the fields. Note that if the      # Loop through the records returned, extracting the fields. Note that if the
1954      # counter is non-zero, we stop when the number of records read hits the count.      # counter is non-zero, we stop when the number of records read hits the count.
1955      my @retVal = ();      my @retVal = ();
# Line 1643  Line 2000 
2000      return $retVal;      return $retVal;
2001  }  }
2002    
2003    =head3 GetFieldTable
2004    
2005    C<< my $fieldHash = $self->GetFieldTable($objectnName); >>
2006    
2007    Get the field structure for a specified entity or relationship.
2008    
2009    =over 4
2010    
2011    =item objectName
2012    
2013    Name of the desired entity or relationship.
2014    
2015    =item RETURN
2016    
2017    The table containing the field descriptors for the specified object.
2018    
2019    =back
2020    
2021    =cut
2022    
2023    sub GetFieldTable {
2024        # Get the parameters.
2025        my ($self, $objectName) = @_;
2026        # Get the descriptor from the metadata.
2027        my $objectData = $self->_GetStructure($objectName);
2028        # Return the object's field table.
2029        return $objectData->{Fields};
2030    }
2031    
2032    =head3 GetUsefulCrossValues
2033    
2034    C<< my @attrNames = $sprout->GetUsefulCrossValues($sourceEntity, $relationship); >>
2035    
2036    Return a list of the useful attributes that would be returned by a B<Cross> call
2037    from an entity of the source entity type through the specified relationship. This
2038    means it will return the fields of the target entity type and the intersection data
2039    fields in the relationship. Only primary table fields are returned. In other words,
2040    the field names returned will be for fields where there is always one and only one
2041    value.
2042    
2043    =over 4
2044    
2045    =item sourceEntity
2046    
2047    Name of the entity from which the relationship crossing will start.
2048    
2049    =item relationship
2050    
2051    Name of the relationship being crossed.
2052    
2053    =item RETURN
2054    
2055    Returns a list of field names in Sprout field format (I<objectName>C<(>I<fieldName>C<)>.
2056    
2057    =back
2058    
2059    =cut
2060    #: Return Type @;
2061    sub GetUsefulCrossValues {
2062        # Get the parameters.
2063        my ($self, $sourceEntity, $relationship) = @_;
2064        # Declare the return variable.
2065        my @retVal = ();
2066        # Determine the target entity for the relationship. This is whichever entity is not
2067        # the source entity. So, if the source entity is the FROM, we'll get the name of
2068        # the TO, and vice versa.
2069        my $relStructure = $self->_GetStructure($relationship);
2070        my $targetEntityType = ($relStructure->{from} eq $sourceEntity ? "to" : "from");
2071        my $targetEntity = $relStructure->{$targetEntityType};
2072        # Get the field table for the entity.
2073        my $entityFields = $self->GetFieldTable($targetEntity);
2074        # The field table is a hash. The hash key is the field name. The hash value is a structure.
2075        # For the entity fields, the key aspect of the target structure is that the {relation} value
2076        # must match the entity name.
2077        my @fieldList = map { "$targetEntity($_)" } grep { $entityFields->{$_}->{relation} eq $targetEntity }
2078                            keys %{$entityFields};
2079        # Push the fields found onto the return variable.
2080        push @retVal, sort @fieldList;
2081        # Get the field table for the relationship.
2082        my $relationshipFields = $self->GetFieldTable($relationship);
2083        # Here we have a different rule. We want all the fields other than "from-link" and "to-link".
2084        # This may end up being an empty set.
2085        my @fieldList2 = map { "$relationship($_)" } grep { $_ ne "from-link" && $_ ne "to-link" }
2086                            keys %{$relationshipFields};
2087        # Push these onto the return list.
2088        push @retVal, sort @fieldList2;
2089        # Return the result.
2090        return @retVal;
2091    }
2092    
2093  =head2 Internal Utility Methods  =head2 Internal Utility Methods
2094    
2095    =head3 SetupSQL
2096    
2097    Process a list of object names and a filter clause so that they can be used to
2098    build an SQL statement. This method takes in a reference to a list of object names
2099    and a filter clause. It will return a corrected filter clause, a list of mapped
2100    names and the mapped name hash.
2101    
2102    This is an instance method.
2103    
2104    =over 4
2105    
2106    =item objectNames
2107    
2108    Reference to a list of the object names to be included in the query.
2109    
2110    =item filterClause
2111    
2112    A string containing the WHERE clause for the query (without the C<WHERE>) and also
2113    optionally the C<ORDER BY> and C<LIMIT> clauses.
2114    
2115    =item RETURN
2116    
2117    Returns a three-element list. The first element is the SQL statement suffix, beginning
2118    with the FROM clause. The second element is a reference to a list of the names to be
2119    used in retrieving the fields. The third element is a hash mapping the names to the
2120    objects they represent.
2121    
2122    =back
2123    
2124    =cut
2125    
2126    sub _SetupSQL {
2127        my ($self, $objectNames, $filterClause) = @_;
2128        # Adjust the list of object names to account for multiple occurrences of the
2129        # same object. We start with a hash table keyed on object name that will
2130        # return the object suffix. The first time an object is encountered it will
2131        # not be found in the hash. The next time the hash will map the object name
2132        # to 2, then 3, and so forth.
2133        my %objectHash = ();
2134        # This list will contain the object names as they are to appear in the
2135        # FROM list.
2136        my @fromList = ();
2137        # This list contains the suffixed object name for each object. It is exactly
2138        # parallel to the list in the $objectNames parameter.
2139        my @mappedNameList = ();
2140        # Finally, this hash translates from a mapped name to its original object name.
2141        my %mappedNameHash = ();
2142        # Now we create the lists. Note that for every single name we push something into
2143        # @fromList and @mappedNameList. This insures that those two arrays are exactly
2144        # parallel to $objectNames.
2145        for my $objectName (@{$objectNames}) {
2146            # Get the next suffix for this object.
2147            my $suffix = $objectHash{$objectName};
2148            if (! $suffix) {
2149                # Here we are seeing the object for the first time. The object name
2150                # is used as is.
2151                push @mappedNameList, $objectName;
2152                push @fromList, $objectName;
2153                $mappedNameHash{$objectName} = $objectName;
2154                # Denote the next suffix will be 2.
2155                $objectHash{$objectName} = 2;
2156            } else {
2157                # Here we've seen the object before. We construct a new name using
2158                # the suffix from the hash and update the hash.
2159                my $mappedName = "$objectName$suffix";
2160                $objectHash{$objectName} = $suffix + 1;
2161                # The FROM list has the object name followed by the mapped name. This
2162                # tells SQL it's still the same table, but we're using a different name
2163                # for it to avoid confusion.
2164                push @fromList, "$objectName $mappedName";
2165                # The mapped-name list contains the real mapped name.
2166                push @mappedNameList, $mappedName;
2167                # Finally, enable us to get back from the mapped name to the object name.
2168                $mappedNameHash{$mappedName} = $objectName;
2169            }
2170        }
2171        # Begin the SELECT suffix. It starts with
2172        #
2173        # FROM name1, name2, ... nameN
2174        #
2175        my $suffix = "FROM " . join(', ', @fromList);
2176        # Check for a filter clause.
2177        if ($filterClause) {
2178            # Here we have one, so we convert its field names and add it to the query. First,
2179            # We create a copy of the filter string we can work with.
2180            my $filterString = $filterClause;
2181            # Next, we sort the object names by length. This helps protect us from finding
2182            # object names inside other object names when we're doing our search and replace.
2183            my @sortedNames = sort { length($b) - length($a) } @mappedNameList;
2184            # We will also keep a list of conditions to add to the WHERE clause in order to link
2185            # entities and relationships as well as primary relations to secondary ones.
2186            my @joinWhere = ();
2187            # The final preparatory step is to create a hash table of relation names. The
2188            # table begins with the relation names already in the SELECT command. We may
2189            # need to add relations later if there is filtering on a field in a secondary
2190            # relation. The secondary relations are the ones that contain multiply-
2191            # occurring or optional fields.
2192            my %fromNames = map { $_ => 1 } @sortedNames;
2193            # We are ready to begin. We loop through the object names, replacing each
2194            # object name's field references by the corresponding SQL field reference.
2195            # Along the way, if we find a secondary relation, we will need to add it
2196            # to the FROM clause.
2197            for my $mappedName (@sortedNames) {
2198                # Get the length of the object name plus 2. This is the value we add to the
2199                # size of the field name to determine the size of the field reference as a
2200                # whole.
2201                my $nameLength = 2 + length $mappedName;
2202                # Get the real object name for this mapped name.
2203                my $objectName = $mappedNameHash{$mappedName};
2204                Trace("Processing $mappedName for object $objectName.") if T(4);
2205                # Get the object's field list.
2206                my $fieldList = $self->GetFieldTable($objectName);
2207                # Find the field references for this object.
2208                while ($filterString =~ m/$mappedName\(([^)]*)\)/g) {
2209                    # At this point, $1 contains the field name, and the current position
2210                    # is set immediately after the final parenthesis. We pull out the name of
2211                    # the field and the position and length of the field reference as a whole.
2212                    my $fieldName = $1;
2213                    my $len = $nameLength + length $fieldName;
2214                    my $pos = pos($filterString) - $len;
2215                    # Insure the field exists.
2216                    if (!exists $fieldList->{$fieldName}) {
2217                        Confess("Field $fieldName not found for object $objectName.");
2218                    } else {
2219                        Trace("Processing $fieldName at position $pos.") if T(4);
2220                        # Get the field's relation.
2221                        my $relationName = $fieldList->{$fieldName}->{relation};
2222                        # Now we have a secondary relation. We need to insure it matches the
2223                        # mapped name of the primary relation. First we peel off the suffix
2224                        # from the mapped name.
2225                        my $mappingSuffix = substr $mappedName, length($objectName);
2226                        # Put the mapping suffix onto the relation name to get the
2227                        # mapped relation name.
2228                        my $mappedRelationName = "$relationName$mappingSuffix";
2229                        # Insure the relation is in the FROM clause.
2230                        if (!exists $fromNames{$mappedRelationName}) {
2231                            # Add the relation to the FROM clause.
2232                            if ($mappedRelationName eq $relationName) {
2233                                # The name is un-mapped, so we add it without
2234                                # any frills.
2235                                $suffix .= ", $relationName";
2236                                push @joinWhere, "$objectName.id = $relationName.id";
2237                            } else {
2238                                # Here we have a mapping situation.
2239                                $suffix .= ", $relationName $mappedRelationName";
2240                                push @joinWhere, "$mappedRelationName.id = $mappedName.id";
2241                            }
2242                            # Denote we have this relation available for future fields.
2243                            $fromNames{$mappedRelationName} = 1;
2244                        }
2245                        # Form an SQL field reference from the relation name and the field name.
2246                        my $sqlReference = "$mappedRelationName." . _FixName($fieldName);
2247                        # Put it into the filter string in place of the old value.
2248                        substr($filterString, $pos, $len) = $sqlReference;
2249                        # Reposition the search.
2250                        pos $filterString = $pos + length $sqlReference;
2251                    }
2252                }
2253            }
2254            # The next step is to join the objects together. We only need to do this if there
2255            # is more than one object in the object list. We start with the first object and
2256            # run through the objects after it. Note also that we make a safety copy of the
2257            # list before running through it.
2258            my @mappedObjectList = @mappedNameList;
2259            my $lastMappedObject = shift @mappedObjectList;
2260            # Get the join table.
2261            my $joinTable = $self->{_metaData}->{Joins};
2262            # Loop through the object list.
2263            for my $thisMappedObject (@mappedObjectList) {
2264                # Look for a join using the real object names.
2265                my $lastObject = $mappedNameHash{$lastMappedObject};
2266                my $thisObject = $mappedNameHash{$thisMappedObject};
2267                my $joinKey = "$lastObject/$thisObject";
2268                if (!exists $joinTable->{$joinKey}) {
2269                    # Here there's no join, so we throw an error.
2270                    Confess("No join exists to connect from $lastMappedObject to $thisMappedObject.");
2271                } else {
2272                    # Get the join clause.
2273                    my $unMappedJoin = $joinTable->{$joinKey};
2274                    # Fix the names.
2275                    $unMappedJoin =~ s/$lastObject/$lastMappedObject/;
2276                    $unMappedJoin =~ s/$thisObject/$thisMappedObject/;
2277                    push @joinWhere, $unMappedJoin;
2278                    # Save this object as the last object for the next iteration.
2279                    $lastMappedObject = $thisMappedObject;
2280                }
2281            }
2282            # Now we need to handle the whole ORDER BY / LIMIT thing. The important part
2283            # here is we want the filter clause to be empty if there's no WHERE filter.
2284            # We'll put the ORDER BY / LIMIT clauses in the following variable.
2285            my $orderClause = "";
2286            # Locate the ORDER BY or LIMIT verbs (if any). We use a non-greedy
2287            # operator so that we find the first occurrence of either verb.
2288            if ($filterString =~ m/^(.*?)\s*(ORDER BY|LIMIT)/g) {
2289                # Here we have an ORDER BY or LIMIT verb. Split it off of the filter string.
2290                my $pos = pos $filterString;
2291                $orderClause = $2 . substr($filterString, $pos);
2292                $filterString = $1;
2293            }
2294            # Add the filter and the join clauses (if any) to the SELECT command.
2295            if ($filterString) {
2296                Trace("Filter string is \"$filterString\".") if T(4);
2297                push @joinWhere, "($filterString)";
2298            }
2299            if (@joinWhere) {
2300                $suffix .= " WHERE " . join(' AND ', @joinWhere);
2301            }
2302            # Add the sort or limit clause (if any) to the SELECT command.
2303            if ($orderClause) {
2304                $suffix .= " $orderClause";
2305            }
2306        }
2307        # Return the suffix, the mapped name list, and the mapped name hash.
2308        return ($suffix, \@mappedNameList, \%mappedNameHash);
2309    }
2310    
2311    =head3 GetStatementHandle
2312    
2313    This method will prepare and execute an SQL query, returning the statement handle.
2314    The main reason for doing this here is so that everybody who does SQL queries gets
2315    the benefit of tracing.
2316    
2317    This is an instance method.
2318    
2319    =over 4
2320    
2321    =item command
2322    
2323    Command to prepare and execute.
2324    
2325    =item params
2326    
2327    Reference to a list of the values to be substituted in for the parameter marks.
2328    
2329    =item RETURN
2330    
2331    Returns a prepared and executed statement handle from which the caller can extract
2332    results.
2333    
2334    =back
2335    
2336    =cut
2337    
2338    sub _GetStatementHandle {
2339        # Get the parameters.
2340        my ($self, $command, $params) = @_;
2341        # Trace the query.
2342        Trace("SQL query: $command") if T(SQL => 3);
2343        Trace("PARMS: '" . (join "', '", @{$params}) . "'") if (T(SQL => 4) && (@{$params} > 0));
2344        # Get the database handle.
2345        my $dbh = $self->{_dbh};
2346        # Prepare the command.
2347        my $sth = $dbh->prepare_command($command);
2348        # Execute it with the parameters bound in.
2349        $sth->execute(@{$params}) || Confess("SELECT error" . $sth->errstr());
2350        # Return the statement handle.
2351        return $sth;
2352    }
2353    
2354  =head3 GetLoadStats  =head3 GetLoadStats
2355    
2356  Return a blank statistics object for use by the load methods.  Return a blank statistics object for use by the load methods.
# Line 1654  Line 2360 
2360  =cut  =cut
2361    
2362  sub _GetLoadStats {  sub _GetLoadStats {
2363      return Stats->new('records');      return Stats->new();
2364  }  }
2365    
2366  =head3 GenerateFields  =head3 GenerateFields
# Line 1849  Line 2555 
2555      return $objectData->{Relations};      return $objectData->{Relations};
2556  }  }
2557    
 =head3 GetFieldTable  
   
 Get the field structure for a specified entity or relationship.  
   
 This is an instance method.  
   
 =over 4  
   
 =item objectName  
   
 Name of the desired entity or relationship.  
   
 =item RETURN  
   
 The table containing the field descriptors for the specified object.  
   
 =back  
   
 =cut  
   
 sub _GetFieldTable {  
     # Get the parameters.  
     my ($self, $objectName) = @_;  
     # Get the descriptor from the metadata.  
     my $objectData = $self->_GetStructure($objectName);  
     # Return the object's field table.  
     return $objectData->{Fields};  
 }  
   
2558  =head3 ValidateFieldNames  =head3 ValidateFieldNames
2559    
2560  Determine whether or not the field names are valid. A description of the problems with the names  Determine whether or not the field names are valid. A description of the problems with the names
# Line 2225  Line 2902 
2902          my @fromList = ();          my @fromList = ();
2903          my @toList = ();          my @toList = ();
2904          my @bothList = ();          my @bothList = ();
2905          Trace("Join table build for $entityName.") if T(4);          Trace("Join table build for $entityName.") if T(metadata => 4);
2906          for my $relationshipName (keys %{$relationshipList}) {          for my $relationshipName (keys %{$relationshipList}) {
2907              my $relationship = $relationshipList->{$relationshipName};              my $relationship = $relationshipList->{$relationshipName};
2908              # Determine if this relationship has our entity in one of its link fields.              # Determine if this relationship has our entity in one of its link fields.
2909              my $fromEntity = $relationship->{from};              my $fromEntity = $relationship->{from};
2910              my $toEntity = $relationship->{to};              my $toEntity = $relationship->{to};
2911              Trace("Join check for relationship $relationshipName from $fromEntity to $toEntity.") if T(4);              Trace("Join check for relationship $relationshipName from $fromEntity to $toEntity.") if T(Joins => 4);
2912              if ($fromEntity eq $entityName) {              if ($fromEntity eq $entityName) {
2913                  if ($toEntity eq $entityName) {                  if ($toEntity eq $entityName) {
2914                      # Here the relationship is recursive.                      # Here the relationship is recursive.
2915                      push @bothList, $relationshipName;                      push @bothList, $relationshipName;
2916                      Trace("Relationship $relationshipName put in both-list.") if T(4);                      Trace("Relationship $relationshipName put in both-list.") if T(metadata => 4);
2917                  } else {                  } else {
2918                      # Here the relationship comes from the entity.                      # Here the relationship comes from the entity.
2919                      push @fromList, $relationshipName;                      push @fromList, $relationshipName;
2920                      Trace("Relationship $relationshipName put in from-list.") if T(4);                      Trace("Relationship $relationshipName put in from-list.") if T(metadata => 4);
2921                  }                  }
2922              } elsif ($toEntity eq $entityName) {              } elsif ($toEntity eq $entityName) {
2923                  # Here the relationship goes to the entity.                  # Here the relationship goes to the entity.
2924                  push @toList, $relationshipName;                  push @toList, $relationshipName;
2925                  Trace("Relationship $relationshipName put in to-list.") if T(4);                  Trace("Relationship $relationshipName put in to-list.") if T(metadata => 4);
2926              }              }
2927          }          }
2928          # Create the nonrecursive joins. Note that we build two hashes for running          # Create the nonrecursive joins. Note that we build two hashes for running
# Line 2261  Line 2938 
2938                  # Create joins between the entity and this relationship.                  # Create joins between the entity and this relationship.
2939                  my $linkField = "$relationshipName.${linkType}_link";                  my $linkField = "$relationshipName.${linkType}_link";
2940                  my $joinClause = "$entityName.id = $linkField";                  my $joinClause = "$entityName.id = $linkField";
2941                  Trace("Entity join clause is $joinClause for $entityName and $relationshipName.") if T(4);                  Trace("Entity join clause is $joinClause for $entityName and $relationshipName.") if T(metadata => 4);
2942                  $joinTable{"$entityName/$relationshipName"} = $joinClause;                  $joinTable{"$entityName/$relationshipName"} = $joinClause;
2943                  $joinTable{"$relationshipName/$entityName"} = $joinClause;                  $joinTable{"$relationshipName/$entityName"} = $joinClause;
2944                  # Create joins between this relationship and the other relationships.                  # Create joins between this relationship and the other relationships.
# Line 2282  Line 2959 
2959                              # relationship and itself are prohibited.                              # relationship and itself are prohibited.
2960                              my $relJoinClause = "$otherName.${otherType}_link = $linkField";                              my $relJoinClause = "$otherName.${otherType}_link = $linkField";
2961                              $joinTable{$joinKey} = $relJoinClause;                              $joinTable{$joinKey} = $relJoinClause;
2962                              Trace("Relationship join clause is $relJoinClause for $joinKey.") if T(4);                              Trace("Relationship join clause is $relJoinClause for $joinKey.") if T(metadata => 4);
2963                          }                          }
2964                      }                      }
2965                  }                  }
# Line 2291  Line 2968 
2968                  # relationship can only be ambiguous with another recursive relationship,                  # relationship can only be ambiguous with another recursive relationship,
2969                  # and the incoming relationship from the outer loop is never recursive.                  # and the incoming relationship from the outer loop is never recursive.
2970                  for my $otherName (@bothList) {                  for my $otherName (@bothList) {
2971                      Trace("Setting up relationship joins to recursive relationship $otherName with $relationshipName.") if T(4);                      Trace("Setting up relationship joins to recursive relationship $otherName with $relationshipName.") if T(metadata => 4);
2972                      # Join from the left.                      # Join from the left.
2973                      $joinTable{"$relationshipName/$otherName"} =                      $joinTable{"$relationshipName/$otherName"} =
2974                          "$linkField = $otherName.from_link";                          "$linkField = $otherName.from_link";
# Line 2306  Line 2983 
2983          # rise to situations where we can't create the path we want; however, it is always          # rise to situations where we can't create the path we want; however, it is always
2984          # possible to get the same effect using multiple queries.          # possible to get the same effect using multiple queries.
2985          for my $relationshipName (@bothList) {          for my $relationshipName (@bothList) {
2986              Trace("Setting up entity joins to recursive relationship $relationshipName with $entityName.") if T(4);              Trace("Setting up entity joins to recursive relationship $relationshipName with $entityName.") if T(metadata => 4);
2987              # Join to the entity from each direction.              # Join to the entity from each direction.
2988              $joinTable{"$entityName/$relationshipName"} =              $joinTable{"$entityName/$relationshipName"} =
2989                  "$entityName.id = $relationshipName.from_link";                  "$entityName.id = $relationshipName.from_link";
# Line 2320  Line 2997 
2997      return $metadata;      return $metadata;
2998  }  }
2999    
3000    =head3 SortNeeded
3001    
3002    C<< my $flag = $erdb->SortNeeded($relationName); >>
3003    
3004    Return TRUE if the specified relation should be sorted during loading to remove duplicate keys,
3005    else FALSE.
3006    
3007    =over 4
3008    
3009    =item relationName
3010    
3011    Name of the relation to be examined.
3012    
3013    =item RETURN
3014    
3015    Returns TRUE if the relation needs a sort, else FALSE.
3016    
3017    =back
3018    
3019    =cut
3020    #: Return Type $;
3021    sub SortNeeded {
3022        # Get the parameters.
3023        my ($self, $relationName) = @_;
3024        # Declare the return variable.
3025        my $retVal = 0;
3026        # Find out if the relation is a primary entity relation.
3027        my $entityTable = $self->{_metaData}->{Entities};
3028        if (exists $entityTable->{$relationName}) {
3029            my $keyType = $entityTable->{$relationName}->{keyType};
3030            Trace("Relation $relationName found in entity table with key type $keyType.") if T(3);
3031            # If the key is not a hash string, we must do the sort.
3032            if ($keyType ne 'hash-string') {
3033                $retVal = 1;
3034            }
3035        }
3036        # Return the result.
3037        return $retVal;
3038    }
3039    
3040  =head3 CreateRelationshipIndex  =head3 CreateRelationshipIndex
3041    
3042  Create an index for a relationship's relation.  Create an index for a relationship's relation.

Legend:
Removed from v.1.20  
changed lines
  Added in v.1.45

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3