[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.71, Sat Oct 14 18:08:12 2006 UTC revision 1.99, Fri Jul 11 01:04:08 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 217  Line 218 
218  index will be created for each relation with at least one searchable field in it.  index will be created for each relation with at least one searchable field in it.
219  For best results, this option should only be used for string or text fields.  For best results, this option should only be used for string or text fields.
220    
221    =item special
222    
223    This attribute allows the subclass to assign special meaning for certain fields.
224    The interpretation is up to the subclass itself. Currently, only entity fields
225    can have this attribute.
226    
227  =back  =back
228    
229  =head3 Indexes  =head3 Indexes
230    
231  An entity can have multiple alternate indexes associated with it. The fields must  An entity can have multiple alternate indexes associated with it. The fields in an
232  be from the primary relation. The alternate indexes assist in ordering results  index must all be from the same relation. The alternate indexes assist in searching
233  from a query. A relationship can have up to two indexes-- a I<to-index> and a  on fields other than the entity ID. A relationship has at least two indexes-- a I<to-index> and a
234  I<from-index>. These order the results when crossing the relationship. For  I<from-index> that order the results when crossing the relationship. For
235  example, in the relationship C<HasContig> from C<Genome> to C<Contig>, the  example, in the relationship C<HasContig> from C<Genome> to C<Contig>, the
236  from-index would order the contigs of a ganome, and the to-index would order  from-index would order the contigs of a ganome, and the to-index would order
237  the genomes of a contig. A relationship's index must specify only fields in  the genomes of a contig. In addition, it can have zero or more alternate
238    indexes. A relationship's index must specify only fields in
239  the relationship.  the relationship.
240    
241  The indexes for an entity must be listed inside the B<Indexes> tag. The from-index  The alternate indexes for an entity or relationship must be listed inside the B<Indexes> tag.
242  of a relationship is specified using the B<FromIndex> tag; the to-index is specified  The from-index of a relationship is specified using the B<FromIndex> tag; the to-index is
243  using the B<ToIndex> tag.  specified using the B<ToIndex> tag.
244    
245  Each index can contain a B<Notes> tag. In addition, it will have an B<IndexFields>  Each index can contain a B<Notes> tag. In addition, it will have an B<IndexFields>
246  tag containing the B<IndexField> tags. These specify, in order, the fields used in  tag containing the B<IndexField> tags. These specify, in order, the fields used in
# Line 250  Line 258 
258    
259  =back  =back
260    
261  The B<Index>, B<FromIndex>, and B<ToIndex> tags themselves have no attributes.  The B<FromIndex>, and B<ToIndex> tags have no attributes. The B<Index> tag can
262    have a B<Unique> attribute. If specified, the index will be generated as a unique
263    index.
264    
265  =head3 Object and Field Names  =head3 Object and Field Names
266    
# Line 294  Line 304 
304    
305  A relationship is described by the C<Relationship> tag. Within a relationship,  A relationship is described by the C<Relationship> tag. Within a relationship,
306  there can be a C<Notes> tag, a C<Fields> tag containing the intersection data  there can be a C<Notes> tag, a C<Fields> tag containing the intersection data
307  fields, a C<FromIndex> tag containing the from-index, and a C<ToIndex> tag containing  fields, a C<FromIndex> tag containing the from-index, a C<ToIndex> tag containing
308  the to-index.  the to-index, and an C<Indexes> tag containing the alternate indexes.
309    
310  The C<Relationship> tag has the following attributes.  The C<Relationship> tag has the following attributes.
311    
# Line 328  Line 338 
338    
339  # Table of information about our datatypes. "sqlType" is the corresponding SQL datatype string.  # Table of information about our datatypes. "sqlType" is the corresponding SQL datatype string.
340  # "maxLen" is the maximum permissible length of the incoming string data used to populate a field  # "maxLen" is the maximum permissible length of the incoming string data used to populate a field
341  # of the specified type. "dataGen" is PERL string that will be evaluated if no test data generation  # of the specified type. "avgLen" is the average byte length for estimating
342  # string is specified in the field definition. "avgLen" is the average byte length for estimating  # record sizes. "sort" is the key modifier for the sort command, "notes" is a type description,
343  # record sizes. "sort" is the key modifier for the sort command.  # and "indexMod", if non-zero, is the number of characters to use when the field is specified in an
344  my %TypeTable = ( char =>    { sqlType => 'CHAR(1)',            maxLen => 1,            avgLen =>   1, sort => "",  dataGen => "StringGen('A')" },  # index
345                    int =>     { sqlType => 'INTEGER',            maxLen => 20,           avgLen =>   4, sort => "n", dataGen => "IntGen(0, 99999999)" },  my %TypeTable = ( char =>    { sqlType => 'CHAR(1)',            maxLen => 1,            avgLen =>   1, sort => "",
346                    counter => { sqlType => 'INTEGER UNSIGNED',   maxLen => 20,           avgLen =>   4, sort => "n", dataGen => "IntGen(0, 99999999)" },                                 indexMod =>   0, notes => "single ASCII character"},
347                    string =>  { sqlType => 'VARCHAR(255)',       maxLen => 255,          avgLen => 100, sort => "",  dataGen => "StringGen(IntGen(10,250))" },                    int =>     { sqlType => 'INTEGER',            maxLen => 20,           avgLen =>   4, sort => "n",
348                    text =>    { sqlType => 'TEXT',               maxLen => 1000000000,   avgLen => 500, sort => "",  dataGen => "StringGen(IntGen(80,1000))" },                                 indexMod =>   0, notes => "signed 32-bit integer"},
349                    date =>    { sqlType => 'BIGINT',             maxLen => 80,           avgLen =>   8, sort => "n", dataGen => "DateGen(-7, 7, IntGen(0,1400))" },                    counter => { sqlType => 'INTEGER UNSIGNED',   maxLen => 20,           avgLen =>   4, sort => "n",
350                    float =>   { sqlType => 'DOUBLE PRECISION',   maxLen => 40,           avgLen =>   8, sort => "g", dataGen => "FloatGen(0.0, 100.0)" },                                 indexMod =>   0, notes => "unsigned 32-bit integer"},
351                    boolean => { sqlType => 'SMALLINT',           maxLen => 1,            avgLen =>   1, sort => "n", dataGen => "IntGen(0, 1)" },                    string =>  { sqlType => 'VARCHAR(255)',       maxLen => 255,          avgLen => 100, sort => "",
352                                   indexMod =>   0, notes => "character string, 0 to 255 characters"},
353                      text =>    { sqlType => 'TEXT',               maxLen => 1000000000,   avgLen => 500, sort => "",
354                                   indexMod => 255, notes => "character string, nearly unlimited length, only first 255 characters are indexed"},
355                      date =>    { sqlType => 'BIGINT',             maxLen => 80,           avgLen =>   8, sort => "n",
356                                   indexMod =>   0, notes => "signed, 64-bit integer"},
357                      float =>   { sqlType => 'DOUBLE PRECISION',   maxLen => 40,           avgLen =>   8, sort => "g",
358                                   indexMod =>   0, notes => "64-bit double precision floating-point number"},
359                      boolean => { sqlType => 'SMALLINT',           maxLen => 1,            avgLen =>   1, sort => "n",
360                                   indexMod =>   0, notes => "boolean value: 0 if false, 1 if true"},
361                   'hash-string' =>                   'hash-string' =>
362                               { sqlType => 'VARCHAR(22)',        maxLen => 22,           avgLen =>  22, sort => "",  dataGen => "SringGen(22)" },                               { sqlType => 'VARCHAR(22)',        maxLen => 22,           avgLen =>  22, sort => "",
363                                   indexMod =>   0, notes => "string stored in digested form, used for certain types of key fields"},
364                   'id-string' =>                   'id-string' =>
365                               { sqlType => 'VARCHAR(25)',        maxLen => 25,           avgLen =>  25, sort => "",  dataGen => "SringGen(22)" },                               { sqlType => 'VARCHAR(25)',        maxLen => 25,           avgLen =>  25, sort => "",
366                                   indexMod =>   0, notes => "character string, 0 to 25 characters"},
367                   'key-string' =>                   'key-string' =>
368                               { sqlType => 'VARCHAR(40)',        maxLen => 40,           avgLen =>  10, sort => "",  dataGen => "StringGen(IntGen(10,40))" },                               { sqlType => 'VARCHAR(40)',        maxLen => 40,           avgLen =>  10, sort => "",
369                                   indexMod =>   0, notes => "character string, 0 to 40 characters"},
370                   'name-string' =>                   'name-string' =>
371                               { sqlType => 'VARCHAR(80)',        maxLen => 80,           avgLen =>  40, sort => "",  dataGen => "StringGen(IntGen(10,80))" },                               { sqlType => 'VARCHAR(80)',        maxLen => 80,           avgLen =>  40, sort => "",
372                                   indexMod =>   0, notes => "character string, 0 to 80 characters"},
373                   'medium-string' =>                   'medium-string' =>
374                               { sqlType => 'VARCHAR(160)',       maxLen => 160,          avgLen =>  40, sort => "",  dataGen => "StringGen(IntGen(10,160))" },                               { sqlType => 'VARCHAR(160)',       maxLen => 160,          avgLen =>  40, sort => "",
375                                   indexMod =>   0, notes => "character string, 0 to 160 characters"},
376                     'long-string' =>
377                                 { sqlType => 'VARCHAR(500)',       maxLen => 500,          avglen => 255, sort => "",
378                                   indexMod =>   0, notes => "character string, 0 to 500 characters"},
379                  );                  );
380    
381  # Table translating arities into natural language.  # Table translating arities into natural language.
# Line 357  Line 384 
384                     'MM' => 'many-to-many'                     'MM' => 'many-to-many'
385                   );                   );
386    
387  # Table for interpreting string patterns.  # Options for XML input and output.
388    
389    my %XmlOptions = (GroupTags =>  { Relationships => 'Relationship',
390                                      Entities => 'Entity',
391                                      Fields => 'Field',
392                                      Indexes => 'Index',
393                                      IndexFields => 'IndexField',
394                                      Issues => 'Issue',
395                                      Shapes => 'Shape'
396                                    },
397                      KeyAttr =>    { Relationship => 'name',
398                                      Entity => 'name',
399                                      Field => 'name',
400                                      Shape => 'name'
401                                    },
402                      SuppressEmpty => 1,
403                     );
404    
405  my %PictureTable = ( 'A' => "abcdefghijklmnopqrstuvwxyz",  my %XmlInOpts  = (
406                       '9' => "0123456789",                    ForceArray => [qw(Field Index IndexField Relationship Entity Shape)],
407                       'X' => "abcdefghijklmnopqrstuvwxyz0123456789",                    ForceContent => 1,
408                       'V' => "aeiou",                    NormalizeSpace => 2,
409                       'K' => "bcdfghjklmnoprstvwxyz"                   );
410    my %XmlOutOpts = (
411                      RootName => 'Database',
412                      XMLDecl => 1,
413                     );                     );
414    
415  =head2 Public Methods  =head2 Public Methods
416    
417  =head3 new  =head3 new
418    
419  C<< my $database = ERDB->new($dbh, $metaFileName); >>      my $database = ERDB->new($dbh, $metaFileName);
420    
421  Create a new ERDB object.  Create a new ERDB object.
422    
# Line 390  Line 436 
436    
437  sub new {  sub new {
438      # Get the parameters.      # Get the parameters.
439      my ($class, $dbh, $metaFileName, $options) = @_;      my ($class, $dbh, $metaFileName, %options) = @_;
440      # Load the meta-data.      # Load the meta-data.
441      my $metaData = _LoadMetaData($metaFileName);      my $metaData = _LoadMetaData($metaFileName);
442      # Create the object.      # Create the object.
# Line 404  Line 450 
450    
451  =head3 ShowMetaData  =head3 ShowMetaData
452    
453  C<< $erdb->ShowMetaData($fileName); >>      $erdb->ShowMetaData($fileName);
454    
455  This method outputs a description of the database. This description can be used to help users create  This method outputs a description of the database. This description can be used to help users create
456  the data to be loaded into the relations.  the data to be loaded into the relations.
# Line 445  Line 491 
491    
492  =head3 DisplayMetaData  =head3 DisplayMetaData
493    
494  C<< my $html = $erdb->DisplayMetaData(); >>      my $html = $erdb->DisplayMetaData();
495    
496  Return an HTML description of the database. This description can be used to help users create  Return an HTML description of the database. This description can be used to help users create
497  the data to be loaded into the relations and form queries. The output is raw includable HTML  the data to be loaded into the relations and form queries. The output is raw includable HTML
# Line 506  Line 552 
552          my $entityData = $entityList->{$key};          my $entityData = $entityList->{$key};
553          # If there's descriptive text, display it.          # If there's descriptive text, display it.
554          if (my $notes = $entityData->{Notes}) {          if (my $notes = $entityData->{Notes}) {
555              $retVal .= "<p>" . _HTMLNote($notes->{content}) . "</p>\n";              $retVal .= "<p>" . HTMLNote($notes->{content}) . "</p>\n";
556          }          }
557          # Now we want a list of the entity's relationships. First, we set up the relationship subsection.          # See if we need a list of the entity's relationships.
558            my $relCount = keys %{$relationshipList};
559            if ($relCount > 0) {
560                # First, we set up the relationship subsection.
561          $retVal .= "<h4>Relationships for <b>$key</b></h4>\n<ul>\n";          $retVal .= "<h4>Relationships for <b>$key</b></h4>\n<ul>\n";
562          # Loop through the relationships.          # Loop through the relationships.
563          for my $relationship (sort keys %{$relationshipList}) {          for my $relationship (sort keys %{$relationshipList}) {
# Line 524  Line 573 
573          }          }
574          # Close off the relationship list.          # Close off the relationship list.
575          $retVal .= "</ul>\n";          $retVal .= "</ul>\n";
576            }
577          # Get the entity's relations.          # Get the entity's relations.
578          my $relationList = $entityData->{Relations};          my $relationList = $entityData->{Relations};
579          # Create a header for the relation subsection.          # Create a header for the relation subsection.
# Line 563  Line 613 
613          $retVal .= "</p>\n";          $retVal .= "</p>\n";
614          # If there are notes on this relationship, display them.          # If there are notes on this relationship, display them.
615          if (my $notes = $relationshipStructure->{Notes}) {          if (my $notes = $relationshipStructure->{Notes}) {
616              $retVal .= "<p>" . _HTMLNote($notes->{content}) . "</p>\n";              $retVal .= "<p>" . HTMLNote($notes->{content}) . "</p>\n";
617          }          }
618          # Generate the relationship's relation table.          # Generate the relationship's relation table.
619          my $htmlString = _ShowRelationTable($key, $relationshipStructure->{Relations}->{$key});          my $htmlString = _ShowRelationTable($key, $relationshipStructure->{Relations}->{$key});
# Line 597  Line 647 
647    
648  =head3 DumpMetaData  =head3 DumpMetaData
649    
650  C<< $erdb->DumpMetaData(); >>      $erdb->DumpMetaData();
651    
652  Return a dump of the metadata structure.  Return a dump of the metadata structure.
653    
# Line 610  Line 660 
660      return Data::Dumper::Dumper($self->{_metaData});      return Data::Dumper::Dumper($self->{_metaData});
661  }  }
662    
663    =head3 GenerateWikiData
664    
665        my @wikiLines = $erdb->GenerateWikiData();
666    
667    Build a description of the database for the wiki. The database will be
668    organized into a single page, with sections for each entity and relationship.
669    The return value is a list of text lines.
670    
671    =cut
672    
673    sub GenerateWikiData {
674        # Get the parameters.
675        my ($self) = @_;
676        # We'll build the wiki text in here.
677        my @retVal = ();
678        # Get the metadata object.
679        my $metadata = $self->{_metaData};
680        # Get the title string. This will become the page name.
681        my $title = $metadata->{Title}->{content};
682        # Get the entity and relationship lists.
683        my $entityList = $metadata->{Entities};
684        my $relationshipList = $metadata->{Relationships};
685        my $shapeList = $metadata->{Shapes};
686        # Start with the introductory text.
687        push @retVal, WikiTools::Heading(2, "Introduction");
688        if (my $notes = $metadata->{Notes}) {
689            push @retVal, WikiNote($notes->{content});
690        }
691        # Generate issue list.
692        if (my $issues = $metadata->{Issues}) {
693            push @retVal, WikiTools::Heading(3, 'Issues');
694            push @retVal, WikiTools::List(map { $_->{content} } @{$issues});
695        }
696        # Start the entity section.
697        push @retVal, WikiTools::Heading(2, "Entities");
698        # Loop through the entities. Note that unlike the situation with HTML, we
699        # don't need to generate the table of contents manually, just the data
700        # itself.
701        for my $key (sort keys %$entityList) {
702            # Create a header for this entity.
703            push @retVal, "", WikiTools::Heading(3, $key);
704            # Get the entity data.
705            my $entityData = $entityList->{$key};
706            # Plant the notes here, if there are any.
707            push @retVal, _ObjectNotes($entityData);
708            # Now we list the entity's relationships (if any). First, we build a list
709            # of the relationships relevant to this entity.
710            my @rels = ();
711            for my $rel (sort keys %$relationshipList) {
712                my $relStructure = $relationshipList->{$rel};
713                if ($relStructure->{from} eq $key || $relStructure->{to} eq $key) {
714                    # Get the relationship sentence.
715                    my $relSentence = _ComputeRelationshipSentence($rel, $relStructure);
716                    # Linkify it.
717                    my $linkedRel = WikiTools::LinkMarkup("#$rel", $rel);
718                    $relSentence =~ s/$rel/$linkedRel/;
719                    push @rels, $relSentence;
720                }
721            }
722            # Add the relationships as a Wiki list.
723            push @retVal, WikiTools::List(@rels);
724            # Get the entity's relations.
725            my $relationList = $entityData->{Relations};
726            # Loop through the relations, displaying them.
727            for my $relation (sort keys %{$relationList}) {
728                my $wikiString = _WikiRelationTable($relation, $relationList->{$relation});
729                push @retVal, $wikiString;
730            }
731        }
732        # Now the entities are documented. Next we do the relationships.
733        push @retVal, WikiTools::Heading(2, "Relationships");
734        for my $key (sort keys %$relationshipList) {
735            my $relationshipData = $relationshipList->{$key};
736            # Create the relationship heading.
737            push @retVal, WikiTools::Heading(3, $key);
738            # Describe the relationship arity. Note there's a bit of trickiness involving recursive
739            # many-to-many relationships. In a normal many-to-many we use two sentences to describe
740            # the arity (one for each direction). This is a bad idea for a recursive relationship,
741            # since both sentences will say the same thing.
742            my $arity = $relationshipData->{arity};
743            my $fromEntity = $relationshipData->{from};
744            my $toEntity = $relationshipData->{to};
745            my @listElements = ();
746            my $boldCode = WikiTools::BoldCode();
747            if ($arity eq "11") {
748                push @listElements, "Each $boldCode$fromEntity$boldCode relates to at most one $boldCode$toEntity$boldCode.";
749            } else {
750                push @listElements, "Each $boldCode$fromEntity$boldCode relates to multiple $boldCode${toEntity}s$boldCode.";
751                if ($arity eq "MM" && $fromEntity ne $toEntity) {
752                    push @listElements, "Each $boldCode$toEntity$boldCode relates to multiple $boldCode${fromEntity}s$boldCode.";
753                }
754            }
755            push @retVal, WikiTools::List(@listElements);
756            # Plant the notes here, if there are any.
757            push @retVal, _ObjectNotes($relationshipData);
758            # Finally, the relationship table.
759            my $wikiString = _WikiRelationTable($key, $relationshipData->{Relations}->{$key});
760            push @retVal, $wikiString;
761        }
762        # Now loop through the miscellaneous shapes.
763        if ($shapeList) {
764            push @retVal, WikiTools::Heading(2, "Miscellaneous");
765            for my $shape (sort keys %$shapeList) {
766                push @retVal, WikiTools::Heading(3, $shape);
767                my $shapeData = $shapeList->{$shape};
768                push @retVal, _ObjectNotes($shapeData);
769            }
770        }
771        # All done. Return the lines.
772        return @retVal;
773    }
774    
775    
776    =head3 CreatePPO
777    
778        ERDB::CreatePPO($erdbXMLFile, $ppoXMLFile);
779    
780    Create a PPO XML file from an ERDB data definition XML file. At the
781    current time, the PPO XML file can be used to create a database with
782    similar functionality. Eventually, the PPO will be able to use the
783    created XML to access the live ERDB database.
784    
785    =over 4
786    
787    =item erdbXMLFile
788    
789    Name of the XML data definition file for the ERDB database. This
790    file must exist.
791    
792    =item ppoXMLFile
793    
794    Output file for the PPO XML definition. If this file exists, it
795    will be overwritten.
796    
797    =back
798    
799    =cut
800    
801    sub CreatePPO {
802        # Get the parameters.
803        my ($erdbXMLFile, $ppoXMLFile) = @_;
804        # First, we want to slurp in the ERDB XML file in its raw form.
805        my $xml = ReadMetaXML($erdbXMLFile);
806        # Create a variable to hold all of the objects in the PPO project.
807        my @objects = ();
808        # Get the relationship hash.
809        my $relationships = $xml->{Relationships};
810        # Loop through the entities.
811        my $entities = $xml->{Entities};
812        for my $entityName (keys %{$entities}) {
813            # Get the entity's data structures.
814            my $entityObject = $entities->{$entityName};
815            # We put the object's fields in here, according to their type.
816            my (@object_refs, @scalars, @indexes, @arrays);
817            # Create the ID field for the entity. We get the key type from the
818            # entity object and compute the corresponding SQL type.
819            my $type = $TypeTable{$entityObject->{keyType}}->{sqlType};
820            push @scalars, { label => 'id', type => $type };
821            # Loop through the entity fields.
822            for my $fieldName ( keys %{$entityObject->{Fields}} ) {
823                # Get the field object.
824                my $fieldObject = $entityObject->{Fields}->{$fieldName};
825                # Convert it to a scalar tag.
826                my $scalar = _CreatePPOField($fieldName, $fieldObject);
827                # If we have a relation, this field is stored in an array.
828                # otherwise, it is a scalar. The array tag has scalars
829                # stored as an XML array. In ERDB, there is only ever one,
830                # but PPO can have more.
831                my $relation = $fieldObject->{relation};
832                if ($relation) {
833                    push @arrays, { scalar => [$scalar] };
834                } else {
835                    push @scalars, $scalar;
836                }
837            }
838            # Loop through the relationships. If this entity is the to-entity
839            # on a relationship of 1M arity, then it is implemented as a PPO
840            # object reference.
841            for my $relationshipName (keys %{$relationships}) {
842                # Get the relationship data.
843                my $relationshipData = $relationships->{$relationshipName};
844                # If we have a from for this entity and an arity of 1M, we
845                # have an object reference.
846                if ($relationshipData->{to} eq $entityName &&
847                    $relationshipData->{arity} eq '1M') {
848                    # Build the object reference tag.
849                    push @object_refs, { label => $relationshipName,
850                                         type => $relationshipData->{from} };
851                }
852            }
853            # Create the indexes.
854            my $indexList = $entityObject->{Indexes};
855            push @indexes, map { _CreatePPOIndex($_) } @{$indexList};
856            # Build the object XML tree.
857            my $object = { label => $entityName,
858                           object_ref => \@object_refs,
859                           scalar => \@scalars,
860                           index => \@indexes,
861                           array => \@arrays
862                          };
863            # Push the object onto the objects list.
864            push @objects, $object;
865        }
866        # Loop through the relationships, searching for MMs. The 1Ms were
867        # already handled by the entity search above.
868        for my $relationshipName (keys %{$relationships}) {
869            # Get this relationship's object.
870            my $relationshipObject = $relationships->{$relationshipName};
871            # Only proceed if it's many-to-many.
872            if ($relationshipObject->{arity} eq 'MM') {
873                # Create the tag lists for the relationship object.
874                my (@object_refs, @scalars, @indexes);
875                # The relationship will be created as an object with object
876                # references for its links to the participating entities.
877                my %links = ( from_link => $relationshipObject->{from},
878                              to_link => $relationshipObject->{to} );
879                for my $link (keys %links) {
880                    # Create an object_ref tag for this piece of the
881                    # relationship (from or to).
882                    my $object_ref = { label => $link,
883                                       type => $links{$link} };
884                    push @object_refs, $object_ref;
885                }
886                # Loop through the intersection data fields, creating scalar tags.
887                # There are no fancy array tags in a relationship.
888                for my $fieldName (keys %{$relationshipObject->{Fields}}) {
889                    my $fieldObject = $relationshipObject->{Fields}->{$fieldName};
890                    push @scalars, _CreatePPOField($fieldName, $fieldObject);
891                }
892                # Finally, the indexes: currently we cannot support the to-index and
893                # from-index in PPO, so we just process the alternate indexes.
894                my $indexList = $relationshipObject->{Indexes};
895                push @indexes, map { _CreatePPOIndex($_) } @{$indexList};
896                # Wrap up all the stuff about this relationship.
897                my $object = { label => $relationshipName,
898                               scalar => \@scalars,
899                               object_ref => \@object_refs,
900                               index => \@indexes
901                             };
902                # Push it into the object list.
903                push @objects, $object;
904            }
905        }
906        # Compute a title.
907        my $title;
908        if ($erdbXMLFile =~ /(\/|^)([^\/]+)DBD\.xml/) {
909            # Here we have a standard file name we can use for a title.
910            $title = $2;
911        } else {
912            # Here the file name is non-standard, so we carve up the
913            # database title.
914            $title = $xml->{Title}->{content};
915            $title =~ s/\s\.,//g;
916        }
917        # Wrap up the XML as a project.
918        my $ppoXML = { project => { label => $title,
919                                    object => \@objects }};
920        # Write out the results.
921        my $ppoString = XML::Simple::XMLout($ppoXML,
922                                            AttrIndent => 1,
923                                            KeepRoot => 1);
924        Tracer::PutFile($ppoXMLFile, [ $ppoString ]);
925    }
926    
927    =head3 FindIndexForEntity
928    
929        my $indexFound = ERDB::FindIndexForEntity($xml, $entityName, $attributeName);
930    
931    This method locates the entry in an entity's index list that begins with the
932    specified attribute name. If the entity has no index list, one will be
933    created. This method works on raw XML, not a live ERDB object.
934    
935    =over 4
936    
937    =item xml
938    
939    The raw XML structure defining the database.
940    
941    =item entityName
942    
943    The name of the relevant entity.
944    
945    =item attributeName
946    
947    The name of the attribute relevant to the search.
948    
949    =item RETURN
950    
951    The numerical index in the index list of the index entry for the specified entity and
952    attribute, or C<undef> if no such index exists.
953    
954    =back
955    
956    =cut
957    
958    sub FindIndexForEntity {
959        # Get the parameters.
960        my ($xml, $entityName, $attributeName) = @_;
961        # Declare the return variable.
962        my $retVal;
963        # Get the named entity.
964        my $entityData = $xml->{Entities}->{$entityName};
965        if (! $entityData) {
966            Confess("Entity $entityName not found in DBD structure.");
967        } else {
968            # Insure it has an index list.
969            if (! exists $entityData->{Indexes}) {
970                $entityData->{Indexes} = [];
971            } else {
972                # Search for the desired index.
973                my $indexList = $entityData->{Indexes};
974                my $n = scalar @{$indexList};
975                Trace("Searching $n indexes in index list for $entityName.") if T(2);
976                # We use an indexed FOR here because we're returning an
977                # index number instead of an object. We do THAT so we can
978                # delete the index from the list if needed.
979                for (my $i = 0; $i < $n && !defined($retVal); $i++) {
980                    my $index = $indexList->[$i];
981                    my $fields = $index->{IndexFields};
982                    # Technically this IF should be safe (that is, we are guaranteed
983                    # the existence of a "$fields->[0]"), because when we load the XML
984                    # we have SuppressEmpty specified.
985                    if ($fields->[0]->{name} eq $attributeName) {
986                        $retVal = $i;
987                    }
988                }
989            }
990        }
991        Trace("Index for $attributeName of $entityName found at position $retVal.") if defined($retVal) && T(3);
992        Trace("Index for $attributeName not found in $entityName.") if !defined($retVal) && T(3);
993        # Return the result.
994        return $retVal;
995    }
996    
997  =head3 CreateTables  =head3 CreateTables
998    
999  C<< $erdb->CreateTables(); >>      $erdb->CreateTables();
1000    
1001  This method creates the tables for the database from the metadata structure loaded by the  This method creates the tables for the database from the metadata structure loaded by the
1002  constructor. It is expected this function will only be used on rare occasions, when the  constructor. It is expected this function will only be used on rare occasions, when the
# Line 629  Line 1013 
1013      # Loop through the relations.      # Loop through the relations.
1014      for my $relationName (@relNames) {      for my $relationName (@relNames) {
1015          # Create a table for this relation.          # Create a table for this relation.
1016          $self->CreateTable($relationName);          $self->CreateTable($relationName, 1);
1017          Trace("Relation $relationName created.") if T(2);          Trace("Relation $relationName created.") if T(2);
1018      }      }
1019  }  }
1020    
1021  =head3 CreateTable  =head3 CreateTable
1022    
1023  C<< $erdb->CreateTable($tableName, $indexFlag, $estimatedRows); >>      $erdb->CreateTable($tableName, $indexFlag, $estimatedRows);
1024    
1025  Create the table for a relation and optionally create its indexes.  Create the table for a relation and optionally create its indexes.
1026    
# Line 692  Line 1076 
1076      my $estimation = undef;      my $estimation = undef;
1077      if ($estimatedRows) {      if ($estimatedRows) {
1078          $estimation = [$self->EstimateRowSize($relationName), $estimatedRows];          $estimation = [$self->EstimateRowSize($relationName), $estimatedRows];
1079            Trace("$estimation->[1] rows of $estimation->[0] bytes each.") if T(3);
1080      }      }
1081      # Create the table.      # Create the table.
1082      Trace("Creating table $relationName: $fieldThing") if T(2);      Trace("Creating table $relationName: $fieldThing") if T(2);
# Line 706  Line 1091 
1091    
1092  =head3 VerifyFields  =head3 VerifyFields
1093    
1094  C<< my $count = $erdb->VerifyFields($relName, \@fieldList); >>      my $count = $erdb->VerifyFields($relName, \@fieldList);
1095    
1096  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
1097  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 749  Line 1134 
1134              my $oldString = $fieldList->[$i];              my $oldString = $fieldList->[$i];
1135              if (length($oldString) > $maxLen) {              if (length($oldString) > $maxLen) {
1136                  # Here it's too big, so we truncate it.                  # Here it's too big, so we truncate it.
1137                  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);
1138                  $fieldList->[$i] = substr $oldString, 0, $maxLen;                  $fieldList->[$i] = substr $oldString, 0, $maxLen;
1139                  $retVal++;                  $retVal++;
1140              }              }
# Line 761  Line 1146 
1146    
1147  =head3 DigestFields  =head3 DigestFields
1148    
1149  C<< $erdb->DigestFields($relName, $fieldList); >>      $erdb->DigestFields($relName, $fieldList);
1150    
1151  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
1152  specified relation.  specified relation.
# Line 801  Line 1186 
1186    
1187  =head3 DigestKey  =head3 DigestKey
1188    
1189  C<< my $digested = $erdb->DigestKey($keyValue); >>      my $digested = $erdb->DigestKey($keyValue);
1190    
1191  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
1192  key-based search into a table with key-type hash-string.  key-based search into a table with key-type hash-string.
# Line 834  Line 1219 
1219    
1220  =head3 CreateIndex  =head3 CreateIndex
1221    
1222  C<< $erdb->CreateIndex($relationName); >>      $erdb->CreateIndex($relationName);
1223    
1224  Create the indexes for a relation. If a table is being loaded from a large source file (as  Create the indexes for a relation. If a table is being loaded from a large source file (as
1225  is the case in L</LoadTable>), it is 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 855  Line 1240 
1240      for my $indexName (keys %{$indexHash}) {      for my $indexName (keys %{$indexHash}) {
1241          my $indexData = $indexHash->{$indexName};          my $indexData = $indexHash->{$indexName};
1242          # Get the index's field list.          # Get the index's field list.
1243          my @fieldList = _FixNames(@{$indexData->{IndexFields}});          my @rawFields = @{$indexData->{IndexFields}};
1244            # Get a hash of the relation's field types.
1245            my %types = map { $_->{name} => $_->{type} } @{$relationData->{Fields}};
1246            # We need to check for text fields so we can append a length limitation for them. To do
1247            # that, we need the relation's field list.
1248            my $relFields = $relationData->{Fields};
1249            for (my $i = 0; $i <= $#rawFields; $i++) {
1250                # Get the field type.
1251                my $field = $rawFields[$i];
1252                my $type = $types{$field};
1253                # Ask if it requires using prefix notation for the index.
1254                my $mod = $TypeTable{$type}->{indexMod};
1255                Trace("Field $field ($i) in $relationName has type $type and indexMod $mod.") if T(3);
1256                if ($mod) {
1257                    # Append the prefix length to the field name,
1258                    $rawFields[$i] .= "($mod)";
1259                }
1260            }
1261            my @fieldList = _FixNames(@rawFields);
1262          my $flds = join(', ', @fieldList);          my $flds = join(', ', @fieldList);
1263          # Get the index's uniqueness flag.          # Get the index's uniqueness flag.
1264          my $unique = (exists $indexData->{Unique} ? 'unique' : undef);          my $unique = (exists $indexData->{Unique} ? 'unique' : undef);
# Line 870  Line 1273 
1273      }      }
1274  }  }
1275    
1276    =head3 GetSecondaryFields
1277    
1278        my %fieldTuples = $erdb->GetSecondaryFields($entityName);
1279    
1280    This method will return a list of the name and type of each of the secondary
1281    fields for a specified entity. Secondary fields are stored in two-column tables
1282    in addition to the primary entity table. This enables the field to have no value
1283    or to have multiple values.
1284    
1285    =over 4
1286    
1287    =item entityName
1288    
1289    Name of the entity whose secondary fields are desired.
1290    
1291    =item RETURN
1292    
1293    Returns a hash mapping the field names to their field types.
1294    
1295    =back
1296    
1297    =cut
1298    
1299    sub GetSecondaryFields {
1300        # Get the parameters.
1301        my ($self, $entityName) = @_;
1302        # Declare the return variable.
1303        my %retVal = ();
1304        # Look for the entity.
1305        my $table = $self->GetFieldTable($entityName);
1306        # Loop through the fields, pulling out the secondaries.
1307        for my $field (sort keys %{$table}) {
1308            if ($table->{$field}->{relation} ne $entityName) {
1309                # Here we have a secondary field.
1310                $retVal{$field} = $table->{$field}->{type};
1311            }
1312        }
1313        # Return the result.
1314        return %retVal;
1315    }
1316    
1317    =head3 GetFieldRelationName
1318    
1319        my $name = $erdb->GetFieldRelationName($objectName, $fieldName);
1320    
1321    Return the name of the relation containing a specified field.
1322    
1323    =over 4
1324    
1325    =item objectName
1326    
1327    Name of the entity or relationship containing the field.
1328    
1329    =item fieldName
1330    
1331    Name of the relevant field in that entity or relationship.
1332    
1333    =item RETURN
1334    
1335    Returns the name of the database relation containing the field, or C<undef> if
1336    the field does not exist.
1337    
1338    =back
1339    
1340    =cut
1341    
1342    sub GetFieldRelationName {
1343        # Get the parameters.
1344        my ($self, $objectName, $fieldName) = @_;
1345        # Declare the return variable.
1346        my $retVal;
1347        # Get the object field table.
1348        my $table = $self->GetFieldTable($objectName);
1349        # Only proceed if the field exists.
1350        if (exists $table->{$fieldName}) {
1351            # Determine the name of the relation that contains this field.
1352            $retVal = $table->{$fieldName}->{relation};
1353        }
1354        # Return the result.
1355        return $retVal;
1356    }
1357    
1358    =head3 DeleteValue
1359    
1360        my $numDeleted = $erdb->DeleteValue($entityName, $id, $fieldName, $fieldValue);
1361    
1362    Delete secondary field values from the database. This method can be used to delete all
1363    values of a specified field for a particular entity instance, or only a single value.
1364    
1365    Secondary fields are stored in two-column relations separate from an entity's primary
1366    table, and as a result a secondary field can legitimately have no value or multiple
1367    values. Therefore, it makes sense to talk about deleting secondary fields where it
1368    would not make sense for primary fields.
1369    
1370    =over 4
1371    
1372    =item entityName
1373    
1374    Name of the entity from which the fields are to be deleted.
1375    
1376    =item id
1377    
1378    ID of the entity instance to be processed. If the instance is not found, this
1379    method will have no effect. If C<undef> is specified, all values for all of
1380    the entity instances will be deleted.
1381    
1382    =item fieldName
1383    
1384    Name of the field whose values are to be deleted.
1385    
1386    =item fieldValue (optional)
1387    
1388    Value to be deleted. If not specified, then all values of the specified field
1389    will be deleted for the entity instance. If specified, then only the values which
1390    match this parameter will be deleted.
1391    
1392    =item RETURN
1393    
1394    Returns the number of rows deleted.
1395    
1396    =back
1397    
1398    =cut
1399    
1400    sub DeleteValue {
1401        # Get the parameters.
1402        my ($self, $entityName, $id, $fieldName, $fieldValue) = @_;
1403        # Declare the return value.
1404        my $retVal = 0;
1405        # We need to set up an SQL command to do the deletion. First, we
1406        # find the name of the field's relation.
1407        my $table = $self->GetFieldTable($entityName);
1408        my $field = $table->{$fieldName};
1409        my $relation = $field->{relation};
1410        # Make sure this is a secondary field.
1411        if ($relation eq $entityName) {
1412            Confess("Cannot delete values of $fieldName for $entityName.");
1413        } else {
1414            # Set up the SQL command to delete all values.
1415            my $sql = "DELETE FROM $relation";
1416            # Build the filter.
1417            my @filters = ();
1418            my @parms = ();
1419            # Check for a filter by ID.
1420            if (defined $id) {
1421                push @filters, "id = ?";
1422                push @parms, $id;
1423            }
1424            # Check for a filter by value.
1425            if (defined $fieldValue) {
1426                push @filters, "$fieldName = ?";
1427                push @parms, $fieldValue;
1428            }
1429            # Append the filters to the command.
1430            if (@filters) {
1431                $sql .= " WHERE " . join(" AND ", @filters);
1432            }
1433            # Execute the command.
1434            my $dbh = $self->{_dbh};
1435            $retVal = $dbh->SQL($sql, 0, @parms);
1436        }
1437        # Return the result.
1438        return $retVal;
1439    }
1440    
1441  =head3 LoadTables  =head3 LoadTables
1442    
1443  C<< my $stats = $erdb->LoadTables($directoryName, $rebuild); >>      my $stats = $erdb->LoadTables($directoryName, $rebuild);
1444    
1445  This method will load the database tables from a directory. The tables must already have been created  This method will load the database tables from a directory. The tables must already have been created
1446  in the database. (This can be done by calling L</CreateTables>.) The caller passes in a directory name;  in the database. (This can be done by calling L</CreateTables>.) The caller passes in a directory name;
# Line 932  Line 1500 
1500    
1501  =head3 GetTableNames  =head3 GetTableNames
1502    
1503  C<< my @names = $erdb->GetTableNames; >>      my @names = $erdb->GetTableNames;
1504    
1505  Return a list of the relations required to implement this database.  Return a list of the relations required to implement this database.
1506    
# Line 949  Line 1517 
1517    
1518  =head3 GetEntityTypes  =head3 GetEntityTypes
1519    
1520  C<< my @names = $erdb->GetEntityTypes; >>      my @names = $erdb->GetEntityTypes;
1521    
1522  Return a list of the entity type names.  Return a list of the entity type names.
1523    
# Line 964  Line 1532 
1532      return sort keys %{$entityList};      return sort keys %{$entityList};
1533  }  }
1534    
1535    =head3 GetDataTypes
1536    
1537        my %types = ERDB::GetDataTypes();
1538    
1539    Return a table of ERDB data types. The table returned is a hash of hashes.
1540    The keys of the big hash are the datatypes. Each smaller hash has several
1541    values used to manage the data. The most interesting is the SQL type (key
1542    C<sqlType>) and the descriptive node (key C<notes>).
1543    
1544    Note that changing the values in the smaller hashes will seriously break
1545    things, so this data should be treated as read-only.
1546    
1547    =cut
1548    
1549    sub GetDataTypes {
1550        return %TypeTable;
1551    }
1552    
1553    
1554  =head3 IsEntity  =head3 IsEntity
1555    
1556  C<< my $flag = $erdb->IsEntity($entityName); >>      my $flag = $erdb->IsEntity($entityName);
1557    
1558  Return TRUE if the parameter is an entity name, else FALSE.  Return TRUE if the parameter is an entity name, else FALSE.
1559    
# Line 993  Line 1580 
1580    
1581  =head3 Get  =head3 Get
1582    
1583  C<< my $query = $erdb->Get(\@objectNames, $filterClause, \@params); >>      my $query = $erdb->Get(\@objectNames, $filterClause, \@params);
1584    
1585  This method returns a query object for entities of a specified type using a specified filter.  This method returns a query object for entities of a specified type using a specified filter.
1586  The filter is a standard WHERE/ORDER BY clause with question marks as parameter markers and each  The filter is a standard WHERE/ORDER BY clause with question marks as parameter markers and each
# Line 1001  Line 1588 
1588  following call requests all B<Genome> objects for the genus specified in the variable  following call requests all B<Genome> objects for the genus specified in the variable
1589  $genus.  $genus.
1590    
1591  C<< $query = $erdb->Get(['Genome'], "Genome(genus) = ?", [$genus]); >>      $query = $erdb->Get(['Genome'], "Genome(genus) = ?", [$genus]);
1592    
1593  The WHERE clause contains a single question mark, so there is a single additional  The WHERE clause contains a single question mark, so there is a single additional
1594  parameter representing the parameter value. It would also be possible to code  parameter representing the parameter value. It would also be possible to code
1595    
1596  C<< $query = $erdb->Get(['Genome'], "Genome(genus) = \'$genus\'"); >>      $query = $erdb->Get(['Genome'], "Genome(genus) = \'$genus\'");
1597    
1598  however, this version of the call would generate a syntax error if there were any quote  however, this version of the call would generate a syntax error if there were any quote
1599  characters inside the variable C<$genus>.  characters inside the variable C<$genus>.
# Line 1018  Line 1605 
1605  It is possible to specify multiple entity and relationship names in order to retrieve more than  It is possible to specify multiple entity and relationship names in order to retrieve more than
1606  one object's data at the same time, which allows highly complex joined queries. For example,  one object's data at the same time, which allows highly complex joined queries. For example,
1607    
1608  C<< $query = $erdb->Get(['Genome', 'ComesFrom', 'Source'], "Genome(genus) = ?", [$genus]); >>      $query = $erdb->Get(['Genome', 'ComesFrom', 'Source'], "Genome(genus) = ?", [$genus]);
1609    
1610  If multiple names are specified, then the query processor will automatically determine a  If multiple names are specified, then the query processor will automatically determine a
1611  join path between the entities and relationships. The algorithm used is very simplistic.  join path between the entities and relationships. The algorithm used is very simplistic.
# Line 1054  Line 1641 
1641  with an ORDER BY clause. For example, the following filter string gets all genomes for a  with an ORDER BY clause. For example, the following filter string gets all genomes for a
1642  particular genus and sorts them by species name.  particular genus and sorts them by species name.
1643    
1644  C<< "Genome(genus) = ? ORDER BY Genome(species)" >>      "Genome(genus) = ? ORDER BY Genome(species)"
1645    
1646  Note that the case is important. Only an uppercase "ORDER BY" with a single space will  Note that the case is important. Only an uppercase "ORDER BY" with a single space will
1647  be processed. The idea is to make it less likely to find the verb by accident.  be processed. The idea is to make it less likely to find the verb by accident.
# Line 1067  Line 1654 
1654  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
1655  a positive number. So, for example  a positive number. So, for example
1656    
1657  C<< "Genome(genus) = ? ORDER BY Genome(species) LIMIT 10" >>      "Genome(genus) = ? ORDER BY Genome(species) LIMIT 10"
1658    
1659  will only return the first ten genomes for the specified genus. The ORDER BY clause is not  will only return the first ten genomes for the specified genus. The ORDER BY clause is not
1660  required. For example, to just get the first 10 genomes in the B<Genome> table, you could  required. For example, to just get the first 10 genomes in the B<Genome> table, you could
1661  use  use
1662    
1663  C<< "LIMIT 10" >>      "LIMIT 10"
1664    
1665  =item params  =item params
1666    
# Line 1094  Line 1681 
1681      my ($suffix, $mappedNameListRef, $mappedNameHashRef) =      my ($suffix, $mappedNameListRef, $mappedNameHashRef) =
1682          $self->_SetupSQL($objectNames, $filterClause);          $self->_SetupSQL($objectNames, $filterClause);
1683      # Create the query.      # Create the query.
1684      my $command = "SELECT DISTINCT " . join(".*, ", @{$mappedNameListRef}) .      my $command = "SELECT " . join(".*, ", @{$mappedNameListRef}) .
1685          ".* $suffix";          ".* $suffix";
1686      my $sth = $self->_GetStatementHandle($command, $params);      my $sth = $self->_GetStatementHandle($command, $params);
1687      # 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 1108  Line 1695 
1695      return $retVal;      return $retVal;
1696  }  }
1697    
1698    
1699    
1700  =head3 Search  =head3 Search
1701    
1702  C<< my $query = $erdb->Search($searchExpression, $idx, \@objectNames, $filterClause, \@params); >>      my $query = $erdb->Search($searchExpression, $idx, \@objectNames, $filterClause, \@params);
1703    
1704  Perform a full text search with filtering. The search will be against a specified object  Perform a full text search with filtering. The search will be against a specified object
1705  in the object name list. That object will get an extra field containing the search  in the object name list. That object will get an extra field containing the search
# Line 1121  Line 1710 
1710    
1711  =item searchExpression  =item searchExpression
1712    
1713  Boolean search expression for the text fields of the target object.  Boolean search expression for the text fields of the target object. The default mode for
1714    a Boolean search expression is OR, but we want the default to be AND, so we will
1715    add a C<+> operator to each word with no other operator before it.
1716    
1717  =item idx  =item idx
1718    
# Line 1158  Line 1749 
1749      my ($self, $searchExpression, $idx, $objectNames, $filterClause, $params) = @_;      my ($self, $searchExpression, $idx, $objectNames, $filterClause, $params) = @_;
1750      # Declare the return variable.      # Declare the return variable.
1751      my $retVal;      my $retVal;
1752      # Create a safety copy of the parameter list.      # Create a safety copy of the parameter list. Note we have to be careful to insure
1753      my @myParams = @{$params};      # a parameter list exists before we copy it.
1754        my @myParams = ();
1755        if (defined $params) {
1756            @myParams = @{$params};
1757        }
1758      # Get the first object's structure so we have access to the searchable fields.      # Get the first object's structure so we have access to the searchable fields.
1759      my $object1Name = $objectNames->[$idx];      my $object1Name = $objectNames->[$idx];
1760      my $object1Structure = $self->_GetStructure($object1Name);      my $object1Structure = $self->_GetStructure($object1Name);
# Line 1171  Line 1766 
1766          my @fields = @{$object1Structure->{searchFields}};          my @fields = @{$object1Structure->{searchFields}};
1767          # Clean the search expression.          # Clean the search expression.
1768          my $actualKeywords = $self->CleanKeywords($searchExpression);          my $actualKeywords = $self->CleanKeywords($searchExpression);
1769            # Prefix a "+" to each uncontrolled word. This converts the default
1770            # search mode from OR to AND.
1771            $actualKeywords =~ s/(^|\s)(\w|")/$1\+$2/g;
1772            Trace("Actual keywords for search are\n$actualKeywords") if T(3);
1773          # We need two match expressions, one for the filter clause and one in the          # We need two match expressions, one for the filter clause and one in the
1774          # query itself. Both will use a parameter mark, so we need to push the          # query itself. Both will use a parameter mark, so we need to push the
1775          # search expression onto the front of the parameter list twice.          # search expression onto the front of the parameter list twice.
# Line 1183  Line 1782 
1782              $self->_SetupSQL($objectNames, $filterClause, $matchClause);              $self->_SetupSQL($objectNames, $filterClause, $matchClause);
1783          # Create the query. Note that the match clause is inserted at the front of          # Create the query. Note that the match clause is inserted at the front of
1784          # the select fields.          # the select fields.
1785          my $command = "SELECT DISTINCT $matchClause, " . join(".*, ", @{$mappedNameListRef}) .          my $command = "SELECT $matchClause, " . join(".*, ", @{$mappedNameListRef}) .
1786              ".* $suffix";              ".* $suffix";
1787          my $sth = $self->_GetStatementHandle($command, \@myParams);          my $sth = $self->_GetStatementHandle($command, \@myParams);
1788          # 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 1197  Line 1796 
1796    
1797  =head3 GetFlat  =head3 GetFlat
1798    
1799  C<< my @list = $erdb->GetFlat(\@objectNames, $filterClause, \@parameterList, $field); >>      my @list = $erdb->GetFlat(\@objectNames, $filterClause, \@parameterList, $field);
1800    
1801  This is a variation of L</GetAll> that asks for only a single field per record and  This is a variation of L</GetAll> that asks for only a single field per record and
1802  returns a single flattened list.  returns a single flattened list.
# Line 1248  Line 1847 
1847      return @retVal;      return @retVal;
1848  }  }
1849    
1850    =head3 SpecialFields
1851    
1852        my %specials = $erdb->SpecialFields($entityName);
1853    
1854    Return a hash mapping special fields in the specified entity to the value of their
1855    C<special> attribute. This enables the subclass to get access to the special field
1856    attributes without needed to plumb the internal ERDB data structures.
1857    
1858    =over 4
1859    
1860    =item entityName
1861    
1862    Name of the entity whose special fields are desired.
1863    
1864    =item RETURN
1865    
1866    Returns a hash. The keys of the hash are the special field names, and the values
1867    are the values from each special field's C<special> attribute.
1868    
1869    =back
1870    
1871    =cut
1872    
1873    sub SpecialFields {
1874        # Get the parameters.
1875        my ($self, $entityName) = @_;
1876        # Declare the return variable.
1877        my %retVal = ();
1878        # Find the entity's data structure.
1879        my $entityData = $self->{_metaData}->{Entities}->{$entityName};
1880        # Loop through its fields, adding each special field to the return hash.
1881        my $fieldHash = $entityData->{Fields};
1882        for my $fieldName (keys %{$fieldHash}) {
1883            my $fieldData = $fieldHash->{$fieldName};
1884            if (exists $fieldData->{special}) {
1885                $retVal{$fieldName} = $fieldData->{special};
1886            }
1887        }
1888        # Return the result.
1889        return %retVal;
1890    }
1891    
1892  =head3 Delete  =head3 Delete
1893    
1894  C<< my $stats = $erdb->Delete($entityName, $objectID); >>      my $stats = $erdb->Delete($entityName, $objectID, %options);
1895    
1896  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
1897  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.
1898  always dependent on itself. An object is dependent if it is a 1-to-many or many-to-many  
1899  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
1900    relationship connected to a dependent entity or if it is the "to" entity connected to a 1-to-many
1901  dependent relationship.  dependent relationship.
1902    
1903  =over 4  =over 4
# Line 1269  Line 1911 
1911  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<%>),
1912  then it is presumed to by a LIKE pattern.  then it is presumed to by a LIKE pattern.
1913    
1914  =item testFlag  =item options
1915    
1916  If TRUE, the delete statements will be traced without being executed.  A hash detailing the options for this delete operation.
1917    
1918  =item RETURN  =item RETURN
1919    
# Line 1280  Line 1922 
1922    
1923  =back  =back
1924    
1925    The permissible options for this method are as follows.
1926    
1927    =over 4
1928    
1929    =item testMode
1930    
1931    If TRUE, then the delete statements will be traced, but no changes will be made to the database.
1932    
1933    =item keepRoot
1934    
1935    If TRUE, then the entity instances will not be deleted, only the dependent records.
1936    
1937    =back
1938    
1939  =cut  =cut
1940  #: Return Type $%;  #: Return Type $%;
1941  sub Delete {  sub Delete {
1942      # Get the parameters.      # Get the parameters.
1943      my ($self, $entityName, $objectID, $testFlag) = @_;      my ($self, $entityName, $objectID, %options) = @_;
1944      # Declare the return variable.      # Declare the return variable.
1945      my $retVal = Stats->new();      my $retVal = Stats->new();
1946      # Get the DBKernel object.      # Get the DBKernel object.
# Line 1301  Line 1957 
1957      # FROM-relationships and entities.      # FROM-relationships and entities.
1958      my @fromPathList = ();      my @fromPathList = ();
1959      my @toPathList = ();      my @toPathList = ();
1960      # 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
1961      # 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
1962      # 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
1963      # TODO list is always an entity.      # to-do list is always an entity.
1964      my @todoList = ([$entityName]);      my @todoList = ([$entityName]);
1965      while (@todoList) {      while (@todoList) {
1966          # Get the current path.          # Get the current path.
# Line 1312  Line 1968 
1968          # Copy it into a list.          # Copy it into a list.
1969          my @stackedPath = @{$current};          my @stackedPath = @{$current};
1970          # 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.
1971          my $entityName = pop @stackedPath;          my $myEntityName = pop @stackedPath;
1972          # Add it to the alreadyFound list.          # Add it to the alreadyFound list.
1973          $alreadyFound{$entityName} = 1;          $alreadyFound{$myEntityName} = 1;
1974            # Figure out if we need to delete this entity.
1975            if ($myEntityName ne $entityName || ! $options{keepRoot}) {
1976          # Get the entity data.          # Get the entity data.
1977          my $entityData = $self->_GetStructure($entityName);              my $entityData = $self->_GetStructure($myEntityName);
1978          # 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.  
1979          my $relations = $entityData->{Relations};          my $relations = $entityData->{Relations};
1980          for my $relation (keys %{$relations}) {          for my $relation (keys %{$relations}) {
1981              my @augmentedList = (@stackedPath, $relation);              my @augmentedList = (@stackedPath, $relation);
1982              push @fromPathList, \@augmentedList;              push @fromPathList, \@augmentedList;
1983          }          }
1984            }
1985          # Now we need to look for relationships connected to this entity.          # Now we need to look for relationships connected to this entity.
1986          my $relationshipList = $self->{_metaData}->{Relationships};          my $relationshipList = $self->{_metaData}->{Relationships};
1987          for my $relationshipName (keys %{$relationshipList}) {          for my $relationshipName (keys %{$relationshipList}) {
1988              my $relationship = $relationshipList->{$relationshipName};              my $relationship = $relationshipList->{$relationshipName};
1989              # Check the FROM field. We're only interested if it's us.              # Check the FROM field. We're only interested if it's us.
1990              if ($relationship->{from} eq $entityName) {              if ($relationship->{from} eq $myEntityName) {
1991                  # Add the path to this relationship.                  # Add the path to this relationship.
1992                  my @augmentedList = (@stackedPath, $entityName, $relationshipName);                  my @augmentedList = (@stackedPath, $myEntityName, $relationshipName);
1993                  push @fromPathList, \@augmentedList;                  push @fromPathList, \@augmentedList;
1994                  # 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
1995                  # and the target hasn't been seen yet, we want to                  # and the target hasn't been seen yet, we want to
# Line 1350  Line 2008 
2008              }              }
2009              # Now check the TO field. In this case only the relationship needs              # Now check the TO field. In this case only the relationship needs
2010              # deletion.              # deletion.
2011              if ($relationship->{to} eq $entityName) {              if ($relationship->{to} eq $myEntityName) {
2012                  my @augmentedList = (@stackedPath, $entityName, $relationshipName);                  my @augmentedList = (@stackedPath, $myEntityName, $relationshipName);
2013                  push @toPathList, \@augmentedList;                  push @toPathList, \@augmentedList;
2014              }              }
2015          }          }
2016      }      }
2017      # Create the first qualifier for the WHERE clause. This selects the      # Create the first qualifier for the WHERE clause. This selects the
2018      # keys of the primary entity records to be deleted. When we're deleting      # keys of the primary entity records to be deleted. When we're deleting
2019      # 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
2020      # to the table containing the dependent records to delete.      # to the table containing the dependent records to delete.
2021      my $qualifier = ($objectID =~ /%/ ? "LIKE ?" : "= ?");      my $qualifier = ($objectID =~ /%/ ? "LIKE ?" : "= ?");
2022      # 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 1397  Line 2055 
2055                  }                  }
2056              }              }
2057              # Now we have our desired DELETE statement.              # Now we have our desired DELETE statement.
2058              if ($testFlag) {              if ($options{testMode}) {
2059                  # Here the user wants to trace without executing.                  # Here the user wants to trace without executing.
2060                  Trace($stmt) if T(0);                  Trace($stmt) if T(0);
2061              } else {              } else {
2062                  # 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
2063                  # if an error occurs, so we just go ahead and do it.                  # if an error occurs, so we just go ahead and do it.
2064                  Trace("Executing delete from $target using '$objectID'.") if T(3);                  Trace("Executing delete from $target using '$objectID'.") if T(3);
2065                  my $rv = $db->SQL($stmt, 0, $objectID);                  my $rv = $db->SQL($stmt, 0, $objectID);
# Line 1416  Line 2074 
2074      return $retVal;      return $retVal;
2075  }  }
2076    
2077  =head3 SortNeeded  =head3 Disconnect
2078    
2079  C<< my $parms = $erdb->SortNeeded($relationName); >>      $erdb->Disconnect($relationshipName, $originEntityName, $originEntityID);
2080    
2081  Return the pipe command for the sort that should be applied to the specified  Disconnect an entity instance from all the objects to which it is related. This
2082  relation when creating the load file.  will delete each relationship instance that connects to the specified entity.
2083    
2084    =over 4
2085    
2086    =item relationshipName
2087    
2088    Name of the relationship whose instances are to be deleted.
2089    
2090    =item originEntityName
2091    
2092    Name of the entity that is to be disconnected.
2093    
2094    =item originEntityID
2095    
2096    ID of the entity that is to be disconnected.
2097    
2098    =back
2099    
2100    =cut
2101    
2102    sub Disconnect {
2103        # Get the parameters.
2104        my ($self, $relationshipName, $originEntityName, $originEntityID) = @_;
2105        # Get the relationship descriptor.
2106        my $structure = $self->_GetStructure($relationshipName);
2107        # Insure we have a relationship.
2108        if (! exists $structure->{from}) {
2109            Confess("$relationshipName is not a relationship in the database.");
2110        } else {
2111            # Get the database handle.
2112            my $dbh = $self->{_dbh};
2113            # We'll set this value to 1 if we find our entity.
2114            my $found = 0;
2115            # Loop through the ends of the relationship.
2116            for my $dir ('from', 'to') {
2117                if ($structure->{$dir} eq $originEntityName) {
2118                    $found = 1;
2119                    # Here we want to delete all relationship instances on this side of the
2120                    # entity instance.
2121                    Trace("Disconnecting in $dir direction with ID \"$originEntityID\".");
2122                    # We do this delete in batches to keep it from dragging down the
2123                    # server.
2124                    my $limitClause = ($FIG_Config::delete_limit ? "LIMIT $FIG_Config::delete_limit" : "");
2125                    my $done = 0;
2126                    while (! $done) {
2127                        # Do the delete.
2128                        my $rows = $dbh->SQL("DELETE FROM $relationshipName WHERE ${dir}_link = ? $limitClause", 0, $originEntityID);
2129                        # See if we're done. We're done if no rows were found or the delete is unlimited.
2130                        $done = ($rows == 0 || ! $limitClause);
2131                    }
2132                }
2133            }
2134            # Insure we found the entity on at least one end.
2135            if (! $found) {
2136                Confess("Entity \"$originEntityName\" does not use $relationshipName.");
2137            }
2138        }
2139    }
2140    
2141    =head3 DeleteRow
2142    
2143        $erdb->DeleteRow($relationshipName, $fromLink, $toLink, \%values);
2144    
2145    Delete a row from a relationship. In most cases, only the from-link and to-link are
2146    needed; however, for relationships with intersection data values can be specified
2147    for the other fields using a hash.
2148    
2149    =over 4
2150    
2151    =item relationshipName
2152    
2153    Name of the relationship from which the row is to be deleted.
2154    
2155    =item fromLink
2156    
2157    ID of the entity instance in the From direction.
2158    
2159    =item toLink
2160    
2161    ID of the entity instance in the To direction.
2162    
2163    =item values
2164    
2165    Reference to a hash of other values to be used for filtering the delete.
2166    
2167    =back
2168    
2169    =cut
2170    
2171    sub DeleteRow {
2172        # Get the parameters.
2173        my ($self, $relationshipName, $fromLink, $toLink, $values) = @_;
2174        # Create a hash of all the filter information.
2175        my %filter = ('from-link' => $fromLink, 'to-link' => $toLink);
2176        if (defined $values) {
2177            for my $key (keys %{$values}) {
2178                $filter{$key} = $values->{$key};
2179            }
2180        }
2181        # Build an SQL statement out of the hash.
2182        my @filters = ();
2183        my @parms = ();
2184        for my $key (keys %filter) {
2185            push @filters, _FixName($key) . " = ?";
2186            push @parms, $filter{$key};
2187        }
2188        Trace("Parms for delete row are " . join(", ", map { "\"$_\"" } @parms) . ".") if T(SQL => 4);
2189        my $command = "DELETE FROM $relationshipName WHERE " .
2190                      join(" AND ", @filters);
2191        # Execute it.
2192        my $dbh = $self->{_dbh};
2193        $dbh->SQL($command, undef, @parms);
2194    }
2195    
2196    =head3 DeleteLike
2197    
2198        my $deleteCount = $erdb->DeleteLike($relName, $filter, \@parms);
2199    
2200    Delete all the relationship rows that satisfy a particular filter condition. Unlike a normal
2201    filter, only fields from the relationship itself can be used.
2202    
2203    =over 4
2204    
2205    =item relName
2206    
2207    Name of the relationship whose records are to be deleted.
2208    
2209    =item filter
2210    
2211    A filter clause (L</Get>-style) for the delete query.
2212    
2213    =item parms
2214    
2215    Reference to a list of parameters for the filter clause.
2216    
2217    =item RETURN
2218    
2219    Returns a count of the number of rows deleted.
2220    
2221    =back
2222    
2223    =cut
2224    
2225    sub DeleteLike {
2226        # Get the parameters.
2227        my ($self, $objectName, $filter, $parms) = @_;
2228        # Declare the return variable.
2229        my $retVal;
2230        # Insure the parms argument is an array reference if the caller left it off.
2231        if (! defined($parms)) {
2232            $parms = [];
2233        }
2234        # Insure we have a relationship. The main reason for this is if we delete an entity
2235        # instance we have to yank out a bunch of other stuff with it.
2236        if ($self->IsEntity($objectName)) {
2237            Confess("Cannot use DeleteLike on $objectName, because it is not a relationship.");
2238        } else {
2239            # Create the SQL command suffix to get the desierd records.
2240            my ($suffix) = $self->_SetupSQL([$objectName], $filter);
2241            # Convert it to a DELETE command.
2242            my $command = "DELETE $suffix";
2243            # Execute the command.
2244            my $dbh = $self->{_dbh};
2245            my $result = $dbh->SQL($command, 0, @{$parms});
2246            # Check the results. Note we convert the "0D0" result to a real zero.
2247            # A failure causes an abnormal termination, so the caller isn't going to
2248            # worry about it.
2249            if (! defined $result) {
2250                Confess("Error deleting from $objectName: " . $dbh->errstr());
2251            } elsif ($result == 0) {
2252                $retVal = 0;
2253            } else {
2254                $retVal = $result;
2255            }
2256        }
2257        # Return the result count.
2258        return $retVal;
2259    }
2260    
2261    =head3 SortNeeded
2262    
2263        my $parms = $erdb->SortNeeded($relationName);
2264    
2265    Return the pipe command for the sort that should be applied to the specified
2266    relation when creating the load file.
2267    
2268  For example, if the load file should be sorted ascending by the first  For example, if the load file should be sorted ascending by the first
2269  field, this method would return  field, this method would return
# Line 1466  Line 2308 
2308      } elsif (exists $relationshipTable->{$relationName}) {      } elsif (exists $relationshipTable->{$relationName}) {
2309          # Here we have a relationship. We sort using the FROM index.          # Here we have a relationship. We sort using the FROM index.
2310          my $relationshipData = $relationshipTable->{$relationName};          my $relationshipData = $relationshipTable->{$relationName};
2311          my $index = $relationData->{Indexes}->{"idx${relationName}From"};          my $index = $relationData->{Indexes}->{idxFrom};
2312          push @keyNames, @{$index->{IndexFields}};          push @keyNames, @{$index->{IndexFields}};
2313      } else {      } else {
2314          # Here we have a secondary entity relation, so we have a sort on the ID field.          # Here we have a secondary entity relation, so we have a sort on the ID field.
# Line 1516  Line 2358 
2358    
2359  =head3 GetList  =head3 GetList
2360    
2361  C<< my @dbObjects = $erdb->GetList(\@objectNames, $filterClause, \@params); >>      my @dbObjects = $erdb->GetList(\@objectNames, $filterClause, \@params);
2362    
2363  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
2364  specified filter clause.  specified filter clause.
# Line 1544  Line 2386 
2386  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
2387  particular genus and sorts them by species name.  particular genus and sorts them by species name.
2388    
2389  C<< "Genome(genus) = ? ORDER BY Genome(species)" >>      "Genome(genus) = ? ORDER BY Genome(species)"
2390    
2391  The rules for field references in a sort order are the same as those for field references in the  The rules for field references in a sort order are the same as those for field references in the
2392  filter clause in general; however, odd things may happen if a sort field is from a secondary  filter clause in general; however, odd things may happen if a sort field is from a secondary
# Line 1556  Line 2398 
2398    
2399  =item RETURN  =item RETURN
2400    
2401  Returns a list of B<DBObject>s that satisfy the query conditions.  Returns a list of B<ERDBObject>s that satisfy the query conditions.
2402    
2403  =back  =back
2404    
# Line 1579  Line 2421 
2421    
2422  =head3 GetCount  =head3 GetCount
2423    
2424  C<< my $count = $erdb->GetCount(\@objectNames, $filter, \@params); >>      my $count = $erdb->GetCount(\@objectNames, $filter, \@params);
2425    
2426  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
2427  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 1672  Line 2514 
2514    
2515  =head3 ComputeObjectSentence  =head3 ComputeObjectSentence
2516    
2517  C<< my $sentence = $erdb->ComputeObjectSentence($objectName); >>      my $sentence = $erdb->ComputeObjectSentence($objectName);
2518    
2519  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.
2520    
# Line 1707  Line 2549 
2549    
2550  =head3 DumpRelations  =head3 DumpRelations
2551    
2552  C<< $erdb->DumpRelations($outputDirectory); >>      $erdb->DumpRelations($outputDirectory);
2553    
2554  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.
2555  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 1749  Line 2591 
2591    
2592  =head3 InsertValue  =head3 InsertValue
2593    
2594  C<< $erdb->InsertValue($entityID, $fieldName, $value); >>      $erdb->InsertValue($entityID, $fieldName, $value);
2595    
2596  This method will insert a new value into the database. The value must be one  This method will insert a new value into the database. The value must be one
2597  associated with a secondary relation, since primary values cannot be inserted:  associated with a secondary relation, since primary values cannot be inserted:
# Line 1812  Line 2654 
2654    
2655  =head3 InsertObject  =head3 InsertObject
2656    
2657  C<< my $ok = $erdb->InsertObject($objectType, \%fieldHash); >>      $erdb->InsertObject($objectType, \%fieldHash);
2658    
2659  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
2660  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 1821  Line 2663 
2663  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
2664  C<ZP_00210270.1> and C<gi|46206278>.  C<ZP_00210270.1> and C<gi|46206278>.
2665    
2666  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']});
2667    
2668  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
2669  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>.
2670    
2671  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'});
2672    
2673  =over 4  =over 4
2674    
# Line 1838  Line 2680 
2680    
2681  Hash of field names to values.  Hash of field names to values.
2682    
 =item RETURN  
   
 Returns 1 if successful, 0 if an error occurred.  
   
2683  =back  =back
2684    
2685  =cut  =cut
# Line 1940  Line 2778 
2778                  $retVal = $sth->execute(@parameterList);                  $retVal = $sth->execute(@parameterList);
2779                  if (!$retVal) {                  if (!$retVal) {
2780                      my $errorString = $sth->errstr();                      my $errorString = $sth->errstr();
2781                      Trace("Insert error: $errorString.") if T(0);                      Confess("Error inserting into $relationName: $errorString");
2782                    } else {
2783                        Trace("Insert successful using $parameterList[0].") if T(3);
2784                  }                  }
2785              }              }
2786          }          }
2787      }      }
2788      # Return the success indicator.      # Return a 1 for backward compatability.
2789      return $retVal;      return 1;
2790    }
2791    
2792    =head3 UpdateEntity
2793    
2794        $erdb->UpdateEntity($entityName, $id, \%fields);
2795    
2796    Update the values of an entity. This is an unprotected update, so it should only be
2797    done if the database resides on a database server.
2798    
2799    =over 4
2800    
2801    =item entityName
2802    
2803    Name of the entity to update. (This is the entity type.)
2804    
2805    =item id
2806    
2807    ID of the entity to update. If no entity exists with this ID, an error will be thrown.
2808    
2809    =item fields
2810    
2811    Reference to a hash mapping field names to their new values. All of the fields named
2812    must be in the entity's primary relation, and they cannot any of them be the ID field.
2813    
2814    =back
2815    
2816    =cut
2817    
2818    sub UpdateEntity {
2819        # Get the parameters.
2820        my ($self, $entityName, $id, $fields) = @_;
2821        # Get a list of the field names being updated.
2822        my @fieldList = keys %{$fields};
2823        # Verify that the fields exist.
2824        my $checker = $self->GetFieldTable($entityName);
2825        for my $field (@fieldList) {
2826            if ($field eq 'id') {
2827                Confess("Cannot update the ID field for entity $entityName.");
2828            } elsif ($checker->{$field}->{relation} ne $entityName) {
2829                Confess("Cannot find $field in primary relation of $entityName.");
2830            }
2831        }
2832        # Build the SQL statement.
2833        my @sets = ();
2834        my @valueList = ();
2835        for my $field (@fieldList) {
2836            push @sets, _FixName($field) . " = ?";
2837            push @valueList, $fields->{$field};
2838        }
2839        my $command = "UPDATE $entityName SET " . join(", ", @sets) . " WHERE id = ?";
2840        # Add the ID to the list of binding values.
2841        push @valueList, $id;
2842        # Call SQL to do the work.
2843        my $rows = $self->{_dbh}->SQL($command, 0, @valueList);
2844        # Check for errors.
2845        if ($rows == 0) {
2846            Confess("Entity $id of type $entityName not found.");
2847        }
2848  }  }
2849    
2850  =head3 LoadTable  =head3 LoadTable
2851    
2852  C<< my %results = $erdb->LoadTable($fileName, $relationName, $truncateFlag); >>      my $results = $erdb->LoadTable($fileName, $relationName, %options);
2853    
2854  Load data from a tab-delimited file into a specified table, optionally re-creating the table  Load data from a tab-delimited file into a specified table, optionally re-creating the table
2855  first.  first.
# Line 1966  Line 2864 
2864    
2865  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.
2866    
2867  =item truncateFlag  =item options
2868    
2869  TRUE if the table should be dropped and re-created, else FALSE  A hash of load options.
2870    
2871  =item RETURN  =item RETURN
2872    
# Line 1976  Line 2874 
2874    
2875  =back  =back
2876    
2877    The permissible options are as follows.
2878    
2879    =over 4
2880    
2881    =item truncate
2882    
2883    If TRUE, then the table will be erased before loading.
2884    
2885    =item mode
2886    
2887    Mode in which the load should operate, either C<low_priority> or C<concurrent>.
2888    This option is only applicable to a MySQL database.
2889    
2890    =item partial
2891    
2892    If TRUE, then it is assumed that this is a partial load, and the table will not
2893    be analyzed and compacted at the end.
2894    
2895    =back
2896    
2897  =cut  =cut
2898  sub LoadTable {  sub LoadTable {
2899      # Get the parameters.      # Get the parameters.
2900      my ($self, $fileName, $relationName, $truncateFlag) = @_;      my ($self, $fileName, $relationName, %options) = @_;
2901      # Create the statistical return object.      # Create the statistical return object.
2902      my $retVal = _GetLoadStats();      my $retVal = _GetLoadStats();
2903      # Trace the fact of the load.      # Trace the fact of the load.
# Line 1991  Line 2909 
2909      # Get the relation data.      # Get the relation data.
2910      my $relation = $self->_FindRelation($relationName);      my $relation = $self->_FindRelation($relationName);
2911      # Check the truncation flag.      # Check the truncation flag.
2912      if ($truncateFlag) {      if ($options{truncate}) {
2913          Trace("Creating table $relationName") if T(2);          Trace("Creating table $relationName") if T(2);
2914          # 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,
2915          # 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
2916          # leave extra room. We postulate a minimum row count of 1000 to          # leave extra room. We postulate a minimum row count of 1000 to
2917          # prevent problems with incoming empty load files.          # prevent problems with incoming empty load files.
2918          my $rowSize = $self->EstimateRowSize($relationName);          my $rowSize = $self->EstimateRowSize($relationName);
2919          my $estimate = FIG::max($fileSize * 1.5 / $rowSize, 1000);          my $estimate = $fileSize * 8 / $rowSize;
2920            if ($estimate < 1000) {
2921                $estimate = 1000;
2922            }
2923          # Re-create the table without its index.          # Re-create the table without its index.
2924          $self->CreateTable($relationName, 0, $estimate);          $self->CreateTable($relationName, 0, $estimate);
2925          # If this is a pre-index DBMS, create the index here.          # If this is a pre-index DBMS, create the index here.
# Line 2014  Line 2935 
2935      # Load the table.      # Load the table.
2936      my $rv;      my $rv;
2937      eval {      eval {
2938          $rv = $dbh->load_table(file => $fileName, tbl => $relationName);          $rv = $dbh->load_table(file => $fileName, tbl => $relationName, style => $options{mode});
2939      };      };
2940      if (!defined $rv) {      if (!defined $rv) {
2941          $retVal->AddMessage($@) if ($@);          $retVal->AddMessage($@) if ($@);
2942          $retVal->AddMessage("Table load failed for $relationName using $fileName.");          $retVal->AddMessage("Table load failed for $relationName using $fileName: " . $dbh->error_message);
2943          Trace("Table load failed for $relationName.") if T(1);          Trace("Table load failed for $relationName.") if T(1);
2944      } else {      } else {
2945          # Here we successfully loaded the table.          # Here we successfully loaded the table.
2946          $retVal->Add("tables");          $retVal->Add("tables");
2947          my $size = -s $fileName;          my $size = -s $fileName;
2948          Trace("$size bytes loaded into $relationName.") if T(2);          Trace("$size bytes loaded into $relationName.") if T(2);
2949            $retVal->Add("bytes", $size);
2950          # If we're rebuilding, we need to create the table indexes.          # If we're rebuilding, we need to create the table indexes.
2951          if ($truncateFlag) {          if ($options{truncate}) {
2952              # Indexes are created here for PostGres. For PostGres, indexes are              # Indexes are created here for PostGres. For PostGres, indexes are
2953              # best built at the end. For MySQL, the reverse is true.              # best built at the end. For MySQL, the reverse is true.
2954              if (! $dbh->{_preIndex}) {              if (! $dbh->{_preIndex}) {
# Line 2040  Line 2962 
2962              # The full-text index (if any) is always built last, even for MySQL.              # The full-text index (if any) is always built last, even for MySQL.
2963              # First we need to see if this table has a full-text index. Only              # First we need to see if this table has a full-text index. Only
2964              # primary relations are allowed that privilege.              # primary relations are allowed that privilege.
2965                Trace("Checking for full-text index on $relationName.") if T(2);
2966              if ($self->_IsPrimary($relationName)) {              if ($self->_IsPrimary($relationName)) {
2967                  # Get the relation's entity/relationship structure.                  $self->CreateSearchIndex($relationName);
                 my $structure = $self->_GetStructure($relationName);  
                 # Check for a searchable fields list.  
                 if (exists $structure->{searchFields}) {  
                     # Here we know that we need to create a full-text search index.  
                     # Get an SQL-formatted field name list.  
                     my $fields = join(", ", $self->_FixNames(@{$structure->{searchFields}}));  
                     # Create the index.  
                     $dbh->create_index(tbl => $relationName, idx => "search_idx_$relationName",  
                                        flds => $fields, kind => 'fulltext');  
                 }  
2968              }              }
2969          }          }
2970      }      }
2971      # Analyze the table to improve performance.      # Analyze the table to improve performance.
2972        if (! $options{partial}) {
2973      Trace("Analyzing and compacting $relationName.") if T(3);      Trace("Analyzing and compacting $relationName.") if T(3);
2974      $dbh->vacuum_it($relationName);      $dbh->vacuum_it($relationName);
2975        }
2976      Trace("$relationName load completed.") if T(3);      Trace("$relationName load completed.") if T(3);
2977      # Return the statistics.      # Return the statistics.
2978      return $retVal;      return $retVal;
2979  }  }
2980    
2981  =head3 GenerateEntity  =head3 CreateSearchIndex
2982    
2983  C<< my $fieldHash = $erdb->GenerateEntity($id, $type, \%values); >>      $erdb->CreateSearchIndex($objectName);
2984    
2985  Generate the data for a new entity instance. This method creates a field hash suitable for  Check for a full-text search index on the specified entity or relationship object, and
2986  passing as a parameter to L</InsertObject>. The ID is specified by the callr, but the rest  if one is required, rebuild it.
 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.  
2987    
2988  =over 4  =over 4
2989    
2990  =item id  =item objectName
2991    
2992  ID to assign to the new entity.  Name of the entity or relationship to be indexed.
2993    
2994  =item type  =back
2995    
2996  Type name for the new entity.  =cut
2997    
2998  =item values  sub CreateSearchIndex {
2999        # Get the parameters.
3000        my ($self, $objectName) = @_;
3001        # Get the relation's entity/relationship structure.
3002        my $structure = $self->_GetStructure($objectName);
3003        # Get the database handle.
3004        my $dbh = $self->{_dbh};
3005        Trace("Checking for search fields in $objectName.") if T(3);
3006        # Check for a searchable fields list.
3007        if (exists $structure->{searchFields}) {
3008            # Here we know that we need to create a full-text search index.
3009            # Get an SQL-formatted field name list.
3010            my $fields = join(", ", _FixNames(@{$structure->{searchFields}}));
3011            # Create the index. If it already exists, it will be dropped.
3012            $dbh->create_index(tbl => $objectName, idx => "search_idx",
3013                               flds => $fields, kind => 'fulltext');
3014            Trace("Index created for $fields in $objectName.") if T(2);
3015        }
3016    }
3017    
3018    =head3 DropRelation
3019    
3020        $erdb->DropRelation($relationName);
3021    
3022    Physically drop a relation from the database.
3023    
3024    =over 4
3025    
3026    =item relationName
3027    
3028  Hash containing additional values that might be needed by the data generation methods (optional).  Name of the relation to drop. If it does not exist, this method will have
3029    no effect.
3030    
3031  =back  =back
3032    
3033  =cut  =cut
3034    
3035  sub GenerateEntity {  sub DropRelation {
3036      # Get the parameters.      # Get the parameters.
3037      my ($self, $id, $type, $values) = @_;      my ($self, $relationName) = @_;
3038      # Create the return hash.      # Get the database handle.
3039      my $this = { id => $id };      my $dbh = $self->{_dbh};
3040      # Get the metadata structure.      # Drop the relation. The method used here has no effect if the relation
3041      my $metadata = $self->{_metaData};      # does not exist.
3042      # Get this entity's list of fields.      Trace("Invoking DB Kernel to drop $relationName.") if T(3);
3043      if (!exists $metadata->{Entities}->{$type}) {      $dbh->drop_table(tbl => $relationName);
3044          Confess("Unrecognized entity type $type in GenerateEntity.");  }
3045      } else {  
3046          my $entity = $metadata->{Entities}->{$type};  =head3 MatchSqlPattern
3047          my $fields = $entity->{Fields};  
3048          # Generate data from the fields.      my $matched = ERDB::MatchSqlPattern($value, $pattern);
3049          _GenerateFields($this, $fields, $type, $values);  
3050    Determine whether or not a specified value matches an SQL pattern. An SQL
3051    pattern has two wild card characters: C<%> that matches multiple characters,
3052    and C<_> that matches a single character. These can be escaped using a
3053    backslash (C<\>). We pull this off by converting the SQL pattern to a
3054    PERL regular expression. As per SQL rules, the match is case-insensitive.
3055    
3056    =over 4
3057    
3058    =item value
3059    
3060    Value to be matched against the pattern. Note that an undefined or empty
3061    value will not match anything.
3062    
3063    =item pattern
3064    
3065    SQL pattern against which to match the value. An undefined or empty pattern will
3066    match everything.
3067    
3068    =item RETURN
3069    
3070    Returns TRUE if the value and pattern match, else FALSE.
3071    
3072    =back
3073    
3074    =cut
3075    
3076    sub MatchSqlPattern {
3077        # Get the parameters.
3078        my ($value, $pattern) = @_;
3079        # Declare the return variable.
3080        my $retVal;
3081        # Insure we have a pattern.
3082        if (! defined($pattern) || $pattern eq "") {
3083            $retVal = 1;
3084        } else {
3085            # Break the pattern into pieces around the wildcard characters. Because we
3086            # use parentheses in the split function's delimiter expression, we'll get
3087            # list elements for the delimiters as well as the rest of the string.
3088            my @pieces = split /([_%]|\\[_%])/, $pattern;
3089            # Check some fast special cases.
3090            if ($pattern eq '%') {
3091                # A null pattern matches everything.
3092                $retVal = 1;
3093            } elsif (@pieces == 1) {
3094                # No wildcards, so we have a literal comparison. Note we're case-insensitive.
3095                $retVal = (lc($value) eq lc($pattern));
3096            } elsif (@pieces == 2 && $pieces[1] eq '%') {
3097                # A wildcard at the end, so we have a substring match. This is also case-insensitive.
3098                $retVal = (lc(substr($value, 0, length($pieces[0]))) eq lc($pieces[0]));
3099            } else {
3100                # Okay, we have to do it the hard way. Convert each piece to a PERL pattern.
3101                my $realPattern = "";
3102                for my $piece (@pieces) {
3103                    # Determine the type of piece.
3104                    if ($piece eq "") {
3105                        # Empty pieces are ignored.
3106                    } elsif ($piece eq "%") {
3107                        # Here we have a multi-character wildcard. Note that it can match
3108                        # zero or more characters.
3109                        $realPattern .= ".*"
3110                    } elsif ($piece eq "_") {
3111                        # Here we have a single-character wildcard.
3112                        $realPattern .= ".";
3113                    } elsif ($piece eq "\\%" || $piece eq "\\_") {
3114                        # This is an escape sequence (which is a rare thing, actually).
3115                        $realPattern .= substr($piece, 1, 1);
3116                    } else {
3117                        # Here we have raw text.
3118                        $realPattern .= quotemeta($piece);
3119      }      }
3120      # Return the hash created.              }
3121      return $this;              # Do the match.
3122                $retVal = ($value =~ /^$realPattern$/i ? 1 : 0);
3123            }
3124        }
3125        # Return the result.
3126        return $retVal;
3127  }  }
3128    
3129  =head3 GetEntity  =head3 GetEntity
3130    
3131  C<< my $entityObject = $erdb->GetEntity($entityType, $ID); >>      my $entityObject = $erdb->GetEntity($entityType, $ID);
3132    
3133  Return an object describing the entity instance with a specified ID.  Return an object describing the entity instance with a specified ID.
3134    
# Line 2139  Line 3144 
3144    
3145  =item RETURN  =item RETURN
3146    
3147  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
3148  instance is found with the specified key.  instance is found with the specified key.
3149    
3150  =back  =back
# Line 2159  Line 3164 
3164    
3165  =head3 GetChoices  =head3 GetChoices
3166    
3167  C<< my @values = $erdb->GetChoices($entityName, $fieldName); >>      my @values = $erdb->GetChoices($entityName, $fieldName);
3168    
3169  Return a list of all the values for the specified field that are represented in the  Return a list of all the values for the specified field that are represented in the
3170  specified entity.  specified entity.
# Line 2214  Line 3219 
3219    
3220  =head3 GetEntityValues  =head3 GetEntityValues
3221    
3222  C<< my @values = $erdb->GetEntityValues($entityType, $ID, \@fields); >>      my @values = $erdb->GetEntityValues($entityType, $ID, \@fields);
3223    
3224  Return a list of values from a specified entity instance. If the entity instance  Return a list of values from a specified entity instance. If the entity instance
3225  does not exist, an empty list is returned.  does not exist, an empty list is returned.
# Line 2258  Line 3263 
3263    
3264  =head3 GetAll  =head3 GetAll
3265    
3266  C<< my @list = $erdb->GetAll(\@objectNames, $filterClause, \@parameters, \@fields, $count); >>      my @list = $erdb->GetAll(\@objectNames, $filterClause, \@parameters, \@fields, $count);
3267    
3268  Return a list of values taken from the objects returned by a query. The first three  Return a list of values taken from the objects returned by a query. The first three
3269  parameters correspond to the parameters of the L</Get> method. The final parameter is  parameters correspond to the parameters of the L</Get> method. The final parameter is
# Line 2272  Line 3277 
3277  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
3278  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
3279  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
3280  feature ID followed by all of its aliases.  feature ID followed by all of its essentiality determinations.
3281    
3282  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)']);
3283    
3284  =over 4  =over 4
3285    
# Line 2352  Line 3357 
3357    
3358  =head3 Exists  =head3 Exists
3359    
3360  C<< my $found = $sprout->Exists($entityName, $entityID); >>      my $found = $sprout->Exists($entityName, $entityID);
3361    
3362  Return TRUE if an entity exists, else FALSE.  Return TRUE if an entity exists, else FALSE.
3363    
# Line 2387  Line 3392 
3392    
3393  =head3 EstimateRowSize  =head3 EstimateRowSize
3394    
3395  C<< my $rowSize = $erdb->EstimateRowSize($relName); >>      my $rowSize = $erdb->EstimateRowSize($relName);
3396    
3397  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
3398  up the average length for each data type.  up the average length for each data type.
# Line 2425  Line 3430 
3430    
3431  =head3 GetFieldTable  =head3 GetFieldTable
3432    
3433  C<< my $fieldHash = $self->GetFieldTable($objectnName); >>      my $fieldHash = $self->GetFieldTable($objectnName);
3434    
3435  Get the field structure for a specified entity or relationship.  Get the field structure for a specified entity or relationship.
3436    
# Line 2452  Line 3457 
3457      return $objectData->{Fields};      return $objectData->{Fields};
3458  }  }
3459    
3460  =head2 Data Mining Methods  =head3 SplitKeywords
3461    
3462  =head3 GetUsefulCrossValues      my @keywords = ERDB::SplitKeywords($keywordString);
3463    
3464  C<< my @attrNames = $sprout->GetUsefulCrossValues($sourceEntity, $relationship); >>  This method returns a list of the positive keywords in the specified
3465    keyword string. All of the operators will have been stripped off,
3466    and if the keyword is preceded by a minus operator (C<->), it will
3467    not be in the list returned. The idea here is to get a list of the
3468    keywords the user wants to see. The list will be processed to remove
3469    duplicates.
3470    
3471  Return a list of the useful attributes that would be returned by a B<Cross> call  It is possible to create a string that confuses this method. For example
 from an entity of the source entity type through the specified relationship. This  
 means it will return the fields of the target entity type and the intersection data  
 fields in the relationship. Only primary table fields are returned. In other words,  
 the field names returned will be for fields where there is always one and only one  
 value.  
3472    
3473  =over 4      frog toad -frog
3474    
3475  =item sourceEntity  would return both C<frog> and C<toad>. If this is a problem we can deal
3476    with it later.
3477    
3478  Name of the entity from which the relationship crossing will start.  =over 4
3479    
3480  =item relationship  =item keywordString
3481    
3482  Name of the relationship being crossed.  The keyword string to be parsed.
3483    
3484  =item RETURN  =item RETURN
3485    
3486  Returns a list of field names in Sprout field format (I<objectName>C<(>I<fieldName>C<)>.  Returns a list of the words in the keyword string the user wants to
3487    see.
3488    
3489  =back  =back
3490    
3491  =cut  =cut
3492  #: Return Type @;  
3493  sub GetUsefulCrossValues {  sub SplitKeywords {
3494      # Get the parameters.      # Get the parameters.
3495      my ($self, $sourceEntity, $relationship) = @_;      my ($keywordString) = @_;
3496      # Declare the return variable.      # Make a safety copy of the string. (This helps during debugging.)
3497      my @retVal = ();      my $workString = $keywordString;
3498      # Determine the target entity for the relationship. This is whichever entity is not      # Convert operators we don't care about to spaces.
3499      # the source entity. So, if the source entity is the FROM, we'll get the name of      $workString =~ tr/+"()<>/ /;
3500      # the TO, and vice versa.      # Split the rest of the string along space boundaries. Note that we
3501      my $relStructure = $self->_GetStructure($relationship);      # eliminate any words that are zero length or begin with a minus sign.
3502      my $targetEntityType = ($relStructure->{from} eq $sourceEntity ? "to" : "from");      my @wordList = grep { $_ && substr($_, 0, 1) ne "-" } split /\s+/, $workString;
3503      my $targetEntity = $relStructure->{$targetEntityType};      # Use a hash to remove duplicates.
3504      # Get the field table for the entity.      my %words = map { $_ => 1 } @wordList;
     my $entityFields = $self->GetFieldTable($targetEntity);  
     # The field table is a hash. The hash key is the field name. The hash value is a structure.  
     # For the entity fields, the key aspect of the target structure is that the {relation} value  
     # must match the entity name.  
     my @fieldList = map { "$targetEntity($_)" } grep { $entityFields->{$_}->{relation} eq $targetEntity }  
                         keys %{$entityFields};  
     # Push the fields found onto the return variable.  
     push @retVal, sort @fieldList;  
     # Get the field table for the relationship.  
     my $relationshipFields = $self->GetFieldTable($relationship);  
     # Here we have a different rule. We want all the fields other than "from-link" and "to-link".  
     # This may end up being an empty set.  
     my @fieldList2 = map { "$relationship($_)" } grep { $_ ne "from-link" && $_ ne "to-link" }  
                         keys %{$relationshipFields};  
     # Push these onto the return list.  
     push @retVal, sort @fieldList2;  
3505      # Return the result.      # Return the result.
3506      return @retVal;      return sort keys %words;
3507  }  }
3508    
3509  =head3 FindColumn  =head3 ValidateFieldName
3510    
3511  C<< my $colIndex = ERDB::FindColumn($headerLine, $columnIdentifier); >>      my $okFlag = ERDB::ValidateFieldName($fieldName);
3512    
3513  Return the location a desired column in a data mining header line. The data  Return TRUE if the specified field name is valid, else FALSE. Valid field names must
3514  mining header line is a tab-separated list of column names. The column  be hyphenated words subject to certain restrictions.
 identifier is either the numerical index of a column or the actual column  
 name.  
3515    
3516  =over 4  =over 4
3517    
3518  =item headerLine  =item fieldName
3519    
3520    Field name to be validated.
3521    
3522    =item RETURN
3523    
3524    Returns TRUE if the field name is valid, else FALSE.
3525    
3526    =back
3527    
3528    =cut
3529    
3530    sub ValidateFieldName {
3531        # Get the parameters.
3532        my ($fieldName) = @_;
3533        # Declare the return variable. The field name is valid until we hear
3534        # differently.
3535        my $retVal = 1;
3536        # Compute the maximum name length.
3537        my $maxLen = $TypeTable{'name-string'}->{maxLen};
3538        # Look for bad stuff in the name.
3539        if ($fieldName =~ /--/) {
3540            # Here we have a doubled minus sign.
3541            Trace("Field name $fieldName has a doubled hyphen.") if T(1);
3542            $retVal = 0;
3543        } elsif ($fieldName !~ /^[A-Za-z]/) {
3544            # Here the field name is missing the initial letter.
3545            Trace("Field name $fieldName does not begin with a letter.") if T(1);
3546            $retVal = 0;
3547        } elsif (length($fieldName) > $maxLen) {
3548            # Here the field name is too long.
3549            Trace("Maximum field name length is $maxLen. Field name must be truncated to " . substr($fieldName,0, $maxLen) . ".");
3550        } else {
3551            # Strip out the minus signs. Everything remaining must be a letter,
3552            # underscore, or digit.
3553            my $strippedName = $fieldName;
3554            $strippedName =~ s/-//g;
3555            if ($strippedName !~ /^(\w|\d)+$/) {
3556                Trace("Field name $fieldName contains illegal characters.") if T(1);
3557                $retVal = 0;
3558            }
3559        }
3560        # Return the result.
3561        return $retVal;
3562    }
3563    
3564    =head3 ReadMetaXML
3565    
3566        my $rawMetaData = ERDB::ReadDBD($fileName);
3567    
3568    This method reads a raw database definition XML file and returns it.
3569    Normally, the metadata used by the ERDB system has been processed and
3570    modified to make it easier to load and retrieve the data; however,
3571    this method can be used to get the data in its raw form.
3572    
3573    =over 4
3574    
3575    =item fileName
3576    
3577    Name of the XML file to read.
3578    
3579    =item RETURN
3580    
3581    Returns a hash reference containing the raw XML data from the specified file.
3582    
3583    =back
3584    
3585    =cut
3586    
3587    sub ReadMetaXML {
3588        # Get the parameters.
3589        my ($fileName) = @_;
3590        # Read the XML.
3591        my $retVal = XML::Simple::XMLin($fileName, %XmlOptions, %XmlInOpts);
3592        Trace("XML metadata loaded from file $fileName.") if T(1);
3593        # Return the result.
3594        return $retVal;
3595    }
3596    
3597    =head3 GetEntityFieldHash
3598    
3599        my $fieldHashRef = ERDB::GetEntityFieldHash($structure, $entityName);
3600    
3601    Get the field hash of the named entity in the specified raw XML structure.
3602    The field hash may not exist, in which case we need to create it.
3603    
3604    =over 4
3605    
3606    =item structure
3607    
3608    Raw XML structure defininng the database. This is not the run-time XML used by
3609    an ERDB object, since that has all sorts of optimizations built-in.
3610    
3611    =item entityName
3612    
3613    Name of the entity whose field structure is desired.
3614    
3615    =item RETURN
3616    
3617    Returns the field hash used to define the entity's fields.
3618    
3619    =back
3620    
3621    =cut
3622    
3623    sub GetEntityFieldHash {
3624        # Get the parameters.
3625        my ($structure, $entityName) = @_;
3626        # Get the entity structure.
3627        my $entityData = $structure->{Entities}->{$entityName};
3628        # Look for a field structure.
3629        my $retVal = $entityData->{Fields};
3630        # If it doesn't exist, create it.
3631        if (! defined($retVal)) {
3632            $entityData->{Fields} = {};
3633            $retVal = $entityData->{Fields};
3634        }
3635        # Return the result.
3636        return $retVal;
3637    }
3638    
3639    =head3 WriteMetaXML
3640    
3641        ERDB::WriteMetaXML($structure, $fileName);
3642    
3643    Write the metadata XML to a file. This method is the reverse of L</ReadMetaXML>, and is
3644    used to update the database definition. It must be used with care, however, since it
3645    will only work on a raw structure, not on the processed structure created by an ERDB
3646    constructor.
3647    
3648    =over 4
3649    
3650    =item structure
3651    
3652    XML structure to be written to the file.
3653    
3654    =item fileName
3655    
3656    Name of the output file to which the updated XML should be stored.
3657    
3658    =back
3659    
3660    =cut
3661    
3662    sub WriteMetaXML {
3663        # Get the parameters.
3664        my ($structure, $fileName) = @_;
3665        # Compute the output.
3666        my $fileString = XML::Simple::XMLout($structure, %XmlOptions, %XmlOutOpts);
3667        # Write it to the file.
3668        my $xmlOut = Open(undef, ">$fileName");
3669        print $xmlOut $fileString;
3670    }
3671    
3672    
3673    =head3 HTMLNote
3674    
3675    Convert a note or comment to HTML by replacing some bulletin-board codes with HTML. The codes
3676    supported are C<[b]> for B<bold>, C<[i]> for I<italics>, and C<[p]> for a new paragraph.
3677    Except for C<[p]>, all the codes are closed by slash-codes. So, for
3678    example, C<[b]Feature[/b]> displays the string C<Feature> in boldface.
3679    
3680        my $realHtml = ERDB::HTMLNote($dataString);
3681    
3682    =over 4
3683    
3684    =item dataString
3685    
3686    String to convert to HTML.
3687    
3688    =item RETURN
3689    
3690    An HTML string derived from the input string.
3691    
3692    =back
3693    
3694    =cut
3695    
3696    sub HTMLNote {
3697        # Get the parameter.
3698        my ($dataString) = @_;
3699        # HTML-escape the text.
3700        my $retVal = CGI::escapeHTML($dataString);
3701        # Substitute the bulletin board codes.
3702        $retVal =~ s!\[(/?[bi])\]!<$1>!g;
3703        $retVal =~ s!\[p\]!</p><p>!g;
3704        $retVal =~ s!\[link\s+([^\]]+)\]!<a href="$1">!g;
3705        $retVal =~ s!\[/link\]!</a>!g;
3706        # Return the result.
3707        return $retVal;
3708    }
3709    
3710    =head3 WikiNote
3711    
3712    Convert a note or comment to Wiki text by replacing some bulletin-board codes with HTML. The codes
3713    supported are C<[b]> for B<bold>, C<[i]> for I<italics>, and C<[p]> for a new paragraph.
3714    Except for C<[p]>, all the codes are closed by slash-codes. So, for
3715    example, C<[b]Feature[/b]> displays the string C<Feature> in boldface.
3716    
3717        my $wikiText = ERDB::WikiNote($dataString);
3718    
3719    =over 4
3720    
3721    =item dataString
3722    
3723    String to convert to Wiki text.
3724    
3725    =item RETURN
3726    
3727    An Wiki text string derived from the input string.
3728    
3729    =back
3730    
3731    =cut
3732    
3733    sub WikiNote {
3734        # Get the parameter.
3735        my ($dataString) = @_;
3736        # HTML-escape the text.
3737        my $retVal = CGI::escapeHTML($dataString);
3738        # Substitute the bulletin board codes.
3739        my $italic = WikiTools::ItalicCode();
3740        $retVal =~ s/\[\/?i\]/$italic/g;
3741        my $bold = WikiTools::BoldCode();
3742        $retVal =~ s/\[\/?b\]/$bold/g;
3743        # Paragraph breaks are the same no matter which Wiki you're using.
3744        $retVal =~ s!\[p\]!\n\n!g;
3745        # Now we do the links, which are complicated by the need to know two
3746        # things: the target URL and the text.
3747        while ($retVal =~ /\[link\s+([^\]]+)\]([^\[]+)\[\/link\]/g) {
3748            # Replace the matched string with the Wiki markup for links. Note that
3749            # $-[0] is the starting position of the match for the entire expression,
3750            # and $+[0] is past the ending position.
3751            substr $retVal, $-[0], $+[0] - $-[0], WikiTools::LinkMarkup($1, $2);
3752        }
3753        # Return the result.
3754        return $retVal;
3755    }
3756    
3757    =head3 BeginTran
3758    
3759        $erdb->BeginTran();
3760    
3761    Start a database transaction.
3762    
3763    =cut
3764    
3765    sub BeginTran {
3766        my ($self) = @_;
3767        $self->{_dbh}->begin_tran();
3768    
3769    }
3770    
3771    =head3 CommitTran
3772    
3773        $erdb->CommitTran();
3774    
3775    Commit an active database transaction.
3776    
3777    =cut
3778    
3779    sub CommitTran {
3780        my ($self) = @_;
3781        $self->{_dbh}->commit_tran();
3782    }
3783    
3784    =head3 RollbackTran
3785    
3786        $erdb->RollbackTran();
3787    
3788    Roll back an active database transaction.
3789    
3790    =cut
3791    
3792    sub RollbackTran {
3793        my ($self) = @_;
3794        $self->{_dbh}->roll_tran();
3795    }
3796    
3797    =head3 UpdateField
3798    
3799        my $count = $erdb->UpdateField($objectNames, $fieldName, $oldValue, $newValue, $filter, $parms);
3800    
3801    Update all occurrences of a specific field value to a new value. The number of rows changed will be
3802    returned.
3803    
3804    =over 4
3805    
3806    =item fieldName
3807    
3808    Name of the field in standard I<objectName>C<(>I<fieldName>C<)> format.
3809    
3810    =item oldValue
3811    
3812    Value to be modified. All occurrences of this value in the named field will be replaced by the
3813    new value.
3814    
3815    =item newValue
3816    
3817    New value to be substituted for the old value when it's found.
3818    
3819    =item filter
3820    
3821    A standard ERDB filter clause (see L</Get>). The filter will be applied before any substitutions take place.
3822    
3823    =item parms
3824    
3825    Reference to a list of parameter values in the filter.
3826    
3827    =item RETURN
3828    
3829    Returns the number of rows modified.
3830    
3831    =back
3832    
3833    =cut
3834    
3835    sub UpdateField {
3836        # Get the parameters.
3837        my ($self, $fieldName, $oldValue, $newValue, $filter, $parms) = @_;
3838        # Get the object and field names from the field name parameter.
3839        $fieldName =~ /^([^(]+)\(([^)]+)\)/;
3840        my $objectName = $1;
3841        my $realFieldName = _FixName($2);
3842        # Add the old value to the filter. Note we allow the possibility that no
3843        # filter was specified.
3844        my $realFilter = "$fieldName = ?";
3845        if ($filter) {
3846            $realFilter .= " AND $filter";
3847        }
3848        # Format the query filter.
3849        my ($suffix, $mappedNameListRef, $mappedNameHashRef) =
3850            $self->_SetupSQL([$objectName], $realFilter);
3851        # Create the query. Since there is only one object name, the mapped-name data is not
3852        # necessary. Neither is the FROM clause.
3853        $suffix =~ s/^FROM.+WHERE\s+//;
3854        # Create the update statement.
3855        my $command = "UPDATE $objectName SET $realFieldName = ? WHERE $suffix";
3856        # Get the database handle.
3857        my $dbh = $self->{_dbh};
3858        # Add the old and new values to the parameter list. Note we allow the possibility that
3859        # there are no user-supplied parameters.
3860        my @params = ($newValue, $oldValue);
3861        if (defined $parms) {
3862            push @params, @{$parms};
3863        }
3864        # Execute the update.
3865        my $retVal = $dbh->SQL($command, 0, @params);
3866        # Make the funky zero a real zero.
3867        if ($retVal == 0) {
3868            $retVal = 0;
3869        }
3870        # Return the result.
3871        return $retVal;
3872    }
3873    
3874    
3875    =head2 Data Mining Methods
3876    
3877    =head3 GetUsefulCrossValues
3878    
3879        my @attrNames = $sprout->GetUsefulCrossValues($sourceEntity, $relationship);
3880    
3881    Return a list of the useful attributes that would be returned by a B<Cross> call
3882    from an entity of the source entity type through the specified relationship. This
3883    means it will return the fields of the target entity type and the intersection data
3884    fields in the relationship. Only primary table fields are returned. In other words,
3885    the field names returned will be for fields where there is always one and only one
3886    value.
3887    
3888    =over 4
3889    
3890    =item sourceEntity
3891    
3892    Name of the entity from which the relationship crossing will start.
3893    
3894    =item relationship
3895    
3896    Name of the relationship being crossed.
3897    
3898    =item RETURN
3899    
3900    Returns a list of field names in Sprout field format (I<objectName>C<(>I<fieldName>C<)>.
3901    
3902    =back
3903    
3904    =cut
3905    #: Return Type @;
3906    sub GetUsefulCrossValues {
3907        # Get the parameters.
3908        my ($self, $sourceEntity, $relationship) = @_;
3909        # Declare the return variable.
3910        my @retVal = ();
3911        # Determine the target entity for the relationship. This is whichever entity is not
3912        # the source entity. So, if the source entity is the FROM, we'll get the name of
3913        # the TO, and vice versa.
3914        my $relStructure = $self->_GetStructure($relationship);
3915        my $targetEntityType = ($relStructure->{from} eq $sourceEntity ? "to" : "from");
3916        my $targetEntity = $relStructure->{$targetEntityType};
3917        # Get the field table for the entity.
3918        my $entityFields = $self->GetFieldTable($targetEntity);
3919        # The field table is a hash. The hash key is the field name. The hash value is a structure.
3920        # For the entity fields, the key aspect of the target structure is that the {relation} value
3921        # must match the entity name.
3922        my @fieldList = map { "$targetEntity($_)" } grep { $entityFields->{$_}->{relation} eq $targetEntity }
3923                            keys %{$entityFields};
3924        # Push the fields found onto the return variable.
3925        push @retVal, sort @fieldList;
3926        # Get the field table for the relationship.
3927        my $relationshipFields = $self->GetFieldTable($relationship);
3928        # Here we have a different rule. We want all the fields other than "from-link" and "to-link".
3929        # This may end up being an empty set.
3930        my @fieldList2 = map { "$relationship($_)" } grep { $_ ne "from-link" && $_ ne "to-link" }
3931                            keys %{$relationshipFields};
3932        # Push these onto the return list.
3933        push @retVal, sort @fieldList2;
3934        # Return the result.
3935        return @retVal;
3936    }
3937    
3938    =head3 FindColumn
3939    
3940        my $colIndex = ERDB::FindColumn($headerLine, $columnIdentifier);
3941    
3942    Return the location a desired column in a data mining header line. The data
3943    mining header line is a tab-separated list of column names. The column
3944    identifier is either the numerical index of a column or the actual column
3945    name.
3946    
3947    =over 4
3948    
3949    =item headerLine
3950    
3951  The header line from a data mining command, which consists of a tab-separated  The header line from a data mining command, which consists of a tab-separated
3952  list of column names.  list of column names.
# Line 2575  Line 3995 
3995    
3996  =head3 ParseColumns  =head3 ParseColumns
3997    
3998  C<< my @columns = ERDB::ParseColumns($line); >>      my @columns = ERDB::ParseColumns($line);
3999    
4000  Convert the specified data line to a list of columns.  Convert the specified data line to a list of columns.
4001    
# Line 2607  Line 4027 
4027    
4028  =head2 Virtual Methods  =head2 Virtual Methods
4029    
4030    =head3 _CreatePPOIndex
4031    
4032        my $index = ERDB::_CreatePPOIndex($indexObject);
4033    
4034    Convert the XML for an ERDB index to the XML structure for a PPO
4035    index.
4036    
4037    =over 4
4038    
4039    =item indexObject
4040    
4041    ERDB XML structure for an index.
4042    
4043    =item RETURN
4044    
4045    PPO XML structure for the same index.
4046    
4047    =back
4048    
4049    =cut
4050    
4051    sub _CreatePPOIndex {
4052        # Get the parameters.
4053        my ($indexObject) = @_;
4054        # The incoming index contains a list of the index fields in the IndexFields
4055        # member. We loop through it to create the index tags.
4056        my @fields = map { { label => _FixName($_->{name}) } } @{$indexObject->{IndexFields}};
4057        # Wrap the fields in attribute tags.
4058        my $retVal = { attribute => \@fields };
4059        # Return the result.
4060        return $retVal;
4061    }
4062    
4063    =head3 _CreatePPOField
4064    
4065        my $fieldXML = ERDB::_CreatePPOField($fieldName, $fieldObject);
4066    
4067    Convert the ERDB XML structure for a field to a PPO scalar XML structure.
4068    
4069    =over 4
4070    
4071    =item fieldName
4072    
4073    Name of the scalar field.
4074    
4075    =item fieldObject
4076    
4077    ERDB XML structure describing the field.
4078    
4079    =item RETURN
4080    
4081    Returns a PPO XML structure for the same field.
4082    
4083    =back
4084    
4085    =cut
4086    
4087    sub _CreatePPOField {
4088        # Get the parameters.
4089        my ($fieldName, $fieldObject) = @_;
4090        # Get the field type.
4091        my $type = $TypeTable{$fieldObject->{type}}->{sqlType};
4092        # Fix up the field name.
4093        $fieldName = _FixName($fieldName);
4094        # Build the scalar tag.
4095        my $retVal = { label => $fieldName, type => $type };
4096        # Return the result.
4097        return $retVal;
4098    }
4099    
4100  =head3 CleanKeywords  =head3 CleanKeywords
4101    
4102  C<< my $cleanedString = $erdb->CleanKeywords($searchExpression); >>      my $cleanedString = $erdb->CleanKeywords($searchExpression);
4103    
4104  Clean up a search expression or keyword list. This is a virtual method that may  Clean up a search expression or keyword list. This is a virtual method that may
4105  be overridden by the subclass. The base-class method removes extra spaces  be overridden by the subclass. The base-class method removes extra spaces
# Line 2644  Line 4134 
4134      return $retVal;      return $retVal;
4135  }  }
4136    
4137    =head3 GetSourceObject
4138    
4139        my $source = $erdb->GetSourceObject($entityName);
4140    
4141    Return the object to be used in loading special attributes of the specified entity. The
4142    algorithm for loading special attributes is stored in the C<DataGen> elements of the
4143    XML
4144    
4145  =head2 Internal Utility Methods  =head2 Internal Utility Methods
4146    
4147  =head3 _RelationMap  =head3 _RelationMap
4148    
4149  C<< my @relationMap = _RelationMap($mappedNameHashRef, $mappedNameListRef); >>      my @relationMap = _RelationMap($mappedNameHashRef, $mappedNameListRef);
4150    
4151  Create the relation map for an SQL query. The relation map is used by B<DBObject>  Create the relation map for an SQL query. The relation map is used by B<ERDBObject>
4152  to determine how to interpret the results of the query.  to determine how to interpret the results of the query.
4153    
4154  =over 4  =over 4
# Line 2667  Line 4165 
4165  =item RETURN  =item RETURN
4166    
4167  Returns a list of 2-tuples. Each tuple consists of an object name as used in the  Returns a list of 2-tuples. Each tuple consists of an object name as used in the
4168  query followed by the actual name of that object. This enables the B<DBObject> to  query followed by the actual name of that object. This enables the B<ERDBObject> to
4169  determine the order of the tables in the query and which object name belongs to each  determine the order of the tables in the query and which object name belongs to each
4170  mapped object name. Most of the time these two values are the same; however, if a  mapped object name. Most of the time these two values are the same; however, if a
4171  relation occurs twice in the query, the relation name in the field list and WHERE  relation occurs twice in the query, the relation name in the field list and WHERE
# Line 2961  Line 4459 
4459  sub _GetStatementHandle {  sub _GetStatementHandle {
4460      # Get the parameters.      # Get the parameters.
4461      my ($self, $command, $params) = @_;      my ($self, $command, $params) = @_;
4462        Confess("Invalid parameter list.") if (! defined($params) || ref($params) ne 'ARRAY');
4463      # Trace the query.      # Trace the query.
4464      Trace("SQL query: $command") if T(SQL => 3);      Trace("SQL query: $command") if T(SQL => 3);
4465      Trace("PARMS: '" . (join "', '", @{$params}) . "'") if (T(SQL => 4) && (@{$params} > 0));      Trace("PARMS: '" . (join "', '", @{$params}) . "'") if (T(SQL => 4) && (@{$params} > 0));
# Line 2969  Line 4468 
4468      # Prepare the command.      # Prepare the command.
4469      my $sth = $dbh->prepare_command($command);      my $sth = $dbh->prepare_command($command);
4470      # Execute it with the parameters bound in.      # Execute it with the parameters bound in.
4471      $sth->execute(@{$params}) || Confess("SELECT error" . $sth->errstr());      $sth->execute(@{$params}) || Confess("SELECT error:  " . $sth->errstr());
4472      # Return the statement handle.      # Return the statement handle.
4473      return $sth;      return $sth;
4474  }  }
# Line 2986  Line 4485 
4485      return Stats->new();      return Stats->new();
4486  }  }
4487    
 =head3 _GenerateFields  
   
 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;  
             }  
         }  
     }  
 }  
   
