[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.105, Tue Sep 23 20:43:42 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
102    
103  =item text  =item text
104    
105  long string; Text fields cannot be used in indexes or sorting and do not support the  long string; Text fields do not support the normal syntax of filter clauses,
106  normal syntax of filter clauses, but can be up to a billion character in length  but can be up to a billion character in length
107    
108    =item dna
109    
110    long string, used to store DNA and protein sequences
111    
112    =item image
113    
114    long string, used to store encoded image data
115    
116  =item float  =item float
117    
# Line 186  Line 199 
199    
200  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<->),
201  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
202  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,
203    the name C<search-relevance> has special meaning for full-text searches and should not be
204    used as a field name.
205    
206  =item type  =item type
207    
# Line 205  Line 220 
220  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
221  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.
222    
223    =item searchable
224    
225    If specified, then the field is a candidate for full-text searching. A single full-text
226    index will be created for each relation with at least one searchable field in it.
227    For best results, this option should only be used for string or text fields.
228    
229    =item special
230    
231    This attribute allows the subclass to assign special meaning for certain fields.
232    The interpretation is up to the subclass itself. Currently, only entity fields
233    can have this attribute.
234    
235  =back  =back
236    
237  =head3 Indexes  =head3 Indexes
238    
239  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
240  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
241  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
242  I<from-index>. These order the results when crossing the relationship. For  I<from-index> that order the results when crossing the relationship. For
243  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
244  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
245  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
246    indexes. A relationship's index must specify only fields in
247  the relationship.  the relationship.
248    
249  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.
250  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
251  using the B<ToIndex> tag.  specified using the B<ToIndex> tag.
252    
253  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>
254  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 266 
266    
267  =back  =back
268    
269  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
270    have a B<Unique> attribute. If specified, the index will be generated as a unique
271    index.
272    
273  =head3 Object and Field Names  =head3 Object and Field Names
274    
# Line 282  Line 312 
312    
313  A relationship is described by the C<Relationship> tag. Within a relationship,  A relationship is described by the C<Relationship> tag. Within a relationship,
314  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
315  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
316  the to-index.  the to-index, and an C<Indexes> tag containing the alternate indexes.
317    
318  The C<Relationship> tag has the following attributes.  The C<Relationship> tag has the following attributes.
319    
# Line 316  Line 346 
346    
347  # 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.
348  # "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
349  # 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
350  # 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,
351  # record sizes.  # and "indexMod", if non-zero, is the number of characters to use when the field is specified in an
352  my %TypeTable = ( char =>    { sqlType => 'CHAR(1)',            maxLen => 1,            avgLen =>   1, dataGen => "StringGen('A')" },  # index
353                    int =>     { sqlType => 'INTEGER',            maxLen => 20,           avgLen =>   4, dataGen => "IntGen(0, 99999999)" },  my %TypeTable = ( char =>    { sqlType => 'CHAR(1)',            maxLen => 1,            avgLen =>   1, sort => "",
354                    string =>  { sqlType => 'VARCHAR(255)',       maxLen => 255,          avgLen => 100, dataGen => "StringGen(IntGen(10,250))" },                                 indexMod =>   0, notes => "single ASCII character"},
355                    text =>    { sqlType => 'TEXT',               maxLen => 1000000000,   avgLen => 500, dataGen => "StringGen(IntGen(80,1000))" },                    int =>     { sqlType => 'INTEGER',            maxLen => 20,           avgLen =>   4, sort => "n",
356                    date =>    { sqlType => 'BIGINT',             maxLen => 80,           avgLen =>   8, dataGen => "DateGen(-7, 7, IntGen(0,1400))" },                                 indexMod =>   0, notes => "signed 32-bit integer"},
357                    float =>   { sqlType => 'DOUBLE PRECISION',   maxLen => 40,           avgLen =>   8, dataGen => "FloatGen(0.0, 100.0)" },                    counter => { sqlType => 'INTEGER UNSIGNED',   maxLen => 20,           avgLen =>   4, sort => "n",
358                    boolean => { sqlType => 'SMALLINT',           maxLen => 1,            avgLen =>   1, dataGen => "IntGen(0, 1)" },                                 indexMod =>   0, notes => "unsigned 32-bit integer"},
359                      image =>    { sqlType => 'TEXT',               maxLen => 1000000000,   avgLen => 100000, sort => "",
360                                   indexMod => 255, notes => "UUencoded image, suitable for import into GD, should never be indexed"},
361                      dna =>      { sqlType => 'TEXT',               maxLen => 1000000000,   avgLen => 100000, sort => "",
362                                   indexMod => 255, notes => "DNA or protein sequence, should never be indexed"},
363                      string =>  { sqlType => 'VARCHAR(255)',       maxLen => 255,          avgLen => 100, sort => "",
364                                   indexMod =>   0, notes => "character string, 0 to 255 characters"},
365                      text =>    { sqlType => 'TEXT',               maxLen => 1000000000,   avgLen => 500, sort => "",
366                                   indexMod => 255, notes => "character string, nearly unlimited length, only first 255 characters are indexed"},
367                      date =>    { sqlType => 'BIGINT',             maxLen => 80,           avgLen =>   8, sort => "n",
368                                   indexMod =>   0, notes => "signed, 64-bit integer"},
369                      float =>   { sqlType => 'DOUBLE PRECISION',   maxLen => 40,           avgLen =>   8, sort => "g",
370                                   indexMod =>   0, notes => "64-bit double precision floating-point number"},
371                      boolean => { sqlType => 'SMALLINT',           maxLen => 1,            avgLen =>   1, sort => "n",
372                                   indexMod =>   0, notes => "boolean value: 0 if false, 1 if true"},
373                   'hash-string' =>                   'hash-string' =>
374                               { sqlType => 'VARCHAR(22)',        maxLen => 22,           avgLen =>  22, dataGen => "SringGen(22)" },                               { sqlType => 'VARCHAR(22)',        maxLen => 22,           avgLen =>  22, sort => "",
375                                   indexMod =>   0, notes => "string stored in digested form, used for certain types of key fields"},
376                   'id-string' =>                   'id-string' =>
377                               { sqlType => 'VARCHAR(25)',        maxLen => 25,           avgLen =>  25, dataGen => "SringGen(22)" },                               { sqlType => 'VARCHAR(25)',        maxLen => 25,           avgLen =>  25, sort => "",
378                                   indexMod =>   0, notes => "character string, 0 to 25 characters"},
379                   'key-string' =>                   'key-string' =>
380                               { sqlType => 'VARCHAR(40)',        maxLen => 40,           avgLen =>  10, dataGen => "StringGen(IntGen(10,40))" },                               { sqlType => 'VARCHAR(40)',        maxLen => 40,           avgLen =>  10, sort => "",
381                                   indexMod =>   0, notes => "character string, 0 to 40 characters"},
382                   'name-string' =>                   'name-string' =>
383                               { sqlType => 'VARCHAR(80)',        maxLen => 80,           avgLen =>  40, dataGen => "StringGen(IntGen(10,80))" },                               { sqlType => 'VARCHAR(80)',        maxLen => 80,           avgLen =>  40, sort => "",
384                                   indexMod =>   0, notes => "character string, 0 to 80 characters"},
385                   'medium-string' =>                   'medium-string' =>
386                               { sqlType => 'VARCHAR(160)',       maxLen => 160,          avgLen =>  40, dataGen => "StringGen(IntGen(10,160))" },                               { sqlType => 'VARCHAR(160)',       maxLen => 160,          avgLen =>  40, sort => "",
387                                   indexMod =>   0, notes => "character string, 0 to 160 characters"},
388                     'long-string' =>
389                                 { sqlType => 'VARCHAR(500)',       maxLen => 500,          avglen => 255, sort => "",
390                                   indexMod =>   0, notes => "character string, 0 to 500 characters"},
391                  );                  );
392    
393  # Table translating arities into natural language.  # Table translating arities into natural language.
# Line 344  Line 396 
396                     'MM' => 'many-to-many'                     'MM' => 'many-to-many'
397                   );                   );
398    
399  # Table for interpreting string patterns.  # Options for XML input and output.
400    
401    my %XmlOptions = (GroupTags =>  { Relationships => 'Relationship',
402                                      Entities => 'Entity',
403                                      Fields => 'Field',
404                                      Indexes => 'Index',
405                                      IndexFields => 'IndexField',
406                                      Issues => 'Issue',
407                                      Shapes => 'Shape'
408                                    },
409                      KeyAttr =>    { Relationship => 'name',
410                                      Entity => 'name',
411                                      Field => 'name',
412                                      Shape => 'name'
413                                    },
414                      SuppressEmpty => 1,
415                     );
416    
417  my %PictureTable = ( 'A' => "abcdefghijklmnopqrstuvwxyz",  my %XmlInOpts  = (
418                       '9' => "0123456789",                    ForceArray => [qw(Field Index IndexField Relationship Entity Shape)],
419                       'X' => "abcdefghijklmnopqrstuvwxyz0123456789",                    ForceContent => 1,
420                       'V' => "aeiou",                    NormalizeSpace => 2,
421                       'K' => "bcdfghjklmnoprstvwxyz"                   );
422    my %XmlOutOpts = (
423                      RootName => 'Database',
424                      XMLDecl => 1,
425                     );                     );
426    
427  =head2 Public Methods  =head2 Public Methods
428    
429  =head3 new  =head3 new
430    
431  C<< my $database = ERDB->new($dbh, $metaFileName); >>      my $database = ERDB->new($dbh, $metaFileName);
432    
433  Create a new ERDB object.  Create a new ERDB object.
434    
# Line 377  Line 448 
448    
449  sub new {  sub new {
450      # Get the parameters.      # Get the parameters.
451      my ($class, $dbh, $metaFileName, $options) = @_;      my ($class, $dbh, $metaFileName, %options) = @_;
452      # Load the meta-data.      # Load the meta-data.
453      my $metaData = _LoadMetaData($metaFileName);      my $metaData = _LoadMetaData($metaFileName);
454      # Create the object.      # Create the object.
# Line 391  Line 462 
462    
463  =head3 ShowMetaData  =head3 ShowMetaData
464    
465  C<< $erdb->ShowMetaData($fileName); >>      $erdb->ShowMetaData($fileName);
466    
467  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
468  the data to be loaded into the relations.  the data to be loaded into the relations.
# Line 432  Line 503 
503    
504  =head3 DisplayMetaData  =head3 DisplayMetaData
505    
506  C<< my $html = $erdb->DisplayMetaData(); >>      my $html = $erdb->DisplayMetaData();
507    
508  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
509  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 564 
564          my $entityData = $entityList->{$key};          my $entityData = $entityList->{$key};
565          # If there's descriptive text, display it.          # If there's descriptive text, display it.
566          if (my $notes = $entityData->{Notes}) {          if (my $notes = $entityData->{Notes}) {
567              $retVal .= "<p>" . _HTMLNote($notes->{content}) . "</p>\n";              $retVal .= "<p>" . HTMLNote($notes->{content}) . "</p>\n";
568          }          }
569          # 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.
570            my $relCount = keys %{$relationshipList};
571            if ($relCount > 0) {
572                # First, we set up the relationship subsection.
573          $retVal .= "<h4>Relationships for <b>$key</b></h4>\n<ul>\n";          $retVal .= "<h4>Relationships for <b>$key</b></h4>\n<ul>\n";
574          # Loop through the relationships.          # Loop through the relationships.
575          for my $relationship (sort keys %{$relationshipList}) {          for my $relationship (sort keys %{$relationshipList}) {
# Line 511  Line 585 
585          }          }
586          # Close off the relationship list.          # Close off the relationship list.
587          $retVal .= "</ul>\n";          $retVal .= "</ul>\n";
588            }
589          # Get the entity's relations.          # Get the entity's relations.
590          my $relationList = $entityData->{Relations};          my $relationList = $entityData->{Relations};
591          # Create a header for the relation subsection.          # Create a header for the relation subsection.
# Line 550  Line 625 
625          $retVal .= "</p>\n";          $retVal .= "</p>\n";
626          # If there are notes on this relationship, display them.          # If there are notes on this relationship, display them.
627          if (my $notes = $relationshipStructure->{Notes}) {          if (my $notes = $relationshipStructure->{Notes}) {
628              $retVal .= "<p>" . _HTMLNote($notes->{content}) . "</p>\n";              $retVal .= "<p>" . HTMLNote($notes->{content}) . "</p>\n";
629          }          }
630          # Generate the relationship's relation table.          # Generate the relationship's relation table.
631          my $htmlString = _ShowRelationTable($key, $relationshipStructure->{Relations}->{$key});          my $htmlString = _ShowRelationTable($key, $relationshipStructure->{Relations}->{$key});
# Line 584  Line 659 
659    
660  =head3 DumpMetaData  =head3 DumpMetaData
661    
662  C<< $erdb->DumpMetaData(); >>      $erdb->DumpMetaData();
663    
664  Return a dump of the metadata structure.  Return a dump of the metadata structure.
665    
# Line 597  Line 672 
672      return Data::Dumper::Dumper($self->{_metaData});      return Data::Dumper::Dumper($self->{_metaData});
673  }  }
674    
675    =head3 GenerateWikiData
676    
677        my @wikiLines = $erdb->GenerateWikiData();
678    
679    Build a description of the database for the wiki. The database will be
680    organized into a single page, with sections for each entity and relationship.
681    The return value is a list of text lines.
682    
683    =cut
684    
685    sub GenerateWikiData {
686        # Get the parameters.
687        my ($self) = @_;
688        # We'll build the wiki text in here.
689        my @retVal = ();
690        # Get the metadata object.
691        my $metadata = $self->{_metaData};
692        # Get the title string. This will become the page name.
693        my $title = $metadata->{Title}->{content};
694        # Get the entity and relationship lists.
695        my $entityList = $metadata->{Entities};
696        my $relationshipList = $metadata->{Relationships};
697        my $shapeList = $metadata->{Shapes};
698        # Start with the introductory text.
699        push @retVal, WikiTools::Heading(2, "Introduction");
700        if (my $notes = $metadata->{Notes}) {
701            push @retVal, WikiNote($notes->{content});
702        }
703        # Generate issue list.
704        if (my $issues = $metadata->{Issues}) {
705            push @retVal, WikiTools::Heading(3, 'Issues');
706            push @retVal, WikiTools::List(map { $_->{content} } @{$issues});
707        }
708        # Start the entity section.
709        push @retVal, WikiTools::Heading(2, "Entities");
710        # Loop through the entities. Note that unlike the situation with HTML, we
711        # don't need to generate the table of contents manually, just the data
712        # itself.
713        for my $key (sort keys %$entityList) {
714            # Create a header for this entity.
715            push @retVal, "", WikiTools::Heading(3, $key);
716            # Get the entity data.
717            my $entityData = $entityList->{$key};
718            # Plant the notes here, if there are any.
719            push @retVal, _ObjectNotes($entityData);
720            # Now we list the entity's relationships (if any). First, we build a list
721            # of the relationships relevant to this entity.
722            my @rels = ();
723            for my $rel (sort keys %$relationshipList) {
724                my $relStructure = $relationshipList->{$rel};
725                if ($relStructure->{from} eq $key || $relStructure->{to} eq $key) {
726                    # Get the relationship sentence.
727                    my $relSentence = _ComputeRelationshipSentence($rel, $relStructure);
728                    # Linkify it.
729                    my $linkedRel = WikiTools::LinkMarkup("#$rel", $rel);
730                    $relSentence =~ s/$rel/$linkedRel/;
731                    push @rels, $relSentence;
732                }
733            }
734            # Add the relationships as a Wiki list.
735            push @retVal, WikiTools::List(@rels);
736            # Get the entity's relations.
737            my $relationList = $entityData->{Relations};
738            # Loop through the relations, displaying them.
739            for my $relation (sort keys %{$relationList}) {
740                my $wikiString = _WikiRelationTable($relation, $relationList->{$relation});
741                push @retVal, $wikiString;
742            }
743        }
744        # Now the entities are documented. Next we do the relationships.
745        push @retVal, WikiTools::Heading(2, "Relationships");
746        for my $key (sort keys %$relationshipList) {
747            my $relationshipData = $relationshipList->{$key};
748            # Create the relationship heading.
749            push @retVal, WikiTools::Heading(3, $key);
750            # Describe the relationship arity. Note there's a bit of trickiness involving recursive
751            # many-to-many relationships. In a normal many-to-many we use two sentences to describe
752            # the arity (one for each direction). This is a bad idea for a recursive relationship,
753            # since both sentences will say the same thing.
754            my $arity = $relationshipData->{arity};
755            my $fromEntity = $relationshipData->{from};
756            my $toEntity = $relationshipData->{to};
757            my @listElements = ();
758            my $boldCode = WikiTools::BoldCode();
759            if ($arity eq "11") {
760                push @listElements, "Each $boldCode$fromEntity$boldCode relates to at most one $boldCode$toEntity$boldCode.";
761            } else {
762                push @listElements, "Each $boldCode$fromEntity$boldCode relates to multiple $boldCode${toEntity}s$boldCode.";
763                if ($arity eq "MM" && $fromEntity ne $toEntity) {
764                    push @listElements, "Each $boldCode$toEntity$boldCode relates to multiple $boldCode${fromEntity}s$boldCode.";
765                }
766            }
767            push @retVal, WikiTools::List(@listElements);
768            # Plant the notes here, if there are any.
769            push @retVal, _ObjectNotes($relationshipData);
770            # Finally, the relationship table.
771            my $wikiString = _WikiRelationTable($key, $relationshipData->{Relations}->{$key});
772            push @retVal, $wikiString;
773        }
774        # Now loop through the miscellaneous shapes.
775        if ($shapeList) {
776            push @retVal, WikiTools::Heading(2, "Miscellaneous");
777            for my $shape (sort keys %$shapeList) {
778                push @retVal, WikiTools::Heading(3, $shape);
779                my $shapeData = $shapeList->{$shape};
780                push @retVal, _ObjectNotes($shapeData);
781            }
782        }
783        # All done. Return the lines.
784        return @retVal;
785    }
786    
787    
788    =head3 CreatePPO
789    
790        ERDB::CreatePPO($erdbXMLFile, $ppoXMLFile);
791    
792    Create a PPO XML file from an ERDB data definition XML file. At the
793    current time, the PPO XML file can be used to create a database with
794    similar functionality. Eventually, the PPO will be able to use the
795    created XML to access the live ERDB database.
796    
797    =over 4
798    
799    =item erdbXMLFile
800    
801    Name of the XML data definition file for the ERDB database. This
802    file must exist.
803    
804    =item ppoXMLFile
805    
806    Output file for the PPO XML definition. If this file exists, it
807    will be overwritten.
808    
809    =back
810    
811    =cut
812    
813    sub CreatePPO {
814        # Get the parameters.
815        my ($erdbXMLFile, $ppoXMLFile) = @_;
816        # First, we want to slurp in the ERDB XML file in its raw form.
817        my $xml = ReadMetaXML($erdbXMLFile);
818        # Create a variable to hold all of the objects in the PPO project.
819        my @objects = ();
820        # Get the relationship hash.
821        my $relationships = $xml->{Relationships};
822        # Loop through the entities.
823        my $entities = $xml->{Entities};
824        for my $entityName (keys %{$entities}) {
825            # Get the entity's data structures.
826            my $entityObject = $entities->{$entityName};
827            # We put the object's fields in here, according to their type.
828            my (@object_refs, @scalars, @indexes, @arrays);
829            # Create the ID field for the entity. We get the key type from the
830            # entity object and compute the corresponding SQL type.
831            my $type = $TypeTable{$entityObject->{keyType}}->{sqlType};
832            push @scalars, { label => 'id', type => $type };
833            # Loop through the entity fields.
834            for my $fieldName ( keys %{$entityObject->{Fields}} ) {
835                # Get the field object.
836                my $fieldObject = $entityObject->{Fields}->{$fieldName};
837                # Convert it to a scalar tag.
838                my $scalar = _CreatePPOField($fieldName, $fieldObject);
839                # If we have a relation, this field is stored in an array.
840                # otherwise, it is a scalar. The array tag has scalars
841                # stored as an XML array. In ERDB, there is only ever one,
842                # but PPO can have more.
843                my $relation = $fieldObject->{relation};
844                if ($relation) {
845                    push @arrays, { scalar => [$scalar] };
846                } else {
847                    push @scalars, $scalar;
848                }
849            }
850            # Loop through the relationships. If this entity is the to-entity
851            # on a relationship of 1M arity, then it is implemented as a PPO
852            # object reference.
853            for my $relationshipName (keys %{$relationships}) {
854                # Get the relationship data.
855                my $relationshipData = $relationships->{$relationshipName};
856                # If we have a from for this entity and an arity of 1M, we
857                # have an object reference.
858                if ($relationshipData->{to} eq $entityName &&
859                    $relationshipData->{arity} eq '1M') {
860                    # Build the object reference tag.
861                    push @object_refs, { label => $relationshipName,
862                                         type => $relationshipData->{from} };
863                }
864            }
865            # Create the indexes.
866            my $indexList = $entityObject->{Indexes};
867            push @indexes, map { _CreatePPOIndex($_) } @{$indexList};
868            # Build the object XML tree.
869            my $object = { label => $entityName,
870                           object_ref => \@object_refs,
871                           scalar => \@scalars,
872                           index => \@indexes,
873                           array => \@arrays
874                          };
875            # Push the object onto the objects list.
876            push @objects, $object;
877        }
878        # Loop through the relationships, searching for MMs. The 1Ms were
879        # already handled by the entity search above.
880        for my $relationshipName (keys %{$relationships}) {
881            # Get this relationship's object.
882            my $relationshipObject = $relationships->{$relationshipName};
883            # Only proceed if it's many-to-many.
884            if ($relationshipObject->{arity} eq 'MM') {
885                # Create the tag lists for the relationship object.
886                my (@object_refs, @scalars, @indexes);
887                # The relationship will be created as an object with object
888                # references for its links to the participating entities.
889                my %links = ( from_link => $relationshipObject->{from},
890                              to_link => $relationshipObject->{to} );
891                for my $link (keys %links) {
892                    # Create an object_ref tag for this piece of the
893                    # relationship (from or to).
894                    my $object_ref = { label => $link,
895                                       type => $links{$link} };
896                    push @object_refs, $object_ref;
897                }
898                # Loop through the intersection data fields, creating scalar tags.
899                # There are no fancy array tags in a relationship.
900                for my $fieldName (keys %{$relationshipObject->{Fields}}) {
901                    my $fieldObject = $relationshipObject->{Fields}->{$fieldName};
902                    push @scalars, _CreatePPOField($fieldName, $fieldObject);
903                }
904                # Finally, the indexes: currently we cannot support the to-index and
905                # from-index in PPO, so we just process the alternate indexes.
906                my $indexList = $relationshipObject->{Indexes};
907                push @indexes, map { _CreatePPOIndex($_) } @{$indexList};
908                # Wrap up all the stuff about this relationship.
909                my $object = { label => $relationshipName,
910                               scalar => \@scalars,
911                               object_ref => \@object_refs,
912                               index => \@indexes
913                             };
914                # Push it into the object list.
915                push @objects, $object;
916            }
917        }
918        # Compute a title.
919        my $title;
920        if ($erdbXMLFile =~ /(\/|^)([^\/]+)DBD\.xml/) {
921            # Here we have a standard file name we can use for a title.
922            $title = $2;
923        } else {
924            # Here the file name is non-standard, so we carve up the
925            # database title.
926            $title = $xml->{Title}->{content};
927            $title =~ s/\s\.,//g;
928        }
929        # Wrap up the XML as a project.
930        my $ppoXML = { project => { label => $title,
931                                    object => \@objects }};
932        # Write out the results.
933        my $ppoString = XML::Simple::XMLout($ppoXML,
934                                            AttrIndent => 1,
935                                            KeepRoot => 1);
936        Tracer::PutFile($ppoXMLFile, [ $ppoString ]);
937    }
938    
939    =head3 FindIndexForEntity
940    
941        my $indexFound = ERDB::FindIndexForEntity($xml, $entityName, $attributeName);
942    
943    This method locates the entry in an entity's index list that begins with the
944    specified attribute name. If the entity has no index list, one will be
945    created. This method works on raw XML, not a live ERDB object.
946    
947    =over 4
948    
949    =item xml
950    
951    The raw XML structure defining the database.
952    
953    =item entityName
954    
955    The name of the relevant entity.
956    
957    =item attributeName
958    
959    The name of the attribute relevant to the search.
960    
961    =item RETURN
962    
963    The numerical index in the index list of the index entry for the specified entity and
964    attribute, or C<undef> if no such index exists.
965    
966    =back
967    
968    =cut
969    
970    sub FindIndexForEntity {
971        # Get the parameters.
972        my ($xml, $entityName, $attributeName) = @_;
973        # Declare the return variable.
974        my $retVal;
975        # Get the named entity.
976        my $entityData = $xml->{Entities}->{$entityName};
977        if (! $entityData) {
978            Confess("Entity $entityName not found in DBD structure.");
979        } else {
980            # Insure it has an index list.
981            if (! exists $entityData->{Indexes}) {
982                $entityData->{Indexes} = [];
983            } else {
984                # Search for the desired index.
985                my $indexList = $entityData->{Indexes};
986                my $n = scalar @{$indexList};
987                Trace("Searching $n indexes in index list for $entityName.") if T(2);
988                # We use an indexed FOR here because we're returning an
989                # index number instead of an object. We do THAT so we can
990                # delete the index from the list if needed.
991                for (my $i = 0; $i < $n && !defined($retVal); $i++) {
992                    my $index = $indexList->[$i];
993                    my $fields = $index->{IndexFields};
994                    # Technically this IF should be safe (that is, we are guaranteed
995                    # the existence of a "$fields->[0]"), because when we load the XML
996                    # we have SuppressEmpty specified.
997                    if ($fields->[0]->{name} eq $attributeName) {
998                        $retVal = $i;
999                    }
1000                }
1001            }
1002        }
1003        Trace("Index for $attributeName of $entityName found at position $retVal.") if defined($retVal) && T(3);
1004        Trace("Index for $attributeName not found in $entityName.") if !defined($retVal) && T(3);
1005        # Return the result.
1006        return $retVal;
1007    }
1008    
1009  =head3 CreateTables  =head3 CreateTables
1010    
1011  C<< $erdb->CreateTables(); >>      $erdb->CreateTables();
1012    
1013  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
1014  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 1025 
1025      # Loop through the relations.      # Loop through the relations.
1026      for my $relationName (@relNames) {      for my $relationName (@relNames) {
1027          # Create a table for this relation.          # Create a table for this relation.
1028          $self->CreateTable($relationName);          $self->CreateTable($relationName, 1);
1029          Trace("Relation $relationName created.") if T(2);          Trace("Relation $relationName created.") if T(2);
1030      }      }
1031  }  }
1032    
1033  =head3 CreateTable  =head3 CreateTable
1034    
1035  C<< $erdb->CreateTable($tableName, $indexFlag, $estimatedRows); >>      $erdb->CreateTable($tableName, $indexFlag, $estimatedRows);
1036    
1037  Create the table for a relation and optionally create its indexes.  Create the table for a relation and optionally create its indexes.
1038    
# Line 665  Line 1074 
1074          # Push the result into the field list.          # Push the result into the field list.
1075          push @fieldList, $fieldString;          push @fieldList, $fieldString;
1076      }      }
     # 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";  
     }  
