BlastAdaptor.pm 32.2 KB
Newer Older
1 2 3 4 5 6 7
# Let the code begin...
package Bio::EnsEMBL::External::BlastAdaptor;

use strict;
use DBI;
use Storable qw(freeze thaw);
use Data::Dumper qw( Dumper );
8
use Time::Local;
9 10 11

use vars qw(@ISA);

Will Spooner's avatar
Will Spooner committed
12 13
use Bio::EnsEMBL::DBSQL::BaseAdaptor;
use Bio::EnsEMBL::DBSQL::DBConnection;
14
use Bio::Search::HSP::EnsemblHSP; # This is a web module
15

Will Spooner's avatar
Will Spooner committed
16
@ISA = qw( Bio::EnsEMBL::DBSQL::BaseAdaptor );
Ian Longden's avatar
Ian Longden committed
17
#@ISA = qw( Bio::EnsEMBL::DBSQL::DBAdaptor );
18

19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139

#----------------------------------------------------------------------
# Define SQL

#--- CREATE TABLES ---
our $SQL_CREATE_TICKET = "
CREATE TABLE blast_ticket (
  ticket_id int(10) unsigned NOT NULL auto_increment,
  create_time datetime NOT NULL default '0000-00-00 00:00:00',
  update_time datetime NOT NULL default '0000-00-00 00:00:00',
  ticket varchar(32) NOT NULL default '',
  status enum('CURRENT','DELETED') NOT NULL default 'CURRENT',
  object longblob,
  PRIMARY KEY  (ticket_id),
  UNIQUE KEY ticket (ticket),
  KEY create_time (create_time),
  KEY update_time (update_time)
) TYPE=MyISAM";

our $SQL_CREATE_TABLE_LOG = "
CREATE TABLE blast_table_log (
  table_id int(10) unsigned NOT NULL auto_increment,
  table_name varchar(32),
  table_type enum('TICKET','RESULT','HIT','HSP') default NULL,
  table_status enum('CURRENT','FILLED','DELETED') default NULL,
  use_date date default NULL,
  create_time datetime default NULL,
  delete_time datetime default NULL,
  num_objects int(10) default NULL,
  PRIMARY KEY  (table_id),
  KEY table_name (table_name),
  KEY table_type (table_type),
  KEY use_date (use_date),
  KEY table_status (table_status)
) TYPE=MyISAM";


our $SQL_CREATE_DAILY_RESULT = "
CREATE TABLE %s (
  result_id int(10) unsigned NOT NULL auto_increment,
  ticket varchar(32) default NULL,
  object longblob,
  PRIMARY KEY  (result_id),
  KEY ticket (ticket)
) TYPE=MyISAM";

our $SQL_CREATE_DAILY_HIT = "
CREATE TABLE %s (
  hit_id int(10) unsigned NOT NULL auto_increment,
  ticket varchar(32) default NULL,
  object longblob,
  PRIMARY KEY  (hit_id),
  KEY ticket (ticket)
) TYPE=MyISAM";

our $SQL_CREATE_DAILY_HSP = "
CREATE TABLE %s (
  hsp_id int(10) unsigned NOT NULL auto_increment,
  ticket varchar(32) default NULL,
  object longblob,
  chr_name varchar(32) default NULL,
  chr_start int(10) unsigned default NULL,
  chr_end int(10) unsigned default NULL,
  PRIMARY KEY  (hsp_id),
  KEY ticket (ticket)
) TYPE=MyISAM MAX_ROWS=705032704 AVG_ROW_LENGTH=4000";

#--- TABLE LOG ---
our $SQL_SELECT_TABLE_LOG_CURRENT = "
SELECT   use_date
FROM     blast_table_log
WHERE    table_type   = ?
AND      table_status = 'CURRENT'
ORDER BY use_date DESC";

our $SQL_TABLE_LOG_INSERT = "
INSERT into blast_table_log 
       ( table_name, table_status, table_type, use_date, create_time)
VALUES ( ?, ?, ?, ?, NOW() )";

our $SQL_TABLE_LOG_UPDATE = "
UPDATE blast_table_log
SET    table_status = ?,
       delete_time  = ?,
       num_objects  = ?
WHERE  table_name   = ?";

#--- TICKETS ---

our $SQL_SEARCH_MULTI_STORE = "
INSERT INTO blast_ticket ( create_time, update_time, object, ticket )
VALUES                   ( NOW(), NOW(), ? , ? )";

our $SQL_SEARCH_MULTI_UPDATE = "
UPDATE blast_ticket
SET    object      = ?,
       update_time = NOW()
WHERE  ticket      = ?";

our $SQL_SEARCH_MULTI_RETRIEVE = "
SELECT object
FROM   blast_ticket
WHERE  ticket = ? ";

#--- RESULTS ---

our $SQL_RESULT_STORE = "
INSERT INTO blast_result%s ( object, ticket )
VALUES                   ( ? , ? )";

our $SQL_RESULT_UPDATE = "
UPDATE  blast_result%s
SET     object = ?,
        ticket = ?
WHERE   result_id = ?";

our $SQL_RESULT_RETRIEVE = "
SELECT object
FROM   blast_result%s
WHERE  result_id = ? ";

James Smith's avatar
James Smith committed
140 141 142 143 144
our $SQL_RESULT_RETRIEVE_TICKET = "
SELECT object
FROM   blast_result%s
WHERE  ticket = ? ";

145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
#--- HITS ---

our $SQL_HIT_STORE = "
INSERT INTO blast_hit%s ( object, ticket )
VALUES                  ( ? , ? )";

our $SQL_HIT_UPDATE = "
UPDATE  blast_hit%s
SET     object = ?,
        ticket = ?
WHERE   hit_id = ?";

our $SQL_HIT_RETRIEVE = "
SELECT object
FROM   blast_hit%s
WHERE  hit_id = ? ";

#--- HSPS ---