4488  =head3 _DumpRelation  =head3 _DumpRelation
4489    
4490  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.
4491    
4492  This is an instance method.  This is an instance method.
4493    
# Line 3207  Line 4632 
4632          for my $object (values %{$metadata->{$section}}) {          for my $object (values %{$metadata->{$section}}) {
4633              # Loop through the object's fields.              # Loop through the object's fields.
4634              for my $fieldName (keys %{$object->{Fields}}) {              for my $fieldName (keys %{$object->{Fields}}) {
4635                  # Now we make some initial validations.                  # If this field name is invalid, set the return value to zero
4636                  if ($fieldName =~ /--/) {                  # so we know we encountered an error.
4637                      # 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";  
4638                          $retVal = 0;                          $retVal = 0;
4639                      }                      }
4640                  }                  }
4641              }              }
4642          }          }
     }  
4643      # If an error was found, fail.      # If an error was found, fail.
4644      if ($retVal  == 0) {      if ($retVal  == 0) {
4645          Confess("Errors found in field names.");          Confess("Errors found in field names.");
# Line 3286  Line 4697 
4697      # be a null string.      # be a null string.
4698      if ($fileName ne "") {      if ($fileName ne "") {
4699          # Load the relation from the file.          # Load the relation from the file.
4700          $retVal = $self->LoadTable($fileName, $relationName, $rebuild);          $retVal = $self->LoadTable($fileName, $relationName, truncate => $rebuild);
4701      } elsif ($rebuild) {      } elsif ($rebuild) {
4702          # 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.
4703          $self->CreateTable($relationName, 1);          $self->CreateTable($relationName, 1);
# Line 3295  Line 4706 
4706      return $retVal;      return $retVal;
4707  }  }
4708    
4709    
4710  =head3 _LoadMetaData  =head3 _LoadMetaData
4711    
4712        my $metadata = ERDB::_LoadMetaData($filename);
4713    
4714  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.
4715  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
4716  load or use the database. The schema for the XML file is F<ERDatabase.xml>.  load or use the database. The schema for the XML file is F<ERDatabase.xml>.
# Line 3320  Line 4734 
4734  sub _LoadMetaData {  sub _LoadMetaData {
4735      # Get the parameters.      # Get the parameters.
4736      my ($filename) = @_;      my ($filename) = @_;
4737      Trace("Reading Sprout DBD from $filename.") if T(2);      Trace("Reading DBD from $filename.") if T(2);
4738      # 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
4739      # get the exact structure we want.      # get the exact structure we want.
4740      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);  
4741      # 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,
4742      # the method below will fail.      # the method below will fail.
4743      _ValidateFieldNames($metadata);      _ValidateFieldNames($metadata);
# Line 3459  Line 4860 
4860              if ($found == 0) {              if ($found == 0) {
4861                  push @{$indexList}, { IndexFields => [ {name => 'id', order => 'ascending'} ] };                  push @{$indexList}, { IndexFields => [ {name => 'id', order => 'ascending'} ] };
4862              }              }
4863              # 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.
4864              # 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++;  
             }  
4865          }          }
4866          # Finally, we add the relation structure to the entity.          # Finally, we add the relation structure to the entity.
4867          $entityStructure->{Relations} = $relationTable;          $entityStructure->{Relations} = $relationTable;
# Line 3483  Line 4875 
4875          _FixupFields($relationshipStructure, $relationshipName, 2, 3);          _FixupFields($relationshipStructure, $relationshipName, 2, 3);
4876          # Format a description for the FROM field.          # Format a description for the FROM field.
4877          my $fromEntity = $relationshipStructure->{from};          my $fromEntity = $relationshipStructure->{from};
4878          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].";
4879          # Get the FROM entity's key type.          # Get the FROM entity's key type.
4880          my $fromType = $entityList->{$fromEntity}->{keyType};          my $fromType = $entityList->{$fromEntity}->{keyType};
4881          # Add the FROM field.          # Add the FROM field.
# Line 3493  Line 4885 
4885                                                      PrettySort => 1});                                                      PrettySort => 1});
4886          # Format a description for the TO field.          # Format a description for the TO field.
4887          my $toEntity = $relationshipStructure->{to};          my $toEntity = $relationshipStructure->{to};
4888          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].";
4889          # Get the TO entity's key type.          # Get the TO entity's key type.
4890          my $toType = $entityList->{$toEntity}->{keyType};          my $toType = $entityList->{$toEntity}->{keyType};
4891          # Add the TO field.          # Add the TO field.
# Line 3505  Line 4897 
4897          my $thisRelation = { Fields => _ReOrderRelationTable($relationshipStructure->{Fields}),          my $thisRelation = { Fields => _ReOrderRelationTable($relationshipStructure->{Fields}),
4898                               Indexes => { } };                               Indexes => { } };
4899          $relationshipStructure->{Relations} = { $relationshipName => $thisRelation };          $relationshipStructure->{Relations} = { $relationshipName => $thisRelation };
4900    
4901            # Add the alternate indexes (if any). This MUST be done before the FROM and
4902            # TO indexes, because it erases the relation's index list.
4903            if (exists $relationshipStructure->{Indexes}) {
4904                _ProcessIndexes($relationshipStructure->{Indexes}, $thisRelation);
4905            }
4906            # Add the relation to the master table.
4907          # Create the FROM and TO indexes.          # Create the FROM and TO indexes.
4908          _CreateRelationshipIndex("From", $relationshipName, $relationshipStructure);          _CreateRelationshipIndex("From", $relationshipName, $relationshipStructure);
4909          _CreateRelationshipIndex("To", $relationshipName, $relationshipStructure);          _CreateRelationshipIndex("To", $relationshipName, $relationshipStructure);
         # Add the relation to the master table.  
