[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.11, Thu Jun 23 21:24:49 2005 UTC revision 1.98, Mon Jul 7 19:05:55 2008 UTC
# Line 2  Line 2 
2    
3      use strict;      use strict;
4      use Tracer;      use Tracer;
5      use DBKernel;      use DBrtns;
6      use Data::Dumper;      use Data::Dumper;
7      use XML::Simple;      use XML::Simple;
8      use DBQuery;      use DBQuery;
9      use DBObject;      use ERDBObject;
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 CGI;
14        use WikiTools;
15    
16  =head1 Entity-Relationship Database Package  =head1 Entity-Relationship Database Package
17    
# Line 57  Line 60 
60  B<start-position>, which indicates where in the contig that the sequence begins. This attribute  B<start-position>, which indicates where in the contig that the sequence begins. This attribute
61  is implemented as the C<start_position> field in the C<IsMadeUpOf> relation.  is implemented as the C<start_position> field in the C<IsMadeUpOf> relation.
62    
63  The database itself is described by an XML file using the F<ERDatabase.xsd> schema. In addition to  The database itself is described by an XML file. In addition to all the data required to define
64  all the data required to define the entities, relationships, and attributes, the schema provides  the entities, relationships, and attributes, the schema provides space for notes describing
65  space for notes describing the data and what it means. These notes are used by L</ShowMetaData>  the data and what it means. These notes are used by L</ShowMetaData> to generate documentation
66  to generate documentation for the database.  for the database.
67    
68    Special support is provided for text searching. An entity field can be marked as <em>searchable</em>,
69    in which case it will be used to generate a text search index in which the user searches for words
70    in the field instead of a particular field value.
71    
72  Finally, every entity and relationship object has a flag indicating if it is new or old. The object  Finally, every entity and relationship object has a flag indicating if it is new or old. The object
73  is considered I<old> if it was loaded by the L</LoadTables> method. It is considered I<new> if it  is considered I<old> if it was loaded by the L</LoadTables> method. It is considered I<new> if it
74  was inserted by the L</InsertObject> method.  was inserted by the L</InsertObject> method.
75    
 To facilitate testing, the ERDB module supports automatic generation of test data. This process  
 is described in the L</GenerateEntity> and L</GenerateConnection> methods, though it is not yet  
 fully implemented.  
   
76  =head2 XML Database Description  =head2 XML Database Description
77    
78  =head3 Data Types  =head3 Data Types
# Line 89  Line 92 
92    
93  32-bit signed integer  32-bit signed integer
94    
95    =item counter
96    
97    32-bit unsigned integer
98    
99  =item date  =item date
100    
101  64-bit unsigned integer, representing a PERL date/time value  64-bit unsigned integer, representing a PERL date/time value
# Line 108  Line 115 
115  compatability with certain database packages), but the only values supported are  compatability with certain database packages), but the only values supported are
116  0 and 1.  0 and 1.
117    
118    =item id-string
119    
120    variable-length string, maximum 25 characters
121    
122  =item key-string  =item key-string
123    
124  variable-length string, maximum 40 characters  variable-length string, maximum 40 characters
# Line 124  Line 135 
135    
136  variable-length string, maximum 255 characters  variable-length string, maximum 255 characters
137    
138    =item hash-string
139    
140    variable-length string, maximum 22 characters
141    
142  =back  =back
143    
144    The hash-string data type has a special meaning. The actual key passed into the loader will
145    be a string, but it will be digested into a 22-character MD5 code to save space. Although the
146    MD5 algorithm is not perfect, it is extremely unlikely two strings will have the same
147    digest. Therefore, it is presumed the keys will be unique. When the database is actually
148    in use, the hashed keys will be presented rather than the original values. For this reason,
149    they should not be used for entities where the key is meaningful.
150    
151  =head3 Global Tags  =head3 Global Tags
152    
153  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 169  Line 191 
191    
192  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<->),
193  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
194  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,
195    the name C<search-relevance> has special meaning for full-text searches and should not be
196    used as a field name.
197    
198  =item type  =item type
199    
# Line 188  Line 212 
212  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
213  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.
214    
215    =item searchable
216    
217    If specified, then the field is a candidate for full-text searching. A single full-text
218    index will be created for each relation with at least one searchable field in it.
219    For best results, this option should only be used for string or text fields.
220    
221    =item special
222    
223    This attribute allows the subclass to assign special meaning for certain fields.
224    The interpretation is up to the subclass itself. Currently, only entity fields
225    can have this attribute.
226    
227  =back  =back
228    
229  =head3 Indexes  =head3 Indexes
230    
231  An entity can have multiple alternate indexes associated with it. The fields must  An entity can have multiple alternate indexes associated with it. The fields in an
232  be from the primary relation. The alternate indexes assist in ordering results  index must all be from the same relation. The alternate indexes assist in searching
233  from a query. A relationship can have up to two indexes-- a I<to-index> and a  on fields other than the entity ID. A relationship has at least two indexes-- a I<to-index> and a
234  I<from-index>. These order the results when crossing the relationship. For  I<from-index> that order the results when crossing the relationship. For
235  example, in the relationship C<HasContig> from C<Genome> to C<Contig>, the  example, in the relationship C<HasContig> from C<Genome> to C<Contig>, the
236  from-index would order the contigs of a ganome, and the to-index would order  from-index would order the contigs of a ganome, and the to-index would order
237  the genomes of a contig. A relationship's index must specify only fields in  the genomes of a contig. In addition, it can have zero or more alternate
238    indexes. A relationship's index must specify only fields in
239  the relationship.  the relationship.
240    
241  The indexes for an entity must be listed inside the B<Indexes> tag. The from-index  The alternate indexes for an entity or relationship must be listed inside the B<Indexes> tag.
242  of a relationship is specified using the B<FromIndex> tag; the to-index is specified  The from-index of a relationship is specified using the B<FromIndex> tag; the to-index is
243  using the B<ToIndex> tag.  specified using the B<ToIndex> tag.
244    
245  Each index can contain a B<Notes> tag. In addition, it will have an B<IndexFields>  Each index can contain a B<Notes> tag. In addition, it will have an B<IndexFields>
246  tag containing the B<IndexField> tags. These specify, in order, the fields used in  tag containing the B<IndexField> tags. These specify, in order, the fields used in
# Line 221  Line 258 
258    
259  =back  =back
260    
261  The B<Index>, B<FromIndex>, and B<ToIndex> tags themselves have no attributes.  The B<FromIndex>, and B<ToIndex> tags have no attributes. The B<Index> tag can
262    have a B<Unique> attribute. If specified, the index will be generated as a unique
263    index.
264    
265  =head3 Object and Field Names  =head3 Object and Field Names
266    
# Line 265  Line 304 
304    
305  A relationship is described by the C<Relationship> tag. Within a relationship,  A relationship is described by the C<Relationship> tag. Within a relationship,
306  there can be a C<Notes> tag, a C<Fields> tag containing the intersection data  there can be a C<Notes> tag, a C<Fields> tag containing the intersection data
307  fields, a C<FromIndex> tag containing the from-index, and a C<ToIndex> tag containing  fields, a C<FromIndex> tag containing the from-index, a C<ToIndex> tag containing
308  the to-index.  the to-index, and an C<Indexes> tag containing the alternate indexes.
309    
310  The C<Relationship> tag has the following attributes.  The C<Relationship> tag has the following attributes.
311    
# Line 299  Line 338 
338    
339  # Table of information about our datatypes. "sqlType" is the corresponding SQL datatype string.  # Table of information about our datatypes. "sqlType" is the corresponding SQL datatype string.
340  # "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
341  # of the specified type. "dataGen" is PERL string that will be evaluated if no test data generation  # of the specified type. "avgLen" is the average byte length for estimating
342   #string is specified in the field definition.  # record sizes. "sort" is the key modifier for the sort command, "notes" is a type description,
343  my %TypeTable = ( char =>    { sqlType => 'CHAR(1)',            maxLen => 1,            dataGen => "StringGen('A')" },  # and "indexMod", if non-zero, is the number of characters to use when the field is specified in an
344                    int =>     { sqlType => 'INTEGER',            maxLen => 20,           dataGen => "IntGen(0, 99999999)" },  # index
345                    string =>  { sqlType => 'VARCHAR(255)',       maxLen => 255,          dataGen => "StringGen(IntGen(10,250))" },  my %TypeTable = ( char =>    { sqlType => 'CHAR(1)',            maxLen => 1,            avgLen =>   1, sort => "",
346                    text =>    { sqlType => 'TEXT',               maxLen => 1000000000,   dataGen => "StringGen(IntGen(80,1000))" },                                 indexMod =>   0, notes => "single ASCII character"},
347                    date =>    { sqlType => 'BIGINT',             maxLen => 80,           dataGen => "DateGen(-7, 7, IntGen(0,1400))" },                    int =>     { sqlType => 'INTEGER',            maxLen => 20,           avgLen =>   4, sort => "n",
348                    float =>   { sqlType => 'DOUBLE PRECISION',   maxLen => 40,           dataGen => "FloatGen(0.0, 100.0)" },                                 indexMod =>   0, notes => "signed 32-bit integer"},
349                    boolean => { sqlType => 'SMALLINT',           maxLen => 1,            dataGen => "IntGen(0, 1)" },                    counter => { sqlType => 'INTEGER UNSIGNED',   maxLen => 20,           avgLen =>   4, sort => "n",
350                                   indexMod =>   0, notes => "unsigned 32-bit integer"},
351                      string =>  { sqlType => 'VARCHAR(255)',       maxLen => 255,          avgLen => 100, sort => "",
352                                   indexMod =>   0, notes => "character string, 0 to 255 characters"},
353                      text =>    { sqlType => 'TEXT',               maxLen => 1000000000,   avgLen => 500, sort => "",
354                                   indexMod => 255, notes => "character string, nearly unlimited length, only first 255 characters are indexed"},
355                      date =>    { sqlType => 'BIGINT',             maxLen => 80,           avgLen =>   8, sort => "n",
356                                   indexMod =>   0, notes => "signed, 64-bit integer"},
357                      float =>   { sqlType => 'DOUBLE PRECISION',   maxLen => 40,           avgLen =>   8, sort => "g",
358                                   indexMod =>   0, notes => "64-bit double precision floating-point number"},
359                      boolean => { sqlType => 'SMALLINT',           maxLen => 1,            avgLen =>   1, sort => "n",
360                                   indexMod =>   0, notes => "boolean value: 0 if false, 1 if true"},
361                     'hash-string' =>
362                                 { sqlType => 'VARCHAR(22)',        maxLen => 22,           avgLen =>  22, sort => "",
363                                   indexMod =>   0, notes => "string stored in digested form, used for certain types of key fields"},
364                     'id-string' =>
365                                 { sqlType => 'VARCHAR(25)',        maxLen => 25,           avgLen =>  25, sort => "",
366                                   indexMod =>   0, notes => "character string, 0 to 25 characters"},
367                   'key-string' =>                   'key-string' =>
368                               { sqlType => 'VARCHAR(40)',        maxLen => 40,           dataGen => "StringGen(IntGen(10,40))" },                               { sqlType => 'VARCHAR(40)',        maxLen => 40,           avgLen =>  10, sort => "",
369                                   indexMod =>   0, notes => "character string, 0 to 40 characters"},
370                   'name-string' =>                   'name-string' =>
371                               { sqlType => 'VARCHAR(80)',        maxLen => 80,           dataGen => "StringGen(IntGen(10,80))" },                               { sqlType => 'VARCHAR(80)',        maxLen => 80,           avgLen =>  40, sort => "",
372                                   indexMod =>   0, notes => "character string, 0 to 80 characters"},
373                   'medium-string' =>                   'medium-string' =>
374                               { sqlType => 'VARCHAR(160)',       maxLen => 160,          dataGen => "StringGen(IntGen(10,160))" },                               { sqlType => 'VARCHAR(160)',       maxLen => 160,          avgLen =>  40, sort => "",
375                                   indexMod =>   0, notes => "character string, 0 to 160 characters"},
376                     'long-string' =>
377                                 { sqlType => 'VARCHAR(500)',       maxLen => 500,          avglen => 255, sort => "",
378                                   indexMod =>   0, notes => "character string, 0 to 500 characters"},
379                  );                  );
380    
381  # Table translating arities into natural language.  # Table translating arities into natural language.
# Line 322  Line 384 
384                     'MM' => 'many-to-many'                     'MM' => 'many-to-many'
385                   );                   );
386    
387  # Table for interpreting string patterns.  # Options for XML input and output.
388    
389    my %XmlOptions = (GroupTags =>  { Relationships => 'Relationship',
390                                      Entities => 'Entity',
391                                      Fields => 'Field',
392                                      Indexes => 'Index',
393                                      IndexFields => 'IndexField',
394                                      Issues => 'Issue',
395                                      Shapes => 'Shape'
396                                    },
397                      KeyAttr =>    { Relationship => 'name',
398                                      Entity => 'name',
399                                      Field => 'name',
400                                      Shape => 'name'
401                                    },
402                      SuppressEmpty => 1,
403                     );
404    
405  my %PictureTable = ( 'A' => "abcdefghijklmnopqrstuvwxyz",  my %XmlInOpts  = (
406                       '9' => "0123456789",                    ForceArray => [qw(Field Index IndexField Relationship Entity Shape)],
407                       'X' => "abcdefghijklmnopqrstuvwxyz0123456789",                    ForceContent => 1,
408                       'V' => "aeiou",                    NormalizeSpace => 2,
409                       'K' => "bcdfghjklmnoprstvwxyz"                   );
410    my %XmlOutOpts = (
411                      RootName => 'Database',
412                      XMLDecl => 1,
413                     );                     );
414    
415  =head2 Public Methods  =head2 Public Methods
416    
417  =head3 new  =head3 new
418    
419  C<< my $database = ERDB->new($dbh, $metaFileName); >>      my $database = ERDB->new($dbh, $metaFileName);
420    
421  Create a new ERDB object.  Create a new ERDB object.
422    
# Line 355  Line 436 
436    
437  sub new {  sub new {
438      # Get the parameters.      # Get the parameters.
439      my ($class, $dbh, $metaFileName, $options) = @_;      my ($class, $dbh, $metaFileName, %options) = @_;
440      # Load the meta-data.      # Load the meta-data.
441      my $metaData = _LoadMetaData($metaFileName);      my $metaData = _LoadMetaData($metaFileName);
442      # Create the object.      # Create the object.
# Line 369  Line 450 
450    
451  =head3 ShowMetaData  =head3 ShowMetaData
452    
453  C<< $database->ShowMetaData($fileName); >>      $erdb->ShowMetaData($fileName);
454    
455  This method outputs a description of the database. This description can be used to help users create  This method outputs a description of the database. This description can be used to help users create
456  the data to be loaded into the relations.  the data to be loaded into the relations.
# Line 400  Line 481 
481      # Write the HTML heading stuff.      # Write the HTML heading stuff.
482      print HTMLOUT "<html>\n<head>\n<title>$title</title>\n";      print HTMLOUT "<html>\n<head>\n<title>$title</title>\n";
483      print HTMLOUT "</head>\n<body>\n";      print HTMLOUT "</head>\n<body>\n";
484        # Write the documentation.
485        print HTMLOUT $self->DisplayMetaData();
486        # Close the document.
487        print HTMLOUT "</body>\n</html>\n";
488        # Close the file.
489        close HTMLOUT;
490    }
491    
492    =head3 DisplayMetaData
493    
494        my $html = $erdb->DisplayMetaData();
495    
496    Return an HTML description of the database. This description can be used to help users create
497    the data to be loaded into the relations and form queries. The output is raw includable HTML
498    without any HEAD or BODY tags.
499    
500    =over 4
501    
502    =item filename
503    
504    The name of the output file.
505    
506    =back
507    
508    =cut
509    
510    sub DisplayMetaData {
511        # Get the parameters.
512        my ($self) = @_;
513        # Get the metadata and the title string.
514        my $metadata = $self->{_metaData};
515        # Get the title string.
516        my $title = $metadata->{Title};
517        # Get the entity and relationship lists.
518        my $entityList = $metadata->{Entities};
519        my $relationshipList = $metadata->{Relationships};
520        # Declare the return variable.
521        my $retVal = "";
522        # Open the output file.
523        Trace("Building MetaData table of contents.") if T(4);
524      # 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
525      # section contains an ordered list of entity or relationship subsections.      # section contains an ordered list of entity or relationship subsections.
526      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";
527      # Loop through the Entities, displaying a list item for each.      # Loop through the Entities, displaying a list item for each.
528      foreach my $key (sort keys %{$entityList}) {      foreach my $key (sort keys %{$entityList}) {
529          # Display this item.          # Display this item.
530          print HTMLOUT "<li><a href=\"#$key\">$key</a></li>\n";          $retVal .= "<li><a href=\"#$key\">$key</a></li>\n";
531      }      }
532      # Close off the entity section and start the relationship section.      # Close off the entity section and start the relationship section.
533      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";
534      # Loop through the Relationships.      # Loop through the Relationships.
535      foreach my $key (sort keys %{$relationshipList}) {      foreach my $key (sort keys %{$relationshipList}) {
536          # Display this item.          # Display this item.
537          my $relationshipTitle = _ComputeRelationshipSentence($key, $relationshipList->{$key});          my $relationshipTitle = _ComputeRelationshipSentence($key, $relationshipList->{$key});
538          print HTMLOUT "<li><a href=\"#$key\">$relationshipTitle</a></li>\n";          $retVal .= "<li><a href=\"#$key\">$relationshipTitle</a></li>\n";
539      }      }
540      # Close off the relationship section and list the join table section.      # Close off the relationship section and list the join table section.
541      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";
542      # Close off the table of contents itself.      # Close off the table of contents itself.
543      print HTMLOUT "</ul>\n";      $retVal .=  "</ul>\n";
544      # 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.
545      print HTMLOUT "<a name=\"EntitiesSection\"></a><h2>Entities</h2>\n";      $retVal .= "<a name=\"EntitiesSection\"></a><h2>Entities</h2>\n";
546      # Loop through the entities.      # Loop through the entities.
547      for my $key (sort keys %{$entityList}) {      for my $key (sort keys %{$entityList}) {
548          Trace("Building MetaData entry for $key entity.") if T(4);          Trace("Building MetaData entry for $key entity.") if T(4);
549          # Create the entity header. It contains a bookmark and the entity name.          # Create the entity header. It contains a bookmark and the entity name.
550          print HTMLOUT "<a name=\"$key\"></a><h3>$key</h3>\n";          $retVal .= "<a name=\"$key\"></a><h3>$key</h3>\n";
551          # Get the entity data.          # Get the entity data.
552          my $entityData = $entityList->{$key};          my $entityData = $entityList->{$key};
553          # If there's descriptive text, display it.          # If there's descriptive text, display it.
554          if (my $notes = $entityData->{Notes}) {          if (my $notes = $entityData->{Notes}) {
555              print HTMLOUT "<p>" . _HTMLNote($notes->{content}) . "</p>\n";              $retVal .= "<p>" . HTMLNote($notes->{content}) . "</p>\n";
556          }          }
557          # Now we want a list of the entity's relationships. First, we set up the relationship subsection.          # See if we need a list of the entity's relationships.
558          print HTMLOUT "<h4>Relationships for <b>$key</b></h4>\n<ul>\n";          my $relCount = keys %{$relationshipList};
559            if ($relCount > 0) {
560                # First, we set up the relationship subsection.
561                $retVal .= "<h4>Relationships for <b>$key</b></h4>\n<ul>\n";
562          # Loop through the relationships.          # Loop through the relationships.
563          for my $relationship (sort keys %{$relationshipList}) {          for my $relationship (sort keys %{$relationshipList}) {
564              # Get the relationship data.              # Get the relationship data.
# Line 444  Line 568 
568                  # Get the relationship sentence and append the arity.                  # Get the relationship sentence and append the arity.
569                  my $relationshipDescription = _ComputeRelationshipSentence($relationship, $relationshipStructure);                  my $relationshipDescription = _ComputeRelationshipSentence($relationship, $relationshipStructure);
570                  # Display the relationship data.                  # Display the relationship data.
571                  print HTMLOUT "<li><a href=\"#$relationship\">$relationshipDescription</a></li>\n";                      $retVal .= "<li><a href=\"#$relationship\">$relationshipDescription</a></li>\n";
572              }              }
573          }          }
574          # Close off the relationship list.          # Close off the relationship list.
575          print HTMLOUT "</ul>\n";              $retVal .= "</ul>\n";
576            }
577          # Get the entity's relations.          # Get the entity's relations.
578          my $relationList = $entityData->{Relations};          my $relationList = $entityData->{Relations};
579          # Create a header for the relation subsection.          # Create a header for the relation subsection.
580          print HTMLOUT "<h4>Relations for <b>$key</b></h4>\n";          $retVal .= "<h4>Relations for <b>$key</b></h4>\n";
581          # Loop through the relations, displaying them.          # Loop through the relations, displaying them.
582          for my $relation (sort keys %{$relationList}) {          for my $relation (sort keys %{$relationList}) {
583              my $htmlString = _ShowRelationTable($relation, $relationList->{$relation});              my $htmlString = _ShowRelationTable($relation, $relationList->{$relation});
584              print HTMLOUT $htmlString;              $retVal .= $htmlString;
585          }          }
586      }      }
587      # Denote we're starting the relationship section.      # Denote we're starting the relationship section.
588      print HTMLOUT "<a name=\"RelationshipsSection\"></a><h2>Relationships</h2>\n";      $retVal .= "<a name=\"RelationshipsSection\"></a><h2>Relationships</h2>\n";
589      # Loop through the relationships.      # Loop through the relationships.
590      for my $key (sort keys %{$relationshipList}) {      for my $key (sort keys %{$relationshipList}) {
591          Trace("Building MetaData entry for $key relationship.") if T(4);          Trace("Building MetaData entry for $key relationship.") if T(4);
# Line 468  Line 593 
593          my $relationshipStructure = $relationshipList->{$key};          my $relationshipStructure = $relationshipList->{$key};
594          # Create the relationship header.          # Create the relationship header.
595          my $headerText = _ComputeRelationshipHeading($key, $relationshipStructure);          my $headerText = _ComputeRelationshipHeading($key, $relationshipStructure);
596          print HTMLOUT "<h3><a name=\"$key\"></a>$headerText</h3>\n";          $retVal .= "<h3><a name=\"$key\"></a>$headerText</h3>\n";
597          # Get the entity names.          # Get the entity names.
598          my $fromEntity = $relationshipStructure->{from};          my $fromEntity = $relationshipStructure->{from};
599          my $toEntity = $relationshipStructure->{to};          my $toEntity = $relationshipStructure->{to};
# Line 478  Line 603 
603          # since both sentences will say the same thing.          # since both sentences will say the same thing.
604          my $arity = $relationshipStructure->{arity};          my $arity = $relationshipStructure->{arity};
605          if ($arity eq "11") {          if ($arity eq "11") {
606              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";
607          } else {          } else {
608              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";
609              if ($arity eq "MM" && $fromEntity ne $toEntity) {              if ($arity eq "MM" && $fromEntity ne $toEntity) {
610                  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";
611              }              }
612          }          }
613          print HTMLOUT "</p>\n";          $retVal .= "</p>\n";
614          # If there are notes on this relationship, display them.          # If there are notes on this relationship, display them.
615          if (my $notes = $relationshipStructure->{Notes}) {          if (my $notes = $relationshipStructure->{Notes}) {
616              print HTMLOUT "<p>" . _HTMLNote($notes->{content}) . "</p>\n";              $retVal .= "<p>" . HTMLNote($notes->{content}) . "</p>\n";
617          }          }
618          # Generate the relationship's relation table.          # Generate the relationship's relation table.
619          my $htmlString = _ShowRelationTable($key, $relationshipStructure->{Relations}->{$key});          my $htmlString = _ShowRelationTable($key, $relationshipStructure->{Relations}->{$key});
620          print HTMLOUT $htmlString;          $retVal .= $htmlString;
621      }      }
622      Trace("Building MetaData join table.") if T(4);      Trace("Building MetaData join table.") if T(4);
623      # Denote we're starting the join table.      # Denote we're starting the join table.
624      print HTMLOUT "<a name=\"JoinTable\"></a><h3>Join Table</h3>\n";      $retVal .= "<a name=\"JoinTable\"></a><h3>Join Table</h3>\n";
625      # Create a table header.      # Create a table header.
626      print HTMLOUT _OpenTable("Join Table", "Source", "Target", "Join Condition");      $retVal .= _OpenTable("Join Table", "Source", "Target", "Join Condition");
627      # Loop through the joins.      # Loop through the joins.
628      my $joinTable = $metadata->{Joins};      my $joinTable = $metadata->{Joins};
629      my @joinKeys = keys %{$joinTable};      my @joinKeys = keys %{$joinTable};
# Line 506  Line 631 
631          # Separate out the source, the target, and the join clause.          # Separate out the source, the target, and the join clause.
632          $joinKey =~ m!^([^/]+)/(.+)$!;          $joinKey =~ m!^([^/]+)/(.+)$!;
633          my ($sourceRelation, $targetRelation) = ($1, $2);          my ($sourceRelation, $targetRelation) = ($1, $2);
634          Trace("Join with key $joinKey is from $sourceRelation to $targetRelation.") if T(4);          Trace("Join with key $joinKey is from $sourceRelation to $targetRelation.") if T(Joins => 4);
635          my $source = $self->ComputeObjectSentence($sourceRelation);          my $source = $self->ComputeObjectSentence($sourceRelation);
636          my $target = $self->ComputeObjectSentence($targetRelation);          my $target = $self->ComputeObjectSentence($targetRelation);
637          my $clause = $joinTable->{$joinKey};          my $clause = $joinTable->{$joinKey};
638          # Display them in a table row.          # Display them in a table row.
639          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";
640      }      }
641      # Close the table.      # Close the table.
642      print HTMLOUT _CloseTable();      $retVal .= _CloseTable();
643      # Close the document.      Trace("Built MetaData HTML.") if T(3);
644      print HTMLOUT "</body>\n</html>\n";      # Return the HTML.
645      # Close the file.      return $retVal;
     close HTMLOUT;  
     Trace("Built MetaData web page.") if T(3);  