our $SQL_HSP_STORE = "
INSERT INTO blast_hsp%s ( object, ticket, chr_name, chr_start, chr_end )
VALUES                  ( ? , ? , ? , ? , ? )";

our $SQL_HSP_UPDATE = "
UPDATE  blast_hsp%s
SET     object    = ?,
        ticket    = ?,
        chr_name  = ?,
        chr_start = ?,
        chr_end   = ?
WHERE   hsp_id    = ?";

our $SQL_HSP_RETRIEVE = "
SELECT object
FROM   blast_hsp%s
WHERE  hsp_id = ? ";

182 183 184 185 186 187 188
our $SQL_HSP_REMOVE = "
UPDATE  blast_hsp%s
SET     chr_name  = NULL,
        chr_start = NULL,
        chr_end   = NULL
WHERE   hsp_id    = ?";

189

Ian Longden's avatar
Ian Longden committed
190 191 192 193 194 195 196 197 198 199 200 201 202 203
#=head2 new
# 
#  Arg [1]   :
#  Function  :
#  Returntype:
#  Exceptions:
#  Caller    :
#  Example   :
# 
#=cut
#                                                                           
#
sub new {
  my $caller = shift;
Web Admin's avatar
Web Admin committed
204
#warn "DB - @_";
Ian Longden's avatar
Ian Longden committed
205 206
  my $connection = Bio::EnsEMBL::DBSQL::DBConnection->new(@_);
  my $self = $caller->SUPER::new($connection);
Web Admin's avatar
Web Admin committed
207
  $self->{'disconnect_flag'} = 1;
Ian Longden's avatar
Ian Longden committed
208 209 210
  return $self;
}
 
Ian Longden's avatar
Ian Longden committed
211 212 213 214

sub new_fast{
  my ($caller,$connection) = @_;
  my $self = $caller->SUPER::new($connection);
Web Admin's avatar
Web Admin committed
215
  $self->{'disconnect_flag'} = 1;
Ian Longden's avatar
Ian Longden committed
216 217 218
  return $self;
}

219 220
#----------------------------------------------------------------------

Ian Longden's avatar
Ian Longden committed
221 222 223 224 225
sub species {
  my ($self, $arg ) = @_;
  ( defined $arg ) &&
    ( $self->{_species} = $arg );
  $self->{_species};
226 227
}

228 229
#----------------------------------------------------------------------

230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
=head2 ticket

  Arg [1]   : string ticket (optional)
  Function  : Get/get the blast ticket attribute
  Returntype: string ticket
  Exceptions: 
  Caller    : 
  Example   : 

=cut

sub ticket{
  my $key = "_ticket";
  my $self = shift;
  if( @_ ){ $self->{$key} = shift }
  return $self->{$key};
}

#----------------------------------------------------------------------

250 251 252 253 254 255 256 257 258 259 260 261 262 263
=head2 store

  Arg [1]   : 
  Function  : 
  Returntype: 
  Exceptions: 
  Caller    : 
  Example   : 

=cut

sub store {
  my $self = shift;
  my $obj = shift;
Web Admin's avatar
Web Admin committed
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289
  my $ret_value = undef;
  if( $obj->isa("Bio::Tools::Run::SearchMulti") ) {
    $ret_value = $self->store_search_multi( $obj, @_ );
    warn "Just stored as Bio::Tools::Run::SearchMulti";
  } elsif( $obj->isa( "Bio::Search::Result::ResultI" ) ) {
    $ret_value = $self->store_result(       $obj, @_ );
    warn "Just stored as Bio::Tools::Result::ResultI";
  } elsif( $obj->isa( "Bio::Search::Hit::HitI" ) ) {
    $ret_value = $self->store_hit(       $obj, @_ );
    warn "Just stored as Bio::Tools::Hit::HitI";
  } elsif( $obj->isa( "Bio::Search::HSP::HSPI" ) ) {
    $ret_value = $self->store_hsp(       $obj, @_ );
    warn "Just stored as Bio::Tools::HSP::HSPI";
  } else {
    warn "DID NOT STORE  ".ref($obj);
    $self->throw( "Do not know how to store objects of type ".ref($obj) );
    return undef;
  }
  if( $self->{'disconnect_flag'} ) {
    warn "HERE WE ARE DISCONNECTING....";
    $self->dbc->db_handle->disconnect();
    $self->dbc->connected(0);
    warn "AND  WE ARE RECONNECTING....";
    $self->dbc->connect();
  }
  return $ret_value;
290 291
}

Web Admin's avatar
Web Admin committed
292 293 294 295 296 297 298 299
sub prepare {
  my $self = shift;
#  warn( "==> ", $self->dbc->dbname, " ", $self->dbc->db_handle );
#warn @_;
  my $T = $self->SUPER::prepare( @_ );
#  warn( "<== ", $self->dbc->dbname, " ", $self->dbc->db_handle );
  return $T;
}
300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
#----------------------------------------------------------------------

=head2 retrieve

  Arg [1]   : 
  Function  : 
  Returntype: 
  Exceptions: 
  Caller    : 
  Example   : 

=cut

sub retrieve {
  my $self = shift;
  my $caller = shift;
James Smith's avatar
James Smith committed
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
  my %METHODS = qw(
    Bio::Tools::Run::EnsemblSearchMulti search_multi
    Bio::Search::Result::ResultI        result
    Bio::Search::Hit::HitI              hit
    Bio::Search::HSP::HSPI              hsp
  );
  foreach my $type (keys %METHODS) {
    if( UNIVERSAL::isa($caller, $type) ) {
      my $method = "retrieve_$METHODS{$type}";
      return $self->$method( @_ );
    }
  }
  return undef if UNIVERSAL::isa($caller,'Bio::Tools::Run::Search');
  $self->throw( "Do not know how to retrieve objects of type ". 
                ( ref($caller)? ref($caller) : $caller ) );
331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348
}

#----------------------------------------------------------------------

