[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.48, Wed Jun 21 03:12:20 2006 UTC revision 1.103, Tue Sep 16 18:57:59 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 Digest::MD5 qw(md5_base64);      use Digest::MD5 qw(md5_base64);
13      use FIG;      use CGI;
14        use WikiTools;
15    
16  =head1 Entity-Relationship Database Package  =head1 Entity-Relationship Database Package
17    
# Line 59  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 91  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 186  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 205  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 238  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 282  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 316  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 =>   1, 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' =>                   'hash-string' =>
362                               { sqlType => 'VARCHAR(22)',        maxLen => 22,           avgLen =>  22, dataGen => "SringGen(22)" },                               { 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' =>                   'id-string' =>
365                               { sqlType => 'VARCHAR(25)',        maxLen => 25,           avgLen =>  25, dataGen => "SringGen(22)" },                               { 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 344  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 377  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 391  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 432  Line 491 
491    
492  =head3 DisplayMetaData  =head3 DisplayMetaData
493    
494  C<< my $html = $erdb->DisplayMetaData(); >>      my $html = $erdb->DisplayMetaData();
495    
496  Return an HTML description of the database. This description can be used to help users create  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  the data to be loaded into the relations and form queries. The output is raw includable HTML
# Line 493  Line 552 
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              $retVal .= "<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            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";          $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}) {
# Line 511  Line 573 
573          }          }
574          # Close off the relationship list.          # Close off the relationship list.
575          $retVal .= "</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.
# Line 550  Line 613 
613          $retVal .= "</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              $retVal .= "<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});
# Line 584  Line 647 
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 597  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 616  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 665  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 679  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      }      }
# Line 692  Line 1087 
1087    
1088  =head3 VerifyFields  =head3 VerifyFields
1089    
1090  C<< my $count = $erdb->VerifyFields($relName, \@fieldList); >>      my $count = $erdb->VerifyFields($relName, \@fieldList);
1091    
1092  Run through the list of proposed field values, insuring that all the character fields are  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.  below the maximum length. If any fields are too long, they will be truncated in place.
# Line 735  Line 1130 
1130              my $oldString = $fieldList->[$i];              my $oldString = $fieldList->[$i];
1131              if (length($oldString) > $maxLen) {              if (length($oldString) > $maxLen) {
1132                  # Here it's too big, so we truncate it.                  # Here it's too big, so we truncate it.
1133                  Trace("Truncating field $i in relation $relName to $maxLen characters from \"$oldString\".") if T(1);                  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;                  $fieldList->[$i] = substr $oldString, 0, $maxLen;
1135                  $retVal++;                  $retVal++;
1136              }              }
# Line 747  Line 1142 
1142    
1143  =head3 DigestFields  =head3 DigestFields
1144    
1145  C<< $erdb->DigestFields($relName, $fieldList); >>      $erdb->DigestFields($relName, $fieldList);
1146    
1147  Digest the strings in the field list that correspond to data type C<hash-string> in the  Digest the strings in the field list that correspond to data type C<hash-string> in the
1148  specified relation.  specified relation.
# Line 787  Line 1182 
1182    
1183  =head3 DigestKey  =head3 DigestKey
1184    
1185  C<< my $digested = $erdb->DigestKey($keyValue); >>      my $digested = $erdb->DigestKey($keyValue);
1186    
1187  Return the digested value of a symbolic key. The digested value can then be plugged into a  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.  key-based search into a table with key-type hash-string.
# Line 820  Line 1215 
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 841  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 856  Line 1269 
1269      }      }
1270  }  }
1271    
1272    =head3 GetSecondaryFields
1273    
1274        my %fieldTuples = $erdb->GetSecondaryFields($entityName);
1275    
1276    This method will return a list of the name and type of each of the secondary
1277    fields for a specified entity. Secondary fields are stored in two-column tables
1278    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
1282    
1283    =item entityName
1284    
1285    Name of the entity whose secondary fields are desired.
1286    
1287    =item RETURN
1288    
1289    Returns a hash mapping the field names to their field types.
1290    
1291    =back
1292    
1293    =cut
1294    
1295    sub GetSecondaryFields {
1296        # Get the parameters.
1297        my ($self, $entityName) = @_;
1298        # Declare the return variable.
1299        my %retVal = ();
1300        # Look for the entity.
1301        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  =head3 LoadTables
1438    
1439  C<< my $stats = $erdb->LoadTables($directoryName, $rebuild); >>      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  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;  in the database. (This can be done by calling L</CreateTables>.) The caller passes in a directory name;
# Line 918  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 935  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 950  Line 1528 
1528      return sort keys %{$entityList};      return sort keys %{$entityList};
1529  }  }
1530    
1531    
1532    =head3 GetConnectingRelationships
1533    
1534        my @list = $erdb->GetConnectingRelationships($entityName);
1535    
1536    Return a list of the relationships connected to the specified entity.
1537    
1538    =over 4
1539    
1540    =item entityName
1541    
1542    Entity whose connected relationships are desired.
1543    
1544    =item RETURN
1545    
1546    Returns a list of the relationships that originate from the entity.
1547    If the entity is on the from end, it will return the relationship
1548    name. If the entity is on the to end it will return the converse of
1549    the relationship name.
1550    
1551    =back
1552    
1553    =cut
1554    
1555    sub GetConnectingRelationships {
1556        # Get the parameters.
1557        my ($self, $entityName) = @_;
1558        # Declare the return variable.
1559        my @retVal;
1560        # Get the relationship list.
1561        my $relationships = $self->{_metaData}->{Relationships};
1562        # Find the entity.
1563        my $entity = $self->{_metaData}->{Entities}->{$entityName};
1564        # Only proceed if the entity exists.
1565        if (! defined $entity) {
1566            Trace("Entity $entityName not found.") if T(3);
1567        } else {
1568            # Loop through the relationships.
1569            my @rels = keys %$relationships;
1570            Trace(scalar(@rels) . " relationships found in connection search.") if T(3);
1571            for my $relationshipName (@rels) {
1572                my $relationship = $relationships->{$relationshipName};
1573                if ($relationship->{from} eq $entityName) {
1574                    # Here we have a forward relationship.
1575                    push @retVal, $relationshipName;
1576                } elsif ($relationship->{to} eq $entityName) {
1577                    # Here we have a backward relationship. In this case, the
1578                    # converse relationship name is preferred if it exists.
1579                    my $converse = $relationship->{converse} || $relationshipName;
1580                    push @retVal, $converse;
1581                }
1582            }
1583        }
1584        # Return the result.
1585        return @retVal;
1586    }
1587    
1588    
1589    =head3 GetDataTypes
1590    
1591        my %types = ERDB::GetDataTypes();
1592    
1593    Return a table of ERDB data types. The table returned is a hash of hashes.
1594    The keys of the big hash are the datatypes. Each smaller hash has several
1595    values used to manage the data. The most interesting is the SQL type (key
1596    C<sqlType>) and the descriptive node (key C<notes>).
1597    
1598    Note that changing the values in the smaller hashes will seriously break
1599    things, so this data should be treated as read-only.
1600    
1601    =cut
1602    
1603    sub GetDataTypes {
1604        return %TypeTable;
1605    }
1606    
1607    
1608  =head3 IsEntity  =head3 IsEntity
1609    
1610  C<< my $flag = $erdb->IsEntity($entityName); >>      my $flag = $erdb->IsEntity($entityName);
1611    
1612  Return TRUE if the parameter is an entity name, else FALSE.  Return TRUE if the parameter is an entity name, else FALSE.
1613    
# Line 979  Line 1634 
1634    
1635  =head3 Get  =head3 Get
1636    
1637  C<< my $query = $erdb->Get(\@objectNames, $filterClause, \@params); >>      my $query = $erdb->Get(\@objectNames, $filterClause, \@params);
1638    
1639  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.
1640  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 987  Line 1642 
1642  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
1643  $genus.  $genus.
1644    
1645  C<< $query = $erdb->Get(['Genome'], "Genome(genus) = ?", [$genus]); >>      $query = $erdb->Get(['Genome'], "Genome(genus) = ?", [$genus]);
1646    
1647  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
1648  parameter representing the parameter value. It would also be possible to code  parameter representing the parameter value. It would also be possible to code
1649    
1650  C<< $query = $erdb->Get(['Genome'], "Genome(genus) = \'$genus\'"); >>      $query = $erdb->Get(['Genome'], "Genome(genus) = \'$genus\'");
1651    
1652  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
1653  characters inside the variable C<$genus>.  characters inside the variable C<$genus>.
# Line 1004  Line 1659 
1659  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
1660  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,
1661    
1662  C<< $query = $erdb->Get(['Genome', 'ComesFrom', 'Source'], "Genome(genus) = ?", [$genus]); >>      $query = $erdb->Get(['Genome', 'ComesFrom', 'Source'], "Genome(genus) = ?", [$genus]);
1663    
1664  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
1665  join path between the entities and relationships. The algorithm used is very simplistic.  join path between the entities and relationships. The algorithm used is very simplistic.
# Line 1040  Line 1695 
1695  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
1696  particular genus and sorts them by species name.  particular genus and sorts them by species name.
1697    
1698  C<< "Genome(genus) = ? ORDER BY Genome(species)" >>      "Genome(genus) = ? ORDER BY Genome(species)"
1699    
1700  Note that the case is important. Only an uppercase "ORDER BY" with a single space will  Note that the case is important. Only an uppercase "ORDER BY" with a single space will
1701  be processed. The idea is to make it less likely to find the verb by accident.  be processed. The idea is to make it less likely to find the verb by accident.
# Line 1053  Line 1708 
1708  be the last thing in the filter clause, and it contains only the word "LIMIT" followed by  be the last thing in the filter clause, and it contains only the word "LIMIT" followed by
1709  a positive number. So, for example  a positive number. So, for example
1710    
1711  C<< "Genome(genus) = ? ORDER BY Genome(species) LIMIT 10" >>      "Genome(genus) = ? ORDER BY Genome(species) LIMIT 10"
1712    
1713  will only return the first ten genomes for the specified genus. The ORDER BY clause is not  will only return the first ten genomes for the specified genus. The ORDER BY clause is not
1714  required. For example, to just get the first 10 genomes in the B<Genome> table, you could  required. For example, to just get the first 10 genomes in the B<Genome> table, you could
1715  use  use
1716    
1717  C<< "LIMIT 10" >>      "LIMIT 10"
1718    
1719  =item params  =item params
1720    
# Line 1080  Line 1735 
1735      my ($suffix, $mappedNameListRef, $mappedNameHashRef) =      my ($suffix, $mappedNameListRef, $mappedNameHashRef) =
1736          $self->_SetupSQL($objectNames, $filterClause);          $self->_SetupSQL($objectNames, $filterClause);
1737      # Create the query.      # Create the query.
1738      my $command = "SELECT DISTINCT " . join(".*, ", @{$mappedNameListRef}) .      my $command = "SELECT " . join(".*, ", @{$mappedNameListRef}) .
1739          ".* $suffix";          ".* $suffix";
1740      my $sth = $self->_GetStatementHandle($command, $params);      my $sth = $self->_GetStatementHandle($command, $params);
1741      # Now we create the relation map, which enables DBQuery to determine the order, name      # Now we create the relation map, which enables DBQuery to determine the order, name
# Line 1094  Line 1749 
1749      return $retVal;      return $retVal;
1750  }  }
1751    
 =head3 GetFlat  
1752    
 C<< my @list = $erdb->GetFlat(\@objectNames, $filterClause, \@parameterList, $field); >>  