1077      # Convert the field list into a comma-delimited string.      # Convert the field list into a comma-delimited string.
1078      my $fieldThing = join(', ', @fieldList);      my $fieldThing = join(', ', @fieldList);
1079      # Insure the table is not already there.      # Insure the table is not already there.
# Line 679  Line 1084 
1084      my $estimation = undef;      my $estimation = undef;
1085      if ($estimatedRows) {      if ($estimatedRows) {
1086          $estimation = [$self->EstimateRowSize($relationName), $estimatedRows];          $estimation = [$self->EstimateRowSize($relationName), $estimatedRows];
1087            Trace("$estimation->[1] rows of $estimation->[0] bytes each.") if T(3);
1088      }      }
1089      # Create the table.      # Create the table.
1090      Trace("Creating table $relationName: $fieldThing") if T(2);      Trace("Creating table $relationName: $fieldThing") if T(2);
1091      $dbh->create_table(tbl => $relationName, flds => $fieldThing, estimates => $estimation);      $dbh->create_table(tbl => $relationName, flds => $fieldThing, estimates => $estimation);
1092      Trace("Relation $relationName created in database.") if T(2);      Trace("Relation $relationName created in database.") if T(2);
1093      # 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
1094        # index will not be built until the table has been loaded.
1095      if ($indexFlag) {      if ($indexFlag) {
1096          $self->CreateIndex($relationName);          $self->CreateIndex($relationName);
1097      }      }
# Line 692  Line 1099 
1099    
1100  =head3 VerifyFields  =head3 VerifyFields
1101    
1102  C<< my $count = $erdb->VerifyFields($relName, \@fieldList); >>      my $count = $erdb->VerifyFields($relName, \@fieldList);
1103    
1104  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
1105  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 1142 
1142              my $oldString = $fieldList->[$i];              my $oldString = $fieldList->[$i];
1143              if (length($oldString) > $maxLen) {              if (length($oldString) > $maxLen) {
1144                  # Here it's too big, so we truncate it.                  # Here it's too big, so we truncate it.
1145                  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);
1146                  $fieldList->[$i] = substr $oldString, 0, $maxLen;                  $fieldList->[$i] = substr $oldString, 0, $maxLen;
1147                  $retVal++;                  $retVal++;
1148              }              }
# Line 747  Line 1154 
1154    
1155  =head3 DigestFields  =head3 DigestFields
1156    
1157  C<< $erdb->DigestFields($relName, $fieldList); >>      $erdb->DigestFields($relName, $fieldList);
1158    
1159  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
1160  specified relation.  specified relation.
# Line 787  Line 1194 
1194    
1195  =head3 DigestKey  =head3 DigestKey
1196    
1197  C<< my $digested = $erdb->DigestKey($keyValue); >>      my $digested = $erdb->DigestKey($keyValue);
1198    
1199  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
1200  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 1227 
1227    
1228  =head3 CreateIndex  =head3 CreateIndex
1229    
1230  C<< $erdb->CreateIndex($relationName); >>      $erdb->CreateIndex($relationName);
1231    
1232  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
1233  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 1248 
1248      for my $indexName (keys %{$indexHash}) {      for my $indexName (keys %{$indexHash}) {
1249          my $indexData = $indexHash->{$indexName};          my $indexData = $indexHash->{$indexName};
1250          # Get the index's field list.          # Get the index's field list.
1251          my @fieldList = _FixNames(@{$indexData->{IndexFields}});          my @rawFields = @{$indexData->{IndexFields}};
1252            # Get a hash of the relation's field types.
1253            my %types = map { $_->{name} => $_->{type} } @{$relationData->{Fields}};
1254            # We need to check for text fields so we can append a length limitation for them. To do
1255            # that, we need the relation's field list.
1256            my $relFields = $relationData->{Fields};
1257            for (my $i = 0; $i <= $#rawFields; $i++) {
1258                # Get the field type.
1259                my $field = $rawFields[$i];
1260                my $type = $types{$field};
1261                # Ask if it requires using prefix notation for the index.
1262                my $mod = $TypeTable{$type}->{indexMod};
1263                Trace("Field $field ($i) in $relationName has type $type and indexMod $mod.") if T(3);
1264                if ($mod) {
1265                    # Append the prefix length to the field name,
1266                    $rawFields[$i] .= "($mod)";
1267                }
1268            }
1269            my @fieldList = _FixNames(@rawFields);
1270          my $flds = join(', ', @fieldList);          my $flds = join(', ', @fieldList);
1271          # Get the index's uniqueness flag.          # Get the index's uniqueness flag.
1272          my $unique = (exists $indexData->{Unique} ? $indexData->{Unique} : 'false');          my $unique = (exists $indexData->{Unique} ? 'unique' : undef);
1273          # Create the index.          # Create the index.
1274          my $rv = $dbh->create_index(idx => $indexName, tbl => $relationName,          my $rv = $dbh->create_index(idx => $indexName, tbl => $relationName,
1275                                      flds => $flds, unique => $unique);                                      flds => $flds, kind => $unique);
1276          if ($rv) {          if ($rv) {
1277              Trace("Index created: $indexName for $relationName ($flds)") if T(1);              Trace("Index created: $indexName for $relationName ($flds)") if T(1);
1278          } else {          } else {
# Line 856  Line 1281 
1281      }      }
1282  }  }
1283    
1284    =head3 GetSecondaryFields
1285    
1286        my %fieldTuples = $erdb->GetSecondaryFields($entityName);
1287    
1288    This method will return a list of the name and type of each of the secondary
1289    fields for a specified entity. Secondary fields are stored in two-column tables
1290    in addition to the primary entity table. This enables the field to have no value
1291    or to have multiple values.
1292    
1293    =over 4
1294    
1295    =item entityName
1296    
1297    Name of the entity whose secondary fields are desired.
1298    
1299    =item RETURN
1300    
1301    Returns a hash mapping the field names to their field types.
1302    
1303    =back
1304    
1305    =cut
1306    
1307    sub GetSecondaryFields {
1308        # Get the parameters.
1309        my ($self, $entityName) = @_;
1310        # Declare the return variable.
1311        my %retVal = ();
1312        # Look for the entity.
1313        my $table = $self->GetFieldTable($entityName);
1314        # Loop through the fields, pulling out the secondaries.
1315        for my $field (sort keys %{$table}) {
1316            if ($table->{$field}->{relation} ne $entityName) {
1317                # Here we have a secondary field.
1318                $retVal{$field} = $table->{$field}->{type};
1319            }
1320        }
1321        # Return the result.
1322        return %retVal;
1323    }
1324    
1325    =head3 GetFieldRelationName
1326    
1327        my $name = $erdb->GetFieldRelationName($objectName, $fieldName);
1328    
1329    Return the name of the relation containing a specified field.
1330    
1331    =over 4
1332    
1333    =item objectName
1334    
1335    Name of the entity or relationship containing the field.
1336    
1337    =item fieldName
1338    
1339    Name of the relevant field in that entity or relationship.
1340    
1341    =item RETURN
1342    
1343    Returns the name of the database relation containing the field, or C<undef> if
1344    the field does not exist.
1345    
1346    =back
1347    
1348    =cut
1349    
1350    sub GetFieldRelationName {
1351        # Get the parameters.
1352        my ($self, $objectName, $fieldName) = @_;
1353        # Declare the return variable.
1354        my $retVal;
1355        # Get the object field table.
1356        my $table = $self->GetFieldTable($objectName);
1357        # Only proceed if the field exists.
1358        if (exists $table->{$fieldName}) {
1359            # Determine the name of the relation that contains this field.
1360            $retVal = $table->{$fieldName}->{relation};
1361        }
1362        # Return the result.
1363        return $retVal;
1364    }
1365    
1366    =head3 DeleteValue
1367    
1368        my $numDeleted = $erdb->DeleteValue($entityName, $id, $fieldName, $fieldValue);
1369    
1370    Delete secondary field values from the database. This method can be used to delete all
1371    values of a specified field for a particular entity instance, or only a single value.
1372    
1373    Secondary fields are stored in two-column relations separate from an entity's primary
1374    table, and as a result a secondary field can legitimately have no value or multiple
1375    values. Therefore, it makes sense to talk about deleting secondary fields where it
1376    would not make sense for primary fields.
1377    
1378    =over 4
1379    
1380    =item entityName
1381    
1382    Name of the entity from which the fields are to be deleted.
1383    
1384    =item id
1385    
1386    ID of the entity instance to be processed. If the instance is not found, this
1387    method will have no effect. If C<undef> is specified, all values for all of
1388    the entity instances will be deleted.
1389    
1390    =item fieldName
1391    
1392    Name of the field whose values are to be deleted.
1393    
1394    =item fieldValue (optional)
1395    
1396    Value to be deleted. If not specified, then all values of the specified field
1397    will be deleted for the entity instance. If specified, then only the values which
1398    match this parameter will be deleted.
1399    
1400    =item RETURN
1401    
1402    Returns the number of rows deleted.
1403    
1404    =back
1405    
1406    =cut
1407    
1408    sub DeleteValue {
1409        # Get the parameters.
1410        my ($self, $entityName, $id, $fieldName, $fieldValue) = @_;
1411        # Declare the return value.
1412        my $retVal = 0;
1413        # We need to set up an SQL command to do the deletion. First, we
1414        # find the name of the field's relation.
1415        my $table = $self->GetFieldTable($entityName);
1416        my $field = $table->{$fieldName};
1417        my $relation = $field->{relation};
1418        # Make sure this is a secondary field.
1419        if ($relation eq $entityName) {
1420            Confess("Cannot delete values of $fieldName for $entityName.");
1421        } else {
1422            # Set up the SQL command to delete all values.
1423            my $sql = "DELETE FROM $relation";
1424            # Build the filter.
1425            my @filters = ();
1426            my @parms = ();
1427            # Check for a filter by ID.
1428            if (defined $id) {
1429                push @filters, "id = ?";
1430                push @parms, $id;
1431            }
1432            # Check for a filter by value.
1433            if (defined $fieldValue) {
1434                push @filters, "$fieldName = ?";
1435                push @parms, $fieldValue;
1436            }
1437            # Append the filters to the command.
1438            if (@filters) {
1439                $sql .= " WHERE " . join(" AND ", @filters);
1440            }
1441            # Execute the command.
1442            my $dbh = $self->{_dbh};
1443            $retVal = $dbh->SQL($sql, 0, @parms);
1444        }
1445        # Return the result.
1446        return $retVal;
1447    }
1448    
1449  =head3 LoadTables  =head3 LoadTables
1450    
1451  C<< my $stats = $erdb->LoadTables($directoryName, $rebuild); >>      my $stats = $erdb->LoadTables($directoryName, $rebuild);
1452    
1453  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
1454  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 1508 
1508    
1509  =head3 GetTableNames  =head3 GetTableNames
1510    
1511  C<< my @names = $erdb->GetTableNames; >>      my @names = $erdb->GetTableNames;
1512    
1513  Return a list of the relations required to implement this database.  Return a list of the relations required to implement this database.
1514    
# Line 935  Line 1525 
1525    
1526  =head3 GetEntityTypes  =head3 GetEntityTypes
1527    
1528  C<< my @names = $erdb->GetEntityTypes; >>      my @names = $erdb->GetEntityTypes;
1529    
1530  Return a list of the entity type names.  Return a list of the entity type names.
1531    
# Line 950  Line 1540 
1540      return sort keys %{$entityList};      return sort keys %{$entityList};
1541  }  }
1542    
1543    
1544    =head3 GetConnectingRelationships
1545    
1546        my @list = $erdb->GetConnectingRelationships($entityName);
1547    
1548    Return a list of the relationships connected to the specified entity.
1549    
1550    =over 4
1551    
1552    =item entityName
1553    
1554    Entity whose connected relationships are desired.
1555    
1556    =item RETURN
1557    
1558    Returns a list of the relationships that originate from the entity.
1559    If the entity is on the from end, it will return the relationship
1560    name. If the entity is on the to end it will return the converse of
1561    the relationship name.
1562    
1563    =back
1564    
1565    =cut
1566    
1567    sub GetConnectingRelationships {
1568        # Get the parameters.
1569        my ($self, $entityName) = @_;
1570        # Declare the return variable.
1571        my @retVal;
1572        # Get the relationship list.
1573        my $relationships = $self->{_metaData}->{Relationships};
1574        # Find the entity.
1575        my $entity = $self->{_metaData}->{Entities}->{$entityName};
1576        # Only proceed if the entity exists.
1577        if (! defined $entity) {
1578            Trace("Entity $entityName not found.") if T(3);
1579        } else {
1580            # Loop through the relationships.
1581            my @rels = keys %$relationships;
1582            Trace(scalar(@rels) . " relationships found in connection search.") if T(3);
1583            for my $relationshipName (@rels) {
1584                my $relationship = $relationships->{$relationshipName};
1585                if ($relationship->{from} eq $entityName) {
1586                    # Here we have a forward relationship.
1587                    push @retVal, $relationshipName;
1588                } elsif ($relationship->{to} eq $entityName) {
1589                    # Here we have a backward relationship. In this case, the
1590                    # converse relationship name is preferred if it exists.
1591                    my $converse = $relationship->{converse} || $relationshipName;
1592                    push @retVal, $converse;
1593                }
1594            }
1595        }
1596        # Return the result.
1597        return @retVal;
1598    }
1599    
1600    
1601    =head3 GetDataTypes
1602    
1603        my %types = ERDB::GetDataTypes();
1604    
1605    Return a table of ERDB data types. The table returned is a hash of hashes.
1606    The keys of the big hash are the datatypes. Each smaller hash has several
1607    values used to manage the data. The most interesting is the SQL type (key
1608    C<sqlType>) and the descriptive node (key C<notes>).
1609    
1610    Note that changing the values in the smaller hashes will seriously break
1611    things, so this data should be treated as read-only.
1612    
1613    =cut
1614    
1615    sub GetDataTypes {
1616        return %TypeTable;
1617    }
1618    
1619    
1620  =head3 IsEntity  =head3 IsEntity
1621    
1622  C<< my $flag = $erdb->IsEntity($entityName); >>      my $flag = $erdb->IsEntity($entityName);
1623    
1624  Return TRUE if the parameter is an entity name, else FALSE.  Return TRUE if the parameter is an entity name, else FALSE.
1625    
# Line 979  Line 1646 
1646    
1647  =head3 Get  =head3 Get
1648    
1649  C<< my $query = $erdb->Get(\@objectNames, $filterClause, \@params); >>      my $query = $erdb->Get(\@objectNames, $filterClause, \@params);
1650    
1651  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.
1652  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 1654 
1654  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
1655  $genus.  $genus.
1656    
1657  C<< $query = $erdb->Get(['Genome'], "Genome(genus) = ?", [$genus]); >>      $query = $erdb->Get(['Genome'], "Genome(genus) = ?", [$genus]);
1658    
1659  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
1660  parameter representing the parameter value. It would also be possible to code  parameter representing the parameter value. It would also be possible to code
1661    
1662  C<< $query = $erdb->Get(['Genome'], "Genome(genus) = \'$genus\'"); >>      $query = $erdb->Get(['Genome'], "Genome(genus) = \'$genus\'");
1663    
1664  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
1665  characters inside the variable C<$genus>.  characters inside the variable C<$genus>.
# Line 1004  Line 1671 
1671  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
1672  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,
1673    
1674  C<< $query = $erdb->Get(['Genome', 'ComesFrom', 'Source'], "Genome(genus) = ?", [$genus]); >>      $query = $erdb->Get(['Genome', 'ComesFrom', 'Source'], "Genome(genus) = ?", [$genus]);
1675    
1676  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
1677  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 1707 
1707  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
1708  particular genus and sorts them by species name.  particular genus and sorts them by species name.
1709    
1710  C<< "Genome(genus) = ? ORDER BY Genome(species)" >>      "Genome(genus) = ? ORDER BY Genome(species)"
1711    
1712  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
1713  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 1720 
1720  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
1721  a positive number. So, for example  a positive number. So, for example
1722    
1723  C<< "Genome(genus) = ? ORDER BY Genome(species) LIMIT 10" >>      "Genome(genus) = ? ORDER BY Genome(species) LIMIT 10"
1724    
1725  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
1726  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
1727  use  use
1728    
1729  C<< "LIMIT 10" >>      "LIMIT 10"
1730    
1731  =item params  =item params
1732    
# Line 1080  Line 1747 
1747      my ($suffix, $mappedNameListRef, $mappedNameHashRef) =      my ($suffix, $mappedNameListRef, $mappedNameHashRef) =
1748          $self->_SetupSQL($objectNames, $filterClause);          $self->_SetupSQL($objectNames, $filterClause);
1749      # Create the query.      # Create the query.
1750      my $command = "SELECT DISTINCT " . join(".*, ", @{$mappedNameListRef}) .      my $command = "SELECT " . join(".*, ", @{$mappedNameListRef}) .
1751          ".* $suffix";          ".* $suffix";
1752      my $sth = $self->_GetStatementHandle($command, $params);      my $sth = $self->_GetStatementHandle($command, $params);
1753      # 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 1761 
1761      return $retVal;      return $retVal;
1762  }  }
1763    
 =head3 GetFlat  
