[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.26, Tue Oct 18 06:47:46 2005 UTC revision 1.101, Wed Sep 3 20:56:20 2008 UTC
# Line 6  Line 6 
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 FIG;      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 58  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 90  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 109  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 125  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 170  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 189  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 222  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 266  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 300  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. "avgLen" is the average byte length for estimating  # record sizes. "sort" is the key modifier for the sort command, "notes" is a type description,
343  # record sizes.  # and "indexMod", if non-zero, is the number of characters to use when the field is specified in an
344  my %TypeTable = ( char =>    { sqlType => 'CHAR(1)',            maxLen => 1,            avgLen =>   1, dataGen => "StringGen('A')" },  # index
345                    int =>     { sqlType => 'INTEGER',            maxLen => 20,           avgLen =>   4, dataGen => "IntGen(0, 99999999)" },  my %TypeTable = ( char =>    { sqlType => 'CHAR(1)',            maxLen => 1,            avgLen =>   1, sort => "",
346                    string =>  { sqlType => 'VARCHAR(255)',       maxLen => 255,          avgLen => 100, dataGen => "StringGen(IntGen(10,250))" },                                 indexMod =>   0, notes => "single ASCII character"},
347                    text =>    { sqlType => 'TEXT',               maxLen => 1000000000,   avgLen => 500, dataGen => "StringGen(IntGen(80,1000))" },                    int =>     { sqlType => 'INTEGER',            maxLen => 20,           avgLen =>   4, sort => "n",
348                    date =>    { sqlType => 'BIGINT',             maxLen => 80,           avgLen =>   8, dataGen => "DateGen(-7, 7, IntGen(0,1400))" },                                 indexMod =>   0, notes => "signed 32-bit integer"},
349                    float =>   { sqlType => 'DOUBLE PRECISION',   maxLen => 40,           avgLen =>   8, dataGen => "FloatGen(0.0, 100.0)" },                    counter => { sqlType => 'INTEGER UNSIGNED',   maxLen => 20,           avgLen =>   4, sort => "n",
350                    boolean => { sqlType => 'SMALLINT',           maxLen => 1,            avgLen =>   2, dataGen => "IntGen(0, 1)" },                                 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,           avgLen =>  10, 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,           avgLen =>  40, 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,          avgLen =>  40, 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 324  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 357  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 371  Line 450 
450    
451  =head3 ShowMetaData  =head3 ShowMetaData
452    
453  C<< $erdb->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 402  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 446  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 470  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 480  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 508  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<< $erdb->DumpMetaData(); >>      $erdb->DumpMetaData();
651    
652  Return a dump of the metadata structure.  Return a dump of the metadata structure.
653    
# Line 539  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            # Now we list the entity's relationships (if any). First, we build a list
709            # of the relationships relevant to this entity.
710            my @rels = ();
711            for my $rel (sort keys %$relationshipList) {
712                my $relStructure = $relationshipList->{$rel};
713                if ($relStructure->{from} eq $key || $relStructure->{to} eq $key) {
714                    # Get the relationship sentence.
715                    my $relSentence = _ComputeRelationshipSentence($rel, $relStructure);
716                    # Linkify it.
717                    my $linkedRel = WikiTools::LinkMarkup("#$rel", $rel);
718                    $relSentence =~ s/$rel/$linkedRel/;
719                    push @rels, $relSentence;
720                }
721            }
722            # Add the relationships as a Wiki list.
723            push @retVal, WikiTools::List(@rels);
724            # Get the entity's relations.
725            my $relationList = $entityData->{Relations};
726            # Loop through the relations, displaying them.
727            for my $relation (sort keys %{$relationList}) {
728                my $wikiString = _WikiRelationTable($relation, $relationList->{$relation});
729                push @retVal, $wikiString;
730            }
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<< $erdb->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 558  Line 1013 
1013      # Loop through the relations.      # Loop through the relations.
1014      for my $relationName (@relNames) {      for my $relationName (@relNames) {
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(2);          Trace("Relation $relationName created.") if T(2);
1018      }      }
1019  }  }
1020    
1021  =head3 CreateTable  =head3 CreateTable
1022    
1023  C<< $erdb->CreateTable($tableName, $indexFlag, $estimatedRows); >>      $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 607  Line 1062 
1062          # Push the result into the field list.          # Push the result into the field list.
1063          push @fieldList, $fieldString;          push @fieldList, $fieldString;
1064      }      }
     # If this is a root table, add the "new_record" flag. It defaults to 0, so  
     if ($rootFlag) {  
         push @fieldList, "new_record $TypeTable{boolean}->{sqlType} NOT NULL DEFAULT 0";  
     }  
1065      # Convert the field list into a comma-delimited string.      # Convert the field list into a comma-delimited string.
1066      my $fieldThing = join(', ', @fieldList);      my $fieldThing = join(', ', @fieldList);
1067      # Insure the table is not already there.      # Insure the table is not already there.
# Line 621  Line 1072 
1072      my $estimation = undef;      my $estimation = undef;
1073      if ($estimatedRows) {      if ($estimatedRows) {
1074          $estimation = [$self->EstimateRowSize($relationName), $estimatedRows];          $estimation = [$self->EstimateRowSize($relationName), $estimatedRows];
1075            Trace("$estimation->[1] rows of $estimation->[0] bytes each.") if T(3);
1076      }      }
1077      # Create the table.      # Create the table.
1078      Trace("Creating table $relationName: $fieldThing") if T(2);      Trace("Creating table $relationName: $fieldThing") if T(2);
1079      $dbh->create_table(tbl => $relationName, flds => $fieldThing, estimates => $estimation);      $dbh->create_table(tbl => $relationName, flds => $fieldThing, estimates => $estimation);
1080      Trace("Relation $relationName created in database.") if T(2);      Trace("Relation $relationName created in database.") if T(2);
1081      # 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
1082        # index will not be built until the table has been loaded.
1083      if ($indexFlag) {      if ($indexFlag) {
1084          $self->CreateIndex($relationName);          $self->CreateIndex($relationName);
1085      }      }
1086  }  }
1087    
1088    =head3 VerifyFields
1089    
1090        my $count = $erdb->VerifyFields($relName, \@fieldList);
1091    
1092    Run through the list of proposed field values, insuring that all the character fields are
1093    below the maximum length. If any fields are too long, they will be truncated in place.
1094    
1095    =over 4
1096    
1097    =item relName
1098    
1099    Name of the relation for which the specified fields are destined.
1100    
1101    =item fieldList
1102    
1103    Reference to a list, in order, of the fields to be put into the relation.
1104    
1105    =item RETURN
1106    
1107    Returns the number of fields truncated.
1108    
1109    =back
1110    
1111    =cut
1112    
1113    sub VerifyFields {
1114        # Get the parameters.
1115        my ($self, $relName, $fieldList) = @_;
1116        # Initialize the return value.
1117        my $retVal = 0;
1118        # Get the relation definition.
1119        my $relData = $self->_FindRelation($relName);
1120        # Get the list of field descriptors.
1121        my $fieldTypes = $relData->{Fields};
1122        my $fieldCount = scalar @{$fieldTypes};
1123        # Loop through the two lists.
1124        for (my $i = 0; $i < $fieldCount; $i++) {
1125            # Get the type of the current field.
1126            my $fieldType = $fieldTypes->[$i]->{type};
1127            # If it's a character field, verify the length.
1128            if ($fieldType =~ /string/) {
1129                my $maxLen = $TypeTable{$fieldType}->{maxLen};
1130                my $oldString = $fieldList->[$i];
1131                if (length($oldString) > $maxLen) {
1132                    # Here it's too big, so we truncate it.
1133                    Trace("Truncating field $i ($fieldTypes->[$i]->{name}) in relation $relName to $maxLen characters from \"$oldString\".") if T(1);
1134                    $fieldList->[$i] = substr $oldString, 0, $maxLen;
1135                    $retVal++;
1136                }
1137            }
1138        }
1139        # Return the truncation count.
1140        return $retVal;
1141    }
1142    
1143    =head3 DigestFields
1144    
1145        $erdb->DigestFields($relName, $fieldList);
1146    
1147    Digest the strings in the field list that correspond to data type C<hash-string> in the
1148    specified relation.
1149    
1150    =over 4
1151    
1152    =item relName
1153    
1154    Name of the relation to which the fields belong.
1155    
1156    =item fieldList
1157    
1158    List of field contents to be loaded into the relation.
1159    
1160    =back
1161    
1162    =cut
1163    #: Return Type ;
1164    sub DigestFields {
1165        # Get the parameters.
1166        my ($self, $relName, $fieldList) = @_;
1167        # Get the relation definition.
1168        my $relData = $self->_FindRelation($relName);
1169        # Get the list of field descriptors.
1170        my $fieldTypes = $relData->{Fields};
1171        my $fieldCount = scalar @{$fieldTypes};
1172        # Loop through the two lists.
1173        for (my $i = 0; $i < $fieldCount; $i++) {
1174            # Get the type of the current field.
1175            my $fieldType = $fieldTypes->[$i]->{type};
1176            # If it's a hash string, digest it in place.
1177            if ($fieldType eq 'hash-string') {
1178                $fieldList->[$i] = $self->DigestKey($fieldList->[$i]);
1179            }
1180        }
1181    }
1182    
1183    =head3 DigestKey
1184    
1185        my $digested = $erdb->DigestKey($keyValue);
1186    
1187    Return the digested value of a symbolic key. The digested value can then be plugged into a
1188    key-based search into a table with key-type hash-string.
1189    
1190    Currently the digesting process is independent of the database structure, but that may not
1191    always be the case, so this is an instance method instead of a static method.
1192    
1193    =over 4
1194    
1195    =item keyValue
1196    
1197    Key value to digest.
1198    
1199    =item RETURN
1200    
1201    Digested value of the key.
1202    
1203    =back
1204    
1205    =cut
1206    
1207    sub DigestKey {
1208        # Get the parameters.
1209        my ($self, $keyValue) = @_;
1210        # Compute the digest.
1211        my $retVal = md5_base64($keyValue);
1212        # Return the result.
1213        return $retVal;
1214    }
1215    
1216  =head3 CreateIndex  =head3 CreateIndex
1217    
1218  C<< $erdb->CreateIndex($relationName); >>      $erdb->CreateIndex($relationName);
1219    
1220  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
1221  is the case in L</LoadTable>), it is sometimes best to create the indexes after the load.  is the case in L</LoadTable>), it is sometimes best to create the indexes after the load.
# Line 655  Line 1236 
1236      for my $indexName (keys %{$indexHash}) {      for my $indexName (keys %{$indexHash}) {
1237          my $indexData = $indexHash->{$indexName};          my $indexData = $indexHash->{$indexName};
1238          # Get the index's field list.          # Get the index's field list.
1239          my @fieldList = _FixNames(@{$indexData->{IndexFields}});          my @rawFields = @{$indexData->{IndexFields}};
1240            # Get a hash of the relation's field types.
1241            my %types = map { $_->{name} => $_->{type} } @{$relationData->{Fields}};
1242            # We need to check for text fields so we can append a length limitation for them. To do
1243            # that, we need the relation's field list.
1244            my $relFields = $relationData->{Fields};
1245            for (my $i = 0; $i <= $#rawFields; $i++) {
1246                # Get the field type.
1247                my $field = $rawFields[$i];
1248                my $type = $types{$field};
1249                # Ask if it requires using prefix notation for the index.
1250                my $mod = $TypeTable{$type}->{indexMod};
1251                Trace("Field $field ($i) in $relationName has type $type and indexMod $mod.") if T(3);
1252                if ($mod) {
1253                    # Append the prefix length to the field name,
1254                    $rawFields[$i] .= "($mod)";
1255                }
1256            }
1257            my @fieldList = _FixNames(@rawFields);
1258          my $flds = join(', ', @fieldList);          my $flds = join(', ', @fieldList);
1259          # Get the index's uniqueness flag.          # Get the index's uniqueness flag.
1260          my $unique = (exists $indexData->{Unique} ? $indexData->{Unique} : 'false');          my $unique = (exists $indexData->{Unique} ? 'unique' : undef);
1261          # Create the index.          # Create the index.
1262          my $rv = $dbh->create_index(idx => $indexName, tbl => $relationName,          my $rv = $dbh->create_index(idx => $indexName, tbl => $relationName,
1263                                      flds => $flds, unique => $unique);                                      flds => $flds, kind => $unique);
1264          if ($rv) {          if ($rv) {
1265              Trace("Index created: $indexName for $relationName ($flds)") if T(1);              Trace("Index created: $indexName for $relationName ($flds)") if T(1);
1266          } else {          } else {
# Line 670  Line 1269 
1269      }      }
1270  }  }
1271    
1272  =head3 LoadTables  =head3 GetSecondaryFields
   
 C<< my $stats = $erdb->LoadTables($directoryName, $rebuild); >>  
1273    
1274  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.  
1275    
1276  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
1277  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
1278  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
1279    or to have multiple values.
1280    
1281  =over 4  =over 4
1282    
1283  =item directoryName  =item entityName
   
 Name of the directory containing the relation files to be loaded.  
   
 =item rebuild  