4910          $masterRelationTable{$relationshipName} = $thisRelation;          $masterRelationTable{$relationshipName} = $thisRelation;
4911      }      }
4912      # Now store the master relation table in the metadata structure.      # Now store the master relation table in the metadata structure.
# Line 3664  Line 5062 
5062          $newIndex->{Unique} = 'true';          $newIndex->{Unique} = 'true';
5063      }      }
5064      # Add the index to the relation.      # Add the index to the relation.
5065      _AddIndex("idx$relationshipName$indexKey", $relationStructure, $newIndex);      _AddIndex("idx$indexKey", $relationStructure, $newIndex);
5066    }
5067    
5068    =head3 _ProcessIndexes
5069    
5070        ERDB::_ProcessIndexes($indexList, $relation);
5071    
5072    Build the data structures for the specified indexes in the specified relation.
5073    
5074    =over 4
5075    
5076    =item indexList
5077    
5078    Reference to a list of indexes. Each index is a hash reference containing an optional
5079    C<Notes> value that describes the index and an C<IndexFields> value that is a reference
5080    to a list of index field structures. An index field structure, in turn, is a reference
5081    to a hash that contains a C<name> attribute for the field name and an C<order>
5082    attribute that specifies either C<ascending> or C<descending>. In this sense the
5083    index list encapsulates the XML C<Indexes> structure in the database definition.
5084    
5085    =item relation
5086    
5087    The structure that describes the current relation. The new index descriptors will
5088    be stored in the structure's C<Indexes> member. Any previous data in the structure
5089    will be lost.
5090    
5091    =back
5092    
5093    =cut
5094    
5095    sub _ProcessIndexes {
5096        # Get the parameters.
5097        my ($indexList, $relation) = @_;
5098        # Now we need to convert the relation's index list to an index table. We begin by creating
5099        # an empty table in the relation structure.
5100        $relation->{Indexes} = { };
5101        # Loop through the indexes.
5102        my $count = 0;
5103        for my $index (@{$indexList}) {
5104            # Add this index to the index table.
5105            _AddIndex("idx$count", $relation, $index);
5106            # Increment the counter so that the next index has a different name.
5107            $count++;
5108        }
5109  }  }
5110    
5111  =head3 _AddIndex  =head3 _AddIndex
# Line 3763  Line 5204 
5204              my $type = $fieldData->{type};              my $type = $fieldData->{type};
5205              # Plug in a relation name if it is needed.              # Plug in a relation name if it is needed.
5206              Tracer::MergeOptions($fieldData, { relation => $defaultRelationName });              Tracer::MergeOptions($fieldData, { relation => $defaultRelationName });
             # Plug in a data generator if we need one.  
             if (!exists $fieldData->{DataGen}) {  
                 # The data generator will use the default for the field's type.  
                 $fieldData->{DataGen} = { content => $TypeTable{$type}->{dataGen} };  
             }  
