[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.61, Mon Jul 10 09:05:17 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 90  Line 91 
91    
92  32-bit signed integer  32-bit signed integer
93    
94    =item counter
95    
96    32-bit unsigned integer
97    
98  =item date  =item date
99    
100  64-bit unsigned integer, representing a PERL date/time value  64-bit unsigned integer, representing a PERL date/time value
# Line 109  Line 114 
114  compatability with certain database packages), but the only values supported are  compatability with certain database packages), but the only values supported are
115  0 and 1.  0 and 1.
116    
117    =item id-string
118    
119    variable-length string, maximum 25 characters
120    
121  =item key-string  =item key-string
122    
123  variable-length string, maximum 40 characters  variable-length string, maximum 40 characters
# Line 125  Line 134 
134    
135  variable-length string, maximum 255 characters  variable-length string, maximum 255 characters
136    
137    =item hash-string
138    
139    variable-length string, maximum 22 characters
140    
141  =back  =back
142    
143    The hash-string data type has a special meaning. The actual key passed into the loader will
144    be a string, but it will be digested into a 22-character MD5 code to save space. Although the
145    MD5 algorithm is not perfect, it is extremely unlikely two strings will have the same
146    digest. Therefore, it is presumed the keys will be unique. When the database is actually
147    in use, the hashed keys will be presented rather than the original values. For this reason,
148    they should not be used for entities where the key is meaningful.
149    
150  =head3 Global Tags  =head3 Global Tags
151    
152  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 302  Line 322 
322  # "maxLen" is the maximum permissible length of the incoming string data used to populate a field  # "maxLen" is the maximum permissible length of the incoming string data used to populate a field
323  # of the specified type. "dataGen" is PERL string that will be evaluated if no test data generation  # of the specified type. "dataGen" is PERL string that will be evaluated if no test data generation
324  # string is specified in the field definition. "avgLen" is the average byte length for estimating  # string is specified in the field definition. "avgLen" is the average byte length for estimating
325  # record sizes.  # record sizes. "sort" is the key modifier for the sort command.
326  my %TypeTable = ( char =>    { sqlType => 'CHAR(1)',            maxLen => 1,            avgLen =>   1, dataGen => "StringGen('A')" },  my %TypeTable = ( char =>    { sqlType => 'CHAR(1)',            maxLen => 1,            avgLen =>   1, sort => "",  dataGen => "StringGen('A')" },
327                    int =>     { sqlType => 'INTEGER',            maxLen => 20,           avgLen =>   4, dataGen => "IntGen(0, 99999999)" },                    int =>     { sqlType => 'INTEGER',            maxLen => 20,           avgLen =>   4, sort => "n", dataGen => "IntGen(0, 99999999)" },
328                    string =>  { sqlType => 'VARCHAR(255)',       maxLen => 255,          avgLen => 100, dataGen => "StringGen(IntGen(10,250))" },                    counter => { sqlType => 'INTEGER UNSIGNED',   maxLen => 20,           avgLen =>   4, sort => "n", dataGen => "IntGen(0, 99999999)" },
329                    text =>    { sqlType => 'TEXT',               maxLen => 1000000000,   avgLen => 500, dataGen => "StringGen(IntGen(80,1000))" },                    string =>  { sqlType => 'VARCHAR(255)',       maxLen => 255,          avgLen => 100, sort => "",  dataGen => "StringGen(IntGen(10,250))" },
330                    date =>    { sqlType => 'BIGINT',             maxLen => 80,           avgLen =>   8, dataGen => "DateGen(-7, 7, IntGen(0,1400))" },                    text =>    { sqlType => 'TEXT',               maxLen => 1000000000,   avgLen => 500, sort => "",  dataGen => "StringGen(IntGen(80,1000))" },
331                    float =>   { sqlType => 'DOUBLE PRECISION',   maxLen => 40,           avgLen =>   8, dataGen => "FloatGen(0.0, 100.0)" },                    date =>    { sqlType => 'BIGINT',             maxLen => 80,           avgLen =>   8, sort => "n", dataGen => "DateGen(-7, 7, IntGen(0,1400))" },
332                    boolean => { sqlType => 'SMALLINT',           maxLen => 1,            avgLen =>   2, dataGen => "IntGen(0, 1)" },                    float =>   { sqlType => 'DOUBLE PRECISION',   maxLen => 40,           avgLen =>   8, sort => "g", dataGen => "FloatGen(0.0, 100.0)" },
333                      boolean => { sqlType => 'SMALLINT',           maxLen => 1,            avgLen =>   1, sort => "n", dataGen => "IntGen(0, 1)" },
334                     'hash-string' =>
335                                 { sqlType => 'VARCHAR(22)',        maxLen => 22,           avgLen =>  22, sort => "",  dataGen => "SringGen(22)" },
336                     'id-string' =>
337                                 { sqlType => 'VARCHAR(25)',        maxLen => 25,           avgLen =>  25, sort => "",  dataGen => "SringGen(22)" },
338                   'key-string' =>                   'key-string' =>
339                               { sqlType => 'VARCHAR(40)',        maxLen => 40,           avgLen =>  10, dataGen => "StringGen(IntGen(10,40))" },                               { sqlType => 'VARCHAR(40)',        maxLen => 40,           avgLen =>  10, sort => "",  dataGen => "StringGen(IntGen(10,40))" },
340                   'name-string' =>                   'name-string' =>
341                               { sqlType => 'VARCHAR(80)',        maxLen => 80,           avgLen =>  40, dataGen => "StringGen(IntGen(10,80))" },                               { sqlType => 'VARCHAR(80)',        maxLen => 80,           avgLen =>  40, sort => "",  dataGen => "StringGen(IntGen(10,80))" },
342                   'medium-string' =>                   'medium-string' =>
343                               { sqlType => 'VARCHAR(160)',       maxLen => 160,          avgLen =>  40, dataGen => "StringGen(IntGen(10,160))" },                               { sqlType => 'VARCHAR(160)',       maxLen => 160,          avgLen =>  40, sort => "",  dataGen => "StringGen(IntGen(10,160))" },
344                  );                  );
345    
346  # Table translating arities into natural language.  # Table translating arities into natural language.
# Line 402  Line 427 
427      # Write the HTML heading stuff.      # Write the HTML heading stuff.
428      print HTMLOUT "<html>\n<head>\n<title>$title</title>\n";      print HTMLOUT "<html>\n<head>\n<title>$title</title>\n";
429      print HTMLOUT "</head>\n<body>\n";      print HTMLOUT "</head>\n<body>\n";
430        # Write the documentation.
431        print HTMLOUT $self->DisplayMetaData();
432        # Close the document.
433        print HTMLOUT "</body>\n</html>\n";
434        # Close the file.
435        close HTMLOUT;
436    }
437    
438    =head3 DisplayMetaData
439    
440    C<< my $html = $erdb->DisplayMetaData(); >>
441    
442    Return an HTML description of the database. This description can be used to help users create
443    the data to be loaded into the relations and form queries. The output is raw includable HTML
444    without any HEAD or BODY tags.
445    
446    =over 4
447    
448    =item filename
449    
450    The name of the output file.
451    
452    =back
453    
454    =cut
455    
456    sub DisplayMetaData {
457        # Get the parameters.
458        my ($self) = @_;
459        # Get the metadata and the title string.
460        my $metadata = $self->{_metaData};
461        # Get the title string.
462        my $title = $metadata->{Title};
463        # Get the entity and relationship lists.
464        my $entityList = $metadata->{Entities};
465        my $relationshipList = $metadata->{Relationships};
466        # Declare the return variable.
467        my $retVal = "";
468        # Open the output file.
469        Trace("Building MetaData table of contents.") if T(4);
470      # 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
471      # section contains an ordered list of entity or relationship subsections.      # section contains an ordered list of entity or relationship subsections.
472      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";
473      # Loop through the Entities, displaying a list item for each.      # Loop through the Entities, displaying a list item for each.
474      foreach my $key (sort keys %{$entityList}) {      foreach my $key (sort keys %{$entityList}) {
475          # Display this item.          # Display this item.
476          print HTMLOUT "<li><a href=\"#$key\">$key</a></li>\n";          $retVal .= "<li><a href=\"#$key\">$key</a></li>\n";
477      }      }
478      # Close off the entity section and start the relationship section.      # Close off the entity section and start the relationship section.
479      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";
480      # Loop through the Relationships.      # Loop through the Relationships.
481      foreach my $key (sort keys %{$relationshipList}) {      foreach my $key (sort keys %{$relationshipList}) {
482          # Display this item.          # Display this item.
483          my $relationshipTitle = _ComputeRelationshipSentence($key, $relationshipList->{$key});          my $relationshipTitle = _ComputeRelationshipSentence($key, $relationshipList->{$key});
484          print HTMLOUT "<li><a href=\"#$key\">$relationshipTitle</a></li>\n";          $retVal .= "<li><a href=\"#$key\">$relationshipTitle</a></li>\n";
485      }      }
486      # Close off the relationship section and list the join table section.      # Close off the relationship section and list the join table section.
487      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";
488      # Close off the table of contents itself.      # Close off the table of contents itself.
489      print HTMLOUT "</ul>\n";      $retVal .=  "</ul>\n";
490      # 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.
491      print HTMLOUT "<a name=\"EntitiesSection\"></a><h2>Entities</h2>\n";      $retVal .= "<a name=\"EntitiesSection\"></a><h2>Entities</h2>\n";
492      # Loop through the entities.      # Loop through the entities.
493      for my $key (sort keys %{$entityList}) {      for my $key (sort keys %{$entityList}) {
494          Trace("Building MetaData entry for $key entity.") if T(4);          Trace("Building MetaData entry for $key entity.") if T(4);
495          # Create the entity header. It contains a bookmark and the entity name.          # Create the entity header. It contains a bookmark and the entity name.
496          print HTMLOUT "<a name=\"$key\"></a><h3>$key</h3>\n";          $retVal .= "<a name=\"$key\"></a><h3>$key</h3>\n";
497          # Get the entity data.          # Get the entity data.
498          my $entityData = $entityList->{$key};          my $entityData = $entityList->{$key};
499          # If there's descriptive text, display it.          # If there's descriptive text, display it.
500          if (my $notes = $entityData->{Notes}) {          if (my $notes = $entityData->{Notes}) {
501              print HTMLOUT "<p>" . _HTMLNote($notes->{content}) . "</p>\n";              $retVal .= "<p>" . _HTMLNote($notes->{content}) . "</p>\n";
502          }          }
503          # 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.
504          print HTMLOUT "<h4>Relationships for <b>$key</b></h4>\n<ul>\n";          $retVal .= "<h4>Relationships for <b>$key</b></h4>\n<ul>\n";
505          # Loop through the relationships.          # Loop through the relationships.
506          for my $relationship (sort keys %{$relationshipList}) {          for my $relationship (sort keys %{$relationshipList}) {
507              # Get the relationship data.              # Get the relationship data.
# Line 446  Line 511 
511                  # Get the relationship sentence and append the arity.                  # Get the relationship sentence and append the arity.
512                  my $relationshipDescription = _ComputeRelationshipSentence($relationship, $relationshipStructure);                  my $relationshipDescription = _ComputeRelationshipSentence($relationship, $relationshipStructure);
513                  # Display the relationship data.                  # Display the relationship data.
514                  print HTMLOUT "<li><a href=\"#$relationship\">$relationshipDescription</a></li>\n";                  $retVal .= "<li><a href=\"#$relationship\">$relationshipDescription</a></li>\n";
515              }              }
516          }          }
517          # Close off the relationship list.          # Close off the relationship list.
518          print HTMLOUT "</ul>\n";          $retVal .= "</ul>\n";
519          # Get the entity's relations.          # Get the entity's relations.
520          my $relationList = $entityData->{Relations};          my $relationList = $entityData->{Relations};
521          # Create a header for the relation subsection.          # Create a header for the relation subsection.
522          print HTMLOUT "<h4>Relations for <b>$key</b></h4>\n";          $retVal .= "<h4>Relations for <b>$key</b></h4>\n";
523          # Loop through the relations, displaying them.          # Loop through the relations, displaying them.
524          for my $relation (sort keys %{$relationList}) {          for my $relation (sort keys %{$relationList}) {
525              my $htmlString = _ShowRelationTable($relation, $relationList->{$relation});              my $htmlString = _ShowRelationTable($relation, $relationList->{$relation});
526              print HTMLOUT $htmlString;              $retVal .= $htmlString;
527          }          }
528      }      }
529      # Denote we're starting the relationship section.      # Denote we're starting the relationship section.
530      print HTMLOUT "<a name=\"RelationshipsSection\"></a><h2>Relationships</h2>\n";      $retVal .= "<a name=\"RelationshipsSection\"></a><h2>Relationships</h2>\n";
531      # Loop through the relationships.      # Loop through the relationships.
532      for my $key (sort keys %{$relationshipList}) {      for my $key (sort keys %{$relationshipList}) {
533          Trace("Building MetaData entry for $key relationship.") if T(4);          Trace("Building MetaData entry for $key relationship.") if T(4);
# Line 470  Line 535 
535          my $relationshipStructure = $relationshipList->{$key};          my $relationshipStructure = $relationshipList->{$key};
536          # Create the relationship header.          # Create the relationship header.
537          my $headerText = _ComputeRelationshipHeading($key, $relationshipStructure);          my $headerText = _ComputeRelationshipHeading($key, $relationshipStructure);
538          print HTMLOUT "<h3><a name=\"$key\"></a>$headerText</h3>\n";          $retVal .= "<h3><a name=\"$key\"></a>$headerText</h3>\n";
539          # Get the entity names.          # Get the entity names.
540          my $fromEntity = $relationshipStructure->{from};          my $fromEntity = $relationshipStructure->{from};
541          my $toEntity = $relationshipStructure->{to};          my $toEntity = $relationshipStructure->{to};
# Line 480  Line 545 
545          # since both sentences will say the same thing.          # since both sentences will say the same thing.
546          my $arity = $relationshipStructure->{arity};          my $arity = $relationshipStructure->{arity};
547          if ($arity eq "11") {          if ($arity eq "11") {
548              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";
549          } else {          } else {
550              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";
551              if ($arity eq "MM" && $fromEntity ne $toEntity) {              if ($arity eq "MM" && $fromEntity ne $toEntity) {
552                  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";
553              }              }
554          }          }
555          print HTMLOUT "</p>\n";          $retVal .= "</p>\n";
556          # If there are notes on this relationship, display them.          # If there are notes on this relationship, display them.
557          if (my $notes = $relationshipStructure->{Notes}) {          if (my $notes = $relationshipStructure->{Notes}) {
558              print HTMLOUT "<p>" . _HTMLNote($notes->{content}) . "</p>\n";              $retVal .= "<p>" . _HTMLNote($notes->{content}) . "</p>\n";
559          }          }
560          # Generate the relationship's relation table.          # Generate the relationship's relation table.
561          my $htmlString = _ShowRelationTable($key, $relationshipStructure->{Relations}->{$key});          my $htmlString = _ShowRelationTable($key, $relationshipStructure->{Relations}->{$key});
562          print HTMLOUT $htmlString;          $retVal .= $htmlString;
563      }      }
564      Trace("Building MetaData join table.") if T(4);      Trace("Building MetaData join table.") if T(4);
565      # Denote we're starting the join table.      # Denote we're starting the join table.
566      print HTMLOUT "<a name=\"JoinTable\"></a><h3>Join Table</h3>\n";      $retVal .= "<a name=\"JoinTable\"></a><h3>Join Table</h3>\n";
567      # Create a table header.      # Create a table header.
568      print HTMLOUT _OpenTable("Join Table", "Source", "Target", "Join Condition");      $retVal .= _OpenTable("Join Table", "Source", "Target", "Join Condition");
569      # Loop through the joins.      # Loop through the joins.
570      my $joinTable = $metadata->{Joins};      my $joinTable = $metadata->{Joins};
571      my @joinKeys = keys %{$joinTable};      my @joinKeys = keys %{$joinTable};
# Line 508  Line 573 
573          # Separate out the source, the target, and the join clause.          # Separate out the source, the target, and the join clause.
574          $joinKey =~ m!^([^/]+)/(.+)$!;          $joinKey =~ m!^([^/]+)/(.+)$!;
575          my ($sourceRelation, $targetRelation) = ($1, $2);          my ($sourceRelation, $targetRelation) = ($1, $2);
576          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);
577          my $source = $self->ComputeObjectSentence($sourceRelation);          my $source = $self->ComputeObjectSentence($sourceRelation);
578          my $target = $self->ComputeObjectSentence($targetRelation);          my $target = $self->ComputeObjectSentence($targetRelation);
579          my $clause = $joinTable->{$joinKey};          my $clause = $joinTable->{$joinKey};
580          # Display them in a table row.          # Display them in a table row.
581          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";
582      }      }
583      # Close the table.      # Close the table.
584      print HTMLOUT _CloseTable();      $retVal .= _CloseTable();
585      # Close the document.      Trace("Built MetaData HTML.") if T(3);
586      print HTMLOUT "</body>\n</html>\n";      # Return the HTML.
587      # Close the file.      return $retVal;
     close HTMLOUT;  
     Trace("Built MetaData web page.") if T(3);  
