[Bio] / Sprout / ERDBLoad.pm Repository:
ViewVC logotype

Diff of /Sprout/ERDBLoad.pm

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

revision 1.2, Sun Aug 14 23:32:08 2005 UTC revision 1.24, Sat Sep 20 14:30:21 2008 UTC
# Line 12  Line 12 
12    
13  =head2 Introduction  =head2 Introduction
14    
15  This object is designed to assist with loading an ERDB data relation. The user  This object is designed to assist with creating the load file for an ERDB
16  constructs the object by specifying an ERDB object and a relation name. This  data relation. The user constructs the object by specifying an ERDB object
17  re-creates the relevant relation. The client then passes in data lines which  and a relation name. This create the load file for the relevant relation. The client
18  are written to a file. When the file gets big enough, it is loaded into the  then passes in data lines which are written to a file, and calls
19  table. Calling the L</Finish> method loads any leftover data and optionally  L</Finish> to close the file and get the statistics.
 creates the index.  
20    
21  This module makes use of the internal ERDB property C<_dbh> and the internal  This module makes use of the internal ERDB method C<_IsPrimary>.
 method C<_IsPrimary>.  
22    
23  =cut  =cut
24    
# Line 30  Line 28 
28    
29  =head3 new  =head3 new
30    
31  C<< my $erload = ERDBLoad->new($erdb, $relationName, $directory); >>      my $erload = ERDBLoad->new($erdb, $relationName, $directory, $loadOnly, $ignore);
32    
33  Begin loading an ERDB relation.  Begin loading an ERDB relation.
34    
# Line 48  Line 46 
46    
47  Name of the directory to use for the load files, WITHOUT a trailing slash.  Name of the directory to use for the load files, WITHOUT a trailing slash.
48    
49  =item estimatedRows (optional)  =item loadOnly
50    
51  Estimated maximum number of table rows. If omitted, the table will be created in  TRUE if the data is to be loaded from an existing file, FALSE if a file is
52  a format that permits an essentially unlimited number of rows.  to be created.
53    
54    =item ignore
55    
56    TRUE if the data is to be discarded. This is used to save time when only
57    a subset of the tables need to be loaded: the data for the ignored tables
58    is simply discarded.
59    
60  =back  =back
61    
# Line 59  Line 63 
63    
64  sub new {  sub new {
65      # Get the parameters.      # Get the parameters.
66      my ($class, $erdb, $relationName, $directory, $estimatedRows) = @_;      my ($class, $erdb, $relationName, $directory, $loadOnly, $ignore) = @_;
67      # Validate the directory name.      # Validate the directory name.
68      if (! -d $directory) {      if (! -d $directory) {
69          Confess("Load directory \"$directory\" not found.");          Confess("Load directory \"$directory\" not found.");
70      }      }
71      # Determine the name for this relation's load file.      # Determine the name for this relation's load file.
72      my $fileName = "$directory/$relationName.dtx";      my $fileName = "$directory/$relationName.dtx";
73      # Decide whether or not we should specify estimated rows.      # Declare the file handle variable.
74      my $rowEstimate = ($FIG_Config::estimate_rows ? $estimatedRows : undef);      my $fileHandle;
75      # Create the target table. If this is a pre-index DBMS, we      # Determine whether or not this is a simply keyed relation. For a simply keyed
76      # also create the indexes. If the table already exists,      # relation, we can determine at run time if it is pre-sorted, and if so, skip
77      # it will be dropped.      # the sort step.
78      $erdb->CreateTable($relationName, $FIG_Config::preIndex, $rowEstimate);      my $sortString = $erdb->SortNeeded($relationName);
79        # Get all of the key specifiers in the sort string.
80        my @specs = grep { $_ =~ /-k\S+/ } split /\s+/, $sortString;
81        # We are pre-sortable if the key is a single, non-numeric field at the beginning. If
82        # we are pre-sortable, we'll check each incoming key and skip the sort step if the
83        # keys are already in the correct order.
84        my $preSortable = (scalar(@specs) == 1 && $specs[0] eq "-k1,1");
85        # Check to see if this is a load-only, ignore, or a generate-and-load.
86        if ($ignore) {
87            Trace("Relation $relationName will be ignored.") if T(2);
88            $fileHandle = "";
89        } elsif ($loadOnly) {
90            Trace("Relation $relationName will be loaded from $fileName.") if T(2);
91            $fileHandle = "";
92        } else {
93            # Compute the file namefor this relation. We will build a file on
94            # disk and then sort it into the real file when we're done.
95            my $fileString = ">$fileName.tmp";
96      # Open the output file and remember its handle.      # Open the output file and remember its handle.
97      my $fileHandle = Open(undef, ">$fileName");          $fileHandle = Open(undef, $fileString);
98            Trace("Relation $relationName load file created.") if T(2);
99        }
100      # Create the $erload object.      # Create the $erload object.
101      my $retVal = {      my $retVal = {
102                    dbh => $erdb,                    dbh => $erdb,
# Line 83  Line 106 
106                    fileSize => 0,                    fileSize => 0,
107                    lineCount => 0,                    lineCount => 0,
108                    stats => Stats->new(),                    stats => Stats->new(),
109                    primary => $erdb->_IsPrimary($relationName)                    presorted => $preSortable,
110                      ignore => ($ignore ? 1 : 0),
111                      sortString => $sortString,
112                      presorted => $preSortable,
113                      lastKey => ""
114                   };                   };
115      # Bless and return it.      # Bless and return it.
116      bless $retVal, $class;      bless $retVal, $class;
117      return $retVal;      return $retVal;
118  }  }
119    
120    =head3 Ignore
121    
122        my $flag = $erload->Ignore;
123    
124    Return TRUE if we are ignoring this table, else FALSE.
125    
126    =cut
127    #: Return Type $;
128    sub Ignore {
129        # Get the parameters.
130        my ($self) = @_;
131        # Return the result.
132        return $self->{ignore};
133    }
134    
135  =head3 Put  =head3 Put
136    
137  C<< my  = $erload->Put($field1, $field2, ..., $fieldN); >>      my  = $erload->Put($field1, $field2, ..., $fieldN);
138    
139  Write a line of data to the load file. This may also cause the load file to be closed  Write a line of data to the load file. This may also cause the load file to be closed
140  and data read into the table.  and data read into the table.
# Line 110  Line 152 
152  =cut  =cut
153  #: Return Type ;  #: Return Type ;
154  sub Put {  sub Put {
155      # Get the ERDBLoad instance.      # Get the ERDBLoad instance and the field list.
156      my $self = shift @_;      my ($self, @rawFields) = @_;
157        # Only proceed if we're not ignoring.
158        if (! $self->{ignore}) {
159            # Convert the hash-string fields to their digested value.
160            $self->{dbh}->DigestFields($self->{relName}, \@rawFields);
161            # Insure the field values are okay.
162            my $truncates = $self->{dbh}->VerifyFields($self->{relName}, \@rawFields);
163      # Run through the list of field values, escaping them.      # Run through the list of field values, escaping them.
164      my @fields = map { Tracer::Escape($_) } @_;          my @fields = map { Tracer::Escape($_) } @rawFields;
     # If this is a primary relation, append the new-record field.  
     if ($self->{primary}) {  
         push @fields, '0';  
     }  
165      # Form a data line from the fields.      # Form a data line from the fields.
166      my $line = join("\t", @fields) . "\n";      my $line = join("\t", @fields) . "\n";
     # Determine how long this will make the load file.  
     my $lineLength = length $line;  
     if ($lineLength > (200000000 - $self->{fileSize})) {  
         # Here it would be too long, so we force a load.  
         $self->Flush();  
     }  
167      # Write the new record to the load file.      # Write the new record to the load file.
168      my $fh = $self->{fh};      my $fh = $self->{fh};
169      print $fh $line;      print $fh $line;
170            # Determine how long this will make the load file.
171            my $lineLength = length $line;
172            # Check to see if we're still pre-sorted.
173            if ($self->{presorted}) {
174                if ($fields[0] lt $self->{lastKey}) {
175                    # This key is out of order, so we're not pre-sorded any more.
176                    $self->{presorted} = 0;
177                } else {
178                    # We're still pre-sorted, so save this key.
179                    $self->{lastKey} = $fields[0];
180                }
181            }
182      # Update the statistics.      # Update the statistics.
183      $self->{fileSize} += $lineLength;      $self->{fileSize} += $lineLength;
184      $self->{lineCount} ++;      $self->{lineCount} ++;
185            $self->Add("lineOut");
186            if ($truncates > 0) {
187                $self->Add("truncated", $truncates);
188            }
189  }  }
190    }
191    
192    =head3 Add
193    
194  =head3 Flush      my  = $stats->Add($statName, $value);
195    
196  C<< $erload->Flush(); >>  Increment the specified statistic.
197    
198  Load all the data currently in the load file into the database. This clears the load  =over 4
199  file and re-opens it.  
200    =item statName
201    
202    Name of the statistic to increment.
203    
204    =item value (optional)
205    
206    Value by which to increment it. If omitted, C<1> is assumed.
207    
208    =back
209    
210  =cut  =cut
211  #: Return Type ;  #: Return Type ;
212  sub Flush {  sub Add {
213      # Get the parameters.      # Get the parameters.
214      my ($self) = @_;      my ($self, $statName, $value) = @_;
215      # Flush the data in the load file.      # Fix the value.
216      $self->_FlushData();      if (! defined $value) {
217      # Re-open the file so it can accept more data.          $value = 1;
218      $self->_ReOpen();      }
219        # Increment the statistic.
220        $self->{stats}->Add($statName, $value);
221  }  }
222    
223  =head3 Finish  =head3 Finish
224    
225  C<< my $stats = $erload->Finish(); >>      my $stats = $erload->Finish();
226    
227  Finish loading the table. This closes the load file and loads its contents into the database.  Finish loading the table. This closes and sorts the load file.
 It also creates the indexes if the DBMS uses post-indexing.  