1284    
1285  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.  
1286    
1287  =item RETURN  =item RETURN
1288    
1289  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.
1290    
1291  =back  =back
1292    
1293  =cut  =cut
1294    
1295  sub LoadTables {  sub GetSecondaryFields {
1296      # Get the parameters.      # Get the parameters.
1297      my ($self, $directoryName, $rebuild) = @_;      my ($self, $entityName) = @_;
1298      # Start the timer.      # Declare the return variable.
1299      my $startTime = gettimeofday;      my %retVal = ();
1300      # Clean any trailing slash from the directory name.      # Look for the entity.
1301      $directoryName =~ s!/\\$!!;      my $table = $self->GetFieldTable($entityName);
1302        # Loop through the fields, pulling out the secondaries.
1303        for my $field (sort keys %{$table}) {
1304            if ($table->{$field}->{relation} ne $entityName) {
1305                # Here we have a secondary field.
1306                $retVal{$field} = $table->{$field}->{type};
1307            }
1308        }
1309        # Return the result.
1310        return %retVal;
1311    }
1312    
1313    =head3 GetFieldRelationName
1314    
1315        my $name = $erdb->GetFieldRelationName($objectName, $fieldName);
1316    
1317    Return the name of the relation containing a specified field.
1318    
1319    =over 4
1320    
1321    =item objectName
1322    
1323    Name of the entity or relationship containing the field.
1324    
1325    =item fieldName
1326    
1327    Name of the relevant field in that entity or relationship.
1328    
1329    =item RETURN
1330    
1331    Returns the name of the database relation containing the field, or C<undef> if
1332    the field does not exist.
1333    
1334    =back
1335    
1336    =cut
1337    
1338    sub GetFieldRelationName {
1339        # Get the parameters.
1340        my ($self, $objectName, $fieldName) = @_;
1341        # Declare the return variable.
1342        my $retVal;
1343        # Get the object field table.
1344        my $table = $self->GetFieldTable($objectName);
1345        # Only proceed if the field exists.
1346        if (exists $table->{$fieldName}) {
1347            # Determine the name of the relation that contains this field.
1348            $retVal = $table->{$fieldName}->{relation};
1349        }
1350        # Return the result.
1351        return $retVal;
1352    }
1353    
1354    =head3 DeleteValue
1355    
1356        my $numDeleted = $erdb->DeleteValue($entityName, $id, $fieldName, $fieldValue);
1357    
1358    Delete secondary field values from the database. This method can be used to delete all
1359    values of a specified field for a particular entity instance, or only a single value.
1360    
1361    Secondary fields are stored in two-column relations separate from an entity's primary
1362    table, and as a result a secondary field can legitimately have no value or multiple
1363    values. Therefore, it makes sense to talk about deleting secondary fields where it
1364    would not make sense for primary fields.
1365    
1366    =over 4
1367    
1368    =item entityName
1369    
1370    Name of the entity from which the fields are to be deleted.
1371    
1372    =item id
1373    
1374    ID of the entity instance to be processed. If the instance is not found, this
1375    method will have no effect. If C<undef> is specified, all values for all of
1376    the entity instances will be deleted.
1377    
1378    =item fieldName
1379    
1380    Name of the field whose values are to be deleted.
1381    
1382    =item fieldValue (optional)
1383    
1384    Value to be deleted. If not specified, then all values of the specified field
1385    will be deleted for the entity instance. If specified, then only the values which
1386    match this parameter will be deleted.
1387    
1388    =item RETURN
1389    
1390    Returns the number of rows deleted.
1391    
1392    =back
1393    
1394    =cut
1395    
1396    sub DeleteValue {
1397        # Get the parameters.
1398        my ($self, $entityName, $id, $fieldName, $fieldValue) = @_;
1399        # Declare the return value.
1400        my $retVal = 0;
1401        # We need to set up an SQL command to do the deletion. First, we
1402        # find the name of the field's relation.
1403        my $table = $self->GetFieldTable($entityName);
1404        my $field = $table->{$fieldName};
1405        my $relation = $field->{relation};
1406        # Make sure this is a secondary field.
1407        if ($relation eq $entityName) {
1408            Confess("Cannot delete values of $fieldName for $entityName.");
1409        } else {
1410            # Set up the SQL command to delete all values.
1411            my $sql = "DELETE FROM $relation";
1412            # Build the filter.
1413            my @filters = ();
1414            my @parms = ();
1415            # Check for a filter by ID.
1416            if (defined $id) {
1417                push @filters, "id = ?";
1418                push @parms, $id;
1419            }
1420            # Check for a filter by value.
1421            if (defined $fieldValue) {
1422                push @filters, "$fieldName = ?";
1423                push @parms, $fieldValue;
1424            }
1425            # Append the filters to the command.
1426            if (@filters) {
1427                $sql .= " WHERE " . join(" AND ", @filters);
1428            }
1429            # Execute the command.
1430            my $dbh = $self->{_dbh};
1431            $retVal = $dbh->SQL($sql, 0, @parms);
1432        }
1433        # Return the result.
1434        return $retVal;
1435    }
1436    
1437    =head3 LoadTables
1438    
1439        my $stats = $erdb->LoadTables($directoryName, $rebuild);
1440    
1441    This method will load the database tables from a directory. The tables must already have been created
1442    in the database. (This can be done by calling L</CreateTables>.) The caller passes in a directory name;
1443    all of the relations to be loaded must have a file in the directory with the same name as the relation
1444    (optionally with a suffix of C<.dtx>). Each file must be a tab-delimited table of field values. Each
1445    line of the file will be loaded as a row of the target relation table. The field values should be in
1446    the same order as the fields in the relation tables generated by L</ShowMetaData>. The old data is
1447    erased before the new data is loaded in.
1448    
1449    A certain amount of translation automatically takes place. Ctrl-M characters are deleted, and
1450    tab and new-line characters inside a field are escaped as C<\t> and C<\n>, respectively. Dates must
1451    be entered as a Unix timestamp, that is, as an integer number of seconds since the base epoch.
1452    
1453    =over 4
1454    
1455    =item directoryName
1456    
1457    Name of the directory containing the relation files to be loaded.
1458    
1459    =item rebuild
1460    
1461    TRUE if the tables should be dropped and rebuilt, else FALSE. This is, unfortunately, the
1462    only way to erase existing data in the tables, since the TRUNCATE command is not supported
1463    by all of the DB engines we use.
1464    
1465    =item RETURN
1466    
1467    Returns a statistical object describing the number of records read and a list of the error messages.
1468    
1469    =back
1470    
1471    =cut
1472    
1473    sub LoadTables {
1474        # Get the parameters.
1475        my ($self, $directoryName, $rebuild) = @_;
1476        # Start the timer.
1477        my $startTime = gettimeofday;
1478        # Clean any trailing slash from the directory name.
1479        $directoryName =~ s!/\\$!!;
1480      # Declare the return variable.      # Declare the return variable.
1481      my $retVal = Stats->new();      my $retVal = Stats->new();
1482      # Get the relation names.      # Get the relation names.
# Line 732  Line 1496 
1496    
1497  =head3 GetTableNames  =head3 GetTableNames
1498    
1499  C<< my @names = $erdb->GetTableNames; >>      my @names = $erdb->GetTableNames;
1500    
1501  Return a list of the relations required to implement this database.  Return a list of the relations required to implement this database.
1502    
# Line 749  Line 1513 
1513    
1514  =head3 GetEntityTypes  =head3 GetEntityTypes
1515    
1516  C<< my @names = $erdb->GetEntityTypes; >>      my @names = $erdb->GetEntityTypes;
1517    
1518  Return a list of the entity type names.  Return a list of the entity type names.
1519    
# Line 764  Line 1528 
1528      return sort keys %{$entityList};      return sort keys %{$entityList};
1529  }  }
1530    
1531    =head3 GetConnectingRelationships
1532    
1533        my @list = $erdb->GetConnectingRelationships($entityName);
1534    
1535    Return a list of the relationships connected to the specified entity.
1536    
1537    =over 4
1538    
1539    =item entityName
1540    
1541    Entity whose connected relationships are desired.
1542    
1543    =item RETURN
1544    
1545    Returns a list of the relationships that originate from the entity.
1546    If the entity is on the from end, it will return the relationship
1547    name. If the entity is on the to end it will return the converse of
1548    the relationship name.
1549    
1550    =back
1551    
1552    =cut
1553    
1554    sub GetConnectingRelationships {
1555        # Get the parameters.
1556        my ($self, $entityName) = @_;
1557        # Declare the return variable.
1558        my @retVal;
1559        # Get the relationship list.
1560        my $relationships = $self->{_metaData}->{Relationships};
1561        # Find the entity.
1562        my $entity = $self->{_metaData}->{Entities}->{$entityName};
1563        # Only proceed if the entity exists.
1564        if (! defined $entity) {
1565            Trace("Entity $entityName not found.") if T(3);
1566        } else {
1567            # Loop through the relationships.
1568            my @rels = keys %$relationships;
1569            Trace(scalar(@rels) . " relationships found in connection search.") if T(3);
1570            for my $relationshipName (@rels) {
1571                my $relationship = $relationships->{$relationshipName};
1572                if ($relationship->{from} eq $entityName) {
1573                    # Here we have a forward relationship.
1574                    push @retVal, $relationshipName;
1575                } elsif ($relationship->{to} eq $entityName) {
1576                    # Here we have a backward relationship. In this case, the
1577                    # converse relationship name is preferred if it exists.
1578                    my $converse = $relationship->{converse} || $relationshipName;
1579                    push @retVal, $converse;
1580                }
1581            }
1582        }
1583        # Return the result.
1584        return @retVal;
1585    }
1586    
1587    
1588    
1589    
1590    =head3 GetDataTypes
1591    
1592        my %types = ERDB::GetDataTypes();
1593    
1594    Return a table of ERDB data types. The table returned is a hash of hashes.
1595    The keys of the big hash are the datatypes. Each smaller hash has several
1596    values used to manage the data. The most interesting is the SQL type (key
1597    C<sqlType>) and the descriptive node (key C<notes>).
1598    
1599    Note that changing the values in the smaller hashes will seriously break
1600    things, so this data should be treated as read-only.
1601    
1602    =cut
1603    
1604    sub GetDataTypes {
1605        return %TypeTable;
1606    }
1607    
1608    
1609  =head3 IsEntity  =head3 IsEntity
1610    
1611  C<< my $flag = $erdb->IsEntity($entityName); >>      my $flag = $erdb->IsEntity($entityName);
1612    
1613  Return TRUE if the parameter is an entity name, else FALSE.  Return TRUE if the parameter is an entity name, else FALSE.
1614    
# Line 793  Line 1635 
1635    
1636  =head3 Get  =head3 Get
1637    
1638  C<< my $query = $erdb->Get(\@objectNames, $filterClause, $param1, $param2, ..., $paramN); >>      my $query = $erdb->Get(\@objectNames, $filterClause, \@params);
1639    
1640  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.
1641  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 801  Line 1643 
1643  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
1644  $genus.  $genus.
1645    
1646  C<< $query = $erdb->Get(['Genome'], "Genome(genus) = ?", $genus); >>      $query = $erdb->Get(['Genome'], "Genome(genus) = ?", [$genus]);
1647    
1648  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
1649  parameter representing the parameter value. It would also be possible to code  parameter representing the parameter value. It would also be possible to code
1650    
1651  C<< $query = $erdb->Get(['Genome'], "Genome(genus) = \'$genus\'"); >>      $query = $erdb->Get(['Genome'], "Genome(genus) = \'$genus\'");
1652    
1653  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
1654  characters inside the variable C<$genus>.  characters inside the variable C<$genus>.
# Line 818  Line 1660 
1660  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
1661  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,
1662    
1663  C<< $query = $erdb->Get(['Genome', 'ComesFrom', 'Source'], "Genome(genus) = ?", $genus); >>      $query = $erdb->Get(['Genome', 'ComesFrom', 'Source'], "Genome(genus) = ?", [$genus]);
1664    
1665  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
1666  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.
1667  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
1668  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
1669  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  
1670  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,
1671  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.
1672    
1673    If an entity or relationship is mentioned twice, the name for the second occurrence will
1674    be suffixed with C<2>, the third occurrence will be suffixed with C<3>, and so forth. So,
1675    for example, if we have C<['Feature', 'HasContig', 'Contig', 'HasContig']>, then the
1676    B<to-link> field of the first B<HasContig> is specified as C<HasContig(to-link)>, while
1677    the B<to-link> field of the second B<HasContig> is specified as C<HasContig2(to-link)>.
1678    
1679  =over 4  =over 4
1680    
1681  =item objectNames  =item objectNames
# Line 849  Line 1696 
1696  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
1697  particular genus and sorts them by species name.  particular genus and sorts them by species name.
1698    
1699  C<< "Genome(genus) = ? ORDER BY Genome(species)" >>      "Genome(genus) = ? ORDER BY Genome(species)"
1700    
1701    Note that the case is important. Only an uppercase "ORDER BY" with a single space will
1702    be processed. The idea is to make it less likely to find the verb by accident.
1703    
1704  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
1705  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
1706  relation.  relation.
1707    
1708  =item param1, param2, ..., paramN  Finally, you can limit the number of rows returned by adding a LIMIT clause. The LIMIT must
1709    be the last thing in the filter clause, and it contains only the word "LIMIT" followed by
1710    a positive number. So, for example
1711    
1712        "Genome(genus) = ? ORDER BY Genome(species) LIMIT 10"
1713    
1714    will only return the first ten genomes for the specified genus. The ORDER BY clause is not
1715    required. For example, to just get the first 10 genomes in the B<Genome> table, you could
1716    use
1717    
1718  Parameter values to be substituted into the filter clause.      "LIMIT 10"
1719    
1720    =item params
1721    
1722    Reference to a list of parameter values to be substituted into the filter clause.
1723    
1724  =item RETURN  =item RETURN
1725    
# Line 869  Line 1731 
1731    
1732  sub Get {  sub Get {
1733      # Get the parameters.      # Get the parameters.
1734      my ($self, $objectNames, $filterClause, @params) = @_;      my ($self, $objectNames, $filterClause, $params) = @_;
1735      # Construct the SELECT statement. The general pattern is      # Process the SQL stuff.
1736      #      my ($suffix, $mappedNameListRef, $mappedNameHashRef) =
1737      # SELECT name1.*, name2.*, ... nameN.* FROM name1, name2, ... nameN          $self->_SetupSQL($objectNames, $filterClause);
1738      #      # Create the query.
1739      my $dbh = $self->{_dbh};      my $command = "SELECT " . join(".*, ", @{$mappedNameListRef}) .
1740      my $command = "SELECT DISTINCT " . join('.*, ', @{$objectNames}) . ".* FROM " .          ".* $suffix";
1741                  join(', ', @{$objectNames});      my $sth = $self->_GetStatementHandle($command, $params);
1742      Trace("SQL = $command") if T(SQL => 4);      # Now we create the relation map, which enables DBQuery to determine the order, name
1743      # Check for a filter clause.      # and mapped name for each object in the query.
1744      if ($filterClause) {      my @relationMap = ();
1745          # Here we have one, so we convert its field names and add it to the query. First,      for my $mappedName (@{$mappedNameListRef}) {
1746          # We create a copy of the filter string we can work with.          push @relationMap, [$mappedName, $mappedNameHashRef->{$mappedName}];
         my $filterString = $filterClause;  
         # Next, we sort the object names by length. This helps protect us from finding  
         # object names inside other object names when we're doing our search and replace.  
         my @sortedNames = sort { length($b) - length($a) } @{$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";  
         }  
1747      }      }
     Trace("SQL query: $command") if T(3);  
     Trace("PARMS: '" . (join "', '", @params) . "'") if (T(4) && (@params > 0));  
     my $sth = $dbh->prepare_command($command);  
     # Execute it with the parameters bound in.  
     $sth->execute(@params) || Confess("SELECT error" . $sth->errstr());  
1748      # Return the statement object.      # Return the statement object.
1749      my $retVal = DBQuery::_new($self, $sth, @{$objectNames});      my $retVal = DBQuery::_new($self, $sth, \@relationMap);
1750      return $retVal;      return $retVal;
1751  }  }
1752    
 =head3 GetList  