1753    
1754  This is a variation of L</GetAll> that asks for only a single field per record and  =head3 Search
1755  returns a single flattened list.  
1756        my $query = $erdb->Search($searchExpression, $idx, \@objectNames, $filterClause, \@params);
1757    
1758    Perform a full text search with filtering. The search will be against a specified object
1759    in the object name list. That object will get an extra field containing the search
1760    relevance. Note that except for the search expression, the parameters of this method are
1761    the same as those for L</Get> and follow the same rules.
1762    
1763  =over 4  =over 4
1764    
1765    =item searchExpression
1766    
1767    Boolean search expression for the text fields of the target object. The default mode for
1768    a Boolean search expression is OR, but we want the default to be AND, so we will
1769    add a C<+> operator to each word with no other operator before it.
1770    
1771    =item idx
1772    
1773    Index in the I<$objectNames> list of the table to be searched in full-text mode.
1774    
1775  =item objectNames  =item objectNames
1776    
1777  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.
1778    
1779  =item filterClause  =item filterClause
1780    
1781  WHERE/ORDER BY clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can  WHERE clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can
1782    be parameterized with parameter markers (C<?>). Each field used in the WHERE clause must be
1783    specified in the standard form B<I<objectName>(I<fieldName>)>. Any parameters specified
1784    in the filter clause should be added to the parameter list as additional parameters. The
1785    fields in a filter clause can come from primary entity relations, relationship relations,
1786    or secondary entity relations; however, all of the entities and relationships involved must
1787    be included in the list of object names.
1788    
1789    =item params
1790    
1791    Reference to a list of parameter values to be substituted into the filter clause.
1792    
1793    =item RETURN
1794    
1795    Returns a query object for the specified search.
1796    
1797    =back
1798    
1799    =cut
1800    
1801    sub Search {
1802        # Get the parameters.
1803        my ($self, $searchExpression, $idx, $objectNames, $filterClause, $params) = @_;
1804        # Declare the return variable.
1805        my $retVal;
1806        # Create a safety copy of the parameter list. Note we have to be careful to insure
1807        # a parameter list exists before we copy it.
1808        my @myParams = ();
1809        if (defined $params) {
1810            @myParams = @{$params};
1811        }
1812        # Get the first object's structure so we have access to the searchable fields.
1813        my $object1Name = $objectNames->[$idx];
1814        my $object1Structure = $self->_GetStructure($object1Name);
1815        # Get the field list.
1816        if (! exists $object1Structure->{searchFields}) {
1817            Confess("No searchable index for $object1Name.");
1818        } else {
1819            # Get the field list.
1820            my @fields = @{$object1Structure->{searchFields}};
1821            # Clean the search expression.
1822            my $actualKeywords = $self->CleanKeywords($searchExpression);
1823            # Prefix a "+" to each uncontrolled word. This converts the default
1824            # search mode from OR to AND.
1825            $actualKeywords =~ s/(^|\s)(\w|")/$1\+$2/g;
1826            Trace("Actual keywords for search are\n$actualKeywords") if T(3);
1827            # We need two match expressions, one for the filter clause and one in the
1828            # query itself. Both will use a parameter mark, so we need to push the
1829            # search expression onto the front of the parameter list twice.
1830            unshift @myParams, $actualKeywords, $actualKeywords;
1831            # Build the match expression.
1832            my @matchFilterFields = map { "$object1Name." . _FixName($_) } @fields;
1833            my $matchClause = "MATCH (" . join(", ", @matchFilterFields) . ") AGAINST (? IN BOOLEAN MODE)";
1834            # Process the SQL stuff.
1835            my ($suffix, $mappedNameListRef, $mappedNameHashRef) =
1836                $self->_SetupSQL($objectNames, $filterClause, $matchClause);
1837            # Create the query. Note that the match clause is inserted at the front of
1838            # the select fields.
1839            my $command = "SELECT $matchClause, " . join(".*, ", @{$mappedNameListRef}) .
1840                ".* $suffix";
1841            my $sth = $self->_GetStatementHandle($command, \@myParams);
1842            # Now we create the relation map, which enables DBQuery to determine the order, name
1843            # and mapped name for each object in the query.
1844            my @relationMap = _RelationMap($mappedNameHashRef, $mappedNameListRef);
1845            # Return the statement object.
1846            $retVal = DBQuery::_new($self, $sth, \@relationMap, $object1Name);
1847        }
1848        return $retVal;
1849    }
1850    
1851    =head3 GetFlat
1852    
1853        my @list = $erdb->GetFlat(\@objectNames, $filterClause, \@parameterList, $field);
1854    
1855    This is a variation of L</GetAll> that asks for only a single field per record and
1856    returns a single flattened list.
1857    
1858    =over 4
1859    
1860    =item objectNames
1861    
1862    List containing the names of the entity and relationship objects to be retrieved.
1863    
1864    =item filterClause
1865    
1866    WHERE/ORDER BY clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can
1867  be parameterized with parameter markers (C<?>). Each field used must be specified in the standard form  be parameterized with parameter markers (C<?>). Each field used must be specified in the standard form
1868  B<I<objectName>(I<fieldName>)>. Any parameters specified in the filter clause should be added to the  B<I<objectName>(I<fieldName>)>. Any parameters specified in the filter clause should be added to the
1869  parameter list as additional parameters. The fields in a filter clause can come from primary  parameter list as additional parameters. The fields in a filter clause can come from primary
# Line 1147  Line 1901 
1901      return @retVal;      return @retVal;
1902  }  }
1903    
1904    =head3 SpecialFields
1905    
1906        my %specials = $erdb->SpecialFields($entityName);
1907    
1908    Return a hash mapping special fields in the specified entity to the value of their
1909    C<special> attribute. This enables the subclass to get access to the special field
1910    attributes without needed to plumb the internal ERDB data structures.
1911    
1912    =over 4
1913    
1914    =item entityName
1915    
1916    Name of the entity whose special fields are desired.
1917    
1918    =item RETURN
1919    
1920    Returns a hash. The keys of the hash are the special field names, and the values
1921    are the values from each special field's C<special> attribute.
1922    
1923    =back
1924    
1925    =cut
1926    
1927    sub SpecialFields {
1928        # Get the parameters.
1929        my ($self, $entityName) = @_;
1930        # Declare the return variable.
1931        my %retVal = ();
1932        # Find the entity's data structure.
1933        my $entityData = $self->{_metaData}->{Entities}->{$entityName};
1934        # Loop through its fields, adding each special field to the return hash.
1935        my $fieldHash = $entityData->{Fields};
1936        for my $fieldName (keys %{$fieldHash}) {
1937            my $fieldData = $fieldHash->{$fieldName};
1938            if (exists $fieldData->{special}) {
1939                $retVal{$fieldName} = $fieldData->{special};
1940            }
1941        }
1942        # Return the result.
1943        return %retVal;
1944    }
1945    
1946  =head3 Delete  =head3 Delete
1947    
1948  C<< my $stats = $erdb->Delete($entityName, $objectID); >>      my $stats = $erdb->Delete($entityName, $objectID, %options);
1949    
1950  Delete an entity instance from the database. The instance is deleted along with all entity and  Delete an entity instance from the database. The instance is deleted along with all entity and
1951  relationship instances dependent on it. The idea of dependence here is recursive. An object is  relationship instances dependent on it. The definition of I<dependence> is recursive.
1952  always dependent on itself. An object is dependent if it is a 1-to-many or many-to-many  
1953  relationship connected to a dependent entity or the "to" entity connected to a 1-to-many  An object is always dependent on itself. An object is dependent if it is a 1-to-many or many-to-many
1954    relationship connected to a dependent entity or if it is the "to" entity connected to a 1-to-many
1955  dependent relationship.  dependent relationship.
1956    
1957  =over 4  =over 4
# Line 1168  Line 1965 
1965  ID of the entity instance to be deleted. If the ID contains a wild card character (C<%>),  ID of the entity instance to be deleted. If the ID contains a wild card character (C<%>),
1966  then it is presumed to by a LIKE pattern.  then it is presumed to by a LIKE pattern.
1967    
1968  =item testFlag  =item options
1969    
1970  If TRUE, the delete statements will be traced without being executed.  A hash detailing the options for this delete operation.
1971    
1972  =item RETURN  =item RETURN
1973    
# Line 1179  Line 1976 
1976    
1977  =back  =back
1978    
1979    The permissible options for this method are as follows.
1980    
1981    =over 4
1982    
1983    =item testMode
1984    
1985    If TRUE, then the delete statements will be traced, but no changes will be made to the database.
1986    
1987    =item keepRoot
1988    
1989    If TRUE, then the entity instances will not be deleted, only the dependent records.
1990    
1991    =back
1992    
1993  =cut  =cut
1994  #: Return Type $%;  #: Return Type $%;
1995  sub Delete {  sub Delete {
1996      # Get the parameters.      # Get the parameters.
1997      my ($self, $entityName, $objectID, $testFlag) = @_;      my ($self, $entityName, $objectID, %options) = @_;
1998      # Declare the return variable.      # Declare the return variable.
1999      my $retVal = Stats->new();      my $retVal = Stats->new();
2000      # Get the DBKernel object.      # Get the DBKernel object.
# Line 1200  Line 2011 
2011      # FROM-relationships and entities.      # FROM-relationships and entities.
2012      my @fromPathList = ();      my @fromPathList = ();
2013      my @toPathList = ();      my @toPathList = ();
2014      # This final hash is used to remember what work still needs to be done. We push paths      # This final list is used to remember what work still needs to be done. We push paths
2015      # onto the list, then pop them off to extend the paths. We prime it with the starting      # onto the list, then pop them off to extend the paths. We prime it with the starting
2016      # point. Note that we will work hard to insure that the last item on a path in the      # point. Note that we will work hard to insure that the last item on a path in the
2017      # TODO list is always an entity.      # to-do list is always an entity.
2018      my @todoList = ([$entityName]);      my @todoList = ([$entityName]);
2019      while (@todoList) {      while (@todoList) {
2020          # Get the current path.          # Get the current path.
# Line 1211  Line 2022 
2022          # Copy it into a list.          # Copy it into a list.
2023          my @stackedPath = @{$current};          my @stackedPath = @{$current};
2024          # Pull off the last item on the path. It will always be an entity.          # Pull off the last item on the path. It will always be an entity.
2025          my $entityName = pop @stackedPath;          my $myEntityName = pop @stackedPath;
2026          # Add it to the alreadyFound list.          # Add it to the alreadyFound list.
2027          $alreadyFound{$entityName} = 1;          $alreadyFound{$myEntityName} = 1;
2028            # Figure out if we need to delete this entity.
2029            if ($myEntityName ne $entityName || ! $options{keepRoot}) {
2030          # Get the entity data.          # Get the entity data.
2031          my $entityData = $self->_GetStructure($entityName);              my $entityData = $self->_GetStructure($myEntityName);
2032          # The first task is to loop through the entity's relation. A DELETE command will              # Loop through the entity's relations. A DELETE command will be needed for each of them.
         # be needed for each of them.  
2033          my $relations = $entityData->{Relations};          my $relations = $entityData->{Relations};
2034          for my $relation (keys %{$relations}) {          for my $relation (keys %{$relations}) {
2035              my @augmentedList = (@stackedPath, $relation);              my @augmentedList = (@stackedPath, $relation);
2036              push @fromPathList, \@augmentedList;              push @fromPathList, \@augmentedList;
2037          }          }
2038            }
2039          # Now we need to look for relationships connected to this entity.          # Now we need to look for relationships connected to this entity.
2040          my $relationshipList = $self->{_metaData}->{Relationships};          my $relationshipList = $self->{_metaData}->{Relationships};
2041          for my $relationshipName (keys %{$relationshipList}) {          for my $relationshipName (keys %{$relationshipList}) {
2042              my $relationship = $relationshipList->{$relationshipName};              my $relationship = $relationshipList->{$relationshipName};
2043              # Check the FROM field. We're only interested if it's us.              # Check the FROM field. We're only interested if it's us.
2044              if ($relationship->{from} eq $entityName) {              if ($relationship->{from} eq $myEntityName) {
2045                  # Add the path to this relationship.                  # Add the path to this relationship.
2046                  my @augmentedList = (@stackedPath, $entityName, $relationshipName);                  my @augmentedList = (@stackedPath, $myEntityName, $relationshipName);
2047                  push @fromPathList, \@augmentedList;                  push @fromPathList, \@augmentedList;
2048                  # Check the arity. If it's MM we're done. If it's 1M                  # Check the arity. If it's MM we're done. If it's 1M
2049                  # and the target hasn't been seen yet, we want to                  # and the target hasn't been seen yet, we want to
# Line 1249  Line 2062 
2062              }              }
2063              # Now check the TO field. In this case only the relationship needs              # Now check the TO field. In this case only the relationship needs
2064              # deletion.              # deletion.
2065              if ($relationship->{to} eq $entityName) {              if ($relationship->{to} eq $myEntityName) {
2066                  my @augmentedList = (@stackedPath, $entityName, $relationshipName);                  my @augmentedList = (@stackedPath, $myEntityName, $relationshipName);
2067                  push @toPathList, \@augmentedList;                  push @toPathList, \@augmentedList;
2068              }              }
2069          }          }
2070      }      }
2071      # Create the first qualifier for the WHERE clause. This selects the      # Create the first qualifier for the WHERE clause. This selects the
2072      # keys of the primary entity records to be deleted. When we're deleting      # keys of the primary entity records to be deleted. When we're deleting
2073      # from a dependent table, we construct a join page from the first qualifier      # from a dependent table, we construct a join path from the first qualifier
2074      # to the table containing the dependent records to delete.      # to the table containing the dependent records to delete.
2075      my $qualifier = ($objectID =~ /%/ ? "LIKE ?" : "= ?");      my $qualifier = ($objectID =~ /%/ ? "LIKE ?" : "= ?");
2076      # We need to make two passes. The first is through the to-list, and      # We need to make two passes. The first is through the to-list, and
# Line 1296  Line 2109 
2109                  }                  }
2110              }              }
2111              # Now we have our desired DELETE statement.              # Now we have our desired DELETE statement.
2112              if ($testFlag) {              if ($options{testMode}) {
2113                  # Here the user wants to trace without executing.                  # Here the user wants to trace without executing.
2114                  Trace($stmt) if T(0);                  Trace($stmt) if T(0);
2115              } else {              } else {
2116                  # Here we can delete. Note that the SQL method dies with a confessing                  # Here we can delete. Note that the SQL method dies with a confession
2117                  # if an error occurs, so we just go ahead and do it.                  # if an error occurs, so we just go ahead and do it.
2118                  Trace("Executing delete from $target using '$objectID'.") if T(3);                  Trace("Executing delete from $target using '$objectID'.") if T(3);
2119                  my $rv = $db->SQL($stmt, 0, $objectID);                  my $rv = $db->SQL($stmt, 0, $objectID);
# Line 1315  Line 2128 
2128      return $retVal;      return $retVal;
2129  }  }
2130    
2131    =head3 Disconnect
2132    
2133        $erdb->Disconnect($relationshipName, $originEntityName, $originEntityID);
2134    
2135    Disconnect an entity instance from all the objects to which it is related. This
2136    will delete each relationship instance that connects to the specified entity.
2137    
2138    =over 4
2139    
2140    =item relationshipName
2141    
2142    Name of the relationship whose instances are to be deleted.
2143    
2144    =item originEntityName
2145    
2146    Name of the entity that is to be disconnected.
2147    
2148    =item originEntityID
2149    
2150    ID of the entity that is to be disconnected.
2151    
2152    =back
2153    
2154    =cut
2155    
2156    sub Disconnect {
2157        # Get the parameters.
2158        my ($self, $relationshipName, $originEntityName, $originEntityID) = @_;
2159        # Get the relationship descriptor.
2160        my $structure = $self->_GetStructure($relationshipName);
2161        # Insure we have a relationship.
2162        if (! exists $structure->{from}) {
2163            Confess("$relationshipName is not a relationship in the database.");
2164        } else {
2165            # Get the database handle.
2166            my $dbh = $self->{_dbh};
2167            # We'll set this value to 1 if we find our entity.
2168            my $found = 0;
2169            # Loop through the ends of the relationship.
2170            for my $dir ('from', 'to') {
2171                if ($structure->{$dir} eq $originEntityName) {
2172                    $found = 1;
2173                    # Here we want to delete all relationship instances on this side of the
2174                    # entity instance.
2175                    Trace("Disconnecting in $dir direction with ID \"$originEntityID\".");
2176                    # We do this delete in batches to keep it from dragging down the
2177                    # server.
2178                    my $limitClause = ($FIG_Config::delete_limit ? "LIMIT $FIG_Config::delete_limit" : "");
2179                    my $done = 0;
2180                    while (! $done) {
2181                        # Do the delete.
2182                        my $rows = $dbh->SQL("DELETE FROM $relationshipName WHERE ${dir}_link = ? $limitClause", 0, $originEntityID);
2183                        # See if we're done. We're done if no rows were found or the delete is unlimited.
2184                        $done = ($rows == 0 || ! $limitClause);
2185                    }
2186                }
2187            }
2188            # Insure we found the entity on at least one end.
2189            if (! $found) {
2190                Confess("Entity \"$originEntityName\" does not use $relationshipName.");
2191            }
2192        }
2193    }
2194    
2195    =head3 DeleteRow
2196    
2197        $erdb->DeleteRow($relationshipName, $fromLink, $toLink, \%values);
2198    
2199    Delete a row from a relationship. In most cases, only the from-link and to-link are
2200    needed; however, for relationships with intersection data values can be specified
2201    for the other fields using a hash.
2202    
2203    =over 4
2204    
2205    =item relationshipName
2206    
2207    Name of the relationship from which the row is to be deleted.
2208    
2209    =item fromLink
2210    
2211    ID of the entity instance in the From direction.
2212    
2213    =item toLink
2214    
2215    ID of the entity instance in the To direction.
2216    
2217    =item values
2218    
2219    Reference to a hash of other values to be used for filtering the delete.
2220    
2221    =back
2222    
2223    =cut
2224    
2225    sub DeleteRow {
2226        # Get the parameters.
2227        my ($self, $relationshipName, $fromLink, $toLink, $values) = @_;
2228        # Create a hash of all the filter information.
2229        my %filter = ('from-link' => $fromLink, 'to-link' => $toLink);
2230        if (defined $values) {
2231            for my $key (keys %{$values}) {
2232                $filter{$key} = $values->{$key};
2233            }
2234        }
2235        # Build an SQL statement out of the hash.
2236        my @filters = ();
2237        my @parms = ();
2238        for my $key (keys %filter) {
2239            push @filters, _FixName($key) . " = ?";
2240            push @parms, $filter{$key};
2241        }
2242        Trace("Parms for delete row are " . join(", ", map { "\"$_\"" } @parms) . ".") if T(SQL => 4);
2243        my $command = "DELETE FROM $relationshipName WHERE " .
2244                      join(" AND ", @filters);
2245        # Execute it.
2246        my $dbh = $self->{_dbh};
2247        $dbh->SQL($command, undef, @parms);
2248    }
2249    
2250    =head3 DeleteLike
2251    
2252        my $deleteCount = $erdb->DeleteLike($relName, $filter, \@parms);
2253    
2254    Delete all the relationship rows that satisfy a particular filter condition. Unlike a normal
2255    filter, only fields from the relationship itself can be used.
2256    
2257    =over 4
2258    
2259    =item relName
2260    
2261    Name of the relationship whose records are to be deleted.
2262    
2263    =item filter
2264    
2265    A filter clause (L</Get>-style) for the delete query.
2266    
2267    =item parms
2268    
2269    Reference to a list of parameters for the filter clause.
2270    
2271    =item RETURN
2272    
2273    Returns a count of the number of rows deleted.
2274    
2275    =back
2276    
2277    =cut
2278    
2279    sub DeleteLike {
2280        # Get the parameters.
2281        my ($self, $objectName, $filter, $parms) = @_;
2282        # Declare the return variable.
2283        my $retVal;
2284        # Insure the parms argument is an array reference if the caller left it off.
2285        if (! defined($parms)) {
2286            $parms = [];
2287        }
2288        # Insure we have a relationship. The main reason for this is if we delete an entity
2289        # instance we have to yank out a bunch of other stuff with it.
2290        if ($self->IsEntity($objectName)) {
2291            Confess("Cannot use DeleteLike on $objectName, because it is not a relationship.");
2292        } else {
2293            # Create the SQL command suffix to get the desierd records.
2294            my ($suffix) = $self->_SetupSQL([$objectName], $filter);
2295            # Convert it to a DELETE command.
2296            my $command = "DELETE $suffix";
2297            # Execute the command.
2298            my $dbh = $self->{_dbh};
2299            my $result = $dbh->SQL($command, 0, @{$parms});
2300            # Check the results. Note we convert the "0D0" result to a real zero.
2301            # A failure causes an abnormal termination, so the caller isn't going to
2302            # worry about it.
2303            if (! defined $result) {
2304                Confess("Error deleting from $objectName: " . $dbh->errstr());
2305            } elsif ($result == 0) {
2306                $retVal = 0;
2307            } else {
2308                $retVal = $result;
2309            }
2310        }
2311        # Return the result count.
2312        return $retVal;
2313    }
2314    
2315    =head3 SortNeeded
2316    
2317        my $parms = $erdb->SortNeeded($relationName);
2318    
2319    Return the pipe command for the sort that should be applied to the specified
2320    relation when creating the load file.
2321    
2322    For example, if the load file should be sorted ascending by the first
2323    field, this method would return
2324    
2325        sort -k1 -t"\t"
2326    
2327    If the first field is numeric, the method would return
2328    
2329        sort -k1n -t"\t"
2330    
2331    Unfortunately, due to a bug in the C<sort> command, we cannot eliminate duplicate
2332    keys using a sort.
2333    
2334    =over 4
2335    
2336    =item relationName
2337    
2338    Name of the relation to be examined.
2339    
2340    =item
2341    
2342    Returns the sort command to use for sorting the relation, suitable for piping.
2343    
2344    =back
2345    
2346    =cut
2347    #: Return Type $;
2348    sub SortNeeded {
2349        # Get the parameters.
2350        my ($self, $relationName) = @_;
2351        # Declare a descriptor to hold the names of the key fields.
2352        my @keyNames = ();
2353        # Get the relation structure.
2354        my $relationData = $self->_FindRelation($relationName);
2355        # Find out if the relation is a primary entity relation,
2356        # a relationship relation, or a secondary entity relation.
2357        my $entityTable = $self->{_metaData}->{Entities};
2358        my $relationshipTable = $self->{_metaData}->{Relationships};
2359        if (exists $entityTable->{$relationName}) {
2360            # Here we have a primary entity relation.
2361            push @keyNames, "id";
2362        } elsif (exists $relationshipTable->{$relationName}) {
2363            # Here we have a relationship. We sort using the FROM index.
2364            my $relationshipData = $relationshipTable->{$relationName};
2365            my $index = $relationData->{Indexes}->{idxFrom};
2366            push @keyNames, @{$index->{IndexFields}};
2367        } else {
2368            # Here we have a secondary entity relation, so we have a sort on the ID field.
2369            push @keyNames, "id";
2370        }
2371        # Now we parse the key names into sort parameters. First, we prime the return
2372        # string.
2373        my $retVal = "sort -S 1G -T\"$FIG_Config::temp\" -t\"\t\" ";
2374        # Get the relation's field list.
2375        my @fields = @{$relationData->{Fields}};
2376        # Loop through the keys.
2377        for my $keyData (@keyNames) {
2378            # Get the key and the ordering.
2379            my ($keyName, $ordering);
2380            if ($keyData =~ /^([^ ]+) DESC/) {
2381                ($keyName, $ordering) = ($1, "descending");
2382            } else {
2383                ($keyName, $ordering) = ($keyData, "ascending");
2384            }
2385            # Find the key's position and type.
2386            my $fieldSpec;
2387            for (my $i = 0; $i <= $#fields && ! $fieldSpec; $i++) {
2388                my $thisField = $fields[$i];
2389                if ($thisField->{name} eq $keyName) {
2390                    # Get the sort modifier for this field type. The modifier
2391                    # decides whether we're using a character, numeric, or
2392                    # floating-point sort.
2393                    my $modifier = $TypeTable{$thisField->{type}}->{sort};
2394                    # If the index is descending for this field, denote we want
2395                    # to reverse the sort order on this field.
2396                    if ($ordering eq 'descending') {
2397                        $modifier .= "r";
2398                    }
2399                    # Store the position and modifier into the field spec, which
2400                    # will stop the inner loop. Note that the field number is
2401                    # 1-based in the sort command, so we have to increment the
2402                    # index.
2403                    my $realI = $i + 1;
2404                    $fieldSpec = "$realI,$realI$modifier";
2405                }
2406            }
2407            # Add this field to the sort command.
2408            $retVal .= " -k$fieldSpec";
2409        }
2410        # Return the result.
2411        return $retVal;
2412    }
2413    
2414  =head3 GetList  =head3 GetList
2415    
2416  C<< my @dbObjects = $erdb->GetList(\@objectNames, $filterClause, \@params); >>      my @dbObjects = $erdb->GetList(\@objectNames, $filterClause, \@params);
2417    
2418  Return a list of object descriptors for the specified objects as determined by the  Return a list of object descriptors for the specified objects as determined by the
2419  specified filter clause.  specified filter clause.
# Line 1345  Line 2441 
2441  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
2442  particular genus and sorts them by species name.  particular genus and sorts them by species name.
2443    
2444  C<< "Genome(genus) = ? ORDER BY Genome(species)" >>      "Genome(genus) = ? ORDER BY Genome(species)"
2445    
2446  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
2447  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
# Line 1357  Line 2453 
2453    
2454  =item RETURN  =item RETURN
2455    
2456  Returns a list of B<DBObject>s that satisfy the query conditions.  Returns a list of B<ERDBObject>s that satisfy the query conditions.
2457    
2458  =back  =back
2459    
# Line 1380  Line 2476 
2476    
2477  =head3 GetCount  =head3 GetCount
2478    
2479  C<< my $count = $erdb->GetCount(\@objectNames, $filter, \@params); >>      my $count = $erdb->GetCount(\@objectNames, $filter, \@params);
2480    
2481  Return the number of rows found by a specified query. This method would  Return the number of rows found by a specified query. This method would
2482  normally be used to count the records in a single table. For example, in a  normally be used to count the records in a single table. For example, in a
# Line 1431  Line 2527 
2527  sub GetCount {  sub GetCount {
2528      # Get the parameters.      # Get the parameters.
2529      my ($self, $objectNames, $filter, $params) = @_;      my ($self, $objectNames, $filter, $params) = @_;
2530        # Insure the params argument is an array reference if the caller left it off.
2531        if (! defined($params)) {
2532            $params = [];
2533        }
2534      # Declare the return variable.      # Declare the return variable.
2535      my $retVal;      my $retVal;
2536      # Find out if we're counting an entity or a relationship.      # Find out if we're counting an entity or a relationship.
# Line 1469  Line 2569 
2569    
2570  =head3 ComputeObjectSentence  =head3 ComputeObjectSentence
2571    
2572  C<< my $sentence = $erdb->ComputeObjectSentence($objectName); >>      my $sentence = $erdb->ComputeObjectSentence($objectName);
2573    
2574  Check an object name, and if it is a relationship convert it to a relationship sentence.  Check an object name, and if it is a relationship convert it to a relationship sentence.
2575    
# Line 1504  Line 2604 
2604    
2605  =head3 DumpRelations  =head3 DumpRelations
2606    
2607  C<< $erdb->DumpRelations($outputDirectory); >>      $erdb->DumpRelations($outputDirectory);
2608    
2609  Write the contents of all the relations to tab-delimited files in the specified directory.  Write the contents of all the relations to tab-delimited files in the specified directory.
2610  Each file will have the same name as the relation dumped, with an extension of DTX.  Each file will have the same name as the relation dumped, with an extension of DTX.
# Line 1544  Line 2644 
2644      }      }
2645  }  }
2646    
2647    =head3 InsertValue
2648    
2649        $erdb->InsertValue($entityID, $fieldName, $value);
2650    
2651    This method will insert a new value into the database. The value must be one
2652    associated with a secondary relation, since primary values cannot be inserted:
2653    they occur exactly once. Secondary values, on the other hand, can be missing
2654    or multiply-occurring.
2655    
2656    =over 4
2657    
2658    =item entityID
2659    
2660    ID of the object that is to receive the new value.
2661    
2662    =item fieldName
2663    
2664    Field name for the new value-- this includes the entity name, since
2665    field names are of the format I<objectName>C<(>I<fieldName>C<)>.
2666    
2667    =item value
2668    
2669    New value to be put in the field.
2670    
2671    =back
2672    
2673    =cut
2674    
2675    sub InsertValue {
2676        # Get the parameters.
2677        my ($self, $entityID, $fieldName, $value) = @_;
2678        # Parse the entity name and the real field name.
2679        if ($fieldName =~ /^([^(]+)\(([^)]+)\)/) {
2680            my $entityName = $1;
2681            my $fieldTitle = $2;
2682            # Get its descriptor.
2683            if (!$self->IsEntity($entityName)) {
2684                Confess("$entityName is not a valid entity.");
2685            } else {
2686                my $entityData = $self->{_metaData}->{Entities}->{$entityName};
2687                # Find the relation containing this field.
2688                my $fieldHash = $entityData->{Fields};
2689                if (! exists $fieldHash->{$fieldTitle}) {
2690                    Confess("$fieldTitle not found in $entityName.");
2691                } else {
2692                    my $relation = $fieldHash->{$fieldTitle}->{relation};
2693                    if ($relation eq $entityName) {
2694                        Confess("Cannot do InsertValue on primary field $fieldTitle of $entityName.");
2695                    } else {
2696                        # Now we can create an INSERT statement.
2697                        my $dbh = $self->{_dbh};
2698                        my $fixedName = _FixName($fieldTitle);
2699                        my $statement = "INSERT INTO $relation (id, $fixedName) VALUES(?, ?)";
2700                        # Execute the command.
2701                        $dbh->SQL($statement, 0, $entityID, $value);
2702                    }
2703                }
2704            }
2705        } else {
2706            Confess("$fieldName is not a valid field name.");
2707        }
2708    }
2709    
2710  =head3 InsertObject  =head3 InsertObject
2711    
2712  C<< my $ok = $erdb->InsertObject($objectType, \%fieldHash); >>      $erdb->InsertObject($objectType, \%fieldHash);
2713    
2714  Insert an object into the database. The object is defined by a type name and then a hash  Insert an object into the database. The object is defined by a type name and then a hash
2715  of field names to values. Field values in the primary relation are represented by scalars.  of field names to values. Field values in the primary relation are represented by scalars.
# Line 1555  Line 2718 
2718  example, the following line inserts an inactive PEG feature named C<fig|188.1.peg.1> with aliases  example, the following line inserts an inactive PEG feature named C<fig|188.1.peg.1> with aliases
2719  C<ZP_00210270.1> and C<gi|46206278>.  C<ZP_00210270.1> and C<gi|46206278>.
2720    
2721  C<< $erdb->InsertObject('Feature', { id => 'fig|188.1.peg.1', active => 0, feature-type => 'peg', alias => ['ZP_00210270.1', 'gi|46206278']}); >>      $erdb->InsertObject('Feature', { id => 'fig|188.1.peg.1', active => 0, feature-type => 'peg', alias => ['ZP_00210270.1', 'gi|46206278']});
2722    
2723  The next statement inserts a C<HasProperty> relationship between feature C<fig|158879.1.peg.1> and  The next statement inserts a C<HasProperty> relationship between feature C<fig|158879.1.peg.1> and
2724  property C<4> with an evidence URL of C<http://seedu.uchicago.edu/query.cgi?article_id=142>.  property C<4> with an evidence URL of C<http://seedu.uchicago.edu/query.cgi?article_id=142>.
2725    
2726  C<< $erdb->InsertObject('HasProperty', { 'from-link' => 'fig|158879.1.peg.1', 'to-link' => 4, evidence = 'http://seedu.uchicago.edu/query.cgi?article_id=142'}); >>      $erdb->InsertObject('HasProperty', { 'from-link' => 'fig|158879.1.peg.1', 'to-link' => 4, evidence => 'http://seedu.uchicago.edu/query.cgi?article_id=142'});
2727    
2728  =over 4  =over 4
2729    
# Line 1572  Line 2735 
2735    
2736  Hash of field names to values.  Hash of field names to values.
2737    
 =item RETURN  
   
 Returns 1 if successful, 0 if an error occurred.  
   
