[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.105, Tue Sep 23 20:43:42 2008 UTC
# Line 6  Line 6 
6      use Data::Dumper;      use Data::Dumper;
7      use XML::Simple;      use XML::Simple;
8      use DBQuery;      use DBQuery;
9      use DBObject;      use ERDBObject;
10      use Stats;      use Stats;
11      use Time::HiRes qw(gettimeofday);      use Time::HiRes qw(gettimeofday);
12      use Digest::MD5 qw(md5_base64);      use Digest::MD5 qw(md5_base64);
13      use FIG;      use CGI;
14        use WikiTools;
15    
16  =head1 Entity-Relationship Database Package  =head1 Entity-Relationship Database Package
17    
# Line 59  Line 60 
60  B<start-position>, which indicates where in the contig that the sequence begins. This attribute  B<start-position>, which indicates where in the contig that the sequence begins. This attribute
61  is implemented as the C<start_position> field in the C<IsMadeUpOf> relation.  is implemented as the C<start_position> field in the C<IsMadeUpOf> relation.
62    
63  The database itself is described by an XML file using the F<ERDatabase.xsd> schema. In addition to  The database itself is described by an XML file. In addition to all the data required to define
64  all the data required to define the entities, relationships, and attributes, the schema provides  the entities, relationships, and attributes, the schema provides space for notes describing
65  space for notes describing the data and what it means. These notes are used by L</ShowMetaData>  the data and what it means. These notes are used by L</ShowMetaData> to generate documentation
66  to generate documentation for the database.  for the database.
67    
68    Special support is provided for text searching. An entity field can be marked as <em>searchable</em>,
69    in which case it will be used to generate a text search index in which the user searches for words
70    in the field instead of a particular field value.
71    
72  Finally, every entity and relationship object has a flag indicating if it is new or old. The object  Finally, every entity and relationship object has a flag indicating if it is new or old. The object
73  is considered I<old> if it was loaded by the L</LoadTables> method. It is considered I<new> if it  is considered I<old> if it was loaded by the L</LoadTables> method. It is considered I<new> if it
74  was inserted by the L</InsertObject> method.  was inserted by the L</InsertObject> method.
75    
 To facilitate testing, the ERDB module supports automatic generation of test data. This process  
 is described in the L</GenerateEntity> and L</GenerateConnection> methods, though it is not yet  
 fully implemented.  
   
76  =head2 XML Database Description  =head2 XML Database Description
77    
78  =head3 Data Types  =head3 Data Types
# Line 101  Line 102 
102    
103  =item text  =item text
104    
105  long string; Text fields cannot be used in indexes or sorting and do not support the  long string; Text fields do not support the normal syntax of filter clauses,
106  normal syntax of filter clauses, but can be up to a billion character in length  but can be up to a billion character in length
107    
108    =item dna
109    
110    long string, used to store DNA and protein sequences
111    
112    =item image
113    
114    long string, used to store encoded image data
115    
116  =item float  =item float
117    
# Line 217  Line 226 
226  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.
227  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.
228    
229    =item special
230    
231    This attribute allows the subclass to assign special meaning for certain fields.
232    The interpretation is up to the subclass itself. Currently, only entity fields
233    can have this attribute.
234    
235  =back  =back
236    
237  =head3 Indexes  =head3 Indexes
238    
239  An entity can have multiple alternate indexes associated with it. The fields must  An entity can have multiple alternate indexes associated with it. The fields in an
240  be from the primary relation. The alternate indexes assist in ordering results  index must all be from the same relation. The alternate indexes assist in searching
241  from a query. A relationship can have up to two indexes-- a I<to-index> and a  on fields other than the entity ID. A relationship has at least two indexes-- a I<to-index> and a
242  I<from-index>. These order the results when crossing the relationship. For  I<from-index> that order the results when crossing the relationship. For
243  example, in the relationship C<HasContig> from C<Genome> to C<Contig>, the  example, in the relationship C<HasContig> from C<Genome> to C<Contig>, the
244  from-index would order the contigs of a ganome, and the to-index would order  from-index would order the contigs of a ganome, and the to-index would order
245  the genomes of a contig. A relationship's index must specify only fields in  the genomes of a contig. In addition, it can have zero or more alternate
246    indexes. A relationship's index must specify only fields in
247  the relationship.  the relationship.
248    
249  The indexes for an entity must be listed inside the B<Indexes> tag. The from-index  The alternate indexes for an entity or relationship must be listed inside the B<Indexes> tag.
250  of a relationship is specified using the B<FromIndex> tag; the to-index is specified  The from-index of a relationship is specified using the B<FromIndex> tag; the to-index is
251  using the B<ToIndex> tag.  specified using the B<ToIndex> tag.
252    
253  Each index can contain a B<Notes> tag. In addition, it will have an B<IndexFields>  Each index can contain a B<Notes> tag. In addition, it will have an B<IndexFields>
254  tag containing the B<IndexField> tags. These specify, in order, the fields used in  tag containing the B<IndexField> tags. These specify, in order, the fields used in
# Line 250  Line 266 
266    
267  =back  =back
268    
269  The B<Index>, B<FromIndex>, and B<ToIndex> tags themselves have no attributes.  The B<FromIndex>, and B<ToIndex> tags have no attributes. The B<Index> tag can
270    have a B<Unique> attribute. If specified, the index will be generated as a unique
271    index.
272    
273  =head3 Object and Field Names  =head3 Object and Field Names
274    
# Line 294  Line 312 
312    
313  A relationship is described by the C<Relationship> tag. Within a relationship,  A relationship is described by the C<Relationship> tag. Within a relationship,
314  there can be a C<Notes> tag, a C<Fields> tag containing the intersection data  there can be a C<Notes> tag, a C<Fields> tag containing the intersection data
315  fields, a C<FromIndex> tag containing the from-index, and a C<ToIndex> tag containing  fields, a C<FromIndex> tag containing the from-index, a C<ToIndex> tag containing
316  the to-index.  the to-index, and an C<Indexes> tag containing the alternate indexes.
317    
318  The C<Relationship> tag has the following attributes.  The C<Relationship> tag has the following attributes.
319    
# Line 328  Line 346 
346    
347  # Table of information about our datatypes. "sqlType" is the corresponding SQL datatype string.  # Table of information about our datatypes. "sqlType" is the corresponding SQL datatype string.
348  # "maxLen" is the maximum permissible length of the incoming string data used to populate a field  # "maxLen" is the maximum permissible length of the incoming string data used to populate a field
349  # of the specified type. "dataGen" is PERL string that will be evaluated if no test data generation  # of the specified type. "avgLen" is the average byte length for estimating
350  # string is specified in the field definition. "avgLen" is the average byte length for estimating  # record sizes. "sort" is the key modifier for the sort command, "notes" is a type description,
351  # record sizes. "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
352  my %TypeTable = ( char =>    { sqlType => 'CHAR(1)',            maxLen => 1,            avgLen =>   1, sort => "",  dataGen => "StringGen('A')" },  # index
353                    int =>     { sqlType => 'INTEGER',            maxLen => 20,           avgLen =>   4, sort => "n", dataGen => "IntGen(0, 99999999)" },  my %TypeTable = ( char =>    { sqlType => 'CHAR(1)',            maxLen => 1,            avgLen =>   1, sort => "",
354                    counter => { sqlType => 'INTEGER UNSIGNED',   maxLen => 20,           avgLen =>   4, sort => "n", dataGen => "IntGen(0, 99999999)" },                                 indexMod =>   0, notes => "single ASCII character"},
355                    string =>  { sqlType => 'VARCHAR(255)',       maxLen => 255,          avgLen => 100, sort => "",  dataGen => "StringGen(IntGen(10,250))" },                    int =>     { sqlType => 'INTEGER',            maxLen => 20,           avgLen =>   4, sort => "n",
356                    text =>    { sqlType => 'TEXT',               maxLen => 1000000000,   avgLen => 500, sort => "",  dataGen => "StringGen(IntGen(80,1000))" },                                 indexMod =>   0, notes => "signed 32-bit integer"},
357                    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",
358                    float =>   { sqlType => 'DOUBLE PRECISION',   maxLen => 40,           avgLen =>   8, sort => "g", dataGen => "FloatGen(0.0, 100.0)" },                                 indexMod =>   0, notes => "unsigned 32-bit integer"},
359                    boolean => { sqlType => 'SMALLINT',           maxLen => 1,            avgLen =>   1, sort => "n", dataGen => "IntGen(0, 1)" },                    image =>    { sqlType => 'TEXT',               maxLen => 1000000000,   avgLen => 100000, sort => "",
360                                   indexMod => 255, notes => "UUencoded image, suitable for import into GD, should never be indexed"},
361                      dna =>      { sqlType => 'TEXT',               maxLen => 1000000000,   avgLen => 100000, sort => "",
362                                   indexMod => 255, notes => "DNA or protein sequence, should never be indexed"},
363                      string =>  { sqlType => 'VARCHAR(255)',       maxLen => 255,          avgLen => 100, sort => "",
364                                   indexMod =>   0, notes => "character string, 0 to 255 characters"},
365                      text =>    { sqlType => 'TEXT',               maxLen => 1000000000,   avgLen => 500, sort => "",
366                                   indexMod => 255, notes => "character string, nearly unlimited length, only first 255 characters are indexed"},
367                      date =>    { sqlType => 'BIGINT',             maxLen => 80,           avgLen =>   8, sort => "n",
368                                   indexMod =>   0, notes => "signed, 64-bit integer"},
369                      float =>   { sqlType => 'DOUBLE PRECISION',   maxLen => 40,           avgLen =>   8, sort => "g",
370                                   indexMod =>   0, notes => "64-bit double precision floating-point number"},
371                      boolean => { sqlType => 'SMALLINT',           maxLen => 1,            avgLen =>   1, sort => "n",
372                                   indexMod =>   0, notes => "boolean value: 0 if false, 1 if true"},
373                   'hash-string' =>                   'hash-string' =>
374                               { sqlType => 'VARCHAR(22)',        maxLen => 22,           avgLen =>  22, sort => "",  dataGen => "SringGen(22)" },                               { sqlType => 'VARCHAR(22)',        maxLen => 22,           avgLen =>  22, sort => "",
375                                   indexMod =>   0, notes => "string stored in digested form, used for certain types of key fields"},
376                   'id-string' =>                   'id-string' =>
377                               { sqlType => 'VARCHAR(25)',        maxLen => 25,           avgLen =>  25, sort => "",  dataGen => "SringGen(22)" },                               { sqlType => 'VARCHAR(25)',        maxLen => 25,           avgLen =>  25, sort => "",
378                                   indexMod =>   0, notes => "character string, 0 to 25 characters"},
379                   'key-string' =>                   'key-string' =>
380                               { sqlType => 'VARCHAR(40)',        maxLen => 40,           avgLen =>  10, sort => "",  dataGen => "StringGen(IntGen(10,40))" },                               { sqlType => 'VARCHAR(40)',        maxLen => 40,           avgLen =>  10, sort => "",
381                                   indexMod =>   0, notes => "character string, 0 to 40 characters"},
382                   'name-string' =>                   'name-string' =>
383                               { sqlType => 'VARCHAR(80)',        maxLen => 80,           avgLen =>  40, sort => "",  dataGen => "StringGen(IntGen(10,80))" },                               { sqlType => 'VARCHAR(80)',        maxLen => 80,           avgLen =>  40, sort => "",
384                                   indexMod =>   0, notes => "character string, 0 to 80 characters"},
385                   'medium-string' =>                   'medium-string' =>
386                               { sqlType => 'VARCHAR(160)',       maxLen => 160,          avgLen =>  40, sort => "",  dataGen => "StringGen(IntGen(10,160))" },                               { sqlType => 'VARCHAR(160)',       maxLen => 160,          avgLen =>  40, sort => "",
387                                   indexMod =>   0, notes => "character string, 0 to 160 characters"},
388                     'long-string' =>
389                                 { sqlType => 'VARCHAR(500)',       maxLen => 500,          avglen => 255, sort => "",
390                                   indexMod =>   0, notes => "character string, 0 to 500 characters"},
391                  );                  );
392    
393  # Table translating arities into natural language.  # Table translating arities into natural language.
# Line 357  Line 396 
396                     'MM' => 'many-to-many'                     'MM' => 'many-to-many'
397                   );                   );
398    
399  # Table for interpreting string patterns.  # Options for XML input and output.
400    
401    my %XmlOptions = (GroupTags =>  { Relationships => 'Relationship',
402                                      Entities => 'Entity',
403                                      Fields => 'Field',
404                                      Indexes => 'Index',
405                                      IndexFields => 'IndexField',
406                                      Issues => 'Issue',
407                                      Shapes => 'Shape'
408                                    },
409                      KeyAttr =>    { Relationship => 'name',
410                                      Entity => 'name',
411                                      Field => 'name',
412                                      Shape => 'name'
413                                    },
414                      SuppressEmpty => 1,
415                     );
416    
417  my %PictureTable = ( 'A' => "abcdefghijklmnopqrstuvwxyz",  my %XmlInOpts  = (
418                       '9' => "0123456789",                    ForceArray => [qw(Field Index IndexField Relationship Entity Shape)],
419                       'X' => "abcdefghijklmnopqrstuvwxyz0123456789",                    ForceContent => 1,
420                       'V' => "aeiou",                    NormalizeSpace => 2,
421                       'K' => "bcdfghjklmnoprstvwxyz"                   );
422    my %XmlOutOpts = (
423                      RootName => 'Database',
424                      XMLDecl => 1,
425                     );                     );
426    
427  =head2 Public Methods  =head2 Public Methods
428    
429  =head3 new  =head3 new
430    
431  C<< my $database = ERDB->new($dbh, $metaFileName); >>      my $database = ERDB->new($dbh, $metaFileName);
432    
433  Create a new ERDB object.  Create a new ERDB object.
434    
# Line 390  Line 448 
448    
449  sub new {  sub new {
450      # Get the parameters.      # Get the parameters.
451      my ($class, $dbh, $metaFileName, $options) = @_;      my ($class, $dbh, $metaFileName, %options) = @_;
452      # Load the meta-data.      # Load the meta-data.
453      my $metaData = _LoadMetaData($metaFileName);      my $metaData = _LoadMetaData($metaFileName);
454      # Create the object.      # Create the object.
# Line 404  Line 462 
462    
463  =head3 ShowMetaData  =head3 ShowMetaData
464    
465  C<< $erdb->ShowMetaData($fileName); >>      $erdb->ShowMetaData($fileName);
466    
467  This method outputs a description of the database. This description can be used to help users create  This method outputs a description of the database. This description can be used to help users create
468  the data to be loaded into the relations.  the data to be loaded into the relations.
# Line 445  Line 503 
503    
504  =head3 DisplayMetaData  =head3 DisplayMetaData
505    
506  C<< my $html = $erdb->DisplayMetaData(); >>      my $html = $erdb->DisplayMetaData();
507    
508  Return an HTML description of the database. This description can be used to help users create  Return an HTML description of the database. This description can be used to help users create
509  the data to be loaded into the relations and form queries. The output is raw includable HTML  the data to be loaded into the relations and form queries. The output is raw includable HTML
# Line 506  Line 564 
564          my $entityData = $entityList->{$key};          my $entityData = $entityList->{$key};
565          # If there's descriptive text, display it.          # If there's descriptive text, display it.
566          if (my $notes = $entityData->{Notes}) {          if (my $notes = $entityData->{Notes}) {
567              $retVal .= "<p>" . _HTMLNote($notes->{content}) . "</p>\n";              $retVal .= "<p>" . HTMLNote($notes->{content}) . "</p>\n";
568          }          }
569          # Now we want a list of the entity's relationships. First, we set up the relationship subsection.          # See if we need a list of the entity's relationships.
570            my $relCount = keys %{$relationshipList};
571            if ($relCount > 0) {
572                # First, we set up the relationship subsection.
573          $retVal .= "<h4>Relationships for <b>$key</b></h4>\n<ul>\n";          $retVal .= "<h4>Relationships for <b>$key</b></h4>\n<ul>\n";
574          # Loop through the relationships.          # Loop through the relationships.
575          for my $relationship (sort keys %{$relationshipList}) {          for my $relationship (sort keys %{$relationshipList}) {
# Line 524  Line 585 
585          }          }
586          # Close off the relationship list.          # Close off the relationship list.
587          $retVal .= "</ul>\n";          $retVal .= "</ul>\n";
588            }
589          # Get the entity's relations.          # Get the entity's relations.
590          my $relationList = $entityData->{Relations};          my $relationList = $entityData->{Relations};
591          # Create a header for the relation subsection.          # Create a header for the relation subsection.
# Line 563  Line 625 
625          $retVal .= "</p>\n";          $retVal .= "</p>\n";
626          # If there are notes on this relationship, display them.          # If there are notes on this relationship, display them.
627          if (my $notes = $relationshipStructure->{Notes}) {          if (my $notes = $relationshipStructure->{Notes}) {
628              $retVal .= "<p>" . _HTMLNote($notes->{content}) . "</p>\n";              $retVal .= "<p>" . HTMLNote($notes->{content}) . "</p>\n";
629          }          }
630          # Generate the relationship's relation table.          # Generate the relationship's relation table.
631          my $htmlString = _ShowRelationTable($key, $relationshipStructure->{Relations}->{$key});          my $htmlString = _ShowRelationTable($key, $relationshipStructure->{Relations}->{$key});
# Line 597  Line 659 
659    
660  =head3 DumpMetaData  =head3 DumpMetaData
661    
662  C<< $erdb->DumpMetaData(); >>      $erdb->DumpMetaData();
663    
664  Return a dump of the metadata structure.  Return a dump of the metadata structure.
665    
# Line 610  Line 672 
672      return Data::Dumper::Dumper($self->{_metaData});      return Data::Dumper::Dumper($self->{_metaData});
673  }  }
674    
675    =head3 GenerateWikiData
676    
677        my @wikiLines = $erdb->GenerateWikiData();
678    
679    Build a description of the database for the wiki. The database will be
680    organized into a single page, with sections for each entity and relationship.
681    The return value is a list of text lines.
682    
683    =cut
684    
685    sub GenerateWikiData {
686        # Get the parameters.
687        my ($self) = @_;
688        # We'll build the wiki text in here.
689        my @retVal = ();
690        # Get the metadata object.
691        my $metadata = $self->{_metaData};
692        # Get the title string. This will become the page name.
693        my $title = $metadata->{Title}->{content};
694        # Get the entity and relationship lists.
695        my $entityList = $metadata->{Entities};
696        my $relationshipList = $metadata->{Relationships};
697        my $shapeList = $metadata->{Shapes};
698        # Start with the introductory text.
699        push @retVal, WikiTools::Heading(2, "Introduction");
700        if (my $notes = $metadata->{Notes}) {
701            push @retVal, WikiNote($notes->{content});
702        }
703        # Generate issue list.
704        if (my $issues = $metadata->{Issues}) {
705            push @retVal, WikiTools::Heading(3, 'Issues');
706            push @retVal, WikiTools::List(map { $_->{content} } @{$issues});
707        }
708        # Start the entity section.
709        push @retVal, WikiTools::Heading(2, "Entities");
710        # Loop through the entities. Note that unlike the situation with HTML, we
711        # don't need to generate the table of contents manually, just the data
712        # itself.
713        for my $key (sort keys %$entityList) {
714            # Create a header for this entity.
715            push @retVal, "", WikiTools::Heading(3, $key);
716            # Get the entity data.
717            my $entityData = $entityList->{$key};
718            # Plant the notes here, if there are any.
719            push @retVal, _ObjectNotes($entityData);
720            # Now we list the entity's relationships (if any). First, we build a list
721            # of the relationships relevant to this entity.
722            my @rels = ();
723            for my $rel (sort keys %$relationshipList) {
724                my $relStructure = $relationshipList->{$rel};
725                if ($relStructure->{from} eq $key || $relStructure->{to} eq $key) {
726                    # Get the relationship sentence.
727                    my $relSentence = _ComputeRelationshipSentence($rel, $relStructure);
728                    # Linkify it.
729                    my $linkedRel = WikiTools::LinkMarkup("#$rel", $rel);
730                    $relSentence =~ s/$rel/$linkedRel/;
731                    push @rels, $relSentence;
732                }
733            }
734            # Add the relationships as a Wiki list.
735            push @retVal, WikiTools::List(@rels);
736            # Get the entity's relations.
737            my $relationList = $entityData->{Relations};
738            # Loop through the relations, displaying them.
739            for my $relation (sort keys %{$relationList}) {
740                my $wikiString = _WikiRelationTable($relation, $relationList->{$relation});
741                push @retVal, $wikiString;
742            }
743        }
744        # Now the entities are documented. Next we do the relationships.
745        push @retVal, WikiTools::Heading(2, "Relationships");
746        for my $key (sort keys %$relationshipList) {
747            my $relationshipData = $relationshipList->{$key};
748            # Create the relationship heading.
749            push @retVal, WikiTools::Heading(3, $key);
750            # Describe the relationship arity. Note there's a bit of trickiness involving recursive
751            # many-to-many relationships. In a normal many-to-many we use two sentences to describe
752            # the arity (one for each direction). This is a bad idea for a recursive relationship,
753            # since both sentences will say the same thing.
754            my $arity = $relationshipData->{arity};
755            my $fromEntity = $relationshipData->{from};
756            my $toEntity = $relationshipData->{to};
757            my @listElements = ();
758            my $boldCode = WikiTools::BoldCode();
759            if ($arity eq "11") {
760                push @listElements, "Each $boldCode$fromEntity$boldCode relates to at most one $boldCode$toEntity$boldCode.";
761            } else {
762                push @listElements, "Each $boldCode$fromEntity$boldCode relates to multiple $boldCode${toEntity}s$boldCode.";
763                if ($arity eq "MM" && $fromEntity ne $toEntity) {
764                    push @listElements, "Each $boldCode$toEntity$boldCode relates to multiple $boldCode${fromEntity}s$boldCode.";
765                }
766            }
767            push @retVal, WikiTools::List(@listElements);
768            # Plant the notes here, if there are any.
769            push @retVal, _ObjectNotes($relationshipData);
770            # Finally, the relationship table.
771            my $wikiString = _WikiRelationTable($key, $relationshipData->{Relations}->{$key});
772            push @retVal, $wikiString;
773        }
774        # Now loop through the miscellaneous shapes.
775        if ($shapeList) {
776            push @retVal, WikiTools::Heading(2, "Miscellaneous");
777            for my $shape (sort keys %$shapeList) {
778                push @retVal, WikiTools::Heading(3, $shape);
779                my $shapeData = $shapeList->{$shape};
780                push @retVal, _ObjectNotes($shapeData);
781            }
782        }
783        # All done. Return the lines.
784        return @retVal;
785    }
786    
787    
788    =head3 CreatePPO
789    
790        ERDB::CreatePPO($erdbXMLFile, $ppoXMLFile);
791    
792    Create a PPO XML file from an ERDB data definition XML file. At the
793    current time, the PPO XML file can be used to create a database with
794    similar functionality. Eventually, the PPO will be able to use the
795    created XML to access the live ERDB database.
796    
797    =over 4
798    
799    =item erdbXMLFile
800    
801    Name of the XML data definition file for the ERDB database. This
802    file must exist.
803    
804    =item ppoXMLFile
805    
806    Output file for the PPO XML definition. If this file exists, it
807    will be overwritten.
808    
809    =back
810    
811    =cut
812    
813    sub CreatePPO {
814        # Get the parameters.
815        my ($erdbXMLFile, $ppoXMLFile) = @_;
816        # First, we want to slurp in the ERDB XML file in its raw form.
817        my $xml = ReadMetaXML($erdbXMLFile);
818        # Create a variable to hold all of the objects in the PPO project.
819        my @objects = ();
820        # Get the relationship hash.
821        my $relationships = $xml->{Relationships};
822        # Loop through the entities.
823        my $entities = $xml->{Entities};
824        for my $entityName (keys %{$entities}) {
825            # Get the entity's data structures.
826            my $entityObject = $entities->{$entityName};
827            # We put the object's fields in here, according to their type.
828            my (@object_refs, @scalars, @indexes, @arrays);
829            # Create the ID field for the entity. We get the key type from the
830            # entity object and compute the corresponding SQL type.
831            my $type = $TypeTable{$entityObject->{keyType}}->{sqlType};
832            push @scalars, { label => 'id', type => $type };
833            # Loop through the entity fields.
834            for my $fieldName ( keys %{$entityObject->{Fields}} ) {
835                # Get the field object.
836                my $fieldObject = $entityObject->{Fields}->{$fieldName};
837                # Convert it to a scalar tag.
838                my $scalar = _CreatePPOField($fieldName, $fieldObject);
839                # If we have a relation, this field is stored in an array.
840                # otherwise, it is a scalar. The array tag has scalars
841                # stored as an XML array. In ERDB, there is only ever one,
842                # but PPO can have more.
843                my $relation = $fieldObject->{relation};
844                if ($relation) {
845                    push @arrays, { scalar => [$scalar] };
846                } else {
847                    push @scalars, $scalar;
848                }
849            }
850            # Loop through the relationships. If this entity is the to-entity
851            # on a relationship of 1M arity, then it is implemented as a PPO
852            # object reference.
853            for my $relationshipName (keys %{$relationships}) {
854                # Get the relationship data.
855                my $relationshipData = $relationships->{$relationshipName};
856                # If we have a from for this entity and an arity of 1M, we
857                # have an object reference.
858                if ($relationshipData->{to} eq $entityName &&
859                    $relationshipData->{arity} eq '1M') {
860                    # Build the object reference tag.
861                    push @object_refs, { label => $relationshipName,
862                                         type => $relationshipData->{from} };
863                }
864            }
865            # Create the indexes.
866            my $indexList = $entityObject->{Indexes};
867            push @indexes, map { _CreatePPOIndex($_) } @{$indexList};
868            # Build the object XML tree.
869            my $object = { label => $entityName,
870                           object_ref => \@object_refs,
871                           scalar => \@scalars,
872                           index => \@indexes,
873                           array => \@arrays
874                          };
875            # Push the object onto the objects list.
876            push @objects, $object;
877        }
878        # Loop through the relationships, searching for MMs. The 1Ms were
879        # already handled by the entity search above.
880        for my $relationshipName (keys %{$relationships}) {
881            # Get this relationship's object.
882            my $relationshipObject = $relationships->{$relationshipName};
883            # Only proceed if it's many-to-many.
884            if ($relationshipObject->{arity} eq 'MM') {
885                # Create the tag lists for the relationship object.
886                my (@object_refs, @scalars, @indexes);
887                # The relationship will be created as an object with object
888                # references for its links to the participating entities.
889                my %links = ( from_link => $relationshipObject->{from},
890                              to_link => $relationshipObject->{to} );
891                for my $link (keys %links) {
892                    # Create an object_ref tag for this piece of the
893                    # relationship (from or to).
894                    my $object_ref = { label => $link,
895                                       type => $links{$link} };
896                    push @object_refs, $object_ref;
897                }
898                # Loop through the intersection data fields, creating scalar tags.
899                # There are no fancy array tags in a relationship.
900                for my $fieldName (keys %{$relationshipObject->{Fields}}) {
901                    my $fieldObject = $relationshipObject->{Fields}->{$fieldName};
902                    push @scalars, _CreatePPOField($fieldName, $fieldObject);
903                }
904                # Finally, the indexes: currently we cannot support the to-index and
905                # from-index in PPO, so we just process the alternate indexes.
906                my $indexList = $relationshipObject->{Indexes};
907                push @indexes, map { _CreatePPOIndex($_) } @{$indexList};
908                # Wrap up all the stuff about this relationship.
909                my $object = { label => $relationshipName,
910                               scalar => \@scalars,
911                               object_ref => \@object_refs,
912                               index => \@indexes
913                             };
914                # Push it into the object list.
915                push @objects, $object;
916            }
917        }
918        # Compute a title.
919        my $title;
920        if ($erdbXMLFile =~ /(\/|^)([^\/]+)DBD\.xml/) {
921            # Here we have a standard file name we can use for a title.
922            $title = $2;
923        } else {
924            # Here the file name is non-standard, so we carve up the
925            # database title.
926            $title = $xml->{Title}->{content};
927            $title =~ s/\s\.,//g;
928        }
929        # Wrap up the XML as a project.
930        my $ppoXML = { project => { label => $title,
931                                    object => \@objects }};
932        # Write out the results.
933        my $ppoString = XML::Simple::XMLout($ppoXML,
934                                            AttrIndent => 1,
935                                            KeepRoot => 1);
936        Tracer::PutFile($ppoXMLFile, [ $ppoString ]);
937    }
938    
939    =head3 FindIndexForEntity
940    
941        my $indexFound = ERDB::FindIndexForEntity($xml, $entityName, $attributeName);
942    
943    This method locates the entry in an entity's index list that begins with the
944    specified attribute name. If the entity has no index list, one will be
945    created. This method works on raw XML, not a live ERDB object.
946    
947    =over 4
948    
949    =item xml
950    
951    The raw XML structure defining the database.
952    
953    =item entityName
954    
955    The name of the relevant entity.
956    
957    =item attributeName
958    
959    The name of the attribute relevant to the search.
960    
961    =item RETURN
962    
963    The numerical index in the index list of the index entry for the specified entity and
964    attribute, or C<undef> if no such index exists.
965    
966    =back
967    
968    =cut
969    
970    sub FindIndexForEntity {
971        # Get the parameters.
972        my ($xml, $entityName, $attributeName) = @_;
973        # Declare the return variable.
974        my $retVal;
975        # Get the named entity.
976        my $entityData = $xml->{Entities}->{$entityName};
977        if (! $entityData) {
978            Confess("Entity $entityName not found in DBD structure.");
979        } else {
980            # Insure it has an index list.
981            if (! exists $entityData->{Indexes}) {
982                $entityData->{Indexes} = [];
983            } else {
984                # Search for the desired index.
985                my $indexList = $entityData->{Indexes};
986                my $n = scalar @{$indexList};
987                Trace("Searching $n indexes in index list for $entityName.") if T(2);
988                # We use an indexed FOR here because we're returning an
989                # index number instead of an object. We do THAT so we can
990                # delete the index from the list if needed.
991                for (my $i = 0; $i < $n && !defined($retVal); $i++) {
992                    my $index = $indexList->[$i];
993                    my $fields = $index->{IndexFields};
994                    # Technically this IF should be safe (that is, we are guaranteed
995                    # the existence of a "$fields->[0]"), because when we load the XML
996                    # we have SuppressEmpty specified.
997                    if ($fields->[0]->{name} eq $attributeName) {
998                        $retVal = $i;
999                    }
1000                }
1001            }
1002        }
1003        Trace("Index for $attributeName of $entityName found at position $retVal.") if defined($retVal) && T(3);
1004        Trace("Index for $attributeName not found in $entityName.") if !defined($retVal) && T(3);
1005        # Return the result.
1006        return $retVal;
1007    }
1008    
1009  =head3 CreateTables  =head3 CreateTables
1010    
1011  C<< $erdb->CreateTables(); >>      $erdb->CreateTables();
1012    
1013  This method creates the tables for the database from the metadata structure loaded by the  This method creates the tables for the database from the metadata structure loaded by the
1014  constructor. It is expected this function will only be used on rare occasions, when the  constructor. It is expected this function will only be used on rare occasions, when the
# Line 629  Line 1025 
1025      # Loop through the relations.      # Loop through the relations.
1026      for my $relationName (@relNames) {      for my $relationName (@relNames) {
1027          # Create a table for this relation.          # Create a table for this relation.
1028          $self->CreateTable($relationName);          $self->CreateTable($relationName, 1);
1029          Trace("Relation $relationName created.") if T(2);          Trace("Relation $relationName created.") if T(2);
1030      }      }
1031  }  }
1032    
1033  =head3 CreateTable  =head3 CreateTable
1034    
1035  C<< $erdb->CreateTable($tableName, $indexFlag, $estimatedRows); >>      $erdb->CreateTable($tableName, $indexFlag, $estimatedRows);
1036    
1037  Create the table for a relation and optionally create its indexes.  Create the table for a relation and optionally create its indexes.
1038    
# Line 678  Line 1074 
1074          # Push the result into the field list.          # Push the result into the field list.
1075          push @fieldList, $fieldString;          push @fieldList, $fieldString;
1076      }      }
     # If this is a root table, add the "new_record" flag. It defaults to 0, so  
     if ($rootFlag) {  
         push @fieldList, "new_record $TypeTable{boolean}->{sqlType} NOT NULL DEFAULT 0";  
     }  
