[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.92, Mon Jun 11 18:51:23 2007 UTC revision 1.96, Tue Feb 5 04:52:24 2008 UTC
# Line 11  Line 11 
11      use Time::HiRes qw(gettimeofday);      use Time::HiRes qw(gettimeofday);
12      use Digest::MD5 qw(md5_base64);      use Digest::MD5 qw(md5_base64);
13      use CGI;      use CGI;
14        use WikiTools;
15    
16  =head1 Entity-Relationship Database Package  =head1 Entity-Relationship Database Package
17    
# Line 413  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 433  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 447  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 488  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 644  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 657  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  =head3 CreatePPO
764    
765  C<< ERDB::CreatePPO($erdbXMLFile, $ppoXMLFile); >>      ERDB::CreatePPO($erdbXMLFile, $ppoXMLFile);
766    
767  Create a PPO XML file from an ERDB data definition XML file. At the  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  current time, the PPO XML file can be used to create a database with
# Line 810  Line 913 
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 880  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 904  Line 1007 
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 960  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 974  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 1029  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 1069  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 1102  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 1158  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 1199  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 1240  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 1323  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 1383  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 1400  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 1417  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 1436  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 1463  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 1471  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 1488  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 1524  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 1537  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 1564  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 1582  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 1665  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 1679  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 1732  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 1774  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 1959  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 1998  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.  
                 Trace("Disconnecting in $dir direction with ID \"$originEntityID\".");  
                 $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 2013  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 2068  Line 2182 
2182    
2183  =head3 DeleteLike  =head3 DeleteLike
2184    
2185  C<< my $deleteCount = $erdb->DeleteLike($relName, $filter, \@parms); >>      my $deleteCount = $erdb->DeleteLike($relName, $filter, \@parms);
2186    
2187  Delete all the relationship rows that satisfy a particular filter condition. Unlike a normal  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.  filter, only fields from the relationship itself can be used.
# Line 2133  Line 2247 
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 2231  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 2259  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 2294  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 2387  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 2422  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 2464  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 2527  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 2536  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 2664  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 2722  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 2737  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 2747  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 2762  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 = $fileSize * 1.5 / $rowSize;          my $estimate = $fileSize * 8 / $rowSize;
2907          if ($estimate < 1000) {          if ($estimate < 1000) {
2908              $estimate = 1000;              $estimate = 1000;
2909          }          }
# Line 2788  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 2799  Line 2933 
2933          $retVal->Add("tables");          $retVal->Add("tables");
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            $retVal->Add("bytes", $size);
2937          # If we're rebuilding, we need to create the table indexes.          # If we're rebuilding, we need to create the table indexes.
2938          if ($truncateFlag) {          if ($options{truncate}) {
2939              # Indexes are created here for PostGres. For PostGres, indexes are              # Indexes are created here for PostGres. For PostGres, indexes are
2940              # best built at the end. For MySQL, the reverse is true.              # best built at the end. For MySQL, the reverse is true.
2941              if (! $dbh->{_preIndex}) {              if (! $dbh->{_preIndex}) {
# Line 2821  Line 2956 
2956          }          }
2957      }      }
2958      # Analyze the table to improve performance.      # Analyze the table to improve performance.
2959        if (! $options{partial}) {
2960      Trace("Analyzing and compacting $relationName.") if T(3);      Trace("Analyzing and compacting $relationName.") if T(3);
2961      $dbh->vacuum_it($relationName);      $dbh->vacuum_it($relationName);
2962        }
2963      Trace("$relationName load completed.") if T(3);      Trace("$relationName load completed.") if T(3);
2964      # Return the statistics.      # Return the statistics.
2965      return $retVal;      return $retVal;
# Line 2830  Line 2967 
2967    
2968  =head3 CreateSearchIndex  =head3 CreateSearchIndex
2969    
2970  C<< $erdb->CreateSearchIndex($objectName); >>      $erdb->CreateSearchIndex($objectName);
2971    
2972  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
2973  if one is required, rebuild it.  if one is required, rebuild it.
# Line 2867  Line 3004 
3004    
3005  =head3 DropRelation  =head3 DropRelation
3006    
3007  C<< $erdb->DropRelation($relationName); >>      $erdb->DropRelation($relationName);
3008    
3009  Physically drop a relation from the database.  Physically drop a relation from the database.
3010    
# Line 2895  Line 3032 
3032    
3033  =head3 MatchSqlPattern  =head3 MatchSqlPattern
3034    
3035  C<< my $matched = ERDB::MatchSqlPattern($value, $pattern); >>      my $matched = ERDB::MatchSqlPattern($value, $pattern);
3036    
3037  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
3038  pattern has two wild card characters: C<%> that matches multiple characters,  pattern has two wild card characters: C<%> that matches multiple characters,
# Line 2978  Line 3115 
3115    
3116  =head3 GetEntity  =head3 GetEntity
3117    
3118  C<< my $entityObject = $erdb->GetEntity($entityType, $ID); >>      my $entityObject = $erdb->GetEntity($entityType, $ID);
3119    
3120  Return an object describing the entity instance with a specified ID.  Return an object describing the entity instance with a specified ID.
3121    
# Line 3014  Line 3151 
3151    
3152  =head3 GetChoices  =head3 GetChoices
3153    
3154  C<< my @values = $erdb->GetChoices($entityName, $fieldName); >>      my @values = $erdb->GetChoices($entityName, $fieldName);
3155    
3156  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
3157  specified entity.  specified entity.
# Line 3069  Line 3206 
3206    
3207  =head3 GetEntityValues  =head3 GetEntityValues
3208    
3209  C<< my @values = $erdb->GetEntityValues($entityType, $ID, \@fields); >>      my @values = $erdb->GetEntityValues($entityType, $ID, \@fields);
3210    
3211  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
3212  does not exist, an empty list is returned.  does not exist, an empty list is returned.
# Line 3113  Line 3250 
3250    
3251  =head3 GetAll  =head3 GetAll
3252    
3253  C<< my @list = $erdb->GetAll(\@objectNames, $filterClause, \@parameters, \@fields, $count); >>      my @list = $erdb->GetAll(\@objectNames, $filterClause, \@parameters, \@fields, $count);
3254    
3255  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
3256  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 3129  Line 3266 
3266  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
3267  feature ID followed by all of its essentiality determinations.  feature ID followed by all of its essentiality determinations.
3268    
3269  C<< @query = $erdb->Get(['ContainsFeature', 'Feature'], "ContainsFeature(from-link) = ?", [$ssCellID], ['Feature(id)', 'Feature(essential)']); >>      @query = $erdb->Get(['ContainsFeature', 'Feature'], "ContainsFeature(from-link) = ?", [$ssCellID], ['Feature(id)', 'Feature(essential)']);
3270    
3271  =over 4  =over 4
3272    
# Line 3207  Line 3344 
3344    
3345  =head3 Exists  =head3 Exists
3346    
3347  C<< my $found = $sprout->Exists($entityName, $entityID); >>      my $found = $sprout->Exists($entityName, $entityID);
3348    
3349  Return TRUE if an entity exists, else FALSE.  Return TRUE if an entity exists, else FALSE.
3350    
# Line 3242  Line 3379 
3379    
3380  =head3 EstimateRowSize  =head3 EstimateRowSize
3381    
3382  C<< my $rowSize = $erdb->EstimateRowSize($relName); >>      my $rowSize = $erdb->EstimateRowSize($relName);
3383    
3384  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
3385  up the average length for each data type.  up the average length for each data type.
# Line 3280  Line 3417 
3417    
3418  =head3 GetFieldTable  =head3 GetFieldTable
3419    
3420  C<< my $fieldHash = $self->GetFieldTable($objectnName); >>      my $fieldHash = $self->GetFieldTable($objectnName);
3421    
3422  Get the field structure for a specified entity or relationship.  Get the field structure for a specified entity or relationship.
3423    
# Line 3309  Line 3446 
3446    
3447  =head3 SplitKeywords  =head3 SplitKeywords
3448    
3449  C<< my @keywords = ERDB::SplitKeywords($keywordString); >>      my @keywords = ERDB::SplitKeywords($keywordString);
3450    
3451  This method returns a list of the positive keywords in the specified  This method returns a list of the positive keywords in the specified
3452  keyword string. All of the operators will have been stripped off,  keyword string. All of the operators will have been stripped off,
# Line 3358  Line 3495 
3495    
3496  =head3 ValidateFieldName  =head3 ValidateFieldName
3497    
3498  C<< my $okFlag = ERDB::ValidateFieldName($fieldName); >>      my $okFlag = ERDB::ValidateFieldName($fieldName);
3499    
3500  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
3501  be hyphenated words subject to certain restrictions.  be hyphenated words subject to certain restrictions.
# Line 3413  Line 3550 
3550    
3551  =head3 ReadMetaXML  =head3 ReadMetaXML
3552    
3553  C<< my $rawMetaData = ERDB::ReadDBD($fileName); >>      my $rawMetaData = ERDB::ReadDBD($fileName);
3554    
3555  This method reads a raw database definition XML file and returns it.  This method reads a raw database definition XML file and returns it.
3556  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 3446  Line 3583 
3583    
3584  =head3 GetEntityFieldHash  =head3 GetEntityFieldHash
3585    
3586  C<< my $fieldHashRef = ERDB::GetEntityFieldHash($structure, $entityName); >>      my $fieldHashRef = ERDB::GetEntityFieldHash($structure, $entityName);
3587    
3588  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.
3589  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 3488  Line 3625 
3625    
3626  =head3 WriteMetaXML  =head3 WriteMetaXML
3627    
3628  C<< ERDB::WriteMetaXML($structure, $fileName); >>      ERDB::WriteMetaXML($structure, $fileName);
3629    
3630  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
3631  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 3527  Line 3664 
3664  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
3665  example, C<[b]Feature[/b]> displays the string C<Feature> in boldface.  example, C<[b]Feature[/b]> displays the string C<Feature> in boldface.
3666    
3667  C<< my $realHtml = ERDB::HTMLNote($dataString); >>      my $realHtml = ERDB::HTMLNote($dataString);
3668    
3669  =over 4  =over 4
3670    
# Line 3557  Line 3694 
3694      return $retVal;      return $retVal;
3695  }  }
3696    
3697    =head3 WikiNote
3698    
3699    Convert a note or comment to Wiki text by replacing some bulletin-board codes with HTML. The codes
3700    supported are C<[b]> for B<bold>, C<[i]> for I<italics>, and C<[p]> for a new paragraph.
3701    Except for C<[p]>, all the codes are closed by slash-codes. So, for
3702    example, C<[b]Feature[/b]> displays the string C<Feature> in boldface.
3703    
3704        my $wikiText = ERDB::WikiNote($dataString);
3705    
3706    =over 4
3707    
3708    =item dataString
3709    
3710    String to convert to Wiki text.
3711    
3712    =item RETURN
3713    
3714    An Wiki text string derived from the input string.
3715    
3716    =back
3717    
3718    =cut
3719    
3720    sub WikiNote {
3721        # Get the parameter.
3722        my ($dataString) = @_;
3723        # HTML-escape the text.
3724        my $retVal = CGI::escapeHTML($dataString);
3725        # Substitute the bulletin board codes.
3726        my $italic = WikiTools::ItalicCode();
3727        $retVal =~ s/\[\/?i\]/$italic/g;
3728        my $bold = WikiTools::BoldCode();
3729        $retVal =~ s/\[\/?b\]/$bold/g;
3730        # Paragraph breaks are the same no matter which Wiki you're using.
3731        $retVal =~ s!\[p\]!\n\n!g;
3732        # Now we do the links, which are complicated by the need to know two
3733        # things: the target URL and the text.
3734        while ($retVal =~ /\[link\s+([^\]]+)\]([^\[]+)\[\/link\]/g) {
3735            # Replace the matched string with the Wiki markup for links. Note that
3736            # $-[0] is the starting position of the match for the entire expression,
3737            # and $+[0] is past the ending position.
3738            substr $retVal, $-[0], $+[0] - $-[0], WikiTools::LinkMarkup($1, $2);
3739        }
3740        # Return the result.
3741        return $retVal;
3742    }
3743    
3744  =head3 BeginTran  =head3 BeginTran
3745    
3746  C<< $erdb->BeginTran(); >>      $erdb->BeginTran();
3747    
3748  Start a database transaction.  Start a database transaction.
3749    
# Line 3573  Line 3757 
3757    
3758  =head3 CommitTran  =head3 CommitTran
3759    
3760  C<< $erdb->CommitTran(); >>      $erdb->CommitTran();
3761    
3762  Commit an active database transaction.  Commit an active database transaction.
3763    
# Line 3586  Line 3770 
3770    
3771  =head3 RollbackTran  =head3 RollbackTran
3772    
3773  C<< $erdb->RollbackTran(); >>      $erdb->RollbackTran();
3774    
3775  Roll back an active database transaction.  Roll back an active database transaction.
3776    
# Line 3599  Line 3783 
3783    
3784  =head3 UpdateField  =head3 UpdateField
3785    
3786  C<< my $count = $erdb->UpdateField($objectNames, $fieldName, $oldValue, $newValue, $filter, $parms); >>      my $count = $erdb->UpdateField($objectNames, $fieldName, $oldValue, $newValue, $filter, $parms);
3787    
3788  Update all occurrences of a specific field value to a new value. The number of rows changed will be  Update all occurrences of a specific field value to a new value. The number of rows changed will be
3789  returned.  returned.
# Line 3679  Line 3863 
3863    
3864  =head3 GetUsefulCrossValues  =head3 GetUsefulCrossValues
3865    
3866  C<< my @attrNames = $sprout->GetUsefulCrossValues($sourceEntity, $relationship); >>      my @attrNames = $sprout->GetUsefulCrossValues($sourceEntity, $relationship);
3867    
3868  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
3869  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 3740  Line 3924 
3924    
3925  =head3 FindColumn  =head3 FindColumn
3926    
3927  C<< my $colIndex = ERDB::FindColumn($headerLine, $columnIdentifier); >>      my $colIndex = ERDB::FindColumn($headerLine, $columnIdentifier);
3928    
3929  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
3930  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 3798  Line 3982 
3982    
3983  =head3 ParseColumns  =head3 ParseColumns
3984    
3985  C<< my @columns = ERDB::ParseColumns($line); >>      my @columns = ERDB::ParseColumns($line);
3986    
3987  Convert the specified data line to a list of columns.  Convert the specified data line to a list of columns.
3988    
# Line 3832  Line 4016 
4016    
4017  =head3 _CreatePPOIndex  =head3 _CreatePPOIndex
4018    
4019  C<< my $index = ERDB::_CreatePPOIndex($indexObject); >>      my $index = ERDB::_CreatePPOIndex($indexObject);
4020    
4021  Convert the XML for an ERDB index to the XML structure for a PPO  Convert the XML for an ERDB index to the XML structure for a PPO
4022  index.  index.
4023    
4024  =over 4  =over 4
4025    
4026    =item indexObject
4027    
4028  ERDB XML structure for an index.  ERDB XML structure for an index.
4029    
4030  =item RETURN  =item RETURN
# Line 3863  Line 4049 
4049    
4050  =head3 _CreatePPOField  =head3 _CreatePPOField
4051    
4052  C<< my $fieldXML = ERDB::_CreatePPOField($fieldName, $fieldObject); >>      my $fieldXML = ERDB::_CreatePPOField($fieldName, $fieldObject);
4053    
4054  Convert the ERDB XML structure for a field to a PPO scalar XML structure.  Convert the ERDB XML structure for a field to a PPO scalar XML structure.
4055    
# Line 3900  Line 4086 
4086    
4087  =head3 CleanKeywords  =head3 CleanKeywords
4088    
4089  C<< my $cleanedString = $erdb->CleanKeywords($searchExpression); >>      my $cleanedString = $erdb->CleanKeywords($searchExpression);
4090    
4091  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
4092  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 3937  Line 4123 
4123    
4124  =head3 GetSourceObject  =head3 GetSourceObject
4125    
4126  C<< my $source = $erdb->GetSourceObject($entityName); >>      my $source = $erdb->GetSourceObject($entityName);
4127    
4128  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
4129  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 3947  Line 4133 
4133    
4134  =head3 _RelationMap  =head3 _RelationMap
4135    
4136  C<< my @relationMap = _RelationMap($mappedNameHashRef, $mappedNameListRef); >>      my @relationMap = _RelationMap($mappedNameHashRef, $mappedNameListRef);
4137    
4138  Create the relation map for an SQL query. The relation map is used by B<ERDBObject>  Create the relation map for an SQL query. The relation map is used by B<ERDBObject>
4139  to determine how to interpret the results of the query.  to determine how to interpret the results of the query.
# Line 4260  Line 4446 
4446  sub _GetStatementHandle {  sub _GetStatementHandle {
4447      # Get the parameters.      # Get the parameters.
4448      my ($self, $command, $params) = @_;      my ($self, $command, $params) = @_;
4449        Confess("Invalid parameter list.") if (! defined($params) || ref($params) ne 'ARRAY');
4450      # Trace the query.      # Trace the query.
4451      Trace("SQL query: $command") if T(SQL => 3);      Trace("SQL query: $command") if T(SQL => 3);
4452      Trace("PARMS: '" . (join "', '", @{$params}) . "'") if (T(SQL => 4) && (@{$params} > 0));      Trace("PARMS: '" . (join "', '", @{$params}) . "'") if (T(SQL => 4) && (@{$params} > 0));
# Line 4497  Line 4684 
4684      # be a null string.      # be a null string.
4685      if ($fileName ne "") {      if ($fileName ne "") {
4686          # Load the relation from the file.          # Load the relation from the file.
4687          $retVal = $self->LoadTable($fileName, $relationName, $rebuild);          $retVal = $self->LoadTable($fileName, $relationName, truncate => $rebuild);
4688      } elsif ($rebuild) {      } elsif ($rebuild) {
4689          # 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.
4690          $self->CreateTable($relationName, 1);          $self->CreateTable($relationName, 1);
# Line 4509  Line 4696 
4696    
4697  =head3 _LoadMetaData  =head3 _LoadMetaData
4698    
4699  C<< my $metadata = ERDB::_LoadMetaData($filename); >>      my $metadata = ERDB::_LoadMetaData($filename);
4700    
4701  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.
4702  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 4867  Line 5054 
5054    
5055  =head3 _ProcessIndexes  =head3 _ProcessIndexes
5056    
5057  C<< ERDB::_ProcessIndexes($indexList, $relation); >>      ERDB::_ProcessIndexes($indexList, $relation);
5058    
5059  Build the data structures for the specified indexes in the specified relation.  Build the data structures for the specified indexes in the specified relation.
5060    
# Line 5276  Line 5463 
5463      # Get the parameters.      # Get the parameters.
5464      my ($relationshipName, $relationshipStructure) = @_;      my ($relationshipName, $relationshipStructure) = @_;
5465      # Format the relationship sentence.      # Format the relationship sentence.
5466      my $result = "$relationshipStructure->{from} <b>$relationshipName</b> $relationshipStructure->{to}";      my $result = "$relationshipStructure->{from} $relationshipName $relationshipStructure->{to}";
5467      # Compute the arity.      # Compute the arity.
5468      my $arityCode = $relationshipStructure->{arity};      my $arityCode = $relationshipStructure->{arity};
5469      my $arity = $ArityTable{$arityCode};      my $arity = $ArityTable{$arityCode};
# Line 5321  Line 5508 
5508      return $result;      return $result;
5509  }  }
5510    
5511    =head3 _WikiRelationTable
5512    
5513    Generate the Wiki text for a particular relation. The relation's data will be formatted as a
5514    table with three columns-- the field name, the field type, and the field description.
5515    
5516    This is a static method.
5517    
5518    =over 4
5519    
5520    =item relationName
5521    
5522    Name of the relation being formatted.
5523    
5524    =item relationData
5525    
5526    Hash containing the relation's fields and indexes.
5527    
5528    =item RETURN
5529    
5530    Returns a Wiki string that can be used to display the relation name and all of its fields.
5531    
5532    =back
5533    
5534    =cut
5535    
5536    sub _WikiRelationTable {
5537        # Get the parameters.
5538        my ($relationName, $relationData) = @_;
5539        # We'll create a list of lists in here, then call WikiTools::Table to
5540        # convert it into a table.
5541        my @rows = ();
5542        # Push in the header row.
5543        push @rows, [qw(Field Type Description)];
5544        # Loop through the fields.
5545        for my $field (@{$relationData->{Fields}}) {
5546            # Create this field's row. We always have a name and type.
5547            my @row = ($field->{name}, $field->{type});
5548            # If we have a description, add it as the third column.
5549            if (exists $field->{Notes}) {
5550                push @row, WikiNote($field->{Notes}->{content});
5551            }
5552            # Push this row onto the table list.
5553            push @rows, \@row;
5554        }
5555        # Store the rows as a Wiki table.
5556        my $retVal = WikiTools::Table(@rows);
5557        # Now we show the relation's indexes. These are formatted as another
5558        # table.
5559        @rows = ();
5560        # Push in the header row.
5561        push @rows, [qw(Index Unique Fields Notes)];
5562        # Get the index hash.
5563        my $indexTable = $relationData->{Indexes};
5564        # Loop through the indexes. For an entity, there is always at least one index.
5565        # For a relationship, there are at least two. The upshot is we don't need to
5566        # worry about accidentally generating a frivolous table here.
5567        for my $indexName (sort keys %$indexTable) {
5568            my $indexData = $indexTable->{$indexName};
5569            # Determine whether or not the index is unique.
5570            my $unique = ((exists $indexData->{Unique} && $indexData->{Unique} eq "true") ?
5571                          "yes" : "");
5572            # Get the field list.
5573            my $fields = join(', ', @{$indexData->{IndexFields}});
5574            # Get the note text.
5575            my $description = "";
5576            if (my $note = $indexData->{Notes}) {
5577                $description = WikiNote($note->{content});
5578            }
5579            # Format this row.
5580            my @row = ($indexName, $unique, $fields, $description);
5581            push @rows, \@row;
5582        }
5583        # Add the index list to the result.
5584        $retVal .= "\n\n" . WikiTools::Table(@rows);
5585    }
5586    
5587    
5588  =head3 _ShowRelationTable  =head3 _ShowRelationTable
5589    
5590  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.92  
changed lines
  Added in v.1.96

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3