[Bio] / Sprout / ERDBLoader.pl Repository:
ViewVC logotype

Diff of /Sprout/ERDBLoader.pl

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1.10, Mon May 4 18:49:49 2009 UTC revision 1.19, Sat Apr 30 15:21:18 2011 UTC
# Line 22  Line 22 
22  use ERDB;  use ERDB;
23  use ERDBLoadGroup;  use ERDBLoadGroup;
24  use ERDBGenerate;  use ERDBGenerate;
25    use ERDBExtras;
26  use Stats;  use Stats;
27  use Time::HiRes;  use Time::HiRes;
28    
# Line 34  Line 35 
35    
36  =head2 Introduction  =head2 Introduction
37    
38  This script finishes the database load process begun by [[ERDBGeneratorPl]].  This script finishes the database load process begun by L<ERDBGenerator.pl>.
39    
40  [[ERDBGeneratorPl]] divides the source data into sections, and generates a  L<ERDBGenerator.pl> divides the source data into sections, and generates a
41  partial load file for each section of each table. To finish the load process, we  partial load file for each section of each table. To finish the load process, we
42  need to combine the partial files into single files and load the resulting  need to combine the partial files into single files and load the resulting
43  single files into the database tables.  single files into the database tables.
44    
45  Like [[ERDBGeneratorPl]], this script acts on load groups-- sets of related  Like L<ERDBGenerator.pl>, this script acts on load groups-- sets of related
46  tables that are loaded at the same time. For each table in a named group that  tables that are loaded at the same time. For each table in a named group that
47  does not exist in the database, the script first attempts to find a completed  does not exist in the database, the script first attempts to find a complete set
48  data file. If one does not exist, it attempts to create one by collating section  of section files that it will collate into a data file. If there are no sections,
49  files. Once the collated section files for a load group are finished, they are  then it will look for a data file that is already collated. Once the collated
50  loaded into the database.  section files for a load group are all verified, they are loaded into the database.
51    
52  =head2 Positional Parameters  =head2 Positional Parameters
53    
# Line 76  Line 77 
77    
78  If specified, turns on tracing of SQL activity.  If specified, turns on tracing of SQL activity.
79    
 =item clear  
   
 If specified, existing load files will be recreated from sections if the sections  
 are present.  
   