1077      # Convert the field list into a comma-delimited string.      # Convert the field list into a comma-delimited string.
1078      my $fieldThing = join(', ', @fieldList);      my $fieldThing = join(', ', @fieldList);
1079      # Insure the table is not already there.      # Insure the table is not already there.
# Line 692  Line 1084 
1084      my $estimation = undef;      my $estimation = undef;
1085      if ($estimatedRows) {      if ($estimatedRows) {
1086          $estimation = [$self->EstimateRowSize($relationName), $estimatedRows];          $estimation = [$self->EstimateRowSize($relationName), $estimatedRows];
1087            Trace("$estimation->[1] rows of $estimation->[0] bytes each.") if T(3);
1088      }      }
1089      # Create the table.      # Create the table.
1090      Trace("Creating table $relationName: $fieldThing") if T(2);      Trace("Creating table $relationName: $fieldThing") if T(2);
# Line 706  Line 1099 
1099    
1100  =head3 VerifyFields  =head3 VerifyFields
1101    
1102  C<< my $count = $erdb->VerifyFields($relName, \@fieldList); >>      my $count = $erdb->VerifyFields($relName, \@fieldList);
1103    
1104  Run through the list of proposed field values, insuring that all the character fields are  Run through the list of proposed field values, insuring that all the character fields are
1105  below the maximum length. If any fields are too long, they will be truncated in place.  below the maximum length. If any fields are too long, they will be truncated in place.
# Line 749  Line 1142 
1142              my $oldString = $fieldList->[$i];              my $oldString = $fieldList->[$i];
1143              if (length($oldString) > $maxLen) {              if (length($oldString) > $maxLen) {
1144                  # Here it's too big, so we truncate it.                  # Here it's too big, so we truncate it.
1145                  Trace("Truncating field $i in relation $relName to $maxLen characters from \"$oldString\".") if T(1);                  Trace("Truncating field $i ($fieldTypes->[$i]->{name}) in relation $relName to $maxLen characters from \"$oldString\".") if T(1);
1146                  $fieldList->[$i] = substr $oldString, 0, $maxLen;                  $fieldList->[$i] = substr $oldString, 0, $maxLen;
1147                  $retVal++;                  $retVal++;
1148              }              }
# Line 761  Line 1154 
1154    
1155  =head3 DigestFields  =head3 DigestFields
1156    
1157  C<< $erdb->DigestFields($relName, $fieldList); >>      $erdb->DigestFields($relName, $fieldList);
1158    
1159  Digest the strings in the field list that correspond to data type C<hash-string> in the  Digest the strings in the field list that correspond to data type C<hash-string> in the
1160  specified relation.  specified relation.
# Line 801  Line 1194 
1194    
1195  =head3 DigestKey  =head3 DigestKey
1196    
1197  C<< my $digested = $erdb->DigestKey($keyValue); >>      my $digested = $erdb->DigestKey($keyValue);
1198    
1199  Return the digested value of a symbolic key. The digested value can then be plugged into a  Return the digested value of a symbolic key. The digested value can then be plugged into a
1200  key-based search into a table with key-type hash-string.  key-based search into a table with key-type hash-string.
# Line 834  Line 1227 
1227    
1228  =head3 CreateIndex  =head3 CreateIndex
1229    
1230  C<< $erdb->CreateIndex($relationName); >>      $erdb->CreateIndex($relationName);
1231    
1232  Create the indexes for a relation. If a table is being loaded from a large source file (as  Create the indexes for a relation. If a table is being loaded from a large source file (as
1233  is the case in L</LoadTable>), it is sometimes best to create the indexes after the load.  is the case in L</LoadTable>), it is sometimes best to create the indexes after the load.
# Line 855  Line 1248 
1248      for my $indexName (keys %{$indexHash}) {      for my $indexName (keys %{$indexHash}) {
1249          my $indexData = $indexHash->{$indexName};          my $indexData = $indexHash->{$indexName};
1250          # Get the index's field list.          # Get the index's field list.
1251          my @fieldList = _FixNames(@{$indexData->{IndexFields}});          my @rawFields = @{$indexData->{IndexFields}};
1252            # Get a hash of the relation's field types.
1253            my %types = map { $_->{name} => $_->{type} } @{$relationData->{Fields}};
1254            # We need to check for text fields so we can append a length limitation for them. To do
1255            # that, we need the relation's field list.
1256            my $relFields = $relationData->{Fields};
1257            for (my $i = 0; $i <= $#rawFields; $i++) {
1258                # Get the field type.
1259                my $field = $rawFields[$i];
1260                my $type = $types{$field};
1261                # Ask if it requires using prefix notation for the index.
1262                my $mod = $TypeTable{$type}->{indexMod};
1263                Trace("Field $field ($i) in $relationName has type $type and indexMod $mod.") if T(3);
1264                if ($mod) {
1265                    # Append the prefix length to the field name,
1266                    $rawFields[$i] .= "($mod)";
1267                }
1268            }
1269            my @fieldList = _FixNames(@rawFields);
1270          my $flds = join(', ', @fieldList);          my $flds = join(', ', @fieldList);
1271          # Get the index's uniqueness flag.          # Get the index's uniqueness flag.
1272          my $unique = (exists $indexData->{Unique} ? 'unique' : undef);          my $unique = (exists $indexData->{Unique} ? 'unique' : undef);
# Line 870  Line 1281 
1281      }      }
1282  }  }
1283    
1284    =head3 GetSecondaryFields
1285    
1286        my %fieldTuples = $erdb->GetSecondaryFields($entityName);
1287    
1288    This method will return a list of the name and type of each of the secondary
1289    fields for a specified entity. Secondary fields are stored in two-column tables
1290    in addition to the primary entity table. This enables the field to have no value
1291    or to have multiple values.
1292    
1293    =over 4
1294    
1295    =item entityName
1296    
1297    Name of the entity whose secondary fields are desired.
1298    
1299    =item RETURN
1300    
1301    Returns a hash mapping the field names to their field types.
1302    
1303    =back
1304    
1305    =cut
1306    
1307    sub GetSecondaryFields {
1308        # Get the parameters.
1309        my ($self, $entityName) = @_;
1310        # Declare the return variable.
1311        my %retVal = ();
1312        # Look for the entity.
1313        my $table = $self->GetFieldTable($entityName);
1314        # Loop through the fields, pulling out the secondaries.
1315        for my $field (sort keys %{$table}) {
1316            if ($table->{$field}->{relation} ne $entityName) {
1317                # Here we have a secondary field.
1318                $retVal{$field} = $table->{$field}->{type};
1319            }
1320        }
1321        # Return the result.
1322        return %retVal;
1323    }
1324    
1325    =head3 GetFieldRelationName
1326    
1327        my $name = $erdb->GetFieldRelationName($objectName, $fieldName);
1328    
1329    Return the name of the relation containing a specified field.
1330    
1331    =over 4
1332    
1333    =item objectName
1334    
1335    Name of the entity or relationship containing the field.
1336    
1337    =item fieldName
1338    
1339    Name of the relevant field in that entity or relationship.
1340    
1341    =item RETURN
1342    
1343    Returns the name of the database relation containing the field, or C<undef> if
1344    the field does not exist.
1345    
1346    =back
1347    
1348    =cut
1349    
1350    sub GetFieldRelationName {
1351        # Get the parameters.
1352        my ($self, $objectName, $fieldName) = @_;
1353        # Declare the return variable.
1354        my $retVal;
1355        # Get the object field table.
1356        my $table = $self->GetFieldTable($objectName);
1357        # Only proceed if the field exists.
1358        if (exists $table->{$fieldName}) {
1359            # Determine the name of the relation that contains this field.
1360            $retVal = $table->{$fieldName}->{relation};
1361        }
1362        # Return the result.
1363        return $retVal;
1364    }
1365    
1366    =head3 DeleteValue
1367    
1368        my $numDeleted = $erdb->DeleteValue($entityName, $id, $fieldName, $fieldValue);
1369    
1370    Delete secondary field values from the database. This method can be used to delete all
1371    values of a specified field for a particular entity instance, or only a single value.
1372    
1373    Secondary fields are stored in two-column relations separate from an entity's primary
1374    table, and as a result a secondary field can legitimately have no value or multiple
1375    values. Therefore, it makes sense to talk about deleting secondary fields where it
1376    would not make sense for primary fields.
1377    
1378    =over 4
1379    
1380    =item entityName
1381    
1382    Name of the entity from which the fields are to be deleted.
1383    
1384    =item id
1385    
1386    ID of the entity instance to be processed. If the instance is not found, this
1387    method will have no effect. If C<undef> is specified, all values for all of
1388    the entity instances will be deleted.
1389    
1390    =item fieldName
1391    
1392    Name of the field whose values are to be deleted.
1393    
1394    =item fieldValue (optional)
1395    
1396    Value to be deleted. If not specified, then all values of the specified field
1397    will be deleted for the entity instance. If specified, then only the values which
1398    match this parameter will be deleted.
1399    
1400    =item RETURN
1401    
1402    Returns the number of rows deleted.
1403    
1404    =back
1405    
1406    =cut
1407    
1408    sub DeleteValue {
1409        # Get the parameters.
1410        my ($self, $entityName, $id, $fieldName, $fieldValue) = @_;
1411        # Declare the return value.
1412        my $retVal = 0;
1413        # We need to set up an SQL command to do the deletion. First, we
1414        # find the name of the field's relation.
1415        my $table = $self->GetFieldTable($entityName);
1416        my $field = $table->{$fieldName};
1417        my $relation = $field->{relation};
1418        # Make sure this is a secondary field.
1419        if ($relation eq $entityName) {
1420            Confess("Cannot delete values of $fieldName for $entityName.");
1421        } else {
1422            # Set up the SQL command to delete all values.
1423            my $sql = "DELETE FROM $relation";
1424            # Build the filter.
1425            my @filters = ();
1426            my @parms = ();
1427            # Check for a filter by ID.
1428            if (defined $id) {
1429                push @filters, "id = ?";
1430                push @parms, $id;
1431            }
1432            # Check for a filter by value.
1433            if (defined $fieldValue) {
1434                push @filters, "$fieldName = ?";
1435                push @parms, $fieldValue;
1436            }
1437            # Append the filters to the command.
1438            if (@filters) {
1439                $sql .= " WHERE " . join(" AND ", @filters);
1440            }
1441            # Execute the command.
1442            my $dbh = $self->{_dbh};
1443            $retVal = $dbh->SQL($sql, 0, @parms);
1444        }
1445        # Return the result.
1446        return $retVal;
1447    }
1448    
1449  =head3 LoadTables  =head3 LoadTables
1450    
1451  C<< my $stats = $erdb->LoadTables($directoryName, $rebuild); >>      my $stats = $erdb->LoadTables($directoryName, $rebuild);
1452    
1453  This method will load the database tables from a directory. The tables must already have been created  This method will load the database tables from a directory. The tables must already have been created
1454  in the database. (This can be done by calling L</CreateTables>.) The caller passes in a directory name;  in the database. (This can be done by calling L</CreateTables>.) The caller passes in a directory name;
# Line 932  Line 1508 
1508    
1509  =head3 GetTableNames  =head3 GetTableNames
1510    
1511  C<< my @names = $erdb->GetTableNames; >>      my @names = $erdb->GetTableNames;
1512    
1513  Return a list of the relations required to implement this database.  Return a list of the relations required to implement this database.
1514    
# Line 949  Line 1525 
1525    
1526  =head3 GetEntityTypes  =head3 GetEntityTypes
1527    
1528  C<< my @names = $erdb->GetEntityTypes; >>      my @names = $erdb->GetEntityTypes;
1529    
1530  Return a list of the entity type names.  Return a list of the entity type names.
1531    
# Line 964  Line 1540 
1540      return sort keys %{$entityList};      return sort keys %{$entityList};
1541  }  }
1542    
1543    
1544    =head3 GetConnectingRelationships
1545    
1546        my @list = $erdb->GetConnectingRelationships($entityName);
1547    
1548    Return a list of the relationships connected to the specified entity.
1549    
1550    =over 4
1551    
1552    =item entityName
1553    
1554    Entity whose connected relationships are desired.
1555    
1556    =item RETURN
1557    
1558    Returns a list of the relationships that originate from the entity.
1559    If the entity is on the from end, it will return the relationship
1560    name. If the entity is on the to end it will return the converse of
1561    the relationship name.
1562    
1563    =back
1564    
1565    =cut
1566    
1567    sub GetConnectingRelationships {
1568        # Get the parameters.
1569        my ($self, $entityName) = @_;
1570        # Declare the return variable.
1571        my @retVal;
1572        # Get the relationship list.
1573        my $relationships = $self->{_metaData}->{Relationships};
1574        # Find the entity.
1575        my $entity = $self->{_metaData}->{Entities}->{$entityName};
1576        # Only proceed if the entity exists.
1577        if (! defined $entity) {
1578            Trace("Entity $entityName not found.") if T(3);
1579        } else {
1580            # Loop through the relationships.
1581            my @rels = keys %$relationships;
1582            Trace(scalar(@rels) . " relationships found in connection search.") if T(3);
1583            for my $relationshipName (@rels) {
1584                my $relationship = $relationships->{$relationshipName};
1585                if ($relationship->{from} eq $entityName) {
1586                    # Here we have a forward relationship.
1587                    push @retVal, $relationshipName;
1588                } elsif ($relationship->{to} eq $entityName) {
1589                    # Here we have a backward relationship. In this case, the
1590                    # converse relationship name is preferred if it exists.
1591                    my $converse = $relationship->{converse} || $relationshipName;
1592                    push @retVal, $converse;
1593                }
1594            }
1595        }
1596        # Return the result.
1597        return @retVal;
1598    }
1599    
1600    
1601    =head3 GetDataTypes
1602    
1603        my %types = ERDB::GetDataTypes();
1604    
1605    Return a table of ERDB data types. The table returned is a hash of hashes.
1606    The keys of the big hash are the datatypes. Each smaller hash has several
1607    values used to manage the data. The most interesting is the SQL type (key
1608    C<sqlType>) and the descriptive node (key C<notes>).
1609    
1610    Note that changing the values in the smaller hashes will seriously break
1611    things, so this data should be treated as read-only.
1612    
1613    =cut
1614    
1615    sub GetDataTypes {
1616        return %TypeTable;
1617    }
1618    
1619    
1620  =head3 IsEntity  =head3 IsEntity
1621    
1622  C<< my $flag = $erdb->IsEntity($entityName); >>      my $flag = $erdb->IsEntity($entityName);
1623    
1624  Return TRUE if the parameter is an entity name, else FALSE.  Return TRUE if the parameter is an entity name, else FALSE.
1625    
# Line 993  Line 1646 
1646    
1647  =head3 Get  =head3 Get
1648    
1649  C<< my $query = $erdb->Get(\@objectNames, $filterClause, \@params); >>      my $query = $erdb->Get(\@objectNames, $filterClause, \@params);
1650    
1651  This method returns a query object for entities of a specified type using a specified filter.  This method returns a query object for entities of a specified type using a specified filter.
1652  The filter is a standard WHERE/ORDER BY clause with question marks as parameter markers and each  The filter is a standard WHERE/ORDER BY clause with question marks as parameter markers and each
# Line 1001  Line 1654 
1654  following call requests all B<Genome> objects for the genus specified in the variable  following call requests all B<Genome> objects for the genus specified in the variable
1655  $genus.  $genus.
1656    
1657  C<< $query = $erdb->Get(['Genome'], "Genome(genus) = ?", [$genus]); >>      $query = $erdb->Get(['Genome'], "Genome(genus) = ?", [$genus]);
1658    
1659  The WHERE clause contains a single question mark, so there is a single additional  The WHERE clause contains a single question mark, so there is a single additional
1660  parameter representing the parameter value. It would also be possible to code  parameter representing the parameter value. It would also be possible to code
1661    
1662  C<< $query = $erdb->Get(['Genome'], "Genome(genus) = \'$genus\'"); >>      $query = $erdb->Get(['Genome'], "Genome(genus) = \'$genus\'");
1663    
1664  however, this version of the call would generate a syntax error if there were any quote  however, this version of the call would generate a syntax error if there were any quote
1665  characters inside the variable C<$genus>.  characters inside the variable C<$genus>.
# Line 1018  Line 1671 
1671  It is possible to specify multiple entity and relationship names in order to retrieve more than  It is possible to specify multiple entity and relationship names in order to retrieve more than
1672  one object's data at the same time, which allows highly complex joined queries. For example,  one object's data at the same time, which allows highly complex joined queries. For example,
1673    
1674  C<< $query = $erdb->Get(['Genome', 'ComesFrom', 'Source'], "Genome(genus) = ?", [$genus]); >>      $query = $erdb->Get(['Genome', 'ComesFrom', 'Source'], "Genome(genus) = ?", [$genus]);
1675    
1676  If multiple names are specified, then the query processor will automatically determine a  If multiple names are specified, then the query processor will automatically determine a
1677  join path between the entities and relationships. The algorithm used is very simplistic.  join path between the entities and relationships. The algorithm used is very simplistic.
# Line 1054  Line 1707 
1707  with an ORDER BY clause. For example, the following filter string gets all genomes for a  with an ORDER BY clause. For example, the following filter string gets all genomes for a
1708  particular genus and sorts them by species name.  particular genus and sorts them by species name.
1709    
1710  C<< "Genome(genus) = ? ORDER BY Genome(species)" >>      "Genome(genus) = ? ORDER BY Genome(species)"
1711    
1712  Note that the case is important. Only an uppercase "ORDER BY" with a single space will  Note that the case is important. Only an uppercase "ORDER BY" with a single space will
1713  be processed. The idea is to make it less likely to find the verb by accident.  be processed. The idea is to make it less likely to find the verb by accident.
# Line 1067  Line 1720 
1720  be the last thing in the filter clause, and it contains only the word "LIMIT" followed by  be the last thing in the filter clause, and it contains only the word "LIMIT" followed by
1721  a positive number. So, for example  a positive number. So, for example
1722    
1723  C<< "Genome(genus) = ? ORDER BY Genome(species) LIMIT 10" >>      "Genome(genus) = ? ORDER BY Genome(species) LIMIT 10"
1724    
1725  will only return the first ten genomes for the specified genus. The ORDER BY clause is not  will only return the first ten genomes for the specified genus. The ORDER BY clause is not
1726  required. For example, to just get the first 10 genomes in the B<Genome> table, you could  required. For example, to just get the first 10 genomes in the B<Genome> table, you could
1727  use  use
1728    
1729  C<< "LIMIT 10" >>      "LIMIT 10"
1730    
1731  =item params  =item params
1732    
# Line 1094  Line 1747 
1747      my ($suffix, $mappedNameListRef, $mappedNameHashRef) =      my ($suffix, $mappedNameListRef, $mappedNameHashRef) =
1748          $self->_SetupSQL($objectNames, $filterClause);          $self->_SetupSQL($objectNames, $filterClause);
1749      # Create the query.      # Create the query.
1750      my $command = "SELECT DISTINCT " . join(".*, ", @{$mappedNameListRef}) .      my $command = "SELECT " . join(".*, ", @{$mappedNameListRef}) .
1751          ".* $suffix";          ".* $suffix";
1752      my $sth = $self->_GetStatementHandle($command, $params);      my $sth = $self->_GetStatementHandle($command, $params);
1753      # Now we create the relation map, which enables DBQuery to determine the order, name      # Now we create the relation map, which enables DBQuery to determine the order, name
# Line 1108  Line 1761 
1761      return $retVal;      return $retVal;
1762  }  }
1763    
1764    
1765    
1766  =head3 Search  =head3 Search
1767    
1768  C<< my $query = $erdb->Search($searchExpression, $idx, \@objectNames, $filterClause, \@params); >>      my $query = $erdb->Search($searchExpression, $idx, \@objectNames, $filterClause, \@params);
1769    
1770  Perform a full text search with filtering. The search will be against a specified object  Perform a full text search with filtering. The search will be against a specified object
1771  in the object name list. That object will get an extra field containing the search  in the object name list. That object will get an extra field containing the search
# Line 1121  Line 1776 
1776    
1777  =item searchExpression  =item searchExpression
1778    
1779  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
1780    a Boolean search expression is OR, but we want the default to be AND, so we will
1781    add a C<+> operator to each word with no other operator before it.
1782    
1783  =item idx  =item idx
1784    
# Line 1158  Line 1815 
1815      my ($self, $searchExpression, $idx, $objectNames, $filterClause, $params) = @_;      my ($self, $searchExpression, $idx, $objectNames, $filterClause, $params) = @_;
1816      # Declare the return variable.      # Declare the return variable.
1817      my $retVal;      my $retVal;
1818      # Create a safety copy of the parameter list.      # Create a safety copy of the parameter list. Note we have to be careful to insure
1819      my @myParams = @{$params};      # a parameter list exists before we copy it.
1820        my @myParams = ();
1821        if (defined $params) {
1822            @myParams = @{$params};
1823        }
1824      # Get the first object's structure so we have access to the searchable fields.      # Get the first object's structure so we have access to the searchable fields.
1825      my $object1Name = $objectNames->[$idx];      my $object1Name = $objectNames->[$idx];
1826      my $object1Structure = $self->_GetStructure($object1Name);      my $object1Structure = $self->_GetStructure($object1Name);
# Line 1171  Line 1832 
1832          my @fields = @{$object1Structure->{searchFields}};          my @fields = @{$object1Structure->{searchFields}};
1833          # Clean the search expression.          # Clean the search expression.
1834          my $actualKeywords = $self->CleanKeywords($searchExpression);          my $actualKeywords = $self->CleanKeywords($searchExpression);
1835            # Prefix a "+" to each uncontrolled word. This converts the default
1836            # search mode from OR to AND.
1837            $actualKeywords =~ s/(^|\s)(\w|")/$1\+$2/g;
1838            Trace("Actual keywords for search are\n$actualKeywords") if T(3);
1839          # We need two match expressions, one for the filter clause and one in the          # We need two match expressions, one for the filter clause and one in the
1840          # query itself. Both will use a parameter mark, so we need to push the          # query itself. Both will use a parameter mark, so we need to push the
1841          # search expression onto the front of the parameter list twice.          # search expression onto the front of the parameter list twice.
# Line 1183  Line 1848 
1848              $self->_SetupSQL($objectNames, $filterClause, $matchClause);              $self->_SetupSQL($objectNames, $filterClause, $matchClause);
1849          # 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
1850          # the select fields.          # the select fields.
1851          my $command = "SELECT DISTINCT $matchClause, " . join(".*, ", @{$mappedNameListRef}) .          my $command = "SELECT $matchClause, " . join(".*, ", @{$mappedNameListRef}) .
1852              ".* $suffix";              ".* $suffix";
1853          my $sth = $self->_GetStatementHandle($command, \@myParams);          my $sth = $self->_GetStatementHandle($command, \@myParams);
1854          # 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 1862 
1862    
1863  =head3 GetFlat  =head3 GetFlat
1864    
1865  C<< my @list = $erdb->GetFlat(\@objectNames, $filterClause, \@parameterList, $field); >>      my @list = $erdb->GetFlat(\@objectNames, $filterClause, \@parameterList, $field);
1866    
1867  This is a variation of L</GetAll> that asks for only a single field per record and  This is a variation of L</GetAll> that asks for only a single field per record and
1868  returns a single flattened list.  returns a single flattened list.
# Line 1248  Line 1913 
1913      return @retVal;      return @retVal;
1914  }  }
1915    
1916  =head3 Delete  =head3 SpecialFields
1917    
1918  C<< my $stats = $erdb->Delete($entityName, $objectID); >>      my %specials = $erdb->SpecialFields($entityName);
1919    
1920  Delete an entity instance from the database. The instance is deleted along with all entity and  Return a hash mapping special fields in the specified entity to the value of their
1921  relationship instances dependent on it. The idea of dependence here is recursive. An object is  C<special> attribute. This enables the subclass to get access to the special field
1922  always dependent on itself. An object is dependent if it is a 1-to-many or many-to-many  attributes without needed to plumb the internal ERDB data structures.
 relationship connected to a dependent entity or the "to" entity connected to a 1-to-many  
 dependent relationship.  