646  }  }
647    
648  =head3 DumpMetaData  =head3 DumpMetaData
649    
650  C<< $database->DumpMetaData(); >>      $erdb->DumpMetaData();
651    
652  Return a dump of the metadata structure.  Return a dump of the metadata structure.
653    
# Line 537  Line 660 
660      return Data::Dumper::Dumper($self->{_metaData});      return Data::Dumper::Dumper($self->{_metaData});
661  }  }
662    
663    =head3 GenerateWikiData
664    
665        my @wikiLines = $erdb->GenerateWikiData();
666    
667    Build a description of the database for the wiki. The database will be
668    organized into a single page, with sections for each entity and relationship.
669    The return value is a list of text lines.
670    
671    =cut
672    
673    sub GenerateWikiData {
674        # Get the parameters.
675        my ($self) = @_;
676        # We'll build the wiki text in here.
677        my @retVal = ();
678        # Get the metadata object.
679        my $metadata = $self->{_metaData};
680        # Get the title string. This will become the page name.
681        my $title = $metadata->{Title}->{content};
682        # Get the entity and relationship lists.
683        my $entityList = $metadata->{Entities};
684        my $relationshipList = $metadata->{Relationships};
685        my $shapeList = $metadata->{Shapes};
686        # Start with the introductory text.
687        push @retVal, WikiTools::Heading(2, "Introduction");
688        if (my $notes = $metadata->{Notes}) {
689            push @retVal, WikiNote($notes->{content});
690        }
691        # Generate issue list.
692        if (my $issues = $metadata->{Issues}) {
693            push @retVal, WikiTools::Heading(3, 'Issues');
694            push @retVal, WikiTools::List(map { $_->{content} } @{$issues});
695        }
696        # Start the entity section.
697        push @retVal, WikiTools::Heading(2, "Entities");
698        # Loop through the entities. Note that unlike the situation with HTML, we
699        # don't need to generate the table of contents manually, just the data
700        # itself.
701        for my $key (sort keys %$entityList) {
702            # Create a header for this entity.
703            push @retVal, "", WikiTools::Heading(3, $key);
704            # Get the entity data.
705            my $entityData = $entityList->{$key};
706            # Plant the notes here, if there are any.
707            push @retVal, _ObjectNotes($entityData);
708            # Get the entity's relations.
709            my $relationList = $entityData->{Relations};
710            # Loop through the relations, displaying them.
711            for my $relation (sort keys %{$relationList}) {
712                my $wikiString = _WikiRelationTable($relation, $relationList->{$relation});
713                push @retVal, $wikiString;
714            }
715            # Now we list the entity's relationships (if any). First, we build a list
716            # of the relationships relevant to this entity.
717            my @rels = ();
718            for my $rel (sort keys %$relationshipList) {
719                my $relStructure = $relationshipList->{$rel};
720                if ($relStructure->{from} eq $key || $relStructure->{to} eq $key) {
721                    # Get the relationship sentence.
722                    my $relSentence = _ComputeRelationshipSentence($rel, $relStructure);
723                    # Linkify it.
724                    my $linkedRel = WikiTools::LinkMarkup("#$rel", $rel);
725                    $relSentence =~ s/$rel/$linkedRel/;
726                    push @rels, $relSentence;
727                }
728            }
729            # Add the relationships as a Wiki list.
730            push @retVal, WikiTools::List(@rels);
731        }
732        # Now the entities are documented. Next we do the relationships.
733        push @retVal, WikiTools::Heading(2, "Relationships");
734        for my $key (sort keys %$relationshipList) {
735            my $relationshipData = $relationshipList->{$key};
736            # Create the relationship heading.
737            push @retVal, WikiTools::Heading(3, $key);
738            # Describe the relationship arity. Note there's a bit of trickiness involving recursive
739            # many-to-many relationships. In a normal many-to-many we use two sentences to describe
740            # the arity (one for each direction). This is a bad idea for a recursive relationship,
741            # since both sentences will say the same thing.
742            my $arity = $relationshipData->{arity};
743            my $fromEntity = $relationshipData->{from};
744            my $toEntity = $relationshipData->{to};
745            my @listElements = ();
746            my $boldCode = WikiTools::BoldCode();
747            if ($arity eq "11") {
748                push @listElements, "Each $boldCode$fromEntity$boldCode relates to at most one $boldCode$toEntity$boldCode.";
749            } else {
750                push @listElements, "Each $boldCode$fromEntity$boldCode relates to multiple $boldCode${toEntity}s$boldCode.";
751                if ($arity eq "MM" && $fromEntity ne $toEntity) {
752                    push @listElements, "Each $boldCode$toEntity$boldCode relates to multiple $boldCode${fromEntity}s$boldCode.";
753                }
754            }
755            push @retVal, WikiTools::List(@listElements);
756            # Plant the notes here, if there are any.
757            push @retVal, _ObjectNotes($relationshipData);
758            # Finally, the relationship table.
759            my $wikiString = _WikiRelationTable($key, $relationshipData->{Relations}->{$key});
760            push @retVal, $wikiString;
761        }
762        # Now loop through the miscellaneous shapes.
763        if ($shapeList) {
764            push @retVal, WikiTools::Heading(2, "Miscellaneous");
765            for my $shape (sort keys %$shapeList) {
766                push @retVal, WikiTools::Heading(3, $shape);
767                my $shapeData = $shapeList->{$shape};
768                push @retVal, _ObjectNotes($shapeData);
769            }
770        }
771        # All done. Return the lines.
772        return @retVal;
773    }
774    
775    
776    =head3 CreatePPO
777    
778        ERDB::CreatePPO($erdbXMLFile, $ppoXMLFile);
779    
780    Create a PPO XML file from an ERDB data definition XML file. At the
781    current time, the PPO XML file can be used to create a database with
782    similar functionality. Eventually, the PPO will be able to use the
783    created XML to access the live ERDB database.
784    
785    =over 4
786    
787    =item erdbXMLFile
788    
789    Name of the XML data definition file for the ERDB database. This
790    file must exist.
791    
792    =item ppoXMLFile
793    
794    Output file for the PPO XML definition. If this file exists, it
795    will be overwritten.
796    
797    =back
798    
799    =cut
800    
801    sub CreatePPO {
802        # Get the parameters.
803        my ($erdbXMLFile, $ppoXMLFile) = @_;
804        # First, we want to slurp in the ERDB XML file in its raw form.
805        my $xml = ReadMetaXML($erdbXMLFile);
806        # Create a variable to hold all of the objects in the PPO project.
807        my @objects = ();
808        # Get the relationship hash.
809        my $relationships = $xml->{Relationships};
810        # Loop through the entities.
811        my $entities = $xml->{Entities};
812        for my $entityName (keys %{$entities}) {
813            # Get the entity's data structures.
814            my $entityObject = $entities->{$entityName};
815            # We put the object's fields in here, according to their type.
816            my (@object_refs, @scalars, @indexes, @arrays);
817            # Create the ID field for the entity. We get the key type from the
818            # entity object and compute the corresponding SQL type.
819            my $type = $TypeTable{$entityObject->{keyType}}->{sqlType};
820            push @scalars, { label => 'id', type => $type };
821            # Loop through the entity fields.
822            for my $fieldName ( keys %{$entityObject->{Fields}} ) {
823                # Get the field object.
824                my $fieldObject = $entityObject->{Fields}->{$fieldName};
825                # Convert it to a scalar tag.
826                my $scalar = _CreatePPOField($fieldName, $fieldObject);
827                # If we have a relation, this field is stored in an array.
828                # otherwise, it is a scalar. The array tag has scalars
829                # stored as an XML array. In ERDB, there is only ever one,
830                # but PPO can have more.
831                my $relation = $fieldObject->{relation};
832                if ($relation) {
833                    push @arrays, { scalar => [$scalar] };
834                } else {
835                    push @scalars, $scalar;
836                }
837            }
838            # Loop through the relationships. If this entity is the to-entity
839            # on a relationship of 1M arity, then it is implemented as a PPO
840            # object reference.
841            for my $relationshipName (keys %{$relationships}) {
842                # Get the relationship data.
843                my $relationshipData = $relationships->{$relationshipName};
844                # If we have a from for this entity and an arity of 1M, we
845                # have an object reference.
846                if ($relationshipData->{to} eq $entityName &&
847                    $relationshipData->{arity} eq '1M') {
848                    # Build the object reference tag.
849                    push @object_refs, { label => $relationshipName,
850                                         type => $relationshipData->{from} };
851                }
852            }
853            # Create the indexes.
854            my $indexList = $entityObject->{Indexes};
855            push @indexes, map { _CreatePPOIndex($_) } @{$indexList};
856            # Build the object XML tree.
857            my $object = { label => $entityName,
858                           object_ref => \@object_refs,
859                           scalar => \@scalars,
860                           index => \@indexes,
861                           array => \@arrays
862                          };
863            # Push the object onto the objects list.
864            push @objects, $object;
865        }
866        # Loop through the relationships, searching for MMs. The 1Ms were
867        # already handled by the entity search above.
868        for my $relationshipName (keys %{$relationships}) {
869            # Get this relationship's object.
870            my $relationshipObject = $relationships->{$relationshipName};
871            # Only proceed if it's many-to-many.
872            if ($relationshipObject->{arity} eq 'MM') {
873                # Create the tag lists for the relationship object.
874                my (@object_refs, @scalars, @indexes);
875                # The relationship will be created as an object with object
876                # references for its links to the participating entities.
877                my %links = ( from_link => $relationshipObject->{from},
878                              to_link => $relationshipObject->{to} );
879                for my $link (keys %links) {
880                    # Create an object_ref tag for this piece of the
881                    # relationship (from or to).
882                    my $object_ref = { label => $link,
883                                       type => $links{$link} };
884                    push @object_refs, $object_ref;
885                }
886                # Loop through the intersection data fields, creating scalar tags.
887                # There are no fancy array tags in a relationship.
888                for my $fieldName (keys %{$relationshipObject->{Fields}}) {
889                    my $fieldObject = $relationshipObject->{Fields}->{$fieldName};
890                    push @scalars, _CreatePPOField($fieldName, $fieldObject);
891                }
892                # Finally, the indexes: currently we cannot support the to-index and
893                # from-index in PPO, so we just process the alternate indexes.
894                my $indexList = $relationshipObject->{Indexes};
895                push @indexes, map { _CreatePPOIndex($_) } @{$indexList};
896                # Wrap up all the stuff about this relationship.
897                my $object = { label => $relationshipName,
898                               scalar => \@scalars,
899                               object_ref => \@object_refs,
900                               index => \@indexes
901                             };
902                # Push it into the object list.
903                push @objects, $object;
904            }
905        }
906        # Compute a title.
907        my $title;
908        if ($erdbXMLFile =~ /(\/|^)([^\/]+)DBD\.xml/) {
909            # Here we have a standard file name we can use for a title.
910            $title = $2;
911        } else {
912            # Here the file name is non-standard, so we carve up the
913            # database title.
914            $title = $xml->{Title}->{content};
915            $title =~ s/\s\.,//g;
916        }
917        # Wrap up the XML as a project.
918        my $ppoXML = { project => { label => $title,
919                                    object => \@objects }};
920        # Write out the results.
921        my $ppoString = XML::Simple::XMLout($ppoXML,
922                                            AttrIndent => 1,
923                                            KeepRoot => 1);
924        Tracer::PutFile($ppoXMLFile, [ $ppoString ]);
925    }
926    
927    =head3 FindIndexForEntity
928    
929        my $indexFound = ERDB::FindIndexForEntity($xml, $entityName, $attributeName);
930    
931    This method locates the entry in an entity's index list that begins with the
932    specified attribute name. If the entity has no index list, one will be
933    created. This method works on raw XML, not a live ERDB object.
934    
935    =over 4
936    
937    =item xml
938    
939    The raw XML structure defining the database.
940    
941    =item entityName
942    
943    The name of the relevant entity.
944    
945    =item attributeName
946    
947    The name of the attribute relevant to the search.
948    
949    =item RETURN
950    
951    The numerical index in the index list of the index entry for the specified entity and
952    attribute, or C<undef> if no such index exists.
953    
954    =back
955    
956    =cut
957    
958    sub FindIndexForEntity {
959        # Get the parameters.
960        my ($xml, $entityName, $attributeName) = @_;
961        # Declare the return variable.
962        my $retVal;
963        # Get the named entity.
964        my $entityData = $xml->{Entities}->{$entityName};
965        if (! $entityData) {
966            Confess("Entity $entityName not found in DBD structure.");
967        } else {
968            # Insure it has an index list.
969            if (! exists $entityData->{Indexes}) {
970                $entityData->{Indexes} = [];
971            } else {
972                # Search for the desired index.
973                my $indexList = $entityData->{Indexes};
974                my $n = scalar @{$indexList};
975                Trace("Searching $n indexes in index list for $entityName.") if T(2);
976                # We use an indexed FOR here because we're returning an
977                # index number instead of an object. We do THAT so we can
978                # delete the index from the list if needed.
979                for (my $i = 0; $i < $n && !defined($retVal); $i++) {
980                    my $index = $indexList->[$i];
981                    my $fields = $index->{IndexFields};
982                    # Technically this IF should be safe (that is, we are guaranteed
983                    # the existence of a "$fields->[0]"), because when we load the XML
984                    # we have SuppressEmpty specified.
985                    if ($fields->[0]->{name} eq $attributeName) {
986                        $retVal = $i;
987                    }
988                }
989            }
990        }
991        Trace("Index for $attributeName of $entityName found at position $retVal.") if defined($retVal) && T(3);
992        Trace("Index for $attributeName not found in $entityName.") if !defined($retVal) && T(3);
993        # Return the result.
994        return $retVal;
995    }
996    
997  =head3 CreateTables  =head3 CreateTables
998    
999  C<< $datanase->CreateTables(); >>      $erdb->CreateTables();
1000    
1001  This method creates the tables for the database from the metadata structure loaded by the  This method creates the tables for the database from the metadata structure loaded by the
1002  constructor. It is expected this function will only be used on rare occasions, when the  constructor. It is expected this function will only be used on rare occasions, when the
# Line 551  Line 1008 
1008  sub CreateTables {  sub CreateTables {
1009      # Get the parameters.      # Get the parameters.
1010      my ($self) = @_;      my ($self) = @_;
1011      my $metadata = $self->{_metaData};      # Get the relation names.
1012      my $dbh = $self->{_dbh};      my @relNames = $self->GetTableNames();
1013      # Loop through the entities.      # Loop through the relations.
1014      my $entityHash = $metadata->{Entities};      for my $relationName (@relNames) {
     for my $entityName (keys %{$entityHash}) {  
         my $entityData = $entityHash->{$entityName};  
         # Tell the user what we're doing.  
         Trace("Creating relations for entity $entityName.") if T(1);  
         # Loop through the entity's relations.  
         for my $relationName (keys %{$entityData->{Relations}}) {  
1015              # Create a table for this relation.              # Create a table for this relation.
1016              $self->CreateTable($relationName);          $self->CreateTable($relationName, 1);
1017              Trace("Relation $relationName created.") if T(1);          Trace("Relation $relationName created.") if T(2);
         }  
     }  
     # Loop through the relationships.  
     my $relationshipTable = $metadata->{Relationships};  
     for my $relationshipName (keys %{$metadata->{Relationships}}) {  
         # Create a table for this relationship.  
         Trace("Creating relationship $relationshipName.") if T(1);  
         $self->CreateTable($relationshipName);  
1018      }      }
1019  }  }
1020    
1021  =head3 CreateTable  =head3 CreateTable
1022    
1023  C<< $database->CreateTable($tableName, $indexFlag); >>      $erdb->CreateTable($tableName, $indexFlag, $estimatedRows);
1024    
1025  Create the table for a relation and optionally create its indexes.  Create the table for a relation and optionally create its indexes.
1026    
# Line 587  Line 1030 
1030    
1031  Name of the relation (which will also be the table name).  Name of the relation (which will also be the table name).
1032    
1033  =item $indexFlag  =item indexFlag
1034    
1035  TRUE if the indexes for the relation should be created, else FALSE. If FALSE,  TRUE if the indexes for the relation should be created, else FALSE. If FALSE,
1036  L</CreateIndexes> must be called later to bring the indexes into existence.  L</CreateIndexes> must be called later to bring the indexes into existence.
1037    
1038    =item estimatedRows (optional)
1039    
1040    If specified, the estimated maximum number of rows for the relation. This
1041    information allows the creation of tables using storage engines that are
1042    faster but require size estimates, such as MyISAM.
1043    
1044  =back  =back
1045    
1046  =cut  =cut
1047    
1048  sub CreateTable {  sub CreateTable {
1049      # Get the parameters.      # Get the parameters.
1050      my ($self, $relationName, $indexFlag) = @_;      my ($self, $relationName, $indexFlag, $estimatedRows) = @_;
1051      # Get the database handle.      # Get the database handle.
1052      my $dbh = $self->{_dbh};      my $dbh = $self->{_dbh};
1053      # Get the relation data and determine whether or not the relation is primary.      # Get the relation data and determine whether or not the relation is primary.
# Line 622  Line 1071 
1071      # Insure the table is not already there.      # Insure the table is not already there.
1072      $dbh->drop_table(tbl => $relationName);      $dbh->drop_table(tbl => $relationName);
1073      Trace("Table $relationName dropped.") if T(2);      Trace("Table $relationName dropped.") if T(2);
1074        # If there are estimated rows, create an estimate so we can take advantage of
1075        # faster DB technologies.
1076        my $estimation = undef;
1077        if ($estimatedRows) {
1078            $estimation = [$self->EstimateRowSize($relationName), $estimatedRows];
1079            Trace("$estimation->[1] rows of $estimation->[0] bytes each.") if T(3);
1080        }
1081      # Create the table.      # Create the table.
1082      Trace("Creating table $relationName: $fieldThing") if T(2);      Trace("Creating table $relationName: $fieldThing") if T(2);
1083      $dbh->create_table(tbl => $relationName, flds => $fieldThing);      $dbh->create_table(tbl => $relationName, flds => $fieldThing, estimates => $estimation);
1084      Trace("Relation $relationName created in database.") if T(2);      Trace("Relation $relationName created in database.") if T(2);
1085      # 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
1086        # index will not be built until the table has been loaded.
1087      if ($indexFlag) {      if ($indexFlag) {
1088          $self->CreateIndex($relationName);          $self->CreateIndex($relationName);
1089      }      }
1090  }  }
1091    
1092    =head3 VerifyFields
1093    
1094        my $count = $erdb->VerifyFields($relName, \@fieldList);
1095    
1096    Run through the list of proposed field values, insuring that all the character fields are
1097    below the maximum length. If any fields are too long, they will be truncated in place.
1098    
1099    =over 4
1100    
1101    =item relName
1102    
1103    Name of the relation for which the specified fields are destined.
1104    
1105    =item fieldList
1106    
1107    Reference to a list, in order, of the fields to be put into the relation.
1108    
1109    =item RETURN
1110    
1111    Returns the number of fields truncated.
1112    
1113    =back
1114    
1115    =cut
1116    
1117    sub VerifyFields {
1118        # Get the parameters.
1119        my ($self, $relName, $fieldList) = @_;
1120        # Initialize the return value.
1121        my $retVal = 0;
1122        # Get the relation definition.
1123        my $relData = $self->_FindRelation($relName);
1124        # Get the list of field descriptors.
1125        my $fieldTypes = $relData->{Fields};
1126        my $fieldCount = scalar @{$fieldTypes};
1127        # Loop through the two lists.
1128        for (my $i = 0; $i < $fieldCount; $i++) {
1129            # Get the type of the current field.
1130            my $fieldType = $fieldTypes->[$i]->{type};
1131            # If it's a character field, verify the length.
1132            if ($fieldType =~ /string/) {
1133                my $maxLen = $TypeTable{$fieldType}->{maxLen};
1134                my $oldString = $fieldList->[$i];
1135                if (length($oldString) > $maxLen) {
1136                    # Here it's too big, so we truncate it.
1137                    Trace("Truncating field $i ($fieldTypes->[$i]->{name}) in relation $relName to $maxLen characters from \"$oldString\".") if T(1);
1138                    $fieldList->[$i] = substr $oldString, 0, $maxLen;
1139                    $retVal++;
1140                }
1141            }
1142        }
1143        # Return the truncation count.
1144        return $retVal;
1145    }
1146    
1147    =head3 DigestFields
1148    
1149        $erdb->DigestFields($relName, $fieldList);
1150    
1151    Digest the strings in the field list that correspond to data type C<hash-string> in the
1152    specified relation.
1153    
1154    =over 4
1155    
1156    =item relName
1157    
1158    Name of the relation to which the fields belong.
1159    
1160    =item fieldList
1161    
1162    List of field contents to be loaded into the relation.
1163    
1164    =back
1165    
1166    =cut
1167    #: Return Type ;
1168    sub DigestFields {
1169        # Get the parameters.
1170        my ($self, $relName, $fieldList) = @_;
1171        # Get the relation definition.
1172        my $relData = $self->_FindRelation($relName);
1173        # Get the list of field descriptors.
1174        my $fieldTypes = $relData->{Fields};
1175        my $fieldCount = scalar @{$fieldTypes};
1176        # Loop through the two lists.
1177        for (my $i = 0; $i < $fieldCount; $i++) {
1178            # Get the type of the current field.
1179            my $fieldType = $fieldTypes->[$i]->{type};
1180            # If it's a hash string, digest it in place.
1181            if ($fieldType eq 'hash-string') {
1182                $fieldList->[$i] = $self->DigestKey($fieldList->[$i]);
1183            }
1184        }
1185    }
1186    
1187    =head3 DigestKey
1188    
1189        my $digested = $erdb->DigestKey($keyValue);
1190    
1191    Return the digested value of a symbolic key. The digested value can then be plugged into a
1192    key-based search into a table with key-type hash-string.
1193    
1194    Currently the digesting process is independent of the database structure, but that may not
1195    always be the case, so this is an instance method instead of a static method.
1196    
1197    =over 4
1198    
1199    =item keyValue
1200    
1201    Key value to digest.
1202    
1203    =item RETURN
1204    
1205    Digested value of the key.
1206    
1207    =back
1208    
1209    =cut
1210    
1211    sub DigestKey {
1212        # Get the parameters.
1213        my ($self, $keyValue) = @_;
1214        # Compute the digest.
1215        my $retVal = md5_base64($keyValue);
1216        # Return the result.
1217        return $retVal;
1218    }
1219    
1220  =head3 CreateIndex  =head3 CreateIndex
1221    
1222  C<< $database->CreateIndex($relationName); >>      $erdb->CreateIndex($relationName);
1223    
1224  Create the indexes for a relation. If a table is being loaded from a large source file (as  Create the indexes for a relation. If a table is being loaded from a large source file (as
1225  is the case in L</LoadTable>), it is best to create the indexes after the load. If that is  is the case in L</LoadTable>), it is sometimes best to create the indexes after the load.
1226  the case, then L</CreateTable> should be called with the index flag set to FALSE, and this  If that is the case, then L</CreateTable> should be called with the index flag set to
1227  method used after the load to create the indexes for the table.  FALSE, and this method used after the load to create the indexes for the table.
1228    
1229  =cut  =cut
1230    
# Line 655  Line 1240 
1240      for my $indexName (keys %{$indexHash}) {      for my $indexName (keys %{$indexHash}) {
1241          my $indexData = $indexHash->{$indexName};          my $indexData = $indexHash->{$indexName};
1242          # Get the index's field list.          # Get the index's field list.
1243          my @fieldList = _FixNames(@{$indexData->{IndexFields}});          my @rawFields = @{$indexData->{IndexFields}};
1244            # Get a hash of the relation's field types.
1245            my %types = map { $_->{name} => $_->{type} } @{$relationData->{Fields}};
1246            # We need to check for text fields so we can append a length limitation for them. To do
1247            # that, we need the relation's field list.
1248            my $relFields = $relationData->{Fields};
1249            for (my $i = 0; $i <= $#rawFields; $i++) {
1250                # Get the field type.
1251                my $field = $rawFields[$i];
1252                my $type = $types{$field};
1253                # Ask if it requires using prefix notation for the index.
1254                my $mod = $TypeTable{$type}->{indexMod};
1255                Trace("Field $field ($i) in $relationName has type $type and indexMod $mod.") if T(3);
1256                if ($mod) {
1257                    # Append the prefix length to the field name,
1258                    $rawFields[$i] .= "($mod)";
1259                }
1260            }
1261            my @fieldList = _FixNames(@rawFields);
1262          my $flds = join(', ', @fieldList);          my $flds = join(', ', @fieldList);
1263          # Get the index's uniqueness flag.          # Get the index's uniqueness flag.
1264          my $unique = (exists $indexData->{Unique} ? $indexData->{Unique} : 'false');          my $unique = (exists $indexData->{Unique} ? 'unique' : undef);
1265          # Create the index.          # Create the index.
1266          $dbh->create_index(idx => $indexName, tbl => $relationName, flds => $flds, unique => $unique);          my $rv = $dbh->create_index(idx => $indexName, tbl => $relationName,
1267                                        flds => $flds, kind => $unique);
1268            if ($rv) {
1269          Trace("Index created: $indexName for $relationName ($flds)") if T(1);          Trace("Index created: $indexName for $relationName ($flds)") if T(1);
1270            } else {
1271                Confess("Error creating index $indexName for $relationName using ($flds): " . $dbh->error_message());
1272            }
1273      }      }
1274  }  }
1275    
1276  =head3 LoadTables  =head3 GetSecondaryFields
   
 C<< my $stats = $database->LoadTables($directoryName, $rebuild); >>  