80  =item background  =item background
81    
82  Save the standard and error output to files. The files will be created  Save the standard and error output to files. The files will be created
# Line 95  Line 91 
91  =item keepSections  =item keepSections
92    
93  If specified, section files (the fragments of data load files created by  If specified, section files (the fragments of data load files created by
94  [[ERDBGeneratorPl]], will not be deleted after they are collated.  L<ERDBGenerator.pl>, will not be deleted after they are collated.
   
 =item sanityCheck  
   
 If specified, no tables will be loaded. Instead, the first I<N> records from the  
 assembled load files will be displayed so that the file contents can be  
 visually matched against the column names.  
95    
96  =item warn  =item warn
97    
# Line 130  Line 120 
120  This option allows you to specify a backup or alternate database that can  This option allows you to specify a backup or alternate database that can
121  be loaded without compromising the main database.  be loaded without compromising the main database.
122    
123    =item dbhost
124    
125    Name of the MySQL database host. If not specified, the default host is used.
126    This option is required when the default host is restricted to read-only
127    database access.
128    
129  =back  =back
130    
131  =cut  =cut
# Line 138  Line 134 
134  my ($options, @parameters) = StandardSetup([qw(ERDBLoadGroup ERDB Stats) ],  my ($options, @parameters) = StandardSetup([qw(ERDBLoadGroup ERDB Stats) ],
135                                             {                                             {
136                                                dbName => ["", "if specified, the SQL name of the target database"],                                                dbName => ["", "if specified, the SQL name of the target database"],
137                                                clear => ["", "overwrite existing load files if sections are present"],                                                dbhost => ["", "if specified, the name of the target database"],
                                               sanityCheck => ["", "don't load, trace contents of first N load file records instead"],  
138                                                trace => ["2", "tracing level"],                                                trace => ["2", "tracing level"],
139                                                keepSections => ["", "if specified, section files will not be deleted after being collated"],                                                keepSections => ["", "if specified, section files will not be deleted after being collated"],
140                                                phone => ["", "phone number (international format) to call when load finishes"],                                                phone => ["", "phone number (international format) to call when load finishes"],
# Line 155  Line 150 
150      # Get the parameters.      # Get the parameters.
151      my ($database, @groups) = @parameters;      my ($database, @groups) = @parameters;
152      # Connect to the database and get its load directory.      # Connect to the database and get its load directory.
153      my $erdb = ERDB::GetDatabase($database, undef, %$options);      my $erdb = ERDB::GetDatabase($database, undef, %$options, externalDBD => 1);
154      # Fix the group list.      # Fix the group list.
155      my @realGroups = ERDBLoadGroup::ComputeGroups($erdb, \@groups);      my @realGroups = ERDBLoadGroup::ComputeGroups($erdb, \@groups);
156      # Get the source object and load directory for this database.      # Get the source object and load directory for this database.
# Line 165  Line 160 
160      my @sectionList = $erdb->SectionList($source);      my @sectionList = $erdb->SectionList($source);
161      # Create a statistics object to track our progress.      # Create a statistics object to track our progress.
162      my $stats = Stats->new();      my $stats = Stats->new();
163      # Find out if we're doing a sanity check.      # We make one pass to assemble all the tables in all the groups, and
164      my $sanityCheck = $options->{sanityCheck} || "";      # then another to do the actual loads. The groups that are ready to load
165        # in the second pass will go in this list.
166        my @goodGroups;
167      # Start a timer.      # Start a timer.
168      my $totalStart = time();      my $totalStart = time();
169      # Loop through the groups.      # Loop through the groups.
# Line 185  Line 182 
182              # Get the data file name.              # Get the data file name.
183              my $dataFile = ERDBGenerate::CreateFileName($table, undef, 'data', $directory);              my $dataFile = ERDBGenerate::CreateFileName($table, undef, 'data', $directory);
184              # Do we have it?              # Do we have it?
185              if (-f $dataFile && ! $options->{clear}) {              my $haveFile = -f $dataFile;
186                  # Yes. This is good news.              # See if we can build it. Verify that we have all the sections.
                 $stats->Add('tables-found' => 1);  
                 Trace("Table file found for $table.") if T(3);  
             } else {  
                 # No, we must build it. Verify that we have all the sections.  
187                  my @missingFiles = grep { ! -f $_ } @sectionFiles;                  my @missingFiles = grep { ! -f $_ } @sectionFiles;
188                  # Did we find everything?                  # Did we find everything?
189                  if (scalar @missingFiles) {              if (scalar(@missingFiles) && ! $haveFile) {
190                      # No! Denote that we have a missing table.                  # No, and there's no main file! Denote that we have a missing table.
191                      $missingTable++;                      $missingTable++;
192                      $stats->Add('tables-skipped' => 1);                      $stats->Add('tables-skipped' => 1);
193                      # If the user wants a sanity check, we want to give him some                  # Tell the user about all the missing files.
                     # data anyway.  
                     if ($sanityCheck) {  
                         # Get some data lines in the sections. Note we stop when we've exceeded  
                         # the number of lines expected by the sanity check.  
                         my @lines;  
                         for my $sectionFile (@sectionFiles) {  
                             if (-s $sectionFile && scalar(@lines) < $sanityCheck) {  
                                 Trace("Reading from $sectionFile for $table.") if T(3);  
                                 push @lines, Tracer::GetFile($sectionFile);  
                             }  
                         }  
                         # Create a new temporary file.  
                         my $tmpFile = "$FIG_Config::temp/$table$$.temp.dtx";  
                         my $oh = Open(undef, ">$tmpFile");  
                         # Put all the data into it.  
                         Trace(scalar(@lines) . " data lines found.") if T(3);  
                         print $oh join("\n", @lines);  
                         close $oh;  
                         # Sanity check the temp file.  
                         CheckLoadFile($erdb, $table, $tmpFile, $sanityCheck);  
                         # Clean it up.  
                         unlink $tmpFile;  
                     } else {  
                         # Otherwise tell the user about all the missing files.  
194                          for my $missingFile (@missingFiles) {                          for my $missingFile (@missingFiles) {
195                              $stats->Add('sections-missing' => 1);                              $stats->Add('sections-missing' => 1);
196                              $stats->AddMessage("Data file $missingFile not found for table $table.");                              $stats->AddMessage("Data file $missingFile not found for table $table.");
197                          }                          }
198                      }              } elsif (! scalar @missingFiles) {
                 } else {  
199                      # We have all the sections. Try to assemble them into a data file.                      # We have all the sections. Try to assemble them into a data file.
200                      my $sortStart = time();                      my $sortStart = time();
201                      my $sortCommand = $erdb->SortNeeded($table) . " >$dataFile";                      my $sortCommand = $erdb->SortNeeded($table) . " >$dataFile";
# Line 248  Line 216 
216                          }                          }
217                      }                      }
218                      # Finish the sort step.                      # Finish the sort step.
219                      Trace("Finishing collate for $table.") if T(3);                  Trace("Finishing collate for $table.") if T(2);
220                      close $oh;                      close $oh;
221                      $stats->Add('tables-collated' => 1);                      $stats->Add('tables-collated' => 1);
222                      $stats->Add('collate-time' => time() - $sortStart);                      $stats->Add('collate-time' => time() - $sortStart);
                 }  
             }  
223              # Now that we know we have a full data file, we can delete the              # Now that we know we have a full data file, we can delete the
224              # section files to make room in the data directory. The user can              # section files to make room in the data directory. The user can
225              # turn this behavior off with the keepSections option.              # turn this behavior off with the keepSections option.
# Line 266  Line 232 
232                  }                  }
233                  Trace("Section files for $table deleted.") if T(3);                  Trace("Section files for $table deleted.") if T(3);
234              }              }
235                } else {
236                    # We have a data file and no sections, so we use the data file.
237                    $stats->Add('tables-found' => 1);
238                }
239          }          }
240          # Were any tables missing?          # Were any tables missing?
241          if ($missingTable) {          if ($missingTable) {
# Line 273  Line 243 
243              $stats->Add('groups-skipped' => 1);              $stats->Add('groups-skipped' => 1);
244              Trace("Skipping $group group: $missingTable missing tables.") if T(2);              Trace("Skipping $group group: $missingTable missing tables.") if T(2);
245          } else {          } else {
246              # No! Process this group's files.              # No! File this group for processing in the second pass.
247              if ($sanityCheck eq "") {              push @goodGroups, $group;
248                  Trace("Loading group $group into database.") if T(2);          }
249        }
250        # Now we loop through the good groups, doing the actual loads.
251        for my $group (@goodGroups) {
252            # Get a group object.
253            my $groupData = $erdb->Loader($group);
254            # Do the post-processing.
255            my $postStats = $groupData->PostProcess();
256            # Determine what happened.
257            if (! defined $postStats) {
258                Trace("Post-processing not required for $group.") if T(3);
259              } else {              } else {
260                  Trace("Sanity check for group $group.") if T(2);              $stats->Accumulate($postStats);
261                $stats->Add('post-processing' => 1);
262              }              }
263            # Process this group's files.
264            Trace("Loading group $group into database.") if T(2);
265            # Get the list of tables.
266            my @tableList = $groupData->GetTables();
267            # Start a timer.
268              my $loadStart = time();              my $loadStart = time();
269              for my $table (@tableList) {              for my $table (@tableList) {
270                # Compute the load file name.
271                  my $fileName = ERDBGenerate::CreateFileName($table, undef, 'data', $directory);                  my $fileName = ERDBGenerate::CreateFileName($table, undef, 'data', $directory);
272                  # Do we want a real load or a sanity check?              # Do the actual load.
                 if ($sanityCheck eq "") {  
                     # Real load.  
273                      my $newStats = $erdb->LoadTable($fileName, $table, truncate => 1, failOnError => 1);                      my $newStats = $erdb->LoadTable($fileName, $table, truncate => 1, failOnError => 1);
274                      $stats->Accumulate($newStats);                      $stats->Accumulate($newStats);
275                      Trace("$fileName loaded into $table.") if T(3);                      Trace("$fileName loaded into $table.") if T(3);
                 } elsif ($sanityCheck > 0) {  
                     # Here we want a sanity check. Note that if the check value is 0,  
                     # we don't bother. The user just wants to suppress the load step.  
                     CheckLoadFile($erdb, $table, $fileName, $sanityCheck);  
                 }  
276              }              }
277              $stats->Add("groups-loaded" => 1);              $stats->Add("groups-loaded" => 1);
278              $stats->Add('load-time' => 1);          $stats->Add('load-time' => (time() - $loadStart));
         }  
