EnsEMBL/DBSQL/DBConnection.pm untested

filter: Statementstmt 0.0% 0 / 300 Branchbran 0.0% 0 / 122 Conditioncond 0.0% 0 / 101 Subroutinesub 0.0% 0 / 42 Podpod 0.0% 0 / 34 totaltotal 0.0% 0 / 599 CC 62 SCAR 40.7
CC
62
Cov
0%
new
272.0
work_with_db_handle
90.0
connect
30.0
CRAP 58.5
1 =head1 LICENSE
2  
3 See the NOTICE file distributed with this work for additional information
4 regarding copyright ownership.
5  
6 Licensed under the Apache License, Version 2.0 (the "License");
7 you may not use this file except in compliance with the License.
8 You may obtain a copy of the License at
9  
10 http://www.apache.org/licenses/LICENSE-2.0
11  
12 Unless required by applicable law or agreed to in writing, software
13 distributed under the License is distributed on an "AS IS" BASIS,
14 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 See the License for the specific language governing permissions and
16 limitations under the License.
17  
18 =cut
19  
20  
21 =head1 CONTACT
22  
23 Please email comments or questions to the public Ensembl
24 developers list at <http://lists.ensembl.org/mailman/listinfo/dev>.
25  
26 Questions may also be sent to the Ensembl help desk at
27 <http://www.ensembl.org/Help/Contact>.
28  
29 =cut
30  
31 =head1 NAME
32  
33 Bio::EnsEMBL::DBSQL::DBConnection
34  
35 =head1 SYNOPSIS
36  
37 $dbc = Bio::EnsEMBL::DBSQL::DBConnection->new(
38 -user => 'anonymous',
39 -dbname => 'homo_sapiens_core_20_34c',
40 -host => 'ensembldb.ensembl.org',
41 -driver => 'mysql',
42 );
43  
44 # SQL statements should be created/executed through this modules
45 # prepare() and do() methods.
46  
47 $sth = $dbc->prepare("SELECT something FROM yourtable");
48  
49 $sth->execute();
50  
51 # do something with rows returned ...
52  
53 $sth->finish();
54  
55 =head1 DESCRIPTION
56  
57 This class is a wrapper around DBIs datbase handle. It provides some
58 additional functionality such as the ability to automatically disconnect
59 when inactive and reconnect when needed.
60  
61 Generally this class will be used through one of the object adaptors or
62 the Bio::EnsEMBL::Registry and will not be instantiated directly.
63  
64 =head1 METHODS
65  
66 =cut
67  
68  
69 package Bio::EnsEMBL::DBSQL::DBConnection;
70 $Bio::EnsEMBL::DBSQL::DBConnection::VERSION = '114.0.0_50'; # TRIAL
71 $Bio::EnsEMBL::DBSQL::DBConnection::VERSION = '114.0.050';
72 use vars qw(@ISA);
73 use strict;
74  
75 use DBI;
76  
77 use Bio::EnsEMBL::DBSQL::StatementHandle;
78  
79 use Bio::EnsEMBL::Utils::Exception qw/deprecate throw warning/;
80 use Bio::EnsEMBL::Utils::Argument qw/rearrange/;
81 use Bio::EnsEMBL::Utils::Scalar qw/assert_ref wrap_array/;
82 use Bio::EnsEMBL::Utils::SqlHelper;
83  
84 =head2 new
85  
86 Arg [DBNAME] : (optional) string
87 The name of the database to connect to.
88 Arg [HOST] : (optional) string
89 The domain name of the database host to connect to.
90 'localhost' by default.
91 Arg [USER] : string
92 The name of the database user to connect with
93 Arg [PASS] : (optional) string
94 The password to be used to connect to the database
95 Arg [PORT] : (optional) int
96 The port to use when connecting to the database
97 3306 by default if the driver is mysql.
98 Arg [DRIVER] : (optional) string
99 The type of database driver to use to connect to the DB
100 mysql by default.
101 Arg [DBCONN] : (optional)
102 Open another handle to the same database as another connection
103 If this argument is specified, no other arguments should be
104 specified.
105 Arg [DISCONNECT_WHEN_INACTIVE]: (optional) boolean
106 If set to true, the database connection will be disconnected
107 everytime there are no active statement handles. This is
108 useful when running a lot of jobs on a compute farm
109 which would otherwise keep open a lot of connections to the
110 database. Database connections are automatically reopened
111 when required.Do not use this option together with RECONNECT_WHEN_CONNECTION_LOST.
112 Arg [WAIT_TIMEOUT]: (optional) integer
113 Time in seconds for the wait timeout to happen. Time after which
114 the connection is deleted if not used. By default this is 28800 (8 hours)
115 on most systems.
116 So set this to greater than this if your connection are getting deleted.
117 Only set this if you are having problems and know what you are doing.
118 Arg [RECONNECT_WHEN_CONNECTION_LOST]: (optional) boolean
119 In case you're reusing the same database connection, i.e. DISCONNECT_WHEN_INACTIVE is
120 set to false and running a job which takes a long time to process (over 8hrs),
121 which means that the db connection may be lost, set this option to true.
122 On each prepare or do statement the db handle will be pinged and the database
123 connection will be reconnected if it's lost.
124  
125 Example : $dbc = Bio::EnsEMBL::DBSQL::DBConnection->new
126 (-user => 'anonymous',
127 -dbname => 'homo_sapiens_core_20_34c',
128 -host => 'ensembldb.ensembl.org',
129 -driver => 'mysql');
130  
131 Description: Constructor for a Database Connection. Any adaptors that require
132 database connectivity should inherit from this class.
133 Returntype : Bio::EnsEMBL::DBSQL::DBConnection
134 Exceptions : thrown if USER or DBNAME are not specified, or if the database
135 cannot be connected to.
136 Caller : Bio::EnsEMBL::Utils::ConfigRegistry ( for newer code using the registry)
137 Bio::EnsEMBL::DBSQL::DBAdaptor ( for old style code)
138 Status : Stable
139  
140 =cut
141  
142 sub new {
143 my $class = shift;
144  
145 my (
146 $db, $host, $driver_arg,
147 $user, $password, $port,
148 $inactive_disconnect, $dbconn, $wait_timeout, $reconnect
149 )
150 = rearrange( [
151 'DBNAME', 'HOST', 'DRIVER', 'USER', 'PASS', 'PORT',
152 'DISCONNECT_WHEN_INACTIVE', 'DBCONN', 'WAIT_TIMEOUT', 'RECONNECT_WHEN_CONNECTION_LOST'
153 ],
154 @_
155 );
156  
157 my $self = {};
158 bless $self, $class;
159  
160 my $driver = $dbconn ? $dbconn->driver() : $driver_arg;
161 $driver ||= 'mysql';
162 if ($driver eq 'pgsql') {
163 deprecate("Using 'pgsql' as an alias for the 'Pg' driver is deprecated.");
164 $driver = 'Pg';
165 }
166 $self->driver($driver);
167  
168 my $driver_class = 'Bio::EnsEMBL::DBSQL::Driver::' . $driver;
169 eval "require $driver_class"; ## no critic
170 throw("Cannot load '$driver_class': $@") if $@;
171 my $driver_object = $driver_class->new($self);
172 $self->_driver_object($driver_object);
173  
174 if($dbconn) {
175 if($db || $host || $driver_arg || $password || $port || $inactive_disconnect || $reconnect) {
176 throw("Cannot specify other arguments when -DBCONN argument used.");
177 }
178  
179 $self->host($dbconn->host());
180 $self->port($dbconn->port());
181 $self->username($dbconn->username());
182 $self->password($dbconn->password());
183 $self->dbname($dbconn->dbname());
184  
185 if($dbconn->disconnect_when_inactive()) {
186 $self->disconnect_when_inactive(1);
187 }
188 } else {
189  
190 if($driver eq 'mysql') {
191 $user || throw("-USER argument is required.");
192 $host ||= 'mysql';
193 if(!defined($port)){
194 $port = 3306;
195 if($host eq "ensembldb.ensembl.org"){
196 if( $db =~ /\w+_\w+_\w+_(\d+)/){
197 if($1 >= 48){
198 $port = 5306;
199 }
200 }
201 }
202 }
203 } elsif($driver eq 'pgsql') {
204 if(!defined($port)){
205 $port = 5432;
206 }
207 }
208  
209 $wait_timeout ||= 0;
210  
211 $self->host( $host );
212 $self->port($port);
213 $self->username( $user );
214 $self->password( $password );
215 $self->dbname( $db );
216 $self->timeout($wait_timeout);
217  
218 if($inactive_disconnect) {
219 $self->disconnect_when_inactive($inactive_disconnect);
220 }
221 if($reconnect) {
222 $self->reconnect_when_lost($reconnect);
223 }
224 }
225  
226 # if(defined $dnadb) {
227 # $self->dnadb($dnadb);
228 # }
229 return $self;
230 }
231  
232  
233 =head2 connect
234  
235 Example : $dbcon->connect()
236 Description: Connects to the database using the connection attribute
237 information.
238 Returntype : none
239 Exceptions : none
240 Caller : new, db_handle
241 Status : Stable
242  
243 =cut
244  
245 sub connect {
246 my ($self) = @_;
247  
248 if ( $self->connected() ) { return }
249  
250 $self->connected(1);
251  
252 if ( defined( $self->db_handle() ) and $self->db_handle()->ping() ) {
253 warning( "unconnected db_handle is still pingable, "
254 . "reseting connected boolean\n" );
255 }
256  
257 my $dbh;
258  
259 my $params = $self->_driver_object->connect_params($self);
260 eval {
261 $dbh = DBI->connect( @{$params}{qw(dsn username password attributes)} );
262 };
263 my $error = $@;
264  
265 if ( !$dbh || $error || !$dbh->ping() ) {
266  
267 my $dsn = $params->{dsn};
268 warn( "Could not connect to database "
269 . $self->dbname()
270 . " as user "
271 . $self->username()
272 . " using [$dsn] as a locator:\n"
273 . $error );
274  
275 $self->connected(0);
276  
277 throw( "Could not connect to database "
278 . $self->dbname()
279 . " as user "
280 . $self->username()
281 . " using [$dsn] as a locator:\n"
282 . $error );
283 }
284  
285 $self->db_handle($dbh);
286  
287 if ( $self->timeout() ) {
288 $self->_driver_object->set_wait_timeout( $dbh, $self->timeout() );
289 }
290  
291 #print("CONNECT\n");
292 } ## end sub connect
293  
294  
295 =head2 connected
296  
297 Example : $dbcon->connected()
298 Description: Boolean which tells if DBConnection is connected or not.
299 State is set internally, and external processes should not alter state.
300 Returntype : undef or 1
301 Exceptions : none
302 Caller : db_handle, connect, disconnect_if_idle, user processes
303 Status : Stable
304  
305 =cut
306  
307 sub connected {
308 my $self = shift;
309  
310 # Use the process id ($$) as part of the key for the connected flag.
311 # This forces the opening of another connection in a forked subprocess.
312 $self->{'connected'.$$} = shift if(@_);
313 return $self->{'connected'.$$};
314 }
315  
316 sub disconnect_count {
317 my $self = shift;
318 return $self->{'disconnect_count'} = shift if(@_);
319 $self->{'disconnect_count'}=0 unless(defined($self->{'disconnect_count'}));
320 return $self->{'disconnect_count'};
321 }
322  
323 sub timeout{
324 my($self, $arg ) = @_;
325  
326 (defined $arg) &&
327 ($self->{_timeout} = $arg );
328  
329 return $self->{_timeout};
330  
331 }
332  
333 sub query_count {
334 my $self = shift;
335 return $self->{'_query_count'} = shift if(@_);
336 $self->{'_query_count'}=0 unless(defined($self->{'_query_count'}));
337 return $self->{'_query_count'};
338 }
339  
340 =head2 equals
341  
342 Example : warn 'Same!' if($dbc->equals($other_dbc));
343 Description: Equality checker for DBConnection objects
344 Returntype : boolean
345 Exceptions : none
346 Caller : new
347 Status : Stable
348  
349 =cut
350  
351  
352 sub equals {
353 my ( $self, $dbc ) = @_;
354 return 0 if ! defined $dbc;
355 my $return = 0;
356 my $undef_str = q{!-undef-!};
357 my $undef_num = -1;
358  
359 $return = 1 if (
360 (($self->host() || $undef_str) eq ($dbc->host() || $undef_str)) &&
361 (($self->dbname() || $undef_str) eq ($dbc->dbname() || $undef_str)) &&
362 (($self->port() || $undef_num) == ($dbc->port() || $undef_num)) &&
363 (($self->username() || $undef_str) eq ($dbc->username() || $undef_str)) &&
364 ($self->driver() eq $dbc->driver())
365 );
366  
367 return $return;
368 }
369  
370 =head2 driver
371  
372 Arg [1] : (optional) string $arg
373 the name of the driver to use to connect to the database
374 Example : $driver = $db_connection->driver()
375 Description: Getter / Setter for the driver this connection uses.
376 Right now there is no point to setting this value after a
377 connection has already been established in the constructor.
378 Returntype : string
379 Exceptions : none
380 Caller : new
381 Status : Stable
382  
383 =cut
384  
385 sub driver {
386 my($self, $arg ) = @_;
387  
388 (defined $arg) &&
389 ($self->{_driver} = $arg );
390 return $self->{_driver};
391 }
392  
393  
394 =head2 port
395  
396 Arg [1] : (optional) int $arg
397 the TCP or UDP port to use to connect to the database
398 Example : $port = $db_connection->port();
399 Description: Getter / Setter for the port this connection uses to communicate
400 to the database daemon. There currently is no point in
401 setting this value after the connection has already been
402 established by the constructor.
403 Returntype : string
404 Exceptions : none
405 Caller : new
406 Status : Stable
407  
408 =cut
409  
410 sub port {
411 my ( $self, @args ) = @_;
412  
413 if ( @args ) {
414 $self->{'_port'} = $args[0];
415 }
416  
417 return $self->{'_port'};
418 }
419  
420  
421 =head2 dbname
422  
423 Arg [1] : (optional) string $arg
424 The new value of the database name used by this connection.
425 Example : $dbname = $db_connection->dbname()
426 Description: Getter/Setter for the name of the database used by this
427 connection. There is currently no point in setting this value
428 after the connection has already been established by the
429 constructor.
430 Returntype : string
431 Exceptions : none
432 Caller : new
433 Status : Stable
434  
435 =cut
436  
437 sub dbname {
438 my ($self, @args ) = @_;
439 ( @args ) &&
440 ( $self->{_dbname} = $args[0] );
441 $self->{_dbname};
442 }
443  
444  
445 =head2 username
446  
447 Arg [1] : (optional) string $arg
448 The new value of the username used by this connection.
449 Example : $username = $db_connection->username()
450 Description: Getter/Setter for the username used by this
451 connection. There is currently no point in setting this value
452 after the connection has already been established by the
453 constructor.
454 Returntype : string
455 Exceptions : none
456 Caller : new
457 Status : Stable
458  
459 =cut
460  
461 sub username {
462 my ($self, @args ) = @_;
463 ( @args ) &&
464 ( $self->{_username} = $args[0] );
465 $self->{_username};
466 }
467  
468 =head2 user
469  
470 Arg [1] : (optional) string $arg
471 The new value of the username used by this connection.
472 Example : $user = $db_connection->user()
473 Description: Convenience alias for the username method
474 Returntype : String
475  
476 =cut
477  
478 sub user {
479 my ($self, @args) = @_;
480 return $self->username(@args);
481 }
482  
483  
484 =head2 host
485  
486 Arg [1] : (optional) string $arg
487 The new value of the host used by this connection.
488 Example : $host = $db_connection->host()
489 Description: Getter/Setter for the domain name of the database host use by
490 this connection. There is currently no point in setting
491 this value after the connection has already been established
492 by the constructor.
493 Returntype : string
494 Exceptions : none
495 Caller : new
496 Status : Stable
497  
498 =cut
499  
500 sub host {
501 my ($self, @args ) = @_;
502 ( @args ) &&
503 ( $self->{_host} = $args[0] );
504 $self->{_host};
505 }
506  
507 =head2 hostname
508  
509 Arg [1] : (optional) string $arg
510 The new value of the host used by this connection.
511 Example : $hostname = $db_connection->hostname()
512 Description: Convenience alias for the host method
513 Returntype : String
514  
515 =cut
516  
517 sub hostname {
518 my ($self, @args) = @_;
519 return $self->host(@args);
520 }
521  
522  
523 =head2 password
524  
525 Arg [1] : (optional) string $arg
526 The new value of the password used by this connection.
527 Example : $host = $db_connection->password()
528 Description: Getter/Setter for the password of to use for this
529 connection. There is currently no point in setting
530 this value after the connection has already been
531 established by the constructor.
532 Returntype : string
533 Exceptions : none
534 Caller : new
535 Status : Stable
536  
537 =cut
538  
539 sub password {
540 my ( $self, @args ) = @_;
541  
542 if ( @args ) {
543 # Use an anonymous subroutine that will return the password when
544 # invoked. This will prevent the password from being accidentally
545 # displayed when using e.g. Data::Dumper on a structure containing
546 # one of these objects.
547  
548 $self->{_password} = sub { $args[0] };
549 }
550  
551 return ( ref( $self->{_password} ) && &{ $self->{_password} } ) || '';
552 }
553  
554 =head2 pass
555  
556 Arg [1] : (optional) string $arg
557 The new value of the password used by this connection.
558 Example : $pass = $db_connection->pass()
559 Description: Convenience alias for the password method
560 Returntype : String
561  
562 =cut
563  
564 sub pass {
565 my ($self, @args) = @_;
566 return $self->password(@args);
567 }
568  
569 =head2 disconnect_when_inactive
570  
571 Arg [1] : (optional) boolean $newval
572 Example : $db->disconnect_when_inactive(1);
573 Description: Getter/Setter for the disconnect_when_inactive flag. If set
574 to true this DBConnection will continually disconnect itself
575 when there are no active statement handles and reconnect as
576 necessary. Useful for farm environments when there can be
577 many (often inactive) open connections to a database at once.
578 Returntype : boolean
579 Exceptions : none
580 Caller : Pipeline
581 Status : Stable
582  
583 =cut
584  
585 sub disconnect_when_inactive {
586 my ( $self, $value ) = @_;
587  
588 if ( defined($value) ) {
589 $self->{'disconnect_when_inactive'} = $value;
590 if ($value) {
591 $self->disconnect_if_idle();
592 }
593 }
594  
595 return $self->{'disconnect_when_inactive'};
596 }
597  
598  
599 =head2 reconnect_when_lost
600  
601 Arg [1] : (optional) boolean $newval
602 Example : $db->reconnect_when_lost(1);
603 Description: Getter/Setter for the reconnect_when_lost flag. If set
604 to true the db handle will be pinged on each prepare or do statement
605 and the connection will be reestablished in case it's lost.
606 Useful for long running jobs (over 8hrs), which means that the db
607 connection may be lost.
608 Returntype : boolean
609 Exceptions : none
610 Caller : Pipeline
611 Status : Stable
612  
613 =cut
614  
615 sub reconnect_when_lost {
616 my ( $self, $value ) = @_;
617  
618 if ( defined($value) ) {
619 $self->{'reconnect_when_lost'} = $value;
620 }
621  
622 return $self->{'reconnect_when_lost'};
623 }
624  
625  
626  
627 =head2 locator
628  
629 Arg [1] : none
630 Example : $locator = $dbc->locator;
631 Description: Constructs a locator string for this database connection
632 that can, for example, be used by the DBLoader module
633 Returntype : string
634 Exceptions : none
635 Caller : general
636 Status : Stable
637  
638 =cut
639  
640  
641 sub locator {
642 my ($self) = @_;
643  
644 return sprintf(
645 "%s/host=%s;port=%s;dbname=%s;user=%s;pass=%s",
646 ref($self), $self->host(), $self->port(),
647 $self->dbname(), $self->username(), $self->password() );
648 }
649  
650  
651 =head2 db_handle
652  
653 Arg [1] : DBI Database Handle $value
654 Example : $dbh = $db_connection->db_handle()
655 Description: Getter / Setter for the Database handle used by this
656 database connection.
657 Returntype : DBI Database Handle
658 Exceptions : none
659 Caller : new, DESTROY
660 Status : Stable
661  
662 =cut
663  
664 sub db_handle {
665 my $self = shift;
666  
667 # Use the process id ($$) as part of the key for the database handle
668 # this makes this object fork safe. fork() does not makes copies
669 # of the open socket which creates problems when one of the forked
670 # processes disconnects,
671 return $self->{'db_handle'.$$} = shift if(@_);
672 return $self->{'db_handle'.$$} if($self->connected);
673  
674 $self->connect();
675 return $self->{'db_handle'.$$};
676 }
677  
678  
679 =head2 prepare
680  
681 Arg [1] : string $string
682 the SQL statement to prepare
683 Example : $sth = $db_connection->prepare("SELECT column FROM table");
684 Description: Prepares a SQL statement using the internal DBI database handle
685 and returns the DBI statement handle.
686 Returntype : DBI statement handle
687 Exceptions : thrown if the SQL statement is empty, or if the internal
688 database handle is not present
689 Caller : Adaptor modules
690 Status : Stable
691  
692 =cut
693  
694 sub prepare {
695 my ($self,@args) = @_;
696  
697 if( ! $args[0] ) {
698 throw("Attempting to prepare an empty SQL query.");
699 }
700  
701 #warn "SQL(".$self->dbname."):" . join(' ', @args) . "\n";
702 if ( ($self->reconnect_when_lost()) and (!$self->db_handle()->ping()) ) {
703 $self->reconnect();
704 }
705 my $sth = $self->db_handle->prepare(@args);
706  
707 # return an overridden statement handle that provides us with
708 # the means to disconnect inactive statement handles automatically
709 bless $sth, "Bio::EnsEMBL::DBSQL::StatementHandle";
710 $sth->dbc($self);
711 $sth->sql($args[0]);
712  
713 $self->query_count($self->query_count()+1);
714 return $sth;
715 }
716  
717  
718 =head2 prepare_cached
719  
720 Arg [1] : string $string
721 the SQL statement to prepare
722 Example : $sth = $db_connection->prepare_cached("SELECT column FROM table");
723 Description: Prepares a SQL statement using the internal DBI database handle
724 and returns the DBI statement handle. The prepared statement is
725 cached so that it does not have to be prepared again.
726  
727 If only a subset of rows are required, finish() should be called
728 on the object to free up the statement handle.
729  
730 For further information please consult https://metacpan.org/pod/DBI#prepare_cached
731 Returntype : DBI statement handle
732 Exceptions : thrown if the SQL statement is empty, or if the internal
733 database handle is not present
734 Caller : Adaptor modules
735 Status : Experimental
736  
737 =cut
738  
739 sub prepare_cached {
740 my ($self, @args) = @_;
741  
742 if( ! $args[0] ) {
743 throw("Attempting to prepare_cached an empty SQL query.");
744 }
745  
746 if ( ( $self->reconnect_when_lost() ) and ( !$self->db_handle()->{Active} ) ) {
747 $self->reconnect();
748 }
749 my $sth = $self->db_handle->prepare_cached( @args );
750  
751 # return an overridden statement handle that provides us with
752 # the means to disconnect inactive statement handles automatically
753 bless $sth, "Bio::EnsEMBL::DBSQL::StatementHandle";
754 $sth->dbc( $self );
755 $sth->sql( $args[0] );
756  
757 $self->query_count( $self->query_count() + 1 );
758 return $sth;
759 }
760  
761  
762 =head2 reconnect
763  
764 Example : $dbcon->reconnect()
765 Description: Reconnects to the database using the connection attribute
766 information if db_handle no longer pingable.
767 Returntype : none
768 Exceptions : none
769 Caller : new, db_handle
770 Status : Stable
771  
772 =cut
773  
774 sub reconnect {
775 my ($self) = @_;
776 $self->connected(undef);
777 $self->db_handle(undef);
778 $self->connect();
779 return;
780 }
781  
782  
783 =head2 do
784  
785 Arg [1] : string $string
786 the SQL statement to prepare
787 Example : $sth = $db_connection->do("SELECT column FROM table");
788 Description: Executes a SQL statement using the internal DBI database handle.
789 Returntype : Result of DBI dbh do() method
790 Exceptions : thrown if the SQL statement is empty, or if the internal
791 database handle is not present.
792 Caller : Adaptor modules
793 Status : Stable
794  
795 =cut
796  
797 sub do {
798 my ($self,$string, $attr, @bind_values) = @_;
799  
800 if( ! $string ) {
801 throw("Attempting to do an empty SQL query.");
802 }
803  
804 # warn "SQL(".$self->dbname."): $string";
805 my $error;
806  
807 my $do_result = $self->work_with_db_handle(sub {
808 my ($dbh) = @_;
809 my $result = eval { $dbh->do($string, $attr, @bind_values) };
810 $error = $@ if $@;
811 return $result;
812 });
813  
814 throw "Detected an error whilst executing statement '$string': $error" if $error;
815  
816 return $do_result;
817 }
818  
819 =head2 work_with_db_handle
820  
821 Arg [1] : CodeRef $callback
822 Example : my $q_t = $dbc->work_with_db_handle(sub { my ($dbh) = @_; return $dbh->quote_identifier('table'); });
823 Description: Gives access to the DBI handle to execute methods not normally
824 provided by the DBConnection interface
825 Returntype : Any from callback
826 Exceptions : If the callback paramater is not a CodeRef; all other
827 errors are re-thrown after cleanup.
828 Caller : Adaptor modules
829 Status : Stable
830  
831 =cut
832  
833 sub work_with_db_handle {
834 my ($self, $callback) = @_;
835 my $wantarray = wantarray;
836 assert_ref($callback, 'CODE', 'callback');
837 if( $self->reconnect_when_lost() && !$self->db_handle()->ping()) {
838 $self->reconnect();
839 }
840 my @results;
841 eval {
842 if($wantarray) {
843 @results = $callback->($self->db_handle())
844 }
845 elsif(defined $wantarray) {
846 $results[0] = $callback->($self->db_handle());
847 }
848 else {
849 $callback->($self->db_handle());
850 }
851 };
852 my $original_error = $@;
853  
854 $self->query_count($self->query_count()+1);
855 eval {
856 if($self->disconnect_when_inactive()) {
857 $self->disconnect_if_idle();
858 }
859 };
860 if($@) {
861 warning "Detected an error whilst attempting to disconnect the DBI handle: $@";
862 }
863 if($original_error) {
864 throw "Detected an error when running DBI wrapper callback:\n$original_error";
865 }
866  
867 if(defined $wantarray) {
868 return ($wantarray) ? @results : $results[0];
869 }
870 return;
871 }
872  
873 =head2 prevent_disconnect
874  
875 Arg[1] : CodeRef $callback
876 Example : $dbc->prevent_disconnect(sub { $dbc->do('do something'); $dbc->do('something else')});
877 Description : A wrapper method which prevents database disconnection for the
878 duration of the callback. This is very useful if you need
879 to make multiple database calls avoiding excessive database
880 connection creation/destruction but still want the API
881 to disconnect after the body of work.
882  
883 The value of C<disconnect_when_inactive()> is set to 0 no
884 matter what the original value was & after $callback has
885 been executed. If C<disconnect_when_inactive()> was
886 already set to 0 then this method will be an effective no-op.
887 Returntype : None
888 Exceptions : Raised if there are issues with reverting the connection to its
889 default state.
890 Caller : DBConnection methods
891 Status : Beta
892  
893 =cut
894  
895 sub prevent_disconnect {
896 my ($self, $callback) = @_;
897 assert_ref($callback, 'CODE', 'callback');
898 my $original_dwi = $self->disconnect_when_inactive();
899 $self->disconnect_when_inactive(0);
900 eval { $callback->(); };
901 my $original_error = $@;
902 eval {
903 $self->disconnect_when_inactive($original_dwi);
904 };
905 if($@) {
906 warning "Detected an error whilst attempting to reset disconnect_when_idle: $@";
907 }
908 if($original_error) {
909 throw "Detected an error when running DBI wrapper callback:\n$original_error";
910 }
911 return;
912 }
913  
914 =head2 quote_identifier
915  
916 Arg [n] : scalar/ArrayRef
917 Example : $q = $dbc->quote_identifier('table', 'other');
918 $q = $dbc->quote_identifier([undef, 'my_db', 'table'], [undef, 'my_db', 'other']);
919 Description: Executes the DBI C<quote_identifier> method which will quote
920 any given string using the database driver's quote character.
921 Returntype : ArrayRef
922 Exceptions : None
923 Caller : General
924 Status : Stable
925  
926 =cut
927  
928 sub quote_identifier {
929 my ($self, @identifiers) = @_;
930 return $self->work_with_db_handle(sub {
931 my ($dbh) = @_;
932 my @output;
933 foreach my $identifier_array (@identifiers) {
934 $identifier_array = wrap_array($identifier_array);
935 push(@output, $dbh->quote_identifier(@{$identifier_array}));
936 }
937 return \@output;
938 });
939 }
940  
941 =head2 disconnect_if_idle
942  
943 Arg [1] : none
944 Example : $dbc->disconnect_if_idle();
945 Description: Disconnects from the database if there are no currently active
946 statement handles.
947 It is called automatically by the DESTROY method of the
948 Bio::EnsEMBL::DBSQL::SQL::StatementHandle if the
949 disconect_when_inactive flag is set.
950 Users may call it whenever they want to disconnect. Connection will
951 reestablish on next access to db_handle()
952 Returntype : 1 or 0
953 1=problem trying to disconnect while a statement handle was still active
954 Exceptions : none
955 Caller : Bio::EnsEMBL::DBSQL::SQL::StatementHandle::DESTROY
956 Bio::EnsEMBL::DBSQL::DBConnection::do
957 Status : Stable
958  
959 =cut
960  
961 sub disconnect_if_idle {
962 my $self = shift;
963  
964 return 0 if(!$self->connected());
965 my $db_handle = $self->db_handle();
966 return 0 unless(defined($db_handle));
967  
968 #printf("disconnect_if_idle : kids=%d activekids=%d\n",
969 # $db_handle->{Kids}, $db_handle->{ActiveKids});
970  
971 #If InactiveDestroy is set, don't disconnect.
972 #To comply with DBI specification
973 return 0 if($db_handle->{InactiveDestroy});
974  
975 #If any statement handles are still active, don't allow disconnection
976 #In this case it is being called before a query has been fully processed
977 #either by not reading all rows of data returned, or not calling ->finish
978 #on the statement handle. Don't disconnect, send warning
979 if($db_handle->{ActiveKids} != 0) {
980 warn("Problem disconnect : kids=",$db_handle->{Kids},
981 " activekids=",$db_handle->{ActiveKids},"\n");
982 return 1;
983 }
984  
985 $db_handle->disconnect();
986 $self->connected(undef);
987 $self->disconnect_count($self->disconnect_count()+1);
988 #print("DISCONNECT\n");
989 $self->db_handle(undef);
990 return 0;
991 }
992  
993  
994 =head2 add_limit_clause
995  
996 Arg [1] : string $sql
997 Arg [2] : int $max_number
998 Example : my $new_sql = $dbc->add_limit_clause($sql,$max_number);
999 Description: Giving an SQL statement, it adds a limit clause, dependent on the database
1000 (in MySQL, should add a LIMIT at the end, MSSQL uses a TOP clause)
1001 Returntype : String containing the new valid SQL statement
1002 Exceptions : none
1003 Caller : general
1004 Status : at risk
1005  
1006 =cut
1007  
1008  
1009 sub add_limit_clause{
1010 my $self = shift;
1011 my $sql = shift;
1012 my $max_number = shift;
1013  
1014 my $new_sql = '';
1015 if ($self->driver eq 'mysql'){
1016 $new_sql = $sql . ' LIMIT ' . $max_number;
1017 }
1018 elsif ($self->driver eq 'odbc'){
1019 #need to get anything after the SELECT statement
1020 $sql =~ /select(.*)/i;
1021 $new_sql = 'SELECT TOP ' . $max_number . $1;
1022 }
1023 else{
1024 warning("Not possible to convert $sql to an unknow database driver: ", $self->driver, " no limit applied");
1025 $new_sql = $sql;
1026 }
1027 return $new_sql;
1028 }
1029  
1030  
1031 =head2 from_date_to_seconds
1032  
1033 Arg [1] : date $date
1034 Example : my $string = $dbc->from_date_to_seconds($date);
1035 Description: Giving a string representing a column of type date
1036 applies the database function to convert to the number of seconds from 01-01-1970
1037 Returntype : string
1038 Exceptions : none
1039 Caller : general
1040 Status : at risk
1041  
1042 =cut
1043  
1044 sub from_date_to_seconds{
1045 my ($self, @args) = @_;
1046 return $self->_driver_object->from_date_to_seconds(@args);
1047 }
1048  
1049 =head2 from_seconds_to_date
1050  
1051 Arg [1] : int $seconds
1052 Example : my $string = $dbc->from_seconds_to_date($seconds);
1053 Description: Giving an int representing number of seconds
1054 applies the database function to convert to a date
1055 Returntype : string
1056 Exceptions : none
1057 Caller : general
1058 Status : at risk
1059  
1060 =cut
1061  
1062 sub from_seconds_to_date {
1063 my $self = shift;
1064 my $seconds = shift;
1065  
1066 if ($seconds) {
1067 return $self->_driver_object->from_seconds_to_date($seconds);
1068 }
1069 return;
1070 }
1071  
1072 =head2 sql_helper
1073  
1074 Example : my $h = $dbc->sql_helper();
1075 Description: Lazy generated instance of L<Bio::EnsEMBL::Utils::SqlHelper>
1076 which provides useful wrapper methods for interacting with a
1077 DBConnection instance.
1078 Returntype : Bio::EnsEMBL::Utils::SqlHelper
1079 Exceptions : none
1080 Caller : general
1081 Status : Stable
1082  
1083 =cut
1084  
1085 sub sql_helper {
1086 my ($self) = @_;
1087 if(! exists $self->{_sql_helper}) {
1088 my $helper = Bio::EnsEMBL::Utils::SqlHelper->new(-DB_CONNECTION => $self);
1089 $self->{_sql_helper} = $helper;
1090 }
1091 return $self->{_sql_helper};
1092 }
1093  
1094 =head2 to_hash
1095  
1096 Example : my $hash = $dbc->to_hash();
1097 my $new_dbc = $dbc->new(%{$hash});
1098 Description: Provides a hash which is compatible with the
1099 parameters for DBConnection's new() method. This can be
1100 useful during serialisation
1101 Returntype : Hash
1102 Exceptions : none
1103 Caller : general
1104 Status : New
1105  
1106 =cut
1107  
1108 sub to_hash {
1109 my ($self) = @_;
1110 my $hash = {
1111 -HOST => $self->host(),
1112 -PORT => $self->port(),
1113 -USER => $self->username(),
1114 -DRIVER => $self->driver(),
1115 };
1116 $hash->{'-DBNAME'} = $self->dbname() if defined $self->dbname();
1117 $hash->{'-PASS'} = $self->password() if defined $self->password();
1118 return $hash;
1119 }
1120  
1121 =head2 _driver_object
1122 =cut
1123  
1124 sub _driver_object {
1125 my ($self, @args) = @_;
1126 ($self->{_driver_object}) = @args if @args;
1127 return $self->{_driver_object};
1128 }
1129  
1130 1;