1764    
 C<< my @list = $erdb->GetFlat(\@objectNames, $filterClause, \@parameterList, $field); >>  
1765    
1766  This is a variation of L</GetAll> that asks for only a single field per record and  =head3 Search
1767  returns a single flattened list.  
1768        my $query = $erdb->Search($searchExpression, $idx, \@objectNames, $filterClause, \@params);
1769    
1770    Perform a full text search with filtering. The search will be against a specified object
1771    in the object name list. That object will get an extra field containing the search
1772    relevance. Note that except for the search expression, the parameters of this method are
1773    the same as those for L</Get> and follow the same rules.
1774    
1775  =over 4  =over 4
1776    
1777  =item objectNames  =item searchExpression
1778    
1779    Boolean search expression for the text fields of the target object. The default mode for
1780    a Boolean search expression is OR, but we want the default to be AND, so we will
1781    add a C<+> operator to each word with no other operator before it.
1782    
1783    =item idx
1784    
1785    Index in the I<$objectNames> list of the table to be searched in full-text mode.
1786    
1787    =item objectNames
1788    
1789    List containing the names of the entity and relationship objects to be retrieved.
1790    
1791    =item filterClause
1792    
1793    WHERE clause (without the WHERE) to be used to filter and sort the query. The WHERE clause can
1794    be parameterized with parameter markers (C<?>). Each field used in the WHERE clause must be
1795    specified in the standard form B<I<objectName>(I<fieldName>)>. Any parameters specified
1796    in the filter clause should be added to the parameter list as additional parameters. The
1797    fields in a filter clause can come from primary entity relations, relationship relations,
1798    or secondary entity relations; however, all of the entities and relationships involved must
1799    be included in the list of object names.
1800    
1801    =item params
1802    
1803    Reference to a list of parameter values to be substituted into the filter clause.
1804    
1805    =item RETURN
1806    
1807    Returns a query object for the specified search.
1808    
1809    =back
1810    
1811    =cut
1812    
1813    sub Search {
1814        # Get the parameters.
1815        my ($self, $searchExpression, $idx, $objectNames, $filterClause, $params) = @_;
1816        # Declare the return variable.
1817        my $retVal;
1818        # Create a safety copy of the parameter list. Note we have to be careful to insure
1819        # a parameter list exists before we copy it.
1820        my @myParams = ();
1821        if (defined $params) {
1822            @myParams = @{$params};
1823        }
1824        # Get the first object's structure so we have access to the searchable fields.
1825        my $object1Name = $objectNames->[$idx];
1826        my $object1Structure = $self->_GetStructure($object1Name);
1827        # Get the field list.
1828        if (! exists $object1Structure->{searchFields}) {
1829            Confess("No searchable index for $object1Name.");
1830        } else {
1831            # Get the field list.
1832            my @fields = @{$object1Structure->{searchFields}};
1833            # Clean the search expression.
1834            my $actualKeywords = $self->CleanKeywords($searchExpression);
1835            # Prefix a "+" to each uncontrolled word. This converts the default
1836            # search mode from OR to AND.
1837            $actualKeywords =~ s/(^|\s)(\w|")/$1\+$2/g;
1838            Trace("Actual keywords for search are\n$actualKeywords") if T(3);
1839            # We need two match expressions, one for the filter clause and one in the
1840            # query itself. Both will use a parameter mark, so we need to push the
1841            # search expression onto the front of the parameter list twice.
1842            unshift @myParams, $actualKeywords, $actualKeywords;
1843            # Build the match expression.
1844            my @matchFilterFields = map { "$object1Name." . _FixName($_) } @fields;
1845            my $matchClause = "MATCH (" . join(", ", @matchFilterFields) . ") AGAINST (? IN BOOLEAN MODE)";
1846            # Process the SQL stuff.
1847            my ($suffix, $mappedNameListRef, $mappedNameHashRef) =
1848                $self->_SetupSQL($objectNames, $filterClause, $matchClause);
1849            # Create the query. Note that the match clause is inserted at the front of
1850            # the select fields.
1851            my $command = "SELECT $matchClause, " . join(".*, ", @{$mappedNameListRef}) .
1852                ".* $suffix";
1853            my $sth = $self->_GetStatementHandle($command, \@myParams);
1854            # Now we create the relation map, which enables DBQuery to determine the order, name
1855            # and mapped name for each object in the query.
1856            my @relationMap = _RelationMap($mappedNameHashRef, $mappedNameListRef);
1857            # Return the statement object.
1858            $retVal = DBQuery::_new($self, $sth, \@relationMap, $object1Name);
1859        }
1860        return $retVal;
1861    }
1862    
1863    =head3 GetFlat
1864    
1865        my @list = $erdb->GetFlat(\@objectNames, $filterClause, \@parameterList, $field);
1866    
1867    This is a variation of L</GetAll> that asks for only a single field per record and
1868    returns a single flattened list.
1869    
1870    =over 4
1871    
1872    =item objectNames
1873    
1874  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.
1875    
# Line 1147  Line 1913 
1913      return @retVal;      return @retVal;
1914  }  }
1915    
1916    =head3 SpecialFields
1917    
1918        my %specials = $erdb->SpecialFields($entityName);
1919    
1920    Return a hash mapping special fields in the specified entity to the value of their
1921    C<special> attribute. This enables the subclass to get access to the special field
1922    attributes without needed to plumb the internal ERDB data structures.
1923    
1924    =over 4
1925    
1926    =item entityName
1927    
1928    Name of the entity whose special fields are desired.
1929    
1930    =item RETURN
1931    
1932    Returns a hash. The keys of the hash are the special field names, and the values
1933    are the values from each special field's C<special> attribute.
1934    
1935    =back
1936    
1937    =cut
1938    
1939    sub SpecialFields {
1940        # Get the parameters.
1941        my ($self, $entityName) = @_;
1942        # Declare the return variable.
1943        my %retVal = ();
1944        # Find the entity's data structure.
1945        my $entityData = $self->{_metaData}->{Entities}->{$entityName};
1946        # Loop through its fields, adding each special field to the return hash.
1947        my $fieldHash = $entityData->{Fields};
1948        for my $fieldName (keys %{$fieldHash}) {
1949            my $fieldData = $fieldHash->{$fieldName};
1950            if (exists $fieldData->{special}) {
1951                $retVal{$fieldName} = $fieldData->{special};
1952            }
1953        }
1954        # Return the result.
1955        return %retVal;
1956    }
1957    
1958  =head3 Delete  =head3 Delete
1959    
1960  C<< my $stats = $erdb->Delete($entityName, $objectID); >>      my $stats = $erdb->Delete($entityName, $objectID, %options);
1961    
1962  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
1963  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.
1964  always dependent on itself. An object is dependent if it is a 1-to-many or many-to-many  
1965  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
1966    relationship connected to a dependent entity or if it is the "to" entity connected to a 1-to-many
1967  dependent relationship.  dependent relationship.
1968    
1969  =over 4  =over 4
# Line 1168  Line 1977 
1977  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<%>),
1978  then it is presumed to by a LIKE pattern.  then it is presumed to by a LIKE pattern.
1979    
1980  =item testFlag  =item options
1981    
1982  If TRUE, the delete statements will be traced without being executed.  A hash detailing the options for this delete operation.
1983    
1984  =item RETURN  =item RETURN
1985    
# Line 1179  Line 1988 
1988    
1989  =back  =back
1990    
1991    The permissible options for this method are as follows.
1992    
1993    =over 4
1994    
1995    =item testMode
1996    
1997    If TRUE, then the delete statements will be traced, but no changes will be made to the database.
1998    
1999    =item keepRoot
2000    
2001    If TRUE, then the entity instances will not be deleted, only the dependent records.
2002    
2003    =back
2004    
2005  =cut  =cut
2006  #: Return Type $%;  #: Return Type $%;
2007  sub Delete {  sub Delete {
2008      # Get the parameters.      # Get the parameters.
2009      my ($self, $entityName, $objectID, $testFlag) = @_;      my ($self, $entityName, $objectID, %options) = @_;
2010      # Declare the return variable.      # Declare the return variable.
2011      my $retVal = Stats->new();      my $retVal = Stats->new();
2012      # Get the DBKernel object.      # Get the DBKernel object.
# Line 1200  Line 2023 
2023      # FROM-relationships and entities.      # FROM-relationships and entities.
2024      my @fromPathList = ();      my @fromPathList = ();
2025      my @toPathList = ();      my @toPathList = ();
2026      # 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
2027      # 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
2028      # 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
2029      # TODO list is always an entity.      # to-do list is always an entity.
2030      my @todoList = ([$entityName]);      my @todoList = ([$entityName]);
2031      while (@todoList) {      while (@todoList) {
2032          # Get the current path.          # Get the current path.
# Line 1211  Line 2034 
2034          # Copy it into a list.          # Copy it into a list.
2035          my @stackedPath = @{$current};          my @stackedPath = @{$current};
2036          # 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.
2037          my $entityName = pop @stackedPath;          my $myEntityName = pop @stackedPath;
2038          # Add it to the alreadyFound list.          # Add it to the alreadyFound list.
2039          $alreadyFound{$entityName} = 1;          $alreadyFound{$myEntityName} = 1;
2040            # Figure out if we need to delete this entity.
2041            if ($myEntityName ne $entityName || ! $options{keepRoot}) {
2042          # Get the entity data.          # Get the entity data.
2043          my $entityData = $self->_GetStructure($entityName);              my $entityData = $self->_GetStructure($myEntityName);
2044          # 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.  
2045          my $relations = $entityData->{Relations};          my $relations = $entityData->{Relations};
2046          for my $relation (keys %{$relations}) {          for my $relation (keys %{$relations}) {
2047              my @augmentedList = (@stackedPath, $relation);              my @augmentedList = (@stackedPath, $relation);
2048              push @fromPathList, \@augmentedList;              push @fromPathList, \@augmentedList;
2049          }          }
2050            }
2051          # Now we need to look for relationships connected to this entity.          # Now we need to look for relationships connected to this entity.
2052          my $relationshipList = $self->{_metaData}->{Relationships};          my $relationshipList = $self->{_metaData}->{Relationships};
2053          for my $relationshipName (keys %{$relationshipList}) {          for my $relationshipName (keys %{$relationshipList}) {
2054              my $relationship = $relationshipList->{$relationshipName};              my $relationship = $relationshipList->{$relationshipName};
2055              # Check the FROM field. We're only interested if it's us.              # Check the FROM field. We're only interested if it's us.
2056              if ($relationship->{from} eq $entityName) {              if ($relationship->{from} eq $myEntityName) {
2057                  # Add the path to this relationship.                  # Add the path to this relationship.
2058                  my @augmentedList = (@stackedPath, $entityName, $relationshipName);                  my @augmentedList = (@stackedPath, $myEntityName, $relationshipName);
2059                  push @fromPathList, \@augmentedList;                  push @fromPathList, \@augmentedList;
2060                  # 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
2061                  # 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 2074 
2074              }              }
2075              # Now check the TO field. In this case only the relationship needs              # Now check the TO field. In this case only the relationship needs
2076              # deletion.              # deletion.
2077              if ($relationship->{to} eq $entityName) {              if ($relationship->{to} eq $myEntityName) {
2078                  my @augmentedList = (@stackedPath, $entityName, $relationshipName);                  my @augmentedList = (@stackedPath, $myEntityName, $relationshipName);
2079                  push @toPathList, \@augmentedList;                  push @toPathList, \@augmentedList;
2080              }              }
2081          }          }
2082      }      }
2083      # Create the first qualifier for the WHERE clause. This selects the      # Create the first qualifier for the WHERE clause. This selects the
2084      # 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
2085      # 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
2086      # to the table containing the dependent records to delete.      # to the table containing the dependent records to delete.
2087      my $qualifier = ($objectID =~ /%/ ? "LIKE ?" : "= ?");      my $qualifier = ($objectID =~ /%/ ? "LIKE ?" : "= ?");
2088      # 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 2121 
2121                  }                  }
2122              }              }
2123              # Now we have our desired DELETE statement.              # Now we have our desired DELETE statement.
2124              if ($testFlag) {              if ($options{testMode}) {
2125                  # Here the user wants to trace without executing.                  # Here the user wants to trace without executing.
2126                  Trace($stmt) if T(0);                  Trace($stmt) if T(0);
2127              } else {              } else {
2128                  # 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
2129                  # if an error occurs, so we just go ahead and do it.                  # if an error occurs, so we just go ahead and do it.
2130                  Trace("Executing delete from $target using '$objectID'.") if T(3);                  Trace("Executing delete from $target using '$objectID'.") if T(3);
2131                  my $rv = $db->SQL($stmt, 0, $objectID);                  my $rv = $db->SQL($stmt, 0, $objectID);
# Line 1315  Line 2140 
2140      return $retVal;      return $retVal;
2141  }  }
2142    
2143    =head3 Disconnect
2144    
2145        $erdb->Disconnect($relationshipName, $originEntityName, $originEntityID);
2146    
2147    Disconnect an entity instance from all the objects to which it is related. This
2148    will delete each relationship instance that connects to the specified entity.
2149    
2150    =over 4
2151    
2152    =item relationshipName
2153    
2154    Name of the relationship whose instances are to be deleted.
2155    
2156    =item originEntityName
2157    
2158    Name of the entity that is to be disconnected.
2159    
2160    =item originEntityID
2161    
2162    ID of the entity that is to be disconnected.
2163    
2164    =back
2165    
2166    =cut
2167    
2168    sub Disconnect {
2169        # Get the parameters.
2170        my ($self, $relationshipName, $originEntityName, $originEntityID) = @_;
2171        # Get the relationship descriptor.
2172        my $structure = $self->_GetStructure($relationshipName);
2173        # Insure we have a relationship.
2174        if (! exists $structure->{from}) {
2175            Confess("$relationshipName is not a relationship in the database.");
2176        } else {
2177            # Get the database handle.
2178            my $dbh = $self->{_dbh};
2179            # We'll set this value to 1 if we find our entity.
2180            my $found = 0;
2181            # Loop through the ends of the relationship.
2182            for my $dir ('from', 'to') {
2183                if ($structure->{$dir} eq $originEntityName) {
2184                    $found = 1;
2185                    # Here we want to delete all relationship instances on this side of the
2186                    # entity instance.
2187                    Trace("Disconnecting in $dir direction with ID \"$originEntityID\".");
2188                    # We do this delete in batches to keep it from dragging down the
2189                    # server.
2190                    my $limitClause = ($FIG_Config::delete_limit ? "LIMIT $FIG_Config::delete_limit" : "");
2191                    my $done = 0;
2192                    while (! $done) {
2193                        # Do the delete.
2194                        my $rows = $dbh->SQL("DELETE FROM $relationshipName WHERE ${dir}_link = ? $limitClause", 0, $originEntityID);
2195                        # See if we're done. We're done if no rows were found or the delete is unlimited.
2196                        $done = ($rows == 0 || ! $limitClause);
2197                    }
2198                }
2199            }
2200            # Insure we found the entity on at least one end.
2201            if (! $found) {
2202                Confess("Entity \"$originEntityName\" does not use $relationshipName.");
2203            }
2204        }
2205    }
2206    
2207    =head3 DeleteRow
2208    
2209        $erdb->DeleteRow($relationshipName, $fromLink, $toLink, \%values);
2210    
2211    Delete a row from a relationship. In most cases, only the from-link and to-link are
2212    needed; however, for relationships with intersection data values can be specified
2213    for the other fields using a hash.
2214    
2215    =over 4
2216    
2217    =item relationshipName
2218    
2219    Name of the relationship from which the row is to be deleted.
2220    
2221    =item fromLink
2222    
2223    ID of the entity instance in the From direction.
2224    
2225    =item toLink
2226    
2227    ID of the entity instance in the To direction.
2228    
2229    =item values
2230    
2231    Reference to a hash of other values to be used for filtering the delete.
2232    
2233    =back
2234    
2235    =cut
2236    
2237    sub DeleteRow {
2238        # Get the parameters.
2239        my ($self, $relationshipName, $fromLink, $toLink, $values) = @_;
2240        # Create a hash of all the filter information.
2241        my %filter = ('from-link' => $fromLink, 'to-link' => $toLink);
2242        if (defined $values) {
2243            for my $key (keys %{$values}) {
2244                $filter{$key} = $values->{$key};
2245            }
2246        }
2247        # Build an SQL statement out of the hash.
2248        my @filters = ();
2249        my @parms = ();
2250        for my $key (keys %filter) {
2251            push @filters, _FixName($key) . " = ?";
2252            push @parms, $filter{$key};
2253        }
2254        Trace("Parms for delete row are " . join(", ", map { "\"$_\"" } @parms) . ".") if T(SQL => 4);
2255        my $command = "DELETE FROM $relationshipName WHERE " .
2256                      join(" AND ", @filters);
2257        # Execute it.
2258        my $dbh = $self->{_dbh};
2259        $dbh->SQL($command, undef, @parms);
2260    }
2261    
2262    =head3 DeleteLike
2263    
2264        my $deleteCount = $erdb->DeleteLike($relName, $filter, \@parms);
2265    
2266    Delete all the relationship rows that satisfy a particular filter condition. Unlike a normal
2267    filter, only fields from the relationship itself can be used.
2268    
2269    =over 4
2270    
2271    =item relName
2272    
2273    Name of the relationship whose records are to be deleted.
2274    
2275    =item filter
2276    
2277    A filter clause (L</Get>-style) for the delete query.
2278    
2279    =item parms
2280    
2281    Reference to a list of parameters for the filter clause.
2282    
2283    =item RETURN
2284    
2285    Returns a count of the number of rows deleted.
2286    
2287    =back
2288    
2289    =cut
2290    
2291    sub DeleteLike {
2292        # Get the parameters.
2293        my ($self, $objectName, $filter, $parms) = @_;
2294        # Declare the return variable.
2295        my $retVal;
2296        # Insure the parms argument is an array reference if the caller left it off.
2297        if (! defined($parms)) {
2298            $parms = [];
2299        }
2300        # Insure we have a relationship. The main reason for this is if we delete an entity
2301        # instance we have to yank out a bunch of other stuff with it.
2302        if ($self->IsEntity($objectName)) {
2303            Confess("Cannot use DeleteLike on $objectName, because it is not a relationship.");
2304        } else {
2305            # Create the SQL command suffix to get the desierd records.
2306            my ($suffix) = $self->_SetupSQL([$objectName], $filter);
2307            # Convert it to a DELETE command.
2308            my $command = "DELETE $suffix";
2309            # Execute the command.
2310            my $dbh = $self->{_dbh};
2311            my $result = $dbh->SQL($command, 0, @{$parms});
2312            # Check the results. Note we convert the "0D0" result to a real zero.
2313            # A failure causes an abnormal termination, so the caller isn't going to
2314            # worry about it.
2315            if (! defined $result) {
2316                Confess("Error deleting from $objectName: " . $dbh->errstr());
2317            } elsif ($result == 0) {
2318                $retVal = 0;
2319            } else {
2320                $retVal = $result;
2321            }
2322        }
2323        # Return the result count.
2324        return $retVal;
2325    }
2326    
2327    =head3 SortNeeded
2328    
2329        my $parms = $erdb->SortNeeded($relationName);
2330    
2331    Return the pipe command for the sort that should be applied to the specified
2332    relation when creating the load file.
2333    
2334    For example, if the load file should be sorted ascending by the first
2335    field, this method would return
2336    
2337        sort -k1 -t"\t"
2338    
2339    If the first field is numeric, the method would return
2340    
2341        sort -k1n -t"\t"
2342    
2343    Unfortunately, due to a bug in the C<sort> command, we cannot eliminate duplicate
2344    keys using a sort.
2345    
2346    =over 4
2347    
2348    =item relationName
2349    
2350    Name of the relation to be examined.
2351    
2352    =item
2353    
2354    Returns the sort command to use for sorting the relation, suitable for piping.
2355    
2356    =back
2357    
2358    =cut
2359    #: Return Type $;
2360    sub SortNeeded {
2361        # Get the parameters.
2362        my ($self, $relationName) = @_;
2363        # Declare a descriptor to hold the names of the key fields.
2364        my @keyNames = ();
2365        # Get the relation structure.
2366        my $relationData = $self->_FindRelation($relationName);
2367        # Find out if the relation is a primary entity relation,
2368        # a relationship relation, or a secondary entity relation.
2369        my $entityTable = $self->{_metaData}->{Entities};
2370        my $relationshipTable = $self->{_metaData}->{Relationships};
2371        if (exists $entityTable->{$relationName}) {
2372            # Here we have a primary entity relation.
2373            push @keyNames, "id";
2374        } elsif (exists $relationshipTable->{$relationName}) {
2375            # Here we have a relationship. We sort using the FROM index.
2376            my $relationshipData = $relationshipTable->{$relationName};
2377            my $index = $relationData->{Indexes}->{idxFrom};
2378            push @keyNames, @{$index->{IndexFields}};
2379        } else {
2380            # Here we have a secondary entity relation, so we have a sort on the ID field.
2381            push @keyNames, "id";
2382        }
2383        # Now we parse the key names into sort parameters. First, we prime the return
2384        # string.
2385        my $retVal = "sort -S 1G -T\"$FIG_Config::temp\" -t\"\t\" ";
2386        # Get the relation's field list.
2387        my @fields = @{$relationData->{Fields}};
2388        # Loop through the keys.
2389        for my $keyData (@keyNames) {
2390            # Get the key and the ordering.
2391            my ($keyName, $ordering);
2392            if ($keyData =~ /^([^ ]+) DESC/) {
2393                ($keyName, $ordering) = ($1, "descending");
2394            } else {
2395                ($keyName, $ordering) = ($keyData, "ascending");
2396            }
2397            # Find the key's position and type.
2398            my $fieldSpec;
2399            for (my $i = 0; $i <= $#fields && ! $fieldSpec; $i++) {
2400                my $thisField = $fields[$i];
2401                if ($thisField->{name} eq $keyName) {
2402                    # Get the sort modifier for this field type. The modifier
2403                    # decides whether we're using a character, numeric, or
2404                    # floating-point sort.
2405                    my $modifier = $TypeTable{$thisField->{type}}->{sort};
2406                    # If the index is descending for this field, denote we want
2407                    # to reverse the sort order on this field.
2408                    if ($ordering eq 'descending') {
2409                        $modifier .= "r";
2410                    }
2411                    # Store the position and modifier into the field spec, which
2412                    # will stop the inner loop. Note that the field number is
2413                    # 1-based in the sort command, so we have to increment the
2414                    # index.
2415                    my $realI = $i + 1;
2416                    $fieldSpec = "$realI,$realI$modifier";
2417                }
2418            }
2419            # Add this field to the sort command.
2420            $retVal .= " -k$fieldSpec";
2421        }
2422        # Return the result.
2423        return $retVal;
2424    }
2425    
2426  =head3 GetList  =head3 GetList
2427    
2428  C<< my @dbObjects = $erdb->GetList(\@objectNames, $filterClause, \@params); >>      my @dbObjects = $erdb->GetList(\@objectNames, $filterClause, \@params);
2429    
2430  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
2431  specified filter clause.  specified filter clause.
# Line 1345  Line 2453 
2453  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
2454  particular genus and sorts them by species name.  particular genus and sorts them by species name.
2455    
2456  C<< "Genome(genus) = ? ORDER BY Genome(species)" >>      "Genome(genus) = ? ORDER BY Genome(species)"
2457    
2458  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
2459  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 2465 
2465    
2466  =item RETURN  =item RETURN
2467    
2468  Returns a list of B<DBObject>s that satisfy the query conditions.  Returns a list of B<ERDBObject>s that satisfy the query conditions.
2469    
2470  =back  =back
2471    
# Line 1380  Line 2488 
2488    
2489  =head3 GetCount  =head3 GetCount
2490    
2491  C<< my $count = $erdb->GetCount(\@objectNames, $filter, \@params); >>      my $count = $erdb->GetCount(\@objectNames, $filter, \@params);
2492    
2493  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
2494  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 1397  Line 2505 
2505  would return the number of features for genomes in the genus I<homo>. Note that  would return the number of features for genomes in the genus I<homo>. Note that
2506  only the rows from the first table are counted. If the above command were  only the rows from the first table are counted. If the above command were
2507    
2508      my $count = $erdb->GetCount(['Genome', 'Feature'], 'Genome(genus-species) LIKE ?',      my $count = $erdb->GetCount(['Genome', 'HasFeature'], 'Genome(genus-species) LIKE ?',
2509                                  ['homo %']);                                  ['homo %']);
2510    
2511  it would return the number of genomes, not the number of genome/feature pairs.  it would return the number of genomes, not the number of genome/feature pairs.
# Line 1431  Line 2539 
2539  sub GetCount {  sub GetCount {
2540      # Get the parameters.      # Get the parameters.
2541      my ($self, $objectNames, $filter, $params) = @_;      my ($self, $objectNames, $filter, $params) = @_;
2542        # Insure the params argument is an array reference if the caller left it off.
2543        if (! defined($params)) {
2544            $params = [];
2545        }
2546      # Declare the return variable.      # Declare the return variable.
2547      my $retVal;      my $retVal;
2548      # 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 2581 
2581    
2582  =head3 ComputeObjectSentence  =head3 ComputeObjectSentence
2583    
2584  C<< my $sentence = $erdb->ComputeObjectSentence($objectName); >>      my $sentence = $erdb->ComputeObjectSentence($objectName);
2585    
2586  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.
2587    
# Line 1504  Line 2616 
2616    
2617  =head3 DumpRelations  =head3 DumpRelations
2618    
2619  C<< $erdb->DumpRelations($outputDirectory); >>      $erdb->DumpRelations($outputDirectory);
2620    
2621  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.
2622  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 2656 
2656      }      }
2657  }  }
2658    
2659    =head3 InsertValue
2660    
2661        $erdb->InsertValue($entityID, $fieldName, $value);
2662    
2663    This method will insert a new value into the database. The value must be one
2664    associated with a secondary relation, since primary values cannot be inserted:
2665    they occur exactly once. Secondary values, on the other hand, can be missing
2666    or multiply-occurring.
2667    
2668    =over 4
2669    
2670    =item entityID
2671    
2672    ID of the object that is to receive the new value.
2673    
2674    =item fieldName
2675    
2676    Field name for the new value-- this includes the entity name, since
2677    field names are of the format I<objectName>C<(>I<fieldName>C<)>.
2678    
2679    =item value
2680    
2681    New value to be put in the field.
2682    
2683    =back
2684    
2685    =cut
2686    
2687    sub InsertValue {
2688        # Get the parameters.
2689        my ($self, $entityID, $fieldName, $value) = @_;
2690        # Parse the entity name and the real field name.
2691        if ($fieldName =~ /^([^(]+)\(([^)]+)\)/) {
2692            my $entityName = $1;
2693            my $fieldTitle = $2;
2694            # Get its descriptor.
2695            if (!$self->IsEntity($entityName)) {
2696                Confess("$entityName is not a valid entity.");
2697            } else {
2698                my $entityData = $self->{_metaData}->{Entities}->{$entityName};
2699                # Find the relation containing this field.
2700                my $fieldHash = $entityData->{Fields};
2701                if (! exists $fieldHash->{$fieldTitle}) {
2702                    Confess("$fieldTitle not found in $entityName.");
2703                } else {
2704                    my $relation = $fieldHash->{$fieldTitle}->{relation};
2705                    if ($relation eq $entityName) {
2706                        Confess("Cannot do InsertValue on primary field $fieldTitle of $entityName.");
2707                    } else {
2708                        # Now we can create an INSERT statement.
2709                        my $dbh = $self->{_dbh};
2710                        my $fixedName = _FixName($fieldTitle);
2711                        my $statement = "INSERT INTO $relation (id, $fixedName) VALUES(?, ?)";
2712                        # Execute the command.
2713                        $dbh->SQL($statement, 0, $entityID, $value);
2714                    }
2715                }
2716            }
2717        } else {
2718            Confess("$fieldName is not a valid field name.");
2719        }
2720    }
2721    
2722  =head3 InsertObject  =head3 InsertObject
2723    
2724  C<< my $ok = $erdb->InsertObject($objectType, \%fieldHash); >>      $erdb->InsertObject($objectType, \%fieldHash);
2725    
2726  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
2727  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 2730 
2730  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
2731  C<ZP_00210270.1> and C<gi|46206278>.  C<ZP_00210270.1> and C<gi|46206278>.
2732    
2733  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']});
2734    
2735  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
2736  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>.
2737    
2738  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'});
2739    
2740  =over 4  =over 4
2741    
# Line 1572  Line 2747 
2747    
2748  Hash of field names to values.  Hash of field names to values.
2749    
 =item RETURN  
   
 Returns 1 if successful, 0 if an error occurred.  
   