279      }      }
280        # Save the DBD.
281        Trace("Saving DBD.") if T(2);
282        $erdb->InternalizeDBD();
283      $stats->Add('total-time' => time() - $totalStart);      $stats->Add('total-time' => time() - $totalStart);
284      # Display the statistics from this run.      # Display the statistics from this run.
285      Trace("Statistics for load:\n" . $stats->Show()) if T(2);      Trace("Statistics for load:\n" . $stats->Show()) if T(2);
# Line 316  Line 298 
298      }      }
299  }  }
300    
 =head2 Internal Methods  
   
 =head3 CheckLoadFile  
   
     CheckLoadFile($erdb, $table, $fileName, $count);  
   
 Read the first few records of a load file and trace the contents at level  
 2. This allows the user to visually compare the load file contents with  
 the database definition.  
   
 =over 4  
   
 =item erdb  
   
 [[ErdbPm]] object describing the database.  
   
 =item table  
   
 Name of the table to check.  
   
 =item fileName  
   
 Name of the load file to check.  
   
 =item count  
   
 Number of records to check.  
   
 =back  
   
 =cut  
   
 sub CheckLoadFile {  
     # Get the parameters.  
     my ($erdb, $table, $fileName, $count) = @_;  
     # Open the file for input.  
     my $ih = Open(undef, "<$fileName");  
     # Slurp the first N records.  
     my @records;  
     while (! eof $ih && scalar(@records) < $count) {  
         push @records, [ Tracer::GetLine($ih) ];  
     }  
     my $found = scalar(@records);  
     Trace("$found records for $table found in sanity check using $fileName.") if T(2);  
     # Do we have any data at all?  
     if ($found) {  
         # Yes. Get the table's descriptor. We use this to determine the field names.  
         my $relationData = $erdb->FindRelation($table);  
         Confess("Relation $table not found in database.") if (! defined $relationData);  
         my @fields = @{$relationData->{Fields}};  
         # If this is a relationship, we need the FROM and TO data.  
         my %ends; ($ends{from}, $ends{to}) = $erdb->GetRelationshipEntities($table);  
         # Loop through the fields. We generate one message per field.  
         for (my $i = 0; $i <= $#fields; $i++) {  
             # Get this field's information.  
             my $fieldInfo = $fields[$i];  
             my $type = $fieldInfo->{type};  
             my $name = $fieldInfo->{name};  
             if ($name =~ /^(from|to)-link$/) {  
                 # Here it's a relationship link, so add the name of the target table to  
                 # the type.  
                 $type .= " ($ends{$1})";  
             }  
             # This is going to be a multi-line trace message. We start with the field name and type.  
             my @lines = ("Values for $table($name), type $type:\n");  
             # Loop through the records. We generate one line of data per record.  
             for (my $j = 0; $j < $found; $j++) {  
                 # Get the field value.  
                 my $field = $records[$j]->[$i];  
                 # Compute the record label.  
                 my $line = "Record $j";  
                 # Check for unusual cases.  
                 if (! defined $field || $field eq '') {  
                     $line .= "= <empty>";  
                 } else {  
                     # Make sure we don't trace something ungodly.  
                     my $excess = (length $field) - 40;  
                     if ($excess > 0) {  
                         $field = substr($field, 0, 40) . " >> + $excess characters";  
                     }  
                     $line .= ": $field";  
                 }  
                 # Save this line. We indent a little for readability.  
                 push @lines, "   $line";  
             }  
             # Trace this field.  
             Trace(join("\n", @lines)) if T(2);  
         }  
     }  
 }  
   
301    
302  1;  1;

Legend:
Removed from v.1.10  
changed lines
  Added in v.1.19

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3