1277    
1278  This method will load the database tables from a directory. The tables must already have been created      my %fieldTuples = $erdb->GetSecondaryFields($entityName);
 in the database. (This can be done by calling L</CreateTables>.) The caller passes in a directory name;  
 all of the relations to be loaded must have a file in the directory with the same name as the relation  
 (optionally with a suffix of C<.dtx>). Each file must be a tab-delimited table of field values. Each  
 line of the file will be loaded as a row of the target relation table. The field values should be in  
 the same order as the fields in the relation tables generated by L</ShowMetaData>. The old data is  
 erased before the new data is loaded in.  
1279    
1280  A certain amount of translation automatically takes place. Ctrl-M characters are deleted, and  This method will return a list of the name and type of each of the secondary
1281  tab and new-line characters inside a field are escaped as C<\t> and C<\n>, respectively. Dates must  fields for a specified entity. Secondary fields are stored in two-column tables
1282  be entered as a Unix timestamp, that is, as an integer number of seconds since the base epoch.  in addition to the primary entity table. This enables the field to have no value
1283    or to have multiple values.
1284    
1285  =over 4  =over 4
1286    
1287  =item directoryName  =item entityName
   
 Name of the directory containing the relation files to be loaded.  
   
 =item rebuild  
1288    
1289  TRUE if the tables should be dropped and rebuilt, else FALSE. This is, unfortunately, the  Name of the entity whose secondary fields are desired.
 only way to erase existing data in the tables, since the TRUNCATE command is not supported  
 by all of the DB engines we use.  