588  }  }
589    
590  =head3 DumpMetaData  =head3 DumpMetaData
# Line 553  Line 616 
616  sub CreateTables {  sub CreateTables {
617      # Get the parameters.      # Get the parameters.
618      my ($self) = @_;      my ($self) = @_;
619      my $metadata = $self->{_metaData};      # Get the relation names.
620      my $dbh = $self->{_dbh};      my @relNames = $self->GetTableNames();
621      # Loop through the entities.      # Loop through the relations.
622      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}}) {  
623              # Create a table for this relation.              # Create a table for this relation.
624              $self->CreateTable($relationName);              $self->CreateTable($relationName);
625              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);  
626      }      }
627  }  }
628    
# Line 646  Line 695 
695      }      }
696  }  }
697    
698    =head3 VerifyFields
699    
700    C<< my $count = $erdb->VerifyFields($relName, \@fieldList); >>
701    
702    Run through the list of proposed field values, insuring that all the character fields are
703    below the maximum length. If any fields are too long, they will be truncated in place.
704    
705    =over 4
706    
707    =item relName
708    
709    Name of the relation for which the specified fields are destined.
710    
711    =item fieldList
712    
713    Reference to a list, in order, of the fields to be put into the relation.
714    
715    =item RETURN
716    
717    Returns the number of fields truncated.
718    
719    =back
720    
721    =cut
722    
723    sub VerifyFields {
724        # Get the parameters.
725        my ($self, $relName, $fieldList) = @_;
726        # Initialize the return value.
727        my $retVal = 0;
728        # Get the relation definition.
729        my $relData = $self->_FindRelation($relName);
730        # Get the list of field descriptors.
731        my $fieldTypes = $relData->{Fields};
732        my $fieldCount = scalar @{$fieldTypes};
733        # Loop through the two lists.
734        for (my $i = 0; $i < $fieldCount; $i++) {
735            # Get the type of the current field.
736            my $fieldType = $fieldTypes->[$i]->{type};
737            # If it's a character field, verify the length.
738            if ($fieldType =~ /string/) {
739                my $maxLen = $TypeTable{$fieldType}->{maxLen};
740                my $oldString = $fieldList->[$i];
741                if (length($oldString) > $maxLen) {
742                    # Here it's too big, so we truncate it.
743                    Trace("Truncating field $i in relation $relName to $maxLen characters from \"$oldString\".") if T(1);
744                    $fieldList->[$i] = substr $oldString, 0, $maxLen;
745                    $retVal++;
746                }
747            }
748        }
749        # Return the truncation count.
750        return $retVal;
751    }
752    
753    =head3 DigestFields
754    
755    C<< $erdb->DigestFields($relName, $fieldList); >>
756    
757    Digest the strings in the field list that correspond to data type C<hash-string> in the
758    specified relation.
759    
760    =over 4
761    
762    =item relName
763    
764    Name of the relation to which the fields belong.
765    
766    =item fieldList
767    
768    List of field contents to be loaded into the relation.
769    
770    =back
771    
772    =cut
773    #: Return Type ;
774    sub DigestFields {
775        # Get the parameters.
776        my ($self, $relName, $fieldList) = @_;
777        # Get the relation definition.
778        my $relData = $self->_FindRelation($relName);
779        # Get the list of field descriptors.
780        my $fieldTypes = $relData->{Fields};
781        my $fieldCount = scalar @{$fieldTypes};
782        # Loop through the two lists.
783        for (my $i = 0; $i < $fieldCount; $i++) {
784            # Get the type of the current field.
785            my $fieldType = $fieldTypes->[$i]->{type};
786            # If it's a hash string, digest it in place.
787            if ($fieldType eq 'hash-string') {
788                $fieldList->[$i] = $self->DigestKey($fieldList->[$i]);
789            }
790        }
791    }
792    
793    =head3 DigestKey
794    
795    C<< my $digested = $erdb->DigestKey($keyValue); >>
796    
797    Return the digested value of a symbolic key. The digested value can then be plugged into a
798    key-based search into a table with key-type hash-string.
799    
800    Currently the digesting process is independent of the database structure, but that may not
801    always be the case, so this is an instance method instead of a static method.
802    
803    =over 4
804    
805    =item keyValue
806    
807    Key value to digest.
808    
809    =item RETURN
810    
811    Digested value of the key.
812    
813    =back
814    
815    =cut
816    
817    sub DigestKey {
818        # Get the parameters.
819        my ($self, $keyValue) = @_;
820        # Compute the digest.
821        my $retVal = md5_base64($keyValue);
822        # Return the result.
823        return $retVal;
824    }
825    
826  =head3 CreateIndex  =head3 CreateIndex
827    
828  C<< $erdb->CreateIndex($relationName); >>  C<< $erdb->CreateIndex($relationName); >>
# Line 674  Line 851 
851          # Get the index's uniqueness flag.          # Get the index's uniqueness flag.
852          my $unique = (exists $indexData->{Unique} ? $indexData->{Unique} : 'false');          my $unique = (exists $indexData->{Unique} ? $indexData->{Unique} : 'false');
853          # Create the index.          # Create the index.
854          $dbh->create_index(idx => $indexName, tbl => $relationName, flds => $flds, unique => $unique);          my $rv = $dbh->create_index(idx => $indexName, tbl => $relationName,
855                                        flds => $flds, unique => $unique);
856            if ($rv) {
857          Trace("Index created: $indexName for $relationName ($flds)") if T(1);          Trace("Index created: $indexName for $relationName ($flds)") if T(1);
858            } else {
859                Confess("Error creating index $indexName for $relationName using ($flds): " . $dbh->error_message());
860            }
861      }      }
862  }  }
863    
# Line 724  Line 906 
906      $directoryName =~ s!/\\$!!;      $directoryName =~ s!/\\$!!;
907      # Declare the return variable.      # Declare the return variable.
908      my $retVal = Stats->new();      my $retVal = Stats->new();
909      # Get the metadata structure.      # Get the relation names.
910      my $metaData = $self->{_metaData};      my @relNames = $self->GetTableNames();
911      # 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}}) {  
912              # Try to load this relation.              # Try to load this relation.
913              my $result = $self->_LoadRelation($directoryName, $relationName, $rebuild);              my $result = $self->_LoadRelation($directoryName, $relationName, $rebuild);
914              # Accumulate the statistics.              # Accumulate the statistics.
915              $retVal->Accumulate($result);              $retVal->Accumulate($result);
916          }          }
     }  
     # 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);  
     }  