2750  =back  =back
2751    
2752  =cut  =cut
# Line 1633  Line 2804 
2804                  push @missing, $fieldName;                  push @missing, $fieldName;
2805              }              }
2806          }          }
         # If we are the primary relation, add the new-record flag.  
         if ($relationName eq $newObjectType) {  
             push @valueList, 1;  
             push @fieldNameList, "new_record";  
         }  
2807          # Only proceed if there are no missing fields.          # Only proceed if there are no missing fields.
2808          if (@missing > 0) {          if (@missing > 0) {
2809              Trace("Relation $relationName for $newObjectType skipped due to missing fields: " .              Trace("Relation $relationName for $newObjectType skipped due to missing fields: " .
# Line 1674  Line 2840 
2840                  $retVal = $sth->execute(@parameterList);                  $retVal = $sth->execute(@parameterList);
2841                  if (!$retVal) {                  if (!$retVal) {
2842                      my $errorString = $sth->errstr();                      my $errorString = $sth->errstr();
2843                      Trace("Insert error: $errorString.") if T(0);                      Confess("Error inserting into $relationName: $errorString");
2844                    } else {
2845                        Trace("Insert successful using $parameterList[0].") if T(3);
2846                  }                  }
2847              }              }
2848          }          }
2849      }      }
2850      # Return the success indicator.      # Return a 1 for backward compatability.
2851      return $retVal;      return 1;
2852  }  }
2853    
2854  =head3 LoadTable  =head3 UpdateEntity
2855    
2856  C<< my %results = $erdb->LoadTable($fileName, $relationName, $truncateFlag); >>      $erdb->UpdateEntity($entityName, $id, \%fields);
2857    
2858  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
2859  first.  done if the database resides on a database server.
2860    
2861  =over 4  =over 4
2862    
2863  =item fileName  =item entityName
2864    
2865    Name of the entity to update. (This is the entity type.)
2866    
2867    =item id
2868    
2869    ID of the entity to update. If no entity exists with this ID, an error will be thrown.
2870    
2871    =item fields
2872    
2873    Reference to a hash mapping field names to their new values. All of the fields named
2874    must be in the entity's primary relation, and they cannot any of them be the ID field.
2875    
2876    =back
2877    
2878    =cut
2879    
2880    sub UpdateEntity {
2881        # Get the parameters.
2882        my ($self, $entityName, $id, $fields) = @_;
2883        # Get a list of the field names being updated.
2884        my @fieldList = keys %{$fields};
2885        # Verify that the fields exist.
2886        my $checker = $self->GetFieldTable($entityName);
2887        for my $field (@fieldList) {
2888            if ($field eq 'id') {
2889                Confess("Cannot update the ID field for entity $entityName.");
2890            } elsif ($checker->{$field}->{relation} ne $entityName) {
2891                Confess("Cannot find $field in primary relation of $entityName.");
2892            }
2893        }
2894        # Build the SQL statement.
2895        my @sets = ();
2896        my @valueList = ();
2897        for my $field (@fieldList) {
2898            push @sets, _FixName($field) . " = ?";
2899            push @valueList, $fields->{$field};
2900        }
2901        my $command = "UPDATE $entityName SET " . join(", ", @sets) . " WHERE id = ?";
2902        # Add the ID to the list of binding values.
2903        push @valueList, $id;
2904        # Call SQL to do the work.
2905        my $rows = $self->{_dbh}->SQL($command, 0, @valueList);
2906        # Check for errors.
2907        if ($rows == 0) {
2908            Confess("Entity $id of type $entityName not found.");
2909        }
2910    }
2911    
2912    =head3 LoadTable
2913    
2914        my $results = $erdb->LoadTable($fileName, $relationName, %options);
2915    
2916    Load data from a tab-delimited file into a specified table, optionally re-creating the table
2917    first.
2918    
2919    =over 4
2920    
2921    =item fileName
2922    
2923  Name of the file from which the table data should be loaded.  Name of the file from which the table data should be loaded.
2924    
# Line 1700  Line 2926 
2926    
2927  Name of the relation to be loaded. This is the same as the table name.  Name of the relation to be loaded. This is the same as the table name.
2928    
2929  =item truncateFlag  =item options
2930    
2931  TRUE if the table should be dropped and re-created, else FALSE  A hash of load options.
2932    
2933  =item RETURN  =item RETURN
2934    
# Line 1710  Line 2936 
2936    
2937  =back  =back
2938    
2939    The permissible options are as follows.
2940    
2941    =over 4
2942    
2943    =item truncate
2944    
2945    If TRUE, then the table will be erased before loading.
2946    
2947    =item mode
2948    
2949    Mode in which the load should operate, either C<low_priority> or C<concurrent>.
2950    This option is only applicable to a MySQL database.
2951    
2952    =item partial
2953    
2954    If TRUE, then it is assumed that this is a partial load, and the table will not
2955    be analyzed and compacted at the end.
2956    
2957    =back
2958    
2959  =cut  =cut
2960  sub LoadTable {  sub LoadTable {
2961      # Get the parameters.      # Get the parameters.
2962      my ($self, $fileName, $relationName, $truncateFlag) = @_;      my ($self, $fileName, $relationName, %options) = @_;
2963      # Create the statistical return object.      # Create the statistical return object.
2964      my $retVal = _GetLoadStats();      my $retVal = _GetLoadStats();
2965      # Trace the fact of the load.      # Trace the fact of the load.
# Line 1725  Line 2971 
2971      # Get the relation data.      # Get the relation data.
2972      my $relation = $self->_FindRelation($relationName);      my $relation = $self->_FindRelation($relationName);
2973      # Check the truncation flag.      # Check the truncation flag.
2974      if ($truncateFlag) {      if ($options{truncate}) {
2975          Trace("Creating table $relationName") if T(2);          Trace("Creating table $relationName") if T(2);
2976          # 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,
2977          # 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
2978          # leave extra room. We postulate a minimum row count of 1000 to          # leave extra room. We postulate a minimum row count of 1000 to
2979          # prevent problems with incoming empty load files.          # prevent problems with incoming empty load files.
2980          my $rowSize = $self->EstimateRowSize($relationName);          my $rowSize = $self->EstimateRowSize($relationName);
2981          my $estimate = FIG::max($fileSize * 1.5 / $rowSize, 1000);          my $estimate = $fileSize * 8 / $rowSize;
2982            if ($estimate < 1000) {
2983                $estimate = 1000;
2984            }
2985          # Re-create the table without its index.          # Re-create the table without its index.
2986          $self->CreateTable($relationName, 0, $estimate);          $self->CreateTable($relationName, 0, $estimate);
2987          # 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 2997 
2997      # Load the table.      # Load the table.
2998      my $rv;      my $rv;
2999      eval {      eval {
3000          $rv = $dbh->load_table(file => $fileName, tbl => $relationName);          $rv = $dbh->load_table(file => $fileName, tbl => $relationName, style => $options{mode});
3001      };      };
3002      if (!defined $rv) {      if (!defined $rv) {
3003          $retVal->AddMessage($@) if ($@);          $retVal->AddMessage($@) if ($@);
3004          $retVal->AddMessage("Table load failed for $relationName using $fileName.");          $retVal->AddMessage("Table load failed for $relationName using $fileName: " . $dbh->error_message);
3005          Trace("Table load failed for $relationName.") if T(1);          Trace("Table load failed for $relationName.") if T(1);
3006      } else {      } else {
3007          # Here we successfully loaded the table.          # Here we successfully loaded the table.
3008          $retVal->Add("tables");          $retVal->Add("tables");
3009          my $size = -s $fileName;          my $size = -s $fileName;
3010          Trace("$size bytes loaded into $relationName.") if T(2);          Trace("$size bytes loaded into $relationName.") if T(2);
3011            $retVal->Add("bytes", $size);
3012          # If we're rebuilding, we need to create the table indexes.          # If we're rebuilding, we need to create the table indexes.
3013          if ($truncateFlag && ! $dbh->{_preIndex}) {          if ($options{truncate}) {
3014                # Indexes are created here for PostGres. For PostGres, indexes are
3015                # best built at the end. For MySQL, the reverse is true.
3016                if (! $dbh->{_preIndex}) {
3017              eval {              eval {
3018                  $self->CreateIndex($relationName);                  $self->CreateIndex($relationName);
3019              };              };
# Line 1768  Line 3021 
3021                  $retVal->AddMessage($@);                  $retVal->AddMessage($@);
3022              }              }
3023          }          }
3024                # The full-text index (if any) is always built last, even for MySQL.
3025                # First we need to see if this table has a full-text index. Only
3026                # primary relations are allowed that privilege.
3027                Trace("Checking for full-text index on $relationName.") if T(2);
3028                if ($self->_IsPrimary($relationName)) {
3029                    $self->CreateSearchIndex($relationName);
3030                }
3031            }
3032      }      }
3033      # Analyze the table to improve performance.      # Analyze the table to improve performance.
3034      $dbh->vacuum_it($relationName);      if (! $options{partial}) {
3035            Trace("Analyzing and compacting $relationName.") if T(3);
3036            $self->Analyze($relationName);
3037        }
3038        Trace("$relationName load completed.") if T(3);
3039      # Return the statistics.      # Return the statistics.
3040      return $retVal;      return $retVal;
3041  }  }
3042    
3043  =head3 GenerateEntity  =head3 Analyze
3044    
3045  C<< my $fieldHash = $erdb->GenerateEntity($id, $type, \%values); >>      $erdb->Analyze($tableName);
3046    
3047  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
3048  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.  
3049    
3050  =over 4  =over 4
3051    
3052  =item id  =item tableName
3053    
3054  ID to assign to the new entity.  Name of the table to be analyzed and compacted.
3055    
3056  =item type  =back
3057    
3058  Type name for the new entity.  =cut
3059    
3060  =item values  sub Analyze {
3061        # Get the parameters.
3062        my ($self, $tableName) = @_;
3063        # Analyze the table.
3064        $self->{_dbh}->vacuum_it($tableName);
3065    }
3066    
3067    =head3 TruncateTable
3068    
3069        $erdb->TruncateTable($table);
3070    
3071    Delete all rows from a table quickly. This uses the built-in SQL
3072    C<TRUNCATE> statement, which effectively drops and re-creates a table
3073    with all its settings intact.
3074    
3075    =over 4
3076    
3077  Hash containing additional values that might be needed by the data generation methods (optional).  =item table
3078    
3079    Name of the table to be cleared.
3080    
3081  =back  =back
3082    
3083  =cut  =cut
3084    
3085  sub GenerateEntity {  sub TruncateTable {
3086      # Get the parameters.      # Get the parameters.
3087      my ($self, $id, $type, $values) = @_;      my ($self, $table) = @_;
3088      # Create the return hash.      # Get the database handle.
3089      my $this = { id => $id };      my $dbh = $self->{_dbh};
3090      # Get the metadata structure.      # Execute a truncation comment.
3091      my $metadata = $self->{_metaData};      $dbh->SQL("TRUNCATE TABLE $table");
3092      # Get this entity's list of fields.  }
3093      if (!exists $metadata->{Entities}->{$type}) {  
3094          Confess("Unrecognized entity type $type in GenerateEntity.");  
3095      } else {  =head3 CreateSearchIndex
3096          my $entity = $metadata->{Entities}->{$type};  
3097          my $fields = $entity->{Fields};      $erdb->CreateSearchIndex($objectName);
3098          # Generate data from the fields.  
3099          _GenerateFields($this, $fields, $type, $values);  Check for a full-text search index on the specified entity or relationship object, and
3100    if one is required, rebuild it.
3101    
3102    =over 4
3103    
3104    =item objectName
3105    
3106    Name of the entity or relationship to be indexed.
3107    
3108    =back
3109    
3110    =cut
3111    
3112    sub CreateSearchIndex {
3113        # Get the parameters.
3114        my ($self, $objectName) = @_;
3115        # Get the relation's entity/relationship structure.
3116        my $structure = $self->_GetStructure($objectName);
3117        # Get the database handle.
3118        my $dbh = $self->{_dbh};
3119        Trace("Checking for search fields in $objectName.") if T(3);
3120        # Check for a searchable fields list.
3121        if (exists $structure->{searchFields}) {
3122            # Here we know that we need to create a full-text search index.
3123            # Get an SQL-formatted field name list.
3124            my $fields = join(", ", _FixNames(@{$structure->{searchFields}}));
3125            # Create the index. If it already exists, it will be dropped.
3126            $dbh->create_index(tbl => $objectName, idx => "search_idx",
3127                               flds => $fields, kind => 'fulltext');
3128            Trace("Index created for $fields in $objectName.") if T(2);
3129        }
3130    }
3131    
3132    =head3 DropRelation
3133    
3134        $erdb->DropRelation($relationName);
3135    
3136    Physically drop a relation from the database.
3137    
3138    =over 4
3139    
3140    =item relationName
3141    
3142    Name of the relation to drop. If it does not exist, this method will have
3143    no effect.
3144    
3145    =back
3146    
3147    =cut
3148    
3149    sub DropRelation {
3150        # Get the parameters.
3151        my ($self, $relationName) = @_;
3152        # Get the database handle.
3153        my $dbh = $self->{_dbh};
3154        # Drop the relation. The method used here has no effect if the relation
3155        # does not exist.
3156        Trace("Invoking DB Kernel to drop $relationName.") if T(3);
3157        $dbh->drop_table(tbl => $relationName);
3158    }
3159    
3160    =head3 MatchSqlPattern
3161    
3162        my $matched = ERDB::MatchSqlPattern($value, $pattern);
3163    
3164    Determine whether or not a specified value matches an SQL pattern. An SQL
3165    pattern has two wild card characters: C<%> that matches multiple characters,
3166    and C<_> that matches a single character. These can be escaped using a
3167    backslash (C<\>). We pull this off by converting the SQL pattern to a
3168    PERL regular expression. As per SQL rules, the match is case-insensitive.
3169    
3170    =over 4
3171    
3172    =item value
3173    
3174    Value to be matched against the pattern. Note that an undefined or empty
3175    value will not match anything.
3176    
3177    =item pattern
3178    
3179    SQL pattern against which to match the value. An undefined or empty pattern will
3180    match everything.
3181    
3182    =item RETURN
3183    
3184    Returns TRUE if the value and pattern match, else FALSE.
3185    
3186    =back
3187    
3188    =cut
3189    
3190    sub MatchSqlPattern {
3191        # Get the parameters.
3192        my ($value, $pattern) = @_;
3193        # Declare the return variable.
3194        my $retVal;
3195        # Insure we have a pattern.
3196        if (! defined($pattern) || $pattern eq "") {
3197            $retVal = 1;
3198        } else {
3199            # Break the pattern into pieces around the wildcard characters. Because we
3200            # use parentheses in the split function's delimiter expression, we'll get
3201            # list elements for the delimiters as well as the rest of the string.
3202            my @pieces = split /([_%]|\\[_%])/, $pattern;
3203            # Check some fast special cases.
3204            if ($pattern eq '%') {
3205                # A null pattern matches everything.
3206                $retVal = 1;
3207            } elsif (@pieces == 1) {
3208                # No wildcards, so we have a literal comparison. Note we're case-insensitive.
3209                $retVal = (lc($value) eq lc($pattern));
3210            } elsif (@pieces == 2 && $pieces[1] eq '%') {
3211                # A wildcard at the end, so we have a substring match. This is also case-insensitive.
3212                $retVal = (lc(substr($value, 0, length($pieces[0]))) eq lc($pieces[0]));
3213            } else {
3214                # Okay, we have to do it the hard way. Convert each piece to a PERL pattern.
3215                my $realPattern = "";
3216                for my $piece (@pieces) {
3217                    # Determine the type of piece.
3218                    if ($piece eq "") {
3219                        # Empty pieces are ignored.
3220                    } elsif ($piece eq "%") {
3221                        # Here we have a multi-character wildcard. Note that it can match
3222                        # zero or more characters.
3223                        $realPattern .= ".*"
3224                    } elsif ($piece eq "_") {
3225                        # Here we have a single-character wildcard.
3226                        $realPattern .= ".";
3227                    } elsif ($piece eq "\\%" || $piece eq "\\_") {
3228                        # This is an escape sequence (which is a rare thing, actually).
3229                        $realPattern .= substr($piece, 1, 1);
3230                    } else {
3231                        # Here we have raw text.
3232                        $realPattern .= quotemeta($piece);
3233                    }
3234                }
3235                # Do the match.
3236                $retVal = ($value =~ /^$realPattern$/i ? 1 : 0);
3237      }      }
3238      # Return the hash created.      }
3239      return $this;      # Return the result.
3240        return $retVal;
3241  }  }
3242    
3243  =head3 GetEntity  =head3 GetEntity
3244    
3245  C<< my $entityObject = $erdb->GetEntity($entityType, $ID); >>      my $entityObject = $erdb->GetEntity($entityType, $ID);
3246    
3247  Return an object describing the entity instance with a specified ID.  Return an object describing the entity instance with a specified ID.
3248    
# Line 1851  Line 3258 
3258    
3259  =item RETURN  =item RETURN
3260    
3261  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
3262  instance is found with the specified key.  instance is found with the specified key.
3263    
3264  =back  =back
# Line 1865  Line 3272 
3272      my $query = $self->Get([$entityType], "$entityType(id) = ?", [$ID]);      my $query = $self->Get([$entityType], "$entityType(id) = ?", [$ID]);
3273      # Get the first (and only) object.      # Get the first (and only) object.
3274      my $retVal = $query->Fetch();      my $retVal = $query->Fetch();
3275        if (T(3)) {
3276            if ($retVal) {
3277                Trace("Entity $entityType \"$ID\" found.");
3278            } else {
3279                Trace("Entity $entityType \"$ID\" not found.");
3280            }
3281        }
3282      # Return the result.      # Return the result.
3283      return $retVal;      return $retVal;
3284  }  }
3285    
3286    =head3 GetChoices
3287    
3288        my @values = $erdb->GetChoices($entityName, $fieldName);
3289    
3290    Return a list of all the values for the specified field that are represented in the
3291    specified entity.
3292    
3293    Note that if the field is not indexed, then this will be a very slow operation.
3294    
3295    =over 4
3296    
3297    =item entityName
3298    
3299    Name of an entity in the database.
3300    
3301    =item fieldName
3302    
3303    Name of a field belonging to the entity. This is a raw field name without
3304    the standard parenthesized notation used in most calls.
3305    
3306    =item RETURN
3307    
3308    Returns a list of the distinct values for the specified field in the database.
3309    
3310    =back
3311    
3312    =cut
3313    
3314    sub GetChoices {
3315        # Get the parameters.
3316        my ($self, $entityName, $fieldName) = @_;
3317        # Declare the return variable.
3318        my @retVal;
3319        # Get the entity data structure.
3320        my $entityData = $self->_GetStructure($entityName);
3321        # Get the field.
3322        my $fieldHash = $entityData->{Fields};
3323        if (! exists $fieldHash->{$fieldName}) {
3324            Confess("$fieldName not found in $entityName.");
3325        } else {
3326            # Get the name of the relation containing the field.
3327            my $relation = $fieldHash->{$fieldName}->{relation};
3328            # Fix up the field name.
3329            my $realName = _FixName($fieldName);
3330            # Get the database handle.
3331            my $dbh = $self->{_dbh};
3332            # Query the database.
3333            my $results = $dbh->SQL("SELECT DISTINCT $realName FROM $relation");
3334            # Clean the results. They are stored as a list of lists, and we just want the one list.
3335            @retVal = sort map { $_->[0] } @{$results};
3336        }
3337        # Return the result.
3338        return @retVal;
3339    }
3340    
3341  =head3 GetEntityValues  =head3 GetEntityValues
3342    
3343  C<< my @values = $erdb->GetEntityValues($entityType, $ID, \@fields); >>      my @values = $erdb->GetEntityValues($entityType, $ID, \@fields);
3344    
3345  Return a list of values from a specified entity instance.  Return a list of values from a specified entity instance. If the entity instance
3346    does not exist, an empty list is returned.
3347    
3348  =over 4  =over 4
3349    
# Line 1914  Line 3384 
3384    
3385  =head3 GetAll  =head3 GetAll
3386    
3387  C<< my @list = $erdb->GetAll(\@objectNames, $filterClause, \@parameters, \@fields, $count); >>      my @list = $erdb->GetAll(\@objectNames, $filterClause, \@parameters, \@fields, $count);
3388    
3389  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
3390  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 3398 
3398  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
3399  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
3400  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
3401  feature ID followed by all of its aliases.  feature ID followed by all of its essentiality determinations.
3402    
3403  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)']);
3404    
3405  =over 4  =over 4
3406    
# Line 2005  Line 3475 
3475      return @retVal;      return @retVal;
3476  }  }
3477    
3478    =head3 Exists
3479    
3480        my $found = $sprout->Exists($entityName, $entityID);
3481    
3482    Return TRUE if an entity exists, else FALSE.
3483    
3484    =over 4
3485    
3486    =item entityName
3487    
3488    Name of the entity type (e.g. C<Feature>) relevant to the existence check.
3489    
3490    =item entityID
3491    
3492    ID of the entity instance whose existence is to be checked.
3493    
3494    =item RETURN
3495    
3496    Returns TRUE if the entity instance exists, else FALSE.
3497    
3498    =back
3499    
3500    =cut
3501    #: Return Type $;
3502    sub Exists {
3503        # Get the parameters.
3504        my ($self, $entityName, $entityID) = @_;
3505        # Check for the entity instance.
3506        Trace("Checking existence of $entityName with ID=$entityID.") if T(4);
3507        my $testInstance = $self->GetEntity($entityName, $entityID);
3508        # Return an existence indicator.
3509        my $retVal = ($testInstance ? 1 : 0);
3510        return $retVal;
3511    }
3512    
3513  =head3 EstimateRowSize  =head3 EstimateRowSize
3514    
3515  C<< my $rowSize = $erdb->EstimateRowSize($relName); >>      my $rowSize = $erdb->EstimateRowSize($relName);
3516    
3517  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
3518  up the average length for each data type.  up the average length for each data type.
# Line 2018  Line 3523 
3523    
3524  Name of the relation whose estimated row size is desired.  Name of the relation whose estimated row size is desired.
3525    
3526  =item RETURN  =item RETURN
3527    
3528    Returns an estimate of the row size for the specified relation.
3529    
3530    =back
3531    
3532    =cut
3533    #: Return Type $;
3534    sub EstimateRowSize {
3535        # Get the parameters.
3536        my ($self, $relName) = @_;
3537        # Declare the return variable.
3538        my $retVal = 0;
3539        # Find the relation descriptor.
3540        my $relation = $self->_FindRelation($relName);
3541        # Get the list of fields.
3542        for my $fieldData (@{$relation->{Fields}}) {
3543            # Get the field type and add its length.
3544            my $fieldLen = $TypeTable{$fieldData->{type}}->{avgLen};
3545            $retVal += $fieldLen;
3546        }
3547        # Return the result.
3548        return $retVal;
3549    }
3550    
3551    =head3 GetFieldTable
3552    
3553        my $fieldHash = $self->GetFieldTable($objectnName);
3554    
3555    Get the field structure for a specified entity or relationship.
3556    
3557    =over 4
3558    
3559    =item objectName
3560    
3561    Name of the desired entity or relationship.
3562    
3563    =item RETURN
3564    
3565    The table containing the field descriptors for the specified object.
3566    
3567    =back
3568    
3569    =cut
3570    
3571    sub GetFieldTable {
3572        # Get the parameters.
3573        my ($self, $objectName) = @_;
3574        # Get the descriptor from the metadata.
3575        my $objectData = $self->_GetStructure($objectName);
3576        # Return the object's field table.
3577        return $objectData->{Fields};
3578    }
3579    
3580    =head3 SplitKeywords
3581    
3582        my @keywords = ERDB::SplitKeywords($keywordString);
3583    
3584    This method returns a list of the positive keywords in the specified
3585    keyword string. All of the operators will have been stripped off,
3586    and if the keyword is preceded by a minus operator (C<->), it will
3587    not be in the list returned. The idea here is to get a list of the
3588    keywords the user wants to see. The list will be processed to remove
3589    duplicates.
3590    
3591    It is possible to create a string that confuses this method. For example
3592    
3593        frog toad -frog
3594    
3595    would return both C<frog> and C<toad>. If this is a problem we can deal
3596    with it later.
3597    
3598    =over 4
3599    
3600    =item keywordString
3601    
3602    The keyword string to be parsed.
3603    
3604    =item RETURN
3605    
3606    Returns a list of the words in the keyword string the user wants to
3607    see.
3608    
3609    =back
3610    
3611    =cut
3612    
3613    sub SplitKeywords {
3614        # Get the parameters.
3615        my ($keywordString) = @_;
3616        # Make a safety copy of the string. (This helps during debugging.)
3617        my $workString = $keywordString;
3618        # Convert operators we don't care about to spaces.
3619        $workString =~ tr/+"()<>/ /;
3620        # Split the rest of the string along space boundaries. Note that we
3621        # eliminate any words that are zero length or begin with a minus sign.
3622        my @wordList = grep { $_ && substr($_, 0, 1) ne "-" } split /\s+/, $workString;
3623        # Use a hash to remove duplicates.
3624        my %words = map { $_ => 1 } @wordList;
3625        # Return the result.
3626        return sort keys %words;
3627    }
3628    
3629    =head3 ValidateFieldName
3630    
3631        my $okFlag = ERDB::ValidateFieldName($fieldName);
3632    
3633    Return TRUE if the specified field name is valid, else FALSE. Valid field names must
3634    be hyphenated words subject to certain restrictions.
3635    
3636    =over 4
3637    
3638    =item fieldName
3639    
3640    Field name to be validated.
3641    
3642    =item RETURN
3643    
3644    Returns TRUE if the field name is valid, else FALSE.
3645    
3646    =back
3647    
3648    =cut
3649    
3650    sub ValidateFieldName {
3651        # Get the parameters.
3652        my ($fieldName) = @_;
3653        # Declare the return variable. The field name is valid until we hear
3654        # differently.
3655        my $retVal = 1;
3656        # Compute the maximum name length.
3657        my $maxLen = $TypeTable{'name-string'}->{maxLen};
3658        # Look for bad stuff in the name.
3659        if ($fieldName =~ /--/) {
3660            # Here we have a doubled minus sign.
3661            Trace("Field name $fieldName has a doubled hyphen.") if T(1);
3662            $retVal = 0;
3663        } elsif ($fieldName !~ /^[A-Za-z]/) {
3664            # Here the field name is missing the initial letter.
3665            Trace("Field name $fieldName does not begin with a letter.") if T(1);
3666            $retVal = 0;
3667        } elsif (length($fieldName) > $maxLen) {
3668            # Here the field name is too long.
3669            Trace("Maximum field name length is $maxLen. Field name must be truncated to " . substr($fieldName,0, $maxLen) . ".");
3670        } else {
3671            # Strip out the minus signs. Everything remaining must be a letter,
3672            # underscore, or digit.
3673            my $strippedName = $fieldName;
3674            $strippedName =~ s/-//g;
3675            if ($strippedName !~ /^(\w|\d)+$/) {
3676                Trace("Field name $fieldName contains illegal characters.") if T(1);
3677                $retVal = 0;
3678            }
3679        }
3680        # Return the result.
3681        return $retVal;
3682    }
3683    
3684    =head3 ReadMetaXML
3685    
3686        my $rawMetaData = ERDB::ReadDBD($fileName);
3687    
3688    This method reads a raw database definition XML file and returns it.
3689    Normally, the metadata used by the ERDB system has been processed and
3690    modified to make it easier to load and retrieve the data; however,
3691    this method can be used to get the data in its raw form.
3692    
3693    =over 4
3694    
3695    =item fileName
3696    
3697    Name of the XML file to read.
3698    
3699    =item RETURN
3700    
3701    Returns a hash reference containing the raw XML data from the specified file.
3702    
3703    =back
3704    
3705    =cut
3706    
3707    sub ReadMetaXML {
3708        # Get the parameters.
3709        my ($fileName) = @_;
3710        # Read the XML.
3711        my $retVal = XML::Simple::XMLin($fileName, %XmlOptions, %XmlInOpts);
3712        Trace("XML metadata loaded from file $fileName.") if T(1);
3713        # Return the result.
3714        return $retVal;
3715    }
3716    
3717    =head3 GetEntityFieldHash
3718    
3719        my $fieldHashRef = ERDB::GetEntityFieldHash($structure, $entityName);
3720    
3721    Get the field hash of the named entity in the specified raw XML structure.
3722    The field hash may not exist, in which case we need to create it.
3723    
3724    =over 4
3725    
3726    =item structure
3727    
3728    Raw XML structure defininng the database. This is not the run-time XML used by
3729    an ERDB object, since that has all sorts of optimizations built-in.
3730    
3731    =item entityName
3732    
3733    Name of the entity whose field structure is desired.
3734    
3735    =item RETURN
3736    
3737    Returns the field hash used to define the entity's fields.
3738    
3739    =back
3740    
3741    =cut
3742    
3743    sub GetEntityFieldHash {
3744        # Get the parameters.
3745        my ($structure, $entityName) = @_;
3746        # Get the entity structure.
3747        my $entityData = $structure->{Entities}->{$entityName};
3748        # Look for a field structure.
3749        my $retVal = $entityData->{Fields};
3750        # If it doesn't exist, create it.
3751        if (! defined($retVal)) {
3752            $entityData->{Fields} = {};
3753            $retVal = $entityData->{Fields};
3754        }
3755        # Return the result.
3756        return $retVal;
3757    }
3758    
3759    =head3 WriteMetaXML
3760    
3761        ERDB::WriteMetaXML($structure, $fileName);
3762    
3763    Write the metadata XML to a file. This method is the reverse of L</ReadMetaXML>, and is
3764    used to update the database definition. It must be used with care, however, since it
3765    will only work on a raw structure, not on the processed structure created by an ERDB
3766    constructor.
3767    
3768    =over 4
3769    
3770    =item structure
3771    
3772    XML structure to be written to the file.
3773    
3774    =item fileName
3775    
3776    Name of the output file to which the updated XML should be stored.
3777    
3778    =back
3779    
3780    =cut
3781    
3782    sub WriteMetaXML {
3783        # Get the parameters.
3784        my ($structure, $fileName) = @_;
3785        # Compute the output.
3786        my $fileString = XML::Simple::XMLout($structure, %XmlOptions, %XmlOutOpts);
3787        # Write it to the file.
3788        my $xmlOut = Open(undef, ">$fileName");
3789        print $xmlOut $fileString;
3790    }
3791    
3792    
3793    =head3 HTMLNote
3794    
3795    Convert a note or comment to HTML by replacing some bulletin-board codes with HTML. The codes
3796    supported are C<[b]> for B<bold>, C<[i]> for I<italics>, and C<[p]> for a new paragraph.
3797    Except for C<[p]>, all the codes are closed by slash-codes. So, for
3798    example, C<[b]Feature[/b]> displays the string C<Feature> in boldface.
3799    
3800        my $realHtml = ERDB::HTMLNote($dataString);
3801    
3802    =over 4
3803    
3804    =item dataString
3805    
3806    String to convert to HTML.
3807    
3808    =item RETURN
3809    
3810    An HTML string derived from the input string.
3811    
3812    =back
3813    
3814    =cut
3815    
3816    sub HTMLNote {
3817        # Get the parameter.
3818        my ($dataString) = @_;
3819        # HTML-escape the text.
3820        my $retVal = CGI::escapeHTML($dataString);
3821        # Substitute the bulletin board codes.
3822        $retVal =~ s!\[(/?[bi])\]!<$1>!g;
3823        $retVal =~ s!\[p\]!</p><p>!g;
3824        $retVal =~ s!\[link\s+([^\]]+)\]!<a href="$1">!g;
3825        $retVal =~ s!\[/link\]!</a>!g;
3826        # Return the result.
3827        return $retVal;
3828    }
3829    
3830    =head3 WikiNote
3831    
3832    Convert a note or comment to Wiki text by replacing some bulletin-board codes with HTML. The codes
3833    supported are C<[b]> for B<bold>, C<[i]> for I<italics>, and C<[p]> for a new paragraph.
3834    Except for C<[p]>, all the codes are closed by slash-codes. So, for
3835    example, C<[b]Feature[/b]> displays the string C<Feature> in boldface.
3836    
3837        my $wikiText = ERDB::WikiNote($dataString);
3838    
3839    =over 4
3840    
3841    =item dataString
3842    
3843    String to convert to Wiki text.
3844    
3845    =item RETURN
3846    
3847    An Wiki text string derived from the input string.
3848    
3849    =back
3850    
3851    =cut
3852    
3853    sub WikiNote {
3854        # Get the parameter.
3855        my ($dataString) = @_;
3856        # HTML-escape the text.
3857        my $retVal = CGI::escapeHTML($dataString);
3858        # Substitute the bulletin board codes.
3859        my $italic = WikiTools::ItalicCode();
3860        $retVal =~ s/\[\/?i\]/$italic/g;
3861        my $bold = WikiTools::BoldCode();
3862        $retVal =~ s/\[\/?b\]/$bold/g;
3863        # Paragraph breaks are the same no matter which Wiki you're using.
3864        $retVal =~ s!\[p\]!\n\n!g;
3865        # Now we do the links, which are complicated by the need to know two
3866        # things: the target URL and the text.
3867        while ($retVal =~ /\[link\s+([^\]]+)\]([^\[]+)\[\/link\]/g) {
3868            # Replace the matched string with the Wiki markup for links. Note that
3869            # $-[0] is the starting position of the match for the entire expression,
3870            # and $+[0] is past the ending position.
3871            substr $retVal, $-[0], $+[0] - $-[0], WikiTools::LinkMarkup($1, $2);
3872        }
3873        # Return the result.
3874        return $retVal;
3875    }
3876    
3877    =head3 BeginTran
3878    
3879        $erdb->BeginTran();
3880    
3881    Start a database transaction.
3882    
3883    =cut
3884    
3885    sub BeginTran {
3886        my ($self) = @_;
3887        $self->{_dbh}->begin_tran();
3888    
3889    }
3890    
3891    =head3 CommitTran
3892    
3893        $erdb->CommitTran();
3894    
3895    Commit an active database transaction.
3896    
3897    =cut
3898    
3899    sub CommitTran {
3900        my ($self) = @_;
3901        $self->{_dbh}->commit_tran();
3902    }
3903    
3904    =head3 RollbackTran
3905    
3906        $erdb->RollbackTran();
3907    
3908    Roll back an active database transaction.
3909    
3910    =cut
3911    
3912    sub RollbackTran {
3913        my ($self) = @_;
3914        $self->{_dbh}->roll_tran();
3915    }
3916    
3917    =head3 UpdateField
3918    
3919        my $count = $erdb->UpdateField($objectNames, $fieldName, $oldValue, $newValue, $filter, $parms);
3920    
3921    Update all occurrences of a specific field value to a new value. The number of rows changed will be
3922    returned.
3923    
3924    =over 4
3925    
3926    =item fieldName
3927    
3928  Returns an estimate of the row size for the specified relation.  Name of the field in standard I<objectName>C<(>I<fieldName>C<)> format.
3929    
3930  =back  =item oldValue
3931    
3932  =cut  Value to be modified. All occurrences of this value in the named field will be replaced by the
3933  #: 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;  
 }  
