[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.42, Wed Apr 19 03:34:15 2006 UTC revision 1.68, Tue Sep 19 00:12:21 2006 UTC
# Line 91  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 110  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 314  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 =>   1, 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' =>                   'hash-string' =>
335                               { sqlType => 'VARCHAR(22)',        maxLen => 22,           avgLen =>  22, dataGen => "SringGen(22)" },                               { 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 416  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 460  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 484  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 494  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 527  Line 578 
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 736  Line 785 
785          my $fieldType = $fieldTypes->[$i]->{type};          my $fieldType = $fieldTypes->[$i]->{type};
786          # If it's a hash string, digest it in place.          # If it's a hash string, digest it in place.
787          if ($fieldType eq 'hash-string') {          if ($fieldType eq 'hash-string') {
788              $fieldList->[$i] = md5_base64($fieldList->[$i]);              $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
# Line 902  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 910  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 927  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.
# Line 984  Line 1066 
1066    
1067  C<< "LIMIT 10" >>  C<< "LIMIT 10" >>
1068    
1069  =item param1, param2, ..., paramN  =item params
1070    
1071  Parameter values to be substituted into the filter clause.  Reference to a list of parameter values to be substituted into the filter clause.
1072    
1073  =item RETURN  =item RETURN
1074    
# Line 998  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      # Adjust the list of object names to account for multiple occurrences of the      # Process the SQL stuff.
1085      # same object. We start with a hash table keyed on object name that will      my ($suffix, $mappedNameListRef, $mappedNameHashRef) =
1086      # return the object suffix. The first time an object is encountered it will          $self->_SetupSQL($objectNames, $filterClause);
1087      # not be found in the hash. The next time the hash will map the object name      # Create the query.
1088      # to 2, then 3, and so forth.      my $command = "SELECT DISTINCT " . join(".*, ", @{$mappedNameListRef}) .
1089      my %objectHash = ();          ".* $suffix";
1090      # This list will contain the object names as they are to appear in the      my $sth = $self->_GetStatementHandle($command, $params);
     # FROM list.  
     my @fromList = ();  
     # This list contains the suffixed object name for each object. It is exactly  
     # parallel to the list in the $objectNames parameter.  
     my @mappedNameList = ();  
     # Finally, this hash translates from a mapped name to its original object name.  
     my %mappedNameHash = ();  
     # Now we create the lists. Note that for every single name we push something into  
     # @fromList and @mappedNameList. This insures that those two arrays are exactly  
     # parallel to $objectNames.  
     for my $objectName (@{$objectNames}) {  
         # Get the next suffix for this object.  
         my $suffix = $objectHash{$objectName};  
         if (! $suffix) {  
             # Here we are seeing the object for the first time. The object name  
             # is used as is.  
             push @mappedNameList, $objectName;  
             push @fromList, $objectName;  
             $mappedNameHash{$objectName} = $objectName;  
             # Denote the next suffix will be 2.  
             $objectHash{$objectName} = 2;  
         } else {  
             # Here we've seen the object before. We construct a new name using  
             # the suffix from the hash and update the hash.  
             my $mappedName = "$objectName$suffix";  
             $objectHash{$objectName} = $suffix + 1;  
             # The FROM list has the object name followed by the mapped name. This  
             # tells SQL it's still the same table, but we're using a different name  
             # for it to avoid confusion.  
             push @fromList, "$objectName $mappedName";  
             # The mapped-name list contains the real mapped name.  
             push @mappedNameList, $mappedName;  
             # Finally, enable us to get back from the mapped name to the object name.  
             $mappedNameHash{$mappedName} = $objectName;  
         }  
     }  
     # Construct the SELECT statement. The general pattern is  
     #  
     # SELECT name1.*, name2.*, ... nameN.* FROM name1, name2, ... nameN  
     #  
     my $dbh = $self->{_dbh};  
     my $command = "SELECT DISTINCT " . join('.*, ', @mappedNameList) . ".* FROM " .  
                 join(', ', @fromList);  
     # Check for a filter clause.  
     if ($filterClause) {  
         # Here we have one, so we convert its field names and add it to the query. First,  
         # We create a copy of the filter string we can work with.  
         my $filterString = $filterClause;  
         # 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) } @mappedNameList;  
         # 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. We may  
         # need to add relations later if there is filtering on a field in a secondary  
         # relation. The secondary relations are the ones that contain multiply-  
         # occurring or optional fields.  
         my %fromNames = map { $_ => 1 } @sortedNames;  
         # 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 $mappedName (@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 $mappedName;  
             # Get the real object name for this mapped name.  
             my $objectName = $mappedNameHash{$mappedName};  
             Trace("Processing $mappedName for object $objectName.") if T(4);  
             # Get the object's field list.  
             my $fieldList = $self->GetFieldTable($objectName);  
             # Find the field references for this object.  
             while ($filterString =~ m/$mappedName\(([^)]*)\)/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 {  
                     Trace("Processing $fieldName at position $pos.") if T(4);  
                     # Get the field's relation.  
                     my $relationName = $fieldList->{$fieldName}->{relation};  
                     # Now we have a secondary relation. We need to insure it matches the  
                     # mapped name of the primary relation. First we peel off the suffix  
                     # from the mapped name.  
                     my $mappingSuffix = substr $mappedName, length($objectName);  
                     # Put the mapping suffix onto the relation name to get the  
                     # mapped relation name.  
                     my $mappedRelationName = "$relationName$mappingSuffix";  
                     # Insure the relation is in the FROM clause.  
                     if (!exists $fromNames{$mappedRelationName}) {  
                         # Add the relation to the FROM clause.  
                         if ($mappedRelationName eq $relationName) {  
                             # The name is un-mapped, so we add it without  
                             # any frills.  
                             $command .= ", $relationName";  
                             push @joinWhere, "$objectName.id = $relationName.id";  
                         } else {  
                             # Here we have a mapping situation.  
                             $command .= ", $relationName $mappedRelationName";  
                             push @joinWhere, "$mappedRelationName.id = $mappedName.id";  
                         }  
                         # Denote we have this relation available for future fields.  
                         $fromNames{$mappedRelationName} = 1;  
                     }  
                     # Form an SQL field reference from the relation name and the field name.  
                     my $sqlReference = "$mappedRelationName." . _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 @mappedObjectList = @mappedNameList;  
         my $lastMappedObject = shift @mappedObjectList;  
         # Get the join table.  
         my $joinTable = $self->{_metaData}->{Joins};  
         # Loop through the object list.  
         for my $thisMappedObject (@mappedObjectList) {  
             # Look for a join using the real object names.  
             my $lastObject = $mappedNameHash{$lastMappedObject};  
             my $thisObject = $mappedNameHash{$thisMappedObject};  
             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 $lastMappedObject to $thisMappedObject.");  
             } else {  
                 # Get the join clause.  
                 my $unMappedJoin = $joinTable->{$joinKey};  
                 # Fix the names.  
                 $unMappedJoin =~ s/$lastObject/$lastMappedObject/;  
                 $unMappedJoin =~ s/$thisObject/$thisMappedObject/;  
                 push @joinWhere, $unMappedJoin;  
                 # Save this object as the last object for the next iteration.  
                 $lastMappedObject = $thisMappedObject;  
             }  
         }  
         # Now we need to handle the whole ORDER BY / LIMIT thing. The important part  
         # here is we want the filter clause to be empty if there's no WHERE filter.  
         # We'll put the ORDER BY / LIMIT clauses in the following variable.  
         my $orderClause = "";  
         # Locate the ORDER BY or LIMIT verbs (if any). We use a non-greedy  
         # operator so that we find the first occurrence of either verb.  
         if ($filterString =~ m/^(.*?)\s*(ORDER BY|LIMIT)/g) {  
             # Here we have an ORDER BY or LIMIT verb. Split it off of the filter string.  
             my $pos = pos $filterString;  
             $orderClause = $2 . substr($filterString, $pos);  
             $filterString = $1;  
         }  
         # Add the filter and the join clauses (if any) to the SELECT command.  
         if ($filterString) {  
             Trace("Filter string is \"$filterString\".") if T(4);  
             push @joinWhere, "($filterString)";  
         }  
         if (@joinWhere) {  
             $command .= " WHERE " . join(' AND ', @joinWhere);  
         }  
         # Add the sort or limit clause (if any) to the SELECT command.  
         if ($orderClause) {  
             $command .= " $orderClause";  
         }  
     }  
     Trace("SQL query: $command") if T(SQL => 3);  
     Trace("PARMS: '" . (join "', '", @params) . "'") if (T(SQL => 4) && (@params > 0));  
     my $sth = $dbh->prepare_command($command);  
     # Execute it with the parameters bound in.  
     $sth->execute(@params) || Confess("SELECT error" . $sth->errstr());  
1091      # Now we create the relation map, which enables DBQuery to determine the order, name      # Now we create the relation map, which enables DBQuery to determine the order, name
1092      # and mapped name for each object in the query.      # and mapped name for each object in the query.
1093      my @relationMap = ();      my @relationMap = ();
1094      for my $mappedName (@mappedNameList) {      for my $mappedName (@{$mappedNameListRef}) {
1095          push @relationMap, [$mappedName, $mappedNameHash{$mappedName}];          push @relationMap, [$mappedName, $mappedNameHashRef->{$mappedName}];
1096      }      }
1097      # Return the statement object.      # Return the statement object.
1098      my $retVal = DBQuery::_new($self, $sth, \@relationMap);      my $retVal = DBQuery::_new($self, $sth, \@relationMap);
1099      return $retVal;      return $retVal;
1100  }  }
1101    
1102  =head3 Delete  =head3 GetFlat
1103    
1104  C<< my $stats = $erdb->Delete($entityName, $objectID); >>  C<< my @list = $erdb->GetFlat(\@objectNames, $filterClause, \@parameterList, $field); >>
1105    
1106  Delete an entity instance from the database. The instance is deleted along with all entity and  This is a variation of L</GetAll> that asks for only a single field per record and
1107  relationship instances dependent on it. The idea of dependence here is recursive. An object is  returns a single flattened list.
 always dependent on itself. An object is dependent if it is a 1-to-many or many-to-many  
 relationship connected to a dependent entity or the "to" entity connected to a 1-to-many  
 dependent relationship.  
1108    
1109  =over 4  =over 4
1110    
1111  =item entityName  =item objectNames
   
 Name of the entity type for the instance being deleted.  
   
 =item objectID  
1112    
1113  ID of the entity instance to be deleted. If the ID contains a wild card character (C<%>),  List containing the names of the entity and relationship objects to be retrieved.
 then it is presumed to by a LIKE pattern.  
1114    
1115  =item testFlag  =item filterClause
1116    
1117    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 must be specified in the standard form
1119    B<I<objectName>(I<fieldName>)>. Any parameters specified in the filter clause should be added to the
1120    parameter list as additional parameters. The fields in a filter clause can come from primary
1121    entity relations, relationship relations, or secondary entity relations; however, all of the
1122    entities and relationships involved must be included in the list of object names.
1123    
1124    =item parameterList
1125    
1126    List of the parameters to be substituted in for the parameters marks in the filter clause.
1127    
1128    =item field
1129    
1130    Name of the field to be used to get the elements of the list returned.
1131    
1132    =item RETURN
1133    
1134    Returns a list of values.
1135    
1136    =back
1137    
1138    =cut
1139    #: Return Type @;
1140    sub GetFlat {
1141        # Get the parameters.
1142        my ($self, $objectNames, $filterClause, $parameterList, $field) = @_;
1143        # Construct the query.
1144        my $query = $self->Get($objectNames, $filterClause, $parameterList);
1145        # Create the result list.
1146        my @retVal = ();
1147        # Loop through the records, adding the field values found to the result list.
1148        while (my $row = $query->Fetch()) {
1149            push @retVal, $row->Value($field);
1150        }
1151        # Return the list created.
1152        return @retVal;
1153    }
1154    
1155    =head3 Delete
1156    
1157    C<< my $stats = $erdb->Delete($entityName, $objectID); >>
1158    
1159    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
1166    
1167    =item entityName
1168    
1169    Name of the entity type for the instance being deleted.
1170    
1171    =item objectID
1172    
1173    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    =item testFlag
1177    
1178  If TRUE, the delete statements will be traced without being executed.  If TRUE, the delete statements will be traced without being executed.
1179    
# Line 1366  Line 1322 
1322    
1323  =head3 GetList  =head3 GetList
1324    
1325  C<< my @dbObjects = $erdb->GetList(\@objectNames, $filterClause, $param1, $param2, ..., $paramN); >>  C<< my @dbObjects = $erdb->GetList(\@objectNames, $filterClause, \@params); >>
1326    
1327  Return a list of object descriptors for the specified objects as determined by the  Return a list of object descriptors for the specified objects as determined by the
1328  specified filter clause.  specified filter clause.
# Line 1400  Line 1356 
1356  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
1357  relation.  relation.
1358    
1359  =item param1, param2, ..., paramN  =item params
1360    
1361  Parameter values to be substituted into the filter clause.  Reference to a list of parameter values to be substituted into the filter clause.
1362    
1363  =item RETURN  =item RETURN
1364    
# Line 1414  Line 1370 
1370  #: Return Type @%  #: Return Type @%
1371  sub GetList {  sub GetList {
1372      # Get the parameters.      # Get the parameters.
1373      my ($self, $objectNames, $filterClause, @params) = @_;      my ($self, $objectNames, $filterClause, $params) = @_;
1374      # Declare the return variable.      # Declare the return variable.
1375      my @retVal = ();      my @retVal = ();
1376      # Perform the query.      # Perform the query.
1377      my $query = $self->Get($objectNames, $filterClause, @params);      my $query = $self->Get($objectNames, $filterClause, $params);
1378      # Loop through the results.      # Loop through the results.
1379      while (my $object = $query->Fetch) {      while (my $object = $query->Fetch) {
1380          push @retVal, $object;          push @retVal, $object;
# Line 1427  Line 1383 
1383      return @retVal;      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        # Insure the params argument is an array reference if the caller left it off.
1440        if (! defined($params)) {
1441            $params = [];
1442        }
1443        # Declare the return variable.
1444        my $retVal;
1445        # Find out if we're counting an entity or a relationship.
1446        my $countedField;
1447        if ($self->IsEntity($objectNames->[0])) {
1448            $countedField = "id";
1449        } else {
1450            # For a relationship we count the to-link because it's usually more
1451            # numerous. Note we're automatically converting to the SQL form
1452            # of the field name (to_link vs. to-link).
1453            $countedField = "to_link";
1454        }
1455        # Create the SQL command suffix to get the desired records.
1456        my ($suffix, $mappedNameListRef, $mappedNameHashRef) = $self->_SetupSQL($objectNames,
1457                                                                                $filter);
1458        # Prefix it with text telling it we want a record count.
1459        my $firstObject = $mappedNameListRef->[0];
1460        my $command = "SELECT COUNT($firstObject.$countedField) $suffix";
1461        # Prepare and execute the command.
1462        my $sth = $self->_GetStatementHandle($command, $params);
1463        # Get the count value.
1464        ($retVal) = $sth->fetchrow_array();
1465        # Check for a problem.
1466        if (! defined($retVal)) {
1467            if ($sth->err) {
1468                # Here we had an SQL error.
1469                Confess("Error retrieving row count: " . $sth->errstr());
1470            } else {
1471                # Here we have no result.
1472                Confess("No result attempting to retrieve row count.");
1473            }
1474        }
1475        # Return the result.
1476        return $retVal;
1477    }
1478    
1479  =head3 ComputeObjectSentence  =head3 ComputeObjectSentence
1480    
1481  C<< my $sentence = $erdb->ComputeObjectSentence($objectName); >>  C<< my $sentence = $erdb->ComputeObjectSentence($objectName); >>
# Line 1504  Line 1553 
1553      }      }
1554  }  }
1555    
1556    =head3 InsertValue
1557    
1558    C<< $erdb->InsertValue($entityID, $fieldName, $value); >>
1559    
1560    This method will insert a new value into the database. The value must be one
1561    associated with a secondary relation, since primary values cannot be inserted:
1562    they occur exactly once. Secondary values, on the other hand, can be missing
1563    or multiply-occurring.
1564    
1565    =over 4
1566    
1567    =item entityID
1568    
1569    ID of the object that is to receive the new value.
1570    
1571    =item fieldName
1572    
1573    Field name for the new value-- this includes the entity name, since
1574    field names are of the format I<objectName>C<(>I<fieldName>C<)>.
1575    
1576    =item value
1577    
1578    New value to be put in the field.
1579    
1580    =back
1581    
1582    =cut
1583    
1584    sub InsertValue {
1585        # Get the parameters.
1586        my ($self, $entityID, $fieldName, $value) = @_;
1587        # Parse the entity name and the real field name.
1588        if ($fieldName =~ /^([^(]+)\(([^)]+)\)/) {
1589            my $entityName = $1;
1590            my $fieldTitle = $2;
1591            # Get its descriptor.
1592            if (!$self->IsEntity($entityName)) {
1593                Confess("$entityName is not a valid entity.");
1594            } else {
1595                my $entityData = $self->{_metaData}->{Entities}->{$entityName};
1596                # Find the relation containing this field.
1597                my $fieldHash = $entityData->{Fields};
1598                if (! exists $fieldHash->{$fieldTitle}) {
1599                    Confess("$fieldTitle not found in $entityName.");
1600                } else {
1601                    my $relation = $fieldHash->{$fieldTitle}->{relation};
1602                    if ($relation eq $entityName) {
1603                        Confess("Cannot do InsertValue on primary field $fieldTitle of $entityName.");
1604                    } else {
1605                        # Now we can create an INSERT statement.
1606                        my $dbh = $self->{_dbh};
1607                        my $fixedName = _FixName($fieldTitle);
1608                        my $statement = "INSERT INTO $relation (id, $fixedName) VALUES(?, ?)";
1609                        # Execute the command.
1610                        $dbh->SQL($statement, 0, $entityID, $value);
1611                    }
1612                }
1613            }
1614        } else {
1615            Confess("$fieldName is not a valid field name.");
1616        }
1617    }
1618    
1619  =head3 InsertObject  =head3 InsertObject
1620    
1621  C<< my $ok = $erdb->InsertObject($objectType, \%fieldHash); >>  C<< my $ok = $erdb->InsertObject($objectType, \%fieldHash); >>
# Line 1520  Line 1632 
1632  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
1633  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>.
1634    
1635  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'}); >>
1636    
1637  =over 4  =over 4
1638    
# Line 1730  Line 1842 
1842          }          }
1843      }      }
1844      # Analyze the table to improve performance.      # Analyze the table to improve performance.
1845        Trace("Analyzing and compacting $relationName.") if T(3);
1846      $dbh->vacuum_it($relationName);      $dbh->vacuum_it($relationName);
1847        Trace("$relationName load completed.") if T(3);
1848      # Return the statistics.      # Return the statistics.
1849      return $retVal;      return $retVal;
1850  }  }
# Line 1822  Line 1936 
1936      # Get the parameters.      # Get the parameters.
1937      my ($self, $entityType, $ID) = @_;      my ($self, $entityType, $ID) = @_;
1938      # Create a query.      # Create a query.
1939      my $query = $self->Get([$entityType], "$entityType(id) = ?", $ID);      my $query = $self->Get([$entityType], "$entityType(id) = ?", [$ID]);
1940      # Get the first (and only) object.      # Get the first (and only) object.
1941      my $retVal = $query->Fetch();      my $retVal = $query->Fetch();
1942      # Return the result.      # Return the result.
# Line 1833  Line 1947 
1947    
1948  C<< my @values = $erdb->GetEntityValues($entityType, $ID, \@fields); >>  C<< my @values = $erdb->GetEntityValues($entityType, $ID, \@fields); >>
1949    
1950  Return a list of values from a specified entity instance.  Return a list of values from a specified entity instance. If the entity instance
1951    does not exist, an empty list is returned.
1952    
1953  =over 4  =over 4
1954    
# Line 1935  Line 2050 
2050      # list is a scalar we convert it into a singleton list.      # list is a scalar we convert it into a singleton list.
2051      my @parmList = ();      my @parmList = ();
2052      if (ref $parameterList eq "ARRAY") {      if (ref $parameterList eq "ARRAY") {
2053            Trace("GetAll parm list is an array.") if T(4);
2054          @parmList = @{$parameterList};          @parmList = @{$parameterList};
2055      } else {      } else {
2056            Trace("GetAll parm list is a scalar: $parameterList.") if T(4);
2057          push @parmList, $parameterList;          push @parmList, $parameterList;
2058      }      }
2059      # Insure the counter has a value.      # Insure the counter has a value.
# Line 1948  Line 2065 
2065          $filterClause .= " LIMIT $count";          $filterClause .= " LIMIT $count";
2066      }      }
2067      # Create the query.      # Create the query.
2068      my $query = $self->Get($objectNames, $filterClause, @parmList);      my $query = $self->Get($objectNames, $filterClause, \@parmList);
2069      # Set up a counter of the number of records read.      # Set up a counter of the number of records read.
2070      my $fetched = 0;      my $fetched = 0;
2071      # Loop through the records returned, extracting the fields. Note that if the      # Loop through the records returned, extracting the fields. Note that if the
# Line 1959  Line 2076 
2076          push @retVal, \@rowData;          push @retVal, \@rowData;
2077          $fetched++;          $fetched++;
2078      }      }
2079        Trace("$fetched rows returned in GetAll.") if T(SQL => 4);
2080      # Return the resulting list.      # Return the resulting list.
2081      return @retVal;      return @retVal;
2082  }  }
2083    
2084    =head3 Exists
2085    
2086    C<< my $found = $sprout->Exists($entityName, $entityID); >>
2087    
2088    Return TRUE if an entity exists, else FALSE.
2089    
2090    =over 4
2091    
2092    =item entityName
2093    
2094    Name of the entity type (e.g. C<Feature>) relevant to the existence check.
2095    
2096    =item entityID
2097    
2098    ID of the entity instance whose existence is to be checked.
2099    
2100    =item RETURN
2101    
2102    Returns TRUE if the entity instance exists, else FALSE.
2103    
2104    =back
2105    
2106    =cut
2107    #: Return Type $;
2108    sub Exists {
2109        # Get the parameters.
2110        my ($self, $entityName, $entityID) = @_;
2111        # Check for the entity instance.
2112        Trace("Checking existence of $entityName with ID=$entityID.") if T(4);
2113        my $testInstance = $self->GetEntity($entityName, $entityID);
2114        # Return an existence indicator.
2115        my $retVal = ($testInstance ? 1 : 0);
2116        return $retVal;
2117    }
2118    
2119  =head3 EstimateRowSize  =head3 EstimateRowSize
2120    
2121  C<< my $rowSize = $erdb->EstimateRowSize($relName); >>  C<< my $rowSize = $erdb->EstimateRowSize($relName); >>
# Line 2030  Line 2183 
2183      return $objectData->{Fields};      return $objectData->{Fields};
2184  }  }
2185    
2186    =head2 Data Mining Methods
2187    
2188  =head3 GetUsefulCrossValues  =head3 GetUsefulCrossValues
2189    
2190  C<< my @attrNames = $sprout->GetUsefulCrossValues($sourceEntity, $relationship); >>  C<< my @attrNames = $sprout->GetUsefulCrossValues($sourceEntity, $relationship); >>
# Line 2091  Line 2246 
2246      return @retVal;      return @retVal;
2247  }  }
2248    
2249    =head3 FindColumn
2250    
2251    C<< my $colIndex = ERDB::FindColumn($headerLine, $columnIdentifier); >>
2252    
2253    Return the location a desired column in a data mining header line. The data
2254    mining header line is a tab-separated list of column names. The column
2255    identifier is either the numerical index of a column or the actual column
2256    name.
2257    
2258    =over 4
2259    
2260    =item headerLine
2261    
2262    The header line from a data mining command, which consists of a tab-separated
2263    list of column names.
2264    
2265    =item columnIdentifier
2266    
2267    Either the ordinal number of the desired column (1-based), or the name of the
2268    desired column.
2269    
2270    =item RETURN
2271    
2272    Returns the array index (0-based) of the desired column.
2273    
2274    =back
2275    
2276    =cut
2277    
2278    sub FindColumn {
2279        # Get the parameters.
2280        my ($headerLine, $columnIdentifier) = @_;
2281        # Declare the return variable.
2282        my $retVal;
2283        # Split the header line into column names.
2284        my @headers = ParseColumns($headerLine);
2285        # Determine whether we have a number or a name.
2286        if ($columnIdentifier =~ /^\d+$/) {
2287            # Here we have a number. Subtract 1 and validate the result.
2288            $retVal = $columnIdentifier - 1;
2289            if ($retVal < 0 || $retVal > $#headers) {
2290                Confess("Invalid column identifer \"$columnIdentifier\": value out of range.");
2291            }
2292        } else {
2293            # Here we have a name. We need to find it in the list.
2294            for (my $i = 0; $i <= $#headers && ! defined($retVal); $i++) {
2295                if ($headers[$i] eq $columnIdentifier) {
2296                    $retVal = $i;
2297                }
2298            }
2299            if (! defined($retVal)) {
2300                Confess("Invalid column identifier \"$columnIdentifier\": value not found.");
2301            }
2302        }
2303        # Return the result.
2304        return $retVal;
2305    }
2306    
2307    =head3 ParseColumns
2308    
2309    C<< my @columns = ERDB::ParseColumns($line); >>
2310    
2311    Convert the specified data line to a list of columns.
2312    
2313    =over 4
2314    
2315    =item line
2316    
2317    A data mining input, consisting of a tab-separated list of columns terminated by a
2318    new-line.
2319    
2320    =item RETURN
2321    
2322    Returns a list consisting of the column values.
2323    
2324    =back
2325    
2326    =cut
2327    
2328    sub ParseColumns {
2329        # Get the parameters.
2330        my ($line) = @_;
2331        # Chop off the line-end.
2332        chomp $line;
2333        # Split it into a list.
2334        my @retVal = split(/\t/, $line);
2335        # Return the result.
2336        return @retVal;
2337    }
2338    
2339  =head2 Internal Utility Methods  =head2 Internal Utility Methods
2340    
2341    =head3 SetupSQL
2342    
2343    Process a list of object names and a filter clause so that they can be used to
2344    build an SQL statement. This method takes in a reference to a list of object names
2345    and a filter clause. It will return a corrected filter clause, a list of mapped
2346    names and the mapped name hash.
2347    
2348    This is an instance method.
2349    
2350    =over 4
2351    
2352    =item objectNames
2353    
2354    Reference to a list of the object names to be included in the query.
2355    
2356    =item filterClause
2357    
2358    A string containing the WHERE clause for the query (without the C<WHERE>) and also
2359    optionally the C<ORDER BY> and C<LIMIT> clauses.
2360    
2361    =item RETURN
2362    
2363    Returns a three-element list. The first element is the SQL statement suffix, beginning
2364    with the FROM clause. The second element is a reference to a list of the names to be
2365    used in retrieving the fields. The third element is a hash mapping the names to the
2366    objects they represent.
2367    
2368    =back
2369    
2370    =cut
2371    
2372    sub _SetupSQL {
2373        my ($self, $objectNames, $filterClause) = @_;
2374        # Adjust the list of object names to account for multiple occurrences of the
2375        # same object. We start with a hash table keyed on object name that will
2376        # return the object suffix. The first time an object is encountered it will
2377        # not be found in the hash. The next time the hash will map the object name
2378        # to 2, then 3, and so forth.
2379        my %objectHash = ();
2380        # This list will contain the object names as they are to appear in the
2381        # FROM list.
2382        my @fromList = ();
2383        # This list contains the suffixed object name for each object. It is exactly
2384        # parallel to the list in the $objectNames parameter.
2385        my @mappedNameList = ();
2386        # Finally, this hash translates from a mapped name to its original object name.
2387        my %mappedNameHash = ();
2388        # Now we create the lists. Note that for every single name we push something into
2389        # @fromList and @mappedNameList. This insures that those two arrays are exactly
2390        # parallel to $objectNames.
2391        for my $objectName (@{$objectNames}) {
2392            # Get the next suffix for this object.
2393            my $suffix = $objectHash{$objectName};
2394            if (! $suffix) {
2395                # Here we are seeing the object for the first time. The object name
2396                # is used as is.
2397                push @mappedNameList, $objectName;
2398                push @fromList, $objectName;
2399                $mappedNameHash{$objectName} = $objectName;
2400                # Denote the next suffix will be 2.
2401                $objectHash{$objectName} = 2;
2402            } else {
2403                # Here we've seen the object before. We construct a new name using
2404                # the suffix from the hash and update the hash.
2405                my $mappedName = "$objectName$suffix";
2406                $objectHash{$objectName} = $suffix + 1;
2407                # The FROM list has the object name followed by the mapped name. This
2408                # tells SQL it's still the same table, but we're using a different name
2409                # for it to avoid confusion.
2410                push @fromList, "$objectName $mappedName";
2411                # The mapped-name list contains the real mapped name.
2412                push @mappedNameList, $mappedName;
2413                # Finally, enable us to get back from the mapped name to the object name.
2414                $mappedNameHash{$mappedName} = $objectName;
2415            }
2416        }
2417        # Begin the SELECT suffix. It starts with
2418        #
2419        # FROM name1, name2, ... nameN
2420        #
2421        my $suffix = "FROM " . join(', ', @fromList);
2422        # Check for a filter clause.
2423        if ($filterClause) {
2424            # Here we have one, so we convert its field names and add it to the query. First,
2425            # We create a copy of the filter string we can work with.
2426            my $filterString = $filterClause;
2427            # Next, we sort the object names by length. This helps protect us from finding
2428            # object names inside other object names when we're doing our search and replace.
2429            my @sortedNames = sort { length($b) - length($a) } @mappedNameList;
2430            # We will also keep a list of conditions to add to the WHERE clause in order to link
2431            # entities and relationships as well as primary relations to secondary ones.
2432            my @joinWhere = ();
2433            # The final preparatory step is to create a hash table of relation names. The
2434            # table begins with the relation names already in the SELECT command. We may
2435            # need to add relations later if there is filtering on a field in a secondary
2436            # relation. The secondary relations are the ones that contain multiply-
2437            # occurring or optional fields.
2438            my %fromNames = map { $_ => 1 } @sortedNames;
2439            # We are ready to begin. We loop through the object names, replacing each
2440            # object name's field references by the corresponding SQL field reference.
2441            # Along the way, if we find a secondary relation, we will need to add it
2442            # to the FROM clause.
2443            for my $mappedName (@sortedNames) {
2444                # Get the length of the object name plus 2. This is the value we add to the
2445                # size of the field name to determine the size of the field reference as a
2446                # whole.
2447                my $nameLength = 2 + length $mappedName;
2448                # Get the real object name for this mapped name.
2449                my $objectName = $mappedNameHash{$mappedName};
2450                Trace("Processing $mappedName for object $objectName.") if T(4);
2451                # Get the object's field list.
2452                my $fieldList = $self->GetFieldTable($objectName);
2453                # Find the field references for this object.
2454                while ($filterString =~ m/$mappedName\(([^)]*)\)/g) {
2455                    # At this point, $1 contains the field name, and the current position
2456                    # is set immediately after the final parenthesis. We pull out the name of
2457                    # the field and the position and length of the field reference as a whole.
2458                    my $fieldName = $1;
2459                    my $len = $nameLength + length $fieldName;
2460                    my $pos = pos($filterString) - $len;
2461                    # Insure the field exists.
2462                    if (!exists $fieldList->{$fieldName}) {
2463                        Confess("Field $fieldName not found for object $objectName.");
2464                    } else {
2465                        Trace("Processing $fieldName at position $pos.") if T(4);
2466                        # Get the field's relation.
2467                        my $relationName = $fieldList->{$fieldName}->{relation};
2468                        # Now we have a secondary relation. We need to insure it matches the
2469                        # mapped name of the primary relation. First we peel off the suffix
2470                        # from the mapped name.
2471                        my $mappingSuffix = substr $mappedName, length($objectName);
2472                        # Put the mapping suffix onto the relation name to get the
2473                        # mapped relation name.
2474                        my $mappedRelationName = "$relationName$mappingSuffix";
2475                        # Insure the relation is in the FROM clause.
2476                        if (!exists $fromNames{$mappedRelationName}) {
2477                            # Add the relation to the FROM clause.
2478                            if ($mappedRelationName eq $relationName) {
2479                                # The name is un-mapped, so we add it without
2480                                # any frills.
2481                                $suffix .= ", $relationName";
2482                                push @joinWhere, "$objectName.id = $relationName.id";
2483                            } else {
2484                                # Here we have a mapping situation.
2485                                $suffix .= ", $relationName $mappedRelationName";
2486                                push @joinWhere, "$mappedRelationName.id = $mappedName.id";
2487                            }
2488                            # Denote we have this relation available for future fields.
2489                            $fromNames{$mappedRelationName} = 1;
2490                        }
2491                        # Form an SQL field reference from the relation name and the field name.
2492                        my $sqlReference = "$mappedRelationName." . _FixName($fieldName);
2493                        # Put it into the filter string in place of the old value.
2494                        substr($filterString, $pos, $len) = $sqlReference;
2495                        # Reposition the search.
2496                        pos $filterString = $pos + length $sqlReference;
2497                    }
2498                }
2499            }
2500            # The next step is to join the objects together. We only need to do this if there
2501            # is more than one object in the object list. We start with the first object and
2502            # run through the objects after it. Note also that we make a safety copy of the
2503            # list before running through it.
2504            my @mappedObjectList = @mappedNameList;
2505            my $lastMappedObject = shift @mappedObjectList;
2506            # Get the join table.
2507            my $joinTable = $self->{_metaData}->{Joins};
2508            # Loop through the object list.
2509            for my $thisMappedObject (@mappedObjectList) {
2510                # Look for a join using the real object names.
2511                my $lastObject = $mappedNameHash{$lastMappedObject};
2512                my $thisObject = $mappedNameHash{$thisMappedObject};
2513                my $joinKey = "$lastObject/$thisObject";
2514                if (!exists $joinTable->{$joinKey}) {
2515                    # Here there's no join, so we throw an error.
2516                    Confess("No join exists to connect from $lastMappedObject to $thisMappedObject.");
2517                } else {
2518                    # Get the join clause.
2519                    my $unMappedJoin = $joinTable->{$joinKey};
2520                    # Fix the names.
2521                    $unMappedJoin =~ s/$lastObject/$lastMappedObject/;
2522                    $unMappedJoin =~ s/$thisObject/$thisMappedObject/;
2523                    push @joinWhere, $unMappedJoin;
2524                    # Save this object as the last object for the next iteration.
2525                    $lastMappedObject = $thisMappedObject;
2526                }
2527            }
2528            # Now we need to handle the whole ORDER BY / LIMIT thing. The important part
2529            # here is we want the filter clause to be empty if there's no WHERE filter.
2530            # We'll put the ORDER BY / LIMIT clauses in the following variable.
2531            my $orderClause = "";
2532            # Locate the ORDER BY or LIMIT verbs (if any). We use a non-greedy
2533            # operator so that we find the first occurrence of either verb.
2534            if ($filterString =~ m/^(.*?)\s*(ORDER BY|LIMIT)/g) {
2535                # Here we have an ORDER BY or LIMIT verb. Split it off of the filter string.
2536                my $pos = pos $filterString;
2537                $orderClause = $2 . substr($filterString, $pos);
2538                $filterString = $1;
2539            }
2540            # Add the filter and the join clauses (if any) to the SELECT command.
2541            if ($filterString) {
2542                Trace("Filter string is \"$filterString\".") if T(4);
2543                push @joinWhere, "($filterString)";
2544            }
2545            if (@joinWhere) {
2546                $suffix .= " WHERE " . join(' AND ', @joinWhere);
2547            }
2548            # Add the sort or limit clause (if any) to the SELECT command.
2549            if ($orderClause) {
2550                $suffix .= " $orderClause";
2551            }
2552        }
2553        # Return the suffix, the mapped name list, and the mapped name hash.
2554        return ($suffix, \@mappedNameList, \%mappedNameHash);
2555    }
2556    
2557    =head3 GetStatementHandle
2558    
2559    This method will prepare and execute an SQL query, returning the statement handle.
2560    The main reason for doing this here is so that everybody who does SQL queries gets
2561    the benefit of tracing.
2562    
2563    This is an instance method.
2564    
2565    =over 4
2566    
2567    =item command
2568    
2569    Command to prepare and execute.
2570    
2571    =item params
2572    
2573    Reference to a list of the values to be substituted in for the parameter marks.
2574    
2575    =item RETURN
2576    
2577    Returns a prepared and executed statement handle from which the caller can extract
2578    results.
2579    
2580    =back
2581    
2582    =cut
2583    
2584    sub _GetStatementHandle {
2585        # Get the parameters.
2586        my ($self, $command, $params) = @_;
2587        # Trace the query.
2588        Trace("SQL query: $command") if T(SQL => 3);
2589        Trace("PARMS: '" . (join "', '", @{$params}) . "'") if (T(SQL => 4) && (@{$params} > 0));
2590        # Get the database handle.
2591        my $dbh = $self->{_dbh};
2592        # Prepare the command.
2593        my $sth = $dbh->prepare_command($command);
2594        # Execute it with the parameters bound in.
2595        $sth->execute(@{$params}) || Confess("SELECT error" . $sth->errstr());
2596        # Return the statement handle.
2597        return $sth;
2598    }
2599    
2600  =head3 GetLoadStats  =head3 GetLoadStats
2601    
2602  Return a blank statistics object for use by the load methods.  Return a blank statistics object for use by the load methods.
# Line 2741  Line 3245 
3245    
3246  =head3 SortNeeded  =head3 SortNeeded
3247    
3248  C<< my $flag = $erdb->SortNeeded($relationName); >>  C<< my $parms = $erdb->SortNeeded($relationName); >>
3249    
3250    Return the pipe command for the sort that should be applied to the specified
3251    relation when creating the load file.
3252    
3253    For example, if the load file should be sorted ascending by the first
3254    field, this method would return
3255    
3256        sort -k1 -t"\t"
3257    
3258    If the first field is numeric, the method would return
3259    
3260  Return TRUE if the specified relation should be sorted during loading to remove duplicate keys,      sort -k1n -t"\t"
3261  else FALSE.  
3262    Unfortunately, due to a bug in the C<sort> command, we cannot eliminate duplicate
3263    keys using a sort.
3264    
3265  =over 4  =over 4
3266    
# Line 2752  Line 3268 
3268    
3269  Name of the relation to be examined.  Name of the relation to be examined.
3270    
3271  =item RETURN  =item
3272    
3273  Returns TRUE if the relation needs a sort, else FALSE.  Returns the sort command to use for sorting the relation, suitable for piping.
3274    
3275  =back  =back
3276    
# Line 2763  Line 3279 
3279  sub SortNeeded {  sub SortNeeded {
3280      # Get the parameters.      # Get the parameters.
3281      my ($self, $relationName) = @_;      my ($self, $relationName) = @_;
3282      # Declare the return variable.      # Declare a descriptor to hold the names of the key fields.
3283      my $retVal = 0;      my @keyNames = ();
3284      # Find out if the relation is a primary entity relation.      # Get the relation structure.
3285      my $entityTable = $self->{Entities};      my $relationData = $self->_FindRelation($relationName);
3286        # Find out if the relation is a primary entity relation,
3287        # a relationship relation, or a secondary entity relation.
3288        my $entityTable = $self->{_metaData}->{Entities};
3289        my $relationshipTable = $self->{_metaData}->{Relationships};
3290      if (exists $entityTable->{$relationName}) {      if (exists $entityTable->{$relationName}) {
3291          my $keyType = $entityTable->{$relationName}->{keyType};          # Here we have a primary entity relation.
3292          # If the key is not a hash string, we must do the sort.          push @keyNames, "id";
3293          if ($keyType ne 'hash-string') {      } elsif (exists $relationshipTable->{$relationName}) {
3294              $retVal = 1;          # Here we have a relationship. We sort using the FROM index.
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 sort on the ID field.
3300            push @keyNames, "id";
3301        }
3302        # Now we parse the key names into sort parameters. First, we prime the return
3303        # string.
3304        my $retVal = "sort -t\"\t\" ";
3305        # Get the relation's field list.
3306        my @fields = @{$relationData->{Fields}};
3307        # Loop through the keys.
3308        for my $keyData (@keyNames) {
3309            # Get the key and the ordering.
3310            my ($keyName, $ordering);
3311            if ($keyData =~ /^([^ ]+) DESC/) {
3312                ($keyName, $ordering) = ($1, "descending");
3313            } else {
3314                ($keyName, $ordering) = ($keyData, "ascending");
3315            }
3316            # Find the key's position and type.
3317            my $fieldSpec;
3318            for (my $i = 0; $i <= $#fields && ! $fieldSpec; $i++) {
3319                my $thisField = $fields[$i];
3320                if ($thisField->{name} eq $keyName) {
3321                    # Get the sort modifier for this field type. The modifier
3322                    # decides whether we're using a character, numeric, or
3323                    # floating-point sort.
3324                    my $modifier = $TypeTable{$thisField->{type}}->{sort};
3325                    # If the index is descending for this field, denote we want
3326                    # to reverse the sort order on this field.
3327                    if ($ordering eq 'descending') {
3328                        $modifier .= "r";
3329                    }
3330                    # Store the position and modifier into the field spec, which
3331                    # will stop the inner loop. Note that the field number is
3332                    # 1-based in the sort command, so we have to increment the
3333                    # index.
3334                    $fieldSpec = ($i + 1) . $modifier;
3335                }
3336          }          }
3337            # Add this field to the sort command.
3338            $retVal .= " -k$fieldSpec";
3339      }      }
3340      # Return the result.      # Return the result.
3341      return $retVal;      return $retVal;

Legend:
Removed from v.1.42  
changed lines
  Added in v.1.68

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3