[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.103, Tue Sep 16 18:57:59 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 389  Line 390 
390                                    Entities => 'Entity',                                    Entities => 'Entity',
391                                    Fields => 'Field',                                    Fields => 'Field',
392                                    Indexes => 'Index',                                    Indexes => 'Index',
393                                    IndexFields => 'IndexField'                                    IndexFields => 'IndexField',
394                                      Issues => 'Issue',
395                                      Shapes => 'Shape'
396                                  },                                  },
397                    KeyAttr =>    { Relationship => 'name',                    KeyAttr =>    { Relationship => 'name',
398                                    Entity => 'name',                                    Entity => 'name',
399                                    Field => 'name'                                    Field => 'name',
400                                      Shape => 'name'
401                                  },                                  },
402                    SuppressEmpty => 1,                    SuppressEmpty => 1,
403                   );                   );
404    
405  my %XmlInOpts  = (  my %XmlInOpts  = (
406                    ForceArray => ['Field', 'Index', 'IndexField', 'Relationship', 'Entity'],                    ForceArray => [qw(Field Index IndexField Relationship Entity Shape)],
407                    ForceContent => 1,                    ForceContent => 1,
408                    NormalizeSpace => 2,                    NormalizeSpace => 2,
409                   );                   );
# Line 408  Line 412 
412                    XMLDecl => 1,                    XMLDecl => 1,
413                   );                   );
414    
   
415  =head2 Public Methods  =head2 Public Methods
416    
417  =head3 new  =head3 new
418    
419  C<< my $database = ERDB->new($dbh, $metaFileName); >>      my $database = ERDB->new($dbh, $metaFileName);
420    
421  Create a new ERDB object.  Create a new ERDB object.
422    
# Line 433  Line 436 
436    
437  sub new {  sub new {
438      # Get the parameters.      # Get the parameters.
439      my ($class, $dbh, $metaFileName, $options) = @_;      my ($class, $dbh, $metaFileName, %options) = @_;
440      # Load the meta-data.      # Load the meta-data.
441      my $metaData = _LoadMetaData($metaFileName);      my $metaData = _LoadMetaData($metaFileName);
442      # Create the object.      # Create the object.
# Line 447  Line 450 
450    
451  =head3 ShowMetaData  =head3 ShowMetaData
452    
453  C<< $erdb->ShowMetaData($fileName); >>      $erdb->ShowMetaData($fileName);
454    
455  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
456  the data to be loaded into the relations.  the data to be loaded into the relations.
# Line 488  Line 491 
491    
492  =head3 DisplayMetaData  =head3 DisplayMetaData
493    
494  C<< my $html = $erdb->DisplayMetaData(); >>      my $html = $erdb->DisplayMetaData();
495    
496  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
497  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 647 
647    
648  =head3 DumpMetaData  =head3 DumpMetaData
649    
650  C<< $erdb->DumpMetaData(); >>      $erdb->DumpMetaData();
651    
652  Return a dump of the metadata structure.  Return a dump of the metadata structure.
653    
# Line 657  Line 660 
660      return Data::Dumper::Dumper($self->{_metaData});      return Data::Dumper::Dumper($self->{_metaData});
661  }  }
662    
663    =head3 GenerateWikiData
664    
665        my @wikiLines = $erdb->GenerateWikiData();
666    
667    Build a description of the database for the wiki. The database will be
668    organized into a single page, with sections for each entity and relationship.
669    The return value is a list of text lines.
670    
671    =cut
672    
673    sub GenerateWikiData {
674        # Get the parameters.
675        my ($self) = @_;
676        # We'll build the wiki text in here.
677        my @retVal = ();
678        # Get the metadata object.
679        my $metadata = $self->{_metaData};
680        # Get the title string. This will become the page name.
681        my $title = $metadata->{Title}->{content};
682        # Get the entity and relationship lists.
683        my $entityList = $metadata->{Entities};
684        my $relationshipList = $metadata->{Relationships};
685        my $shapeList = $metadata->{Shapes};
686        # Start with the introductory text.
687        push @retVal, WikiTools::Heading(2, "Introduction");
688        if (my $notes = $metadata->{Notes}) {
689            push @retVal, WikiNote($notes->{content});
690        }
691        # Generate issue list.
692        if (my $issues = $metadata->{Issues}) {
693            push @retVal, WikiTools::Heading(3, 'Issues');
694            push @retVal, WikiTools::List(map { $_->{content} } @{$issues});
695        }
696        # Start the entity section.
697        push @retVal, WikiTools::Heading(2, "Entities");
698        # Loop through the entities. Note that unlike the situation with HTML, we
699        # don't need to generate the table of contents manually, just the data
700        # itself.
701        for my $key (sort keys %$entityList) {
702            # Create a header for this entity.
703            push @retVal, "", WikiTools::Heading(3, $key);
704            # Get the entity data.
705            my $entityData = $entityList->{$key};
706            # Plant the notes here, if there are any.
707            push @retVal, _ObjectNotes($entityData);
708            # Now we list the entity's relationships (if any). First, we build a list
709            # of the relationships relevant to this entity.
710            my @rels = ();
711            for my $rel (sort keys %$relationshipList) {
712                my $relStructure = $relationshipList->{$rel};
713                if ($relStructure->{from} eq $key || $relStructure->{to} eq $key) {
714                    # Get the relationship sentence.
715                    my $relSentence = _ComputeRelationshipSentence($rel, $relStructure);
716                    # Linkify it.
717                    my $linkedRel = WikiTools::LinkMarkup("#$rel", $rel);
718                    $relSentence =~ s/$rel/$linkedRel/;
719                    push @rels, $relSentence;
720                }
721            }
722            # Add the relationships as a Wiki list.
723            push @retVal, WikiTools::List(@rels);
724            # Get the entity's relations.
725            my $relationList = $entityData->{Relations};
726            # Loop through the relations, displaying them.
727            for my $relation (sort keys %{$relationList}) {
728                my $wikiString = _WikiRelationTable($relation, $relationList->{$relation});
729                push @retVal, $wikiString;
730            }
731        }
732        # Now the entities are documented. Next we do the relationships.
733        push @retVal, WikiTools::Heading(2, "Relationships");
734        for my $key (sort keys %$relationshipList) {
735            my $relationshipData = $relationshipList->{$key};
736            # Create the relationship heading.
737            push @retVal, WikiTools::Heading(3, $key);
738            # Describe the relationship arity. Note there's a bit of trickiness involving recursive
739            # many-to-many relationships. In a normal many-to-many we use two sentences to describe
740            # the arity (one for each direction). This is a bad idea for a recursive relationship,
741            # since both sentences will say the same thing.
742            my $arity = $relationshipData->{arity};
743            my $fromEntity = $relationshipData->{from};
744            my $toEntity = $relationshipData->{to};
745            my @listElements = ();
746            my $boldCode = WikiTools::BoldCode();
747            if ($arity eq "11") {
748                push @listElements, "Each $boldCode$fromEntity$boldCode relates to at most one $boldCode$toEntity$boldCode.";
749            } else {
750                push @listElements, "Each $boldCode$fromEntity$boldCode relates to multiple $boldCode${toEntity}s$boldCode.";
751                if ($arity eq "MM" && $fromEntity ne $toEntity) {
752                    push @listElements, "Each $boldCode$toEntity$boldCode relates to multiple $boldCode${fromEntity}s$boldCode.";
753                }
754            }
755            push @retVal, WikiTools::List(@listElements);
756            # Plant the notes here, if there are any.
757            push @retVal, _ObjectNotes($relationshipData);
758            # Finally, the relationship table.
759            my $wikiString = _WikiRelationTable($key, $relationshipData->{Relations}->{$key});
760            push @retVal, $wikiString;
761        }
762        # Now loop through the miscellaneous shapes.
763        if ($shapeList) {
764            push @retVal, WikiTools::Heading(2, "Miscellaneous");
765            for my $shape (sort keys %$shapeList) {
766                push @retVal, WikiTools::Heading(3, $shape);
767                my $shapeData = $shapeList->{$shape};
768                push @retVal, _ObjectNotes($shapeData);
769            }
770        }
771        # All done. Return the lines.
772        return @retVal;
773    }
774    
775    
776  =head3 CreatePPO  =head3 CreatePPO
777    
778  C<< ERDB::CreatePPO($erdbXMLFile, $ppoXMLFile); >>      ERDB::CreatePPO($erdbXMLFile, $ppoXMLFile);
779    
780  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
781  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 926 
926    
927  =head3 FindIndexForEntity  =head3 FindIndexForEntity
928    
929  C<< my $indexFound = ERDB::FindIndexForEntity($xml, $entityName, $attributeName); >>      my $indexFound = ERDB::FindIndexForEntity($xml, $entityName, $attributeName);
930    
931  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
932  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 996 
996    
997  =head3 CreateTables  =head3 CreateTables
998    
999  C<< $erdb->CreateTables(); >>      $erdb->CreateTables();
1000    
1001  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
1002  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 1020 
1020    
1021  =head3 CreateTable  =head3 CreateTable
1022    
1023  C<< $erdb->CreateTable($tableName, $indexFlag, $estimatedRows); >>      $erdb->CreateTable($tableName, $indexFlag, $estimatedRows);
1024    
1025  Create the table for a relation and optionally create its indexes.  Create the table for a relation and optionally create its indexes.
1026    
# Line 946  Line 1062 
1062          # Push the result into the field list.          # Push the result into the field list.
1063          push @fieldList, $fieldString;          push @fieldList, $fieldString;
1064      }      }
     # If this is a root table, add the "new_record" flag. It defaults to 0, so  
     if ($rootFlag) {  
         push @fieldList, "new_record $TypeTable{boolean}->{sqlType} NOT NULL DEFAULT 0";  
     }  