1923    
1924  =over 4  =over 4
1925    
1926  =item entityName  =item entityName
1927    
1928  Name of the entity type for the instance being deleted.  Name of the entity whose special fields are desired.
1929    
1930    =item RETURN
1931    
1932    Returns a hash. The keys of the hash are the special field names, and the values
1933    are the values from each special field's C<special> attribute.
1934    
1935    =back
1936    
1937    =cut
1938    
1939    sub SpecialFields {
1940        # Get the parameters.
1941        my ($self, $entityName) = @_;
1942        # Declare the return variable.
1943        my %retVal = ();
1944        # Find the entity's data structure.
1945        my $entityData = $self->{_metaData}->{Entities}->{$entityName};
1946        # Loop through its fields, adding each special field to the return hash.
1947        my $fieldHash = $entityData->{Fields};
1948        for my $fieldName (keys %{$fieldHash}) {
1949            my $fieldData = $fieldHash->{$fieldName};
1950            if (exists $fieldData->{special}) {
1951                $retVal{$fieldName} = $fieldData->{special};
1952            }
1953        }
1954        # Return the result.
1955        return %retVal;
1956    }
1957    
1958    =head3 Delete
1959    
1960        my $stats = $erdb->Delete($entityName, $objectID, %options);
1961    
1962    Delete an entity instance from the database. The instance is deleted along with all entity and
1963    relationship instances dependent on it. The definition of I<dependence> is recursive.
1964    
1965    An object is always dependent on itself. An object is dependent if it is a 1-to-many or many-to-many
1966    relationship connected to a dependent entity or if it is the "to" entity connected to a 1-to-many
1967    dependent relationship.
1968    
1969    =over 4
1970    
1971    =item entityName
1972    
1973    Name of the entity type for the instance being deleted.
1974    
1975  =item objectID  =item objectID
1976    
1977  ID of the entity instance to be deleted. If the ID contains a wild card character (C<%>),  ID of the entity instance to be deleted. If the ID contains a wild card character (C<%>),
1978  then it is presumed to by a LIKE pattern.  then it is presumed to by a LIKE pattern.
1979    
1980  =item testFlag  =item options
1981    
1982  If TRUE, the delete statements will be traced without being executed.  A hash detailing the options for this delete operation.
1983    
1984  =item RETURN  =item RETURN
1985    
# Line 1280  Line 1988 
1988    
1989  =back  =back
1990    
1991    The permissible options for this method are as follows.
1992    
1993    =over 4
1994    
1995    =item testMode
1996    
1997    If TRUE, then the delete statements will be traced, but no changes will be made to the database.
1998    
1999    =item keepRoot
2000    
2001    If TRUE, then the entity instances will not be deleted, only the dependent records.
2002    
2003    =back
2004    
2005  =cut  =cut
2006  #: Return Type $%;  #: Return Type $%;
2007  sub Delete {  sub Delete {
2008      # Get the parameters.      # Get the parameters.
2009      my ($self, $entityName, $objectID, $testFlag) = @_;      my ($self, $entityName, $objectID, %options) = @_;
2010      # Declare the return variable.      # Declare the return variable.
2011      my $retVal = Stats->new();      my $retVal = Stats->new();
2012      # Get the DBKernel object.      # Get the DBKernel object.
# Line 1301  Line 2023 
2023      # FROM-relationships and entities.      # FROM-relationships and entities.
2024      my @fromPathList = ();      my @fromPathList = ();
2025      my @toPathList = ();      my @toPathList = ();
2026      # This final hash is used to remember what work still needs to be done. We push paths      # This final list is used to remember what work still needs to be done. We push paths
2027      # onto the list, then pop them off to extend the paths. We prime it with the starting      # onto the list, then pop them off to extend the paths. We prime it with the starting
2028      # point. Note that we will work hard to insure that the last item on a path in the      # point. Note that we will work hard to insure that the last item on a path in the
2029      # TODO list is always an entity.      # to-do list is always an entity.
2030      my @todoList = ([$entityName]);      my @todoList = ([$entityName]);
2031      while (@todoList) {      while (@todoList) {
2032          # Get the current path.          # Get the current path.
# Line 1312  Line 2034 
2034          # Copy it into a list.          # Copy it into a list.
2035          my @stackedPath = @{$current};          my @stackedPath = @{$current};
2036          # Pull off the last item on the path. It will always be an entity.          # Pull off the last item on the path. It will always be an entity.
2037          my $entityName = pop @stackedPath;          my $myEntityName = pop @stackedPath;
2038          # Add it to the alreadyFound list.          # Add it to the alreadyFound list.
2039          $alreadyFound{$entityName} = 1;          $alreadyFound{$myEntityName} = 1;
2040            # Figure out if we need to delete this entity.
2041            if ($myEntityName ne $entityName || ! $options{keepRoot}) {
2042          # Get the entity data.          # Get the entity data.
2043          my $entityData = $self->_GetStructure($entityName);              my $entityData = $self->_GetStructure($myEntityName);
2044          # The first task is to loop through the entity's relation. A DELETE command will              # Loop through the entity's relations. A DELETE command will be needed for each of them.
         # be needed for each of them.  
2045          my $relations = $entityData->{Relations};          my $relations = $entityData->{Relations};
2046          for my $relation (keys %{$relations}) {          for my $relation (keys %{$relations}) {
2047              my @augmentedList = (@stackedPath, $relation);              my @augmentedList = (@stackedPath, $relation);
2048              push @fromPathList, \@augmentedList;              push @fromPathList, \@augmentedList;
2049          }          }
2050            }
2051          # Now we need to look for relationships connected to this entity.          # Now we need to look for relationships connected to this entity.
2052          my $relationshipList = $self->{_metaData}->{Relationships};          my $relationshipList = $self->{_metaData}->{Relationships};
2053          for my $relationshipName (keys %{$relationshipList}) {          for my $relationshipName (keys %{$relationshipList}) {
2054              my $relationship = $relationshipList->{$relationshipName};              my $relationship = $relationshipList->{$relationshipName};
2055              # Check the FROM field. We're only interested if it's us.              # Check the FROM field. We're only interested if it's us.
2056              if ($relationship->{from} eq $entityName) {              if ($relationship->{from} eq $myEntityName) {
2057                  # Add the path to this relationship.                  # Add the path to this relationship.
2058                  my @augmentedList = (@stackedPath, $entityName, $relationshipName);                  my @augmentedList = (@stackedPath, $myEntityName, $relationshipName);
2059                  push @fromPathList, \@augmentedList;                  push @fromPathList, \@augmentedList;
2060                  # Check the arity. If it's MM we're done. If it's 1M                  # Check the arity. If it's MM we're done. If it's 1M
2061                  # and the target hasn't been seen yet, we want to                  # and the target hasn't been seen yet, we want to
# Line 1350  Line 2074 
2074              }              }
2075              # Now check the TO field. In this case only the relationship needs              # Now check the TO field. In this case only the relationship needs
2076              # deletion.              # deletion.
2077              if ($relationship->{to} eq $entityName) {              if ($relationship->{to} eq $myEntityName) {
2078                  my @augmentedList = (@stackedPath, $entityName, $relationshipName);                  my @augmentedList = (@stackedPath, $myEntityName, $relationshipName);
2079                  push @toPathList, \@augmentedList;                  push @toPathList, \@augmentedList;
2080              }              }
2081          }          }
2082      }      }
2083      # Create the first qualifier for the WHERE clause. This selects the      # Create the first qualifier for the WHERE clause. This selects the
2084      # keys of the primary entity records to be deleted. When we're deleting      # keys of the primary entity records to be deleted. When we're deleting
2085      # from a dependent table, we construct a join page from the first qualifier      # from a dependent table, we construct a join path from the first qualifier
2086      # to the table containing the dependent records to delete.      # to the table containing the dependent records to delete.
2087      my $qualifier = ($objectID =~ /%/ ? "LIKE ?" : "= ?");      my $qualifier = ($objectID =~ /%/ ? "LIKE ?" : "= ?");
2088      # We need to make two passes. The first is through the to-list, and      # We need to make two passes. The first is through the to-list, and
# Line 1397  Line 2121 
2121                  }                  }
2122              }              }
2123              # Now we have our desired DELETE statement.              # Now we have our desired DELETE statement.
2124              if ($testFlag) {              if ($options{testMode}) {
2125                  # Here the user wants to trace without executing.                  # Here the user wants to trace without executing.
2126                  Trace($stmt) if T(0);                  Trace($stmt) if T(0);
2127              } else {              } else {
2128                  # Here we can delete. Note that the SQL method dies with a confessing                  # Here we can delete. Note that the SQL method dies with a confession
2129                  # if an error occurs, so we just go ahead and do it.                  # if an error occurs, so we just go ahead and do it.
2130                  Trace("Executing delete from $target using '$objectID'.") if T(3);                  Trace("Executing delete from $target using '$objectID'.") if T(3);
2131                  my $rv = $db->SQL($stmt, 0, $objectID);                  my $rv = $db->SQL($stmt, 0, $objectID);
# Line 1416  Line 2140 
2140      return $retVal;      return $retVal;
2141  }  }
2142    
2143    =head3 Disconnect
2144    
2145        $erdb->Disconnect($relationshipName, $originEntityName, $originEntityID);
2146    
2147    Disconnect an entity instance from all the objects to which it is related. This
2148    will delete each relationship instance that connects to the specified entity.
2149    
2150    =over 4
2151    
2152    =item relationshipName
2153    
2154    Name of the relationship whose instances are to be deleted.
2155    
2156    =item originEntityName
2157    
2158    Name of the entity that is to be disconnected.
2159    
2160    =item originEntityID
2161    
2162    ID of the entity that is to be disconnected.
2163    
2164    =back
2165    
2166    =cut
2167    
2168    sub Disconnect {
2169        # Get the parameters.
2170        my ($self, $relationshipName, $originEntityName, $originEntityID) = @_;
2171        # Get the relationship descriptor.
2172        my $structure = $self->_GetStructure($relationshipName);
2173        # Insure we have a relationship.
2174        if (! exists $structure->{from}) {
2175            Confess("$relationshipName is not a relationship in the database.");
2176        } else {
2177            # Get the database handle.
2178            my $dbh = $self->{_dbh};
2179            # We'll set this value to 1 if we find our entity.
2180            my $found = 0;
2181            # Loop through the ends of the relationship.
2182            for my $dir ('from', 'to') {
2183                if ($structure->{$dir} eq $originEntityName) {
2184                    $found = 1;
2185                    # Here we want to delete all relationship instances on this side of the
2186                    # entity instance.
2187                    Trace("Disconnecting in $dir direction with ID \"$originEntityID\".");
2188                    # We do this delete in batches to keep it from dragging down the
2189                    # server.
2190                    my $limitClause = ($FIG_Config::delete_limit ? "LIMIT $FIG_Config::delete_limit" : "");
2191                    my $done = 0;
2192                    while (! $done) {
2193                        # Do the delete.
2194                        my $rows = $dbh->SQL("DELETE FROM $relationshipName WHERE ${dir}_link = ? $limitClause", 0, $originEntityID);
2195                        # See if we're done. We're done if no rows were found or the delete is unlimited.
2196                        $done = ($rows == 0 || ! $limitClause);
2197                    }
2198                }
2199            }
2200            # Insure we found the entity on at least one end.
2201            if (! $found) {
2202                Confess("Entity \"$originEntityName\" does not use $relationshipName.");
2203            }
2204        }
2205    }
2206    
2207    =head3 DeleteRow
2208    
2209        $erdb->DeleteRow($relationshipName, $fromLink, $toLink, \%values);
2210    
2211    Delete a row from a relationship. In most cases, only the from-link and to-link are
2212    needed; however, for relationships with intersection data values can be specified
2213    for the other fields using a hash.
2214    
2215    =over 4
2216    
2217    =item relationshipName
2218    
2219    Name of the relationship from which the row is to be deleted.
2220    
2221    =item fromLink
2222    
2223    ID of the entity instance in the From direction.
2224    
2225    =item toLink
2226    
2227    ID of the entity instance in the To direction.
2228    
2229    =item values
2230    
2231    Reference to a hash of other values to be used for filtering the delete.
2232    
2233    =back
2234    
2235    =cut
2236    
2237    sub DeleteRow {
2238        # Get the parameters.
2239        my ($self, $relationshipName, $fromLink, $toLink, $values) = @_;
2240        # Create a hash of all the filter information.
2241        my %filter = ('from-link' => $fromLink, 'to-link' => $toLink);
2242        if (defined $values) {
2243            for my $key (keys %{$values}) {
2244                $filter{$key} = $values->{$key};
2245            }
2246        }
2247        # Build an SQL statement out of the hash.
2248        my @filters = ();
2249        my @parms = ();
2250        for my $key (keys %filter) {
2251            push @filters, _FixName($key) . " = ?";
2252            push @parms, $filter{$key};
2253        }
2254        Trace("Parms for delete row are " . join(", ", map { "\"$_\"" } @parms) . ".") if T(SQL => 4);
2255        my $command = "DELETE FROM $relationshipName WHERE " .
2256                      join(" AND ", @filters);
2257        # Execute it.
2258        my $dbh = $self->{_dbh};
2259        $dbh->SQL($command, undef, @parms);
2260    }
2261    
2262    =head3 DeleteLike
2263    
2264        my $deleteCount = $erdb->DeleteLike($relName, $filter, \@parms);
2265    
2266    Delete all the relationship rows that satisfy a particular filter condition. Unlike a normal
2267    filter, only fields from the relationship itself can be used.
2268    
2269    =over 4
2270    
2271    =item relName
2272    
2273    Name of the relationship whose records are to be deleted.
2274    
2275    =item filter
2276    
2277    A filter clause (L</Get>-style) for the delete query.
2278    
2279    =item parms
2280    
2281    Reference to a list of parameters for the filter clause.
2282    
2283    =item RETURN
2284    
2285    Returns a count of the number of rows deleted.
2286    
2287    =back
2288    
2289    =cut
2290    
2291    sub DeleteLike {
2292        # Get the parameters.
2293        my ($self, $objectName, $filter, $parms) = @_;
2294        # Declare the return variable.
2295        my $retVal;
2296        # Insure the parms argument is an array reference if the caller left it off.
2297        if (! defined($parms)) {
2298            $parms = [];
2299        }
2300        # Insure we have a relationship. The main reason for this is if we delete an entity
2301        # instance we have to yank out a bunch of other stuff with it.
2302        if ($self->IsEntity($objectName)) {
2303            Confess("Cannot use DeleteLike on $objectName, because it is not a relationship.");
2304        } else {
2305            # Create the SQL command suffix to get the desierd records.
2306            my ($suffix) = $self->_SetupSQL([$objectName], $filter);
2307            # Convert it to a DELETE command.
2308            my $command = "DELETE $suffix";
2309            # Execute the command.
2310            my $dbh = $self->{_dbh};
2311            my $result = $dbh->SQL($command, 0, @{$parms});
2312            # Check the results. Note we convert the "0D0" result to a real zero.
2313            # A failure causes an abnormal termination, so the caller isn't going to
2314            # worry about it.
2315            if (! defined $result) {
2316                Confess("Error deleting from $objectName: " . $dbh->errstr());
2317            } elsif ($result == 0) {
2318                $retVal = 0;
2319            } else {
2320                $retVal = $result;
2321            }
2322        }
2323        # Return the result count.
2324        return $retVal;
2325    }
2326    
2327  =head3 SortNeeded  =head3 SortNeeded
2328    
2329  C<< my $parms = $erdb->SortNeeded($relationName); >>      my $parms = $erdb->SortNeeded($relationName);
2330    
2331  Return the pipe command for the sort that should be applied to the specified  Return the pipe command for the sort that should be applied to the specified
2332  relation when creating the load file.  relation when creating the load file.
# Line 1466  Line 2374 
2374      } elsif (exists $relationshipTable->{$relationName}) {      } elsif (exists $relationshipTable->{$relationName}) {
2375          # Here we have a relationship. We sort using the FROM index.          # Here we have a relationship. We sort using the FROM index.
2376          my $relationshipData = $relationshipTable->{$relationName};          my $relationshipData = $relationshipTable->{$relationName};
2377          my $index = $relationData->{Indexes}->{"idx${relationName}From"};          my $index = $relationData->{Indexes}->{idxFrom};
2378          push @keyNames, @{$index->{IndexFields}};          push @keyNames, @{$index->{IndexFields}};
2379      } else {      } else {
2380          # 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 1474  Line 2382 
2382      }      }
2383      # Now we parse the key names into sort parameters. First, we prime the return      # Now we parse the key names into sort parameters. First, we prime the return
2384      # string.      # string.
2385      my $retVal = "sort -t\"\t\" ";      my $retVal = "sort -S 1G -T\"$FIG_Config::temp\" -t\"\t\" ";
2386      # Get the relation's field list.      # Get the relation's field list.
2387      my @fields = @{$relationData->{Fields}};      my @fields = @{$relationData->{Fields}};
2388      # Loop through the keys.      # Loop through the keys.
# Line 1504  Line 2412 
2412                  # will stop the inner loop. Note that the field number is                  # will stop the inner loop. Note that the field number is
2413                  # 1-based in the sort command, so we have to increment the                  # 1-based in the sort command, so we have to increment the
2414                  # index.                  # index.
2415                  $fieldSpec = ($i + 1) . $modifier;                  my $realI = $i + 1;
2416                    $fieldSpec = "$realI,$realI$modifier";
2417              }              }
2418          }          }
2419          # Add this field to the sort command.          # Add this field to the sort command.
# Line 1516  Line 2425 
2425    
2426  =head3 GetList  =head3 GetList
2427    
2428  C<< my @dbObjects = $erdb->GetList(\@objectNames, $filterClause, \@params); >>      my @dbObjects = $erdb->GetList(\@objectNames, $filterClause, \@params);
2429    
2430  Return a list of object descriptors for the specified objects as determined by the  Return a list of object descriptors for the specified objects as determined by the
2431  specified filter clause.  specified filter clause.
# Line 1544  Line 2453 
2453  with an ORDER BY clause. For example, the following filter string gets all genomes for a  with an ORDER BY clause. For example, the following filter string gets all genomes for a
2454  particular genus and sorts them by species name.  particular genus and sorts them by species name.
2455    
2456  C<< "Genome(genus) = ? ORDER BY Genome(species)" >>      "Genome(genus) = ? ORDER BY Genome(species)"
2457    
2458  The rules for field references in a sort order are the same as those for field references in the  The rules for field references in a sort order are the same as those for field references in the
2459  filter clause in general; however, odd things may happen if a sort field is from a secondary  filter clause in general; however, odd things may happen if a sort field is from a secondary
# Line 1556  Line 2465 
2465    
2466  =item RETURN  =item RETURN
2467    
2468  Returns a list of B<DBObject>s that satisfy the query conditions.  Returns a list of B<ERDBObject>s that satisfy the query conditions.
2469    
2470  =back  =back
2471    
# Line 1579  Line 2488 
2488    
2489  =head3 GetCount  =head3 GetCount
2490    
2491  C<< my $count = $erdb->GetCount(\@objectNames, $filter, \@params); >>      my $count = $erdb->GetCount(\@objectNames, $filter, \@params);
2492    
2493  Return the number of rows found by a specified query. This method would  Return the number of rows found by a specified query. This method would
2494  normally be used to count the records in a single table. For example, in a  normally be used to count the records in a single table. For example, in a
# Line 1596  Line 2505 
2505  would return the number of features for genomes in the genus I<homo>. Note that  would return the number of features for genomes in the genus I<homo>. Note that
2506  only the rows from the first table are counted. If the above command were  only the rows from the first table are counted. If the above command were
2507    
2508      my $count = $erdb->GetCount(['Genome', 'Feature'], 'Genome(genus-species) LIKE ?',      my $count = $erdb->GetCount(['Genome', 'HasFeature'], 'Genome(genus-species) LIKE ?',
2509                                  ['homo %']);                                  ['homo %']);
2510    
2511  it would return the number of genomes, not the number of genome/feature pairs.  it would return the number of genomes, not the number of genome/feature pairs.
# Line 1672  Line 2581 
2581    
2582  =head3 ComputeObjectSentence  =head3 ComputeObjectSentence
2583    
2584  C<< my $sentence = $erdb->ComputeObjectSentence($objectName); >>      my $sentence = $erdb->ComputeObjectSentence($objectName);
2585    
2586  Check an object name, and if it is a relationship convert it to a relationship sentence.  Check an object name, and if it is a relationship convert it to a relationship sentence.
2587    
# Line 1707  Line 2616 
2616    
2617  =head3 DumpRelations  =head3 DumpRelations
2618    
2619  C<< $erdb->DumpRelations($outputDirectory); >>      $erdb->DumpRelations($outputDirectory);
2620    
2621  Write the contents of all the relations to tab-delimited files in the specified directory.  Write the contents of all the relations to tab-delimited files in the specified directory.
2622  Each file will have the same name as the relation dumped, with an extension of DTX.  Each file will have the same name as the relation dumped, with an extension of DTX.
# Line 1749  Line 2658 
2658    
2659  =head3 InsertValue  =head3 InsertValue
2660    
2661  C<< $erdb->InsertValue($entityID, $fieldName, $value); >>      $erdb->InsertValue($entityID, $fieldName, $value);
2662    
2663  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
2664  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 2721 
2721    
2722  =head3 InsertObject  =head3 InsertObject
2723    
2724  C<< my $ok = $erdb->InsertObject($objectType, \%fieldHash); >>      $erdb->InsertObject($objectType, \%fieldHash);
2725    
2726  Insert an object into the database. The object is defined by a type name and then a hash  Insert an object into the database. The object is defined by a type name and then a hash
2727  of field names to values. Field values in the primary relation are represented by scalars.  of field names to values. Field values in the primary relation are represented by scalars.
# Line 1821  Line 2730 
2730  example, the following line inserts an inactive PEG feature named C<fig|188.1.peg.1> with aliases  example, the following line inserts an inactive PEG feature named C<fig|188.1.peg.1> with aliases
2731  C<ZP_00210270.1> and C<gi|46206278>.  C<ZP_00210270.1> and C<gi|46206278>.
2732    
2733  C<< $erdb->InsertObject('Feature', { id => 'fig|188.1.peg.1', active => 0, feature-type => 'peg', alias => ['ZP_00210270.1', 'gi|46206278']}); >>      $erdb->InsertObject('Feature', { id => 'fig|188.1.peg.1', active => 0, feature-type => 'peg', alias => ['ZP_00210270.1', 'gi|46206278']});
2734    
2735  The next statement inserts a C<HasProperty> relationship between feature C<fig|158879.1.peg.1> and  The next statement inserts a C<HasProperty> relationship between feature C<fig|158879.1.peg.1> and
2736  property C<4> with an evidence URL of C<http://seedu.uchicago.edu/query.cgi?article_id=142>.  property C<4> with an evidence URL of C<http://seedu.uchicago.edu/query.cgi?article_id=142>.
2737    
2738  C<< $erdb->InsertObject('HasProperty', { 'from-link' => 'fig|158879.1.peg.1', 'to-link' => 4, evidence => 'http://seedu.uchicago.edu/query.cgi?article_id=142'}); >>      $erdb->InsertObject('HasProperty', { 'from-link' => 'fig|158879.1.peg.1', 'to-link' => 4, evidence => 'http://seedu.uchicago.edu/query.cgi?article_id=142'});
2739    
2740  =over 4  =over 4
2741    
# Line 1838  Line 2747 
2747    
2748  Hash of field names to values.  Hash of field names to values.
2749    
 =item RETURN  
   
 Returns 1 if successful, 0 if an error occurred.  
   