=head2 remove

  Arg [1]   : 
  Function  : TODO: implement remove functions
  Returntype: 
  Exceptions: 
  Caller    : 
  Example   : 

=cut

sub remove {
  my $self = shift;
  my $obj = shift;
Web Admin's avatar
Web Admin committed
349 350 351 352 353
  return 1 if $obj->isa("Bio::Tools::Run::EnsemblSearchMulti"); # Nothing to do here { return $self->remove_search_multi( @_ ); }
  return 1 if $obj->isa("Bio::Search::Result::ResultI");        # Nothing to do here { return $self->remove_result( @_ ); }
  return 1 if $obj->isa("Bio::Search::Hit::HitI");              # Nothing to do here { return $self->remove_hit( @_ ); }
  return $self->remove_hsp( $obj ) if $obj->isa("Bio::Search::HSP::HSPI");
  return undef(); # Do not know how to remove objects of this type 
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373
}
#----------------------------------------------------------------------
=head2 store_search_multi

  Arg [1]   : Bio::Tools::Run::EnsemblSearchMulti obj
  Function  : Stores the ensembl SearchMulti container object in the database
  Returntype: scalar (token)
  Exceptions: 
  Caller    : 
  Example   : my $container_token = $blast_adpt->store_ticket( $container );

=cut

sub store_search_multi{
  my $self         = shift;
  my $search_multi = shift || 
    $self->throw( "Need a Bio::Tools::Run::EnsemblSearchMulti obj" );

  my $frozen = shift || $search_multi->serialise;

Ian Longden's avatar
Ian Longden committed
374
  my $dbh  = $self->dbc->db_handle;
Web Admin's avatar
Web Admin committed
375
  my $ticket  = $search_multi->token || $self->throw( "Bio::Tools::Run::EnsemblSearchMulti obj has no ticket" );
376

Web Admin's avatar
Web Admin committed
377
  my $sth = $self->prepare( $SQL_SEARCH_MULTI_RETRIEVE );
378 379 380 381
  my $rv = $sth->execute( $ticket ) ||  $self->throw( $sth->errstr );
  $sth->finish;

  if( $rv < 1 ){ # Insert (do first to minimise risk of race)
Web Admin's avatar
Web Admin committed
382
    my $sth = $self->prepare( $SQL_SEARCH_MULTI_STORE );
383 384 385 386 387
    $sth->execute( $frozen, $ticket ) || $self->throw( $sth->errstr );
    #$search_multi->token( $self->dbh->{mysql_insertid} );
    $sth->finish;
  }
  else{ # Update
Web Admin's avatar
Web Admin committed
388
    my $sth = $self->prepare( $SQL_SEARCH_MULTI_UPDATE );
389 390 391
    $sth->execute( $frozen, $ticket ) || $self->throw( $sth->errstr );
    $sth->finish;
  }
Web Admin's avatar
Web Admin committed
392
  $sth = $self->prepare('show tables'); $sth->execute(); $sth->finish;
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412
  return $search_multi->token();
}

#----------------------------------------------------------------------

=head2 retrieve_search_multi

  Arg [1]   : 
  Function  : 
  Returntype: 
  Exceptions: 
  Caller    : 
  Example   : 

=cut

sub retrieve_search_multi {
  my $self   = shift;
  my $ticket = shift || $self->throw( "Need an EnsemblSearchMulti ticket" );  

Ian Longden's avatar
Ian Longden committed
413
  my $dbh  = $self->dbc->db_handle;
Web Admin's avatar
Web Admin committed
414 415 416 417
warn $dbh;
warn $SQL_SEARCH_MULTI_RETRIEVE;
  my $sth = $self->prepare( $SQL_SEARCH_MULTI_RETRIEVE );
warn $sth;
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
  my $rv  = $sth->execute( $ticket ) || $self->throw( $sth->errstr );
  if( $rv < 1 ){ $self->throw( "Token $ticket not found" ) }
  my ( $frozen ) = $sth->fetchrow_array;
  $frozen || $self->throw( "Object from ticket $ticket is empty" );
  $sth->finish;
  return $frozen;
}



#----------------------------------------------------------------------
=head2 store_result

  Arg [1]   : Bio::Search::Result::EnsemblResult obj
  Function  : Stores the ensembl Result in the database
  Returntype: scalar (token)
  Exceptions: 
  Caller    : 
  Example   : my $result_token = $blast_adpt->store_result( $result );

=cut

sub store_result{
Web Admin's avatar
Web Admin committed
441 442
  my $self   = shift;
  my $res    = shift || $self->throw( "Need a Bio::Search::Result::EnsemblResult obj" );
443
  my $frozen = shift || $res->serialise;
Web Admin's avatar
Web Admin committed
444 445
  my $dbh    = $self->dbc->db_handle;
  my $sth;
446 447

  my ( $id, $use_date ) = split( '!!', $res->token || '' );
Web Admin's avatar
Web Admin committed
448 449 450
  $use_date ||= $self->use_date( 'RESULT' );
          #my $ticket = $res->group_ticket || warn( "Result $id has no ticket" );
  my $ticket  = $self->ticket || warn("Result $id BlastAdaptor has no ticket");
451 452 453

  my $rv = 0;
  if( $id ){
Web Admin's avatar
Web Admin committed
454
    $sth = $self->prepare( sprintf $SQL_RESULT_RETRIEVE, $use_date );
455 456 457
    $rv = $sth->execute( $id ) ||  $self->throw( $sth->errstr );
    $sth->finish;
  }
Web Admin's avatar
Web Admin committed
458 459
  if( $rv < 1 ){ # We have no result with this token string Insert
    my $use_date = $res->use_date() || $res->use_date($self->use_date('RESULT'));
Web Admin's avatar
Web Admin committed
460
    $sth = $self->prepare( sprintf $SQL_RESULT_STORE, $use_date );
461 462 463 464
    $sth->execute( $frozen, $ticket ) || $self->throw( $sth->errstr );
    my $id = $dbh->{mysql_insertid};
    $res->token( join( '!!', $id, $use_date ) );
    $sth->finish;
Web Admin's avatar
Web Admin committed
465
  } else {  # Update
Web Admin's avatar
Web Admin committed
466
    $sth = $self->prepare( sprintf $SQL_RESULT_UPDATE, $use_date );
467 468 469 470 471 472
    $sth->execute( $frozen, $ticket, $id ) || $self->throw( $sth->errstr );
    $sth->finish;
  }
  return $res->token();
}