1065      # Convert the field list into a comma-delimited string.      # Convert the field list into a comma-delimited string.
1066      my $fieldThing = join(', ', @fieldList);      my $fieldThing = join(', ', @fieldList);
1067      # Insure the table is not already there.      # Insure the table is not already there.
# Line 960  Line 1072 
1072      my $estimation = undef;      my $estimation = undef;
1073      if ($estimatedRows) {      if ($estimatedRows) {
1074          $estimation = [$self->EstimateRowSize($relationName), $estimatedRows];          $estimation = [$self->EstimateRowSize($relationName), $estimatedRows];
1075            Trace("$estimation->[1] rows of $estimation->[0] bytes each.") if T(3);
1076      }      }
1077      # Create the table.      # Create the table.
1078      Trace("Creating table $relationName: $fieldThing") if T(2);      Trace("Creating table $relationName: $fieldThing") if T(2);
# Line 974  Line 1087 
1087    
1088  =head3 VerifyFields  =head3 VerifyFields
1089    
1090  C<< my $count = $erdb->VerifyFields($relName, \@fieldList); >>      my $count = $erdb->VerifyFields($relName, \@fieldList);
1091    
1092  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
1093  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 1142 
1142    
1143  =head3 DigestFields  =head3 DigestFields
1144    
1145  C<< $erdb->DigestFields($relName, $fieldList); >>      $erdb->DigestFields($relName, $fieldList);
1146    
1147  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
1148  specified relation.  specified relation.
# Line 1069  Line 1182 
1182    
1183  =head3 DigestKey  =head3 DigestKey
1184    
1185  C<< my $digested = $erdb->DigestKey($keyValue); >>      my $digested = $erdb->DigestKey($keyValue);
1186    
1187  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
1188  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 1215 
1215    
1216  =head3 CreateIndex  =head3 CreateIndex
1217    
1218  C<< $erdb->CreateIndex($relationName); >>      $erdb->CreateIndex($relationName);
1219    
1220  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
1221  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 1271 
1271    
1272  =head3 GetSecondaryFields  =head3 GetSecondaryFields
1273    
1274  C<< my %fieldTuples = $erdb->GetSecondaryFields($entityName); >>      my %fieldTuples = $erdb->GetSecondaryFields($entityName);
1275    
1276  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
1277  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 1312 
1312    
1313  =head3 GetFieldRelationName  =head3 GetFieldRelationName
1314    
1315  C<< my $name = $erdb->GetFieldRelationName($objectName, $fieldName); >>      my $name = $erdb->GetFieldRelationName($objectName, $fieldName);
1316    
1317  Return the name of the relation containing a specified field.  Return the name of the relation containing a specified field.
1318    
# Line 1240  Line 1353 
1353    
1354  =head3 DeleteValue  =head3 DeleteValue
1355    
1356  C<< my $numDeleted = $erdb->DeleteValue($entityName, $id, $fieldName, $fieldValue); >>      my $numDeleted = $erdb->DeleteValue($entityName, $id, $fieldName, $fieldValue);
1357    
1358  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
1359  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 1436 
1436    
1437  =head3 LoadTables  =head3 LoadTables
1438    
1439  C<< my $stats = $erdb->LoadTables($directoryName, $rebuild); >>      my $stats = $erdb->LoadTables($directoryName, $rebuild);
1440    
1441  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
1442  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 1496 
1496    
1497  =head3 GetTableNames  =head3 GetTableNames
1498    
1499  C<< my @names = $erdb->GetTableNames; >>      my @names = $erdb->GetTableNames;
1500    
1501  Return a list of the relations required to implement this database.  Return a list of the relations required to implement this database.
1502    
# Line 1400  Line 1513 
1513    
1514  =head3 GetEntityTypes  =head3 GetEntityTypes
1515    
1516  C<< my @names = $erdb->GetEntityTypes; >>      my @names = $erdb->GetEntityTypes;
1517    
1518  Return a list of the entity type names.  Return a list of the entity type names.
1519    
# Line 1415  Line 1528 
1528      return sort keys %{$entityList};      return sort keys %{$entityList};
1529  }  }
1530    
1531    
1532    =head3 GetConnectingRelationships
1533    
1534        my @list = $erdb->GetConnectingRelationships($entityName);
1535    
1536    Return a list of the relationships connected to the specified entity.
1537    
1538    =over 4
1539    
1540    =item entityName
1541    
1542    Entity whose connected relationships are desired.
1543    
1544    =item RETURN
1545    
1546    Returns a list of the relationships that originate from the entity.
1547    If the entity is on the from end, it will return the relationship
1548    name. If the entity is on the to end it will return the converse of
1549    the relationship name.
1550    
1551    =back
1552    
1553    =cut
1554    
1555    sub GetConnectingRelationships {
1556        # Get the parameters.
1557        my ($self, $entityName) = @_;
1558        # Declare the return variable.
1559        my @retVal;
1560        # Get the relationship list.
1561        my $relationships = $self->{_metaData}->{Relationships};
1562        # Find the entity.
1563        my $entity = $self->{_metaData}->{Entities}->{$entityName};
1564        # Only proceed if the entity exists.
1565        if (! defined $entity) {
1566            Trace("Entity $entityName not found.") if T(3);
1567        } else {
1568            # Loop through the relationships.
1569            my @rels = keys %$relationships;
1570            Trace(scalar(@rels) . " relationships found in connection search.") if T(3);
1571            for my $relationshipName (@rels) {
1572                my $relationship = $relationships->{$relationshipName};
1573                if ($relationship->{from} eq $entityName) {
1574                    # Here we have a forward relationship.
1575                    push @retVal, $relationshipName;
1576                } elsif ($relationship->{to} eq $entityName) {
1577                    # Here we have a backward relationship. In this case, the
1578                    # converse relationship name is preferred if it exists.
1579                    my $converse = $relationship->{converse} || $relationshipName;
1580                    push @retVal, $converse;
1581                }
1582            }
1583        }
1584        # Return the result.
1585        return @retVal;
1586    }
1587    
1588    
1589  =head3 GetDataTypes  =head3 GetDataTypes
1590    
1591  C<< my %types = ERDB::GetDataTypes(); >>      my %types = ERDB::GetDataTypes();
1592    
1593  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.
1594  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 1607 
1607    
1608  =head3 IsEntity  =head3 IsEntity
1609    
1610  C<< my $flag = $erdb->IsEntity($entityName); >>      my $flag = $erdb->IsEntity($entityName);
1611    
1612  Return TRUE if the parameter is an entity name, else FALSE.  Return TRUE if the parameter is an entity name, else FALSE.
1613    
# Line 1463  Line 1634 
1634    
1635  =head3 Get  =head3 Get
1636    
1637  C<< my $query = $erdb->Get(\@objectNames, $filterClause, \@params); >>      my $query = $erdb->Get(\@objectNames, $filterClause, \@params);
1638    
1639  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.
1640  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 1642 
1642  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
1643  $genus.  $genus.
1644    
1645  C<< $query = $erdb->Get(['Genome'], "Genome(genus) = ?", [$genus]); >>      $query = $erdb->Get(['Genome'], "Genome(genus) = ?", [$genus]);
1646    
1647  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
1648  parameter representing the parameter value. It would also be possible to code  parameter representing the parameter value. It would also be possible to code
1649    
1650  C<< $query = $erdb->Get(['Genome'], "Genome(genus) = \'$genus\'"); >>      $query = $erdb->Get(['Genome'], "Genome(genus) = \'$genus\'");
1651    
1652  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
1653  characters inside the variable C<$genus>.  characters inside the variable C<$genus>.
# Line 1488  Line 1659 
1659  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
1660  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,
1661    
1662  C<< $query = $erdb->Get(['Genome', 'ComesFrom', 'Source'], "Genome(genus) = ?", [$genus]); >>      $query = $erdb->Get(['Genome', 'ComesFrom', 'Source'], "Genome(genus) = ?", [$genus]);
1663    
1664  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
1665  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 1695 
1695  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
1696  particular genus and sorts them by species name.  particular genus and sorts them by species name.
1697    
1698  C<< "Genome(genus) = ? ORDER BY Genome(species)" >>      "Genome(genus) = ? ORDER BY Genome(species)"
1699    
1700  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
1701  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 1708 
1708  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
1709  a positive number. So, for example  a positive number. So, for example
1710    
1711  C<< "Genome(genus) = ? ORDER BY Genome(species) LIMIT 10" >>      "Genome(genus) = ? ORDER BY Genome(species) LIMIT 10"
1712    
1713  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
1714  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
1715  use  use
1716    
1717  C<< "LIMIT 10" >>      "LIMIT 10"
1718    
1719  =item params  =item params
1720    
# Line 1564  Line 1735 
1735      my ($suffix, $mappedNameListRef, $mappedNameHashRef) =      my ($suffix, $mappedNameListRef, $mappedNameHashRef) =
1736          $self->_SetupSQL($objectNames, $filterClause);          $self->_SetupSQL($objectNames, $filterClause);
1737      # Create the query.      # Create the query.
1738      my $command = "SELECT DISTINCT " . join(".*, ", @{$mappedNameListRef}) .      my $command = "SELECT " . join(".*, ", @{$mappedNameListRef}) .
1739          ".* $suffix";          ".* $suffix";
1740      my $sth = $self->_GetStatementHandle($command, $params);      my $sth = $self->_GetStatementHandle($command, $params);
1741      # 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 1753 
1753    
1754  =head3 Search  =head3 Search
1755    
1756  C<< my $query = $erdb->Search($searchExpression, $idx, \@objectNames, $filterClause, \@params); >>      my $query = $erdb->Search($searchExpression, $idx, \@objectNames, $filterClause, \@params);
1757    
1758  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
1759  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 1836 
1836              $self->_SetupSQL($objectNames, $filterClause, $matchClause);              $self->_SetupSQL($objectNames, $filterClause, $matchClause);
1837          # 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
1838          # the select fields.          # the select fields.
1839          my $command = "SELECT DISTINCT $matchClause, " . join(".*, ", @{$mappedNameListRef}) .          my $command = "SELECT $matchClause, " . join(".*, ", @{$mappedNameListRef}) .
1840              ".* $suffix";              ".* $suffix";
1841          my $sth = $self->_GetStatementHandle($command, \@myParams);          my $sth = $self->_GetStatementHandle($command, \@myParams);
1842          # 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 1850 
1850    
1851  =head3 GetFlat  =head3 GetFlat
1852    
1853  C<< my @list = $erdb->GetFlat(\@objectNames, $filterClause, \@parameterList, $field); >>      my @list = $erdb->GetFlat(\@objectNames, $filterClause, \@parameterList, $field);
1854    
1855  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
1856  returns a single flattened list.  returns a single flattened list.
# Line 1732  Line 1903 
1903    
1904  =head3 SpecialFields  =head3 SpecialFields
1905    
1906  C<< my %specials = $erdb->SpecialFields($entityName); >>      my %specials = $erdb->SpecialFields($entityName);
1907    
1908  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
1909  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 1945 
1945    
1946  =head3 Delete  =head3 Delete
1947    
1948  C<< my $stats = $erdb->Delete($entityName, $objectID, %options); >>      my $stats = $erdb->Delete($entityName, $objectID, %options);
1949    
1950  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
1951  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 2130 
2130    
2131  =head3 Disconnect  =head3 Disconnect
2132    
2133  C<< $erdb->Disconnect($relationshipName, $originEntityName, $originEntityID); >>      $erdb->Disconnect($relationshipName, $originEntityName, $originEntityID);
2134    
2135  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
2136  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 2169 
2169          # Loop through the ends of the relationship.          # Loop through the ends of the relationship.
2170          for my $dir ('from', 'to') {          for my $dir ('from', 'to') {
2171              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);  
2172                  $found = 1;                  $found = 1;
2173                    # Here we want to delete all relationship instances on this side of the
2174                    # entity instance.
2175                    Trace("Disconnecting in $dir direction with ID \"$originEntityID\".");
2176                    # We do this delete in batches to keep it from dragging down the
2177                    # server.
2178                    my $limitClause = ($FIG_Config::delete_limit ? "LIMIT $FIG_Config::delete_limit" : "");
2179                    my $done = 0;
2180                    while (! $done) {
2181                        # Do the delete.
2182                        my $rows = $dbh->SQL("DELETE FROM $relationshipName WHERE ${dir}_link = ? $limitClause", 0, $originEntityID);
2183                        # See if we're done. We're done if no rows were found or the delete is unlimited.
2184                        $done = ($rows == 0 || ! $limitClause);
2185                    }
2186              }              }
2187          }          }
2188          # Insure we found the entity on at least one end.          # Insure we found the entity on at least one end.
# Line 2013  Line 2194 
2194    
2195  =head3 DeleteRow  =head3 DeleteRow
2196    
2197  C<< $erdb->DeleteRow($relationshipName, $fromLink, $toLink, \%values); >>      $erdb->DeleteRow($relationshipName, $fromLink, $toLink, \%values);
2198    
2199  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
2200  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 2249 
2249    
2250  =head3 DeleteLike  =head3 DeleteLike
2251    
2252  C<< my $deleteCount = $erdb->DeleteLike($relName, $filter, \@parms); >>      my $deleteCount = $erdb->DeleteLike($relName, $filter, \@parms);
2253    
2254  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
2255  filter, only fields from the relationship itself can be used.  filter, only fields from the relationship itself can be used.
# Line 2133  Line 2314 
2314    
2315  =head3 SortNeeded  =head3 SortNeeded
2316    
2317  C<< my $parms = $erdb->SortNeeded($relationName); >>      my $parms = $erdb->SortNeeded($relationName);
2318    
2319  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
2320  relation when creating the load file.  relation when creating the load file.
# Line 2189  Line 2370 
2370      }      }
2371      # Now we parse the key names into sort parameters. First, we prime the return      # Now we parse the key names into sort parameters. First, we prime the return
2372      # string.      # string.
2373      my $retVal = "sort -t\"\t\" ";      my $retVal = "sort -S 1G -T\"$FIG_Config::temp\" -t\"\t\" ";
2374      # Get the relation's field list.      # Get the relation's field list.
2375      my @fields = @{$relationData->{Fields}};      my @fields = @{$relationData->{Fields}};
2376      # Loop through the keys.      # Loop through the keys.
# Line 2219  Line 2400 
2400                  # will stop the inner loop. Note that the field number is                  # will stop the inner loop. Note that the field number is
2401                  # 1-based in the sort command, so we have to increment the                  # 1-based in the sort command, so we have to increment the
2402                  # index.                  # index.
2403                  $fieldSpec = ($i + 1) . $modifier;                  my $realI = $i + 1;
2404                    $fieldSpec = "$realI,$realI$modifier";
2405              }              }
2406          }          }
2407          # Add this field to the sort command.          # Add this field to the sort command.
# Line 2231  Line 2413 
2413    
2414  =head3 GetList  =head3 GetList
2415    
2416  C<< my @dbObjects = $erdb->GetList(\@objectNames, $filterClause, \@params); >>      my @dbObjects = $erdb->GetList(\@objectNames, $filterClause, \@params);
2417    
2418  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
2419  specified filter clause.  specified filter clause.
# Line 2259  Line 2441 
2441  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
2442  particular genus and sorts them by species name.  particular genus and sorts them by species name.
2443    
2444  C<< "Genome(genus) = ? ORDER BY Genome(species)" >>      "Genome(genus) = ? ORDER BY Genome(species)"
2445    
2446  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
2447  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 2476 
2476    
2477  =head3 GetCount  =head3 GetCount
2478    
2479  C<< my $count = $erdb->GetCount(\@objectNames, $filter, \@params); >>      my $count = $erdb->GetCount(\@objectNames, $filter, \@params);
2480    
2481  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
2482  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 2569 
2569    
2570  =head3 ComputeObjectSentence  =head3 ComputeObjectSentence
2571    
2572  C<< my $sentence = $erdb->ComputeObjectSentence($objectName); >>      my $sentence = $erdb->ComputeObjectSentence($objectName);
2573    
2574  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.
2575    
# Line 2422  Line 2604 
2604    
2605  =head3 DumpRelations  =head3 DumpRelations
2606    
2607  C<< $erdb->DumpRelations($outputDirectory); >>      $erdb->DumpRelations($outputDirectory);
2608    
2609  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.
2610  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 2646 
2646    
2647  =head3 InsertValue  =head3 InsertValue
2648    
2649  C<< $erdb->InsertValue($entityID, $fieldName, $value); >>      $erdb->InsertValue($entityID, $fieldName, $value);
2650    
2651  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
2652  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 2709 
2709    
2710  =head3 InsertObject  =head3 InsertObject
2711    
2712  C<< $erdb->InsertObject($objectType, \%fieldHash); >>      $erdb->InsertObject($objectType, \%fieldHash);
2713    
2714  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
2715  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 2718 
2718  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
2719  C<ZP_00210270.1> and C<gi|46206278>.  C<ZP_00210270.1> and C<gi|46206278>.
2720    
2721  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']});
2722    
2723  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
2724  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>.
2725    
2726  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'});
2727    
2728  =over 4  =over 4
2729    
# Line 2610  Line 2792 
2792                  push @missing, $fieldName;                  push @missing, $fieldName;
2793              }              }
2794          }          }
         # If we are the primary relation, add the new-record flag.  
         if ($relationName eq $newObjectType) {  
             push @valueList, 1;  
             push @fieldNameList, "new_record";  
         }  
