EnsEMBL/DBSQL/BaseAdaptor.pm untested

filter: Statementstmt 0.0% 0 / 338 Branchbran 0.0% 0 / 142 Conditioncond 0.0% 0 / 62 Subroutinesub 0.0% 0 / 43 Podpod 0.0% 0 / 35 totaltotal 0.0% 0 / 620 CC 72 SCAR 42.5
CC
72
Cov
0%
_generate_sql
272.0
_uncached_fetch_all_by_id_list
156.0
generate_in_constraint
56.0
CRAP 70.0
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  
22 =head1 CONTACT
23  
24 Please email comments or questions to the public Ensembl
25 developers list at <http://lists.ensembl.org/mailman/listinfo/dev>.
26  
27 Questions may also be sent to the Ensembl help desk at
28 <http://www.ensembl.org/Help/Contact>.
29  
30 =cut
31  
32 =head1 NAME
33  
34 Bio::EnsEMBL::DBSQL::BaseAdaptor - Base Adaptor for DBSQL adaptors
35  
36 =head1 SYNOPSIS
37  
38 # base adaptor provides
39  
40 # SQL prepare function
41 $adaptor->prepare("sql statement");
42  
43 # get of root DBAdaptor object
44 $adaptor->db();
45  
46 # constructor, ok for inheritence
47 $adaptor = Bio::EnsEMBL::DBSQL::SubClassOfBaseAdaptor->new($dbobj);
48  
49 =head1 DESCRIPTION
50  
51 This is a true base class for Adaptors in the Ensembl DBSQL
52 system.
53  
54 Adaptors are expected to have the following functions
55  
56 $obj = $adaptor->fetch_by_dbID($internal_id);
57  
58 which builds the object from the primary key of the object. This
59 function is crucial because it allows adaptors to collaborate relatively
60 independently of each other - in other words, we can change the schema
61 under one adaptor without too many knock on changes through the other
62 adaptors.
63  
64 Most adaptors will also have
65  
66 $dbid = $adaptor->store($obj);
67  
68 which stores the object. Currently the storing of an object also causes
69 the objects to set
70  
71 $obj->dbID();
72  
73 correctly and attach the adaptor.
74  
75 Other fetch functions go by the convention of
76  
77 @object_array = @{ $adaptor->fetch_all_by_XXXX($arguments_for_XXXX) };
78  
79 sometimes it returns an array ref denoted by the 'all' in the name of
80 the method, sometimes an individual object. For example
81  
82 $gene = $gene_adaptor->fetch_by_stable_id($stable_id);
83  
84 or
85  
86 @fp = @{ $simple_feature_adaptor->fetch_all_by_Slice($slice) };
87  
88 Occassionally adaptors need to provide access to lists of ids. In this
89 case the convention is to go list_XXXX, such as
90  
91 @gene_ids = @{ $gene_adaptor->list_geneIds() };
92  
93 (note: this method is poorly named)
94  
95 =cut
96  
97 package Bio::EnsEMBL::DBSQL::BaseAdaptor;
98 $Bio::EnsEMBL::DBSQL::BaseAdaptor::VERSION = '114.0.0_50'; # TRIAL
99 $Bio::EnsEMBL::DBSQL::BaseAdaptor::VERSION = '114.0.050';
100 require Exporter;
101 use vars qw(@ISA @EXPORT);
102 use strict;
103  
104 use Bio::EnsEMBL::Utils::Exception qw(throw);
105 use Bio::EnsEMBL::Utils::Scalar qw(wrap_array);
106 use DBI qw(:sql_types);
107 use Data::Dumper;
108 use Scalar::Util qw/looks_like_number/;
109  
110 @ISA = qw(Exporter);
111 @EXPORT = (@{$DBI::EXPORT_TAGS{'sql_types'}});
112  
113 =head2 new
114  
115 Arg [1] : Bio::EnsEMBL::DBSQL::DBConnection $dbobj
116 Example : $adaptor = new AdaptorInheritedFromBaseAdaptor($dbobj);
117 Description: Creates a new BaseAdaptor object. The intent is that this
118 constructor would be called by an inherited superclass either
119 automatically or through $self->SUPER::new in an overridden
120 new method.
121 Returntype : Bio::EnsEMBL::DBSQL::BaseAdaptor
122 Exceptions : none
123 Caller : Bio::EnsEMBL::DBSQL::DBConnection
124 Status : Stable
125  
126 =cut
127  
128 sub new {
129 my ( $class, $dbobj ) = @_;
130  
131 my $self = bless {}, $class;
132  
133 if ( !defined $dbobj || !ref $dbobj ) {
134 throw("Don't have a db [$dbobj] for new adaptor");
135 }
136  
137 if ( $dbobj->isa('Bio::EnsEMBL::DBSQL::DBAdaptor') ) {
138 $self->db($dbobj);
139 $self->dbc( $dbobj->dbc );
140 $self->species_id( $dbobj->species_id() );
141 $self->is_multispecies( $dbobj->is_multispecies() );
142 } elsif ( ref($dbobj) =~ /DBAdaptor$/ ) {
143 $self->db($dbobj);
144 $self->dbc( $dbobj->dbc );
145 } elsif ( ref($dbobj) =~ /DBConnection$/ ) {
146 $self->dbc($dbobj);
147 } else {
148 throw("Don't have a DBAdaptor [$dbobj] for new adaptor");
149 }
150  
151 return $self;
152 }
153  
154  
155 =head2 prepare
156  
157 Arg [1] : string $string
158 a SQL query to be prepared by this adaptors database
159 Example : $sth = $adaptor->prepare("select yadda from blabla")
160 Description: provides a DBI statement handle from the adaptor. A convenience
161 function so you dont have to write $adaptor->db->prepare all the
162 time
163 Returntype : DBI::StatementHandle
164 Exceptions : none
165 Caller : Adaptors inherited from BaseAdaptor
166 Status : Stable
167  
168 =cut
169  
170 sub prepare {
171 my ( $self, $string ) = @_;
172  
173 # Uncomment next line to cancel caching on the SQL side.
174 # Needed for timing comparisons etc.
175 #$string =~ s/SELECT/SELECT SQL_NO_CACHE/i;
176  
177 return $self->dbc->prepare($string);
178 }
179  
180  
181 =head2 db
182  
183 Arg [1] : (optional) Bio::EnsEMBL::DBSQL::DBAdaptor $obj
184 the database this adaptor is using.
185 Example : $db = $adaptor->db();
186 Description: Getter/Setter for the DatabaseConnection that this adaptor is
187 using.
188 Returntype : Bio::EnsEMBL::DBSQL::DBAdaptor
189 Exceptions : none
190 Caller : Adaptors inherited from BaseAdaptor
191 Status : Stable
192  
193 =cut
194  
195 sub db {
196 my ( $self, $value ) = @_;
197  
198 if ( defined($value) ) {
199 $self->{'db'} = $value;
200 }
201  
202 return $self->{'db'};
203 }
204  
205 =head2 dbc
206  
207 Arg [1] : (optional) Bio::EnsEMBL::DBSQL::DBConnection $obj
208 the database this adaptor is using.
209 Example : $db = $adaptor->db();
210 Description: Getter/Setter for the DatabaseConnection that this adaptor is
211 using.
212 Returntype : Bio::EnsEMBL::DBSQL::DBConnection
213 Exceptions : none
214 Caller : Adaptors inherited from BaseAdaptor
215 Status : Stable
216  
217 =cut
218  
219 sub dbc {
220 my ( $self, $value ) = @_;
221  
222 if ( defined($value) ) {
223 $self->{'dbc'} = $value;
224 }
225  
226 return $self->{'dbc'};
227 }
228  
229 =head2 is_multispecies
230  
231 Arg [1] : (optional) boolean $arg
232 Example : if ($adaptor->is_multispecies()) { }
233 Description: Getter/Setter for the is_multispecies boolean of
234 to use for this adaptor.
235 Returntype : boolean
236 Exceptions : none
237 Caller : general
238 Status : Stable
239  
240 =cut
241  
242 sub is_multispecies {
243 my ( $self, $arg ) = @_;
244  
245 if ( defined($arg) ) {
246 $self->{_is_multispecies} = $arg;
247 }
248  
249 return $self->{_is_multispecies};
250 }
251  
252 =head2 species_id
253  
254 Arg [1] : (optional) int $species_id
255 The internal ID of the species in a multi-species database.
256 Example : $db = $adaptor->db();
257 Description: Getter/Setter for the internal ID of the species in a
258 multi-species database. The default species ID is 1.
259 Returntype : Integer
260 Exceptions : none
261 Caller : Adaptors inherited from BaseAdaptor
262 Status : Stable
263  
264 =cut
265  
266 sub species_id {
267 my ( $self, $value ) = @_;
268  
269 if ( defined($value) ) {
270 $self->{'species_id'} = $value;
271 }
272  
273 return $self->{'species_id'} || 1;
274 }
275  
276  
277 # list primary keys for a particular table
278 # args are table name and primary key field
279 # if primary key field is not supplied, tablename_id is assumed
280 # returns listref of IDs
281 sub _list_dbIDs {
282 my ( $self, $table, $pk, $ordered ) = @_;
283  
284 if ( !defined($pk) ) { $pk = $table . "_id" }
285  
286 my $sql = sprintf( "SELECT `%s` FROM `%s`", $pk, $table );
287  
288 my $join_with_cs = 0;
289 if ( $self->is_multispecies()
290 && $self->isa('Bio::EnsEMBL::DBSQL::BaseFeatureAdaptor')
291 && !$self->isa('Bio::EnsEMBL::DBSQL::UnmappedObjectAdaptor') )
292 {
293
294 $sql .= q(
295 JOIN seq_region USING (seq_region_id)
296 JOIN coord_system cs USING (coord_system_id)
297 WHERE cs.species_id = ?
298 );
299  
300 $join_with_cs = 1;
301 }
302  
303 if ( defined($ordered) && $ordered ) {
304 $sql .= " ORDER BY seq_region_id, seq_region_start";
305 }
306  
307 my $sth = $self->prepare($sql);
308  
309 if ($join_with_cs) {
310 $sth->bind_param( 1, $self->species_id(), SQL_INTEGER );
311 }
312  
313 eval { $sth->execute() };
314 if ($@) {
315 throw("Detected an error whilst executing SQL '${sql}': $@");
316 }
317  
318 my $id;
319 $sth->bind_col( 1, \$id );
320  
321 my @out;
322 while ( $sth->fetch() ) {
323 push( @out, $id );
324 }
325  
326 return \@out;
327 } ## end sub _list_dbIDs
328  
329  
330 # _straight_join
331  
332 # Arg [1] : (optional) boolean $new_val
333 # Example : $self->_straight_join(1);
334 # $self->generic_fetch($constraint);
335 # $self->_straight_join(0);
336 # Description: PROTECTED Getter/Setter that turns on/off the use of
337 # a straight join in queries.
338 # Returntype : boolean
339 # Exceptions : none
340 # Caller : general
341  
342 sub _straight_join {
343 my $self = shift;
344 if(@_) {
345 $self->{'_straight_join'} = shift;
346 }
347  
348 return $self->{'_straight_join'};
349 }
350  
351 sub _can_straight_join {
352 my $self = shift;
353 return $self->dbc->_driver_object->can_straight_join;
354 }
355  
356 =head2 bind_param_generic_fetch
357  
358 Arg [1] : (optional) scalar $param
359 This is the parameter to bind
360 Arg [2] : (optional) int $sql_type
361 Type of the parameter (from DBI (:sql_types))
362 Example : $adaptor->bind_param_generic_fetch($stable_id,SQL_VARCHAR);
363 $adaptor->generic_fetch();
364 Description: When using parameters for the query, will call the bind_param to avoid
365 some security issues. If there are no arguments, will return the bind_parameters
366 ReturnType : listref
367 Exceptions: if called with one argument
368  
369 =cut
370  
371 sub bind_param_generic_fetch{
372 my $self = shift;
373 my $param = shift;
374 my $sql_type = shift;
375  
376 if (defined $param && !defined $sql_type){
377 throw("Need to specify sql_type for parameter $param\n");
378 }
379 elsif (defined $param && defined $sql_type){
380 #check when there is a SQL_INTEGER type that the parameter is really a number
381 if ($sql_type eq SQL_INTEGER){
382 throw "Trying to assign a non numerical parameter to an integer value in the database" if ($param !~ /^[+-]{0,1}\d+$/);
383 }
384 #both paramters have been entered, push it to the bind_param array
385 push @{$self->{'_bind_param_generic_fetch'}},[$param,$sql_type];
386 }
387 elsif (!defined $param && !defined $sql_type){
388 #when there are no arguments, return the array
389 return $self->{'_bind_param_generic_fetch'};
390 }
391
392 }
393  
394 # Used to reset the params without circumventing scope
395 sub _bind_param_generic_fetch {
396 my ($self, $_bind_param_generic_fetch) = @_;
397 $self->{'_bind_param_generic_fetch'} = $_bind_param_generic_fetch if $_bind_param_generic_fetch;
398 return $self->{_bind_param_generic_fetch};
399 }
400  
401 =head2 generate_in_constraint
402
403 Arg [1] : ArrayRef or Scalar $list
404 List or a single value of items to be pushed into an IN statement
405 Arg [2] : Scalar $column
406 Column this IN statement is being applied to. Please fully resolve the
407 column.
408 Arg [3] : Scalar $param_type
409 Data type which should be used when binding. Please use DBI data type symbols
410 Arg [4] : Scalar boolean $inline_variables
411 Boolean to control if variables are inlined in the constraint. If
412 false values are bound via bind_param_generic_fetch() (the default behaviour).
413  
414 Description : Used internally to generate a SQL constraint to restrict a query by an IN statement.
415 The code generates the complete IN statement.
416 Returntype : String
417 Exceptions : If no list is supplied, the list of values is empty or no data type was given
418 Caller : general
419  
420 =cut
421  
422 sub generate_in_constraint {
423 my ($self, $list, $column, $param_type, $inline_variables) = @_;
424 throw("A list of values must be given") if ! defined $list;
425 $list = wrap_array($list); # homogenise into an array
426 throw "We should be given at least one value to insert" if scalar(@{$list}) == 0;
427 throw "Please supply the DBI param type" if ! defined $param_type;
428 #Figure out if we need to quote our values if we are asked to inline the variables
429 my $quote_values = 1;
430 if($param_type == SQL_INTEGER || $param_type == SQL_TINYINT || $param_type == SQL_DOUBLE ) {
431 $quote_values = 0;
432 }
433  
434 my $constraint = qq{${column} IN (};
435 if($inline_variables) {
436 if($quote_values) {
437 $constraint .= join(q{,}, map { qq{"${_}"} } @{$list});
438 }
439 else {
440 $constraint .= join(q{,}, @{$list});
441 }
442 }
443 else {
444 my @subs = ('?') x scalar(@{$list});
445 $constraint .= join(q{,}, @subs);
446 $self->bind_param_generic_fetch($_, $param_type) for @{$list};
447 }
448 $constraint .= q{)};
449 return $constraint;
450 }
451  
452 =head2 generic_fetch
453  
454 Arg [1] : (optional) string $constraint
455 An SQL query constraint (i.e. part of the WHERE clause)
456 Arg [2] : (optional) Bio::EnsEMBL::AssemblyMapper $mapper
457 A mapper object used to remap features
458 as they are retrieved from the database
459 Arg [3] : (optional) Bio::EnsEMBL::Slice $slice
460 A slice that features should be remapped to
461 Example : $fts = $a->generic_fetch('contig_id in (1234, 1235)');
462 Description: Performs a database fetch and returns feature objects in
463 contig coordinates.
464 Returntype : listref of Bio::EnsEMBL::SeqFeature in contig coordinates
465 Exceptions : Thrown if there is an issue with querying the data
466 Caller : BaseFeatureAdaptor, ProxyDnaAlignFeatureAdaptor::generic_fetch
467 Status : Stable
468  
469 =cut
470  
471 sub generic_fetch {
472 my ($self, $constraint, $mapper, $slice) = @_;
473 my $sql = $self->_generate_sql($constraint);
474 my $params = $self->bind_param_generic_fetch();
475 $params ||= [];
476 $self->{_bind_param_generic_fetch} = undef;
477 my $sth = $self->db()->dbc()->prepare($sql);
478 my $i = 1;
479 foreach my $param (@{$params}){
480 $sth->bind_param($i,$param->[0],$param->[1]);
481 $i++;
482 }
483 eval { $sth->execute() };
484 if ($@) {
485 throw("Detected an error whilst executing SQL '${sql}': $@");
486 }
487  
488 my $res = $self->_objs_from_sth($sth, $mapper, $slice);
489 $sth->finish();
490 return $res;
491 }
492  
493 =head2 generic_count
494  
495 Arg [1] : (optional) string $constraint
496 An SQL query constraint (i.e. part of the WHERE clause)
497 Example : $number_feats = $a->generic_count('contig_id in (1234, 1235)');
498 Description: Performs a database fetch and returns a count of those features
499 found. This is analagous to C<generic_fetch()>
500 Returntype : Integer count of the elements.
501 Exceptions : Thrown if there is an issue with querying the data
502  
503 =cut
504  
505 sub generic_count {
506 my ($self, $constraint) = @_;
507 my $sql = $self->_generate_sql($constraint, 'count(*)');
508 my $params = $self->bind_param_generic_fetch();
509 $params ||= [];
510 $self->{_bind_param_generic_fetch} = undef;
511 my $h = $self->db()->dbc()->sql_helper();
512 my $count = $h->execute_single_result(-SQL => $sql, -PARAMS => $params);
513 return $count;
514 }
515  
516 sub _generate_sql {
517 my ($self, $constraint, @input_columns) = @_;
518
519 my @tabs = $self->_tables();
520  
521 my $extra_default_where;
522  
523 # Hack for feature types that needs to be restricted to species_id (in
524 # coord_system).
525 if ( $self->is_multispecies()
526 && $self->isa('Bio::EnsEMBL::DBSQL::BaseFeatureAdaptor')
527 && !$self->isa('Bio::EnsEMBL::DBSQL::BaseAlignFeatureAdaptor')
528 && !$self->isa('Bio::EnsEMBL::DBSQL::UnmappedObjectAdaptor') )
529 {
530 # We do a check to see if there is already seq_region
531 # and coord_system defined to ensure we get the right
532 # alias. We then do the extra query irrespectively of
533 # what has already been specified by the user.
534 my %thash = map { $_->[0] => $_->[1] } @tabs;
535  
536 my $sr_alias =
537 ( exists( $thash{seq_region} ) ? $thash{seq_region} : 'sr' );
538 my $cs_alias =
539 ( exists( $thash{coord_system} ) ? $thash{coord_system} : 'cs' );
540  
541 if ( !exists( $thash{seq_region} ) ) {
542 push( @tabs, [ 'seq_region', $sr_alias ] );
543 }
544 if ( !exists( $thash{coord_system} ) ) {
545 push( @tabs, [ 'coord_system', $cs_alias ] );
546 }
547  
548 $extra_default_where = sprintf(
549 '%s.seq_region_id = %s.seq_region_id '
550 . 'AND %s.coord_system_id = %s.coord_system_id '
551 . 'AND %s.species_id = ?',
552 $tabs[0]->[1], $sr_alias, $sr_alias,
553 $cs_alias, $cs_alias );
554  
555 $self->bind_param_generic_fetch( $self->species_id(), SQL_INTEGER );
556 } ## end if ( $self->is_multispecies...)
557  
558 @input_columns = $self->_columns() if ! @input_columns;
559 my $columns = join(', ', @input_columns);
560  
561 #
562 # Construct a left join statement if one was defined, and remove the
563 # left-joined table from the table list
564 #
565 my @left_join_list = $self->_left_join();
566 my $left_join_prefix = '';
567 my $left_join = '';
568 my @tables;
569 if(@left_join_list) {
570 my %left_join_hash = map { $_->[0] => $_->[1] } @left_join_list;
571 while(my $t = shift @tabs) {
572 my $t_alias = $t->[0] . " " . $t->[1];
573 if( exists $left_join_hash{ $t->[0] } || exists $left_join_hash{$t_alias}) {
574 my $condition = $left_join_hash{ $t->[0] };
575 $condition ||= $left_join_hash{$t_alias};
576 my $syn = $t->[1];
577 $left_join .=
578 "\n LEFT JOIN " . $t->[0] . " $syn ON $condition ) ";
579 $left_join_prefix .= '(';
580 } else {
581 push @tables, $t;
582 }
583 }
584 } else {
585 @tables = @tabs;
586 }
587  
588 my $straight_join = '';
589  
590 if($self->_straight_join() and $self->_can_straight_join) {
591 $straight_join = "STRAIGHT_JOIN";
592 }
593  
594 #construct a nice table string like 'table1 t1, table2 t2'
595 my $tablenames = join(', ', map({ join(' ', @$_) } @tables));
596  
597 my $sql =
598 "SELECT $straight_join $columns \n"
599 . "FROM $left_join_prefix ($tablenames) $left_join";
600  
601 my $default_where = $self->_default_where_clause();
602 my $final_clause = $self->_final_clause;
603  
604 if ($extra_default_where) {
605 if ($default_where) {
606 $default_where .= "\n AND $extra_default_where";
607 } else {
608 $default_where = $extra_default_where;
609 }
610 }
611  
612 #append a where clause if it was defined
613 if ($constraint) {
614 $sql .= "\n WHERE $constraint ";
615 if ($default_where) {
616 $sql .= " AND\n $default_where ";
617 }
618 } elsif ($default_where) {
619 $sql .= "\n WHERE $default_where ";
620 }
621  
622 #append additional clauses which may have been defined, don't append ORDER BY twice
623 if (index($final_clause, "ORDER") == -1 || index($sql, "ORDER") == -1) {
624 $sql .= "\n$final_clause";
625 }
626
627 # FOR DEBUG:
628 #printf(STDERR "SQL:\n%s\n", $sql);
629
630 return $sql;
631 }
632  
633  
634 =head2 fetch_by_dbID
635  
636 Arg [1] : int $id
637 The unique database identifier for the feature to be obtained
638 Example : $feat = $adaptor->fetch_by_dbID(1234));
639 $feat = $feat->transform('contig');
640 Description: Returns the feature created from the database defined by the
641 the id $id. The feature will be returned in its native
642 coordinate system. That is, the coordinate system in which it
643 is stored in the database. In order to convert it to a
644 particular coordinate system use the transfer() or transform()
645 method. If the feature is not found in the database then
646 undef is returned instead
647 Returntype : Bio::EnsEMBL::Feature or undef
648 Exceptions : thrown if $id arg is not provided
649 does not exist
650 Caller : general
651 Status : Stable
652  
653 =cut
654  
655 sub fetch_by_dbID {
656 my ($self, $id) = @_;
657 if ($self->_no_id_cache()) {
658 return $self->_uncached_fetch_by_dbID($id);
659 }
660 return $self->_id_cache()->get($id);
661 }
662  
663 # The actual implmenetation moved sideways to allow for uncached access
664 # otherwise we'd constantly loop
665  
666 sub _uncached_fetch_by_dbID{
667 my ($self,$id) = @_;
668  
669 throw("id argument is required") if(!defined $id);
670  
671 #construct a constraint like 't1.table1_id = 123'
672 my @tabs = $self->_tables;
673 my ($name, $syn) = @{$tabs[0]};
674 $self->bind_param_generic_fetch($id,SQL_INTEGER);
675 my $constraint = "${syn}.${name}_id = ?";
676  
677 #Should only be one
678 my ($feat) = @{$self->generic_fetch($constraint)};
679  
680 return if(!$feat);
681  
682 return $feat;
683 }
684  
685  
686 =head2 fetch_all_by_dbID_list
687  
688 Arg [1] : listref of integers $id_list
689 The unique database identifiers for the features to
690 be obtained.
691 Arg [2] : optional - Bio::EnsEMBL::Slice to map features onto.
692 Example : @feats = @{$adaptor->fetch_all_by_dbID_list([1234, 2131, 982]))};
693 Description: Returns the features created from the database
694 defined by the the IDs in contained in the provided
695 ID list $id_list. The features will be returned
696 in their native coordinate system. That is, the
697 coordinate system in which they are stored in the
698 database. In order to convert the features to a
699 particular coordinate system use the transfer() or
700 transform() method. If none of the features are
701 found in the database a reference to an empty list is
702 returned.
703 Returntype : listref of Bio::EnsEMBL::Features
704 Exceptions : thrown if $id arg is not provided
705 does not exist
706 Caller : general
707 Status : Stable
708  
709 =cut
710  
711 sub fetch_all_by_dbID_list {
712 my ($self, $id_list_ref, $slice) = @_;
713 if ($self->_no_id_cache()) {
714 return $self->_uncached_fetch_all_by_dbID_list($id_list_ref, $slice);
715 }
716 return $self->_id_cache()->get_by_list($id_list_ref, $slice);
717 }
718  
719 # The actual implmenetation moved sideways to allow for uncached access
720 # otherwise we'd constantly loop
721 sub _uncached_fetch_all_by_dbID_list {
722 my ( $self, $id_list_ref, $slice ) = @_;
723 return $self->_uncached_fetch_all_by_id_list($id_list_ref, $slice, "dbID", 1);
724 } ## end sub fetch_all_by_dbID_list
725  
726 =head2 _uncached_fetch_all_by_id_list
727  
728 Arg [1] : listref of IDs
729 Arg [2] : (optional) Bio::EnsEMBL::Slice $slice
730 A slice that features should be remapped to
731 Arg [3] : String describing the ID type.
732 Valid values include dbID and stable_id. dbID is an alias for
733 the primary key, while other names map directly to table columns
734 of the Feature this adaptor manages.
735 Arg [4] : Boolean $numeric
736 Indicates if the incoming data is to be processed as a numeric
737 or as a String. If arg [3] was set to dbID then we default this to
738 be true. If arg [3] was set to stable_id then we default this to
739 be false.
740 When not using a standard arg[3] the IDs are assumed to be Strings.
741 Arg [5] : Integer $max_size
742 Control the maximum number of IDs sent to a database in a single
743 query. Defaults to 2K for Strings and 16K for integers. Only
744 provide if you know *exactly* why you need to edit it.
745 Example : $list_of_features = $adaptor->_uncached_fetch_all_by_id_list(
746 [qw(ENSG00000101321 ENSG00000101346 ENSG00000101367)],
747 undef,
748 "stable_id", 0); #using strings
749
750 # Numeric set to true because we are using numerics
751 $list_of_features = $adaptor->_uncached_fetch_all_by_id_list(
752 [1,2,3,4],
753 undef,
754 "dbID", 1);
755  
756 # Numeric defaults to true because we are querying using dbID
757 $list_of_features = $adaptor->_uncached_fetch_all_by_id_list(
758 [1,2,3,4],
759 undef,
760 "dbID");
761 Description: This is a generic method used to fetch lists of features by IDs.
762 It avoids caches, meaning it is best suited for block fetching.
763 See fetch_all_by_dbID_list() for more info.
764 Returntype : ArrayRef of Bio::EnsEMBL::Feature
765 Exceptions : Thrown if a list of IDs is not supplied.
766 Caller : BaseFeatureAdaptor, BaseAdaptor and derived classes.
767  
768 =cut
769  
770 sub _uncached_fetch_all_by_id_list {
771 my ( $self, $id_list_ref, $slice, $id_type, $numeric, $max_size ) = @_;
772  
773 if ( !defined($id_list_ref) || ref($id_list_ref) ne 'ARRAY' ) {
774 throw("id_list list reference argument is required");
775 }
776  
777 if ( !@{$id_list_ref} ) { return [] }
778  
779 # Construct a constraint like 't1.table1_id = 123'
780 my @tabs = $self->_tables();
781 my ( $name, $syn ) = @{ $tabs[0] };
782  
783 # prepare column name for query. If the id_type was
784 # set to dbID then we assume the column must be
785 # tablename_id e.g. gene_id. Otherwise we assume the id_type
786 # is the field/column name
787 my $field_name;
788 if($id_type eq 'dbID') {
789 $field_name = $name.'_id';
790 # If numeric was not set default it to 1 since this is an int
791 $numeric = 1 if ! defined $numeric;
792 }
793 elsif($id_type eq 'stable_id') {
794 # If numeric was not set default it to 0 since this is a string
795 $numeric = 0 if ! defined $numeric;
796 $field_name = $id_type;
797 }
798 else {
799 $field_name = $id_type;
800 }
801  
802 my $sql_data_type;
803  
804 # Ensuring we do not exceed MySQL's max_allowed_packet (defaults to 1MB)
805 # by splitting large queries into smaller queries of at most 256KB
806 # (262,144 8-bit characters)
807 # If we had a numeric then really we are talking about working with
808 # integers. Normal max ensembl id size is 12 plus 2 characters for
809 # commas in our IN statement comes to 14. Even bloating this to 16 gives
810 # a max number of 16,384 IDs (262114/16).
811 #
812 if($numeric) {
813 my $first_id = $id_list_ref->[0];
814 if(!looks_like_number($first_id)) {
815 throw "You specified that we are looking for numerics but $first_id is not a numeric";
816 }
817 $max_size = 16384 if ! defined $max_size;
818 $sql_data_type = SQL_INTEGER;
819 }
820 # However when dealing with Strings those can be very large (assuming
821 # 128 is the max length of a stable ID). 128 is 8x smaller than our
822 # previous max expected integer so we reduce the max ids by 8. This gives
823 # 2048 IDs (16384/8)
824 else {
825 $max_size = 2048 if ! defined $max_size;
826 $sql_data_type = SQL_VARCHAR;
827 }
828
829 # build up unique id list, also validate on the way by
830 my %id_list;
831 for (@{$id_list_ref}) {
832 $id_list{$_}++;
833 }
834 my @id_list = keys %id_list;
835  
836 my @out;
837 my $inline = 1;
838 while (@id_list) {
839 my @ids;
840 my $id_str;
841  
842 if ( scalar(@id_list) > $max_size ) {
843 @ids = splice( @id_list, 0, $max_size );
844 }
845 else {
846 @ids = @id_list;
847 @id_list = ();
848 }
849 # Push off to our IN statement constructor for this work
850 my $constraint = $self->generate_in_constraint(\@ids, "${syn}.${field_name}", $sql_data_type, $inline);
851 push @out, @{ $self->generic_fetch($constraint, undef, $slice) };
852 }
853  
854 return \@out;
855 }
856  
857 # might not be a good idea, but for convenience
858 # shouldnt be called on the BIG tables though
859  
860 sub fetch_all {
861 my $self = shift;
862 return $self->generic_fetch();
863 }
864  
865 =head2 last_insert_id
866  
867 Arg [1] : (optional) $field the name of the field the inserted ID was pushed
868 into
869 Arg [2] : (optional) HashRef used to pass extra attributes through to the
870 DBD driver
871 Arg [3] : (optional) $table the name of the table to use if the adaptor
872 does not implement C<_tables()>
873 Description : Delegating method which uses DBI to extract the last inserted
874 identifier. If using MySQL we just call the DBI method
875 L<DBI::last_insert_id()> since MySQL ignores any extra
876 arguments. See L<DBI> for more information about this
877 delegated method.
878 Example : my $id = $self->last_insert_id('my_id'); my $other_id = $self->last_insert_id();
879 Returntype : Scalar or undef
880
881 =cut
882  
883 sub last_insert_id {
884 my ($self, $field, $attributes, $table) = @_;
885 my $dbc = $self->dbc();
886 my $dbh = $dbc->db_handle();
887 my @args;
888 unless (@args = $dbc->_driver_object->last_insert_id_args($field, $table)) {
889 if(!$table) {
890 my ($table_entry) = $self->_tables(); # first table entry
891 $table = $table_entry->[0]; # table_entry is [ name, alias ]
892 }
893 @args = (undef, $dbc->dbname(), $table, $field);
894 }
895 $attributes ||= {};
896 return $dbh->last_insert_id(@args, $attributes);
897 }
898  
899 =head2 insert_ignore_clause
900 =cut
901  
902 sub insert_ignore_clause {
903 my $self = shift;
904 return $self->dbc->_driver_object->insert_ignore_clause;
905 }
906  
907 =head2 _id_cache
908  
909 Description : Used to return an instance of a support BaseCache module
910 which can be used to speed up object access. The method
911 also respects the DBAdaptor's no_cache() flag and will
912 return undef in those situations
913 Example : my $cache = $self->_id_cache();
914 Returntype : Bio::EnsEMBL::DBSQL::Support::BaseCache
915
916 =cut
917  
918 sub _id_cache {
919 my ($self) = @_;
920 return if $self->db()->no_cache() && !$self->ignore_cache_override;
921 if(! exists $self->{_id_cache}) {
922 $self->{_id_cache} = $self->_build_id_cache();
923 }
924 return $self->{_id_cache};
925 }
926  
927 =head2 _no_id_cache
928  
929 Description : Flags if the ID based caching is active or not. This could be
930 due to the adaptor not wanting to cache or because of
931 a global no_cache() flag on the DBAdaptor instance
932 Returntype : Boolean
933
934 =cut
935  
936 sub _no_id_cache {
937 my ($self) = @_;
938 return 1 if ! $self->_id_cache();
939 return 0;
940 }
941  
942 =head2 ignore_cache_override
943  
944 Description : Method to interfere with no_cache directive from Registry on
945 a per adaptor basis. This method should be called after new()
946 in order to trigger the _build_id_cache at first query.
947 Example : $adaptor->ignore_cache_override(1);
948 Returntype : Boolean
949  
950 =cut
951  
952 sub ignore_cache_override {
953 my $self = shift;
954 $self->{'_override'} = shift if(@_);
955 unless (defined($self->{'_override'})) {return}
956 return $self->{'_override'};
957 }
958  
959 =head2 schema_version
960  
961 Description : Returns the schema version of the currently connected
962 DBAdaptor. The subroutine also caches this value so
963 repeated calls continue to be speedy.
964 Example : $adaptor->schema_version();
965 Returntype : Integer
966  
967 =cut
968  
969 sub schema_version {
970 my ($self) = @_;
971 return $self->{_schema_version} if exists $self->{_schema_version};
972 my $mc = $self->db()->get_MetaContainer();
973 return $self->{_schema_version} = $mc->get_schema_version();
974 }
975  
976 #_tables
977 #
978 # Args : none
979 # Example : $tablename = $self->_table_name()
980 # Description: ABSTRACT PROTECTED
981 # Subclasses are responsible for implementing this
982 # method. It should list of [tablename, alias] pairs.
983 # Additionally the primary table (with the dbID,
984 # analysis_id, and score) should be the first table in
985 # the list. e.g:
986 # ( ['repeat_feature', 'rf'],
987 # ['repeat_consensus', 'rc']);
988 # used to obtain features.
989 # Returntype : list of [tablename, alias] pairs
990 # Exceptions : thrown if not implemented by subclass
991 # Caller : BaseFeatureAdaptor::generic_fetch
992 #
993  
994 sub _tables {
995 throw( "abstract method _tables not defined "
996 . "by implementing subclass of BaseAdaptor" );
997 }
998  
999  
1000 #_columns
1001 #
1002 # Args : none
1003 # Example : $tablename = $self->_columns()
1004 # Description: ABSTRACT PROTECTED
1005 # Subclasses are responsible for implementing this
1006 # method. It should return a list of columns to be
1007 # used for feature creation.
1008 # Returntype : list of strings
1009 # Exceptions : thrown if not implemented by subclass
1010 # Caller : BaseFeatureAdaptor::generic_fetch
1011 #
1012  
1013 sub _columns {
1014 throw( "abstract method _columns not defined "
1015 . "by implementing subclass of BaseAdaptor" );
1016 }
1017  
1018  
1019 # _default_where_clause
1020 #
1021 # Arg [1] : none
1022 # Example : none
1023 # Description: May be overridden to provide an additional where
1024 # constraint to the SQL query which is generated to
1025 # fetch feature records. This constraint is always
1026 # appended to the end of the generated where clause
1027 # Returntype : string
1028 # Exceptions : none
1029 # Caller : generic_fetch
1030 #
1031  
1032 sub _default_where_clause { return '' }
1033  
1034  
1035 # _left_join
1036  
1037 # Arg [1] : none
1038 # Example : none
1039 # Description: Can be overridden by a subclass to specify any left
1040 # joins which should occur. The table name specigfied
1041 # in the join must still be present in the return
1042 # values of.
1043 # Returntype : a {'tablename' => 'join condition'} pair
1044 # Exceptions : none
1045 # Caller : general
1046 #
1047  
1048 sub _left_join { return () }
1049  
1050  
1051 #_final_clause
1052  
1053 # Arg [1] : none
1054 # Example : none
1055 # Description: May be overriden to provide an additional clause
1056 # to the end of the SQL query used to fetch feature
1057 # records. This is useful to add a required ORDER BY
1058 # clause to the query for example.
1059 # Returntype : string
1060 # Exceptions : none
1061 # Caller : generic_fetch
1062  
1063 sub _final_clause { return '' }
1064  
1065  
1066 #_objs_from_sth
1067  
1068 # Arg [1] : DBI::row_hashref $hashref containing key-value pairs
1069 # for each of the columns specified by the _columns method
1070 # Example : my @feats = $self->_obj_from_hashref
1071 # Description: ABSTRACT PROTECTED
1072 # The subclass is responsible for implementing this
1073 # method. It should take in a DBI row hash reference
1074 # and return a list of created features in contig
1075 # coordinates.
1076 # Returntype : list of Bio::EnsEMBL::*Features in contig coordinates
1077 # Exceptions : thrown if not implemented by subclass
1078 # Caller : BaseFeatureAdaptor::generic_fetch
1079  
1080 sub _objs_from_sth {
1081 throw( "abstract method _objs_from_sth not defined "
1082 . "by implementing subclass of BaseAdaptor" );
1083 }
1084  
1085 #_build_id_cache
1086  
1087 # Example : my $id_cache = $self->_build_id_cache
1088 # Description: ABSTRACT PROTECTED
1089 # The subclass is responsible for returning an instance
1090 # of the Bio::EnsEMBL::DBSQL::Support::BaseCache
1091 # which can be used to speed up ID based fetch operations
1092 # Returntype : Instance of Bio::EnsEMBL::DBSQL::Support::BaseCache
1093 # Exceptions : Could be thrown by the implementing sub-class
1094 # Caller : BaseAdaptor::_id_cache
1095 sub _build_id_cache {
1096 return;
1097 }
1098  
1099 #
1100 # Given a logic name and an existing constraint this will
1101 # add an analysis table constraint to the feature. Note that if no
1102 # analysis_id exists in the columns of the primary table then no
1103 # constraint is added at all
1104 #
1105 sub _logic_name_to_constraint {
1106 my $self = shift;
1107 my $constraint = shift;
1108 my $logic_name = shift;
1109  
1110 return $constraint if(!$logic_name);
1111  
1112 #make sure that an analysis_id exists in the primary table
1113 my ($prim_tab) = $self->_tables();
1114 my $prim_synonym = $prim_tab->[1];
1115  
1116 my $found_analysis=0;
1117 foreach my $col ($self->_columns) {
1118 my ($syn,$col_name) = split(/\./,$col);
1119 next if($syn ne $prim_synonym);
1120 if($col_name eq 'analysis_id') {
1121 $found_analysis = 1;
1122 last;
1123 }
1124 }
1125  
1126 if(!$found_analysis) {
1127 warning("This feature is not associated with an analysis.\n" .
1128 "Ignoring logic_name argument = [$logic_name].\n");
1129 return $constraint;
1130 }
1131  
1132 my $aa = $self->db->get_AnalysisAdaptor();
1133 my $an = $aa->fetch_by_logic_name($logic_name);
1134  
1135 if ( !defined($an) ) {
1136 return;
1137 }
1138  
1139 my $an_id = $an->dbID();
1140  
1141 $constraint .= ' AND' if($constraint);
1142 $constraint .= " ${prim_synonym}.analysis_id = $an_id";
1143 return $constraint;
1144 }
1145  
1146  
1147 1;