3934    
3935  =head3 GetFieldTable  =item newValue
3936    
3937  C<< my $fieldHash = $self->GetFieldTable($objectnName); >>  New value to be substituted for the old value when it's found.
3938    
3939  Get the field structure for a specified entity or relationship.  =item filter
3940    
3941  =over 4  A standard ERDB filter clause (see L</Get>). The filter will be applied before any substitutions take place.
3942    
3943  =item objectName  =item parms
3944    
3945  Name of the desired entity or relationship.  Reference to a list of parameter values in the filter.
3946    
3947  =item RETURN  =item RETURN
3948    
3949  The table containing the field descriptors for the specified object.  Returns the number of rows modified.
3950    
3951  =back  =back
3952    
3953  =cut  =cut
3954    
3955  sub GetFieldTable {  sub UpdateField {
3956      # Get the parameters.      # Get the parameters.
3957      my ($self, $objectName) = @_;      my ($self, $fieldName, $oldValue, $newValue, $filter, $parms) = @_;
3958      # Get the descriptor from the metadata.      # Get the object and field names from the field name parameter.
3959      my $objectData = $self->_GetStructure($objectName);      $fieldName =~ /^([^(]+)\(([^)]+)\)/;
3960      # Return the object's field table.      my $objectName = $1;
3961      return $objectData->{Fields};      my $realFieldName = _FixName($2);
3962        # Add the old value to the filter. Note we allow the possibility that no
3963        # filter was specified.
3964        my $realFilter = "$fieldName = ?";
3965        if ($filter) {
3966            $realFilter .= " AND $filter";
3967        }
3968        # Format the query filter.
3969        my ($suffix, $mappedNameListRef, $mappedNameHashRef) =
3970            $self->_SetupSQL([$objectName], $realFilter);
3971        # Create the query. Since there is only one object name, the mapped-name data is not
3972        # necessary. Neither is the FROM clause.
3973        $suffix =~ s/^FROM.+WHERE\s+//;
3974        # Create the update statement.
3975        my $command = "UPDATE $objectName SET $realFieldName = ? WHERE $suffix";
3976        # Get the database handle.
3977        my $dbh = $self->{_dbh};
3978        # Add the old and new values to the parameter list. Note we allow the possibility that
3979        # there are no user-supplied parameters.
3980        my @params = ($newValue, $oldValue);
3981        if (defined $parms) {
3982            push @params, @{$parms};
3983        }
3984        # Execute the update.
3985        my $retVal = $dbh->SQL($command, 0, @params);
3986        # Make the funky zero a real zero.
3987        if ($retVal == 0) {
3988            $retVal = 0;
3989        }
3990        # Return the result.
3991        return $retVal;
3992  }  }
3993    
3994    
3995  =head2 Data Mining Methods  =head2 Data Mining Methods
3996    
3997  =head3 GetUsefulCrossValues  =head3 GetUsefulCrossValues
3998    
3999  C<< my @attrNames = $sprout->GetUsefulCrossValues($sourceEntity, $relationship); >>      my @attrNames = $sprout->GetUsefulCrossValues($sourceEntity, $relationship);
4000    
4001  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
4002  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 4057 
4057    
4058  =head3 FindColumn  =head3 FindColumn
4059    
4060  C<< my $colIndex = ERDB::FindColumn($headerLine, $columnIdentifier); >>      my $colIndex = ERDB::FindColumn($headerLine, $columnIdentifier);
4061    
4062  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
4063  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 4115 
4115    
4116  =head3 ParseColumns  =head3 ParseColumns
4117    
4118  C<< my @columns = ERDB->ParseColumns($line); >>      my @columns = ERDB::ParseColumns($line);
4119    
4120  Convert the specified data line to a list of columns.  Convert the specified data line to a list of columns.
4121    
# Line 2216  Line 4136 
4136    
4137  sub ParseColumns {  sub ParseColumns {
4138      # Get the parameters.      # Get the parameters.
4139      my ($self, $line) = @_;      my ($line) = @_;
4140      # Chop off the line-end.      # Chop off the line-end.
4141      chomp $line;      chomp $line;
4142      # Split it into a list.      # Split it into a list.
# Line 2225  Line 4145 
4145      return @retVal;      return @retVal;
4146  }  }
4147    
4148    =head2 Virtual Methods
4149    
4150    =head3 _CreatePPOIndex
4151    
4152        my $index = ERDB::_CreatePPOIndex($indexObject);
4153    
4154    Convert the XML for an ERDB index to the XML structure for a PPO
4155    index.
4156    
4157    =over 4
4158    
4159    =item indexObject
4160    
4161    ERDB XML structure for an index.
4162    
4163    =item RETURN
4164    
4165    PPO XML structure for the same index.
4166    
4167    =back
4168    
4169    =cut
4170    
4171    sub _CreatePPOIndex {
4172        # Get the parameters.
4173        my ($indexObject) = @_;
4174        # The incoming index contains a list of the index fields in the IndexFields
4175        # member. We loop through it to create the index tags.
4176        my @fields = map { { label => _FixName($_->{name}) } } @{$indexObject->{IndexFields}};
4177        # Wrap the fields in attribute tags.
4178        my $retVal = { attribute => \@fields };
4179        # Return the result.
4180        return $retVal;
4181    }
4182    
4183    =head3 _CreatePPOField
4184    
4185        my $fieldXML = ERDB::_CreatePPOField($fieldName, $fieldObject);
4186    
4187    Convert the ERDB XML structure for a field to a PPO scalar XML structure.
4188    
4189    =over 4
4190    
4191    =item fieldName
4192    
4193    Name of the scalar field.
4194    
4195    =item fieldObject
4196    
4197    ERDB XML structure describing the field.
4198    
4199    =item RETURN
4200    
4201    Returns a PPO XML structure for the same field.
4202    
4203    =back
4204    
4205    =cut
4206    
4207    sub _CreatePPOField {
4208        # Get the parameters.
4209        my ($fieldName, $fieldObject) = @_;
4210        # Get the field type.
4211        my $type = $TypeTable{$fieldObject->{type}}->{sqlType};
4212        # Fix up the field name.
4213        $fieldName = _FixName($fieldName);
4214        # Build the scalar tag.
4215        my $retVal = { label => $fieldName, type => $type };
4216        # Return the result.
4217        return $retVal;
4218    }
4219    
4220    =head3 CleanKeywords
4221    
4222        my $cleanedString = $erdb->CleanKeywords($searchExpression);
4223    
4224    Clean up a search expression or keyword list. This is a virtual method that may
4225    be overridden by the subclass. The base-class method removes extra spaces
4226    and converts everything to lower case.
4227    
4228    =over 4
4229    
4230    =item searchExpression
4231    
4232    Search expression or keyword list to clean. Note that a search expression may
4233    contain boolean operators which need to be preserved. This includes leading
4234    minus signs.
4235    
4236    =item RETURN
4237    
4238    Cleaned expression or keyword list.
4239    
4240    =back
4241    
4242    =cut
4243    
4244    sub CleanKeywords {
4245        # Get the parameters.
4246        my ($self, $searchExpression) = @_;
4247        # Lower-case the expression and copy it into the return variable. Note that we insure we
4248        # don't accidentally end up with an undefined value.
4249        my $retVal = lc($searchExpression || "");
4250        # Remove extra spaces.
4251        $retVal =~ s/\s+/ /g;
4252        $retVal =~ s/(^\s+)|(\s+$)//g;
4253        # Return the result.
4254        return $retVal;
4255    }
4256    
4257    =head3 GetSourceObject
4258    
4259        my $source = $erdb->GetSourceObject($entityName);
4260    
4261    Return the object to be used in loading special attributes of the specified entity. The
4262    algorithm for loading special attributes is stored in the C<DataGen> elements of the
4263    XML
4264    
4265  =head2 Internal Utility Methods  =head2 Internal Utility Methods
4266    
4267  =head3 SetupSQL  =head3 _RelationMap
4268    
4269        my @relationMap = _RelationMap($mappedNameHashRef, $mappedNameListRef);
4270    
4271    Create the relation map for an SQL query. The relation map is used by B<ERDBObject>
4272    to determine how to interpret the results of the query.
4273    
4274    =over 4
4275    
4276    =item mappedNameHashRef
4277    
4278    Reference to a hash that maps modified object names to real object names.
4279    
4280    =item mappedNameListRef
4281    
4282    Reference to a list of modified object names in the order they appear in the
4283    SELECT list.
4284    
4285    =item RETURN
4286    
4287    Returns a list of 2-tuples. Each tuple consists of an object name as used in the
4288    query followed by the actual name of that object. This enables the B<ERDBObject> to
4289    determine the order of the tables in the query and which object name belongs to each
4290    mapped object name. Most of the time these two values are the same; however, if a
4291    relation occurs twice in the query, the relation name in the field list and WHERE
4292    clause will use a mapped name (generally the actual relation name with a numeric
4293    suffix) that does not match the actual relation name.
4294    
4295    =back
4296    
4297    =cut
4298    
4299    sub _RelationMap {
4300        # Get the parameters.
4301        my ($mappedNameHashRef, $mappedNameListRef) = @_;
4302        # Declare the return variable.
4303        my @retVal = ();
4304        # Build the map.
4305        for my $mappedName (@{$mappedNameListRef}) {
4306            push @retVal, [$mappedName, $mappedNameHashRef->{$mappedName}];
4307        }
4308        # Return it.
4309        return @retVal;
4310    }
4311    
4312    
4313    =head3 _SetupSQL
4314    
4315  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
4316  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 4330 
4330  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
4331  optionally the C<ORDER BY> and C<LIMIT> clauses.  optionally the C<ORDER BY> and C<LIMIT> clauses.
4332    
4333    =item matchClause
4334    
4335    An optional full-text search clause. If specified, it will be inserted at the
4336    front of the WHERE clause. It should already be SQL-formatted; that is, the
4337    field names should be in the form I<table>C<.>I<fieldName>.
4338    
4339  =item RETURN  =item RETURN
4340    
4341  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 4348 
4348  =cut  =cut
4349    
4350  sub _SetupSQL {  sub _SetupSQL {
4351      my ($self, $objectNames, $filterClause) = @_;      my ($self, $objectNames, $filterClause, $matchClause) = @_;
4352      # 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
4353      # 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
4354      # 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 4397 
4397      # FROM name1, name2, ... nameN      # FROM name1, name2, ... nameN
4398      #      #
4399      my $suffix = "FROM " . join(', ', @fromList);      my $suffix = "FROM " . join(', ', @fromList);
4400        # Now for the WHERE. First, we need a place for the filter string.
4401        my $filterString = "";
4402        # We will also keep a list of conditions to add to the WHERE clause in order to link
4403        # entities and relationships as well as primary relations to secondary ones.
4404        my @joinWhere = ();
4405      # Check for a filter clause.      # Check for a filter clause.
4406      if ($filterClause) {      if ($filterClause) {
4407          # 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,
4408          # We create a copy of the filter string we can work with.          # We create a copy of the filter string we can work with.
4409          my $filterString = $filterClause;          $filterString = $filterClause;
4410          # 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
4411          # 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.
4412          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 = ();  
4413          # 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
4414          # 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
4415          # 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 4477 
4477                  }                  }
4478              }              }
4479          }          }
4480        }
4481          # 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
4482          # 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
4483          # 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
4484          # list before running through it.      # list before running through it, because we shift off the first object before
4485        # processing the rest.
4486          my @mappedObjectList = @mappedNameList;          my @mappedObjectList = @mappedNameList;
4487          my $lastMappedObject = shift @mappedObjectList;          my $lastMappedObject = shift @mappedObjectList;
4488          # Get the join table.          # Get the join table.
# Line 2418  Line 4511 
4511          # 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.
4512          # We'll put the ORDER BY / LIMIT clauses in the following variable.          # We'll put the ORDER BY / LIMIT clauses in the following variable.
4513          my $orderClause = "";          my $orderClause = "";
4514        # This is only necessary if we have a filter string in which the ORDER BY
4515        # and LIMIT clauses can live.
4516        if ($filterString) {
4517          # 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
4518          # operator so that we find the first occurrence of either verb.          # operator so that we find the first occurrence of either verb.
4519          if ($filterString =~ m/^(.*?)\s*(ORDER BY|LIMIT)/g) {          if ($filterString =~ m/^(.*?)\s*(ORDER BY|LIMIT)/g) {
# Line 2426  Line 4522 
4522              $orderClause = $2 . substr($filterString, $pos);              $orderClause = $2 . substr($filterString, $pos);
4523              $filterString = $1;              $filterString = $1;
4524          }          }
4525          # Add the filter and the join clauses (if any) to the SELECT command.      }
4526        # All the things that are supposed to be in the WHERE clause of the
4527        # SELECT command need to be put into @joinWhere so we can string them
4528        # together. We begin with the match clause. This is important,
4529        # because the match clause's parameter mark must precede any parameter
4530        # marks in the filter string.
4531        if ($matchClause) {
4532            push @joinWhere, $matchClause;
4533        }
4534        # Add the filter string. We put it in parentheses to avoid operator
4535        # precedence problems with the match clause or the joins.
4536          if ($filterString) {          if ($filterString) {
4537              Trace("Filter string is \"$filterString\".") if T(4);              Trace("Filter string is \"$filterString\".") if T(4);
4538              push @joinWhere, "($filterString)";              push @joinWhere, "($filterString)";
4539          }          }
4540        # String it all together into a big filter clause.
4541          if (@joinWhere) {          if (@joinWhere) {
4542              $suffix .= " WHERE " . join(' AND ', @joinWhere);              $suffix .= " WHERE " . join(' AND ', @joinWhere);
4543          }          }
4544          # Add the sort or limit clause (if any) to the SELECT command.      # Add the sort or limit clause (if any).
4545          if ($orderClause) {          if ($orderClause) {
4546              $suffix .= " $orderClause";              $suffix .= " $orderClause";
4547          }          }
     }  
