EnsEMBL/IdMapping/BaseObject.pm untested

filter: Statementstmt 0.0% 0 / 150 Branchbran 0.0% 0 / 54 Conditioncond 0.0% 0 / 38 Subroutinesub 0.0% 0 / 15 Podpod 0.0% 0 / 9 totaltotal 0.0% 0 / 266 CC 28 SCAR 40.2
CC
28
Cov
0%
upload_file_into_table
156.0
dump_table_to_file
42.0
new
20.0
CRAP 55.6
1 =head1 LICENSE
2  
3 See the NOTICE file distributed with this work for additional information
4 regarding copyright ownership.
5  
6 Licensed under the Apache License, Version 2.0 (the "License");
7 you may not use this file except in compliance with the License.
8 You may obtain a copy of the License at
9  
10 http://www.apache.org/licenses/LICENSE-2.0
11  
12 Unless required by applicable law or agreed to in writing, software
13 distributed under the License is distributed on an "AS IS" BASIS,
14 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 See the License for the specific language governing permissions and
16 limitations under the License.
17  
18 =cut
19  
20  
21 =head1 CONTACT
22  
23 Please email comments or questions to the public Ensembl
24 developers list at <http://lists.ensembl.org/mailman/listinfo/dev>.
25  
26 Questions may also be sent to the Ensembl help desk at
27 <http://www.ensembl.org/Help/Contact>.
28  
29 =cut
30  
31 =head1 NAME
32  
33 Bio::EnsEMBL::IdMapping::BaseObject - base object for IdMapping objects
34  
35 =head1 SYNOPSIS
36  
37 # this object isn't instantiated directly but rather extended
38 use Bio::EnsEMBL::IdMapping::BaseObject;
39 our @ISA = qw(Bio::EnsEMBL::IdMapping::BaseObject);
40  
41 =head1 DESCRIPTION
42  
43 This is the base object for some of the objects used in the IdMapping
44 application. An object that extends BaseObject will have a ConfParser,
45 Logger and Cache object. BaseObject also implements some useful utility
46 functions related to file and db access.
47  
48 This isn't very clean OO design but it's efficient and easy to use...
49  
50 =head1 METHODS
51  
52 new
53 get_filehandle
54 file_exists
55 fetch_value_from_db
56 dump_table_to_file
57 upload_file_into_table
58 logger
59 conf
60 cache
61  
62 =cut
63  
64  
65 package Bio::EnsEMBL::IdMapping::BaseObject;
66 $Bio::EnsEMBL::IdMapping::BaseObject::VERSION = '114.0.0_50'; # TRIAL
67 $Bio::EnsEMBL::IdMapping::BaseObject::VERSION = '114.0.050';
68 use strict;
69 use warnings;
70 no warnings 'uninitialized';
71  
72 use Bio::EnsEMBL::Utils::Exception qw(throw warning);
73 use Bio::EnsEMBL::Utils::Argument qw(rearrange);
74 use Bio::EnsEMBL::Utils::ScriptUtils qw(path_append);
75  
76  
77 =head2 new
78  
79 Arg [LOGGER]: Bio::EnsEMBL::Utils::Logger $logger - a logger object
80 Arg [CONF] : Bio::EnsEMBL::Utils::ConfParser $conf - a configuration object
81 Arg [CACHE] : Bio::EnsEMBL::IdMapping::Cache $cache - a cache object
82 Example : my $object = Bio::EnsEMBL::IdMapping::BaseObjectSubclass->new(
83 -LOGGER => $logger,
84 -CONF => $conf,
85 -CACHE => $cache
86 );
87 Description : Constructor
88 Return type : implementing subclass type
89 Exceptions : thrown on wrong or missing arguments
90 Caller : general
91 Status : At Risk
92 : under development
93  
94 =cut
95  
96 sub new {
97 my $caller = shift;
98 my $class = ref($caller) || $caller;
99  
100 my ($logger, $conf, $cache) = rearrange(['LOGGER', 'CONF', 'CACHE'], @_);
101  
102 unless ($logger and ref($logger) and
103 $logger->isa('Bio::EnsEMBL::Utils::Logger')) {
104 throw("You must provide a Bio::EnsEMBL::Utils::Logger for logging.");
105 }
106
107 unless ($conf and ref($conf) and
108 $conf->isa('Bio::EnsEMBL::Utils::ConfParser')) {
109 throw("You must provide configuration as a Bio::EnsEMBL::Utils::ConfParser object.");
110 }
111
112 unless ($cache and ref($cache) and
113 $cache->isa('Bio::EnsEMBL::IdMapping::Cache')) {
114 throw("You must provide configuration as a Bio::EnsEMBL::IdMapping::Cache object.");
115 }
116
117 my $self = {};
118 bless ($self, $class);
119  
120 # initialise
121 $self->logger($logger);
122 $self->conf($conf);
123 $self->cache($cache);
124
125 return $self;
126 }
127  
128  
129 =head2 get_filehandle
130  
131 Arg[1] : String $filename - filename for filehandle
132 Arg[2] : String $path_append - append subdirectory name to basedir
133 Arg[3] : String $mode - filehandle mode (<|>|>>)
134 Example : my $fh = $object->get_filehandle('mapping_stats.txt', 'stats',
135 '>');
136 print $fh "Stats:\n";
137 Description : Returns a filehandle to a file for reading or writing. The file
138 is qualified with the basedir defined in the configuration and
139 an optional subdirectory name.
140 Return type : filehandle
141 Exceptions : thrown on missing filename
142 Caller : general
143 Status : At Risk
144 : under development
145  
146 =cut
147  
148 sub get_filehandle {
149 my $self = shift;
150 my $filename = shift;
151 my $path_append = shift;
152 my $mode = shift;
153  
154 throw("Need a filename for this filehandle.") unless (defined($filename));
155
156 my $path = $self->conf->param('basedir');
157 $path = path_append($path, $path_append) if (defined($path_append));
158  
159 $mode ||= '>';
160
161 open(my $fh, $mode, "$path/$filename") or
162 throw("Unable to open $path/$filename: $!");
163  
164 return $fh;
165 }
166  
167  
168 =head2 file_exists
169  
170 Arg[1] : String $filename - filename to test
171 Arg[2] : Boolean $path_append - turn on pre-pending of basedir
172 Example : unless ($object->file_exists('gene_mappings.ser', 1)) {
173 $object->do_gene_mapping;
174 }
175 Description : Tests if a file exists and has non-zero size.
176 Return type : Boolean
177 Exceptions : none
178 Caller : general
179 Status : At Risk
180 : under development
181  
182 =cut
183  
184 sub file_exists {
185 my $self = shift;
186 my $filename = shift;
187 my $path_append = shift;
188  
189 my $path = $self->conf->param('basedir');
190 $path = path_append($path, $path_append) if (defined($path_append));
191  
192 return (-s "$path/$filename");
193 }
194  
195  
196 =head2 fetch_value_from_db
197  
198 Arg[1] : DBI::db $dbh - a DBI database handle
199 Arg[2] : String $sql - SQL statement to execute
200 Example : my $num_genes = $object->fetch_value_from_db($dbh,
201 'SELECT count(*) FROM gene');
202 Description : Executes an SQL statement on a db handle and returns the first
203 column of the first row returned. Useful for queries returning a
204 single value, like table counts.
205 Return type : Return type of SQL statement
206 Exceptions : thrown on wrong or missing arguments
207 Caller : general
208 Status : At Risk
209 : under development
210  
211 =cut
212  
213 sub fetch_value_from_db {
214 my $self = shift;
215 my $dbh = shift;
216 my $sql = shift;
217  
218 throw("Need a db handle.") unless ($dbh and $dbh->isa('DBI::db'));
219 throw("Need an SQL query to execute.") unless ($sql);
220  
221 my $sth = $dbh->prepare($sql);
222 $sth->execute;
223 my ($retval) = $sth->fetchrow_array;
224  
225 return $retval;
226 }
227  
228  
229 =head2 dump_table_to_file
230  
231 Arg[1] : String $dbtype - db type (source|target)
232 Arg[2] : String $table - name of table to dump
233 Arg[3] : String $filename - name of dump file
234 Arg[4] : Boolean $check_existing - turn on test for existing dump
235 Example : my $rows_dumped = $object->dump_table_to_file('source',
236 'stable_id_event', 'stable_id_event_existing.txt');
237 Description : Dumps the contents of a db table to a tab-delimited file. The
238 dump file will be written to a subdirectory called 'tables'
239 under the basedir from your configuration.
240 Return type : Int - the number of rows dumped
241 Exceptions : thrown on wrong or missing arguments
242 Caller : general
243 Status : At Risk
244 : under development
245  
246 =cut
247  
248 sub dump_table_to_file {
249 my $self = shift;
250 my $dbtype = shift;
251 my $table = shift;
252 my $filename = shift;
253 my $check_existing = shift;
254  
255 # argument check
256 unless (($dbtype eq 'source') or ($dbtype eq 'target')) {
257 throw("Missing or unknown db type: $dbtype.");
258 }
259 throw("Need a table name.") unless ($table);
260 throw("Need a filename.") unless ($filename);
261  
262 # conditionally check if table was already dumped
263 if ($check_existing and $self->file_exists($filename, 'tables')) {
264 $self->logger->info("$filename exists, won't dump again.\n");
265 return 0;
266 }
267
268 my $fh = $self->get_filehandle($filename, 'tables');
269  
270 my $dba = $self->cache->get_DBAdaptor($dbtype);
271 my $dbh = $dba->dbc->db_handle;
272 my $sth = $dbh->prepare("SELECT * FROM $table");
273 $sth->execute;
274  
275 my $i = 0;
276  
277 while (my @row = $sth->fetchrow_array) {
278 $i++;
279  
280 # use '\N' for NULL values
281 for (my $j = 0; $j < scalar(@row); $j++) {
282 $row[$j] = '\N' unless (defined($row[$j]));
283 }
284
285 print $fh join("\t", @row);
286 print $fh "\n";
287 }
288  
289 $sth->finish;
290
291 return $i;
292 }
293  
294  
295 =head2 upload_file_into_table
296  
297 Arg[1] : String $dbtype - db type (source|target)
298 Arg[2] : String $table - name of table to upload the data to
299 Arg[3] : String $filename - name of dump file
300 Arg[4] : Boolean $no_check_empty - don't check if table is empty
301 Example : my $rows_uploaded = $object->upload_file_into_table('target',
302 'stable_id_event', 'stable_id_event_new.txt');
303 Description : Uploads a tab-delimited data file into a db table. The data file
304 will be taken from a subdirectory 'tables' under your configured
305 basedir. If the db table isn't empty and $no_check_empty isn't
306 set, no data is uploaded (and a warning is issued).
307 Return type : Int - the number of rows uploaded
308 Exceptions : thrown on wrong or missing arguments
309 Caller : general
310 Status : At Risk
311 : under development
312  
313 =cut
314  
315 sub upload_file_into_table {
316 my $self = shift;
317 my $dbtype = shift;
318 my $table = shift;
319 my $filename = shift;
320 my $no_check_empty = shift;
321  
322 # argument check
323 unless ( ( $dbtype eq 'source' ) or ( $dbtype eq 'target' ) ) {
324 throw("Missing or unknown db type: $dbtype.");
325 }
326 throw("Need a table name.") unless ($table);
327 throw("Need a filename.") unless ($filename);
328  
329 # sanity check for dry run
330 if ( $self->conf->param('dry_run') ) {
331 $self->logger->warning(
332 "dry_run - skipping db upload for $filename.\n");
333 return;
334 }
335  
336 my $file =
337 join( '/', $self->conf->param('basedir'), 'tables', $filename );
338 my $r = 0;
339  
340 if ( -s $file ) {
341  
342 $self->logger->debug( "$file -> $table\n", 1 );
343  
344 my $dba = $self->cache->get_DBAdaptor($dbtype);
345 my $dbh = $dba->dbc->db_handle;
346  
347 my $idtable = 0;
348 if ( $table =~ /^([^_]+)_stable_id/ ) {
349 # This is a stable_id table we're working with.
350 $idtable = 1;
351 $table = $1;
352 }
353  
354 # check table is empty
355 my ( $sql, $sth );
356 unless ($no_check_empty) {
357 if ($idtable) {
358 $sql =
359 qq(SELECT count(*) FROM $table WHERE stable_id IS NOT NULL);
360 }
361 else {
362 $sql = qq(SELECT count(*) FROM $table);
363 }
364 $sth = $dbh->prepare($sql);
365 $sth->execute;
366 my ($c) = $sth->fetchrow_array;
367 $sth->finish;
368  
369 if ( $c > 0 ) {
370 if ($idtable) {
371 $self->logger->warning(
372 "Table $table contains $c stable IDs.\n",
373 1 );
374 }
375 else {
376 $self->logger->warning(
377 "Table $table not empty: found $c entries.\n",
378 1 );
379 }
380 $self->logger->info( "Data not uploaded!\n", 1 );
381 return $r;
382 }
383 } ## end unless ($no_check_empty)
384  
385 # now upload the data
386 if ($idtable) {
387 # Create a temporary table, upload the data into it, and then
388 # update the main table.
389 $dbh->do(
390 qq( CREATE TABLE stable_id_$$ ( object_id INTEGER UNSIGNED,
391 stable_id VARCHAR(255),
392 version SMALLINT UNSIGNED,
393 created_date DATETIME,
394 modified_date DATETIME,
395 PRIMARY KEY(object_id) ) )
396 );
397  
398 $dbh->do(
399 qq(LOAD DATA LOCAL INFILE '$file' INTO TABLE stable_id_$$));
400  
401 $dbh->do(
402 qq(
403 UPDATE $table, stable_id_$$
404 SET $table.stable_id=stable_id_$$.stable_id,
405 $table.version=stable_id_$$.version,
406 $table.created_date=stable_id_$$.created_date,
407 $table.modified_date=stable_id_$$.modified_date
408 WHERE $table.${table}_id = stable_id_$$.object_id )
409 );
410  
411 $dbh->do(qq(DROP TABLE stable_id_$$));
412 } ## end if ($idtable)
413 else {
414 $dbh->do(qq(LOAD DATA LOCAL INFILE '$file' INTO TABLE $table));
415 }
416 $dbh->do(qq(OPTIMIZE TABLE $table));
417  
418 } ## end if ( -s $file )
419 else {
420 $self->logger->warning( "No data found in file $filename.\n", 1 );
421 }
422  
423 return $r;
424 } ## end sub upload_file_into_table
425  
426  
427 =head2 logger
428  
429 Arg[1] : (optional) Bio::EnsEMBL::Utils::Logger - the logger to set
430 Example : $object->logger->info("Starting ID mapping.\n");
431 Description : Getter/setter for logger object
432 Return type : Bio::EnsEMBL::Utils::Logger
433 Exceptions : none
434 Caller : constructor
435 Status : At Risk
436 : under development
437  
438 =cut
439  
440 sub logger {
441 my $self = shift;
442 $self->{'_logger'} = shift if (@_);
443 return $self->{'_logger'};
444 }
445  
446  
447 =head2 conf
448  
449 Arg[1] : (optional) Bio::EnsEMBL::Utils::ConfParser - the configuration
450 to set
451 Example : my $basedir = $object->conf->param('basedir');
452 Description : Getter/setter for configuration object
453 Return type : Bio::EnsEMBL::Utils::ConfParser
454 Exceptions : none
455 Caller : constructor
456 Status : At Risk
457 : under development
458  
459 =cut
460  
461 sub conf {
462 my $self = shift;
463 $self->{'_conf'} = shift if (@_);
464 return $self->{'_conf'};
465 }
466  
467  
468 =head2 cache
469  
470 Arg[1] : (optional) Bio::EnsEMBL::IdMapping::Cache - the cache to set
471 Example : $object->cache->read_from_file('source');
472 Description : Getter/setter for cache object
473 Return type : Bio::EnsEMBL::IdMapping::Cache
474 Exceptions : none
475 Caller : constructor
476 Status : At Risk
477 : under development
478  
479 =cut
480  
481 sub cache {
482 my $self = shift;
483 $self->{'_cache'} = shift if (@_);
484 return $self->{'_cache'};
485 }
486  
487  
488 1;
489