2750  =back  =back
2751    
2752  =cut  =cut
# Line 1899  Line 2804 
2804                  push @missing, $fieldName;                  push @missing, $fieldName;
2805              }              }
2806          }          }
         # If we are the primary relation, add the new-record flag.  
         if ($relationName eq $newObjectType) {  
             push @valueList, 1;  
             push @fieldNameList, "new_record";  
         }  
2807          # Only proceed if there are no missing fields.          # Only proceed if there are no missing fields.
2808          if (@missing > 0) {          if (@missing > 0) {
2809              Trace("Relation $relationName for $newObjectType skipped due to missing fields: " .              Trace("Relation $relationName for $newObjectType skipped due to missing fields: " .
# Line 1940  Line 2840 
2840                  $retVal = $sth->execute(@parameterList);                  $retVal = $sth->execute(@parameterList);
2841                  if (!$retVal) {                  if (!$retVal) {
2842                      my $errorString = $sth->errstr();                      my $errorString = $sth->errstr();
2843                      Trace("Insert error: $errorString.") if T(0);                      Confess("Error inserting into $relationName: $errorString");
2844                    } else {
2845                        Trace("Insert successful using $parameterList[0].") if T(3);
2846                  }                  }
2847              }              }
2848          }          }
2849      }      }
2850      # Return the success indicator.      # Return a 1 for backward compatability.
2851      return $retVal;      return 1;
2852    }
2853    
2854    =head3 UpdateEntity
2855    
2856        $erdb->UpdateEntity($entityName, $id, \%fields);
2857    
2858    Update the values of an entity. This is an unprotected update, so it should only be
2859    done if the database resides on a database server.
2860    
2861    =over 4
2862    
2863    =item entityName
2864    
2865    Name of the entity to update. (This is the entity type.)
2866    
2867    =item id
2868    
2869    ID of the entity to update. If no entity exists with this ID, an error will be thrown.
2870    
2871    =item fields
2872    
2873    Reference to a hash mapping field names to their new values. All of the fields named
2874    must be in the entity's primary relation, and they cannot any of them be the ID field.
2875    
2876    =back
2877    
2878    =cut
2879    
2880    sub UpdateEntity {
2881        # Get the parameters.
2882        my ($self, $entityName, $id, $fields) = @_;
2883        # Get a list of the field names being updated.
2884        my @fieldList = keys %{$fields};
2885        # Verify that the fields exist.
2886        my $checker = $self->GetFieldTable($entityName);
2887        for my $field (@fieldList) {
2888            if ($field eq 'id') {
2889                Confess("Cannot update the ID field for entity $entityName.");
2890            } elsif ($checker->{$field}->{relation} ne $entityName) {
2891                Confess("Cannot find $field in primary relation of $entityName.");
2892            }
2893        }
2894        # Build the SQL statement.
2895        my @sets = ();
2896        my @valueList = ();
2897        for my $field (@fieldList) {
2898            push @sets, _FixName($field) . " = ?";
2899            push @valueList, $fields->{$field};
2900        }
2901        my $command = "UPDATE $entityName SET " . join(", ", @sets) . " WHERE id = ?";
2902        # Add the ID to the list of binding values.
2903        push @valueList, $id;
2904        # Call SQL to do the work.
2905        my $rows = $self->{_dbh}->SQL($command, 0, @valueList);
2906        # Check for errors.
2907        if ($rows == 0) {
2908            Confess("Entity $id of type $entityName not found.");
2909        }
2910  }  }
2911    
2912  =head3 LoadTable  =head3 LoadTable
2913    
2914  C<< my %results = $erdb->LoadTable($fileName, $relationName, $truncateFlag); >>      my $results = $erdb->LoadTable($fileName, $relationName, %options);
2915    
2916  Load data from a tab-delimited file into a specified table, optionally re-creating the table  Load data from a tab-delimited file into a specified table, optionally re-creating the table
2917  first.  first.
# Line 1966  Line 2926 
2926    
2927  Name of the relation to be loaded. This is the same as the table name.  Name of the relation to be loaded. This is the same as the table name.
2928    
2929  =item truncateFlag  =item options
2930    
2931  TRUE if the table should be dropped and re-created, else FALSE  A hash of load options.
2932    
2933  =item RETURN  =item RETURN
2934    
# Line 1976  Line 2936 
2936    
2937  =back  =back
2938    
2939    The permissible options are as follows.
2940    
2941    =over 4
2942    
2943    =item truncate
2944    
2945    If TRUE, then the table will be erased before loading.
2946    
2947    =item mode
2948    
2949    Mode in which the load should operate, either C<low_priority> or C<concurrent>.
2950    This option is only applicable to a MySQL database.
2951    
2952    =item partial
2953    
2954    If TRUE, then it is assumed that this is a partial load, and the table will not
2955    be analyzed and compacted at the end.
2956    
2957    =back
2958    
2959  =cut  =cut
2960  sub LoadTable {  sub LoadTable {
2961      # Get the parameters.      # Get the parameters.
2962      my ($self, $fileName, $relationName, $truncateFlag) = @_;      my ($self, $fileName, $relationName, %options) = @_;
2963      # Create the statistical return object.      # Create the statistical return object.
2964      my $retVal = _GetLoadStats();      my $retVal = _GetLoadStats();
2965      # Trace the fact of the load.      # Trace the fact of the load.
# Line 1991  Line 2971 
2971      # Get the relation data.      # Get the relation data.
2972      my $relation = $self->_FindRelation($relationName);      my $relation = $self->_FindRelation($relationName);
2973      # Check the truncation flag.      # Check the truncation flag.
2974      if ($truncateFlag) {      if ($options{truncate}) {
2975          Trace("Creating table $relationName") if T(2);          Trace("Creating table $relationName") if T(2);
2976          # Compute the row count estimate. We take the size of the load file,          # Compute the row count estimate. We take the size of the load file,
2977          # divide it by the estimated row size, and then multiply by 1.5 to          # divide it by the estimated row size, and then multiply by 2 to
2978          # leave extra room. We postulate a minimum row count of 1000 to          # leave extra room. We postulate a minimum row count of 1000 to
2979          # prevent problems with incoming empty load files.          # prevent problems with incoming empty load files.
2980          my $rowSize = $self->EstimateRowSize($relationName);          my $rowSize = $self->EstimateRowSize($relationName);
2981          my $estimate = FIG::max($fileSize * 1.5 / $rowSize, 1000);          my $estimate = $fileSize * 8 / $rowSize;
2982            if ($estimate < 1000) {
2983                $estimate = 1000;
2984            }
2985          # Re-create the table without its index.          # Re-create the table without its index.
2986          $self->CreateTable($relationName, 0, $estimate);          $self->CreateTable($relationName, 0, $estimate);
2987          # If this is a pre-index DBMS, create the index here.          # If this is a pre-index DBMS, create the index here.
# Line 2014  Line 2997 
2997      # Load the table.      # Load the table.
2998      my $rv;      my $rv;
2999      eval {      eval {
3000          $rv = $dbh->load_table(file => $fileName, tbl => $relationName);          $rv = $dbh->load_table(file => $fileName, tbl => $relationName, style => $options{mode});
3001      };      };
3002      if (!defined $rv) {      if (!defined $rv) {
3003          $retVal->AddMessage($@) if ($@);          $retVal->AddMessage($@) if ($@);
3004          $retVal->AddMessage("Table load failed for $relationName using $fileName.");          $retVal->AddMessage("Table load failed for $relationName using $fileName: " . $dbh->error_message);
3005          Trace("Table load failed for $relationName.") if T(1);          Trace("Table load failed for $relationName.") if T(1);
3006      } else {      } else {
3007          # Here we successfully loaded the table.          # Here we successfully loaded the table.
3008          $retVal->Add("tables");          $retVal->Add("tables");
3009          my $size = -s $fileName;          my $size = -s $fileName;
3010          Trace("$size bytes loaded into $relationName.") if T(2);          Trace("$size bytes loaded into $relationName.") if T(2);
3011            $retVal->Add("bytes", $size);
3012          # If we're rebuilding, we need to create the table indexes.          # If we're rebuilding, we need to create the table indexes.
3013          if ($truncateFlag) {          if ($options{truncate}) {
3014              # Indexes are created here for PostGres. For PostGres, indexes are              # Indexes are created here for PostGres. For PostGres, indexes are
3015              # best built at the end. For MySQL, the reverse is true.              # best built at the end. For MySQL, the reverse is true.
3016              if (! $dbh->{_preIndex}) {              if (! $dbh->{_preIndex}) {
# Line 2040  Line 3024 
3024              # 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.
3025              # 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
3026              # primary relations are allowed that privilege.              # primary relations are allowed that privilege.
3027                Trace("Checking for full-text index on $relationName.") if T(2);
3028              if ($self->_IsPrimary($relationName)) {              if ($self->_IsPrimary($relationName)) {
3029                  # 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');  
                 }  
3030              }              }
3031          }          }
3032      }      }
3033      # Analyze the table to improve performance.      # Analyze the table to improve performance.
3034        if (! $options{partial}) {
3035      Trace("Analyzing and compacting $relationName.") if T(3);      Trace("Analyzing and compacting $relationName.") if T(3);
3036      $dbh->vacuum_it($relationName);          $self->Analyze($relationName);
3037        }
3038      Trace("$relationName load completed.") if T(3);      Trace("$relationName load completed.") if T(3);
3039      # Return the statistics.      # Return the statistics.
3040      return $retVal;      return $retVal;
3041  }  }
3042    
3043  =head3 GenerateEntity  =head3 Analyze
3044    
3045  C<< my $fieldHash = $erdb->GenerateEntity($id, $type, \%values); >>      $erdb->Analyze($tableName);
3046    
3047  Generate the data for a new entity instance. This method creates a field hash suitable for  Analyze and compact a table in the database. This is useful after a load
3048  passing as a parameter to L</InsertObject>. The ID is specified by the callr, but the rest  to improve the performance of the indexes.
 of the fields are generated using information in the database schema.  
   
 Each data type has a default algorithm for generating random test data. This can be overridden  
 by including a B<DataGen> element in the field. If this happens, the content of the element is  
 executed as a PERL program in the context of this module. The element may make use of a C<$this>  
 variable which contains the field hash as it has been built up to the current point. If any  
 fields are dependent on other fields, the C<pass> attribute can be used to control the order  
 in which the fields are generated. A field with a high data pass number will be generated after  
 a field with a lower one. If any external values are needed, they should be passed in via the  
 optional third parameter, which will be available to the data generation script under the name  
 C<$value>. Several useful utility methods are provided for generating random values, including  
 L</IntGen>, L</StringGen>, L</FloatGen>, and L</DateGen>. Note that dates are stored and generated  
 in the form of a timestamp number rather than a string.  
3049    
3050  =over 4  =over 4
3051    
3052  =item id  =item tableName
3053    
3054  ID to assign to the new entity.  Name of the table to be analyzed and compacted.
3055    
3056  =item type  =back
3057    
3058  Type name for the new entity.  =cut
3059    
3060  =item values  sub Analyze {
3061        # Get the parameters.
3062        my ($self, $tableName) = @_;
3063        # Analyze the table.
3064        $self->{_dbh}->vacuum_it($tableName);
3065    }
3066    
3067    =head3 TruncateTable
3068    
3069        $erdb->TruncateTable($table);
3070    
3071  Hash containing additional values that might be needed by the data generation methods (optional).  Delete all rows from a table quickly. This uses the built-in SQL
3072    C<TRUNCATE> statement, which effectively drops and re-creates a table
3073    with all its settings intact.
3074    
3075    =over 4
3076    
3077    =item table
3078    
3079    Name of the table to be cleared.
3080    
3081  =back  =back
3082    
3083  =cut  =cut
3084    
3085  sub GenerateEntity {  sub TruncateTable {
3086      # Get the parameters.      # Get the parameters.
3087      my ($self, $id, $type, $values) = @_;      my ($self, $table) = @_;
3088      # Create the return hash.      # Get the database handle.
3089      my $this = { id => $id };      my $dbh = $self->{_dbh};
3090      # Get the metadata structure.      # Execute a truncation comment.
3091      my $metadata = $self->{_metaData};      $dbh->SQL("TRUNCATE TABLE $table");
     # Get this entity's list of fields.  
     if (!exists $metadata->{Entities}->{$type}) {  
         Confess("Unrecognized entity type $type in GenerateEntity.");  
     } else {  
         my $entity = $metadata->{Entities}->{$type};  
         my $fields = $entity->{Fields};  
         # Generate data from the fields.  
         _GenerateFields($this, $fields, $type, $values);  
     }  
     # Return the hash created.  
     return $this;  
3092  }  }
3093    
 =head3 GetEntity  
3094    
3095  C<< my $entityObject = $erdb->GetEntity($entityType, $ID); >>  =head3 CreateSearchIndex
3096    
3097  Return an object describing the entity instance with a specified ID.      $erdb->CreateSearchIndex($objectName);
3098    
3099    Check for a full-text search index on the specified entity or relationship object, and
3100    if one is required, rebuild it.
3101    
3102  =over 4  =over 4
3103    
3104  =item entityType  =item objectName
3105    
3106  Entity type name.  Name of the entity or relationship to be indexed.
3107    
3108  =item ID  =back
3109    
3110  ID of the desired entity.  =cut
3111    
3112  =item RETURN  sub CreateSearchIndex {
3113        # Get the parameters.
3114        my ($self, $objectName) = @_;
3115        # Get the relation's entity/relationship structure.
3116        my $structure = $self->_GetStructure($objectName);
3117        # Get the database handle.
3118        my $dbh = $self->{_dbh};
3119        Trace("Checking for search fields in $objectName.") if T(3);
3120        # Check for a searchable fields list.
3121        if (exists $structure->{searchFields}) {
3122            # Here we know that we need to create a full-text search index.
3123            # Get an SQL-formatted field name list.
3124            my $fields = join(", ", _FixNames(@{$structure->{searchFields}}));
3125            # Create the index. If it already exists, it will be dropped.
3126            $dbh->create_index(tbl => $objectName, idx => "search_idx",
3127                               flds => $fields, kind => 'fulltext');
3128            Trace("Index created for $fields in $objectName.") if T(2);
3129        }
3130    }
3131    
3132  Returns a B<DBObject> representing the desired entity instance, or an undefined value if no  =head3 DropRelation
3133  instance is found with the specified key.  
3134        $erdb->DropRelation($relationName);
3135    
3136    Physically drop a relation from the database.
3137    
3138    =over 4
3139    
3140    =item relationName
3141    
3142    Name of the relation to drop. If it does not exist, this method will have
3143    no effect.
3144    
3145  =back  =back
3146    
3147  =cut  =cut
3148    
3149  sub GetEntity {  sub DropRelation {
3150      # Get the parameters.      # Get the parameters.
3151      my ($self, $entityType, $ID) = @_;      my ($self, $relationName) = @_;
3152      # Create a query.      # Get the database handle.
3153      my $query = $self->Get([$entityType], "$entityType(id) = ?", [$ID]);      my $dbh = $self->{_dbh};
3154      # Get the first (and only) object.      # Drop the relation. The method used here has no effect if the relation
3155      my $retVal = $query->Fetch();      # does not exist.
3156      # Return the result.      Trace("Invoking DB Kernel to drop $relationName.") if T(3);
3157      return $retVal;      $dbh->drop_table(tbl => $relationName);
3158  }  }
3159    
3160  =head3 GetChoices  =head3 MatchSqlPattern
   
 C<< my @values = $erdb->GetChoices($entityName, $fieldName); >>  
3161    
3162  Return a list of all the values for the specified field that are represented in the      my $matched = ERDB::MatchSqlPattern($value, $pattern);
 specified entity.  
3163    
3164  Note that if the field is not indexed, then this will be a very slow operation.  Determine whether or not a specified value matches an SQL pattern. An SQL
3165    pattern has two wild card characters: C<%> that matches multiple characters,
3166    and C<_> that matches a single character. These can be escaped using a
3167    backslash (C<\>). We pull this off by converting the SQL pattern to a
3168    PERL regular expression. As per SQL rules, the match is case-insensitive.
3169    
3170  =over 4  =over 4
3171    
3172  =item entityName  =item value
3173    
3174  Name of an entity in the database.  Value to be matched against the pattern. Note that an undefined or empty
3175    value will not match anything.
3176    
3177  =item fieldName  =item pattern
3178    
3179  Name of a field belonging to the entity. This is a raw field name without  SQL pattern against which to match the value. An undefined or empty pattern will
3180  the standard parenthesized notation used in most calls.  match everything.
3181    
3182    =item RETURN
3183    
3184    Returns TRUE if the value and pattern match, else FALSE.
3185    
3186    =back
3187    
3188    =cut
3189    
3190    sub MatchSqlPattern {
3191        # Get the parameters.
3192        my ($value, $pattern) = @_;
3193        # Declare the return variable.
3194        my $retVal;
3195        # Insure we have a pattern.
3196        if (! defined($pattern) || $pattern eq "") {
3197            $retVal = 1;
3198        } else {
3199            # Break the pattern into pieces around the wildcard characters. Because we
3200            # use parentheses in the split function's delimiter expression, we'll get
3201            # list elements for the delimiters as well as the rest of the string.
3202            my @pieces = split /([_%]|\\[_%])/, $pattern;
3203            # Check some fast special cases.
3204            if ($pattern eq '%') {
3205                # A null pattern matches everything.
3206                $retVal = 1;
3207            } elsif (@pieces == 1) {
3208                # No wildcards, so we have a literal comparison. Note we're case-insensitive.
3209                $retVal = (lc($value) eq lc($pattern));
3210            } elsif (@pieces == 2 && $pieces[1] eq '%') {
3211                # A wildcard at the end, so we have a substring match. This is also case-insensitive.
3212                $retVal = (lc(substr($value, 0, length($pieces[0]))) eq lc($pieces[0]));
3213            } else {
3214                # Okay, we have to do it the hard way. Convert each piece to a PERL pattern.
3215                my $realPattern = "";
3216                for my $piece (@pieces) {
3217                    # Determine the type of piece.
3218                    if ($piece eq "") {
3219                        # Empty pieces are ignored.
3220                    } elsif ($piece eq "%") {
3221                        # Here we have a multi-character wildcard. Note that it can match
3222                        # zero or more characters.
3223                        $realPattern .= ".*"
3224                    } elsif ($piece eq "_") {
3225                        # Here we have a single-character wildcard.
3226                        $realPattern .= ".";
3227                    } elsif ($piece eq "\\%" || $piece eq "\\_") {
3228                        # This is an escape sequence (which is a rare thing, actually).
3229                        $realPattern .= substr($piece, 1, 1);
3230                    } else {
3231                        # Here we have raw text.
3232                        $realPattern .= quotemeta($piece);
3233                    }
3234                }
3235                # Do the match.
3236                $retVal = ($value =~ /^$realPattern$/i ? 1 : 0);
3237            }
3238        }
3239        # Return the result.
3240        return $retVal;
3241    }
3242    
3243    =head3 GetEntity
3244    
3245        my $entityObject = $erdb->GetEntity($entityType, $ID);
3246    
3247    Return an object describing the entity instance with a specified ID.
3248    
3249    =over 4
3250    
3251    =item entityType
3252    
3253    Entity type name.
3254    
3255    =item ID
3256    
3257    ID of the desired entity.
3258    
3259    =item RETURN
3260    
3261    Returns a B<ERDBObject> representing the desired entity instance, or an undefined value if no
3262    instance is found with the specified key.
3263    
3264    =back
3265    
3266    =cut
3267    
3268    sub GetEntity {
3269        # Get the parameters.
3270        my ($self, $entityType, $ID) = @_;
3271        # Create a query.
3272        my $query = $self->Get([$entityType], "$entityType(id) = ?", [$ID]);
3273        # Get the first (and only) object.
3274        my $retVal = $query->Fetch();
3275        if (T(3)) {
3276            if ($retVal) {
3277                Trace("Entity $entityType \"$ID\" found.");
3278            } else {
3279                Trace("Entity $entityType \"$ID\" not found.");
3280            }
3281        }
3282        # Return the result.
3283        return $retVal;
3284    }
3285    
3286    =head3 GetChoices
3287    
3288        my @values = $erdb->GetChoices($entityName, $fieldName);
3289    
3290    Return a list of all the values for the specified field that are represented in the
3291    specified entity.
3292    
3293    Note that if the field is not indexed, then this will be a very slow operation.
3294    
3295    =over 4
3296    
3297    =item entityName
3298    
3299    Name of an entity in the database.
3300    
3301    =item fieldName
3302    
3303    Name of a field belonging to the entity. This is a raw field name without
3304    the standard parenthesized notation used in most calls.
3305    
3306  =item RETURN  =item RETURN
3307    
# Line 2214  Line 3340 
3340    
3341  =head3 GetEntityValues  =head3 GetEntityValues
3342    
3343  C<< my @values = $erdb->GetEntityValues($entityType, $ID, \@fields); >>      my @values = $erdb->GetEntityValues($entityType, $ID, \@fields);
3344    
3345  Return a list of values from a specified entity instance. If the entity instance  Return a list of values from a specified entity instance. If the entity instance
3346  does not exist, an empty list is returned.  does not exist, an empty list is returned.
# Line 2258  Line 3384 
3384    
3385  =head3 GetAll  =head3 GetAll
3386    
3387  C<< my @list = $erdb->GetAll(\@objectNames, $filterClause, \@parameters, \@fields, $count); >>      my @list = $erdb->GetAll(\@objectNames, $filterClause, \@parameters, \@fields, $count);
3388    
3389  Return a list of values taken from the objects returned by a query. The first three  Return a list of values taken from the objects returned by a query. The first three
3390  parameters correspond to the parameters of the L</Get> method. The final parameter is  parameters correspond to the parameters of the L</Get> method. The final parameter is
# Line 2272  Line 3398 
3398  fields specified returns multiple values, they are flattened in with the rest. For  fields specified returns multiple values, they are flattened in with the rest. For
3399  example, the following call will return a list of the features in a particular  example, the following call will return a list of the features in a particular
3400  spreadsheet cell, and each feature will be represented by a list containing the  spreadsheet cell, and each feature will be represented by a list containing the
3401  feature ID followed by all of its aliases.  feature ID followed by all of its essentiality determinations.
3402    
3403  C<< $query = $erdb->Get(['ContainsFeature', 'Feature'], "ContainsFeature(from-link) = ?", [$ssCellID], ['Feature(id)', 'Feature(alias)']); >>      @query = $erdb->Get(['ContainsFeature', 'Feature'], "ContainsFeature(from-link) = ?", [$ssCellID], ['Feature(id)', 'Feature(essential)']);
3404    
3405  =over 4  =over 4
3406    
# Line 2297  Line 3423 
3423    
3424  =item fields  =item fields
3425    
3426  List of the fields to be returned in each element of the list returned.  List of the fields to be returned in each element of the list returned.
3427    
3428    =item count
3429    
3430    Maximum number of records to return. If omitted or 0, all available records will be returned.
3431    
3432    =item RETURN
3433    
3434    Returns a list of list references. Each element of the return list contains the values for the
3435    fields specified in the B<fields> parameter.
3436    
3437    =back
3438    
3439    =cut
3440    #: Return Type @@;
3441    sub GetAll {
3442        # Get the parameters.
3443        my ($self, $objectNames, $filterClause, $parameterList, $fields, $count) = @_;
3444        # Translate the parameters from a list reference to a list. If the parameter
3445        # list is a scalar we convert it into a singleton list.
3446        my @parmList = ();
3447        if (ref $parameterList eq "ARRAY") {
3448            Trace("GetAll parm list is an array.") if T(4);
3449            @parmList = @{$parameterList};
3450        } else {
3451            Trace("GetAll parm list is a scalar: $parameterList.") if T(4);
3452            push @parmList, $parameterList;
3453        }
3454        # Insure the counter has a value.
3455        if (!defined $count) {
3456            $count = 0;
3457        }
3458        # Add the row limit to the filter clause.
3459        if ($count > 0) {
3460            $filterClause .= " LIMIT $count";
3461        }
3462        # Create the query.
3463        my $query = $self->Get($objectNames, $filterClause, \@parmList);
3464        # Set up a counter of the number of records read.
3465        my $fetched = 0;
3466        # Loop through the records returned, extracting the fields. Note that if the
3467        # counter is non-zero, we stop when the number of records read hits the count.
3468        my @retVal = ();
3469        while (($count == 0 || $fetched < $count) && (my $row = $query->Fetch())) {
3470            my @rowData = $row->Values($fields);
3471            push @retVal, \@rowData;
3472            $fetched++;
3473        }
3474        # Return the resulting list.
3475        return @retVal;
3476    }
3477    
3478    =head3 Exists
3479    
3480        my $found = $sprout->Exists($entityName, $entityID);
3481    
3482    Return TRUE if an entity exists, else FALSE.
3483    
3484    =over 4
3485    
3486    =item entityName
3487    
3488    Name of the entity type (e.g. C<Feature>) relevant to the existence check.
3489    
3490    =item entityID
3491    
3492    ID of the entity instance whose existence is to be checked.
3493    
3494    =item RETURN
3495    
3496    Returns TRUE if the entity instance exists, else FALSE.
3497    
3498    =back
3499    
3500    =cut
3501    #: Return Type $;
3502    sub Exists {
3503        # Get the parameters.
3504        my ($self, $entityName, $entityID) = @_;
3505        # Check for the entity instance.
3506        Trace("Checking existence of $entityName with ID=$entityID.") if T(4);
3507        my $testInstance = $self->GetEntity($entityName, $entityID);
3508        # Return an existence indicator.
3509        my $retVal = ($testInstance ? 1 : 0);
3510        return $retVal;
3511    }
3512    
3513    =head3 EstimateRowSize
3514    
3515        my $rowSize = $erdb->EstimateRowSize($relName);
3516    
3517    Estimate the row size of the specified relation. The estimated row size is computed by adding
3518    up the average length for each data type.
3519    
3520    =over 4
3521    
3522    =item relName
3523    
3524    Name of the relation whose estimated row size is desired.
3525    
3526    =item RETURN
3527    
3528    Returns an estimate of the row size for the specified relation.
3529    
3530    =back
3531    
3532    =cut
3533    #: Return Type $;
3534    sub EstimateRowSize {
3535        # Get the parameters.
3536        my ($self, $relName) = @_;
3537        # Declare the return variable.
3538        my $retVal = 0;
3539        # Find the relation descriptor.
3540        my $relation = $self->_FindRelation($relName);
3541        # Get the list of fields.
3542        for my $fieldData (@{$relation->{Fields}}) {
3543            # Get the field type and add its length.
3544            my $fieldLen = $TypeTable{$fieldData->{type}}->{avgLen};
3545            $retVal += $fieldLen;
3546        }
3547        # Return the result.
3548        return $retVal;
3549    }
3550    
3551    =head3 GetFieldTable
3552    
3553        my $fieldHash = $self->GetFieldTable($objectnName);
3554    
3555    Get the field structure for a specified entity or relationship.
3556    
3557    =over 4
3558    
3559    =item objectName
3560    
3561    Name of the desired entity or relationship.
3562    
3563    =item RETURN
3564    
3565    The table containing the field descriptors for the specified object.
3566    
3567    =back
3568    
3569    =cut
3570    
3571    sub GetFieldTable {
3572        # Get the parameters.
3573        my ($self, $objectName) = @_;
3574        # Get the descriptor from the metadata.
3575        my $objectData = $self->_GetStructure($objectName);
3576        # Return the object's field table.
3577        return $objectData->{Fields};
3578    }
3579    
3580    =head3 SplitKeywords
3581    
3582        my @keywords = ERDB::SplitKeywords($keywordString);
3583    
3584    This method returns a list of the positive keywords in the specified
3585    keyword string. All of the operators will have been stripped off,
3586    and if the keyword is preceded by a minus operator (C<->), it will
3587    not be in the list returned. The idea here is to get a list of the
3588    keywords the user wants to see. The list will be processed to remove
3589    duplicates.
3590    
3591    It is possible to create a string that confuses this method. For example
3592    
3593        frog toad -frog
3594    
3595    would return both C<frog> and C<toad>. If this is a problem we can deal
3596    with it later.
3597    
3598    =over 4
3599    
3600    =item keywordString
3601    
3602    The keyword string to be parsed.
3603    
3604    =item RETURN
3605    
3606    Returns a list of the words in the keyword string the user wants to
3607    see.
3608    
3609    =back
3610    
3611    =cut
3612    
3613    sub SplitKeywords {
3614        # Get the parameters.
3615        my ($keywordString) = @_;
3616        # Make a safety copy of the string. (This helps during debugging.)
3617        my $workString = $keywordString;
3618        # Convert operators we don't care about to spaces.
3619        $workString =~ tr/+"()<>/ /;
3620        # Split the rest of the string along space boundaries. Note that we
3621        # eliminate any words that are zero length or begin with a minus sign.
3622        my @wordList = grep { $_ && substr($_, 0, 1) ne "-" } split /\s+/, $workString;
3623        # Use a hash to remove duplicates.
3624        my %words = map { $_ => 1 } @wordList;
3625        # Return the result.
3626        return sort keys %words;
3627    }
3628    
3629    =head3 ValidateFieldName
3630    
3631        my $okFlag = ERDB::ValidateFieldName($fieldName);
3632    
3633    Return TRUE if the specified field name is valid, else FALSE. Valid field names must
3634    be hyphenated words subject to certain restrictions.
3635    
3636    =over 4
3637    
3638    =item fieldName
3639    
3640    Field name to be validated.
3641    
3642    =item RETURN
3643    
3644    Returns TRUE if the field name is valid, else FALSE.
3645    
3646    =back
3647    
3648    =cut
3649    
3650    sub ValidateFieldName {
3651        # Get the parameters.
3652        my ($fieldName) = @_;
3653        # Declare the return variable. The field name is valid until we hear
3654        # differently.
3655        my $retVal = 1;
3656        # Compute the maximum name length.
3657        my $maxLen = $TypeTable{'name-string'}->{maxLen};
3658        # Look for bad stuff in the name.
3659        if ($fieldName =~ /--/) {
3660            # Here we have a doubled minus sign.
3661            Trace("Field name $fieldName has a doubled hyphen.") if T(1);
3662            $retVal = 0;
3663        } elsif ($fieldName !~ /^[A-Za-z]/) {
3664            # Here the field name is missing the initial letter.
3665            Trace("Field name $fieldName does not begin with a letter.") if T(1);
3666            $retVal = 0;
3667        } elsif (length($fieldName) > $maxLen) {
3668            # Here the field name is too long.
3669            Trace("Maximum field name length is $maxLen. Field name must be truncated to " . substr($fieldName,0, $maxLen) . ".");
3670        } else {
3671            # Strip out the minus signs. Everything remaining must be a letter,
3672            # underscore, or digit.
3673            my $strippedName = $fieldName;
3674            $strippedName =~ s/-//g;
3675            if ($strippedName !~ /^(\w|\d)+$/) {
3676                Trace("Field name $fieldName contains illegal characters.") if T(1);
3677                $retVal = 0;
3678            }
3679        }
3680        # Return the result.
3681        return $retVal;
3682    }
3683    
3684    =head3 ReadMetaXML
3685    
3686        my $rawMetaData = ERDB::ReadDBD($fileName);
3687    
3688    This method reads a raw database definition XML file and returns it.
3689    Normally, the metadata used by the ERDB system has been processed and
3690    modified to make it easier to load and retrieve the data; however,
3691    this method can be used to get the data in its raw form.
3692    
3693    =over 4
3694    
3695    =item fileName
3696    
3697    Name of the XML file to read.
3698    
3699    =item RETURN
3700    
3701    Returns a hash reference containing the raw XML data from the specified file.
3702    
3703    =back
3704    
3705    =cut
3706    
3707    sub ReadMetaXML {
3708        # Get the parameters.
3709        my ($fileName) = @_;
3710        # Read the XML.
3711        my $retVal = XML::Simple::XMLin($fileName, %XmlOptions, %XmlInOpts);
3712        Trace("XML metadata loaded from file $fileName.") if T(1);
3713        # Return the result.
3714        return $retVal;
3715    }
3716    
3717    =head3 GetEntityFieldHash
3718    
3719        my $fieldHashRef = ERDB::GetEntityFieldHash($structure, $entityName);
3720    
3721    Get the field hash of the named entity in the specified raw XML structure.
3722    The field hash may not exist, in which case we need to create it.
3723    
3724    =over 4
3725    
3726    =item structure
3727    
3728    Raw XML structure defininng the database. This is not the run-time XML used by
3729    an ERDB object, since that has all sorts of optimizations built-in.
3730    
3731    =item entityName
3732    
3733    Name of the entity whose field structure is desired.
3734    
3735    =item RETURN
3736    
3737    Returns the field hash used to define the entity's fields.
3738    
3739    =back
3740    
3741    =cut
3742    
3743    sub GetEntityFieldHash {
3744        # Get the parameters.
3745        my ($structure, $entityName) = @_;
3746        # Get the entity structure.
3747        my $entityData = $structure->{Entities}->{$entityName};
3748        # Look for a field structure.
3749        my $retVal = $entityData->{Fields};
3750        # If it doesn't exist, create it.
3751        if (! defined($retVal)) {
3752            $entityData->{Fields} = {};
3753            $retVal = $entityData->{Fields};
3754        }
3755        # Return the result.
3756        return $retVal;
3757    }
3758    
3759    =head3 WriteMetaXML
3760    
3761        ERDB::WriteMetaXML($structure, $fileName);
3762    
3763    Write the metadata XML to a file. This method is the reverse of L</ReadMetaXML>, and is
3764    used to update the database definition. It must be used with care, however, since it
3765    will only work on a raw structure, not on the processed structure created by an ERDB
3766    constructor.
3767    
3768    =over 4
3769    
3770  =item count  =item structure
3771    
3772  Maximum number of records to return. If omitted or 0, all available records will be returned.  XML structure to be written to the file.
3773    
3774  =item RETURN  =item fileName
3775    
3776  Returns a list of list references. Each element of the return list contains the values for the  Name of the output file to which the updated XML should be stored.
 fields specified in the B<fields> parameter.  
3777    
3778  =back  =back
3779    
3780  =cut  =cut
3781  #: Return Type @@;  
3782  sub GetAll {  sub WriteMetaXML {
3783      # Get the parameters.      # Get the parameters.
3784      my ($self, $objectNames, $filterClause, $parameterList, $fields, $count) = @_;      my ($structure, $fileName) = @_;
3785      # Translate the parameters from a list reference to a list. If the parameter      # Compute the output.
3786      # list is a scalar we convert it into a singleton list.      my $fileString = XML::Simple::XMLout($structure, %XmlOptions, %XmlOutOpts);
3787      my @parmList = ();      # Write it to the file.
3788      if (ref $parameterList eq "ARRAY") {      my $xmlOut = Open(undef, ">$fileName");
3789          Trace("GetAll parm list is an array.") if T(4);      print $xmlOut $fileString;
         @parmList = @{$parameterList};  
     } else {  
         Trace("GetAll parm list is a scalar: $parameterList.") if T(4);  
         push @parmList, $parameterList;  
     }  
     # Insure the counter has a value.  
     if (!defined $count) {  
         $count = 0;  
     }  
     # Add the row limit to the filter clause.  
     if ($count > 0) {  
         $filterClause .= " LIMIT $count";  
     }  
     # Create the query.  
     my $query = $self->Get($objectNames, $filterClause, \@parmList);  
     # Set up a counter of the number of records read.  
     my $fetched = 0;  
     # Loop through the records returned, extracting the fields. Note that if the  
     # counter is non-zero, we stop when the number of records read hits the count.  
     my @retVal = ();  
     while (($count == 0 || $fetched < $count) && (my $row = $query->Fetch())) {  
         my @rowData = $row->Values($fields);  
         push @retVal, \@rowData;  
         $fetched++;  
     }  
     Trace("$fetched rows returned in GetAll.") if T(SQL => 4);  
     # Return the resulting list.  
     return @retVal;  
3790  }  }
3791    
 =head3 Exists  
   
 C<< my $found = $sprout->Exists($entityName, $entityID); >>  
3792    
3793  Return TRUE if an entity exists, else FALSE.  =head3 HTMLNote
3794    
3795  =over 4  Convert a note or comment to HTML by replacing some bulletin-board codes with HTML. The codes
3796    supported are C<[b]> for B<bold>, C<[i]> for I<italics>, and C<[p]> for a new paragraph.
3797    Except for C<[p]>, all the codes are closed by slash-codes. So, for
3798    example, C<[b]Feature[/b]> displays the string C<Feature> in boldface.
3799    
3800  =item entityName      my $realHtml = ERDB::HTMLNote($dataString);
3801    
3802  Name of the entity type (e.g. C<Feature>) relevant to the existence check.  =over 4
3803    
3804  =item entityID  =item dataString
3805    
3806  ID of the entity instance whose existence is to be checked.  String to convert to HTML.
3807    
3808  =item RETURN  =item RETURN
3809    
3810  Returns TRUE if the entity instance exists, else FALSE.  An HTML string derived from the input string.
3811    
3812  =back  =back
3813    
3814  =cut  =cut
3815  #: Return Type $;  
3816  sub Exists {  sub HTMLNote {
3817      # Get the parameters.      # Get the parameter.
3818      my ($self, $entityName, $entityID) = @_;      my ($dataString) = @_;
3819      # Check for the entity instance.      # HTML-escape the text.
3820      Trace("Checking existence of $entityName with ID=$entityID.") if T(4);      my $retVal = CGI::escapeHTML($dataString);
3821      my $testInstance = $self->GetEntity($entityName, $entityID);      # Substitute the bulletin board codes.
3822      # Return an existence indicator.      $retVal =~ s!\[(/?[bi])\]!<$1>!g;
3823      my $retVal = ($testInstance ? 1 : 0);      $retVal =~ s!\[p\]!</p><p>!g;
3824        $retVal =~ s!\[link\s+([^\]]+)\]!<a href="$1">!g;
3825        $retVal =~ s!\[/link\]!</a>!g;
3826        # Return the result.
3827      return $retVal;      return $retVal;
3828  }  }
3829    
3830  =head3 EstimateRowSize  =head3 WikiNote
3831    
3832  C<< my $rowSize = $erdb->EstimateRowSize($relName); >>  Convert a note or comment to Wiki text by replacing some bulletin-board codes with HTML. The codes
3833    supported are C<[b]> for B<bold>, C<[i]> for I<italics>, and C<[p]> for a new paragraph.
3834    Except for C<[p]>, all the codes are closed by slash-codes. So, for
3835    example, C<[b]Feature[/b]> displays the string C<Feature> in boldface.
3836    
3837  Estimate the row size of the specified relation. The estimated row size is computed by adding      my $wikiText = ERDB::WikiNote($dataString);
 up the average length for each data type.  
3838    
3839  =over 4  =over 4
3840    
3841  =item relName  =item dataString
3842    
3843  Name of the relation whose estimated row size is desired.  String to convert to Wiki text.
3844    
3845  =item RETURN  =item RETURN
3846    
3847  Returns an estimate of the row size for the specified relation.  An Wiki text string derived from the input string.
3848    
3849  =back  =back
3850    
3851  =cut  =cut
3852  #: Return Type $;  
3853  sub EstimateRowSize {  sub WikiNote {
3854      # Get the parameters.      # Get the parameter.
3855      my ($self, $relName) = @_;      my ($dataString) = @_;
3856      # Declare the return variable.      # HTML-escape the text.
3857      my $retVal = 0;      my $retVal = CGI::escapeHTML($dataString);
3858      # Find the relation descriptor.      # Substitute the bulletin board codes.
3859      my $relation = $self->_FindRelation($relName);      my $italic = WikiTools::ItalicCode();
3860      # Get the list of fields.      $retVal =~ s/\[\/?i\]/$italic/g;
3861      for my $fieldData (@{$relation->{Fields}}) {      my $bold = WikiTools::BoldCode();
3862          # Get the field type and add its length.      $retVal =~ s/\[\/?b\]/$bold/g;
3863          my $fieldLen = $TypeTable{$fieldData->{type}}->{avgLen};      # Paragraph breaks are the same no matter which Wiki you're using.
3864          $retVal += $fieldLen;      $retVal =~ s!\[p\]!\n\n!g;
3865        # Now we do the links, which are complicated by the need to know two
3866        # things: the target URL and the text.
3867        while ($retVal =~ /\[link\s+([^\]]+)\]([^\[]+)\[\/link\]/g) {
3868            # Replace the matched string with the Wiki markup for links. Note that
3869            # $-[0] is the starting position of the match for the entire expression,
3870            # and $+[0] is past the ending position.
3871            substr $retVal, $-[0], $+[0] - $-[0], WikiTools::LinkMarkup($1, $2);
3872      }      }
3873      # Return the result.      # Return the result.
3874      return $retVal;      return $retVal;
3875  }  }
3876    
3877  =head3 GetFieldTable  =head3 BeginTran
3878    
3879  C<< my $fieldHash = $self->GetFieldTable($objectnName); >>      $erdb->BeginTran();
3880    
3881  Get the field structure for a specified entity or relationship.  Start a database transaction.
3882    
3883    =cut
3884    
3885    sub BeginTran {
3886        my ($self) = @_;
3887        $self->{_dbh}->begin_tran();
3888    
3889    }
3890    
3891    =head3 CommitTran
3892    
3893        $erdb->CommitTran();
3894    
3895    Commit an active database transaction.
3896    
3897    =cut
3898    
3899    sub CommitTran {
3900        my ($self) = @_;
3901        $self->{_dbh}->commit_tran();
3902    }
3903    
3904    =head3 RollbackTran
3905    
3906        $erdb->RollbackTran();
3907    
3908    Roll back an active database transaction.
3909    
3910    =cut
3911    
3912    sub RollbackTran {
3913        my ($self) = @_;
3914        $self->{_dbh}->roll_tran();
3915    }
3916    
3917    =head3 UpdateField
3918    
3919        my $count = $erdb->UpdateField($objectNames, $fieldName, $oldValue, $newValue, $filter, $parms);
3920    
3921    Update all occurrences of a specific field value to a new value. The number of rows changed will be
3922    returned.
3923    
3924  =over 4  =over 4
3925    
3926  =item objectName  =item fieldName
3927    
3928  Name of the desired entity or relationship.  Name of the field in standard I<objectName>C<(>I<fieldName>C<)> format.
3929    
3930    =item oldValue
3931    
3932    Value to be modified. All occurrences of this value in the named field will be replaced by the
3933    new value.
3934    
3935    =item newValue
3936    
3937    New value to be substituted for the old value when it's found.
3938    
3939    =item filter
3940    
3941    A standard ERDB filter clause (see L</Get>). The filter will be applied before any substitutions take place.
3942    
3943    =item parms
3944    
3945    Reference to a list of parameter values in the filter.
3946    
3947  =item RETURN  =item RETURN
3948    
3949  The table containing the field descriptors for the specified object.  Returns the number of rows modified.
3950    
3951  =back  =back
3952    
3953  =cut  =cut
3954    
3955  sub GetFieldTable {  sub UpdateField {
3956      # Get the parameters.      # Get the parameters.
3957      my ($self, $objectName) = @_;      my ($self, $fieldName, $oldValue, $newValue, $filter, $parms) = @_;
3958      # Get the descriptor from the metadata.      # Get the object and field names from the field name parameter.
3959      my $objectData = $self->_GetStructure($objectName);      $fieldName =~ /^([^(]+)\(([^)]+)\)/;
3960      # Return the object's field table.      my $objectName = $1;
3961      return $objectData->{Fields};      my $realFieldName = _FixName($2);
3962        # Add the old value to the filter. Note we allow the possibility that no
3963        # filter was specified.
3964        my $realFilter = "$fieldName = ?";
3965        if ($filter) {
3966            $realFilter .= " AND $filter";
3967        }
3968        # Format the query filter.
3969        my ($suffix, $mappedNameListRef, $mappedNameHashRef) =
3970            $self->_SetupSQL([$objectName], $realFilter);
3971        # Create the query. Since there is only one object name, the mapped-name data is not
3972        # necessary. Neither is the FROM clause.
3973        $suffix =~ s/^FROM.+WHERE\s+//;
3974        # Create the update statement.
3975        my $command = "UPDATE $objectName SET $realFieldName = ? WHERE $suffix";
3976        # Get the database handle.
3977        my $dbh = $self->{_dbh};
3978        # Add the old and new values to the parameter list. Note we allow the possibility that
3979        # there are no user-supplied parameters.
3980        my @params = ($newValue, $oldValue);
3981        if (defined $parms) {
3982            push @params, @{$parms};
3983        }
3984        # Execute the update.
3985        my $retVal = $dbh->SQL($command, 0, @params);
3986        # Make the funky zero a real zero.
3987        if ($retVal == 0) {
3988            $retVal = 0;
3989        }
3990        # Return the result.
3991        return $retVal;
3992  }  }
3993    
3994    
3995  =head2 Data Mining Methods  =head2 Data Mining Methods
3996    
3997  =head3 GetUsefulCrossValues  =head3 GetUsefulCrossValues
3998    
3999  C<< my @attrNames = $sprout->GetUsefulCrossValues($sourceEntity, $relationship); >>      my @attrNames = $sprout->GetUsefulCrossValues($sourceEntity, $relationship);
4000    
4001  Return a list of the useful attributes that would be returned by a B<Cross> call  Return a list of the useful attributes that would be returned by a B<Cross> call
4002  from an entity of the source entity type through the specified relationship. This  from an entity of the source entity type through the specified relationship. This
# Line 2517  Line 4057 
4057    
4058  =head3 FindColumn  =head3 FindColumn
4059    
4060  C<< my $colIndex = ERDB::FindColumn($headerLine, $columnIdentifier); >>      my $colIndex = ERDB::FindColumn($headerLine, $columnIdentifier);
4061    
4062  Return the location a desired column in a data mining header line. The data  Return the location a desired column in a data mining header line. The data
4063  mining header line is a tab-separated list of column names. The column  mining header line is a tab-separated list of column names. The column
# Line 2575  Line 4115 
4115    
4116  =head3 ParseColumns  =head3 ParseColumns
4117    
4118  C<< my @columns = ERDB::ParseColumns($line); >>      my @columns = ERDB::ParseColumns($line);
4119    
4120  Convert the specified data line to a list of columns.  Convert the specified data line to a list of columns.
4121    
# Line 2607  Line 4147 
4147    
4148  =head2 Virtual Methods  =head2 Virtual Methods
4149    
4150    =head3 _CreatePPOIndex
4151    
4152        my $index = ERDB::_CreatePPOIndex($indexObject);
4153    
4154    Convert the XML for an ERDB index to the XML structure for a PPO
4155    index.
4156    
4157    =over 4
4158    
4159    =item indexObject
4160    
4161    ERDB XML structure for an index.
4162    
4163    =item RETURN
4164    
4165    PPO XML structure for the same index.
4166    
4167    =back
4168    
4169    =cut
4170    
4171    sub _CreatePPOIndex {
4172        # Get the parameters.
4173        my ($indexObject) = @_;
4174        # The incoming index contains a list of the index fields in the IndexFields
4175        # member. We loop through it to create the index tags.
4176        my @fields = map { { label => _FixName($_->{name}) } } @{$indexObject->{IndexFields}};
4177        # Wrap the fields in attribute tags.
4178        my $retVal = { attribute => \@fields };
4179        # Return the result.
4180        return $retVal;
4181    }
4182    
4183    =head3 _CreatePPOField
4184    
4185        my $fieldXML = ERDB::_CreatePPOField($fieldName, $fieldObject);
4186    
4187    Convert the ERDB XML structure for a field to a PPO scalar XML structure.
4188    
4189    =over 4
4190    
4191    =item fieldName
4192    
4193    Name of the scalar field.
4194    
4195    =item fieldObject
4196    
4197    ERDB XML structure describing the field.
4198    
4199    =item RETURN
4200    
4201    Returns a PPO XML structure for the same field.
4202    
4203    =back
4204    
4205    =cut
4206    
4207    sub _CreatePPOField {
4208        # Get the parameters.
4209        my ($fieldName, $fieldObject) = @_;
4210        # Get the field type.
4211        my $type = $TypeTable{$fieldObject->{type}}->{sqlType};
4212        # Fix up the field name.
4213        $fieldName = _FixName($fieldName);
4214        # Build the scalar tag.
4215        my $retVal = { label => $fieldName, type => $type };
4216        # Return the result.
4217        return $retVal;
4218    }
4219    
4220  =head3 CleanKeywords  =head3 CleanKeywords
4221    
4222  C<< my $cleanedString = $erdb->CleanKeywords($searchExpression); >>      my $cleanedString = $erdb->CleanKeywords($searchExpression);
4223    
4224  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
4225  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 4254 
4254      return $retVal;      return $retVal;
4255  }  }
4256    
4257    =head3 GetSourceObject
4258    
4259        my $source = $erdb->GetSourceObject($entityName);
4260    
4261    Return the object to be used in loading special attributes of the specified entity. The
4262    algorithm for loading special attributes is stored in the C<DataGen> elements of the
4263    XML
4264    
4265  =head2 Internal Utility Methods  =head2 Internal Utility Methods
4266    
4267  =head3 _RelationMap  =head3 _RelationMap
4268    
4269  C<< my @relationMap = _RelationMap($mappedNameHashRef, $mappedNameListRef); >>      my @relationMap = _RelationMap($mappedNameHashRef, $mappedNameListRef);
4270    
4271  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>
4272  to determine how to interpret the results of the query.  to determine how to interpret the results of the query.
4273    
4274  =over 4  =over 4
# Line 2667  Line 4285 
4285  =item RETURN  =item RETURN
4286    
4287  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
4288  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
4289  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
4290  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
4291  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 4579 
4579  sub _GetStatementHandle {  sub _GetStatementHandle {
4580      # Get the parameters.      # Get the parameters.
4581      my ($self, $command, $params) = @_;      my ($self, $command, $params) = @_;
4582        Confess("Invalid parameter list.") if (! defined($params) || ref($params) ne 'ARRAY');
4583      # Trace the query.      # Trace the query.
4584      Trace("SQL query: $command") if T(SQL => 3);      Trace("SQL query: $command") if T(SQL => 3);
4585      Trace("PARMS: '" . (join "', '", @{$params}) . "'") if (T(SQL => 4) && (@{$params} > 0));      Trace("PARMS: '" . (join "', '", @{$params}) . "'") if (T(SQL => 4) && (@{$params} > 0));
# Line 2969  Line 4588 
4588      # Prepare the command.      # Prepare the command.
4589      my $sth = $dbh->prepare_command($command);      my $sth = $dbh->prepare_command($command);
4590      # Execute it with the parameters bound in.      # Execute it with the parameters bound in.
4591      $sth->execute(@{$params}) || Confess("SELECT error" . $sth->errstr());      $sth->execute(@{$params}) || Confess("SELECT error:  " . $sth->errstr());
4592      # Return the statement handle.      # Return the statement handle.
4593      return $sth;      return $sth;
4594  }  }
# Line 2986  Line 4605 
4605      return Stats->new();      return Stats->new();
4606  }  }
4607    
 =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;  
             }  
         }  
     }  
 }  
   