228    
229  =over 4  =over 4
230    
# Line 173  Line 240 
240  sub Finish {  sub Finish {
241      # Get this object instance.      # Get this object instance.
242      my ($self) = @_;      my ($self) = @_;
243      # Flush out the data in the load file.      if ($self->{fh}) {
244      $self->_FlushData();          # Close the load file.
245      # If this is a post-index DBMS, create the indexes.          close $self->{fh};
246      if (! $FIG_Config::preIndex) {          # Get the ERDB object.
247          $self->{dbh}->CreateIndex($self->RelName);          my $erdb = $self->{dbh};
248            # Get the output file name.
249            my $fileName = $self->{fileName};
250            # Do we need a sort?
251            if ($self->{presorted}) {
252                # No, so just rename the file.
253                Trace("$fileName is pre-sorted.") if T(3);
254                unlink $fileName;
255                rename "$fileName.tmp", $fileName;
256            } else {
257                # Get the sort command for this relation.
258                my $sortCommand = $erdb->SortNeeded($self->{relName});
259                Trace("Sorting into $fileName with command: $sortCommand") if T(3);
260                # Set up a timer.
261                my $start = time();
262                # Execute the sort command and save the error output.
263                my @messages = `$sortCommand 2>&1 1>$fileName <$fileName.tmp`;
264                # Record the time spent
265                $self->{stats}->Add(sortTime => (time() - $start));
266                # If there was no error, delete the temp file.
267                if (! scalar(@messages)) {
268                    unlink "$fileName.tmp";
269                } else {
270                    # Here there was an error.
271                    Confess("Error messages from $sortCommand:\n" . join("\n", @messages));
272                }
273            }
274            # Tell the user we're done.
275            Trace("Load file $fileName created.") if T(3);
276      }      }
     # Delete the load file.  
     unlink $self->{fileName};  
277      # Return the statistics object.      # Return the statistics object.
278      return $self->{stats};      return $self->{stats};
279  }  }
280    
281  =head3 RelName  =head3 FinishAndLoad
282    
283  C<< my $name = $erload->RelName; >>      my $stats = $erload->FinishAndLoad();
284    
285  Name of the relation being loaded by this object.  Finish the load and load the table, returning the statistics.
286    
287  =cut  =cut
288    
289  sub RelName {  sub FinishAndLoad {
290      # Get the object instance.      # Get the parameters.
291      my ($self) = @_;      my ($self) = @_;
292      # Return the relation name.      # Finish the load file.
293      return $self->{relName};      my $retVal = $self->Finish();
294        # Load the table.
295        my $newStats = $self->LoadTable();
296        # Accumulate the stats.
297        $retVal->Accumulate($newStats);
298        # Return the result.
299        return $retVal;
300  }  }
301    
302  =head2 Internal Methods  =head3 RelName
   
 =head3 ReOpen  