917      # Add the duration of the load to the statistical object.      # Add the duration of the load to the statistical object.
918      $retVal->Add('duration', gettimeofday - $startTime);      $retVal->Add('duration', gettimeofday - $startTime);
919      # Return the accumulated statistics.      # Return the accumulated statistics.
920      return $retVal;      return $retVal;
921  }  }
922    
923    
924  =head3 GetTableNames  =head3 GetTableNames
925    
926  C<< my @names = $erdb->GetTableNames; >>  C<< my @names = $erdb->GetTableNames; >>
# Line 812  Line 984 
984    
985  =head3 Get  =head3 Get
986    
987  C<< my $query = $erdb->Get(\@objectNames, $filterClause, $param1, $param2, ..., $paramN); >>  C<< my $query = $erdb->Get(\@objectNames, $filterClause, \@params); >>
988    
989  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.
990  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 992 
992  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
993  $genus.  $genus.
994    
995  C<< $query = $erdb->Get(['Genome'], "Genome(genus) = ?", $genus); >>  C<< $query = $erdb->Get(['Genome'], "Genome(genus) = ?", [$genus]); >>
996    
997  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
998  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 1009 
1009  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
1010  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,
1011    
1012  C<< $query = $erdb->Get(['Genome', 'ComesFrom', 'Source'], "Genome(genus) = ?", $genus); >>  C<< $query = $erdb->Get(['Genome', 'ComesFrom', 'Source'], "Genome(genus) = ?", [$genus]); >>
1013    
1014  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
1015  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.
1016  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
1017  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
1018  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  
1019  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,
1020  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.
1021    
1022    If an entity or relationship is mentioned twice, the name for the second occurrence will
1023    be suffixed with C<2>, the third occurrence will be suffixed with C<3>, and so forth. So,
1024    for example, if we have C<['Feature', 'HasContig', 'Contig', 'HasContig']>, then the
1025    B<to-link> field of the first B<HasContig> is specified as C<HasContig(to-link)>, while
1026    the B<to-link> field of the second B<HasContig> is specified as C<HasContig2(to-link)>.
1027    
1028  =over 4  =over 4
1029    
1030  =item objectNames  =item objectNames
# Line 870  Line 1047 
1047    
1048  C<< "Genome(genus) = ? ORDER BY Genome(species)" >>  C<< "Genome(genus) = ? ORDER BY Genome(species)" >>
1049    
1050    Note that the case is important. Only an uppercase "ORDER BY" with a single space will
1051    be processed. The idea is to make it less likely to find the verb by accident.
1052    
1053  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
1054  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
1055  relation.  relation.
1056    
1057  =item param1, param2, ..., paramN  Finally, you can limit the number of rows returned by adding a LIMIT clause. The LIMIT must
1058    be the last thing in the filter clause, and it contains only the word "LIMIT" followed by
1059    a positive number. So, for example
1060    
1061    C<< "Genome(genus) = ? ORDER BY Genome(species) LIMIT 10" >>
1062    
1063  Parameter values to be substituted into the filter clause.  will only return the first ten genomes for the specified genus. The ORDER BY clause is not
1064    required. For example, to just get the first 10 genomes in the B<Genome> table, you could
1065    use
1066    
1067    C<< "LIMIT 10" >>
1068    
1069    =item params
1070    
1071    Reference to a list of parameter values to be substituted into the filter clause.
1072    
1073  =item RETURN  =item RETURN
1074    
# Line 888  Line 1080 
1080    
1081  sub Get {  sub Get {
1082      # Get the parameters.      # Get the parameters.
1083      my ($self, $objectNames, $filterClause, @params) = @_;      my ($self, $objectNames, $filterClause, $params) = @_;
1084      # Construct the SELECT statement. The general pattern is      # Process the SQL stuff.
1085      #      my ($suffix, $mappedNameListRef, $mappedNameHashRef) =
1086      # SELECT name1.*, name2.*, ... nameN.* FROM name1, name2, ... nameN          $self->_SetupSQL($objectNames, $filterClause);
1087      #      # Create the query.
1088      my $dbh = $self->{_dbh};      my $command = "SELECT DISTINCT " . join(".*, ", @{$mappedNameListRef}) .
1089      my $command = "SELECT DISTINCT " . join('.*, ', @{$objectNames}) . ".* FROM " .          ".* $suffix";
1090                  join(', ', @{$objectNames});      my $sth = $self->_GetStatementHandle($command, $params);
1091      # Check for a filter clause.      # Now we create the relation map, which enables DBQuery to determine the order, name
1092      if ($filterClause) {      # and mapped name for each object in the query.
1093          # Here we have one, so we convert its field names and add it to the query. First,      my @relationMap = ();
1094          # We create a copy of the filter string we can work with.      for my $mappedName (@{$mappedNameListRef}) {
1095          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;  
         }  
         # We are ready to begin. We loop through the object names, replacing each  
         # object name's field references by the corresponding SQL field reference.  
         # Along the way, if we find a secondary relation, we will need to add it  
         # 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;  
                     }  
                     # Form an SQL field reference from the relation name and the field name.  
                     my $sqlReference = "$relationName." . _FixName($fieldName);  
                     # Put it into the filter string in place of the old value.  
                     substr($filterString, $pos, $len) = $sqlReference;  
                     # Reposition the search.  
                     pos $filterString = $pos + length $sqlReference;  
                 }  
             }  
         }  
         # The next step is to join the objects together. We only need to do this if there  
         # is more than one object in the object list. We start with the first object and  
         # run through the objects after it. Note also that we make a safety copy of the  
         # list before running through it.  
         my @objectList = @{$objectNames};  
         my $lastObject = shift @objectList;  
         # Get the join table.  
         my $joinTable = $self->{_metaData}->{Joins};  
         # Loop through the object list.  
         for my $thisObject (@objectList) {  
             # Look for a join.  
             my $joinKey = "$lastObject/$thisObject";  
             if (!exists $joinTable->{$joinKey}) {  
                 # Here there's no join, so we throw an error.  
                 Confess("No join exists to connect from $lastObject to $thisObject.");  
             } else {  
                 # Get the join clause and add it to the WHERE list.  
                 push @joinWhere, $joinTable->{$joinKey};  
                 # Save this object as the last object for the next iteration.  
                 $lastObject = $thisObject;  
             }  
         }  
         # 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;  
         }  
         # Add the filter and the join clauses (if any) to the SELECT command.  
         if ($filterString) {  
             push @joinWhere, "($filterString)";  
         }  
         if (@joinWhere) {  
             $command .= " WHERE " . join(' AND ', @joinWhere);  
         }  
         # Add the sort clause (if any) to the SELECT command.  
         if ($orderClause) {  
             $command .= " ORDER BY $orderClause";  
         }  
1096      }      }
     Trace("SQL query: $command") if T(3);  
     Trace("PARMS: '" . (join "', '", @params) . "'") if (T(4) && (@params > 0));  
     my $sth = $dbh->prepare_command($command);  
     # Execute it with the parameters bound in.  
     $sth->execute(@params) || Confess("SELECT error" . $sth->errstr());  
1097      # Return the statement object.      # Return the statement object.
1098      my $retVal = DBQuery::_new($self, $sth, @{$objectNames});      my $retVal = DBQuery::_new($self, $sth, \@relationMap);
1099      return $retVal;      return $retVal;
1100  }  }
1101    
1102  =head3 GetList  =head3 GetFlat
   
 C<< my @dbObjects = $erdb->GetList(\@objectNames, $filterClause, $param1, $param2, ..., $paramN); >>  
1103    
1104  Return a list of object descriptors for the specified objects as determined by the  C<< my @list = $erdb->GetFlat(\@objectNames, $filterClause, \@parameterList, $field); >>
 specified filter clause.  
1105    
1106  This method is essentially the same as L</Get> except it returns a list of objects rather  This is a variation of L</GetAll> that asks for only a single field per record and
1107  than a query object that can be used to get the results one record at a time.  returns a single flattened list.
1108    
1109  =over 4  =over 4
1110    
# Line 1028  Line 1114 
1114    
1115  =item filterClause  =item filterClause
1116    
1117  WHERE clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can  WHERE/ORDER BY clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can
1118  be parameterized with parameter markers (C<?>). Each field used in the WHERE clause must be  be parameterized with parameter markers (C<?>). Each field used must be specified in the standard form
1119  specified in the standard form B<I<objectName>(I<fieldName>)>. Any parameters specified  B<I<objectName>(I<fieldName>)>. Any parameters specified in the filter clause should be added to the
1120  in the filter clause should be added to the parameter list as additional parameters. The  parameter list as additional parameters. The fields in a filter clause can come from primary
1121  fields in a filter clause can come from primary entity relations, relationship relations,  entity relations, relationship relations, or secondary entity relations; however, all of the
1122  or secondary entity relations; however, all of the entities and relationships involved must  entities and relationships involved must be included in the list of object names.
 be included in the list of object names.  
   
 The filter clause can also specify a sort order. To do this, simply follow the filter string  
 with an ORDER BY clause. For example, the following filter string gets all genomes for a  
 particular genus and sorts them by species name.  