1290    
1291  =item RETURN  =item RETURN
1292    
1293  Returns a statistical object describing the number of records read and a list of the error messages.  Returns a hash mapping the field names to their field types.
1294    
1295  =back  =back
1296    
1297  =cut  =cut
1298    
1299  sub LoadTables {  sub GetSecondaryFields {
1300      # Get the parameters.      # Get the parameters.
1301      my ($self, $directoryName, $rebuild) = @_;      my ($self, $entityName) = @_;
1302      # Start the timer.      # Declare the return variable.
1303        my %retVal = ();
1304        # Look for the entity.
1305        my $table = $self->GetFieldTable($entityName);
1306        # Loop through the fields, pulling out the secondaries.
1307        for my $field (sort keys %{$table}) {
1308            if ($table->{$field}->{relation} ne $entityName) {
1309                # Here we have a secondary field.
1310                $retVal{$field} = $table->{$field}->{type};
1311            }
1312        }
1313        # Return the result.
1314        return %retVal;
1315    }
1316    
1317    =head3 GetFieldRelationName
1318    
1319        my $name = $erdb->GetFieldRelationName($objectName, $fieldName);
1320    
1321    Return the name of the relation containing a specified field.
1322    
1323    =over 4
1324    
1325    =item objectName
1326    
1327    Name of the entity or relationship containing the field.
1328    
1329    =item fieldName
1330    
1331    Name of the relevant field in that entity or relationship.
1332    
1333    =item RETURN
1334    
1335    Returns the name of the database relation containing the field, or C<undef> if
1336    the field does not exist.
1337    
1338    =back
1339    
1340    =cut
1341    
1342    sub GetFieldRelationName {
1343        # Get the parameters.
1344        my ($self, $objectName, $fieldName) = @_;
1345        # Declare the return variable.
1346        my $retVal;
1347        # Get the object field table.
1348        my $table = $self->GetFieldTable($objectName);
1349        # Only proceed if the field exists.
1350        if (exists $table->{$fieldName}) {
1351            # Determine the name of the relation that contains this field.
1352            $retVal = $table->{$fieldName}->{relation};
1353        }
1354        # Return the result.
1355        return $retVal;
1356    }
1357    
1358    =head3 DeleteValue
1359    
1360        my $numDeleted = $erdb->DeleteValue($entityName, $id, $fieldName, $fieldValue);
1361    
1362    Delete secondary field values from the database. This method can be used to delete all
1363    values of a specified field for a particular entity instance, or only a single value.
1364    
1365    Secondary fields are stored in two-column relations separate from an entity's primary
1366    table, and as a result a secondary field can legitimately have no value or multiple
1367    values. Therefore, it makes sense to talk about deleting secondary fields where it
1368    would not make sense for primary fields.
1369    
1370    =over 4
1371    
1372    =item entityName
1373    
1374    Name of the entity from which the fields are to be deleted.
1375    
1376    =item id
1377    
1378    ID of the entity instance to be processed. If the instance is not found, this
1379    method will have no effect. If C<undef> is specified, all values for all of
1380    the entity instances will be deleted.
1381    
1382    =item fieldName
1383    
1384    Name of the field whose values are to be deleted.
1385    
1386    =item fieldValue (optional)
1387    
1388    Value to be deleted. If not specified, then all values of the specified field
1389    will be deleted for the entity instance. If specified, then only the values which
1390    match this parameter will be deleted.
1391    
1392    =item RETURN
1393    
1394    Returns the number of rows deleted.
1395    
1396    =back
1397    
1398    =cut
1399    
1400    sub DeleteValue {
1401        # Get the parameters.
1402        my ($self, $entityName, $id, $fieldName, $fieldValue) = @_;
1403        # Declare the return value.
1404        my $retVal = 0;
1405        # We need to set up an SQL command to do the deletion. First, we
1406        # find the name of the field's relation.
1407        my $table = $self->GetFieldTable($entityName);
1408        my $field = $table->{$fieldName};
1409        my $relation = $field->{relation};
1410        # Make sure this is a secondary field.
1411        if ($relation eq $entityName) {
1412            Confess("Cannot delete values of $fieldName for $entityName.");
1413        } else {
1414            # Set up the SQL command to delete all values.
1415            my $sql = "DELETE FROM $relation";
1416            # Build the filter.
1417            my @filters = ();
1418            my @parms = ();
1419            # Check for a filter by ID.
1420            if (defined $id) {
1421                push @filters, "id = ?";
1422                push @parms, $id;
1423            }
1424            # Check for a filter by value.
1425            if (defined $fieldValue) {
1426                push @filters, "$fieldName = ?";
1427                push @parms, $fieldValue;
1428            }
1429            # Append the filters to the command.
1430            if (@filters) {
1431                $sql .= " WHERE " . join(" AND ", @filters);
1432            }
1433            # Execute the command.
1434            my $dbh = $self->{_dbh};
1435            $retVal = $dbh->SQL($sql, 0, @parms);
1436        }
1437        # Return the result.
1438        return $retVal;
1439    }
1440    
1441    =head3 LoadTables
1442    
1443        my $stats = $erdb->LoadTables($directoryName, $rebuild);
1444    
1445    This method will load the database tables from a directory. The tables must already have been created
1446    in the database. (This can be done by calling L</CreateTables>.) The caller passes in a directory name;
1447    all of the relations to be loaded must have a file in the directory with the same name as the relation
1448    (optionally with a suffix of C<.dtx>). Each file must be a tab-delimited table of field values. Each
1449    line of the file will be loaded as a row of the target relation table. The field values should be in
1450    the same order as the fields in the relation tables generated by L</ShowMetaData>. The old data is
1451    erased before the new data is loaded in.
1452    
1453    A certain amount of translation automatically takes place. Ctrl-M characters are deleted, and
1454    tab and new-line characters inside a field are escaped as C<\t> and C<\n>, respectively. Dates must
1455    be entered as a Unix timestamp, that is, as an integer number of seconds since the base epoch.
1456    
1457    =over 4
1458    
1459    =item directoryName
1460    
1461    Name of the directory containing the relation files to be loaded.
1462    
1463    =item rebuild
1464    
1465    TRUE if the tables should be dropped and rebuilt, else FALSE. This is, unfortunately, the
1466    only way to erase existing data in the tables, since the TRUNCATE command is not supported
1467    by all of the DB engines we use.
1468    
1469    =item RETURN
1470    
1471    Returns a statistical object describing the number of records read and a list of the error messages.
1472    
1473    =back
1474    
1475    =cut
1476    
1477    sub LoadTables {
1478        # Get the parameters.
1479        my ($self, $directoryName, $rebuild) = @_;
1480        # Start the timer.
1481      my $startTime = gettimeofday;      my $startTime = gettimeofday;
1482      # Clean any trailing slash from the directory name.      # Clean any trailing slash from the directory name.
1483      $directoryName =~ s!/\\$!!;      $directoryName =~ s!/\\$!!;
1484      # Declare the return variable.      # Declare the return variable.
1485      my $retVal = Stats->new();      my $retVal = Stats->new();
1486      # Get the metadata structure.      # Get the relation names.
1487      my $metaData = $self->{_metaData};      my @relNames = $self->GetTableNames();
1488      # Loop through the entities.      for my $relationName (@relNames) {
     for my $entity (values %{$metaData->{Entities}}) {  
         # Loop through the entity's relations.  
         for my $relationName (keys %{$entity->{Relations}}) {  
1489              # Try to load this relation.              # Try to load this relation.
1490              my $result = $self->_LoadRelation($directoryName, $relationName, $rebuild);              my $result = $self->_LoadRelation($directoryName, $relationName, $rebuild);
1491              # Accumulate the statistics.              # Accumulate the statistics.
1492              $retVal->Accumulate($result);              $retVal->Accumulate($result);
1493          }          }
     }  
     # Loop through the relationships.  
     for my $relationshipName (keys %{$metaData->{Relationships}}) {  
         # Try to load this relationship's relation.  
         my $result = $self->_LoadRelation($directoryName, $relationshipName, $rebuild);  
         # Accumulate the statistics.  
         $retVal->Accumulate($result);  
     }  
1494      # Add the duration of the load to the statistical object.      # Add the duration of the load to the statistical object.
1495      $retVal->Add('duration', gettimeofday - $startTime);      $retVal->Add('duration', gettimeofday - $startTime);
1496      # Return the accumulated statistics.      # Return the accumulated statistics.
1497      return $retVal;      return $retVal;
1498  }  }
1499    
1500    
1501  =head3 GetTableNames  =head3 GetTableNames
1502    
1503  C<< my @names = $database->GetTableNames; >>      my @names = $erdb->GetTableNames;
1504    
1505  Return a list of the relations required to implement this database.  Return a list of the relations required to implement this database.
1506    
# Line 754  Line 1517 
1517    
1518  =head3 GetEntityTypes  =head3 GetEntityTypes
1519    
1520  C<< my @names = $database->GetEntityTypes; >>      my @names = $erdb->GetEntityTypes;
1521    
1522  Return a list of the entity type names.  Return a list of the entity type names.
1523    
# Line 769  Line 1532 
1532      return sort keys %{$entityList};      return sort keys %{$entityList};
1533  }  }
1534    
1535    =head3 GetDataTypes
1536    
1537        my %types = ERDB::GetDataTypes();
1538    
1539    Return a table of ERDB data types. The table returned is a hash of hashes.
1540    The keys of the big hash are the datatypes. Each smaller hash has several
1541    values used to manage the data. The most interesting is the SQL type (key
1542    C<sqlType>) and the descriptive node (key C<notes>).
1543    
1544    Note that changing the values in the smaller hashes will seriously break
1545    things, so this data should be treated as read-only.
1546    
1547    =cut
1548    
1549    sub GetDataTypes {
1550        return %TypeTable;
1551    }
1552    
1553    
1554    =head3 IsEntity
1555    
1556        my $flag = $erdb->IsEntity($entityName);
1557    
1558    Return TRUE if the parameter is an entity name, else FALSE.
1559    
1560    =over 4
1561    
1562    =item entityName
1563    
1564    Object name to be tested.
1565    
1566    =item RETURN
1567    
1568    Returns TRUE if the specified string is an entity name, else FALSE.
1569    
1570    =back
1571    
1572    =cut
1573    
1574    sub IsEntity {
1575        # Get the parameters.
1576        my ($self, $entityName) = @_;
1577        # Test to see if it's an entity.
1578        return exists $self->{_metaData}->{Entities}->{$entityName};
1579    }
1580    
1581  =head3 Get  =head3 Get
1582    
1583  C<< my $query = $database->Get(\@objectNames, $filterClause, $param1, $param2, ..., $paramN); >>      my $query = $erdb->Get(\@objectNames, $filterClause, \@params);
1584    
1585  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.
1586  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 779  Line 1588 
1588  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
1589  $genus.  $genus.
1590    
1591  C<< $query = $sprout->Get(['Genome'], "Genome(genus) = ?", $genus); >>      $query = $erdb->Get(['Genome'], "Genome(genus) = ?", [$genus]);
1592    
1593  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
1594  parameter representing the parameter value. It would also be possible to code  parameter representing the parameter value. It would also be possible to code
1595    
1596  C<< $query = $sprout->Get(['Genome'], "Genome(genus) = \'$genus\'"); >>      $query = $erdb->Get(['Genome'], "Genome(genus) = \'$genus\'");
1597    
1598  however, this version of the call would generate a syntax error if there were any quote  however, this version of the call would generate a syntax error if there were any quote
1599  characters inside the variable C<$genus>.  characters inside the variable C<$genus>.
# Line 796  Line 1605 
1605  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
1606  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,
1607    
1608  C<< $query = $sprout->Get(['Genome', 'ComesFrom', 'Source'], "Genome(genus) = ?", $genus); >>      $query = $erdb->Get(['Genome', 'ComesFrom', 'Source'], "Genome(genus) = ?", [$genus]);
1609    
1610  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
1611  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.
1612  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
1613  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
1614  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  
1615  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,
1616  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.
1617    
1618    If an entity or relationship is mentioned twice, the name for the second occurrence will
1619    be suffixed with C<2>, the third occurrence will be suffixed with C<3>, and so forth. So,
1620    for example, if we have C<['Feature', 'HasContig', 'Contig', 'HasContig']>, then the
1621    B<to-link> field of the first B<HasContig> is specified as C<HasContig(to-link)>, while
1622    the B<to-link> field of the second B<HasContig> is specified as C<HasContig2(to-link)>.
1623    
1624  =over 4  =over 4
1625    
1626  =item objectNames  =item objectNames
# Line 827  Line 1641 
1641  with an ORDER BY clause. For example, the following filter string gets all genomes for a  with an ORDER BY clause. For example, the following filter string gets all genomes for a
1642  particular genus and sorts them by species name.  particular genus and sorts them by species name.
1643    
1644  C<< "Genome(genus) = ? ORDER BY Genome(species)" >>      "Genome(genus) = ? ORDER BY Genome(species)"
1645    
1646    Note that the case is important. Only an uppercase "ORDER BY" with a single space will
1647    be processed. The idea is to make it less likely to find the verb by accident.
1648    
1649  The rules for field references in a sort order are the same as those for field references in the  The rules for field references in a sort order are the same as those for field references in the
1650  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
1651  relation.  relation.
1652    
1653  =item param1, param2, ..., paramN  Finally, you can limit the number of rows returned by adding a LIMIT clause. The LIMIT must
1654    be the last thing in the filter clause, and it contains only the word "LIMIT" followed by
1655    a positive number. So, for example
1656    
1657        "Genome(genus) = ? ORDER BY Genome(species) LIMIT 10"
1658    
1659    will only return the first ten genomes for the specified genus. The ORDER BY clause is not
1660    required. For example, to just get the first 10 genomes in the B<Genome> table, you could
1661    use
1662    
1663        "LIMIT 10"
1664    
1665    =item params
1666    
1667  Parameter values to be substituted into the filter clause.  Reference to a list of parameter values to be substituted into the filter clause.
1668    
1669  =item RETURN  =item RETURN
1670    
# Line 847  Line 1676 
1676    
1677  sub Get {  sub Get {
1678      # Get the parameters.      # Get the parameters.
1679      my ($self, $objectNames, $filterClause, @params) = @_;      my ($self, $objectNames, $filterClause, $params) = @_;
1680      # Construct the SELECT statement. The general pattern is      # Process the SQL stuff.
1681      #      my ($suffix, $mappedNameListRef, $mappedNameHashRef) =
1682      # SELECT name1.*, name2.*, ... nameN.* FROM name1, name2, ... nameN          $self->_SetupSQL($objectNames, $filterClause);
1683      #      # Create the query.
1684      my $dbh = $self->{_dbh};      my $command = "SELECT " . join(".*, ", @{$mappedNameListRef}) .
1685      my $command = "SELECT DISTINCT " . join('.*, ', @{$objectNames}) . ".* FROM " .          ".* $suffix";
1686                  join(', ', @{$objectNames});      my $sth = $self->_GetStatementHandle($command, $params);
1687      # Check for a filter clause.      # Now we create the relation map, which enables DBQuery to determine the order, name
1688      if ($filterClause) {      # and mapped name for each object in the query.
1689          # Here we have one, so we convert its field names and add it to the query. First,      my @relationMap = ();
1690          # We create a copy of the filter string we can work with.      for my $mappedName (@{$mappedNameListRef}) {
1691          my $filterString = $filterClause;          push @relationMap, [$mappedName, $mappedNameHashRef->{$mappedName}];
         # Next, we sort the object names by length. This helps protect us from finding  
         # object names inside other object names when we're doing our search and replace.  
         my @sortedNames = sort { length($b) - length($a) } @{$objectNames};  
         # We will also keep a list of conditions to add to the WHERE clause in order to link  
         # entities and relationships as well as primary relations to secondary ones.  
         my @joinWhere = ();  
         # The final preparatory step is to create a hash table of relation names. The  
         # table begins with the relation names already in the SELECT command.  
         my %fromNames = ();  
         for my $objectName (@sortedNames) {  
             $fromNames{$objectName} = 1;  
         }  
         # We are ready to begin. We loop through the object names, replacing each  
         # object name's field references by the corresponding SQL field reference.  
         # Along the way, if we find a secondary relation, we will need to add it  
         # to the FROM clause.  
         for my $objectName (@sortedNames) {  
             # Get the length of the object name plus 2. This is the value we add to the  
             # size of the field name to determine the size of the field reference as a  
             # whole.  
             my $nameLength = 2 + length $objectName;  
             # Get the object's field list.  
             my $fieldList = $self->_GetFieldTable($objectName);  
             # Find the field references for this object.  
             while ($filterString =~ m/$objectName\(([^)]*)\)/g) {  
                 # At this point, $1 contains the field name, and the current position  
                 # is set immediately after the final parenthesis. We pull out the name of  
                 # the field and the position and length of the field reference as a whole.  
                 my $fieldName = $1;  
                 my $len = $nameLength + length $fieldName;  
                 my $pos = pos($filterString) - $len;  
                 # Insure the field exists.  
                 if (!exists $fieldList->{$fieldName}) {  
                     Confess("Field $fieldName not found for object $objectName.");  
                 } else {  
                     # Get the field's relation.  
                     my $relationName = $fieldList->{$fieldName}->{relation};  
                     # Insure the relation is in the FROM clause.  
                     if (!exists $fromNames{$relationName}) {  
                         # Add the relation to the FROM clause.  
                         $command .= ", $relationName";  
                         # Create its join sub-clause.  
                         push @joinWhere, "$objectName.id = $relationName.id";  
                         # Denote we have it available for future fields.  
                         $fromNames{$relationName} = 1;  
                     }  
                     # Form an SQL field reference from the relation name and the field name.  
                     my $sqlReference = "$relationName." . _FixName($fieldName);  
                     # Put it into the filter string in place of the old value.  
                     substr($filterString, $pos, $len) = $sqlReference;  
                     # Reposition the search.  
                     pos $filterString = $pos + length $sqlReference;  
                 }  
             }  
         }  
         # The next step is to join the objects together. We only need to do this if there  
         # is more than one object in the object list. We start with the first object and  
         # run through the objects after it. Note also that we make a safety copy of the  
         # list before running through it.  
         my @objectList = @{$objectNames};  
         my $lastObject = shift @objectList;  
         # Get the join table.  
         my $joinTable = $self->{_metaData}->{Joins};  
         # Loop through the object list.  
         for my $thisObject (@objectList) {  
             # Look for a join.  
             my $joinKey = "$lastObject/$thisObject";  
             if (!exists $joinTable->{$joinKey}) {  
                 # Here there's no join, so we throw an error.  
                 Confess("No join exists to connect from $lastObject to $thisObject.");  
             } else {  
                 # Get the join clause and add it to the WHERE list.  
                 push @joinWhere, $joinTable->{$joinKey};  
                 # Save this object as the last object for the next iteration.  
                 $lastObject = $thisObject;  
             }  
         }  
         # Now we need to handle the whole ORDER BY thing. We'll put the order by clause  
         # in the following variable.  
         my $orderClause = "";  
         # Locate the ORDER BY verb (if any).  
         if ($filterString =~ m/^(.*)ORDER BY/g) {  
             # Here we have an ORDER BY verb. Split it off of the filter string.  
             my $pos = pos $filterString;  
             $orderClause = substr($filterString, $pos);  
             $filterString = $1;  
         }  
         # Add the filter and the join clauses (if any) to the SELECT command.  
         if ($filterString) {  
             push @joinWhere, "($filterString)";  
         }  
         if (@joinWhere) {  
             $command .= " WHERE " . join(' AND ', @joinWhere);  
         }  
         # Add the sort clause (if any) to the SELECT command.  
         if ($orderClause) {  
             $command .= " ORDER BY $orderClause";  
         }  
1692      }      }
     Trace("SQL query: $command") if T(2);  
     Trace("PARMS: '" . (join "', '", @params) . "'") if (T(3) && (@params > 0));  
     my $sth = $dbh->prepare_command($command);  
     # Execute it with the parameters bound in.  
     $sth->execute(@params) || Confess("SELECT error" . $sth->errstr());  
1693      # Return the statement object.      # Return the statement object.
1694      my $retVal = DBQuery::_new($self, $sth, @{$objectNames});      my $retVal = DBQuery::_new($self, $sth, \@relationMap);
1695      return $retVal;      return $retVal;
1696  }  }
1697    
 =head3 GetList  
1698    
 C<< my @dbObjects = $database->GetList(\@objectNames, $filterClause, $param1, $param2, ..., $paramN); >>  
1699    
1700  Return a list of object descriptors for the specified objects as determined by the  =head3 Search
 specified filter clause.  
1701    
1702  This method is essentially the same as L</Get> except it returns a list of objects rather      my $query = $erdb->Search($searchExpression, $idx, \@objectNames, $filterClause, \@params);
1703  than a query object that can be used to get the results one record at a time.  
1704    Perform a full text search with filtering. The search will be against a specified object
1705    in the object name list. That object will get an extra field containing the search
1706    relevance. Note that except for the search expression, the parameters of this method are
1707    the same as those for L</Get> and follow the same rules.
1708    
1709  =over 4  =over 4
1710    
1711    =item searchExpression
1712    
1713    Boolean search expression for the text fields of the target object. The default mode for
1714    a Boolean search expression is OR, but we want the default to be AND, so we will
1715    add a C<+> operator to each word with no other operator before it.
1716    
1717    =item idx
1718    
1719    Index in the I<$objectNames> list of the table to be searched in full-text mode.
1720    
1721  =item objectNames  =item objectNames
1722    
1723  List containing the names of the entity and relationship objects to be retrieved.  List containing the names of the entity and relationship objects to be retrieved.
# Line 995  Line 1732 
1732  or secondary entity relations; however, all of the entities and relationships involved must  or secondary entity relations; however, all of the entities and relationships involved must
1733  be included in the list of object names.  be included in the list of object names.
1734    
1735  The filter clause can also specify a sort order. To do this, simply follow the filter string  =item params
 with an ORDER BY clause. For example, the following filter string gets all genomes for a  
 particular genus and sorts them by species name.  
   
 C<< "Genome(genus) = ? ORDER BY Genome(species)" >>  
1736    
1737  The rules for field references in a sort order are the same as those for field references in the  Reference to a list of parameter values to be substituted into the filter clause.
 filter clause in general; however, odd things may happen if a sort field is from a secondary  
 relation.  
   
 =item param1, param2, ..., paramN  
   
 Parameter values to be substituted into the filter clause.  
1738    
1739  =item RETURN  =item RETURN
1740    
1741  Returns a list of B<DBObject>s that satisfy the query conditions.  Returns a query object for the specified search.
1742    
1743  =back  =back
1744    
1745  =cut  =cut
1746  #: Return Type @%  
1747  sub GetList {  sub Search {
1748      # Get the parameters.      # Get the parameters.
1749      my ($self, $objectNames, $filterClause, @params) = @_;      my ($self, $searchExpression, $idx, $objectNames, $filterClause, $params) = @_;
1750      # Declare the return variable.      # Declare the return variable.
1751      my @retVal = ();      my $retVal;
1752      # Perform the query.      # Create a safety copy of the parameter list. Note we have to be careful to insure
1753      my $query = $self->Get($objectNames, $filterClause, @params);      # a parameter list exists before we copy it.
1754      # Loop through the results.      my @myParams = ();
1755      while (my $object = $query->Fetch) {      if (defined $params) {
1756          push @retVal, $object;          @myParams = @{$params};
1757        }
1758        # Get the first object's structure so we have access to the searchable fields.
1759        my $object1Name = $objectNames->[$idx];
1760        my $object1Structure = $self->_GetStructure($object1Name);
1761        # Get the field list.
1762        if (! exists $object1Structure->{searchFields}) {
1763            Confess("No searchable index for $object1Name.");
1764        } else {
1765            # Get the field list.
1766            my @fields = @{$object1Structure->{searchFields}};
1767            # Clean the search expression.
1768            my $actualKeywords = $self->CleanKeywords($searchExpression);
1769            # Prefix a "+" to each uncontrolled word. This converts the default
1770            # search mode from OR to AND.
1771            $actualKeywords =~ s/(^|\s)(\w|")/$1\+$2/g;
1772            Trace("Actual keywords for search are\n$actualKeywords") if T(3);
1773            # We need two match expressions, one for the filter clause and one in the
1774            # query itself. Both will use a parameter mark, so we need to push the
1775            # search expression onto the front of the parameter list twice.
1776            unshift @myParams, $actualKeywords, $actualKeywords;
1777            # Build the match expression.
1778            my @matchFilterFields = map { "$object1Name." . _FixName($_) } @fields;
1779            my $matchClause = "MATCH (" . join(", ", @matchFilterFields) . ") AGAINST (? IN BOOLEAN MODE)";
1780            # Process the SQL stuff.
1781            my ($suffix, $mappedNameListRef, $mappedNameHashRef) =
1782                $self->_SetupSQL($objectNames, $filterClause, $matchClause);
1783            # Create the query. Note that the match clause is inserted at the front of
1784            # the select fields.
1785            my $command = "SELECT $matchClause, " . join(".*, ", @{$mappedNameListRef}) .
1786                ".* $suffix";
1787            my $sth = $self->_GetStatementHandle($command, \@myParams);
1788            # Now we create the relation map, which enables DBQuery to determine the order, name
1789            # and mapped name for each object in the query.
1790            my @relationMap = _RelationMap($mappedNameHashRef, $mappedNameListRef);
1791            # Return the statement object.
1792            $retVal = DBQuery::_new($self, $sth, \@relationMap, $object1Name);
1793      }      }
1794      # Return the result.      return $retVal;
     return @retVal;  
1795  }  }
1796    
1797  =head3 ComputeObjectSentence  =head3 GetFlat
1798    
1799  C<< my $sentence = $database->ComputeObjectSentence($objectName); >>      my @list = $erdb->GetFlat(\@objectNames, $filterClause, \@parameterList, $field);
1800    
1801  Check an object name, and if it is a relationship convert it to a relationship sentence.  This is a variation of L</GetAll> that asks for only a single field per record and
1802    returns a single flattened list.
1803    
1804  =over 4  =over 4
1805    
1806  =item objectName  =item objectNames
1807    
1808  Name of the entity or relationship.  List containing the names of the entity and relationship objects to be retrieved.
1809    
1810    =item filterClause
1811    
1812    WHERE/ORDER BY clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can
1813    be parameterized with parameter markers (C<?>). Each field used must be specified in the standard form
1814    B<I<objectName>(I<fieldName>)>. Any parameters specified in the filter clause should be added to the
1815    parameter list as additional parameters. The fields in a filter clause can come from primary
1816    entity relations, relationship relations, or secondary entity relations; however, all of the
1817    entities and relationships involved must be included in the list of object names.
1818    
1819    =item parameterList
1820    
1821    List of the parameters to be substituted in for the parameters marks in the filter clause.
1822    
1823    =item field
1824    
1825    Name of the field to be used to get the elements of the list returned.
1826    
1827  =item RETURN  =item RETURN
1828    
1829  Returns a string containing the entity name or a relationship sentence.  Returns a list of values.
1830    
1831  =back  =back
1832    
1833  =cut  =cut
1834    #: Return Type @;
1835  sub ComputeObjectSentence {  sub GetFlat {
1836      # Get the parameters.      # Get the parameters.
1837      my ($self, $objectName) = @_;      my ($self, $objectNames, $filterClause, $parameterList, $field) = @_;
1838      # Set the default return value.      # Construct the query.
1839      my $retVal = $objectName;      my $query = $self->Get($objectNames, $filterClause, $parameterList);
1840      # Look for the object as a relationship.      # Create the result list.
1841      my $relTable = $self->{_metaData}->{Relationships};      my @retVal = ();
1842      if (exists $relTable->{$objectName}) {      # Loop through the records, adding the field values found to the result list.
1843          # Get the relationship sentence.      while (my $row = $query->Fetch()) {
1844          $retVal = _ComputeRelationshipSentence($objectName, $relTable->{$objectName});          push @retVal, $row->Value($field);
1845      }      }
1846      # Return the result.      # Return the list created.
1847      return $retVal;      return @retVal;
1848  }  }
1849    
1850  =head3 DumpRelations  =head3 SpecialFields
1851    
1852  C<< $database->DumpRelations($outputDirectory); >>      my %specials = $erdb->SpecialFields($entityName);
1853    
1854  Write the contents of all the relations to tab-delimited files in the specified directory.  Return a hash mapping special fields in the specified entity to the value of their
1855  Each file will have the same name as the relation dumped, with an extension of DTX.  C<special> attribute. This enables the subclass to get access to the special field
1856    attributes without needed to plumb the internal ERDB data structures.
1857    
1858  =over 4  =over 4
1859    
1860  =item outputDirectory  =item entityName
1861    
1862  Name of the directory into which the relation files should be dumped.  Name of the entity whose special fields are desired.
1863    
1864    =item RETURN
1865    
1866    Returns a hash. The keys of the hash are the special field names, and the values
1867    are the values from each special field's C<special> attribute.
1868    
1869  =back  =back
1870    
1871  =cut  =cut
1872    
1873  sub DumpRelations {  sub SpecialFields {
1874      # Get the parameters.      # Get the parameters.
1875      my ($self, $outputDirectory) = @_;      my ($self, $entityName) = @_;
1876      # Now we need to run through all the relations. First, we loop through the entities.      # Declare the return variable.
1877      my $metaData = $self->{_metaData};      my %retVal = ();
1878      my $entities = $metaData->{Entities};      # Find the entity's data structure.
1879      for my $entityName (keys %{$entities}) {      my $entityData = $self->{_metaData}->{Entities}->{$entityName};
1880          my $entityStructure = $entities->{$entityName};      # Loop through its fields, adding each special field to the return hash.
1881          # Get the entity's relations.      my $fieldHash = $entityData->{Fields};
1882          my $relationList = $entityStructure->{Relations};      for my $fieldName (keys %{$fieldHash}) {
1883          # Loop through the relations, dumping them.          my $fieldData = $fieldHash->{$fieldName};
1884          for my $relationName (keys %{$relationList}) {          if (exists $fieldData->{special}) {
1885              my $relation = $relationList->{$relationName};              $retVal{$fieldName} = $fieldData->{special};
             $self->_DumpRelation($outputDirectory, $relationName, $relation);  
         }  
1886      }      }
     # Next, we loop through the relationships.  
     my $relationships = $metaData->{Relationships};  
     for my $relationshipName (keys %{$relationships}) {  
         my $relationshipStructure = $relationships->{$relationshipName};  
         # Dump this relationship's relation.  
         $self->_DumpRelation($outputDirectory, $relationshipName, $relationshipStructure->{Relations}->{$relationshipName});  
1887      }      }
1888        # Return the result.
1889        return %retVal;
1890  }  }
1891    
1892  =head3 InsertObject  =head3 Delete
1893    
1894  C<< my $ok = $database->InsertObject($objectType, \%fieldHash); >>      my $stats = $erdb->Delete($entityName, $objectID, %options);
1895    
1896  Insert an object into the database. The object is defined by a type name and then a hash  Delete an entity instance from the database. The instance is deleted along with all entity and
1897  of field names to values. Field values in the primary relation are represented by scalars.  relationship instances dependent on it. The definition of I<dependence> is recursive.
 (Note that for relationships, the primary relation is the B<only> relation.)  
 Field values for the other relations comprising the entity are always list references. For  
 example, the following line inserts an inactive PEG feature named C<fig|188.1.peg.1> with aliases  
 C<ZP_00210270.1> and C<gi|46206278>.  