4548      # Return the suffix, the mapped name list, and the mapped name hash.      # Return the suffix, the mapped name list, and the mapped name hash.
4549      return ($suffix, \@mappedNameList, \%mappedNameHash);      return ($suffix, \@mappedNameList, \%mappedNameHash);
4550  }  }
4551    
4552  =head3 GetStatementHandle  =head3 _GetStatementHandle
4553    
4554  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.
4555  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 4579 
4579  sub _GetStatementHandle {  sub _GetStatementHandle {
4580      # Get the parameters.      # Get the parameters.
4581      my ($self, $command, $params) = @_;      my ($self, $command, $params) = @_;
4582        Confess("Invalid parameter list.") if (! defined($params) || ref($params) ne 'ARRAY');
4583      # Trace the query.      # Trace the query.
4584      Trace("SQL query: $command") if T(SQL => 3);      Trace("SQL query: $command") if T(SQL => 3);
4585      Trace("PARMS: '" . (join "', '", @{$params}) . "'") if (T(SQL => 4) && (@{$params} > 0));      Trace("PARMS: '" . (join "', '", @{$params}) . "'") if (T(SQL => 4) && (@{$params} > 0));
# Line 2481  Line 4588 
4588      # Prepare the command.      # Prepare the command.
4589      my $sth = $dbh->prepare_command($command);      my $sth = $dbh->prepare_command($command);
4590      # Execute it with the parameters bound in.      # Execute it with the parameters bound in.
4591      $sth->execute(@{$params}) || Confess("SELECT error" . $sth->errstr());      $sth->execute(@{$params}) || Confess("SELECT error:  " . $sth->errstr());
4592      # Return the statement handle.      # Return the statement handle.
4593      return $sth;      return $sth;
4594  }  }
4595    
4596  =head3 GetLoadStats  =head3 _GetLoadStats
4597    
4598  Return a blank statistics object for use by the load methods.  Return a blank statistics object for use by the load methods.
4599    
# Line 2498  Line 4605 
4605      return Stats->new();      return Stats->new();
4606  }  }
4607    
4608  =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  
4609    
4610  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.
4611    
4612  This is an instance method.  This is an instance method.
4613    
# Line 2622  Line 4655 
4655      close DTXOUT;      close DTXOUT;
4656  }  }
4657    
4658  =head3 GetStructure  =head3 _GetStructure
4659    
4660  Get the data structure for a specified entity or relationship.  Get the data structure for a specified entity or relationship.
4661    
# Line 2661  Line 4694 
4694      return $retVal;      return $retVal;
4695  }  }
4696    
4697  =head3 GetRelationTable  
4698    
4699    =head3 _GetRelationTable
4700    
4701  Get the list of relations for a specified entity or relationship.  Get the list of relations for a specified entity or relationship.
4702    
# Line 2690  Line 4725 
4725      return $objectData->{Relations};      return $objectData->{Relations};
4726  }  }
4727    
4728  =head3 ValidateFieldNames  =head3 _ValidateFieldNames
4729    
4730  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
4731  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 4752 
4752          for my $object (values %{$metadata->{$section}}) {          for my $object (values %{$metadata->{$section}}) {
4753              # Loop through the object's fields.              # Loop through the object's fields.
4754              for my $fieldName (keys %{$object->{Fields}}) {              for my $fieldName (keys %{$object->{Fields}}) {
4755                  # Now we make some initial validations.                  # If this field name is invalid, set the return value to zero
4756                  if ($fieldName =~ /--/) {                  # so we know we encountered an error.
4757                      # 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";  
4758                          $retVal = 0;                          $retVal = 0;
4759                      }                      }
4760                  }                  }
4761              }              }
4762          }          }
     }  