1753    
 C<< my @dbObjects = $erdb->GetList(\@objectNames, $filterClause, $param1, $param2, ..., $paramN); >>  
1754    
1755  Return a list of object descriptors for the specified objects as determined by the  =head3 Search
 specified filter clause.  
1756    
1757  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);
1758  than a query object that can be used to get the results one record at a time.  
1759    Perform a full text search with filtering. The search will be against a specified object
1760    in the object name list. That object will get an extra field containing the search
1761    relevance. Note that except for the search expression, the parameters of this method are
1762    the same as those for L</Get> and follow the same rules.
1763    
1764  =over 4  =over 4
1765    
1766    =item searchExpression
1767    
1768    Boolean search expression for the text fields of the target object. The default mode for
1769    a Boolean search expression is OR, but we want the default to be AND, so we will
1770    add a C<+> operator to each word with no other operator before it.
1771    
1772    =item idx
1773    
1774    Index in the I<$objectNames> list of the table to be searched in full-text mode.
1775    
1776  =item objectNames  =item objectNames
1777    
1778  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 1018  Line 1787 
1787  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
1788  be included in the list of object names.  be included in the list of object names.
1789    
1790  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)" >>  
   
 The rules for field references in a sort order are the same as those for field references in the  
 filter clause in general; however, odd things may happen if a sort field is from a secondary  
 relation.  
   
 =item param1, param2, ..., paramN  