1123    
1124  C<< "Genome(genus) = ? ORDER BY Genome(species)" >>  =item parameterList
1125    
1126  The rules for field references in a sort order are the same as those for field references in the  List of the parameters to be substituted in for the parameters marks in the filter clause.
 filter clause in general; however, odd things may happen if a sort field is from a secondary  
 relation.  
1127    
1128  =item param1, param2, ..., paramN  =item field
1129    
1130  Parameter values to be substituted into the filter clause.  Name of the field to be used to get the elements of the list returned.
1131    
1132  =item RETURN  =item RETURN
1133    
1134  Returns a list of B<DBObject>s that satisfy the query conditions.  Returns a list of values.
1135    
1136  =back  =back
1137    
1138  =cut  =cut
1139  #: Return Type @%  #: Return Type @;
1140  sub GetList {  sub GetFlat {
1141      # Get the parameters.      # Get the parameters.
1142      my ($self, $objectNames, $filterClause, @params) = @_;      my ($self, $objectNames, $filterClause, $parameterList, $field) = @_;
1143      # Declare the return variable.      # Construct the query.
1144        my $query = $self->Get($objectNames, $filterClause, $parameterList);
1145        # Create the result list.
1146      my @retVal = ();      my @retVal = ();
1147      # Perform the query.      # Loop through the records, adding the field values found to the result list.
1148      my $query = $self->Get($objectNames, $filterClause, @params);      while (my $row = $query->Fetch()) {
1149      # Loop through the results.          push @retVal, $row->Value($field);
     while (my $object = $query->Fetch) {  
         push @retVal, $object;  
1150      }      }
1151      # Return the result.      # Return the list created.
1152      return @retVal;      return @retVal;
1153  }  }
1154    
1155  =head3 ComputeObjectSentence  =head3 Delete
1156    
1157  C<< my $sentence = $erdb->ComputeObjectSentence($objectName); >>  C<< my $stats = $erdb->Delete($entityName, $objectID); >>
1158    
1159  Check an object name, and if it is a relationship convert it to a relationship sentence.  Delete an entity instance from the database. The instance is deleted along with all entity and
1160    relationship instances dependent on it. The idea of dependence here is recursive. An object is
1161    always dependent on itself. An object is dependent if it is a 1-to-many or many-to-many
1162    relationship connected to a dependent entity or the "to" entity connected to a 1-to-many
1163    dependent relationship.
1164    
1165  =over 4  =over 4
1166    
1167  =item objectName  =item entityName
1168    
1169  Name of the entity or relationship.  Name of the entity type for the instance being deleted.
1170    
1171  =item RETURN  =item objectID
1172    
1173  Returns a string containing the entity name or a relationship sentence.  ID of the entity instance to be deleted. If the ID contains a wild card character (C<%>),
1174    then it is presumed to by a LIKE pattern.
1175    
1176  =back  =item testFlag
1177    
1178    If TRUE, the delete statements will be traced without being executed.
1179    
1180    =item RETURN
1181    
1182    Returns a statistics object indicating how many records of each particular table were
1183    deleted.
1184    
1185    =back
1186    
1187    =cut
1188    #: Return Type $%;
1189    sub Delete {
1190        # Get the parameters.
1191        my ($self, $entityName, $objectID, $testFlag) = @_;
1192        # Declare the return variable.
1193        my $retVal = Stats->new();
1194        # Get the DBKernel object.
1195        my $db = $self->{_dbh};
1196        # We're going to generate all the paths branching out from the starting entity. One of
1197        # the things we have to be careful about is preventing loops. We'll use a hash to
1198        # determine if we've hit a loop.
1199        my %alreadyFound = ();
1200        # These next lists will serve as our result stack. We start by pushing object lists onto
1201        # the stack, and then popping them off to do the deletes. This means the deletes will
1202        # start with the longer paths before getting to the shorter ones. That, in turn, makes
1203        # sure we don't delete records that might be needed to forge relationships back to the
1204        # original item. We have two lists-- one for TO-relationships, and one for
1205        # FROM-relationships and entities.
1206        my @fromPathList = ();
1207        my @toPathList = ();
1208        # This final hash is used to remember what work still needs to be done. We push paths
1209        # onto the list, then pop them off to extend the paths. We prime it with the starting
1210        # point. Note that we will work hard to insure that the last item on a path in the
1211        # TODO list is always an entity.
1212        my @todoList = ([$entityName]);
1213        while (@todoList) {
1214            # Get the current path.
1215            my $current = pop @todoList;
1216            # Copy it into a list.
1217            my @stackedPath = @{$current};
1218            # Pull off the last item on the path. It will always be an entity.
1219            my $entityName = pop @stackedPath;
1220            # Add it to the alreadyFound list.
1221            $alreadyFound{$entityName} = 1;
1222            # Get the entity data.
1223            my $entityData = $self->_GetStructure($entityName);
1224            # The first task is to loop through the entity's relation. A DELETE command will
1225            # be needed for each of them.
1226            my $relations = $entityData->{Relations};
1227            for my $relation (keys %{$relations}) {
1228                my @augmentedList = (@stackedPath, $relation);
1229                push @fromPathList, \@augmentedList;
1230            }
1231            # Now we need to look for relationships connected to this entity.
1232            my $relationshipList = $self->{_metaData}->{Relationships};
1233            for my $relationshipName (keys %{$relationshipList}) {
1234                my $relationship = $relationshipList->{$relationshipName};
1235                # Check the FROM field. We're only interested if it's us.
1236                if ($relationship->{from} eq $entityName) {
1237                    # Add the path to this relationship.
1238                    my @augmentedList = (@stackedPath, $entityName, $relationshipName);
1239                    push @fromPathList, \@augmentedList;
1240                    # Check the arity. If it's MM we're done. If it's 1M
1241                    # and the target hasn't been seen yet, we want to
1242                    # stack the entity for future processing.
1243                    if ($relationship->{arity} eq '1M') {
1244                        my $toEntity = $relationship->{to};
1245                        if (! exists $alreadyFound{$toEntity}) {
1246                            # Here we have a new entity that's dependent on
1247                            # the current entity, so we need to stack it.
1248                            my @stackList = (@augmentedList, $toEntity);
1249                            push @fromPathList, \@stackList;
1250                        } else {
1251                            Trace("$toEntity ignored because it occurred previously.") if T(4);
1252                        }
1253                    }
1254                }
1255                # Now check the TO field. In this case only the relationship needs
1256                # deletion.
1257                if ($relationship->{to} eq $entityName) {
1258                    my @augmentedList = (@stackedPath, $entityName, $relationshipName);
1259                    push @toPathList, \@augmentedList;
1260                }
1261            }
1262        }
1263        # Create the first qualifier for the WHERE clause. This selects the
1264        # keys of the primary entity records to be deleted. When we're deleting
1265        # from a dependent table, we construct a join page from the first qualifier
1266        # to the table containing the dependent records to delete.
1267        my $qualifier = ($objectID =~ /%/ ? "LIKE ?" : "= ?");
1268        # We need to make two passes. The first is through the to-list, and
1269        # the second through the from-list. The from-list is second because
1270        # the to-list may need to pass through some of the entities the
1271        # from-list would delete.
1272        my %stackList = ( from_link => \@fromPathList, to_link => \@toPathList );
1273        # Now it's time to do the deletes. We do it in two passes.
1274        for my $keyName ('to_link', 'from_link') {
1275            # Get the list for this key.
1276            my @pathList = @{$stackList{$keyName}};
1277            Trace(scalar(@pathList) . " entries in path list for $keyName.") if T(3);
1278            # Loop through this list.
1279            while (my $path = pop @pathList) {
1280                # Get the table whose rows are to be deleted.
1281                my @pathTables = @{$path};
1282                # Start the DELETE statement. We need to call DBKernel because the
1283                # syntax of a DELETE-USING varies among DBMSs.
1284                my $target = $pathTables[$#pathTables];
1285                my $stmt = $db->SetUsing(@pathTables);
1286                # Now start the WHERE. The first thing is the ID field from the starting table. That
1287                # starting table will either be the entity relation or one of the entity's
1288                # sub-relations.
1289                $stmt .= " WHERE $pathTables[0].id $qualifier";
1290                # Now we run through the remaining entities in the path, connecting them up.
1291                for (my $i = 1; $i <= $#pathTables; $i += 2) {
1292                    # Connect the current relationship to the preceding entity.
1293                    my ($entity, $rel) = @pathTables[$i-1,$i];
1294                    # The style of connection depends on the direction of the relationship.
1295                    $stmt .= " AND $entity.id = $rel.$keyName";
1296                    if ($i + 1 <= $#pathTables) {
1297                        # Here there's a next entity, so connect that to the relationship's
1298                        # to-link.
1299                        my $entity2 = $pathTables[$i+1];
1300                        $stmt .= " AND $rel.to_link = $entity2.id";
1301                    }
1302                }
1303                # Now we have our desired DELETE statement.
1304                if ($testFlag) {
1305                    # Here the user wants to trace without executing.
1306                    Trace($stmt) if T(0);
1307                } else {
1308                    # Here we can delete. Note that the SQL method dies with a confessing
1309                    # if an error occurs, so we just go ahead and do it.
1310                    Trace("Executing delete from $target using '$objectID'.") if T(3);
1311                    my $rv = $db->SQL($stmt, 0, $objectID);
1312                    # Accumulate the statistics for this delete. The only rows deleted
1313                    # are from the target table, so we use its name to record the
1314                    # statistic.
1315                    $retVal->Add($target, $rv);
1316                }
1317            }
1318        }
1319        # Return the result.
1320        return $retVal;
1321    }
1322    
1323    =head3 GetList
1324    
1325    C<< my @dbObjects = $erdb->GetList(\@objectNames, $filterClause, \@params); >>
1326    
1327    Return a list of object descriptors for the specified objects as determined by the
1328    specified filter clause.
1329    
1330    This method is essentially the same as L</Get> except it returns a list of objects rather
1331    than a query object that can be used to get the results one record at a time.
1332    
1333    =over 4
1334    
1335    =item objectNames
1336    
1337    List containing the names of the entity and relationship objects to be retrieved.
1338    
1339    =item filterClause
1340    
1341    WHERE clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can
1342    be parameterized with parameter markers (C<?>). Each field used in the WHERE clause must be
1343    specified in the standard form B<I<objectName>(I<fieldName>)>. Any parameters specified
1344    in the filter clause should be added to the parameter list as additional parameters. The
1345    fields in a filter clause can come from primary entity relations, relationship relations,
1346    or secondary entity relations; however, all of the entities and relationships involved must
1347    be included in the list of object names.
1348    
1349    The filter clause can also specify a sort order. To do this, simply follow the filter string
1350    with an ORDER BY clause. For example, the following filter string gets all genomes for a
1351    particular genus and sorts them by species name.
1352    
1353    C<< "Genome(genus) = ? ORDER BY Genome(species)" >>
1354    
1355    The rules for field references in a sort order are the same as those for field references in the
1356    filter clause in general; however, odd things may happen if a sort field is from a secondary
1357    relation.
1358    
1359    =item params
1360    
1361    Reference to a list of parameter values to be substituted into the filter clause.
1362    
1363    =item RETURN
1364    
1365    Returns a list of B<DBObject>s that satisfy the query conditions.
1366    
1367    =back
1368    
1369    =cut
1370    #: Return Type @%
1371    sub GetList {
1372        # Get the parameters.
1373        my ($self, $objectNames, $filterClause, $params) = @_;
1374        # Declare the return variable.
1375        my @retVal = ();
1376        # Perform the query.
1377        my $query = $self->Get($objectNames, $filterClause, $params);
1378        # Loop through the results.
1379        while (my $object = $query->Fetch) {
1380            push @retVal, $object;
1381        }
1382        # Return the result.
1383        return @retVal;
1384    }
1385    
1386    =head3 GetCount
1387    
1388    C<< my $count = $erdb->GetCount(\@objectNames, $filter, \@params); >>
1389    
1390    Return the number of rows found by a specified query. This method would
1391    normally be used to count the records in a single table. For example, in a
1392    genetics database
1393    
1394        my $count = $erdb->GetCount(['Genome'], 'Genome(genus-species) LIKE ?', ['homo %']);
1395    
1396    would return the number of genomes for the genus I<homo>. It is conceivable, however,
1397    to use it to return records based on a join. For example,
1398    
1399        my $count = $erdb->GetCount(['HasFeature', 'Genome'], 'Genome(genus-species) LIKE ?',
1400                                    ['homo %']);
1401    
1402    would return the number of features for genomes in the genus I<homo>. Note that
1403    only the rows from the first table are counted. If the above command were
1404    
1405        my $count = $erdb->GetCount(['Genome', 'Feature'], 'Genome(genus-species) LIKE ?',
1406                                    ['homo %']);
1407    
1408    it would return the number of genomes, not the number of genome/feature pairs.
1409    
1410    =over 4
1411    
1412    =item objectNames
1413    
1414    Reference to a list of the objects (entities and relationships) included in the
1415    query.
1416    
1417    =item filter
1418    
1419    A filter clause for restricting the query. The rules are the same as for the L</Get>
1420    method.
1421    
1422    =item params
1423    
1424    Reference to a list of the parameter values to be substituted for the parameter marks
1425    in the filter.
1426    
1427    =item RETURN
1428    
1429    Returns a count of the number of records in the first table that would satisfy
1430    the query.
1431    
1432    =back
1433    
1434    =cut
1435    
1436    sub GetCount {
1437        # Get the parameters.
1438        my ($self, $objectNames, $filter, $params) = @_;
1439        # Declare the return variable.
1440        my $retVal;
1441        # Find out if we're counting an entity or a relationship.
1442        my $countedField;
1443        if ($self->IsEntity($objectNames->[0])) {
1444            $countedField = "id";
1445        } else {
1446            # For a relationship we count the to-link because it's usually more
1447            # numerous. Note we're automatically converting to the SQL form
1448            # of the field name (to_link vs. to-link).
1449            $countedField = "to_link";
1450        }
1451        # Create the SQL command suffix to get the desired records.
1452        my ($suffix, $mappedNameListRef, $mappedNameHashRef) = $self->_SetupSQL($objectNames,
1453                                                                                $filter);
1454        # Prefix it with text telling it we want a record count.
1455        my $firstObject = $mappedNameListRef->[0];
1456        my $command = "SELECT COUNT($firstObject.$countedField) $suffix";
1457        # Prepare and execute the command.
1458        my $sth = $self->_GetStatementHandle($command, $params);
1459        # Get the count value.
1460        ($retVal) = $sth->fetchrow_array();
1461        # Check for a problem.
1462        if (! defined($retVal)) {
1463            if ($sth->err) {
1464                # Here we had an SQL error.
1465                Confess("Error retrieving row count: " . $sth->errstr());
1466            } else {
1467                # Here we have no result.
1468                Confess("No result attempting to retrieve row count.");
1469            }
1470        }
1471        # Return the result.
1472        return $retVal;
1473    }
1474    
1475    =head3 ComputeObjectSentence
1476    
1477    C<< my $sentence = $erdb->ComputeObjectSentence($objectName); >>
1478    
1479    Check an object name, and if it is a relationship convert it to a relationship sentence.
1480    
1481    =over 4
1482    
1483    =item objectName
1484    
1485    Name of the entity or relationship.
1486    
1487    =item RETURN
1488    
1489    Returns a string containing the entity name or a relationship sentence.
1490    
1491    =back
1492    
1493  =cut  =cut
1494    
# Line 1150  Line 1549 
1549      }      }
1550  }  }
1551    
1552    =head3 InsertValue
1553    
1554    C<< $erdb->InsertValue($entityID, $fieldName, $value); >>
1555    
1556    This method will insert a new value into the database. The value must be one
1557    associated with a secondary relation, since primary values cannot be inserted:
1558    they occur exactly once. Secondary values, on the other hand, can be missing
1559    or multiply-occurring.
1560    
1561    =over 4
1562    
1563    =item entityID
1564    
1565    ID of the object that is to receive the new value.
1566    
1567    =item fieldName
1568    
1569    Field name for the new value-- this includes the entity name, since
1570    field names are of the format I<objectName>C<(>I<fieldName>C<)>.
1571    
1572    =item value
1573    
1574    New value to be put in the field.
1575    
1576    =back
1577    
1578    =cut
1579    
1580    sub InsertValue {
1581        # Get the parameters.
1582        my ($self, $entityID, $fieldName, $value) = @_;
1583        # Parse the entity name and the real field name.
1584        if ($fieldName =~ /^([^(]+)\(([^)]+)\)/) {
1585            my $entityName = $1;
1586            my $fieldTitle = $2;
1587            # Get its descriptor.
1588            if (!$self->IsEntity($entityName)) {
1589                Confess("$entityName is not a valid entity.");
1590            } else {
1591                my $entityData = $self->{_metaData}->{Entities}->{$entityName};
1592                # Find the relation containing this field.
1593                my $fieldHash = $entityData->{Fields};
1594                if (! exists $fieldHash->{$fieldTitle}) {
1595                    Confess("$fieldTitle not found in $entityName.");
1596                } else {
1597                    my $relation = $fieldHash->{$fieldTitle}->{relation};
1598                    if ($relation eq $entityName) {
1599                        Confess("Cannot do InsertValue on primary field $fieldTitle of $entityName.");
1600                    } else {
1601                        # Now we can create an INSERT statement.
1602                        my $dbh = $self->{_dbh};
1603                        my $fixedName = _FixName($fieldTitle);
1604                        my $statement = "INSERT INTO $relation (id, $fixedName) VALUES(?, ?)";
1605                        # Execute the command.
1606                        $dbh->SQL($statement, 0, $entityID, $value);
1607                    }
1608                }
1609            }
1610        } else {
1611            Confess("$fieldName is not a valid field name.");
1612        }
1613    }
1614    
1615  =head3 InsertObject  =head3 InsertObject
1616    
1617  C<< my $ok = $erdb->InsertObject($objectType, \%fieldHash); >>  C<< my $ok = $erdb->InsertObject($objectType, \%fieldHash); >>
# Line 1166  Line 1628 
1628  The next statement inserts a C<HasProperty> relationship between feature C<fig|158879.1.peg.1> and  The next statement inserts a C<HasProperty> relationship between feature C<fig|158879.1.peg.1> and
1629  property C<4> with an evidence URL of C<http://seedu.uchicago.edu/query.cgi?article_id=142>.  property C<4> with an evidence URL of C<http://seedu.uchicago.edu/query.cgi?article_id=142>.
1630    
1631  C<< $erdb->InsertObject('HasProperty', { 'from-link' => 'fig|158879.1.peg.1', 'to-link' => 4, evidence = 'http://seedu.uchicago.edu/query.cgi?article_id=142'}); >>  C<< $erdb->InsertObject('HasProperty', { 'from-link' => 'fig|158879.1.peg.1', 'to-link' => 4, evidence => 'http://seedu.uchicago.edu/query.cgi?article_id=142'}); >>
1632    
1633  =over 4  =over 4
1634    
# Line 1312  Line 1774 
1774    
1775  =item RETURN  =item RETURN
1776    
1777  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.  
1778    
1779  =back  =back
1780    
# Line 1327  Line 1788 
1788      Trace("Loading table $relationName from $fileName") if T(2);      Trace("Loading table $relationName from $fileName") if T(2);
1789      # Get the database handle.      # Get the database handle.
1790      my $dbh = $self->{_dbh};      my $dbh = $self->{_dbh};
1791        # Get the input file size.
1792        my $fileSize = -s $fileName;
1793      # Get the relation data.      # Get the relation data.
1794      my $relation = $self->_FindRelation($relationName);      my $relation = $self->_FindRelation($relationName);
1795      # Check the truncation flag.      # Check the truncation flag.
# Line 1337  Line 1800 
1800          # leave extra room. We postulate a minimum row count of 1000 to          # leave extra room. We postulate a minimum row count of 1000 to
1801          # prevent problems with incoming empty load files.          # prevent problems with incoming empty load files.
1802          my $rowSize = $self->EstimateRowSize($relationName);          my $rowSize = $self->EstimateRowSize($relationName);
         my $fileSize = -s $fileName;  
