[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.18, Sun Aug 14 23:32:08 2005 UTC revision 1.26, Tue Oct 18 06:47:46 2005 UTC
# Line 9  Line 9 
9      use DBObject;      use DBObject;
10      use Stats;      use Stats;
11      use Time::HiRes qw(gettimeofday);      use Time::HiRes qw(gettimeofday);
12        use FIG;
13    
14  =head1 Entity-Relationship Database Package  =head1 Entity-Relationship Database Package
15    
# Line 552  Line 553 
553  sub CreateTables {  sub CreateTables {
554      # Get the parameters.      # Get the parameters.
555      my ($self) = @_;      my ($self) = @_;
556      my $metadata = $self->{_metaData};      # Get the relation names.
557      my $dbh = $self->{_dbh};      my @relNames = $self->GetTableNames();
558      # Loop through the entities.      # Loop through the relations.
559      my $entityHash = $metadata->{Entities};      for my $relationName (@relNames) {
     for my $entityName (keys %{$entityHash}) {  
         my $entityData = $entityHash->{$entityName};  
         # Tell the user what we're doing.  
         Trace("Creating relations for entity $entityName.") if T(1);  
         # Loop through the entity's relations.  
         for my $relationName (keys %{$entityData->{Relations}}) {  
560              # Create a table for this relation.              # Create a table for this relation.
561              $self->CreateTable($relationName);              $self->CreateTable($relationName);
562              Trace("Relation $relationName created.") if T(1);          Trace("Relation $relationName created.") if T(2);
         }  
     }  
     # Loop through the relationships.  
     my $relationshipTable = $metadata->{Relationships};  
     for my $relationshipName (keys %{$metadata->{Relationships}}) {  
         # Create a table for this relationship.  
         Trace("Creating relationship $relationshipName.") if T(1);  
         $self->CreateTable($relationshipName);  
563      }      }
564  }  }
565    
# Line 673  Line 660 
660          # Get the index's uniqueness flag.          # Get the index's uniqueness flag.
661          my $unique = (exists $indexData->{Unique} ? $indexData->{Unique} : 'false');          my $unique = (exists $indexData->{Unique} ? $indexData->{Unique} : 'false');
662          # Create the index.          # Create the index.
663          $dbh->create_index(idx => $indexName, tbl => $relationName, flds => $flds, unique => $unique);          my $rv = $dbh->create_index(idx => $indexName, tbl => $relationName,
664                                        flds => $flds, unique => $unique);
665            if ($rv) {
666          Trace("Index created: $indexName for $relationName ($flds)") if T(1);          Trace("Index created: $indexName for $relationName ($flds)") if T(1);
667            } else {
668                Confess("Error creating index $indexName for $relationName using ($flds): " . $dbh->error_message());
669            }
670      }      }
671  }  }
672    
# Line 723  Line 715 
715      $directoryName =~ s!/\\$!!;      $directoryName =~ s!/\\$!!;
716      # Declare the return variable.      # Declare the return variable.
717      my $retVal = Stats->new();      my $retVal = Stats->new();
718      # Get the metadata structure.      # Get the relation names.
719      my $metaData = $self->{_metaData};      my @relNames = $self->GetTableNames();
720      # Loop through the entities.      for my $relationName (@relNames) {
     for my $entity (values %{$metaData->{Entities}}) {  
         # Loop through the entity's relations.  
         for my $relationName (keys %{$entity->{Relations}}) {  
721              # Try to load this relation.              # Try to load this relation.
722              my $result = $self->_LoadRelation($directoryName, $relationName, $rebuild);              my $result = $self->_LoadRelation($directoryName, $relationName, $rebuild);
723              # Accumulate the statistics.              # Accumulate the statistics.
724              $retVal->Accumulate($result);              $retVal->Accumulate($result);
725          }          }
     }  
     # Loop through the relationships.  
     for my $relationshipName (keys %{$metaData->{Relationships}}) {  
         # Try to load this relationship's relation.  
         my $result = $self->_LoadRelation($directoryName, $relationshipName, $rebuild);  
         # Accumulate the statistics.  
         $retVal->Accumulate($result);  
     }  
