[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.79, Wed Nov 29 20:29:53 2006 UTC revision 1.95, Wed Jan 23 00:56:31 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);
     use FIG;  
13      use CGI;      use CGI;
14    #    use WikiTools;  ## HACK
15    
16  =head1 Entity-Relationship Database Package  =head1 Entity-Relationship Database Package
17    
# Line 228  Line 228 
228    
229  =head3 Indexes  =head3 Indexes
230    
231  An entity can have multiple alternate indexes associated with it. The fields must  An entity can have multiple alternate indexes associated with it. The fields in an
232  all be from the same relation. The alternate indexes assist in ordering results  index must all be from the same relation. The alternate indexes assist in searching
233  from a query. A relationship can have up to two indexes-- a I<to-index> and a  on fields other than the entity ID. A relationship has at least two indexes-- a I<to-index> and a
234  I<from-index>. These order the results when crossing the relationship. For  I<from-index> that order the results when crossing the relationship. For
235  example, in the relationship C<HasContig> from C<Genome> to C<Contig>, the  example, in the relationship C<HasContig> from C<Genome> to C<Contig>, the
236  from-index would order the contigs of a ganome, and the to-index would order  from-index would order the contigs of a ganome, and the to-index would order
237  the genomes of a contig. A relationship's index must specify only fields in  the genomes of a contig. In addition, it can have zero or more alternate
238    indexes. A relationship's index must specify only fields in
239  the relationship.  the relationship.
240    
241  The indexes for an entity must be listed inside the B<Indexes> tag. The from-index  The alternate indexes for an entity or relationship must be listed inside the B<Indexes> tag.
242  of a relationship is specified using the B<FromIndex> tag; the to-index is specified  The from-index of a relationship is specified using the B<FromIndex> tag; the to-index is
243  using the B<ToIndex> tag.  specified using the B<ToIndex> tag.
244    
245  Each index can contain a B<Notes> tag. In addition, it will have an B<IndexFields>  Each index can contain a B<Notes> tag. In addition, it will have an B<IndexFields>
246  tag containing the B<IndexField> tags. These specify, in order, the fields used in  tag containing the B<IndexField> tags. These specify, in order, the fields used in
# Line 303  Line 304 
304    
305  A relationship is described by the C<Relationship> tag. Within a relationship,  A relationship is described by the C<Relationship> tag. Within a relationship,
306  there can be a C<Notes> tag, a C<Fields> tag containing the intersection data  there can be a C<Notes> tag, a C<Fields> tag containing the intersection data
307  fields, a C<FromIndex> tag containing the from-index, and a C<ToIndex> tag containing  fields, a C<FromIndex> tag containing the from-index, a C<ToIndex> tag containing
308  the to-index.  the to-index, and an C<Indexes> tag containing the alternate indexes.
309    
310  The C<Relationship> tag has the following attributes.  The C<Relationship> tag has the following attributes.
311    
# Line 372  Line 373 
373                   'medium-string' =>                   'medium-string' =>
374                               { sqlType => 'VARCHAR(160)',       maxLen => 160,          avgLen =>  40, sort => "",                               { sqlType => 'VARCHAR(160)',       maxLen => 160,          avgLen =>  40, sort => "",
375                                 indexMod =>   0, notes => "character string, 0 to 160 characters"},                                 indexMod =>   0, notes => "character string, 0 to 160 characters"},
376                     'long-string' =>
377                                 { sqlType => 'VARCHAR(500)',       maxLen => 500,          avglen => 255, sort => "",
378                                   indexMod =>   0, notes => "character string, 0 to 500 characters"},
379                  );                  );
380    
381  # Table translating arities into natural language.  # Table translating arities into natural language.
# Line 410  Line 414 
414    
415  =head3 new  =head3 new
416    
417  C<< my $database = ERDB->new($dbh, $metaFileName); >>      my $database = ERDB->new($dbh, $metaFileName);
418    
419  Create a new ERDB object.  Create a new ERDB object.
420    
# Line 430  Line 434 
434    
435  sub new {  sub new {
436      # Get the parameters.      # Get the parameters.
437      my ($class, $dbh, $metaFileName, $options) = @_;      my ($class, $dbh, $metaFileName, %options) = @_;
438      # Load the meta-data.      # Load the meta-data.
439      my $metaData = _LoadMetaData($metaFileName);      my $metaData = _LoadMetaData($metaFileName);
440      # Create the object.      # Create the object.
# Line 444  Line 448 
448    
449  =head3 ShowMetaData  =head3 ShowMetaData
450    
451  C<< $erdb->ShowMetaData($fileName); >>      $erdb->ShowMetaData($fileName);
452    
453  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
454  the data to be loaded into the relations.  the data to be loaded into the relations.
# Line 485  Line 489 
489    
490  =head3 DisplayMetaData  =head3 DisplayMetaData
491    
492  C<< my $html = $erdb->DisplayMetaData(); >>      my $html = $erdb->DisplayMetaData();
493    
494  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
495  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 548  Line 552 
552          if (my $notes = $entityData->{Notes}) {          if (my $notes = $entityData->{Notes}) {
553              $retVal .= "<p>" . HTMLNote($notes->{content}) . "</p>\n";              $retVal .= "<p>" . HTMLNote($notes->{content}) . "</p>\n";
554          }          }
555          # 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.
556            my $relCount = keys %{$relationshipList};
557            if ($relCount > 0) {
558                # First, we set up the relationship subsection.
559          $retVal .= "<h4>Relationships for <b>$key</b></h4>\n<ul>\n";          $retVal .= "<h4>Relationships for <b>$key</b></h4>\n<ul>\n";
560          # Loop through the relationships.          # Loop through the relationships.
561          for my $relationship (sort keys %{$relationshipList}) {          for my $relationship (sort keys %{$relationshipList}) {
# Line 564  Line 571 
571          }          }
572          # Close off the relationship list.          # Close off the relationship list.
573          $retVal .= "</ul>\n";          $retVal .= "</ul>\n";
574            }
575          # Get the entity's relations.          # Get the entity's relations.
576          my $relationList = $entityData->{Relations};          my $relationList = $entityData->{Relations};
577          # Create a header for the relation subsection.          # Create a header for the relation subsection.
# Line 637  Line 645 
645    
646  =head3 DumpMetaData  =head3 DumpMetaData
647    
648  C<< $erdb->DumpMetaData(); >>      $erdb->DumpMetaData();
649    
650  Return a dump of the metadata structure.  Return a dump of the metadata structure.
651    
# Line 650  Line 658 
658      return Data::Dumper::Dumper($self->{_metaData});      return Data::Dumper::Dumper($self->{_metaData});
659  }  }
660    
661    =head3 GenerateWikiData
662    
663        my @wikiLines = $erdb->GenerateWikiData();
664    
665    Build a description of the database for the wiki. The database will be
666    organized into a single page, with sections for each entity and relationship.
667    The return value is a list of text lines.
668    
669    =cut
670    
671    sub GenerateWikiData {
672        # Get the parameters.
673        my ($self) = @_;
674        # We'll build the wiki text in here.
675        my @retVal = ();
676        # Get the metadata object.
677        my $metadata = $self->{_metaData};
678        # Get the title string. This will become the page name.
679        my $title = $metadata->{Title}->{content};
680        # Get the entity and relationship lists.
681        my $entityList = $metadata->{Entities};
682        my $relationshipList = $metadata->{Relationships};
683        # Start with the introductory text.
684        push @retVal, WikiTools::Heading(2, "Introduction");
685        if (my $notes = $metadata->{Notes}) {
686            push @retVal, WikiNote($notes->{content});
687        }
688        # Start the entity section.
689        push @retVal, WikiTools::Heading(2, "Entities");
690        # Loop through the entities. Note that unlike the situation with HTML, we
691        # don't need to generate the table of contents manually, just the data
692        # itself.
693        for my $key (sort keys %$entityList) {
694            # Create a header for this entity.
695            push @retVal, "", WikiTools::Heading(3, $key);
696            # Get the entity data.
697            my $entityData = $entityList->{$key};
698            # Plant the notes here, if there are any.
699            if (my $notes = $entityData->{Notes}) {
700                push @retVal, "", WikiNote($notes->{content});
701            }
702            # Get the entity's relations.
703            my $relationList = $entityData->{Relations};
704            # Loop through the relations, displaying them.
705            for my $relation (sort keys %{$relationList}) {
706                my $wikiString = _WikiRelationTable($relation, $relationList->{$relation});
707                push @retVal, $wikiString;
708            }
709            # Now we list the entity's relationships (if any). First, we build a list
710            # of the relationships relevant to this entity.
711            my @rels = ();
712            for my $rel (sort keys %$relationshipList) {
713                my $relStructure = $relationshipList->{$rel};
714                if ($relStructure->{from} eq $key || $relStructure->{to} eq $key) {
715                    # Get the relationship sentence.
716                    my $relSentence = _ComputeRelationshipSentence($rel, $relStructure);
717                    # Linkify it.
718                    my $linkedRel = WikiTools::LinkMarkup("#$rel", $rel);
719                    $relSentence =~ s/$rel/$linkedRel/;
720                    push @rels, $relSentence;
721                }
722            }
723            # Add the relationships as a Wiki list.
724            push @retVal, WikiTools::List(@rels);
725        }
726        # Now the entities are documented. Next we do the relationships.
727        push @retVal, WikiTools::Heading(2, "Relationships");
728        for my $key (sort keys %$relationshipList) {
729            my $relationshipData = $relationshipList->{$key};
730            # Create the relationship heading.
731            push @retVal, WikiTools::Heading(3, $key);
732            # Describe the relationship arity. Note there's a bit of trickiness involving recursive
733            # many-to-many relationships. In a normal many-to-many we use two sentences to describe
734            # the arity (one for each direction). This is a bad idea for a recursive relationship,
735            # since both sentences will say the same thing.
736            my $arity = $relationshipData->{arity};
737            my $fromEntity = $relationshipData->{from};
738            my $toEntity = $relationshipData->{to};
739            my @listElements = ();
740            my $boldCode = WikiTools::BoldCode();
741            if ($arity eq "11") {
742                push @listElements, "Each $boldCode$fromEntity$boldCode relates to at most one $boldCode$toEntity$boldCode.";
743            } else {
744                push @listElements, "Each $boldCode$fromEntity$boldCode relates to multiple $boldCode${toEntity}s$boldCode.\n";
745                if ($arity eq "MM" && $fromEntity ne $toEntity) {
746                    push @listElements, "Each $boldCode$toEntity$boldCode relates to multiple $boldCode${fromEntity}s$boldCode.\n";
747                }
748            }
749            push @retVal, WikiTools::List(@listElements);
750            # Plant the notes here, if there are any.
751            if (my $notes = $relationshipData->{Notes}) {
752                push @retVal, "", WikiNote($notes->{content});
753            }
754            # Finally, the relationship table.
755            my $wikiString = _WikiRelationTable($key, $relationshipData->{Relations}->{$key});
756            push @retVal, $wikiString;
757        }
758        # All done. Return the lines.
759        return @retVal;
760    }
761    
762    
763    =head3 CreatePPO
764    
765        ERDB::CreatePPO($erdbXMLFile, $ppoXMLFile);
766    
767    Create a PPO XML file from an ERDB data definition XML file. At the
768    current time, the PPO XML file can be used to create a database with
769    similar functionality. Eventually, the PPO will be able to use the
770    created XML to access the live ERDB database.
771    
772    =over 4
773    
774    =item erdbXMLFile
775    
776    Name of the XML data definition file for the ERDB database. This
777    file must exist.
778    
779    =item ppoXMLFile
780    
781    Output file for the PPO XML definition. If this file exists, it
782    will be overwritten.
783    
784    =back
785    
786    =cut
787    
788    sub CreatePPO {
789        # Get the parameters.
790        my ($erdbXMLFile, $ppoXMLFile) = @_;
791        # First, we want to slurp in the ERDB XML file in its raw form.
792        my $xml = ReadMetaXML($erdbXMLFile);
793        # Create a variable to hold all of the objects in the PPO project.
794        my @objects = ();
795        # Get the relationship hash.
796        my $relationships = $xml->{Relationships};
797        # Loop through the entities.
798        my $entities = $xml->{Entities};
799        for my $entityName (keys %{$entities}) {
800            # Get the entity's data structures.
801            my $entityObject = $entities->{$entityName};
802            # We put the object's fields in here, according to their type.
803            my (@object_refs, @scalars, @indexes, @arrays);
804            # Create the ID field for the entity. We get the key type from the
805            # entity object and compute the corresponding SQL type.
806            my $type = $TypeTable{$entityObject->{keyType}}->{sqlType};
807            push @scalars, { label => 'id', type => $type };
808            # Loop through the entity fields.
809            for my $fieldName ( keys %{$entityObject->{Fields}} ) {
810                # Get the field object.
811                my $fieldObject = $entityObject->{Fields}->{$fieldName};
812                # Convert it to a scalar tag.
813                my $scalar = _CreatePPOField($fieldName, $fieldObject);
814                # If we have a relation, this field is stored in an array.
815                # otherwise, it is a scalar. The array tag has scalars
816                # stored as an XML array. In ERDB, there is only ever one,
817                # but PPO can have more.
818                my $relation = $fieldObject->{relation};
819                if ($relation) {
820                    push @arrays, { scalar => [$scalar] };
821                } else {
822                    push @scalars, $scalar;
823                }
824            }
825            # Loop through the relationships. If this entity is the to-entity
826            # on a relationship of 1M arity, then it is implemented as a PPO
827            # object reference.
828            for my $relationshipName (keys %{$relationships}) {
829                # Get the relationship data.
830                my $relationshipData = $relationships->{$relationshipName};
831                # If we have a from for this entity and an arity of 1M, we
832                # have an object reference.
833                if ($relationshipData->{to} eq $entityName &&
834                    $relationshipData->{arity} eq '1M') {
835                    # Build the object reference tag.
836                    push @object_refs, { label => $relationshipName,
837                                         type => $relationshipData->{from} };
838                }
839            }
840            # Create the indexes.
841            my $indexList = $entityObject->{Indexes};
842            push @indexes, map { _CreatePPOIndex($_) } @{$indexList};
843            # Build the object XML tree.
844            my $object = { label => $entityName,
845                           object_ref => \@object_refs,
846                           scalar => \@scalars,
847                           index => \@indexes,
848                           array => \@arrays
849                          };
850            # Push the object onto the objects list.
851            push @objects, $object;
852        }
853        # Loop through the relationships, searching for MMs. The 1Ms were
854        # already handled by the entity search above.
855        for my $relationshipName (keys %{$relationships}) {
856            # Get this relationship's object.
857            my $relationshipObject = $relationships->{$relationshipName};
858            # Only proceed if it's many-to-many.
859            if ($relationshipObject->{arity} eq 'MM') {
860                # Create the tag lists for the relationship object.
861                my (@object_refs, @scalars, @indexes);
862                # The relationship will be created as an object with object
863                # references for its links to the participating entities.
864                my %links = ( from_link => $relationshipObject->{from},
865                              to_link => $relationshipObject->{to} );
866                for my $link (keys %links) {
867                    # Create an object_ref tag for this piece of the
868                    # relationship (from or to).
869                    my $object_ref = { label => $link,
870                                       type => $links{$link} };
871                    push @object_refs, $object_ref;
872                }
873                # Loop through the intersection data fields, creating scalar tags.
874                # There are no fancy array tags in a relationship.
875                for my $fieldName (keys %{$relationshipObject->{Fields}}) {
876                    my $fieldObject = $relationshipObject->{Fields}->{$fieldName};
877                    push @scalars, _CreatePPOField($fieldName, $fieldObject);
878                }
879                # Finally, the indexes: currently we cannot support the to-index and
880                # from-index in PPO, so we just process the alternate indexes.
881                my $indexList = $relationshipObject->{Indexes};
882                push @indexes, map { _CreatePPOIndex($_) } @{$indexList};
883                # Wrap up all the stuff about this relationship.
884                my $object = { label => $relationshipName,
885                               scalar => \@scalars,
886                               object_ref => \@object_refs,
887                               index => \@indexes
888                             };
889                # Push it into the object list.
890                push @objects, $object;
891            }
892        }
893        # Compute a title.
894        my $title;
895        if ($erdbXMLFile =~ /(\/|^)([^\/]+)DBD\.xml/) {
896            # Here we have a standard file name we can use for a title.
897            $title = $2;
898        } else {
899            # Here the file name is non-standard, so we carve up the
900            # database title.
901            $title = $xml->{Title}->{content};
902            $title =~ s/\s\.,//g;
903        }
904        # Wrap up the XML as a project.
905        my $ppoXML = { project => { label => $title,
906                                    object => \@objects }};
907        # Write out the results.
908        my $ppoString = XML::Simple::XMLout($ppoXML,
909                                            AttrIndent => 1,
910                                            KeepRoot => 1);
911        Tracer::PutFile($ppoXMLFile, [ $ppoString ]);
912    }
913    
914  =head3 FindIndexForEntity  =head3 FindIndexForEntity
915    
916  C<< my $indexFound = ERDB::FindIndexForEntity($xml, $entityName, $attributeName); >>      my $indexFound = ERDB::FindIndexForEntity($xml, $entityName, $attributeName);
917    
918  This method locates the entry in an entity's index list that begins with the  This method locates the entry in an entity's index list that begins with the
919  specified attribute name. If the entity has no index list, one will be  specified attribute name. If the entity has no index list, one will be
# Line 722  Line 983 
983    
984  =head3 CreateTables  =head3 CreateTables
985    
986  C<< $erdb->CreateTables(); >>      $erdb->CreateTables();
987    
988  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
989  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 739  Line 1000 
1000      # Loop through the relations.      # Loop through the relations.
1001      for my $relationName (@relNames) {      for my $relationName (@relNames) {
1002          # Create a table for this relation.          # Create a table for this relation.
1003          $self->CreateTable($relationName);          $self->CreateTable($relationName, 1);
1004          Trace("Relation $relationName created.") if T(2);          Trace("Relation $relationName created.") if T(2);
1005      }      }
1006  }  }
1007    
1008  =head3 CreateTable  =head3 CreateTable
1009    
1010  C<< $erdb->CreateTable($tableName, $indexFlag, $estimatedRows); >>      $erdb->CreateTable($tableName, $indexFlag, $estimatedRows);
1011    
1012  Create the table for a relation and optionally create its indexes.  Create the table for a relation and optionally create its indexes.
1013    
# Line 802  Line 1063 
1063      my $estimation = undef;      my $estimation = undef;
1064      if ($estimatedRows) {      if ($estimatedRows) {
1065          $estimation = [$self->EstimateRowSize($relationName), $estimatedRows];          $estimation = [$self->EstimateRowSize($relationName), $estimatedRows];
1066            Trace("$estimation->[1] rows of $estimation->[0] bytes each.") if T(3);
1067      }      }
1068      # Create the table.      # Create the table.
1069      Trace("Creating table $relationName: $fieldThing") if T(2);      Trace("Creating table $relationName: $fieldThing") if T(2);
# Line 816  Line 1078 
1078    
1079  =head3 VerifyFields  =head3 VerifyFields
1080    
1081  C<< my $count = $erdb->VerifyFields($relName, \@fieldList); >>      my $count = $erdb->VerifyFields($relName, \@fieldList);
1082    
1083  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
1084  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 859  Line 1121 
1121              my $oldString = $fieldList->[$i];              my $oldString = $fieldList->[$i];
1122              if (length($oldString) > $maxLen) {              if (length($oldString) > $maxLen) {
1123                  # Here it's too big, so we truncate it.                  # Here it's too big, so we truncate it.
1124                  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);
1125                  $fieldList->[$i] = substr $oldString, 0, $maxLen;                  $fieldList->[$i] = substr $oldString, 0, $maxLen;
1126                  $retVal++;                  $retVal++;
1127              }              }
# Line 871  Line 1133 
1133    
1134  =head3 DigestFields  =head3 DigestFields
1135    
1136  C<< $erdb->DigestFields($relName, $fieldList); >>      $erdb->DigestFields($relName, $fieldList);
1137    
1138  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
1139  specified relation.  specified relation.
# Line 911  Line 1173 
1173    
1174  =head3 DigestKey  =head3 DigestKey
1175    
1176  C<< my $digested = $erdb->DigestKey($keyValue); >>      my $digested = $erdb->DigestKey($keyValue);
1177    
1178  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
1179  key-based search into a table with key-type hash-string.  key-based search into a table with key-type hash-string.
# Line 944  Line 1206 
1206    
1207  =head3 CreateIndex  =head3 CreateIndex
1208    
1209  C<< $erdb->CreateIndex($relationName); >>      $erdb->CreateIndex($relationName);
1210    
1211  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
1212  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 1000  Line 1262 
1262    
1263  =head3 GetSecondaryFields  =head3 GetSecondaryFields
1264    
1265  C<< my %fieldTuples = $erdb->GetSecondaryFields($entityName); >>      my %fieldTuples = $erdb->GetSecondaryFields($entityName);
1266    
1267  This method will return a list of the name and type of each of the secondary  This method will return a list of the name and type of each of the secondary
1268  fields for a specified entity. Secondary fields are stored in two-column tables  fields for a specified entity. Secondary fields are stored in two-column tables
# Line 1041  Line 1303 
1303    
1304  =head3 GetFieldRelationName  =head3 GetFieldRelationName
1305    
1306  C<< my $name = $erdb->GetFieldRelationName($objectName, $fieldName); >>      my $name = $erdb->GetFieldRelationName($objectName, $fieldName);
1307    
1308  Return the name of the relation containing a specified field.  Return the name of the relation containing a specified field.
1309    
# Line 1082  Line 1344 
1344    
1345  =head3 DeleteValue  =head3 DeleteValue
1346    
1347  C<< my $numDeleted = $erdb->DeleteValue($entityName, $id, $fieldName, $fieldValue); >>      my $numDeleted = $erdb->DeleteValue($entityName, $id, $fieldName, $fieldValue);
1348    
1349  Delete secondary field values from the database. This method can be used to delete all  Delete secondary field values from the database. This method can be used to delete all
1350  values of a specified field for a particular entity instance, or only a single value.  values of a specified field for a particular entity instance, or only a single value.
# Line 1165  Line 1427 
1427    
1428  =head3 LoadTables  =head3 LoadTables
1429    
1430  C<< my $stats = $erdb->LoadTables($directoryName, $rebuild); >>      my $stats = $erdb->LoadTables($directoryName, $rebuild);
1431    
1432  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
1433  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 1225  Line 1487 
1487    
1488  =head3 GetTableNames  =head3 GetTableNames
1489    
1490  C<< my @names = $erdb->GetTableNames; >>      my @names = $erdb->GetTableNames;
1491    
1492  Return a list of the relations required to implement this database.  Return a list of the relations required to implement this database.
1493    
# Line 1242  Line 1504 
1504    
1505  =head3 GetEntityTypes  =head3 GetEntityTypes
1506    
1507  C<< my @names = $erdb->GetEntityTypes; >>      my @names = $erdb->GetEntityTypes;
1508    
1509  Return a list of the entity type names.  Return a list of the entity type names.
1510    
# Line 1259  Line 1521 
1521    
1522  =head3 GetDataTypes  =head3 GetDataTypes
1523    
1524  C<< my %types = ERDB::GetDataTypes(); >>      my %types = ERDB::GetDataTypes();
1525    
1526  Return a table of ERDB data types. The table returned is a hash of hashes.  Return a table of ERDB data types. The table returned is a hash of hashes.
1527  The keys of the big hash are the datatypes. Each smaller hash has several  The keys of the big hash are the datatypes. Each smaller hash has several
# Line 1278  Line 1540 
1540    
1541  =head3 IsEntity  =head3 IsEntity
1542    
1543  C<< my $flag = $erdb->IsEntity($entityName); >>      my $flag = $erdb->IsEntity($entityName);
1544    
1545  Return TRUE if the parameter is an entity name, else FALSE.  Return TRUE if the parameter is an entity name, else FALSE.
1546    
# Line 1305  Line 1567 
1567    
1568  =head3 Get  =head3 Get
1569    
1570  C<< my $query = $erdb->Get(\@objectNames, $filterClause, \@params); >>      my $query = $erdb->Get(\@objectNames, $filterClause, \@params);
1571    
1572  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.
1573  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 1313  Line 1575 
1575  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
1576  $genus.  $genus.
1577    
1578  C<< $query = $erdb->Get(['Genome'], "Genome(genus) = ?", [$genus]); >>      $query = $erdb->Get(['Genome'], "Genome(genus) = ?", [$genus]);
1579    
1580  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
1581  parameter representing the parameter value. It would also be possible to code  parameter representing the parameter value. It would also be possible to code
1582    
1583  C<< $query = $erdb->Get(['Genome'], "Genome(genus) = \'$genus\'"); >>      $query = $erdb->Get(['Genome'], "Genome(genus) = \'$genus\'");
1584    
1585  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
1586  characters inside the variable C<$genus>.  characters inside the variable C<$genus>.
# Line 1330  Line 1592 
1592  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
1593  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,
1594    
1595  C<< $query = $erdb->Get(['Genome', 'ComesFrom', 'Source'], "Genome(genus) = ?", [$genus]); >>      $query = $erdb->Get(['Genome', 'ComesFrom', 'Source'], "Genome(genus) = ?", [$genus]);
1596    
1597  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
1598  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 1366  Line 1628 
1628  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
1629  particular genus and sorts them by species name.  particular genus and sorts them by species name.
1630    
1631  C<< "Genome(genus) = ? ORDER BY Genome(species)" >>      "Genome(genus) = ? ORDER BY Genome(species)"
1632    
1633  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
1634  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 1379  Line 1641 
1641  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
1642  a positive number. So, for example  a positive number. So, for example
1643    
1644  C<< "Genome(genus) = ? ORDER BY Genome(species) LIMIT 10" >>      "Genome(genus) = ? ORDER BY Genome(species) LIMIT 10"
1645    
1646  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
1647  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
1648  use  use
1649    
1650  C<< "LIMIT 10" >>      "LIMIT 10"
1651    
1652  =item params  =item params
1653    
# Line 1406  Line 1668 
1668      my ($suffix, $mappedNameListRef, $mappedNameHashRef) =      my ($suffix, $mappedNameListRef, $mappedNameHashRef) =
1669          $self->_SetupSQL($objectNames, $filterClause);          $self->_SetupSQL($objectNames, $filterClause);
1670      # Create the query.      # Create the query.
1671      my $command = "SELECT DISTINCT " . join(".*, ", @{$mappedNameListRef}) .      my $command = "SELECT " . join(".*, ", @{$mappedNameListRef}) .
1672          ".* $suffix";          ".* $suffix";
1673      my $sth = $self->_GetStatementHandle($command, $params);      my $sth = $self->_GetStatementHandle($command, $params);
1674      # 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 1424  Line 1686 
1686    
1687  =head3 Search  =head3 Search
1688    
1689  C<< my $query = $erdb->Search($searchExpression, $idx, \@objectNames, $filterClause, \@params); >>      my $query = $erdb->Search($searchExpression, $idx, \@objectNames, $filterClause, \@params);
1690    
1691  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
1692  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 1493  Line 1755 
1755          my $actualKeywords = $self->CleanKeywords($searchExpression);          my $actualKeywords = $self->CleanKeywords($searchExpression);
1756          # Prefix a "+" to each uncontrolled word. This converts the default          # Prefix a "+" to each uncontrolled word. This converts the default
1757          # search mode from OR to AND.          # search mode from OR to AND.
1758          $actualKeywords =~ s/(^|\s)(\w)/$1\+$2/g;          $actualKeywords =~ s/(^|\s)(\w|")/$1\+$2/g;
1759          Trace("Actual keywords for search are\n$actualKeywords") if T(3);          Trace("Actual keywords for search are\n$actualKeywords") if T(3);
1760          # 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
1761          # 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
# Line 1507  Line 1769 
1769              $self->_SetupSQL($objectNames, $filterClause, $matchClause);              $self->_SetupSQL($objectNames, $filterClause, $matchClause);
1770          # 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
1771          # the select fields.          # the select fields.
1772          my $command = "SELECT DISTINCT $matchClause, " . join(".*, ", @{$mappedNameListRef}) .          my $command = "SELECT $matchClause, " . join(".*, ", @{$mappedNameListRef}) .
1773              ".* $suffix";              ".* $suffix";
1774          my $sth = $self->_GetStatementHandle($command, \@myParams);          my $sth = $self->_GetStatementHandle($command, \@myParams);
1775          # 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 1521  Line 1783 
1783    
1784  =head3 GetFlat  =head3 GetFlat
1785    
1786  C<< my @list = $erdb->GetFlat(\@objectNames, $filterClause, \@parameterList, $field); >>      my @list = $erdb->GetFlat(\@objectNames, $filterClause, \@parameterList, $field);
1787    
1788  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
1789  returns a single flattened list.  returns a single flattened list.
# Line 1574  Line 1836 
1836    
1837  =head3 SpecialFields  =head3 SpecialFields
1838    
1839  C<< my %specials = $erdb->SpecialFields($entityName); >>      my %specials = $erdb->SpecialFields($entityName);
1840    
1841  Return a hash mapping special fields in the specified entity to the value of their  Return a hash mapping special fields in the specified entity to the value of their
1842  C<special> attribute. This enables the subclass to get access to the special field  C<special> attribute. This enables the subclass to get access to the special field
# Line 1616  Line 1878 
1878    
1879  =head3 Delete  =head3 Delete
1880    
1881  C<< my $stats = $erdb->Delete($entityName, $objectID, %options); >>      my $stats = $erdb->Delete($entityName, $objectID, %options);
1882    
1883  Delete an entity instance from the database. The instance is deleted along with all entity and  Delete an entity instance from the database. The instance is deleted along with all entity and
1884  relationship instances dependent on it. The definition of I<dependence> is recursive.  relationship instances dependent on it. The definition of I<dependence> is recursive.
# Line 1801  Line 2063 
2063    
2064  =head3 Disconnect  =head3 Disconnect
2065    
2066  C<< $erdb->Disconnect($relationshipName, $originEntityName, $originEntityID); >>      $erdb->Disconnect($relationshipName, $originEntityName, $originEntityID);
2067    
2068  Disconnect an entity instance from all the objects to which it is related. This  Disconnect an entity instance from all the objects to which it is related. This
2069  will delete each relationship instance that connects to the specified entity.  will delete each relationship instance that connects to the specified entity.
# Line 1840  Line 2102 
2102          # Loop through the ends of the relationship.          # Loop through the ends of the relationship.
2103          for my $dir ('from', 'to') {          for my $dir ('from', 'to') {
2104              if ($structure->{$dir} eq $originEntityName) {              if ($structure->{$dir} eq $originEntityName) {
                 # Delete all relationship instances on this side of the entity instance.  
                 $dbh->SQL("DELETE FROM $relationshipName WHERE ${dir}_link = ?", 0, $originEntityID);  
2105                  $found = 1;                  $found = 1;
2106                    # Here we want to delete all relationship instances on this side of the
2107                    # entity instance.
2108                    Trace("Disconnecting in $dir direction with ID \"$originEntityID\".");
2109                    # We do this delete in batches to keep it from dragging down the
2110                    # server.
2111                    my $limitClause = ($FIG_Config::delete_limit ? "LIMIT $FIG_Config::delete_limit" : "");
2112                    my $done = 0;
2113                    while (! $done) {
2114                        # Do the delete.
2115                        my $rows = $dbh->SQL("DELETE FROM $relationshipName WHERE ${dir}_link = ? $limitClause", 0, $originEntityID);
2116                        # See if we're done. We're done if no rows were found or the delete is unlimited.
2117                        $done = ($rows == 0 || ! $limitClause);
2118                    }
2119              }              }
2120          }          }
2121          # Insure we found the entity on at least one end.          # Insure we found the entity on at least one end.
# Line 1854  Line 2127 
2127    
2128  =head3 DeleteRow  =head3 DeleteRow
2129    
2130  C<< $erdb->DeleteRow($relationshipName, $fromLink, $toLink, \%values); >>      $erdb->DeleteRow($relationshipName, $fromLink, $toLink, \%values);
2131    
2132  Delete a row from a relationship. In most cases, only the from-link and to-link are  Delete a row from a relationship. In most cases, only the from-link and to-link are
2133  needed; however, for relationships with intersection data values can be specified  needed; however, for relationships with intersection data values can be specified
# Line 1907  Line 2180 
2180      $dbh->SQL($command, undef, @parms);      $dbh->SQL($command, undef, @parms);
2181  }  }
2182    
2183    =head3 DeleteLike
2184    
2185        my $deleteCount = $erdb->DeleteLike($relName, $filter, \@parms);
2186    
2187    Delete all the relationship rows that satisfy a particular filter condition. Unlike a normal
2188    filter, only fields from the relationship itself can be used.
2189    
2190    =over 4
2191    
2192    =item relName
2193    
2194    Name of the relationship whose records are to be deleted.
2195    
2196    =item filter
2197    
2198    A filter clause (L</Get>-style) for the delete query.
2199    
2200    =item parms
2201    
2202    Reference to a list of parameters for the filter clause.
2203    
2204    =item RETURN
2205    
2206    Returns a count of the number of rows deleted.
2207    
2208    =back
2209    
2210    =cut
2211    
2212    sub DeleteLike {
2213        # Get the parameters.
2214        my ($self, $objectName, $filter, $parms) = @_;
2215        # Declare the return variable.
2216        my $retVal;
2217        # Insure the parms argument is an array reference if the caller left it off.
2218        if (! defined($parms)) {
2219            $parms = [];
2220        }
2221        # Insure we have a relationship. The main reason for this is if we delete an entity
2222        # instance we have to yank out a bunch of other stuff with it.
2223        if ($self->IsEntity($objectName)) {
2224            Confess("Cannot use DeleteLike on $objectName, because it is not a relationship.");
2225        } else {
2226            # Create the SQL command suffix to get the desierd records.
2227            my ($suffix) = $self->_SetupSQL([$objectName], $filter);
2228            # Convert it to a DELETE command.
2229            my $command = "DELETE $suffix";
2230            # Execute the command.
2231            my $dbh = $self->{_dbh};
2232            my $result = $dbh->SQL($command, 0, @{$parms});
2233            # Check the results. Note we convert the "0D0" result to a real zero.
2234            # A failure causes an abnormal termination, so the caller isn't going to
2235            # worry about it.
2236            if (! defined $result) {
2237                Confess("Error deleting from $objectName: " . $dbh->errstr());
2238            } elsif ($result == 0) {
2239                $retVal = 0;
2240            } else {
2241                $retVal = $result;
2242            }
2243        }
2244        # Return the result count.
2245        return $retVal;
2246    }
2247    
2248  =head3 SortNeeded  =head3 SortNeeded
2249    
2250  C<< my $parms = $erdb->SortNeeded($relationName); >>      my $parms = $erdb->SortNeeded($relationName);
2251    
2252  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
2253  relation when creating the load file.  relation when creating the load file.
# Line 2007  Line 2345 
2345    
2346  =head3 GetList  =head3 GetList
2347    
2348  C<< my @dbObjects = $erdb->GetList(\@objectNames, $filterClause, \@params); >>      my @dbObjects = $erdb->GetList(\@objectNames, $filterClause, \@params);
2349    
2350  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
2351  specified filter clause.  specified filter clause.
# Line 2035  Line 2373 
2373  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
2374  particular genus and sorts them by species name.  particular genus and sorts them by species name.
2375    
2376  C<< "Genome(genus) = ? ORDER BY Genome(species)" >>      "Genome(genus) = ? ORDER BY Genome(species)"
2377    
2378  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
2379  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 2047  Line 2385 
2385    
2386  =item RETURN  =item RETURN
2387    
2388  Returns a list of B<DBObject>s that satisfy the query conditions.  Returns a list of B<ERDBObject>s that satisfy the query conditions.
2389    
2390  =back  =back
2391    
# Line 2070  Line 2408 
2408    
2409  =head3 GetCount  =head3 GetCount
2410    
2411  C<< my $count = $erdb->GetCount(\@objectNames, $filter, \@params); >>      my $count = $erdb->GetCount(\@objectNames, $filter, \@params);
2412    
2413  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
2414  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 2163  Line 2501 
2501    
2502  =head3 ComputeObjectSentence  =head3 ComputeObjectSentence
2503    
2504  C<< my $sentence = $erdb->ComputeObjectSentence($objectName); >>      my $sentence = $erdb->ComputeObjectSentence($objectName);
2505    
2506  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.
2507    
# Line 2198  Line 2536 
2536    
2537  =head3 DumpRelations  =head3 DumpRelations
2538    
2539  C<< $erdb->DumpRelations($outputDirectory); >>      $erdb->DumpRelations($outputDirectory);
2540    
2541  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.
2542  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 2240  Line 2578 
2578    
2579  =head3 InsertValue  =head3 InsertValue
2580    
2581  C<< $erdb->InsertValue($entityID, $fieldName, $value); >>      $erdb->InsertValue($entityID, $fieldName, $value);
2582    
2583  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
2584  associated with a secondary relation, since primary values cannot be inserted:  associated with a secondary relation, since primary values cannot be inserted:
# Line 2303  Line 2641 
2641    
2642  =head3 InsertObject  =head3 InsertObject
2643    
2644  C<< $erdb->InsertObject($objectType, \%fieldHash); >>      $erdb->InsertObject($objectType, \%fieldHash);
2645    
2646  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
2647  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 2312  Line 2650 
2650  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
2651  C<ZP_00210270.1> and C<gi|46206278>.  C<ZP_00210270.1> and C<gi|46206278>.
2652    
2653  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']});
2654    
2655  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
2656  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>.
2657    
2658  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'});
2659    
2660  =over 4  =over 4
2661    
# Line 2428  Line 2766 
2766                  if (!$retVal) {                  if (!$retVal) {
2767                      my $errorString = $sth->errstr();                      my $errorString = $sth->errstr();
2768                      Confess("Error inserting into $relationName: $errorString");                      Confess("Error inserting into $relationName: $errorString");
2769                    } else {
2770                        Trace("Insert successful using $parameterList[0].") if T(3);
2771                  }                  }
2772              }              }
2773          }          }
# Line 2438  Line 2778 
2778    
2779  =head3 UpdateEntity  =head3 UpdateEntity
2780    
2781  C<< $erdb->UpdateEntity($entityName, $id, \%fields); >>      $erdb->UpdateEntity($entityName, $id, \%fields);
2782    
2783  Update the values of an entity. This is an unprotected update, so it should only be  Update the values of an entity. This is an unprotected update, so it should only be
2784  done if the database resides on a database server.  done if the database resides on a database server.
# Line 2496  Line 2836 
2836    
2837  =head3 LoadTable  =head3 LoadTable
2838    
2839  C<< my $results = $erdb->LoadTable($fileName, $relationName, $truncateFlag); >>      my $results = $erdb->LoadTable($fileName, $relationName, %options);
2840    
2841  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
2842  first.  first.
# Line 2511  Line 2851 
2851    
2852  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.
2853    
2854  =item truncateFlag  =item options
2855    
2856  TRUE if the table should be dropped and re-created, else FALSE  A hash of load options.
2857    
2858  =item RETURN  =item RETURN
2859    
# Line 2521  Line 2861 
2861    
2862  =back  =back
2863    
2864    The permissible options are as follows.
2865    
2866    =over 4
2867    
2868    =item truncate
2869    
2870    If TRUE, then the table will be erased before loading.
2871    
2872    =item mode
2873    
2874    Mode in which the load should operate, either C<low_priority> or C<concurrent>.
2875    This option is only applicable to a MySQL database.
2876    
2877    =item partial
2878    
2879    If TRUE, then it is assumed that this is a partial load, and the table will not
2880    be analyzed and compacted at the end.
2881    
2882    =back
2883    
2884  =cut  =cut
2885  sub LoadTable {  sub LoadTable {
2886      # Get the parameters.      # Get the parameters.
2887      my ($self, $fileName, $relationName, $truncateFlag) = @_;      my ($self, $fileName, $relationName, %options) = @_;
2888      # Create the statistical return object.      # Create the statistical return object.
2889      my $retVal = _GetLoadStats();      my $retVal = _GetLoadStats();
2890      # Trace the fact of the load.      # Trace the fact of the load.
# Line 2536  Line 2896 
2896      # Get the relation data.      # Get the relation data.
2897      my $relation = $self->_FindRelation($relationName);      my $relation = $self->_FindRelation($relationName);
2898      # Check the truncation flag.      # Check the truncation flag.
2899      if ($truncateFlag) {      if ($options{truncate}) {
2900          Trace("Creating table $relationName") if T(2);          Trace("Creating table $relationName") if T(2);
2901          # 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,
2902          # 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
2903          # leave extra room. We postulate a minimum row count of 1000 to          # leave extra room. We postulate a minimum row count of 1000 to
2904          # prevent problems with incoming empty load files.          # prevent problems with incoming empty load files.
2905          my $rowSize = $self->EstimateRowSize($relationName);          my $rowSize = $self->EstimateRowSize($relationName);
2906          my $estimate = FIG::max($fileSize * 1.5 / $rowSize, 1000);          my $estimate = $fileSize * 8 / $rowSize;
2907            if ($estimate < 1000) {
2908                $estimate = 1000;
2909            }
2910          # Re-create the table without its index.          # Re-create the table without its index.
2911          $self->CreateTable($relationName, 0, $estimate);          $self->CreateTable($relationName, 0, $estimate);
2912          # If this is a pre-index DBMS, create the index here.          # If this is a pre-index DBMS, create the index here.
# Line 2559  Line 2922 
2922      # Load the table.      # Load the table.
2923      my $rv;      my $rv;
2924      eval {      eval {
2925          $rv = $dbh->load_table(file => $fileName, tbl => $relationName);          $rv = $dbh->load_table(file => $fileName, tbl => $relationName, style => $options{mode});
2926      };      };
2927      if (!defined $rv) {      if (!defined $rv) {
2928          $retVal->AddMessage($@) if ($@);          $retVal->AddMessage($@) if ($@);
# Line 2571  Line 2934 
2934          my $size = -s $fileName;          my $size = -s $fileName;
2935          Trace("$size bytes loaded into $relationName.") if T(2);          Trace("$size bytes loaded into $relationName.") if T(2);
2936          # If we're rebuilding, we need to create the table indexes.          # If we're rebuilding, we need to create the table indexes.
2937          if ($truncateFlag) {          if ($options{truncate}) {
2938              # Indexes are created here for PostGres. For PostGres, indexes are              # Indexes are created here for PostGres. For PostGres, indexes are
2939              # best built at the end. For MySQL, the reverse is true.              # best built at the end. For MySQL, the reverse is true.
2940              if (! $dbh->{_preIndex}) {              if (! $dbh->{_preIndex}) {
# Line 2585  Line 2948 
2948              # 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.
2949              # 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
2950              # primary relations are allowed that privilege.              # primary relations are allowed that privilege.
2951                Trace("Checking for full-text index on $relationName.") if T(2);
2952              if ($self->_IsPrimary($relationName)) {              if ($self->_IsPrimary($relationName)) {
2953                  # 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",  
                                        flds => $fields, kind => 'fulltext');  
                 }  
2954              }              }
2955          }          }
2956      }      }
2957      # Analyze the table to improve performance.      # Analyze the table to improve performance.
2958        if (! $options{partial}) {
2959      Trace("Analyzing and compacting $relationName.") if T(3);      Trace("Analyzing and compacting $relationName.") if T(3);
2960      $dbh->vacuum_it($relationName);      $dbh->vacuum_it($relationName);
2961        }
2962      Trace("$relationName load completed.") if T(3);      Trace("$relationName load completed.") if T(3);
2963      # Return the statistics.      # Return the statistics.
2964      return $retVal;      return $retVal;
2965  }  }
2966    
2967    =head3 CreateSearchIndex
2968    
2969        $erdb->CreateSearchIndex($objectName);
2970    
2971    Check for a full-text search index on the specified entity or relationship object, and
2972    if one is required, rebuild it.
2973    
2974    =over 4
2975    
2976    =item objectName
2977    
2978    Name of the entity or relationship to be indexed.
2979    
2980    =back
2981    
2982    =cut
2983    
2984    sub CreateSearchIndex {
2985        # Get the parameters.
2986        my ($self, $objectName) = @_;
2987        # Get the relation's entity/relationship structure.
2988        my $structure = $self->_GetStructure($objectName);
2989        # Get the database handle.
2990        my $dbh = $self->{_dbh};
2991        Trace("Checking for search fields in $objectName.") if T(3);
2992        # Check for a searchable fields list.
2993        if (exists $structure->{searchFields}) {
2994            # Here we know that we need to create a full-text search index.
2995            # Get an SQL-formatted field name list.
2996            my $fields = join(", ", _FixNames(@{$structure->{searchFields}}));
2997            # Create the index. If it already exists, it will be dropped.
2998            $dbh->create_index(tbl => $objectName, idx => "search_idx",
2999                               flds => $fields, kind => 'fulltext');
3000            Trace("Index created for $fields in $objectName.") if T(2);
3001        }
3002    }
3003    
3004  =head3 DropRelation  =head3 DropRelation
3005    
3006  C<< $erdb->DropRelation($relationName); >>      $erdb->DropRelation($relationName);
3007    
3008  Physically drop a relation from the database.  Physically drop a relation from the database.
3009    
# Line 2638  Line 3031 
3031    
3032  =head3 MatchSqlPattern  =head3 MatchSqlPattern
3033    
3034  C<< my $matched = ERDB::MatchSqlPattern($value, $pattern); >>      my $matched = ERDB::MatchSqlPattern($value, $pattern);
3035    
3036  Determine whether or not a specified value matches an SQL pattern. An SQL  Determine whether or not a specified value matches an SQL pattern. An SQL
3037  pattern has two wild card characters: C<%> that matches multiple characters,  pattern has two wild card characters: C<%> that matches multiple characters,
# Line 2721  Line 3114 
3114    
3115  =head3 GetEntity  =head3 GetEntity
3116    
3117  C<< my $entityObject = $erdb->GetEntity($entityType, $ID); >>      my $entityObject = $erdb->GetEntity($entityType, $ID);
3118    
3119  Return an object describing the entity instance with a specified ID.  Return an object describing the entity instance with a specified ID.
3120    
# Line 2737  Line 3130 
3130    
3131  =item RETURN  =item RETURN
3132    
3133  Returns a B<DBObject> representing the desired entity instance, or an undefined value if no  Returns a B<ERDBObject> representing the desired entity instance, or an undefined value if no
3134  instance is found with the specified key.  instance is found with the specified key.
3135    
3136  =back  =back
# Line 2757  Line 3150 
3150    
3151  =head3 GetChoices  =head3 GetChoices
3152    
3153  C<< my @values = $erdb->GetChoices($entityName, $fieldName); >>      my @values = $erdb->GetChoices($entityName, $fieldName);
3154    
3155  Return a list of all the values for the specified field that are represented in the  Return a list of all the values for the specified field that are represented in the
3156  specified entity.  specified entity.
# Line 2812  Line 3205 
3205    
3206  =head3 GetEntityValues  =head3 GetEntityValues
3207    
3208  C<< my @values = $erdb->GetEntityValues($entityType, $ID, \@fields); >>      my @values = $erdb->GetEntityValues($entityType, $ID, \@fields);
3209    
3210  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
3211  does not exist, an empty list is returned.  does not exist, an empty list is returned.
# Line 2856  Line 3249 
3249    
3250  =head3 GetAll  =head3 GetAll
3251    
3252  C<< my @list = $erdb->GetAll(\@objectNames, $filterClause, \@parameters, \@fields, $count); >>      my @list = $erdb->GetAll(\@objectNames, $filterClause, \@parameters, \@fields, $count);
3253    
3254  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
3255  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 2870  Line 3263 
3263  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
3264  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
3265  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
3266  feature ID followed by all of its aliases.  feature ID followed by all of its essentiality determinations.
3267    
3268  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)']);
3269    
3270  =over 4  =over 4
3271    
# Line 2950  Line 3343 
3343    
3344  =head3 Exists  =head3 Exists
3345    
3346  C<< my $found = $sprout->Exists($entityName, $entityID); >>      my $found = $sprout->Exists($entityName, $entityID);
3347    
3348  Return TRUE if an entity exists, else FALSE.  Return TRUE if an entity exists, else FALSE.
3349    
# Line 2985  Line 3378 
3378    
3379  =head3 EstimateRowSize  =head3 EstimateRowSize
3380    
3381  C<< my $rowSize = $erdb->EstimateRowSize($relName); >>      my $rowSize = $erdb->EstimateRowSize($relName);
3382    
3383  Estimate the row size of the specified relation. The estimated row size is computed by adding  Estimate the row size of the specified relation. The estimated row size is computed by adding
3384  up the average length for each data type.  up the average length for each data type.
# Line 3023  Line 3416 
3416    
3417  =head3 GetFieldTable  =head3 GetFieldTable
3418    
3419  C<< my $fieldHash = $self->GetFieldTable($objectnName); >>      my $fieldHash = $self->GetFieldTable($objectnName);
3420    
3421  Get the field structure for a specified entity or relationship.  Get the field structure for a specified entity or relationship.
3422    
# Line 3052  Line 3445 
3445    
3446  =head3 SplitKeywords  =head3 SplitKeywords
3447    
3448  C<< my @keywords = ERDB::SplitKeywords($keywordString); >>      my @keywords = ERDB::SplitKeywords($keywordString);
3449    
3450  This method returns a list of the positive keywords in the specified  This method returns a list of the positive keywords in the specified
3451  keyword string. All of the operators will have been stripped off,  keyword string. All of the operators will have been stripped off,
# Line 3101  Line 3494 
3494    
3495  =head3 ValidateFieldName  =head3 ValidateFieldName
3496    
3497  C<< my $okFlag = ERDB::ValidateFieldName($fieldName); >>      my $okFlag = ERDB::ValidateFieldName($fieldName);
3498    
3499  Return TRUE if the specified field name is valid, else FALSE. Valid field names must  Return TRUE if the specified field name is valid, else FALSE. Valid field names must
3500  be hyphenated words subject to certain restrictions.  be hyphenated words subject to certain restrictions.
# Line 3156  Line 3549 
3549    
3550  =head3 ReadMetaXML  =head3 ReadMetaXML
3551    
3552  C<< my $rawMetaData = ERDB::ReadDBD($fileName); >>      my $rawMetaData = ERDB::ReadDBD($fileName);
3553    
3554  This method reads a raw database definition XML file and returns it.  This method reads a raw database definition XML file and returns it.
3555  Normally, the metadata used by the ERDB system has been processed and  Normally, the metadata used by the ERDB system has been processed and
# Line 3189  Line 3582 
3582    
3583  =head3 GetEntityFieldHash  =head3 GetEntityFieldHash
3584    
3585  C<< my $fieldHashRef = ERDB::GetEntityFieldHash($structure, $entityName); >>      my $fieldHashRef = ERDB::GetEntityFieldHash($structure, $entityName);
3586    
3587  Get the field hash of the named entity in the specified raw XML structure.  Get the field hash of the named entity in the specified raw XML structure.
3588  The field hash may not exist, in which case we need to create it.  The field hash may not exist, in which case we need to create it.
# Line 3231  Line 3624 
3624    
3625  =head3 WriteMetaXML  =head3 WriteMetaXML
3626    
3627  C<< ERDB::WriteMetaXML($structure, $fileName); >>      ERDB::WriteMetaXML($structure, $fileName);
3628    
3629  Write the metadata XML to a file. This method is the reverse of L</ReadMetaXML>, and is  Write the metadata XML to a file. This method is the reverse of L</ReadMetaXML>, and is
3630  used to update the database definition. It must be used with care, however, since it  used to update the database definition. It must be used with care, however, since it
# Line 3270  Line 3663 
3663  Except for C<[p]>, all the codes are closed by slash-codes. So, for  Except for C<[p]>, all the codes are closed by slash-codes. So, for
3664  example, C<[b]Feature[/b]> displays the string C<Feature> in boldface.  example, C<[b]Feature[/b]> displays the string C<Feature> in boldface.
3665    
3666  C<< my $realHtml = ERDB::HTMLNote($dataString); >>      my $realHtml = ERDB::HTMLNote($dataString);
3667    
3668  =over 4  =over 4
3669    
# Line 3294  Line 3687 
3687      # Substitute the bulletin board codes.      # Substitute the bulletin board codes.
3688      $retVal =~ s!\[(/?[bi])\]!<$1>!g;      $retVal =~ s!\[(/?[bi])\]!<$1>!g;
3689      $retVal =~ s!\[p\]!</p><p>!g;      $retVal =~ s!\[p\]!</p><p>!g;
3690        $retVal =~ s!\[link\s+([^\]]+)\]!<a href="$1">!g;
3691        $retVal =~ s!\[/link\]!</a>!g;
3692        # Return the result.
3693        return $retVal;
3694    }
3695    
3696    =head3 WikiNote
3697    
3698    Convert a note or comment to Wiki text by replacing some bulletin-board codes with HTML. The codes
3699    supported are C<[b]> for B<bold>, C<[i]> for I<italics>, and C<[p]> for a new paragraph.
3700    Except for C<[p]>, all the codes are closed by slash-codes. So, for
3701    example, C<[b]Feature[/b]> displays the string C<Feature> in boldface.
3702    
3703        my $wikiText = ERDB::WikiNote($dataString);
3704    
3705    =over 4
3706    
3707    =item dataString
3708    
3709    String to convert to Wiki text.
3710    
3711    =item RETURN
3712    
3713    An Wiki text string derived from the input string.
3714    
3715    =back
3716    
3717    =cut
3718    
3719    sub WikiNote {
3720        # Get the parameter.
3721        my ($dataString) = @_;
3722        # HTML-escape the text.
3723        my $retVal = CGI::escapeHTML($dataString);
3724        # Substitute the bulletin board codes.
3725        my $italic = WikiTools::ItalicCode();
3726        $retVal =~ s/\[\/?i\]/$italic/g;
3727        my $bold = WikiTools::BoldCode();
3728        $retVal =~ s/\[\/?b\]/$bold/g;
3729        # Paragraph breaks are the same no matter which Wiki you're using.
3730        $retVal =~ s!\[p\]!\n\n!g;
3731        # Now we do the links, which are complicated by the need to know two
3732        # things: the target URL and the text.
3733        while ($retVal =~ /\[link\s+([^\]]+)\]([^\[]+)\[\/link\]/g) {
3734            # Replace the matched string with the Wiki markup for links. Note that
3735            # $-[0] is the starting position of the match for the entire expression,
3736            # and $+[0] is past the ending position.
3737            substr $retVal, $-[0], $+[0] - $-[0], WikiTools::LinkMarkup($1, $2);
3738        }
3739        # Return the result.
3740        return $retVal;
3741    }
3742    
3743    =head3 BeginTran
3744    
3745        $erdb->BeginTran();
3746    
3747    Start a database transaction.
3748    
3749    =cut
3750    
3751    sub BeginTran {
3752        my ($self) = @_;
3753        $self->{_dbh}->begin_tran();
3754    
3755    }
3756    
3757    =head3 CommitTran
3758    
3759        $erdb->CommitTran();
3760    
3761    Commit an active database transaction.
3762    
3763    =cut
3764    
3765    sub CommitTran {
3766        my ($self) = @_;
3767        $self->{_dbh}->commit_tran();
3768    }
3769    
3770    =head3 RollbackTran
3771    
3772        $erdb->RollbackTran();
3773    
3774    Roll back an active database transaction.
3775    
3776    =cut
3777    
3778    sub RollbackTran {
3779        my ($self) = @_;
3780        $self->{_dbh}->roll_tran();
3781    }
3782    
3783    =head3 UpdateField
3784    
3785        my $count = $erdb->UpdateField($objectNames, $fieldName, $oldValue, $newValue, $filter, $parms);
3786    
3787    Update all occurrences of a specific field value to a new value. The number of rows changed will be
3788    returned.
3789    
3790    =over 4
3791    
3792    =item fieldName
3793    
3794    Name of the field in standard I<objectName>C<(>I<fieldName>C<)> format.
3795    
3796    =item oldValue
3797    
3798    Value to be modified. All occurrences of this value in the named field will be replaced by the
3799    new value.
3800    
3801    =item newValue
3802    
3803    New value to be substituted for the old value when it's found.
3804    
3805    =item filter
3806    
3807    A standard ERDB filter clause (see L</Get>). The filter will be applied before any substitutions take place.
3808    
3809    =item parms
3810    
3811    Reference to a list of parameter values in the filter.
3812    
3813    =item RETURN
3814    
3815    Returns the number of rows modified.
3816    
3817    =back
3818    
3819    =cut
3820    
3821    sub UpdateField {
3822        # Get the parameters.
3823        my ($self, $fieldName, $oldValue, $newValue, $filter, $parms) = @_;
3824        # Get the object and field names from the field name parameter.
3825        $fieldName =~ /^([^(]+)\(([^)]+)\)/;
3826        my $objectName = $1;
3827        my $realFieldName = _FixName($2);
3828        # Add the old value to the filter. Note we allow the possibility that no
3829        # filter was specified.
3830        my $realFilter = "$fieldName = ?";
3831        if ($filter) {
3832            $realFilter .= " AND $filter";
3833        }
3834        # Format the query filter.
3835        my ($suffix, $mappedNameListRef, $mappedNameHashRef) =
3836            $self->_SetupSQL([$objectName], $realFilter);
3837        # Create the query. Since there is only one object name, the mapped-name data is not
3838        # necessary. Neither is the FROM clause.
3839        $suffix =~ s/^FROM.+WHERE\s+//;
3840        # Create the update statement.
3841        my $command = "UPDATE $objectName SET $realFieldName = ? WHERE $suffix";
3842        # Get the database handle.
3843        my $dbh = $self->{_dbh};
3844        # Add the old and new values to the parameter list. Note we allow the possibility that
3845        # there are no user-supplied parameters.
3846        my @params = ($newValue, $oldValue);
3847        if (defined $parms) {
3848            push @params, @{$parms};
3849        }
3850        # Execute the update.
3851        my $retVal = $dbh->SQL($command, 0, @params);
3852        # Make the funky zero a real zero.
3853        if ($retVal == 0) {
3854            $retVal = 0;
3855        }
3856      # Return the result.      # Return the result.
3857      return $retVal;      return $retVal;
3858  }  }
# Line 3303  Line 3862 
3862    
3863  =head3 GetUsefulCrossValues  =head3 GetUsefulCrossValues
3864    
3865  C<< my @attrNames = $sprout->GetUsefulCrossValues($sourceEntity, $relationship); >>      my @attrNames = $sprout->GetUsefulCrossValues($sourceEntity, $relationship);
3866    
3867  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
3868  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 3364  Line 3923 
3923    
3924  =head3 FindColumn  =head3 FindColumn
3925    
3926  C<< my $colIndex = ERDB::FindColumn($headerLine, $columnIdentifier); >>      my $colIndex = ERDB::FindColumn($headerLine, $columnIdentifier);
3927    
3928  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
3929  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 3422  Line 3981 
3981    
3982  =head3 ParseColumns  =head3 ParseColumns
3983    
3984  C<< my @columns = ERDB::ParseColumns($line); >>      my @columns = ERDB::ParseColumns($line);
3985    
3986  Convert the specified data line to a list of columns.  Convert the specified data line to a list of columns.
3987    
# Line 3454  Line 4013 
4013    
4014  =head2 Virtual Methods  =head2 Virtual Methods
4015    
4016    =head3 _CreatePPOIndex
4017    
4018        my $index = ERDB::_CreatePPOIndex($indexObject);
4019    
4020    Convert the XML for an ERDB index to the XML structure for a PPO
4021    index.
4022    
4023    =over 4
4024    
4025    =item indexObject
4026    
4027    ERDB XML structure for an index.
4028    
4029    =item RETURN
4030    
4031    PPO XML structure for the same index.
4032    
4033    =back
4034    
4035    =cut
4036    
4037    sub _CreatePPOIndex {
4038        # Get the parameters.
4039        my ($indexObject) = @_;
4040        # The incoming index contains a list of the index fields in the IndexFields
4041        # member. We loop through it to create the index tags.
4042        my @fields = map { { label => _FixName($_->{name}) } } @{$indexObject->{IndexFields}};
4043        # Wrap the fields in attribute tags.
4044        my $retVal = { attribute => \@fields };
4045        # Return the result.
4046        return $retVal;
4047    }
4048    
4049    =head3 _CreatePPOField
4050    
4051        my $fieldXML = ERDB::_CreatePPOField($fieldName, $fieldObject);
4052    
4053    Convert the ERDB XML structure for a field to a PPO scalar XML structure.
4054    
4055    =over 4
4056    
4057    =item fieldName
4058    
4059    Name of the scalar field.
4060    
4061    =item fieldObject
4062    
4063    ERDB XML structure describing the field.
4064    
4065    =item RETURN
4066    
4067    Returns a PPO XML structure for the same field.
4068    
4069    =back
4070    
4071    =cut
4072    
4073    sub _CreatePPOField {
4074        # Get the parameters.
4075        my ($fieldName, $fieldObject) = @_;
4076        # Get the field type.
4077        my $type = $TypeTable{$fieldObject->{type}}->{sqlType};
4078        # Fix up the field name.
4079        $fieldName = _FixName($fieldName);
4080        # Build the scalar tag.
4081        my $retVal = { label => $fieldName, type => $type };
4082        # Return the result.
4083        return $retVal;
4084    }
4085    
4086  =head3 CleanKeywords  =head3 CleanKeywords
4087    
4088  C<< my $cleanedString = $erdb->CleanKeywords($searchExpression); >>      my $cleanedString = $erdb->CleanKeywords($searchExpression);
4089    
4090  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
4091  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 3493  Line 4122 
4122    
4123  =head3 GetSourceObject  =head3 GetSourceObject
4124    
4125  C<< my $source = $erdb->GetSourceObject($entityName); >>      my $source = $erdb->GetSourceObject($entityName);
4126    
4127  Return the object to be used in loading special attributes of the specified entity. The  Return the object to be used in loading special attributes of the specified entity. The
4128  algorithm for loading special attributes is stored in the C<DataGen> elements of the  algorithm for loading special attributes is stored in the C<DataGen> elements of the
# Line 3503  Line 4132 
4132    
4133  =head3 _RelationMap  =head3 _RelationMap
4134    
4135  C<< my @relationMap = _RelationMap($mappedNameHashRef, $mappedNameListRef); >>      my @relationMap = _RelationMap($mappedNameHashRef, $mappedNameListRef);
4136    
4137  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>
4138  to determine how to interpret the results of the query.  to determine how to interpret the results of the query.
4139    
4140  =over 4  =over 4
# Line 3522  Line 4151 
4151  =item RETURN  =item RETURN
4152    
4153  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
4154  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
4155  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
4156  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
4157  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 3816  Line 4445 
4445  sub _GetStatementHandle {  sub _GetStatementHandle {
4446      # Get the parameters.      # Get the parameters.
4447      my ($self, $command, $params) = @_;      my ($self, $command, $params) = @_;
4448        Confess("Invalid parameter list.") if (! defined($params) || ref($params) ne 'ARRAY');
4449      # Trace the query.      # Trace the query.
4450      Trace("SQL query: $command") if T(SQL => 3);      Trace("SQL query: $command") if T(SQL => 3);
4451      Trace("PARMS: '" . (join "', '", @{$params}) . "'") if (T(SQL => 4) && (@{$params} > 0));      Trace("PARMS: '" . (join "', '", @{$params}) . "'") if (T(SQL => 4) && (@{$params} > 0));
# Line 4053  Line 4683 
4683      # be a null string.      # be a null string.
4684      if ($fileName ne "") {      if ($fileName ne "") {
4685          # Load the relation from the file.          # Load the relation from the file.
4686          $retVal = $self->LoadTable($fileName, $relationName, $rebuild);          $retVal = $self->LoadTable($fileName, $relationName, truncate => $rebuild);
4687      } elsif ($rebuild) {      } elsif ($rebuild) {
4688          # 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.
4689          $self->CreateTable($relationName, 1);          $self->CreateTable($relationName, 1);
# Line 4065  Line 4695 
4695    
4696  =head3 _LoadMetaData  =head3 _LoadMetaData
4697    
4698        my $metadata = ERDB::_LoadMetaData($filename);
4699    
4700  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.
4701  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
4702  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 4214  Line 4846 
4846              if ($found == 0) {              if ($found == 0) {
4847                  push @{$indexList}, { IndexFields => [ {name => 'id', order => 'ascending'} ] };                  push @{$indexList}, { IndexFields => [ {name => 'id', order => 'ascending'} ] };
4848              }              }
4849              # 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.
4850              # 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$count", $relation, $index);  
                 # Increment the counter so that the next index has a different name.  
                 $count++;  
             }  
4851          }          }
4852          # Finally, we add the relation structure to the entity.          # Finally, we add the relation structure to the entity.
4853          $entityStructure->{Relations} = $relationTable;          $entityStructure->{Relations} = $relationTable;
# Line 4238  Line 4861 
4861          _FixupFields($relationshipStructure, $relationshipName, 2, 3);          _FixupFields($relationshipStructure, $relationshipName, 2, 3);
4862          # Format a description for the FROM field.          # Format a description for the FROM field.
4863          my $fromEntity = $relationshipStructure->{from};          my $fromEntity = $relationshipStructure->{from};
4864          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].";
4865          # Get the FROM entity's key type.          # Get the FROM entity's key type.
4866          my $fromType = $entityList->{$fromEntity}->{keyType};          my $fromType = $entityList->{$fromEntity}->{keyType};
4867          # Add the FROM field.          # Add the FROM field.
# Line 4248  Line 4871 
4871                                                      PrettySort => 1});                                                      PrettySort => 1});
4872          # Format a description for the TO field.          # Format a description for the TO field.
4873          my $toEntity = $relationshipStructure->{to};          my $toEntity = $relationshipStructure->{to};
4874          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].";
4875          # Get the TO entity's key type.          # Get the TO entity's key type.
4876          my $toType = $entityList->{$toEntity}->{keyType};          my $toType = $entityList->{$toEntity}->{keyType};
4877          # Add the TO field.          # Add the TO field.
# Line 4260  Line 4883 
4883          my $thisRelation = { Fields => _ReOrderRelationTable($relationshipStructure->{Fields}),          my $thisRelation = { Fields => _ReOrderRelationTable($relationshipStructure->{Fields}),
4884                               Indexes => { } };                               Indexes => { } };
4885          $relationshipStructure->{Relations} = { $relationshipName => $thisRelation };          $relationshipStructure->{Relations} = { $relationshipName => $thisRelation };
4886    
4887            # Add the alternate indexes (if any). This MUST be done before the FROM and
4888            # TO indexes, because it erases the relation's index list.
4889            if (exists $relationshipStructure->{Indexes}) {
4890                _ProcessIndexes($relationshipStructure->{Indexes}, $thisRelation);
4891            }
4892            # Add the relation to the master table.
4893          # Create the FROM and TO indexes.          # Create the FROM and TO indexes.
4894          _CreateRelationshipIndex("From", $relationshipName, $relationshipStructure);          _CreateRelationshipIndex("From", $relationshipName, $relationshipStructure);
4895          _CreateRelationshipIndex("To", $relationshipName, $relationshipStructure);          _CreateRelationshipIndex("To", $relationshipName, $relationshipStructure);
         # Add the relation to the master table.  