2738  =back  =back
2739    
2740  =cut  =cut
# Line 1633  Line 2792 
2792                  push @missing, $fieldName;                  push @missing, $fieldName;
2793              }              }
2794          }          }
         # If we are the primary relation, add the new-record flag.  
         if ($relationName eq $newObjectType) {  
             push @valueList, 1;  
             push @fieldNameList, "new_record";  
         }  
2795          # Only proceed if there are no missing fields.          # Only proceed if there are no missing fields.
2796          if (@missing > 0) {          if (@missing > 0) {
2797              Trace("Relation $relationName for $newObjectType skipped due to missing fields: " .              Trace("Relation $relationName for $newObjectType skipped due to missing fields: " .
# Line 1674  Line 2828 
2828                  $retVal = $sth->execute(@parameterList);                  $retVal = $sth->execute(@parameterList);
2829                  if (!$retVal) {                  if (!$retVal) {
2830                      my $errorString = $sth->errstr();                      my $errorString = $sth->errstr();
2831                      Trace("Insert error: $errorString.") if T(0);                      Confess("Error inserting into $relationName: $errorString");
2832                    } else {
2833                        Trace("Insert successful using $parameterList[0].") if T(3);
2834                  }                  }
2835              }              }
2836          }          }
2837      }      }
2838      # Return the success indicator.      # Return a 1 for backward compatability.
2839      return $retVal;      return 1;
2840  }  }
2841    
2842  =head3 LoadTable  =head3 UpdateEntity
2843    
2844  C<< my %results = $erdb->LoadTable($fileName, $relationName, $truncateFlag); >>      $erdb->UpdateEntity($entityName, $id, \%fields);
2845    
2846  Load data from a tab-delimited file into a specified table, optionally re-creating the table  Update the values of an entity. This is an unprotected update, so it should only be
2847  first.  done if the database resides on a database server.
2848    
2849  =over 4  =over 4
2850    
2851  =item fileName  =item entityName
2852    
2853  Name of the file from which the table data should be loaded.  Name of the entity to update. (This is the entity type.)
2854    
2855  =item relationName  =item id
2856    
2857  Name of the relation to be loaded. This is the same as the table name.  ID of the entity to update. If no entity exists with this ID, an error will be thrown.
2858    
2859  =item truncateFlag  =item fields
2860    
2861    Reference to a hash mapping field names to their new values. All of the fields named
2862    must be in the entity's primary relation, and they cannot any of them be the ID field.
2863    
2864    =back
2865    
2866    =cut
2867    
2868    sub UpdateEntity {
2869        # Get the parameters.
2870        my ($self, $entityName, $id, $fields) = @_;
2871        # Get a list of the field names being updated.
2872        my @fieldList = keys %{$fields};
2873        # Verify that the fields exist.
2874        my $checker = $self->GetFieldTable($entityName);
2875        for my $field (@fieldList) {
2876            if ($field eq 'id') {
2877                Confess("Cannot update the ID field for entity $entityName.");
2878            } elsif ($checker->{$field}->{relation} ne $entityName) {
2879                Confess("Cannot find $field in primary relation of $entityName.");
2880            }
2881        }
2882        # Build the SQL statement.
2883        my @sets = ();
2884        my @valueList = ();
2885        for my $field (@fieldList) {
2886            push @sets, _FixName($field) . " = ?";
2887            push @valueList, $fields->{$field};
2888        }
2889        my $command = "UPDATE $entityName SET " . join(", ", @sets) . " WHERE id = ?";
2890        # Add the ID to the list of binding values.
2891        push @valueList, $id;
2892        # Call SQL to do the work.
2893        my $rows = $self->{_dbh}->SQL($command, 0, @valueList);
2894        # Check for errors.
2895        if ($rows == 0) {
2896            Confess("Entity $id of type $entityName not found.");
2897        }
2898    }
2899    
2900    =head3 LoadTable
2901    
2902        my $results = $erdb->LoadTable($fileName, $relationName, %options);
2903    
2904    Load data from a tab-delimited file into a specified table, optionally re-creating the table
2905    first.
2906    
2907    =over 4
2908    
2909    =item fileName
2910    
2911    Name of the file from which the table data should be loaded.
2912    
2913    =item relationName
2914    
2915    Name of the relation to be loaded. This is the same as the table name.
2916    
2917    =item options
2918    
2919  TRUE if the table should be dropped and re-created, else FALSE  A hash of load options.
2920    
2921  =item RETURN  =item RETURN
2922    
# Line 1710  Line 2924 
2924    
2925  =back  =back
2926    
2927    The permissible options are as follows.
2928    
2929    =over 4
2930    
2931    =item truncate
2932    
2933    If TRUE, then the table will be erased before loading.
2934    
2935    =item mode
2936    
2937    Mode in which the load should operate, either C<low_priority> or C<concurrent>.
2938    This option is only applicable to a MySQL database.
2939    
2940    =item partial
2941    
2942    If TRUE, then it is assumed that this is a partial load, and the table will not
2943    be analyzed and compacted at the end.
2944    
2945    =back
2946    
2947  =cut  =cut
2948  sub LoadTable {  sub LoadTable {
2949      # Get the parameters.      # Get the parameters.
2950      my ($self, $fileName, $relationName, $truncateFlag) = @_;      my ($self, $fileName, $relationName, %options) = @_;
2951      # Create the statistical return object.      # Create the statistical return object.
2952      my $retVal = _GetLoadStats();      my $retVal = _GetLoadStats();
2953      # Trace the fact of the load.      # Trace the fact of the load.
# Line 1725  Line 2959 
2959      # Get the relation data.      # Get the relation data.
2960      my $relation = $self->_FindRelation($relationName);      my $relation = $self->_FindRelation($relationName);
2961      # Check the truncation flag.      # Check the truncation flag.
2962      if ($truncateFlag) {      if ($options{truncate}) {
2963          Trace("Creating table $relationName") if T(2);          Trace("Creating table $relationName") if T(2);
2964          # Compute the row count estimate. We take the size of the load file,          # Compute the row count estimate. We take the size of the load file,
2965          # divide it by the estimated row size, and then multiply by 1.5 to          # divide it by the estimated row size, and then multiply by 2 to
2966          # leave extra room. We postulate a minimum row count of 1000 to          # leave extra room. We postulate a minimum row count of 1000 to
2967          # prevent problems with incoming empty load files.          # prevent problems with incoming empty load files.
2968          my $rowSize = $self->EstimateRowSize($relationName);          my $rowSize = $self->EstimateRowSize($relationName);
2969          my $estimate = FIG::max($fileSize * 1.5 / $rowSize, 1000);          my $estimate = $fileSize * 8 / $rowSize;
2970            if ($estimate < 1000) {
2971                $estimate = 1000;
2972            }
2973          # Re-create the table without its index.          # Re-create the table without its index.
2974          $self->CreateTable($relationName, 0, $estimate);          $self->CreateTable($relationName, 0, $estimate);
2975          # If this is a pre-index DBMS, create the index here.          # If this is a pre-index DBMS, create the index here.
# Line 1748  Line 2985 
2985      # Load the table.      # Load the table.
2986      my $rv;      my $rv;
2987      eval {      eval {
2988          $rv = $dbh->load_table(file => $fileName, tbl => $relationName);          $rv = $dbh->load_table(file => $fileName, tbl => $relationName, style => $options{mode});
2989      };      };
2990      if (!defined $rv) {      if (!defined $rv) {
2991          $retVal->AddMessage($@) if ($@);          $retVal->AddMessage($@) if ($@);
2992          $retVal->AddMessage("Table load failed for $relationName using $fileName.");          $retVal->AddMessage("Table load failed for $relationName using $fileName: " . $dbh->error_message);
2993          Trace("Table load failed for $relationName.") if T(1);          Trace("Table load failed for $relationName.") if T(1);
2994      } else {      } else {
2995          # Here we successfully loaded the table.          # Here we successfully loaded the table.
2996          $retVal->Add("tables");          $retVal->Add("tables");
2997          my $size = -s $fileName;          my $size = -s $fileName;
2998          Trace("$size bytes loaded into $relationName.") if T(2);          Trace("$size bytes loaded into $relationName.") if T(2);
2999            $retVal->Add("bytes", $size);
3000          # If we're rebuilding, we need to create the table indexes.          # If we're rebuilding, we need to create the table indexes.
3001          if ($truncateFlag && ! $dbh->{_preIndex}) {          if ($options{truncate}) {
3002                # Indexes are created here for PostGres. For PostGres, indexes are
3003                # best built at the end. For MySQL, the reverse is true.
3004                if (! $dbh->{_preIndex}) {
3005              eval {              eval {
3006                  $self->CreateIndex($relationName);                  $self->CreateIndex($relationName);
3007              };              };
# Line 1768  Line 3009 
3009                  $retVal->AddMessage($@);                  $retVal->AddMessage($@);
3010              }              }
3011          }          }
3012                # The full-text index (if any) is always built last, even for MySQL.
3013                # First we need to see if this table has a full-text index. Only
3014                # primary relations are allowed that privilege.
3015                Trace("Checking for full-text index on $relationName.") if T(2);
3016                if ($self->_IsPrimary($relationName)) {
3017                    $self->CreateSearchIndex($relationName);
3018                }
3019            }
3020      }      }
3021      # Analyze the table to improve performance.      # Analyze the table to improve performance.
3022      $dbh->vacuum_it($relationName);      if (! $options{partial}) {
3023            Trace("Analyzing and compacting $relationName.") if T(3);
3024            $self->Analyze($relationName);
3025        }
3026        Trace("$relationName load completed.") if T(3);
3027      # Return the statistics.      # Return the statistics.
3028      return $retVal;      return $retVal;
3029  }  }
3030    
3031  =head3 GenerateEntity  =head3 Analyze
3032    
3033  C<< my $fieldHash = $erdb->GenerateEntity($id, $type, \%values); >>      $erdb->Analyze($tableName);
3034    
3035  Generate the data for a new entity instance. This method creates a field hash suitable for  Analyze and compact a table in the database. This is useful after a load
3036  passing as a parameter to L</InsertObject>. The ID is specified by the callr, but the rest  to improve the performance of the indexes.
 of the fields are generated using information in the database schema.  
   
 Each data type has a default algorithm for generating random test data. This can be overridden  
 by including a B<DataGen> element in the field. If this happens, the content of the element is  
 executed as a PERL program in the context of this module. The element may make use of a C<$this>  
 variable which contains the field hash as it has been built up to the current point. If any  
 fields are dependent on other fields, the C<pass> attribute can be used to control the order  
 in which the fields are generated. A field with a high data pass number will be generated after  
 a field with a lower one. If any external values are needed, they should be passed in via the  
 optional third parameter, which will be available to the data generation script under the name  
 C<$value>. Several useful utility methods are provided for generating random values, including  
 L</IntGen>, L</StringGen>, L</FloatGen>, and L</DateGen>. Note that dates are stored and generated  
 in the form of a timestamp number rather than a string.  
