[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.87, Sun Feb 18 21:28:19 2007 UTC revision 1.97, Wed May 7 23:08:19 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;
15    
16  =head1 Entity-Relationship Database Package  =head1 Entity-Relationship Database Package
17    
# Line 373  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 406  Line 409 
409                    XMLDecl => 1,                    XMLDecl => 1,
410                   );                   );
411    
   
412  =head2 Public Methods  =head2 Public Methods
413    
414  =head3 new  =head3 new
415    
416  C<< my $database = ERDB->new($dbh, $metaFileName); >>      my $database = ERDB->new($dbh, $metaFileName);
417    
418  Create a new ERDB object.  Create a new ERDB object.
419    
# Line 431  Line 433 
433    
434  sub new {  sub new {
435      # Get the parameters.      # Get the parameters.
436      my ($class, $dbh, $metaFileName, $options) = @_;      my ($class, $dbh, $metaFileName, %options) = @_;
437      # Load the meta-data.      # Load the meta-data.
438      my $metaData = _LoadMetaData($metaFileName);      my $metaData = _LoadMetaData($metaFileName);
439      # Create the object.      # Create the object.
# Line 445  Line 447 
447    
448  =head3 ShowMetaData  =head3 ShowMetaData
449    
450  C<< $erdb->ShowMetaData($fileName); >>      $erdb->ShowMetaData($fileName);
451    
452  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
453  the data to be loaded into the relations.  the data to be loaded into the relations.
# Line 486  Line 488 
488    
489  =head3 DisplayMetaData  =head3 DisplayMetaData
490    
491  C<< my $html = $erdb->DisplayMetaData(); >>      my $html = $erdb->DisplayMetaData();
492    
493  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
494  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 642  Line 644 
644    
645  =head3 DumpMetaData  =head3 DumpMetaData
646    
647  C<< $erdb->DumpMetaData(); >>      $erdb->DumpMetaData();
648    
649  Return a dump of the metadata structure.  Return a dump of the metadata structure.
650    
# Line 655  Line 657 
657      return Data::Dumper::Dumper($self->{_metaData});      return Data::Dumper::Dumper($self->{_metaData});
658  }  }
659    
660    =head3 GenerateWikiData
661    
662        my @wikiLines = $erdb->GenerateWikiData();
663    
664    Build a description of the database for the wiki. The database will be
665    organized into a single page, with sections for each entity and relationship.
666    The return value is a list of text lines.
667    
668    =cut
669    
670    sub GenerateWikiData {
671        # Get the parameters.
672        my ($self) = @_;
673        # We'll build the wiki text in here.
674        my @retVal = ();
675        # Get the metadata object.
676        my $metadata = $self->{_metaData};
677        # Get the title string. This will become the page name.
678        my $title = $metadata->{Title}->{content};
679        # Get the entity and relationship lists.
680        my $entityList = $metadata->{Entities};
681        my $relationshipList = $metadata->{Relationships};
682        # Start with the introductory text.
683        push @retVal, WikiTools::Heading(2, "Introduction");
684        if (my $notes = $metadata->{Notes}) {
685            push @retVal, WikiNote($notes->{content});
686        }
687        # Start the entity section.
688        push @retVal, WikiTools::Heading(2, "Entities");
689        # Loop through the entities. Note that unlike the situation with HTML, we
690        # don't need to generate the table of contents manually, just the data
691        # itself.
692        for my $key (sort keys %$entityList) {
693            # Create a header for this entity.
694            push @retVal, "", WikiTools::Heading(3, $key);
695            # Get the entity data.
696            my $entityData = $entityList->{$key};
697            # Plant the notes here, if there are any.
698            if (my $notes = $entityData->{Notes}) {
699                push @retVal, "", WikiNote($notes->{content});
700            }
701            # Get the entity's relations.
702            my $relationList = $entityData->{Relations};
703            # Loop through the relations, displaying them.
704            for my $relation (sort keys %{$relationList}) {
705                my $wikiString = _WikiRelationTable($relation, $relationList->{$relation});
706                push @retVal, $wikiString;
707            }
708            # Now we list the entity's relationships (if any). First, we build a list
709            # of the relationships relevant to this entity.
710            my @rels = ();
711            for my $rel (sort keys %$relationshipList) {
712                my $relStructure = $relationshipList->{$rel};
713                if ($relStructure->{from} eq $key || $relStructure->{to} eq $key) {
714                    # Get the relationship sentence.
715                    my $relSentence = _ComputeRelationshipSentence($rel, $relStructure);
716                    # Linkify it.
717                    my $linkedRel = WikiTools::LinkMarkup("#$rel", $rel);
718                    $relSentence =~ s/$rel/$linkedRel/;
719                    push @rels, $relSentence;
720                }
721            }
722            # Add the relationships as a Wiki list.
723            push @retVal, WikiTools::List(@rels);
724        }
725        # Now the entities are documented. Next we do the relationships.
726        push @retVal, WikiTools::Heading(2, "Relationships");
727        for my $key (sort keys %$relationshipList) {
728            my $relationshipData = $relationshipList->{$key};
729            # Create the relationship heading.
730            push @retVal, WikiTools::Heading(3, $key);
731            # Describe the relationship arity. Note there's a bit of trickiness involving recursive
732            # many-to-many relationships. In a normal many-to-many we use two sentences to describe
733            # the arity (one for each direction). This is a bad idea for a recursive relationship,
734            # since both sentences will say the same thing.
735            my $arity = $relationshipData->{arity};
736            my $fromEntity = $relationshipData->{from};
737            my $toEntity = $relationshipData->{to};
738            my @listElements = ();
739            my $boldCode = WikiTools::BoldCode();
740            if ($arity eq "11") {
741                push @listElements, "Each $boldCode$fromEntity$boldCode relates to at most one $boldCode$toEntity$boldCode.";
742            } else {
743                push @listElements, "Each $boldCode$fromEntity$boldCode relates to multiple $boldCode${toEntity}s$boldCode.\n";
744                if ($arity eq "MM" && $fromEntity ne $toEntity) {
745                    push @listElements, "Each $boldCode$toEntity$boldCode relates to multiple $boldCode${fromEntity}s$boldCode.\n";
746                }
747            }
748            push @retVal, WikiTools::List(@listElements);
749            # Plant the notes here, if there are any.
750            if (my $notes = $relationshipData->{Notes}) {
751                push @retVal, "", WikiNote($notes->{content});
752            }
753            # Finally, the relationship table.
754            my $wikiString = _WikiRelationTable($key, $relationshipData->{Relations}->{$key});
755            push @retVal, $wikiString;
756        }
757        # All done. Return the lines.
758        return @retVal;
759    }
760    
761    
762    =head3 CreatePPO
763    
764        ERDB::CreatePPO($erdbXMLFile, $ppoXMLFile);
765    
766    Create a PPO XML file from an ERDB data definition XML file. At the
767    current time, the PPO XML file can be used to create a database with
768    similar functionality. Eventually, the PPO will be able to use the
769    created XML to access the live ERDB database.
770    
771    =over 4
772    
773    =item erdbXMLFile
774    
775    Name of the XML data definition file for the ERDB database. This
776    file must exist.
777    
778    =item ppoXMLFile
779    
780    Output file for the PPO XML definition. If this file exists, it
781    will be overwritten.
782    
783    =back
784    
785    =cut
786    
787    sub CreatePPO {
788        # Get the parameters.
789        my ($erdbXMLFile, $ppoXMLFile) = @_;
790        # First, we want to slurp in the ERDB XML file in its raw form.
791        my $xml = ReadMetaXML($erdbXMLFile);
792        # Create a variable to hold all of the objects in the PPO project.
793        my @objects = ();
794        # Get the relationship hash.
795        my $relationships = $xml->{Relationships};
796        # Loop through the entities.
797        my $entities = $xml->{Entities};
798        for my $entityName (keys %{$entities}) {
799            # Get the entity's data structures.
800            my $entityObject = $entities->{$entityName};
801            # We put the object's fields in here, according to their type.
802            my (@object_refs, @scalars, @indexes, @arrays);
803            # Create the ID field for the entity. We get the key type from the
804            # entity object and compute the corresponding SQL type.
805            my $type = $TypeTable{$entityObject->{keyType}}->{sqlType};
806            push @scalars, { label => 'id', type => $type };
807            # Loop through the entity fields.
808            for my $fieldName ( keys %{$entityObject->{Fields}} ) {
809                # Get the field object.
810                my $fieldObject = $entityObject->{Fields}->{$fieldName};
811                # Convert it to a scalar tag.
812                my $scalar = _CreatePPOField($fieldName, $fieldObject);
813                # If we have a relation, this field is stored in an array.
814                # otherwise, it is a scalar. The array tag has scalars
815                # stored as an XML array. In ERDB, there is only ever one,
816                # but PPO can have more.
817                my $relation = $fieldObject->{relation};
818                if ($relation) {
819                    push @arrays, { scalar => [$scalar] };
820                } else {
821                    push @scalars, $scalar;
822                }
823            }
824            # Loop through the relationships. If this entity is the to-entity
825            # on a relationship of 1M arity, then it is implemented as a PPO
826            # object reference.
827            for my $relationshipName (keys %{$relationships}) {
828                # Get the relationship data.
829                my $relationshipData = $relationships->{$relationshipName};
830                # If we have a from for this entity and an arity of 1M, we
831                # have an object reference.
832                if ($relationshipData->{to} eq $entityName &&
833                    $relationshipData->{arity} eq '1M') {
834                    # Build the object reference tag.
835                    push @object_refs, { label => $relationshipName,
836                                         type => $relationshipData->{from} };
837                }
838            }
839            # Create the indexes.
840            my $indexList = $entityObject->{Indexes};
841            push @indexes, map { _CreatePPOIndex($_) } @{$indexList};
842            # Build the object XML tree.
843            my $object = { label => $entityName,
844                           object_ref => \@object_refs,
845                           scalar => \@scalars,
846                           index => \@indexes,
847                           array => \@arrays
848                          };
849            # Push the object onto the objects list.
850            push @objects, $object;
851        }
852        # Loop through the relationships, searching for MMs. The 1Ms were
853        # already handled by the entity search above.
854        for my $relationshipName (keys %{$relationships}) {
855            # Get this relationship's object.
856            my $relationshipObject = $relationships->{$relationshipName};
857            # Only proceed if it's many-to-many.
858            if ($relationshipObject->{arity} eq 'MM') {
859                # Create the tag lists for the relationship object.
860                my (@object_refs, @scalars, @indexes);
861                # The relationship will be created as an object with object
862                # references for its links to the participating entities.
863                my %links = ( from_link => $relationshipObject->{from},
864                              to_link => $relationshipObject->{to} );
865                for my $link (keys %links) {
866                    # Create an object_ref tag for this piece of the
867                    # relationship (from or to).
868                    my $object_ref = { label => $link,
869                                       type => $links{$link} };
870                    push @object_refs, $object_ref;
871                }
872                # Loop through the intersection data fields, creating scalar tags.
873                # There are no fancy array tags in a relationship.
874                for my $fieldName (keys %{$relationshipObject->{Fields}}) {
875                    my $fieldObject = $relationshipObject->{Fields}->{$fieldName};
876                    push @scalars, _CreatePPOField($fieldName, $fieldObject);
877                }
878                # Finally, the indexes: currently we cannot support the to-index and
879                # from-index in PPO, so we just process the alternate indexes.
880                my $indexList = $relationshipObject->{Indexes};
881                push @indexes, map { _CreatePPOIndex($_) } @{$indexList};
882                # Wrap up all the stuff about this relationship.
883                my $object = { label => $relationshipName,
884                               scalar => \@scalars,
885                               object_ref => \@object_refs,
886                               index => \@indexes
887                             };
888                # Push it into the object list.
889                push @objects, $object;
890            }
891        }
892        # Compute a title.
893        my $title;
894        if ($erdbXMLFile =~ /(\/|^)([^\/]+)DBD\.xml/) {
895            # Here we have a standard file name we can use for a title.
896            $title = $2;
897        } else {
898            # Here the file name is non-standard, so we carve up the
899            # database title.
900            $title = $xml->{Title}->{content};
901            $title =~ s/\s\.,//g;
902        }
903        # Wrap up the XML as a project.
904        my $ppoXML = { project => { label => $title,
905                                    object => \@objects }};
906        # Write out the results.
907        my $ppoString = XML::Simple::XMLout($ppoXML,
908                                            AttrIndent => 1,
909                                            KeepRoot => 1);
910        Tracer::PutFile($ppoXMLFile, [ $ppoString ]);
911    }
912    
913  =head3 FindIndexForEntity  =head3 FindIndexForEntity
914    
915  C<< my $indexFound = ERDB::FindIndexForEntity($xml, $entityName, $attributeName); >>      my $indexFound = ERDB::FindIndexForEntity($xml, $entityName, $attributeName);
916    
917  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
918  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 727  Line 982 
982    
983  =head3 CreateTables  =head3 CreateTables
984    
985  C<< $erdb->CreateTables(); >>      $erdb->CreateTables();
986    
987  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
988  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 751  Line 1006 
1006    
1007  =head3 CreateTable  =head3 CreateTable
1008    
1009  C<< $erdb->CreateTable($tableName, $indexFlag, $estimatedRows); >>      $erdb->CreateTable($tableName, $indexFlag, $estimatedRows);
1010    
1011  Create the table for a relation and optionally create its indexes.  Create the table for a relation and optionally create its indexes.
1012    
# Line 807  Line 1062 
1062      my $estimation = undef;      my $estimation = undef;
1063      if ($estimatedRows) {      if ($estimatedRows) {
1064          $estimation = [$self->EstimateRowSize($relationName), $estimatedRows];          $estimation = [$self->EstimateRowSize($relationName), $estimatedRows];
1065            Trace("$estimation->[1] rows of $estimation->[0] bytes each.") if T(3);
1066      }      }
1067      # Create the table.      # Create the table.
1068      Trace("Creating table $relationName: $fieldThing") if T(2);      Trace("Creating table $relationName: $fieldThing") if T(2);
# Line 821  Line 1077 
1077    
1078  =head3 VerifyFields  =head3 VerifyFields
1079    
1080  C<< my $count = $erdb->VerifyFields($relName, \@fieldList); >>      my $count = $erdb->VerifyFields($relName, \@fieldList);
1081    
1082  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
1083  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 864  Line 1120 
1120              my $oldString = $fieldList->[$i];              my $oldString = $fieldList->[$i];
1121              if (length($oldString) > $maxLen) {              if (length($oldString) > $maxLen) {
1122                  # Here it's too big, so we truncate it.                  # Here it's too big, so we truncate it.
1123                  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);
1124                  $fieldList->[$i] = substr $oldString, 0, $maxLen;                  $fieldList->[$i] = substr $oldString, 0, $maxLen;
1125                  $retVal++;                  $retVal++;
1126              }              }
# Line 876  Line 1132 
1132    
1133  =head3 DigestFields  =head3 DigestFields
1134    
1135  C<< $erdb->DigestFields($relName, $fieldList); >>      $erdb->DigestFields($relName, $fieldList);
1136    
1137  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
1138  specified relation.  specified relation.
# Line 916  Line 1172 
1172    
1173  =head3 DigestKey  =head3 DigestKey
1174    
1175  C<< my $digested = $erdb->DigestKey($keyValue); >>      my $digested = $erdb->DigestKey($keyValue);
1176    
1177  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
1178  key-based search into a table with key-type hash-string.  key-based search into a table with key-type hash-string.
# Line 949  Line 1205 
1205    
1206  =head3 CreateIndex  =head3 CreateIndex
1207    
1208  C<< $erdb->CreateIndex($relationName); >>      $erdb->CreateIndex($relationName);
1209    
1210  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
1211  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 1005  Line 1261 
1261    
1262  =head3 GetSecondaryFields  =head3 GetSecondaryFields
1263    
1264  C<< my %fieldTuples = $erdb->GetSecondaryFields($entityName); >>      my %fieldTuples = $erdb->GetSecondaryFields($entityName);
1265    
1266  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
1267  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 1046  Line 1302 
1302    
1303  =head3 GetFieldRelationName  =head3 GetFieldRelationName
1304    
1305  C<< my $name = $erdb->GetFieldRelationName($objectName, $fieldName); >>      my $name = $erdb->GetFieldRelationName($objectName, $fieldName);
1306    
1307  Return the name of the relation containing a specified field.  Return the name of the relation containing a specified field.
1308    
# Line 1087  Line 1343 
1343    
1344  =head3 DeleteValue  =head3 DeleteValue
1345    
1346  C<< my $numDeleted = $erdb->DeleteValue($entityName, $id, $fieldName, $fieldValue); >>      my $numDeleted = $erdb->DeleteValue($entityName, $id, $fieldName, $fieldValue);
1347    
1348  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
1349  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 1170  Line 1426 
1426    
1427  =head3 LoadTables  =head3 LoadTables
1428    
1429  C<< my $stats = $erdb->LoadTables($directoryName, $rebuild); >>      my $stats = $erdb->LoadTables($directoryName, $rebuild);
1430    
1431  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
1432  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 1230  Line 1486 
1486    
1487  =head3 GetTableNames  =head3 GetTableNames
1488    
1489  C<< my @names = $erdb->GetTableNames; >>      my @names = $erdb->GetTableNames;
1490    
1491  Return a list of the relations required to implement this database.  Return a list of the relations required to implement this database.
1492    
# Line 1247  Line 1503 
1503    
1504  =head3 GetEntityTypes  =head3 GetEntityTypes
1505    
1506  C<< my @names = $erdb->GetEntityTypes; >>      my @names = $erdb->GetEntityTypes;
1507    
1508  Return a list of the entity type names.  Return a list of the entity type names.
1509    
# Line 1264  Line 1520 
1520    
1521  =head3 GetDataTypes  =head3 GetDataTypes
1522    
1523  C<< my %types = ERDB::GetDataTypes(); >>      my %types = ERDB::GetDataTypes();
1524    
1525  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.
1526  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 1283  Line 1539 
1539    
1540  =head3 IsEntity  =head3 IsEntity
1541    
1542  C<< my $flag = $erdb->IsEntity($entityName); >>      my $flag = $erdb->IsEntity($entityName);
1543    
1544  Return TRUE if the parameter is an entity name, else FALSE.  Return TRUE if the parameter is an entity name, else FALSE.
1545    
# Line 1310  Line 1566 
1566    
1567  =head3 Get  =head3 Get
1568    
1569  C<< my $query = $erdb->Get(\@objectNames, $filterClause, \@params); >>      my $query = $erdb->Get(\@objectNames, $filterClause, \@params);
1570    
1571  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.
1572  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 1318  Line 1574 
1574  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
1575  $genus.  $genus.
1576    
1577  C<< $query = $erdb->Get(['Genome'], "Genome(genus) = ?", [$genus]); >>      $query = $erdb->Get(['Genome'], "Genome(genus) = ?", [$genus]);
1578    
1579  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
1580  parameter representing the parameter value. It would also be possible to code  parameter representing the parameter value. It would also be possible to code
1581    
1582  C<< $query = $erdb->Get(['Genome'], "Genome(genus) = \'$genus\'"); >>      $query = $erdb->Get(['Genome'], "Genome(genus) = \'$genus\'");
1583    
1584  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
1585  characters inside the variable C<$genus>.  characters inside the variable C<$genus>.
# Line 1335  Line 1591 
1591  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
1592  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,
1593    
1594  C<< $query = $erdb->Get(['Genome', 'ComesFrom', 'Source'], "Genome(genus) = ?", [$genus]); >>      $query = $erdb->Get(['Genome', 'ComesFrom', 'Source'], "Genome(genus) = ?", [$genus]);
1595    
1596  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
1597  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 1371  Line 1627 
1627  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
1628  particular genus and sorts them by species name.  particular genus and sorts them by species name.
1629    
1630  C<< "Genome(genus) = ? ORDER BY Genome(species)" >>      "Genome(genus) = ? ORDER BY Genome(species)"
1631    
1632  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
1633  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 1384  Line 1640 
1640  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
1641  a positive number. So, for example  a positive number. So, for example
1642    
1643  C<< "Genome(genus) = ? ORDER BY Genome(species) LIMIT 10" >>      "Genome(genus) = ? ORDER BY Genome(species) LIMIT 10"
1644    
1645  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
1646  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
1647  use  use
1648    
1649  C<< "LIMIT 10" >>      "LIMIT 10"
1650    
1651  =item params  =item params
1652    
# Line 1411  Line 1667 
1667      my ($suffix, $mappedNameListRef, $mappedNameHashRef) =      my ($suffix, $mappedNameListRef, $mappedNameHashRef) =
1668          $self->_SetupSQL($objectNames, $filterClause);          $self->_SetupSQL($objectNames, $filterClause);
1669      # Create the query.      # Create the query.
1670      my $command = "SELECT DISTINCT " . join(".*, ", @{$mappedNameListRef}) .      my $command = "SELECT " . join(".*, ", @{$mappedNameListRef}) .
1671          ".* $suffix";          ".* $suffix";
1672      my $sth = $self->_GetStatementHandle($command, $params);      my $sth = $self->_GetStatementHandle($command, $params);
1673      # 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 1429  Line 1685 
1685    
1686  =head3 Search  =head3 Search
1687    
1688  C<< my $query = $erdb->Search($searchExpression, $idx, \@objectNames, $filterClause, \@params); >>      my $query = $erdb->Search($searchExpression, $idx, \@objectNames, $filterClause, \@params);
1689    
1690  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
1691  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 1512  Line 1768 
1768              $self->_SetupSQL($objectNames, $filterClause, $matchClause);              $self->_SetupSQL($objectNames, $filterClause, $matchClause);
1769          # 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
1770          # the select fields.          # the select fields.
1771          my $command = "SELECT DISTINCT $matchClause, " . join(".*, ", @{$mappedNameListRef}) .          my $command = "SELECT $matchClause, " . join(".*, ", @{$mappedNameListRef}) .
1772              ".* $suffix";              ".* $suffix";
1773          my $sth = $self->_GetStatementHandle($command, \@myParams);          my $sth = $self->_GetStatementHandle($command, \@myParams);
1774          # 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 1526  Line 1782 
1782    
1783  =head3 GetFlat  =head3 GetFlat
1784    
1785  C<< my @list = $erdb->GetFlat(\@objectNames, $filterClause, \@parameterList, $field); >>      my @list = $erdb->GetFlat(\@objectNames, $filterClause, \@parameterList, $field);
1786    
1787  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
1788  returns a single flattened list.  returns a single flattened list.
# Line 1579  Line 1835 
1835    
1836  =head3 SpecialFields  =head3 SpecialFields
1837    
1838  C<< my %specials = $erdb->SpecialFields($entityName); >>      my %specials = $erdb->SpecialFields($entityName);
1839    
1840  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
1841  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 1621  Line 1877 
1877    
1878  =head3 Delete  =head3 Delete
1879    
1880  C<< my $stats = $erdb->Delete($entityName, $objectID, %options); >>      my $stats = $erdb->Delete($entityName, $objectID, %options);
1881    
1882  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
1883  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 1806  Line 2062 
2062    
2063  =head3 Disconnect  =head3 Disconnect
2064    
2065  C<< $erdb->Disconnect($relationshipName, $originEntityName, $originEntityID); >>      $erdb->Disconnect($relationshipName, $originEntityName, $originEntityID);
2066    
2067  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
2068  will delete each relationship instance that connects to the specified entity.  will delete each relationship instance that connects to the specified entity.
# Line 1845  Line 2101 
2101          # Loop through the ends of the relationship.          # Loop through the ends of the relationship.
2102          for my $dir ('from', 'to') {          for my $dir ('from', 'to') {
2103              if ($structure->{$dir} eq $originEntityName) {              if ($structure->{$dir} eq $originEntityName) {
                 # Delete all relationship instances on this side of the entity instance.  
                 Trace("Disconnecting in $dir direction with ID \"$originEntityID\".");  
                 $dbh->SQL("DELETE FROM $relationshipName WHERE ${dir}_link = ?", 0, $originEntityID);  
2104                  $found = 1;                  $found = 1;
2105                    # Here we want to delete all relationship instances on this side of the
2106                    # entity instance.
2107                    Trace("Disconnecting in $dir direction with ID \"$originEntityID\".");
2108                    # We do this delete in batches to keep it from dragging down the
2109                    # server.
2110                    my $limitClause = ($FIG_Config::delete_limit ? "LIMIT $FIG_Config::delete_limit" : "");
2111                    my $done = 0;
2112                    while (! $done) {
2113                        # Do the delete.
2114                        my $rows = $dbh->SQL("DELETE FROM $relationshipName WHERE ${dir}_link = ? $limitClause", 0, $originEntityID);
2115                        # See if we're done. We're done if no rows were found or the delete is unlimited.
2116                        $done = ($rows == 0 || ! $limitClause);
2117                    }
2118              }              }
2119          }          }
2120          # Insure we found the entity on at least one end.          # Insure we found the entity on at least one end.
# Line 1860  Line 2126 
2126    
2127  =head3 DeleteRow  =head3 DeleteRow
2128    
2129  C<< $erdb->DeleteRow($relationshipName, $fromLink, $toLink, \%values); >>      $erdb->DeleteRow($relationshipName, $fromLink, $toLink, \%values);
2130    
2131  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
2132  needed; however, for relationships with intersection data values can be specified  needed; however, for relationships with intersection data values can be specified
# Line 1913  Line 2179 
2179      $dbh->SQL($command, undef, @parms);      $dbh->SQL($command, undef, @parms);
2180  }  }
2181    
2182    =head3 DeleteLike
2183    
2184        my $deleteCount = $erdb->DeleteLike($relName, $filter, \@parms);
2185    
2186    Delete all the relationship rows that satisfy a particular filter condition. Unlike a normal
2187    filter, only fields from the relationship itself can be used.
2188    
2189    =over 4
2190    
2191    =item relName
2192    
2193    Name of the relationship whose records are to be deleted.
2194    
2195    =item filter
2196    
2197    A filter clause (L</Get>-style) for the delete query.
2198    
2199    =item parms
2200    
2201    Reference to a list of parameters for the filter clause.
2202    
2203    =item RETURN
2204    
2205    Returns a count of the number of rows deleted.
2206    
2207    =back
2208    
2209    =cut
2210    
2211    sub DeleteLike {
2212        # Get the parameters.
2213        my ($self, $objectName, $filter, $parms) = @_;
2214        # Declare the return variable.
2215        my $retVal;
2216        # Insure the parms argument is an array reference if the caller left it off.
2217        if (! defined($parms)) {
2218            $parms = [];
2219        }
2220        # Insure we have a relationship. The main reason for this is if we delete an entity
2221        # instance we have to yank out a bunch of other stuff with it.
2222        if ($self->IsEntity($objectName)) {
2223            Confess("Cannot use DeleteLike on $objectName, because it is not a relationship.");
2224        } else {
2225            # Create the SQL command suffix to get the desierd records.
2226            my ($suffix) = $self->_SetupSQL([$objectName], $filter);
2227            # Convert it to a DELETE command.
2228            my $command = "DELETE $suffix";
2229            # Execute the command.
2230            my $dbh = $self->{_dbh};
2231            my $result = $dbh->SQL($command, 0, @{$parms});
2232            # Check the results. Note we convert the "0D0" result to a real zero.
2233            # A failure causes an abnormal termination, so the caller isn't going to
2234            # worry about it.
2235            if (! defined $result) {
2236                Confess("Error deleting from $objectName: " . $dbh->errstr());
2237            } elsif ($result == 0) {
2238                $retVal = 0;
2239            } else {
2240                $retVal = $result;
2241            }
2242        }
2243        # Return the result count.
2244        return $retVal;
2245    }
2246    
2247  =head3 SortNeeded  =head3 SortNeeded
2248    
2249  C<< my $parms = $erdb->SortNeeded($relationName); >>      my $parms = $erdb->SortNeeded($relationName);
2250    
2251  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
2252  relation when creating the load file.  relation when creating the load file.
# Line 2013  Line 2344 
2344    
2345  =head3 GetList  =head3 GetList
2346    
2347  C<< my @dbObjects = $erdb->GetList(\@objectNames, $filterClause, \@params); >>      my @dbObjects = $erdb->GetList(\@objectNames, $filterClause, \@params);
2348    
2349  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
2350  specified filter clause.  specified filter clause.
# Line 2041  Line 2372 
2372  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
2373  particular genus and sorts them by species name.  particular genus and sorts them by species name.
2374    
2375  C<< "Genome(genus) = ? ORDER BY Genome(species)" >>      "Genome(genus) = ? ORDER BY Genome(species)"
2376    
2377  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
2378  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 2053  Line 2384 
2384    
2385  =item RETURN  =item RETURN
2386    
2387  Returns a list of B<DBObject>s that satisfy the query conditions.  Returns a list of B<ERDBObject>s that satisfy the query conditions.
2388    
2389  =back  =back
2390    
# Line 2076  Line 2407 
2407    
2408  =head3 GetCount  =head3 GetCount
2409    
2410  C<< my $count = $erdb->GetCount(\@objectNames, $filter, \@params); >>      my $count = $erdb->GetCount(\@objectNames, $filter, \@params);
2411    
2412  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
2413  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 2169  Line 2500 
2500    
2501  =head3 ComputeObjectSentence  =head3 ComputeObjectSentence
2502    
2503  C<< my $sentence = $erdb->ComputeObjectSentence($objectName); >>      my $sentence = $erdb->ComputeObjectSentence($objectName);
2504    
2505  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.
2506    
# Line 2204  Line 2535 
2535    
2536  =head3 DumpRelations  =head3 DumpRelations
2537    
2538  C<< $erdb->DumpRelations($outputDirectory); >>      $erdb->DumpRelations($outputDirectory);
2539    
2540  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.
2541  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 2246  Line 2577 
2577    
2578  =head3 InsertValue  =head3 InsertValue
2579    
2580  C<< $erdb->InsertValue($entityID, $fieldName, $value); >>      $erdb->InsertValue($entityID, $fieldName, $value);
2581    
2582  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
2583  associated with a secondary relation, since primary values cannot be inserted:  associated with a secondary relation, since primary values cannot be inserted:
# Line 2309  Line 2640 
2640    
2641  =head3 InsertObject  =head3 InsertObject
2642    
2643  C<< $erdb->InsertObject($objectType, \%fieldHash); >>      $erdb->InsertObject($objectType, \%fieldHash);
2644    
2645  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
2646  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 2318  Line 2649 
2649  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
2650  C<ZP_00210270.1> and C<gi|46206278>.  C<ZP_00210270.1> and C<gi|46206278>.
2651    
2652  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']});
2653    
2654  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
2655  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>.
2656    
2657  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'});
2658    
2659  =over 4  =over 4
2660    
# Line 2446  Line 2777 
2777    
2778  =head3 UpdateEntity  =head3 UpdateEntity
2779    
2780  C<< $erdb->UpdateEntity($entityName, $id, \%fields); >>      $erdb->UpdateEntity($entityName, $id, \%fields);
2781    
2782  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
2783  done if the database resides on a database server.  done if the database resides on a database server.
# Line 2504  Line 2835 
2835    
2836  =head3 LoadTable  =head3 LoadTable
2837    
2838  C<< my $results = $erdb->LoadTable($fileName, $relationName, $truncateFlag); >>      my $results = $erdb->LoadTable($fileName, $relationName, %options);
2839    
2840  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
2841  first.  first.
# Line 2519  Line 2850 
2850    
2851  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.
2852    
2853  =item truncateFlag  =item options
2854    
2855  TRUE if the table should be dropped and re-created, else FALSE  A hash of load options.
2856    
2857  =item RETURN  =item RETURN
2858    
# Line 2529  Line 2860 
2860    
2861  =back  =back
2862    
2863    The permissible options are as follows.
2864    
2865    =over 4
2866    
2867    =item truncate
2868    
2869    If TRUE, then the table will be erased before loading.
2870    
2871    =item mode
2872    
2873    Mode in which the load should operate, either C<low_priority> or C<concurrent>.
2874    This option is only applicable to a MySQL database.
2875    
2876    =item partial
2877    
2878    If TRUE, then it is assumed that this is a partial load, and the table will not
2879    be analyzed and compacted at the end.
2880    
2881    =back
2882    
2883  =cut  =cut
2884  sub LoadTable {  sub LoadTable {
2885      # Get the parameters.      # Get the parameters.
2886      my ($self, $fileName, $relationName, $truncateFlag) = @_;      my ($self, $fileName, $relationName, %options) = @_;
2887      # Create the statistical return object.      # Create the statistical return object.
2888      my $retVal = _GetLoadStats();      my $retVal = _GetLoadStats();
2889      # Trace the fact of the load.      # Trace the fact of the load.
# Line 2544  Line 2895 
2895      # Get the relation data.      # Get the relation data.
2896      my $relation = $self->_FindRelation($relationName);      my $relation = $self->_FindRelation($relationName);
2897      # Check the truncation flag.      # Check the truncation flag.
2898      if ($truncateFlag) {      if ($options{truncate}) {
2899          Trace("Creating table $relationName") if T(2);          Trace("Creating table $relationName") if T(2);
2900          # 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,
2901          # 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
2902          # leave extra room. We postulate a minimum row count of 1000 to          # leave extra room. We postulate a minimum row count of 1000 to
2903          # prevent problems with incoming empty load files.          # prevent problems with incoming empty load files.
2904          my $rowSize = $self->EstimateRowSize($relationName);          my $rowSize = $self->EstimateRowSize($relationName);
2905          my $estimate = FIG::max($fileSize * 1.5 / $rowSize, 1000);          my $estimate = $fileSize * 8 / $rowSize;
2906            if ($estimate < 1000) {
2907                $estimate = 1000;
2908            }
2909          # Re-create the table without its index.          # Re-create the table without its index.
2910          $self->CreateTable($relationName, 0, $estimate);          $self->CreateTable($relationName, 0, $estimate);
2911          # If this is a pre-index DBMS, create the index here.          # If this is a pre-index DBMS, create the index here.
# Line 2567  Line 2921 
2921      # Load the table.      # Load the table.
2922      my $rv;      my $rv;
2923      eval {      eval {
2924          $rv = $dbh->load_table(file => $fileName, tbl => $relationName);          $rv = $dbh->load_table(file => $fileName, tbl => $relationName, style => $options{mode});
2925      };      };
2926      if (!defined $rv) {      if (!defined $rv) {
2927          $retVal->AddMessage($@) if ($@);          $retVal->AddMessage($@) if ($@);
# Line 2578  Line 2932 
2932          $retVal->Add("tables");          $retVal->Add("tables");
2933          my $size = -s $fileName;          my $size = -s $fileName;
2934          Trace("$size bytes loaded into $relationName.") if T(2);          Trace("$size bytes loaded into $relationName.") if T(2);
2935            $retVal->Add("bytes", $size);
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 2600  Line 2955 
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;
# Line 2609  Line 2966 
2966    
2967  =head3 CreateSearchIndex  =head3 CreateSearchIndex
2968    
2969  C<< $erdb->CreateSearchIndex($objectName); >>      $erdb->CreateSearchIndex($objectName);
2970    
2971  Check for a full-text search index on the specified entity or relationship object, and  Check for a full-text search index on the specified entity or relationship object, and
2972  if one is required, rebuild it.  if one is required, rebuild it.
# Line 2646  Line 3003 
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 2674  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 2757  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 2773  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 2793  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 2848  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 2892  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 2906  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 2986  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 3021  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 3059  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 3088  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 3137  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 3192  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 3225  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 3267  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 3306  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 3336  Line 3693 
3693      return $retVal;      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  =head3 BeginTran
3744    
3745  C<< $erdb->BeginTran(); >>      $erdb->BeginTran();
3746    
3747  Start a database transaction.  Start a database transaction.
3748    
# Line 3352  Line 3756 
3756    
3757  =head3 CommitTran  =head3 CommitTran
3758    
3759  C<< $erdb->CommitTran(); >>      $erdb->CommitTran();
3760    
3761  Commit an active database transaction.  Commit an active database transaction.
3762    
# Line 3365  Line 3769 
3769    
3770  =head3 RollbackTran  =head3 RollbackTran
3771    
3772  C<< $erdb->RollbackTran(); >>      $erdb->RollbackTran();
3773    
3774  Roll back an active database transaction.  Roll back an active database transaction.
3775    
# Line 3376  Line 3780 
3780      $self->{_dbh}->roll_tran();      $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.
3857        return $retVal;
3858    }
3859    
3860    
3861  =head2 Data Mining Methods  =head2 Data Mining Methods
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 3442  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 3500  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 3532  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 3571  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 3581  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 3600  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 3894  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 4131  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 4143  Line 4695 
4695    
4696  =head3 _LoadMetaData  =head3 _LoadMetaData
4697    
4698  C<< my $metadata = ERDB::_LoadMetaData($filename); >>      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
# Line 4501  Line 5053 
5053    
5054  =head3 _ProcessIndexes  =head3 _ProcessIndexes
5055    
5056  C<< ERDB::_ProcessIndexes($indexList, $relation); >>      ERDB::_ProcessIndexes($indexList, $relation);
5057    
5058  Build the data structures for the specified indexes in the specified relation.  Build the data structures for the specified indexes in the specified relation.
5059    
# Line 4910  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 4955  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

Legend:
Removed from v.1.87  
changed lines
  Added in v.1.97

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3