File Coverage

blib/lib/Apache/DBI.pm
Criterion Covered Total %
statement 19 136 13.9
branch 3 62 4.8
condition 2 44 4.5
subroutine 7 20 35.0
pod 0 11 0.0
total 31 273 11.3


line stmt bran cond sub pod time code
1             # $Id: DBI.pm 1490648 2013-06-07 13:46:30Z perrin $
2             package Apache::DBI;
3 1     1   35132 use strict;
  1         3  
  1         68  
4              
5 1 50 33     222 use constant MP2 => (exists $ENV{MOD_PERL_API_VERSION} &&
6 1     1   6 $ENV{MOD_PERL_API_VERSION} == 2) ? 1 : 0;
  1         2  
7              
8             BEGIN {
9 1 50   1   23 if (MP2) {
10             require mod_perl2;
11             require Apache2::Module;
12             require Apache2::RequestUtil;
13             require Apache2::ServerUtil;
14             require ModPerl::Util;
15             }
16 0 50 33     0 elsif (defined $modperl::VERSION && $modperl::VERSION > 1 &&
17             $modperl::VERSION < 1.99) {
18 0         0 require Apache;
19             }
20             }
21 1     1   4550 use DBI ();
  1         26136  
  1         91  
22 1     1   13 use Carp ();
  1         3  
  1         13215  