1803          my $estimate = FIG::max($fileSize * 1.5 / $rowSize, 1000);          my $estimate = FIG::max($fileSize * 1.5 / $rowSize, 1000);
1804          # Re-create the table without its index.          # Re-create the table without its index.
1805          $self->CreateTable($relationName, 0, $estimate);          $self->CreateTable($relationName, 0, $estimate);
# Line 1361  Line 1823 
1823          $retVal->AddMessage("Table load failed for $relationName using $fileName.");          $retVal->AddMessage("Table load failed for $relationName using $fileName.");
1824          Trace("Table load failed for $relationName.") if T(1);          Trace("Table load failed for $relationName.") if T(1);
1825      } else {      } else {
1826          # Here we successfully loaded the table. Trace the number of records loaded.          # Here we successfully loaded the table.
1827          Trace("$retVal->{records} records read for $relationName.") if T(2);          $retVal->Add("tables");
1828            my $size = -s $fileName;
1829            Trace("$size bytes loaded into $relationName.") if T(2);
1830          # If we're rebuilding, we need to create the table indexes.          # If we're rebuilding, we need to create the table indexes.
1831          if ($truncateFlag && ! $dbh->{_preIndex}) {          if ($truncateFlag && ! $dbh->{_preIndex}) {
1832              eval {              eval {
# Line 1373  Line 1837 
1837              }              }
1838          }          }
1839      }      }
     # Commit the database changes.  
     $dbh->commit_tran;  