2795          # Only proceed if there are no missing fields.          # Only proceed if there are no missing fields.
2796          if (@missing > 0) {          if (@missing > 0) {
2797              Trace("Relation $relationName for $newObjectType skipped due to missing fields: " .              Trace("Relation $relationName for $newObjectType skipped due to missing fields: " .
# Line 2664  Line 2841 
2841    
2842  =head3 UpdateEntity  =head3 UpdateEntity
2843    
2844  C<< $erdb->UpdateEntity($entityName, $id, \%fields); >>      $erdb->UpdateEntity($entityName, $id, \%fields);
2845    
2846  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
2847  done if the database resides on a database server.  done if the database resides on a database server.
# Line 2722  Line 2899 
2899    
2900  =head3 LoadTable  =head3 LoadTable
2901    
2902  C<< my $results = $erdb->LoadTable($fileName, $relationName, $truncateFlag); >>      my $results = $erdb->LoadTable($fileName, $relationName, %options);
2903    
2904  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
2905  first.  first.
# Line 2737  Line 2914 
2914    
2915  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.
2916    
2917  =item truncateFlag  =item options
2918    
2919  TRUE if the table should be dropped and re-created, else FALSE  A hash of load options.
2920    
2921  =item RETURN  =item RETURN
2922    
# Line 2747  Line 2924 
2924    
2925  =back  =back
2926    
2927    The permissible options are as follows.
2928    
2929    =over 4
2930    
2931    =item truncate
2932    
2933    If TRUE, then the table will be erased before loading.
2934    
2935    =item mode
2936    
2937    Mode in which the load should operate, either C<low_priority> or C<concurrent>.
2938    This option is only applicable to a MySQL database.
2939    
2940    =item partial
2941    
2942    If TRUE, then it is assumed that this is a partial load, and the table will not
2943    be analyzed and compacted at the end.
2944    
2945    =back
2946    
2947  =cut  =cut
2948  sub LoadTable {  sub LoadTable {
2949      # Get the parameters.      # Get the parameters.
2950      my ($self, $fileName, $relationName, $truncateFlag) = @_;      my ($self, $fileName, $relationName, %options) = @_;
2951      # Create the statistical return object.      # Create the statistical return object.
2952      my $retVal = _GetLoadStats();      my $retVal = _GetLoadStats();
2953      # Trace the fact of the load.      # Trace the fact of the load.
# Line 2762  Line 2959 
2959      # Get the relation data.      # Get the relation data.
2960      my $relation = $self->_FindRelation($relationName);      my $relation = $self->_FindRelation($relationName);
2961      # Check the truncation flag.      # Check the truncation flag.
2962      if ($truncateFlag) {      if ($options{truncate}) {
2963          Trace("Creating table $relationName") if T(2);          Trace("Creating table $relationName") if T(2);
2964          # 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,
2965          # 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
2966          # leave extra room. We postulate a minimum row count of 1000 to          # leave extra room. We postulate a minimum row count of 1000 to
2967          # prevent problems with incoming empty load files.          # prevent problems with incoming empty load files.
2968          my $rowSize = $self->EstimateRowSize($relationName);          my $rowSize = $self->EstimateRowSize($relationName);
2969          my $estimate = $fileSize * 1.5 / $rowSize;          my $estimate = $fileSize * 8 / $rowSize;
2970          if ($estimate < 1000) {          if ($estimate < 1000) {
2971              $estimate = 1000;              $estimate = 1000;
2972          }          }
# Line 2788  Line 2985 
2985      # Load the table.      # Load the table.
2986      my $rv;      my $rv;
2987      eval {      eval {
2988          $rv = $dbh->load_table(file => $fileName, tbl => $relationName);          $rv = $dbh->load_table(file => $fileName, tbl => $relationName, style => $options{mode});
2989      };      };
2990      if (!defined $rv) {      if (!defined $rv) {
2991          $retVal->AddMessage($@) if ($@);          $retVal->AddMessage($@) if ($@);
# Line 2799  Line 2996 
2996          $retVal->Add("tables");          $retVal->Add("tables");
2997          my $size = -s $fileName;          my $size = -s $fileName;
2998          Trace("$size bytes loaded into $relationName.") if T(2);          Trace("$size bytes loaded into $relationName.") if T(2);
2999            $retVal->Add("bytes", $size);
3000          # If we're rebuilding, we need to create the table indexes.          # If we're rebuilding, we need to create the table indexes.
3001          if ($truncateFlag) {          if ($options{truncate}) {
3002              # Indexes are created here for PostGres. For PostGres, indexes are              # Indexes are created here for PostGres. For PostGres, indexes are
3003              # best built at the end. For MySQL, the reverse is true.              # best built at the end. For MySQL, the reverse is true.
3004              if (! $dbh->{_preIndex}) {              if (! $dbh->{_preIndex}) {
# Line 2821  Line 3019 
3019          }          }
3020      }      }
3021      # Analyze the table to improve performance.      # Analyze the table to improve performance.
3022        if (! $options{partial}) {
3023      Trace("Analyzing and compacting $relationName.") if T(3);      Trace("Analyzing and compacting $relationName.") if T(3);
3024      $dbh->vacuum_it($relationName);          $self->Analyze($relationName);
3025        }
3026      Trace("$relationName load completed.") if T(3);      Trace("$relationName load completed.") if T(3);
3027      # Return the statistics.      # Return the statistics.
3028      return $retVal;      return $retVal;
3029  }  }
3030    
3031    =head3 Analyze
3032    
3033        $erdb->Analyze($tableName);
3034    
3035    Analyze and compact a table in the database. This is useful after a load
3036    to improve the performance of the indexes.
3037    
3038    =over 4
3039    
3040    =item tableName
3041    
3042    Name of the table to be analyzed and compacted.
3043    
3044    =back
3045    
3046    =cut
3047    
3048    sub Analyze {
3049        # Get the parameters.
3050        my ($self, $tableName) = @_;
3051        # Analyze the table.
3052        $self->{_dbh}->vacuum_it($tableName);
3053    }
3054    
3055    =head3 TruncateTable
3056    
3057        $erdb->TruncateTable($table);
3058    
3059    Delete all rows from a table quickly. This uses the built-in SQL
3060    C<TRUNCATE> statement, which effectively drops and re-creates a table
3061    with all its settings intact.
3062    
3063    =over 4
3064    
3065    =item table
3066    
3067    Name of the table to be cleared.
3068    
3069    =back
3070    
3071    =cut
3072    
3073    sub TruncateTable {
3074        # Get the parameters.
3075        my ($self, $table) = @_;
3076        # Get the database handle.
3077        my $dbh = $self->{_dbh};
3078        # Execute a truncation comment.
3079        $dbh->SQL("TRUNCATE TABLE $table");
3080    }
3081    
3082    
3083  =head3 CreateSearchIndex  =head3 CreateSearchIndex
3084    
3085  C<< $erdb->CreateSearchIndex($objectName); >>      $erdb->CreateSearchIndex($objectName);
3086    
3087  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
3088  if one is required, rebuild it.  if one is required, rebuild it.
# Line 2867  Line 3119 
3119    
3120  =head3 DropRelation  =head3 DropRelation
3121    
3122  C<< $erdb->DropRelation($relationName); >>      $erdb->DropRelation($relationName);
3123    
3124  Physically drop a relation from the database.  Physically drop a relation from the database.
3125    
# Line 2895  Line 3147 
3147    
3148  =head3 MatchSqlPattern  =head3 MatchSqlPattern
3149    
3150  C<< my $matched = ERDB::MatchSqlPattern($value, $pattern); >>      my $matched = ERDB::MatchSqlPattern($value, $pattern);
3151    
3152  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
3153  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 3230 
3230    
3231  =head3 GetEntity  =head3 GetEntity
3232    
3233  C<< my $entityObject = $erdb->GetEntity($entityType, $ID); >>      my $entityObject = $erdb->GetEntity($entityType, $ID);
3234    
3235  Return an object describing the entity instance with a specified ID.  Return an object describing the entity instance with a specified ID.
3236    
# Line 3008  Line 3260 
3260      my $query = $self->Get([$entityType], "$entityType(id) = ?", [$ID]);      my $query = $self->Get([$entityType], "$entityType(id) = ?", [$ID]);
3261      # Get the first (and only) object.      # Get the first (and only) object.
3262      my $retVal = $query->Fetch();      my $retVal = $query->Fetch();
3263        if (T(3)) {
3264            if ($retVal) {
3265                Trace("Entity $entityType \"$ID\" found.");
3266            } else {
3267                Trace("Entity $entityType \"$ID\" not found.");
3268            }
3269        }
3270      # Return the result.      # Return the result.
3271      return $retVal;      return $retVal;
3272  }  }
3273    
3274  =head3 GetChoices  =head3 GetChoices
3275    
3276  C<< my @values = $erdb->GetChoices($entityName, $fieldName); >>      my @values = $erdb->GetChoices($entityName, $fieldName);
3277    
3278  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
3279  specified entity.  specified entity.
# Line 3069  Line 3328 
3328    
3329  =head3 GetEntityValues  =head3 GetEntityValues
3330    
3331  C<< my @values = $erdb->GetEntityValues($entityType, $ID, \@fields); >>      my @values = $erdb->GetEntityValues($entityType, $ID, \@fields);
3332    
3333  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
3334  does not exist, an empty list is returned.  does not exist, an empty list is returned.
# Line 3113  Line 3372 
3372    
3373  =head3 GetAll  =head3 GetAll
3374    
3375  C<< my @list = $erdb->GetAll(\@objectNames, $filterClause, \@parameters, \@fields, $count); >>      my @list = $erdb->GetAll(\@objectNames, $filterClause, \@parameters, \@fields, $count);
3376    
3377  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
3378  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 3388 
3388  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
3389  feature ID followed by all of its essentiality determinations.  feature ID followed by all of its essentiality determinations.
3390    
3391  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)']);
3392    
3393  =over 4  =over 4
3394    
# Line 3200  Line 3459 
3459          push @retVal, \@rowData;          push @retVal, \@rowData;
3460          $fetched++;          $fetched++;
3461      }      }
     Trace("$fetched rows returned in GetAll.") if T(SQL => 4);  
3462      # Return the resulting list.      # Return the resulting list.
3463      return @retVal;      return @retVal;
3464  }  }
3465    
3466  =head3 Exists  =head3 Exists
3467    
3468  C<< my $found = $sprout->Exists($entityName, $entityID); >>      my $found = $sprout->Exists($entityName, $entityID);
3469    
3470  Return TRUE if an entity exists, else FALSE.  Return TRUE if an entity exists, else FALSE.
3471    
# Line 3242  Line 3500 
3500    
3501  =head3 EstimateRowSize  =head3 EstimateRowSize
3502    
3503  C<< my $rowSize = $erdb->EstimateRowSize($relName); >>      my $rowSize = $erdb->EstimateRowSize($relName);
3504    
3505  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
3506  up the average length for each data type.  up the average length for each data type.
# Line 3280  Line 3538 
3538    
3539  =head3 GetFieldTable  =head3 GetFieldTable
3540    
3541  C<< my $fieldHash = $self->GetFieldTable($objectnName); >>      my $fieldHash = $self->GetFieldTable($objectnName);
3542    
3543  Get the field structure for a specified entity or relationship.  Get the field structure for a specified entity or relationship.
3544    
# Line 3309  Line 3567 
3567    
3568  =head3 SplitKeywords  =head3 SplitKeywords
3569    
3570  C<< my @keywords = ERDB::SplitKeywords($keywordString); >>      my @keywords = ERDB::SplitKeywords($keywordString);
3571    
3572  This method returns a list of the positive keywords in the specified  This method returns a list of the positive keywords in the specified
3573  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 3616 
3616    
3617  =head3 ValidateFieldName  =head3 ValidateFieldName
3618    
3619  C<< my $okFlag = ERDB::ValidateFieldName($fieldName); >>      my $okFlag = ERDB::ValidateFieldName($fieldName);
3620    
3621  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
3622  be hyphenated words subject to certain restrictions.  be hyphenated words subject to certain restrictions.
# Line 3413  Line 3671 
3671    
3672  =head3 ReadMetaXML  =head3 ReadMetaXML
3673    
3674  C<< my $rawMetaData = ERDB::ReadDBD($fileName); >>      my $rawMetaData = ERDB::ReadDBD($fileName);
3675    
3676  This method reads a raw database definition XML file and returns it.  This method reads a raw database definition XML file and returns it.
3677  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 3704 
3704    
3705  =head3 GetEntityFieldHash  =head3 GetEntityFieldHash
3706    
3707  C<< my $fieldHashRef = ERDB::GetEntityFieldHash($structure, $entityName); >>      my $fieldHashRef = ERDB::GetEntityFieldHash($structure, $entityName);
3708    
3709  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.
3710  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 3746 
3746    
3747  =head3 WriteMetaXML  =head3 WriteMetaXML
3748    
3749  C<< ERDB::WriteMetaXML($structure, $fileName); >>      ERDB::WriteMetaXML($structure, $fileName);
3750    
3751  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
3752  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 3785 
3785  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
3786  example, C<[b]Feature[/b]> displays the string C<Feature> in boldface.  example, C<[b]Feature[/b]> displays the string C<Feature> in boldface.
3787    
3788  C<< my $realHtml = ERDB::HTMLNote($dataString); >>      my $realHtml = ERDB::HTMLNote($dataString);
3789    
3790  =over 4  =over 4
3791    
# Line 3557  Line 3815 
3815      return $retVal;      return $retVal;
3816  }  }
3817    
3818    =head3 WikiNote
3819    
3820    Convert a note or comment to Wiki text by replacing some bulletin-board codes with HTML. The codes
3821    supported are C<[b]> for B<bold>, C<[i]> for I<italics>, and C<[p]> for a new paragraph.
3822    Except for C<[p]>, all the codes are closed by slash-codes. So, for
3823    example, C<[b]Feature[/b]> displays the string C<Feature> in boldface.
3824    
3825        my $wikiText = ERDB::WikiNote($dataString);
3826    
3827    =over 4
3828    
3829    =item dataString
3830    
3831    String to convert to Wiki text.
3832    
3833    =item RETURN
3834    
3835    An Wiki text string derived from the input string.
3836    
3837    =back
3838    
3839    =cut
3840    
3841    sub WikiNote {
3842        # Get the parameter.
3843        my ($dataString) = @_;
3844        # HTML-escape the text.
3845        my $retVal = CGI::escapeHTML($dataString);
3846        # Substitute the bulletin board codes.
3847        my $italic = WikiTools::ItalicCode();
3848        $retVal =~ s/\[\/?i\]/$italic/g;
3849        my $bold = WikiTools::BoldCode();
3850        $retVal =~ s/\[\/?b\]/$bold/g;
3851        # Paragraph breaks are the same no matter which Wiki you're using.
3852        $retVal =~ s!\[p\]!\n\n!g;
3853        # Now we do the links, which are complicated by the need to know two
3854        # things: the target URL and the text.
3855        while ($retVal =~ /\[link\s+([^\]]+)\]([^\[]+)\[\/link\]/g) {
3856            # Replace the matched string with the Wiki markup for links. Note that
3857            # $-[0] is the starting position of the match for the entire expression,
3858            # and $+[0] is past the ending position.
3859            substr $retVal, $-[0], $+[0] - $-[0], WikiTools::LinkMarkup($1, $2);
3860        }
3861        # Return the result.
3862        return $retVal;
3863    }
3864    
3865  =head3 BeginTran  =head3 BeginTran
3866    
3867  C<< $erdb->BeginTran(); >>      $erdb->BeginTran();
3868    
3869  Start a database transaction.  Start a database transaction.
3870    
# Line 3573  Line 3878 
3878    
3879  =head3 CommitTran  =head3 CommitTran
3880    
3881  C<< $erdb->CommitTran(); >>      $erdb->CommitTran();
3882    
3883  Commit an active database transaction.  Commit an active database transaction.
3884    
# Line 3586  Line 3891 
3891    
3892  =head3 RollbackTran  =head3 RollbackTran
3893    
3894  C<< $erdb->RollbackTran(); >>      $erdb->RollbackTran();
3895    
3896  Roll back an active database transaction.  Roll back an active database transaction.
3897    
# Line 3599  Line 3904 
3904    
3905  =head3 UpdateField  =head3 UpdateField
3906    
3907  C<< my $count = $erdb->UpdateField($objectNames, $fieldName, $oldValue, $newValue, $filter, $parms); >>      my $count = $erdb->UpdateField($objectNames, $fieldName, $oldValue, $newValue, $filter, $parms);
3908    
3909  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
3910  returned.  returned.
# Line 3679  Line 3984 
3984    
3985  =head3 GetUsefulCrossValues  =head3 GetUsefulCrossValues
3986    
3987  C<< my @attrNames = $sprout->GetUsefulCrossValues($sourceEntity, $relationship); >>      my @attrNames = $sprout->GetUsefulCrossValues($sourceEntity, $relationship);
3988    
3989  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
3990  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 4045 
4045    
4046  =head3 FindColumn  =head3 FindColumn
4047    
4048  C<< my $colIndex = ERDB::FindColumn($headerLine, $columnIdentifier); >>      my $colIndex = ERDB::FindColumn($headerLine, $columnIdentifier);
4049    
4050  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
4051  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 4103 
4103    
4104  =head3 ParseColumns  =head3 ParseColumns
4105    
4106  C<< my @columns = ERDB::ParseColumns($line); >>      my @columns = ERDB::ParseColumns($line);
4107    
4108  Convert the specified data line to a list of columns.  Convert the specified data line to a list of columns.
4109    
# Line 3832  Line 4137 
4137    
4138  =head3 _CreatePPOIndex  =head3 _CreatePPOIndex
4139    
4140  C<< my $index = ERDB::_CreatePPOIndex($indexObject); >>      my $index = ERDB::_CreatePPOIndex($indexObject);
4141    
4142  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
4143  index.  index.
4144    
4145  =over 4  =over 4
4146    
4147    =item indexObject
4148    
4149  ERDB XML structure for an index.  ERDB XML structure for an index.
4150    
4151  =item RETURN  =item RETURN
# Line 3863  Line 4170 
4170    
4171  =head3 _CreatePPOField  =head3 _CreatePPOField
4172    
4173  C<< my $fieldXML = ERDB::_CreatePPOField($fieldName, $fieldObject); >>      my $fieldXML = ERDB::_CreatePPOField($fieldName, $fieldObject);
4174    
4175  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.
4176    
# Line 3900  Line 4207 
4207    
4208  =head3 CleanKeywords  =head3 CleanKeywords
4209    
4210  C<< my $cleanedString = $erdb->CleanKeywords($searchExpression); >>      my $cleanedString = $erdb->CleanKeywords($searchExpression);
4211    
4212  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
4213  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 4244 
4244    
4245  =head3 GetSourceObject  =head3 GetSourceObject
4246    
4247  C<< my $source = $erdb->GetSourceObject($entityName); >>      my $source = $erdb->GetSourceObject($entityName);
4248    
4249  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
4250  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 4254 
4254    
4255  =head3 _RelationMap  =head3 _RelationMap
4256    
4257  C<< my @relationMap = _RelationMap($mappedNameHashRef, $mappedNameListRef); >>      my @relationMap = _RelationMap($mappedNameHashRef, $mappedNameListRef);
4258    
4259  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>
4260  to determine how to interpret the results of the query.  to determine how to interpret the results of the query.
# Line 4260  Line 4567 
4567  sub _GetStatementHandle {  sub _GetStatementHandle {
4568      # Get the parameters.      # Get the parameters.
4569      my ($self, $command, $params) = @_;      my ($self, $command, $params) = @_;
4570        Confess("Invalid parameter list.") if (! defined($params) || ref($params) ne 'ARRAY');
4571      # Trace the query.      # Trace the query.
4572      Trace("SQL query: $command") if T(SQL => 3);      Trace("SQL query: $command") if T(SQL => 3);
4573      Trace("PARMS: '" . (join "', '", @{$params}) . "'") if (T(SQL => 4) && (@{$params} > 0));      Trace("PARMS: '" . (join "', '", @{$params}) . "'") if (T(SQL => 4) && (@{$params} > 0));
# Line 4497  Line 4805 
4805      # be a null string.      # be a null string.
4806      if ($fileName ne "") {      if ($fileName ne "") {
4807          # Load the relation from the file.          # Load the relation from the file.
4808          $retVal = $self->LoadTable($fileName, $relationName, $rebuild);          $retVal = $self->LoadTable($fileName, $relationName, truncate => $rebuild);
4809      } elsif ($rebuild) {      } elsif ($rebuild) {
4810          # 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.
4811          $self->CreateTable($relationName, 1);          $self->CreateTable($relationName, 1);
# Line 4509  Line 4817 
4817    
4818  =head3 _LoadMetaData  =head3 _LoadMetaData
4819    
4820  C<< my $metadata = ERDB::_LoadMetaData($filename); >>      my $metadata = ERDB::_LoadMetaData($filename);
4821    
4822  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.
4823  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 5175 
5175    
5176  =head3 _ProcessIndexes  =head3 _ProcessIndexes
5177    
5178  C<< ERDB::_ProcessIndexes($indexList, $relation); >>      ERDB::_ProcessIndexes($indexList, $relation);
5179    
5180  Build the data structures for the specified indexes in the specified relation.  Build the data structures for the specified indexes in the specified relation.
5181    
# Line 5244  Line 5552 
5552      return $retVal;      return $retVal;
5553  }  }
5554    
5555  =head2 HTML Documentation Utility Methods  =head2 Documentation Utility Methods
5556    
5557  =head3 _ComputeRelationshipSentence  =head3 _ComputeRelationshipSentence
5558    
# Line 5276  Line 5584 
5584      # Get the parameters.      # Get the parameters.
5585      my ($relationshipName, $relationshipStructure) = @_;      my ($relationshipName, $relationshipStructure) = @_;
5586      # Format the relationship sentence.      # Format the relationship sentence.
5587      my $result = "$relationshipStructure->{from} <b>$relationshipName</b> $relationshipStructure->{to}";      my $result = "$relationshipStructure->{from} $relationshipName $relationshipStructure->{to}";
5588      # Compute the arity.      # Compute the arity.
5589      my $arityCode = $relationshipStructure->{arity};      my $arityCode = $relationshipStructure->{arity};
5590      my $arity = $ArityTable{$arityCode};      my $arity = $ArityTable{$arityCode};
# Line 5321  Line 5629 
5629      return $result;      return $result;
5630  }  }
5631    
5632    =head3 _WikiRelationTable
5633    
5634    Generate the Wiki text for a particular relation. The relation's data will be formatted as a
5635    table with three columns-- the field name, the field type, and the field description.
5636    
5637    This is a static method.
5638    
5639    =over 4
5640    
5641    =item relationName
5642    
5643    Name of the relation being formatted.
5644    
5645    =item relationData
5646    
5647    Hash containing the relation's fields and indexes.
5648    
5649    =item RETURN
5650    
5651    Returns a Wiki string that can be used to display the relation name and all of its fields.
5652    
5653    =back
5654    
5655    =cut
5656    
5657    sub _WikiRelationTable {
5658        # Get the parameters.
5659        my ($relationName, $relationData) = @_;
5660        # We'll create a list of lists in here, then call WikiTools::Table to
5661        # convert it into a table.
5662        my @rows = ();
5663        # Push in the header row.
5664        push @rows, [qw(Field Type Description)];
5665        # Loop through the fields.
5666        for my $field (@{$relationData->{Fields}}) {
5667            # Create this field's row. We always have a name and type.
5668            my @row = ($field->{name}, $field->{type});
5669            # If we have a description, add it as the third column.
5670            if (exists $field->{Notes}) {
5671                push @row, WikiNote($field->{Notes}->{content});
5672            }
5673            # Push this row onto the table list.
5674            push @rows, \@row;
5675        }
5676        # Store the rows as a Wiki table with a level-4 heading.
5677        my $retVal = join("\n\n", WikiTools::Heading(4, "$relationName Table"),
5678                          WikiTools::Table(@rows));
5679        # Now we show the relation's indexes. These are formatted as another
5680        # table.
5681        @rows = ();
5682        # Push in the header row.
5683        push @rows, [qw(Index Unique Fields Notes)];
5684        # Get the index hash.
5685        my $indexTable = $relationData->{Indexes};
5686        # Loop through the indexes. For an entity, there is always at least one index.
5687        # For a relationship, there are at least two. The upshot is we don't need to
5688        # worry about accidentally generating a frivolous table here.
5689        for my $indexName (sort keys %$indexTable) {
5690            my $indexData = $indexTable->{$indexName};
5691            # Determine whether or not the index is unique.
5692            my $unique = ((exists $indexData->{Unique} && $indexData->{Unique} eq "true") ?
5693                          "yes" : "");
5694            # Get the field list.
5695            my $fields = join(', ', @{$indexData->{IndexFields}});
5696            # Get the note text.
5697            my $description = "";
5698            if (my $note = $indexData->{Notes}) {
5699                $description = WikiNote($note->{content});
5700            }
5701            # Format this row.
5702            my @row = ($indexName, $unique, $fields, $description);
5703            push @rows, \@row;
5704        }
5705        # Add the index list to the result.
5706        $retVal .= "\n\n" . WikiTools::Table(@rows);
5707    }
5708    
5709  =head3 _ShowRelationTable  =head3 _ShowRelationTable
5710    
5711  Generate the HTML string for a particular relation. The relation's data will be formatted as an HTML  Generate the HTML string for a particular relation. The relation's data will be formatted as an HTML
# Line 5494  Line 5879 
5879      return $htmlString;      return $htmlString;
5880  }  }
5881    
5882    =head3 _ObjectNotes
5883    
5884        my @noteParagraphs = _ObjectNotes($objectData);
5885    
5886    Return a list of the notes and asides for an entity or relationship in
5887    Wiki format.
5888    
5889    =over 4
5890    
5891    =item objectData
5892    
5893    The metadata for the desired entity or relationship.
5894    
5895    =item RETURN
5896    
5897    Returns a list of text paragraphs in Wiki markup form.
5898    
5899    =back
5900    
5901    =cut
5902    
5903    sub _ObjectNotes {
5904        # Get the parameters.
5905        my ($objectData) = @_;
5906        # Declare the return variable.
5907        my @retVal;
5908        # Loop through the types of notes.
5909        for my $noteType (qw(Notes Asides)) {
5910            my $text = $objectData->{$noteType};
5911            if ($text) {
5912                push @retVal, "", WikiNote($text->{content});
5913            }
5914        }
5915        # Return the result.
5916        return @retVal;
5917    }
5918    
5919  1;  1;

Legend:
Removed from v.1.92  
changed lines
  Added in v.1.103

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3