4608  =head3 _DumpRelation  =head3 _DumpRelation
4609    
4610  Dump the specified relation's to the specified output file in tab-delimited format.  Dump the specified relation to the specified output file in tab-delimited format.
4611    
4612  This is an instance method.  This is an instance method.
4613    
# Line 3207  Line 4752 
4752          for my $object (values %{$metadata->{$section}}) {          for my $object (values %{$metadata->{$section}}) {
4753              # Loop through the object's fields.              # Loop through the object's fields.
4754              for my $fieldName (keys %{$object->{Fields}}) {              for my $fieldName (keys %{$object->{Fields}}) {
4755                  # Now we make some initial validations.                  # If this field name is invalid, set the return value to zero
4756                  if ($fieldName =~ /--/) {                  # so we know we encountered an error.
4757                      # Here we have a doubled minus sign.                  if (! ValidateFieldName($fieldName)) {
                     print STDERR "Field name $fieldName has a doubled hyphen.\n";  
                     $retVal = 0;  
                 } elsif ($fieldName !~ /^[A-Za-z]/) {  
                     # Here the field name is missing the initial letter.  
                     print STDERR "Field name $fieldName does not begin with a letter.\n";  
                     $retVal = 0;  
                 } else {  
                     # Strip out the minus signs. Everything remaining must be a letter  
                     # or digit.  
                     my $strippedName = $fieldName;  
                     $strippedName =~ s/-//g;  
                     if ($strippedName !~ /^[A-Za-z0-9]+$/) {  
                         print STDERR "Field name $fieldName contains illegal characters.\n";  
4758                          $retVal = 0;                          $retVal = 0;
4759                      }                      }
4760                  }                  }
4761              }              }
4762          }          }
     }  