1840      # Analyze the table to improve performance.      # Analyze the table to improve performance.
1841        Trace("Analyzing and compacting $relationName.") if T(3);
1842      $dbh->vacuum_it($relationName);      $dbh->vacuum_it($relationName);
1843        # Flush the database cache.
1844        $dbh->flush_tables();
1845        Trace("$relationName load completed.") if T(3);
1846      # Return the statistics.      # Return the statistics.
1847      return $retVal;      return $retVal;
1848  }  }
# Line 1468  Line 1934 
1934      # Get the parameters.      # Get the parameters.
1935      my ($self, $entityType, $ID) = @_;      my ($self, $entityType, $ID) = @_;
1936      # Create a query.      # Create a query.
1937      my $query = $self->Get([$entityType], "$entityType(id) = ?", $ID);      my $query = $self->Get([$entityType], "$entityType(id) = ?", [$ID]);
1938      # Get the first (and only) object.      # Get the first (and only) object.
1939      my $retVal = $query->Fetch();      my $retVal = $query->Fetch();
1940      # Return the result.      # Return the result.
# Line 1581  Line 2047 
2047      # list is a scalar we convert it into a singleton list.      # list is a scalar we convert it into a singleton list.
2048      my @parmList = ();      my @parmList = ();
2049      if (ref $parameterList eq "ARRAY") {      if (ref $parameterList eq "ARRAY") {
2050            Trace("GetAll parm list is an array.") if T(4);
2051          @parmList = @{$parameterList};          @parmList = @{$parameterList};
2052      } else {      } else {
2053            Trace("GetAll parm list is a scalar: $parameterList.") if T(4);
2054          push @parmList, $parameterList;          push @parmList, $parameterList;
2055      }      }
     # Create the query.  
     my $query = $self->Get($objectNames, $filterClause, @parmList);  
     # Set up a counter of the number of records read.  
     my $fetched = 0;  
