[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.38, Fri Mar 17 22:02:03 2006 UTC revision 1.72, Mon Oct 16 07:44:41 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 170  Line 190 
190    
191  Name of the field. The field name should contain only letters, digits, and hyphens (C<->),  Name of the field. The field name should contain only letters, digits, and hyphens (C<->),
192  and the first character should be a letter. Most underlying databases are case-insensitive  and the first character should be a letter. Most underlying databases are case-insensitive
193  with the respect to field names, so a best practice is to use lower-case letters only.  with the respect to field names, so a best practice is to use lower-case letters only. Finally,
194    the name C<search-relevance> has special meaning for full-text searches and should not be
195    used as a field name.
196    
197  =item type  =item type
198    
# Line 189  Line 211 
211  entity, the fields without a relation attribute are said to belong to the  entity, the fields without a relation attribute are said to belong to the
212  I<primary relation>. This relation has the same name as the entity itself.  I<primary relation>. This relation has the same name as the entity itself.
213    
214    =item searchable
215    
216    If specified, then the field is a candidate for full-text searching. A single full-text
217    index will be created for each relation with at least one searchable field in it.
218    For best results, this option should only be used for string or text fields.
219    
220  =back  =back
221    
222  =head3 Indexes  =head3 Indexes
# Line 302  Line 330 
330  # "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
331  # 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
332  # 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
333  # record sizes.  # record sizes. "sort" is the key modifier for the sort command.
334  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')" },
335                    int =>     { sqlType => 'INTEGER',            maxLen => 20,           avgLen =>   4, dataGen => "IntGen(0, 99999999)" },                    int =>     { sqlType => 'INTEGER',            maxLen => 20,           avgLen =>   4, sort => "n", dataGen => "IntGen(0, 99999999)" },
336                    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)" },
337                    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))" },
338                    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))" },
339                    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))" },
340                    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)" },
341                      boolean => { sqlType => 'SMALLINT',           maxLen => 1,            avgLen =>   1, sort => "n", dataGen => "IntGen(0, 1)" },
342                     'hash-string' =>
343                                 { sqlType => 'VARCHAR(22)',        maxLen => 22,           avgLen =>  22, sort => "",  dataGen => "SringGen(22)" },
344                     'id-string' =>
345                                 { sqlType => 'VARCHAR(25)',        maxLen => 25,           avgLen =>  25, sort => "",  dataGen => "SringGen(22)" },
346                   'key-string' =>                   'key-string' =>
347                               { 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))" },
348                   'name-string' =>                   'name-string' =>
349                               { 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))" },
350                   'medium-string' =>                   'medium-string' =>
351                               { 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))" },
352                  );                  );
353    
354  # Table translating arities into natural language.  # Table translating arities into natural language.
# Line 402  Line 435 
435      # Write the HTML heading stuff.      # Write the HTML heading stuff.
436      print HTMLOUT "<html>\n<head>\n<title>$title</title>\n";      print HTMLOUT "<html>\n<head>\n<title>$title</title>\n";
437      print HTMLOUT "</head>\n<body>\n";      print HTMLOUT "</head>\n<body>\n";
438        # Write the documentation.
439        print HTMLOUT $self->DisplayMetaData();
440        # Close the document.
441        print HTMLOUT "</body>\n</html>\n";
442        # Close the file.
443        close HTMLOUT;
444    }
445    
446    =head3 DisplayMetaData
447    
448    C<< my $html = $erdb->DisplayMetaData(); >>
449    
450    Return an HTML description of the database. This description can be used to help users create
451    the data to be loaded into the relations and form queries. The output is raw includable HTML
452    without any HEAD or BODY tags.
453    
454    =over 4
455    
456    =item filename
457    
458    The name of the output file.
459    
460    =back
461    
462    =cut
463    
464    sub DisplayMetaData {
465        # Get the parameters.
466        my ($self) = @_;
467        # Get the metadata and the title string.
468        my $metadata = $self->{_metaData};
469        # Get the title string.
470        my $title = $metadata->{Title};
471        # Get the entity and relationship lists.
472        my $entityList = $metadata->{Entities};
473        my $relationshipList = $metadata->{Relationships};
474        # Declare the return variable.
475        my $retVal = "";
476        # Open the output file.
477        Trace("Building MetaData table of contents.") if T(4);
478      # 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
479      # section contains an ordered list of entity or relationship subsections.      # section contains an ordered list of entity or relationship subsections.
480      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";
481      # Loop through the Entities, displaying a list item for each.      # Loop through the Entities, displaying a list item for each.
482      foreach my $key (sort keys %{$entityList}) {      foreach my $key (sort keys %{$entityList}) {
483          # Display this item.          # Display this item.
484          print HTMLOUT "<li><a href=\"#$key\">$key</a></li>\n";          $retVal .= "<li><a href=\"#$key\">$key</a></li>\n";
485      }      }
486      # Close off the entity section and start the relationship section.      # Close off the entity section and start the relationship section.
487      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";
488      # Loop through the Relationships.      # Loop through the Relationships.
489      foreach my $key (sort keys %{$relationshipList}) {      foreach my $key (sort keys %{$relationshipList}) {
490          # Display this item.          # Display this item.
491          my $relationshipTitle = _ComputeRelationshipSentence($key, $relationshipList->{$key});          my $relationshipTitle = _ComputeRelationshipSentence($key, $relationshipList->{$key});
492          print HTMLOUT "<li><a href=\"#$key\">$relationshipTitle</a></li>\n";          $retVal .= "<li><a href=\"#$key\">$relationshipTitle</a></li>\n";
493      }      }
494      # Close off the relationship section and list the join table section.      # Close off the relationship section and list the join table section.
495      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";
496      # Close off the table of contents itself.      # Close off the table of contents itself.
497      print HTMLOUT "</ul>\n";      $retVal .=  "</ul>\n";
498      # 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.
499      print HTMLOUT "<a name=\"EntitiesSection\"></a><h2>Entities</h2>\n";      $retVal .= "<a name=\"EntitiesSection\"></a><h2>Entities</h2>\n";
500      # Loop through the entities.      # Loop through the entities.
501      for my $key (sort keys %{$entityList}) {      for my $key (sort keys %{$entityList}) {
502          Trace("Building MetaData entry for $key entity.") if T(4);          Trace("Building MetaData entry for $key entity.") if T(4);
503          # Create the entity header. It contains a bookmark and the entity name.          # Create the entity header. It contains a bookmark and the entity name.
504          print HTMLOUT "<a name=\"$key\"></a><h3>$key</h3>\n";          $retVal .= "<a name=\"$key\"></a><h3>$key</h3>\n";
505          # Get the entity data.          # Get the entity data.
506          my $entityData = $entityList->{$key};          my $entityData = $entityList->{$key};
507          # If there's descriptive text, display it.          # If there's descriptive text, display it.
508          if (my $notes = $entityData->{Notes}) {          if (my $notes = $entityData->{Notes}) {
509              print HTMLOUT "<p>" . _HTMLNote($notes->{content}) . "</p>\n";              $retVal .= "<p>" . _HTMLNote($notes->{content}) . "</p>\n";
510          }          }
511          # 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.
512          print HTMLOUT "<h4>Relationships for <b>$key</b></h4>\n<ul>\n";          $retVal .= "<h4>Relationships for <b>$key</b></h4>\n<ul>\n";
513          # Loop through the relationships.          # Loop through the relationships.
514          for my $relationship (sort keys %{$relationshipList}) {          for my $relationship (sort keys %{$relationshipList}) {
515              # Get the relationship data.              # Get the relationship data.
# Line 446  Line 519 
519                  # Get the relationship sentence and append the arity.                  # Get the relationship sentence and append the arity.
520                  my $relationshipDescription = _ComputeRelationshipSentence($relationship, $relationshipStructure);                  my $relationshipDescription = _ComputeRelationshipSentence($relationship, $relationshipStructure);
521                  # Display the relationship data.                  # Display the relationship data.
522                  print HTMLOUT "<li><a href=\"#$relationship\">$relationshipDescription</a></li>\n";                  $retVal .= "<li><a href=\"#$relationship\">$relationshipDescription</a></li>\n";
523              }              }
524          }          }
525          # Close off the relationship list.          # Close off the relationship list.
526          print HTMLOUT "</ul>\n";          $retVal .= "</ul>\n";
527          # Get the entity's relations.          # Get the entity's relations.
528          my $relationList = $entityData->{Relations};          my $relationList = $entityData->{Relations};
529          # Create a header for the relation subsection.          # Create a header for the relation subsection.
530          print HTMLOUT "<h4>Relations for <b>$key</b></h4>\n";          $retVal .= "<h4>Relations for <b>$key</b></h4>\n";
531          # Loop through the relations, displaying them.          # Loop through the relations, displaying them.
532          for my $relation (sort keys %{$relationList}) {          for my $relation (sort keys %{$relationList}) {
533              my $htmlString = _ShowRelationTable($relation, $relationList->{$relation});              my $htmlString = _ShowRelationTable($relation, $relationList->{$relation});
534              print HTMLOUT $htmlString;              $retVal .= $htmlString;
535          }          }
536      }      }
537      # Denote we're starting the relationship section.      # Denote we're starting the relationship section.
538      print HTMLOUT "<a name=\"RelationshipsSection\"></a><h2>Relationships</h2>\n";      $retVal .= "<a name=\"RelationshipsSection\"></a><h2>Relationships</h2>\n";
539      # Loop through the relationships.      # Loop through the relationships.
540      for my $key (sort keys %{$relationshipList}) {      for my $key (sort keys %{$relationshipList}) {
541          Trace("Building MetaData entry for $key relationship.") if T(4);          Trace("Building MetaData entry for $key relationship.") if T(4);
# Line 470  Line 543 
543          my $relationshipStructure = $relationshipList->{$key};          my $relationshipStructure = $relationshipList->{$key};
544          # Create the relationship header.          # Create the relationship header.
545          my $headerText = _ComputeRelationshipHeading($key, $relationshipStructure);          my $headerText = _ComputeRelationshipHeading($key, $relationshipStructure);
546          print HTMLOUT "<h3><a name=\"$key\"></a>$headerText</h3>\n";          $retVal .= "<h3><a name=\"$key\"></a>$headerText</h3>\n";
547          # Get the entity names.          # Get the entity names.
548          my $fromEntity = $relationshipStructure->{from};          my $fromEntity = $relationshipStructure->{from};
549          my $toEntity = $relationshipStructure->{to};          my $toEntity = $relationshipStructure->{to};
# Line 480  Line 553 
553          # since both sentences will say the same thing.          # since both sentences will say the same thing.
554          my $arity = $relationshipStructure->{arity};          my $arity = $relationshipStructure->{arity};
555          if ($arity eq "11") {          if ($arity eq "11") {
556              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";
557          } else {          } else {
558              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";
559              if ($arity eq "MM" && $fromEntity ne $toEntity) {              if ($arity eq "MM" && $fromEntity ne $toEntity) {
560                  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";
561              }              }
562          }          }
563          print HTMLOUT "</p>\n";          $retVal .= "</p>\n";
564          # If there are notes on this relationship, display them.          # If there are notes on this relationship, display them.
565          if (my $notes = $relationshipStructure->{Notes}) {          if (my $notes = $relationshipStructure->{Notes}) {
566              print HTMLOUT "<p>" . _HTMLNote($notes->{content}) . "</p>\n";              $retVal .= "<p>" . _HTMLNote($notes->{content}) . "</p>\n";
567          }          }
568          # Generate the relationship's relation table.          # Generate the relationship's relation table.
569          my $htmlString = _ShowRelationTable($key, $relationshipStructure->{Relations}->{$key});          my $htmlString = _ShowRelationTable($key, $relationshipStructure->{Relations}->{$key});
570          print HTMLOUT $htmlString;          $retVal .= $htmlString;
571      }      }
572      Trace("Building MetaData join table.") if T(4);      Trace("Building MetaData join table.") if T(4);
573      # Denote we're starting the join table.      # Denote we're starting the join table.
574      print HTMLOUT "<a name=\"JoinTable\"></a><h3>Join Table</h3>\n";      $retVal .= "<a name=\"JoinTable\"></a><h3>Join Table</h3>\n";
575      # Create a table header.      # Create a table header.
576      print HTMLOUT _OpenTable("Join Table", "Source", "Target", "Join Condition");      $retVal .= _OpenTable("Join Table", "Source", "Target", "Join Condition");
577      # Loop through the joins.      # Loop through the joins.
578      my $joinTable = $metadata->{Joins};      my $joinTable = $metadata->{Joins};
579      my @joinKeys = keys %{$joinTable};      my @joinKeys = keys %{$joinTable};
# Line 513  Line 586 
586          my $target = $self->ComputeObjectSentence($targetRelation);          my $target = $self->ComputeObjectSentence($targetRelation);
587          my $clause = $joinTable->{$joinKey};          my $clause = $joinTable->{$joinKey};
588          # Display them in a table row.          # Display them in a table row.
589          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";
590      }      }
591      # Close the table.      # Close the table.
592      print HTMLOUT _CloseTable();      $retVal .= _CloseTable();
593      # Close the document.      Trace("Built MetaData HTML.") if T(3);
594      print HTMLOUT "</body>\n</html>\n";      # Return the HTML.
595      # Close the file.      return $retVal;
     close HTMLOUT;  
     Trace("Built MetaData web page.") if T(3);  