5207              # Check for searchability.              # Check for searchability.
5208              if ($fieldData->{searchable}) {              if ($fieldData->{searchable}) {
5209                  # Only allow this for a primary relation.                  # Only allow this for a primary relation.
# Line 3777  Line 5213 
5213                      push @textFields, $fieldName;                      push @textFields, $fieldName;
5214                  }                  }
5215              }              }
             # Plug in the defaults for the optional data generation parameters.  
             Tracer::MergeOptions($fieldData->{DataGen}, { testCount => 1, pass => 0 });  
5216              # Add the PrettySortValue.              # Add the PrettySortValue.
5217              $fieldData->{PrettySort} = (($type eq "text") ? $textPrettySortValue : $prettySortValue);              $fieldData->{PrettySort} = (($type eq "text") ? $textPrettySortValue : $prettySortValue);
5218          }          }
# Line 4010  Line 5444 
5444      return $retVal;      return $retVal;
5445  }  }
5446    
5447  =head2 HTML Documentation Utility Methods  =head2 Documentation Utility Methods
5448    
5449  =head3 _ComputeRelationshipSentence  =head3 _ComputeRelationshipSentence
5450    
# Line 4042  Line 5476 
5476      # Get the parameters.      # Get the parameters.
5477      my ($relationshipName, $relationshipStructure) = @_;      my ($relationshipName, $relationshipStructure) = @_;
5478      # Format the relationship sentence.      # Format the relationship sentence.
5479      my $result = "$relationshipStructure->{from} <b>$relationshipName</b> $relationshipStructure->{to}";      my $result = "$relationshipStructure->{from} $relationshipName $relationshipStructure->{to}";
5480      # Compute the arity.      # Compute the arity.
5481      my $arityCode = $relationshipStructure->{arity};      my $arityCode = $relationshipStructure->{arity};
5482      my $arity = $ArityTable{$arityCode};      my $arity = $ArityTable{$arityCode};
# Line 4087  Line 5521 
5521      return $result;      return $result;
5522  }  }
5523    
5524    =head3 _WikiRelationTable
5525    
5526    Generate the Wiki text for a particular relation. The relation's data will be formatted as a
5527    table with three columns-- the field name, the field type, and the field description.
5528    
5529    This is a static method.
5530    
5531    =over 4
5532    
5533    =item relationName
5534    
5535    Name of the relation being formatted.
5536    
5537    =item relationData
5538    
5539    Hash containing the relation's fields and indexes.
5540    
5541    =item RETURN
5542    
5543    Returns a Wiki string that can be used to display the relation name and all of its fields.
5544    
5545    =back
5546    
5547    =cut
5548    
5549    sub _WikiRelationTable {
5550        # Get the parameters.
5551        my ($relationName, $relationData) = @_;
5552        # We'll create a list of lists in here, then call WikiTools::Table to
5553        # convert it into a table.
5554        my @rows = ();
5555        # Push in the header row.
5556        push @rows, [qw(Field Type Description)];
5557        # Loop through the fields.
5558        for my $field (@{$relationData->{Fields}}) {
5559            # Create this field's row. We always have a name and type.
5560            my @row = ($field->{name}, $field->{type});
5561            # If we have a description, add it as the third column.
5562            if (exists $field->{Notes}) {
5563                push @row, WikiNote($field->{Notes}->{content});
5564            }
5565            # Push this row onto the table list.
5566            push @rows, \@row;
5567        }
5568        # Store the rows as a Wiki table with a level-4 heading.
5569        my $retVal = join("\n\n", WikiTools::Heading(4, "$relationName Table"),
5570                          WikiTools::Table(@rows));
5571        # Now we show the relation's indexes. These are formatted as another
5572        # table.
5573        @rows = ();
5574        # Push in the header row.
5575        push @rows, [qw(Index Unique Fields Notes)];
5576        # Get the index hash.
5577        my $indexTable = $relationData->{Indexes};
5578        # Loop through the indexes. For an entity, there is always at least one index.
5579        # For a relationship, there are at least two. The upshot is we don't need to
5580        # worry about accidentally generating a frivolous table here.
5581        for my $indexName (sort keys %$indexTable) {
5582            my $indexData = $indexTable->{$indexName};
5583            # Determine whether or not the index is unique.
5584            my $unique = ((exists $indexData->{Unique} && $indexData->{Unique} eq "true") ?
5585                          "yes" : "");
5586            # Get the field list.
5587            my $fields = join(', ', @{$indexData->{IndexFields}});
5588            # Get the note text.
5589            my $description = "";
5590            if (my $note = $indexData->{Notes}) {
5591                $description = WikiNote($note->{content});
5592            }
5593            # Format this row.
5594            my @row = ($indexName, $unique, $fields, $description);
5595            push @rows, \@row;
5596        }
5597        # Add the index list to the result.
5598        $retVal .= "\n\n" . WikiTools::Table(@rows);
5599    }
5600    
5601  =head3 _ShowRelationTable  =head3 _ShowRelationTable
5602    
5603  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
# Line 4137  Line 5648 
5648          $htmlString .= "<li><b>Index $fullName</b>\n<ul>\n";          $htmlString .= "<li><b>Index $fullName</b>\n<ul>\n";
5649          # Add any note text.          # Add any note text.
5650          if (my $note = $indexData->{Notes}) {          if (my $note = $indexData->{Notes}) {
5651              $htmlString .= "<li>" . _HTMLNote($note->{content}) . "</li>\n";              $htmlString .= "<li>" . HTMLNote($note->{content}) . "</li>\n";
5652          }          }
5653          # Add the fiield list.          # Add the fiield list.
5654          $htmlString .= "<li><i>" . join(', ', @{$indexData->{IndexFields}}) . "</i></li>\n";          $htmlString .= "<li><i>" . join(', ', @{$indexData->{IndexFields}}) . "</i></li>\n";
# Line 4203  Line 5714 
5714      # Compute the number of columns.      # Compute the number of columns.
5715      my $colCount = @colNames;      my $colCount = @colNames;
5716      # Generate the title row.      # Generate the title row.
5717      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";
5718      # Loop through the columns, adding the column header rows.      # Loop through the columns, adding the column header rows.
5719      $htmlString .= "<tr>";      $htmlString .= "<tr>";
5720      for my $colName (@colNames) {      for my $colName (@colNames) {
# Line 4222  Line 5733 
5733  =cut  =cut
5734    
5735  sub _CloseTable {  sub _CloseTable {
5736      return "</table></p>\n";      return "</table>\n";
5737  }  }
5738    
5739  =head3 _ShowField  =head3 _ShowField
# Line 4252  Line 5763 
5763      my $htmlString = "<tr><th align=\"left\">$fieldData->{name}</th><td>$fieldData->{type}</td>";      my $htmlString = "<tr><th align=\"left\">$fieldData->{name}</th><td>$fieldData->{type}</td>";
5764      # If we have content, add it as a third column.      # If we have content, add it as a third column.
5765      if (exists $fieldData->{Notes}) {      if (exists $fieldData->{Notes}) {
5766          $htmlString .= "<td>" . _HTMLNote($fieldData->{Notes}->{content}) . "</td>";          $htmlString .= "<td>" . HTMLNote($fieldData->{Notes}->{content}) . "</td>";
5767      }      }
5768      # Close off the row.      # Close off the row.
5769      $htmlString .= "</tr>\n";      $htmlString .= "</tr>\n";
# Line 4260  Line 5771 
5771      return $htmlString;      return $htmlString;
5772  }  }
5773    
5774  =head3 _HTMLNote  =head3 _ObjectNotes
   
 Convert a note or comment to HTML by replacing some bulletin-board codes with HTML. The codes  
 supported are C<[b]> for B<bold>, C<[i]> for I<italics>, and C<[p]> for a new paragraph.  
 Except for C<[p]>, all the codes are closed by slash-codes. So, for  
 example, C<[b]Feature[/b]> displays the string C<Feature> in boldface.  
   
 This is a static method.  
   
 =over 4  
   
 =item dataString  
   
 String to convert to HTML.  
   
 =item RETURN  
   
 An HTML string derived from the input string.  
   
 =back  
   
 =cut  
   
 sub _HTMLNote {  
     # Get the parameter.  
     my ($dataString) = @_;  
     # Substitute the codes.  
     $dataString =~ s!\[(/?[bi])\]!<$1>!g;  
     $dataString =~ s!\[p\]!</p><p>!g;  
     # Return the result.  
     return $dataString;  
 }  
   
 =head2 Data Generation Utilities  
   
 =head3 IntGen  
   
 C<< my $integer = IntGen($min, $max); >>  
   
 Returns a random number between the specified minimum and maximum (inclusive).  
   
 =over 4  
   
 =item min  
   
 Minimum permissible return value.  
   
 =item max  
   
 Maximum permissible return value.  
   
 =item RETURN  
   
 Returns a value no lower than the minimum and no greater than the maximum.  
   
 =back  
   
 =cut  
   
 sub IntGen {  
     # Get the parameters.  
     my ($min, $max) = @_;  
     # Determine the range of possible values. Note we put some space well above the  
     # maximum value to give it a fighting chance of apppearing in the list.  
     my $span = $max + 0.99 - $min;  
     # Create an integer in the range.  
     my $retVal = $min + int(rand($span));  
     # Return the result.  
     return $retVal;  
 }  
   
 =head3 RandChar  
   
 C<< my $char = RandChar($sourceString); >>  
   
 Select a random character from a string.  
   
 =over 4  
   
 =item sourceString  
   
 String from which the random character should be selected.  
   
 =item RETURN  
   
 Returns a single character from the incoming string.  
   
 =back  
   
 =cut  
   
 sub RandChar {  
     # Get the parameter.  
     my ($sourceString) = @_;  
     # Select a random character.  
     my $retVal = IntGen(0, (length $sourceString) - 1);  
     # Return it.  
     return substr($sourceString, $retVal, 1);  
 }  
   
 =head3 RandChars  
   
 C<< my $string = RandChars($sourceString, $length); >>  
   
 Create a string from characters taken from a source string.  
   
 =over 4  
   
 =item sourceString  
   
 String from which the random characters should be selected.  
   
 =item length  
   
 Number of characters to put in the output string.  
   
 =item RETURN  
   
 Returns a string of the specified length consisting of characters taken from the  
 source string.  
   
 =back  
   
 =cut  
   
 sub RandChars {  
     # Get the parameters.  
     my ($sourceString, $length) = @_;  
     # Call RandChar repeatedly to generate the string.  
     my $retVal = "";  
     for (my $i = 0; $i < $length; $i++) {  
         $retVal .= RandChar($sourceString);  
     }  
     # Return the result.  
     return $retVal;  
 }  
   
 =head3 RandParam  
   
 C<< my $value = RandParam($parm1, $parm2, ... $parmN); >>  
   
 Return a randomly-selected value from the parameter list.  
   
 =over 4  
   
 =item parm1, parm2, ... parmN  
   
 List of values of which one will be selected.  
   
 =item RETURN  
   
 Returns a randomly-chosen value from the specified list.  
   
 =back  
   
 =cut  
   
 sub RandParam {  
     # Get the parameter.  
     my @parms = @_;  
     # Choose a random parameter from the list.  
     my $chosenIndex = IntGen(0, $#parms);  
     return $parms[$chosenIndex];  
 }  
   
 =head3 StringGen  
5775    
5776  C<< my $string = StringGen($pattern1, $pattern2, ... $patternN); >>      my @noteParagraphs = _ObjectNotes($objectData);
5777    
5778  Returns a random string derived from a randomly-chosen format pattern. The pattern  Return a list of the notes and asides for an entity or relationship in
5779  can either be a number (indicating the number of characters desired, or the letter  Wiki format.
 C<P> followed by a picture. The picture should contain C<A> when a letter is desired,  
 C<9> when a digit is desired, C<V> when a vowel is desired, C<K> when a consonant is  
 desired, and C<X> when a letter or a digit is desired. Any other character will be  
 translated as a literal.  
5780    
5781  =over 4  =over 4
5782    
5783  =item pattern1, pattern2, ... patternN  =item objectData
5784    
5785  List of patterns to be used to generate string values.  The metadata for the desired entity or relationship.
5786    
5787  =item RETURN  =item RETURN
5788    
5789  A single string generated from a pattern.  Returns a list of text paragraphs in Wiki markup form.
5790    
5791  =back  =back
5792    
5793  =cut  =cut
5794    
5795  sub StringGen {  sub _ObjectNotes {
5796      # Get the parameters.      # Get the parameters.
5797      my @patterns = @_;      my ($objectData) = @_;
     # Choose the appropriate pattern.  
     my $chosenPattern = RandParam(@patterns);  
5798      # Declare the return variable.      # Declare the return variable.
5799      my $retVal = "";      my @retVal;
5800      # Determine whether this is a count or a picture pattern.      # Loop through the types of notes.
5801      if ($chosenPattern =~ m/^\d+/) {      for my $noteType (qw(Notes Asides)) {
5802          # Here we have a count. Get the string of source characters.          my $text = $objectData->{$noteType};
5803          my $letterString = $PictureTable{'X'};          if ($text) {
5804          my $stringLen = length $letterString;              push @retVal, "", WikiNote($text->{content});
         # Save the number of characters we have to generate.  
         my $charsLeft = $chosenPattern;  
         # Loop until the return variable is full.  
         while ($charsLeft > 0) {  
             # Generate a random position in the soruce string.  
             my $stringIndex = IntGen(0, $stringLen - 1);  
             # Compute the number of characters to pull out of the source string.  
             my $chunkSize = $stringLen - $stringIndex;  
             if ($chunkSize > $charsLeft) { $chunkSize = $charsLeft; }  
             # Stuff this chunk into the return value.  
             $retVal .= substr($letterString, $stringIndex, $chunkSize);  
             # Record the data moved.  
             $charsLeft -= $chunkSize;  
         }  
     } elsif ($chosenPattern =~ m/^P/) {  
         # Here we have a picture string. We will move through the picture one  
         # character at a time generating data.  
         for (my $i = 1; $i < length $chosenPattern; $i++) {  
             # Get this picture character.  
             my $chr = substr($chosenPattern, $i, 1);  
             # Check to see if the picture char is one we recognize.  
             if (exists $PictureTable{$chr}) {  
                 # Choose a random character from the available values for this  
                 # picture character.  
                 $retVal .= RandChar($PictureTable{$chr});  
             } else {  
                 # Copy in the picture character as a literal.  
                 $retVal .= $chr;  
             }  
         }  
     } else {  
         # Here we have neither a picture string or a letter count, so we treat  
         # the string as a literal.  
         $retVal = $chosenPattern;  
5805      }      }
     # Return the string formed.  
     return $retVal;  
5806  }  }
   
 =head3 DateGen  
   
 C<< my $date = DateGen($startDayOffset, $endDayOffset, $minutes); >>  
   
 Return a numeric timestamp within the specified range of days with the specified minute  
 value. The range of days is specified relevant to the current day. Thus, the call  
   
 C<< my $date = DateGen(-1, 5, 720); >>  
   
 will return a timestamp at noon (72 minutes past midnight) sometime during the week that  
 began on the preceding day. If you want a random minute of the day, simply combine with  
 a call to L</IntGen>, as follows.  
   
 C<< my $date = DateGen(-1, 5, IntGen(0, 1439)); >>  
   
 =over 4  
   
 =item startDayOffset  
   
 The earliest day that can be returned, relative to the current day.  
   
 =item endDayOffset  
   
 The latest day that can be returned, related to the current day.  
   
 =item minutes  
   
 Number of minutes into the selected day that should be used.  
   
 =back  
   
 =cut  
   
 sub DateGen {  
     # Get the parameters.  
     my ($startDayOffset, $endDayOffset, $minutes) = @_;  
     # Get midnight of the current day.  
     my $now = time();  
     my ($sec, $min, $hour) = localtime($now);  
     my $today = $now - (($hour * 60 + $min) * 60 + $sec);  
     # Compute the day we want.  
     my $newDay = IntGen($startDayOffset, $endDayOffset) * 86400 + $today;  
     # Add the minutes.  
     my $retVal = $newDay + $minutes * 60;  
5807      # Return the result.      # Return the result.
     return $retVal;  
 }  
   
 =head3 FloatGen  
   
 C<< my $number = FloatGen($min, $max); >>  
   
 Return a random floating-point number greater than or equal to the specified minimum and  
 less than the specified maximum.  
   
 =over 4  
   
 =item min  
   
 Minimum permissible value for the number returned.  
   
 =item max  
   
 Maximum permissible value for the number returned.  
   
 =item RETURN  
   
 Returns a floating-point number anywhere in the specified range.  
   
 =back  
   
 =cut  
   
 sub FloatGen {  
     # Get the parameters.  
     my ($min, $max) = @_;  
     # Generate the result.  
     my $retVal = rand($max - $min) + $min;  
     return $retVal;  
 }  
   
 =head3 ListGen  
   
 C<< my @list = ListGen($pattern, $count); >>  
   
 Return a list containing a fixed number of randomly-generated strings.  
   
 =over 4  
   
 =item pattern  
   
 A pattern (in the form expected by L</StringGen>) that should be used to generate the  
 strings in the list.  
   
 =item count  
   
 The number of list entries to generate.  
   
 =item RETURN  
   
 Returns a list consisting of the specified number of strings.  
   
 =back  
   
 =cut  
   
 sub ListGen {  
     # Get the parameters.  
     my ($pattern, $count) = @_;  
     # Generate the list.  
     my @retVal = ();  
     for (my $i = 0; $i < $count; $i++) {  
         push @retVal, StringGen($pattern);  
     }  
     # Return it.  
5808      return @retVal;      return @retVal;
5809  }  }
5810    

Legend:
Removed from v.1.71  
changed lines
  Added in v.1.99

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3