1898    
1899  C<< $database->InsertObject('Feature', { id => 'fig|188.1.peg.1', active => 0, feature-type => 'peg', alias => ['ZP_00210270.1', 'gi|46206278']}); >>  An object is always dependent on itself. An object is dependent if it is a 1-to-many or many-to-many
1900    relationship connected to a dependent entity or if it is the "to" entity connected to a 1-to-many
1901    dependent relationship.
1902    
1903  The next statement inserts a C<HasProperty> relationship between feature C<fig|158879.1.peg.1> and  =over 4
 property C<4> with an evidence URL of C<http://seedu.uchicago.edu/query.cgi?article_id=142>.  
1904    
1905  C<< $database->InsertObject('HasProperty', { 'from-link' => 'fig|158879.1.peg.1', 'to-link' => 4, evidence = 'http://seedu.uchicago.edu/query.cgi?article_id=142'}); >>  =item entityName
1906    
1907  =over 4  Name of the entity type for the instance being deleted.
1908    
1909  =item newObjectType  =item objectID
1910    
1911  Type name of the object to insert.  ID of the entity instance to be deleted. If the ID contains a wild card character (C<%>),
1912    then it is presumed to by a LIKE pattern.
1913    
1914  =item fieldHash  =item options
1915    
1916  Hash of field names to values.  A hash detailing the options for this delete operation.
1917    
1918  =item RETURN  =item RETURN
1919    
1920  Returns 1 if successful, 0 if an error occurred.  Returns a statistics object indicating how many records of each particular table were
1921    deleted.
1922    
1923  =back  =back
1924    
1925  =cut  The permissible options for this method are as follows.
1926    
1927  sub InsertObject {  =over 4
1928    
1929    =item testMode
1930    
1931    If TRUE, then the delete statements will be traced, but no changes will be made to the database.
1932    
1933    =item keepRoot
1934    
1935    If TRUE, then the entity instances will not be deleted, only the dependent records.
1936    
1937    =back
1938    
1939    =cut
1940    #: Return Type $%;
1941    sub Delete {
1942      # Get the parameters.      # Get the parameters.
1943      my ($self, $newObjectType, $fieldHash) = @_;      my ($self, $entityName, $objectID, %options) = @_;
1944      # Denote that so far we appear successful.      # Declare the return variable.
1945      my $retVal = 1;      my $retVal = Stats->new();
1946      # Get the database handle.      # Get the DBKernel object.
1947      my $dbh = $self->{_dbh};      my $db = $self->{_dbh};
1948      # Get the relation list.      # We're going to generate all the paths branching out from the starting entity. One of
1949      my $relationTable = $self->_GetRelationTable($newObjectType);      # the things we have to be careful about is preventing loops. We'll use a hash to
1950      # Loop through the relations. We'll build insert statements for each one. If a relation is      # determine if we've hit a loop.
1951      # secondary, we may end up generating multiple insert statements. If an error occurs, we      my %alreadyFound = ();
1952      # stop the loop.      # These next lists will serve as our result stack. We start by pushing object lists onto
1953      my @relationList = keys %{$relationTable};      # the stack, and then popping them off to do the deletes. This means the deletes will
1954      for (my $i = 0; $retVal && $i <= $#relationList; $i++) {      # start with the longer paths before getting to the shorter ones. That, in turn, makes
1955          my $relationName = $relationList[$i];      # sure we don't delete records that might be needed to forge relationships back to the
1956          my $relationDefinition = $relationTable->{$relationName};      # original item. We have two lists-- one for TO-relationships, and one for
1957          # Get the relation's fields. For each field we will collect a value in the corresponding      # FROM-relationships and entities.
1958          # position of the @valueList array. If one of the fields is missing, we will add it to the      my @fromPathList = ();
1959          # @missing list.      my @toPathList = ();
1960          my @fieldList = @{$relationDefinition->{Fields}};      # This final list is used to remember what work still needs to be done. We push paths
1961          my @fieldNameList = ();      # onto the list, then pop them off to extend the paths. We prime it with the starting
1962          my @valueList = ();      # point. Note that we will work hard to insure that the last item on a path in the
1963          my @missing = ();      # to-do list is always an entity.
1964          my $recordCount = 1;      my @todoList = ([$entityName]);
1965          for my $fieldDescriptor (@fieldList) {      while (@todoList) {
1966              # Get the field name and save it. Note we need to fix it up so the hyphens          # Get the current path.
1967              # are converted to underscores.          my $current = pop @todoList;
1968              my $fieldName = $fieldDescriptor->{name};          # Copy it into a list.
1969              push @fieldNameList, _FixName($fieldName);          my @stackedPath = @{$current};
1970              # Look for the named field in the incoming structure. Note that we are looking          # Pull off the last item on the path. It will always be an entity.
1971              # for the real field name, not the fixed-up one!          my $myEntityName = pop @stackedPath;
1972              if (exists $fieldHash->{$fieldName}) {          # Add it to the alreadyFound list.
1973                  # Here we found the field. Stash it in the value list.          $alreadyFound{$myEntityName} = 1;
1974                  my $value = $fieldHash->{$fieldName};          # Figure out if we need to delete this entity.
1975                  push @valueList, $value;          if ($myEntityName ne $entityName || ! $options{keepRoot}) {
1976                  # If the value is a list, we may need to increment the record count.              # Get the entity data.
1977                  if (ref $value eq "ARRAY") {              my $entityData = $self->_GetStructure($myEntityName);
1978                      my $thisCount = @{$value};              # Loop through the entity's relations. A DELETE command will be needed for each of them.
1979                      if ($recordCount == 1) {              my $relations = $entityData->{Relations};
1980                          # Here we have our first list, so we save its count.              for my $relation (keys %{$relations}) {
1981                          $recordCount = $thisCount;                  my @augmentedList = (@stackedPath, $relation);
1982                      } elsif ($recordCount != $thisCount) {                  push @fromPathList, \@augmentedList;
                         # Here we have a second list, so its length has to match the  
                         # previous lists.  
                         Trace("Field $value in new $newObjectType object has an invalid list length $thisCount. Expected $recordCount.") if T(0);  
                         $retVal = 0;  
1983                      }                      }
1984                  }                  }
1985            # Now we need to look for relationships connected to this entity.
1986            my $relationshipList = $self->{_metaData}->{Relationships};
1987            for my $relationshipName (keys %{$relationshipList}) {
1988                my $relationship = $relationshipList->{$relationshipName};
1989                # Check the FROM field. We're only interested if it's us.
1990                if ($relationship->{from} eq $myEntityName) {
1991                    # Add the path to this relationship.
1992                    my @augmentedList = (@stackedPath, $myEntityName, $relationshipName);
1993                    push @fromPathList, \@augmentedList;
1994                    # Check the arity. If it's MM we're done. If it's 1M
1995                    # and the target hasn't been seen yet, we want to
1996                    # stack the entity for future processing.
1997                    if ($relationship->{arity} eq '1M') {
1998                        my $toEntity = $relationship->{to};
1999                        if (! exists $alreadyFound{$toEntity}) {
2000                            # Here we have a new entity that's dependent on
2001                            # the current entity, so we need to stack it.
2002                            my @stackList = (@augmentedList, $toEntity);
2003                            push @fromPathList, \@stackList;
2004              } else {              } else {
2005                  # Here the field is not present. Flag it as missing.                          Trace("$toEntity ignored because it occurred previously.") if T(4);
                 push @missing, $fieldName;  
2006              }              }
2007          }          }
         # If we are the primary relation, add the new-record flag.  
         if ($relationName eq $newObjectType) {  
             push @valueList, 1;  
             push @fieldNameList, "new_record";  
2008          }          }
2009          # Only proceed if there are no missing fields.              # Now check the TO field. In this case only the relationship needs
2010          if (@missing > 0) {              # deletion.
2011              Trace("Relation $relationName for $newObjectType skipped due to missing fields: " .              if ($relationship->{to} eq $myEntityName) {
2012                  join(' ', @missing)) if T(1);                  my @augmentedList = (@stackedPath, $myEntityName, $relationshipName);
2013          } else {                  push @toPathList, \@augmentedList;
             # Build the INSERT statement.  
             my $statement = "INSERT INTO $relationName (" . join (', ', @fieldNameList) .  
                 ") VALUES (";  
             # Create a marker list of the proper size and put it in the statement.  
             my @markers = ();  
             while (@markers < @fieldNameList) { push @markers, '?'; }  
             $statement .= join(', ', @markers) . ")";  
             # We have the insert statement, so prepare it.  
             my $sth = $dbh->prepare_command($statement);  
             Trace("Insert statement prepared: $statement") if T(3);  
             # Now we loop through the values. If a value is scalar, we use it unmodified. If it's  
             # a list, we use the current element. The values are stored in the @parameterList array.  
             my $done = 0;  
             for (my $i = 0; $i < $recordCount; $i++) {  
                 # Clear the parameter list array.  
                 my @parameterList = ();  
                 # Loop through the values.  
                 for my $value (@valueList) {  
                     # Check to see if this is a scalar value.  
                     if (ref $value eq "ARRAY") {  
                         # Here we have a list value. Pull the current entry.  
                         push @parameterList, $value->[$i];  
                     } else {  
                         # Here we have a scalar value. Use it unmodified.  
                         push @parameterList, $value;  
2014                      }                      }
2015                  }                  }
                 # Execute the INSERT statement with the specified parameter list.  
                 $retVal = $sth->execute(@parameterList);  
                 if (!$retVal) {  
                     my $errorString = $sth->errstr();  
                     Trace("Insert error: $errorString.") if T(0);  
2016                  }                  }
2017        # Create the first qualifier for the WHERE clause. This selects the
2018        # keys of the primary entity records to be deleted. When we're deleting
2019        # from a dependent table, we construct a join path from the first qualifier
2020        # to the table containing the dependent records to delete.
2021        my $qualifier = ($objectID =~ /%/ ? "LIKE ?" : "= ?");
2022        # We need to make two passes. The first is through the to-list, and
2023        # the second through the from-list. The from-list is second because
2024        # the to-list may need to pass through some of the entities the
2025        # from-list would delete.
2026        my %stackList = ( from_link => \@fromPathList, to_link => \@toPathList );
2027        # Now it's time to do the deletes. We do it in two passes.
2028        for my $keyName ('to_link', 'from_link') {
2029            # Get the list for this key.
2030            my @pathList = @{$stackList{$keyName}};
2031            Trace(scalar(@pathList) . " entries in path list for $keyName.") if T(3);
2032            # Loop through this list.
2033            while (my $path = pop @pathList) {
2034                # Get the table whose rows are to be deleted.
2035                my @pathTables = @{$path};
2036                # Start the DELETE statement. We need to call DBKernel because the
2037                # syntax of a DELETE-USING varies among DBMSs.
2038                my $target = $pathTables[$#pathTables];
2039                my $stmt = $db->SetUsing(@pathTables);
2040                # Now start the WHERE. The first thing is the ID field from the starting table. That
2041                # starting table will either be the entity relation or one of the entity's
2042                # sub-relations.
2043                $stmt .= " WHERE $pathTables[0].id $qualifier";
2044                # Now we run through the remaining entities in the path, connecting them up.
2045                for (my $i = 1; $i <= $#pathTables; $i += 2) {
2046                    # Connect the current relationship to the preceding entity.
2047                    my ($entity, $rel) = @pathTables[$i-1,$i];
2048                    # The style of connection depends on the direction of the relationship.
2049                    $stmt .= " AND $entity.id = $rel.$keyName";
2050                    if ($i + 1 <= $#pathTables) {
2051                        # Here there's a next entity, so connect that to the relationship's
2052                        # to-link.
2053                        my $entity2 = $pathTables[$i+1];
2054                        $stmt .= " AND $rel.to_link = $entity2.id";
2055                    }
2056                }
2057                # Now we have our desired DELETE statement.
2058                if ($options{testMode}) {
2059                    # Here the user wants to trace without executing.
2060                    Trace($stmt) if T(0);
2061                } else {
2062                    # Here we can delete. Note that the SQL method dies with a confession
2063                    # if an error occurs, so we just go ahead and do it.
2064                    Trace("Executing delete from $target using '$objectID'.") if T(3);
2065                    my $rv = $db->SQL($stmt, 0, $objectID);
2066                    # Accumulate the statistics for this delete. The only rows deleted
2067                    # are from the target table, so we use its name to record the
2068                    # statistic.
2069                    $retVal->Add($target, $rv);
2070              }              }
2071          }          }
2072      }      }
2073      # Return the success indicator.      # Return the result.
2074      return $retVal;      return $retVal;
2075  }  }
2076    
2077  =head3 LoadTable  =head3 Disconnect
2078    
2079  C<< my %results = $database->LoadTable($fileName, $relationName, $truncateFlag); >>      $erdb->Disconnect($relationshipName, $originEntityName, $originEntityID);
2080    
2081  Load data from a tab-delimited file into a specified table, optionally re-creating the table  Disconnect an entity instance from all the objects to which it is related. This
2082  first.  will delete each relationship instance that connects to the specified entity.
2083    
2084  =over 4  =over 4
2085    
2086  =item fileName  =item relationshipName
   
 Name of the file from which the table data should be loaded.  
   
 =item relationName  
2087    
2088  Name of the relation to be loaded. This is the same as the table name.  Name of the relationship whose instances are to be deleted.
2089    
2090  =item truncateFlag  =item originEntityName
2091    
2092  TRUE if the table should be dropped and re-created, else FALSE  Name of the entity that is to be disconnected.
2093    
2094  =item RETURN  =item originEntityID
2095    
2096  Returns a statistical object containing the number of records read and a list of  ID of the entity that is to be disconnected.
 the error messages.  