James Smith's avatar
James Smith committed
473 474 475 476 477 478 479 480 481 482 483 484 485 486
sub store_result_2{
  my $self   = shift;
  my $res    = shift || $self->throw( "Need a Bio::Search::Result::EnsemblResult obj" );
  my $frozen = shift || $res->serialise;
  my $dbh    = $self->dbc->db_handle;
  my $sth;

  my ( $id, $use_date ) = split( '!!', $res->token || '' );
  $use_date ||= $self->use_date( 'RESULT' );
          #my $ticket = $res->group_ticket || warn( "Result $id has no ticket" );
  my $ticket  = $self->ticket || warn("Result $id BlastAdaptor has no ticket");

  my $rv = 0;
  if( $ticket ){
Web Admin's avatar
Web Admin committed
487
    $sth = $self->prepare( sprintf $SQL_RESULT_RETRIEVE_TICKET, $use_date );
James Smith's avatar
James Smith committed
488 489 490 491
    $rv = $sth->execute( $ticket ) ||  $self->throw( $sth->errstr );
    $sth->finish;
  } 
  if( !$rv && $id ){
Web Admin's avatar
Web Admin committed
492
    $sth = $self->prepare( sprintf $SQL_RESULT_RETRIEVE, $use_date );
James Smith's avatar
James Smith committed
493 494 495 496 497
    $rv = $sth->execute( $id ) ||  $self->throw( $sth->errstr );
    $sth->finish;
  }
  if( $rv < 1 ){ # We have no result with this token string Insert
    my $use_date = $res->use_date() || $res->use_date($self->use_date('RESULT'));
Web Admin's avatar
Web Admin committed
498
    $sth = $self->prepare( sprintf $SQL_RESULT_STORE, $use_date );
James Smith's avatar
James Smith committed
499 500 501 502 503
    $sth->execute( $frozen, $ticket ) || $self->throw( $sth->errstr );
    my $id = $dbh->{mysql_insertid};
    $res->token( join( '!!', $id, $use_date ) );
    $sth->finish;
  } else {  # Update
Web Admin's avatar
Web Admin committed
504
    $sth = $self->prepare( sprintf $SQL_RESULT_UPDATE, $use_date );
James Smith's avatar
James Smith committed
505 506 507 508 509 510
    $sth->execute( $frozen, $ticket, $id ) || $self->throw( $sth->errstr );
    $sth->finish;
  }
  return $res->token();
}

511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529
#----------------------------------------------------------------------

=head2 retrieve_result

  Arg [1]   : 
  Function  : 
  Returntype: 
  Exceptions: 
  Caller    : 
  Example   : 

=cut

sub retrieve_result{
  my $self = shift;
  my $token  = shift || $self->throw( "Need a Hit token" );
  my ( $id, $use_date ) = split( '!!',$token);
  $use_date ||= '';

Ian Longden's avatar
Ian Longden committed
530
  my $dbh  = $self->dbc->db_handle;
Web Admin's avatar
Web Admin committed
531
  my $sth = $self->prepare( sprintf $SQL_RESULT_RETRIEVE, $use_date );
532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557
  my $rv  = $sth->execute( $id ) || $self->throw( $sth->errstr );
  if( $rv < 1 ){ $self->throw( "Token $id not found" ) }
  my ( $frozen ) = $sth->fetchrow_array;
  $frozen || $self->throw( "Object from result $id is empty" );
  $sth->finish;
  return $frozen;
}

#----------------------------------------------------------------------
=head2 store_hit

  Arg [1]   : Bio::Search::Hit::EnsemblHit obj
  Function  : Stores the ensembl Hit in the database
  Returntype: scalar (token)
  Exceptions: 
  Caller    : 
  Example   : my $hit_token = $blast_adpt->store_hit( $hit );

=cut

sub store_hit{
  my $self = shift;
  my $hit  = shift || 
    $self->throw( "Need a Bio::Search::Hit::EnsemblHit obj" );
  my $frozen = shift || $hit->serialise;

Ian Longden's avatar
Ian Longden committed
558
  my $dbh  = $self->dbc->db_handle;
559 560

  my ( $id, $use_date ) = split( '!!', $hit->token || '' );
561
  $use_date ||= $hit->use_date() || $hit->use_date($self->use_date('HIT'));;
562 563
  #my $ticket = $hit->group_ticket || warn( "Hit $id has no ticket" );
  my $ticket = $self->ticket || warn("Hit $id BlastAdaptor has no ticket");
564 565 566

  my $rv = 0;
  if( $id ){
Web Admin's avatar
Web Admin committed
567
    my $sth = $self->prepare( sprintf $SQL_HIT_RETRIEVE, $use_date );
568 569 570 571
    $rv = $sth->execute( $id ) ||  $self->throw( $sth->errstr );
    $sth->finish;
  }
  if( $rv < 1 ){ # Insert
Web Admin's avatar
Web Admin committed
572
    my $sth = $self->prepare( sprintf $SQL_HIT_STORE, $use_date );
573 574 575 576 577 578
    $sth->execute( $frozen, $ticket ) || $self->throw( $sth->errstr );
    my $id = $dbh->{mysql_insertid};
    $hit->token( join( '!!', $id, $use_date ) );
    $sth->finish;
  }
  else{ # Update
Web Admin's avatar
Web Admin committed
579
    my $sth = $self->prepare( sprintf $SQL_HIT_UPDATE, $use_date );
580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603
    $sth->execute( $frozen, $ticket, $id ) || $self->throw( $sth->errstr );
    $sth->finish;
  }
  return $hit->token();
}