3037    
3038  =over 4  =over 4
3039    
3040  =item id  =item tableName
3041    
3042  ID to assign to the new entity.  Name of the table to be analyzed and compacted.
3043    
3044  =item type  =back
3045    
3046    =cut
3047    
3048  Type name for the new entity.  sub Analyze {
3049        # Get the parameters.
3050        my ($self, $tableName) = @_;
3051        # Analyze the table.
3052        $self->{_dbh}->vacuum_it($tableName);
3053    }
3054    
3055  =item values  =head3 TruncateTable
3056    
3057  Hash containing additional values that might be needed by the data generation methods (optional).      $erdb->TruncateTable($table);
3058    
3059    Delete all rows from a table quickly. This uses the built-in SQL
3060    C<TRUNCATE> statement, which effectively drops and re-creates a table
3061    with all its settings intact.
3062    
3063    =over 4
3064    
3065    =item table
3066    
3067    Name of the table to be cleared.
3068    
3069  =back  =back
3070    
3071  =cut  =cut
3072    
3073  sub GenerateEntity {  sub TruncateTable {
3074      # Get the parameters.      # Get the parameters.
3075      my ($self, $id, $type, $values) = @_;      my ($self, $table) = @_;
3076      # Create the return hash.      # Get the database handle.
3077      my $this = { id => $id };      my $dbh = $self->{_dbh};
3078      # Get the metadata structure.      # Execute a truncation comment.
3079      my $metadata = $self->{_metaData};      $dbh->SQL("TRUNCATE TABLE $table");
3080      # Get this entity's list of fields.  }
3081      if (!exists $metadata->{Entities}->{$type}) {  
3082          Confess("Unrecognized entity type $type in GenerateEntity.");  
3083      } else {  =head3 CreateSearchIndex
3084          my $entity = $metadata->{Entities}->{$type};  
3085          my $fields = $entity->{Fields};      $erdb->CreateSearchIndex($objectName);
3086          # Generate data from the fields.  
3087          _GenerateFields($this, $fields, $type, $values);  Check for a full-text search index on the specified entity or relationship object, and
3088    if one is required, rebuild it.
3089    
3090    =over 4
3091    
3092    =item objectName
3093    
3094    Name of the entity or relationship to be indexed.
3095    
3096    =back
3097    
3098    =cut
3099    
3100    sub CreateSearchIndex {
3101        # Get the parameters.
3102        my ($self, $objectName) = @_;
3103        # Get the relation's entity/relationship structure.
3104        my $structure = $self->_GetStructure($objectName);
3105        # Get the database handle.
3106        my $dbh = $self->{_dbh};
3107        Trace("Checking for search fields in $objectName.") if T(3);
3108        # Check for a searchable fields list.
3109        if (exists $structure->{searchFields}) {
3110            # Here we know that we need to create a full-text search index.
3111            # Get an SQL-formatted field name list.
3112            my $fields = join(", ", _FixNames(@{$structure->{searchFields}}));
3113            # Create the index. If it already exists, it will be dropped.
3114            $dbh->create_index(tbl => $objectName, idx => "search_idx",
3115                               flds => $fields, kind => 'fulltext');
3116            Trace("Index created for $fields in $objectName.") if T(2);
3117      }      }
3118      # Return the hash created.  }
3119      return $this;  
3120    =head3 DropRelation
3121    
3122        $erdb->DropRelation($relationName);
3123    
3124    Physically drop a relation from the database.
3125    
3126    =over 4
3127    
3128    =item relationName
3129    
3130    Name of the relation to drop. If it does not exist, this method will have
3131    no effect.
3132    
3133    =back
3134    
3135    =cut
3136    
3137    sub DropRelation {
3138        # Get the parameters.
3139        my ($self, $relationName) = @_;
3140        # Get the database handle.
3141        my $dbh = $self->{_dbh};
3142        # Drop the relation. The method used here has no effect if the relation
3143        # does not exist.
3144        Trace("Invoking DB Kernel to drop $relationName.") if T(3);
3145        $dbh->drop_table(tbl => $relationName);
3146    }
3147    
3148    =head3 MatchSqlPattern
3149    
3150        my $matched = ERDB::MatchSqlPattern($value, $pattern);
3151    
3152    Determine whether or not a specified value matches an SQL pattern. An SQL
3153    pattern has two wild card characters: C<%> that matches multiple characters,
3154    and C<_> that matches a single character. These can be escaped using a
3155    backslash (C<\>). We pull this off by converting the SQL pattern to a
3156    PERL regular expression. As per SQL rules, the match is case-insensitive.
3157    
3158    =over 4
3159    
3160    =item value
3161    
3162    Value to be matched against the pattern. Note that an undefined or empty
3163    value will not match anything.
3164    
3165    =item pattern
3166    
3167    SQL pattern against which to match the value. An undefined or empty pattern will
3168    match everything.
3169    
3170    =item RETURN
3171    
3172    Returns TRUE if the value and pattern match, else FALSE.
3173    
3174    =back
3175    
3176    =cut
3177    
3178    sub MatchSqlPattern {
3179        # Get the parameters.
3180        my ($value, $pattern) = @_;
3181        # Declare the return variable.
3182        my $retVal;
3183        # Insure we have a pattern.
3184        if (! defined($pattern) || $pattern eq "") {
3185            $retVal = 1;
3186        } else {
3187            # Break the pattern into pieces around the wildcard characters. Because we
3188            # use parentheses in the split function's delimiter expression, we'll get
3189            # list elements for the delimiters as well as the rest of the string.
3190            my @pieces = split /([_%]|\\[_%])/, $pattern;
3191            # Check some fast special cases.
3192            if ($pattern eq '%') {
3193                # A null pattern matches everything.
3194                $retVal = 1;
3195            } elsif (@pieces == 1) {
3196                # No wildcards, so we have a literal comparison. Note we're case-insensitive.
3197                $retVal = (lc($value) eq lc($pattern));
3198            } elsif (@pieces == 2 && $pieces[1] eq '%') {
3199                # A wildcard at the end, so we have a substring match. This is also case-insensitive.
3200                $retVal = (lc(substr($value, 0, length($pieces[0]))) eq lc($pieces[0]));
3201            } else {
3202                # Okay, we have to do it the hard way. Convert each piece to a PERL pattern.
3203                my $realPattern = "";
3204                for my $piece (@pieces) {
3205                    # Determine the type of piece.
3206                    if ($piece eq "") {
3207                        # Empty pieces are ignored.
3208                    } elsif ($piece eq "%") {
3209                        # Here we have a multi-character wildcard. Note that it can match
3210                        # zero or more characters.
3211                        $realPattern .= ".*"
3212                    } elsif ($piece eq "_") {
3213                        # Here we have a single-character wildcard.
3214                        $realPattern .= ".";
3215                    } elsif ($piece eq "\\%" || $piece eq "\\_") {
3216                        # This is an escape sequence (which is a rare thing, actually).
3217                        $realPattern .= substr($piece, 1, 1);
3218                    } else {
3219                        # Here we have raw text.
3220                        $realPattern .= quotemeta($piece);
3221                    }
3222                }
3223                # Do the match.
3224                $retVal = ($value =~ /^$realPattern$/i ? 1 : 0);
3225            }
3226        }
3227        # Return the result.
3228        return $retVal;
3229  }  }
3230    
3231  =head3 GetEntity  =head3 GetEntity
3232    
3233  C<< my $entityObject = $erdb->GetEntity($entityType, $ID); >>      my $entityObject = $erdb->GetEntity($entityType, $ID);
3234    
3235  Return an object describing the entity instance with a specified ID.  Return an object describing the entity instance with a specified ID.
3236    
# Line 1851  Line 3246 
3246    
3247  =item RETURN  =item RETURN
3248    
3249  Returns a B<DBObject> representing the desired entity instance, or an undefined value if no  Returns a B<ERDBObject> representing the desired entity instance, or an undefined value if no
3250  instance is found with the specified key.  instance is found with the specified key.
3251    
3252  =back  =back
# Line 1865  Line 3260 
3260      my $query = $self->Get([$entityType], "$entityType(id) = ?", [$ID]);      my $query = $self->Get([$entityType], "$entityType(id) = ?", [$ID]);
3261      # Get the first (and only) object.      # Get the first (and only) object.
3262      my $retVal = $query->Fetch();      my $retVal = $query->Fetch();
3263        if (T(3)) {
3264            if ($retVal) {
3265                Trace("Entity $entityType \"$ID\" found.");
3266            } else {
3267                Trace("Entity $entityType \"$ID\" not found.");
3268            }
3269        }
3270      # Return the result.      # Return the result.
3271      return $retVal;      return $retVal;
3272  }  }
3273    
3274    =head3 GetChoices
3275    
3276        my @values = $erdb->GetChoices($entityName, $fieldName);
3277    
3278    Return a list of all the values for the specified field that are represented in the
3279    specified entity.
3280    
3281    Note that if the field is not indexed, then this will be a very slow operation.
3282    
3283    =over 4
3284    
3285    =item entityName
3286    
3287    Name of an entity in the database.
3288    
3289    =item fieldName
3290    
3291    Name of a field belonging to the entity. This is a raw field name without
3292    the standard parenthesized notation used in most calls.
3293    
3294    =item RETURN
3295    
3296    Returns a list of the distinct values for the specified field in the database.
3297    
3298    =back
3299    
3300    =cut
3301    
3302    sub GetChoices {
3303        # Get the parameters.
3304        my ($self, $entityName, $fieldName) = @_;
3305        # Declare the return variable.
3306        my @retVal;
3307        # Get the entity data structure.
3308        my $entityData = $self->_GetStructure($entityName);
3309        # Get the field.
3310        my $fieldHash = $entityData->{Fields};
3311        if (! exists $fieldHash->{$fieldName}) {
3312            Confess("$fieldName not found in $entityName.");
3313        } else {
3314            # Get the name of the relation containing the field.
3315            my $relation = $fieldHash->{$fieldName}->{relation};
3316            # Fix up the field name.
3317            my $realName = _FixName($fieldName);
3318            # Get the database handle.
3319            my $dbh = $self->{_dbh};
3320            # Query the database.
3321            my $results = $dbh->SQL("SELECT DISTINCT $realName FROM $relation");
3322            # Clean the results. They are stored as a list of lists, and we just want the one list.
3323            @retVal = sort map { $_->[0] } @{$results};
3324        }
3325        # Return the result.
3326        return @retVal;
3327    }
3328    
3329  =head3 GetEntityValues  =head3 GetEntityValues
3330    
3331  C<< my @values = $erdb->GetEntityValues($entityType, $ID, \@fields); >>      my @values = $erdb->GetEntityValues($entityType, $ID, \@fields);
3332    
3333  Return a list of values from a specified entity instance.  Return a list of values from a specified entity instance. If the entity instance
3334    does not exist, an empty list is returned.
3335    
3336  =over 4  =over 4
3337    
# Line 1914  Line 3372 
3372    
3373  =head3 GetAll  =head3 GetAll
3374    
3375  C<< my @list = $erdb->GetAll(\@objectNames, $filterClause, \@parameters, \@fields, $count); >>      my @list = $erdb->GetAll(\@objectNames, $filterClause, \@parameters, \@fields, $count);
3376    
3377  Return a list of values taken from the objects returned by a query. The first three  Return a list of values taken from the objects returned by a query. The first three
3378  parameters correspond to the parameters of the L</Get> method. The final parameter is  parameters correspond to the parameters of the L</Get> method. The final parameter is
# Line 1928  Line 3386 
3386  fields specified returns multiple values, they are flattened in with the rest. For  fields specified returns multiple values, they are flattened in with the rest. For
3387  example, the following call will return a list of the features in a particular  example, the following call will return a list of the features in a particular
3388  spreadsheet cell, and each feature will be represented by a list containing the  spreadsheet cell, and each feature will be represented by a list containing the
3389  feature ID followed by all of its aliases.  feature ID followed by all of its essentiality determinations.
3390    
3391  C<< $query = $erdb->Get(['ContainsFeature', 'Feature'], "ContainsFeature(from-link) = ?", [$ssCellID], ['Feature(id)', 'Feature(alias)']); >>      @query = $erdb->Get(['ContainsFeature', 'Feature'], "ContainsFeature(from-link) = ?", [$ssCellID], ['Feature(id)', 'Feature(essential)']);
3392    
3393  =over 4  =over 4
3394    
# Line 2005  Line 3463 
3463      return @retVal;      return @retVal;
3464  }  }
3465    
3466    =head3 Exists
3467    
3468        my $found = $sprout->Exists($entityName, $entityID);
3469    
3470    Return TRUE if an entity exists, else FALSE.
3471    
3472    =over 4
3473    
3474    =item entityName
3475    
3476    Name of the entity type (e.g. C<Feature>) relevant to the existence check.
3477    
3478    =item entityID
3479    
3480    ID of the entity instance whose existence is to be checked.
3481    
3482    =item RETURN
3483    
3484    Returns TRUE if the entity instance exists, else FALSE.
3485    
3486    =back
3487    
3488    =cut
3489    #: Return Type $;
3490    sub Exists {
3491        # Get the parameters.
3492        my ($self, $entityName, $entityID) = @_;
3493        # Check for the entity instance.
3494        Trace("Checking existence of $entityName with ID=$entityID.") if T(4);
3495        my $testInstance = $self->GetEntity($entityName, $entityID);
3496        # Return an existence indicator.
3497        my $retVal = ($testInstance ? 1 : 0);
3498        return $retVal;
3499    }
3500    
3501  =head3 EstimateRowSize  =head3 EstimateRowSize
3502    
3503  C<< my $rowSize = $erdb->EstimateRowSize($relName); >>      my $rowSize = $erdb->EstimateRowSize($relName);
3504    
3505  Estimate the row size of the specified relation. The estimated row size is computed by adding  Estimate the row size of the specified relation. The estimated row size is computed by adding
3506  up the average length for each data type.  up the average length for each data type.
# Line 2018  Line 3511 
3511    
3512  Name of the relation whose estimated row size is desired.  Name of the relation whose estimated row size is desired.
3513    
3514  =item RETURN  =item RETURN
3515    
3516    Returns an estimate of the row size for the specified relation.
3517    
3518    =back
3519    
3520    =cut
3521    #: Return Type $;
3522    sub EstimateRowSize {
3523        # Get the parameters.
3524        my ($self, $relName) = @_;
3525        # Declare the return variable.
3526        my $retVal = 0;
3527        # Find the relation descriptor.
3528        my $relation = $self->_FindRelation($relName);
3529        # Get the list of fields.
3530        for my $fieldData (@{$relation->{Fields}}) {
3531            # Get the field type and add its length.
3532            my $fieldLen = $TypeTable{$fieldData->{type}}->{avgLen};
3533            $retVal += $fieldLen;
3534        }
3535        # Return the result.
3536        return $retVal;
3537    }
3538    
3539    =head3 GetFieldTable
3540    
3541        my $fieldHash = $self->GetFieldTable($objectnName);
3542    
3543    Get the field structure for a specified entity or relationship.
3544    
3545    =over 4
3546    
3547    =item objectName
3548    
3549    Name of the desired entity or relationship.
3550    
3551    =item RETURN
3552    
3553    The table containing the field descriptors for the specified object.
3554    
3555    =back
3556    
3557    =cut
3558    
3559    sub GetFieldTable {
3560        # Get the parameters.
3561        my ($self, $objectName) = @_;
3562        # Get the descriptor from the metadata.
3563        my $objectData = $self->_GetStructure($objectName);
3564        # Return the object's field table.
3565        return $objectData->{Fields};
3566    }
3567    
3568    =head3 SplitKeywords
3569    
3570        my @keywords = ERDB::SplitKeywords($keywordString);
3571    
3572    This method returns a list of the positive keywords in the specified
3573    keyword string. All of the operators will have been stripped off,
3574    and if the keyword is preceded by a minus operator (C<->), it will
3575    not be in the list returned. The idea here is to get a list of the
3576    keywords the user wants to see. The list will be processed to remove
3577    duplicates.
3578    
3579    It is possible to create a string that confuses this method. For example
3580    
3581        frog toad -frog
3582    
3583    would return both C<frog> and C<toad>. If this is a problem we can deal
3584    with it later.
3585    
3586    =over 4
3587    
3588    =item keywordString
3589    
3590    The keyword string to be parsed.
3591    
3592    =item RETURN
3593    
3594    Returns a list of the words in the keyword string the user wants to
3595    see.
3596    
3597    =back
3598    
3599    =cut
3600    
3601    sub SplitKeywords {
3602        # Get the parameters.
3603        my ($keywordString) = @_;
3604        # Make a safety copy of the string. (This helps during debugging.)
3605        my $workString = $keywordString;
3606        # Convert operators we don't care about to spaces.
3607        $workString =~ tr/+"()<>/ /;
3608        # Split the rest of the string along space boundaries. Note that we
3609        # eliminate any words that are zero length or begin with a minus sign.
3610        my @wordList = grep { $_ && substr($_, 0, 1) ne "-" } split /\s+/, $workString;
3611        # Use a hash to remove duplicates.
3612        my %words = map { $_ => 1 } @wordList;
3613        # Return the result.
3614        return sort keys %words;
3615    }
3616    
3617    =head3 ValidateFieldName
3618    
3619        my $okFlag = ERDB::ValidateFieldName($fieldName);
3620    
3621    Return TRUE if the specified field name is valid, else FALSE. Valid field names must
3622    be hyphenated words subject to certain restrictions.
3623    
3624    =over 4
3625    
3626    =item fieldName
3627    
3628    Field name to be validated.
3629    
3630    =item RETURN
3631    
3632    Returns TRUE if the field name is valid, else FALSE.
3633    
3634    =back
3635    
3636    =cut
3637    
3638    sub ValidateFieldName {
3639        # Get the parameters.
3640        my ($fieldName) = @_;
3641        # Declare the return variable. The field name is valid until we hear
3642        # differently.
3643        my $retVal = 1;
3644        # Compute the maximum name length.
3645        my $maxLen = $TypeTable{'name-string'}->{maxLen};
3646        # Look for bad stuff in the name.
3647        if ($fieldName =~ /--/) {
3648            # Here we have a doubled minus sign.
3649            Trace("Field name $fieldName has a doubled hyphen.") if T(1);
3650            $retVal = 0;
3651        } elsif ($fieldName !~ /^[A-Za-z]/) {
3652            # Here the field name is missing the initial letter.
3653            Trace("Field name $fieldName does not begin with a letter.") if T(1);
3654            $retVal = 0;
3655        } elsif (length($fieldName) > $maxLen) {
3656            # Here the field name is too long.
3657            Trace("Maximum field name length is $maxLen. Field name must be truncated to " . substr($fieldName,0, $maxLen) . ".");
3658        } else {
3659            # Strip out the minus signs. Everything remaining must be a letter,
3660            # underscore, or digit.
3661            my $strippedName = $fieldName;
3662            $strippedName =~ s/-//g;
3663            if ($strippedName !~ /^(\w|\d)+$/) {
3664                Trace("Field name $fieldName contains illegal characters.") if T(1);
3665                $retVal = 0;
3666            }
3667        }
3668        # Return the result.
3669        return $retVal;
3670    }
3671    
3672    =head3 ReadMetaXML
3673    
3674        my $rawMetaData = ERDB::ReadDBD($fileName);
3675    
3676    This method reads a raw database definition XML file and returns it.
3677    Normally, the metadata used by the ERDB system has been processed and
3678    modified to make it easier to load and retrieve the data; however,
3679    this method can be used to get the data in its raw form.
3680    
3681    =over 4
3682    
3683    =item fileName
3684    
3685    Name of the XML file to read.
3686    
3687    =item RETURN
3688    
3689    Returns a hash reference containing the raw XML data from the specified file.
3690    
3691    =back
3692    
3693    =cut
3694    
3695    sub ReadMetaXML {
3696        # Get the parameters.
3697        my ($fileName) = @_;
3698        # Read the XML.
3699        my $retVal = XML::Simple::XMLin($fileName, %XmlOptions, %XmlInOpts);
3700        Trace("XML metadata loaded from file $fileName.") if T(1);
3701        # Return the result.
3702        return $retVal;
3703    }
3704    
3705    =head3 GetEntityFieldHash
3706    
3707        my $fieldHashRef = ERDB::GetEntityFieldHash($structure, $entityName);
3708    
3709    Get the field hash of the named entity in the specified raw XML structure.
3710    The field hash may not exist, in which case we need to create it.
3711    
3712    =over 4
3713    
3714    =item structure
3715    
3716    Raw XML structure defininng the database. This is not the run-time XML used by
3717    an ERDB object, since that has all sorts of optimizations built-in.
3718    
3719    =item entityName
3720    
3721    Name of the entity whose field structure is desired.
3722    
3723    =item RETURN
3724    
3725    Returns the field hash used to define the entity's fields.
3726    
3727    =back
3728    
3729    =cut
3730    
3731    sub GetEntityFieldHash {
3732        # Get the parameters.
3733        my ($structure, $entityName) = @_;
3734        # Get the entity structure.
3735        my $entityData = $structure->{Entities}->{$entityName};
3736        # Look for a field structure.
3737        my $retVal = $entityData->{Fields};
3738        # If it doesn't exist, create it.
3739        if (! defined($retVal)) {
3740            $entityData->{Fields} = {};
3741            $retVal = $entityData->{Fields};
3742        }
3743        # Return the result.
3744        return $retVal;
3745    }
3746    
3747    =head3 WriteMetaXML
3748    
3749        ERDB::WriteMetaXML($structure, $fileName);
3750    
3751    Write the metadata XML to a file. This method is the reverse of L</ReadMetaXML>, and is
3752    used to update the database definition. It must be used with care, however, since it
3753    will only work on a raw structure, not on the processed structure created by an ERDB
3754    constructor.
3755    
3756    =over 4
3757    
3758    =item structure
3759    
3760    XML structure to be written to the file.
3761    
3762    =item fileName
3763    
3764    Name of the output file to which the updated XML should be stored.
3765    
3766    =back
3767    
3768    =cut
3769    
3770    sub WriteMetaXML {
3771        # Get the parameters.
3772        my ($structure, $fileName) = @_;
3773        # Compute the output.
3774        my $fileString = XML::Simple::XMLout($structure, %XmlOptions, %XmlOutOpts);
3775        # Write it to the file.
3776        my $xmlOut = Open(undef, ">$fileName");
3777        print $xmlOut $fileString;
3778    }
3779    
3780    
3781    =head3 HTMLNote
3782    
3783    Convert a note or comment to HTML by replacing some bulletin-board codes with HTML. The codes
3784    supported are C<[b]> for B<bold>, C<[i]> for I<italics>, and C<[p]> for a new paragraph.
3785    Except for C<[p]>, all the codes are closed by slash-codes. So, for
3786    example, C<[b]Feature[/b]> displays the string C<Feature> in boldface.
3787    
3788        my $realHtml = ERDB::HTMLNote($dataString);
3789    
3790    =over 4
3791    
3792    =item dataString
3793    
3794    String to convert to HTML.
3795    
3796    =item RETURN
3797    
3798    An HTML string derived from the input string.
3799    
3800    =back
3801    
3802    =cut
3803    
3804    sub HTMLNote {
3805        # Get the parameter.
3806        my ($dataString) = @_;
3807        # HTML-escape the text.
3808        my $retVal = CGI::escapeHTML($dataString);
3809        # Substitute the bulletin board codes.
3810        $retVal =~ s!\[(/?[bi])\]!<$1>!g;
3811        $retVal =~ s!\[p\]!</p><p>!g;
3812        $retVal =~ s!\[link\s+([^\]]+)\]!<a href="$1">!g;
3813        $retVal =~ s!\[/link\]!</a>!g;
3814        # Return the result.
3815        return $retVal;
3816    }
3817    
3818    =head3 WikiNote
3819    
3820    Convert a note or comment to Wiki text by replacing some bulletin-board codes with HTML. The codes
3821    supported are C<[b]> for B<bold>, C<[i]> for I<italics>, and C<[p]> for a new paragraph.
3822    Except for C<[p]>, all the codes are closed by slash-codes. So, for
3823    example, C<[b]Feature[/b]> displays the string C<Feature> in boldface.
3824    
3825        my $wikiText = ERDB::WikiNote($dataString);
3826    
3827    =over 4
3828    
3829    =item dataString
3830    
3831    String to convert to Wiki text.
3832    
3833    =item RETURN
3834    
3835    An Wiki text string derived from the input string.
3836    
3837    =back
3838    
3839    =cut
3840    
3841    sub WikiNote {
3842        # Get the parameter.
3843        my ($dataString) = @_;
3844        # HTML-escape the text.
3845        my $retVal = CGI::escapeHTML($dataString);
3846        # Substitute the bulletin board codes.
3847        my $italic = WikiTools::ItalicCode();
3848        $retVal =~ s/\[\/?i\]/$italic/g;
3849        my $bold = WikiTools::BoldCode();
3850        $retVal =~ s/\[\/?b\]/$bold/g;
3851        # Paragraph breaks are the same no matter which Wiki you're using.
3852        $retVal =~ s!\[p\]!\n\n!g;
3853        # Now we do the links, which are complicated by the need to know two
3854        # things: the target URL and the text.
3855        while ($retVal =~ /\[link\s+([^\]]+)\]([^\[]+)\[\/link\]/g) {
3856            # Replace the matched string with the Wiki markup for links. Note that
3857            # $-[0] is the starting position of the match for the entire expression,
3858            # and $+[0] is past the ending position.
3859            substr $retVal, $-[0], $+[0] - $-[0], WikiTools::LinkMarkup($1, $2);
3860        }
3861        # Return the result.
3862        return $retVal;
3863    }
3864    
3865    =head3 BeginTran
3866    
3867        $erdb->BeginTran();
3868    
3869    Start a database transaction.
3870    
3871    =cut
3872    
3873    sub BeginTran {
3874        my ($self) = @_;
3875        $self->{_dbh}->begin_tran();
3876    
3877    }
3878    
3879    =head3 CommitTran
3880    
3881        $erdb->CommitTran();
3882    
3883    Commit an active database transaction.
3884    
3885    =cut
3886    
3887    sub CommitTran {
3888        my ($self) = @_;
3889        $self->{_dbh}->commit_tran();
3890    }
3891    
3892    =head3 RollbackTran
3893    
3894        $erdb->RollbackTran();
3895    
3896    Roll back an active database transaction.
3897    
3898    =cut
3899    
3900    sub RollbackTran {
3901        my ($self) = @_;
3902        $self->{_dbh}->roll_tran();
3903    }
3904    
3905    =head3 UpdateField
3906    
3907        my $count = $erdb->UpdateField($objectNames, $fieldName, $oldValue, $newValue, $filter, $parms);
3908    
3909    Update all occurrences of a specific field value to a new value. The number of rows changed will be
3910    returned.
3911    
3912    =over 4
3913    
3914    =item fieldName
3915    
3916  Returns an estimate of the row size for the specified relation.  Name of the field in standard I<objectName>C<(>I<fieldName>C<)> format.
3917    
3918  =back  =item oldValue
3919    
3920  =cut  Value to be modified. All occurrences of this value in the named field will be replaced by the
3921  #: Return Type $;  new value.
 sub EstimateRowSize {  
     # Get the parameters.  
     my ($self, $relName) = @_;  
     # Declare the return variable.  
     my $retVal = 0;  
     # Find the relation descriptor.  
     my $relation = $self->_FindRelation($relName);  
     # Get the list of fields.  
     for my $fieldData (@{$relation->{Fields}}) {  
         # Get the field type and add its length.  
         my $fieldLen = $TypeTable{$fieldData->{type}}->{avgLen};  
         $retVal += $fieldLen;  
     }  
     # Return the result.  
     return $retVal;  
 }  