596  }  }
597    
598  =head3 DumpMetaData  =head3 DumpMetaData
# Line 626  Line 697 
697      Trace("Creating table $relationName: $fieldThing") if T(2);      Trace("Creating table $relationName: $fieldThing") if T(2);
698      $dbh->create_table(tbl => $relationName, flds => $fieldThing, estimates => $estimation);      $dbh->create_table(tbl => $relationName, flds => $fieldThing, estimates => $estimation);
699      Trace("Relation $relationName created in database.") if T(2);      Trace("Relation $relationName created in database.") if T(2);
700      # If we want to build the indexes, we do it here.      # If we want to build the indexes, we do it here. Note that the full-text search
701        # index will not be built until the table has been loaded.
702      if ($indexFlag) {      if ($indexFlag) {
703          $self->CreateIndex($relationName);          $self->CreateIndex($relationName);
704      }      }
# Line 687  Line 759 
759      return $retVal;      return $retVal;
760  }  }
761    
762    =head3 DigestFields
763    
764    C<< $erdb->DigestFields($relName, $fieldList); >>
765    
766    Digest the strings in the field list that correspond to data type C<hash-string> in the
767    specified relation.
768    
769    =over 4
770    
771    =item relName
772    
773    Name of the relation to which the fields belong.
774    
775    =item fieldList
776    
777    List of field contents to be loaded into the relation.
778    
779    =back
780    
781    =cut
782    #: Return Type ;
783    sub DigestFields {
784        # Get the parameters.
785        my ($self, $relName, $fieldList) = @_;
786        # Get the relation definition.
787        my $relData = $self->_FindRelation($relName);
788        # Get the list of field descriptors.
789        my $fieldTypes = $relData->{Fields};
790        my $fieldCount = scalar @{$fieldTypes};
791        # Loop through the two lists.
792        for (my $i = 0; $i < $fieldCount; $i++) {
793            # Get the type of the current field.
794            my $fieldType = $fieldTypes->[$i]->{type};
795            # If it's a hash string, digest it in place.
796            if ($fieldType eq 'hash-string') {
797                $fieldList->[$i] = $self->DigestKey($fieldList->[$i]);
798            }
799        }
800    }
801    
802    =head3 DigestKey
803    
804    C<< my $digested = $erdb->DigestKey($keyValue); >>
805    
806    Return the digested value of a symbolic key. The digested value can then be plugged into a
807    key-based search into a table with key-type hash-string.
808    
809    Currently the digesting process is independent of the database structure, but that may not
810    always be the case, so this is an instance method instead of a static method.
811    
812    =over 4
813    
814    =item keyValue
815    
816    Key value to digest.
817    
818    =item RETURN
819    
820    Digested value of the key.
821    
822    =back
823    
824    =cut
825    
826    sub DigestKey {
827        # Get the parameters.
828        my ($self, $keyValue) = @_;
829        # Compute the digest.
830        my $retVal = md5_base64($keyValue);
831        # Return the result.
832        return $retVal;
833    }
834    
835  =head3 CreateIndex  =head3 CreateIndex
836    
837  C<< $erdb->CreateIndex($relationName); >>  C<< $erdb->CreateIndex($relationName); >>
# Line 713  Line 858 
858          my @fieldList = _FixNames(@{$indexData->{IndexFields}});          my @fieldList = _FixNames(@{$indexData->{IndexFields}});
859          my $flds = join(', ', @fieldList);          my $flds = join(', ', @fieldList);
860          # Get the index's uniqueness flag.          # Get the index's uniqueness flag.
861          my $unique = (exists $indexData->{Unique} ? $indexData->{Unique} : 'false');          my $unique = (exists $indexData->{Unique} ? 'unique' : undef);
862          # Create the index.          # Create the index.
863          my $rv = $dbh->create_index(idx => $indexName, tbl => $relationName,          my $rv = $dbh->create_index(idx => $indexName, tbl => $relationName,
864                                      flds => $flds, unique => $unique);                                      flds => $flds, kind => $unique);
865          if ($rv) {          if ($rv) {
866              Trace("Index created: $indexName for $relationName ($flds)") if T(1);              Trace("Index created: $indexName for $relationName ($flds)") if T(1);
867          } else {          } else {
# Line 848  Line 993 
993    
994  =head3 Get  =head3 Get
995    
996  C<< my $query = $erdb->Get(\@objectNames, $filterClause, $param1, $param2, ..., $paramN); >>  C<< my $query = $erdb->Get(\@objectNames, $filterClause, \@params); >>
997    
998  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.
999  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 856  Line 1001 
1001  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
1002  $genus.  $genus.
1003    
1004  C<< $query = $erdb->Get(['Genome'], "Genome(genus) = ?", $genus); >>  C<< $query = $erdb->Get(['Genome'], "Genome(genus) = ?", [$genus]); >>
1005    
1006  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
1007  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 873  Line 1018 
1018  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
1019  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,
1020    
1021  C<< $query = $erdb->Get(['Genome', 'ComesFrom', 'Source'], "Genome(genus) = ?", $genus); >>  C<< $query = $erdb->Get(['Genome', 'ComesFrom', 'Source'], "Genome(genus) = ?", [$genus]); >>
1022    
1023  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
1024  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.
1025  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
1026  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
1027  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  
1028  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,
1029  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.
1030    
1031    If an entity or relationship is mentioned twice, the name for the second occurrence will
1032    be suffixed with C<2>, the third occurrence will be suffixed with C<3>, and so forth. So,
1033    for example, if we have C<['Feature', 'HasContig', 'Contig', 'HasContig']>, then the
1034    B<to-link> field of the first B<HasContig> is specified as C<HasContig(to-link)>, while
1035    the B<to-link> field of the second B<HasContig> is specified as C<HasContig2(to-link)>.
1036    
1037  =over 4  =over 4
1038    
1039  =item objectNames  =item objectNames
# Line 913  Line 1063 
1063  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
1064  relation.  relation.
1065    
1066  =item param1, param2, ..., paramN  Finally, you can limit the number of rows returned by adding a LIMIT clause. The LIMIT must
1067    be the last thing in the filter clause, and it contains only the word "LIMIT" followed by
1068    a positive number. So, for example
1069    
1070  Parameter values to be substituted into the filter clause.  C<< "Genome(genus) = ? ORDER BY Genome(species) LIMIT 10" >>
1071    
1072    will only return the first ten genomes for the specified genus. The ORDER BY clause is not
1073    required. For example, to just get the first 10 genomes in the B<Genome> table, you could
1074    use
1075    
1076    C<< "LIMIT 10" >>
1077    
1078    =item params
1079    
1080    Reference to a list of parameter values to be substituted into the filter clause.
1081    
1082  =item RETURN  =item RETURN
1083    
# Line 927  Line 1089 
1089    
1090  sub Get {  sub Get {
1091      # Get the parameters.      # Get the parameters.
1092      my ($self, $objectNames, $filterClause, @params) = @_;      my ($self, $objectNames, $filterClause, $params) = @_;
1093      # Construct the SELECT statement. The general pattern is      # Process the SQL stuff.
1094      #      my ($suffix, $mappedNameListRef, $mappedNameHashRef) =
1095      # SELECT name1.*, name2.*, ... nameN.* FROM name1, name2, ... nameN          $self->_SetupSQL($objectNames, $filterClause);
1096      #      # Create the query.
1097      my $dbh = $self->{_dbh};      my $command = "SELECT DISTINCT " . join(".*, ", @{$mappedNameListRef}) .
1098      my $command = "SELECT DISTINCT " . join('.*, ', @{$objectNames}) . ".* FROM " .          ".* $suffix";
1099                  join(', ', @{$objectNames});      my $sth = $self->_GetStatementHandle($command, $params);
1100      # Check for a filter clause.      # Now we create the relation map, which enables DBQuery to determine the order, name
1101      if ($filterClause) {      # and mapped name for each object in the query.
1102          # Here we have one, so we convert its field names and add it to the query. First,      my @relationMap = ();
1103          # We create a copy of the filter string we can work with.      for my $mappedName (@{$mappedNameListRef}) {
1104          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;  
                 }  
1105              }              }
1106        # Return the statement object.
1107        my $retVal = DBQuery::_new($self, $sth, \@relationMap);
1108        return $retVal;
1109          }          }
1110          # The next step is to join the objects together. We only need to do this if there  
1111          # is more than one object in the object list. We start with the first object and  =head3 Search
1112          # run through the objects after it. Note also that we make a safety copy of the  
1113          # list before running through it.  C<< my $query = $erdb->Search($searchExpression, $idx, \@objectNames, $filterClause, \@params); >>
1114          my @objectList = @{$objectNames};  
1115          my $lastObject = shift @objectList;  Perform a full text search with filtering. The search will be against a specified object
1116          # Get the join table.  in the object name list. That object will get an extra field containing the search
1117          my $joinTable = $self->{_metaData}->{Joins};  relevance. Note that except for the search expression, the parameters of this method are
1118          # Loop through the object list.  the same as those for L</Get> and follow the same rules.
1119          for my $thisObject (@objectList) {  
1120              # Look for a join.  =over 4
1121              my $joinKey = "$lastObject/$thisObject";  
1122              if (!exists $joinTable->{$joinKey}) {  =item searchExpression
1123                  # Here there's no join, so we throw an error.  
1124                  Confess("No join exists to connect from $lastObject to $thisObject.");  Boolean search expression for the text fields of the target object.
1125    
1126    =item idx
1127    
1128    Index in the I<$objectNames> list of the table to be searched in full-text mode.
1129    
1130    =item objectNames
1131    
1132    List containing the names of the entity and relationship objects to be retrieved.
1133    
1134    =item filterClause
1135    
1136    WHERE clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can
1137    be parameterized with parameter markers (C<?>). Each field used in the WHERE clause must be
1138    specified in the standard form B<I<objectName>(I<fieldName>)>. Any parameters specified
1139    in the filter clause should be added to the parameter list as additional parameters. The
1140    fields in a filter clause can come from primary entity relations, relationship relations,
1141    or secondary entity relations; however, all of the entities and relationships involved must
1142    be included in the list of object names.
1143    
1144    =item params
1145    
1146    Reference to a list of parameter values to be substituted into the filter clause.
1147    
1148    =item RETURN
1149    
1150    Returns a query object for the specified search.
1151    
1152    =back
1153    
1154    =cut
1155    
1156    sub Search {
1157        # Get the parameters.
1158        my ($self, $searchExpression, $idx, $objectNames, $filterClause, $params) = @_;
1159        # Declare the return variable.
1160        my $retVal;
1161        # Create a safety copy of the parameter list. Note we have to be careful to insure
1162        # a parameter list exists before we copy it.
1163        my @myParams = ();
1164        if (defined $params) {
1165            @myParams = @{$params};
1166        }
1167        # Get the first object's structure so we have access to the searchable fields.
1168        my $object1Name = $objectNames->[$idx];
1169        my $object1Structure = $self->_GetStructure($object1Name);
1170        # Get the field list.
1171        if (! exists $object1Structure->{searchFields}) {
1172            Confess("No searchable index for $object1Name.");
1173              } else {              } else {
1174                  # Get the join clause and add it to the WHERE list.          # Get the field list.
1175                  push @joinWhere, $joinTable->{$joinKey};          my @fields = @{$object1Structure->{searchFields}};
1176                  # Save this object as the last object for the next iteration.          # Clean the search expression.
1177                  $lastObject = $thisObject;          my $actualKeywords = $self->CleanKeywords($searchExpression);
1178              }          Trace("Actual keywords for search are\n$actualKeywords") if T(3);
1179          }          # We need two match expressions, one for the filter clause and one in the
1180          # Now we need to handle the whole ORDER BY / LIMIT thing. The important part          # query itself. Both will use a parameter mark, so we need to push the
1181          # here is we want the filter clause to be empty if there's no WHERE filter.          # search expression onto the front of the parameter list twice.
1182          # We'll put the ORDER BY / LIMIT clauses in the following variable.          unshift @myParams, $actualKeywords, $actualKeywords;
1183          my $orderClause = "";          # Build the match expression.
1184          # Locate the ORDER BY or LIMIT verbs (if any). We use a non-greedy          my @matchFilterFields = map { "$object1Name." . _FixName($_) } @fields;
1185          # operator so that we find the first occurrence of either verb.          my $matchClause = "MATCH (" . join(", ", @matchFilterFields) . ") AGAINST (? IN BOOLEAN MODE)";
1186          if ($filterString =~ m/^(.*?)\s*(ORDER BY|LIMIT)/g) {          # Process the SQL stuff.
1187              # Here we have an ORDER BY or LIMIT verb. Split it off of the filter string.          my ($suffix, $mappedNameListRef, $mappedNameHashRef) =
1188              my $pos = pos $filterString;              $self->_SetupSQL($objectNames, $filterClause, $matchClause);
1189              $orderClause = $2 . substr($filterString, $pos);          # Create the query. Note that the match clause is inserted at the front of
1190              $filterString = $1;          # the select fields.
1191          }          my $command = "SELECT DISTINCT $matchClause, " . join(".*, ", @{$mappedNameListRef}) .
1192          # Add the filter and the join clauses (if any) to the SELECT command.              ".* $suffix";
1193          if ($filterString) {          my $sth = $self->_GetStatementHandle($command, \@myParams);
1194              push @joinWhere, "($filterString)";          # Now we create the relation map, which enables DBQuery to determine the order, name
1195          }          # and mapped name for each object in the query.
1196          if (@joinWhere) {          my @relationMap = _RelationMap($mappedNameHashRef, $mappedNameListRef);
1197              $command .= " WHERE " . join(' AND ', @joinWhere);          # Return the statement object.
1198            $retVal = DBQuery::_new($self, $sth, \@relationMap, $object1Name);
1199          }          }
1200          # Add the sort or limit clause (if any) to the SELECT command.      return $retVal;
         if ($orderClause) {  
             $command .= " $orderClause";  
1201          }          }
1202    
1203    =head3 GetFlat
1204    
1205    C<< my @list = $erdb->GetFlat(\@objectNames, $filterClause, \@parameterList, $field); >>
1206    
1207    This is a variation of L</GetAll> that asks for only a single field per record and
1208    returns a single flattened list.
1209    
1210    =over 4
1211    
1212    =item objectNames
1213    
1214    List containing the names of the entity and relationship objects to be retrieved.
1215    
1216    =item filterClause
1217    
1218    WHERE/ORDER BY clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can
1219    be parameterized with parameter markers (C<?>). Each field used must be specified in the standard form
1220    B<I<objectName>(I<fieldName>)>. Any parameters specified in the filter clause should be added to the
1221    parameter list as additional parameters. The fields in a filter clause can come from primary
1222    entity relations, relationship relations, or secondary entity relations; however, all of the
1223    entities and relationships involved must be included in the list of object names.
1224    
1225    =item parameterList
1226    
1227    List of the parameters to be substituted in for the parameters marks in the filter clause.
1228    
1229    =item field
1230    
1231    Name of the field to be used to get the elements of the list returned.
1232    
1233    =item RETURN
1234    
1235    Returns a list of values.
1236    
1237    =back
1238    
1239    =cut
1240    #: Return Type @;
1241    sub GetFlat {
1242        # Get the parameters.
1243        my ($self, $objectNames, $filterClause, $parameterList, $field) = @_;
1244        # Construct the query.
1245        my $query = $self->Get($objectNames, $filterClause, $parameterList);
1246        # Create the result list.
1247        my @retVal = ();
1248        # Loop through the records, adding the field values found to the result list.
1249        while (my $row = $query->Fetch()) {
1250            push @retVal, $row->Value($field);
1251      }      }
1252      Trace("SQL query: $command") if T(SQL => 4);      # Return the list created.
1253      Trace("PARMS: '" . (join "', '", @params) . "'") if (T(SQL => 4) && (@params > 0));      return @retVal;
     my $sth = $dbh->prepare_command($command);  
     # Execute it with the parameters bound in.  
     $sth->execute(@params) || Confess("SELECT error" . $sth->errstr());  
     # Return the statement object.  
     my $retVal = DBQuery::_new($self, $sth, @{$objectNames});  
     return $retVal;  