4763      # If an error was found, fail.      # If an error was found, fail.
4764      if ($retVal  == 0) {      if ($retVal  == 0) {
4765          Confess("Errors found in field names.");          Confess("Errors found in field names.");
4766      }      }
4767  }  }
4768    
4769  =head3 LoadRelation  =head3 _LoadRelation
4770    
4771  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
4772  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 4817 
4817      # be a null string.      # be a null string.
4818      if ($fileName ne "") {      if ($fileName ne "") {
4819          # Load the relation from the file.          # Load the relation from the file.
4820          $retVal = $self->LoadTable($fileName, $relationName, $rebuild);          $retVal = $self->LoadTable($fileName, $relationName, truncate => $rebuild);
4821      } elsif ($rebuild) {      } elsif ($rebuild) {
4822          # 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.
4823          $self->CreateTable($relationName, 1);          $self->CreateTable($relationName, 1);
# Line 2805  Line 4826 
4826      return $retVal;      return $retVal;
4827  }  }
4828    
4829  =head3 LoadMetaData  
4830    =head3 _LoadMetaData
4831    
4832        my $metadata = ERDB::_LoadMetaData($filename);
4833    
4834  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.
4835  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 4854 
4854  sub _LoadMetaData {  sub _LoadMetaData {
4855      # Get the parameters.      # Get the parameters.
4856      my ($filename) = @_;      my ($filename) = @_;
4857      Trace("Reading Sprout DBD from $filename.") if T(2);      Trace("Reading DBD from $filename.") if T(2);
4858      # 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
4859      # get the exact structure we want.      # get the exact structure we want.
4860      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);  
4861      # 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,
4862      # the method below will fail.      # the method below will fail.
4863      _ValidateFieldNames($metadata);      _ValidateFieldNames($metadata);
# Line 2969  Line 4980 
4980              if ($found == 0) {              if ($found == 0) {
4981                  push @{$indexList}, { IndexFields => [ {name => 'id', order => 'ascending'} ] };                  push @{$indexList}, { IndexFields => [ {name => 'id', order => 'ascending'} ] };
4982              }              }
4983              # 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.
4984              # 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++;  
             }  