3922    
3923  =head3 GetFieldTable  =item newValue
3924    
3925  C<< my $fieldHash = $self->GetFieldTable($objectnName); >>  New value to be substituted for the old value when it's found.
3926    
3927  Get the field structure for a specified entity or relationship.  =item filter
3928    
3929  =over 4  A standard ERDB filter clause (see L</Get>). The filter will be applied before any substitutions take place.
3930    
3931  =item objectName  =item parms
3932    
3933  Name of the desired entity or relationship.  Reference to a list of parameter values in the filter.
3934    
3935  =item RETURN  =item RETURN
3936    
3937  The table containing the field descriptors for the specified object.  Returns the number of rows modified.
3938    
3939  =back  =back
3940    
3941  =cut  =cut
3942    
3943  sub GetFieldTable {  sub UpdateField {
3944      # Get the parameters.      # Get the parameters.
3945      my ($self, $objectName) = @_;      my ($self, $fieldName, $oldValue, $newValue, $filter, $parms) = @_;
3946      # Get the descriptor from the metadata.      # Get the object and field names from the field name parameter.
3947      my $objectData = $self->_GetStructure($objectName);      $fieldName =~ /^([^(]+)\(([^)]+)\)/;
3948      # Return the object's field table.      my $objectName = $1;
3949      return $objectData->{Fields};      my $realFieldName = _FixName($2);
3950        # Add the old value to the filter. Note we allow the possibility that no
3951        # filter was specified.
3952        my $realFilter = "$fieldName = ?";
3953        if ($filter) {
3954            $realFilter .= " AND $filter";
3955        }
3956        # Format the query filter.
3957        my ($suffix, $mappedNameListRef, $mappedNameHashRef) =
3958            $self->_SetupSQL([$objectName], $realFilter);
3959        # Create the query. Since there is only one object name, the mapped-name data is not
3960        # necessary. Neither is the FROM clause.
3961        $suffix =~ s/^FROM.+WHERE\s+//;
3962        # Create the update statement.
3963        my $command = "UPDATE $objectName SET $realFieldName = ? WHERE $suffix";
3964        # Get the database handle.
3965        my $dbh = $self->{_dbh};
3966        # Add the old and new values to the parameter list. Note we allow the possibility that
3967        # there are no user-supplied parameters.
3968        my @params = ($newValue, $oldValue);
3969        if (defined $parms) {
3970            push @params, @{$parms};
3971        }
3972        # Execute the update.
3973        my $retVal = $dbh->SQL($command, 0, @params);
3974        # Make the funky zero a real zero.
3975        if ($retVal == 0) {
3976            $retVal = 0;
3977        }
3978        # Return the result.
3979        return $retVal;
3980  }  }
3981    
3982    
3983  =head2 Data Mining Methods  =head2 Data Mining Methods
3984    
3985  =head3 GetUsefulCrossValues  =head3 GetUsefulCrossValues
3986    
3987  C<< my @attrNames = $sprout->GetUsefulCrossValues($sourceEntity, $relationship); >>      my @attrNames = $sprout->GetUsefulCrossValues($sourceEntity, $relationship);
3988    
3989  Return a list of the useful attributes that would be returned by a B<Cross> call  Return a list of the useful attributes that would be returned by a B<Cross> call
3990  from an entity of the source entity type through the specified relationship. This  from an entity of the source entity type through the specified relationship. This
# Line 2137  Line 4045 
4045    
4046  =head3 FindColumn  =head3 FindColumn
4047    
4048  C<< my $colIndex = ERDB::FindColumn($headerLine, $columnIdentifier); >>      my $colIndex = ERDB::FindColumn($headerLine, $columnIdentifier);
4049    
4050  Return the location a desired column in a data mining header line. The data  Return the location a desired column in a data mining header line. The data
4051  mining header line is a tab-separated list of column names. The column  mining header line is a tab-separated list of column names. The column
# Line 2195  Line 4103 
4103    
4104  =head3 ParseColumns  =head3 ParseColumns
4105    
4106  C<< my @columns = ERDB->ParseColumns($line); >>      my @columns = ERDB::ParseColumns($line);
4107    
4108  Convert the specified data line to a list of columns.  Convert the specified data line to a list of columns.
4109    
# Line 2216  Line 4124 
4124    
4125  sub ParseColumns {  sub ParseColumns {
4126      # Get the parameters.      # Get the parameters.
4127      my ($self, $line) = @_;      my ($line) = @_;
4128      # Chop off the line-end.      # Chop off the line-end.
4129      chomp $line;      chomp $line;
4130      # Split it into a list.      # Split it into a list.
# Line 2225  Line 4133 
4133      return @retVal;      return @retVal;
4134  }  }
4135    
4136    =head2 Virtual Methods
4137    
4138    =head3 _CreatePPOIndex
4139    
4140        my $index = ERDB::_CreatePPOIndex($indexObject);
4141    
4142    Convert the XML for an ERDB index to the XML structure for a PPO
4143    index.
4144    
4145    =over 4
4146    
4147    =item indexObject
4148    
4149    ERDB XML structure for an index.
4150    
4151    =item RETURN
4152    
4153    PPO XML structure for the same index.
4154    
4155    =back
4156    
4157    =cut
4158    
4159    sub _CreatePPOIndex {
4160        # Get the parameters.
4161        my ($indexObject) = @_;
4162        # The incoming index contains a list of the index fields in the IndexFields
4163        # member. We loop through it to create the index tags.
4164        my @fields = map { { label => _FixName($_->{name}) } } @{$indexObject->{IndexFields}};
4165        # Wrap the fields in attribute tags.
4166        my $retVal = { attribute => \@fields };
4167        # Return the result.
4168        return $retVal;
4169    }
4170    
4171    =head3 _CreatePPOField
4172    
4173        my $fieldXML = ERDB::_CreatePPOField($fieldName, $fieldObject);
4174    
4175    Convert the ERDB XML structure for a field to a PPO scalar XML structure.
4176    
4177    =over 4
4178    
4179    =item fieldName
4180    
4181    Name of the scalar field.
4182    
4183    =item fieldObject
4184    
4185    ERDB XML structure describing the field.
4186    
4187    =item RETURN
4188    
4189    Returns a PPO XML structure for the same field.
4190    
4191    =back
4192    
4193    =cut
4194    
4195    sub _CreatePPOField {
4196        # Get the parameters.
4197        my ($fieldName, $fieldObject) = @_;
4198        # Get the field type.
4199        my $type = $TypeTable{$fieldObject->{type}}->{sqlType};
4200        # Fix up the field name.
4201        $fieldName = _FixName($fieldName);
4202        # Build the scalar tag.
4203        my $retVal = { label => $fieldName, type => $type };
4204        # Return the result.
4205        return $retVal;
4206    }
4207    
4208    =head3 CleanKeywords
4209    
4210        my $cleanedString = $erdb->CleanKeywords($searchExpression);
4211    
4212    Clean up a search expression or keyword list. This is a virtual method that may
4213    be overridden by the subclass. The base-class method removes extra spaces
4214    and converts everything to lower case.
4215    
4216    =over 4
4217    
4218    =item searchExpression
4219    
4220    Search expression or keyword list to clean. Note that a search expression may
4221    contain boolean operators which need to be preserved. This includes leading
4222    minus signs.
4223    
4224    =item RETURN
4225    
4226    Cleaned expression or keyword list.
4227    
4228    =back
4229    
4230    =cut
4231    
4232    sub CleanKeywords {
4233        # Get the parameters.
4234        my ($self, $searchExpression) = @_;
4235        # Lower-case the expression and copy it into the return variable. Note that we insure we
4236        # don't accidentally end up with an undefined value.
4237        my $retVal = lc($searchExpression || "");
4238        # Remove extra spaces.
4239        $retVal =~ s/\s+/ /g;
4240        $retVal =~ s/(^\s+)|(\s+$)//g;
4241        # Return the result.
4242        return $retVal;
4243    }
4244    
4245    =head3 GetSourceObject
4246    
4247        my $source = $erdb->GetSourceObject($entityName);
4248    
4249    Return the object to be used in loading special attributes of the specified entity. The
4250    algorithm for loading special attributes is stored in the C<DataGen> elements of the
4251    XML
4252    
4253  =head2 Internal Utility Methods  =head2 Internal Utility Methods
4254    
4255  =head3 SetupSQL  =head3 _RelationMap
4256    
4257        my @relationMap = _RelationMap($mappedNameHashRef, $mappedNameListRef);
4258    
4259    Create the relation map for an SQL query. The relation map is used by B<ERDBObject>
4260    to determine how to interpret the results of the query.
4261    
4262    =over 4
4263    
4264    =item mappedNameHashRef
4265    
4266    Reference to a hash that maps modified object names to real object names.
4267    
4268    =item mappedNameListRef
4269    
4270    Reference to a list of modified object names in the order they appear in the
4271    SELECT list.
4272    
4273    =item RETURN
4274    
4275    Returns a list of 2-tuples. Each tuple consists of an object name as used in the
4276    query followed by the actual name of that object. This enables the B<ERDBObject> to
4277    determine the order of the tables in the query and which object name belongs to each
4278    mapped object name. Most of the time these two values are the same; however, if a
4279    relation occurs twice in the query, the relation name in the field list and WHERE
4280    clause will use a mapped name (generally the actual relation name with a numeric
4281    suffix) that does not match the actual relation name.
4282    
4283    =back
4284    
4285    =cut
4286    
4287    sub _RelationMap {
4288        # Get the parameters.
4289        my ($mappedNameHashRef, $mappedNameListRef) = @_;
4290        # Declare the return variable.
4291        my @retVal = ();
4292        # Build the map.
4293        for my $mappedName (@{$mappedNameListRef}) {
4294            push @retVal, [$mappedName, $mappedNameHashRef->{$mappedName}];
4295        }
4296        # Return it.
4297        return @retVal;
4298    }
4299    
4300    
4301    =head3 _SetupSQL
4302    
4303  Process a list of object names and a filter clause so that they can be used to  Process a list of object names and a filter clause so that they can be used to
4304  build an SQL statement. This method takes in a reference to a list of object names  build an SQL statement. This method takes in a reference to a list of object names
# Line 2247  Line 4318 
4318  A string containing the WHERE clause for the query (without the C<WHERE>) and also  A string containing the WHERE clause for the query (without the C<WHERE>) and also
4319  optionally the C<ORDER BY> and C<LIMIT> clauses.  optionally the C<ORDER BY> and C<LIMIT> clauses.
4320    
4321    =item matchClause
4322    
4323    An optional full-text search clause. If specified, it will be inserted at the
4324    front of the WHERE clause. It should already be SQL-formatted; that is, the
4325    field names should be in the form I<table>C<.>I<fieldName>.
4326    
4327  =item RETURN  =item RETURN
4328    
4329  Returns a three-element list. The first element is the SQL statement suffix, beginning  Returns a three-element list. The first element is the SQL statement suffix, beginning
# Line 2259  Line 4336 
4336  =cut  =cut
4337    
4338  sub _SetupSQL {  sub _SetupSQL {
4339      my ($self, $objectNames, $filterClause) = @_;      my ($self, $objectNames, $filterClause, $matchClause) = @_;
4340      # Adjust the list of object names to account for multiple occurrences of the      # Adjust the list of object names to account for multiple occurrences of the
4341      # same object. We start with a hash table keyed on object name that will      # same object. We start with a hash table keyed on object name that will
4342      # return the object suffix. The first time an object is encountered it will      # return the object suffix. The first time an object is encountered it will
# Line 2308  Line 4385 
4385      # FROM name1, name2, ... nameN      # FROM name1, name2, ... nameN
4386      #      #
4387      my $suffix = "FROM " . join(', ', @fromList);      my $suffix = "FROM " . join(', ', @fromList);
4388        # Now for the WHERE. First, we need a place for the filter string.
4389        my $filterString = "";
4390        # We will also keep a list of conditions to add to the WHERE clause in order to link
4391        # entities and relationships as well as primary relations to secondary ones.
4392        my @joinWhere = ();
4393      # Check for a filter clause.      # Check for a filter clause.
4394      if ($filterClause) {      if ($filterClause) {
4395          # Here we have one, so we convert its field names and add it to the query. First,          # Here we have one, so we convert its field names and add it to the query. First,
4396          # We create a copy of the filter string we can work with.          # We create a copy of the filter string we can work with.
4397          my $filterString = $filterClause;          $filterString = $filterClause;
4398          # Next, we sort the object names by length. This helps protect us from finding          # Next, we sort the object names by length. This helps protect us from finding
4399          # object names inside other object names when we're doing our search and replace.          # object names inside other object names when we're doing our search and replace.
4400          my @sortedNames = sort { length($b) - length($a) } @mappedNameList;          my @sortedNames = sort { length($b) - length($a) } @mappedNameList;
         # We will also keep a list of conditions to add to the WHERE clause in order to link  
         # entities and relationships as well as primary relations to secondary ones.  
         my @joinWhere = ();  
4401          # The final preparatory step is to create a hash table of relation names. The          # The final preparatory step is to create a hash table of relation names. The
4402          # table begins with the relation names already in the SELECT command. We may          # table begins with the relation names already in the SELECT command. We may
4403          # need to add relations later if there is filtering on a field in a secondary          # need to add relations later if there is filtering on a field in a secondary
# Line 2386  Line 4465 
4465                  }                  }
4466              }              }
4467          }          }
4468        }
4469          # The next step is to join the objects together. We only need to do this if there          # The next step is to join the objects together. We only need to do this if there
4470          # is more than one object in the object list. We start with the first object and          # is more than one object in the object list. We start with the first object and
4471          # run through the objects after it. Note also that we make a safety copy of the          # run through the objects after it. Note also that we make a safety copy of the
4472          # list before running through it.      # list before running through it, because we shift off the first object before
4473        # processing the rest.
4474          my @mappedObjectList = @mappedNameList;          my @mappedObjectList = @mappedNameList;
4475          my $lastMappedObject = shift @mappedObjectList;          my $lastMappedObject = shift @mappedObjectList;
4476          # Get the join table.          # Get the join table.
# Line 2418  Line 4499 
4499          # here is we want the filter clause to be empty if there's no WHERE filter.          # here is we want the filter clause to be empty if there's no WHERE filter.
4500          # We'll put the ORDER BY / LIMIT clauses in the following variable.          # We'll put the ORDER BY / LIMIT clauses in the following variable.
4501          my $orderClause = "";          my $orderClause = "";
4502        # This is only necessary if we have a filter string in which the ORDER BY
4503        # and LIMIT clauses can live.
4504        if ($filterString) {
4505          # Locate the ORDER BY or LIMIT verbs (if any). We use a non-greedy          # Locate the ORDER BY or LIMIT verbs (if any). We use a non-greedy
4506          # operator so that we find the first occurrence of either verb.          # operator so that we find the first occurrence of either verb.
4507          if ($filterString =~ m/^(.*?)\s*(ORDER BY|LIMIT)/g) {          if ($filterString =~ m/^(.*?)\s*(ORDER BY|LIMIT)/g) {
# Line 2426  Line 4510 
4510              $orderClause = $2 . substr($filterString, $pos);              $orderClause = $2 . substr($filterString, $pos);
4511              $filterString = $1;              $filterString = $1;
4512          }          }
4513          # Add the filter and the join clauses (if any) to the SELECT command.      }
4514        # All the things that are supposed to be in the WHERE clause of the
4515        # SELECT command need to be put into @joinWhere so we can string them
4516        # together. We begin with the match clause. This is important,
4517        # because the match clause's parameter mark must precede any parameter
4518        # marks in the filter string.
4519        if ($matchClause) {
4520            push @joinWhere, $matchClause;
4521        }
4522        # Add the filter string. We put it in parentheses to avoid operator
4523        # precedence problems with the match clause or the joins.
4524          if ($filterString) {          if ($filterString) {
4525              Trace("Filter string is \"$filterString\".") if T(4);              Trace("Filter string is \"$filterString\".") if T(4);
4526              push @joinWhere, "($filterString)";              push @joinWhere, "($filterString)";
4527          }          }
4528        # String it all together into a big filter clause.
4529          if (@joinWhere) {          if (@joinWhere) {
4530              $suffix .= " WHERE " . join(' AND ', @joinWhere);              $suffix .= " WHERE " . join(' AND ', @joinWhere);
4531          }          }
4532          # Add the sort or limit clause (if any) to the SELECT command.      # Add the sort or limit clause (if any).
4533          if ($orderClause) {          if ($orderClause) {
4534              $suffix .= " $orderClause";              $suffix .= " $orderClause";
4535          }          }
     }  