4763      # If an error was found, fail.      # If an error was found, fail.
4764      if ($retVal  == 0) {      if ($retVal  == 0) {
4765          Confess("Errors found in field names.");          Confess("Errors found in field names.");
# Line 3286  Line 4817 
4817      # be a null string.      # be a null string.
4818      if ($fileName ne "") {      if ($fileName ne "") {
4819          # Load the relation from the file.          # Load the relation from the file.
4820          $retVal = $self->LoadTable($fileName, $relationName, $rebuild);          $retVal = $self->LoadTable($fileName, $relationName, truncate => $rebuild);
4821      } elsif ($rebuild) {      } elsif ($rebuild) {
4822          # Here we are rebuilding, but no file exists, so we just re-create the table.          # Here we are rebuilding, but no file exists, so we just re-create the table.
4823          $self->CreateTable($relationName, 1);          $self->CreateTable($relationName, 1);
# Line 3295  Line 4826 
4826      return $retVal;      return $retVal;
4827  }  }
4828    
4829    
4830  =head3 _LoadMetaData  =head3 _LoadMetaData
4831    
4832        my $metadata = ERDB::_LoadMetaData($filename);
4833    
4834  This method loads the data describing this database from an XML file into a metadata structure.  This method loads the data describing this database from an XML file into a metadata structure.
4835  The resulting structure is a set of nested hash tables containing all the information needed to  The resulting structure is a set of nested hash tables containing all the information needed to
4836  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 4854 
4854  sub _LoadMetaData {  sub _LoadMetaData {
4855      # Get the parameters.      # Get the parameters.
4856      my ($filename) = @_;      my ($filename) = @_;
4857      Trace("Reading Sprout DBD from $filename.") if T(2);      Trace("Reading DBD from $filename.") if T(2);
4858      # Slurp the XML file into a variable. Extensive use of options is used to insure we      # Slurp the XML file into a variable. Extensive use of options is used to insure we
4859      # get the exact structure we want.      # get the exact structure we want.
4860      my $metadata = XML::Simple::XMLin($filename,      my $metadata = ReadMetaXML($filename);
                                       GroupTags => { Relationships => 'Relationship',  
                                                      Entities => 'Entity',  
                                                      Fields => 'Field',  
                                                      Indexes => 'Index',  
                                                      IndexFields => 'IndexField'},  
                                       KeyAttr => { Relationship => 'name',  
                                                    Entity => 'name',  
                                                    Field => 'name'},  
                                       ForceArray => ['Field', 'Index', 'IndexField'],  
                                       ForceContent => 1,  
                                       NormalizeSpace => 2  
                                       );  
     Trace("XML metadata loaded from file $filename.") if T(1);  
4861      # Before we go any farther, we need to validate the field and object names. If an error is found,      # Before we go any farther, we need to validate the field and object names. If an error is found,
4862      # the method below will fail.      # the method below will fail.
4863      _ValidateFieldNames($metadata);      _ValidateFieldNames($metadata);
# Line 3459  Line 4980 
4980              if ($found == 0) {              if ($found == 0) {
4981                  push @{$indexList}, { IndexFields => [ {name => 'id', order => 'ascending'} ] };                  push @{$indexList}, { IndexFields => [ {name => 'id', order => 'ascending'} ] };
4982              }              }
4983              # Now we need to convert the relation's index list to an index table. We begin by creating              # Attach all the indexes to the relation.
4984              # an empty table in the relation structure.              _ProcessIndexes($indexList, $relation);
             $relation->{Indexes} = { };  
             # Loop through the indexes.  
             my $count = 0;  
             for my $index (@{$indexList}) {  
                 # Add this index to the index table.  
                 _AddIndex("idx$relationName$count", $relation, $index);  
                 # Increment the counter so that the next index has a different name.  
                 $count++;  
             }  
4985          }          }
4986          # Finally, we add the relation structure to the entity.          # Finally, we add the relation structure to the entity.
4987          $entityStructure->{Relations} = $relationTable;          $entityStructure->{Relations} = $relationTable;
# Line 3483  Line 4995 
4995          _FixupFields($relationshipStructure, $relationshipName, 2, 3);          _FixupFields($relationshipStructure, $relationshipName, 2, 3);
4996          # Format a description for the FROM field.          # Format a description for the FROM field.
4997          my $fromEntity = $relationshipStructure->{from};          my $fromEntity = $relationshipStructure->{from};
4998          my $fromComment = "<b>id</b> of the source <b><a href=\"#$fromEntity\">$fromEntity</a></b>.";          my $fromComment = "[b]id[/b] of the source [b][link #$fromEntity]$fromEntity\[/link][/b].";
4999          # Get the FROM entity's key type.          # Get the FROM entity's key type.
5000          my $fromType = $entityList->{$fromEntity}->{keyType};          my $fromType = $entityList->{$fromEntity}->{keyType};
5001          # Add the FROM field.          # Add the FROM field.
# Line 3493  Line 5005 
5005                                                      PrettySort => 1});                                                      PrettySort => 1});
5006          # Format a description for the TO field.          # Format a description for the TO field.
5007          my $toEntity = $relationshipStructure->{to};          my $toEntity = $relationshipStructure->{to};
5008          my $toComment = "<b>id</b> of the target <b><a href=\"#$toEntity\">$toEntity</a></b>.";          my $toComment = "[b]id[/b] of the target [b][link #$toEntity]$toEntity\[/link][/b].";
5009          # Get the TO entity's key type.          # Get the TO entity's key type.
5010          my $toType = $entityList->{$toEntity}->{keyType};          my $toType = $entityList->{$toEntity}->{keyType};
5011          # Add the TO field.          # Add the TO field.
# Line 3505  Line 5017 
5017          my $thisRelation = { Fields => _ReOrderRelationTable($relationshipStructure->{Fields}),          my $thisRelation = { Fields => _ReOrderRelationTable($relationshipStructure->{Fields}),
5018                               Indexes => { } };                               Indexes => { } };
5019          $relationshipStructure->{Relations} = { $relationshipName => $thisRelation };          $relationshipStructure->{Relations} = { $relationshipName => $thisRelation };
5020    
5021            # Add the alternate indexes (if any). This MUST be done before the FROM and
5022            # TO indexes, because it erases the relation's index list.
5023            if (exists $relationshipStructure->{Indexes}) {
5024                _ProcessIndexes($relationshipStructure->{Indexes}, $thisRelation);
5025            }
5026            # Add the relation to the master table.
5027          # Create the FROM and TO indexes.          # Create the FROM and TO indexes.
5028          _CreateRelationshipIndex("From", $relationshipName, $relationshipStructure);          _CreateRelationshipIndex("From", $relationshipName, $relationshipStructure);
5029          _CreateRelationshipIndex("To", $relationshipName, $relationshipStructure);          _CreateRelationshipIndex("To", $relationshipName, $relationshipStructure);
         # Add the relation to the master table.  