4985          }          }
4986          # Finally, we add the relation structure to the entity.          # Finally, we add the relation structure to the entity.
4987          $entityStructure->{Relations} = $relationTable;          $entityStructure->{Relations} = $relationTable;
# Line 2993  Line 4995 
4995          _FixupFields($relationshipStructure, $relationshipName, 2, 3);          _FixupFields($relationshipStructure, $relationshipName, 2, 3);
4996          # Format a description for the FROM field.          # Format a description for the FROM field.
4997          my $fromEntity = $relationshipStructure->{from};          my $fromEntity = $relationshipStructure->{from};
4998          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].";
4999          # Get the FROM entity's key type.          # Get the FROM entity's key type.
5000          my $fromType = $entityList->{$fromEntity}->{keyType};          my $fromType = $entityList->{$fromEntity}->{keyType};
5001          # Add the FROM field.          # Add the FROM field.
# Line 3003  Line 5005 
5005                                                      PrettySort => 1});                                                      PrettySort => 1});
5006          # Format a description for the TO field.          # Format a description for the TO field.
5007          my $toEntity = $relationshipStructure->{to};          my $toEntity = $relationshipStructure->{to};
5008          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].";
5009          # Get the TO entity's key type.          # Get the TO entity's key type.
5010          my $toType = $entityList->{$toEntity}->{keyType};          my $toType = $entityList->{$toEntity}->{keyType};
5011          # Add the TO field.          # Add the TO field.
# Line 3015  Line 5017 
5017          my $thisRelation = { Fields => _ReOrderRelationTable($relationshipStructure->{Fields}),          my $thisRelation = { Fields => _ReOrderRelationTable($relationshipStructure->{Fields}),
5018                               Indexes => { } };                               Indexes => { } };
5019          $relationshipStructure->{Relations} = { $relationshipName => $thisRelation };          $relationshipStructure->{Relations} = { $relationshipName => $thisRelation };
5020    
5021            # Add the alternate indexes (if any). This MUST be done before the FROM and
5022            # TO indexes, because it erases the relation's index list.
5023            if (exists $relationshipStructure->{Indexes}) {
5024                _ProcessIndexes($relationshipStructure->{Indexes}, $thisRelation);
5025            }
5026            # Add the relation to the master table.
5027          # Create the FROM and TO indexes.          # Create the FROM and TO indexes.
5028          _CreateRelationshipIndex("From", $relationshipName, $relationshipStructure);          _CreateRelationshipIndex("From", $relationshipName, $relationshipStructure);
5029          _CreateRelationshipIndex("To", $relationshipName, $relationshipStructure);          _CreateRelationshipIndex("To", $relationshipName, $relationshipStructure);
         # Add the relation to the master table.  
5030          $masterRelationTable{$relationshipName} = $thisRelation;          $masterRelationTable{$relationshipName} = $thisRelation;
5031      }      }
5032      # Now store the master relation table in the metadata structure.      # Now store the master relation table in the metadata structure.
# Line 3117  Line 5125 
5125          # 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
5126          # 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
5127          # possible to get the same effect using multiple queries.          # possible to get the same effect using multiple queries.
5128          for my $relationshipName (@bothList) {          for my $relationshipName (@bothList) {
5129              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);
5130              # Join to the entity from each direction.              # Join to the entity from each direction.
5131              $joinTable{"$entityName/$relationshipName"} =              $joinTable{"$entityName/$relationshipName"} =
5132                  "$entityName.id = $relationshipName.from_link";                  "$entityName.id = $relationshipName.from_link";
5133              $joinTable{"$relationshipName/$entityName"} =              $joinTable{"$relationshipName/$entityName"} =
5134                  "$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;  
5135          }          }
5136      }      }
5137      # Return the result.      # Add the join table to the structure.
5138      return $retVal;      $metadata->{Joins} = \%joinTable;
5139        # Return the slurped and fixed-up structure.
5140        return $metadata;
5141  }  }
5142    
5143  =head3 CreateRelationshipIndex  =head3 _CreateRelationshipIndex
5144    
5145  Create an index for a relationship's relation.  Create an index for a relationship's relation.
5146    
# Line 3214  Line 5182 
5182          $newIndex->{Unique} = 'true';          $newIndex->{Unique} = 'true';
5183      }      }
5184      # Add the index to the relation.      # Add the index to the relation.
5185      _AddIndex("idx$relationshipName$indexKey", $relationStructure, $newIndex);      _AddIndex("idx$indexKey", $relationStructure, $newIndex);
5186    }
5187    
5188    =head3 _ProcessIndexes
5189    
5190        ERDB::_ProcessIndexes($indexList, $relation);
5191    
5192    Build the data structures for the specified indexes in the specified relation.
5193    
5194    =over 4
5195    
5196    =item indexList
5197    
5198    Reference to a list of indexes. Each index is a hash reference containing an optional
5199    C<Notes> value that describes the index and an C<IndexFields> value that is a reference
5200    to a list of index field structures. An index field structure, in turn, is a reference
5201    to a hash that contains a C<name> attribute for the field name and an C<order>
5202    attribute that specifies either C<ascending> or C<descending>. In this sense the
5203    index list encapsulates the XML C<Indexes> structure in the database definition.
5204    
5205    =item relation
5206    
5207    The structure that describes the current relation. The new index descriptors will
5208    be stored in the structure's C<Indexes> member. Any previous data in the structure
5209    will be lost.
5210    
5211    =back
5212    
5213    =cut
5214    
5215    sub _ProcessIndexes {
5216        # Get the parameters.
5217        my ($indexList, $relation) = @_;
5218        # Now we need to convert the relation's index list to an index table. We begin by creating
5219        # an empty table in the relation structure.
5220        $relation->{Indexes} = { };
5221        # Loop through the indexes.
5222        my $count = 0;
5223        for my $index (@{$indexList}) {
5224            # Add this index to the index table.
5225            _AddIndex("idx$count", $relation, $index);
5226            # Increment the counter so that the next index has a different name.
5227            $count++;
5228        }
5229  }  }
5230    
5231  =head3 AddIndex  =head3 _AddIndex
5232    
5233  Add an index to a relation structure.  Add an index to a relation structure.
5234    
# Line 3263  Line 5274 
5274      $relationStructure->{Indexes}->{$indexName} = $newIndex;      $relationStructure->{Indexes}->{$indexName} = $newIndex;
5275  }  }
5276    
5277  =head3 FixupFields  =head3 _FixupFields
5278    
5279  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
5280  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 5312 
5312          # Here it doesn't, so we create a new one.          # Here it doesn't, so we create a new one.
5313          $structure->{Fields} = { };          $structure->{Fields} = { };
5314      } else {      } else {
5315          # 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
5316            # create a list for stashing them.
5317            my @textFields = ();
5318            # Loop through the fields.
5319          my $fieldStructures = $structure->{Fields};          my $fieldStructures = $structure->{Fields};
5320          for my $fieldName (keys %{$fieldStructures}) {          for my $fieldName (keys %{$fieldStructures}) {
5321              Trace("Processing field $fieldName of $defaultRelationName.") if T(4);              Trace("Processing field $fieldName of $defaultRelationName.") if T(4);
# Line 3310  Line 5324 
5324              my $type = $fieldData->{type};              my $type = $fieldData->{type};
5325              # Plug in a relation name if it is needed.              # Plug in a relation name if it is needed.
5326              Tracer::MergeOptions($fieldData, { relation => $defaultRelationName });              Tracer::MergeOptions($fieldData, { relation => $defaultRelationName });
5327              # Plug in a data generator if we need one.              # Check for searchability.
5328              if (!exists $fieldData->{DataGen}) {              if ($fieldData->{searchable}) {
5329                  # The data generator will use the default for the field's type.                  # Only allow this for a primary relation.
5330                  $fieldData->{DataGen} = { content => $TypeTable{$type}->{dataGen} };                  if ($fieldData->{relation} ne $defaultRelationName) {
5331                        Confess("Field $fieldName of $defaultRelationName is in secondary relations and cannot be searchable.");
5332                    } else {
5333                        push @textFields, $fieldName;
5334                    }
5335              }              }
             # Plug in the defaults for the optional data generation parameters.  
             Tracer::MergeOptions($fieldData->{DataGen}, { testCount => 1, pass => 0 });  
5336              # Add the PrettySortValue.              # Add the PrettySortValue.
5337              $fieldData->{PrettySort} = (($type eq "text") ? $textPrettySortValue : $prettySortValue);              $fieldData->{PrettySort} = (($type eq "text") ? $textPrettySortValue : $prettySortValue);
5338          }          }
5339            # If there are searchable fields, remember the fact.
5340            if (@textFields) {
5341                $structure->{searchFields} = \@textFields;
5342            }
5343      }      }
5344  }  }
5345    
5346  =head3 FixName  =head3 _FixName
5347    
5348  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.
5349    
# Line 3352  Line 5372 
5372      return $fieldName;      return $fieldName;
5373  }  }
5374    
5375  =head3 FixNames  =head3 _FixNames
5376    
5377  Fix all the field names in a list.  Fix all the field names in a list.
5378    
# Line 3383  Line 5403 
5403      return @result;      return @result;
5404  }  }
5405    
5406  =head3 AddField  =head3 _AddField
5407    
5408  Add a field to a field list.  Add a field to a field list.
5409    
# Line 3418  Line 5438 
5438      $fieldList->{$fieldName} = $fieldStructure;      $fieldList->{$fieldName} = $fieldStructure;
5439  }  }
5440    
5441  =head3 ReOrderRelationTable  =head3 _ReOrderRelationTable
5442    
5443  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
5444  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 5499 
5499    
5500  }  }
5501    
5502  =head3 IsPrimary  =head3 _IsPrimary
5503    
5504  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
5505  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 5535 
5535      return $retVal;      return $retVal;
5536  }  }
5537    
5538  =head3 FindRelation  =head3 _FindRelation
5539    
5540  Return the descriptor for the specified relation.  Return the descriptor for the specified relation.
5541    
# Line 3544  Line 5564 
5564      return $retVal;      return $retVal;
5565  }  }
5566    
5567  =head2 HTML Documentation Utility Methods  =head2 Documentation Utility Methods
5568    
5569  =head3 ComputeRelationshipSentence  =head3 _ComputeRelationshipSentence
5570    
5571  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
5572  two related entities and an arity indicator.  two related entities and an arity indicator.
# Line 3576  Line 5596 
5596      # Get the parameters.      # Get the parameters.
5597      my ($relationshipName, $relationshipStructure) = @_;      my ($relationshipName, $relationshipStructure) = @_;
5598      # Format the relationship sentence.      # Format the relationship sentence.
5599      my $result = "$relationshipStructure->{from} <b>$relationshipName</b> $relationshipStructure->{to}";      my $result = "$relationshipStructure->{from} $relationshipName $relationshipStructure->{to}";
5600      # Compute the arity.      # Compute the arity.
5601      my $arityCode = $relationshipStructure->{arity};      my $arityCode = $relationshipStructure->{arity};
5602      my $arity = $ArityTable{$arityCode};      my $arity = $ArityTable{$arityCode};
# Line 3584  Line 5604 
5604      return $result;      return $result;
5605  }  }
5606    
5607  =head3 ComputeRelationshipHeading  =head3 _ComputeRelationshipHeading
5608    
5609  The relationship heading is the L<relationship sentence|/ComputeRelationshipSentence> with the entity  The relationship heading is the L<relationship sentence|/ComputeRelationshipSentence> with the entity
5610  names hyperlinked to the appropriate entity sections of the document.  names hyperlinked to the appropriate entity sections of the document.
# Line 3621  Line 5641 
5641      return $result;      return $result;
5642  }  }
5643    
5644  =head3 ShowRelationTable  =head3 _WikiRelationTable
5645    
5646    Generate the Wiki text for a particular relation. The relation's data will be formatted as a
5647    table with three columns-- the field name, the field type, and the field description.
5648    
5649    This is a static method.
5650    
5651    =over 4
5652    
5653    =item relationName
5654    
5655    Name of the relation being formatted.
5656    
5657    =item relationData
5658    
5659    Hash containing the relation's fields and indexes.
5660    
5661    =item RETURN
5662    
5663    Returns a Wiki string that can be used to display the relation name and all of its fields.
5664    
5665    =back
5666    
5667    =cut
5668    
5669    sub _WikiRelationTable {
5670        # Get the parameters.
5671        my ($relationName, $relationData) = @_;
5672        # We'll create a list of lists in here, then call WikiTools::Table to
5673        # convert it into a table.
5674        my @rows = ();
5675        # Push in the header row.
5676        push @rows, [qw(Field Type Description)];
5677        # Loop through the fields.
5678        for my $field (@{$relationData->{Fields}}) {
5679            # Create this field's row. We always have a name and type.
5680            my @row = ($field->{name}, $field->{type});
5681            # If we have a description, add it as the third column.
5682            if (exists $field->{Notes}) {
5683                push @row, WikiNote($field->{Notes}->{content});
5684            }
5685            # Push this row onto the table list.
5686            push @rows, \@row;
5687        }
5688        # Store the rows as a Wiki table with a level-4 heading.
5689        my $retVal = join("\n\n", WikiTools::Heading(4, "$relationName Table"),
5690                          WikiTools::Table(@rows));
5691        # Now we show the relation's indexes. These are formatted as another
5692        # table.
5693        @rows = ();
5694        # Push in the header row.
5695        push @rows, [qw(Index Unique Fields Notes)];
5696        # Get the index hash.
5697        my $indexTable = $relationData->{Indexes};
5698        # Loop through the indexes. For an entity, there is always at least one index.
5699        # For a relationship, there are at least two. The upshot is we don't need to
5700        # worry about accidentally generating a frivolous table here.
5701        for my $indexName (sort keys %$indexTable) {
5702            my $indexData = $indexTable->{$indexName};
5703            # Determine whether or not the index is unique.
5704            my $unique = ((exists $indexData->{Unique} && $indexData->{Unique} eq "true") ?
5705                          "yes" : "");
5706            # Get the field list.
5707            my $fields = join(', ', @{$indexData->{IndexFields}});
5708            # Get the note text.
5709            my $description = "";
5710            if (my $note = $indexData->{Notes}) {
5711                $description = WikiNote($note->{content});
5712            }
5713            # Format this row.
5714            my @row = ($indexName, $unique, $fields, $description);
5715            push @rows, \@row;
5716        }
5717        # Add the index list to the result.
5718        $retVal .= "\n\n" . WikiTools::Table(@rows);
5719    }
5720    
5721    =head3 _ShowRelationTable
5722    
5723  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
5724  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 5768 
5768          $htmlString .= "<li><b>Index $fullName</b>\n<ul>\n";          $htmlString .= "<li><b>Index $fullName</b>\n<ul>\n";
5769          # Add any note text.          # Add any note text.
5770          if (my $note = $indexData->{Notes}) {          if (my $note = $indexData->{Notes}) {
5771              $htmlString .= "<li>" . _HTMLNote($note->{content}) . "</li>\n";              $htmlString .= "<li>" . HTMLNote($note->{content}) . "</li>\n";
5772          }          }
5773          # Add the fiield list.          # Add the fiield list.
5774          $htmlString .= "<li><i>" . join(', ', @{$indexData->{IndexFields}}) . "</i></li>\n";          $htmlString .= "<li><i>" . join(', ', @{$indexData->{IndexFields}}) . "</i></li>\n";
# Line 3682  Line 5779 
5779      $htmlString .= "</ul>\n";      $htmlString .= "</ul>\n";
5780  }  }
5781    
5782  =head3 OpenFieldTable  =head3 _OpenFieldTable
5783    
5784  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>.
5785    
# Line 3707  Line 5804 
5804      return _OpenTable($tablename, 'Field', 'Type', 'Description');      return _OpenTable($tablename, 'Field', 'Type', 'Description');
5805  }  }
5806    
5807  =head3 OpenTable  =head3 _OpenTable
5808    
5809  This method creates the header string for an HTML table.  This method creates the header string for an HTML table.
5810    
# Line 3737  Line 5834 
5834      # Compute the number of columns.      # Compute the number of columns.
5835      my $colCount = @colNames;      my $colCount = @colNames;
5836      # Generate the title row.      # Generate the title row.
5837      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";
5838      # Loop through the columns, adding the column header rows.      # Loop through the columns, adding the column header rows.
5839      $htmlString .= "<tr>";      $htmlString .= "<tr>";
5840      for my $colName (@colNames) {      for my $colName (@colNames) {
# Line 3747  Line 5844 
5844      return $htmlString;      return $htmlString;
5845  }  }
5846    
5847  =head3 CloseTable  =head3 _CloseTable
5848    
5849  This method returns the HTML for closing a table.  This method returns the HTML for closing a table.
5850    
#