#----------------------------------------------------------------------

=head2 retrieve_hit

  Arg [1]   : 
  Function  : 
  Returntype: 
  Exceptions: 
  Caller    : 
  Example   : 

=cut

sub retrieve_hit{
  my $self   = shift;
  my $token  = shift || $self->throw( "Need a Hit token" );
  my ( $id, $use_date ) = split( '!!',$token);
  $use_date ||= '';
Ian Longden's avatar
Ian Longden committed
604
  my $dbh  = $self->dbc->db_handle;
Web Admin's avatar
Web Admin committed
605
  my $sth = $self->prepare( sprintf $SQL_HIT_RETRIEVE, $use_date );
606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631
  my $rv  = $sth->execute( $id ) || $self->throw( $sth->errstr );
  if( $rv < 1 ){ $self->throw( "Token $token not found" ) }
  my ( $frozen ) = $sth->fetchrow_array;
  $frozen || $self->throw( "Object from hit $id is empty" );
  $sth->finish;
  return $frozen;
}

#----------------------------------------------------------------------
=head2 store_hsp

  Arg [1]   : Bio::Search::HSP::EnsemblHSP obj
  Function  : Stores the ensembl HSP in the database
  Returntype: 
  Exceptions: 
  Caller    : 
  Example   : 

=cut

sub store_hsp{
  my $self = shift;
  my $hsp  = shift || 
    $self->throw( "Need a Bio::Search::HSP::EnsemblHSP obj" );
  my $frozen = shift || $hsp->serialise;

Ian Longden's avatar
Ian Longden committed
632
  my $dbh  = $self->dbc->db_handle;
633
  my ( $id, $use_date ) = split( '!!', $hsp->token || '');
634 635
  $use_date ||= $hsp->use_date() || $hsp->use_date($self->use_date('HSP'));

636 637
  #my $ticket = $hsp->group_ticket || warn( "HSP $id has no ticket" );
  my $ticket = $self->ticket || warn( "HSP $id BlastAdaptor has no ticket" );
638

639 640 641
  my $chr_name  = '';
  my $chr_start = 0;
  my $chr_end   = 0;
642
  if( my $genomic = $hsp->genomic_hit ){
643
    $chr_name  = $genomic->seq_region_name;
644 645
    $chr_start = $genomic->start;
    $chr_end   = $genomic->end;
646
  }
647 648
  my $rv = 0;
  if( $id ){
Web Admin's avatar
Web Admin committed
649
    my $sth = $self->prepare( sprintf $SQL_HSP_RETRIEVE, $use_date );
650 651 652 653 654
    $rv = $sth->execute( $id ) ||  $self->throw( $sth->errstr );
    $sth->finish;
  }
  if( $rv < 1 ){ # Insert
    my $use_date = $hsp->use_date() || $hsp->use_date($self->use_date('HSP'));
Web Admin's avatar
Web Admin committed
655 656
    my $sth = $self->prepare( 'show tables' ); $sth->execute(); $sth->finish();
    $sth = $self->prepare( sprintf $SQL_HSP_STORE, $use_date );
657 658 659 660 661 662 663
    my @bound = ( $frozen, $ticket, $chr_name,  $chr_start, $chr_end );
    $sth->execute( @bound ) || $self->throw( $sth->errstr );
    my $id = $dbh->{mysql_insertid};
    $hsp->token( join( '!!', $id, $use_date ) );
    $sth->finish;
  }
  else{ # Update
Web Admin's avatar
Web Admin committed
664
    my $sth = $self->prepare( sprintf $SQL_HSP_UPDATE, $use_date );
665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689
    my @bound = ( $frozen, $ticket, $chr_name,  $chr_start, $chr_end, $id );
    $sth->execute( @bound ) || $self->throw( $sth->errstr );
    $sth->finish;
  }
  return $hsp->token();
}

#----------------------------------------------------------------------

=head2 retrieve_hsp

  Arg [1]   : 
  Function  : 
  Returntype: 
  Exceptions: 
  Caller    : 
  Example   : 

=cut

sub retrieve_hsp{
  my $self   = shift;
  my $token  = shift || $self->throw( "Need an HSP token" );
  my ( $id, $use_date ) = split( '!!',$token);
  $use_date ||= '';
Ian Longden's avatar
Ian Longden committed
690
  my $dbh  = $self->dbc->db_handle;
Web Admin's avatar
Web Admin committed
691
  my $sth = $self->prepare( sprintf $SQL_HSP_RETRIEVE, $use_date );
692 693 694 695 696 697 698 699
  my $rv  = $sth->execute( $id ) || $self->throw( $sth->errstr );
  if( $rv < 1 ){ $self->throw( "Token $token not found" ) }
  my ( $frozen ) = $sth->fetchrow_array;
  $frozen || $self->throw( "Object from hsp $id is empty" );
  $sth->finish;
  return $frozen;
}

700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718
#----------------------------------------------------------------------

=head2 remove_hsp

  Arg [1]   : $hsp object to be removed
  Function  : 'removes' hsp from e.g. contigview by setting chr fields
              to null
  Returntype: 
  Exceptions: 
  Caller    : $self->remove
  Example   : 

=cut

sub remove_hsp {
  my $self = shift;
  my $hsp  = shift || 
    $self->throw( "Need a Bio::Search::HSP::EnsemblHSP obj" );

Ian Longden's avatar
Ian Longden committed
719
  my $dbh  = $self->dbc->db_handle;
720 721 722 723

  my ( $id, $use_date ) = split( '!!', $hsp->token || '');
  $use_date ||= $hsp->use_date() || $hsp->use_date($self->use_date('HSP'));

Web Admin's avatar
Web Admin committed
724
  my $sth = $self->prepare( sprintf $SQL_HSP_REMOVE, $use_date );
725 726 727 728 729 730 731
  my @bound = ( $id );
  my $rv = $sth->execute( @bound ) || $self->throw( $sth->errstr );
  $sth->finish;
  return 1;
}


