[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.90, Fri Apr 27 22:19:49 2007 UTC revision 1.95, Wed Jan 23 00:56:31 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;  ## HACK
15    
16  =head1 Entity-Relationship Database Package  =head1 Entity-Relationship Database Package
17    
# Line 372  Line 373 
373                   'medium-string' =>                   'medium-string' =>
374                               { sqlType => 'VARCHAR(160)',       maxLen => 160,          avgLen =>  40, sort => "",                               { sqlType => 'VARCHAR(160)',       maxLen => 160,          avgLen =>  40, sort => "",
375                                 indexMod =>   0, notes => "character string, 0 to 160 characters"},                                 indexMod =>   0, notes => "character string, 0 to 160 characters"},
376                     'long-string' =>
377                                 { sqlType => 'VARCHAR(500)',       maxLen => 500,          avglen => 255, sort => "",
378                                   indexMod =>   0, notes => "character string, 0 to 500 characters"},
379                  );                  );
380    
381  # Table translating arities into natural language.  # Table translating arities into natural language.
# Line 410  Line 414 
414    
415  =head3 new  =head3 new
416    
417  C<< my $database = ERDB->new($dbh, $metaFileName); >>      my $database = ERDB->new($dbh, $metaFileName);
418    
419  Create a new ERDB object.  Create a new ERDB object.
420    
# Line 430  Line 434 
434    
435  sub new {  sub new {
436      # Get the parameters.      # Get the parameters.
437      my ($class, $dbh, $metaFileName, $options) = @_;      my ($class, $dbh, $metaFileName, %options) = @_;
438      # Load the meta-data.      # Load the meta-data.
439      my $metaData = _LoadMetaData($metaFileName);      my $metaData = _LoadMetaData($metaFileName);
440      # Create the object.      # Create the object.
# Line 444  Line 448 
448    
449  =head3 ShowMetaData  =head3 ShowMetaData
450    
451  C<< $erdb->ShowMetaData($fileName); >>      $erdb->ShowMetaData($fileName);
452    
453  This method outputs a description of the database. This description can be used to help users create  This method outputs a description of the database. This description can be used to help users create
454  the data to be loaded into the relations.  the data to be loaded into the relations.
# Line 485  Line 489 
489    
490  =head3 DisplayMetaData  =head3 DisplayMetaData
491    
492  C<< my $html = $erdb->DisplayMetaData(); >>      my $html = $erdb->DisplayMetaData();
493    
494  Return an HTML description of the database. This description can be used to help users create  Return an HTML description of the database. This description can be used to help users create
495  the data to be loaded into the relations and form queries. The output is raw includable HTML  the data to be loaded into the relations and form queries. The output is raw includable HTML
# Line 641  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 654  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 807  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 877  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 901  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 957  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 971  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 1014  Line 1121 
1121              my $oldString = $fieldList->[$i];              my $oldString = $fieldList->[$i];
1122              if (length($oldString) > $maxLen) {              if (length($oldString) > $maxLen) {
1123                  # Here it's too big, so we truncate it.                  # Here it's too big, so we truncate it.
1124                  Trace("Truncating field $i in relation $relName to $maxLen characters from \"$oldString\".") if T(1);                  Trace("Truncating field $i ($fieldTypes->[$i]->{name}) in relation $relName to $maxLen characters from \"$oldString\".") if T(1);
1125                  $fieldList->[$i] = substr $oldString, 0, $maxLen;                  $fieldList->[$i] = substr $oldString, 0, $maxLen;
1126                  $retVal++;                  $retVal++;
1127              }              }
# Line 1026  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 1066  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 1099  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 1155  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 1196  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 1237  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 1320  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 1380  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 1397  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 1414  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 1433  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 1460  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 1468  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 1485  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 1521  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 1534  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 1561  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 1579  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 1662  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 1676  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 1729  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 1771  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 1956  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 1995  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 2010  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 2063  Line 2180 
2180      $dbh->SQL($command, undef, @parms);      $dbh->SQL($command, undef, @parms);
2181  }  }
2182    
2183    =head3 DeleteLike
2184    
2185        my $deleteCount = $erdb->DeleteLike($relName, $filter, \@parms);
2186    
2187    Delete all the relationship rows that satisfy a particular filter condition. Unlike a normal
2188    filter, only fields from the relationship itself can be used.
2189    
2190    =over 4
2191    
2192    =item relName
2193    
2194    Name of the relationship whose records are to be deleted.
2195    
2196    =item filter
2197    
2198    A filter clause (L</Get>-style) for the delete query.
2199    
2200    =item parms
2201    
2202    Reference to a list of parameters for the filter clause.
2203    
2204    =item RETURN
2205    
2206    Returns a count of the number of rows deleted.
2207    
2208    =back
2209    
2210    =cut
2211    
2212    sub DeleteLike {
2213        # Get the parameters.
2214        my ($self, $objectName, $filter, $parms) = @_;
2215        # Declare the return variable.
2216        my $retVal;
2217        # Insure the parms argument is an array reference if the caller left it off.
2218        if (! defined($parms)) {
2219            $parms = [];
2220        }
2221        # Insure we have a relationship. The main reason for this is if we delete an entity
2222        # instance we have to yank out a bunch of other stuff with it.
2223        if ($self->IsEntity($objectName)) {
2224            Confess("Cannot use DeleteLike on $objectName, because it is not a relationship.");
2225        } else {
2226            # Create the SQL command suffix to get the desierd records.
2227            my ($suffix) = $self->_SetupSQL([$objectName], $filter);
2228            # Convert it to a DELETE command.
2229            my $command = "DELETE $suffix";
2230            # Execute the command.
2231            my $dbh = $self->{_dbh};
2232            my $result = $dbh->SQL($command, 0, @{$parms});
2233            # Check the results. Note we convert the "0D0" result to a real zero.
2234            # A failure causes an abnormal termination, so the caller isn't going to
2235            # worry about it.
2236            if (! defined $result) {
2237                Confess("Error deleting from $objectName: " . $dbh->errstr());
2238            } elsif ($result == 0) {
2239                $retVal = 0;
2240            } else {
2241                $retVal = $result;
2242            }
2243        }
2244        # Return the result count.
2245        return $retVal;
2246    }
2247    
2248  =head3 SortNeeded  =head3 SortNeeded
2249    
2250  C<< my $parms = $erdb->SortNeeded($relationName); >>      my $parms = $erdb->SortNeeded($relationName);
2251    
2252  Return the pipe command for the sort that should be applied to the specified  Return the pipe command for the sort that should be applied to the specified
2253  relation when creating the load file.  relation when creating the load file.
# Line 2163  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 2191  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 2226  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 2319  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 2354  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 2396  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 2459  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 2468  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 2596  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 2654  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 2669  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 2679  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 2694  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 2720  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 2732  Line 2934 
2934          my $size = -s $fileName;          my $size = -s $fileName;
2935          Trace("$size bytes loaded into $relationName.") if T(2);          Trace("$size bytes loaded into $relationName.") if T(2);
2936          # If we're rebuilding, we need to create the table indexes.          # If we're rebuilding, we need to create the table indexes.
2937          if ($truncateFlag) {          if ($options{truncate}) {
2938              # Indexes are created here for PostGres. For PostGres, indexes are              # Indexes are created here for PostGres. For PostGres, indexes are
2939              # best built at the end. For MySQL, the reverse is true.              # best built at the end. For MySQL, the reverse is true.
2940              if (! $dbh->{_preIndex}) {              if (! $dbh->{_preIndex}) {
# Line 2753  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 2762  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 2799  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 2827  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 2910  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 2946  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 3001  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 3045  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 3059  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 3139  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 3174  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 3212  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 3241  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 3290  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 3345  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 3378  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 3420  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 3459  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 3489  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 3505  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 3518  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 3531  Line 3782 
3782    
3783  =head3 UpdateField  =head3 UpdateField
3784    
3785  C<< my $count = $erdb->UpdateField($objectNames, $fieldName, $oldValue, $newValue, $filter, $parms); >>      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  Update all occurrences of a specific field value to a new value. The number of rows changed will be
3788  returned.  returned.
# Line 3611  Line 3862 
3862    
3863  =head3 GetUsefulCrossValues  =head3 GetUsefulCrossValues
3864    
3865  C<< my @attrNames = $sprout->GetUsefulCrossValues($sourceEntity, $relationship); >>      my @attrNames = $sprout->GetUsefulCrossValues($sourceEntity, $relationship);
3866    
3867  Return a list of the useful attributes that would be returned by a B<Cross> call  Return a list of the useful attributes that would be returned by a B<Cross> call
3868  from an entity of the source entity type through the specified relationship. This  from an entity of the source entity type through the specified relationship. This
# Line 3672  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 3730  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 3764  Line 4015 
4015    
4016  =head3 _CreatePPOIndex  =head3 _CreatePPOIndex
4017    
4018  C<< my $index = ERDB::_CreatePPOIndex($indexObject); >>      my $index = ERDB::_CreatePPOIndex($indexObject);
4019    
4020  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
4021  index.  index.
4022    
4023  =over 4  =over 4
4024    
4025    =item indexObject
4026    
4027  ERDB XML structure for an index.  ERDB XML structure for an index.
4028    
4029  =item RETURN  =item RETURN
# Line 3795  Line 4048 
4048    
4049  =head3 _CreatePPOField  =head3 _CreatePPOField
4050    
4051  C<< my $fieldXML = ERDB::_CreatePPOField($fieldName, $fieldObject); >>      my $fieldXML = ERDB::_CreatePPOField($fieldName, $fieldObject);
4052    
4053  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.
4054    
# Line 3832  Line 4085 
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 3869  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 3879  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<ERDBObject>  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.
# Line 4192  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 4429  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 4441  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 4799  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 5208  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 5253  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.90  
changed lines
  Added in v.1.95

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3