5030          $masterRelationTable{$relationshipName} = $thisRelation;          $masterRelationTable{$relationshipName} = $thisRelation;
5031      }      }
5032      # Now store the master relation table in the metadata structure.      # Now store the master relation table in the metadata structure.
# Line 3664  Line 5182 
5182          $newIndex->{Unique} = 'true';          $newIndex->{Unique} = 'true';
5183      }      }
5184      # Add the index to the relation.      # Add the index to the relation.
5185      _AddIndex("idx$relationshipName$indexKey", $relationStructure, $newIndex);      _AddIndex("idx$indexKey", $relationStructure, $newIndex);
5186    }
5187    
5188    =head3 _ProcessIndexes
5189    
5190        ERDB::_ProcessIndexes($indexList, $relation);
5191    
5192    Build the data structures for the specified indexes in the specified relation.
5193    
5194    =over 4
5195    
5196    =item indexList
5197    
5198    Reference to a list of indexes. Each index is a hash reference containing an optional
5199    C<Notes> value that describes the index and an C<IndexFields> value that is a reference
5200    to a list of index field structures. An index field structure, in turn, is a reference
5201    to a hash that contains a C<name> attribute for the field name and an C<order>
5202    attribute that specifies either C<ascending> or C<descending>. In this sense the
5203    index list encapsulates the XML C<Indexes> structure in the database definition.
5204    
5205    =item relation
5206    
5207    The structure that describes the current relation. The new index descriptors will
5208    be stored in the structure's C<Indexes> member. Any previous data in the structure
5209    will be lost.
5210    
5211    =back
5212    
5213    =cut
5214    
5215    sub _ProcessIndexes {
5216        # Get the parameters.
5217        my ($indexList, $relation) = @_;
5218        # Now we need to convert the relation's index list to an index table. We begin by creating
5219        # an empty table in the relation structure.
5220        $relation->{Indexes} = { };
5221        # Loop through the indexes.
5222        my $count = 0;
5223        for my $index (@{$indexList}) {
5224            # Add this index to the index table.
5225            _AddIndex("idx$count", $relation, $index);
5226            # Increment the counter so that the next index has a different name.
5227            $count++;
5228        }
5229  }  }
5230    
5231  =head3 _AddIndex  =head3 _AddIndex
# Line 3763  Line 5324 
5324              my $type = $fieldData->{type};              my $type = $fieldData->{type};
5325              # Plug in a relation name if it is needed.              # Plug in a relation name if it is needed.
5326              Tracer::MergeOptions($fieldData, { relation => $defaultRelationName });              Tracer::MergeOptions($fieldData, { relation => $defaultRelationName });
             # 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} };  
             }  