4536      # Return the suffix, the mapped name list, and the mapped name hash.      # Return the suffix, the mapped name list, and the mapped name hash.
4537      return ($suffix, \@mappedNameList, \%mappedNameHash);      return ($suffix, \@mappedNameList, \%mappedNameHash);
4538  }  }
4539    
4540  =head3 GetStatementHandle  =head3 _GetStatementHandle
4541    
4542  This method will prepare and execute an SQL query, returning the statement handle.  This method will prepare and execute an SQL query, returning the statement handle.
4543  The main reason for doing this here is so that everybody who does SQL queries gets  The main reason for doing this here is so that everybody who does SQL queries gets
# Line 2473  Line 4567 
4567  sub _GetStatementHandle {  sub _GetStatementHandle {
4568      # Get the parameters.      # Get the parameters.
4569      my ($self, $command, $params) = @_;      my ($self, $command, $params) = @_;
4570        Confess("Invalid parameter list.") if (! defined($params) || ref($params) ne 'ARRAY');
4571      # Trace the query.      # Trace the query.
4572      Trace("SQL query: $command") if T(SQL => 3);      Trace("SQL query: $command") if T(SQL => 3);
4573      Trace("PARMS: '" . (join "', '", @{$params}) . "'") if (T(SQL => 4) && (@{$params} > 0));      Trace("PARMS: '" . (join "', '", @{$params}) . "'") if (T(SQL => 4) && (@{$params} > 0));
# Line 2481  Line 4576 
4576      # Prepare the command.      # Prepare the command.
4577      my $sth = $dbh->prepare_command($command);      my $sth = $dbh->prepare_command($command);
4578      # Execute it with the parameters bound in.      # Execute it with the parameters bound in.
4579      $sth->execute(@{$params}) || Confess("SELECT error" . $sth->errstr());      $sth->execute(@{$params}) || Confess("SELECT error:  " . $sth->errstr());
4580      # Return the statement handle.      # Return the statement handle.
4581      return $sth;      return $sth;
4582  }  }
4583    
4584  =head3 GetLoadStats  =head3 _GetLoadStats
4585    
4586  Return a blank statistics object for use by the load methods.  Return a blank statistics object for use by the load methods.
4587    
# Line 2498  Line 4593 
4593      return Stats->new();      return Stats->new();
4594  }  }
4595    
4596  =head3 GenerateFields  =head3 _DumpRelation
   
 Generate field values from a field structure and store in a specified table. The field names  
 are first sorted by pass count, certain pre-defined fields are removed from the list, and  
 then we rip through them evaluation the data generation string. Fields in the primary relation  
 are stored as scalars; fields in secondary relations are stored as value lists.  
   
 This is a static method.  
   
 =over 4  
   
 =item this  
   
 Hash table into which the field values should be placed.  
   
 =item fields  
   
 Field structure from which the field descriptors should be taken.  
   
 =item type  
   
 Type name of the object whose fields are being generated.  
   
 =item values (optional)  
   
 Reference to a value structure from which additional values can be taken.  
   
 =item from (optiona)  
   
 Reference to the source entity instance if relationship data is being generated.  
   
 =item to (optional)  
   
 Reference to the target entity instance if relationship data is being generated.  
   
 =back  
   
 =cut  
   
 sub _GenerateFields {  
     # Get the parameters.  
     my ($this, $fields, $type, $values, $from, $to) = @_;  
     # Sort the field names by pass number.  
     my @fieldNames = sort { $fields->{$a}->{DataGen}->{pass} <=> $fields->{$b}->{DataGen}->{pass} } keys %{$fields};  
     # Loop through the field names, generating data.  
     for my $name (@fieldNames) {  
         # Only proceed if this field needs to be generated.  
         if (!exists $this->{$name}) {  
             # Get this field's data generation descriptor.  
             my $fieldDescriptor = $fields->{$name};  
             my $data = $fieldDescriptor->{DataGen};  
             # Get the code to generate the field value.  
             my $codeString = $data->{content};  
             # Determine whether or not this field is in the primary relation.  
             if ($fieldDescriptor->{relation} eq $type) {  
                 # Here we have a primary relation field. Store the field value as  
                 # a scalar.  
                 $this->{$name} = eval($codeString);  
             } else {  
                 # Here we have a secondary relation field. Create a null list  
                 # and push the desired number of field values onto it.  
                 my @fieldValues = ();  
                 my $count = IntGen(0,$data->{testCount});  
                 for (my $i = 0; $i < $count; $i++) {  
                     my $newValue = eval($codeString);  
                     push @fieldValues, $newValue;  
                 }  
                 # Store the value list in the main hash.  
                 $this->{$name} = \@fieldValues;  
             }  
         }  
     }  
 }  
   
 =head3 DumpRelation  