4896          $masterRelationTable{$relationshipName} = $thisRelation;          $masterRelationTable{$relationshipName} = $thisRelation;
4897      }      }
4898      # Now store the master relation table in the metadata structure.      # Now store the master relation table in the metadata structure.
# Line 4422  Line 5051 
5051      _AddIndex("idx$indexKey", $relationStructure, $newIndex);      _AddIndex("idx$indexKey", $relationStructure, $newIndex);
5052  }  }
5053    
5054    =head3 _ProcessIndexes
5055    
5056        ERDB::_ProcessIndexes($indexList, $relation);
5057    
5058    Build the data structures for the specified indexes in the specified relation.
5059    
5060    =over 4
5061    
5062    =item indexList
5063    
5064    Reference to a list of indexes. Each index is a hash reference containing an optional
5065    C<Notes> value that describes the index and an C<IndexFields> value that is a reference
5066    to a list of index field structures. An index field structure, in turn, is a reference
5067    to a hash that contains a C<name> attribute for the field name and an C<order>
5068    attribute that specifies either C<ascending> or C<descending>. In this sense the
5069    index list encapsulates the XML C<Indexes> structure in the database definition.
5070    
5071    =item relation
5072    
5073    The structure that describes the current relation. The new index descriptors will
5074    be stored in the structure's C<Indexes> member. Any previous data in the structure
5075    will be lost.
5076    
5077    =back
5078    
5079    =cut
5080    
5081    sub _ProcessIndexes {
5082        # Get the parameters.
5083        my ($indexList, $relation) = @_;
5084        # Now we need to convert the relation's index list to an index table. We begin by creating
5085        # an empty table in the relation structure.
5086        $relation->{Indexes} = { };
5087        # Loop through the indexes.
5088        my $count = 0;
5089        for my $index (@{$indexList}) {
5090            # Add this index to the index table.
5091            _AddIndex("idx$count", $relation, $index);
5092            # Increment the counter so that the next index has a different name.
5093            $count++;
5094        }
5095    }
5096    
5097  =head3 _AddIndex  =head3 _AddIndex
5098    
5099  Add an index to a relation structure.  Add an index to a relation structure.
# Line 4790  Line 5462 
5462      # Get the parameters.      # Get the parameters.
5463      my ($relationshipName, $relationshipStructure) = @_;      my ($relationshipName, $relationshipStructure) = @_;
5464      # Format the relationship sentence.      # Format the relationship sentence.
5465      my $result = "$relationshipStructure->{from} <b>$relationshipName</b> $relationshipStructure->{to}";      my $result = "$relationshipStructure->{from} $relationshipName $relationshipStructure->{to}";
5466      # Compute the arity.      # Compute the arity.
5467      my $arityCode = $relationshipStructure->{arity};      my $arityCode = $relationshipStructure->{arity};
5468      my $arity = $ArityTable{$arityCode};      my $arity = $ArityTable{$arityCode};
# Line 4835  Line 5507 
5507      return $result;      return $result;
5508  }  }
5509    
5510    =head3 _WikiRelationTable
5511    
5512    Generate the Wiki text for a particular relation. The relation's data will be formatted as a
5513    table with three columns-- the field name, the field type, and the field description.
5514    
5515    This is a static method.
5516    
5517    =over 4
5518    
5519    =item relationName
5520    
5521    Name of the relation being formatted.
5522    
5523    =item relationData
5524    
5525    Hash containing the relation's fields and indexes.
5526    
5527    =item RETURN
5528    
5529    Returns a Wiki string that can be used to display the relation name and all of its fields.
5530    
5531    =back
5532    
5533    =cut
5534    
5535    sub _WikiRelationTable {
5536        # Get the parameters.
5537        my ($relationName, $relationData) = @_;
5538        # We'll create a list of lists in here, then call WikiTools::Table to
5539        # convert it into a table.
5540        my @rows = ();
5541        # Push in the header row.
5542        push @rows, [qw(Field Type Description)];
5543        # Loop through the fields.
5544        for my $field (@{$relationData->{Fields}}) {
5545            # Create this field's row. We always have a name and type.
5546            my @row = ($field->{name}, $field->{type});
5547            # If we have a description, add it as the third column.
5548            if (exists $field->{Notes}) {
5549                push @row, WikiNote($field->{Notes}->{content});
5550            }
5551            # Push this row onto the table list.
5552            push @rows, \@row;
5553        }
5554        # Store the rows as a Wiki table.
5555        my $retVal = WikiTools::Table(@rows);
5556        # Now we show the relation's indexes. These are formatted as another
5557        # table.
5558        @rows = ();
5559        # Push in the header row.
5560        push @rows, [qw(Index Unique Fields Notes)];
5561        # Get the index hash.
5562        my $indexTable = $relationData->{Indexes};
5563        # Loop through the indexes. For an entity, there is always at least one index.
5564        # For a relationship, there are at least two. The upshot is we don't need to
5565        # worry about accidentally generating a frivolous table here.
5566        for my $indexName (sort keys %$indexTable) {
5567            my $indexData = $indexTable->{$indexName};
5568            # Determine whether or not the index is unique.
5569            my $unique = ((exists $indexData->{Unique} && $indexData->{Unique} eq "true") ?
5570                          "yes" : "");
5571            # Get the field list.
5572            my $fields = join(', ', @{$indexData->{IndexFields}});
5573            # Get the note text.
5574            my $description = "";
5575            if (my $note = $indexData->{Notes}) {
5576                $description = WikiNote($note->{content});
5577            }
5578            # Format this row.
5579            my @row = ($indexName, $unique, $fields, $description);
5580            push @rows, \@row;
5581        }
5582        # Add the index list to the result.
5583        $retVal .= "\n\n" . WikiTools::Table(@rows);
5584    }
5585    
5586    
5587  =head3 _ShowRelationTable  =head3 _ShowRelationTable
5588    
5589  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 4951  Line 5700 
5700      # Compute the number of columns.      # Compute the number of columns.
5701      my $colCount = @colNames;      my $colCount = @colNames;
5702      # Generate the title row.      # Generate the title row.
5703      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";
5704      # Loop through the columns, adding the column header rows.      # Loop through the columns, adding the column header rows.
5705      $htmlString .= "<tr>";      $htmlString .= "<tr>";
5706      for my $colName (@colNames) {      for my $colName (@colNames) {
# Line 4970  Line 5719 
5719  =cut  =cut
5720    
5721  sub _CloseTable {  sub _CloseTable {
5722      return "</table></p>\n";      return "</table>\n";
5723  }  }
5724    
5725  =head3 _ShowField  =head3 _ShowField

Legend:
Removed from v.1.79  
changed lines
  Added in v.1.95

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3