2056      # Insure the counter has a value.      # Insure the counter has a value.
2057      if (!defined $count) {      if (!defined $count) {
2058          $count = 0;          $count = 0;
2059      }      }
2060        # Add the row limit to the filter clause.
2061        if ($count > 0) {
2062            $filterClause .= " LIMIT $count";
2063        }
2064        # Create the query.
2065        my $query = $self->Get($objectNames, $filterClause, \@parmList);
2066        # Set up a counter of the number of records read.
2067        my $fetched = 0;
2068      # Loop through the records returned, extracting the fields. Note that if the      # Loop through the records returned, extracting the fields. Note that if the
2069      # 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.
2070      my @retVal = ();      my @retVal = ();
# Line 1601  Line 2073 
2073          push @retVal, \@rowData;          push @retVal, \@rowData;
2074          $fetched++;          $fetched++;
2075      }      }
2076        Trace("$fetched rows returned in GetAll.") if T(SQL => 4);
2077      # Return the resulting list.      # Return the resulting list.
2078      return @retVal;      return @retVal;
2079  }  }
2080    
2081    =head3 Exists
2082    
2083    C<< my $found = $sprout->Exists($entityName, $entityID); >>
2084    
2085    Return TRUE if an entity exists, else FALSE.
2086    
2087    =over 4
2088    
2089    =item entityName
2090    
2091    Name of the entity type (e.g. C<Feature>) relevant to the existence check.
2092    
2093    =item entityID
2094    
2095    ID of the entity instance whose existence is to be checked.
2096    
2097    =item RETURN
2098    
2099    Returns TRUE if the entity instance exists, else FALSE.
2100    
2101    =back
2102    
2103    =cut
2104    #: Return Type $;
2105    sub Exists {
2106        # Get the parameters.
2107        my ($self, $entityName, $entityID) = @_;
2108        # Check for the entity instance.
2109        Trace("Checking existence of $entityName with ID=$entityID.") if T(4);
2110        my $testInstance = $self->GetEntity($entityName, $entityID);
2111        # Return an existence indicator.
2112        my $retVal = ($testInstance ? 1 : 0);
2113        return $retVal;
2114    }
2115    
2116  =head3 EstimateRowSize  =head3 EstimateRowSize
2117    
2118  C<< my $rowSize = $erdb->EstimateRowSize($relName); >>  C<< my $rowSize = $erdb->EstimateRowSize($relName); >>
# Line 1643  Line 2151 
2151      return $retVal;      return $retVal;
2152  }  }
2153    
2154    =head3 GetFieldTable
2155    
2156    C<< my $fieldHash = $self->GetFieldTable($objectnName); >>
2157    
2158    Get the field structure for a specified entity or relationship.
2159    
2160    =over 4
2161    
2162    =item objectName
2163    
2164    Name of the desired entity or relationship.
2165    
2166    =item RETURN
2167    
2168    The table containing the field descriptors for the specified object.
2169    
2170    =back
2171    
2172    =cut
2173    
2174    sub GetFieldTable {
2175        # Get the parameters.
2176        my ($self, $objectName) = @_;
2177        # Get the descriptor from the metadata.
2178        my $objectData = $self->_GetStructure($objectName);
2179        # Return the object's field table.
2180        return $objectData->{Fields};
2181    }
2182    
2183    =head2 Data Mining Methods
2184    
2185    =head3 GetUsefulCrossValues
2186    
2187    C<< my @attrNames = $sprout->GetUsefulCrossValues($sourceEntity, $relationship); >>
2188    
2189    Return a list of the useful attributes that would be returned by a B<Cross> call
2190    from an entity of the source entity type through the specified relationship. This
2191    means it will return the fields of the target entity type and the intersection data
2192    fields in the relationship. Only primary table fields are returned. In other words,
2193    the field names returned will be for fields where there is always one and only one
2194    value.
2195    
2196    =over 4
2197    
2198    =item sourceEntity
2199    
2200    Name of the entity from which the relationship crossing will start.
2201    
2202    =item relationship
2203    
2204    Name of the relationship being crossed.
2205    
2206    =item RETURN
2207    
2208    Returns a list of field names in Sprout field format (I<objectName>C<(>I<fieldName>C<)>.
2209    
2210    =back
2211    
2212    =cut
2213    #: Return Type @;
2214    sub GetUsefulCrossValues {
2215        # Get the parameters.
2216        my ($self, $sourceEntity, $relationship) = @_;
2217        # Declare the return variable.
2218        my @retVal = ();
2219        # Determine the target entity for the relationship. This is whichever entity is not
2220        # the source entity. So, if the source entity is the FROM, we'll get the name of
2221        # the TO, and vice versa.
2222        my $relStructure = $self->_GetStructure($relationship);
2223        my $targetEntityType = ($relStructure->{from} eq $sourceEntity ? "to" : "from");
2224        my $targetEntity = $relStructure->{$targetEntityType};
2225        # Get the field table for the entity.
2226        my $entityFields = $self->GetFieldTable($targetEntity);
2227        # The field table is a hash. The hash key is the field name. The hash value is a structure.
2228        # For the entity fields, the key aspect of the target structure is that the {relation} value
2229        # must match the entity name.
2230        my @fieldList = map { "$targetEntity($_)" } grep { $entityFields->{$_}->{relation} eq $targetEntity }
2231                            keys %{$entityFields};
2232        # Push the fields found onto the return variable.
2233        push @retVal, sort @fieldList;
2234        # Get the field table for the relationship.
2235        my $relationshipFields = $self->GetFieldTable($relationship);
2236        # Here we have a different rule. We want all the fields other than "from-link" and "to-link".
2237        # This may end up being an empty set.
2238        my @fieldList2 = map { "$relationship($_)" } grep { $_ ne "from-link" && $_ ne "to-link" }
2239                            keys %{$relationshipFields};
2240        # Push these onto the return list.
2241        push @retVal, sort @fieldList2;
2242        # Return the result.
2243        return @retVal;
2244    }
2245    
2246    =head3 FindColumn
2247    
2248    C<< my $colIndex = ERDB::FindColumn($headerLine, $columnIdentifier); >>
2249    
2250    Return the location a desired column in a data mining header line. The data
2251    mining header line is a tab-separated list of column names. The column
2252    identifier is either the numerical index of a column or the actual column
2253    name.
2254    
2255    =over 4
2256    
2257    =item headerLine
2258    
2259    The header line from a data mining command, which consists of a tab-separated
2260    list of column names.
2261    
2262    =item columnIdentifier
2263    
2264    Either the ordinal number of the desired column (1-based), or the name of the
2265    desired column.
2266    
2267    =item RETURN
2268    
2269    Returns the array index (0-based) of the desired column.
2270    
2271    =back
2272    
2273    =cut
2274    
2275    sub FindColumn {
2276        # Get the parameters.
2277        my ($headerLine, $columnIdentifier) = @_;
2278        # Declare the return variable.
2279        my $retVal;
2280        # Split the header line into column names.
2281        my @headers = ParseColumns($headerLine);
2282        # Determine whether we have a number or a name.
2283        if ($columnIdentifier =~ /^\d+$/) {
2284            # Here we have a number. Subtract 1 and validate the result.
2285            $retVal = $columnIdentifier - 1;
2286            if ($retVal < 0 || $retVal > $#headers) {
2287                Confess("Invalid column identifer \"$columnIdentifier\": value out of range.");
2288            }
2289        } else {
2290            # Here we have a name. We need to find it in the list.
2291            for (my $i = 0; $i <= $#headers && ! defined($retVal); $i++) {
2292                if ($headers[$i] eq $columnIdentifier) {
2293                    $retVal = $i;
2294                }
2295            }
2296            if (! defined($retVal)) {
2297                Confess("Invalid column identifier \"$columnIdentifier\": value not found.");
2298            }
2299        }
2300        # Return the result.
2301        return $retVal;
2302    }
2303    
2304    =head3 ParseColumns
2305    
2306    C<< my @columns = ERDB::ParseColumns($line); >>
2307    
2308    Convert the specified data line to a list of columns.
2309    
2310    =over 4
2311    
2312    =item line
2313    
2314    A data mining input, consisting of a tab-separated list of columns terminated by a
2315    new-line.
2316    
2317    =item RETURN
2318    
2319    Returns a list consisting of the column values.
2320    
2321    =back
2322    
2323    =cut
2324    
2325    sub ParseColumns {
2326        # Get the parameters.
2327        my ($line) = @_;
2328        # Chop off the line-end.
2329        chomp $line;
2330        # Split it into a list.
2331        my @retVal = split(/\t/, $line);
2332        # Return the result.
2333        return @retVal;
2334    }
2335    
2336  =head2 Internal Utility Methods  =head2 Internal Utility Methods
2337    
2338    =head3 SetupSQL
2339    
2340    Process a list of object names and a filter clause so that they can be used to
2341    build an SQL statement. This method takes in a reference to a list of object names
2342    and a filter clause. It will return a corrected filter clause, a list of mapped
2343    names and the mapped name hash.
2344    
2345    This is an instance method.
2346    
2347    =over 4
2348    
2349    =item objectNames
2350    
2351    Reference to a list of the object names to be included in the query.
2352    
2353    =item filterClause
2354    
2355    A string containing the WHERE clause for the query (without the C<WHERE>) and also
2356    optionally the C<ORDER BY> and C<LIMIT> clauses.
2357    
2358    =item RETURN
2359    
2360    Returns a three-element list. The first element is the SQL statement suffix, beginning
2361    with the FROM clause. The second element is a reference to a list of the names to be
2362    used in retrieving the fields. The third element is a hash mapping the names to the
2363    objects they represent.
2364    
2365    =back
2366    
2367    =cut
2368    
2369    sub _SetupSQL {
2370        my ($self, $objectNames, $filterClause) = @_;
2371        # Adjust the list of object names to account for multiple occurrences of the
2372        # same object. We start with a hash table keyed on object name that will
2373        # return the object suffix. The first time an object is encountered it will
2374        # not be found in the hash. The next time the hash will map the object name
2375        # to 2, then 3, and so forth.
2376        my %objectHash = ();
2377        # This list will contain the object names as they are to appear in the
2378        # FROM list.
2379        my @fromList = ();
2380        # This list contains the suffixed object name for each object. It is exactly
2381        # parallel to the list in the $objectNames parameter.
2382        my @mappedNameList = ();
2383        # Finally, this hash translates from a mapped name to its original object name.
2384        my %mappedNameHash = ();
2385        # Now we create the lists. Note that for every single name we push something into
2386        # @fromList and @mappedNameList. This insures that those two arrays are exactly
2387        # parallel to $objectNames.
2388        for my $objectName (@{$objectNames}) {
2389            # Get the next suffix for this object.
2390            my $suffix = $objectHash{$objectName};
2391            if (! $suffix) {
2392                # Here we are seeing the object for the first time. The object name
2393                # is used as is.
2394                push @mappedNameList, $objectName;
2395                push @fromList, $objectName;
2396                $mappedNameHash{$objectName} = $objectName;
2397                # Denote the next suffix will be 2.
2398                $objectHash{$objectName} = 2;
2399            } else {
2400                # Here we've seen the object before. We construct a new name using
2401                # the suffix from the hash and update the hash.
2402                my $mappedName = "$objectName$suffix";
2403                $objectHash{$objectName} = $suffix + 1;
2404                # The FROM list has the object name followed by the mapped name. This
2405                # tells SQL it's still the same table, but we're using a different name
2406                # for it to avoid confusion.
2407                push @fromList, "$objectName $mappedName";
2408                # The mapped-name list contains the real mapped name.
2409                push @mappedNameList, $mappedName;
2410                # Finally, enable us to get back from the mapped name to the object name.
2411                $mappedNameHash{$mappedName} = $objectName;
2412            }
2413        }
2414        # Begin the SELECT suffix. It starts with
2415        #
2416        # FROM name1, name2, ... nameN
2417        #
2418        my $suffix = "FROM " . join(', ', @fromList);
2419        # Check for a filter clause.
2420        if ($filterClause) {
2421            # Here we have one, so we convert its field names and add it to the query. First,
2422            # We create a copy of the filter string we can work with.
2423            my $filterString = $filterClause;
2424            # Next, we sort the object names by length. This helps protect us from finding
2425            # object names inside other object names when we're doing our search and replace.
2426            my @sortedNames = sort { length($b) - length($a) } @mappedNameList;
2427            # We will also keep a list of conditions to add to the WHERE clause in order to link
2428            # entities and relationships as well as primary relations to secondary ones.
2429            my @joinWhere = ();
2430            # The final preparatory step is to create a hash table of relation names. The
2431            # table begins with the relation names already in the SELECT command. We may
2432            # need to add relations later if there is filtering on a field in a secondary
2433            # relation. The secondary relations are the ones that contain multiply-
2434            # occurring or optional fields.
2435            my %fromNames = map { $_ => 1 } @sortedNames;
2436            # We are ready to begin. We loop through the object names, replacing each
2437            # object name's field references by the corresponding SQL field reference.
2438            # Along the way, if we find a secondary relation, we will need to add it
2439            # to the FROM clause.
2440            for my $mappedName (@sortedNames) {
2441                # Get the length of the object name plus 2. This is the value we add to the
2442                # size of the field name to determine the size of the field reference as a
2443                # whole.
2444                my $nameLength = 2 + length $mappedName;
2445                # Get the real object name for this mapped name.
2446                my $objectName = $mappedNameHash{$mappedName};
2447                Trace("Processing $mappedName for object $objectName.") if T(4);
2448                # Get the object's field list.
2449                my $fieldList = $self->GetFieldTable($objectName);
2450                # Find the field references for this object.
2451                while ($filterString =~ m/$mappedName\(([^)]*)\)/g) {
2452                    # At this point, $1 contains the field name, and the current position
2453                    # is set immediately after the final parenthesis. We pull out the name of
2454                    # the field and the position and length of the field reference as a whole.
2455                    my $fieldName = $1;
2456                    my $len = $nameLength + length $fieldName;
2457                    my $pos = pos($filterString) - $len;
2458                    # Insure the field exists.
2459                    if (!exists $fieldList->{$fieldName}) {
2460                        Confess("Field $fieldName not found for object $objectName.");
2461                    } else {
2462                        Trace("Processing $fieldName at position $pos.") if T(4);
2463                        # Get the field's relation.
2464                        my $relationName = $fieldList->{$fieldName}->{relation};
2465                        # Now we have a secondary relation. We need to insure it matches the
2466                        # mapped name of the primary relation. First we peel off the suffix
2467                        # from the mapped name.
2468                        my $mappingSuffix = substr $mappedName, length($objectName);
2469                        # Put the mapping suffix onto the relation name to get the
2470                        # mapped relation name.
2471                        my $mappedRelationName = "$relationName$mappingSuffix";
2472                        # Insure the relation is in the FROM clause.
2473                        if (!exists $fromNames{$mappedRelationName}) {
2474                            # Add the relation to the FROM clause.
2475                            if ($mappedRelationName eq $relationName) {
2476                                # The name is un-mapped, so we add it without
2477                                # any frills.
2478                                $suffix .= ", $relationName";
2479                                push @joinWhere, "$objectName.id = $relationName.id";
2480                            } else {
2481                                # Here we have a mapping situation.
2482                                $suffix .= ", $relationName $mappedRelationName";
2483                                push @joinWhere, "$mappedRelationName.id = $mappedName.id";
2484                            }
2485                            # Denote we have this relation available for future fields.
2486                            $fromNames{$mappedRelationName} = 1;
2487                        }
2488                        # Form an SQL field reference from the relation name and the field name.
2489                        my $sqlReference = "$mappedRelationName." . _FixName($fieldName);
2490                        # Put it into the filter string in place of the old value.
2491                        substr($filterString, $pos, $len) = $sqlReference;
2492                        # Reposition the search.
2493                        pos $filterString = $pos + length $sqlReference;
2494                    }
2495                }
2496            }
2497            # The next step is to join the objects together. We only need to do this if there
2498            # is more than one object in the object list. We start with the first object and
2499            # run through the objects after it. Note also that we make a safety copy of the
2500            # list before running through it.
2501            my @mappedObjectList = @mappedNameList;
2502            my $lastMappedObject = shift @mappedObjectList;
2503            # Get the join table.
2504            my $joinTable = $self->{_metaData}->{Joins};
2505            # Loop through the object list.
2506            for my $thisMappedObject (@mappedObjectList) {
2507                # Look for a join using the real object names.
2508                my $lastObject = $mappedNameHash{$lastMappedObject};
2509                my $thisObject = $mappedNameHash{$thisMappedObject};
2510                my $joinKey = "$lastObject/$thisObject";
2511                if (!exists $joinTable->{$joinKey}) {
2512                    # Here there's no join, so we throw an error.
2513                    Confess("No join exists to connect from $lastMappedObject to $thisMappedObject.");
2514                } else {
2515                    # Get the join clause.
2516                    my $unMappedJoin = $joinTable->{$joinKey};
2517                    # Fix the names.
2518                    $unMappedJoin =~ s/$lastObject/$lastMappedObject/;
2519                    $unMappedJoin =~ s/$thisObject/$thisMappedObject/;
2520                    push @joinWhere, $unMappedJoin;
2521                    # Save this object as the last object for the next iteration.
2522                    $lastMappedObject = $thisMappedObject;
2523                }
2524            }
2525            # Now we need to handle the whole ORDER BY / LIMIT thing. The important part
2526            # here is we want the filter clause to be empty if there's no WHERE filter.
2527            # We'll put the ORDER BY / LIMIT clauses in the following variable.
2528            my $orderClause = "";
2529            # Locate the ORDER BY or LIMIT verbs (if any). We use a non-greedy
2530            # operator so that we find the first occurrence of either verb.
2531            if ($filterString =~ m/^(.*?)\s*(ORDER BY|LIMIT)/g) {
2532                # Here we have an ORDER BY or LIMIT verb. Split it off of the filter string.
2533                my $pos = pos $filterString;
2534                $orderClause = $2 . substr($filterString, $pos);
2535                $filterString = $1;
2536            }
2537            # Add the filter and the join clauses (if any) to the SELECT command.
2538            if ($filterString) {
2539                Trace("Filter string is \"$filterString\".") if T(4);
2540                push @joinWhere, "($filterString)";
2541            }
2542            if (@joinWhere) {
2543                $suffix .= " WHERE " . join(' AND ', @joinWhere);
2544            }
2545            # Add the sort or limit clause (if any) to the SELECT command.
2546            if ($orderClause) {
2547                $suffix .= " $orderClause";
2548            }
2549        }
2550        # Return the suffix, the mapped name list, and the mapped name hash.
2551        return ($suffix, \@mappedNameList, \%mappedNameHash);
2552    }
2553    
2554    =head3 GetStatementHandle
2555    
2556    This method will prepare and execute an SQL query, returning the statement handle.
2557    The main reason for doing this here is so that everybody who does SQL queries gets
2558    the benefit of tracing.
2559    
2560    This is an instance method.
2561    
2562    =over 4
2563    
2564    =item command
2565    
2566    Command to prepare and execute.
2567    
2568    =item params
2569    
2570    Reference to a list of the values to be substituted in for the parameter marks.
2571    
2572    =item RETURN
2573    
2574    Returns a prepared and executed statement handle from which the caller can extract
2575    results.
2576    
2577    =back
2578    
2579    =cut
2580    
2581    sub _GetStatementHandle {
2582        # Get the parameters.
2583        my ($self, $command, $params) = @_;
2584        # Trace the query.
2585        Trace("SQL query: $command") if T(SQL => 3);
2586        Trace("PARMS: '" . (join "', '", @{$params}) . "'") if (T(SQL => 4) && (@{$params} > 0));
2587        # Get the database handle.
2588        my $dbh = $self->{_dbh};
2589        # Prepare the command.
2590        my $sth = $dbh->prepare_command($command);
2591        # Execute it with the parameters bound in.
2592        $sth->execute(@{$params}) || Confess("SELECT error" . $sth->errstr());
2593        # Return the statement handle.
2594        return $sth;
2595    }
2596    
2597  =head3 GetLoadStats  =head3 GetLoadStats
2598    
2599  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 2603 
2603  =cut  =cut
2604    
2605  sub _GetLoadStats {  sub _GetLoadStats {
2606      return Stats->new('records');      return Stats->new();
2607  }  }
2608    
2609  =head3 GenerateFields  =head3 GenerateFields
# Line 1849  Line 2798 
2798      return $objectData->{Relations};      return $objectData->{Relations};
2799  }  }
2800    
 =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};  
 }  
   