4597    
4598  Dump the specified relation's to the specified output file in tab-delimited format.  Dump the specified relation to the specified output file in tab-delimited format.
4599    
4600  This is an instance method.  This is an instance method.
4601    
# Line 2622  Line 4643 
4643      close DTXOUT;      close DTXOUT;
4644  }  }
4645    
4646  =head3 GetStructure  =head3 _GetStructure
4647    
4648  Get the data structure for a specified entity or relationship.  Get the data structure for a specified entity or relationship.
4649    
# Line 2661  Line 4682 
4682      return $retVal;      return $retVal;
4683  }  }
4684    
4685  =head3 GetRelationTable  
4686    
4687    =head3 _GetRelationTable
4688    
4689  Get the list of relations for a specified entity or relationship.  Get the list of relations for a specified entity or relationship.
4690    
# Line 2690  Line 4713 
4713      return $objectData->{Relations};      return $objectData->{Relations};
4714  }  }
4715    
4716  =head3 ValidateFieldNames  =head3 _ValidateFieldNames
4717    
4718  Determine whether or not the field names are valid. A description of the problems with the names  Determine whether or not the field names are valid. A description of the problems with the names
4719  will be written to the standard error output. If there is an error, this method will abort. This is  will be written to the standard error output. If there is an error, this method will abort. This is
# Line 2717  Line 4740 
4740          for my $object (values %{$metadata->{$section}}) {          for my $object (values %{$metadata->{$section}}) {
4741              # Loop through the object's fields.              # Loop through the object's fields.
4742              for my $fieldName (keys %{$object->{Fields}}) {              for my $fieldName (keys %{$object->{Fields}}) {
4743                  # Now we make some initial validations.                  # If this field name is invalid, set the return value to zero
4744                  if ($fieldName =~ /--/) {                  # so we know we encountered an error.
4745                      # Here we have a doubled minus sign.                  if (! ValidateFieldName($fieldName)) {
                     print STDERR "Field name $fieldName has a doubled hyphen.\n";  
                     $retVal = 0;  
                 } elsif ($fieldName !~ /^[A-Za-z]/) {  
                     # Here the field name is missing the initial letter.  
                     print STDERR "Field name $fieldName does not begin with a letter.\n";  
                     $retVal = 0;  
                 } else {  
                     # Strip out the minus signs. Everything remaining must be a letter  
                     # or digit.  
                     my $strippedName = $fieldName;  
                     $strippedName =~ s/-//g;  
                     if ($strippedName !~ /^[A-Za-z0-9]+$/) {  
                         print STDERR "Field name $fieldName contains illegal characters.\n";  
4746                          $retVal = 0;                          $retVal = 0;
4747                      }                      }
4748                  }                  }
4749              }              }
4750          }          }
     }  
4751      # If an error was found, fail.      # If an error was found, fail.
4752      if ($retVal  == 0) {      if ($retVal  == 0) {
4753          Confess("Errors found in field names.");          Confess("Errors found in field names.");
4754      }      }
4755  }  }
4756    
4757  =head3 LoadRelation  =head3 _LoadRelation
4758    
4759  Load a relation from the data in a tab-delimited disk file. The load will only take place if a disk  Load a relation from the data in a tab-delimited disk file. The load will only take place if a disk
4760  file with the same name as the relation exists in the specified directory.  file with the same name as the relation exists in the specified directory.
# Line 2796  Line 4805 
4805      # be a null string.      # be a null string.
4806      if ($fileName ne "") {      if ($fileName ne "") {
4807          # Load the relation from the file.          # Load the relation from the file.
4808          $retVal = $self->LoadTable($fileName, $relationName, $rebuild);          $retVal = $self->LoadTable($fileName, $relationName, truncate => $rebuild);
4809      } elsif ($rebuild) {      } elsif ($rebuild) {
4810          # Here we are rebuilding, but no file exists, so we just re-create the table.          # Here we are rebuilding, but no file exists, so we just re-create the table.
4811          $self->CreateTable($relationName, 1);          $self->CreateTable($relationName, 1);
# Line 2805  Line 4814 
4814      return $retVal;      return $retVal;
4815  }  }
4816    
4817  =head3 LoadMetaData  
4818    =head3 _LoadMetaData
4819    
4820        my $metadata = ERDB::_LoadMetaData($filename);
4821    
4822  This method loads the data describing this database from an XML file into a metadata structure.  This method loads the data describing this database from an XML file into a metadata structure.
4823  The resulting structure is a set of nested hash tables containing all the information needed to  The resulting structure is a set of nested hash tables containing all the information needed to
# Line 2830  Line 4842 
4842  sub _LoadMetaData {  sub _LoadMetaData {
4843      # Get the parameters.      # Get the parameters.
4844      my ($filename) = @_;      my ($filename) = @_;
4845      Trace("Reading Sprout DBD from $filename.") if T(2);      Trace("Reading DBD from $filename.") if T(2);
4846      # Slurp the XML file into a variable. Extensive use of options is used to insure we      # Slurp the XML file into a variable. Extensive use of options is used to insure we
4847      # get the exact structure we want.      # get the exact structure we want.
4848      my $metadata = XML::Simple::XMLin($filename,      my $metadata = ReadMetaXML($filename);
                                       GroupTags => { Relationships => 'Relationship',  
                                                      Entities => 'Entity',  
                                                      Fields => 'Field',  
                                                      Indexes => 'Index',  
                                                      IndexFields => 'IndexField'},  
                                       KeyAttr => { Relationship => 'name',  
                                                    Entity => 'name',  
                                                    Field => 'name'},  
                                       ForceArray => ['Field', 'Index', 'IndexField'],  
                                       ForceContent => 1,  
                                       NormalizeSpace => 2  
                                       );  
     Trace("XML metadata loaded from file $filename.") if T(1);  
4849      # Before we go any farther, we need to validate the field and object names. If an error is found,      # Before we go any farther, we need to validate the field and object names. If an error is found,
4850      # the method below will fail.      # the method below will fail.
4851      _ValidateFieldNames($metadata);      _ValidateFieldNames($metadata);
# Line 2969  Line 4968 
4968              if ($found == 0) {              if ($found == 0) {
4969                  push @{$indexList}, { IndexFields => [ {name => 'id', order => 'ascending'} ] };                  push @{$indexList}, { IndexFields => [ {name => 'id', order => 'ascending'} ] };
4970              }              }
4971              # Now we need to convert the relation's index list to an index table. We begin by creating              # Attach all the indexes to the relation.
4972              # an empty table in the relation structure.              _ProcessIndexes($indexList, $relation);
             $relation->{Indexes} = { };  
             # Loop through the indexes.  
             my $count = 0;  
             for my $index (@{$indexList}) {  
                 # Add this index to the index table.  
                 _AddIndex("idx$relationName$count", $relation, $index);  
                 # Increment the counter so that the next index has a different name.  
                 $count++;  
             }  
4973          }          }
4974          # Finally, we add the relation structure to the entity.          # Finally, we add the relation structure to the entity.
4975          $entityStructure->{Relations} = $relationTable;          $entityStructure->{Relations} = $relationTable;
# Line 2993  Line 4983 
4983          _FixupFields($relationshipStructure, $relationshipName, 2, 3);          _FixupFields($relationshipStructure, $relationshipName, 2, 3);
4984          # Format a description for the FROM field.          # Format a description for the FROM field.
4985          my $fromEntity = $relationshipStructure->{from};          my $fromEntity = $relationshipStructure->{from};
4986          my $fromComment = "<b>id</b> of the source <b><a href=\"#$fromEntity\">$fromEntity</a></b>.";          my $fromComment = "[b]id[/b] of the source [b][link #$fromEntity]$fromEntity\[/link][/b].";
4987          # Get the FROM entity's key type.          # Get the FROM entity's key type.
4988          my $fromType = $entityList->{$fromEntity}->{keyType};          my $fromType = $entityList->{$fromEntity}->{keyType};
4989          # Add the FROM field.          # Add the FROM field.
# Line 3003  Line 4993 
4993                                                      PrettySort => 1});                                                      PrettySort => 1});
4994          # Format a description for the TO field.          # Format a description for the TO field.
4995          my $toEntity = $relationshipStructure->{to};          my $toEntity = $relationshipStructure->{to};
4996          my $toComment = "<b>id</b> of the target <b><a href=\"#$toEntity\">$toEntity</a></b>.";          my $toComment = "[b]id[/b] of the target [b][link #$toEntity]$toEntity\[/link][/b].";
4997          # Get the TO entity's key type.          # Get the TO entity's key type.
4998          my $toType = $entityList->{$toEntity}->{keyType};          my $toType = $entityList->{$toEntity}->{keyType};
4999          # Add the TO field.          # Add the TO field.
# Line 3015  Line 5005 
5005          my $thisRelation = { Fields => _ReOrderRelationTable($relationshipStructure->{Fields}),          my $thisRelation = { Fields => _ReOrderRelationTable($relationshipStructure->{Fields}),
5006                               Indexes => { } };                               Indexes => { } };
5007          $relationshipStructure->{Relations} = { $relationshipName => $thisRelation };          $relationshipStructure->{Relations} = { $relationshipName => $thisRelation };
5008    
5009            # Add the alternate indexes (if any). This MUST be done before the FROM and
5010            # TO indexes, because it erases the relation's index list.
5011            if (exists $relationshipStructure->{Indexes}) {
5012                _ProcessIndexes($relationshipStructure->{Indexes}, $thisRelation);
5013            }
5014            # Add the relation to the master table.
5015          # Create the FROM and TO indexes.          # Create the FROM and TO indexes.
5016          _CreateRelationshipIndex("From", $relationshipName, $relationshipStructure);          _CreateRelationshipIndex("From", $relationshipName, $relationshipStructure);
5017          _CreateRelationshipIndex("To", $relationshipName, $relationshipStructure);          _CreateRelationshipIndex("To", $relationshipName, $relationshipStructure);
         # Add the relation to the master table.  
