home *** CD-ROM | disk | FTP | other *** search
/ CD Actual Thematic 7: Programming / CDAT7.iso / Share / Editores / Perl5 / perl / lib / site / DBI.pm < prev    next >
Encoding:
Perl POD Document  |  1997-08-10  |  70.6 KB  |  2,229 lines

  1. require 5.003;
  2.  
  3. $DBI::VERSION = '0.89'; # ==> ALSO update the version in the pod text below!
  4.  
  5. =head1 NAME
  6.  
  7. DBI - Database independent interface for Perl
  8.  
  9. =head1 SYNOPSIS
  10.  
  11.   use DBI;
  12.  
  13.   @data_sources = DBI->data_sources($driver_name);
  14.  
  15.   $dbh = DBI->connect($data_source, $username, $auth);
  16.   $dbh = DBI->connect($data_source, $username, $auth, \%attr);
  17.  
  18.   $rc  = $dbh->disconnect;
  19.  
  20.   $rv  = $dbh->do($statement);
  21.   $rv  = $dbh->do($statement, \%attr);
  22.   $rv  = $dbh->do($statement, \%attr, @bind_values);
  23.  
  24.   $sth = $dbh->prepare($statement);
  25.   $sth = $dbh->prepare($statement, \%attr);
  26.  
  27.   $rc = $sth->bind_col($col_num, \$col_variable);
  28.   $rc = $sth->bind_columns(\%attr, @list_of_refs_to_vars_to_bind);
  29.  
  30.   $rv = $sth->bind_param($param_num, $bind_value);
  31.   $rv = $sth->bind_param($param_num, $bind_value, $bind_type);
  32.   $rv = $sth->bind_param($param_num, $bind_value, \%attr);
  33.  
  34.   $rv = $sth->execute;
  35.   $rv = $sth->execute(@bind_values);
  36.  
  37.   @row_ary  = $sth->fetchrow_array;
  38.   $ary_ref  = $sth->fetchrow_arrayref;
  39.   $hash_ref = $sth->fetchrow_hashref;
  40.  
  41.   $rc = $sth->finish;
  42.  
  43.   $rv = $sth->rows;
  44.  
  45.   $rc  = $dbh->commit;
  46.   $rc  = $dbh->rollback;
  47.  
  48.   $sql = $dbh->quote($string);
  49.  
  50.   $rc  = $h->err;
  51.   $str = $h->errstr;
  52.   $rv  = $h->state;
  53.  
  54. =head2 NOTE
  55.  
  56. This is the draft DBI specification that corresponds to the DBI version 0.89
  57. ($Date: 1997/07/25 11:17:49 $).
  58.  
  59.  * The DBI specification is currently evolving quite quickly so it is
  60.  * important to check that you have the latest copy. The RECENT CHANGES
  61.  * section below has a summary of user-visible changes and the F<Changes>
  62.  * file supplied with the DBI holds more detailed change information.
  63.  
  64.  * Note also that whenever the DBI changes the drivers take some time to
  65.  * catch up. Recent versions of the DBI have added many new features that
  66.  * may not yet be supported by the drivers you use. Talk to the authors of
  67.  * those drivers if you need the features.
  68.  
  69. Please also read the DBI FAQ which is installed as a DBI::FAQ module so
  70. you can use perldoc to read it by executing the C<perldoc DBI::FAQ> command.
  71.  
  72. =head2 RECENT CHANGES 
  73.  
  74. A brief summary of significant user-visible changes in recent versions
  75. (if a recent version isn't mentioned it simply means that there were no
  76. significant user-visible changes in that version).
  77.  
  78. =over 4 
  79.  
  80. =item DBI 0.86 - 16th July 1997
  81.  
  82. Added $h->{LongReadLen} and $h->{LongTruncOk} attributes for BLOBS.
  83. Added DBI_USER and DBI_PASS env vars. See L</connect> for usage.
  84. Added DBI->trace() to set global trace level (like per-handle $h->trace).
  85. PERL_DBI_DEBUG env var renamed DBI_TRACE (old name still works for now).
  86. Updated docs, including commit, rollback, AutoCommit and Transactions sections.
  87. Added bind_param method and execute(@bind_values) to docs.
  88.  
  89. =item DBI 0.85 - 25th June 1997
  90.  
  91. The 'new-style connect' (see below) now defaults to AutoCommit mode unless
  92. { AutoCommit => 0 } specified in connect attributes (see L</connect>).
  93. New DBI_DSN env var default for connect method (supersedes DBI_DRIVER).
  94. Documented the func method.
  95.  
  96. =item DBI 0.84 - 20th June 1997
  97.  
  98. Added $h->{PrintError} attribute which, if set true, causes all errors
  99. to trigger a warn().  New-style DBI->connect call now automatically
  100. sets PrintError=1 unless { PrintError => 0 } specified in the connect
  101. attributes (see L</connect>).  The old-style connect with a separate
  102. driver parameter is deprecated.  Renamed $h->debug to $h->trace() and
  103. added a trace filename arg.
  104.  
  105. =item DBI 0.83 - 11th June 1997
  106.  
  107. Added 'new-style' driver specification syntax to the DBI->connect
  108. data_source parameter: DBI->connect( 'dbi:driver:...', $user, $passwd);
  109. The DBI->data_sources method should return data_source names with the
  110. appropriate 'dbi:driver:' prefix.  DBI->connect will warn if \%attr is
  111. true but not a hash ref.  Added new fetchrow methods (fetchrow_array,
  112. fetchrow_arrayref and fetchrow_hashref):  Added the DBI FAQ from
  113. Alligator Descartes in module form for easy reading via "perldoc DBI::FAQ".
  114.  
  115. =item DBI 0.82 - 23rd May 1997
  116.  
  117. Added $h->{RaiseError} attribute which, if set true, causes all errors to
  118. trigger a die(). This makes it much easier to implement robust applications
  119. in terms of higher level eval { ... } blocks and rollbacks.
  120. Added DBI->data_sources($driver) method for implementation by drivers.
  121.  
  122. =back 
  123.  
  124. =cut
  125.  
  126. # The POD text continues at the end of the file.
  127.  
  128. {
  129. package DBI;
  130.  
  131. my $Revision = substr(q$Revision: 1.82 $, 10);
  132.  
  133. # $Id: DBI.pm,v 1.82 1997/07/25 11:17:49 timbo Exp $
  134. #
  135. # Copyright (c) 1995,1996,1997, Tim Bunce
  136. #
  137. # You may distribute under the terms of either the GNU General Public
  138. # License or the Artistic License, as specified in the Perl README file.
  139.  
  140. use Carp;
  141. use DynaLoader ();
  142. use Exporter ();
  143.  
  144. @ISA = qw(Exporter DynaLoader);
  145.  
  146. # Make some utility functions available if asked for
  147. @EXPORT_OK = qw();
  148. @EXPORT    = (); # populated by export_tags:
  149. %EXPORT_TAGS = (
  150.    sql_types => [ qw(SQL_CHAR SQL_NUMERIC SQL_DECIMAL SQL_INTEGER SQL_SMALLINT
  151.             SQL_FLOAT SQL_REAL SQL_DOUBLE SQL_VARCHAR) ],
  152.    utils     => [ qw(neat neat_list dump_results sql) ],
  153. );
  154. Exporter::export_ok_tags('sql_types', 'utils');
  155.  
  156. use strict;
  157.  
  158. $DBI::dbi_debug = $ENV{DBI_TRACE} || $ENV{PERL_DBI_DEBUG} || 0;
  159. carp "Loaded DBI.pm (debug $DBI::dbi_debug)\n" if $DBI::dbi_debug;
  160.  
  161. bootstrap DBI;
  162.  
  163. my $connect_via = "connect";
  164.  
  165. # check if user wants a persistent database connection ( Apache + mod_perl )
  166. my $GATEWAY_INTERFACE = $ENV{GATEWAY_INTERFACE} || '';
  167. if (substr($GATEWAY_INTERFACE,0,8) eq 'CGI-Perl' and $INC{'Apache/DBI.pm'}) {
  168.     $connect_via = "Apache::DBI::connect";
  169.     carp "DBI connect via $INC{'Apache/DBI.pm'}\n" if $DBI::dbi_debug;
  170. }
  171.  
  172.  
  173. if ($DBI::dbi_debug) {
  174.     # this is a bit of a handy hack for "DBI_TRACE=/tmp/dbi.log"
  175.     if ($DBI::dbi_debug =~ m/^\d/) {
  176.     # dbi_debug is number so debug to stderr at that level
  177.     DBI->trace($DBI::dbi_debug);
  178.     }
  179.     else {
  180.     # dbi_debug is a file name to debug to file at level 2
  181.     # the function will reset $dbi_debug to the value 2.
  182.     DBI->trace(2, $DBI::dbi_debug);
  183.     }
  184. }
  185.  
  186. %DBI::installed_drh = ();  # maps driver names to installed driver handles
  187.  
  188.  
  189. # Setup special DBI dynamic variables. See DBI::var::FETCH for details.
  190. # These are dynamically associated with the last handle used.
  191. tie $DBI::err,    'DBI::var', '*err';    # special case: referenced via IHA list
  192. tie $DBI::state,  'DBI::var', '"state';  # special case: referenced via IHA list
  193. tie $DBI::lasth,  'DBI::var', '!lasth';  # special case: return boolean
  194. tie $DBI::errstr, 'DBI::var', '&errstr'; # call &errstr in last used pkg
  195. tie $DBI::rows,   'DBI::var', '&rows';   # call &rows   in last used pkg
  196. sub DBI::var::TIESCALAR{ my $var = $_[1]; bless \$var, 'DBI::var'; }
  197. sub DBI::var::STORE    { Carp::croak "Can't modify \$DBI::${$_[0]} special variable" }
  198. sub DBI::var::DESTROY  { }
  199.  
  200.  
  201. # --- Dynamically create the DBI Standard Interface
  202.  
  203. my $std = undef;
  204. my $keeperr = { O=>0x04 };
  205.  
  206. my @TieHash_IF = (    # Generic Tied Hash Interface
  207.     'STORE'   => $std,
  208.     'FETCH'   => $keeperr,
  209.     'FIRSTKEY'=> $keeperr,
  210.     'NEXTKEY' => $keeperr,
  211.     'EXISTS'  => $keeperr,
  212.     'CLEAR'   => $keeperr,
  213.     'DESTROY' => $keeperr,
  214. );
  215. my @Common_IF = (    # Interface functions common to all DBI classes
  216.     func    =>    {                O=>0x06    },
  217.     event   =>    { U =>[2,0,'$type, @args'],    O=>0x04 },
  218.     trace   =>    { U =>[1,2,'[$trace_level]'],    O=>0x04 },
  219.     debug   =>    { U =>[1,2,'[$debug_level]'],    O=>0x04 }, # old name for trace
  220.     private_data =>    { U =>[1,1],            O=>0x04 },
  221.     err     =>    $keeperr,
  222.     errstr  =>    $keeperr,
  223.     state   =>    { U =>[1,1], O=>0x04 },
  224. );
  225.  
  226. my %DBI_IF = (    # Define the DBI Interface:
  227.  
  228.     dr => {        # Database Driver Interface
  229.     'connect'  =>    { U =>[1,5,'[$db [,$user [,$passwd [,\%attr]]]]'] },
  230.     'disconnect_all'=>{ U =>[1,1] },
  231.     data_sources => { U =>[1,2] },
  232.     @Common_IF,
  233.     @TieHash_IF,
  234.     },
  235.     db => {        # Database Session Class Interface
  236.     commit     =>    { U =>[1,1] },
  237.     rollback   =>    { U =>[1,1] },
  238.     'do'       =>    { U =>[2,0,'$statement [, \%attribs [, @bind_params ] ]'] },
  239.     prepare    =>    { U =>[2,3,'$statement [, \%attribs]'] },
  240.     handler    =>    { U =>[2,2,'\&handler'] },
  241.     ping       =>    { U =>[1,1] },
  242.     disconnect =>    { U =>[1,1] },
  243.     tables     =>    { U =>[1,1] },
  244.     quote      =>    { U =>[2,2, '$str'] },
  245.     rows       =>    $keeperr,
  246.     @Common_IF,
  247.     @TieHash_IF,
  248.     },
  249.     st => {        # Statement Class Interface
  250.     bind_col   =>    { U =>[3,4,'$column, \\$var [, \%attribs]'] },
  251.     bind_columns =>    { U =>[3,0,'\%attribs, \\$var1 [, \\$var2, ...]'] },
  252.     bind_param =>    { U =>[3,4,'$parameter, $var [, \%attribs]'] },
  253.     bind_param_inout => { U =>[4,5,'$parameter, \\$var, $maxlen, [, \%attribs]'] },
  254.     execute    =>    { U =>[1,0,'[@args]'] },
  255.  
  256.     fetch          =>    undef, # alias for fetchrow_arrayref
  257.     fetchrow_arrayref =>    undef,
  258.     fetchrow_hashref  =>    undef,
  259.     fetchrow_array    =>    undef,
  260.     fetchrow         =>    undef, # old alias for fetchrow_array
  261.  
  262.     fetchall_arrayref =>    { U =>[1,1] },
  263.  
  264.     blob_read  =>    { U =>[4,5,'$field, $offset, $len [, \\$buf [, $bufoffset]]'] },
  265.     blob_copy_to_file => { U =>[3,3,'$field, $filename_or_handleref'] },
  266.     finish     =>     { U =>[1,1] },
  267.     rows       =>    $keeperr,
  268.     @Common_IF,
  269.     @TieHash_IF,
  270.     },
  271. );
  272.  
  273. my($class, $method);
  274. foreach $class (keys %DBI_IF){
  275.     my %pkgif = %{$DBI_IF{$class}};
  276.     foreach $method (keys %pkgif){
  277.     DBI->_install_method("DBI::${class}::$method", 'DBI.pm',
  278.             $pkgif{$method});
  279.     }
  280. }
  281.  
  282. # End of init code
  283.  
  284.  
  285. END {
  286.     print STDERR "    DBI::END\n" if $DBI::dbi_debug >= 2;
  287.     # Let drivers know why we are calling disconnect_all:
  288.     $DBI::PERL_ENDING = $DBI::PERL_ENDING = 1;    # avoid typo warning
  289.     DBI->disconnect_all();
  290.     print STDERR "    DBI::END complete\n" if $DBI::dbi_debug >= 2;
  291. }
  292.  
  293.  
  294.  
  295. # --- The DBI->connect Front Door function
  296.  
  297. sub connect {
  298.     my $class = shift;
  299.     my($dsn, $user, $pass, $attr, $driver) = @_;
  300.     my $dsn_driver;
  301.     my $dbh;
  302.  
  303.     # switch $driver<->$attr if called in old style
  304.     ($driver, $attr) = ($attr, $driver) if $attr and !ref($attr);
  305.  
  306.     $dsn ||= $ENV{DBI_DSN} || $ENV{DBI_DBNAME} || '';
  307.     $user = $ENV{DBI_USER} unless defined $user;
  308.     $pass = $ENV{DBI_PASS} unless defined $pass;
  309.  
  310.     if ($DBI::dbi_debug) {
  311.     local $^W = 0;    # prevent 'Use of uninitialized value' warnings
  312.     Carp::carp "$class->connect($dsn, $user, $pass, $driver, $attr)\n"
  313.     }
  314.     die 'Usage: $class->connect([$dsn [,$user [,$passwd [, $driver [,\%attr]]]]])'
  315.         if ( ($driver and ref $driver) or ($attr and not ref $attr));
  316.  
  317.     # get driver from dsn if possible
  318.     $dsn_driver = $1 if $dsn =~ s/^DBI:(.*?)://i;
  319.  
  320.     # set driver from dsn if possible and driver arg not given
  321.     $driver = $dsn_driver if $dsn_driver and !$driver;
  322.  
  323.     my $drh = $class->install_driver($driver)
  324.         or confess "$class->install_driver($driver) failed";
  325.     warn "$class->$connect_via using $driver driver $drh\n" if $DBI::dbi_debug;
  326.  
  327.     unless ($dbh = $drh->$connect_via($dsn, $user, $pass, $attr)) {
  328.     warn "$class->connect failed: ".($drh->errstr)."\n" if $DBI::dbi_debug;
  329.     return undef;
  330.     }
  331.     warn "$class->connect = $dbh\n" if $DBI::dbi_debug;
  332.  
  333.     if ($dsn_driver && !$driver) { # new-style connect so new default semantics
  334.     $dbh->{PrintError} = 1;
  335.     $dbh->{AutoCommit} = 1;
  336.     }
  337.     if (ref $attr) {
  338.     my $a;
  339.     foreach $a (qw(PrintError RaiseError AutoCommit)) {
  340.         $dbh->{$a} = $attr->{$a} if exists $attr->{$a};
  341.     }
  342.     }
  343.  
  344.     $dbh;
  345. }
  346.  
  347.  
  348. sub disconnect_all {
  349.     Carp::carp "DBI::disconnect_all @_\n" if $DBI::dbi_debug;
  350.     foreach(keys %DBI::installed_drh){
  351.     warn "DBI::disconnect_all for '$_'\n" if $DBI::dbi_debug;
  352.     my $drh = $DBI::installed_drh{$_};
  353.     next unless ref $drh;    # avoid problems on premature death
  354.     $drh->disconnect_all();
  355.     }
  356. }
  357.  
  358.  
  359. sub install_driver {
  360.     my $class = shift;
  361.     my($driver, $attribs) = @_;
  362.     my $drh;
  363.  
  364.     $driver ||= $ENV{DBI_DRIVER} || '';
  365.  
  366.     # allow driver to be specified as a 'dbi:driver:' string
  367.     $driver = $1 if $driver =~ s/^DBI:(.*?)://i;
  368.  
  369.     Carp::croak "DBI->install_driver: DBD driver not specified.\n"
  370.     unless $driver;
  371.  
  372.     # already installed
  373.     return $drh if $drh = $DBI::installed_drh{$driver};
  374.  
  375.     Carp::carp "$class->install_driver($driver)\n" if $DBI::dbi_debug;
  376.     Carp::croak 'usage DBI->install_driver($driver [, \%attribs])'
  377.     unless ($class eq 'DBI' and $driver and @_<=3);
  378.  
  379.     # --- load the code
  380.     eval "package DBI::_firesafe; require DBD::$driver";
  381.     if ($@) {
  382.     my $advice = "";
  383.     $advice = "\nPerhaps DBD::$driver was statically linked into a new perl binary."
  384.          ."\nIn which case you need to use that new perl binary."
  385.         if $@ =~ /Can't find loadable object/;
  386.     confess "install_driver($driver) failed: $@$advice\n"
  387.     }
  388.     Carp::carp "DBI->install_driver($driver) loaded\n" if $DBI::dbi_debug;
  389.  
  390.     # --- do some behind-the-scenes checks and setups on the driver
  391.     _setup_driver($driver);
  392.  
  393.     # --- run the driver function
  394.     my $driver_class = "DBD::$driver";
  395.     $drh = eval { $driver_class->driver($attribs || {}) };
  396.     croak "$driver_class initialisation failed: $@"
  397.     unless $drh && ref $drh && !$@;
  398.  
  399.     $DBI::installed_drh{$driver} = $drh;
  400.     Carp::carp "DBI->install_driver($driver) = $drh\n" if $DBI::dbi_debug;
  401.     $drh;
  402. }
  403.  
  404. sub _setup_driver {
  405.     my $driver = shift;
  406.     my $type;
  407.     foreach $type (qw(dr db st)){
  408.     my $class = "DBD::${driver}::$type";
  409.     no strict 'refs';
  410.     push(@{"${class}::ISA"},     "DBD::_::$type");
  411.     push(@{"${class}_mem::ISA"}, "DBD::_mem::$type");
  412.     }
  413. }
  414.  
  415.  
  416. *internal = \&DBD::Switch::dr::driver;
  417. #sub internal { return DBD::Switch::dr::driver(@_); }
  418.  
  419.  
  420. sub available_drivers {
  421.     my($quiet) = @_;
  422.     my(@drivers, $d, $f);
  423.     local(*DBI::DIR);
  424.     my(%seen_dir, %seen_dbd);
  425.     foreach $d (@INC){
  426.     chomp($d); # perl 5 beta 3 bug in #!./perl -Ilib from Test::Harness
  427.     next unless -d "$d/DBD";
  428.     next if $seen_dir{$d};
  429.     $seen_dir{$d} = 1;
  430.     opendir(DBI::DIR,"$d/DBD") || Carp::carp "opendir $d/DBD: $!\n";
  431.     foreach $f (sort readdir(DBI::DIR)){
  432.         next unless $f =~ s/\.pm$//;
  433.         if ($seen_dbd{$f}){
  434.         Carp::carp "DBD::$f in $d is hidden by DBD::$f in $seen_dbd{$f}\n"
  435.             unless $quiet;
  436.             } else {
  437.         push(@drivers, $f);
  438.         }
  439.         $seen_dbd{$f} = $d;
  440.     }
  441.     closedir(DBI::DIR);
  442.     }
  443.     @drivers;
  444. }
  445.  
  446. sub data_sources {
  447.     my($class, $driver) = @_;
  448.     my $drh = $class->install_driver($driver);
  449.     return $drh->data_sources;
  450. }
  451.  
  452. sub neat_list {
  453.     my($listref, $maxlen, $sep) = @_;
  454.     $maxlen = 0 unless defined $maxlen;    # 0 == use internal default
  455.     $sep = ", " unless defined $sep;
  456.     join($sep, map { neat($_,$maxlen) } @$listref);
  457. }
  458.  
  459.  
  460. sub dump_results {
  461.     my($sth, $maxlen, $lsep, $fsep) = @_;
  462.     return 0 unless $sth;
  463.     $maxlen ||= 35;
  464.     $lsep   ||= "\n";
  465.     my $rows = 0;
  466.     my $ref;
  467.     while($ref = $sth->fetch) {
  468.     print $lsep if $rows++ and $lsep;
  469.     print neat_list($ref,$maxlen,$fsep);
  470.     }
  471.     print "\n$rows rows".($DBI::err ? " ($DBI::err: $DBI::errstr)" : "")."\n";
  472.     $rows;
  473. }
  474.  
  475.  
  476. sub sql {        # a simple sql shell
  477.     my $prompt = "dbi> ";
  478.     my $dbh;
  479.     $| = 1;
  480.     if (@ARGV) {
  481.     warn "DBI Connecting to @ARGV\n";
  482.     $dbh = DBI->connect(@ARGV);
  483.     die "$DBI::errstr\n" unless $dbh;
  484.     }
  485.     while(1) {
  486.     print "$prompt ";
  487.     my $cmd = <>;
  488.     return unless $cmd;
  489.     chomp $cmd;
  490.     warn("Not connected yet.\n"),next unless $dbh;
  491.     my $sth = $dbh->prepare($cmd);
  492.     if ($sth) {
  493.         dump_results($sth);
  494.     }
  495.     else {
  496.         warn "$DBI::errstr\n";
  497.     }
  498.     }
  499. }
  500.  
  501.  
  502. sub connect_test_perf {
  503.     my($class, $dsn,$dbuser,$dbpass, $attr) = @_;
  504.     croak "connect_test_perf needs hash ref as fourth arg" unless ref $attr;
  505.     # these are non standard attributes just for this special method
  506.     my $loops ||= $attr->{dbi_loops} || 5;
  507.     my $par   ||= $attr->{dbi_par}   || 1;    # parallelism
  508.     my $verb  ||= $attr->{dbi_verb}  || 1;
  509.     print "$dsn: testing $loops sets of $par connections:\n";
  510.     require Benchmark;
  511.     require FileHandle;
  512.     $| = 1;
  513.     my $t0 = new Benchmark;        # not currently used
  514.     my $drh = $class->install_driver($dsn) or die "Can't install $dsn driver\n";
  515.     my $t1 = new Benchmark;
  516.     my $loop;
  517.     for $loop (1..$loops) {
  518.     my @cons;
  519.     print "Connecting... " if $verb;
  520.     for (1..$par) {
  521.         print "$_ ";
  522.         push @cons, ($drh->connect($dsn,$dbuser,$dbpass)
  523.             or die "Can't connect # $_: $DBI::errstr\n");
  524.     }
  525.     print "\nDisconnecting...\n" if $verb;
  526.     for (@cons) {
  527.         $_->disconnect or warn "bad disconnect $DBI::errstr"
  528.     }
  529.     }
  530.     my $t2 = new Benchmark;
  531.     my $td = Benchmark::timediff($t2, $t1);
  532.     printf "Made %2d connections in %s\n\n", $loops*$par, Benchmark::timestr($td);
  533.     return $td;
  534. }
  535.  
  536.  
  537. sub MakeMakerAttribs {
  538.     # return extra attributes for DBD Makefile.PL WriteMakefile()
  539.     ();
  540. }
  541.  
  542.  
  543. # --- Private Internal Function for Creating New DBI Handles
  544.  
  545. sub _new_handle {
  546.     my($class, $parent, $attr, $imp_data) = @_;
  547.     $parent = '' unless $parent;
  548.  
  549.     confess 'Usage: DBI::_new_handle'
  550.     .'($class_name, parent_handle, \%attribs, $imp_data)'."\n"
  551.     .'got: ('.join(", ",$class, $parent, $attr, $imp_data).")\n"
  552.     unless(@_ == 4
  553.         and (!$parent or ref $parent)
  554.         and ref $attr eq 'HASH'
  555.         );
  556.  
  557.     my $imp_class = $attr->{ImplementorClass} or
  558.     croak "_new_handle($class): 'ImplementorClass' attribute not given";
  559.  
  560.     printf(STDERR "    New $class (for $imp_class, parent=$parent, id=%s)\n",
  561.         ($imp_data||''))
  562.     if ($DBI::dbi_debug >= 2);
  563.  
  564.     warn "_new_handle($class): "
  565.         ."invalid implementor class '$imp_class' given\n"
  566.         unless $imp_class =~ m/::(dr|db|st)$/;
  567.  
  568.     # This is how we create a DBI style Object:
  569.     my(%hash, $i, $h);
  570.     $i = tie    %hash, $class, $attr;  # ref to inner hash (for driver)
  571.     $h = bless \%hash, $class;         # ref to outer hash (for application)
  572.     # The above tie and bless may migrate down into _setup_handle()...
  573.     # Now add magic so DBI method dispatch works
  574.     my @imp_data;
  575.     push(@imp_data, $imp_data) if defined $imp_data;
  576.     DBI::_setup_handle($h, $imp_class, $parent, @imp_data);
  577.  
  578.     warn "    New $class => $h (inner=$i) for $imp_class\n"
  579.     if ($DBI::dbi_debug >= 2);
  580.     return $h unless wantarray;
  581.     ($h, $i);
  582. }
  583. {   # implement minimum constructors for the tie's (could be moved to xs)
  584.     package DBI::dr; sub TIEHASH { bless $_[1] };
  585.     package DBI::db; sub TIEHASH { bless $_[1] };
  586.     package DBI::st; sub TIEHASH { bless $_[1] };
  587. }
  588.  
  589.  
  590. # These three constructors are called by the drivers
  591.  
  592. sub _new_drh {    # called by DBD::<drivername>::driver()
  593.     my($class, $initial_attr, $imp_data) = @_;
  594.     # Provide default storage for State,Err and Errstr.
  595.     # State must be undef to get automatic faking in DBI::var::FETCH
  596.     my($h_state_store, $h_err_store, $h_errstr_store) = (undef, 0, '');
  597.     my $attr = {
  598.     'ImplementorClass' => $class,
  599.     # these attributes get copied down to child handles
  600.     'Handlers'    => [],
  601.     'State'        => \$h_state_store,  # Holder for DBI::state
  602.     'Err'        => \$h_err_store,    # Holder for DBI::err
  603.     'Errstr'    => \$h_errstr_store, # Holder for DBI::errstr
  604.     'Debug'     => 0,
  605.     %$initial_attr,
  606.     'Type'=>'dr',
  607.     };
  608.     _new_handle('DBI::dr', undef, $attr, $imp_data);
  609. }
  610.  
  611. sub _new_dbh {    # called by DBD::<drivername>::dr::connect()
  612.     my($drh, $initial_attr, $imp_data) = @_;
  613.     my($imp_class) = $drh->{ImplementorClass};
  614.     $imp_class =~ s/::dr$/::db/;
  615.     confess "new db($drh, $imp_class): not given an driver handle"
  616.         unless $drh->{Type} eq 'dr';
  617.     my $attr = {
  618.     'ImplementorClass' => $imp_class,
  619.     %$initial_attr,
  620.     'Type'   => 'db',
  621.     'Driver' => $drh,
  622.     };
  623.     _new_handle('DBI::db', $drh, $attr, $imp_data);
  624. }
  625.  
  626. sub _new_sth {    # called by DBD::<drivername>::db::prepare()
  627.     my($dbh, $initial_attr, $imp_data) = @_;
  628.     my($imp_class) = $dbh->{ImplementorClass};
  629.     $imp_class =~ s/::db$/::st/;
  630.     confess "new st($dbh, $imp_class): not given a database handle"
  631.     unless (ref $dbh eq 'DBI::db' and $dbh->{Type} eq 'db');
  632.     my $attr = {
  633.     'ImplementorClass' => $imp_class,
  634.     %$initial_attr,
  635.     'Type'     => 'st',
  636.     'Database' => $dbh,
  637.     };
  638.     _new_handle('DBI::st', $dbh, $attr, $imp_data);
  639. }
  640.  
  641. } # end of DBI package scope
  642.  
  643.  
  644.  
  645. # --------------------------------------------------------------------
  646. # === The internal DBI Switch pseudo 'driver' class ===
  647.  
  648. {   package DBD::Switch::dr;
  649.     DBI::_setup_driver('Switch');    # sets up @ISA
  650.     require Carp;
  651.  
  652.     $imp_data_size = 0;
  653.     $imp_data_size = 0;    # avoid typo warning
  654.     $err = 0;
  655.  
  656.     sub driver {
  657.     return $drh if $drh;    # a package global
  658.  
  659.     my $inner;
  660.     ($drh, $inner) = DBI::_new_drh('DBD::Switch::dr', {
  661.         'Name'    => 'Switch',
  662.         'Version' => $DBI::VERSION,
  663.         # the Attribution is defined as a sub as an example
  664.         'Attribution' => sub { "DBI-$DBI::VERSION Switch by Tim Bunce" },
  665.         }, \$err);
  666.     Carp::confess("DBD::Switch init failed!") unless ($drh && $inner);
  667.     $DBD::Switch::dr::drh;
  668.     }
  669.  
  670.     sub FETCH {
  671.     my($drh, $key) = @_;
  672.     return DBI->trace if $key eq 'DebugDispatch';
  673.     return undef if $key eq 'DebugLog';    # not worth fetching, sorry
  674.     return $drh->DBD::_::dr::FETCH($key);
  675.     undef;
  676.     }
  677.     sub STORE {
  678.     my($drh, $key, $value) = @_;
  679.     if ($key eq 'DebugDispatch') {
  680.         DBI->trace($value);
  681.     } elsif ($key eq 'DebugLog') {
  682.         DBI->trace(-1, $value);
  683.     } else {
  684.         $drh->DBD::_::dr::STORE($key, $value);
  685.     }
  686.     }
  687. }
  688.  
  689.  
  690. # --------------------------------------------------------------------
  691. # === OPTIONAL MINIMAL BASE CLASSES FOR DBI SUBCLASSES ===
  692.  
  693. # We only define default methods for harmless functions.
  694. # We don't, for example, define a DBD::_::st::prepare()
  695.  
  696. {   package DBD::_::common; # ====== Common base class methods ======
  697.     use strict;
  698.  
  699.     # methods common to all handle types:
  700.  
  701.     # generic TIEHASH default methods:
  702.     sub FIRSTKEY { undef }
  703.     sub NEXTKEY  { undef }
  704.     sub EXISTS   { defined($_[0]->FETCH($_[1])) } # to be sure
  705.     sub CLEAR    { Carp::carp "Can't CLEAR $_[0] (DBI)" }
  706. }
  707.  
  708.  
  709. {   package DBD::_::dr;  # ====== DRIVER ======
  710.     @ISA = qw(DBD::_::common);
  711.     use strict;
  712.  
  713.     sub connect { # normally overridden, but a handy default
  714.     my($drh, $dsn, $user, $auth)= @_;
  715.     my($this) = DBI::_new_dbh($drh, {
  716.         'Name' => $dsn,
  717.         'User' => $user,
  718.         });
  719.     $this;
  720.     }
  721.     sub disconnect_all {    # Driver must take responsibility for this
  722.     Carp::confess "Driver has not implemented the disconnect_all method.";
  723.     }
  724.     sub data_sources {
  725.     Carp::confess "Driver has not implemented the data_sources method.";
  726.     }
  727. }
  728.  
  729.  
  730. {   package DBD::_::db;  # ====== DATABASE ======
  731.     @ISA = qw(DBD::_::common);
  732.     use strict;
  733.  
  734.     sub quote {
  735.     my $self = shift;
  736.     my $str  = shift;
  737.     return "NULL" unless defined $str;
  738.     $str=~s/'/''/g;        # ISO SQL2
  739.     "'$str'";
  740.     }
  741.  
  742.     sub rows { -1 }
  743.  
  744.     sub do {
  745.     my($dbh, $statement, $attribs, @params) = @_;
  746.     my $sth = $dbh->prepare($statement, $attribs) or return undef;
  747.     $sth->execute(@params) or return undef;
  748.     my $rows = $sth->rows;
  749.     ($rows == 0) ? "0E0" : $rows;
  750.     }
  751.  
  752.     sub commit    {
  753.     Carp::carp "commit: not supported by $_[0]\n" if $DBI::dbi_debug;
  754.     undef;
  755.     }
  756.     sub rollback{
  757.     Carp::carp "rollback: not supported by $_[0]\n" if $DBI::dbi_debug;
  758.     undef;
  759.     }
  760.     sub ping        { 1 }        # we assume that all is well
  761.     sub disconnect  { undef }
  762. }
  763.  
  764.  
  765. {   package DBD::_::st;  # ====== STATEMENT ======
  766.     @ISA = qw(DBD::_::common);
  767.     use strict;
  768.  
  769.     sub finish  { undef }
  770.     sub rows    { -1 }
  771.     # bind_param => not implemented - fail
  772.  
  773.     sub fetchrow_hashref {
  774.     my $sth = shift;
  775.     # This may be recoded in XS. It could work with fb_av and bind_col.
  776.     # Probably best to add an AV*fields_hvav to dbih_stc_t and set it up
  777.     # on the first call to fetchhash which alternate name/value pairs.
  778.     # This implementation is just rather simple and not very optimised.
  779.     my $row = $sth->fetch or return undef;
  780.     my %hash;
  781.     @hash{ @{ $sth->FETCH('NAME') } } = @$row;
  782.     return \%hash;
  783.     }
  784.  
  785.     sub fetchall_arrayref {
  786.     my $sth = shift;
  787.     my $via = shift || 'fetch';    # XXX not documented: may change
  788.     my @rows;
  789.     my $row;
  790.     if ($via eq 'fetch') {
  791.         while( $row = $sth->fetch ) {
  792.         # we copy the array here because fetch (currently) always
  793.         # returns the same array ref. Eventually scrolling cursors
  794.         # will be added to the DBI.
  795.         push @rows, [ @$row ];
  796.         }
  797.     }
  798.     elsif ($via eq 'fetchhash') {
  799.         while( $row = $sth->fetchhash ) {
  800.         push @rows, $row;
  801.         }
  802.     }
  803.     else { Carp::croak "fetchall($via) invalid" }
  804.     return \@rows;
  805.     }
  806.  
  807.     sub blob_copy_to_file {    # returns length or undef on error
  808.     my($self, $field, $filename_or_handleref, $blocksize) = @_;
  809.     my $fh = $filename_or_handleref;
  810.     my($len, $buf) = (0, "");
  811.     $blocksize ||= 512;    # not too ambitious
  812.     local(*FH);
  813.     unless(ref $fh) {
  814.         open(FH, ">$fh") || return undef;
  815.         $fh = \*FH;
  816.     }
  817.     while(defined($self->blob_read($field, $len, $blocksize, \$buf))) {
  818.         print $fh $buf;
  819.         $len += length $buf;
  820.     }
  821.     close(FH);
  822.     $len;
  823.     }
  824.  
  825.     # Drivers are required to implement *::st::DESTROY to encourage tidy-up
  826.     sub DESTROY  { Carp::confess "Driver has not implemented DESTROY for @_" }
  827. }
  828.  
  829. {   # See install_driver
  830.     { package DBD::_mem::dr; @ISA = qw(DBD::_mem::common);    }
  831.     { package DBD::_mem::db; @ISA = qw(DBD::_mem::common);    }
  832.     { package DBD::_mem::st; @ISA = qw(DBD::_mem::common);    }
  833.     # DBD::_mem::common::DESTROY is implemented in DBI.xs
  834. }
  835.  
  836. 1;
  837. __END__
  838.  
  839. =head1 DESCRIPTION
  840.  
  841. The Perl DBI is a database access Application Programming Interface
  842. (API) for the Perl Language.  The DBI defines a set of functions,
  843. variables and conventions that provide a consistent database interface
  844. independant of the actual database being used.
  845.  
  846. It is important to remember that the DBI is just an interface. A thin
  847. layer of 'glue' between an application and one or more Database Drivers.
  848. It is the drivers which do the real work. The DBI provides a standard
  849. interface and framework for the drivers to operate within.
  850.  
  851. This document is a I<work-in-progress>. Although it is incomplete it
  852. should be useful in getting started with the DBI.
  853.  
  854.  
  855. =head2 Architecture of a DBI Application
  856.  
  857.              |<- Scope of DBI ->|
  858.                   .-.   .--------------.   .-------------.
  859.   .-------.       | |---| XYZ Driver   |---| XYZ Engine  |
  860.   | Perl  |       |S|   `--------------'   `-------------'
  861.   | script|  |A|  |w|   .--------------.   .-------------.
  862.   | using |--|P|--|i|---|Oracle Driver |---|Oracle Engine|
  863.   | DBI   |  |I|  |t|   `--------------'   `-------------'
  864.   | API   |       |c|...
  865.   |methods|       |h|... Other drivers
  866.   `-------'       | |...
  867.                   `-'
  868.  
  869. The API is the Application Perl-script (or Programming) Interface.  The
  870. call interface and variables provided by DBI to perl scripts. The API
  871. is implemented by the DBI Perl extension.
  872.  
  873. The 'Switch' is the code that 'dispatches' the DBI method calls to the
  874. appropriate Driver for actual execution.  The Switch is also
  875. responsible for the dynamic loading of Drivers, error checking/handling
  876. and other duties. The DBI and Switch are generally synonymous.
  877.  
  878. The Drivers implement support for a given type of Engine (database).
  879. Drivers contain implementations of the DBI methods written using the
  880. private interface functions of the corresponding Engine.  Only authors
  881. of sophisticated/multi-database applications or generic library
  882. functions need be concerned with Drivers.
  883.  
  884. =head2 Notation and Conventions
  885.  
  886.   DBI    static 'top-level' class name
  887.   $dbh   Database handle object
  888.   $sth   Statement handle object
  889.   $drh   Driver handle object (rarely seen or used in applications)
  890.   $h     Any of the $??h handle types above
  891.   $rc    General Return Code  (boolean: true=ok, false=error)
  892.   $rv    General Return Value (typically an integer)
  893.   @ary   List of values returned from the database, typically a row of data
  894.   $rows  Number of rows processed by a function (if available, else -1)
  895.   $fh    A filehandle
  896.   undef  NULL values are represented by undefined values in perl
  897.  
  898. Note that Perl will automatically destroy database and statement objects
  899. if all references to them are deleted.
  900.  
  901. Handle object attributes are shown as:
  902.  
  903. C<  $h-E<gt>{attribute_name}>   (I<type>)
  904.  
  905. where I<type> indicates the type of the value of the attribute (if it's
  906. not a simple scalar):
  907.  
  908.   \$   reference to a scalar: $h->{attr}       or  $a = ${$h->{attr}}
  909.   \@   reference to a list:   $h->{attr}->[0]  or  @a = @{$h->{attr}}
  910.   \%   reference to a hash:   $h->{attr}->{a}  or  %a = %{$h->{attr}}
  911.  
  912.  
  913. =head2 General Interface Rules & Caveats
  914.  
  915. The DBI does not have a concept of a `current session'. Every session
  916. has a handle object (i.e., a $dbh) returned from the connect method and
  917. that handle object is used to invoke database related methods.
  918.  
  919. Most data is returned to the perl script as strings (null values are
  920. returned as undef).  This allows arbitrary precision numeric data to be
  921. handled without loss of accuracy.  Be aware that perl may not preserve
  922. the same accuracy when the string is used as a number.
  923.  
  924. Dates and times are returned as character strings in the native format
  925. of the corresponding Engine.  Time Zone effects are Engine/Driver
  926. dependent.
  927.  
  928. Perl supports binary data in perl strings and the DBI will pass binary
  929. data to and from the Driver without change. It is up to the Driver
  930. implementors to decide how they wish to handle such binary data.
  931.  
  932. Multiple SQL statements may not be combined in a single statement
  933. handle, e.g., a single $sth.
  934.  
  935. Non-sequential record reads are not supported in this version of the
  936. DBI. E.g., records can only be fetched in the order that the database
  937. returned them and once fetched they are forgotten.
  938.  
  939. Positioned updates and deletes are not directly supported by the DBI.
  940. See the description of the CursorName attribute for an alternative.
  941.  
  942. Individual Driver implementors are free to provide any private
  943. functions and/or handle attributes that they feel are useful.  Private
  944. functions can be invoked using the DBI C<func> method (which is
  945. currently not documented). Private attributes are accessed just like
  946. standard attributes.
  947.  
  948. Character sets: Most databases which understand character sets have a
  949. default global charset and text stored in the database is, or should
  950. be, stored in that charset (if it's not then that's the fault of either
  951. the database or the application that inserted the data). When text is
  952. fetched it should be (automatically) converted to the charset of the
  953. client (presumably based on the locale). If a driver needs to set a
  954. flag to get that behaviour then it should do so. It should not require
  955. the application to do that.
  956.  
  957.  
  958. =head2 Naming Conventions
  959.  
  960. The DBI package and all packages below it (DBI::*) are reserved for
  961. use by the DBI. Package names beginning with DBD:: are reserved for use
  962. by DBI database drivers.  All environment variables used by the DBI
  963. or DBD's begin with 'DBI_' or 'DBD_'.
  964.  
  965. The letter case used for attribute names is significant and plays an
  966. important part in the portability of DBI scripts.  The case of the
  967. attribute name is used to signify who defined the meaning of that name
  968. and its values.
  969.  
  970.   Case of name  Has a meaning defined by
  971.   ------------  ------------------------
  972.   UPPER_CASE    Standards, e.g.,  X/Open, SQL92 etc (portable)
  973.   MixedCase     DBI API (portable), underscores are not used.
  974.   lower_case    Driver or Engine specific (non-portable)
  975.  
  976. It is of the utmost importance that Driver developers only use
  977. lowercase attribute names when defining private attributes.
  978.  
  979.  
  980. =head2 Data Query Methods
  981.  
  982. The DBI allows an application to `prepare' a statement for later execution.
  983. A prepared statement is identified by a statement handle object, e.g., $sth.
  984.  
  985. Typical method call sequence for a select statement:
  986.  
  987.   connect,
  988.     prepare,
  989.       execute, fetch, fetch, ... finish,
  990.       execute, fetch, fetch, ... finish,
  991.       execute, fetch, fetch, ... finish.
  992.  
  993. Typical method call sequence for a non-select statement:
  994.  
  995.   connect,
  996.     prepare,
  997.       execute,
  998.       execute,
  999.       execute.
  1000.  
  1001.  
  1002. =head2 Placeholders and Bind Values
  1003.  
  1004. Some drivers support Placeholders and Bind Values. These drivers allow
  1005. a database statement to contain placeholders, sometimes called
  1006. parameter markers, that indicate values that will be supplied later,
  1007. before the prepared statement is executed.  For example, an application
  1008. might use the following to insert a row of data into the SALES table:
  1009.  
  1010.   insert into sales (product_code, qty, price) values (?, ?, ?)
  1011.  
  1012. or the following, to select the description for a product:
  1013.  
  1014.   select product_description from products where product_code = ?
  1015.  
  1016. The C<?> characters are the placeholders.  The association of actual
  1017. values with placeholders is known as binding and the values are
  1018. referred to as bind values. Undefined values or C<undef> can be used
  1019. to indicate null values.
  1020.  
  1021. Without using placeholders, the insert statement above would have to
  1022. contain the literal values to be inserted and it would have to be
  1023. re-prepared and re-executed for each row. With placeholders, the insert
  1024. statement only needs to be prepared once. The bind values for each row
  1025. can be given to the execute method each time it's called. By avoiding
  1026. the need to re-prepare the statement for each row the application
  1027. typically many times faster! Here's an example:
  1028.  
  1029.   my $sth = $dbh->prepare(q{
  1030.     insert into sales (product_code, qty, price) values (?, ?, ?)
  1031.   }) || die $dbh->errstr;
  1032.   while(<>) {
  1033.       chop;
  1034.       my($product_code, $qty, $price) = split(/,/);
  1035.       $sth->execute($product_code, $qty, $price) || die $dbh->errstr;
  1036.   }
  1037.   $dbh->commit || die $dbh->errstr;
  1038.  
  1039. See L</execute> and L</bind_param> for more details.
  1040.  
  1041. =head2 SQL - A Query Language
  1042.  
  1043. Most DBI drivers require applications to use a dialect of SQL (the
  1044. Structured Query Language) to interact with the database engine.  These
  1045. links may provide some useful information about SQL:
  1046.  
  1047.   http://www.jcc.com/sql_stnd.html
  1048.   http://w3.one.net/~jhoffman/sqltut.htm
  1049.   http://skpc10.rdg.ac.uk/misc/sqltut.htm
  1050.  
  1051. The DBI itself does not mandate or require any particular language to
  1052. be used.  It is language independant. In ODBC terms it is always in
  1053. pass-thru mode. The only requirement is that queries and other
  1054. statements must be expressed as a single string of letters passed
  1055. as the first argument to the L</prepare> method.
  1056.  
  1057. =head1 THE DBI CLASS
  1058.  
  1059. =head2 DBI Class Methods
  1060.  
  1061. =over 4
  1062.  
  1063. =item B<connect>
  1064.  
  1065.   $dbh = DBI->connect($data_source, $username, $password);
  1066.   $dbh = DBI->connect($data_source, $username, $password, \%attr);
  1067.  
  1068. Establishes a database connection (session) to the requested data_source.
  1069. Returns a database handle object.
  1070.  
  1071. Multiple simultaneous connections to multiple databases through multiple
  1072. drivers can be made via the DBI. Simply make one connect call for each
  1073. and keep a copy of each returned database handle.
  1074.  
  1075. The $data_source value should begin with 'dbi:driver_name:'. That
  1076. prefix will be stripped off and the driver_name part is used to specify
  1077. the driver.  As a convenience, if the $data_source field is undefined
  1078. or empty the DBI will substitute the value of the environment variable
  1079. DBI_DSN if any.
  1080.  
  1081. If driver is not specified, the environment variable DBI_DRIVER is
  1082. used. If that variable is not set then the connect dies.
  1083.  
  1084. If $username or $password are I<undefined> (rather than empty) then the
  1085. DBI will substitute the values of the DBI_USER and DBI_PASS environment
  1086. variables respectively.  The use of the environment for these values is
  1087. not recommended for security reasons. The mechanism is only intended to
  1088. simplify testing.
  1089.  
  1090. DBI->connect automatically installs the driver if it has not been
  1091. installed yet. Driver installation I<always> returns a valid driver
  1092. handle or it I<dies> with an error message which includes the string
  1093. 'install_driver' and the underlying problem. So, DBI->connect will die
  1094. on a driver installation failure and will only return undef on a
  1095. connect failure, for which $DBI::errstr will hold the error.
  1096.  
  1097. The $data_source argument (with the 'dbi:...:' prefix removed) and the
  1098. $username and $password arguments are then passed to the driver for
  1099. processing. The DBI does not define I<any> interpretation for the
  1100. contents of these fields.  The driver is free to interpret the
  1101. data_source, username and password fields in any way and supply
  1102. whatever defaults are appropriate for the engine being accessed
  1103. (Oracle, for example, uses the ORACLE_SID and TWO_TASK env vars if no
  1104. data_source is specified).
  1105.  
  1106. The AutoCommit and PrintError attributes for each connection default to
  1107. default to I<on> (see L</AutoCommit> and L</PrintError> for more information).
  1108.  
  1109. The \%attr parameter can be used to alter the default settings of the
  1110. PrintError, RaiseError and AutoCommit attributes. For example:
  1111.  
  1112.   $dbh = DBI->connect($data_source, $user, $pass, {
  1113.     PrintError => 0,
  1114.     AutoCommit => 0
  1115.   });
  1116.  
  1117. These are currently the I<only> defined uses for the DBI->connect \%attr.
  1118.  
  1119. Portable applications should not assume that a single driver will be
  1120. able to support multiple simultaneous sessions.
  1121.  
  1122. Where possible each session ($dbh) is independent from the transactions
  1123. in other sessions. This is useful where you need to hold cursors open
  1124. across transactions, e.g., use one session for your long lifespan
  1125. cursors (typically read-only) and another for your short update
  1126. transactions.
  1127.  
  1128. For compatibility with old DBI scripts the driver can be specified by
  1129. passing its name as the fourth argument to connect (instead of \%attr):
  1130.  
  1131.   $dbh = DBI->connect($data_source, $user, $pass, $driver);
  1132.  
  1133. In this 'old-style' form of connect the $data_source should not start
  1134. with 'dbi:driver_name:' and, even if it does, the embedded driver_name
  1135. will be ignored. The $dbh->{AutoCommit} attribute is I<undefined>. The
  1136. $dbh->{PrintError} attribute is off. And the old DBI_DBNAME env var is
  1137. checked if DBI_DSN is not defined.
  1138.  
  1139. =item B<available_drivers>
  1140.  
  1141.   @ary = DBI->available_drivers;
  1142.   @ary = DBI->available_drivers($quiet);
  1143.  
  1144. Returns a list of all available drivers by searching for DBD::* modules
  1145. through the directories in @INC. By default a warning will be given if
  1146. some drivers are hidden by others of the same name in earlier
  1147. directories. Passing a true value for $quiet will inhibit the warning.
  1148.  
  1149.  
  1150. =item B<data_sources>
  1151.  
  1152.   @ary = DBI->data_sources($driver);
  1153.  
  1154. Returns a list of all data sources (databases) available via the named
  1155. driver. The driver will be loaded if not already. If $driver is empty
  1156. or undef then the value of the DBI_DRIVER environment variable will be
  1157. used.
  1158.  
  1159. Note that many drivers have no way of knowing what data sources might
  1160. be available for it and thus, typically, return an empty list.
  1161.  
  1162.  
  1163. =item B<trace>
  1164.  
  1165.   DBI->trace($trace_level)
  1166.   DBI->trace($trace_level, $trace_file)
  1167.  
  1168. DBI trace information can be enabled for all handles using this DBI
  1169. class method. To enable trace information for a specific handle use
  1170. the similar $h->trace method described elsewhere.
  1171.  
  1172. Use $trace_level 2 to see detailed call trace information including
  1173. parameters and return values.  The trace output is detailed and
  1174. typically I<very> useful.
  1175.  
  1176. Use $trace_level 0 to disable the trace.
  1177.  
  1178. If $trace_filename is specified then the file is opened in append
  1179. mode and I<all> trace output (including that from other handles)
  1180. is redirected to that file.
  1181.  
  1182. See also the $h->trace() method and L</DEBUGGING> for information
  1183. about the DBI_TRACE environment variable.
  1184.  
  1185.  
  1186. =back
  1187.  
  1188.  
  1189. =head2 DBI Utility Functions
  1190.  
  1191. =over 4
  1192.  
  1193. =item B<neat>
  1194.  
  1195.   $str = DBI::neat($value, $maxlen);
  1196.  
  1197. Return a string containing a neat (and tidy) representation of the
  1198. supplied value. Strings will be quoted and undefined (NULL) values
  1199. will be shown as C<undef>. Unprintable characters will be replaced by
  1200. dot (.) and the string will be truncated and terminated with '...'
  1201. if longer than $maxlen (0 or undef defaults to 400 characters).
  1202.  
  1203. =item B<neat_list>
  1204.  
  1205.   $str = DBI::neat_list(\@listref, $maxlen, $field_sep);
  1206.  
  1207. Calls DBI::neat on each element of the list and returns a string
  1208. containing the results joined with $field_sep. $field_sep defaults
  1209. to C<", ">.
  1210.  
  1211.  
  1212. =item B<dump_results>
  1213.  
  1214.   $rows = DBI::dump_results($sth, $maxlen, $lsep, $fsep, $fh);
  1215.  
  1216. Fetches all the rows from $sth, calls DBI::neat_list for each row and
  1217. prints the results to $fh (defaults to C<STDOUT>) separated by $lsep
  1218. (default C<"\n">). $fsep defaults to C<", "> and $maxlen defaults to 35.
  1219. This function is designed as a handy utility for prototyping and
  1220. testing queries.
  1221.  
  1222. =back
  1223.  
  1224.  
  1225. =head2 DBI Dynamic Attributes
  1226.  
  1227. These attributes are always associated with the last handle used.
  1228.  
  1229. Where an attribute is Equivalent to a method call, then refer to
  1230. the method call for all related documentation.
  1231.  
  1232. =over 4
  1233.  
  1234. =item B<$DBI::err>
  1235.  
  1236. Equivalent to $h->err.
  1237.  
  1238. =item B<$DBI::errstr>
  1239.  
  1240. Equivalent to $h->errstr.
  1241.  
  1242. =item B<$DBI::state>
  1243.  
  1244. Equivalent to $h->state.
  1245.  
  1246. =item B<$DBI::rows>
  1247.  
  1248. Equivalent to $h->rows.
  1249.  
  1250. =back
  1251.  
  1252.  
  1253. =head1 METHODS COMMON TO ALL HANDLES
  1254.  
  1255. =over 4
  1256.  
  1257. =item B<err>
  1258.  
  1259.   $rv = $h->err;
  1260.  
  1261. Returns the native database engine error code from the last driver
  1262. function called.
  1263.  
  1264. =item B<errstr>
  1265.  
  1266.   $str = $h->errstr;
  1267.  
  1268. Returns the native database engine error message from the last driver
  1269. function called.
  1270.  
  1271. =item B<state>
  1272.  
  1273.   $str = $h->state;
  1274.  
  1275. Returns an error code in the standard SQLSTATE five character format.
  1276. Note that the specific success code C<00000> is translated to C<0>
  1277. (false). If the driver does not support SQLSTATE then state will
  1278. return C<S1000> (General Error) for all errors.
  1279.  
  1280. =item B<trace>
  1281.  
  1282.   $h->trace($trace_level);
  1283.   $h->trace($trace_level, $trace_filename);
  1284.  
  1285. DBI trace information can be enabled for a specific handle (and any
  1286. future children of that handle) by setting the trace level using the
  1287. trace method.
  1288.  
  1289. Use $trace_level 2 to see detailed call trace information including
  1290. parameters and return values.  The trace output is detailed and
  1291. typically I<very> useful.
  1292.  
  1293. Use $trace_level 0 to disable the trace.
  1294.  
  1295. If $trace_filename is specified then the file is opened in append
  1296. mode and I<all> trace output (including that from other handles)
  1297. is redirected to that file.
  1298.  
  1299. See also the DBI->trace() method and L</DEBUGGING> for information
  1300. about the DBI_TRACE environment variable.
  1301.  
  1302.  
  1303. =item B<func>
  1304.  
  1305.   $h->func(@func_arguments, $func_name);
  1306.  
  1307. The func method can be used to call private non-standard and
  1308. non-portable methods implemented by the driver. Note that the function
  1309. name is given as the I<last> argument.
  1310.  
  1311. =back
  1312.  
  1313.  
  1314. =head1 ATTRIBUTES COMMON TO ALL HANDLES
  1315.  
  1316. These attributes are common to all types of DBI handles.
  1317.  
  1318. Some attributes are inherited by I<child> handles. That is, the value
  1319. of an inherited attribute in a newly created statement handle is the
  1320. same as the value in the parent database handle. Changes to attributes
  1321. in the new statement handle do not affect the parent database handle
  1322. and changes to the database handle do not affect I<existing> statement
  1323. handles, only future ones.
  1324.  
  1325. Attempting to set or get the value of an undefined attribute is fatal,
  1326. except for private driver specific attributes (which all have names
  1327. starting with a lowercase letter).
  1328.  
  1329. =over 4
  1330.  
  1331. =item B<Warn> (inherited)
  1332.  
  1333.   $h->{Warn}
  1334.  
  1335. Enables useful warnings for certain bad practices. Enabled by default. Some
  1336. emulation layers, especially those for perl4 interfaces, disable warnings.
  1337.  
  1338. =item B<CompatMode> (inherited)
  1339.  
  1340.   $h->{CompatMode}
  1341.  
  1342. Used by emulation layers (such as Oraperl) to enable compatible behaviour
  1343. in the underlying driver (e.g., DBD::Oracle) for this handle. Not normally
  1344. set by application code.
  1345.  
  1346. =item B<InactiveDestroy>
  1347.  
  1348.   $h->{InactiveDestroy}
  1349.  
  1350. This attribute can be used to disable the effect of destroying a handle
  1351. (which would normally close a prepared statement or disconnect from the
  1352. database etc). It is specifically designed for use in unix applications
  1353. which 'fork' child processes. Either the parent or the child process,
  1354. but not both, should set InactiveDestroy on all their handles.
  1355.  
  1356. =item B<PrintError> (inherited)
  1357.  
  1358.   $h->{PrintError}
  1359.  
  1360. This attribute can be used to force errors to generate warnings (using
  1361. warn) in addition to returning error codes in the normal way.  When set
  1362. on, any method which results in an error occuring ($DBI::err being set
  1363. true) will cause the DBI to effectively do warn("$DBI::errstr").  Note
  1364. that the contents of the warning are currently just $DBI::errstr but
  1365. that may change and should not be relied upon.
  1366.  
  1367. By default DBI->connect sets PrintError on (except for old-style connect
  1368. usage, see connect for more details).
  1369.  
  1370. If desired, the warnings can be caught and processed using a $SIG{__WARN__}
  1371. handler or modules like CGI::ErrorWrap.
  1372.  
  1373. =item B<RaiseError> (inherited)
  1374.  
  1375.   $h->{RaiseError}
  1376.  
  1377. This attribute can be used to force errors to raise exceptions rather
  1378. than simply return error codes in the normal way. It defaults to off.
  1379. When set on, any method which results in an error occuring ($DBI::err
  1380. being set true) will cause the DBI to effectively do croak("$DBI::errstr").
  1381.  
  1382. If PrintError is also on then the PrintError is done before the
  1383. RaiseError unless no __DIE__ handler has been defined, in which case
  1384. PrintError is skipped since the croak will print the message.
  1385.  
  1386. Note that the contents of $@ are currently just $DBI::errstr but that
  1387. may change and should not be relied upon.
  1388.  
  1389. =item B<ChopBlanks> (inherited)
  1390.  
  1391.   $h->{ChopBlanks}
  1392.  
  1393. This attribute can be used to control the trimming of trailing space
  1394. characters from fixed width char fields. No other field types are
  1395. affected.
  1396.  
  1397. The default is false (it is possible that that may change).
  1398. Applications that need specific behaviour should set the attribute as
  1399. needed. Emulation interfaces should set the attribute to match the
  1400. behaviour of the interface they are emulating.
  1401.  
  1402. Drivers are not required to support this attribute but any driver which
  1403. does not must arrange to return undef as the attribute value.
  1404.  
  1405. =item B<LongReadLen> (inherited)
  1406.  
  1407.   $h->{LongReadLen}
  1408.  
  1409. This attribute may be used to control the maximum length of 'long' (or
  1410. 'blob') fields which the driver will read from the database
  1411. automatically when it fetches each row of data.
  1412.  
  1413. The default is typically 80 bytes but may vary between drivers. Most
  1414. applications using long fields will set this value to slightly larger
  1415. than the longest long field value which will be fetched.
  1416.  
  1417. See L</LongTruncOk> about truncation behaviour.
  1418.  
  1419. =item B<LongTruncOk> (inherited)
  1420.  
  1421.   $h->{LongTruncOk}
  1422.  
  1423. This attribute may be used to control the effect of fetching a long
  1424. field value which has been truncated (typically because it's longer
  1425. than the value of the LongReadLen attribute).
  1426.  
  1427. By default LongTruncOk is false and fetching a truncated long value
  1428. will cause the fetch to fail. (Applications should always take care to
  1429. check for errors after a fetch loop in case a database error, such as a
  1430. divide by zero or long field truncation, caused the fetch to terminate
  1431. prematurely.)
  1432.  
  1433. =back
  1434.  
  1435.  
  1436. =head1 DBI DATABASE HANDLE OBJECTS
  1437.  
  1438. =head2 Database Handle Methods
  1439.  
  1440. =over 4
  1441.  
  1442. =item B<prepare>
  1443.  
  1444.   $sth = $dbh->prepare($statement)           || die $dbh->errstr;
  1445.   $sth = $dbh->prepare($statement, \%attr)   || die $dbh->errstr;
  1446.  
  1447. Prepare a single statement for execution by the database engine and
  1448. return a  reference to a statement handle object which can be used to
  1449. get attributes of the statement and invoke the L</execute> method.
  1450.  
  1451. Note that prepare should never execute a statement, even if it is not a
  1452. select statement, it only prepares it for execution. Having said that,
  1453. some drivers, notably Oracle, will execute data definition statements
  1454. such as create/drop table when they are prepared. In practice this is
  1455. rarely a problem.
  1456.  
  1457. Drivers for engines which don't have the concept of preparing a
  1458. statement will typically just store the statement in the returned
  1459. handle and process it when $sth->execute is called. Such drivers are
  1460. likely to be unable to give much useful information about the
  1461. statement, such as $sth->{NUM_OF_FIELDS}, until after $sth->execute
  1462. has been called. Portable applications should take this into account.
  1463.  
  1464.  
  1465. =item B<do>
  1466.  
  1467.   $rc  = $dbh->do($statement)           || die $dbh->errstr;
  1468.   $rc  = $dbh->do($statement, \%attr)   || die $dbh->errstr;
  1469.   $rv  = $dbh->do($statement, \%attr, @bind_values) || ...
  1470.  
  1471. Prepare and execute a statement. Returns the number of rows affected
  1472. (-1 if not known or not available) or undef on error.
  1473.  
  1474. This method is typically most useful for non-select statements which
  1475. either cannot be prepared in advance (due to a limitation in the
  1476. driver) or which do not need to be executed repeatedly.
  1477.  
  1478. The default do method is logically similar to:
  1479.  
  1480.   sub do {
  1481.       my($dbh, $statement, $attr, @bind_values) = @_;
  1482.       my $sth = $dbh->prepare($statement) or return undef;
  1483.       $sth->execute(@bind_values) or return undef;
  1484.       my $rows = $sth->rows;
  1485.       ($rows == 0) ? "0E0" : $rows;
  1486.   }
  1487.  
  1488. Example:
  1489.  
  1490.   my $rows_deleted = $dbh->do(q{
  1491.       delete from table
  1492.       where status = 'DONE'
  1493.   }) || die $dbh->errstr;
  1494.  
  1495. Using placeholders and C<@bind_values> with the C<do> method can be
  1496. useful because it avoids the need to correctly quote any variables
  1497. in the $statement.
  1498.  
  1499. =item B<commit>
  1500.  
  1501.   $rc  = $dbh->commit     || die $dbh->errstr;
  1502.  
  1503. Commit (make permanent) the most recent series of database changes
  1504. if the database supports transactions.
  1505.  
  1506. If the database supports transactions and AutoCommit is on then the
  1507. commit should issue a "commit ineffective with AutoCommit" warning.
  1508.  
  1509. See also L</Transactions>.
  1510.  
  1511. =item B<rollback>
  1512.  
  1513.   $rc  = $dbh->rollback   || die $dbh->errstr;
  1514.  
  1515. Roll-back (undo) the most recent series of uncommitted database
  1516. changes if the database supports transactions.
  1517.  
  1518. If the database supports transactions and AutoCommit is on then the
  1519. rollback should issue a "rollback ineffective with AutoCommit" warning.
  1520.  
  1521. See also L</Transactions>.
  1522.  
  1523.  
  1524. =item B<disconnect>
  1525.  
  1526.   $rc  = $dbh->disconnect   || warn $dbh->errstr;
  1527.  
  1528. Disconnects the database from the database handle. Typically only used
  1529. before exiting the program. The handle is of little use after disconnecting.
  1530.  
  1531. The transaction behaviour of disconnect is undefined.  Some database
  1532. systems (such as Oracle and Ingres) will automatically commit any
  1533. outstanding changes, but others (such as Informix) will rollback any
  1534. outstanding changes.  Applications should explicitly call commit or
  1535. rollback before calling disconnect.
  1536.  
  1537. The database is automatically disconnected (by the DESTROY method) if
  1538. still connected when there are no longer any references to the handle.
  1539. The DESTROY method for each driver should explicitly call rollback to
  1540. undo any uncommitted changes. This is I<vital> behaviour to ensure that
  1541. incomplete transactions don't get committed simply because Perl calls
  1542. DESTROY on every object before exiting.
  1543.  
  1544.  
  1545. =item B<ping>
  1546.  
  1547.   $rc = $dbh->ping;
  1548.  
  1549. Attempts to determine, in a reasonably efficient way, if the database
  1550. server is still running and the connection to it is still working.
  1551. The default implementation currently always returns true without
  1552. actually doing anything. Individual drivers should implement this
  1553. function in the most suitable manner for their database engine.
  1554.  
  1555. Very few applications would have any use for this method. See the
  1556. specialist Apache::DBI module for one example usage.
  1557.  
  1558.  
  1559. =item B<quote>
  1560.  
  1561.   $sql = $dbh->quote($string);
  1562.  
  1563. Quote a string literal for use in an SQL statement by I<escaping> any
  1564. special characters (such as quotation marks) contained within the
  1565. string and adding the required type of outer quotation marks.
  1566.  
  1567.   $sql = sprintf "select foo from bar where baz = %s",
  1568.                 $dbh->quote("Don't\n");
  1569.  
  1570. For most database types quote would return C<'Don''t'> (including the
  1571. outer quotation marks).
  1572.  
  1573. An undefined $string value will be returned as NULL (without quotation
  1574. marks).
  1575.  
  1576. =back
  1577.  
  1578.  
  1579. =head2 Database Handle Attributes
  1580.  
  1581. =over 4
  1582.  
  1583. =item B<AutoCommit>
  1584.  
  1585.   $dbh->{AutoCommit}     ($)
  1586.  
  1587. If true then database changes cannot be rolledback (undone).  If false
  1588. then database changes automatically occur within a 'transaction' which
  1589. must either be committed or rolled-back using the commit or rollback
  1590. methods.
  1591.  
  1592. Drivers should always default to AutoCommit mode. (An unfortunate
  1593. choice forced on the DBI by ODBC and JDBC conventions.)
  1594.  
  1595. Attempting to set AutoCommit to an unsupported value is a fatal error.
  1596. This is an important feature of the DBI. Applications which need
  1597. full transaction behaviour can set $dbh->{AutoCommit}=0 (or via
  1598. connect) without having to check the value was assigned okay.
  1599.  
  1600. For the purposes of this description we can divide databases into three
  1601. categories:
  1602.  
  1603.   Database which don't support transactions at all.
  1604.   Database in which a transaction is always active.
  1605.   Database in which a transaction must be explicitly started ('BEGIN WORK').
  1606.  
  1607. B<* Database which don't support transactions at all>
  1608.  
  1609. For these databases attempting to turn AutoCommit off is a fatal error.
  1610. Commit and rollback both issue warnings about being ineffective while
  1611. AutoCommit is in effect.
  1612.  
  1613. B<* Database in which a transaction is always active>
  1614.  
  1615. These are typically mainstream commercial relational databases with
  1616. 'ANSI standandard' transaction behaviour.
  1617.  
  1618. If AutoCommit is off then changes to the database won't have any
  1619. lasting effect unless L</commit> is called (but see also
  1620. L</disconnect>). If L</rollback> is called then any changes since the
  1621. last commit are undone.
  1622.  
  1623. If AutoCommit is on then the effect is the same as if the DBI were to
  1624. have called commit automatically after every successful database
  1625. operation. In other words, calling commit or rollback explicitly while
  1626. AutoCommit is on would be ineffective because the changes would
  1627. have already been commited.
  1628.  
  1629. Changing AutoCommit from off to on may issue a L</commit> in some drivers.
  1630.  
  1631. Changing AutoCommit from on to off should have no immediate effect.
  1632.  
  1633. For databases which don't support a specific auto-commit mode, the
  1634. driver has to commit each statement automatically using an explicit
  1635. COMMIT after it completes successfully (and roll it back using an
  1636. explicit ROLLBACK if it fails).  The error information reported to the
  1637. application will correspond to the statement which was executed, unless
  1638. it succeeded and the commit or rollback failed.
  1639.  
  1640. B<* Database in which a transaction must be explicitly started>
  1641.  
  1642. For these database the intention is to have them act like databases in
  1643. which a transaction is always active (as described above).
  1644.  
  1645. To do this the DBI driver will automatically begin a transaction when
  1646. AutoCommit is turned off (from the default on state) and will
  1647. automatically begin another transaction after a L</commit> or L</rollback>.
  1648.  
  1649. In this way, the application does not have to treat these databases as a
  1650. special case.
  1651.  
  1652. =back
  1653.  
  1654.  
  1655. =head1 DBI STATEMENT HANDLE OBJECTS
  1656.  
  1657. =head2 Statement Handle Methods
  1658.  
  1659. =over 4
  1660.  
  1661. =item B<bind_param>
  1662.  
  1663.   $rc = $sth->bind_param($param_num, $bind_value)  || die $sth->errstr;
  1664.   $rv = $sth->bind_param($param_num, $bind_value, \%attr)     || ...
  1665.   $rv = $sth->bind_param($param_num, $bind_value, $bind_type) || ...
  1666.  
  1667. The bind_param method can be used to I<bind> (assign/associate) a value
  1668. with a I<placeholder> embedded in the prepared statement. Placeholders
  1669. are indicated with question mark character (C<?>). For example:
  1670.  
  1671.   $dbh->{RaiseError} = 1;        # save having to check each method call
  1672.   $sth = $dbh->prepare("select name, age from people where name like ?");
  1673.   $sth->bind_param(1, "John%");  # placeholders are numbered from 1
  1674.   $sth->execute;
  1675.   DBI::dump_results($sth);
  1676.  
  1677. Note that the C<?> is not enclosed in quotation marks even when the
  1678. placeholder represents a string.  Some drivers also allow C<:1>, C<:2>
  1679. etc and C<:name> style placeholders in addition to C<?> but their use
  1680. is not portable.
  1681.  
  1682. Sadly, placeholders can only represent single scalar values, so this
  1683. statement, for example, won't work as expected for more than one value:
  1684.  
  1685.   "select name, age from people where name in (?)"    # wrong
  1686.  
  1687. The C<\%attr> parameter can be used to specify the data type the
  1688. placeholder should have. Typically the driver is only interested in
  1689. knowing if the placeholder should be bound as a number or a string.
  1690.  
  1691.   $sth->bind_param(1, $value, { TYPE => SQL_INTEGER });
  1692.  
  1693. As a short-cut for this common case, the data type can be passed
  1694. directly inplace of the attr hash reference. This example is
  1695. equivalent to the one above:
  1696.  
  1697.   $sth->bind_param(1, $value, SQL_INTEGER);
  1698.  
  1699. Perl only has string and number scalar data types. All database types
  1700. that aren't numbers are bound as strings and must be in a format the
  1701. database will understand.
  1702.  
  1703. Undefined values or C<undef> can be used to indicate null values.
  1704.  
  1705.  
  1706. =item B<execute>
  1707.  
  1708.   $rv = $sth->execute                || die $sth->errstr;
  1709.   $rv = $sth->execute(@bind_values)  || die $sth->errstr;
  1710.  
  1711. Perform whatever processing is necessary to execute the prepared
  1712. statement.  An undef is returned if an error occurs, a successful
  1713. execute always returns true (see below). It is always important to
  1714. check the return status of execute (and most other DBI methods).
  1715.  
  1716. For a non-select statement execute returns the number of rows affected
  1717. (if known). Zero rows is returned as "0E0" which Perl will treat
  1718. as 0 but will regard as true. If the number of rows affected is not
  1719. known then execute returns -1.
  1720.  
  1721. For select statements execute simply 'starts' the query within the
  1722. Engine. Use one of the fetch methods to retreive the data after
  1723. calling execute.  Note that the execute method does I<not> return the
  1724. number of rows that will be returned by the query (because most Engines
  1725. can't tell in advance).
  1726.  
  1727. If any arguments are given then execute will effectively call
  1728. L</bind_param> for each value before executing the statement.
  1729. Values bound in this way are treated as SQL_VARCHAR types.
  1730.  
  1731.  
  1732. =item B<fetchrow_arrayref>
  1733.  
  1734.   $ary_ref = $sth->fetchrow_arrayref;
  1735.   $ary_ref = $sth->fetch;    # alias
  1736.  
  1737. Fetches the next row of data and returns a reference to an array
  1738. holding the field values. If there are no more rows fetchrow_arrayref
  1739. returns undef.  Null values are returned as undef. This is the fastest
  1740. way to fetch data, particularly if used with $sth->bind_columns.
  1741.  
  1742. =item B<fetchrow_array>
  1743.  
  1744.  @ary = $sth->fetchrow_array;
  1745.  
  1746. An alternative to C<fetchrow_arrayref>. Fetches the next row of data
  1747. and returns it as an array holding the field values. If there are no
  1748. more rows fetchrow_array returns an empty list.  Null values are
  1749. returned as undef.
  1750.  
  1751. =item B<fetchrow_hashref>
  1752.  
  1753.  $hash_ref = $sth->fetchrow_hashref;
  1754.  
  1755. An alternative to C<fetchrow_arrayref>. Fetches the next row of data
  1756. and returns it as a reference to a hash containing field name and field
  1757. value pairs.  Null values are returned as undef.  If there are no more
  1758. rows fetchhash returns undef.
  1759.  
  1760. The keys of the hash are the same names returned by $sth->{NAME}. If
  1761. more than one field has the same name there will only be one entry in
  1762. the returned hash.
  1763.  
  1764. Because of the extra work fetchrow_hashref and perl have to perform it
  1765. is not as efficient as fetchrow_arrayref or fetchrow_array and is not
  1766. recommended where performance is very important. Currently a new hash
  1767. reference is returned for each row.  This is likely to change in the
  1768. future so don't rely on it.
  1769.  
  1770.  
  1771. =item B<fetchall_arrayref>
  1772.  
  1773.   $tbl_ary_ref = $sth->fetchall_arrayref;
  1774.  
  1775. The C<fetchall_arrayref> method can be used to fetch all the data to be
  1776. returned from a prepared statement. It returns a reference to an array
  1777. which contains one array reference per row (as returned by
  1778. C<fetchrow_arrayref>).
  1779.  
  1780. If there are no rows to return, fetchall_arrayref returns a reference to an
  1781. empty array.
  1782.  
  1783.  
  1784. =item B<finish>
  1785.  
  1786.   $rc  = $sth->finish;
  1787.  
  1788. Indicates that no more data will be fetched from this statement before
  1789. it is either prepared again or destroyed.  It is helpful to call this
  1790. method where appropriate in order to allow the server to free off any
  1791. internal resources (such as read locks) currently being held. It does
  1792. not affect the transaction status of the session in any way.
  1793.  
  1794.  
  1795. =item B<rows>
  1796.  
  1797.   $rv = $sth->rows;
  1798.  
  1799. Returns the number of rows affected by the last database altering
  1800. command, or -1 if not known or not available.
  1801.  
  1802. Generally you can only rely on a row count after a do() or non-select
  1803. execute().  Some drivers only offer a row count after executing some
  1804. specific operations (e.g., update and delete).
  1805.  
  1806. It is generally not possible to know how many rows will be returned from
  1807. an arbitrary select statement except by fetching and counting them all.
  1808. Also note that some drivers, such as DBD::Oracle, implement read-ahead
  1809. row caches for select statements which means that the row count may
  1810. appear to be incorrect while there are still more records to fetch.
  1811.  
  1812.  
  1813. =item B<bind_col>
  1814.  
  1815.   $rc = $sth->bind_col($column_number, \$var_to_bind);
  1816.   $rc = $sth->bind_col($column_number, \$var_to_bind, \%attr);
  1817.  
  1818. Binds a column (field) of a select statement to a perl variable.
  1819. Whenever a row is fetched from the database the corresponding perl
  1820. variable is automatically updated. There is no need to fetch and assign
  1821. the values manually. This makes using bound variables very efficient.
  1822. See bind_columns below for an example.  Note that column numbers count
  1823. up from 1.
  1824.  
  1825. The binding is performed at a very low level using perl aliasing so
  1826. there is no extra copying taking place. So long as the driver uses the
  1827. correct internal DBI call to get the array the fetch function returns,
  1828. it will automatically support column binding.
  1829.  
  1830. =item B<bind_columns>
  1831.  
  1832.   $rc = $sth->bind_columns(\%attr, @list_of_refs_to_vars_to_bind);
  1833.  
  1834. e.g.
  1835.  
  1836.   $sth->prepare(q{ select region, sales from sales_by_region }) or die ...;
  1837.   my($region, $sales);
  1838.   # Bind perl variables to columns.
  1839.   $rv = $sth->bind_columns(undef, \$region, \$sales);
  1840.   # you can also use perl's \(...) syntax (see perlref docs):
  1841.   #     $sth->bind_columns(undef, \($region, $sales));
  1842.   # Column binding is the most eficient way to fetch data
  1843.   while($sth->fetch) {
  1844.       print "$region: $sales\n";
  1845.   }
  1846.  
  1847. Calls bind_col for each column of the select statement. bind_columns will
  1848. croak if the number of references does not match the number of fields.
  1849.  
  1850. =back
  1851.  
  1852.  
  1853. =head2 Statement Handle Attributes
  1854.  
  1855. Note that some drivers cannot provide valid values for some or all of
  1856. these attributes until after $sth->execute has been called.
  1857.  
  1858. =over 4
  1859.  
  1860. =item B<NUM_OF_FIELDS>
  1861.  
  1862.   $sth->{NUM_OF_FIELDS}  ($)
  1863.  
  1864. Number of fields (columns) the prepared statement will return. Non-select
  1865. statements will have NUM_OF_FIELDS == 0.
  1866.  
  1867.  
  1868. =item B<NUM_OF_PARAMS>
  1869.  
  1870.   $sth->{NUM_OF_PARAMS}  ($)
  1871.  
  1872. The number of parameters (placeholders) in the prepared statement.
  1873. See SUBSTITUTION VARIABLES below for more details.
  1874.  
  1875.  
  1876. =item B<NAME>
  1877.  
  1878.   $sth->{NAME}           (\@)
  1879.  
  1880. Returns a I<reference> to an array of field names for each column. The
  1881. names may contain spaces but should not be truncated or have any
  1882. trailing space.
  1883.  
  1884.   print "First column name: $sth->{NAME}->[0]\n";
  1885.  
  1886.  
  1887. =item B<NULLABLE>
  1888.  
  1889.   $sth->{NULLABLE}       (\@)
  1890.  
  1891. Returns a I<reference> to an array indicating the possibility of each
  1892. column returning a null.
  1893.  
  1894.   print "First column may return NULL\n" if $sth->{NULLABLE}->[0];
  1895.  
  1896.  
  1897. =item B<CursorName>
  1898.  
  1899.   $sth->{CursorName}     ($)
  1900.  
  1901. Returns the name of the cursor associated with the statement handle if
  1902. available. If not available or the database driver does not support the
  1903. C<"where current of ..."> SQL syntax then it returns undef.
  1904.  
  1905.  
  1906. =back
  1907.  
  1908.  
  1909. =head1 TRANSACTIONS
  1910.  
  1911. Transactions are a fundamental part of any quality database system. They
  1912. protect against errors and database corruption by ensuring that changes
  1913. to the database take place in atomic (indivisible, all-or-nothing) units.
  1914.  
  1915. See L</AutoCommit> for details of using AutoCommit with various types of
  1916. database.
  1917.  
  1918. =head2 Robust Applications
  1919.  
  1920. This section applies to databases which support transactions and where
  1921. AutoCommit is off.
  1922.  
  1923. The recommended way to implement robust transactions in Perl
  1924. applications is to make use of S<C<eval { ... }>> (which is very fast,
  1925. unlike S<C<eval "...">>).
  1926.  
  1927.   eval {
  1928.       foo(...)
  1929.   };
  1930.   if ($@) {
  1931.       $dbh->rollback;
  1932.       # add other application on-error-clean-up code here
  1933.   }
  1934.   else {
  1935.       $dbh->commit;
  1936.   }
  1937.  
  1938. The code in foo(), or any other code executed from within the curly braces,
  1939. can be implemented in this way:
  1940.  
  1941.   $h->method(@args) || die $h->errstr
  1942.  
  1943. or the $h->{RaiseError} attribute can be set on, in which case the DBI
  1944. will automatically croak() on error so you don't have to test the
  1945. return value of each method call. See L</RaiseError> for more details.
  1946.  
  1947. A major advantage of the eval approach is that the transaction will be
  1948. properly rolled back if I<any> code in the inner application croaks or
  1949. dies for any reason.
  1950.  
  1951.  
  1952. =head1 SIMPLE EXAMPLE
  1953.  
  1954.   my $dbh = DBI->connect("dbi:Oracle:$data_source", $user, $password)
  1955.       || die "Can't connect to $data_source: $DBI::errstr";
  1956.  
  1957.   my $sth = $dbh->prepare( q{
  1958.           SELECT name, phone
  1959.           FROM mytelbook
  1960.   }) || die "Can't prepare statement: $DBI::errstr";
  1961.  
  1962.   my $rc = $sth->execute
  1963.       || die "Can't execute statement: $DBI::errstr";
  1964.  
  1965.   print "Query will return $sth->{NUM_FIELDS} fields.\n\n";
  1966.  
  1967.   print "$sth->{NAME}->[0]: $sth->{NAME}->[1]\n";
  1968.   while (($name, $phone) = $sth->fetchrow_array) {
  1969.       print "$name: $phone\n";
  1970.   }
  1971.   # check for problems which may have terminated the fetch early
  1972.   warn $DBI::errstr if $DBI::err;
  1973.  
  1974.   $sth->finish;
  1975.  
  1976.  
  1977. =head1 DEBUGGING
  1978.  
  1979. In addition to the L</trace> method you can enable the same trace
  1980. information by setting the DBI_TRACE environment variable before
  1981. starting perl.
  1982.  
  1983. On unix-like systems using a bourne-like shell you can do this easily
  1984. for a single command:
  1985.  
  1986.   DBI_TRACE=2 perl your_test_script.pl
  1987.  
  1988. If DBI_TRACE is set to a non-numeric value then it is assumed to
  1989. be a file name and the trace level will be set to 2 with all trace
  1990. output will be appended to that file.
  1991.  
  1992. See also the L</trace> method.
  1993.  
  1994.  
  1995. =head1 WARNINGS
  1996.  
  1997. The DBI is I<alpha> software. It is I<only> 'alpha' because the
  1998. interface (api) is not finalised. The alpha status does not reflect
  1999. code quality.
  2000.  
  2001. =head1 SEE ALSO
  2002.  
  2003. =head2 Database Documentation
  2004.  
  2005. SQL Language Reference Manual.
  2006.  
  2007. =head2 Books and Journals
  2008.  
  2009.  Programming Perl 2nd Ed. by Larry Wall, Tom Christiansen & Randal Schwartz.
  2010.  Learning Perl by Randal Schwartz.
  2011.  
  2012.  Dr Dobb's Journal, November 1996.
  2013.  The Perl Journal, April 1997.
  2014.  
  2015. =head2 Manual Pages
  2016.  
  2017. L<perl(1)>, L<perlmod(1)>, L<perlbook(1)>
  2018.  
  2019. =head2 Mailing List
  2020.  
  2021. The dbi-users mailing list is the primary means of communication among
  2022. uses of the DBI and its related modules. Subscribe and unsubscribe via:
  2023.  
  2024.  http://www.fugue.com/dbi
  2025.  
  2026. Mailing list archives are held at:
  2027.  
  2028.  http://www.rosat.mpe-garching.mpg.de/mailing-lists/PerlDB-Interest/
  2029.  http://www.coe.missouri.edu/~faq/lists/dbi.html
  2030.  
  2031. =head2 Assorted Related WWW Links
  2032.  
  2033. The DBI 'Home Page' (not maintained by me):
  2034.  
  2035.  http://www.hermetica.com/technologia/DBI
  2036.  
  2037. Other related links:
  2038.  
  2039.  http://www-ccs.cs.umass.edu/db.html
  2040.  http://www.odmg.org/odmg93/updates_dbarry.html
  2041.  http://www.jcc.com/sql_stnd.html
  2042.  ftp://alpha.gnu.ai.mit.edu/gnu/gnusql-0.7b3.tar.gz
  2043.  
  2044. =head2 FAQ
  2045.  
  2046. Please also read the DBI FAQ which is installed as a DBI::FAQ module so
  2047. you can use perldoc to read it by executing the C<perldoc DBI::FAQ> command.
  2048.  
  2049. =head1 AUTHORS
  2050.  
  2051. DBI by Tim Bunce.  This pod text by Tim Bunce, J. Douglas Dunlop,
  2052. Jonathan Leffler and others.  Perl by Larry Wall and the
  2053. perl5-porters.
  2054.  
  2055. =head1 COPYRIGHT
  2056.  
  2057. The DBI module is Copyright (c) 1995,1996,1997 Tim Bunce. England.
  2058. The DBI module is free software; you can redistribute it and/or
  2059. modify it under the same terms as Perl itself.
  2060.  
  2061. This document is Copyright (c) 1997 by Tim Bunce. All rights reserved.
  2062. Permission to distribute this document, in full or part, via email,
  2063. usenet or ftp/http archives or printed copy is granted providing that
  2064. no charges are involved, reasonable attempt is made to use the most
  2065. current version, and all credits and copyright notices are retained.
  2066. Requests for other distribution rights, including incorporation in
  2067. commercial products, such as books, magazine articles, or CD-ROMs
  2068. should be made to Tim.Bunce@ig.co.uk (please I<don't> use this mail
  2069. address for other DBI related mail - use the dbi-users mailing list).
  2070.  
  2071. =head1 ACKNOWLEDGEMENTS
  2072.  
  2073. I would like to acknowledge the valuable contributions of the many
  2074. people I have worked with on the DBI project, especially in the early
  2075. years (1992-1994): Kevin Stock, Buzz Moschetti, Kurt Andersen, Ted Lemon,
  2076. William Hails, Garth Kennedy, Michael Peppler, Neil S. Briscoe,
  2077. David J. Hughes, Jeff Stander, Forrest D Whitcher, Larry Wall, Jeff Fried,
  2078. Roy Johnson, Paul Hudson, Georg Rehfeld, Steve Sizemore, Ron Pool,
  2079. Jon Meek, Tom Christiansen, Steve Baumgarten, Randal Schwartz,
  2080. and a whole lot more.
  2081.  
  2082. =head1 SUPPORT / WARRANTY
  2083.  
  2084. The DBI is free software. IT COMES WITHOUT WARRANTY OF ANY KIND.
  2085.  
  2086. Commercial support agreements for Perl and the DBI, DBD::Oracle and
  2087. Oraperl modules can be arranged via The Perl Clinic. See
  2088. http://www.perl.co.uk/tpc for more details.
  2089.  
  2090. =head1 OUTSTANDING ISSUES TO DO
  2091.  
  2092.     data types (ISO type numbers and type name conversions)
  2093.     error handling
  2094.     data dictionary methods
  2095.     test harness support methods
  2096.     portability
  2097.     blob_read
  2098.     etc
  2099.  
  2100. =head1 FREQUENTLY ASKED QUESTIONS
  2101.  
  2102. See the DBI FAQ for a more comprehensive list of FAQs. Use the
  2103. C<perldoc DBI::FAQ> command to read it.
  2104.  
  2105. =head2 Why doesn't my CGI script work right?
  2106.  
  2107. Read the information in the references below.  Please do I<not> post
  2108. CGI related questions to the dbi-users mailing list (or to me).
  2109.  
  2110.  http://www.perl.com/perl/faq/idiots-guide.html
  2111.  http://www3.pair.com/webthing/docs/cgi/faqs/cgifaq.shtml
  2112.  http://www.perl.com/perl/faq/perl-cgi-faq.html
  2113.  http://www-genome.wi.mit.edu/WWW/faqs/www-security-faq.html
  2114.  http://www.boutell.com/faq/
  2115.  http://www.perl.com/perl/faq/
  2116.  
  2117. General problems and good ideas:
  2118.  
  2119.  Use the CGI::ErrorWrap module.
  2120.  Remember that many env vars won't be set for CGI scripts
  2121.  
  2122. =head2 How can I maintain a WWW connection to a database?
  2123.  
  2124. For information on the Apache httpd server and the mod_perl module see
  2125. http://www.osf.org/~dougm/apache
  2126.  
  2127. =head2 A driver build fails because it can't find DBIXS.h
  2128.  
  2129. The installed location of the DBIXS.h file changed with 0.77 (it was
  2130. being installed into the 'wrong' directory but that's where driver
  2131. developers came to expect it to be). The first thing to do is check to
  2132. see if you have the latest version of your driver. Driver authors will
  2133. be releasing new versions which use the new location. If you have the
  2134. latest then ask for a new release. You can edit the Makefile.PL file
  2135. yourself. Change the part which reads C<"-I.../DBI"> so it reads
  2136. C<"-I.../auto/DBI"> (where ... is a string of non-space characters).
  2137.  
  2138. =head2 Has the DBI and DBD::Foo been ported to NT / Win32?
  2139.  
  2140. The latest version of the DBI and, at least, the DBD::Oracle module
  2141. will build - without changes - on NT/Win32 I<if> your are using the
  2142. standard Perl 5.004 and I<not> the ActiveWare port.
  2143.  
  2144. Jeffrey Urlwin <jurlwin@access.digex.net> (or <jurlwin@hq.caci.com>) is
  2145. helping me with the port (actually he's doing it and I'm integrating
  2146. the changes :-).
  2147.  
  2148. =head2 What about ODBC?
  2149.  
  2150. See the statement and following notes in the DBI README file.
  2151.  
  2152.  
  2153. =head1 KNOWN DRIVER MODULES
  2154.  
  2155. =over 4
  2156.  
  2157. =item Oracle - DBD::Oracle
  2158.  
  2159.  Author:  Tim Bunce
  2160.  Email:   dbi-users@fugue.com
  2161.  
  2162. =item Ingres - DBD::Ingres
  2163.  
  2164.  Author:  Henrik Tougaard
  2165.  Email:   ht@datani.dk,  dbi-users@fugue.com
  2166.  
  2167. =item mSQL - DBD::mSQL
  2168.  
  2169. =item DB2 - DBD::DB2
  2170.  
  2171. =item Empress - DBD::Empress
  2172.  
  2173. =item Informix - DBD::Informix
  2174.  
  2175.  Author:  Jonathan Leffler
  2176.  Email:   johnl@informix.com, dbi-users@fugue.com
  2177.  
  2178. =item Solid - DBD::Solid
  2179.  
  2180.  Author:  Thomas Wenrich
  2181.  Email:   wenrich@site58.ping.at, dbi-users@fugue.com
  2182.  
  2183. =item Postgres - DBD::Pg
  2184.  
  2185.  Author:  Edmund Mergl
  2186.  Email:   mergl@nadia.s.bawue.de, dbi-users@fugue.com
  2187.  
  2188. =item Fulcrum SearchServer - DBD::Fulcrum
  2189.  
  2190.  Author:  Davide Migliavacca
  2191.  Email:   davide.migliavacca@inferentia.it
  2192.  
  2193. =back
  2194.  
  2195. =head1 OTHER RELATED WORK AND PERL MODULES
  2196.  
  2197. =over 4
  2198.  
  2199. =item Apache::DBI by E.Mergl@bawue.de
  2200.  
  2201. To be used with the Apache daemon together with an embedded perl
  2202. interpreter like mod_perl. Establishes a database connection which
  2203. remains open for the lifetime of the http daemon. This way the CGI
  2204. connect and disconnect for every database access becomes superfluous.
  2205.  
  2206. =item JDBC Server by Stuart 'Zen' Bishop <zen@bf.rmit.edu.au>
  2207.  
  2208. The server is written in Perl. The client classes that talk to it are 
  2209. of course in Java. Thus, a Java applet or application will be able to 
  2210. comunicate via the JDBC API with any database that has a DBI driver installed.
  2211. The URL used is in the form jdbc:dbi://host.domain.etc:999/Driver/DBName.
  2212. It seems to be very similar to some commercial products, such as jdbcKona.
  2213.  
  2214. =item Remote Proxy DBD support
  2215.  
  2216.   Carl Declerck <carl@miskatonic.inbe.net>
  2217.   Terry Greenlaw <z50816@mip.mar.lmco.com>
  2218.  
  2219. Carl is developing a generic proxy object module which could form the basis
  2220. of a DBD::Proxy driver in the future. Terry is doing something similar.
  2221.  
  2222. =item SQL Parser - Stephen Zander <stephen.zander@mckesson.com>
  2223.  
  2224. Based on the O'Reilly lex/yacc book examples and byacc.
  2225.  
  2226. =back
  2227.  
  2228. =cut
  2229.