1254  }  }
1255    
1256  =head3 Delete  =head3 Delete
# Line 1219  Line 1421 
1421      return $retVal;      return $retVal;
1422  }  }
1423    
1424    =head3 SortNeeded
1425    
1426    C<< my $parms = $erdb->SortNeeded($relationName); >>
1427    
1428    Return the pipe command for the sort that should be applied to the specified
1429    relation when creating the load file.
1430    
1431    For example, if the load file should be sorted ascending by the first
1432    field, this method would return
1433    
1434        sort -k1 -t"\t"
1435    
1436    If the first field is numeric, the method would return
1437    
1438        sort -k1n -t"\t"
1439    
1440    Unfortunately, due to a bug in the C<sort> command, we cannot eliminate duplicate
1441    keys using a sort.
1442    
1443    =over 4
1444    
1445    =item relationName
1446    
1447    Name of the relation to be examined.
1448    
1449    =item
1450    
1451    Returns the sort command to use for sorting the relation, suitable for piping.
1452    
1453    =back
1454    
1455    =cut
1456    #: Return Type $;
1457    sub SortNeeded {
1458        # Get the parameters.
1459        my ($self, $relationName) = @_;
1460        # Declare a descriptor to hold the names of the key fields.
1461        my @keyNames = ();
1462        # Get the relation structure.
1463        my $relationData = $self->_FindRelation($relationName);
1464        # Find out if the relation is a primary entity relation,
1465        # a relationship relation, or a secondary entity relation.
1466        my $entityTable = $self->{_metaData}->{Entities};
1467        my $relationshipTable = $self->{_metaData}->{Relationships};
1468        if (exists $entityTable->{$relationName}) {
1469            # Here we have a primary entity relation.
1470            push @keyNames, "id";
1471        } elsif (exists $relationshipTable->{$relationName}) {
1472            # Here we have a relationship. We sort using the FROM index.
1473            my $relationshipData = $relationshipTable->{$relationName};
1474            my $index = $relationData->{Indexes}->{"idx${relationName}From"};
1475            push @keyNames, @{$index->{IndexFields}};
1476        } else {
1477            # Here we have a secondary entity relation, so we have a sort on the ID field.
1478            push @keyNames, "id";
1479        }
1480        # Now we parse the key names into sort parameters. First, we prime the return
1481        # string.
1482        my $retVal = "sort -t\"\t\" ";
1483        # Get the relation's field list.
1484        my @fields = @{$relationData->{Fields}};
1485        # Loop through the keys.
1486        for my $keyData (@keyNames) {
1487            # Get the key and the ordering.
1488            my ($keyName, $ordering);
1489            if ($keyData =~ /^([^ ]+) DESC/) {
1490                ($keyName, $ordering) = ($1, "descending");
1491            } else {
1492                ($keyName, $ordering) = ($keyData, "ascending");
1493            }
1494            # Find the key's position and type.
1495            my $fieldSpec;
1496            for (my $i = 0; $i <= $#fields && ! $fieldSpec; $i++) {
1497                my $thisField = $fields[$i];
1498                if ($thisField->{name} eq $keyName) {
1499                    # Get the sort modifier for this field type. The modifier
1500                    # decides whether we're using a character, numeric, or
1501                    # floating-point sort.
1502                    my $modifier = $TypeTable{$thisField->{type}}->{sort};
1503                    # If the index is descending for this field, denote we want
1504                    # to reverse the sort order on this field.
1505                    if ($ordering eq 'descending') {
1506                        $modifier .= "r";
1507                    }
1508                    # Store the position and modifier into the field spec, which
1509                    # will stop the inner loop. Note that the field number is
1510                    # 1-based in the sort command, so we have to increment the
1511                    # index.
1512                    $fieldSpec = ($i + 1) . $modifier;
1513                }
1514            }
1515            # Add this field to the sort command.
1516            $retVal .= " -k$fieldSpec";
1517        }
1518        # Return the result.
1519        return $retVal;
1520    }
1521    
1522  =head3 GetList  =head3 GetList
1523    
1524  C<< my @dbObjects = $erdb->GetList(\@objectNames, $filterClause, $param1, $param2, ..., $paramN); >>  C<< my @dbObjects = $erdb->GetList(\@objectNames, $filterClause, \@params); >>
1525    
1526  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
1527  specified filter clause.  specified filter clause.
# Line 1255  Line 1555 
1555  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
1556  relation.  relation.
1557    
1558  =item param1, param2, ..., paramN  =item params
1559    
1560  Parameter values to be substituted into the filter clause.  Reference to a list of parameter values to be substituted into the filter clause.
1561    
1562  =item RETURN  =item RETURN
1563    
# Line 1269  Line 1569 
1569  #: Return Type @%  #: Return Type @%
1570  sub GetList {  sub GetList {
1571      # Get the parameters.      # Get the parameters.
1572      my ($self, $objectNames, $filterClause, @params) = @_;      my ($self, $objectNames, $filterClause, $params) = @_;
1573      # Declare the return variable.      # Declare the return variable.
1574      my @retVal = ();      my @retVal = ();
1575      # Perform the query.      # Perform the query.
1576      my $query = $self->Get($objectNames, $filterClause, @params);      my $query = $self->Get($objectNames, $filterClause, $params);
1577      # Loop through the results.      # Loop through the results.
1578      while (my $object = $query->Fetch) {      while (my $object = $query->Fetch) {
1579          push @retVal, $object;          push @retVal, $object;
# Line 1282  Line 1582 
1582      return @retVal;      return @retVal;
1583  }  }
1584    
1585    =head3 GetCount
1586    
1587    C<< my $count = $erdb->GetCount(\@objectNames, $filter, \@params); >>
1588    
1589    Return the number of rows found by a specified query. This method would
1590    normally be used to count the records in a single table. For example, in a
1591    genetics database
1592    
1593        my $count = $erdb->GetCount(['Genome'], 'Genome(genus-species) LIKE ?', ['homo %']);
1594    
1595    would return the number of genomes for the genus I<homo>. It is conceivable, however,
1596    to use it to return records based on a join. For example,
1597    
1598        my $count = $erdb->GetCount(['HasFeature', 'Genome'], 'Genome(genus-species) LIKE ?',
1599                                    ['homo %']);
1600    
1601    would return the number of features for genomes in the genus I<homo>. Note that
1602    only the rows from the first table are counted. If the above command were
1603    
1604        my $count = $erdb->GetCount(['Genome', 'Feature'], 'Genome(genus-species) LIKE ?',
1605                                    ['homo %']);
1606    
1607    it would return the number of genomes, not the number of genome/feature pairs.
1608    
1609    =over 4
1610    
1611    =item objectNames
1612    
1613    Reference to a list of the objects (entities and relationships) included in the
1614    query.
1615    
1616    =item filter
1617    
1618    A filter clause for restricting the query. The rules are the same as for the L</Get>
1619    method.
1620    
1621    =item params
1622    
1623    Reference to a list of the parameter values to be substituted for the parameter marks
1624    in the filter.
1625    
1626    =item RETURN
1627    
1628    Returns a count of the number of records in the first table that would satisfy
1629    the query.
1630    
1631    =back
1632    
1633    =cut
1634    
1635    sub GetCount {
1636        # Get the parameters.
1637        my ($self, $objectNames, $filter, $params) = @_;
1638        # Insure the params argument is an array reference if the caller left it off.
1639        if (! defined($params)) {
1640            $params = [];
1641        }
1642        # Declare the return variable.
1643        my $retVal;
1644        # Find out if we're counting an entity or a relationship.
1645        my $countedField;
1646        if ($self->IsEntity($objectNames->[0])) {
1647            $countedField = "id";
1648        } else {
1649            # For a relationship we count the to-link because it's usually more
1650            # numerous. Note we're automatically converting to the SQL form
1651            # of the field name (to_link vs. to-link).
1652            $countedField = "to_link";
1653        }
1654        # Create the SQL command suffix to get the desired records.
1655        my ($suffix, $mappedNameListRef, $mappedNameHashRef) = $self->_SetupSQL($objectNames,
1656                                                                                $filter);
1657        # Prefix it with text telling it we want a record count.
1658        my $firstObject = $mappedNameListRef->[0];
1659        my $command = "SELECT COUNT($firstObject.$countedField) $suffix";
1660        # Prepare and execute the command.
1661        my $sth = $self->_GetStatementHandle($command, $params);
1662        # Get the count value.
1663        ($retVal) = $sth->fetchrow_array();
1664        # Check for a problem.
1665        if (! defined($retVal)) {
1666            if ($sth->err) {
1667                # Here we had an SQL error.
1668                Confess("Error retrieving row count: " . $sth->errstr());
1669            } else {
1670                # Here we have no result.
1671                Confess("No result attempting to retrieve row count.");
1672            }
1673        }
1674        # Return the result.
1675        return $retVal;
1676    }
1677    
1678  =head3 ComputeObjectSentence  =head3 ComputeObjectSentence
1679    
1680  C<< my $sentence = $erdb->ComputeObjectSentence($objectName); >>  C<< my $sentence = $erdb->ComputeObjectSentence($objectName); >>
# Line 1359  Line 1752 
1752      }      }
1753  }  }
1754    
1755    =head3 InsertValue
1756    
1757    C<< $erdb->InsertValue($entityID, $fieldName, $value); >>
1758    
1759    This method will insert a new value into the database. The value must be one
1760    associated with a secondary relation, since primary values cannot be inserted:
1761    they occur exactly once. Secondary values, on the other hand, can be missing
1762    or multiply-occurring.
1763    
1764    =over 4
1765    
1766    =item entityID
1767    
1768    ID of the object that is to receive the new value.
1769    
1770    =item fieldName
1771    
1772    Field name for the new value-- this includes the entity name, since
1773    field names are of the format I<objectName>C<(>I<fieldName>C<)>.
1774    
1775    =item value
1776    
1777    New value to be put in the field.
1778    
1779    =back
1780    
1781    =cut
1782    
1783    sub InsertValue {
1784        # Get the parameters.
1785        my ($self, $entityID, $fieldName, $value) = @_;
1786        # Parse the entity name and the real field name.
1787        if ($fieldName =~ /^([^(]+)\(([^)]+)\)/) {
1788            my $entityName = $1;
1789            my $fieldTitle = $2;
1790            # Get its descriptor.
1791            if (!$self->IsEntity($entityName)) {
1792                Confess("$entityName is not a valid entity.");
1793            } else {
1794                my $entityData = $self->{_metaData}->{Entities}->{$entityName};
1795                # Find the relation containing this field.
1796                my $fieldHash = $entityData->{Fields};
1797                if (! exists $fieldHash->{$fieldTitle}) {
1798                    Confess("$fieldTitle not found in $entityName.");
1799                } else {
1800                    my $relation = $fieldHash->{$fieldTitle}->{relation};
1801                    if ($relation eq $entityName) {
1802                        Confess("Cannot do InsertValue on primary field $fieldTitle of $entityName.");
1803                    } else {
1804                        # Now we can create an INSERT statement.
1805                        my $dbh = $self->{_dbh};
1806                        my $fixedName = _FixName($fieldTitle);
1807                        my $statement = "INSERT INTO $relation (id, $fixedName) VALUES(?, ?)";
1808                        # Execute the command.
1809                        $dbh->SQL($statement, 0, $entityID, $value);
1810                    }
1811                }
1812            }
1813        } else {
1814            Confess("$fieldName is not a valid field name.");
1815        }
1816    }
1817    
1818  =head3 InsertObject  =head3 InsertObject
1819    
1820  C<< my $ok = $erdb->InsertObject($objectType, \%fieldHash); >>  C<< my $ok = $erdb->InsertObject($objectType, \%fieldHash); >>
# Line 1375  Line 1831 
1831  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
1832  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>.
1833    
1834  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'}); >>
1835    
1836  =over 4  =over 4
1837    
# Line 1575  Line 2031 
2031          my $size = -s $fileName;          my $size = -s $fileName;
2032          Trace("$size bytes loaded into $relationName.") if T(2);          Trace("$size bytes loaded into $relationName.") if T(2);
2033          # If we're rebuilding, we need to create the table indexes.          # If we're rebuilding, we need to create the table indexes.
2034          if ($truncateFlag && ! $dbh->{_preIndex}) {          if ($truncateFlag) {
2035                # Indexes are created here for PostGres. For PostGres, indexes are
2036                # best built at the end. For MySQL, the reverse is true.
2037                if (! $dbh->{_preIndex}) {
2038              eval {              eval {
2039                  $self->CreateIndex($relationName);                  $self->CreateIndex($relationName);
2040              };              };
# Line 1583  Line 2042 
2042                  $retVal->AddMessage($@);                  $retVal->AddMessage($@);
2043              }              }
2044          }          }
2045                # The full-text index (if any) is always built last, even for MySQL.
2046                # First we need to see if this table has a full-text index. Only
2047                # primary relations are allowed that privilege.
2048                if ($self->_IsPrimary($relationName)) {
2049                    # Get the relation's entity/relationship structure.
2050                    my $structure = $self->_GetStructure($relationName);
2051                    # Check for a searchable fields list.
2052                    if (exists $structure->{searchFields}) {
2053                        # Here we know that we need to create a full-text search index.
2054                        # Get an SQL-formatted field name list.
2055                        my $fields = join(", ", $self->_FixNames(@{$structure->{searchFields}}));
2056                        # Create the index.
2057                        $dbh->create_index(tbl => $relationName, idx => "search_idx_$relationName",
2058                                           flds => $fields, kind => 'fulltext');
2059                    }
2060                }
2061            }
2062      }      }
2063      # Analyze the table to improve performance.      # Analyze the table to improve performance.
2064        Trace("Analyzing and compacting $relationName.") if T(3);
2065      $dbh->vacuum_it($relationName);      $dbh->vacuum_it($relationName);
2066        Trace("$relationName load completed.") if T(3);
2067      # Return the statistics.      # Return the statistics.
2068      return $retVal;      return $retVal;
2069  }  }
# Line 1677  Line 2155 
2155      # Get the parameters.      # Get the parameters.
2156      my ($self, $entityType, $ID) = @_;      my ($self, $entityType, $ID) = @_;
2157      # Create a query.      # Create a query.
2158      my $query = $self->Get([$entityType], "$entityType(id) = ?", $ID);      my $query = $self->Get([$entityType], "$entityType(id) = ?", [$ID]);
2159      # Get the first (and only) object.      # Get the first (and only) object.
2160      my $retVal = $query->Fetch();      my $retVal = $query->Fetch();
2161      # Return the result.      # Return the result.
2162      return $retVal;      return $retVal;
2163  }  }
2164    
2165    =head3 GetChoices
2166    
2167    C<< my @values = $erdb->GetChoices($entityName, $fieldName); >>
2168    
2169    Return a list of all the values for the specified field that are represented in the
2170    specified entity.
2171    
2172    Note that if the field is not indexed, then this will be a very slow operation.
2173    
2174    =over 4
2175    
2176    =item entityName
2177    
2178    Name of an entity in the database.
2179    
2180    =item fieldName
2181    
2182    Name of a field belonging to the entity. This is a raw field name without
2183    the standard parenthesized notation used in most calls.
2184    
2185    =item RETURN
2186    
2187    Returns a list of the distinct values for the specified field in the database.
2188    
2189    =back
2190    
2191    =cut
2192    
2193    sub GetChoices {
2194        # Get the parameters.
2195        my ($self, $entityName, $fieldName) = @_;
2196        # Declare the return variable.
2197        my @retVal;
2198        # Get the entity data structure.
2199        my $entityData = $self->_GetStructure($entityName);
2200        # Get the field.
2201        my $fieldHash = $entityData->{Fields};
2202        if (! exists $fieldHash->{$fieldName}) {
2203            Confess("$fieldName not found in $entityName.");
2204        } else {
2205            # Get the name of the relation containing the field.
2206            my $relation = $fieldHash->{$fieldName}->{relation};
2207            # Fix up the field name.
2208            my $realName = _FixName($fieldName);
2209            # Get the database handle.
2210            my $dbh = $self->{_dbh};
2211            # Query the database.
2212            my $results = $dbh->SQL("SELECT DISTINCT $realName FROM $relation");
2213            # Clean the results. They are stored as a list of lists, and we just want the one list.
2214            @retVal = sort map { $_->[0] } @{$results};
2215        }
2216        # Return the result.
2217        return @retVal;
2218    }
2219    
2220  =head3 GetEntityValues  =head3 GetEntityValues
2221    
2222  C<< my @values = $erdb->GetEntityValues($entityType, $ID, \@fields); >>  C<< my @values = $erdb->GetEntityValues($entityType, $ID, \@fields); >>
2223    
2224  Return a list of values from a specified entity instance.  Return a list of values from a specified entity instance. If the entity instance
2225    does not exist, an empty list is returned.
2226    
2227  =over 4  =over 4
2228    
# Line 1790  Line 2324 
2324      # list is a scalar we convert it into a singleton list.      # list is a scalar we convert it into a singleton list.
2325      my @parmList = ();      my @parmList = ();
2326      if (ref $parameterList eq "ARRAY") {      if (ref $parameterList eq "ARRAY") {
2327            Trace("GetAll parm list is an array.") if T(4);
2328          @parmList = @{$parameterList};          @parmList = @{$parameterList};
2329      } else {      } else {
2330            Trace("GetAll parm list is a scalar: $parameterList.") if T(4);
2331          push @parmList, $parameterList;          push @parmList, $parameterList;
2332      }      }
2333      # Insure the counter has a value.      # Insure the counter has a value.
# Line 1803  Line 2339 
2339          $filterClause .= " LIMIT $count";          $filterClause .= " LIMIT $count";
2340      }      }
2341      # Create the query.      # Create the query.
2342      my $query = $self->Get($objectNames, $filterClause, @parmList);      my $query = $self->Get($objectNames, $filterClause, \@parmList);
2343      # Set up a counter of the number of records read.      # Set up a counter of the number of records read.
2344      my $fetched = 0;      my $fetched = 0;
2345      # 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 1814  Line 2350 
2350          push @retVal, \@rowData;          push @retVal, \@rowData;
2351          $fetched++;          $fetched++;
2352      }      }
2353        Trace("$fetched rows returned in GetAll.") if T(SQL => 4);
2354      # Return the resulting list.      # Return the resulting list.
2355      return @retVal;      return @retVal;
2356  }  }
2357    
2358    =head3 Exists
2359    
2360    C<< my $found = $sprout->Exists($entityName, $entityID); >>
2361    
2362    Return TRUE if an entity exists, else FALSE.
2363    
2364    =over 4
2365    
2366    =item entityName
2367    
2368    Name of the entity type (e.g. C<Feature>) relevant to the existence check.
2369    
2370    =item entityID
2371    
2372    ID of the entity instance whose existence is to be checked.
2373    
2374    =item RETURN
2375    
2376    Returns TRUE if the entity instance exists, else FALSE.
2377    
2378    =back
2379    
2380    =cut
2381    #: Return Type $;
2382    sub Exists {
2383        # Get the parameters.
2384        my ($self, $entityName, $entityID) = @_;
2385        # Check for the entity instance.
2386        Trace("Checking existence of $entityName with ID=$entityID.") if T(4);
2387        my $testInstance = $self->GetEntity($entityName, $entityID);
2388        # Return an existence indicator.
2389        my $retVal = ($testInstance ? 1 : 0);
2390        return $retVal;
2391    }
2392    
2393  =head3 EstimateRowSize  =head3 EstimateRowSize
2394    
2395  C<< my $rowSize = $erdb->EstimateRowSize($relName); >>  C<< my $rowSize = $erdb->EstimateRowSize($relName); >>
# Line 1885  Line 2457 
2457      return $objectData->{Fields};      return $objectData->{Fields};
2458  }  }
2459    
2460    =head2 Data Mining Methods
2461    
2462  =head3 GetUsefulCrossValues  =head3 GetUsefulCrossValues
2463    
2464  C<< my @attrNames = $sprout->GetUsefulCrossValues($sourceEntity, $relationship); >>  C<< my @attrNames = $sprout->GetUsefulCrossValues($sourceEntity, $relationship); >>
# Line 1946  Line 2520 
2520      return @retVal;      return @retVal;
2521  }  }
2522    
2523    =head3 FindColumn
2524    
2525    C<< my $colIndex = ERDB::FindColumn($headerLine, $columnIdentifier); >>
2526    
2527    Return the location a desired column in a data mining header line. The data
2528    mining header line is a tab-separated list of column names. The column
2529    identifier is either the numerical index of a column or the actual column
2530    name.
2531    
2532    =over 4
2533    
2534    =item headerLine
2535    
2536    The header line from a data mining command, which consists of a tab-separated
2537    list of column names.
2538    
2539    =item columnIdentifier
2540    
2541    Either the ordinal number of the desired column (1-based), or the name of the
2542    desired column.
2543    
2544    =item RETURN
2545    
2546    Returns the array index (0-based) of the desired column.
2547    
2548    =back
2549    
2550    =cut
2551    
2552    sub FindColumn {
2553        # Get the parameters.
2554        my ($headerLine, $columnIdentifier) = @_;
2555        # Declare the return variable.
2556        my $retVal;
2557        # Split the header line into column names.
2558        my @headers = ParseColumns($headerLine);
2559        # Determine whether we have a number or a name.
2560        if ($columnIdentifier =~ /^\d+$/) {
2561            # Here we have a number. Subtract 1 and validate the result.
2562            $retVal = $columnIdentifier - 1;
2563            if ($retVal < 0 || $retVal > $#headers) {
2564                Confess("Invalid column identifer \"$columnIdentifier\": value out of range.");
2565            }
2566        } else {
2567            # Here we have a name. We need to find it in the list.
2568            for (my $i = 0; $i <= $#headers && ! defined($retVal); $i++) {
2569                if ($headers[$i] eq $columnIdentifier) {
2570                    $retVal = $i;
2571                }
2572            }
2573            if (! defined($retVal)) {
2574                Confess("Invalid column identifier \"$columnIdentifier\": value not found.");
2575            }
2576        }
2577        # Return the result.
2578        return $retVal;
2579    }
2580    
2581    =head3 ParseColumns
2582    
2583    C<< my @columns = ERDB::ParseColumns($line); >>
2584    
2585    Convert the specified data line to a list of columns.
2586    
2587    =over 4
2588    
2589    =item line
2590    
2591    A data mining input, consisting of a tab-separated list of columns terminated by a
2592    new-line.
2593    
2594    =item RETURN
2595    
2596    Returns a list consisting of the column values.
2597    
2598    =back
2599    
2600    =cut
2601    
2602    sub ParseColumns {
2603        # Get the parameters.
2604        my ($line) = @_;
2605        # Chop off the line-end.
2606        chomp $line;
2607        # Split it into a list.
2608        my @retVal = split(/\t/, $line);
2609        # Return the result.
2610        return @retVal;
2611    }
2612    
2613    =head2 Virtual Methods
2614    
2615    =head3 CleanKeywords
2616    
2617    C<< my $cleanedString = $erdb->CleanKeywords($searchExpression); >>
2618    
2619    Clean up a search expression or keyword list. This is a virtual method that may
2620    be overridden by the subclass. The base-class method removes extra spaces
2621    and converts everything to lower case.
2622    
2623    =over 4
2624    
2625    =item searchExpression
2626    
2627    Search expression or keyword list to clean. Note that a search expression may
2628    contain boolean operators which need to be preserved. This includes leading
2629    minus signs.
2630    
2631    =item RETURN
2632    
2633    Cleaned expression or keyword list.
2634    
2635    =back
2636    
2637    =cut
2638    
2639    sub CleanKeywords {
2640        # Get the parameters.
2641        my ($self, $searchExpression) = @_;
2642        # Lower-case the expression and copy it into the return variable. Note that we insure we
2643        # don't accidentally end up with an undefined value.
2644        my $retVal = lc($searchExpression || "");
2645        # Remove extra spaces.
2646        $retVal =~ s/\s+/ /g;
2647        $retVal =~ s/(^\s+)|(\s+$)//g;
2648        # Return the result.
2649        return $retVal;
2650    }
2651    
2652  =head2 Internal Utility Methods  =head2 Internal Utility Methods
2653    
2654  =head3 GetLoadStats  =head3 _RelationMap
2655    
2656    C<< my @relationMap = _RelationMap($mappedNameHashRef, $mappedNameListRef); >>
2657    
2658    Create the relation map for an SQL query. The relation map is used by B<DBObject>
2659    to determine how to interpret the results of the query.
2660    
2661    =over 4
2662    
2663    =item mappedNameHashRef
2664    
2665    Reference to a hash that maps modified object names to real object names.
2666    
2667    =item mappedNameListRef
2668    
2669    Reference to a list of modified object names in the order they appear in the
2670    SELECT list.
2671    
2672    =item RETURN
2673    
2674    Returns a list of 2-tuples. Each tuple consists of an object name as used in the
2675    query followed by the actual name of that object. This enables the B<DBObject> to
2676    determine the order of the tables in the query and which object name belongs to each
2677    mapped object name. Most of the time these two values are the same; however, if a
2678    relation occurs twice in the query, the relation name in the field list and WHERE
2679    clause will use a mapped name (generally the actual relation name with a numeric
2680    suffix) that does not match the actual relation name.
2681    
2682    =back
2683    
2684    =cut
2685    
2686    sub _RelationMap {
2687        # Get the parameters.
2688        my ($mappedNameHashRef, $mappedNameListRef) = @_;
2689        # Declare the return variable.
2690        my @retVal = ();
2691        # Build the map.
2692        for my $mappedName (@{$mappedNameListRef}) {
2693            push @retVal, [$mappedName, $mappedNameHashRef->{$mappedName}];
2694        }
2695        # Return it.
2696        return @retVal;
2697    }
2698    
2699    
2700    =head3 _SetupSQL
2701    
2702    Process a list of object names and a filter clause so that they can be used to
2703    build an SQL statement. This method takes in a reference to a list of object names
2704    and a filter clause. It will return a corrected filter clause, a list of mapped
2705    names and the mapped name hash.
2706    
2707    This is an instance method.
2708    
2709    =over 4
2710    
2711    =item objectNames
2712    
2713    Reference to a list of the object names to be included in the query.
2714    
2715    =item filterClause
2716    
2717    A string containing the WHERE clause for the query (without the C<WHERE>) and also
2718    optionally the C<ORDER BY> and C<LIMIT> clauses.
2719    
2720    =item matchClause
2721    
2722    An optional full-text search clause. If specified, it will be inserted at the
2723    front of the WHERE clause. It should already be SQL-formatted; that is, the
2724    field names should be in the form I<table>C<.>I<fieldName>.
2725    
2726    =item RETURN
2727    
2728    Returns a three-element list. The first element is the SQL statement suffix, beginning
2729    with the FROM clause. The second element is a reference to a list of the names to be
2730    used in retrieving the fields. The third element is a hash mapping the names to the
2731    objects they represent.
2732    
2733    =back
2734    
2735    =cut
2736    
2737    sub _SetupSQL {
2738        my ($self, $objectNames, $filterClause, $matchClause) = @_;
2739        # Adjust the list of object names to account for multiple occurrences of the
2740        # same object. We start with a hash table keyed on object name that will
2741        # return the object suffix. The first time an object is encountered it will
2742        # not be found in the hash. The next time the hash will map the object name
2743        # to 2, then 3, and so forth.
2744        my %objectHash = ();
2745        # This list will contain the object names as they are to appear in the
2746        # FROM list.
2747        my @fromList = ();
2748        # This list contains the suffixed object name for each object. It is exactly
2749        # parallel to the list in the $objectNames parameter.
2750        my @mappedNameList = ();
2751        # Finally, this hash translates from a mapped name to its original object name.
2752        my %mappedNameHash = ();
2753        # Now we create the lists. Note that for every single name we push something into
2754        # @fromList and @mappedNameList. This insures that those two arrays are exactly
2755        # parallel to $objectNames.
2756        for my $objectName (@{$objectNames}) {
2757            # Get the next suffix for this object.
2758            my $suffix = $objectHash{$objectName};
2759            if (! $suffix) {
2760                # Here we are seeing the object for the first time. The object name
2761                # is used as is.
2762                push @mappedNameList, $objectName;
2763                push @fromList, $objectName;
2764                $mappedNameHash{$objectName} = $objectName;
2765                # Denote the next suffix will be 2.
2766                $objectHash{$objectName} = 2;
2767            } else {
2768                # Here we've seen the object before. We construct a new name using
2769                # the suffix from the hash and update the hash.
2770                my $mappedName = "$objectName$suffix";
2771                $objectHash{$objectName} = $suffix + 1;
2772                # The FROM list has the object name followed by the mapped name. This
2773                # tells SQL it's still the same table, but we're using a different name
2774                # for it to avoid confusion.
2775                push @fromList, "$objectName $mappedName";
2776                # The mapped-name list contains the real mapped name.
2777                push @mappedNameList, $mappedName;
2778                # Finally, enable us to get back from the mapped name to the object name.
2779                $mappedNameHash{$mappedName} = $objectName;
2780            }
2781        }
2782        # Begin the SELECT suffix. It starts with
2783        #
2784        # FROM name1, name2, ... nameN
2785        #
2786        my $suffix = "FROM " . join(', ', @fromList);
2787        # Now for the WHERE. First, we need a place for the filter string.
2788        my $filterString = "";
2789        # We will also keep a list of conditions to add to the WHERE clause in order to link
2790        # entities and relationships as well as primary relations to secondary ones.
2791        my @joinWhere = ();
2792        # Check for a filter clause.
2793        if ($filterClause) {
2794            # Here we have one, so we convert its field names and add it to the query. First,
2795            # We create a copy of the filter string we can work with.
2796            $filterString = $filterClause;
2797            # Next, we sort the object names by length. This helps protect us from finding
2798            # object names inside other object names when we're doing our search and replace.
2799            my @sortedNames = sort { length($b) - length($a) } @mappedNameList;
2800            # The final preparatory step is to create a hash table of relation names. The
2801            # table begins with the relation names already in the SELECT command. We may
2802            # need to add relations later if there is filtering on a field in a secondary
2803            # relation. The secondary relations are the ones that contain multiply-
2804            # occurring or optional fields.
2805            my %fromNames = map { $_ => 1 } @sortedNames;
2806            # We are ready to begin. We loop through the object names, replacing each
2807            # object name's field references by the corresponding SQL field reference.
2808            # Along the way, if we find a secondary relation, we will need to add it
2809            # to the FROM clause.
2810            for my $mappedName (@sortedNames) {
2811                # Get the length of the object name plus 2. This is the value we add to the
2812                # size of the field name to determine the size of the field reference as a
2813                # whole.
2814                my $nameLength = 2 + length $mappedName;
2815                # Get the real object name for this mapped name.
2816                my $objectName = $mappedNameHash{$mappedName};
2817                Trace("Processing $mappedName for object $objectName.") if T(4);
2818                # Get the object's field list.
2819                my $fieldList = $self->GetFieldTable($objectName);
2820                # Find the field references for this object.
2821                while ($filterString =~ m/$mappedName\(([^)]*)\)/g) {
2822                    # At this point, $1 contains the field name, and the current position
2823                    # is set immediately after the final parenthesis. We pull out the name of
2824                    # the field and the position and length of the field reference as a whole.
2825                    my $fieldName = $1;
2826                    my $len = $nameLength + length $fieldName;
2827                    my $pos = pos($filterString) - $len;
2828                    # Insure the field exists.
2829                    if (!exists $fieldList->{$fieldName}) {
2830                        Confess("Field $fieldName not found for object $objectName.");
2831                    } else {
2832                        Trace("Processing $fieldName at position $pos.") if T(4);
2833                        # Get the field's relation.
2834                        my $relationName = $fieldList->{$fieldName}->{relation};
2835                        # Now we have a secondary relation. We need to insure it matches the
2836                        # mapped name of the primary relation. First we peel off the suffix
2837                        # from the mapped name.
2838                        my $mappingSuffix = substr $mappedName, length($objectName);
2839                        # Put the mapping suffix onto the relation name to get the
2840                        # mapped relation name.
2841                        my $mappedRelationName = "$relationName$mappingSuffix";
2842                        # Insure the relation is in the FROM clause.
2843                        if (!exists $fromNames{$mappedRelationName}) {
2844                            # Add the relation to the FROM clause.
2845                            if ($mappedRelationName eq $relationName) {
2846                                # The name is un-mapped, so we add it without
2847                                # any frills.
2848                                $suffix .= ", $relationName";
2849                                push @joinWhere, "$objectName.id = $relationName.id";
2850                            } else {
2851                                # Here we have a mapping situation.
2852                                $suffix .= ", $relationName $mappedRelationName";
2853                                push @joinWhere, "$mappedRelationName.id = $mappedName.id";
2854                            }
2855                            # Denote we have this relation available for future fields.
2856                            $fromNames{$mappedRelationName} = 1;
2857                        }
2858                        # Form an SQL field reference from the relation name and the field name.
2859                        my $sqlReference = "$mappedRelationName." . _FixName($fieldName);
2860                        # Put it into the filter string in place of the old value.
2861                        substr($filterString, $pos, $len) = $sqlReference;
2862                        # Reposition the search.
2863                        pos $filterString = $pos + length $sqlReference;
2864                    }
2865                }
2866            }
2867        }
2868        # The next step is to join the objects together. We only need to do this if there
2869        # is more than one object in the object list. We start with the first object and
2870        # run through the objects after it. Note also that we make a safety copy of the
2871        # list before running through it, because we shift off the first object before
2872        # processing the rest.
2873        my @mappedObjectList = @mappedNameList;
2874        my $lastMappedObject = shift @mappedObjectList;
2875        # Get the join table.
2876        my $joinTable = $self->{_metaData}->{Joins};
2877        # Loop through the object list.
2878        for my $thisMappedObject (@mappedObjectList) {
2879            # Look for a join using the real object names.
2880            my $lastObject = $mappedNameHash{$lastMappedObject};
2881            my $thisObject = $mappedNameHash{$thisMappedObject};
2882            my $joinKey = "$lastObject/$thisObject";
2883            if (!exists $joinTable->{$joinKey}) {
2884                # Here there's no join, so we throw an error.
2885                Confess("No join exists to connect from $lastMappedObject to $thisMappedObject.");
2886            } else {
2887                # Get the join clause.
2888                my $unMappedJoin = $joinTable->{$joinKey};
2889                # Fix the names.
2890                $unMappedJoin =~ s/$lastObject/$lastMappedObject/;
2891                $unMappedJoin =~ s/$thisObject/$thisMappedObject/;
2892                push @joinWhere, $unMappedJoin;
2893                # Save this object as the last object for the next iteration.
2894                $lastMappedObject = $thisMappedObject;
2895            }
2896        }
2897        # Now we need to handle the whole ORDER BY / LIMIT thing. The important part
2898        # here is we want the filter clause to be empty if there's no WHERE filter.
2899        # We'll put the ORDER BY / LIMIT clauses in the following variable.
2900        my $orderClause = "";
2901        # This is only necessary if we have a filter string in which the ORDER BY
2902        # and LIMIT clauses can live.
2903        if ($filterString) {
2904            # Locate the ORDER BY or LIMIT verbs (if any). We use a non-greedy
2905            # operator so that we find the first occurrence of either verb.
2906            if ($filterString =~ m/^(.*?)\s*(ORDER BY|LIMIT)/g) {
2907                # Here we have an ORDER BY or LIMIT verb. Split it off of the filter string.
2908                my $pos = pos $filterString;
2909                $orderClause = $2 . substr($filterString, $pos);
2910                $filterString = $1;
2911            }
2912        }
2913        # All the things that are supposed to be in the WHERE clause of the
2914        # SELECT command need to be put into @joinWhere so we can string them
2915        # together. We begin with the match clause. This is important,
2916        # because the match clause's parameter mark must precede any parameter
2917        # marks in the filter string.
2918        if ($matchClause) {
2919            push @joinWhere, $matchClause;
2920        }
2921        # Add the filter string. We put it in parentheses to avoid operator
2922        # precedence problems with the match clause or the joins.
2923        if ($filterString) {
2924            Trace("Filter string is \"$filterString\".") if T(4);
2925            push @joinWhere, "($filterString)";
2926        }
2927        # String it all together into a big filter clause.
2928        if (@joinWhere) {
2929            $suffix .= " WHERE " . join(' AND ', @joinWhere);
2930        }
2931        # Add the sort or limit clause (if any).
2932        if ($orderClause) {
2933            $suffix .= " $orderClause";
2934        }
2935        # Return the suffix, the mapped name list, and the mapped name hash.
2936        return ($suffix, \@mappedNameList, \%mappedNameHash);
2937    }
2938    
2939    =head3 _GetStatementHandle
2940    
2941    This method will prepare and execute an SQL query, returning the statement handle.
2942    The main reason for doing this here is so that everybody who does SQL queries gets
2943    the benefit of tracing.
2944    
2945    This is an instance method.
2946    
2947    =over 4
2948    
2949    =item command
2950    
2951    Command to prepare and execute.
2952    
2953    =item params
2954    
2955    Reference to a list of the values to be substituted in for the parameter marks.
2956    
2957    =item RETURN
2958    
2959    Returns a prepared and executed statement handle from which the caller can extract
2960    results.
2961    
2962    =back
2963    
2964    =cut
2965    
2966    sub _GetStatementHandle {
2967        # Get the parameters.
2968        my ($self, $command, $params) = @_;
2969        # Trace the query.
2970        Trace("SQL query: $command") if T(SQL => 3);
2971        Trace("PARMS: '" . (join "', '", @{$params}) . "'") if (T(SQL => 4) && (@{$params} > 0));
2972        # Get the database handle.
2973        my $dbh = $self->{_dbh};
2974        # Prepare the command.
2975        my $sth = $dbh->prepare_command($command);
2976        # Execute it with the parameters bound in.
2977        $sth->execute(@{$params}) || Confess("SELECT error" . $sth->errstr());
2978        # Return the statement handle.
2979        return $sth;
2980    }
2981    
2982    =head3 _GetLoadStats
2983    
2984  Return a blank statistics object for use by the load methods.  Return a blank statistics object for use by the load methods.
2985    
# Line 1960  Line 2991 
2991      return Stats->new();      return Stats->new();
2992  }  }
2993    
2994  =head3 GenerateFields  =head3 _GenerateFields
2995    
2996  Generate field values from a field structure and store in a specified table. The field names  Generate field values from a field structure and store in a specified table. The field names
2997  are first sorted by pass count, certain pre-defined fields are removed from the list, and  are first sorted by pass count, certain pre-defined fields are removed from the list, and
# Line 2034  Line 3065 
3065      }      }
3066  }  }
3067    
3068  =head3 DumpRelation  =head3 _DumpRelation
3069    
3070  Dump the specified relation's to the specified output file in tab-delimited format.  Dump the specified relation's to the specified output file in tab-delimited format.
3071    
# Line 2084  Line 3115 
3115      close DTXOUT;      close DTXOUT;
3116  }  }
3117    
3118  =head3 GetStructure  =head3 _GetStructure
3119    
3120  Get the data structure for a specified entity or relationship.  Get the data structure for a specified entity or relationship.
3121    
# Line 2123  Line 3154 
3154      return $retVal;      return $retVal;
3155  }  }
3156    
3157  =head3 GetRelationTable  
3158    
3159    =head3 _GetRelationTable
3160    
3161  Get the list of relations for a specified entity or relationship.  Get the list of relations for a specified entity or relationship.
3162    
# Line 2152  Line 3185 
3185      return $objectData->{Relations};      return $objectData->{Relations};
3186  }  }
3187    
3188  =head3 ValidateFieldNames  =head3 _ValidateFieldNames
3189    
3190  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
3191  will be written to the standard error output. If there is an error, this method will abort. This is  will be written to the standard error output. If there is an error, this method will abort. This is
# Line 2207  Line 3240 
3240      }      }
3241  }  }
3242    
3243  =head3 LoadRelation  =head3 _LoadRelation
3244    
3245  Load a relation from the data in a tab-delimited disk file. The load will only take place if a disk  Load a relation from the data in a tab-delimited disk file. The load will only take place if a disk
3246  file with the same name as the relation exists in the specified directory.  file with the same name as the relation exists in the specified directory.
# Line 2267  Line 3300 
3300      return $retVal;      return $retVal;
3301  }  }
3302    
3303  =head3 LoadMetaData  =head3 _LoadMetaData
3304    
3305  This method loads the data describing this database from an XML file into a metadata structure.  This method loads the data describing this database from an XML file into a metadata structure.
3306  The resulting structure is a set of nested hash tables containing all the information needed to  The resulting structure is a set of nested hash tables containing all the information needed to
# Line 2505  Line 3538 
3538              # 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.
3539              my $fromEntity = $relationship->{from};              my $fromEntity = $relationship->{from};
3540              my $toEntity = $relationship->{to};              my $toEntity = $relationship->{to};
3541              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);
3542              if ($fromEntity eq $entityName) {              if ($fromEntity eq $entityName) {
3543                  if ($toEntity eq $entityName) {                  if ($toEntity eq $entityName) {
3544                      # Here the relationship is recursive.                      # Here the relationship is recursive.
# Line 2594  Line 3627 
3627      return $metadata;      return $metadata;
3628  }  }
3629    
3630  =head3 CreateRelationshipIndex  =head3 _CreateRelationshipIndex
3631    
3632  Create an index for a relationship's relation.  Create an index for a relationship's relation.
3633    
# Line 2639  Line 3672 
3672      _AddIndex("idx$relationshipName$indexKey", $relationStructure, $newIndex);      _AddIndex("idx$relationshipName$indexKey", $relationStructure, $newIndex);
3673  }  }
3674    
3675  =head3 AddIndex  =head3 _AddIndex
3676    
3677  Add an index to a relation structure.  Add an index to a relation structure.
3678    
# Line 2685  Line 3718 
3718      $relationStructure->{Indexes}->{$indexName} = $newIndex;      $relationStructure->{Indexes}->{$indexName} = $newIndex;
3719  }  }
3720    
3721  =head3 FixupFields  =head3 _FixupFields
3722    
3723  This method fixes the field list for an entity or relationship. It will add the caller-specified  This method fixes the field list for an entity or relationship. It will add the caller-specified
3724  relation name to fields that do not have a name and set the C<PrettySort> value as specified.  relation name to fields that do not have a name and set the C<PrettySort> value as specified.
# Line 2723  Line 3756 
3756          # Here it doesn't, so we create a new one.          # Here it doesn't, so we create a new one.
3757          $structure->{Fields} = { };          $structure->{Fields} = { };
3758      } else {      } else {
3759          # Here we have a field list. Loop through its fields.          # Here we have a field list. We need to track the searchable fields, so we
3760            # create a list for stashing them.
3761            my @textFields = ();
3762            # Loop through the fields.
3763          my $fieldStructures = $structure->{Fields};          my $fieldStructures = $structure->{Fields};
3764          for my $fieldName (keys %{$fieldStructures}) {          for my $fieldName (keys %{$fieldStructures}) {
3765              Trace("Processing field $fieldName of $defaultRelationName.") if T(4);              Trace("Processing field $fieldName of $defaultRelationName.") if T(4);
# Line 2737  Line 3773 
3773                  # The data generator will use the default for the field's type.                  # The data generator will use the default for the field's type.
3774                  $fieldData->{DataGen} = { content => $TypeTable{$type}->{dataGen} };                  $fieldData->{DataGen} = { content => $TypeTable{$type}->{dataGen} };
3775              }              }
3776                # Check for searchability.
3777                if ($fieldData->{searchable}) {
3778                    # Only allow this for a primary relation.
3779                    if ($fieldData->{relation} ne $defaultRelationName) {
3780                        Confess("Field $fieldName of $defaultRelationName is in secondary relations and cannot be searchable.");
3781                    } else {
3782                        push @textFields, $fieldName;
3783                    }
3784                }
3785              # Plug in the defaults for the optional data generation parameters.              # Plug in the defaults for the optional data generation parameters.
3786              Tracer::MergeOptions($fieldData->{DataGen}, { testCount => 1, pass => 0 });              Tracer::MergeOptions($fieldData->{DataGen}, { testCount => 1, pass => 0 });
3787              # Add the PrettySortValue.              # Add the PrettySortValue.
3788              $fieldData->{PrettySort} = (($type eq "text") ? $textPrettySortValue : $prettySortValue);              $fieldData->{PrettySort} = (($type eq "text") ? $textPrettySortValue : $prettySortValue);
3789          }          }
3790            # If there are searchable fields, remember the fact.
3791            if (@textFields) {
3792                $structure->{searchFields} = \@textFields;
3793            }
3794      }      }
3795  }  }
3796    
3797  =head3 FixName  =head3 _FixName
3798    
3799  Fix the incoming field name so that it is a legal SQL column name.  Fix the incoming field name so that it is a legal SQL column name.
3800    
# Line 2774  Line 3823 
3823      return $fieldName;      return $fieldName;
3824  }  }
3825    
3826  =head3 FixNames  =head3 _FixNames
3827    
3828  Fix all the field names in a list.  Fix all the field names in a list.
3829    
# Line 2805  Line 3854 
3854      return @result;      return @result;
3855  }  }
3856    
3857  =head3 AddField  =head3 _AddField
3858    
3859  Add a field to a field list.  Add a field to a field list.
3860    
# Line 2840  Line 3889 
3889      $fieldList->{$fieldName} = $fieldStructure;      $fieldList->{$fieldName} = $fieldStructure;
3890  }  }
3891    
3892  =head3 ReOrderRelationTable  =head3 _ReOrderRelationTable
3893    
3894  This method will take a relation table and re-sort it according to the implicit ordering of the  This method will take a relation table and re-sort it according to the implicit ordering of the
3895  C<PrettySort> property. Instead of a hash based on field names, it will return a list of fields.  C<PrettySort> property. Instead of a hash based on field names, it will return a list of fields.
# Line 2901  Line 3950 
3950    
3951  }  }
3952    
3953  =head3 IsPrimary  =head3 _IsPrimary
3954    
3955  Return TRUE if a specified relation is a primary relation, else FALSE. A relation is primary  Return TRUE if a specified relation is a primary relation, else FALSE. A relation is primary
3956  if it has the same name as an entity or relationship.  if it has the same name as an entity or relationship.
# Line 2937  Line 3986 
3986      return $retVal;      return $retVal;
3987  }  }
3988    
3989  =head3 FindRelation  =head3 _FindRelation
3990    
3991  Return the descriptor for the specified relation.  Return the descriptor for the specified relation.
3992    
# Line 2968  Line 4017 
4017    
4018  =head2 HTML Documentation Utility Methods  =head2 HTML Documentation Utility Methods
4019    
4020  =head3 ComputeRelationshipSentence  =head3 _ComputeRelationshipSentence
4021    
4022  The relationship sentence consists of the relationship name between the names of the  The relationship sentence consists of the relationship name between the names of the
4023  two related entities and an arity indicator.  two related entities and an arity indicator.
# Line 3006  Line 4055 
4055      return $result;      return $result;
4056  }  }
4057    
4058  =head3 ComputeRelationshipHeading  =head3 _ComputeRelationshipHeading
4059    
4060  The relationship heading is the L<relationship sentence|/ComputeRelationshipSentence> with the entity  The relationship heading is the L<relationship sentence|/ComputeRelationshipSentence> with the entity
4061  names hyperlinked to the appropriate entity sections of the document.  names hyperlinked to the appropriate entity sections of the document.
# Line 3043  Line 4092 
4092      return $result;      return $result;
4093  }  }
4094    
4095  =head3 ShowRelationTable  =head3 _ShowRelationTable
4096    
4097  Generate the HTML string for a particular relation. The relation's data will be formatted as an HTML  Generate the HTML string for a particular relation. The relation's data will be formatted as an HTML
4098  table with three columns-- the field name, the field type, and the field description.  table with three columns-- the field name, the field type, and the field description.
# Line 3104  Line 4153 
4153      $htmlString .= "</ul>\n";      $htmlString .= "</ul>\n";
4154  }  }
4155    
4156  =head3 OpenFieldTable  =head3 _OpenFieldTable
4157    
4158  This method creates the header string for the field table generated by L</ShowMetaData>.  This method creates the header string for the field table generated by L</ShowMetaData>.
4159    
# Line 3129  Line 4178 
4178      return _OpenTable($tablename, 'Field', 'Type', 'Description');      return _OpenTable($tablename, 'Field', 'Type', 'Description');
4179  }  }
4180    
4181  =head3 OpenTable  =head3 _OpenTable
4182    
4183  This method creates the header string for an HTML table.  This method creates the header string for an HTML table.
4184    
# Line 3169  Line 4218 
4218      return $htmlString;      return $htmlString;
4219  }  }
4220    
4221  =head3 CloseTable  =head3 _CloseTable
4222    
4223  This method returns the HTML for closing a table.  This method returns the HTML for closing a table.
4224    
# Line 3181  Line 4230 
4230      return "</table></p>\n";      return "</table></p>\n";
4231  }  }
4232    
4233  =head3 ShowField  =head3 _ShowField
4234    
4235  This method returns the HTML for displaying a row of field information in a field table.  This method returns the HTML for displaying a row of field information in a field table.
4236    
# Line 3216  Line 4265 
4265      return $htmlString;      return $htmlString;
4266  }  }
4267    
4268  =head3 HTMLNote  =head3 _HTMLNote
4269    
4270  Convert a note or comment to HTML by replacing some bulletin-board codes with HTML. The codes  Convert a note or comment to HTML by replacing some bulletin-board codes with HTML. The codes
4271  supported are C<[b]> for B<bold>, C<[i]> for I<italics>, and C<[p]> for a new paragraph.  supported are C<[b]> for B<bold>, C<[i]> for I<italics>, and C<[p]> for a new paragraph.

Legend:
Removed from v.1.38  
changed lines
  Added in v.1.72

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3