2097    
2098  =back  =back
2099    
2100  =cut  =cut
2101  sub LoadTable {  
2102    sub Disconnect {
2103      # Get the parameters.      # Get the parameters.
2104      my ($self, $fileName, $relationName, $truncateFlag) = @_;      my ($self, $relationshipName, $originEntityName, $originEntityID) = @_;
2105      # Create the statistical return object.      # Get the relationship descriptor.
2106      my $retVal = _GetLoadStats();      my $structure = $self->_GetStructure($relationshipName);
2107      # Trace the fact of the load.      # Insure we have a relationship.
2108      Trace("Loading table $relationName from $fileName") if T(2);      if (! exists $structure->{from}) {
2109            Confess("$relationshipName is not a relationship in the database.");
2110        } else {
2111      # Get the database handle.      # Get the database handle.
2112      my $dbh = $self->{_dbh};      my $dbh = $self->{_dbh};
2113      # Get the relation data.          # We'll set this value to 1 if we find our entity.
2114      my $relation = $self->_FindRelation($relationName);          my $found = 0;
2115      # Check the truncation flag.          # Loop through the ends of the relationship.
2116      if ($truncateFlag) {          for my $dir ('from', 'to') {
2117          Trace("Creating table $relationName") if T(2);              if ($structure->{$dir} eq $originEntityName) {
2118          # Re-create the table without its index.                  $found = 1;
2119          $self->CreateTable($relationName, 0);                  # Here we want to delete all relationship instances on this side of the
2120          # If this is a pre-index DBMS, create the index here.                  # entity instance.
2121          if ($dbh->{_preIndex}) {                  Trace("Disconnecting in $dir direction with ID \"$originEntityID\".");
2122              eval {                  # We do this delete in batches to keep it from dragging down the
2123                  $self->CreateIndex($relationName);                  # server.
2124              };                  my $limitClause = ($FIG_Config::delete_limit ? "LIMIT $FIG_Config::delete_limit" : "");
2125              if ($@) {                  my $done = 0;
2126                  $retVal->AddMessage($@);                  while (! $done) {
2127              }                      # Do the delete.
2128                        my $rows = $dbh->SQL("DELETE FROM $relationshipName WHERE ${dir}_link = ? $limitClause", 0, $originEntityID);
2129                        # See if we're done. We're done if no rows were found or the delete is unlimited.
2130                        $done = ($rows == 0 || ! $limitClause);
2131          }          }
2132      }      }
     # Determine whether or not this is a primary relation. Primary relations have an extra  
     # field indicating whether or not a given object is new or was loaded from the flat files.  
     my $primary = $self->_IsPrimary($relationName);  
     # Get the number of fields in this relation.  
     my @fieldList = @{$relation->{Fields}};  
     my $fieldCount = @fieldList;  
     # Start a database transaction.  
     $dbh->begin_tran;  
     # Open the relation file. We need to create a cleaned-up copy before loading.  
     open TABLEIN, '<', $fileName;  
     my $tempName = "$fileName.tbl";  
     open TABLEOUT, '>', $tempName;  
     my $inputCount = 0;  
     # Loop through the file.  
     while (<TABLEIN>) {  
         $inputCount++;  
         # Chop off the new-line character.  
         my $record = Tracer::Strip($_);  
         # Only proceed if the record is non-blank.  
         if ($record) {  
             # Escape all the backslashes found in the line.  
             $record =~ s/\\/\\\\/g;  
             # Insure the number of fields is correct.  
             my @fields = split /\t/, $record;  
             while (@fields > $fieldCount) {  
                 my $extraField = $fields[$#fields];  
                 delete $fields[$#fields];  
                 if ($extraField) {  
                     Trace("Nonblank extra field value \"$extraField\" deleted from record $inputCount of $fileName.") if T(1);  
                 }  
             }  
             while (@fields < $fieldCount) {  
                 push @fields, "";  
             }  
             # If this is a primary relation, add a 0 for the new-record flag (indicating that  
             # this record is not new, but part of the original load).  
             if ($primary) {  
                 push @fields, "0";  
             }  
             # Write the record.  
             $record = join "\t", @fields;  
             print TABLEOUT "$record\n";  
             # Count the record written.  
             my $count = $retVal->Add('records');  
             my $len = length $record;  
             Trace("Record $count written with $len characters.") if T(4);  
         } else {  
             # Here we have a blank record.  
             $retVal->Add('skipped');  
         }  
     }  
     # Close the files.  
     close TABLEIN;  
     close TABLEOUT;  
     Trace("Temporary file $tempName created.") if T(2);  
     # Load the table.  
     my $rv;  
     eval {  
         $rv = $dbh->load_table(file => $tempName, tbl => $relationName);  
     };  
     if (!defined $rv) {  
         $retVal->AddMessage($@) if ($@);  
         $retVal->AddMessage("Table load failed for $relationName using $tempName.");  
         Trace("Table load failed for $relationName.") if T(1);  
     } else {  
         # Here we successfully loaded the table. Trace the number of records loaded.  
         Trace("$retVal->{records} records read for $relationName.") if T(2);  
         # If we're rebuilding, we need to create the table indexes.  
         if ($truncateFlag && ! $dbh->{_preIndex}) {  
             eval {  
                 $self->CreateIndex($relationName);  
             };  
             if ($@) {  
                 $retVal->AddMessage($@);  
2133              }              }
2134            # Insure we found the entity on at least one end.
2135            if (! $found) {
2136                Confess("Entity \"$originEntityName\" does not use $relationshipName.");
2137          }          }
2138      }      }
     # Commit the database changes.  
     $dbh->commit_tran;  
     # Delete the temporary file.  
     unlink $tempName;  
     # Return the statistics.  
     return $retVal;  
2139  }  }
2140    
2141  =head3 GenerateEntity  =head3 DeleteRow
2142    
2143  C<< my $fieldHash = $database->GenerateEntity($id, $type, \%values); >>      $erdb->DeleteRow($relationshipName, $fromLink, $toLink, \%values);
2144    
2145  Generate the data for a new entity instance. This method creates a field hash suitable for  Delete a row from a relationship. In most cases, only the from-link and to-link are
2146  passing as a parameter to L</InsertObject>. The ID is specified by the callr, but the rest  needed; however, for relationships with intersection data values can be specified
2147  of the fields are generated using information in the database schema.  for the other fields using a hash.
   
 Each data type has a default algorithm for generating random test data. This can be overridden  
 by including a B<DataGen> element in the field. If this happens, the content of the element is  
 executed as a PERL program in the context of this module. The element may make use of a C<$this>  
 variable which contains the field hash as it has been built up to the current point. If any  
 fields are dependent on other fields, the C<pass> attribute can be used to control the order  
 in which the fields are generated. A field with a high data pass number will be generated after  
 a field with a lower one. If any external values are needed, they should be passed in via the  
 optional third parameter, which will be available to the data generation script under the name  
 C<$value>. Several useful utility methods are provided for generating random values, including  
 L</IntGen>, L</StringGen>, L</FloatGen>, and L</DateGen>. Note that dates are stored and generated  
 in the form of a timestamp number rather than a string.  
2148    
2149  =over 4  =over 4
2150    
2151  =item id  =item relationshipName
2152    
2153  ID to assign to the new entity.  Name of the relationship from which the row is to be deleted.
2154    
2155  =item type  =item fromLink
2156    
2157    ID of the entity instance in the From direction.
2158    
2159  Type name for the new entity.  =item toLink
2160    
2161    ID of the entity instance in the To direction.
2162    
2163  =item values  =item values
2164    
2165  Hash containing additional values that might be needed by the data generation methods (optional).  Reference to a hash of other values to be used for filtering the delete.
2166    
2167  =back  =back
2168    
2169  =cut  =cut
2170    
2171  sub GenerateEntity {  sub DeleteRow {
2172      # Get the parameters.      # Get the parameters.
2173      my ($self, $id, $type, $values) = @_;      my ($self, $relationshipName, $fromLink, $toLink, $values) = @_;
2174      # Create the return hash.      # Create a hash of all the filter information.
2175      my $this = { id => $id };      my %filter = ('from-link' => $fromLink, 'to-link' => $toLink);
2176      # Get the metadata structure.      if (defined $values) {
2177      my $metadata = $self->{_metaData};          for my $key (keys %{$values}) {
2178      # Get this entity's list of fields.              $filter{$key} = $values->{$key};
2179      if (!exists $metadata->{Entities}->{$type}) {          }
         Confess("Unrecognized entity type $type in GenerateEntity.");  
     } else {  
         my $entity = $metadata->{Entities}->{$type};  
         my $fields = $entity->{Fields};  
         # Generate data from the fields.  
         _GenerateFields($this, $fields, $type, $values);  
2180      }      }
2181      # Return the hash created.      # Build an SQL statement out of the hash.
2182      return $this;      my @filters = ();
2183        my @parms = ();
2184        for my $key (keys %filter) {
2185            push @filters, _FixName($key) . " = ?";
2186            push @parms, $filter{$key};
2187        }
2188        Trace("Parms for delete row are " . join(", ", map { "\"$_\"" } @parms) . ".") if T(SQL => 4);
2189        my $command = "DELETE FROM $relationshipName WHERE " .
2190                      join(" AND ", @filters);
2191        # Execute it.
2192        my $dbh = $self->{_dbh};
2193        $dbh->SQL($command, undef, @parms);
2194  }  }
2195    
2196  =head3 GetEntity  =head3 DeleteLike
2197    
2198  C<< my $entityObject = $sprout->GetEntity($entityType, $ID); >>      my $deleteCount = $erdb->DeleteLike($relName, $filter, \@parms);
2199    
2200  Return an object describing the entity instance with a specified ID.  Delete all the relationship rows that satisfy a particular filter condition. Unlike a normal
2201    filter, only fields from the relationship itself can be used.
2202    
2203  =over 4  =over 4
2204    
2205  =item entityType  =item relName
2206    
2207  Entity type name.  Name of the relationship whose records are to be deleted.
2208    
2209  =item ID  =item filter
2210    
2211  ID of the desired entity.  A filter clause (L</Get>-style) for the delete query.
2212    
2213    =item parms
2214    
2215    Reference to a list of parameters for the filter clause.
2216    
2217  =item RETURN  =item RETURN
2218    
2219  Returns a B<DBObject> representing the desired entity instance, or an undefined value if no  Returns a count of the number of rows deleted.
 instance is found with the specified key.  
2220    
2221  =back  =back
2222    
2223  =cut  =cut
2224    
2225  sub GetEntity {  sub DeleteLike {
2226      # Get the parameters.      # Get the parameters.
2227      my ($self, $entityType, $ID) = @_;      my ($self, $objectName, $filter, $parms) = @_;
2228      # Create a query.      # Declare the return variable.
2229      my $query = $self->Get([$entityType], "$entityType(id) = ?", $ID);      my $retVal;
2230      # Get the first (and only) object.      # Insure the parms argument is an array reference if the caller left it off.
2231      my $retVal = $query->Fetch();      if (! defined($parms)) {
2232      # Return the result.          $parms = [];
2233      return $retVal;      }
2234        # Insure we have a relationship. The main reason for this is if we delete an entity
2235        # instance we have to yank out a bunch of other stuff with it.
2236        if ($self->IsEntity($objectName)) {
2237            Confess("Cannot use DeleteLike on $objectName, because it is not a relationship.");
2238        } else {
2239            # Create the SQL command suffix to get the desierd records.
2240            my ($suffix) = $self->_SetupSQL([$objectName], $filter);
2241            # Convert it to a DELETE command.
2242            my $command = "DELETE $suffix";
2243            # Execute the command.
2244            my $dbh = $self->{_dbh};
2245            my $result = $dbh->SQL($command, 0, @{$parms});
2246            # Check the results. Note we convert the "0D0" result to a real zero.
2247            # A failure causes an abnormal termination, so the caller isn't going to
2248            # worry about it.
2249            if (! defined $result) {
2250                Confess("Error deleting from $objectName: " . $dbh->errstr());
2251            } elsif ($result == 0) {
2252                $retVal = 0;
2253            } else {
2254                $retVal = $result;
2255            }
2256        }
2257        # Return the result count.
2258        return $retVal;
2259    }
2260    
2261    =head3 SortNeeded
2262    
2263        my $parms = $erdb->SortNeeded($relationName);
2264    
2265    Return the pipe command for the sort that should be applied to the specified
2266    relation when creating the load file.
2267    
2268    For example, if the load file should be sorted ascending by the first
2269    field, this method would return
2270    
2271        sort -k1 -t"\t"
2272    
2273    If the first field is numeric, the method would return
2274    
2275        sort -k1n -t"\t"
2276    
2277    Unfortunately, due to a bug in the C<sort> command, we cannot eliminate duplicate
2278    keys using a sort.
2279    
2280    =over 4
2281    
2282    =item relationName
2283    
2284    Name of the relation to be examined.
2285    
2286    =item
2287    
2288    Returns the sort command to use for sorting the relation, suitable for piping.
2289    
2290    =back
2291    
2292    =cut
2293    #: Return Type $;
2294    sub SortNeeded {
2295        # Get the parameters.
2296        my ($self, $relationName) = @_;
2297        # Declare a descriptor to hold the names of the key fields.
2298        my @keyNames = ();
2299        # Get the relation structure.
2300        my $relationData = $self->_FindRelation($relationName);
2301        # Find out if the relation is a primary entity relation,
2302        # a relationship relation, or a secondary entity relation.
2303        my $entityTable = $self->{_metaData}->{Entities};
2304        my $relationshipTable = $self->{_metaData}->{Relationships};
2305        if (exists $entityTable->{$relationName}) {
2306            # Here we have a primary entity relation.
2307            push @keyNames, "id";
2308        } elsif (exists $relationshipTable->{$relationName}) {
2309            # Here we have a relationship. We sort using the FROM index.
2310            my $relationshipData = $relationshipTable->{$relationName};
2311            my $index = $relationData->{Indexes}->{idxFrom};
2312            push @keyNames, @{$index->{IndexFields}};
2313        } else {
2314            # Here we have a secondary entity relation, so we have a sort on the ID field.
2315            push @keyNames, "id";
2316        }
2317        # Now we parse the key names into sort parameters. First, we prime the return
2318        # string.
2319        my $retVal = "sort -t\"\t\" ";
2320        # Get the relation's field list.
2321        my @fields = @{$relationData->{Fields}};
2322        # Loop through the keys.
2323        for my $keyData (@keyNames) {
2324            # Get the key and the ordering.
2325            my ($keyName, $ordering);
2326            if ($keyData =~ /^([^ ]+) DESC/) {
2327                ($keyName, $ordering) = ($1, "descending");
2328            } else {
2329                ($keyName, $ordering) = ($keyData, "ascending");
2330            }
2331            # Find the key's position and type.
2332            my $fieldSpec;
2333            for (my $i = 0; $i <= $#fields && ! $fieldSpec; $i++) {
2334                my $thisField = $fields[$i];
2335                if ($thisField->{name} eq $keyName) {
2336                    # Get the sort modifier for this field type. The modifier
2337                    # decides whether we're using a character, numeric, or
2338                    # floating-point sort.
2339                    my $modifier = $TypeTable{$thisField->{type}}->{sort};
2340                    # If the index is descending for this field, denote we want
2341                    # to reverse the sort order on this field.
2342                    if ($ordering eq 'descending') {
2343                        $modifier .= "r";
2344                    }
2345                    # Store the position and modifier into the field spec, which
2346                    # will stop the inner loop. Note that the field number is
2347                    # 1-based in the sort command, so we have to increment the
2348                    # index.
2349                    $fieldSpec = ($i + 1) . $modifier;
2350                }
2351            }
2352            # Add this field to the sort command.
2353            $retVal .= " -k$fieldSpec";
2354        }
2355        # Return the result.
2356        return $retVal;
2357    }
2358    
2359    =head3 GetList
2360    
2361        my @dbObjects = $erdb->GetList(\@objectNames, $filterClause, \@params);
2362    
2363    Return a list of object descriptors for the specified objects as determined by the
2364    specified filter clause.
2365    
2366    This method is essentially the same as L</Get> except it returns a list of objects rather
2367    than a query object that can be used to get the results one record at a time.
2368    
2369    =over 4
2370    
2371    =item objectNames
2372    
2373    List containing the names of the entity and relationship objects to be retrieved.
2374    
2375    =item filterClause
2376    
2377    WHERE clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can
2378    be parameterized with parameter markers (C<?>). Each field used in the WHERE clause must be
2379    specified in the standard form B<I<objectName>(I<fieldName>)>. Any parameters specified
2380    in the filter clause should be added to the parameter list as additional parameters. The
2381    fields in a filter clause can come from primary entity relations, relationship relations,
2382    or secondary entity relations; however, all of the entities and relationships involved must
2383    be included in the list of object names.
2384    
2385    The filter clause can also specify a sort order. To do this, simply follow the filter string
2386    with an ORDER BY clause. For example, the following filter string gets all genomes for a
2387    particular genus and sorts them by species name.
2388    
2389        "Genome(genus) = ? ORDER BY Genome(species)"
2390    
2391    The rules for field references in a sort order are the same as those for field references in the
2392    filter clause in general; however, odd things may happen if a sort field is from a secondary
2393    relation.
2394    
2395    =item params
2396    
2397    Reference to a list of parameter values to be substituted into the filter clause.
2398    
2399    =item RETURN
2400    
2401    Returns a list of B<ERDBObject>s that satisfy the query conditions.
2402    
2403    =back
2404    
2405    =cut
2406    #: Return Type @%
2407    sub GetList {
2408        # Get the parameters.
2409        my ($self, $objectNames, $filterClause, $params) = @_;
2410        # Declare the return variable.
2411        my @retVal = ();
2412        # Perform the query.
2413        my $query = $self->Get($objectNames, $filterClause, $params);
2414        # Loop through the results.
2415        while (my $object = $query->Fetch) {
2416            push @retVal, $object;
2417        }
2418        # Return the result.
2419        return @retVal;
2420    }
2421    
2422    =head3 GetCount
2423    
2424        my $count = $erdb->GetCount(\@objectNames, $filter, \@params);
2425    
2426    Return the number of rows found by a specified query. This method would
2427    normally be used to count the records in a single table. For example, in a
2428    genetics database
2429    
2430        my $count = $erdb->GetCount(['Genome'], 'Genome(genus-species) LIKE ?', ['homo %']);
2431    
2432    would return the number of genomes for the genus I<homo>. It is conceivable, however,
2433    to use it to return records based on a join. For example,
2434    
2435        my $count = $erdb->GetCount(['HasFeature', 'Genome'], 'Genome(genus-species) LIKE ?',
2436                                    ['homo %']);
2437    
2438    would return the number of features for genomes in the genus I<homo>. Note that
2439    only the rows from the first table are counted. If the above command were
2440    
2441        my $count = $erdb->GetCount(['Genome', 'Feature'], 'Genome(genus-species) LIKE ?',
2442                                    ['homo %']);
2443    
2444    it would return the number of genomes, not the number of genome/feature pairs.
2445    
2446    =over 4
2447    
2448    =item objectNames
2449    
2450    Reference to a list of the objects (entities and relationships) included in the
2451    query.
2452    
2453    =item filter
2454    
2455    A filter clause for restricting the query. The rules are the same as for the L</Get>
2456    method.
2457    
2458    =item params
2459    
2460    Reference to a list of the parameter values to be substituted for the parameter marks
2461    in the filter.
2462    
2463    =item RETURN
2464    
2465    Returns a count of the number of records in the first table that would satisfy
2466    the query.
2467    
2468    =back
2469    
2470    =cut
2471    
2472    sub GetCount {
2473        # Get the parameters.
2474        my ($self, $objectNames, $filter, $params) = @_;
2475        # Insure the params argument is an array reference if the caller left it off.
2476        if (! defined($params)) {
2477            $params = [];
2478        }
2479        # Declare the return variable.
2480        my $retVal;
2481        # Find out if we're counting an entity or a relationship.
2482        my $countedField;
2483        if ($self->IsEntity($objectNames->[0])) {
2484            $countedField = "id";
2485        } else {
2486            # For a relationship we count the to-link because it's usually more
2487            # numerous. Note we're automatically converting to the SQL form
2488            # of the field name (to_link vs. to-link).
2489            $countedField = "to_link";
2490        }
2491        # Create the SQL command suffix to get the desired records.
2492        my ($suffix, $mappedNameListRef, $mappedNameHashRef) = $self->_SetupSQL($objectNames,
2493                                                                                $filter);
2494        # Prefix it with text telling it we want a record count.
2495        my $firstObject = $mappedNameListRef->[0];
2496        my $command = "SELECT COUNT($firstObject.$countedField) $suffix";
2497        # Prepare and execute the command.
2498        my $sth = $self->_GetStatementHandle($command, $params);
2499        # Get the count value.
2500        ($retVal) = $sth->fetchrow_array();
2501        # Check for a problem.
2502        if (! defined($retVal)) {
2503            if ($sth->err) {
2504                # Here we had an SQL error.
2505                Confess("Error retrieving row count: " . $sth->errstr());
2506            } else {
2507                # Here we have no result.
2508                Confess("No result attempting to retrieve row count.");
2509            }
2510        }
2511        # Return the result.
2512        return $retVal;
2513    }
2514    
2515    =head3 ComputeObjectSentence
2516    
2517        my $sentence = $erdb->ComputeObjectSentence($objectName);
2518    
2519    Check an object name, and if it is a relationship convert it to a relationship sentence.
2520    
2521    =over 4
2522    
2523    =item objectName
2524    
2525    Name of the entity or relationship.
2526    
2527    =item RETURN
2528    
2529    Returns a string containing the entity name or a relationship sentence.
2530    
2531    =back
2532    
2533    =cut
2534    
2535    sub ComputeObjectSentence {
2536        # Get the parameters.
2537        my ($self, $objectName) = @_;
2538        # Set the default return value.
2539        my $retVal = $objectName;
2540        # Look for the object as a relationship.
2541        my $relTable = $self->{_metaData}->{Relationships};
2542        if (exists $relTable->{$objectName}) {
2543            # Get the relationship sentence.
2544            $retVal = _ComputeRelationshipSentence($objectName, $relTable->{$objectName});
2545        }
2546        # Return the result.
2547        return $retVal;
2548    }
2549    
2550    =head3 DumpRelations
2551    
2552        $erdb->DumpRelations($outputDirectory);
2553    
2554    Write the contents of all the relations to tab-delimited files in the specified directory.
2555    Each file will have the same name as the relation dumped, with an extension of DTX.
2556    
2557    =over 4
2558    
2559    =item outputDirectory
2560    
2561    Name of the directory into which the relation files should be dumped.
2562    
2563    =back
2564    
2565    =cut
2566    
2567    sub DumpRelations {
2568        # Get the parameters.
2569        my ($self, $outputDirectory) = @_;
2570        # Now we need to run through all the relations. First, we loop through the entities.
2571        my $metaData = $self->{_metaData};
2572        my $entities = $metaData->{Entities};
2573        for my $entityName (keys %{$entities}) {
2574            my $entityStructure = $entities->{$entityName};
2575            # Get the entity's relations.
2576            my $relationList = $entityStructure->{Relations};
2577            # Loop through the relations, dumping them.
2578            for my $relationName (keys %{$relationList}) {
2579                my $relation = $relationList->{$relationName};
2580                $self->_DumpRelation($outputDirectory, $relationName, $relation);
2581            }
2582        }
2583        # Next, we loop through the relationships.
2584        my $relationships = $metaData->{Relationships};
2585        for my $relationshipName (keys %{$relationships}) {
2586            my $relationshipStructure = $relationships->{$relationshipName};
2587            # Dump this relationship's relation.
2588            $self->_DumpRelation($outputDirectory, $relationshipName, $relationshipStructure->{Relations}->{$relationshipName});
2589        }
2590    }
2591    
2592    =head3 InsertValue
2593    
2594        $erdb->InsertValue($entityID, $fieldName, $value);
2595    
2596    This method will insert a new value into the database. The value must be one
2597    associated with a secondary relation, since primary values cannot be inserted:
2598    they occur exactly once. Secondary values, on the other hand, can be missing
2599    or multiply-occurring.
2600    
2601    =over 4
2602    
2603    =item entityID
2604    
2605    ID of the object that is to receive the new value.
2606    
2607    =item fieldName
2608    
2609    Field name for the new value-- this includes the entity name, since
2610    field names are of the format I<objectName>C<(>I<fieldName>C<)>.
2611    
2612    =item value
2613    
2614    New value to be put in the field.
2615    
2616    =back
2617    
2618    =cut
2619    
2620    sub InsertValue {
2621        # Get the parameters.
2622        my ($self, $entityID, $fieldName, $value) = @_;
2623        # Parse the entity name and the real field name.
2624        if ($fieldName =~ /^([^(]+)\(([^)]+)\)/) {
2625            my $entityName = $1;
2626            my $fieldTitle = $2;
2627            # Get its descriptor.
2628            if (!$self->IsEntity($entityName)) {
2629                Confess("$entityName is not a valid entity.");
2630            } else {
2631                my $entityData = $self->{_metaData}->{Entities}->{$entityName};
2632                # Find the relation containing this field.
2633                my $fieldHash = $entityData->{Fields};
2634                if (! exists $fieldHash->{$fieldTitle}) {
2635                    Confess("$fieldTitle not found in $entityName.");
2636                } else {
2637                    my $relation = $fieldHash->{$fieldTitle}->{relation};
2638                    if ($relation eq $entityName) {
2639                        Confess("Cannot do InsertValue on primary field $fieldTitle of $entityName.");
2640                    } else {
2641                        # Now we can create an INSERT statement.
2642                        my $dbh = $self->{_dbh};
2643                        my $fixedName = _FixName($fieldTitle);
2644                        my $statement = "INSERT INTO $relation (id, $fixedName) VALUES(?, ?)";
2645                        # Execute the command.
2646                        $dbh->SQL($statement, 0, $entityID, $value);
2647                    }
2648                }
2649            }
2650        } else {
2651            Confess("$fieldName is not a valid field name.");
2652        }
2653    }
2654    
2655    =head3 InsertObject
2656    
2657        $erdb->InsertObject($objectType, \%fieldHash);
2658    
2659    Insert an object into the database. The object is defined by a type name and then a hash
2660    of field names to values. Field values in the primary relation are represented by scalars.
2661    (Note that for relationships, the primary relation is the B<only> relation.)
2662    Field values for the other relations comprising the entity are always list references. For
2663    example, the following line inserts an inactive PEG feature named C<fig|188.1.peg.1> with aliases
2664    C<ZP_00210270.1> and C<gi|46206278>.
2665    
2666        $erdb->InsertObject('Feature', { id => 'fig|188.1.peg.1', active => 0, feature-type => 'peg', alias => ['ZP_00210270.1', 'gi|46206278']});
2667    
2668    The next statement inserts a C<HasProperty> relationship between feature C<fig|158879.1.peg.1> and
2669    property C<4> with an evidence URL of C<http://seedu.uchicago.edu/query.cgi?article_id=142>.
2670    
2671        $erdb->InsertObject('HasProperty', { 'from-link' => 'fig|158879.1.peg.1', 'to-link' => 4, evidence => 'http://seedu.uchicago.edu/query.cgi?article_id=142'});
2672    
2673    =over 4
2674    
2675    =item newObjectType
2676    
2677    Type name of the object to insert.
2678    
2679    =item fieldHash
2680    
2681    Hash of field names to values.
2682    
2683    =back
2684    
2685    =cut
2686    
2687    sub InsertObject {
2688        # Get the parameters.
2689        my ($self, $newObjectType, $fieldHash) = @_;
2690        # Denote that so far we appear successful.
2691        my $retVal = 1;
2692        # Get the database handle.
2693        my $dbh = $self->{_dbh};
2694        # Get the relation list.
2695        my $relationTable = $self->_GetRelationTable($newObjectType);
2696        # Loop through the relations. We'll build insert statements for each one. If a relation is
2697        # secondary, we may end up generating multiple insert statements. If an error occurs, we
2698        # stop the loop.
2699        my @relationList = keys %{$relationTable};
2700        for (my $i = 0; $retVal && $i <= $#relationList; $i++) {
2701            my $relationName = $relationList[$i];
2702            my $relationDefinition = $relationTable->{$relationName};
2703            # Get the relation's fields. For each field we will collect a value in the corresponding
2704            # position of the @valueList array. If one of the fields is missing, we will add it to the
2705            # @missing list.
2706            my @fieldList = @{$relationDefinition->{Fields}};
2707            my @fieldNameList = ();
2708            my @valueList = ();
2709            my @missing = ();
2710            my $recordCount = 1;
2711            for my $fieldDescriptor (@fieldList) {
2712                # Get the field name and save it. Note we need to fix it up so the hyphens
2713                # are converted to underscores.
2714                my $fieldName = $fieldDescriptor->{name};
2715                push @fieldNameList, _FixName($fieldName);
2716                # Look for the named field in the incoming structure. Note that we are looking
2717                # for the real field name, not the fixed-up one!
2718                if (exists $fieldHash->{$fieldName}) {
2719                    # Here we found the field. Stash it in the value list.
2720                    my $value = $fieldHash->{$fieldName};
2721                    push @valueList, $value;
2722                    # If the value is a list, we may need to increment the record count.
2723                    if (ref $value eq "ARRAY") {
2724                        my $thisCount = @{$value};
2725                        if ($recordCount == 1) {
2726                            # Here we have our first list, so we save its count.
2727                            $recordCount = $thisCount;
2728                        } elsif ($recordCount != $thisCount) {
2729                            # Here we have a second list, so its length has to match the
2730                            # previous lists.
2731                            Trace("Field $value in new $newObjectType object has an invalid list length $thisCount. Expected $recordCount.") if T(0);
2732                            $retVal = 0;
2733                        }
2734                    }
2735                } else {
2736                    # Here the field is not present. Flag it as missing.
2737                    push @missing, $fieldName;
2738                }
2739            }
2740            # If we are the primary relation, add the new-record flag.
2741            if ($relationName eq $newObjectType) {
2742                push @valueList, 1;
2743                push @fieldNameList, "new_record";
2744            }
2745            # Only proceed if there are no missing fields.
2746            if (@missing > 0) {
2747                Trace("Relation $relationName for $newObjectType skipped due to missing fields: " .
2748                    join(' ', @missing)) if T(1);
2749            } else {
2750                # Build the INSERT statement.
2751                my $statement = "INSERT INTO $relationName (" . join (', ', @fieldNameList) .
2752                    ") VALUES (";
2753                # Create a marker list of the proper size and put it in the statement.
2754                my @markers = ();
2755                while (@markers < @fieldNameList) { push @markers, '?'; }
2756                $statement .= join(', ', @markers) . ")";
2757                # We have the insert statement, so prepare it.
2758                my $sth = $dbh->prepare_command($statement);
2759                Trace("Insert statement prepared: $statement") if T(3);
2760                # Now we loop through the values. If a value is scalar, we use it unmodified. If it's
2761                # a list, we use the current element. The values are stored in the @parameterList array.
2762                my $done = 0;
2763                for (my $i = 0; $i < $recordCount; $i++) {
2764                    # Clear the parameter list array.
2765                    my @parameterList = ();
2766                    # Loop through the values.
2767                    for my $value (@valueList) {
2768                        # Check to see if this is a scalar value.
2769                        if (ref $value eq "ARRAY") {
2770                            # Here we have a list value. Pull the current entry.
2771                            push @parameterList, $value->[$i];
2772                        } else {
2773                            # Here we have a scalar value. Use it unmodified.
2774                            push @parameterList, $value;
2775                        }
2776                    }
2777                    # Execute the INSERT statement with the specified parameter list.
2778                    $retVal = $sth->execute(@parameterList);
2779                    if (!$retVal) {
2780                        my $errorString = $sth->errstr();
2781                        Confess("Error inserting into $relationName: $errorString");
2782                    } else {
2783                        Trace("Insert successful using $parameterList[0].") if T(3);
2784                    }
2785                }
2786            }
2787        }
2788        # Return a 1 for backward compatability.
2789        return 1;
2790    }
2791    
2792    =head3 UpdateEntity
2793    
2794        $erdb->UpdateEntity($entityName, $id, \%fields);
2795    
2796    Update the values of an entity. This is an unprotected update, so it should only be
2797    done if the database resides on a database server.
2798    
2799    =over 4
2800    
2801    =item entityName
2802    
2803    Name of the entity to update. (This is the entity type.)
2804    
2805    =item id
2806    
2807    ID of the entity to update. If no entity exists with this ID, an error will be thrown.
2808    
2809    =item fields
2810    
2811    Reference to a hash mapping field names to their new values. All of the fields named
2812    must be in the entity's primary relation, and they cannot any of them be the ID field.
2813    
2814    =back
2815    
2816    =cut
2817    
2818    sub UpdateEntity {
2819        # Get the parameters.
2820        my ($self, $entityName, $id, $fields) = @_;
2821        # Get a list of the field names being updated.
2822        my @fieldList = keys %{$fields};
2823        # Verify that the fields exist.
2824        my $checker = $self->GetFieldTable($entityName);
2825        for my $field (@fieldList) {
2826            if ($field eq 'id') {
2827                Confess("Cannot update the ID field for entity $entityName.");
2828            } elsif ($checker->{$field}->{relation} ne $entityName) {
2829                Confess("Cannot find $field in primary relation of $entityName.");
2830            }
2831        }
2832        # Build the SQL statement.
2833        my @sets = ();
2834        my @valueList = ();
2835        for my $field (@fieldList) {
2836            push @sets, _FixName($field) . " = ?";
2837            push @valueList, $fields->{$field};
2838        }
2839        my $command = "UPDATE $entityName SET " . join(", ", @sets) . " WHERE id = ?";
2840        # Add the ID to the list of binding values.
2841        push @valueList, $id;
2842        # Call SQL to do the work.
2843        my $rows = $self->{_dbh}->SQL($command, 0, @valueList);
2844        # Check for errors.
2845        if ($rows == 0) {
2846            Confess("Entity $id of type $entityName not found.");
2847        }
2848    }
2849    
2850    =head3 LoadTable
2851    
2852        my $results = $erdb->LoadTable($fileName, $relationName, %options);
2853    
2854    Load data from a tab-delimited file into a specified table, optionally re-creating the table
2855    first.
2856    
2857    =over 4
2858    
2859    =item fileName
2860    
2861    Name of the file from which the table data should be loaded.
2862    
2863    =item relationName
2864    
2865    Name of the relation to be loaded. This is the same as the table name.
2866    
2867    =item options
2868    
2869    A hash of load options.
2870    
2871    =item RETURN
2872    
2873    Returns a statistical object containing a list of the error messages.
2874    
2875    =back
2876    
2877    The permissible options are as follows.
2878    
2879    =over 4
2880    
2881    =item truncate
2882    
2883    If TRUE, then the table will be erased before loading.
2884    
2885    =item mode
2886    
2887    Mode in which the load should operate, either C<low_priority> or C<concurrent>.
2888    This option is only applicable to a MySQL database.
2889    
2890    =item partial
2891    
2892    If TRUE, then it is assumed that this is a partial load, and the table will not
2893    be analyzed and compacted at the end.
2894    
2895    =back
2896    
2897    =cut
2898    sub LoadTable {
2899        # Get the parameters.
2900        my ($self, $fileName, $relationName, %options) = @_;
2901        # Create the statistical return object.
2902        my $retVal = _GetLoadStats();
2903        # Trace the fact of the load.
2904        Trace("Loading table $relationName from $fileName") if T(2);
2905        # Get the database handle.
2906        my $dbh = $self->{_dbh};
2907        # Get the input file size.
2908        my $fileSize = -s $fileName;
2909        # Get the relation data.
2910        my $relation = $self->_FindRelation($relationName);
2911        # Check the truncation flag.
2912        if ($options{truncate}) {
2913            Trace("Creating table $relationName") if T(2);
2914            # Compute the row count estimate. We take the size of the load file,
2915            # divide it by the estimated row size, and then multiply by 2 to
2916            # leave extra room. We postulate a minimum row count of 1000 to
2917            # prevent problems with incoming empty load files.
2918            my $rowSize = $self->EstimateRowSize($relationName);
2919            my $estimate = $fileSize * 8 / $rowSize;
2920            if ($estimate < 1000) {
2921                $estimate = 1000;
2922            }
2923            # Re-create the table without its index.
2924            $self->CreateTable($relationName, 0, $estimate);
2925            # If this is a pre-index DBMS, create the index here.
2926            if ($dbh->{_preIndex}) {
2927                eval {
2928                    $self->CreateIndex($relationName);
2929                };
2930                if ($@) {
2931                    $retVal->AddMessage($@);
2932                }
2933            }
2934        }
2935        # Load the table.
2936        my $rv;
2937        eval {
2938            $rv = $dbh->load_table(file => $fileName, tbl => $relationName, style => $options{mode});
2939        };
2940        if (!defined $rv) {
2941            $retVal->AddMessage($@) if ($@);
2942            $retVal->AddMessage("Table load failed for $relationName using $fileName: " . $dbh->error_message);
2943            Trace("Table load failed for $relationName.") if T(1);
2944        } else {
2945            # Here we successfully loaded the table.
2946            $retVal->Add("tables");
2947            my $size = -s $fileName;
2948            Trace("$size bytes loaded into $relationName.") if T(2);
2949            $retVal->Add("bytes", $size);
2950            # If we're rebuilding, we need to create the table indexes.
2951            if ($options{truncate}) {
2952                # Indexes are created here for PostGres. For PostGres, indexes are
2953                # best built at the end. For MySQL, the reverse is true.
2954                if (! $dbh->{_preIndex}) {
2955                    eval {
2956                        $self->CreateIndex($relationName);
2957                    };
2958                    if ($@) {
2959                        $retVal->AddMessage($@);
2960                    }
2961                }
2962                # The full-text index (if any) is always built last, even for MySQL.
2963                # First we need to see if this table has a full-text index. Only
2964                # primary relations are allowed that privilege.
2965                Trace("Checking for full-text index on $relationName.") if T(2);
2966                if ($self->_IsPrimary($relationName)) {
2967                    $self->CreateSearchIndex($relationName);
2968                }
2969            }
2970        }
2971        # Analyze the table to improve performance.
2972        if (! $options{partial}) {
2973            Trace("Analyzing and compacting $relationName.") if T(3);
2974            $dbh->vacuum_it($relationName);
2975        }
2976        Trace("$relationName load completed.") if T(3);
2977        # Return the statistics.
2978        return $retVal;
2979    }
2980    
2981    =head3 CreateSearchIndex
2982    
2983        $erdb->CreateSearchIndex($objectName);
2984    
2985    Check for a full-text search index on the specified entity or relationship object, and
2986    if one is required, rebuild it.
2987    
2988    =over 4
2989    
2990    =item objectName
2991    
2992    Name of the entity or relationship to be indexed.
2993    
2994    =back
2995    
2996    =cut
2997    
2998    sub CreateSearchIndex {
2999        # Get the parameters.
3000        my ($self, $objectName) = @_;
3001        # Get the relation's entity/relationship structure.
3002        my $structure = $self->_GetStructure($objectName);
3003        # Get the database handle.
3004        my $dbh = $self->{_dbh};
3005        Trace("Checking for search fields in $objectName.") if T(3);
3006        # Check for a searchable fields list.
3007        if (exists $structure->{searchFields}) {
3008            # Here we know that we need to create a full-text search index.
3009            # Get an SQL-formatted field name list.
3010            my $fields = join(", ", _FixNames(@{$structure->{searchFields}}));
3011            # Create the index. If it already exists, it will be dropped.
3012            $dbh->create_index(tbl => $objectName, idx => "search_idx",
3013                               flds => $fields, kind => 'fulltext');
3014            Trace("Index created for $fields in $objectName.") if T(2);
3015        }
3016    }
3017    
3018    =head3 DropRelation
3019    
3020        $erdb->DropRelation($relationName);
3021    
3022    Physically drop a relation from the database.
3023    
3024    =over 4
3025    
3026    =item relationName
3027    
3028    Name of the relation to drop. If it does not exist, this method will have
3029    no effect.
3030    
3031    =back
3032    
3033    =cut
3034    
3035    sub DropRelation {
3036        # Get the parameters.
3037        my ($self, $relationName) = @_;
3038        # Get the database handle.
3039        my $dbh = $self->{_dbh};
3040        # Drop the relation. The method used here has no effect if the relation
3041        # does not exist.
3042        Trace("Invoking DB Kernel to drop $relationName.") if T(3);
3043        $dbh->drop_table(tbl => $relationName);
3044    }
3045    
3046    =head3 MatchSqlPattern
3047    
3048        my $matched = ERDB::MatchSqlPattern($value, $pattern);
3049    
3050    Determine whether or not a specified value matches an SQL pattern. An SQL
3051    pattern has two wild card characters: C<%> that matches multiple characters,
3052    and C<_> that matches a single character. These can be escaped using a
3053    backslash (C<\>). We pull this off by converting the SQL pattern to a
3054    PERL regular expression. As per SQL rules, the match is case-insensitive.
3055    
3056    =over 4
3057    
3058    =item value
3059    
3060    Value to be matched against the pattern. Note that an undefined or empty
3061    value will not match anything.
3062    
3063    =item pattern
3064    
3065    SQL pattern against which to match the value. An undefined or empty pattern will
3066    match everything.
3067    
3068    =item RETURN
3069    
3070    Returns TRUE if the value and pattern match, else FALSE.
3071    
3072    =back
3073    
3074    =cut
3075    
3076    sub MatchSqlPattern {
3077        # Get the parameters.
3078        my ($value, $pattern) = @_;
3079        # Declare the return variable.
3080        my $retVal;
3081        # Insure we have a pattern.
3082        if (! defined($pattern) || $pattern eq "") {
3083            $retVal = 1;
3084        } else {
3085            # Break the pattern into pieces around the wildcard characters. Because we
3086            # use parentheses in the split function's delimiter expression, we'll get
3087            # list elements for the delimiters as well as the rest of the string.
3088            my @pieces = split /([_%]|\\[_%])/, $pattern;
3089            # Check some fast special cases.
3090            if ($pattern eq '%') {
3091                # A null pattern matches everything.
3092                $retVal = 1;
3093            } elsif (@pieces == 1) {
3094                # No wildcards, so we have a literal comparison. Note we're case-insensitive.
3095                $retVal = (lc($value) eq lc($pattern));
3096            } elsif (@pieces == 2 && $pieces[1] eq '%') {
3097                # A wildcard at the end, so we have a substring match. This is also case-insensitive.
3098                $retVal = (lc(substr($value, 0, length($pieces[0]))) eq lc($pieces[0]));
3099            } else {
3100                # Okay, we have to do it the hard way. Convert each piece to a PERL pattern.
3101                my $realPattern = "";
3102                for my $piece (@pieces) {
3103                    # Determine the type of piece.
3104                    if ($piece eq "") {
3105                        # Empty pieces are ignored.
3106                    } elsif ($piece eq "%") {
3107                        # Here we have a multi-character wildcard. Note that it can match
3108                        # zero or more characters.
3109                        $realPattern .= ".*"
3110                    } elsif ($piece eq "_") {
3111                        # Here we have a single-character wildcard.
3112                        $realPattern .= ".";
3113                    } elsif ($piece eq "\\%" || $piece eq "\\_") {
3114                        # This is an escape sequence (which is a rare thing, actually).
3115                        $realPattern .= substr($piece, 1, 1);
3116                    } else {
3117                        # Here we have raw text.
3118                        $realPattern .= quotemeta($piece);
3119                    }
3120                }
3121                # Do the match.
3122                $retVal = ($value =~ /^$realPattern$/i ? 1 : 0);
3123            }
3124        }
3125        # Return the result.
3126        return $retVal;
3127    }
3128    
3129    =head3 GetEntity
3130    
3131        my $entityObject = $erdb->GetEntity($entityType, $ID);
3132    
3133    Return an object describing the entity instance with a specified ID.
3134    
3135    =over 4
3136    
3137    =item entityType
3138    
3139    Entity type name.
3140    
3141    =item ID
3142    
3143    ID of the desired entity.
3144    
3145    =item RETURN
3146    
3147    Returns a B<ERDBObject> representing the desired entity instance, or an undefined value if no
3148    instance is found with the specified key.
3149    
3150    =back
3151    
3152    =cut
3153    
3154    sub GetEntity {
3155        # Get the parameters.
3156        my ($self, $entityType, $ID) = @_;
3157        # Create a query.
3158        my $query = $self->Get([$entityType], "$entityType(id) = ?", [$ID]);
3159        # Get the first (and only) object.
3160        my $retVal = $query->Fetch();
3161        # Return the result.
3162        return $retVal;
3163    }
3164    
3165    =head3 GetChoices
3166    
3167        my @values = $erdb->GetChoices($entityName, $fieldName);
3168    
3169    Return a list of all the values for the specified field that are represented in the
3170    specified entity.
3171    
3172    Note that if the field is not indexed, then this will be a very slow operation.
3173    
3174    =over 4
3175    
3176    =item entityName
3177    
3178    Name of an entity in the database.
3179    
3180    =item fieldName
3181    
3182    Name of a field belonging to the entity. This is a raw field name without
3183    the standard parenthesized notation used in most calls.
3184    
3185    =item RETURN
3186    
3187    Returns a list of the distinct values for the specified field in the database.
3188    
3189    =back
3190    
3191    =cut
3192    
3193    sub GetChoices {
3194        # Get the parameters.
3195        my ($self, $entityName, $fieldName) = @_;
3196        # Declare the return variable.
3197        my @retVal;
3198        # Get the entity data structure.
3199        my $entityData = $self->_GetStructure($entityName);
3200        # Get the field.
3201        my $fieldHash = $entityData->{Fields};
3202        if (! exists $fieldHash->{$fieldName}) {
3203            Confess("$fieldName not found in $entityName.");
3204        } else {
3205            # Get the name of the relation containing the field.
3206            my $relation = $fieldHash->{$fieldName}->{relation};
3207            # Fix up the field name.
3208            my $realName = _FixName($fieldName);
3209            # Get the database handle.
3210            my $dbh = $self->{_dbh};
3211            # Query the database.
3212            my $results = $dbh->SQL("SELECT DISTINCT $realName FROM $relation");
3213            # Clean the results. They are stored as a list of lists, and we just want the one list.
3214            @retVal = sort map { $_->[0] } @{$results};
3215        }
3216        # Return the result.
3217        return @retVal;
3218    }
3219    
3220    =head3 GetEntityValues
3221    
3222        my @values = $erdb->GetEntityValues($entityType, $ID, \@fields);
3223    
3224    Return a list of values from a specified entity instance. If the entity instance
3225    does not exist, an empty list is returned.
3226    
3227    =over 4
3228    
3229    =item entityType
3230    
3231    Entity type name.
3232    
3233    =item ID
3234    
3235    ID of the desired entity.
3236    
3237    =item fields
3238    
3239    List of field names, each of the form I<objectName>C<(>I<fieldName>C<)>.
3240    
3241    =item RETURN
3242    
3243    Returns a flattened list of the values of the specified fields for the specified entity.
3244    
3245    =back
3246    
3247    =cut
3248    
3249    sub GetEntityValues {
3250        # Get the parameters.
3251        my ($self, $entityType, $ID, $fields) = @_;
3252        # Get the specified entity.
3253        my $entity = $self->GetEntity($entityType, $ID);
3254        # Declare the return list.
3255        my @retVal = ();
3256        # If we found the entity, push the values into the return list.
3257        if ($entity) {
3258            push @retVal, $entity->Values($fields);
3259        }
3260        # Return the result.
3261        return @retVal;
3262    }
3263    
3264    =head3 GetAll
3265    
3266        my @list = $erdb->GetAll(\@objectNames, $filterClause, \@parameters, \@fields, $count);
3267    
3268    Return a list of values taken from the objects returned by a query. The first three
3269    parameters correspond to the parameters of the L</Get> method. The final parameter is
3270    a list of the fields desired from each record found by the query. The field name
3271    syntax is the standard syntax used for fields in the B<ERDB> system--
3272    B<I<objectName>(I<fieldName>)>-- where I<objectName> is the name of the relevant entity
3273    or relationship and I<fieldName> is the name of the field.
3274    
3275    The list returned will be a list of lists. Each element of the list will contain
3276    the values returned for the fields specified in the fourth parameter. If one of the
3277    fields specified returns multiple values, they are flattened in with the rest. For
3278    example, the following call will return a list of the features in a particular
3279    spreadsheet cell, and each feature will be represented by a list containing the
3280    feature ID followed by all of its essentiality determinations.
3281    
3282        @query = $erdb->Get(['ContainsFeature', 'Feature'], "ContainsFeature(from-link) = ?", [$ssCellID], ['Feature(id)', 'Feature(essential)']);
3283    
3284    =over 4
3285    
3286    =item objectNames
3287    
3288    List containing the names of the entity and relationship objects to be retrieved.
3289    
3290    =item filterClause
3291    
3292    WHERE/ORDER BY clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can
3293    be parameterized with parameter markers (C<?>). Each field used must be specified in the standard form
3294    B<I<objectName>(I<fieldName>)>. Any parameters specified in the filter clause should be added to the
3295    parameter list as additional parameters. The fields in a filter clause can come from primary
3296    entity relations, relationship relations, or secondary entity relations; however, all of the
3297    entities and relationships involved must be included in the list of object names.
3298    
3299    =item parameterList
3300    
3301    List of the parameters to be substituted in for the parameters marks in the filter clause.
3302    
3303    =item fields
3304    
3305    List of the fields to be returned in each element of the list returned.
3306    
3307    =item count
3308    
3309    Maximum number of records to return. If omitted or 0, all available records will be returned.
3310    
3311    =item RETURN
3312    
3313    Returns a list of list references. Each element of the return list contains the values for the
3314    fields specified in the B<fields> parameter.
3315    
3316    =back
3317    
3318    =cut
3319    #: Return Type @@;
3320    sub GetAll {
3321        # Get the parameters.
3322        my ($self, $objectNames, $filterClause, $parameterList, $fields, $count) = @_;
3323        # Translate the parameters from a list reference to a list. If the parameter
3324        # list is a scalar we convert it into a singleton list.
3325        my @parmList = ();
3326        if (ref $parameterList eq "ARRAY") {
3327            Trace("GetAll parm list is an array.") if T(4);
3328            @parmList = @{$parameterList};
3329        } else {
3330            Trace("GetAll parm list is a scalar: $parameterList.") if T(4);
3331            push @parmList, $parameterList;
3332        }
3333        # Insure the counter has a value.
3334        if (!defined $count) {
3335            $count = 0;
3336        }
3337        # Add the row limit to the filter clause.
3338        if ($count > 0) {
3339            $filterClause .= " LIMIT $count";
3340        }
3341        # Create the query.
3342        my $query = $self->Get($objectNames, $filterClause, \@parmList);
3343        # Set up a counter of the number of records read.
3344        my $fetched = 0;
3345        # Loop through the records returned, extracting the fields. Note that if the
3346        # counter is non-zero, we stop when the number of records read hits the count.
3347        my @retVal = ();
3348        while (($count == 0 || $fetched < $count) && (my $row = $query->Fetch())) {
3349            my @rowData = $row->Values($fields);
3350            push @retVal, \@rowData;
3351            $fetched++;
3352        }
3353        Trace("$fetched rows returned in GetAll.") if T(SQL => 4);
3354        # Return the resulting list.
3355        return @retVal;
3356    }
3357    
3358    =head3 Exists
3359    
3360        my $found = $sprout->Exists($entityName, $entityID);
3361    
3362    Return TRUE if an entity exists, else FALSE.
3363    
3364    =over 4
3365    
3366    =item entityName
3367    
3368    Name of the entity type (e.g. C<Feature>) relevant to the existence check.
3369    
3370    =item entityID
3371    
3372    ID of the entity instance whose existence is to be checked.
3373    
3374    =item RETURN
3375    
3376    Returns TRUE if the entity instance exists, else FALSE.
3377    
3378    =back
3379    
3380    =cut
3381    #: Return Type $;
3382    sub Exists {
3383        # Get the parameters.
3384        my ($self, $entityName, $entityID) = @_;
3385        # Check for the entity instance.
3386        Trace("Checking existence of $entityName with ID=$entityID.") if T(4);
3387        my $testInstance = $self->GetEntity($entityName, $entityID);
3388        # Return an existence indicator.
3389        my $retVal = ($testInstance ? 1 : 0);
3390        return $retVal;
3391    }
3392    
3393    =head3 EstimateRowSize
3394    
3395        my $rowSize = $erdb->EstimateRowSize($relName);
3396    
3397    Estimate the row size of the specified relation. The estimated row size is computed by adding
3398    up the average length for each data type.
3399    
3400    =over 4
3401    
3402    =item relName
3403    
3404    Name of the relation whose estimated row size is desired.
3405    
3406    =item RETURN
3407    
3408    Returns an estimate of the row size for the specified relation.
3409    
3410    =back
3411    
3412    =cut
3413    #: Return Type $;
3414    sub EstimateRowSize {
3415        # Get the parameters.
3416        my ($self, $relName) = @_;
3417        # Declare the return variable.
3418        my $retVal = 0;
3419        # Find the relation descriptor.
3420        my $relation = $self->_FindRelation($relName);
3421        # Get the list of fields.
3422        for my $fieldData (@{$relation->{Fields}}) {
3423            # Get the field type and add its length.
3424            my $fieldLen = $TypeTable{$fieldData->{type}}->{avgLen};
3425            $retVal += $fieldLen;
3426        }
3427        # Return the result.
3428        return $retVal;
3429    }
3430    
3431    =head3 GetFieldTable
3432    
3433        my $fieldHash = $self->GetFieldTable($objectnName);
3434    
3435    Get the field structure for a specified entity or relationship.
3436    
3437    =over 4
3438    
3439    =item objectName
3440    
3441    Name of the desired entity or relationship.
3442    
3443    =item RETURN
3444    
3445    The table containing the field descriptors for the specified object.
3446    
3447    =back
3448    
3449    =cut
3450    
3451    sub GetFieldTable {
3452        # Get the parameters.
3453        my ($self, $objectName) = @_;
3454        # Get the descriptor from the metadata.
3455        my $objectData = $self->_GetStructure($objectName);
3456        # Return the object's field table.
3457        return $objectData->{Fields};
3458    }
3459    
3460    =head3 SplitKeywords
3461    
3462        my @keywords = ERDB::SplitKeywords($keywordString);
3463    
3464    This method returns a list of the positive keywords in the specified
3465    keyword string. All of the operators will have been stripped off,
3466    and if the keyword is preceded by a minus operator (C<->), it will
3467    not be in the list returned. The idea here is to get a list of the
3468    keywords the user wants to see. The list will be processed to remove
3469    duplicates.
3470    
3471    It is possible to create a string that confuses this method. For example
3472    
3473        frog toad -frog
3474    
3475    would return both C<frog> and C<toad>. If this is a problem we can deal
3476    with it later.
3477    
3478    =over 4
3479    
3480    =item keywordString
3481    
3482    The keyword string to be parsed.
3483    
3484    =item RETURN
3485    
3486    Returns a list of the words in the keyword string the user wants to
3487    see.
3488    
3489    =back
3490    
3491    =cut
3492    
3493    sub SplitKeywords {
3494        # Get the parameters.
3495        my ($keywordString) = @_;
3496        # Make a safety copy of the string. (This helps during debugging.)
3497        my $workString = $keywordString;
3498        # Convert operators we don't care about to spaces.
3499        $workString =~ tr/+"()<>/ /;
3500        # Split the rest of the string along space boundaries. Note that we
3501        # eliminate any words that are zero length or begin with a minus sign.
3502        my @wordList = grep { $_ && substr($_, 0, 1) ne "-" } split /\s+/, $workString;
3503        # Use a hash to remove duplicates.
3504        my %words = map { $_ => 1 } @wordList;
3505        # Return the result.
3506        return sort keys %words;
3507    }
3508    
3509    =head3 ValidateFieldName
3510    
3511        my $okFlag = ERDB::ValidateFieldName($fieldName);
3512    
3513    Return TRUE if the specified field name is valid, else FALSE. Valid field names must
3514    be hyphenated words subject to certain restrictions.
3515    
3516    =over 4
3517    
3518    =item fieldName
3519    
3520    Field name to be validated.
3521    
3522    =item RETURN
3523    
3524    Returns TRUE if the field name is valid, else FALSE.
3525    
3526    =back
3527    
3528    =cut
3529    
3530    sub ValidateFieldName {
3531        # Get the parameters.
3532        my ($fieldName) = @_;
3533        # Declare the return variable. The field name is valid until we hear
3534        # differently.
3535        my $retVal = 1;
3536        # Compute the maximum name length.
3537        my $maxLen = $TypeTable{'name-string'}->{maxLen};
3538        # Look for bad stuff in the name.
3539        if ($fieldName =~ /--/) {
3540            # Here we have a doubled minus sign.
3541            Trace("Field name $fieldName has a doubled hyphen.") if T(1);
3542            $retVal = 0;
3543        } elsif ($fieldName !~ /^[A-Za-z]/) {
3544            # Here the field name is missing the initial letter.
3545            Trace("Field name $fieldName does not begin with a letter.") if T(1);
3546            $retVal = 0;
3547        } elsif (length($fieldName) > $maxLen) {
3548            # Here the field name is too long.
3549            Trace("Maximum field name length is $maxLen. Field name must be truncated to " . substr($fieldName,0, $maxLen) . ".");
3550        } else {
3551            # Strip out the minus signs. Everything remaining must be a letter,
3552            # underscore, or digit.
3553            my $strippedName = $fieldName;
3554            $strippedName =~ s/-//g;
3555            if ($strippedName !~ /^(\w|\d)+$/) {
3556                Trace("Field name $fieldName contains illegal characters.") if T(1);
3557                $retVal = 0;
3558            }
3559        }
3560        # Return the result.
3561        return $retVal;
3562    }
3563    
3564    =head3 ReadMetaXML
3565    
3566        my $rawMetaData = ERDB::ReadDBD($fileName);
3567    
3568    This method reads a raw database definition XML file and returns it.
3569    Normally, the metadata used by the ERDB system has been processed and
3570    modified to make it easier to load and retrieve the data; however,
3571    this method can be used to get the data in its raw form.
3572    
3573    =over 4
3574    
3575    =item fileName
3576    
3577    Name of the XML file to read.
3578    
3579    =item RETURN
3580    
3581    Returns a hash reference containing the raw XML data from the specified file.
3582    
3583    =back
3584    
3585    =cut
3586    
3587    sub ReadMetaXML {
3588        # Get the parameters.
3589        my ($fileName) = @_;
3590        # Read the XML.
3591        my $retVal = XML::Simple::XMLin($fileName, %XmlOptions, %XmlInOpts);
3592        Trace("XML metadata loaded from file $fileName.") if T(1);
3593        # Return the result.
3594        return $retVal;
3595    }
3596    
3597    =head3 GetEntityFieldHash
3598    
3599        my $fieldHashRef = ERDB::GetEntityFieldHash($structure, $entityName);
3600    
3601    Get the field hash of the named entity in the specified raw XML structure.
3602    The field hash may not exist, in which case we need to create it.
3603    
3604    =over 4
3605    
3606    =item structure
3607    
3608    Raw XML structure defininng the database. This is not the run-time XML used by
3609    an ERDB object, since that has all sorts of optimizations built-in.
3610    
3611    =item entityName
3612    
3613    Name of the entity whose field structure is desired.
3614    
3615    =item RETURN
3616    
3617    Returns the field hash used to define the entity's fields.
3618    
3619    =back
3620    
3621    =cut
3622    
3623    sub GetEntityFieldHash {
3624        # Get the parameters.
3625        my ($structure, $entityName) = @_;
3626        # Get the entity structure.
3627        my $entityData = $structure->{Entities}->{$entityName};
3628        # Look for a field structure.
3629        my $retVal = $entityData->{Fields};
3630        # If it doesn't exist, create it.
3631        if (! defined($retVal)) {
3632            $entityData->{Fields} = {};
3633            $retVal = $entityData->{Fields};
3634        }
3635        # Return the result.
3636        return $retVal;
3637    }
3638    
3639    =head3 WriteMetaXML
3640    
3641        ERDB::WriteMetaXML($structure, $fileName);
3642    
3643    Write the metadata XML to a file. This method is the reverse of L</ReadMetaXML>, and is
3644    used to update the database definition. It must be used with care, however, since it
3645    will only work on a raw structure, not on the processed structure created by an ERDB
3646    constructor.
3647    
3648    =over 4
3649    
3650    =item structure
3651    
3652    XML structure to be written to the file.
3653    
3654    =item fileName
3655    
3656    Name of the output file to which the updated XML should be stored.
3657    
3658    =back
3659    
3660    =cut
3661    
3662    sub WriteMetaXML {
3663        # Get the parameters.
3664        my ($structure, $fileName) = @_;
3665        # Compute the output.
3666        my $fileString = XML::Simple::XMLout($structure, %XmlOptions, %XmlOutOpts);
3667        # Write it to the file.
3668        my $xmlOut = Open(undef, ">$fileName");
3669        print $xmlOut $fileString;
3670    }
3671    
3672    
3673    =head3 HTMLNote
3674    
3675    Convert a note or comment to HTML by replacing some bulletin-board codes with HTML. The codes
3676    supported are C<[b]> for B<bold>, C<[i]> for I<italics>, and C<[p]> for a new paragraph.
3677    Except for C<[p]>, all the codes are closed by slash-codes. So, for
3678    example, C<[b]Feature[/b]> displays the string C<Feature> in boldface.
3679    
3680        my $realHtml = ERDB::HTMLNote($dataString);
3681    
3682    =over 4
3683    
3684    =item dataString
3685    
3686    String to convert to HTML.
3687    
3688    =item RETURN
3689    
3690    An HTML string derived from the input string.
3691    
3692    =back
3693    
3694    =cut
3695    
3696    sub HTMLNote {
3697        # Get the parameter.
3698        my ($dataString) = @_;
3699        # HTML-escape the text.
3700        my $retVal = CGI::escapeHTML($dataString);
3701        # Substitute the bulletin board codes.
3702        $retVal =~ s!\[(/?[bi])\]!<$1>!g;
3703        $retVal =~ s!\[p\]!</p><p>!g;
3704        $retVal =~ s!\[link\s+([^\]]+)\]!<a href="$1">!g;
3705        $retVal =~ s!\[/link\]!</a>!g;
3706        # Return the result.
3707        return $retVal;
3708    }
3709    
3710    =head3 WikiNote
3711    
3712    Convert a note or comment to Wiki text by replacing some bulletin-board codes with HTML. The codes
3713    supported are C<[b]> for B<bold>, C<[i]> for I<italics>, and C<[p]> for a new paragraph.
3714    Except for C<[p]>, all the codes are closed by slash-codes. So, for
3715    example, C<[b]Feature[/b]> displays the string C<Feature> in boldface.
3716    
3717        my $wikiText = ERDB::WikiNote($dataString);
3718    
3719    =over 4
3720    
3721    =item dataString
3722    
3723    String to convert to Wiki text.
3724    
3725    =item RETURN
3726    
3727    An Wiki text string derived from the input string.
3728    
3729    =back
3730    
3731    =cut
3732    
3733    sub WikiNote {
3734        # Get the parameter.
3735        my ($dataString) = @_;
3736        # HTML-escape the text.
3737        my $retVal = CGI::escapeHTML($dataString);
3738        # Substitute the bulletin board codes.
3739        my $italic = WikiTools::ItalicCode();
3740        $retVal =~ s/\[\/?i\]/$italic/g;
3741        my $bold = WikiTools::BoldCode();
3742        $retVal =~ s/\[\/?b\]/$bold/g;
3743        # Paragraph breaks are the same no matter which Wiki you're using.
3744        $retVal =~ s!\[p\]!\n\n!g;
3745        # Now we do the links, which are complicated by the need to know two
3746        # things: the target URL and the text.
3747        while ($retVal =~ /\[link\s+([^\]]+)\]([^\[]+)\[\/link\]/g) {
3748            # Replace the matched string with the Wiki markup for links. Note that
3749            # $-[0] is the starting position of the match for the entire expression,
3750            # and $+[0] is past the ending position.
3751            substr $retVal, $-[0], $+[0] - $-[0], WikiTools::LinkMarkup($1, $2);
3752        }
3753        # Return the result.
3754        return $retVal;
3755    }
3756    
3757    =head3 BeginTran
3758    
3759        $erdb->BeginTran();
3760    
3761    Start a database transaction.
3762    
3763    =cut
3764    
3765    sub BeginTran {
3766        my ($self) = @_;
3767        $self->{_dbh}->begin_tran();
3768    
3769    }
3770    
3771    =head3 CommitTran
3772    
3773        $erdb->CommitTran();
3774    
3775    Commit an active database transaction.
3776    
3777    =cut
3778    
3779    sub CommitTran {
3780        my ($self) = @_;
3781        $self->{_dbh}->commit_tran();
3782    }
3783    
3784    =head3 RollbackTran
3785    
3786        $erdb->RollbackTran();
3787    
3788    Roll back an active database transaction.
3789    
3790    =cut
3791    
3792    sub RollbackTran {
3793        my ($self) = @_;
3794        $self->{_dbh}->roll_tran();
3795    }
3796    
3797    =head3 UpdateField
3798    
3799        my $count = $erdb->UpdateField($objectNames, $fieldName, $oldValue, $newValue, $filter, $parms);
3800    
3801    Update all occurrences of a specific field value to a new value. The number of rows changed will be
3802    returned.
3803    
3804    =over 4
3805    
3806    =item fieldName
3807    
3808    Name of the field in standard I<objectName>C<(>I<fieldName>C<)> format.
3809    
3810    =item oldValue
3811    
3812    Value to be modified. All occurrences of this value in the named field will be replaced by the
3813    new value.
3814    
3815    =item newValue
3816    
3817    New value to be substituted for the old value when it's found.
3818    
3819    =item filter
3820    
3821    A standard ERDB filter clause (see L</Get>). The filter will be applied before any substitutions take place.
3822    
3823    =item parms
3824    
3825    Reference to a list of parameter values in the filter.
3826    
3827    =item RETURN
3828    
3829    Returns the number of rows modified.
3830    
3831    =back
3832    
3833    =cut
3834    
3835    sub UpdateField {
3836        # Get the parameters.
3837        my ($self, $fieldName, $oldValue, $newValue, $filter, $parms) = @_;