5327              # Check for searchability.              # Check for searchability.
5328              if ($fieldData->{searchable}) {              if ($fieldData->{searchable}) {
5329                  # Only allow this for a primary relation.                  # Only allow this for a primary relation.
# Line 3777  Line 5333 
5333                      push @textFields, $fieldName;                      push @textFields, $fieldName;
5334                  }                  }
5335              }              }
             # Plug in the defaults for the optional data generation parameters.  
             Tracer::MergeOptions($fieldData->{DataGen}, { testCount => 1, pass => 0 });  
5336              # Add the PrettySortValue.              # Add the PrettySortValue.
5337              $fieldData->{PrettySort} = (($type eq "text") ? $textPrettySortValue : $prettySortValue);              $fieldData->{PrettySort} = (($type eq "text") ? $textPrettySortValue : $prettySortValue);
5338          }          }
# Line 4010  Line 5564 
5564      return $retVal;      return $retVal;
5565  }  }
5566    
5567  =head2 HTML Documentation Utility Methods  =head2 Documentation Utility Methods
5568    
5569  =head3 _ComputeRelationshipSentence  =head3 _ComputeRelationshipSentence
5570    
# Line 4042  Line 5596 
5596      # Get the parameters.      # Get the parameters.
5597      my ($relationshipName, $relationshipStructure) = @_;      my ($relationshipName, $relationshipStructure) = @_;
5598      # Format the relationship sentence.      # Format the relationship sentence.
5599      my $result = "$relationshipStructure->{from} <b>$relationshipName</b> $relationshipStructure->{to}";      my $result = "$relationshipStructure->{from} $relationshipName $relationshipStructure->{to}";
5600      # Compute the arity.      # Compute the arity.
5601      my $arityCode = $relationshipStructure->{arity};      my $arityCode = $relationshipStructure->{arity};
5602      my $arity = $ArityTable{$arityCode};      my $arity = $ArityTable{$arityCode};
# Line 4087  Line 5641 
5641      return $result;      return $result;
5642  }  }
5643    
5644    =head3 _WikiRelationTable
5645    
5646    Generate the Wiki text for a particular relation. The relation's data will be formatted as a
5647    table with three columns-- the field name, the field type, and the field description.
5648    
5649    This is a static method.
5650    
5651    =over 4
5652    
5653    =item relationName
5654    
5655    Name of the relation being formatted.
5656    
5657    =item relationData
5658    
5659    Hash containing the relation's fields and indexes.
5660    
5661    =item RETURN
5662    
5663    Returns a Wiki string that can be used to display the relation name and all of its fields.
5664    
5665    =back
5666    
5667    =cut
5668    
5669    sub _WikiRelationTable {
5670        # Get the parameters.
5671        my ($relationName, $relationData) = @_;
5672        # We'll create a list of lists in here, then call WikiTools::Table to
5673        # convert it into a table.
5674        my @rows = ();
5675        # Push in the header row.
5676        push @rows, [qw(Field Type Description)];
5677        # Loop through the fields.
5678        for my $field (@{$relationData->{Fields}}) {
5679            # Create this field's row. We always have a name and type.
5680            my @row = ($field->{name}, $field->{type});
5681            # If we have a description, add it as the third column.
5682            if (exists $field->{Notes}) {
5683                push @row, WikiNote($field->{Notes}->{content});
5684            }
5685            # Push this row onto the table list.
5686            push @rows, \@row;
5687        }
5688        # Store the rows as a Wiki table with a level-4 heading.
5689        my $retVal = join("\n\n", WikiTools::Heading(4, "$relationName Table"),
5690                          WikiTools::Table(@rows));
5691        # Now we show the relation's indexes. These are formatted as another
5692        # table.
5693        @rows = ();
5694        # Push in the header row.
5695        push @rows, [qw(Index Unique Fields Notes)];
5696        # Get the index hash.
5697        my $indexTable = $relationData->{Indexes};
5698        # Loop through the indexes. For an entity, there is always at least one index.
5699        # For a relationship, there are at least two. The upshot is we don't need to
5700        # worry about accidentally generating a frivolous table here.
5701        for my $indexName (sort keys %$indexTable) {
5702            my $indexData = $indexTable->{$indexName};
5703            # Determine whether or not the index is unique.
5704            my $unique = ((exists $indexData->{Unique} && $indexData->{Unique} eq "true") ?
5705                          "yes" : "");
5706            # Get the field list.
5707            my $fields = join(', ', @{$indexData->{IndexFields}});
5708            # Get the note text.
5709            my $description = "";
5710            if (my $note = $indexData->{Notes}) {
5711                $description = WikiNote($note->{content});
5712            }
5713            # Format this row.
5714            my @row = ($indexName, $unique, $fields, $description);
5715            push @rows, \@row;
5716        }
5717        # Add the index list to the result.
5718        $retVal .= "\n\n" . WikiTools::Table(@rows);
5719    }
5720    
5721  =head3 _ShowRelationTable  =head3 _ShowRelationTable
5722    
5723  Generate the HTML string for a particular relation. The relation's data will be formatted as an HTML  Generate the HTML string for a particular relation. The relation's data will be formatted as an HTML
# Line 4137  Line 5768 
5768          $htmlString .= "<li><b>Index $fullName</b>\n<ul>\n";          $htmlString .= "<li><b>Index $fullName</b>\n<ul>\n";
5769          # Add any note text.          # Add any note text.
5770          if (my $note = $indexData->{Notes}) {          if (my $note = $indexData->{Notes}) {
5771              $htmlString .= "<li>" . _HTMLNote($note->{content}) . "</li>\n";              $htmlString .= "<li>" . HTMLNote($note->{content}) . "</li>\n";
5772          }          }
5773          # Add the fiield list.          # Add the fiield list.
5774          $htmlString .= "<li><i>" . join(', ', @{$indexData->{IndexFields}}) . "</i></li>\n";          $htmlString .= "<li><i>" . join(', ', @{$indexData->{IndexFields}}) . "</i></li>\n";
# Line 4203  Line 5834 
5834      # Compute the number of columns.      # Compute the number of columns.
5835      my $colCount = @colNames;      my $colCount = @colNames;
5836      # Generate the title row.      # Generate the title row.
5837      my $htmlString = "<p><table border=\"2\"><tr><td colspan=\"$colCount\" align=\"center\">$tablename</td></tr>\n";      my $htmlString = "<table border=\"2\"><tr><td colspan=\"$colCount\" align=\"center\">$tablename</td></tr>\n";
5838      # Loop through the columns, adding the column header rows.      # Loop through the columns, adding the column header rows.
5839      $htmlString .= "<tr>";      $htmlString .= "<tr>";
5840      for my $colName (@colNames) {      for my $colName (@colNames) {
# Line 4222  Line 5853 
5853  =cut  =cut
5854    
5855  sub _CloseTable {  sub _CloseTable {
5856      return "</table></p>\n";      return "</table>\n";
5857  }  }
5858    
5859  =head3 _ShowField  =head3 _ShowField
# Line 4252  Line 5883 
5883      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>";
5884      # If we have content, add it as a third column.      # If we have content, add it as a third column.
5885      if (exists $fieldData->{Notes}) {      if (exists $fieldData->{Notes}) {
5886          $htmlString .= "<td>" . _HTMLNote($fieldData->{Notes}->{content}) . "</td>";          $htmlString .= "<td>" . HTMLNote($fieldData->{Notes}->{content}) . "</td>";
5887      }      }
5888      # Close off the row.      # Close off the row.
5889      $htmlString .= "</tr>\n";      $htmlString .= "</tr>\n";
# Line 4260  Line 5891 
5891      return $htmlString;      return $htmlString;
5892  }  }
5893    
5894  =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  
5895    
5896  C<< my $string = StringGen($pattern1, $pattern2, ... $patternN); >>      my @noteParagraphs = _ObjectNotes($objectData);
5897    
5898  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
5899  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.  
5900    
5901  =over 4  =over 4
5902    
5903  =item pattern1, pattern2, ... patternN  =item objectData
5904    
5905  List of patterns to be used to generate string values.  The metadata for the desired entity or relationship.
5906    
5907  =item RETURN  =item RETURN
5908    
5909  A single string generated from a pattern.  Returns a list of text paragraphs in Wiki markup form.
5910    
5911  =back  =back
5912    
5913  =cut  =cut
5914    
5915  sub StringGen {  sub _ObjectNotes {
5916      # Get the parameters.      # Get the parameters.
5917      my @patterns = @_;      my ($objectData) = @_;
     # Choose the appropriate pattern.  
     my $chosenPattern = RandParam(@patterns);  
5918      # Declare the return variable.      # Declare the return variable.
5919      my $retVal = "";      my @retVal;
5920      # Determine whether this is a count or a picture pattern.      # Loop through the types of notes.
5921      if ($chosenPattern =~ m/^\d+/) {      for my $noteType (qw(Notes Asides)) {
5922          # Here we have a count. Get the string of source characters.          my $text = $objectData->{$noteType};
5923          my $letterString = $PictureTable{'X'};          if ($text) {
5924          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;  
5925      }      }
     # Return the string formed.  
     return $retVal;  
5926  }  }
   
 =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;  
5927      # 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.  
5928      return @retVal;      return @retVal;
5929  }  }
5930    

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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3