303    
304  Re-open the load file.      my $name = $erload->RelName;
305    
306  This is an instance method.  Name of the relation being loaded by this object.
307    
308  =cut  =cut
309    
310  sub _ReOpen {  sub RelName {
311      # Get this instance.      # Get the object instance.
312      my ($self) = @_;      my ($self) = @_;
313      # Open the file with the current filehandle in truncate mode.      # Return the relation name.
314      Open($self->{fh}, ">" . $self->{fileName});      return $self->{relName};
     # Denote the file is empty.  
     $self->{fileSize} = 0;  
     $self->{lineCount} = 0;  
315  }  }
316    
317  =head3 FlushData  =head3 LoadTable
318    
319  Close the load file and load all its data into the table.      my $stats = $erload->LoadTable();
320    
321  This is an instance method.  Load the database table from the load file and return a statistics object.
322    
323  =cut  =cut
324    
325  sub _FlushData {  sub LoadTable {
326      # Get this instance.      # Get the parameters.
327      my ($self) = @_;      my ($self) = @_;
328      # Get the relation name.      # Get the database object, the file name, and the relation name.
329      my $relName = $self->RelName;      my $erdb = $self->{dbh};
330      Trace("Flushing data to table $relName.") if T(2);      my $fileName = $self->{fileName};
331      # Close the load file.      my $relName = $self->{relName};
332      close $self->{fh};      # Load the table. The third parameter indicates this is a drop and reload.
333      # We must use the load file to load the table. First, we get the DBKernel      my $retVal = $erdb->LoadTable($fileName, $relName, truncate => 1);
334      # handle and the statistics object.      # Return the result.
335      my $stats = $self->{stats};      return $retVal;
     my $dbh = $self->{dbh}->{_dbh};  
     # Begin a database transaction. This is not actually for integrity reasons; it  
     # speeds up the slow load process.  
     $dbh->begin_tran();  
     # Load the database table safely.  
     my $rv;  
     eval {  
         Trace("Loading file into relation $relName.") if T(3);  
         $rv = $dbh->load_table(file => $self->{fileName}, tbl => $relName);  
     };  
     # Check to see if we succeeded.  
     if (!defined $rv) {  
         # We've failed. Format a useful message. If we have an error message from  
         # EVAL, we use it.  
         my $msg = "Table load failed for $relName" . ($@ ? ": $@" : ".");  
         $stats->AddMessage($msg);  
         Trace($msg) if T(1);  
     } else {  
         # Here we successfully loaded the table. Trace the number of records loaded.  
         my $lineCount = $self->{lineCount};  
         my $byteCount = $self->{fileSize};  
         Trace("$lineCount records ($byteCount bytes) loaded into $relName.") if T(2);  
         # Accumulate the statistics.  
         $stats->Add("records", $lineCount);  
         $stats->Add("bytes", $byteCount);  
     }  
     # Close the database transaction.  
     $dbh->commit_tran();  
336  }  }
337    
338  1;  1;

Legend:
Removed from v.1.2  
changed lines
  Added in v.1.24

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3