732

733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751
#----------------------------------------------------------------------

=head2 get_all_HSPs

  Arg [1]   : 
  Function  : 
  Returntype: 
  Exceptions: 
  Caller    : 
  Example   : 

=cut

sub get_all_HSPs {
   my $self = shift;
   my $ticket    = shift || $self->throw( "Need a search ticket!");
   my $chr_name  = shift || undef;
   my $chr_start = shift || undef;
   my $chr_end   = shift || undef;
752 753
   my ( $id, $use_date )  = split( '!!', $ticket );
   $use_date ||= '';
754 755

   my $SQL = qq(
Will Spooner's avatar
Will Spooner committed
756
SELECT object, hsp_id
757
FROM   blast_hsp%s
758
WHERE  ticket = ? );
759 760 761 762 763

   my $CHR_SQL = qq(
AND    chr_name = ? );

   my $RANGE_SQL = qq(
764 765
AND    chr_start <= ?
AND    chr_end   >= ? );
766

767
   my $q = sprintf( $SQL, $use_date );
768
   my @binded = ( $id );
769 770 771 772 773 774 775

   if( $chr_name ){
     $q .= $CHR_SQL;
     push @binded, $chr_name;

     if( $chr_start && $chr_end ){
       $q .= $RANGE_SQL;
776
       push @binded, $chr_end, $chr_start;
777 778
     }
   }
Ian Longden's avatar
Ian Longden committed
779
   my $sth = $self->dbc->db_handle->prepare($q);
780 781
   my $rv = $sth->execute( @binded ) || $self->throw( $sth->errstr );

Will Spooner's avatar
Will Spooner committed
782 783 784 785 786 787 788 789
   my @hsps = ();
   foreach my $row( @{$sth->fetchall_arrayref()} ){
     # Retrieve HSP and reset token
     my $hsp = thaw( $row->[0] );
     my $hsp_id = $row->[1];
     $hsp->token( join( '!!', $hsp_id, $use_date  ) );
     push @hsps, $hsp;
   }
790
   $sth->finish;
791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811
   return [@hsps];
}



#----------------------------------------------------------------------

=head2 get_all_SearchFeatures

  Arg [1]   : 
  Function  : 
  Returntype: 
  Exceptions: 
  Caller    : 
  Example   : 

=cut

sub get_all_SearchFeatures {
  my $self = shift;
  my $hsps = $self->get_all_HSPs(@_);
Will Spooner's avatar
Will Spooner committed
812 813
  my $ticket = shift;

814
  $self->dynamic_use( ref($hsps->[0] ) );
Will Spooner's avatar
Will Spooner committed
815 816
  my @feats = ();
  foreach my $hsp( @$hsps ){
817
    my $base_align = $hsp->genomic_hit || next;
Will Spooner's avatar
Will Spooner committed
818 819 820

    ( $ticket ) = split( "!!", $ticket );
    my $hsp_id = join( "!!", $ticket, $hsp->token );
821

Will Spooner's avatar
Will Spooner committed
822 823 824
    $base_align->hseqname( join( ":", $base_align->hseqname, $hsp_id ) );
    push @feats, $base_align;
  }
825 826 827
  return [ @feats ];
}

828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859
sub dynamic_use {
  my( $self, $classname ) = @_;
  my( $parent_namespace, $module ) = $classname =~/^(.*::)(.*?)$/;
  no strict 'refs';
  return 1 if $parent_namespace->{$module.'::'}; # return if already used
  eval "require $classname";
  if($@) {
    warn "DrawableContainer: failed to use $classname\nDrawableContainer: $@";
    return 0;
  }
  $classname->import();
  return 1;
}

#----------------------------------------------------------------------

=head2 use_date

  Arg [1]   : 
  Function  : 
  Returntype: 
  Exceptions: 
  Caller    : 
  Example   : 

=cut