726      # Add the duration of the load to the statistical object.      # Add the duration of the load to the statistical object.
727      $retVal->Add('duration', gettimeofday - $startTime);      $retVal->Add('duration', gettimeofday - $startTime);
728      # Return the accumulated statistics.      # Return the accumulated statistics.
729      return $retVal;      return $retVal;
730  }  }
731    
732    
733  =head3 GetTableNames  =head3 GetTableNames
734    
735  C<< my @names = $erdb->GetTableNames; >>  C<< my @names = $erdb->GetTableNames; >>
# Line 782  Line 764 
764      return sort keys %{$entityList};      return sort keys %{$entityList};
765  }  }
766    
767    =head3 IsEntity
768    
769    C<< my $flag = $erdb->IsEntity($entityName); >>
770    
771    Return TRUE if the parameter is an entity name, else FALSE.
772    
773    =over 4
774    
775    =item entityName
776    
777    Object name to be tested.
778    
779    =item RETURN
780    
781    Returns TRUE if the specified string is an entity name, else FALSE.
782    
783    =back
784    
785    =cut
786    
787    sub IsEntity {
788        # Get the parameters.
789        my ($self, $entityName) = @_;
790        # Test to see if it's an entity.
791        return exists $self->{_metaData}->{Entities}->{$entityName};
792    }
793    
794  =head3 Get  =head3 Get
795    
796  C<< my $query = $erdb->Get(\@objectNames, $filterClause, $param1, $param2, ..., $paramN); >>  C<< my $query = $erdb->Get(\@objectNames, $filterClause, $param1, $param2, ..., $paramN); >>
# Line 868  Line 877 
877      my $dbh = $self->{_dbh};      my $dbh = $self->{_dbh};
878      my $command = "SELECT DISTINCT " . join('.*, ', @{$objectNames}) . ".* FROM " .      my $command = "SELECT DISTINCT " . join('.*, ', @{$objectNames}) . ".* FROM " .
879                  join(', ', @{$objectNames});                  join(', ', @{$objectNames});
880        Trace("SQL = $command") if T(SQL => 4);
881      # Check for a filter clause.      # Check for a filter clause.
882      if ($filterClause) {      if ($filterClause) {
883          # Here we have one, so we convert its field names and add it to the query. First,          # Here we have one, so we convert its field names and add it to the query. First,
# Line 1299  Line 1309 
1309      Trace("Loading table $relationName from $fileName") if T(2);      Trace("Loading table $relationName from $fileName") if T(2);
1310      # Get the database handle.      # Get the database handle.
1311      my $dbh = $self->{_dbh};      my $dbh = $self->{_dbh};
1312        # Get the input file size.
1313        my $fileSize = -s $fileName;
1314      # Get the relation data.      # Get the relation data.
1315      my $relation = $self->_FindRelation($relationName);      my $relation = $self->_FindRelation($relationName);
1316      # Check the truncation flag.      # Check the truncation flag.
1317      if ($truncateFlag) {      if ($truncateFlag) {
1318          Trace("Creating table $relationName") if T(2);          Trace("Creating table $relationName") if T(2);
1319            # Compute the row count estimate. We take the size of the load file,
1320            # divide it by the estimated row size, and then multiply by 1.5 to
1321            # leave extra room. We postulate a minimum row count of 1000 to
1322            # prevent problems with incoming empty load files.
1323            my $rowSize = $self->EstimateRowSize($relationName);
1324            my $estimate = FIG::max($fileSize * 1.5 / $rowSize, 1000);
1325          # Re-create the table without its index.          # Re-create the table without its index.
1326          $self->CreateTable($relationName, 0);          $self->CreateTable($relationName, 0, $estimate);
1327          # If this is a pre-index DBMS, create the index here.          # If this is a pre-index DBMS, create the index here.
1328          if ($dbh->{_preIndex}) {          if ($dbh->{_preIndex}) {
1329              eval {              eval {
# Line 1316  Line 1334 
1334              }              }
1335          }          }
1336      }      }
     # Determine whether or not this is a primary relation. Primary relations have an extra  
     # field indicating whether or not a given object is new or was loaded from the flat files.  
     my $primary = $self->_IsPrimary($relationName);  
     # Get the number of fields in this relation.  
     my @fieldList = @{$relation->{Fields}};  
     my $fieldCount = @fieldList;  
     # Start a database transaction.  
     $dbh->begin_tran;  
     # Open the relation file. We need to create a cleaned-up copy before loading.  
     open TABLEIN, '<', $fileName;  
     my $tempName = "$fileName.tbl";  
     open TABLEOUT, '>', $tempName;  
     my $inputCount = 0;  
     # Loop through the file.  
     while (<TABLEIN>) {  
         $inputCount++;  
         # Chop off the new-line character.  
         my $record = Tracer::Strip($_);  
         # Only proceed if the record is non-blank.  
         if ($record) {  
             # Escape all the backslashes found in the line.  
             $record =~ s/\\/\\\\/g;  
             # Insure the number of fields is correct.  
             my @fields = split /\t/, $record;  
             while (@fields > $fieldCount) {  
                 my $extraField = $fields[$#fields];  
                 delete $fields[$#fields];  
                 if ($extraField) {  
                     Trace("Nonblank extra field value \"$extraField\" deleted from record $inputCount of $fileName.") if T(1);  
                 }  
             }  
             while (@fields < $fieldCount) {  
                 push @fields, "";  
             }  
             # If this is a primary relation, add a 0 for the new-record flag (indicating that  
             # this record is not new, but part of the original load).  
             if ($primary) {  
                 push @fields, "0";  
             }  
             # Write the record.  
             $record = join "\t", @fields;  
             print TABLEOUT "$record\n";  
             # Count the record written.  
             my $count = $retVal->Add('records');  
             my $len = length $record;  
             Trace("Record $count written with $len characters.") if T(4);  
         } else {  
             # Here we have a blank record.  
             $retVal->Add('skipped');  
         }  
     }  
     # Close the files.  
     close TABLEIN;  
     close TABLEOUT;  
     Trace("Temporary file $tempName created.") if T(2);  
1337      # Load the table.      # Load the table.
1338      my $rv;      my $rv;
1339      eval {      eval {
1340          $rv = $dbh->load_table(file => $tempName, tbl => $relationName);          $rv = $dbh->load_table(file => $fileName, tbl => $relationName);
1341      };      };
1342      if (!defined $rv) {      if (!defined $rv) {
1343          $retVal->AddMessage($@) if ($@);          $retVal->AddMessage($@) if ($@);
1344          $retVal->AddMessage("Table load failed for $relationName using $tempName.");          $retVal->AddMessage("Table load failed for $relationName using $fileName.");
1345          Trace("Table load failed for $relationName.") if T(1);          Trace("Table load failed for $relationName.") if T(1);
1346      } else {      } else {
1347          # Here we successfully loaded the table. Trace the number of records loaded.          # Here we successfully loaded the table.
1348          Trace("$retVal->{records} records read for $relationName.") if T(2);          $retVal->Add("tables");
1349            my $size = -s $fileName;
1350            Trace("$size bytes loaded into $relationName.") if T(2);
1351          # If we're rebuilding, we need to create the table indexes.          # If we're rebuilding, we need to create the table indexes.
1352          if ($truncateFlag && ! $dbh->{_preIndex}) {          if ($truncateFlag && ! $dbh->{_preIndex}) {
1353              eval {              eval {
# Line 1392  Line 1357 
1357                  $retVal->AddMessage($@);                  $retVal->AddMessage($@);
1358              }              }
1359          }          }
         # Analyze the table to help optimize tables.  
1360      }      }
1361      # Commit the database changes.      # Analyze the table to improve performance.
     $dbh->commit_tran;  
1362      $dbh->vacuum_it($relationName);      $dbh->vacuum_it($relationName);
     # Delete the temporary file.  
     unlink $tempName;  
1363      # Return the statistics.      # Return the statistics.
1364      return $retVal;      return $retVal;
1365  }  }
# Line 2247  Line 2208 
2208          my @fromList = ();          my @fromList = ();
2209          my @toList = ();          my @toList = ();
2210          my @bothList = ();          my @bothList = ();
2211          Trace("Join table build for $entityName.") if T(4);          Trace("Join table build for $entityName.") if T(metadata => 4);
2212          for my $relationshipName (keys %{$relationshipList}) {          for my $relationshipName (keys %{$relationshipList}) {
2213              my $relationship = $relationshipList->{$relationshipName};              my $relationship = $relationshipList->{$relationshipName};
2214              # Determine if this relationship has our entity in one of its link fields.              # Determine if this relationship has our entity in one of its link fields.
# Line 2258  Line 2219 
2219                  if ($toEntity eq $entityName) {                  if ($toEntity eq $entityName) {
2220                      # Here the relationship is recursive.                      # Here the relationship is recursive.
2221                      push @bothList, $relationshipName;                      push @bothList, $relationshipName;
2222                      Trace("Relationship $relationshipName put in both-list.") if T(4);                      Trace("Relationship $relationshipName put in both-list.") if T(metadata => 4);
2223                  } else {                  } else {
2224                      # Here the relationship comes from the entity.                      # Here the relationship comes from the entity.
2225                      push @fromList, $relationshipName;                      push @fromList, $relationshipName;
2226                      Trace("Relationship $relationshipName put in from-list.") if T(4);                      Trace("Relationship $relationshipName put in from-list.") if T(metadata => 4);
2227                  }                  }
2228              } elsif ($toEntity eq $entityName) {              } elsif ($toEntity eq $entityName) {
2229                  # Here the relationship goes to the entity.                  # Here the relationship goes to the entity.
2230                  push @toList, $relationshipName;                  push @toList, $relationshipName;
2231                  Trace("Relationship $relationshipName put in to-list.") if T(4);                  Trace("Relationship $relationshipName put in to-list.") if T(metadata => 4);
2232              }              }
2233          }          }
2234          # Create the nonrecursive joins. Note that we build two hashes for running          # Create the nonrecursive joins. Note that we build two hashes for running
# Line 2283  Line 2244 
2244                  # Create joins between the entity and this relationship.                  # Create joins between the entity and this relationship.
2245                  my $linkField = "$relationshipName.${linkType}_link";                  my $linkField = "$relationshipName.${linkType}_link";
2246                  my $joinClause = "$entityName.id = $linkField";                  my $joinClause = "$entityName.id = $linkField";
2247                  Trace("Entity join clause is $joinClause for $entityName and $relationshipName.") if T(4);                  Trace("Entity join clause is $joinClause for $entityName and $relationshipName.") if T(metadata => 4);
2248                  $joinTable{"$entityName/$relationshipName"} = $joinClause;                  $joinTable{"$entityName/$relationshipName"} = $joinClause;
2249                  $joinTable{"$relationshipName/$entityName"} = $joinClause;                  $joinTable{"$relationshipName/$entityName"} = $joinClause;
2250                  # Create joins between this relationship and the other relationships.                  # Create joins between this relationship and the other relationships.
# Line 2304  Line 2265 
2265                              # relationship and itself are prohibited.                              # relationship and itself are prohibited.
2266                              my $relJoinClause = "$otherName.${otherType}_link = $linkField";                              my $relJoinClause = "$otherName.${otherType}_link = $linkField";
2267                              $joinTable{$joinKey} = $relJoinClause;                              $joinTable{$joinKey} = $relJoinClause;
2268                              Trace("Relationship join clause is $relJoinClause for $joinKey.") if T(4);                              Trace("Relationship join clause is $relJoinClause for $joinKey.") if T(metadata => 4);
2269                          }                          }
2270                      }                      }
2271                  }                  }
# Line 2313  Line 2274 
2274                  # relationship can only be ambiguous with another recursive relationship,                  # relationship can only be ambiguous with another recursive relationship,
2275                  # and the incoming relationship from the outer loop is never recursive.                  # and the incoming relationship from the outer loop is never recursive.
2276                  for my $otherName (@bothList) {                  for my $otherName (@bothList) {
2277                      Trace("Setting up relationship joins to recursive relationship $otherName with $relationshipName.") if T(4);                      Trace("Setting up relationship joins to recursive relationship $otherName with $relationshipName.") if T(metadata => 4);
2278                      # Join from the left.                      # Join from the left.
2279                      $joinTable{"$relationshipName/$otherName"} =                      $joinTable{"$relationshipName/$otherName"} =
2280                          "$linkField = $otherName.from_link";                          "$linkField = $otherName.from_link";
# Line 2328  Line 2289 
2289          # rise to situations where we can't create the path we want; however, it is always          # rise to situations where we can't create the path we want; however, it is always
2290          # possible to get the same effect using multiple queries.          # possible to get the same effect using multiple queries.
2291          for my $relationshipName (@bothList) {          for my $relationshipName (@bothList) {
2292              Trace("Setting up entity joins to recursive relationship $relationshipName with $entityName.") if T(4);              Trace("Setting up entity joins to recursive relationship $relationshipName with $entityName.") if T(metadata => 4);
2293              # Join to the entity from each direction.              # Join to the entity from each direction.
2294              $joinTable{"$entityName/$relationshipName"} =              $joinTable{"$entityName/$relationshipName"} =
2295                  "$entityName.id = $relationshipName.from_link";                  "$entityName.id = $relationshipName.from_link";

Legend:
Removed from v.1.18  
changed lines
  Added in v.1.26

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3