23              
24             require_version DBI 1.00;
25              
26             $Apache::DBI::VERSION = '1.12';
27              
28             # 1: report about new connect
29             # 2: full debug output
30             $Apache::DBI::DEBUG = 0;
31             #DBI->trace(2);
32              
33             my %Connected; # cache for database handles
34             my @ChildConnect; # connections to be established when a new
35             # httpd child is created
36             my %Rollback; # keeps track of pushed PerlCleanupHandler
37             # which can do a rollback after the request
38             # has finished
39             my %PingTimeOut; # stores the timeout values per data_source,
40             # a negative value de-activates ping,
41             # default = 0
42             my %LastPingTime; # keeps track of last ping per data_source
43             my $ChildExitHandlerInstalled; # set to true on installation of
44             # PerlChildExitHandler
45             my $InChild;
46              
47             # Check to see if we need to reset TaintIn and TaintOut
48             my $TaintInOut = ($DBI::VERSION >= 1.31) ? 1 : 0;
49              
50             sub debug {
51 0 0   0 0   print STDERR "$_[1]\n" if $Apache::DBI::DEBUG >= $_[0];
52             }
53              
54             # supposed to be called in a startup script.
55             # stores the data_source of all connections, which are supposed to be created
56             # upon server startup, and creates a PerlChildInitHandler, which initiates
57             # the connections. Provide a handler which creates all connections during
58             # server startup
59             sub connect_on_init {
60              
61 0     0 0   if (MP2) {
62             if (!@ChildConnect) {
63             my $s = Apache2::ServerUtil->server;
64             $s->push_handlers(PerlChildInitHandler => \&childinit);
65             }
66             }
67             else {
68 0 0 0       Carp::carp("Apache.pm was not loaded\n")
69             and return unless $INC{'Apache.pm'};
70              
71 0 0 0       if (!@ChildConnect and Apache->can('push_handlers')) {
72 0           Apache->push_handlers(PerlChildInitHandler => \&childinit);
73             }
74             }
75              
76             # store connections
77 0           push @ChildConnect, [@_];
78             }
79              
80             # supposed to be called in a startup script.
81             # stores the timeout per data_source for the ping function.
82             # use a DSN without attribute settings specified within !
83             sub setPingTimeOut {
84 0     0 0   my $class = shift;
85 0           my $data_source = shift;
86 0           my $timeout = shift;
87              
88             # sanity check
89 0 0 0       if ($data_source =~ /dbi:\w+:.*/ and $timeout =~ /\-*\d+/) {
90 0           $PingTimeOut{$data_source} = $timeout;
91             }
92             }
93              
94             # the connect method called from DBI::connect
95             sub connect {
96 0     0 0   my $class = shift;
97 0 0         unshift @_, $class if ref $class;
98 0           my $drh = shift;
99              
100 0 0         my @args = map { defined $_ ? $_ : "" } @_;
  0            
101 0           my $dsn = "dbi:$drh->{Name}:$args[0]";
102 0           my $prefix = "$$ Apache::DBI ";
103              
104             # key of %Connected and %Rollback.
105 0           my $Idx = join $;, $args[0], $args[1], $args[2];
106              
107             # the hash-reference differs between calls even in the same
108             # process, so de-reference the hash-reference
109 0 0 0       if (3 == $#args and ref $args[3] eq "HASH") {
    0          
110             # should we default to '__undef__' or something for undef values?
111 0 0         map {
112 0           $Idx .= "$;$_=" .
113             (defined $args[3]->{$_}
114             ? $args[3]->{$_}
115             : '')
116 0           } sort keys %{$args[3]};
117             }
118             elsif (3 == $#args) {
119 0           pop @args;
120             }
121              
122             # don't cache connections created during server initialization; they
123             # won't be useful after ChildInit, since multiple processes trying to
124             # work over the same database connection simultaneously will receive
125             # unpredictable query results.
126             # See: http://perl.apache.org/docs/2.0/user/porting/compat.html#C__Apache__Server__Starting__and_C__Apache__Server__ReStarting_
127 0           if (MP2) {
128             require ModPerl::Util;
129             my $callback = ModPerl::Util::current_callback();
130             if ($callback !~ m/Handler$/ or
131             $callback =~ m/(PostConfig|OpenLogs)/) {
132             debug(2, "$prefix skipping connection during server startup, read the docu !!");
133             return $drh->connect(@args);
134             }
135             }
136             else {
137 0 0 0       if ($Apache::ServerStarting and $Apache::ServerStarting == 1) {
138 0           debug(2, "$prefix skipping connection during server startup, read the docu !!");
139 0           return $drh->connect(@args);
140             }
141             }
142              
143             # this PerlChildExitHandler is supposed to disconnect all open
144             # connections to the database
145 0 0         if (!$ChildExitHandlerInstalled) {
146 0           $ChildExitHandlerInstalled = 1;
147 0           my $s;
148 0 0         if (MP2) {
149             $s = Apache2::ServerUtil->server;
150             }
151 0           elsif (Apache->can('push_handlers')) {
152 0           $s = 'Apache';
153             }
154 0 0         if ($s) {
155 0           debug(2, "$prefix push PerlChildExitHandler");
156 0           $s->push_handlers(PerlChildExitHandler => \&childexit);
157             }
158             }
159              
160             # this PerlCleanupHandler is supposed to initiate a rollback after the
161             # script has finished if AutoCommit is off. however, cleanup can only
162             # be determined at end of handle life as begin_work may have been called
163             # to temporarily turn off AutoCommit.
164 0 0         if (!$Rollback{$Idx}) {
165 0           my $r;
166 0 0         if (MP2) {
167             # We may not actually be in a request, but in <Perl> (or
168             # equivalent such as startup.pl), in which case this would die.
169             eval { $r = Apache2::RequestUtil->request };
170             }
171 0           elsif (Apache->can('push_handlers')) {
172 0           $r = 'Apache';
173             }
174 0 0         if ($r) {
175 0           debug(2, "$prefix push PerlCleanupHandler");
176 0     0     $r->push_handlers("PerlCleanupHandler", sub { cleanup($Idx) });
  0            
177             # make sure, that the rollback is called only once for every
178             # request, even if the script calls connect more than once
179 0           $Rollback{$Idx} = 1;
180             }
181             }
182              
183             # do we need to ping the database ?
184 0 0         $PingTimeOut{$dsn} = 0 unless $PingTimeOut{$dsn};
185 0 0         $LastPingTime{$dsn} = 0 unless $LastPingTime{$dsn};
186 0           my $now = time;
187             # Must ping if TimeOut = 0 else base on time
188 0 0 0       my $needping = ($PingTimeOut{$dsn} == 0 or
189             ($PingTimeOut{$dsn} > 0 and
190             $now - $LastPingTime{$dsn} > $PingTimeOut{$dsn})
191             ) ? 1 : 0;
192 0 0         debug(2, "$prefix need ping: " . ($needping == 1 ? "yes" : "no"));
193 0           $LastPingTime{$dsn} = $now;
194              
195             # check first if there is already a database-handle cached
196             # if this is the case, possibly verify the database-handle
197             # using the ping-method. Use eval for checking the connection
198             # handle in order to avoid problems (dying inside ping) when
199             # RaiseError being on and the handle is invalid.
200 0 0 0       if ($Connected{$Idx} and (!$needping or eval{$Connected{$Idx}->ping})) {
      0        
201 0           debug(2, "$prefix already connected to '$Idx'");
202              
203             # Force clean up of handle in case previous transaction failed to
204             # clean up the handle
205 0           &reset_startup_state($Idx);
206              
207 0           return (bless $Connected{$Idx}, 'Apache::DBI::db');
208             }
209              
210             # either there is no database handle-cached or it is not valid,
211             # so get a new database-handle and store it in the cache
212 0           delete $Connected{$Idx};
213 0           $Connected{$Idx} = $drh->connect(@args);
214 0 0         return undef if !$Connected{$Idx};
215              
216             # store the parameters of the initial connection in the handle
217 0           set_startup_state($Idx);
218              
219             # return the new database handle
220 0           debug(1, "$prefix new connect to '$Idx'");
221 0           return (bless $Connected{$Idx}, 'Apache::DBI::db');
222             }
223              
224             # The PerlChildInitHandler creates all connections during server startup.
225             # Note: this handler runs in every child server, but not in the main server.
226             sub childinit {
227              
228 0     0 0   my $prefix = "$$ Apache::DBI ";
229 0           debug(2, "$prefix PerlChildInitHandler");
230              
231 0           %Connected = () if MP2;
232              
233 0 0         if (@ChildConnect) {
234 0           for my $aref (@ChildConnect) {
235 0           shift @$aref;
236 0           DBI->connect(@$aref);
237 0           $LastPingTime{@$aref[0]} = time;
238             }
239             }
240              
241 0           1;
242             }
243              
244             # The PerlChildExitHandler disconnects all open connections
245             sub childexit {
246              
247 0     0 0   my $prefix = "$$ Apache::DBI ";
248 0           debug(2, "$prefix PerlChildExitHandler");
249              
250 0           foreach my $dbh (values(%Connected)) {
251 0           eval { DBI::db::disconnect($dbh) };
  0            
252 0 0         if ($@) {
253 0           debug(2, "$prefix DBI::db::disconnect failed - $@");
254             }
255             }
256              
257 0           1;
258             }
259              
260             # The PerlCleanupHandler is supposed to initiate a rollback after the script
261             # has finished if AutoCommit is off.
262             # Note: the PerlCleanupHandler runs after the response has been sent to
263             # the client
264             sub cleanup {
265 0     0 0   my $Idx = shift;
266              
267 0           my $prefix = "$$ Apache::DBI ";
268 0           debug(2, "$prefix PerlCleanupHandler");
269              
270 0           my $dbh = $Connected{$Idx};
271 0 0 0       if ($Rollback{$Idx}
  0   0        
      0        
      0        
272             and $dbh
273             and $dbh->{Active}
274             and !$dbh->{AutoCommit}
275             and eval {$dbh->rollback}) {
276 0           debug (2, "$prefix PerlCleanupHandler rollback for '$Idx'");
277             }
278              
279 0           delete $Rollback{$Idx};
280              
281 0           1;
282             }
283              
284             # Store the default start state of each dbh in the handle
285             # Note: This uses private_Apache_DBI hash ref to store it in the handle itself
286             my @attrs = qw(
287             AutoCommit Warn CompatMode InactiveDestroy
288             PrintError RaiseError HandleError
289             ShowErrorStatement TraceLevel FetchHashKeyName
290             ChopBlanks LongReadLen LongTruncOk
291             Taint Profile
292             );
293              
294             sub set_startup_state {
295 0     0 0   my $Idx = shift;
296              
297 0           foreach my $key (@attrs) {
298 0           $Connected{$Idx}->{private_Apache_DBI}{$key} =
299             $Connected{$Idx}->{$key};
300             }
301              
302 0 0         if ($TaintInOut) {
303 0           foreach my $key ( qw{ TaintIn TaintOut } ) {
304 0           $Connected{$Idx}->{private_Apache_DBI}{$key} =
305             $Connected{$Idx}->{$key};
306             }
307             }
308              
309 0           1;
310             }
311              
312             # Restore the default start state of each dbh
313             sub reset_startup_state {
314 0     0 0   my $Idx = shift;
315              
316             # Rollback current transaction if currently in one
317 0           $Connected{$Idx}->{Active}
318             and !$Connected{$Idx}->{AutoCommit}
319 0 0 0       and eval {$Connected{$Idx}->rollback};
320              
321 0           foreach my $key (@attrs) {
322 0           $Connected{$Idx}->{$key} =
323             $Connected{$Idx}->{private_Apache_DBI}{$key};
324             }
325              
326 0 0         if ($TaintInOut) {
327 0           foreach my $key ( qw{ TaintIn TaintOut } ) {
328 0           $Connected{$Idx}->{$key} =
329             $Connected{$Idx}->{private_Apache_DBI}{$key};
330             }
331             }
332              
333 0           1;
334             }
335              
336              
337             # This function can be called from other handlers to perform tasks on all
338             # cached database handles.
339 0     0 0   sub all_handlers { return \%Connected }
340              
341             # patch from Tim Bunce: Apache::DBI will not return a DBD ref cursor
342             @Apache::DBI::st::ISA = ('DBI::st');
343              
344             # overload disconnect
345             {
346             package Apache::DBI::db;
347 1     1   16 no strict;
  1         2  
  1         55  
348             @ISA=qw(DBI::db);
349 1     1   6 use strict;
  1         2  
  1         322  
350             sub disconnect {
351 0     0     my $prefix = "$$ Apache::DBI ";
352 0           Apache::DBI::debug(2, "$prefix disconnect (overloaded)");
353 0           1;
354             }
355             ;
356             }
357              
358             # prepare menu item for Apache::Status
359             sub status_function {
360 0     0 0   my($r, $q) = @_;
361              
362 0           my(@s) = qw(<TABLE><TR><TD>Datasource</TD><TD>Username</TD></TR>);
363 0           for (keys %Connected) {
364 0           push @s, '<TR><TD>',
365             join('</TD><TD>',
366             (split($;, $_))[0,1]), "</TD></TR>\n";
367             }
368 0           push @s, '</TABLE>';
369              
370 0           \@s;
371             }
372              
373             if (MP2) {
374             if (Apache2::Module::loaded('Apache2::Status')) {
375             Apache2::Status->menu_item(
376             'DBI' => 'DBI connections',
377             \&status_function
378             );
379             }
380             }
381             else {
382             if ($INC{'Apache.pm'} # is Apache.pm loaded?
383             and Apache->can('module') # really?
384             and Apache->module('Apache::Status')) { # Apache::Status too?
385             Apache::Status->menu_item(
386             'DBI' => 'DBI connections',
387             \&status_function
388             );
389             }
390             }
391              
392             1;
393              
394             __END__
395              
396              
397             =head1 NAME
398              
399             Apache::DBI - Initiate a persistent database connection
400              
401              
402             =head1 SYNOPSIS
403              
404             # Configuration in httpd.conf or startup.pl:
405              
406             PerlModule Apache::DBI # this comes before all other modules using DBI
407              
408             Do NOT change anything in your scripts. The usage of this module is
409             absolutely transparent !
410              
411              
412             =head1 DESCRIPTION
413              
414             This module initiates a persistent database connection.
415              
416             The database access uses Perl's DBI. For supported DBI drivers see:
417              
418             http://dbi.perl.org/
419              
420             When loading the DBI module (do not confuse this with the Apache::DBI module)
421             it checks if the environment variable 'MOD_PERL' has been set
422             and if the module Apache::DBI has been loaded. In this case every connect
423             request will be forwarded to the Apache::DBI module. This checks if a database
424             handle from a previous connect request is already stored and if this handle is
425             still valid using the ping method. If these two conditions are fulfilled it
426             just returns the database handle. The parameters defining the connection have
427             to be exactly the same, including the connect attributes! If there is no
428             appropriate database handle or if the ping method fails, a new connection is
429             established and the handle is stored for later re-use. There is no need to
430             remove the disconnect statements from your code. They won't do anything
431             because the Apache::DBI module overloads the disconnect method.
432              
433             The Apache::DBI module still has a limitation: it keeps database connections
434             persistent on a per process basis. The problem is, if a user accesses a database
435             several times, the http requests will be handled very likely by different
436             processes. Every process needs to do its own connect. It would be nice if all
437             servers could share the database handles, but currently this is not possible
438             because of the distinct memory-space of each process. Also it is not possible
439             to create a database handle upon startup of the httpd and then inherit this
440             handle to every subsequent server. This will cause clashes when the handle is
441             used by two processes at the same time. Apache::DBI has built-in protection
442             against this. It will not make a connection persistent if it sees that it is
443             being opened during the server startup. This allows you to safely open a connection
444             for grabbing data needed at startup and disconnect it normally before the end of
445             startup.
446              
447             With this limitation in mind, there are scenarios, where the usage of
448             Apache::DBI is depreciated. Think about a heavy loaded Web-site where every
449             user connects to the database with a unique userid. Every server would create
450             many database handles each of which spawning a new backend process. In a short
451             time this would kill the web server.
452              
453             Another problem are timeouts: some databases disconnect the client after a
454             certain period of inactivity. The module tries to validate the database handle
455             using the C<ping()> method of the DBI-module. This method returns true by default.
456             Most DBI drivers have a working C<ping()> method, but if the driver you're using
457             doesn't have one and the database handle is no longer valid, you will get an error
458             when accessing the database. As a work-around you can try to add your own C<ping()>
459             method using any database command which is cheap and safe, or you can deactivate the
460             usage of the ping method (see CONFIGURATION below).
461              
462             Here is a generalized ping method, which can be added to the driver module:
463              
464             package DBD::xxx::db; # ====== DATABASE ======
465             use strict;
466              
467             sub ping {
468             my ($dbh) = @_;
469             my $ret = 0;
470             eval {
471             local $SIG{__DIE__} = sub { return (0); };
472             local $SIG{__WARN__} = sub { return (0); };
473             # adapt the select statement to your database:
474             $ret = $dbh->do('select 1');
475             };
476             return ($@) ? 0 : $ret;
477             }
478              
479             Transactions: a standard DBI script will automatically perform a rollback
480             whenever the script exits. In the case of persistent database connections,
481             the database handle will not be destroyed and hence no automatic rollback
482             will occur. At a first glance it even seems possible to handle a transaction
483             over multiple requests. But this should be avoided, because different
484             requests are handled by different processes and a process does not know the state
485             of a specific transaction which has been started by another process. In general,
486             it is good practice to perform an explicit commit or rollback at the end of
487             every request. In order to avoid inconsistencies in the database in case
488             AutoCommit is off and the script finishes without an explicit rollback, the
489             Apache::DBI module uses a PerlCleanupHandler to issue a rollback at the
490             end of every request. Note, that this CleanupHandler will only be used, if
491             the initial data_source sets AutoCommit = 0 or AutoCommit is turned off, after
492             the connect has been done (ie begin_work). However, because a connection may
493             have set other parameters, the handle is reset to its initial connection state
494             before it is returned for a second time.
495              
496             This module plugs in a menu item for Apache::Status or Apache2::Status.
497             The menu lists the current database connections. It should be considered
498             incomplete because of the limitations explained above. It shows the current
499             database connections for one specific process, the one which happens to serve
500             the current request. Other processes might have other database connections.
501             The Apache::Status/Apache2::Status module has to be loaded before the
502             Apache::DBI module !
503              
504             =head1 CONFIGURATION
505              
506             The module should be loaded upon startup of the Apache daemon.
507             Add the following line to your httpd.conf or startup.pl:
508              
509             PerlModule Apache::DBI
510              
511             It is important, to load this module before any other modules using DBI !
512              
513             A common usage is to load the module in a startup file called via the PerlRequire
514             directive. See eg/startup.pl and eg/startup2.pl for examples.
515              
516             There are two configurations which are server-specific and which can be done
517             upon server startup:
518              
519             Apache::DBI->connect_on_init($data_source, $username, $auth, \%attr)
520              
521             This can be used as a simple way to have apache servers establish connections
522             on process startup.
523              
524             Apache::DBI->setPingTimeOut($data_source, $timeout)
525              
526             This configures the usage of the ping method, to validate a connection.
527             Setting the timeout to 0 will always validate the database connection
528             using the ping method (default). Setting the timeout < 0 will de-activate
529             the validation of the database handle. This can be used for drivers, which
530             do not implement the ping-method. Setting the timeout > 0 will ping the
531             database only if the last access was more than timeout seconds before.
532              
533             For the menu item 'DBI connections' you need to call
534             Apache::Status/Apache2::Status BEFORE Apache::DBI ! For an example of the
535             configuration order see startup.pl.
536              
537             To enable debugging the variable $Apache::DBI::DEBUG must be set. This
538             can either be done in startup.pl or in the user script. Setting the variable
539             to 1, just reports about a new connect. Setting the variable to 2 enables full
540             debug output.
541              
542             =head1 PREREQUISITES
543              
544             =head2 MOD_PERL 2.0
545              
546             Apache::DBI version 0.96 and later should work under mod_perl 2.0 RC5 and later
547             with httpd 2.0.49 and later.
548              
549             Apache::DBI versions less than 1.00 are NO longer supported. Additionally,
550             mod_perl versions less then 2.0.0 are NO longer supported.
551              
552             =head2 MOD_PERL 1.0
553             Note that this module needs mod_perl-1.08 or higher, apache_1.3.0 or higher
554             and that mod_perl needs to be configured with the appropriate call-back hooks:
555            
556             PERL_CHILD_INIT=1 PERL_STACKED_HANDLERS=1
557              
558             Apache::DBI v0.94 was the last version before dual mod_perl 2.x support was begun.
559             It still recommended that you use the latest version of Apache::DBI because Apache::DBI
560             versions less than 1.00 are NO longer supported.
561              
562             =head1 DO YOU NEED THIS MODULE?
563              
564             Note that this module is intended for use in porting existing DBI code to mod_perl,
565             or writing code that can run under both mod_perl and CGI. If you are using a
566             database abstraction layer such as Class::DBI or DBIx::Class that already manages persistent connections for you, there is no need to use this module
567             in addition. (Another popular choice, Rose::DB::Object, can cooperate with
568             Apache::DBI or use your own custom connection handling.) If you are developing
569             new code that is strictly for use in mod_perl, you may choose to use
570             C<< DBI->connect_cached() >> instead, but consider adding an automatic rollback
571             after each request, as described above.
572              
573             =head1 SEE ALSO
574              
575             L<Apache>, L<mod_perl>, L<DBI>
576              
577             =head1 AUTHORS
578              
579             =over
580              
581             =item *
582             Philip M. Gollucci <pgollucci@p6m7g8.com> is currently packaging new releases.
583              
584             Ask Bjoern Hansen <ask@develooper.com> packaged a large number of releases.
585              
586             =item *
587             Edmund Mergl was the original author of Apache::DBI. It is now
588             supported and maintained by the modperl mailinglist, see the mod_perl
589             documentation for instructions on how to subscribe.
590              
591             =item *
592             mod_perl by Doug MacEachern.
593              
594             =item *
595             DBI by Tim Bunce <dbi-users-subscribe@perl.org>
596              
597             =back
598              
599             =head1 COPYRIGHT
600              
601             The Apache::DBI module is free software; you can redistribute it and/or
602             modify it under the same terms as Perl itself.
603              
604             =cut