my %valid_table_types = ( HIT=>1, HSP=>1, RESULT=>1 );
sub use_date {
  my $key  = '_current_table';
  my $self = shift;
  my $type = uc( shift );
Web Admin's avatar
Web Admin committed
860
#warn "$self --- $key --- $type $self";
861 862 863 864 865
  $valid_table_types{$type} || 
    $self->throw( "Need a table type (Result, Hit or HSP)" );

  $self->{$key} ||= {};
  if( ! $self->{$key}->{$type} ){
Web Admin's avatar
Web Admin committed
866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890
    my $sth = $self->dbc->db_handle->prepare( "
SELECT table_type,  use_date
  FROM blast_table_log
 WHERE table_status = 'CURRENT'
ORDER BY use_date ASC" );
#warn "prepare... $sth";
#warn $SQL_SELECT_TABLE_LOG_CURRENT;
#warn $type;
    my $rv = $sth->execute();# $type );
#warn $rv;
    unless( $rv ) { 
      $sth->finish;
      warn( $sth->errstr );
      return;
    }
#warn "exec...";
    foreach my $r (@{ $sth->fetchall_arrayref }) {
      my $date = $r->[1];
      $date =~ s/-//g;
      $self->{$key}->{$r->[0]} = $date;
#warn "$r->[0] ---> $r->[1] ---> $date";
    }
#    $rv > 0 || ( warn( "No current $type table found" ) && return );
    $sth->finish;
#warn "end of finish...";
891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913
  }
  return $self->{$key}->{$type};
}



#----------------------------------------------------------------------

=head2 clean_blast_database

  Arg [1]   : int $days
  Function  : Removes blast tickets older than $days days
  Returntype: 
  Exceptions: SQL errors
  Caller    : 
  Example   : $ba->clean_blast_database(14)

=cut

sub clean_blast_database{
  my $self = shift;
  my $days = shift || $self->throw( "Missing arg: number of days" );
  $days =~ /\D/    && $self->throw( "Bad arg: number of days $days not int" );
Ian Longden's avatar
Ian Longden committed
914
  my $dbh = $self->dbc->db_handle;
915 916 917 918 919 920 921

  # Get list of tickets > $days days old
  my $q = qq/
SELECT ticket 
FROM   blast_ticket
WHERE  update_time < SUBDATE( NOW(), INTERVAL $days DAY ) /;

Ian Longden's avatar
Ian Longden committed
922
  my $sth = $self->dbc->db_handle->prepare($q);
923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950
  my $rv = $sth->execute() || $self->throw( $sth->errstr );
  my $res = $sth->fetchall_arrayref;
  $sth->finish;
  
  # Delete result and ticket rows associated with old tickets
#  my $q_del_tmpl = qq/
#DELETE
#FROM   blast_%s
#WHERE  ticket like "%s" /;
#
#  my @types = ( 'result','ticket' );
#  my %num_deleted = map{ $_=>0 } @types;
#
#  foreach my $row( @$res ){
#    my $ticket = $row->[0];
#
#    foreach my $type( @types ){
#      my $q_del = sprintf( $q_del_tmpl, $type, $ticket );
#      my $sth = $self->db->db_handle->prepare($q_del);
#      my $rv = $sth->execute() || $self->throw( $sth->errstr );
#      $num_deleted{$type} += $rv;
#    }
#  }
#  map{ warn("Purging $days days: Deleted $num_deleted{$_} rows of type $_\n") }
#  keys %num_deleted;

  # Drop daily Result, Hit and HSP tables not updated within $days days
  my $q_find = 'show table status like ?';
Web Admin's avatar
Web Admin committed
951
  my $sth2 = $self->prepare( $q_find );
952 953 954 955 956 957 958 959 960
  $sth2->execute( "blast_result%" ) || $self->throw( $sth2->errstr );
  my $res_res = $sth2->fetchall_arrayref();
  $sth2->execute( "blast_hit%" ) || $self->throw( $sth2->errstr );
  my $hit_res = $sth2->fetchall_arrayref();
  $sth2->execute( "blast_hsp%" ) || $self->throw( $sth2->errstr );
  my $hsp_res = $sth2->fetchall_arrayref();

  my @deletable_hit_tables;
  foreach my $row( @$res_res, @$hit_res, @$hsp_res ){
Web Admin's avatar
Web Admin committed
961 962 963
    my $table_name  = $row->[0];  ## table name
    my $num_rows    = $row->[4];  ## # Rows...
    my $update_time = $row->[12]; ## update time ---  Should be a string like 2003-08-15 10:36:56
964 965 966 967 968 969 970 971
    my @time = split( /[-:\s]/, $update_time );
    
    my $epoch_then = timelocal( $time[5], $time[4],   $time[3], 
				$time[2], $time[1]-1, $time[0] - 1900 );
    my $secs_old = time() - $epoch_then;
    my $days_old = $secs_old / ( 60 * 60 * 24 );
    if( $days_old > $days ){
      warn( "Dropping table $table_name: $num_rows rows\n" );
Web Admin's avatar
Web Admin committed
972 973
      my $sth_drop = $self->prepare( "DROP table $table_name" );
      my $sth_log  = $self->prepare( $SQL_TABLE_LOG_UPDATE );
974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990
      $sth_drop->execute || $self->throw( $sth_drop->errstr );
      my( $se,$mi,$hr,$da,$mo,$yr ) = (localtime)[0,1,2,3,4,5];
      my $now = sprintf( "%4d-%2d-%2d %2d:%2d:%2d", 
			 $yr+1900,$mo+1,$da,$hr,$mi,$se );
      $sth_log->execute
        ('DELETED',$now,$num_rows,$table_name) ||
	  $self->throw( $sth_log->errstr );
    }
  }


  return 1;
}

#----------------------------------------------------------------------

=head2 create_tables
991

992 993 994 995 996 997 998 999
  Arg [1]   : none
  Function  : Creates the blast_ticket and blast_table_log
              tables in the database indicated by the database handle.
              Checks first to make sure they do not exist
  Returntype: boolean
  Exceptions: 
  Caller    : 
  Example   : 
Will Spooner's avatar
Will Spooner committed
1000

1001 1002 1003 1004
=cut

sub create_tables {
  my $self = shift;
Ian Longden's avatar
Ian Longden committed
1005
  my $dbh = $self->dbc->db_handle;
1006 1007 1008

  # Get list of existing tables in database
  my $q = 'show tables like ?';
Web Admin's avatar
Web Admin committed
1009
  my $sth = $self->prepare( $q );
1010 1011 1012 1013 1014 1015
  my $rv_tck = $sth->execute("blast_ticket")    || $self->throw($sth->errstr);
  my $rv_log = $sth->execute("blast_table_log" )|| $self->throw($sth->errstr);
  $sth->finish;

  if( $rv_tck == 0 ){
    warn( "Creating blast_ticket table\n" );
Web Admin's avatar
Web Admin committed
1016
    my $sth = $self->prepare( $SQL_CREATE_TICKET );
1017 1018 1019 1020 1021 1022 1023
    my $rv = $sth->execute() || $self->throw( $sth->errstr );
    $sth->finish;
  }
  else{ warn( "blast_ticket table already exists\n" ) }

  if( $rv_log == 0 ){
    warn( "Creating blast_result table\n" );
Web Admin's avatar
Web Admin committed
1024
    my $sth = $self->prepare( $SQL_CREATE_TABLE_LOG );
1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052
    my $rv = $sth->execute() || $self->throw( $sth->errstr );    
     $sth->finish;
  }
  else{ warn( "blast_table_log table already exists\n" ) }  

  return 1;
}

#----------------------------------------------------------------------

=head2 rotate_daily_tables

  Arg [1]   : none
  Function  : Creates the daily blast_result{date}, blast_hit{date} 
              and blast_hsp{date} tables in the database indicated by 
              the database handle.
              Checks first to make sure they do not exist.
              Sets the new table to 'CURRENT' in the blast_table_log.
              Sets the previous 'CURRENT' table to filled.
  Returntype: boolean
  Exceptions: 
  Caller    : 
  Example   : 

=cut

sub rotate_daily_tables {
  my $self = shift;
Ian Longden's avatar
Ian Longden committed
1053
  my $dbh = $self->dbc->db_handle;
1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064
 
  # Get date
  my( $day, $month, $year ) = (localtime)[3,4,5];
  my $date = sprintf( "%04d%02d%02d", $year+1900, $month+1, $day );

  my $res_table = "blast_result$date";
  my $hit_table = "blast_hit$date";
  my $hsp_table = "blast_hsp$date";

  # Get list of existing tables in database
  my $q = 'show table status like ?';
Web Admin's avatar
Web Admin committed
1065
  my $sth = $self->prepare( $q );
1066 1067 1068 1069 1070 1071 1072 1073 1074 1075
  my $rv_res  = $sth->execute($res_table) || $self->throw($sth->errstr);
  my $rv_hit  = $sth->execute($hit_table) || $self->throw($sth->errstr);
  my $rv_hsp  = $sth->execute($hsp_table) || $self->throw($sth->errstr);
  $sth->finish;

  if( $rv_res == 0 ){
    warn( "Creating today's $res_table table\n" );

    # Create new table
    my $q = sprintf($SQL_CREATE_DAILY_RESULT, $res_table);
Web Admin's avatar
Web Admin committed
1076
    my $sth1 = $self->prepare( $q );
1077 1078 1079 1080
    my $rv = $sth1->execute() || $self->throw( $sth1->errstr );         

    # Flip current table in blast_table_tog
    my $last_date = $self->use_date( "RESULT" ) || '';
Web Admin's avatar
Web Admin committed
1081 1082
    my $sth2 = $self->prepare( $SQL_TABLE_LOG_INSERT );
    my $sth3 = $self->prepare( $SQL_TABLE_LOG_UPDATE );
1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
    $sth2->execute( "$res_table",'CURRENT','RESULT',$date ) 
      || die( $self->throw( $sth2->errstr ) );
    $sth3->execute( 'FILLED','0',0,"blast_result$last_date") 
      || die( $self->throw( $sth3->errstr ) );
    $sth1->finish();
    $sth2->finish();
    $sth3->finish();    
  }
  else{ warn( "Today's $res_table table already exists\n" ) }

  if( $rv_hit == 0 ){
    warn( "Creating today's $hit_table table\n" );

    # Create new table
    my $q = sprintf($SQL_CREATE_DAILY_HIT, $hit_table);
Web Admin's avatar
Web Admin committed
1098
    my $sth1 = $self->prepare( $q );
1099 1100 1101 1102
    my $rv = $sth1->execute() || $self->throw( $sth1->errstr );         

    # Flip current table in blast_table_tog
    my $last_date = $self->use_date( "HIT" ) || '';
Web Admin's avatar
Web Admin committed
1103 1104
    my $sth2 = $self->prepare( $SQL_TABLE_LOG_INSERT );
    my $sth3 = $self->prepare( $SQL_TABLE_LOG_UPDATE );
1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119
    $sth2->execute( "$hit_table",'CURRENT','HIT',$date ) 
      || die( $self->throw( $sth2->errstr ) );
    $sth3->execute( 'FILLED','0',0,"blast_hit$last_date") 
      || die( $self->throw( $sth3->errstr ) );
    $sth1->finish();
    $sth2->finish();
    $sth3->finish();    
  }
  else{ warn( "Today's $hit_table table already exists\n" ) }
  
  if( $rv_hsp == 0 ){
    warn( "Creating today's $hsp_table table\n" );

    # Create new table
    my $q = sprintf($SQL_CREATE_DAILY_HSP, $hsp_table );
Web Admin's avatar
Web Admin committed
1120
    my $sth1 = $self->prepare( $q );
1121 1122 1123 1124
    my $rv = $sth1->execute() || $self->throw( $sth1->errstr );         

    # Flip current table in blast_table_tog
    my $last_date = $self->use_date( "HSP" ) || '';    
Web Admin's avatar
Web Admin committed
1125 1126
    my $sth2 = $self->prepare( $SQL_TABLE_LOG_INSERT );
    my $sth3 = $self->prepare(  $SQL_TABLE_LOG_UPDATE );
1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137
    $sth2->execute( "$hsp_table",'CURRENT','HSP',$date ) 
      || die( $self->throw( $sth2->errstr ) );
    $sth3->execute( 'FILLED','0',0,"blast_hsp$last_date") 
      || die( $self->throw( $sth3->errstr ) );
    $sth1->finish();
    $sth2->finish();
    $sth3->finish();    
  }
  else{ warn( "Today's $hsp_table table already exists\n" ) }
  return 1;
}
1138 1139

#----------------------------------------------------------------------
Web Admin's avatar
Web Admin committed
1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172

=head2 cleanup_processes

  Arg [1]   : none
  Function  : Kills any sleeping processes older that 1000
  Returntype: boolean
  Exceptions: 
  Caller    : 
  Example   : 

=cut

sub cleanup_processes {
  my $self = shift;
  my $dbh = $self->dbc->db_handle;
  my $sth = $self->prepare( 'show processlist' );
  my $kill_sth = $self->prepare('kill ?');
  $sth->execute;
  my $res = $sth->fetchall_arrayref([0,3,4,5]);
  my $c = 0;
  foreach my $ps (@$res) {
    my ($pid,$db,$stat,$time) = @$ps;
    if ($db eq 'ensembl_blast') {
      if ( ($stat eq 'Sleep') && ($time > 1000) ) {
	$kill_sth->execute($pid);
	$c++;
      }
    }
  }
  warn "Killed $c processes";
  return 1;
}

1173
1;