1791    
1792  Parameter values to be substituted into the filter clause.  Reference to a list of parameter values to be substituted into the filter clause.
1793    
1794  =item RETURN  =item RETURN
1795    
1796  Returns a list of B<DBObject>s that satisfy the query conditions.  Returns a query object for the specified search.
1797    
1798  =back  =back
1799    
1800  =cut  =cut
1801  #: Return Type @%  
1802  sub GetList {  sub Search {
1803      # Get the parameters.      # Get the parameters.
1804      my ($self, $objectNames, $filterClause, @params) = @_;      my ($self, $searchExpression, $idx, $objectNames, $filterClause, $params) = @_;
1805      # Declare the return variable.      # Declare the return variable.
1806      my @retVal = ();      my $retVal;
1807      # Perform the query.      # Create a safety copy of the parameter list. Note we have to be careful to insure
1808      my $query = $self->Get($objectNames, $filterClause, @params);      # a parameter list exists before we copy it.
1809      # Loop through the results.      my @myParams = ();
1810      while (my $object = $query->Fetch) {      if (defined $params) {
1811          push @retVal, $object;          @myParams = @{$params};
1812      }      }
1813        # Get the first object's structure so we have access to the searchable fields.
1814        my $object1Name = $objectNames->[$idx];
1815        my $object1Structure = $self->_GetStructure($object1Name);
1816        # Get the field list.
1817        if (! exists $object1Structure->{searchFields}) {
1818            Confess("No searchable index for $object1Name.");
1819        } else {
1820            # Get the field list.
1821            my @fields = @{$object1Structure->{searchFields}};
1822            # Clean the search expression.
1823            my $actualKeywords = $self->CleanKeywords($searchExpression);
1824            # Prefix a "+" to each uncontrolled word. This converts the default
1825            # search mode from OR to AND.
1826            $actualKeywords =~ s/(^|\s)(\w|")/$1\+$2/g;
1827            Trace("Actual keywords for search are\n$actualKeywords") if T(3);
1828            # We need two match expressions, one for the filter clause and one in the
1829            # query itself. Both will use a parameter mark, so we need to push the
1830            # search expression onto the front of the parameter list twice.
1831            unshift @myParams, $actualKeywords, $actualKeywords;
1832            # Build the match expression.
1833            my @matchFilterFields = map { "$object1Name." . _FixName($_) } @fields;
1834            my $matchClause = "MATCH (" . join(", ", @matchFilterFields) . ") AGAINST (? IN BOOLEAN MODE)";
1835            # Process the SQL stuff.
1836            my ($suffix, $mappedNameListRef, $mappedNameHashRef) =
1837                $self->_SetupSQL($objectNames, $filterClause, $matchClause);
1838            # Create the query. Note that the match clause is inserted at the front of
1839            # the select fields.
1840            my $command = "SELECT $matchClause, " . join(".*, ", @{$mappedNameListRef}) .
1841                ".* $suffix";
1842            my $sth = $self->_GetStatementHandle($command, \@myParams);
1843            # Now we create the relation map, which enables DBQuery to determine the order, name
1844            # and mapped name for each object in the query.
1845            my @relationMap = _RelationMap($mappedNameHashRef, $mappedNameListRef);
1846            # Return the statement object.
1847            $retVal = DBQuery::_new($self, $sth, \@relationMap, $object1Name);
1848        }
1849        return $retVal;
1850    }
1851    
1852    =head3 GetFlat
1853    
1854        my @list = $erdb->GetFlat(\@objectNames, $filterClause, \@parameterList, $field);
1855    
1856    This is a variation of L</GetAll> that asks for only a single field per record and
1857    returns a single flattened list.
1858    
1859    =over 4
1860    
1861    =item objectNames
1862    
1863    List containing the names of the entity and relationship objects to be retrieved.
1864    
1865    =item filterClause
1866    
1867    WHERE/ORDER BY clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can
1868    be parameterized with parameter markers (C<?>). Each field used must be specified in the standard form
1869    B<I<objectName>(I<fieldName>)>. Any parameters specified in the filter clause should be added to the
1870    parameter list as additional parameters. The fields in a filter clause can come from primary
1871    entity relations, relationship relations, or secondary entity relations; however, all of the
1872    entities and relationships involved must be included in the list of object names.
1873    
1874    =item parameterList
1875    
1876    List of the parameters to be substituted in for the parameters marks in the filter clause.
1877    
1878    =item field
1879    
1880    Name of the field to be used to get the elements of the list returned.
1881    
1882    =item RETURN
1883    
1884    Returns a list of values.
1885    
1886    =back
1887    
1888    =cut
1889    #: Return Type @;
1890    sub GetFlat {
1891        # Get the parameters.
1892        my ($self, $objectNames, $filterClause, $parameterList, $field) = @_;
1893        # Construct the query.
1894        my $query = $self->Get($objectNames, $filterClause, $parameterList);
1895        # Create the result list.
1896        my @retVal = ();
1897        # Loop through the records, adding the field values found to the result list.
1898        while (my $row = $query->Fetch()) {
1899            push @retVal, $row->Value($field);
1900        }
1901        # Return the list created.
1902        return @retVal;
1903    }
1904    
1905    =head3 SpecialFields
1906    
1907        my %specials = $erdb->SpecialFields($entityName);
1908    
1909    Return a hash mapping special fields in the specified entity to the value of their
1910    C<special> attribute. This enables the subclass to get access to the special field
1911    attributes without needed to plumb the internal ERDB data structures.
1912    
1913    =over 4
1914    
1915    =item entityName
1916    
1917    Name of the entity whose special fields are desired.
1918    
1919    =item RETURN
1920    
1921    Returns a hash. The keys of the hash are the special field names, and the values
1922    are the values from each special field's C<special> attribute.
1923    
1924    =back
1925    
1926    =cut
1927    
1928    sub SpecialFields {
1929        # Get the parameters.
1930        my ($self, $entityName) = @_;
1931        # Declare the return variable.
1932        my %retVal = ();
1933        # Find the entity's data structure.
1934        my $entityData = $self->{_metaData}->{Entities}->{$entityName};
1935        # Loop through its fields, adding each special field to the return hash.
1936        my $fieldHash = $entityData->{Fields};
1937        for my $fieldName (keys %{$fieldHash}) {
1938            my $fieldData = $fieldHash->{$fieldName};
1939            if (exists $fieldData->{special}) {
1940                $retVal{$fieldName} = $fieldData->{special};
1941            }
1942        }
1943        # Return the result.
1944        return %retVal;
1945    }
1946    
1947    =head3 Delete
1948    
1949        my $stats = $erdb->Delete($entityName, $objectID, %options);
1950    
1951    Delete an entity instance from the database. The instance is deleted along with all entity and
1952    relationship instances dependent on it. The definition of I<dependence> is recursive.
1953    
1954    An object is always dependent on itself. An object is dependent if it is a 1-to-many or many-to-many
1955    relationship connected to a dependent entity or if it is the "to" entity connected to a 1-to-many
1956    dependent relationship.
1957    
1958    =over 4
1959    
1960    =item entityName
1961    
1962    Name of the entity type for the instance being deleted.
1963    
1964    =item objectID
1965    
1966    ID of the entity instance to be deleted. If the ID contains a wild card character (C<%>),
1967    then it is presumed to by a LIKE pattern.
1968    
1969    =item options
1970    
1971    A hash detailing the options for this delete operation.
1972    
1973    =item RETURN
1974    
1975    Returns a statistics object indicating how many records of each particular table were
1976    deleted.
1977    
1978    =back
1979    
1980    The permissible options for this method are as follows.
1981    
1982    =over 4
1983    
1984    =item testMode
1985    
1986    If TRUE, then the delete statements will be traced, but no changes will be made to the database.
1987    
1988    =item keepRoot
1989    
1990    If TRUE, then the entity instances will not be deleted, only the dependent records.
1991    
1992    =back
1993    
1994    =cut
1995    #: Return Type $%;
1996    sub Delete {
1997        # Get the parameters.
1998        my ($self, $entityName, $objectID, %options) = @_;
1999        # Declare the return variable.
2000        my $retVal = Stats->new();
2001        # Get the DBKernel object.
2002        my $db = $self->{_dbh};
2003        # We're going to generate all the paths branching out from the starting entity. One of
2004        # the things we have to be careful about is preventing loops. We'll use a hash to
2005        # determine if we've hit a loop.
2006        my %alreadyFound = ();
2007        # These next lists will serve as our result stack. We start by pushing object lists onto
2008        # the stack, and then popping them off to do the deletes. This means the deletes will
2009        # start with the longer paths before getting to the shorter ones. That, in turn, makes
2010        # sure we don't delete records that might be needed to forge relationships back to the
2011        # original item. We have two lists-- one for TO-relationships, and one for
2012        # FROM-relationships and entities.
2013        my @fromPathList = ();
2014        my @toPathList = ();
2015        # This final list is used to remember what work still needs to be done. We push paths
2016        # onto the list, then pop them off to extend the paths. We prime it with the starting
2017        # point. Note that we will work hard to insure that the last item on a path in the
2018        # to-do list is always an entity.
2019        my @todoList = ([$entityName]);
2020        while (@todoList) {
2021            # Get the current path.
2022            my $current = pop @todoList;
2023            # Copy it into a list.
2024            my @stackedPath = @{$current};
2025            # Pull off the last item on the path. It will always be an entity.
2026            my $myEntityName = pop @stackedPath;
2027            # Add it to the alreadyFound list.
2028            $alreadyFound{$myEntityName} = 1;
2029            # Figure out if we need to delete this entity.
2030            if ($myEntityName ne $entityName || ! $options{keepRoot}) {
2031                # Get the entity data.
2032                my $entityData = $self->_GetStructure($myEntityName);
2033                # Loop through the entity's relations. A DELETE command will be needed for each of them.
2034                my $relations = $entityData->{Relations};
2035                for my $relation (keys %{$relations}) {
2036                    my @augmentedList = (@stackedPath, $relation);
2037                    push @fromPathList, \@augmentedList;
2038                }
2039            }
2040            # Now we need to look for relationships connected to this entity.
2041            my $relationshipList = $self->{_metaData}->{Relationships};
2042            for my $relationshipName (keys %{$relationshipList}) {
2043                my $relationship = $relationshipList->{$relationshipName};
2044                # Check the FROM field. We're only interested if it's us.
2045                if ($relationship->{from} eq $myEntityName) {
2046                    # Add the path to this relationship.
2047                    my @augmentedList = (@stackedPath, $myEntityName, $relationshipName);
2048                    push @fromPathList, \@augmentedList;
2049                    # Check the arity. If it's MM we're done. If it's 1M
2050                    # and the target hasn't been seen yet, we want to
2051                    # stack the entity for future processing.
2052                    if ($relationship->{arity} eq '1M') {
2053                        my $toEntity = $relationship->{to};
2054                        if (! exists $alreadyFound{$toEntity}) {
2055                            # Here we have a new entity that's dependent on
2056                            # the current entity, so we need to stack it.
2057                            my @stackList = (@augmentedList, $toEntity);
2058                            push @fromPathList, \@stackList;
2059                        } else {
2060                            Trace("$toEntity ignored because it occurred previously.") if T(4);
2061                        }
2062                    }
2063                }
2064                # Now check the TO field. In this case only the relationship needs
2065                # deletion.
2066                if ($relationship->{to} eq $myEntityName) {
2067                    my @augmentedList = (@stackedPath, $myEntityName, $relationshipName);
2068                    push @toPathList, \@augmentedList;
2069                }
2070            }
2071        }
2072        # Create the first qualifier for the WHERE clause. This selects the
2073        # keys of the primary entity records to be deleted. When we're deleting
2074        # from a dependent table, we construct a join path from the first qualifier
2075        # to the table containing the dependent records to delete.
2076        my $qualifier = ($objectID =~ /%/ ? "LIKE ?" : "= ?");
2077        # We need to make two passes. The first is through the to-list, and
2078        # the second through the from-list. The from-list is second because
2079        # the to-list may need to pass through some of the entities the
2080        # from-list would delete.
2081        my %stackList = ( from_link => \@fromPathList, to_link => \@toPathList );
2082        # Now it's time to do the deletes. We do it in two passes.
2083        for my $keyName ('to_link', 'from_link') {
2084            # Get the list for this key.
2085            my @pathList = @{$stackList{$keyName}};
2086            Trace(scalar(@pathList) . " entries in path list for $keyName.") if T(3);
2087            # Loop through this list.
2088            while (my $path = pop @pathList) {
2089                # Get the table whose rows are to be deleted.
2090                my @pathTables = @{$path};
2091                # Start the DELETE statement. We need to call DBKernel because the
2092                # syntax of a DELETE-USING varies among DBMSs.
2093                my $target = $pathTables[$#pathTables];
2094                my $stmt = $db->SetUsing(@pathTables);
2095                # Now start the WHERE. The first thing is the ID field from the starting table. That
2096                # starting table will either be the entity relation or one of the entity's
2097                # sub-relations.
2098                $stmt .= " WHERE $pathTables[0].id $qualifier";
2099                # Now we run through the remaining entities in the path, connecting them up.
2100                for (my $i = 1; $i <= $#pathTables; $i += 2) {
2101                    # Connect the current relationship to the preceding entity.
2102                    my ($entity, $rel) = @pathTables[$i-1,$i];
2103                    # The style of connection depends on the direction of the relationship.
2104                    $stmt .= " AND $entity.id = $rel.$keyName";
2105                    if ($i + 1 <= $#pathTables) {
2106                        # Here there's a next entity, so connect that to the relationship's
2107                        # to-link.
2108                        my $entity2 = $pathTables[$i+1];
2109                        $stmt .= " AND $rel.to_link = $entity2.id";
2110                    }
2111                }
2112                # Now we have our desired DELETE statement.
2113                if ($options{testMode}) {
2114                    # Here the user wants to trace without executing.
2115                    Trace($stmt) if T(0);
2116                } else {
2117                    # Here we can delete. Note that the SQL method dies with a confession
2118                    # if an error occurs, so we just go ahead and do it.
2119                    Trace("Executing delete from $target using '$objectID'.") if T(3);
2120                    my $rv = $db->SQL($stmt, 0, $objectID);
2121                    # Accumulate the statistics for this delete. The only rows deleted
2122                    # are from the target table, so we use its name to record the
2123                    # statistic.
2124                    $retVal->Add($target, $rv);
2125                }
2126            }
2127        }
2128        # Return the result.
2129        return $retVal;
2130    }
2131    
2132    =head3 Disconnect
2133    
2134        $erdb->Disconnect($relationshipName, $originEntityName, $originEntityID);
2135    
2136    Disconnect an entity instance from all the objects to which it is related. This
2137    will delete each relationship instance that connects to the specified entity.
2138    
2139    =over 4
2140    
2141    =item relationshipName
2142    
2143    Name of the relationship whose instances are to be deleted.
2144    
2145    =item originEntityName
2146    
2147    Name of the entity that is to be disconnected.
2148    
2149    =item originEntityID
2150    
2151    ID of the entity that is to be disconnected.
2152    
2153    =back
2154    
2155    =cut
2156    
2157    sub Disconnect {
2158        # Get the parameters.
2159        my ($self, $relationshipName, $originEntityName, $originEntityID) = @_;
2160        # Get the relationship descriptor.
2161        my $structure = $self->_GetStructure($relationshipName);
2162        # Insure we have a relationship.
2163        if (! exists $structure->{from}) {
2164            Confess("$relationshipName is not a relationship in the database.");
2165        } else {
2166            # Get the database handle.
2167            my $dbh = $self->{_dbh};
2168            # We'll set this value to 1 if we find our entity.
2169            my $found = 0;
2170            # Loop through the ends of the relationship.
2171            for my $dir ('from', 'to') {
2172                if ($structure->{$dir} eq $originEntityName) {
2173                    $found = 1;
2174                    # Here we want to delete all relationship instances on this side of the
2175                    # entity instance.
2176                    Trace("Disconnecting in $dir direction with ID \"$originEntityID\".");
2177                    # We do this delete in batches to keep it from dragging down the
2178                    # server.
2179                    my $limitClause = ($FIG_Config::delete_limit ? "LIMIT $FIG_Config::delete_limit" : "");
2180                    my $done = 0;
2181                    while (! $done) {
2182                        # Do the delete.
2183                        my $rows = $dbh->SQL("DELETE FROM $relationshipName WHERE ${dir}_link = ? $limitClause", 0, $originEntityID);
2184                        # See if we're done. We're done if no rows were found or the delete is unlimited.
2185                        $done = ($rows == 0 || ! $limitClause);
2186                    }
2187                }
2188            }
2189            # Insure we found the entity on at least one end.
2190            if (! $found) {
2191                Confess("Entity \"$originEntityName\" does not use $relationshipName.");
2192            }
2193        }
2194    }
2195    
2196    =head3 DeleteRow
2197    
2198        $erdb->DeleteRow($relationshipName, $fromLink, $toLink, \%values);
2199    
2200    Delete a row from a relationship. In most cases, only the from-link and to-link are
2201    needed; however, for relationships with intersection data values can be specified
2202    for the other fields using a hash.
2203    
2204    =over 4
2205    
2206    =item relationshipName
2207    
2208    Name of the relationship from which the row is to be deleted.
2209    
2210    =item fromLink
2211    
2212    ID of the entity instance in the From direction.
2213    
2214    =item toLink
2215    
2216    ID of the entity instance in the To direction.
2217    
2218    =item values
2219    
2220    Reference to a hash of other values to be used for filtering the delete.
2221    
2222    =back
2223    
2224    =cut
2225    
2226    sub DeleteRow {
2227        # Get the parameters.
2228        my ($self, $relationshipName, $fromLink, $toLink, $values) = @_;
2229        # Create a hash of all the filter information.
2230        my %filter = ('from-link' => $fromLink, 'to-link' => $toLink);
2231        if (defined $values) {
2232            for my $key (keys %{$values}) {
2233                $filter{$key} = $values->{$key};
2234            }
2235        }
2236        # Build an SQL statement out of the hash.
2237        my @filters = ();
2238        my @parms = ();
2239        for my $key (keys %filter) {
2240            push @filters, _FixName($key) . " = ?";
2241            push @parms, $filter{$key};
2242        }
2243        Trace("Parms for delete row are " . join(", ", map { "\"$_\"" } @parms) . ".") if T(SQL => 4);
2244        my $command = "DELETE FROM $relationshipName WHERE " .
2245                      join(" AND ", @filters);
2246        # Execute it.
2247        my $dbh = $self->{_dbh};
2248        $dbh->SQL($command, undef, @parms);
2249    }
2250    
2251    =head3 DeleteLike
2252    
2253        my $deleteCount = $erdb->DeleteLike($relName, $filter, \@parms);
2254    
2255    Delete all the relationship rows that satisfy a particular filter condition. Unlike a normal
2256    filter, only fields from the relationship itself can be used.
2257    
2258    =over 4
2259    
2260    =item relName
2261    
2262    Name of the relationship whose records are to be deleted.
2263    
2264    =item filter
2265    
2266    A filter clause (L</Get>-style) for the delete query.
2267    
2268    =item parms
2269    
2270    Reference to a list of parameters for the filter clause.
2271    
2272    =item RETURN
2273    
2274    Returns a count of the number of rows deleted.
2275    
2276    =back
2277    
2278    =cut
2279    
2280    sub DeleteLike {
2281        # Get the parameters.
2282        my ($self, $objectName, $filter, $parms) = @_;
2283        # Declare the return variable.
2284        my $retVal;
2285        # Insure the parms argument is an array reference if the caller left it off.
2286        if (! defined($parms)) {
2287            $parms = [];
2288        }
2289        # Insure we have a relationship. The main reason for this is if we delete an entity
2290        # instance we have to yank out a bunch of other stuff with it.
2291        if ($self->IsEntity($objectName)) {
2292            Confess("Cannot use DeleteLike on $objectName, because it is not a relationship.");
2293        } else {
2294            # Create the SQL command suffix to get the desierd records.
2295            my ($suffix) = $self->_SetupSQL([$objectName], $filter);
2296            # Convert it to a DELETE command.
2297            my $command = "DELETE $suffix";
2298            # Execute the command.
2299            my $dbh = $self->{_dbh};
2300            my $result = $dbh->SQL($command, 0, @{$parms});
2301            # Check the results. Note we convert the "0D0" result to a real zero.
2302            # A failure causes an abnormal termination, so the caller isn't going to
2303            # worry about it.
2304            if (! defined $result) {
2305                Confess("Error deleting from $objectName: " . $dbh->errstr());
2306            } elsif ($result == 0) {
2307                $retVal = 0;
2308            } else {
2309                $retVal = $result;
2310            }
2311        }
2312        # Return the result count.
2313        return $retVal;
2314    }
2315    
2316    =head3 SortNeeded
2317    
2318        my $parms = $erdb->SortNeeded($relationName);
2319    
2320    Return the pipe command for the sort that should be applied to the specified
2321    relation when creating the load file.
2322    
2323    For example, if the load file should be sorted ascending by the first
2324    field, this method would return
2325    
2326        sort -k1 -t"\t"
2327    
2328    If the first field is numeric, the method would return
2329    
2330        sort -k1n -t"\t"
2331    
2332    Unfortunately, due to a bug in the C<sort> command, we cannot eliminate duplicate
2333    keys using a sort.
2334    
2335    =over 4
2336    
2337    =item relationName
2338    
2339    Name of the relation to be examined.
2340    
2341    =item
2342    
2343    Returns the sort command to use for sorting the relation, suitable for piping.
2344    
2345    =back
2346    
2347    =cut
2348    #: Return Type $;
2349    sub SortNeeded {
2350        # Get the parameters.
2351        my ($self, $relationName) = @_;
2352        # Declare a descriptor to hold the names of the key fields.
2353        my @keyNames = ();
2354        # Get the relation structure.
2355        my $relationData = $self->_FindRelation($relationName);
2356        # Find out if the relation is a primary entity relation,
2357        # a relationship relation, or a secondary entity relation.
2358        my $entityTable = $self->{_metaData}->{Entities};
2359        my $relationshipTable = $self->{_metaData}->{Relationships};
2360        if (exists $entityTable->{$relationName}) {
2361            # Here we have a primary entity relation.
2362            push @keyNames, "id";
2363        } elsif (exists $relationshipTable->{$relationName}) {
2364            # Here we have a relationship. We sort using the FROM index.
2365            my $relationshipData = $relationshipTable->{$relationName};
2366            my $index = $relationData->{Indexes}->{idxFrom};
2367            push @keyNames, @{$index->{IndexFields}};
2368        } else {
2369            # Here we have a secondary entity relation, so we have a sort on the ID field.
2370            push @keyNames, "id";
2371        }
2372        # Now we parse the key names into sort parameters. First, we prime the return
2373        # string.
2374        my $retVal = "sort -S 1G -T\"$FIG_Config::temp\" -t\"\t\" ";
2375        # Get the relation's field list.
2376        my @fields = @{$relationData->{Fields}};
2377        # Loop through the keys.
2378        for my $keyData (@keyNames) {
2379            # Get the key and the ordering.
2380            my ($keyName, $ordering);
2381            if ($keyData =~ /^([^ ]+) DESC/) {
2382                ($keyName, $ordering) = ($1, "descending");
2383            } else {
2384                ($keyName, $ordering) = ($keyData, "ascending");
2385            }
2386            # Find the key's position and type.
2387            my $fieldSpec;
2388            for (my $i = 0; $i <= $#fields && ! $fieldSpec; $i++) {
2389                my $thisField = $fields[$i];
2390                if ($thisField->{name} eq $keyName) {
2391                    # Get the sort modifier for this field type. The modifier
2392                    # decides whether we're using a character, numeric, or
2393                    # floating-point sort.
2394                    my $modifier = $TypeTable{$thisField->{type}}->{sort};
2395                    # If the index is descending for this field, denote we want
2396                    # to reverse the sort order on this field.
2397                    if ($ordering eq 'descending') {
2398                        $modifier .= "r";
2399                    }
2400                    # Store the position and modifier into the field spec, which
2401                    # will stop the inner loop. Note that the field number is
2402                    # 1-based in the sort command, so we have to increment the
2403                    # index.
2404                    my $realI = $i + 1;
2405                    $fieldSpec = "$realI,$realI$modifier";
2406                }
2407            }
2408            # Add this field to the sort command.
2409            $retVal .= " -k$fieldSpec";
2410        }
2411        # Return the result.
2412        return $retVal;
2413    }
2414    
2415    =head3 GetList
2416    
2417        my @dbObjects = $erdb->GetList(\@objectNames, $filterClause, \@params);
2418    
2419    Return a list of object descriptors for the specified objects as determined by the
2420    specified filter clause.
2421    
2422    This method is essentially the same as L</Get> except it returns a list of objects rather
2423    than a query object that can be used to get the results one record at a time.
2424    
2425    =over 4
2426    
2427    =item objectNames
2428    
2429    List containing the names of the entity and relationship objects to be retrieved.
2430    
2431    =item filterClause
2432    
2433    WHERE clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can
2434    be parameterized with parameter markers (C<?>). Each field used in the WHERE clause must be
2435    specified in the standard form B<I<objectName>(I<fieldName>)>. Any parameters specified
2436    in the filter clause should be added to the parameter list as additional parameters. The
2437    fields in a filter clause can come from primary entity relations, relationship relations,
2438    or secondary entity relations; however, all of the entities and relationships involved must
2439    be included in the list of object names.
2440    
2441    The filter clause can also specify a sort order. To do this, simply follow the filter string
2442    with an ORDER BY clause. For example, the following filter string gets all genomes for a
2443    particular genus and sorts them by species name.
2444    
2445        "Genome(genus) = ? ORDER BY Genome(species)"
2446    
2447    The rules for field references in a sort order are the same as those for field references in the
2448    filter clause in general; however, odd things may happen if a sort field is from a secondary
2449    relation.
2450    
2451    =item params
2452    
2453    Reference to a list of parameter values to be substituted into the filter clause.
2454    
2455    =item RETURN
2456    
2457    Returns a list of B<ERDBObject>s that satisfy the query conditions.
2458    
2459    =back
2460    
2461    =cut
2462    #: Return Type @%
2463    sub GetList {
2464        # Get the parameters.
2465        my ($self, $objectNames, $filterClause, $params) = @_;
2466        # Declare the return variable.
2467        my @retVal = ();
2468        # Perform the query.
2469        my $query = $self->Get($objectNames, $filterClause, $params);
2470        # Loop through the results.
2471        while (my $object = $query->Fetch) {
2472            push @retVal, $object;
2473        }
2474        # Return the result.
2475        return @retVal;
2476    }
2477    
2478    =head3 GetCount
2479    
2480        my $count = $erdb->GetCount(\@objectNames, $filter, \@params);
2481    
2482    Return the number of rows found by a specified query. This method would
2483    normally be used to count the records in a single table. For example, in a
2484    genetics database
2485    
2486        my $count = $erdb->GetCount(['Genome'], 'Genome(genus-species) LIKE ?', ['homo %']);
2487    
2488    would return the number of genomes for the genus I<homo>. It is conceivable, however,
2489    to use it to return records based on a join. For example,
2490    
2491        my $count = $erdb->GetCount(['HasFeature', 'Genome'], 'Genome(genus-species) LIKE ?',
2492                                    ['homo %']);
2493    
2494    would return the number of features for genomes in the genus I<homo>. Note that
2495    only the rows from the first table are counted. If the above command were
2496    
2497        my $count = $erdb->GetCount(['Genome', 'Feature'], 'Genome(genus-species) LIKE ?',
2498                                    ['homo %']);
2499    
2500    it would return the number of genomes, not the number of genome/feature pairs.
2501    
2502    =over 4
2503    
2504    =item objectNames
2505    
2506    Reference to a list of the objects (entities and relationships) included in the
2507    query.
2508    
2509    =item filter
2510    
2511    A filter clause for restricting the query. The rules are the same as for the L</Get>
2512    method.
2513    
2514    =item params
2515    
2516    Reference to a list of the parameter values to be substituted for the parameter marks
2517    in the filter.
2518    
2519    =item RETURN
2520    
2521    Returns a count of the number of records in the first table that would satisfy
2522    the query.
2523    
2524    =back
2525    
2526    =cut
2527    
2528    sub GetCount {
2529        # Get the parameters.
2530        my ($self, $objectNames, $filter, $params) = @_;
2531        # Insure the params argument is an array reference if the caller left it off.
2532        if (! defined($params)) {
2533            $params = [];
2534        }
2535        # Declare the return variable.
2536        my $retVal;
2537        # Find out if we're counting an entity or a relationship.
2538        my $countedField;
2539        if ($self->IsEntity($objectNames->[0])) {
2540            $countedField = "id";
2541        } else {
2542            # For a relationship we count the to-link because it's usually more
2543            # numerous. Note we're automatically converting to the SQL form
2544            # of the field name (to_link vs. to-link).
2545            $countedField = "to_link";
2546        }
2547        # Create the SQL command suffix to get the desired records.
2548        my ($suffix, $mappedNameListRef, $mappedNameHashRef) = $self->_SetupSQL($objectNames,
2549                                                                                $filter);
2550        # Prefix it with text telling it we want a record count.
2551        my $firstObject = $mappedNameListRef->[0];
2552        my $command = "SELECT COUNT($firstObject.$countedField) $suffix";
2553        # Prepare and execute the command.
2554        my $sth = $self->_GetStatementHandle($command, $params);
2555        # Get the count value.
2556        ($retVal) = $sth->fetchrow_array();
2557        # Check for a problem.
2558        if (! defined($retVal)) {
2559            if ($sth->err) {
2560                # Here we had an SQL error.
2561                Confess("Error retrieving row count: " . $sth->errstr());
2562            } else {
2563                # Here we have no result.
2564                Confess("No result attempting to retrieve row count.");
2565            }
2566        }
2567        # Return the result.
2568        return $retVal;
2569    }
2570    
2571    =head3 ComputeObjectSentence
2572    
2573        my $sentence = $erdb->ComputeObjectSentence($objectName);
2574    
2575    Check an object name, and if it is a relationship convert it to a relationship sentence.
2576    
2577    =over 4
2578    
2579    =item objectName
2580    
2581    Name of the entity or relationship.
2582    
2583    =item RETURN
2584    
2585    Returns a string containing the entity name or a relationship sentence.
2586    
2587    =back
2588    
2589    =cut
2590    
2591    sub ComputeObjectSentence {
2592        # Get the parameters.
2593        my ($self, $objectName) = @_;
2594        # Set the default return value.
2595        my $retVal = $objectName;
2596        # Look for the object as a relationship.
2597        my $relTable = $self->{_metaData}->{Relationships};
2598        if (exists $relTable->{$objectName}) {
2599            # Get the relationship sentence.
2600            $retVal = _ComputeRelationshipSentence($objectName, $relTable->{$objectName});
2601        }
2602        # Return the result.
2603        return $retVal;
2604    }
2605    
2606    =head3 DumpRelations
2607    
2608        $erdb->DumpRelations($outputDirectory);
2609    
2610    Write the contents of all the relations to tab-delimited files in the specified directory.
2611    Each file will have the same name as the relation dumped, with an extension of DTX.
2612    
2613    =over 4
2614    
2615    =item outputDirectory
2616    
2617    Name of the directory into which the relation files should be dumped.
2618    
2619    =back
2620    
2621    =cut
2622    
2623    sub DumpRelations {
2624        # Get the parameters.
2625        my ($self, $outputDirectory) = @_;
2626        # Now we need to run through all the relations. First, we loop through the entities.
2627        my $metaData = $self->{_metaData};
2628        my $entities = $metaData->{Entities};
2629        for my $entityName (keys %{$entities}) {
2630            my $entityStructure = $entities->{$entityName};
2631            # Get the entity's relations.
2632            my $relationList = $entityStructure->{Relations};
2633            # Loop through the relations, dumping them.
2634            for my $relationName (keys %{$relationList}) {
2635                my $relation = $relationList->{$relationName};
2636                $self->_DumpRelation($outputDirectory, $relationName, $relation);
2637            }
2638        }
2639        # Next, we loop through the relationships.
2640        my $relationships = $metaData->{Relationships};
2641        for my $relationshipName (keys %{$relationships}) {
2642            my $relationshipStructure = $relationships->{$relationshipName};
2643            # Dump this relationship's relation.
2644            $self->_DumpRelation($outputDirectory, $relationshipName, $relationshipStructure->{Relations}->{$relationshipName});
2645        }
2646    }
2647    
2648    =head3 InsertValue
2649    
2650        $erdb->InsertValue($entityID, $fieldName, $value);
2651    
2652    This method will insert a new value into the database. The value must be one
2653    associated with a secondary relation, since primary values cannot be inserted:
2654    they occur exactly once. Secondary values, on the other hand, can be missing
2655    or multiply-occurring.
2656    
2657    =over 4
2658    
2659    =item entityID
2660    
2661    ID of the object that is to receive the new value.
2662    
2663    =item fieldName
2664    
2665    Field name for the new value-- this includes the entity name, since
2666    field names are of the format I<objectName>C<(>I<fieldName>C<)>.
2667    
2668    =item value
2669    
2670    New value to be put in the field.
2671    
2672    =back
2673    
2674    =cut
2675    
2676    sub InsertValue {
2677        # Get the parameters.
2678        my ($self, $entityID, $fieldName, $value) = @_;
2679        # Parse the entity name and the real field name.
2680        if ($fieldName =~ /^([^(]+)\(([^)]+)\)/) {
2681            my $entityName = $1;
2682            my $fieldTitle = $2;
2683            # Get its descriptor.
2684            if (!$self->IsEntity($entityName)) {
2685                Confess("$entityName is not a valid entity.");
2686            } else {
2687                my $entityData = $self->{_metaData}->{Entities}->{$entityName};
2688                # Find the relation containing this field.
2689                my $fieldHash = $entityData->{Fields};
2690                if (! exists $fieldHash->{$fieldTitle}) {
2691                    Confess("$fieldTitle not found in $entityName.");
2692                } else {
2693                    my $relation = $fieldHash->{$fieldTitle}->{relation};
2694                    if ($relation eq $entityName) {
2695                        Confess("Cannot do InsertValue on primary field $fieldTitle of $entityName.");
2696                    } else {
2697                        # Now we can create an INSERT statement.
2698                        my $dbh = $self->{_dbh};
2699                        my $fixedName = _FixName($fieldTitle);
2700                        my $statement = "INSERT INTO $relation (id, $fixedName) VALUES(?, ?)";
2701                        # Execute the command.
2702                        $dbh->SQL($statement, 0, $entityID, $value);
2703                    }
2704                }
2705            }
2706        } else {
2707            Confess("$fieldName is not a valid field name.");
2708        }
2709    }
2710    
2711    =head3 InsertObject
2712    
2713        $erdb->InsertObject($objectType, \%fieldHash);
2714    
2715    Insert an object into the database. The object is defined by a type name and then a hash
2716    of field names to values. Field values in the primary relation are represented by scalars.
2717    (Note that for relationships, the primary relation is the B<only> relation.)
2718    Field values for the other relations comprising the entity are always list references. For
2719    example, the following line inserts an inactive PEG feature named C<fig|188.1.peg.1> with aliases
2720    C<ZP_00210270.1> and C<gi|46206278>.
2721    
2722        $erdb->InsertObject('Feature', { id => 'fig|188.1.peg.1', active => 0, feature-type => 'peg', alias => ['ZP_00210270.1', 'gi|46206278']});
2723    
2724    The next statement inserts a C<HasProperty> relationship between feature C<fig|158879.1.peg.1> and
2725    property C<4> with an evidence URL of C<http://seedu.uchicago.edu/query.cgi?article_id=142>.
2726    
2727        $erdb->InsertObject('HasProperty', { 'from-link' => 'fig|158879.1.peg.1', 'to-link' => 4, evidence => 'http://seedu.uchicago.edu/query.cgi?article_id=142'});
2728    
2729    =over 4
2730    
2731    =item newObjectType
2732    
2733    Type name of the object to insert.
2734    
2735    =item fieldHash
2736    
2737    Hash of field names to values.
2738    
2739    =back
2740    
2741    =cut
2742    
2743    sub InsertObject {
2744        # Get the parameters.
2745        my ($self, $newObjectType, $fieldHash) = @_;
2746        # Denote that so far we appear successful.
2747        my $retVal = 1;
2748        # Get the database handle.
2749        my $dbh = $self->{_dbh};
2750        # Get the relation list.
2751        my $relationTable = $self->_GetRelationTable($newObjectType);
2752        # Loop through the relations. We'll build insert statements for each one. If a relation is
2753        # secondary, we may end up generating multiple insert statements. If an error occurs, we
2754        # stop the loop.
2755        my @relationList = keys %{$relationTable};
2756        for (my $i = 0; $retVal && $i <= $#relationList; $i++) {
2757            my $relationName = $relationList[$i];
2758            my $relationDefinition = $relationTable->{$relationName};
2759            # Get the relation's fields. For each field we will collect a value in the corresponding
2760            # position of the @valueList array. If one of the fields is missing, we will add it to the
2761            # @missing list.
2762            my @fieldList = @{$relationDefinition->{Fields}};
2763            my @fieldNameList = ();
2764            my @valueList = ();
2765            my @missing = ();
2766            my $recordCount = 1;
2767            for my $fieldDescriptor (@fieldList) {
2768                # Get the field name and save it. Note we need to fix it up so the hyphens
2769                # are converted to underscores.
2770                my $fieldName = $fieldDescriptor->{name};
2771                push @fieldNameList, _FixName($fieldName);
2772                # Look for the named field in the incoming structure. Note that we are looking
2773                # for the real field name, not the fixed-up one!
2774                if (exists $fieldHash->{$fieldName}) {
2775                    # Here we found the field. Stash it in the value list.
2776                    my $value = $fieldHash->{$fieldName};
2777                    push @valueList, $value;
2778                    # If the value is a list, we may need to increment the record count.
2779                    if (ref $value eq "ARRAY") {
2780                        my $thisCount = @{$value};
2781                        if ($recordCount == 1) {
2782                            # Here we have our first list, so we save its count.
2783                            $recordCount = $thisCount;
2784                        } elsif ($recordCount != $thisCount) {
2785                            # Here we have a second list, so its length has to match the
2786                            # previous lists.
2787                            Trace("Field $value in new $newObjectType object has an invalid list length $thisCount. Expected $recordCount.") if T(0);
2788                            $retVal = 0;
2789                        }
2790                    }
2791                } else {
2792                    # Here the field is not present. Flag it as missing.
2793                    push @missing, $fieldName;
2794                }
2795            }
2796            # Only proceed if there are no missing fields.
2797            if (@missing > 0) {
2798                Trace("Relation $relationName for $newObjectType skipped due to missing fields: " .
2799                    join(' ', @missing)) if T(1);
2800            } else {
2801                # Build the INSERT statement.
2802                my $statement = "INSERT INTO $relationName (" . join (', ', @fieldNameList) .
2803                    ") VALUES (";
2804                # Create a marker list of the proper size and put it in the statement.
2805                my @markers = ();
2806                while (@markers < @fieldNameList) { push @markers, '?'; }
2807                $statement .= join(', ', @markers) . ")";
2808                # We have the insert statement, so prepare it.
2809                my $sth = $dbh->prepare_command($statement);
2810                Trace("Insert statement prepared: $statement") if T(3);
2811                # Now we loop through the values. If a value is scalar, we use it unmodified. If it's
2812                # a list, we use the current element. The values are stored in the @parameterList array.
2813                my $done = 0;
2814                for (my $i = 0; $i < $recordCount; $i++) {
2815                    # Clear the parameter list array.
2816                    my @parameterList = ();
2817                    # Loop through the values.
2818                    for my $value (@valueList) {
2819                        # Check to see if this is a scalar value.
2820                        if (ref $value eq "ARRAY") {
2821                            # Here we have a list value. Pull the current entry.
2822                            push @parameterList, $value->[$i];
2823                        } else {
2824                            # Here we have a scalar value. Use it unmodified.
2825                            push @parameterList, $value;
2826                        }
2827                    }
2828                    # Execute the INSERT statement with the specified parameter list.
2829                    $retVal = $sth->execute(@parameterList);
2830                    if (!$retVal) {
2831                        my $errorString = $sth->errstr();
2832                        Confess("Error inserting into $relationName: $errorString");
2833                    } else {
2834                        Trace("Insert successful using $parameterList[0].") if T(3);
2835                    }
2836                }
2837            }
2838        }
2839        # Return a 1 for backward compatability.
2840        return 1;
2841    }
2842    
2843    =head3 UpdateEntity
2844    
2845        $erdb->UpdateEntity($entityName, $id, \%fields);
2846    
2847    Update the values of an entity. This is an unprotected update, so it should only be
2848    done if the database resides on a database server.
2849    
2850    =over 4
2851    
2852    =item entityName
2853    
2854    Name of the entity to update. (This is the entity type.)
2855    
2856    =item id
2857    
2858    ID of the entity to update. If no entity exists with this ID, an error will be thrown.
2859    
2860    =item fields
2861    
2862    Reference to a hash mapping field names to their new values. All of the fields named
2863    must be in the entity's primary relation, and they cannot any of them be the ID field.
2864    
2865    =back
2866    
2867    =cut
2868    
2869    sub UpdateEntity {
2870        # Get the parameters.
2871        my ($self, $entityName, $id, $fields) = @_;
2872        # Get a list of the field names being updated.
2873        my @fieldList = keys %{$fields};
2874        # Verify that the fields exist.
2875        my $checker = $self->GetFieldTable($entityName);
2876        for my $field (@fieldList) {
2877            if ($field eq 'id') {
2878                Confess("Cannot update the ID field for entity $entityName.");
2879            } elsif ($checker->{$field}->{relation} ne $entityName) {
2880                Confess("Cannot find $field in primary relation of $entityName.");
2881            }
2882        }
2883        # Build the SQL statement.
2884        my @sets = ();
2885        my @valueList = ();
2886        for my $field (@fieldList) {
2887            push @sets, _FixName($field) . " = ?";
2888            push @valueList, $fields->{$field};
2889        }
2890        my $command = "UPDATE $entityName SET " . join(", ", @sets) . " WHERE id = ?";
2891        # Add the ID to the list of binding values.
2892        push @valueList, $id;
2893        # Call SQL to do the work.
2894        my $rows = $self->{_dbh}->SQL($command, 0, @valueList);
2895        # Check for errors.
2896        if ($rows == 0) {
2897            Confess("Entity $id of type $entityName not found.");
2898        }
2899    }
2900    
2901    =head3 LoadTable
2902    
2903        my $results = $erdb->LoadTable($fileName, $relationName, %options);
2904    
2905    Load data from a tab-delimited file into a specified table, optionally re-creating the table
2906    first.
2907    
2908    =over 4
2909    
2910    =item fileName
2911    
2912    Name of the file from which the table data should be loaded.
2913    
2914    =item relationName
2915    
2916    Name of the relation to be loaded. This is the same as the table name.
2917    
2918    =item options
2919    
2920    A hash of load options.
2921    
2922    =item RETURN
2923    
2924    Returns a statistical object containing a list of the error messages.
2925    
2926    =back
2927    
2928    The permissible options are as follows.
2929    
2930    =over 4
2931    
2932    =item truncate
2933    
2934    If TRUE, then the table will be erased before loading.
2935    
2936    =item mode
2937    
2938    Mode in which the load should operate, either C<low_priority> or C<concurrent>.
2939    This option is only applicable to a MySQL database.
2940    
2941    =item partial
2942    
2943    If TRUE, then it is assumed that this is a partial load, and the table will not
2944    be analyzed and compacted at the end.
2945    
2946    =back
2947    
2948    =cut
2949    sub LoadTable {
2950        # Get the parameters.
2951        my ($self, $fileName, $relationName, %options) = @_;
2952        # Create the statistical return object.
2953        my $retVal = _GetLoadStats();
2954        # Trace the fact of the load.
2955        Trace("Loading table $relationName from $fileName") if T(2);
2956        # Get the database handle.
2957        my $dbh = $self->{_dbh};
2958        # Get the input file size.
2959        my $fileSize = -s $fileName;
2960        # Get the relation data.
2961        my $relation = $self->_FindRelation($relationName);
2962        # Check the truncation flag.
2963        if ($options{truncate}) {
2964            Trace("Creating table $relationName") if T(2);
2965            # Compute the row count estimate. We take the size of the load file,
2966            # divide it by the estimated row size, and then multiply by 2 to
2967            # leave extra room. We postulate a minimum row count of 1000 to
2968            # prevent problems with incoming empty load files.
2969            my $rowSize = $self->EstimateRowSize($relationName);
2970            my $estimate = $fileSize * 8 / $rowSize;
2971            if ($estimate < 1000) {
2972                $estimate = 1000;
2973            }
2974            # Re-create the table without its index.
2975            $self->CreateTable($relationName, 0, $estimate);
2976            # If this is a pre-index DBMS, create the index here.
2977            if ($dbh->{_preIndex}) {
2978                eval {
2979                    $self->CreateIndex($relationName);
2980                };
2981                if ($@) {
2982                    $retVal->AddMessage($@);
2983                }
2984            }
2985        }
2986        # Load the table.
2987        my $rv;
2988        eval {
2989            $rv = $dbh->load_table(file => $fileName, tbl => $relationName, style => $options{mode});
2990        };
2991        if (!defined $rv) {
2992            $retVal->AddMessage($@) if ($@);
2993            $retVal->AddMessage("Table load failed for $relationName using $fileName: " . $dbh->error_message);
2994            Trace("Table load failed for $relationName.") if T(1);
2995        } else {
2996            # Here we successfully loaded the table.
2997            $retVal->Add("tables");
2998            my $size = -s $fileName;
2999            Trace("$size bytes loaded into $relationName.") if T(2);
3000            $retVal->Add("bytes", $size);
3001            # If we're rebuilding, we need to create the table indexes.
3002            if ($options{truncate}) {
3003                # Indexes are created here for PostGres. For PostGres, indexes are
3004                # best built at the end. For MySQL, the reverse is true.
3005                if (! $dbh->{_preIndex}) {
3006                    eval {
3007                        $self->CreateIndex($relationName);
3008                    };
3009                    if ($@) {
3010                        $retVal->AddMessage($@);
3011                    }
3012                }
3013                # The full-text index (if any) is always built last, even for MySQL.
3014                # First we need to see if this table has a full-text index. Only
3015                # primary relations are allowed that privilege.
3016                Trace("Checking for full-text index on $relationName.") if T(2);
3017                if ($self->_IsPrimary($relationName)) {
3018                    $self->CreateSearchIndex($relationName);
3019                }
3020            }
3021        }
3022        # Analyze the table to improve performance.
3023        if (! $options{partial}) {
3024            Trace("Analyzing and compacting $relationName.") if T(3);
3025            $self->Analyze($relationName);
3026        }
3027        Trace("$relationName load completed.") if T(3);
3028        # Return the statistics.
3029        return $retVal;
3030    }
3031    
3032    =head3 Analyze
3033    
3034        $erdb->Analyze($tableName);
3035    
3036    Analyze and compact a table in the database. This is useful after a load
3037    to improve the performance of the indexes.
3038    
3039    =over 4
3040    
3041    =item tableName
3042    
3043    Name of the table to be analyzed and compacted.
3044    
3045    =back
3046    
3047    =cut
3048    
3049    sub Analyze {
3050        # Get the parameters.
3051        my ($self, $tableName) = @_;
3052        # Analyze the table.
3053        $self->{_dbh}->vacuum_it($tableName);
3054    }
3055    
3056    =head3 TruncateTable
3057    
3058        $erdb->TruncateTable($table);
3059    
3060    Delete all rows from a table quickly. This uses the built-in SQL
3061    C<TRUNCATE> statement, which effectively drops and re-creates a table
3062    with all its settings intact.
3063    
3064    =over 4
3065    
3066    =item table
3067    
3068    Name of the table to be cleared.
3069    
3070    =back
3071    
3072    =cut
3073    
3074    sub TruncateTable {
3075        # Get the parameters.
3076        my ($self, $table) = @_;
3077        # Get the database handle.
3078        my $dbh = $self->{_dbh};
3079        # Execute a truncation comment.
3080        $dbh->SQL("TRUNCATE TABLE $table");
3081    }
3082    
3083    
3084    =head3 CreateSearchIndex
3085    
3086        $erdb->CreateSearchIndex($objectName);
3087    
3088    Check for a full-text search index on the specified entity or relationship object, and
3089    if one is required, rebuild it.
3090    
3091    =over 4
3092    
3093    =item objectName
3094    
3095    Name of the entity or relationship to be indexed.
3096    
3097    =back
3098    
3099    =cut
3100    
3101    sub CreateSearchIndex {
3102        # Get the parameters.
3103        my ($self, $objectName) = @_;
3104        # Get the relation's entity/relationship structure.
3105        my $structure = $self->_GetStructure($objectName);
3106        # Get the database handle.
3107        my $dbh = $self->{_dbh};
3108        Trace("Checking for search fields in $objectName.") if T(3);
3109        # Check for a searchable fields list.
3110        if (exists $structure->{searchFields}) {
3111            # Here we know that we need to create a full-text search index.
3112            # Get an SQL-formatted field name list.
3113            my $fields = join(", ", _FixNames(@{$structure->{searchFields}}));
3114            # Create the index. If it already exists, it will be dropped.
3115            $dbh->create_index(tbl => $objectName, idx => "search_idx",
3116                               flds => $fields, kind => 'fulltext');
3117            Trace("Index created for $fields in $objectName.") if T(2);
3118        }
3119    }
3120    
3121    =head3 DropRelation
3122    
3123        $erdb->DropRelation($relationName);
3124    
3125    Physically drop a relation from the database.
3126    
3127    =over 4
3128    
3129    =item relationName
3130    
3131    Name of the relation to drop. If it does not exist, this method will have
3132    no effect.
3133    
3134    =back
3135    
3136    =cut
3137    
3138    sub DropRelation {
3139        # Get the parameters.
3140        my ($self, $relationName) = @_;
3141        # Get the database handle.
3142        my $dbh = $self->{_dbh};
3143        # Drop the relation. The method used here has no effect if the relation
3144        # does not exist.
3145        Trace("Invoking DB Kernel to drop $relationName.") if T(3);
3146        $dbh->drop_table(tbl => $relationName);
3147    }
3148    
3149    =head3 MatchSqlPattern
3150    
3151        my $matched = ERDB::MatchSqlPattern($value, $pattern);
3152    
3153    Determine whether or not a specified value matches an SQL pattern. An SQL
3154    pattern has two wild card characters: C<%> that matches multiple characters,
3155    and C<_> that matches a single character. These can be escaped using a
3156    backslash (C<\>). We pull this off by converting the SQL pattern to a
3157    PERL regular expression. As per SQL rules, the match is case-insensitive.
3158    
3159    =over 4
3160    
3161    =item value
3162    
3163    Value to be matched against the pattern. Note that an undefined or empty
3164    value will not match anything.
3165    
3166    =item pattern
3167    
3168    SQL pattern against which to match the value. An undefined or empty pattern will
3169    match everything.
3170    
3171    =item RETURN
3172    
3173    Returns TRUE if the value and pattern match, else FALSE.
3174    
3175    =back
3176    
3177    =cut
3178    
3179    sub MatchSqlPattern {
3180        # Get the parameters.
3181        my ($value, $pattern) = @_;
3182        # Declare the return variable.
3183        my $retVal;
3184        # Insure we have a pattern.
3185        if (! defined($pattern) || $pattern eq "") {
3186            $retVal = 1;
3187        } else {
3188            # Break the pattern into pieces around the wildcard characters. Because we
3189            # use parentheses in the split function's delimiter expression, we'll get
3190            # list elements for the delimiters as well as the rest of the string.
3191            my @pieces = split /([_%]|\\[_%])/, $pattern;
3192            # Check some fast special cases.
3193            if ($pattern eq '%') {
3194                # A null pattern matches everything.
3195                $retVal = 1;
3196            } elsif (@pieces == 1) {
3197                # No wildcards, so we have a literal comparison. Note we're case-insensitive.
3198                $retVal = (lc($value) eq lc($pattern));
3199            } elsif (@pieces == 2 && $pieces[1] eq '%') {
3200                # A wildcard at the end, so we have a substring match. This is also case-insensitive.
3201                $retVal = (lc(substr($value, 0, length($pieces[0]))) eq lc($pieces[0]));
3202            } else {
3203                # Okay, we have to do it the hard way. Convert each piece to a PERL pattern.
3204                my $realPattern = "";
3205                for my $piece (@pieces) {
3206                    # Determine the type of piece.
3207                    if ($piece eq "") {
3208                        # Empty pieces are ignored.
3209                    } elsif ($piece eq "%") {
3210                        # Here we have a multi-character wildcard. Note that it can match
3211                        # zero or more characters.
3212                        $realPattern .= ".*"
3213                    } elsif ($piece eq "_") {
3214                        # Here we have a single-character wildcard.
3215                        $realPattern .= ".";
3216                    } elsif ($piece eq "\\%" || $piece eq "\\_") {
3217                        # This is an escape sequence (which is a rare thing, actually).
3218                        $realPattern .= substr($piece, 1, 1);
3219                    } else {
3220                        # Here we have raw text.
3221                        $realPattern .= quotemeta($piece);
3222                    }
3223                }
3224                # Do the match.
3225                $retVal = ($value =~ /^$realPattern$/i ? 1 : 0);
3226            }
3227        }
3228        # Return the result.
3229        return $retVal;
3230    }
3231    
3232    =head3 GetEntity
3233    
3234        my $entityObject = $erdb->GetEntity($entityType, $ID);
3235    
3236    Return an object describing the entity instance with a specified ID.
3237    
3238    =over 4
3239    
3240    =item entityType
3241    
3242    Entity type name.
3243    
3244    =item ID
3245    
3246    ID of the desired entity.
3247    
3248    =item RETURN
3249    
3250    Returns a B<ERDBObject> representing the desired entity instance, or an undefined value if no
3251    instance is found with the specified key.
3252    
3253    =back
3254    
3255    =cut
3256    
3257    sub GetEntity {
3258        # Get the parameters.
3259        my ($self, $entityType, $ID) = @_;
3260        # Create a query.
3261        my $query = $self->Get([$entityType], "$entityType(id) = ?", [$ID]);
3262        # Get the first (and only) object.
3263        my $retVal = $query->Fetch();
3264        if (T(3)) {
3265            if ($retVal) {
3266                Trace("Entity $entityType \"$ID\" found.");
3267            } else {
3268                Trace("Entity $entityType \"$ID\" not found.");
3269            }
3270        }
3271        # Return the result.
3272        return $retVal;
3273    }
3274    
3275    =head3 GetChoices
3276    
3277        my @values = $erdb->GetChoices($entityName, $fieldName);
3278    
3279    Return a list of all the values for the specified field that are represented in the
3280    specified entity.
3281    
3282    Note that if the field is not indexed, then this will be a very slow operation.
3283    
3284    =over 4
3285    
3286    =item entityName
3287    
3288    Name of an entity in the database.
3289    
3290    =item fieldName
3291    
3292    Name of a field belonging to the entity. This is a raw field name without
3293    the standard parenthesized notation used in most calls.
3294    
3295    =item RETURN
3296    
3297    Returns a list of the distinct values for the specified field in the database.
3298    
3299    =back
3300    
3301    =cut
3302    
3303    sub GetChoices {
3304        # Get the parameters.
3305        my ($self, $entityName, $fieldName) = @_;
3306        # Declare the return variable.
3307        my @retVal;
3308        # Get the entity data structure.
3309        my $entityData = $self->_GetStructure($entityName);
3310        # Get the field.
3311        my $fieldHash = $entityData->{Fields};
3312        if (! exists $fieldHash->{$fieldName}) {
3313            Confess("$fieldName not found in $entityName.");
3314        } else {
3315            # Get the name of the relation containing the field.
3316            my $relation = $fieldHash->{$fieldName}->{relation};
3317            # Fix up the field name.
3318            my $realName = _FixName($fieldName);
3319            # Get the database handle.
3320            my $dbh = $self->{_dbh};
3321            # Query the database.
3322            my $results = $dbh->SQL("SELECT DISTINCT $realName FROM $relation");
3323            # Clean the results. They are stored as a list of lists, and we just want the one list.
3324            @retVal = sort map { $_->[0] } @{$results};
3325        }
3326        # Return the result.
3327        return @retVal;
3328    }
3329    
3330    =head3 GetEntityValues
3331    
3332        my @values = $erdb->GetEntityValues($entityType, $ID, \@fields);
3333    
3334    Return a list of values from a specified entity instance. If the entity instance
3335    does not exist, an empty list is returned.
3336    
3337    =over 4
3338    
3339    =item entityType
3340    
3341    Entity type name.
3342    
3343    =item ID
3344    
3345    ID of the desired entity.
3346    
3347    =item fields
3348    
3349    List of field names, each of the form I<objectName>C<(>I<fieldName>C<)>.
3350    
3351    =item RETURN
3352    
3353    Returns a flattened list of the values of the specified fields for the specified entity.
3354    
3355    =back
3356    
3357    =cut
3358    
3359    sub GetEntityValues {
3360        # Get the parameters.
3361        my ($self, $entityType, $ID, $fields) = @_;
3362        # Get the specified entity.
3363        my $entity = $self->GetEntity($entityType, $ID);
3364        # Declare the return list.
3365        my @retVal = ();
3366        # If we found the entity, push the values into the return list.
3367        if ($entity) {
3368            push @retVal, $entity->Values($fields);
3369        }
3370        # Return the result.
3371        return @retVal;
3372    }
3373    
3374    =head3 GetAll
3375    
3376        my @list = $erdb->GetAll(\@objectNames, $filterClause, \@parameters, \@fields, $count);
3377    
3378    Return a list of values taken from the objects returned by a query. The first three
3379    parameters correspond to the parameters of the L</Get> method. The final parameter is
3380    a list of the fields desired from each record found by the query. The field name
3381    syntax is the standard syntax used for fields in the B<ERDB> system--
3382    B<I<objectName>(I<fieldName>)>-- where I<objectName> is the name of the relevant entity
3383    or relationship and I<fieldName> is the name of the field.
3384    
3385    The list returned will be a list of lists. Each element of the list will contain
3386    the values returned for the fields specified in the fourth parameter. If one of the
3387    fields specified returns multiple values, they are flattened in with the rest. For
3388    example, the following call will return a list of the features in a particular
3389    spreadsheet cell, and each feature will be represented by a list containing the
3390    feature ID followed by all of its essentiality determinations.
3391    
3392        @query = $erdb->Get(['ContainsFeature', 'Feature'], "ContainsFeature(from-link) = ?", [$ssCellID], ['Feature(id)', 'Feature(essential)']);
3393    
3394    =over 4
3395    
3396    =item objectNames
3397    
3398    List containing the names of the entity and relationship objects to be retrieved.
3399    
3400    =item filterClause
3401    
3402    WHERE/ORDER BY clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can
3403    be parameterized with parameter markers (C<?>). Each field used must be specified in the standard form
3404    B<I<objectName>(I<fieldName>)>. Any parameters specified in the filter clause should be added to the
3405    parameter list as additional parameters. The fields in a filter clause can come from primary
3406    entity relations, relationship relations, or secondary entity relations; however, all of the
3407    entities and relationships involved must be included in the list of object names.
3408    
3409    =item parameterList
3410    
3411    List of the parameters to be substituted in for the parameters marks in the filter clause.
3412    
3413    =item fields
3414    
3415    List of the fields to be returned in each element of the list returned.
3416    
3417    =item count
3418    
3419    Maximum number of records to return. If omitted or 0, all available records will be returned.
3420    
3421    =item RETURN
3422    
3423    Returns a list of list references. Each element of the return list contains the values for the
3424    fields specified in the B<fields> parameter.
3425    
3426    =back
3427    
3428    =cut
3429    #: Return Type @@;
3430    sub GetAll {
3431        # Get the parameters.
3432        my ($self, $objectNames, $filterClause, $parameterList, $fields, $count) = @_;
3433        # Translate the parameters from a list reference to a list. If the parameter
3434        # list is a scalar we convert it into a singleton list.
3435        my @parmList = ();
3436        if (ref $parameterList eq "ARRAY") {
3437            Trace("GetAll parm list is an array.") if T(4);
3438            @parmList = @{$parameterList};
3439        } else {
3440            Trace("GetAll parm list is a scalar: $parameterList.") if T(4);
3441            push @parmList, $parameterList;
3442        }
3443        # Insure the counter has a value.
3444        if (!defined $count) {
3445            $count = 0;
3446        }
3447        # Add the row limit to the filter clause.
3448        if ($count > 0) {
3449            $filterClause .= " LIMIT $count";
3450        }
3451        # Create the query.
3452        my $query = $self->Get($objectNames, $filterClause, \@parmList);
3453        # Set up a counter of the number of records read.
3454        my $fetched = 0;
3455        # Loop through the records returned, extracting the fields. Note that if the
3456        # counter is non-zero, we stop when the number of records read hits the count.
3457        my @retVal = ();
3458        while (($count == 0 || $fetched < $count) && (my $row = $query->Fetch())) {
3459            my @rowData = $row->Values($fields);
3460            push @retVal, \@rowData;
3461            $fetched++;
3462        }
3463        Trace("$fetched rows returned in GetAll.") if T(SQL => 4);
3464        # Return the resulting list.
3465        return @retVal;
3466    }
3467    
3468    =head3 Exists
3469    
3470        my $found = $sprout->Exists($entityName, $entityID);
3471    
3472    Return TRUE if an entity exists, else FALSE.
3473    
3474    =over 4
3475    
3476    =item entityName
3477    
3478    Name of the entity type (e.g. C<Feature>) relevant to the existence check.
3479    
3480    =item entityID
3481    
3482    ID of the entity instance whose existence is to be checked.
3483    
3484    =item RETURN
3485    
3486    Returns TRUE if the entity instance exists, else FALSE.
3487    
3488    =back
3489    
3490    =cut
3491    #: Return Type $;
3492    sub Exists {
3493        # Get the parameters.
3494        my ($self, $entityName, $entityID) = @_;
3495        # Check for the entity instance.
3496        Trace("Checking existence of $entityName with ID=$entityID.") if T(4);
3497        my $testInstance = $self->GetEntity($entityName, $entityID);
3498        # Return an existence indicator.
3499        my $retVal = ($testInstance ? 1 : 0);
3500        return $retVal;
3501    }
3502    
3503    =head3 EstimateRowSize
3504    
3505        my $rowSize = $erdb->EstimateRowSize($relName);
3506    
3507    Estimate the row size of the specified relation. The estimated row size is computed by adding
3508    up the average length for each data type.
3509    
3510    =over 4
3511    
3512    =item relName
3513    
3514    Name of the relation whose estimated row size is desired.
3515    
3516    =item RETURN
3517    
3518    Returns an estimate of the row size for the specified relation.
3519    
3520    =back
3521    
3522    =cut
3523    #: Return Type $;
3524    sub EstimateRowSize {
3525        # Get the parameters.
3526        my ($self, $relName) = @_;
3527        # Declare the return variable.
3528        my $retVal = 0;
3529        # Find the relation descriptor.
3530        my $relation = $self->_FindRelation($relName);
3531        # Get the list of fields.
3532        for my $fieldData (@{$relation->{Fields}}) {
3533            # Get the field type and add its length.
3534            my $fieldLen = $TypeTable{$fieldData->{type}}->{avgLen};
3535            $retVal += $fieldLen;
3536        }
3537      # Return the result.      # Return the result.
3538      return @retVal;      return $retVal;
3539  }  }
3540    
3541  =head3 ComputeObjectSentence  =head3 GetFieldTable
3542    
3543  C<< my $sentence = $erdb->ComputeObjectSentence($objectName); >>      my $fieldHash = $self->GetFieldTable($objectnName);
3544    
3545  Check an object name, and if it is a relationship convert it to a relationship sentence.  Get the field structure for a specified entity or relationship.
3546    
3547  =over 4  =over 4
3548    
3549  =item objectName  =item objectName
3550    
3551  Name of the entity or relationship.  Name of the desired entity or relationship.
3552    
3553  =item RETURN  =item RETURN
3554    
3555  Returns a string containing the entity name or a relationship sentence.  The table containing the field descriptors for the specified object.
3556    
3557  =back  =back
3558    
3559  =cut  =cut
3560    
3561  sub ComputeObjectSentence {  sub GetFieldTable {
3562      # Get the parameters.      # Get the parameters.
3563      my ($self, $objectName) = @_;      my ($self, $objectName) = @_;
3564      # Set the default return value.      # Get the descriptor from the metadata.
3565      my $retVal = $objectName;      my $objectData = $self->_GetStructure($objectName);
3566      # Look for the object as a relationship.      # Return the object's field table.
3567      my $relTable = $self->{_metaData}->{Relationships};      return $objectData->{Fields};
3568      if (exists $relTable->{$objectName}) {  }
3569          # Get the relationship sentence.  
3570          $retVal = _ComputeRelationshipSentence($objectName, $relTable->{$objectName});  =head3 SplitKeywords
3571    
3572        my @keywords = ERDB::SplitKeywords($keywordString);
3573    
3574    This method returns a list of the positive keywords in the specified
3575    keyword string. All of the operators will have been stripped off,
3576    and if the keyword is preceded by a minus operator (C<->), it will
3577    not be in the list returned. The idea here is to get a list of the
3578    keywords the user wants to see. The list will be processed to remove
3579    duplicates.
3580    
3581    It is possible to create a string that confuses this method. For example
3582    
3583        frog toad -frog
3584    
3585    would return both C<frog> and C<toad>. If this is a problem we can deal
3586    with it later.
3587    
3588    =over 4
3589    
3590    =item keywordString
3591    
3592    The keyword string to be parsed.
3593    
3594    =item RETURN
3595    
3596    Returns a list of the words in the keyword string the user wants to
3597    see.
3598    
3599    =back
3600    
3601    =cut
3602    
3603    sub SplitKeywords {
3604        # Get the parameters.
3605        my ($keywordString) = @_;
3606        # Make a safety copy of the string. (This helps during debugging.)
3607        my $workString = $keywordString;
3608        # Convert operators we don't care about to spaces.
3609        $workString =~ tr/+"()<>/ /;
3610        # Split the rest of the string along space boundaries. Note that we
3611        # eliminate any words that are zero length or begin with a minus sign.
3612        my @wordList = grep { $_ && substr($_, 0, 1) ne "-" } split /\s+/, $workString;
3613        # Use a hash to remove duplicates.
3614        my %words = map { $_ => 1 } @wordList;
3615        # Return the result.
3616        return sort keys %words;
3617    }
3618    
3619    =head3 ValidateFieldName
3620    
3621        my $okFlag = ERDB::ValidateFieldName($fieldName);
3622    
3623    Return TRUE if the specified field name is valid, else FALSE. Valid field names must
3624    be hyphenated words subject to certain restrictions.
3625    
3626    =over 4
3627    
3628    =item fieldName
3629    
3630    Field name to be validated.
3631    
3632    =item RETURN
3633    
3634    Returns TRUE if the field name is valid, else FALSE.
3635    
3636    =back
3637    
3638    =cut
3639    
3640    sub ValidateFieldName {
3641        # Get the parameters.
3642        my ($fieldName) = @_;
3643        # Declare the return variable. The field name is valid until we hear
3644        # differently.
3645        my $retVal = 1;
3646        # Compute the maximum name length.
3647        my $maxLen = $TypeTable{'name-string'}->{maxLen};
3648        # Look for bad stuff in the name.
3649        if ($fieldName =~ /--/) {
3650            # Here we have a doubled minus sign.
3651            Trace("Field name $fieldName has a doubled hyphen.") if T(1);
3652            $retVal = 0;
3653        } elsif ($fieldName !~ /^[A-Za-z]/) {
3654            # Here the field name is missing the initial letter.
3655            Trace("Field name $fieldName does not begin with a letter.") if T(1);
3656            $retVal = 0;
3657        } elsif (length($fieldName) > $maxLen) {
3658            # Here the field name is too long.
3659            Trace("Maximum field name length is $maxLen. Field name must be truncated to " . substr($fieldName,0, $maxLen) . ".");
3660        } else {
3661            # Strip out the minus signs. Everything remaining must be a letter,
3662            # underscore, or digit.
3663            my $strippedName = $fieldName;
3664            $strippedName =~ s/-//g;
3665            if ($strippedName !~ /^(\w|\d)+$/) {
3666                Trace("Field name $fieldName contains illegal characters.") if T(1);
3667                $retVal = 0;
3668            }
3669      }      }
3670      # Return the result.      # Return the result.
3671      return $retVal;      return $retVal;
3672  }  }
3673    
3674  =head3 DumpRelations  =head3 ReadMetaXML
3675    
3676  C<< $erdb->DumpRelations($outputDirectory); >>      my $rawMetaData = ERDB::ReadDBD($fileName);
3677    
3678  Write the contents of all the relations to tab-delimited files in the specified directory.  This method reads a raw database definition XML file and returns it.
3679  Each file will have the same name as the relation dumped, with an extension of DTX.  Normally, the metadata used by the ERDB system has been processed and
3680    modified to make it easier to load and retrieve the data; however,
3681    this method can be used to get the data in its raw form.
3682    
3683  =over 4  =over 4
3684    
3685  =item outputDirectory  =item fileName
3686    
3687  Name of the directory into which the relation files should be dumped.  Name of the XML file to read.
3688    
3689    =item RETURN
3690    
3691    Returns a hash reference containing the raw XML data from the specified file.
3692    
3693  =back  =back
3694    
3695  =cut  =cut
3696    
3697  sub DumpRelations {  sub ReadMetaXML {
3698      # Get the parameters.      # Get the parameters.
3699      my ($self, $outputDirectory) = @_;      my ($fileName) = @_;
3700      # Now we need to run through all the relations. First, we loop through the entities.      # Read the XML.
3701      my $metaData = $self->{_metaData};      my $retVal = XML::Simple::XMLin($fileName, %XmlOptions, %XmlInOpts);
3702      my $entities = $metaData->{Entities};      Trace("XML metadata loaded from file $fileName.") if T(1);
3703      for my $entityName (keys %{$entities}) {      # Return the result.
3704          my $entityStructure = $entities->{$entityName};      return $retVal;
3705          # Get the entity's relations.  }
3706          my $relationList = $entityStructure->{Relations};  
3707          # Loop through the relations, dumping them.  =head3 GetEntityFieldHash
3708          for my $relationName (keys %{$relationList}) {  
3709              my $relation = $relationList->{$relationName};      my $fieldHashRef = ERDB::GetEntityFieldHash($structure, $entityName);
3710              $self->_DumpRelation($outputDirectory, $relationName, $relation);  
3711    Get the field hash of the named entity in the specified raw XML structure.
3712    The field hash may not exist, in which case we need to create it.
3713    
3714    =over 4
3715    
3716    =item structure
3717    
3718    Raw XML structure defininng the database. This is not the run-time XML used by
3719    an ERDB object, since that has all sorts of optimizations built-in.
3720    
3721    =item entityName
3722    
3723    Name of the entity whose field structure is desired.
3724    
3725    =item RETURN
3726    
3727    Returns the field hash used to define the entity's fields.
3728    
3729    =back
3730    
3731    =cut
3732    
3733    sub GetEntityFieldHash {
3734        # Get the parameters.
3735        my ($structure, $entityName) = @_;
3736        # Get the entity structure.
3737        my $entityData = $structure->{Entities}->{$entityName};
3738        # Look for a field structure.
3739        my $retVal = $entityData->{Fields};
3740        # If it doesn't exist, create it.
3741        if (! defined($retVal)) {
3742            $entityData->{Fields} = {};
3743            $retVal = $entityData->{Fields};
3744          }          }
3745        # Return the result.
3746        return $retVal;
3747      }      }
3748      # Next, we loop through the relationships.  
3749      my $relationships = $metaData->{Relationships};  =head3 WriteMetaXML
3750      for my $relationshipName (keys %{$relationships}) {  
3751          my $relationshipStructure = $relationships->{$relationshipName};      ERDB::WriteMetaXML($structure, $fileName);
3752          # Dump this relationship's relation.  
3753          $self->_DumpRelation($outputDirectory, $relationshipName, $relationshipStructure->{Relations}->{$relationshipName});  Write the metadata XML to a file. This method is the reverse of L</ReadMetaXML>, and is
3754    used to update the database definition. It must be used with care, however, since it
3755    will only work on a raw structure, not on the processed structure created by an ERDB
3756    constructor.
3757    
3758    =over 4
3759    
3760    =item structure
3761    
3762    XML structure to be written to the file.
3763    
3764    =item fileName
3765    
3766    Name of the output file to which the updated XML should be stored.
3767    
3768    =back
3769    
3770    =cut
3771    
3772    sub WriteMetaXML {
3773        # Get the parameters.
3774        my ($structure, $fileName) = @_;
3775        # Compute the output.
3776        my $fileString = XML::Simple::XMLout($structure, %XmlOptions, %XmlOutOpts);
3777        # Write it to the file.
3778        my $xmlOut = Open(undef, ">$fileName");
3779        print $xmlOut $fileString;
3780    }
3781    
3782    
3783    =head3 HTMLNote
3784    
3785    Convert a note or comment to HTML by replacing some bulletin-board codes with HTML. The codes
3786    supported are C<[b]> for B<bold>, C<[i]> for I<italics>, and C<[p]> for a new paragraph.
3787    Except for C<[p]>, all the codes are closed by slash-codes. So, for
3788    example, C<[b]Feature[/b]> displays the string C<Feature> in boldface.
3789    
3790        my $realHtml = ERDB::HTMLNote($dataString);
3791    
3792    =over 4
3793    
3794    =item dataString
3795    
3796    String to convert to HTML.
3797    
3798    =item RETURN
3799    
3800    An HTML string derived from the input string.
3801    
3802    =back
3803    
3804    =cut
3805    
3806    sub HTMLNote {
3807        # Get the parameter.
3808        my ($dataString) = @_;
3809        # HTML-escape the text.
3810        my $retVal = CGI::escapeHTML($dataString);
3811        # Substitute the bulletin board codes.
3812        $retVal =~ s!\[(/?[bi])\]!<$1>!g;
3813        $retVal =~ s!\[p\]!</p><p>!g;
3814        $retVal =~ s!\[link\s+([^\]]+)\]!<a href="$1">!g;
3815        $retVal =~ s!\[/link\]!</a>!g;
3816        # Return the result.
3817        return $retVal;
3818    }
3819    
3820    =head3 WikiNote
3821    
3822    Convert a note or comment to Wiki text by replacing some bulletin-board codes with HTML. The codes
3823    supported are C<[b]> for B<bold>, C<[i]> for I<italics>, and C<[p]> for a new paragraph.
3824    Except for C<[p]>, all the codes are closed by slash-codes. So, for
3825    example, C<[b]Feature[/b]> displays the string C<Feature> in boldface.
3826    
3827        my $wikiText = ERDB::WikiNote($dataString);
3828    
3829    =over 4
3830    
3831    =item dataString
3832    
3833    String to convert to Wiki text.
3834    
3835    =item RETURN
3836    
3837    An Wiki text string derived from the input string.
3838    
3839    =back
3840    
3841    =cut
3842    
3843    sub WikiNote {
3844        # Get the parameter.
3845        my ($dataString) = @_;
3846        # HTML-escape the text.
3847        my $retVal = CGI::escapeHTML($dataString);
3848        # Substitute the bulletin board codes.
3849        my $italic = WikiTools::ItalicCode();
3850        $retVal =~ s/\[\/?i\]/$italic/g;
3851        my $bold = WikiTools::BoldCode();
3852        $retVal =~ s/\[\/?b\]/$bold/g;
3853        # Paragraph breaks are the same no matter which Wiki you're using.
3854        $retVal =~ s!\[p\]!\n\n!g;
3855        # Now we do the links, which are complicated by the need to know two
3856        # things: the target URL and the text.
3857        while ($retVal =~ /\[link\s+([^\]]+)\]([^\[]+)\[\/link\]/g) {
3858            # Replace the matched string with the Wiki markup for links. Note that
3859            # $-[0] is the starting position of the match for the entire expression,
3860            # and $+[0] is past the ending position.
3861            substr $retVal, $-[0], $+[0] - $-[0], WikiTools::LinkMarkup($1, $2);
3862      }      }
3863        # Return the result.
3864        return $retVal;
3865  }  }
3866    
3867  =head3 InsertObject  =head3 BeginTran
3868    
3869  C<< my $ok = $erdb->InsertObject($objectType, \%fieldHash); >>      $erdb->BeginTran();
3870    
3871  Insert an object into the database. The object is defined by a type name and then a hash  Start a database transaction.
3872  of field names to values. Field values in the primary relation are represented by scalars.  
3873  (Note that for relationships, the primary relation is the B<only> relation.)  =cut
3874  Field values for the other relations comprising the entity are always list references. For  
3875  example, the following line inserts an inactive PEG feature named C<fig|188.1.peg.1> with aliases  sub BeginTran {
3876  C<ZP_00210270.1> and C<gi|46206278>.      my ($self) = @_;
3877        $self->{_dbh}->begin_tran();
3878    
3879    }
3880    
3881    =head3 CommitTran
3882    
3883        $erdb->CommitTran();
3884    
3885    Commit an active database transaction.
3886    
3887    =cut
3888    
3889    sub CommitTran {
3890        my ($self) = @_;
3891        $self->{_dbh}->commit_tran();
3892    }
3893    
3894    =head3 RollbackTran
3895    
3896        $erdb->RollbackTran();
3897    
3898    Roll back an active database transaction.
3899    
3900    =cut
3901    
3902    sub RollbackTran {
3903        my ($self) = @_;
3904        $self->{_dbh}->roll_tran();
3905    }
3906    
3907    =head3 UpdateField
3908    
3909        my $count = $erdb->UpdateField($objectNames, $fieldName, $oldValue, $newValue, $filter, $parms);
3910    
3911    Update all occurrences of a specific field value to a new value. The number of rows changed will be
3912    returned.
3913    
3914    =over 4
3915    
3916    =item fieldName
3917    
3918  C<< $erdb->InsertObject('Feature', { id => 'fig|188.1.peg.1', active => 0, feature-type => 'peg', alias => ['ZP_00210270.1', 'gi|46206278']}); >>  Name of the field in standard I<objectName>C<(>I<fieldName>C<)> format.
3919    
3920  The next statement inserts a C<HasProperty> relationship between feature C<fig|158879.1.peg.1> and  =item oldValue
 property C<4> with an evidence URL of C<http://seedu.uchicago.edu/query.cgi?article_id=142>.  
3921    
3922  C<< $erdb->InsertObject('HasProperty', { 'from-link' => 'fig|158879.1.peg.1', 'to-link' => 4, evidence = 'http://seedu.uchicago.edu/query.cgi?article_id=142'}); >>  Value to be modified. All occurrences of this value in the named field will be replaced by the
3923    new value.
3924    
3925  =over 4  =item newValue
3926    
3927  =item newObjectType  New value to be substituted for the old value when it's found.
3928    
3929  Type name of the object to insert.  =item filter
3930    
3931  =item fieldHash  A standard ERDB filter clause (see L</Get>). The filter will be applied before any substitutions take place.
3932    
3933  Hash of field names to values.  =item parms
3934    
3935    Reference to a list of parameter values in the filter.
3936    
3937  =item RETURN  =item RETURN
3938    
3939  Returns 1 if successful, 0 if an error occurred.  Returns the number of rows modified.
3940    
3941  =back  =back
3942    
3943  =cut  =cut
3944    
3945  sub InsertObject {  sub UpdateField {
3946      # Get the parameters.      # Get the parameters.
3947      my ($self, $newObjectType, $fieldHash) = @_;      my ($self, $fieldName, $oldValue, $newValue, $filter, $parms) = @_;
3948      # Denote that so far we appear successful.      # Get the object and field names from the field name parameter.
3949      my $retVal = 1;      $fieldName =~ /^([^(]+)\(([^)]+)\)/;
3950        my $objectName = $1;
3951        my $realFieldName = _FixName($2);
3952        # Add the old value to the filter. Note we allow the possibility that no
3953        # filter was specified.
3954        my $realFilter = "$fieldName = ?";
3955        if ($filter) {
3956            $realFilter .= " AND $filter";
3957        }
3958        # Format the query filter.
3959        my ($suffix, $mappedNameListRef, $mappedNameHashRef) =
3960            $self->_SetupSQL([$objectName], $realFilter);
3961        # Create the query. Since there is only one object name, the mapped-name data is not
3962        # necessary. Neither is the FROM clause.
3963        $suffix =~ s/^FROM.+WHERE\s+//;
3964        # Create the update statement.
3965        my $command = "UPDATE $objectName SET $realFieldName = ? WHERE $suffix";
3966      # Get the database handle.      # Get the database handle.
3967      my $dbh = $self->{_dbh};      my $dbh = $self->{_dbh};
3968      # Get the relation list.      # Add the old and new values to the parameter list. Note we allow the possibility that
3969      my $relationTable = $self->_GetRelationTable($newObjectType);      # there are no user-supplied parameters.
3970      # Loop through the relations. We'll build insert statements for each one. If a relation is      my @params = ($newValue, $oldValue);
3971      # secondary, we may end up generating multiple insert statements. If an error occurs, we      if (defined $parms) {
3972      # stop the loop.          push @params, @{$parms};
3973      my @relationList = keys %{$relationTable};      }
3974      for (my $i = 0; $retVal && $i <= $#relationList; $i++) {      # Execute the update.
3975          my $relationName = $relationList[$i];      my $retVal = $dbh->SQL($command, 0, @params);
3976          my $relationDefinition = $relationTable->{$relationName};      # Make the funky zero a real zero.
3977          # Get the relation's fields. For each field we will collect a value in the corresponding      if ($retVal == 0) {
         # position of the @valueList array. If one of the fields is missing, we will add it to the  
         # @missing list.  
         my @fieldList = @{$relationDefinition->{Fields}};  
         my @fieldNameList = ();  
         my @valueList = ();  
         my @missing = ();  
         my $recordCount = 1;  
         for my $fieldDescriptor (@fieldList) {  
             # Get the field name and save it. Note we need to fix it up so the hyphens  
             # are converted to underscores.  
             my $fieldName = $fieldDescriptor->{name};  
             push @fieldNameList, _FixName($fieldName);  
             # Look for the named field in the incoming structure. Note that we are looking  
             # for the real field name, not the fixed-up one!  
             if (exists $fieldHash->{$fieldName}) {  
                 # Here we found the field. Stash it in the value list.  
                 my $value = $fieldHash->{$fieldName};  
                 push @valueList, $value;  
                 # If the value is a list, we may need to increment the record count.  
                 if (ref $value eq "ARRAY") {  
                     my $thisCount = @{$value};  
                     if ($recordCount == 1) {  
                         # Here we have our first list, so we save its count.  
                         $recordCount = $thisCount;  
                     } elsif ($recordCount != $thisCount) {  
                         # 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);  
3978                          $retVal = 0;                          $retVal = 0;
3979                      }                      }
3980                  }      # Return the result.
             } else {  
                 # Here the field is not present. Flag it as missing.  
                 push @missing, $fieldName;  
             }  
         }  
         # If we are the primary relation, add the new-record flag.  
         if ($relationName eq $newObjectType) {  
             push @valueList, 1;  
             push @fieldNameList, "new_record";  
         }  
         # Only proceed if there are no missing fields.  
         if (@missing > 0) {  
             Trace("Relation $relationName for $newObjectType skipped due to missing fields: " .  
                 join(' ', @missing)) if T(1);  
         } else {  
             # 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 = ();<