5018          $masterRelationTable{$relationshipName} = $thisRelation;          $masterRelationTable{$relationshipName} = $thisRelation;
5019      }      }
5020      # Now store the master relation table in the metadata structure.      # Now store the master relation table in the metadata structure.
# Line 3117  Line 5113 
5113          # joins, the direction makes a difference with the recursive joins. This can give          # joins, the direction makes a difference with the recursive joins. This can give
5114          # rise to situations where we can't create the path we want; however, it is always          # rise to situations where we can't create the path we want; however, it is always
5115          # possible to get the same effect using multiple queries.          # possible to get the same effect using multiple queries.
5116          for my $relationshipName (@bothList) {          for my $relationshipName (@bothList) {
5117              Trace("Setting up entity joins to recursive relationship $relationshipName with $entityName.") if T(metadata => 4);              Trace("Setting up entity joins to recursive relationship $relationshipName with $entityName.") if T(metadata => 4);
5118              # Join to the entity from each direction.              # Join to the entity from each direction.
5119              $joinTable{"$entityName/$relationshipName"} =              $joinTable{"$entityName/$relationshipName"} =
5120                  "$entityName.id = $relationshipName.from_link";                  "$entityName.id = $relationshipName.from_link";
5121              $joinTable{"$relationshipName/$entityName"} =              $joinTable{"$relationshipName/$entityName"} =
5122                  "$relationshipName.to_link = $entityName.id";                  "$relationshipName.to_link = $entityName.id";
         }  
     }  
     # Add the join table to the structure.  
     $metadata->{Joins} = \%joinTable;  
     # Return the slurped and fixed-up structure.  
     return $metadata;  
 }  
   
 =head3 SortNeeded  
   
 C<< my $flag = $erdb->SortNeeded($relationName); >>  
   
 Return TRUE if the specified relation should be sorted during loading to remove duplicate keys,  
 else FALSE.  
   
 =over 4  
   
 =item relationName  
   
 Name of the relation to be examined.  
   
 =item RETURN  
   
 Returns TRUE if the relation needs a sort, else FALSE.  
   
 =back  
   
 =cut  
 #: Return Type $;  
 sub SortNeeded {  
     # Get the parameters.  
     my ($self, $relationName) = @_;  
     # Declare the return variable.  
     my $retVal = 0;  
     # Find out if the relation is a primary entity relation.  
     my $entityTable = $self->{_metaData}->{Entities};  
     if (exists $entityTable->{$relationName}) {  
         my $keyType = $entityTable->{$relationName}->{keyType};  
         Trace("Relation $relationName found in entity table with key type $keyType.") if T(3);  
         # If the key is not a hash string, we must do the sort.  
         if ($keyType ne 'hash-string') {  
             $retVal = 1;  
5123          }          }
5124      }      }
5125      # Return the result.      # Add the join table to the structure.
5126      return $retVal;      $metadata->{Joins} = \%joinTable;
5127        # Return the slurped and fixed-up structure.
5128        return $metadata;
5129  }  }
5130    
5131  =head3 CreateRelationshipIndex  =head3 _CreateRelationshipIndex
5132    
5133  Create an index for a relationship's relation.  Create an index for a relationship's relation.
5134    
# Line 3214  Line 5170 
5170          $newIndex->{Unique} = 'true';          $newIndex->{Unique} = 'true';
5171      }      }
5172      # Add the index to the relation.      # Add the index to the relation.
5173      _AddIndex("idx$relationshipName$indexKey", $relationStructure, $newIndex);      _AddIndex("idx$indexKey", $relationStructure, $newIndex);
5174    }
5175    
5176    =head3 _ProcessIndexes
5177    
5178        ERDB::_ProcessIndexes($indexList, $relation);
5179    
5180    Build the data structures for the specified indexes in the specified relation.
5181    
5182    =over 4
5183    
5184    =item indexList
5185    
5186    Reference to a list of indexes. Each index is a hash reference containing an optional
5187    C<Notes> value that describes the index and an C<IndexFields> value that is a reference
5188    to a list of index field structures. An index field structure, in turn, is a reference
5189    to a hash that contains a C<name> attribute for the field name and an C<order>
5190    attribute that specifies either C<ascending> or C<descending>. In this sense the
5191    index list encapsulates the XML C<Indexes> structure in the database definition.
5192    
5193    =item relation
5194    
5195    The structure that describes the current relation. The new index descriptors will
5196    be stored in the structure's C<Indexes> member. Any previous data in the structure
5197    will be lost.
5198    
5199    =back
5200    
5201    =cut
5202    
5203    sub _ProcessIndexes {
5204        # Get the parameters.
5205        my ($indexList, $relation) = @_;
5206        # Now we need to convert the relation's index list to an index table. We begin by creating
5207        # an empty table in the relation structure.
5208        $relation->{Indexes} = { };
5209        # Loop through the indexes.
5210        my $count = 0;
5211        for my $index (@{$indexList}) {
5212            # Add this index to the index table.
5213            _AddIndex("idx$count", $relation, $index);
5214            # Increment the counter so that the next index has a different name.
5215            $count++;
5216        }
5217  }  }
5218    
5219  =head3 AddIndex  =head3 _AddIndex
5220    
5221  Add an index to a relation structure.  Add an index to a relation structure.
5222    
# Line 3263  Line 5262 
5262      $relationStructure->{Indexes}->{$indexName} = $newIndex;      $relationStructure->{Indexes}->{$indexName} = $newIndex;
5263  }  }
5264    
5265  =head3 FixupFields  =head3 _FixupFields
5266    
5267  This method fixes the field list for an entity or relationship. It will add the caller-specified  This method fixes the field list for an entity or relationship. It will add the caller-specified
5268  relation name to fields that do not have a name and set the C<PrettySort> value as specified.  relation name to fields that do not have a name and set the C<PrettySort> value as specified.
# Line 3301  Line 5300 
5300          # Here it doesn't, so we create a new one.          # Here it doesn't, so we create a new one.
5301          $structure->{Fields} = { };          $structure->{Fields} = { };
5302      } else {      } else {
5303          # Here we have a field list. Loop through its fields.          # Here we have a field list. We need to track the searchable fields, so we
5304            # create a list for stashing them.
5305            my @textFields = ();
5306            # Loop through the fields.
5307          my $fieldStructures = $structure->{Fields};          my $fieldStructures = $structure->{Fields};
5308          for my $fieldName (keys %{$fieldStructures}) {          for my $fieldName (keys %{$fieldStructures}) {
5309              Trace("Processing field $fieldName of $defaultRelationName.") if T(4);              Trace("Processing field $fieldName of $defaultRelationName.") if T(4);
# Line 3310  Line 5312 
5312              my $type = $fieldData->{type};              my $type = $fieldData->{type};
5313              # Plug in a relation name if it is needed.              # Plug in a relation name if it is needed.
5314              Tracer::MergeOptions($fieldData, { relation => $defaultRelationName });              Tracer::MergeOptions($fieldData, { relation => $defaultRelationName });
5315              # Plug in a data generator if we need one.              # Check for searchability.
5316              if (!exists $fieldData->{DataGen}) {              if ($fieldData->{searchable}) {
5317                  # The data generator will use the default for the field's type.                  # Only allow this for a primary relation.
5318                  $fieldData->{DataGen} = { content => $TypeTable{$type}->{dataGen} };                  if ($fieldData->{relation} ne $defaultRelationName) {
5319                        Confess("Field $fieldName of $defaultRelationName is in secondary relations and cannot be searchable.");
5320                    } else {
5321                        push @textFields, $fieldName;
5322                    }
5323              }              }
             # Plug in the defaults for the optional data generation parameters.  
             Tracer::MergeOptions($fieldData->{DataGen}, { testCount => 1, pass => 0 });  
5324              # Add the PrettySortValue.              # Add the PrettySortValue.
5325              $fieldData->{PrettySort} = (($type eq "text") ? $textPrettySortValue : $prettySortValue);              $fieldData->{PrettySort} = (($type eq "text") ? $textPrettySortValue : $prettySortValue);
5326          }          }
5327            # If there are searchable fields, remember the fact.
5328            if (@textFields) {
5329                $structure->{searchFields} = \@textFields;
5330            }
5331      }      }
5332  }  }
5333    
5334  =head3 FixName  =head3 _FixName
5335    
5336  Fix the incoming field name so that it is a legal SQL column name.  Fix the incoming field name so that it is a legal SQL column name.
5337    
# Line 3352  Line 5360 
5360      return $fieldName;      return $fieldName;
5361  }  }
5362    
5363  =head3 FixNames  =head3 _FixNames
5364    
5365  Fix all the field names in a list.  Fix all the field names in a list.
5366    
# Line 3383  Line 5391 
5391      return @result;      return @result;
5392  }  }
5393    
5394  =head3 AddField  =head3 _AddField
5395    
5396  Add a field to a field list.  Add a field to a field list.
5397    
# Line 3418  Line 5426 
5426      $fieldList->{$fieldName} = $fieldStructure;      $fieldList->{$fieldName} = $fieldStructure;
5427  }  }
5428    
5429  =head3 ReOrderRelationTable  =head3 _ReOrderRelationTable
5430    
5431  This method will take a relation table and re-sort it according to the implicit ordering of the  This method will take a relation table and re-sort it according to the implicit ordering of the
5432  C<PrettySort> property. Instead of a hash based on field names, it will return a list of fields.  C<PrettySort> property. Instead of a hash based on field names, it will return a list of fields.
# Line 3479  Line 5487 
5487    
5488  }  }
5489    
5490  =head3 IsPrimary  =head3 _IsPrimary
5491    
5492  Return TRUE if a specified relation is a primary relation, else FALSE. A relation is primary  Return TRUE if a specified relation is a primary relation, else FALSE. A relation is primary
5493  if it has the same name as an entity or relationship.  if it has the same name as an entity or relationship.
# Line 3515  Line 5523 
5523      return $retVal;      return $retVal;
5524  }  }
5525    
5526  =head3 FindRelation  =head3 _FindRelation
5527    
5528  Return the descriptor for the specified relation.  Return the descriptor for the specified relation.
5529    
# Line 3544  Line 5552 
5552      return $retVal;      return $retVal;
5553  }  }
5554    
5555  =head2 HTML Documentation Utility Methods  =head2 Documentation Utility Methods
5556    
5557  =head3 ComputeRelationshipSentence  =head3 _ComputeRelationshipSentence
5558    
5559  The relationship sentence consists of the relationship name between the names of the  The relationship sentence consists of the relationship name between the names of the
5560  two related entities and an arity indicator.  two related entities and an arity indicator.
# Line 3576  Line 5584 
5584      # Get the parameters.      # Get the parameters.
5585      my ($relationshipName, $relationshipStructure) = @_;      my ($relationshipName, $relationshipStructure) = @_;
5586      # Format the relationship sentence.      # Format the relationship sentence.
5587      my $result = "$relationshipStructure->{from} <b>$relationshipName</b> $relationshipStructure->{to}";      my $result = "$relationshipStructure->{from} $relationshipName $relationshipStructure->{to}";
5588      # Compute the arity.      # Compute the arity.
5589      my $arityCode = $relationshipStructure->{arity};      my $arityCode = $relationshipStructure->{arity};
5590      my $arity = $ArityTable{$arityCode};      my $arity = $ArityTable{$arityCode};
# Line 3584  Line 5592 
5592      return $result;      return $result;
5593  }  }
5594    
5595  =head3 ComputeRelationshipHeading  =head3 _ComputeRelationshipHeading
5596    
5597  The relationship heading is the L<relationship sentence|/ComputeRelationshipSentence> with the entity  The relationship heading is the L<relationship sentence|/ComputeRelationshipSentence> with the entity
5598  names hyperlinked to the appropriate entity sections of the document.  names hyperlinked to the appropriate entity sections of the document.
# Line 3621  Line 5629 
5629      return $result;      return $result;
5630  }  }
5631    
5632  =head3 ShowRelationTable  =head3 _WikiRelationTable
5633    
5634    Generate the Wiki text for a particular relation. The relation's data will be formatted as a
5635    table with three columns-- the field name, the field type, and the field description.
5636    
5637    This is a static method.
5638    
5639    =over 4
5640    
5641    =item relationName
5642    
5643    Name of the relation being formatted.
5644    
5645    =item relationData
5646    
5647    Hash containing the relation's fields and indexes.
5648    
5649    =item RETURN
5650    
5651    Returns a Wiki string that can be used to display the relation name and all of its fields.
5652    
5653    =back
5654    
5655    =cut
5656    
5657    sub _WikiRelationTable {
5658        # Get the parameters.
5659        my ($relationName, $relationData) = @_;
5660        # We'll create a list of lists in here, then call WikiTools::Table to
5661        # convert it into a table.
5662        my @rows = ();
5663        # Push in the header row.
5664        push @rows, [qw(Field Type Description)];
5665        # Loop through the fields.
5666        for my $field (@{$relationData->{Fields}}) {
5667            # Create this field's row. We always have a name and type.
5668            my @row = ($field->{name}, $field->{type});
5669            # If we have a description, add it as the third column.
5670            if (exists $field->{Notes}) {
5671                push @row, WikiNote($field->{Notes}->{content});
5672            }
5673            # Push this row onto the table list.
5674            push @rows, \@row;
5675        }
5676        # Store the rows as a Wiki table with a level-4 heading.
5677        my $retVal = join("\n\n", WikiTools::Heading(4, "$relationName Table"),
5678                          WikiTools::Table(@rows));
5679        # Now we show the relation's indexes. These are formatted as another
5680        # table.
5681        @rows = ();
5682        # Push in the header row.
5683        push @rows, [qw(Index Unique Fields Notes)];
5684        # Get the index hash.
5685        my $indexTable = $relationData->{Indexes};
5686        # Loop through the indexes. For an entity, there is always at least one index.
5687        # For a relationship, there are at least two. The upshot is we don't need to
5688        # worry about accidentally generating a frivolous table here.
5689        for my $indexName (sort keys %$indexTable) {
5690            my $indexData = $indexTable->{$indexName};
5691            # Determine whether or not the index is unique.
5692            my $unique = ((exists $indexData->{Unique} && $indexData->{Unique} eq "true") ?
5693                          "yes" : "");
5694            # Get the field list.
5695            my $fields = join(', ', @{$indexData->{IndexFields}});
5696            # Get the note text.
5697            my $description = "";
5698            if (my $note = $indexData->{Notes}) {
5699                $description = WikiNote($note->{content});
5700            }
5701            # Format this row.
5702            my @row = ($indexName, $unique, $fields, $description);
5703            push @rows, \@row;
5704        }
5705        # Add the index list to the result.
5706        $retVal .= "\n\n" . WikiTools::Table(@rows);
5707    }
5708    
5709    =head3 _ShowRelationTable
5710    
5711  Generate the HTML string for a particular relation. The relation's data will be formatted as an HTML  Generate the HTML string for a particular relation. The relation's data will be formatted as an HTML
5712  table with three columns-- the field name, the field type, and the field description.  table with three columns-- the field name, the field type, and the field description.
# Line 3671  Line 5756 
5756          $htmlString .= "<li><b>Index $fullName</b>\n<ul>\n";          $htmlString .= "<li><b>Index $fullName</b>\n<ul>\n";
5757          # Add any note text.          # Add any note text.
5758          if (my $note = $indexData->{Notes}) {          if (my $note = $indexData->{Notes}) {
5759              $htmlString .= "<li>" . _HTMLNote($note->{content}) . "</li>\n";              $htmlString .= "<li>" . HTMLNote($note->{content}) . "</li>\n";
5760          }          }
5761          # Add the fiield list.          # Add the fiield list.
5762          $htmlString .= "<li><i>" . join(', ', @{$indexData->{IndexFields}}) . "</i></li>\n";          $htmlString .= "<li><i>" . join(', ', @{$indexData->{IndexFields}}) . "</i></li>\n";
# Line 3682  Line 5767 
5767      $htmlString .= "</ul>\n";      $htmlString .= "</ul>\n";
5768  }  }
5769    
5770  =head3 OpenFieldTable  =head3 _OpenFieldTable
5771    
5772  This method creates the header string for the field table generated by L</ShowMetaData>.  This method creates the header string for the field table generated by L</ShowMetaData>.
5773    
# Line 3707  Line 5792 
5792      return _OpenTable($tablename, 'Field', 'Type', 'Description');      return _OpenTable($tablename, 'Field', 'Type', 'Description');
5793  }  }
5794    
5795  =head3 OpenTable  =head3 _OpenTable
5796    
5797  This method creates the header string for an HTML table.  This method creates the header string for an HTML table.
5798    
# Line 3737  Line 5822 
5822      # Compute the number of columns.      # Compute the number of columns.
5823      my $colCount = @colNames;      my $colCount = @colNames;
5824      # Generate the title row.      # Generate the title row.
5825      my $htmlString = "<p><table border=\"2\"><tr><td colspan=\"$colCount\" align=\"center\">$tablename</td></tr>\n";      my $htmlString = "<table border=\"2\"><tr><td colspan=\"$colCount\" align=\"center\">$tablename</td></tr>\n";
5826      # Loop through the columns, adding the column header rows.      # Loop through the columns, adding the column header rows.
5827      $htmlString .= "<tr>";      $htmlString .= "<tr>";
5828      for my $colName (@colNames) {      for my $colName (@colNames) {
# Line 3747  Line 5832 
5832      return $htmlString;      return $htmlString;
5833  }  }
5834    
5835  =head3 CloseTable  =head3 _CloseTable
5836    
5837  This method returns the HTML for closing a table.  This method returns the HTML for closing a table.
5838    
# Line 3756  Line 5841 
5841  =cut  =cut
5842    
5843  sub _CloseTable {  sub _CloseTable {
5844      return "</table></p>\n";      return "</table>\n";
5845  }  }
5846    
5847  =head3 ShowField  =head3 _ShowField
5848    
5849  This method returns the HTML for displaying a row of field information in a field table.  This method returns the HTML for displaying a row of field information in a field table.
5850    
# Line 3786  Line 5871 
5871      my $htmlString = "<tr><th align=\"left\">$fieldData->{name}</th><td>$fieldData->{type}</td>";      my $htmlString = "<tr><th align=\"left\">$fieldData->{name}</th><td>$fieldData->{type}</td>";
5872      # If we have content, add it as a third column.      # If we have content, add it as a third column.
5873      if (exists $fieldData->{Notes}) {      if (exists $fieldData->{Notes}) {
5874          $htmlString .= "<td>" . _HTMLNote($fieldData->{Notes}->{content}) . "</td>";          $htmlString .= "<td>" . HTMLNote($fieldData->{Notes}->{content}) . "</td>";
5875      }      }
5876      # Close off the row.      # Close off the row.
5877      $htmlString .= "</tr>\n";      $htmlString .= "</tr>\n";
# Line 3794  Line 5879 
5879      return $htmlString;      return $htmlString;
5880  }  }
5881