2801  =head3 ValidateFieldNames  =head3 ValidateFieldNames
2802    
2803  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 3145 
3145          my @fromList = ();          my @fromList = ();
3146          my @toList = ();          my @toList = ();
3147          my @bothList = ();          my @bothList = ();
3148          Trace("Join table build for $entityName.") if T(4);          Trace("Join table build for $entityName.") if T(metadata => 4);
3149          for my $relationshipName (keys %{$relationshipList}) {          for my $relationshipName (keys %{$relationshipList}) {
3150              my $relationship = $relationshipList->{$relationshipName};              my $relationship = $relationshipList->{$relationshipName};
3151              # 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.
3152              my $fromEntity = $relationship->{from};              my $fromEntity = $relationship->{from};
3153              my $toEntity = $relationship->{to};              my $toEntity = $relationship->{to};
3154              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);
3155              if ($fromEntity eq $entityName) {              if ($fromEntity eq $entityName) {
3156                  if ($toEntity eq $entityName) {                  if ($toEntity eq $entityName) {
3157                      # Here the relationship is recursive.                      # Here the relationship is recursive.
3158                      push @bothList, $relationshipName;                      push @bothList, $relationshipName;
3159                      Trace("Relationship $relationshipName put in both-list.") if T(4);                      Trace("Relationship $relationshipName put in both-list.") if T(metadata => 4);
3160                  } else {                  } else {
3161                      # Here the relationship comes from the entity.                      # Here the relationship comes from the entity.
3162                      push @fromList, $relationshipName;                      push @fromList, $relationshipName;
3163                      Trace("Relationship $relationshipName put in from-list.") if T(4);                      Trace("Relationship $relationshipName put in from-list.") if T(metadata => 4);
3164                  }                  }
3165              } elsif ($toEntity eq $entityName) {              } elsif ($toEntity eq $entityName) {
3166                  # Here the relationship goes to the entity.                  # Here the relationship goes to the entity.
3167                  push @toList, $relationshipName;                  push @toList, $relationshipName;
3168                  Trace("Relationship $relationshipName put in to-list.") if T(4);                  Trace("Relationship $relationshipName put in to-list.") if T(metadata => 4);
3169              }              }
3170          }          }
3171          # 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 3181 
3181                  # Create joins between the entity and this relationship.                  # Create joins between the entity and this relationship.
3182                  my $linkField = "$relationshipName.${linkType}_link";                  my $linkField = "$relationshipName.${linkType}_link";
3183                  my $joinClause = "$entityName.id = $linkField";                  my $joinClause = "$entityName.id = $linkField";
3184                  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);
3185                  $joinTable{"$entityName/$relationshipName"} = $joinClause;                  $joinTable{"$entityName/$relationshipName"} = $joinClause;
3186                  $joinTable{"$relationshipName/$entityName"} = $joinClause;                  $joinTable{"$relationshipName/$entityName"} = $joinClause;
3187                  # Create joins between this relationship and the other relationships.                  # Create joins between this relationship and the other relationships.
# Line 2282  Line 3202 
3202                              # relationship and itself are prohibited.                              # relationship and itself are prohibited.
3203                              my $relJoinClause = "$otherName.${otherType}_link = $linkField";                              my $relJoinClause = "$otherName.${otherType}_link = $linkField";
3204                              $joinTable{$joinKey} = $relJoinClause;                              $joinTable{$joinKey} = $relJoinClause;
3205                              Trace("Relationship join clause is $relJoinClause for $joinKey.") if T(4);                              Trace("Relationship join clause is $relJoinClause for $joinKey.") if T(metadata => 4);
3206                          }                          }
3207                      }                      }
3208                  }                  }
# Line 2291  Line 3211 
3211                  # relationship can only be ambiguous with another recursive relationship,                  # relationship can only be ambiguous with another recursive relationship,
3212                  # and the incoming relationship from the outer loop is never recursive.                  # and the incoming relationship from the outer loop is never recursive.
3213                  for my $otherName (@bothList) {                  for my $otherName (@bothList) {
3214                      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);
3215                      # Join from the left.                      # Join from the left.
3216                      $joinTable{"$relationshipName/$otherName"} =                      $joinTable{"$relationshipName/$otherName"} =
3217                          "$linkField = $otherName.from_link";                          "$linkField = $otherName.from_link";
# Line 2306  Line 3226 
3226          # 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
3227          # possible to get the same effect using multiple queries.          # possible to get the same effect using multiple queries.
3228          for my $relationshipName (@bothList) {          for my $relationshipName (@bothList) {
3229              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);
3230              # Join to the entity from each direction.              # Join to the entity from each direction.
3231              $joinTable{"$entityName/$relationshipName"} =              $joinTable{"$entityName/$relationshipName"} =
3232                  "$entityName.id = $relationshipName.from_link";                  "$entityName.id = $relationshipName.from_link";
# Line 2320  Line 3240 
3240      return $metadata;      return $metadata;
3241  }  }
3242    
3243    =head3 SortNeeded
3244    
3245    C<< my $parms = $erdb->SortNeeded($relationName); >>
3246    
3247    Return the pipe command for the sort that should be applied to the specified
3248    relation when creating the load file.
3249    
3250    For example, if the load file should be sorted ascending by the first
3251    field with duplicates removed, this method would return
3252    
3253        sort -k 1 -u -t "\t"
3254    
3255    If the first field is numeric and duplicates are okay, the method would
3256    return
3257    
3258        sort -k 1n -t "\t"
3259    
3260    =over 4
3261    
3262    =item relationName
3263    
3264    Name of the relation to be examined.
3265    
3266    =item
3267    
3268    Returns the sort command to use for sorting the relation, suitable for piping.
3269    
3270    =back
3271    
3272    =cut
3273    #: Return Type $;
3274    sub SortNeeded {
3275        # Get the parameters.
3276        my ($self, $relationName) = @_;
3277        # Declare a descriptor to hold the names of the key fields.
3278        my @keyNames = ();
3279        # Declare a flag for indicating uniqueness.
3280        my $unique;
3281        # Get the relation structure.
3282        my $relationData = $self->_FindRelation($relationName);
3283        # Find out if the relation is a primary entity relation,
3284        # a relationship relation, or a secondary entity relation.
3285        my $entityTable = $self->{_metaData}->{Entities};
3286        my $relationshipTable = $self->{_metaData}->{Relationships};
3287        if (exists $entityTable->{$relationName}) {
3288            # Here we have a primary entity relation, so we have a unique sort on the
3289            # ID field.
3290            $unique = "-u ";
3291            push @keyNames, "id";
3292        } elsif (exists $relationshipTable->{$relationName}) {
3293            # Here we have a relationship. We sort using the FROM index.
3294            $unique = "";
3295            my $relationshipData = $relationshipTable->{$relationName};
3296            my $index = $relationData->{Indexes}->{"idx${relationName}From"};
3297            push @keyNames, @{$index->{IndexFields}};
3298        } else {
3299            # Here we have a secondary entity relation, so we have a non-unique sort on
3300            # the ID field.
3301            $unique = "";
3302            push @keyNames, "id";
3303        }
3304        # Now we parse the key names into sort parameters. First, we prime the return
3305        # string.
3306        my $retVal = "sort -t \"\t\" $unique";
3307        # Get the relation's field list.
3308        my @fields = @{$relationData->{Fields}};
3309        # Loop through the keys.
3310        for my $keyData (@keyNames) {
3311            # Get the key and the ordering.
3312            my ($keyName, $ordering);
3313            if ($keyData =~ /^([^ ]+) DESC/) {
3314                ($keyName, $ordering) = ($1, "descending");
3315            } else {
3316                ($keyName, $ordering) = ($keyData, "ascending");
3317            }
3318            # Find the key's position and type.
3319            my $fieldSpec;
3320            for (my $i = 0; $i <= $#fields && ! $fieldSpec; $i++) {
3321                my $thisField = $fields[$i];
3322                if ($thisField->{name} eq $keyName) {
3323                    # Get the sort modifier for this field type. The modifier
3324                    # decides whether we're using a character, numeric, or
3325                    # floating-point sort.
3326                    my $modifier = $TypeTable{$thisField->{type}}->{sort};
3327                    # If the index is descending for this field, denote we want
3328                    # to reverse the sort order on this field.
3329                    if ($ordering eq 'descending') {
3330                        $modifier .= "r";
3331                    }
3332                    # Store the position and modifier into the field spec, which
3333                    # will stop the inner loop.
3334                    $fieldSpec = "$i$modifier";
3335                }
3336            }
3337            # Add this field to the sort command.
3338            $retVal .= " -k $fieldSpec";
3339        }
3340        # Return the result.
3341        return $retVal;
3342    }
3343    
3344  =head3 CreateRelationshipIndex  =head3 CreateRelationshipIndex
3345    
3346  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.61

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3