DBEntryAdaptor.pm 76.1 KB
Newer Older
1 2
=head1 LICENSE

3
Copyright [1999-2013] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
4

5 6 7 8 9 10 11 12 13 14 15 16 17
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

=cut
18 19 20 21 22


=head1 CONTACT

  Please email comments or questions to the public Ensembl
Magali Ruffier's avatar
Magali Ruffier committed
23
  developers list at <http://lists.ensembl.org/mailman/listinfo/dev>.
24 25

  Questions may also be sent to the Ensembl help desk at
Magali Ruffier's avatar
Magali Ruffier committed
26
  <http://www.ensembl.org/Help/Contact>.
27 28

=cut
29 30 31

=head1 NAME

32
Bio::EnsEMBL::DBSQL::DBEntryAdaptor -
33 34 35 36
MySQL Database queries to load and store external object references.

=head1 SYNOPSIS

37 38
  $db_entry_adaptor =
    $registry->get_adaptor( 'Human', 'Core', 'DBEntry' );
39

40
  $db_entry = $db_entry_adaptor->fetch_by_dbID($id);
41

42 43 44 45 46 47
  my $gene_adaptor = $registry->get_adaptor( 'Human', 'Core', 'Gene' );

  my $gene = $gene_adaptor->fetch_by_stable_id('ENSG00000101367');

  @db_entries = @{ $db_entry_adaptor->fetch_all_by_Gene($gene) };
  @gene_ids   = $db_entry_adaptor->list_gene_ids_by_extids('BAB15482');
Graham McVicker's avatar
Graham McVicker committed
48

49 50
=head1 METHODS

51 52 53 54 55
=cut

package Bio::EnsEMBL::DBSQL::DBEntryAdaptor;

use Bio::EnsEMBL::DBSQL::BaseAdaptor;
56

57
use Bio::EnsEMBL::DBEntry;
58
use Bio::EnsEMBL::IdentityXref;
59
use Bio::EnsEMBL::OntologyXref;
60

61
use Bio::EnsEMBL::Utils::Exception qw(deprecate throw warning);
62

63 64 65 66 67
use vars qw(@ISA);
use strict;

@ISA = qw( Bio::EnsEMBL::DBSQL::BaseAdaptor );

Graham McVicker's avatar
Graham McVicker committed
68 69 70 71 72
=head2 fetch_by_dbID

  Arg [1]    : int $dbID
               the unique database identifier for the DBEntry to retrieve
  Example    : my $db_entry = $db_entry_adaptor->fetch_by_dbID($dbID);
73 74
  Description: Retrieves a dbEntry from the database via its unique
               identifier.
Graham McVicker's avatar
Graham McVicker committed
75 76
  Returntype : Bio::EnsEMBL::DBEntry
  Exceptions : none
77
  Caller     : general
78
  Status     : Stable
Graham McVicker's avatar
Graham McVicker committed
79 80 81

=cut

82
sub fetch_by_dbID {
83
  my ( $self, $dbID ) = @_;
84

85
  my $sth = $self->prepare(
86 87 88 89 90 91 92 93 94 95 96 97 98
    "SELECT  xref.xref_id,
            xref.dbprimary_acc,
            xref.display_label,
            xref.version,
            exDB.priority,
            exDB.db_name,
            exDB.db_display_name,
            exDB.db_release,
            es.synonym,
            xref.info_type,
            xref.info_text,
            exDB.type,
            exDB.secondary_db_name,
99
            exDB.secondary_db_table,
Nathan Johnson's avatar
Nathan Johnson committed
100
            xref.description
101 102 103 104 105 106 107
    FROM    (xref, external_db exDB)
    LEFT JOIN external_synonym es ON
            es.xref_id = xref.xref_id
    WHERE   xref.xref_id = ?
    AND     xref.external_db_id = exDB.external_db_id" );

  $sth->bind_param( 1, $dbID, SQL_INTEGER );
108
  $sth->execute();
109

110
  my $exDB;
111

112 113 114
  my $max_rows = 1000;

  while ( my $rowcache = $sth->fetchall_arrayref( undef, $max_rows ) ) {
115
      #$description refers to the external_db description, while $desc was referring the xref description
116 117 118
    while ( my $arrayref = shift( @{$rowcache} ) ) {
      my ( $refID,               $dbprimaryId,
           $displayid,           $version,
119
           $priority,
120 121 122 123
           $dbname,              $db_display_name,
           $release,             $synonym,
           $info_type,           $info_text,
           $type,                $secondary_db_name,
124
           $secondary_db_table,  $description
125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
      ) = @$arrayref;

      if ( !defined($exDB) ) {
        $exDB =
          Bio::EnsEMBL::DBEntry->new(
                           -adaptor             => $self,
                           -dbID                => $dbID,
                           -primary_id          => $dbprimaryId,
                           -display_id          => $displayid,
                           -version             => $version,
                           -release             => $release,
                           -dbname              => $dbname,
                           -priority            => $priority,
                           -db_display_name     => $db_display_name,
                           -info_type           => $info_type,
                           -info_text           => $info_text,
                           -type                => $type,
                           -secondary_db_name   => $secondary_db_name,
143
                           -secondary_db_table  => $secondary_db_table,
144
			               -description         => $description
145 146 147 148
          );


      }
149

150
      if ( defined($synonym) ) { $exDB->add_synonym($synonym) }
151

152 153
    } ## end while ( my $arrayref = shift...
  } ## end while ( my $rowcache = $sth...
154 155 156 157

  $sth->finish();

  return $exDB;
158
} ## end sub fetch_by_dbID
159 160


161 162 163 164 165 166 167 168 169 170 171 172
sub _get_all_dm_loc_sth {
  my ($self, $constraint ,$ensembl_object ) = @_;
  my $object_type;
  if($ensembl_object->isa("Bio::EnsEMBL::Gene")){
    $object_type = "Gene";
  }
  elsif($ensembl_object->isa("Bio::EnsEMBL::Transcript")){
    $object_type = "Transcript";
  }
  elsif($ensembl_object->isa("Bio::EnsEMBL::Translation")){
    $object_type = "Translation";
  }
173 174 175 176 177 178
  elsif($ensembl_object->isa("Bio::EnsEMBL::Operon")){
    $object_type = "Operon";
  }
  elsif($ensembl_object->isa("Bio::EnsEMBL::OperonTranscript")){
    $object_type = "OperonTranscript";
  }
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
  else{
    warn(ref($ensembl_object)." is not a Gene Transcript or Translation object??\n");
    return undef;
  }
  my $sql = "SELECT xref.xref_id,
               xref.dbprimary_acc,
            xref.display_label,
            xref.version,
            exDB.priority,
            exDB.db_name,
            exDB.db_display_name,
            exDB.db_release,
            es.synonym,
            xref.info_type,
            xref.info_text,
            exDB.type,
            exDB.secondary_db_name,
            exDB.secondary_db_table,
            xref.description
    FROM    (xref, external_db exDB, dependent_xref dx, object_xref ox)
    LEFT JOIN external_synonym es ON
            es.xref_id = xref.xref_id
    WHERE   xref.external_db_id = exDB.external_db_id AND
            ox.xref_id = xref.xref_id AND
            ox.ensembl_object_type = \'$object_type\' AND
            ox.ensembl_id = ".$ensembl_object->dbID();

  if($constraint){
    $sql .= " AND $constraint";
  }
  else{
    die "NO constraint???\n";
  }
212

213
  my $sth = $self->prepare($sql) || die "Could not prepare $sql";
214

215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
  return $self->_get_all_dm($sth);
}

sub _get_all_dm_sth {
  my ( $self, $constraint) = @_;

 my $sql = "SELECT xref.xref_id,
               xref.dbprimary_acc,
            xref.display_label,
            xref.version,
            exDB.priority,
            exDB.db_name,
            exDB.db_display_name,
            exDB.db_release,
            es.synonym,
            xref.info_type,
            xref.info_text,
            exDB.type,
            exDB.secondary_db_name,
            exDB.secondary_db_table,
            xref.description
    FROM    (xref, external_db exDB, dependent_xref dx)
    LEFT JOIN external_synonym es ON
            es.xref_id = xref.xref_id
    WHERE   xref.external_db_id = exDB.external_db_id ";

  if($constraint){
    $sql .= "AND $constraint";
  }
  else{
    die "NO constraint???\n";
  }

  my $sth = $self->prepare($sql) || die "Could not prepare $sql";

  return $self->_get_all_dm($sth);
}


sub _get_all_dm{

  my ($self, $sth) = @_;

#  $sth->bind_param( 1, $dm_dbid, SQL_INTEGER );

#  print $sth."\n";
  $sth->execute() || die "Not able to execute statement handle";

  my @list =();
  my %seen;

  my $max_rows = 1000;
  while ( my $rowcache = $sth->fetchall_arrayref(undef, $max_rows) ) {
    while ( my $arrayref = shift( @{$rowcache} ) ) {
      my ( $dbID,                $dbprimaryId,
           $displayid,           $version,
271
           $priority,
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
           $dbname,              $db_display_name,
           $release,             $synonym,
           $info_type,           $info_text,
           $type,                $secondary_db_name,
           $secondary_db_table,  $description
      ) = @$arrayref;

      if ( !defined($seen{$dbID}) ) {
       my $exDB =
          Bio::EnsEMBL::DBEntry->new(
                           -adaptor             => $self,
                           -dbID                => $dbID,
                           -primary_id          => $dbprimaryId,
                           -display_id          => $displayid,
                           -version             => $version,
                           -release             => $release,
                           -dbname              => $dbname,
                           -priority            => $priority,
                           -db_display_name     => $db_display_name,
                           -info_type           => $info_type,
                           -info_text           => $info_text,
                           -type                => $type,
                           -secondary_db_name   => $secondary_db_name,
                           -secondary_db_table  => $secondary_db_table,
			   -description         => $description
          );

	if ($synonym) { $exDB->add_synonym($synonym) };
	$seen{$dbID} = 1;
	push @list, $exDB;
      }



    } ## end while ( my $arrayref = shift...
  } ## end while ( my $rowcache = $sth...

  $sth->finish();

  return \@list;

}


=head2 get_all_dependents

  Args[1]    : dbID of the DBentry to get the dependents of.
  Args[2]    : (optional) Bio::EnsEMBL::Gene, Transcript or Translation object
  Example    : my @dependents = @{ $dbe_adaptor->get_all_dependents(1234) };
  Description: Get a list of DBEntrys that are depenednet on the DBEntry.
               if an ensembl gene transcript or translation is given then only
               the ones on that object will be given
  Returntype : listref of DBEntrys. May be empty.
  Exceptions : none
  Caller     : DBEntry->get_all_dependnets
  Status     : UnStable

=cut

sub get_all_dependents {
  my ( $self, $dbid, $ensembl_object) = @_;
  
  if(defined($ensembl_object) and !($ensembl_object->isa("Bio::EnsEMBL::Feature") or $ensembl_object->isa("Bio::EnsEMBL::Translation"))){
    die ref($ensembl_object)." is not an Gene Transcript or Translation";
  }
  
  my $constraint = " dx.master_xref_id = $dbid AND  dx.dependent_xref_id = xref.xref_id";
  if(defined($ensembl_object)){
    return $self->_get_all_dm_loc_sth($constraint, $ensembl_object);
  }
  else{
    return $self->_get_all_dm_sth($constraint, $ensembl_object);
  }

}

=head2 get_all_masters

  Args[1]    : dbID of the DBentry to get the masters of.
  Args[2]    : (optional) Bio::EnsEMBL::Gene, Transcript or Translation object
  Example    : my @masters = @{ $dbe_adaptor->get_all_masters(1234) };
  Description: Get a list of DBEntrys that are the masters of the DBEntry.
               if an ensembl gene transcript or translation is given then only
               the ones on that object will be given.
  Returntype : listref of DBEntrys. May be empty.
  Exceptions : none
  Caller     : DBEntry->get_all_masters
  Status     : UnStable

=cut

sub get_all_masters {
  my ( $self, $dbid, $ensembl_object ) = @_;
  
  if(defined($ensembl_object) and !($ensembl_object->isa("Bio::EnsEMBL::Feature") or $ensembl_object->isa("Bio::EnsEMBL::Translation"))){
    die ref($ensembl_object)." is not an Gene Transcript or Translation";
  }
  
  my $constraint = "dx.dependent_xref_id = $dbid AND  dx.master_xref_id = xref.xref_id";

  if(defined($ensembl_object)){
    return $self->_get_all_dm_loc_sth($constraint, $ensembl_object);
  }
  else{
    return $self->_get_all_dm_sth($constraint, $ensembl_object);
  }
#  return $self->_get_all_dm($constraint, $ensembl_object);
}


382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507
=head fetch_all_by_name

  Arg [1]    : string $name - The name of the external reference.
               found in accession, display_label or synonym
  Arg [2]    : (optional) string $dbname  - The name of the database which 
               the provided name is for.

  Example    : my $xref = @{$dbea->fetch_all_by_name('BRAC2','HGNC')}[0];
               print $xref->description(), "\n" if($xref);
  Description: Retrieves list of DBEntrys (xrefs) via a name.
               The accesion is looked for first then the synonym and finally
               the display_label.
               NOTE $dbname this is optional but adding this speeds the
               process up if you know what you are looking for.

               NOTE:  In a multi-species database, this method will
               return all the entries matching the search criteria, not
               just the ones associated with the current species.
  Returntype : Bio::EnsEMBL::DBSQL::DBEntry
  Exceptions : thrown if arguments are incorrect
  Caller     : general, domainview
  Status     : Stable

=cut

sub fetch_all_by_name {
  my ( $self, $name, $dbname ) = @_;

  my $sql = (<<SQL);
  SELECT xref.xref_id, xref.dbprimary_acc, xref.display_label, xref.version,
         exDB.priority, exDB.db_name, exDB.db_display_name, exDB.db_release,
            es.synonym, xref.info_type, xref.info_text,
            exDB.type, exDB.secondary_db_name, exDB.secondary_db_table,
            xref.description
    FROM    (xref, external_db exDB)
    LEFT JOIN external_synonym es ON
            es.xref_id = xref.xref_id
    WHERE  (xref.dbprimary_acc = ? or xref.display_label = ?)
    AND    xref.external_db_id = exDB.external_db_id
SQL

  if(defined $dbname){
    $sql .= " AND    exDB.db_name = ?";
  }
  my $sth = $self->prepare($sql);
  $sth->bind_param( 1, $name, SQL_VARCHAR );
  $sth->bind_param( 2, $name, SQL_VARCHAR );
  if(defined $dbname){
    $sth->bind_param( 3 , $dbname,    SQL_VARCHAR );
  }
  $sth->execute();


  if ( !$sth->rows() && lc($dbname) eq 'interpro' ) {
  # This is a minor hack that means that results still come back even
  # when a mistake was made and no interpro accessions were loaded into
  # the xref table.  This has happened in the past and had the result of
  # breaking domainview

    $sth->finish();
    $sth = $self->prepare(
      "SELECT   NULL,
                i.interpro_ac,
                i.id,
                NULL,
                NULL,
                'Interpro',
                NULL,
                NULL
        FROM    interpro i
        WHERE   i.interpro_ac = ?" );

    $sth->bind_param( 1, $name, SQL_VARCHAR );
    $sth->execute();
  }

  my %exDB;
  my @exDBlist;
  my $max_rows = 1000;

  while ( my $rowcache = $sth->fetchall_arrayref( undef, $max_rows ) ) {
    while ( my $arrayref = shift( @{$rowcache} ) ) {
      my ( $dbID,                $dbprimaryId,
           $displayid,           $version,
           $priority,
           $dbname,              $db_display_name,
           $release,             $synonym,
           $info_type,           $info_text,
           $type,                $secondary_db_name,
           $secondary_db_table,  $description
      ) = @$arrayref;

      if ( !defined $exDB{$dbID} ) {
	my $entrie = 
          Bio::EnsEMBL::DBEntry->new(
                           -adaptor             => $self,
                           -dbID                => $dbID,
                           -primary_id          => $dbprimaryId,
                           -display_id          => $displayid,
                           -version             => $version,
                           -release             => $release,
                           -dbname              => $dbname,
                           -priority            => $priority,
                           -db_display_name     => $db_display_name,
                           -info_type           => $info_type,
                           -info_text           => $info_text,
                           -type                => $type,
                           -secondary_db_name   => $secondary_db_name,
                           -secondary_db_table  => $secondary_db_table,
			   -description         => $description
          );
	$exDB{$dbID} = $entrie;
	push @exDBlist, $entrie;
      }
      if ($synonym) { $exDB{$dbID}->add_synonym($synonym) }

    } ## end while ( my $arrayref = shift...
  } ## end while ( my $rowcache = $sth...

  $sth->finish();

  return \@exDBlist;
} ## end sub fetch_all_by_name



508 509 510 511 512 513 514 515
=head2 fetch_by_db_accession

  Arg [1]    : string $dbname - The name of the database which the provided
               accession is for.
  Arg [2]    : string $accession - The accesion of the external reference to
               retrieve.
  Example    : my $xref = $dbea->fetch_by_db_accession('Interpro','IPR003439');
               print $xref->description(), "\n" if($xref);
516 517 518 519 520 521 522
  Description: Retrieves a DBEntry (xref) via the name of the database
               it is from and its primary accession in that database.
               Undef is returned if the xref cannot be found in the
               database.
               NOTE:  In a multi-species database, this method will
               return all the entries matching the search criteria, not
               just the ones associated with the current species.
523 524 525
  Returntype : Bio::EnsEMBL::DBSQL::DBEntry
  Exceptions : thrown if arguments are incorrect
  Caller     : general, domainview
526
  Status     : Stable
527 528 529 530

=cut

sub fetch_by_db_accession {
531
  my ( $self, $dbname, $accession ) = @_;
532

533
  my $sth = $self->prepare(
534 535 536 537 538 539 540 541 542 543 544 545 546
    "SELECT xref.xref_id,
            xref.dbprimary_acc,
            xref.display_label,
            xref.version,
            exDB.priority,
            exDB.db_name,
            exDB.db_display_name,
            exDB.db_release,
            es.synonym,
            xref.info_type,
            xref.info_text,
            exDB.type,
            exDB.secondary_db_name,
547
            exDB.secondary_db_table,
Nathan Johnson's avatar
Nathan Johnson committed
548
            xref.description
549 550 551
    FROM    (xref, external_db exDB)
    LEFT JOIN external_synonym es ON
            es.xref_id = xref.xref_id
552 553
    WHERE  xref.dbprimary_acc = ?
    AND    exDB.db_name = ?
554
    AND    xref.external_db_id = exDB.external_db_id" );
555

556 557
  $sth->bind_param( 1, $accession, SQL_VARCHAR );
  $sth->bind_param( 2, $dbname,    SQL_VARCHAR );
558
  $sth->execute();
559

560 561 562 563 564 565
  if ( !$sth->rows() && lc($dbname) eq 'interpro' ) {
  # This is a minor hack that means that results still come back even
  # when a mistake was made and no interpro accessions were loaded into
  # the xref table.  This has happened in the past and had the result of
  # breaking domainview

566
    $sth->finish();
567 568 569 570 571 572 573 574 575 576 577 578 579
    $sth = $self->prepare(
      "SELECT   NULL,
                i.interpro_ac,
                i.id,
                NULL,
                NULL,
                'Interpro',
                NULL,
                NULL
        FROM    interpro i
        WHERE   i.interpro_ac = ?" );

    $sth->bind_param( 1, $accession, SQL_VARCHAR );
580
    $sth->execute();
581 582 583 584
  }

  my $exDB;

585 586 587 588 589 590
  my $max_rows = 1000;

  while ( my $rowcache = $sth->fetchall_arrayref( undef, $max_rows ) ) {
    while ( my $arrayref = shift( @{$rowcache} ) ) {
      my ( $dbID,                $dbprimaryId,
           $displayid,           $version,
591
           $priority,
592 593 594 595
           $dbname,              $db_display_name,
           $release,             $synonym,
           $info_type,           $info_text,
           $type,                $secondary_db_name,
596
           $secondary_db_table,  $description
597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614
      ) = @$arrayref;

      if ( !defined($exDB) ) {
        $exDB =
          Bio::EnsEMBL::DBEntry->new(
                           -adaptor             => $self,
                           -dbID                => $dbID,
                           -primary_id          => $dbprimaryId,
                           -display_id          => $displayid,
                           -version             => $version,
                           -release             => $release,
                           -dbname              => $dbname,
                           -priority            => $priority,
                           -db_display_name     => $db_display_name,
                           -info_type           => $info_type,
                           -info_text           => $info_text,
                           -type                => $type,
                           -secondary_db_name   => $secondary_db_name,
615 616
                           -secondary_db_table  => $secondary_db_table,
			   -description         => $description
617 618
          );

619

620 621 622 623 624 625
      }

      if ($synonym) { $exDB->add_synonym($synonym) }

    } ## end while ( my $arrayref = shift...
  } ## end while ( my $rowcache = $sth...
626 627

  $sth->finish();
628 629

  return $exDB;
630
} ## end sub fetch_by_db_accession
631 632


Graham McVicker's avatar
Graham McVicker committed
633 634
=head2 store

635
  Arg [1]    : Bio::EnsEMBL::DBEntry $dbEntry
636
               The DBEntry (xref) to be stored
637 638 639 640
  Arg [2]    : Int $ensID
               The dbID of an EnsEMBL object to associate with this external
               database entry
  Arg [3]    : string $ensType ('Transcript', 'Translation', 'Gene')
641 642
               The type of EnsEMBL object that this external database entry is
               being associated with.
643 644 645 646 647
  Arg [4]    : boolean $ignore_release
               If unset or zero, will require that the release string
               of the DBEntry object is identical to the release of the
               external database.  If set and non-zero, will ignore the
               release information.
648
  Example    : $dbea->store($db_entry, $transcript_id, 'Transcript');
649 650 651
  Description: Stores a reference to an external database (if it is not stored
               already) and associates an EnsEMBL object of a specified type
               with the external identifier.
652 653 654
  Returntype : int - the dbID of the newly created external refernce
  Exceptions : thrown when invalid dbID is passed to this method
  Caller     : scripts which load Xrefs and ObjectXrefs, etc. into Ensembl
655
  Status     : Stable
Graham McVicker's avatar
Graham McVicker committed
656 657 658

=cut

659
sub store {
660
  my ( $self, $dbEntry, $ensID, $ensType, $ignore_release ) = @_;
661

662
  my $dbJustInserted;
663

664 665 666 667 668 669
  #
  # backwards compatibility check:
  # check if $ensID is an object; if so, use $obj->dbID
  #
  my $ensembl_id;

670 671 672 673 674
  if ( defined($ensID) ) {
    if ( $ensID =~ /^\d+$/ ) {
      $ensembl_id = $ensID;
    } elsif (    ref($ensID) eq 'Bio::EnsEMBL::Gene'
              or ref($ensID) eq 'Bio::EnsEMBL::Transcript'
675 676 677 678
              or ref($ensID) eq 'Bio::EnsEMBL::Translation' 
              or ref($ensID) eq 'Bio::EnsEMBL::OperonTranscript'
              or ref($ensID) eq 'Bio::EnsEMBL::Operon' 
              )
679 680 681 682 683
    {
      warning(   "You should pass DBEntryAdaptor->store() "
               . "a dbID rather than an ensembl object "
               . "to store the xref on" );

684
      if ( defined( $ensID->dbID() ) ) {
685 686 687 688 689
        $ensembl_id = $ensID->dbID();
      } else {
        throw( sprintf( "%s %s doesn't have a dbID, can't store xref",
                        $ensType, $ensID->display_id() ) );
      }
690
    } else {
691
      throw("Invalid dbID passed to DBEntryAdaptor->store()");
692 693
    }
  }
694 695 696 697 698 699 700 701 702 703 704
  
  
  
    # Ensure external_db contains a record of the intended xref source
    my $dbRef;
    $dbRef = $self->_check_external_db($dbEntry,$ignore_release);

    # Attempt to insert DBEntry
    my $xref_id = $self->_store_or_fetch_xref($dbEntry,$dbRef);
    $dbEntry->dbID($xref_id); #keeps DBEntry in sync with database
    ### Attempt to create an object->xref mapping
705
    if ($ensembl_id) {$self->_store_object_xref_mapping($ensembl_id,$dbEntry,$ensType, $ignore_release)};
706 707 708 709 710 711 712 713 714
    
    return $xref_id;
}
    
sub _store_object_xref_mapping {
    my $self = shift;
    my $ensembl_id = shift;
    my $dbEntry = shift;
    my $ensembl_type = shift;
715
    my $ignore_release = shift;
716 717 718 719 720 721 722 723
    
    if (not defined ($ensembl_type)) { warning("No Ensembl data type provided for new xref");}
    
    my $analysis_id;
    if ( $dbEntry->analysis() ) {
        $analysis_id = $self->db()->get_AnalysisAdaptor->store( $dbEntry->analysis() );
    } else {
        $analysis_id = 0; ## This used to be undef, but uniqueness in mysql requires a value
724
    }
725 726 727 728 729 730 731 732 733 734 735 736 737 738
    
    my $sth = $self->prepare(qq(
        INSERT IGNORE INTO object_xref
          SET   xref_id = ?,
                ensembl_object_type = ?,
                ensembl_id = ?,
                linkage_annotation = ?,
                analysis_id = ? ) 
        );
    $sth->bind_param( 1, $dbEntry->dbID(),              SQL_INTEGER );
    $sth->bind_param( 2, $ensembl_type,                 SQL_VARCHAR );
    $sth->bind_param( 3, $ensembl_id,                   SQL_INTEGER );
    $sth->bind_param( 4, $dbEntry->linkage_annotation(),SQL_VARCHAR );
    $sth->bind_param( 5, $analysis_id,                  SQL_INTEGER );
739 740
    $sth->execute();
    $sth->finish();
741 742 743 744 745 746 747
    my $object_xref_id = $self->last_insert_id();
    
    $dbEntry->adaptor($self); # hand Adaptor to dbEntry for future use with OntologyXrefs
    
    if ($object_xref_id) {
        #no existing object_xref, therefore 
        if ( $dbEntry->isa('Bio::EnsEMBL::IdentityXref') ) {
748
        $sth = $self->prepare( "
749 750
             INSERT ignore INTO identity_xref
             SET object_xref_id = ?,
751 752 753 754 755 756
             xref_identity = ?,
             ensembl_identity = ?,
             xref_start = ?,
             xref_end   = ?,
             ensembl_start = ?,
             ensembl_end = ?,
757 758
             cigar_line = ?,
             score = ?,
759
             evalue = ?" );
760 761 762 763 764 765 766 767 768 769
        $sth->bind_param( 1, $object_xref_id,            SQL_INTEGER );
        $sth->bind_param( 2, $dbEntry->xref_identity,    SQL_INTEGER );
        $sth->bind_param( 3, $dbEntry->ensembl_identity, SQL_INTEGER );
        $sth->bind_param( 4, $dbEntry->xref_start,       SQL_INTEGER );
        $sth->bind_param( 5, $dbEntry->xref_end,         SQL_INTEGER );
        $sth->bind_param( 6, $dbEntry->ensembl_start,    SQL_INTEGER );
        $sth->bind_param( 7, $dbEntry->ensembl_end,      SQL_INTEGER );
        $sth->bind_param( 8,  $dbEntry->cigar_line,  SQL_LONGVARCHAR );
        $sth->bind_param( 9,  $dbEntry->score,            SQL_DOUBLE );
        $sth->bind_param( 10, $dbEntry->evalue,           SQL_DOUBLE );
770
        $sth->execute();
771
      } elsif ( $dbEntry->isa('Bio::EnsEMBL::OntologyXref') ) {
772
        $sth = $self->prepare( "
773
             INSERT ignore INTO ontology_xref
774
                SET object_xref_id = ?,
775
                    source_xref_id = ?,
776
                    linkage_type = ? " );
777 778 779 780
        foreach my $info ( @{ $dbEntry->get_all_linkage_info() } ) {
            my ( $linkage_type, $sourceXref ) = @{$info};
            my $sourceXid = undef;
            if ($sourceXref) {
781
              $sourceXref->is_stored( $self->dbc ) || $self->store($sourceXref, undef, undef, $ignore_release);
782 783 784 785 786 787 788
              $sourceXid = $sourceXref->dbID;
            }
            $sth->bind_param( 1, $object_xref_id, SQL_INTEGER );
            $sth->bind_param( 2, $sourceXid, SQL_INTEGER );
            $sth->bind_param( 3, $linkage_type,  SQL_VARCHAR );
            $sth->execute();
        } #end foreach
789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831
        
        $sth = $self->prepare( "
             INSERT ignore INTO associated_xref
                SET object_xref_id = ?,
                    xref_id = ?,
                    source_xref_id = ?,
                    condition_type = ?,
                    associated_group_id = ?,
                    rank = ? " );
        
        my $annotext = $dbEntry->get_all_associated_xrefs();
        foreach my $ax_group (sort keys %{ $annotext }) {
          my $group = $annotext->{$ax_group};
          my $gsth = $self->prepare( " 
                  INSERT INTO associated_group 
                    SET description = ?;" );
          $sth->bind_param( 1, $ax_group,     SQL_INTEGER );
          $gsth->execute();
          my $associatedGid = $self->last_insert_id();
          
          foreach my $ax_rank (sort keys %{ $group }) {
            my @ax = @{ $group->{$ax_rank} };
            
            my $associatedXid = undef;
            my $sourceXid = undef;
            
            $ax[0]->is_stored( $self->dbc ) || $self->store($ax[0]);
            $associatedXid = $ax[0]->dbID;
            $ax[1]->is_stored( $self->dbc ) || $self->store($ax[1]);
            $sourceXid = $ax[1]->dbID;
            
            if (!defined $associatedXid || !defined $sourceXid) {
              next;
            }
            $sth->bind_param( 1, $object_xref_id,     SQL_INTEGER );
            $sth->bind_param( 2, $associatedXid,      SQL_INTEGER );
            $sth->bind_param( 3, $sourceXid,          SQL_INTEGER );
            $sth->bind_param( 4, $ax[2],              SQL_VARCHAR );
            $sth->bind_param( 5, $associatedGid,      SQL_VARCHAR );
            $sth->bind_param( 6, $ax_rank,            SQL_INTEGER );
            $sth->execute();
          }
        } #end foreach
832 833 834 835 836
      } #end elsif
    } # end if ($object_xref_id)
    return $object_xref_id;
}

837 838
=head2 get_external_db_id

839 840 841 842 843 844 845 846 847 848 849 850 851
  Arg [1]    : String
               The external DB name to query by. Supports LIKE statements
  Arg [2]    : String (optional) 
               External DB release to use. If not specified then we 
               will search for NULL db_release entries
  Arg [3]    : Boolean (optional)
               If true we will never look at the db_release value 
               when querying for an external db id
  Description: Looks for the internal identifier of an external DB. You can
               search using direct equality or using like statements specify. We
               only return one value from this method.

               If you want more than one entry use get_external_db_ids().
852 853 854 855 856 857
  Exceptions : None
  Returntype : Int 

=cut

sub get_external_db_id {
858 859 860 861 862
  my $self = shift;
  my $db_ids = $self->get_external_db_ids(@_);
  return shift @$db_ids;
}

863 864 865 866 867 868 869 870 871 872 873 874 875 876 877
=head2 get_external_db_ids

  Arg [1]    : String
               The external DB name to query by. Supports LIKE statements
  Arg [2]    : String (optional) 
               External DB release to use. If not specified then we 
               will search for NULL db_release entries
  Arg [3]    : Boolean (optional)
               If true we will never look at the db_release value 
               when querying for an external db id
  Description: Looks for the internal identifier of an external DB. You can
               search using direct equality or using like statements specify. We
               only return one value from this method. Returns more than one value
  Exceptions : None
  Returntype : ArrayRef of Int 
878 879 880 881 882 883 884 885 886 887 888

=cut

sub get_external_db_ids {
    my ($self, $db_name, $db_release, $ignore_release) = @_;
    my $sql_helper = $self->dbc->sql_helper;
    my $sql = 'SELECT external_db_id FROM external_db WHERE db_name';
    if ($db_name =~ /%|_/) { 
        $sql .= ' LIKE ?';
    } else {
        $sql .= ' = ?';
889
    }
890 891 892 893 894 895 896 897 898 899 900 901 902 903
    my @bound_params;
    push @bound_params,$db_name;
    unless ($ignore_release) {
        if ($db_release) {
            $sql .= ' AND db_release = ?';
            push @bound_params,$db_release;
        } 
        else {
            $sql .= ' AND db_release is NULL';
        }
    }
    
    my @db_ids = @{ $sql_helper->execute_simple(-SQL => $sql, -PARAMS => \@bound_params) };
    return \@db_ids;
904 905
}

906 907 908 909 910 911 912 913 914 915 916 917 918 919 920
=head2 get_distinct_external_dbs

  Description: Queries the external_db table for all unique 
               DB names
  Exceptions : None
  Returntype : ArrayRef of String

=cut

sub get_distinct_external_dbs {
  my ($self) = @_;
  my $sql = 'SELECT DISTINCT db_name FROM external_db';
  my $names =  $self->dbc->sql_helper->execute_simple(-SQL => $sql);
  return [ sort @{$names} ];
}
921

922
=head2 _check_external_db 
923

924 925 926 927 928 929 930 931 932
  Arg [1]    : DBEntry object
  Arg [2]    : Ignore version flag
  Description: Looks for a record of the given external database
  Exceptions : Throws on missing external database entry
  Returntype : Int 

=cut

sub _check_external_db {
933 934 935 936 937 938 939 940 941 942 943 944 945 946
  my ($self,$db_entry,$ignore) = @_;
  my ($db_name,$db_release);
  $db_name = $db_entry->dbname();
  $db_release = $db_entry->release();
  my $db_id = $self->get_external_db_id($db_name, $db_release, $ignore);
  
  if ($db_id) {
    return $db_id;
  }
  else {
    throw( sprintf( "external_db [%s] release [%s] does not exist",
                   $db_name, $db_release)
    );
  }
947 948
}

Nathan Johnson's avatar
Nathan Johnson committed
949
=head2 _store_or_fetch_xref
950 951 952 953 954 955 956 957

    Arg [1]    : DBEntry object
    Arg [2]    : Database accession for external database
    Description: Thread-safe method for adding xrefs, or otherwise returning
                 an xref ID for the inserted or retrieved xref. Also inserts
                 synonyms for that xref when entire new 
    Returns    : Int - the DB ID of the xref after insertion 
=cut
958

959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975
sub _store_or_fetch_xref {
    my $self = shift;
    my $dbEntry = shift;
    my $dbRef = shift;
    my $xref_id;
    
    my $sth = $self->prepare( "
       INSERT IGNORE INTO xref
       SET dbprimary_acc = ?,
           display_label = ?,
           version = ?,
           description = ?,
           external_db_id = ?,
           info_type = ?,
           info_text = ?");
    $sth->bind_param(1, $dbEntry->primary_id,SQL_VARCHAR);
    $sth->bind_param(2, $dbEntry->display_id,SQL_VARCHAR);
Andy Yates's avatar
Andy Yates committed
976
    $sth->bind_param(3, ($dbEntry->version || q{0}),SQL_VARCHAR);
977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010
    $sth->bind_param(4, $dbEntry->description,SQL_VARCHAR);
    $sth->bind_param(5, $dbRef,SQL_INTEGER);
    $sth->bind_param(6, ($dbEntry->info_type || 'NONE'), SQL_VARCHAR);
    $sth->bind_param(7, ($dbEntry->info_text || ''), SQL_VARCHAR);

    $sth->execute();
    $xref_id = $self->last_insert_id('xref_id',undef,'xref');
    $sth->finish();
    
    if ($xref_id) { #insert was successful, store supplementary synonyms
        # thread safety no longer an issue.
        my $synonym_check_sth = $self->prepare(
                  "SELECT xref_id, synonym
                   FROM external_synonym
                   WHERE xref_id = ?
                   AND synonym = ?");
    
        my $synonym_store_sth = $self->prepare(
            "INSERT ignore INTO external_synonym
             SET xref_id = ?, synonym = ?");
    
        my $synonyms = $dbEntry->get_all_synonyms();
        foreach my $syn ( @$synonyms ) {
            $synonym_check_sth->bind_param(1,$xref_id,SQL_INTEGER);
            $synonym_check_sth->bind_param(2,$syn,SQL_VARCHAR);
            $synonym_check_sth->execute();
            my ($dbSyn) = $synonym_check_sth->fetchrow_array();
            $synonym_store_sth->bind_param(1,$xref_id,SQL_INTEGER);
            $synonym_store_sth->bind_param(2,$syn,SQL_VARCHAR);
            $synonym_store_sth->execute() if(!$dbSyn);
        }
        $synonym_check_sth->finish();
        $synonym_store_sth->finish();
        
1011
    } else { # xref_id already exists, retrieve it according to fields in the unique key
1012
        my $sql = 'SELECT xref_id FROM xref 
1013
            WHERE dbprimary_acc = ?
1014
            AND version =?
1015 1016
            AND external_db_id = ?
            AND info_type = ?
1017
            AND info_text = ?';
1018 1019
        my $info_type = $dbEntry->info_type() || 'NONE';
        my $info_text = $dbEntry->info_text() || q{};
1020
        my $version = $dbEntry->version() || q{0};
1021
        $sth = $self->prepare( $sql );
Nathan Johnson's avatar
Nathan Johnson committed
1022

1023
        $sth->bind_param(1, $dbEntry->primary_id,SQL_VARCHAR);
1024
        $sth->bind_param(2, $version, SQL_VARCHAR);
Andy Yates's avatar
Andy Yates committed
1025 1026 1027
        $sth->bind_param(3, $dbRef, SQL_INTEGER);
        $sth->bind_param(4, $info_type, SQL_VARCHAR);
        $sth->bind_param(5, $info_text, SQL_VARCHAR);
1028
        $sth->execute();
Nathan Johnson's avatar
Nathan Johnson committed
1029 1030 1031



1032 1033
        ($xref_id) = $sth->fetchrow_array();
        $sth->finish;
1034
        if(!$xref_id) {
1035
          my $msg = 'Cannot find an xref id for %s (version=%d) with external db id %d.';
1036
          throw(sprintf($msg, $dbEntry->primary_id(), $version, $dbRef))
1037
        }
1038 1039 1040 1041
    }
    
    return $xref_id;
}
1042

1043 1044 1045 1046 1047
=head2 exists

  Arg [1]    : Bio::EnsEMBL::DBEntry $dbe
  Example    : if($dbID = $db_entry_adaptor->exists($dbe)) { do stuff; }
  Description: Returns the db id of this DBEntry if it exists in this database
1048
               otherwise returns undef.  Exists is defined as an entry with
1049 1050 1051 1052
               the same external_db and display_id
  Returntype : int
  Exceptions : thrown on incorrect args
  Caller     : GeneAdaptor::store, TranscriptAdaptor::store
1053
  Status     : Stable
1054 1055 1056 1057

=cut

sub exists {
1058
  my ($self, $dbe) = @_ ;
1059 1060

  unless($dbe && ref $dbe && $dbe->isa('Bio::EnsEMBL::DBEntry')) {
1061
    throw("arg must be a Bio::EnsEMBL::DBEntry not [$dbe]");
1062
  }
1063

1064
  my $sth = $self->prepare('SELECT x.xref_id
1065 1066
                            FROM   xref x, external_db xdb
                            WHERE  x.external_db_id = xdb.external_db_id
1067
                            AND    x.display_label = ?
1068 1069
                            AND    xdb.db_name = ?
                            AND    x.dbprimary_acc = ?');
1070

1071
  $sth->bind_param(1,$dbe->display_id,SQL_VARCHAR);
Glenn Proctor's avatar
Glenn Proctor committed
1072
  $sth->bind_param(2,$dbe->dbname,SQL_VARCHAR);
1073
  $sth->bind_param(3,$dbe->primary_id,SQL_VARCHAR);
1074
  $sth->execute();
1075 1076 1077 1078 1079 1080 1081 1082 1083

  my ($dbID) = $sth->fetchrow_array;

  $sth->finish;

  return $dbID;
}


1084
=head2 fetch_all_by_Gene
Graham McVicker's avatar
Graham McVicker committed
1085

1086
  Arg [1]    : Bio::EnsEMBL::Gene $gene
1087
               (The gene to retrieve DBEntries for)
1088 1089 1090
  Arg [2]    : optional external database name. SQL wildcards are accepted
  Arg [3]    : optional external_db type. SQL wildcards are accepted
  Example    : @db_entries = @{$db_entry_adaptor->fetch_all_by_Gene($gene)};
1091 1092 1093
  Description: This returns a list of DBEntries associated with this gene.
               Note that this method was changed in release 15.  Previously
               it set the DBLinks attribute of the gene passed in to contain
1094
               all of the gene, transcript, and translation xrefs associated
1095
               with this gene.
1096
  Returntype : listref of Bio::EnsEMBL::DBEntries; may be of type IdentityXref if
1097
               there is mapping data, or OntologyXref if there is linkage data.
1098
  Exceptions : thows if gene object not passed
Graham McVicker's avatar
Graham McVicker committed
1099
  Caller     : Bio::EnsEMBL::Gene
1100
  Status     : Stable
Graham McVicker's avatar
Graham McVicker committed
1101 1102 1103

=cut

1104
sub fetch_all_by_Gene {
1105
  my ( $self, $gene, $ex_db_reg, $exdb_type ) = @_;
1106

1107 1108 1109
  if(!ref($gene) || !$gene->isa('Bio::EnsEMBL::Gene')) {
    throw("Bio::EnsEMBL::Gene argument expected.");
  }
1110

1111
  return $self->_fetch_by_object_type($gene->dbID(), 'Gene', $ex_db_reg, $exdb_type);
Arne Stabenau's avatar
Arne Stabenau committed
1112 1113
}

1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128
=head2 fetch_all_by_Operon

  Arg [1]    : Bio::EnsEMBL::Operon $operon
               (The operon to retrieve DBEntries for)
  Arg [2]    : optional external database name. SQL wildcards are accepted
  Arg [3]    : optional external_db type. SQL wildcards are accepted
  Example    : @db_entries = @{$db_entry_adaptor->fetch_all_by_Operon($operon)};
  Description: This returns a list of DBEntries associated with this operon.
  Returntype : listref of Bio::EnsEMBL::DBEntries; may be of type IdentityXref if
               there is mapping data, or OntologyXref if there is linkage data.
  Exceptions : thows if operon object not passed
  Caller     : general

=cut

1129 1130 1131 1132 1133 1134 1135 1136 1137 1138
sub fetch_all_by_Operon {
  my ( $self, $gene, $ex_db_reg, $exdb_type ) = @_;

  if(!ref($gene) || !$gene->isa('Bio::EnsEMBL::Operon')) {
    throw("Bio::EnsEMBL::Operon argument expected.");
  }

  return $self->_fetch_by_object_type($gene->dbID(), 'Operon', $ex_db_reg, $exdb_type);
}

Graham McVicker's avatar
Graham McVicker committed
1139

1140
=head2 fetch_all_by_Transcript
Graham McVicker's avatar
Graham McVicker committed
1141

Graham McVicker's avatar
Graham McVicker committed
1142
  Arg [1]    : Bio::EnsEMBL::Transcript
1143 1144 1145
  Arg [2]    : optional external database name. SQL wildcards are accepted
  Arg [3]    : optional external_db type. SQL wildcards are accepted
  Example    : @db_entries = @{$db_entry_adaptor->fetch_all_by_Transcript($trans)};
1146
  Description: This returns a list of DBEntries associated with this
1147 1148 1149
               transcript. Note that this method was changed in release 15.
               Previously it set the DBLinks attribute of the gene passed in
               to contain all of the gene, transcript, and translation xrefs
1150
               associated with this gene.
1151
  Returntype : listref of Bio::EnsEMBL::DBEntries; may be of type IdentityXref if
1152
               there is mapping data, or OntologyXref if there is linkage data.
1153
  Exceptions : throes if transcript argument not passed
1154
  Caller     : Bio::EnsEMBL::Transcript
1155
  Status     : Stable
Graham McVicker's avatar
Graham McVicker committed
1156 1157 1158

=cut

1159
sub fetch_all_by_Transcript {
1160
  my ( $self, $trans, $ex_db_reg, $exdb_type ) = @_;
1161

1162 1163 1164 1165
  if(!ref($trans) || !$trans->isa('Bio::EnsEMBL::Transcript')) {
    throw("Bio::EnsEMBL::Transcript argument expected.");
  }

1166
  return $self->_fetch_by_object_type( $trans->dbID(), 'Transcript', $ex_db_reg, $exdb_type);
1167 1168
}

Graham McVicker's avatar
Graham McVicker committed
1169

1170
=head2 fetch_all_by_Translation
Graham McVicker's avatar
Graham McVicker committed
1171

Graham McVicker's avatar
Graham McVicker committed
1172
  Arg [1]    : Bio::EnsEMBL::Translation $trans
1173
               (The translation to fetch database entries for)
1174 1175
  Arg [2]    : optional external database name. SQL wildcards are accepted
  Arg [3]    : optional externaldb type. SQL wildcards are accepted
1176
  Example    : @db_entries = @{$db_entry_adptr->fetch_all_by_Translation($trans)};
Graham McVicker's avatar
Graham McVicker committed
1177
  Description: Retrieves external database entries for an EnsEMBL translation
1178
  Returntype : listref of Bio::EnsEMBL::DBEntries; may be of type IdentityXref if
1179
               there is mapping data, or OntologyXref if there is linkage data.
1180
  Exceptions : throws if translation object not passed
Graham McVicker's avatar
Graham McVicker committed
1181
  Caller     : general
1182
  Status     : Stable
Graham McVicker's avatar
Graham McVicker committed
1183 1184 1185

=cut

1186
sub fetch_all_by_Translation {
1187
  my ( $self, $trans, $ex_db_reg, $exdb_type ) = @_;
1188