# $Id: DBI.pm,v 11.43 2004/02/01 11:16:16 timbo Exp $ # vim: ts=8:sw=4 # # Copyright (c) 1994-2004 Tim Bunce Ireland # # See COPYRIGHT section in pod text below for usage and distribution rights. # require 5.006_00; BEGIN { $DBI::VERSION = "1.42"; # ==> ALSO update the version in the pod text below! } =head1 NAME DBI - Database independent interface for Perl =head1 SYNOPSIS use DBI; @driver_names = DBI->available_drivers; @data_sources = DBI->data_sources($driver_name, \%attr); $dbh = DBI->connect($data_source, $username, $auth, \%attr); $rv = $dbh->do($statement); $rv = $dbh->do($statement, \%attr); $rv = $dbh->do($statement, \%attr, @bind_values); $ary_ref = $dbh->selectall_arrayref($statement); $hash_ref = $dbh->selectall_hashref($statement, $key_field); $ary_ref = $dbh->selectcol_arrayref($statement); $ary_ref = $dbh->selectcol_arrayref($statement, \%attr); @row_ary = $dbh->selectrow_array($statement); $ary_ref = $dbh->selectrow_arrayref($statement); $hash_ref = $dbh->selectrow_hashref($statement); $sth = $dbh->prepare($statement); $sth = $dbh->prepare_cached($statement); $rc = $sth->bind_param($p_num, $bind_value); $rc = $sth->bind_param($p_num, $bind_value, $bind_type); $rc = $sth->bind_param($p_num, $bind_value, \%attr); $rv = $sth->execute; $rv = $sth->execute(@bind_values); $rc = $sth->bind_param_array($p_num, $bind_values, \%attr); $rv = $sth->execute_array(\%attr); $rv = $sth->execute_array(\%attr, @bind_values); $rc = $sth->bind_col($col_num, \$col_variable); $rc = $sth->bind_columns(@list_of_refs_to_vars_to_bind); @row_ary = $sth->fetchrow_array; $ary_ref = $sth->fetchrow_arrayref; $hash_ref = $sth->fetchrow_hashref; $ary_ref = $sth->fetchall_arrayref; $ary_ref = $sth->fetchall_arrayref( $slice, $max_rows ); $hash_ref = $sth->fetchall_hashref( $key_field ); $rv = $sth->rows; $rc = $dbh->begin_work; $rc = $dbh->commit; $rc = $dbh->rollback; $quoted_string = $dbh->quote($string); $rc = $h->err; $str = $h->errstr; $rv = $h->state; $rc = $dbh->disconnect; I =head2 GETTING HELP If you have questions about DBI, or DBD driver modules, you can get help from the I mailing list. You can get help on subscribing and using the list by emailing I. (To help you make the best use of the dbi-users mailing list, and any other lists or forums you may use, I I recommend that you read "How To Ask Questions The Smart Way" by Eric Raymond: L.) The DBI home page at L is always worth a visit and includes an FAQ and links to other resources. Before asking any questions, reread this document, consult the archives and read the DBI FAQ. The archives are listed at the end of this document and on the DBI home page. An FAQ is installed as a L module so you can read it by executing C. However the DBI::FAQ module is currently (2003) outdated relative to the online FAQ on the DBI home page. This document often uses terms like I, I, I. If you're not familar with those terms then it would be a good idea to read at least the following perl manuals first: L, L, L, and L. Please note that Tim Bunce does not maintain the mailing lists or the web page (generous volunteers do that). So please don't send mail directly to him; he just doesn't have the time to answer questions personally. The I mailing list has lots of experienced people who should be able to help you if you need it. If you do email Tim he's very likely to just forward it to the mailing list. =head2 NOTES This is the DBI specification that corresponds to the DBI version 1.42 (C<$Date: 2004/02/01 11:16:16 $>). The DBI is evolving at a steady pace, so it's good to check that you have the latest copy. The significant user-visible changes in each release are documented in the L module so you can read them by executing C. Some DBI changes require changes in the drivers, but the drivers can take some time to catch up. Newer versions of the DBI have added features that may not yet be supported by the drivers you use. Talk to the authors of your drivers if you need a new feature that's not yet supported. Features added after DBI 1.21 (February 2002) are marked in the text with the version number of the DBI release they first appeared in. Extensions to the DBI API often use the C namespace. See L. DBI extension modules can be found at L<"http://search.cpan.org/search?mode=module&query=DBIx%3A%3A">. And all modules related to the DBI can be found at L<"http://search.cpan.org/search?query=DBI&mode=all">. =cut # The POD text continues at the end of the file. package DBI; my $Revision = substr(q$Revision: 11.43 $, 10); use Carp(); use DynaLoader (); use Exporter (); BEGIN { @ISA = qw(Exporter DynaLoader); # Make some utility functions available if asked for @EXPORT = (); # we export nothing by default @EXPORT_OK = qw(%DBI %DBI_methods hash); # also populated by export_ok_tags: %EXPORT_TAGS = ( sql_types => [ qw( SQL_GUID SQL_WLONGVARCHAR SQL_WVARCHAR SQL_WCHAR SQL_BIT SQL_TINYINT SQL_LONGVARBINARY SQL_VARBINARY SQL_BINARY SQL_LONGVARCHAR SQL_UNKNOWN_TYPE SQL_ALL_TYPES SQL_CHAR SQL_NUMERIC SQL_DECIMAL SQL_INTEGER SQL_SMALLINT SQL_FLOAT SQL_REAL SQL_DOUBLE SQL_DATETIME SQL_DATE SQL_INTERVAL SQL_TIME SQL_TIMESTAMP SQL_VARCHAR SQL_BOOLEAN SQL_UDT SQL_UDT_LOCATOR SQL_ROW SQL_REF SQL_BLOB SQL_BLOB_LOCATOR SQL_CLOB SQL_CLOB_LOCATOR SQL_ARRAY SQL_ARRAY_LOCATOR SQL_MULTISET SQL_MULTISET_LOCATOR SQL_TYPE_DATE SQL_TYPE_TIME SQL_TYPE_TIMESTAMP SQL_TYPE_TIME_WITH_TIMEZONE SQL_TYPE_TIMESTAMP_WITH_TIMEZONE SQL_INTERVAL_YEAR SQL_INTERVAL_MONTH SQL_INTERVAL_DAY SQL_INTERVAL_HOUR SQL_INTERVAL_MINUTE SQL_INTERVAL_SECOND SQL_INTERVAL_YEAR_TO_MONTH SQL_INTERVAL_DAY_TO_HOUR SQL_INTERVAL_DAY_TO_MINUTE SQL_INTERVAL_DAY_TO_SECOND SQL_INTERVAL_HOUR_TO_MINUTE SQL_INTERVAL_HOUR_TO_SECOND SQL_INTERVAL_MINUTE_TO_SECOND ) ], sql_cursor_types => [ qw( SQL_CURSOR_FORWARD_ONLY SQL_CURSOR_KEYSET_DRIVEN SQL_CURSOR_DYNAMIC SQL_CURSOR_STATIC SQL_CURSOR_TYPE_DEFAULT ) ], # for ODBC cursor types utils => [ qw( neat neat_list dump_results looks_like_number ) ], profile => [ qw( dbi_profile dbi_profile_merge dbi_time ) ], # notionally "in" DBI::Profile and normally imported from there ); $DBI::dbi_debug = 0; $DBI::neat_maxlen = 400; # If you get an error here like "Can't find loadable object ..." # then you haven't installed the DBI correctly. Read the README # then install it again. if ( $ENV{DBI_PUREPERL} ) { eval { bootstrap DBI } if $ENV{DBI_PUREPERL} == 1; require DBI::PurePerl if $@ or $ENV{DBI_PUREPERL} >= 2; $DBI::PurePerl ||= 0; # just to silence "only used once" warnings } else { bootstrap DBI; } $EXPORT_TAGS{preparse_flags} = [ grep { /^DBIpp_\w\w_/ } keys %{__PACKAGE__."::"} ]; Exporter::export_ok_tags(keys %EXPORT_TAGS); } # Alias some handle methods to also be DBI class methods for (qw(trace_msg set_err parse_trace_flags parse_trace_flag)) { no strict; *$_ = \&{"DBD::_::common::$_"}; } use strict; DBI->trace(split '=', $ENV{DBI_TRACE}, 2) if $ENV{DBI_TRACE}; $DBI::connect_via = "connect"; # check if user wants a persistent database connection ( Apache + mod_perl ) if ($INC{'Apache/DBI.pm'} && $ENV{MOD_PERL}) { $DBI::connect_via = "Apache::DBI::connect"; DBI->trace_msg("DBI connect via $DBI::connect_via in $INC{'Apache/DBI.pm'}\n"); } %DBI::installed_drh = (); # maps driver names to installed driver handles # Setup special DBI dynamic variables. See DBI::var::FETCH for details. # These are dynamically associated with the last handle used. tie $DBI::err, 'DBI::var', '*err'; # special case: referenced via IHA list tie $DBI::state, 'DBI::var', '"state'; # special case: referenced via IHA list tie $DBI::lasth, 'DBI::var', '!lasth'; # special case: return boolean tie $DBI::errstr, 'DBI::var', '&errstr'; # call &errstr in last used pkg tie $DBI::rows, 'DBI::var', '&rows'; # call &rows in last used pkg sub DBI::var::TIESCALAR{ my $var = $_[1]; bless \$var, 'DBI::var'; } sub DBI::var::STORE { Carp::croak("Can't modify \$DBI::${$_[0]} special variable") } { # used to catch DBI->{Attrib} mistake sub DBI::DBI_tie::TIEHASH { bless {} } sub DBI::DBI_tie::STORE { Carp::carp("DBI->{$_[1]} is invalid syntax (you probably want \$h->{$_[1]})");} *DBI::DBI_tie::FETCH = \&DBI::DBI_tie::STORE; } tie %DBI::DBI => 'DBI::DBI_tie'; # --- Driver Specific Prefix Registry --- my $dbd_prefix_registry = { ad_ => { class => 'DBD::AnyData', }, ado_ => { class => 'DBD::ADO', }, best_ => { class => 'DBD::BestWins', }, csv_ => { class => 'DBD::CSV', }, db2_ => { class => 'DBD::DB2', }, dbm_ => { class => 'DBD::DBM', }, dbi_ => { class => 'DBI', }, df_ => { class => 'DBD::DF', }, f_ => { class => 'DBD::File', }, file_ => { class => 'DBD::TextFile', }, ib_ => { class => 'DBD::InterBase', }, ing_ => { class => 'DBD::Ingres', }, ix_ => { class => 'DBD::Informix', }, msql_ => { class => 'DBD::mSQL', }, mysql_ => { class => 'DBD::mysql', }, nullp_ => { class => 'DBD::NullP', }, odbc_ => { class => 'DBD::ODBC', }, ora_ => { class => 'DBD::Oracle', }, pg_ => { class => 'DBD::Pg', }, proxy_ => { class => 'DBD::Proxy', }, rdb_ => { class => 'DBD::RDB', }, sapdb_ => { class => 'DBD::SAP_DB', }, solid_ => { class => 'DBD::Solid', }, sql_ => { class => 'SQL::Statement', }, syb_ => { class => 'DBD::Sybase', }, sponge_ => { class => 'DBD::Sponge', }, tdat_ => { class => 'DBD::Teradata', }, tmpl_ => { class => 'DBD::Template', }, tmplss_ => { class => 'DBD::TemplateSS', }, tuber_ => { class => 'DBD::Tuber', }, uni_ => { class => 'DBD::Unify', }, xbase_ => { class => 'DBD::XBase', }, xl_ => { class => 'DBD::Excel', }, }; sub dump_dbd_registry { require Data::Dumper; print Data::Dumper::Dump($dbd_prefix_registry); } # --- Dynamically create the DBI Standard Interface my $keeperr = { O=>0x0004 }; %DBI::DBI_methods = ( # Define the DBI interface methods per class: common => { # Interface methods common to all DBI handle classes 'DESTROY' => $keeperr, 'CLEAR' => $keeperr, 'EXISTS' => $keeperr, 'FETCH' => { O=>0x0404 }, 'FIRSTKEY' => $keeperr, 'NEXTKEY' => $keeperr, 'STORE' => { O=>0x0418 | 0x4 }, _not_impl => undef, can => { O=>0x0100 }, # special case, see dispatch debug => { U =>[1,2,'[$debug_level]'], O=>0x0004 }, # old name for trace dump_handle => { U =>[1,3,'[$message [, $level]]'], O=>0x0004 }, err => $keeperr, errstr => $keeperr, state => $keeperr, func => { O=>0x0006 }, parse_trace_flag => { U =>[2,2,'$name'], O=>0x0404, T=>8 }, parse_trace_flags => { U =>[2,2,'$flags'], O=>0x0404, T=>8 }, private_data => { U =>[1,1], O=>0x0004 }, set_err => { U =>[3,6,'$err, $errmsg [, $state, $method, $rv]'], O=>0x0010 }, trace => { U =>[1,3,'[$trace_level, [$filename]]'], O=>0x0004 }, trace_msg => { U =>[2,3,'$message_text [, $min_level ]' ], O=>0x0004, T=>8 }, }, dr => { # Database Driver Interface 'connect' => { U =>[1,5,'[$db [,$user [,$passwd [,\%attr]]]]'], H=>3 }, 'connect_cached'=>{U=>[1,5,'[$db [,$user [,$passwd [,\%attr]]]]'], H=>3 }, 'disconnect_all'=>{ U =>[1,1], O=>0x0800 }, data_sources => { U =>[1,2,'[\%attr]' ], O=>0x0800 }, default_user => { U =>[3,4,'$user, $pass [, \%attr]' ] }, }, db => { # Database Session Class Interface data_sources => { U =>[1,2,'[\%attr]' ], O=>0x0200 }, take_imp_data => { U =>[1,1], }, clone => { U =>[1,1,''] }, connected => { O=>0x0100 }, begin_work => { U =>[1,2,'[ \%attr ]'], O=>0x0400 }, commit => { U =>[1,1], O=>0x0480|0x0800 }, rollback => { U =>[1,1], O=>0x0480|0x0800 }, 'do' => { U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'], O=>0x3200 }, last_insert_id => { U =>[3,4,'$table_name, $field_name [, \%attr ]'], O=>0x2100 }, preparse => { }, # XXX prepare => { U =>[2,3,'$statement [, \%attr]'], O=>0x2200 }, prepare_cached => { U =>[2,4,'$statement [, \%attr [, $if_active ] ]'], O=>0x2200 }, selectrow_array => { U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'], O=>0x2000 }, selectrow_arrayref=>{U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'], O=>0x2000 }, selectrow_hashref=>{ U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'], O=>0x2000 }, selectall_arrayref=>{U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'], O=>0x2000 }, selectall_hashref=>{ U =>[3,0,'$statement, $keyfield [, \%attr [, @bind_params ] ]'], O=>0x2000 }, selectcol_arrayref=>{U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'], O=>0x2000 }, ping => { U =>[1,1], O=>0x0404 }, disconnect => { U =>[1,1], O=>0x0400|0x0800 }, quote => { U =>[2,3, '$string [, $data_type ]' ], O=>0x0430 }, quote_identifier=> { U =>[2,6, '$name [, ...] [, \%attr ]' ], O=>0x0430 }, rows => $keeperr, tables => { U =>[1,6,'$catalog, $schema, $table, $type [, \%attr ]' ], O=>0x2200 }, table_info => { U =>[1,6,'$catalog, $schema, $table, $type [, \%attr ]' ], O=>0x2200|0x0800 }, column_info => { U =>[5,6,'$catalog, $schema, $table, $column [, \%attr ]'],O=>0x2200|0x0800 }, primary_key_info=> { U =>[4,5,'$catalog, $schema, $table [, \%attr ]' ], O=>0x2200|0x0800 }, primary_key => { U =>[4,5,'$catalog, $schema, $table [, \%attr ]' ], O=>0x2200 }, foreign_key_info=> { U =>[7,8,'$pk_catalog, $pk_schema, $pk_table, $fk_catalog, $fk_schema, $fk_table [, \%attr ]' ], O=>0x2200|0x0800 }, type_info_all => { U =>[1,1], O=>0x2200|0x0800 }, type_info => { U =>[1,2,'$data_type'], O=>0x2200 }, get_info => { U =>[2,2,'$info_type'], O=>0x2200|0x0800 }, }, st => { # Statement Class Interface bind_col => { U =>[3,4,'$column, \\$var [, \%attr]'] }, bind_columns => { U =>[2,0,'\\$var1 [, \\$var2, ...]'] }, bind_param => { U =>[3,4,'$parameter, $var [, \%attr]'] }, bind_param_inout=> { U =>[4,5,'$parameter, \\$var, $maxlen, [, \%attr]'] }, execute => { U =>[1,0,'[@args]'], O=>0x1040 }, bind_param_array => { U =>[3,4,'$parameter, $var [, \%attr]'] }, bind_param_inout_array => { U =>[4,5,'$parameter, \\@var, $maxlen, [, \%attr]'] }, execute_array => { U =>[2,0,'\\%attribs [, @args]'], O=>0x1040 }, execute_for_fetch => { U =>[2,3,'$fetch_sub [, $tuple_status]'], O=>0x1040 }, fetch => undef, # alias for fetchrow_arrayref fetchrow_arrayref => undef, fetchrow_hashref => undef, fetchrow_array => undef, fetchrow => undef, # old alias for fetchrow_array fetchall_arrayref => { U =>[1,3, '[ $slice [, $max_rows]]'] }, fetchall_hashref => { U =>[2,2,'$key_field'] }, blob_read => { U =>[4,5,'$field, $offset, $len [, \\$buf [, $bufoffset]]'] }, blob_copy_to_file => { U =>[3,3,'$field, $filename_or_handleref'] }, dump_results => { U =>[1,5,'$maxfieldlen, $linesep, $fieldsep, $filehandle'] }, more_results => { U =>[1,1] }, finish => { U =>[1,1] }, cancel => { U =>[1,1], O=>0x0800 }, rows => $keeperr, _get_fbav => undef, _set_fbav => { T=>6 }, }, ); my($class, $method); foreach $class (keys %DBI::DBI_methods){ my %pkgif = %{ $DBI::DBI_methods{$class} }; foreach $method (keys %pkgif){ DBI->_install_method("DBI::${class}::$method", 'DBI.pm', $pkgif{$method}); } } { package DBI::common; @DBI::dr::ISA = ('DBI::common'); @DBI::db::ISA = ('DBI::common'); @DBI::st::ISA = ('DBI::common'); } # End of init code END { return unless defined &DBI::trace_msg; # return unless bootstrap'd ok local ($!,$?); DBI->trace_msg(" -- DBI::END\n", 2); # Let drivers know why we are calling disconnect_all: $DBI::PERL_ENDING = $DBI::PERL_ENDING = 1; # avoid typo warning DBI->disconnect_all() if %DBI::installed_drh; } sub CLONE { my $olddbis = $DBI::_dbistate; _clone_dbis() unless $DBI::PurePerl; # clone the DBIS structure DBI->trace_msg(sprintf "CLONE DBI for new thread %s\n", $DBI::PurePerl ? "" : sprintf("(dbis %x -> %x)",$olddbis, $DBI::_dbistate)); while ( my ($driver, $drh) = each %DBI::installed_drh) { no strict 'refs'; next if defined &{"DBD::${driver}::CLONE"}; warn("$driver has no driver CLONE() function so is unsafe threaded\n"); } %DBI::installed_drh = (); # clear loaded drivers so they have a chance to reinitialize } # --- The DBI->connect Front Door methods sub connect_cached { # For library code using connect_cached() with mod_perl # we redirect those calls to Apache::DBI::connect() as well my ($class, $dsn, $user, $pass, $attr) = @_; ($attr ||= {})->{dbi_connect_method} = ($DBI::connect_via eq "Apache::DBI::connect") ? 'Apache::DBI::connect' : 'connect_cached'; return $class->connect($dsn, $user, $pass, $attr); } sub connect { my $class = shift; my ($dsn, $user, $pass, $attr, $old_driver) = my @orig_args = @_; my $driver; if ($attr and !ref($attr)) { # switch $old_driver<->$attr if called in old style Carp::carp("DBI->connect using 'old-style' syntax is deprecated and will be an error in future versions"); ($old_driver, $attr) = ($attr, $old_driver); } my $connect_meth = $attr->{dbi_connect_method}; $connect_meth ||= $DBI::connect_via; # fallback to default $dsn ||= $ENV{DBI_DSN} || $ENV{DBI_DBNAME} || '' unless $old_driver; if ($DBI::dbi_debug) { local $^W = 0; pop @_ if $connect_meth ne 'connect'; my @args = @_; $args[2] = '****'; # hide password DBI->trace_msg(" -> $class->$connect_meth(".join(", ",@args).")\n"); } Carp::croak('Usage: $class->connect([$dsn [,$user [,$passwd [,\%attr]]]])') if (ref $old_driver or ($attr and not ref $attr) or ref $pass); # extract dbi:driver prefix from $dsn into $1 $dsn =~ s/^dbi:(\w*?)(?:\((.*?)\))?://i or '' =~ /()/; # ensure $1 etc are empty if match fails my $driver_attrib_spec = $2 || ''; # Set $driver. Old style driver, if specified, overrides new dsn style. $driver = $old_driver || $1 || $ENV{DBI_DRIVER} or Carp::croak("Can't connect to data source $dsn, no database driver specified " ."and DBI_DSN env var not set"); if ($ENV{DBI_AUTOPROXY} && $driver ne 'Proxy' && $driver ne 'Sponge' && $driver ne 'Switch') { my $proxy = 'Proxy'; if ($ENV{DBI_AUTOPROXY} =~ s/^dbi:(\w*?)(?:\((.*?)\))?://i) { $proxy = $1; my $attr_spec = $2 || ''; $driver_attrib_spec = ($driver_attrib_spec) ? "$driver_attrib_spec,$attr_spec" : $attr_spec; } $dsn = "$ENV{DBI_AUTOPROXY};dsn=dbi:$driver:$dsn"; $driver = $proxy; DBI->trace_msg(" DBI_AUTOPROXY: dbi:$driver($driver_attrib_spec):$dsn\n"); } my %attributes; # take a copy we can delete from if ($old_driver) { %attributes = %$attr if $attr; } else { # new-style connect so new default semantics %attributes = ( PrintError => 1, AutoCommit => 1, ref $attr ? %$attr : (), # attributes in DSN take precedence over \%attr connect parameter $driver_attrib_spec ? (split /\s*=>?\s*|\s*,\s*/, $driver_attrib_spec, -1) : (), ); } $attr = \%attributes; # now set $attr to refer to our local copy my $drh = $DBI::installed_drh{$driver} || $class->install_driver($driver) or die "panic: $class->install_driver($driver) failed"; # attributes in DSN take precedence over \%attr connect parameter $user = $attr->{Username} if defined $attr->{Username}; $pass = delete $attr->{Password} if defined $attr->{Password}; ($user, $pass) = $drh->default_user($user, $pass, $attr) if !(defined $user && defined $pass); $attr->{Username} = $user; # store username as attribute my $connect_closure = sub { my ($old_dbh, $override_attr) = @_; my $attr = { # copy so we can edit them each time we're called %attributes, # merge in modified attr in %$old_dbh, this should also copy in # the dbi_connect_closure attribute so we can reconnect again. %{ $override_attr || {} }, }; #warn "connect_closure: ".Data::Dumper::Dumper([\%attributes, $override_attr]); my $dbh; unless ($dbh = $drh->$connect_meth($dsn, $user, $pass, $attr)) { $user = '' if !defined $user; $dsn = '' if !defined $dsn; my $errstr = $drh->errstr; $errstr = '(no error string)' if !defined $errstr; my $msg = "$class connect('$dsn','$user',...) failed: $errstr"; DBI->trace_msg(" $msg\n"); # XXX HandleWarn unless ($attr->{HandleError} && $attr->{HandleError}->($msg, $drh, $dbh)) { Carp::croak($msg) if $attr->{RaiseError}; Carp::carp ($msg) if $attr->{PrintError}; } $! = 0; # for the daft people who do DBI->connect(...) || die "$!"; return $dbh; # normally undef, but HandleError could change it } # handle basic RootClass subclassing: my $rebless_class = $attr->{RootClass} || ($class ne 'DBI' ? $class : ''); if ($rebless_class) { no strict 'refs'; if ($attr->{RootClass}) { # explicit attribute (rather than static call) delete $attr->{RootClass}; DBI::_load_class($rebless_class, 0); } unless (@{"$rebless_class\::db::ISA"} && @{"$rebless_class\::st::ISA"}) { Carp::carp("DBI subclasses '$rebless_class\::db' and ::st are not setup, RootClass ignored"); $rebless_class = undef; $class = 'DBI'; } else { $dbh->{RootClass} = $rebless_class; # $dbh->STORE called via plain DBI::db DBI::_set_isa([$rebless_class], 'DBI'); # sets up both '::db' and '::st' DBI::_rebless($dbh, $rebless_class); # appends '::db' } } if (%$attr) { DBI::_rebless_dbtype_subclass($dbh, $rebless_class||$class, delete $attr->{DbTypeSubclass}, $attr) if $attr->{DbTypeSubclass}; my $a; foreach $a (qw(RaiseError PrintError AutoCommit)) { # do these first next unless exists $attr->{$a}; $dbh->{$a} = delete $attr->{$a}; } foreach $a (keys %$attr) { eval { $dbh->{$a} = $attr->{$a} } or $@ && warn $@; } } # if we've been subclassed then let the subclass know that we're connected $dbh->connected($dsn, $user, $pass, $attr) if ref $dbh ne 'DBI::db'; DBI->trace_msg(" <- connect= $dbh\n") if $DBI::dbi_debug; return $dbh; }; my $dbh = &$connect_closure(undef, undef); $dbh->{dbi_connect_closure} = $connect_closure if $dbh; return $dbh; } sub disconnect_all { keys %DBI::installed_drh; # reset iterator while ( my ($name, $drh) = each %DBI::installed_drh ) { $drh->disconnect_all() if ref $drh; } } sub disconnect { # a regular beginners bug Carp::croak("DBI->disconnect is not a DBI method (read the DBI manual)"); } sub install_driver { # croaks on failure my $class = shift; my($driver, $attr) = @_; my $drh; $driver ||= $ENV{DBI_DRIVER} || ''; # allow driver to be specified as a 'dbi:driver:' string $driver = $1 if $driver =~ s/^DBI:(.*?)://i; Carp::croak("usage: $class->install_driver(\$driver [, \%attr])") unless ($driver and @_<=3); # already installed return $drh if $drh = $DBI::installed_drh{$driver}; $class->trace_msg(" -> $class->install_driver($driver" .") for $^O perl=$] pid=$$ ruid=$< euid=$>\n") if $DBI::dbi_debug; # --- load the code my $driver_class = "DBD::$driver"; eval qq{package # hide from PAUSE DBI::_firesafe; # just in case require $driver_class; # load the driver }; if ($@) { my $err = $@; my $advice = ""; if ($err =~ /Can't find loadable object/) { $advice = "Perhaps DBD::$driver was statically linked into a new perl binary." ."\nIn which case you need to use that new perl binary." ."\nOr perhaps only the .pm file was installed but not the shared object file." } elsif ($err =~ /Can't locate.*?DBD\/$driver\.pm in \@INC/) { my @drv = $class->available_drivers(1); $advice = "Perhaps the DBD::$driver perl module hasn't been fully installed,\n" ."or perhaps the capitalisation of '$driver' isn't right.\n" ."Available drivers: ".join(", ", @drv)."."; } elsif ($err =~ /Can't load .*? for module DBD::/) { $advice = "Perhaps a required shared library or dll isn't installed where expected"; } elsif ($err =~ /Can't locate .*? in \@INC/) { $advice = "Perhaps a module that DBD::$driver requires hasn't been fully installed"; } Carp::croak("install_driver($driver) failed: $err$advice\n"); } if ($DBI::dbi_debug) { no strict 'refs'; (my $driver_file = $driver_class) =~ s/::/\//g; my $dbd_ver = ${"$driver_class\::VERSION"} || "undef"; $class->trace_msg(" install_driver: $driver_class version $dbd_ver" ." loaded from $INC{qq($driver_file.pm)}\n"); } # --- do some behind-the-scenes checks and setups on the driver $class->setup_driver($driver_class); # --- run the driver function $drh = eval { $driver_class->driver($attr || {}) }; unless ($drh && ref $drh && !$@) { my $advice = ""; # catch people on case in-sensitive systems using the wrong case $advice = "\nPerhaps the capitalisation of DBD '$driver' isn't right." if $@ =~ /locate object method/; Carp::croak("$driver_class initialisation failed: $@$advice"); } $DBI::installed_drh{$driver} = $drh; $class->trace_msg(" <- install_driver= $drh\n") if $DBI::dbi_debug; $drh; } *driver = \&install_driver; # currently an alias, may change sub setup_driver { my ($class, $driver_class) = @_; my $type; foreach $type (qw(dr db st)){ my $class = $driver_class."::$type"; no strict 'refs'; push @{"${class}::ISA"}, "DBD::_::$type" unless UNIVERSAL::isa($class, "DBD::_::$type"); my $mem_class = "DBD::_mem::$type"; push @{"${class}_mem::ISA"}, $mem_class unless UNIVERSAL::isa("${class}_mem", $mem_class) or $DBI::PurePerl; } } sub _rebless { my $dbh = shift; my ($outer, $inner) = DBI::_handles($dbh); my $class = shift(@_).'::db'; bless $inner => $class; bless $outer => $class; # outer last for return } sub _set_isa { my ($classes, $topclass) = @_; my $trace = DBI->trace_msg(" _set_isa([@$classes])\n"); foreach my $suffix ('::db','::st') { my $previous = $topclass || 'DBI'; # trees are rooted here foreach my $class (@$classes) { my $base_class = $previous.$suffix; my $sub_class = $class.$suffix; my $sub_class_isa = "${sub_class}::ISA"; no strict 'refs'; if (@$sub_class_isa) { DBI->trace_msg(" $sub_class_isa skipped (already set to @$sub_class_isa)\n") if $trace; } else { @$sub_class_isa = ($base_class) unless @$sub_class_isa; DBI->trace_msg(" $sub_class_isa = $base_class\n") if $trace; } $previous = $class; } } } sub _rebless_dbtype_subclass { my ($dbh, $rootclass, $DbTypeSubclass, $attr) = @_; # determine the db type names for class hierarchy my @hierarchy = DBI::_dbtype_names($dbh, $DbTypeSubclass, $attr); # add the rootclass prefix to each ('DBI::' or 'MyDBI::' etc) $_ = $rootclass.'::'.$_ foreach (@hierarchy); # load the modules from the 'top down' DBI::_load_class($_, 1) foreach (reverse @hierarchy); # setup class hierarchy if needed, does both '::db' and '::st' DBI::_set_isa(\@hierarchy, $rootclass); # finally bless the handle into the subclass DBI::_rebless($dbh, $hierarchy[0]); } sub _dbtype_names { # list dbtypes for hierarchy, ie Informix=>ADO=>ODBC my ($dbh, $DbTypeSubclass, $attr) = @_; if ($DbTypeSubclass && $DbTypeSubclass ne '1' && ref $DbTypeSubclass ne 'CODE') { # treat $DbTypeSubclass as a comma separated list of names my @dbtypes = split /\s*,\s*/, $DbTypeSubclass; $dbh->trace_msg(" DbTypeSubclass($DbTypeSubclass)=@dbtypes (explicit)\n"); return @dbtypes; } # XXX will call $dbh->get_info(17) (=SQL_DBMS_NAME) in future? my $driver = $dbh->{Driver}->{Name}; if ( $driver eq 'Proxy' ) { # XXX Looking into the internals of DBD::Proxy is questionable! ($driver) = $dbh->{proxy_client}->{application} =~ /^DBI:(.+?):/i or die "Can't determine driver name from proxy"; } my @dbtypes = (ucfirst($driver)); if ($driver eq 'ODBC' || $driver eq 'ADO') { # XXX will move these out and make extensible later: my $_dbtype_name_regexp = 'Oracle'; # eg 'Oracle|Foo|Bar' my %_dbtype_name_map = ( 'Microsoft SQL Server' => 'MSSQL', 'SQL Server' => 'Sybase', 'Adaptive Server Anywhere' => 'ASAny', 'ADABAS D' => 'AdabasD', ); my $name; $name = $dbh->func(17, 'GetInfo') # SQL_DBMS_NAME if $driver eq 'ODBC'; $name = $dbh->{ado_conn}->Properties->Item('DBMS Name')->Value if $driver eq 'ADO'; die "Can't determine driver name! ($DBI::errstr)\n" unless $name; my $dbtype; if ($_dbtype_name_map{$name}) { $dbtype = $_dbtype_name_map{$name}; } else { if ($name =~ /($_dbtype_name_regexp)/) { $dbtype = lc($1); } else { # generic mangling for other names: $dbtype = lc($name); } $dbtype =~ s/\b(\w)/\U$1/g; $dbtype =~ s/\W+/_/g; } # add ODBC 'behind' ADO push @dbtypes, 'ODBC' if $driver eq 'ADO'; # add discovered dbtype in front of ADO/ODBC unshift @dbtypes, $dbtype; } @dbtypes = &$DbTypeSubclass($dbh, \@dbtypes) if (ref $DbTypeSubclass eq 'CODE'); $dbh->trace_msg(" DbTypeSubclass($DbTypeSubclass)=@dbtypes\n"); return @dbtypes; } sub _load_class { my ($load_class, $missing_ok) = @_; #DBI->trace_msg(" _load_class($load_class, $missing_ok)\n"); no strict 'refs'; return 1 if @{"$load_class\::ISA"}; # already loaded/exists (my $module = $load_class) =~ s!::!/!g; #DBI->trace_msg(" _load_class require $module\n"); eval { require "$module.pm"; }; return 1 unless $@; return 0 if $missing_ok && $@ =~ /^Can't locate \Q$module.pm\E/; die; # propagate $@; } sub init_rootclass { # deprecated return 1; } *internal = \&DBD::Switch::dr::driver; sub available_drivers { my($quiet) = @_; my(@drivers, $d, $f); local(*DBI::DIR, $@); my(%seen_dir, %seen_dbd); my $haveFileSpec = eval { require File::Spec }; foreach $d (@INC){ chomp($d); # Perl 5 beta 3 bug in #!./perl -Ilib from Test::Harness my $dbd_dir = ($haveFileSpec ? File::Spec->catdir($d, 'DBD') : "$d/DBD"); next unless -d $dbd_dir; next if $seen_dir{$d}; $seen_dir{$d} = 1; # XXX we have a problem here with case insensitive file systems # XXX since we can't tell what case must be used when loading. opendir(DBI::DIR, $dbd_dir) || Carp::carp "opendir $dbd_dir: $!\n"; foreach $f (readdir(DBI::DIR)){ next unless $f =~ s/\.pm$//; next if $f eq 'NullP'; if ($seen_dbd{$f}){ Carp::carp "DBD::$f in $d is hidden by DBD::$f in $seen_dbd{$f}\n" unless $quiet; } else { push(@drivers, $f); } $seen_dbd{$f} = $d; } closedir(DBI::DIR); } # "return sort @drivers" will not DWIM in scalar context. return wantarray ? sort @drivers : @drivers; } sub installed_versions { my ($class, $quiet) = @_; my %error; my %version = ( DBI => $DBI::VERSION ); $version{"DBI::PurePerl"} = $DBI::PurePerl::VERSION if $DBI::PurePerl; for my $driver ($class->available_drivers($quiet)) { next if $DBI::PurePerl && grep { -d "$_/auto/DBD/$driver" } @INC; my $drh = eval { local $SIG{__WARN__} = sub {}; $class->install_driver($driver); }; ($error{"DBD::$driver"}=$@),next if $@; no strict 'refs'; my $vers = ${"DBD::$driver" . '::VERSION'}; $version{"DBD::$driver"} = $vers || '?'; } if (wantarray) { return map { m/^DBD::(\w+)/ ? ($1) : () } sort keys %version; } if (!defined wantarray) { # void context require Config; # add more detail $version{OS} = "$^O\t($Config::Config{osvers})"; $version{Perl} = "$]\t($Config::Config{archname})"; $version{$_} = (($error{$_} =~ s/ \(\@INC.*//s),$error{$_}) for keys %error; printf " %-16s: %s\n",$_,$version{$_} for reverse sort keys %version; } return \%version; } sub data_sources { my ($class, $driver, @other) = @_; my $drh = $class->install_driver($driver); my @ds = $drh->data_sources(@other); return @ds; } sub neat_list { my ($listref, $maxlen, $sep) = @_; $maxlen = 0 unless defined $maxlen; # 0 == use internal default $sep = ", " unless defined $sep; join($sep, map { neat($_,$maxlen) } @$listref); } sub dump_results { # also aliased as a method in DBD::_::st my ($sth, $maxlen, $lsep, $fsep, $fh) = @_; return 0 unless $sth; $maxlen ||= 35; $lsep ||= "\n"; $fh ||= \*STDOUT; my $rows = 0; my $ref; while($ref = $sth->fetch) { print $fh $lsep if $rows++ and $lsep; my $str = neat_list($ref,$maxlen,$fsep); print $fh $str; # done on two lines to avoid 5.003 errors } print $fh "\n$rows rows".($DBI::err ? " ($DBI::err: $DBI::errstr)" : "")."\n"; $rows; } sub connect_test_perf { my($class, $dsn,$dbuser,$dbpass, $attr) = @_; Carp::croak("connect_test_perf needs hash ref as fourth arg") unless ref $attr; # these are non standard attributes just for this special method my $loops ||= $attr->{dbi_loops} || 5; my $par ||= $attr->{dbi_par} || 1; # parallelism my $verb ||= $attr->{dbi_verb} || 1; print "$dsn: testing $loops sets of $par connections:\n"; require Benchmark; require "FileHandle.pm"; # don't let toke.c create empty FileHandle package $| = 1; my $t0 = new Benchmark; # not currently used my $drh = $class->install_driver($dsn) or Carp::croak("Can't install $dsn driver\n"); my $t1 = new Benchmark; my $loop; for $loop (1..$loops) { my @cons; print "Connecting... " if $verb; for (1..$par) { print "$_ "; push @cons, ($drh->connect($dsn,$dbuser,$dbpass) or Carp::croak("Can't connect # $_: $DBI::errstr\n")); } print "\nDisconnecting...\n" if $verb; for (@cons) { $_->disconnect or warn "bad disconnect $DBI::errstr" } } my $t2 = new Benchmark; my $td = Benchmark::timediff($t2, $t1); printf "Made %2d connections in %s\n", $loops*$par, Benchmark::timestr($td); print "\n"; return $td; } # Help people doing DBI->errstr, might even document it one day # XXX probably best moved to cheaper XS code sub err { $DBI::err } sub errstr { $DBI::errstr } # --- Private Internal Function for Creating New DBI Handles sub _new_handle { my ($class, $parent, $attr, $imp_data, $imp_class) = @_; Carp::croak('Usage: DBI::_new_handle' .'($class_name, parent_handle, \%attr, $imp_data)'."\n" .'got: ('.join(", ",$class, $parent, $attr, $imp_data).")\n") unless (@_ == 5 and (!$parent or ref $parent) and ref $attr eq 'HASH' and $imp_class); $attr->{ImplementorClass} = $imp_class or Carp::croak("_new_handle($class): 'ImplementorClass' attribute not given"); DBI->trace_msg(" New $class (for $imp_class, parent=$parent, id=".($imp_data||'').")\n") if $DBI::dbi_debug >= 3; # This is how we create a DBI style Object: my (%hash, $i, $h); $i = tie %hash, $class, $attr; # ref to inner hash (for driver) $h = bless \%hash, $class; # ref to outer hash (for application) # The above tie and bless may migrate down into _setup_handle()... # Now add magic so DBI method dispatch works DBI::_setup_handle($h, $imp_class, $parent, $imp_data); return $h unless wantarray; ($h, $i); } # XXX minimum constructors for the tie's (alias to XS version) sub DBI::st::TIEHASH { bless $_[1] => $_[0] }; *DBI::dr::TIEHASH = \&DBI::st::TIEHASH; *DBI::db::TIEHASH = \&DBI::st::TIEHASH; # These three special constructors are called by the drivers # The way they are called is likely to change. my $profile; sub _new_drh { # called by DBD::::driver() my ($class, $initial_attr, $imp_data) = @_; # Provide default storage for State,Err and Errstr. # Note that these are shared by all child handles by default! XXX # State must be undef to get automatic faking in DBI::var::FETCH my ($h_state_store, $h_err_store, $h_errstr_store) = (undef, 0, ''); my $attr = { # these attributes get copied down to child handles by default 'State' => \$h_state_store, # Holder for DBI::state 'Err' => \$h_err_store, # Holder for DBI::err 'Errstr' => \$h_errstr_store, # Holder for DBI::errstr 'TraceLevel' => 0, FetchHashKeyName=> 'NAME', %$initial_attr, }; my ($h, $i) = _new_handle('DBI::dr', '', $attr, $imp_data, $class); # XXX DBI_PROFILE unless DBI::PurePerl because for some reason # it kills the t/zz_*_pp.t tests (they silently exit early) if ($ENV{DBI_PROFILE} && !$DBI::PurePerl) { # The profile object created here when the first driver is loaded # is shared by all drivers so we end up with just one set of profile # data and thus the 'total time in DBI' is really the true total. if (!$profile) { # first time $h->{Profile} = $ENV{DBI_PROFILE}; $profile = $h->{Profile}; } else { $h->{Profile} = $profile; } } return $h unless wantarray; ($h, $i); } sub _new_dbh { # called by DBD::::dr::connect() my ($drh, $attr, $imp_data) = @_; my $imp_class = $drh->{ImplementorClass} or Carp::croak("DBI _new_dbh: $drh has no ImplementorClass"); substr($imp_class,-4,4) = '::db'; my $app_class = ref $drh; substr($app_class,-4,4) = '::db'; $attr->{Err} ||= \my $err; $attr->{Errstr} ||= \my $errstr; $attr->{State} ||= \my $state; _new_handle($app_class, $drh, $attr, $imp_data, $imp_class); } sub _new_sth { # called by DBD::::db::prepare) my ($dbh, $attr, $imp_data) = @_; my $imp_class = $dbh->{ImplementorClass} or Carp::croak("DBI _new_sth: $dbh has no ImplementorClass"); substr($imp_class,-4,4) = '::st'; my $app_class = ref $dbh; substr($app_class,-4,4) = '::st'; _new_handle($app_class, $dbh, $attr, $imp_data, $imp_class); } # end of DBI package # -------------------------------------------------------------------- # === The internal DBI Switch pseudo 'driver' class === { package # hide from PAUSE DBD::Switch::dr; DBI->setup_driver('DBD::Switch'); # sets up @ISA $DBD::Switch::dr::imp_data_size = 0; $DBD::Switch::dr::imp_data_size = 0; # avoid typo warning my $drh; sub driver { return $drh if $drh; # a package global my $inner; ($drh, $inner) = DBI::_new_drh('DBD::Switch::dr', { 'Name' => 'Switch', 'Version' => $DBI::VERSION, 'Attribution' => "DBI $DBI::VERSION by Tim Bunce", }); Carp::croak("DBD::Switch init failed!") unless ($drh && $inner); return $drh; } sub CLONE { undef $drh; } sub FETCH { my($drh, $key) = @_; return DBI->trace if $key eq 'DebugDispatch'; return undef if $key eq 'DebugLog'; # not worth fetching, sorry return $drh->DBD::_::dr::FETCH($key); undef; } sub STORE { my($drh, $key, $value) = @_; if ($key eq 'DebugDispatch') { DBI->trace($value); } elsif ($key eq 'DebugLog') { DBI->trace(-1, $value); } else { $drh->DBD::_::dr::STORE($key, $value); } } } # -------------------------------------------------------------------- # === OPTIONAL MINIMAL BASE CLASSES FOR DBI SUBCLASSES === # We only define default methods for harmless functions. # We don't, for example, define a DBD::_::st::prepare() { package # hide from PAUSE DBD::_::common; # ====== Common base class methods ====== use strict; # methods common to all handle types: sub _not_impl { my ($h, $method) = @_; $h->trace_msg("Driver does not implement the $method method.\n"); return; # empty list / undef } # generic TIEHASH default methods: sub FIRSTKEY { } sub NEXTKEY { } sub EXISTS { defined($_[0]->FETCH($_[1])) } # XXX undef? sub CLEAR { Carp::carp "Can't CLEAR $_[0] (DBI)" } *dump_handle = \&DBI::dump_handle; sub install_method { # special class method called directly by apps and/or drivers # to install new methods into the DBI dispatcher # DBD::Foo::db->install_method("foo_mumble", { usage => [...], options => '...' }); my ($class, $method, $attr) = @_; Carp::croak("Class '$class' must begin with DBD:: and end with ::db or ::st") unless $class =~ /^DBD::(\w+)::(dr|db|st)$/; my ($driver, $subtype) = ($1, $2); Carp::croak("invalid method name '$method'") unless $method =~ m/^([a-z]+_)\w+$/; my $prefix = $1; my $reg_info = $dbd_prefix_registry->{$prefix}; Carp::croak("method name prefix '$prefix' is not registered") unless $reg_info; my %attr = %{$attr||{}}; # copy so we can edit # XXX reformat $attr as needed for _install_method my ($caller_pkg, $filename, $line) = caller; DBI->_install_method("DBI::${subtype}::$method", "$filename at line $line", \%attr); } sub parse_trace_flags { my ($h, $spec) = @_; my $level = 0; my $flags = 0; my @unknown; for my $word (split /\s*[|&]\s*/, $spec) { if (DBI::looks_like_number($word) && $word <= 0xF && $word >= 0) { $level = $word; } elsif ($word eq 'ALL') { $flags = 0x7FFFFFFF; # XXX last bit causes negative headaches last; } elsif (my $flag = $h->parse_trace_flag($word)) { $flags |= $flag; } else { push @unknown, $word; } } if (@unknown && (ref $h ? $h->FETCH('Warn') : 1)) { Carp::carp("$h->parse_trace_flags($spec) ignored unknown trace flags: ". join(" ", map { DBI::neat($_) } @unknown)); } $flags |= $level; return $flags; } sub parse_trace_flag { my ($h, $name) = @_; # 0xddDDDDrL (driver, DBI, reserved, Level) return 0x00000100 if $name eq 'SQL'; return; } } { package # hide from PAUSE DBD::_::dr; # ====== DRIVER ====== @DBD::_::dr::ISA = qw(DBD::_::common); use strict; sub default_user { my ($drh, $user, $pass, $attr) = @_; $user = $ENV{DBI_USER} unless defined $user; $pass = $ENV{DBI_PASS} unless defined $pass; return ($user, $pass); } sub connect { # normally overridden, but a handy default my ($drh, $dsn, $user, $auth) = @_; my ($this) = DBI::_new_dbh($drh, { 'Name' => $dsn, }); $this; } sub connect_cached { my $drh = shift; my ($dsn, $user, $auth, $attr)= @_; # Needs support at dbh level to clear cache before complaining about # active children. The XS template code does this. Drivers not using # the template must handle clearing the cache themselves. my $cache = $drh->FETCH('CachedKids'); $drh->STORE('CachedKids', $cache = {}) unless $cache; my @attr_keys = $attr ? sort keys %$attr : (); my $key = join "~~", $dsn, $user||'', $auth||'', $attr ? (@attr_keys,@{$attr}{@attr_keys}) : (); my $dbh = $cache->{$key}; return $dbh if $dbh && $dbh->FETCH('Active') && eval { $dbh->ping }; $dbh = $drh->connect(@_); $cache->{$key} = $dbh; # replace prev entry, even if connect failed return $dbh; } } { package # hide from PAUSE DBD::_::db; # ====== DATABASE ====== @DBD::_::db::ISA = qw(DBD::_::common); use strict; sub clone { my ($old_dbh, $attr) = @_; my $closure = $old_dbh->{dbi_connect_closure} or return; unless ($attr) { # copy attributes visible in the attribute cache keys %$old_dbh; # reset iterator while ( my ($k, $v) = each %$old_dbh ) { # ignore non-code refs, i.e., caches, handles, Err etc next if ref $v && ref $v ne 'CODE'; # HandleError etc $attr->{$k} = $v; } # explicitly set attributes which are unlikely to be in the # attribute cache, i.e., boolean's and some others $attr->{$_} = $old_dbh->FETCH($_) for (qw( AutoCommit ChopBlanks InactiveDestroy LongTruncOk PrintError PrintWarn Profile RaiseError ShowErrorStatement TaintIn TaintOut )); } # use Data::Dumper; warn Dumper([$old_dbh, $attr]); my $new_dbh = &$closure($old_dbh, $attr); unless ($new_dbh) { # need to copy err/errstr from driver back into $old_dbh my $drh = $old_dbh->{Driver}; return $old_dbh->set_err($drh->err, $drh->errstr, $drh->state); } return $new_dbh; } sub quote_identifier { my ($dbh, @id) = @_; my $attr = (@id > 3 && ref($id[-1])) ? pop @id : undef; my $info = $dbh->{dbi_quote_identifier_cache} ||= [ $dbh->get_info(29) || '"', # SQL_IDENTIFIER_QUOTE_CHAR $dbh->get_info(41) || '.', # SQL_CATALOG_NAME_SEPARATOR $dbh->get_info(114) || 1, # SQL_CATALOG_LOCATION ]; my $quote = $info->[0]; foreach (@id) { # quote the elements next unless defined; s/$quote/$quote$quote/g; # escape embedded quotes $_ = qq{$quote$_$quote}; } # strip out catalog if present for special handling my $catalog = (@id >= 3) ? shift @id : undef; # join the dots, ignoring any null/undef elements (ie schema) my $quoted_id = join '.', grep { defined } @id; if ($catalog) { # add catalog correctly $quoted_id = ($info->[2] == 2) # SQL_CL_END ? $quoted_id . $info->[1] . $catalog : $catalog . $info->[1] . $quoted_id; } return $quoted_id; } sub quote { my ($dbh, $str, $data_type) = @_; return "NULL" unless defined $str; unless ($data_type) { $str =~ s/'/''/g; # ISO SQL2 return "'$str'"; } my $dbi_literal_quote_cache = $dbh->{'dbi_literal_quote_cache'} ||= [ {} , {} ]; my ($prefixes, $suffixes) = @$dbi_literal_quote_cache; my $lp = $prefixes->{$data_type}; my $ls = $suffixes->{$data_type}; if ( ! defined $lp || ! defined $ls ) { my $ti = $dbh->type_info($data_type); $lp = $prefixes->{$data_type} = $ti ? $ti->{LITERAL_PREFIX} || "" : "'"; $ls = $suffixes->{$data_type} = $ti ? $ti->{LITERAL_SUFFIX} || "" : "'"; } return $str unless $lp || $ls; # no quoting required # XXX don't know what the standard says about escaping # in the 'general case' (where $lp != "'"). # So we just do this and hope: $str =~ s/$lp/$lp$lp/g if $lp && $lp eq $ls && ($lp eq "'" || $lp eq '"'); return "$lp$str$ls"; } sub rows { -1 } # here so $DBI::rows 'works' after using $dbh sub do { my($dbh, $statement, $attr, @params) = @_; my $sth = $dbh->prepare($statement, $attr) or return undef; $sth->execute(@params) or return undef; my $rows = $sth->rows; ($rows == 0) ? "0E0" : $rows; } sub _do_selectrow { my ($method, $dbh, $stmt, $attr, @bind) = @_; my $sth = ((ref $stmt) ? $stmt : $dbh->prepare($stmt, $attr)) or return; $sth->execute(@bind) or return; my $row = $sth->$method() and $sth->finish; return $row; } sub selectrow_hashref { return _do_selectrow('fetchrow_hashref', @_); } # XXX selectrow_array/ref also have C implementations in Driver.xst sub selectrow_arrayref { return _do_selectrow('fetchrow_arrayref', @_); } sub selectrow_array { my $row = _do_selectrow('fetchrow_arrayref', @_) or return; return $row->[0] unless wantarray; return @$row; } # XXX selectall_arrayref also has C implementation in Driver.xst # which fallsback to this if a slice is given sub selectall_arrayref { my ($dbh, $stmt, $attr, @bind) = @_; my $sth = (ref $stmt) ? $stmt : $dbh->prepare($stmt, $attr) or return; $sth->execute(@bind) || return; my $slice = $attr->{Slice}; # typically undef, else hash or array ref if (!$slice and $slice=$attr->{Columns}) { if (ref $slice eq 'ARRAY') { # map col idx to perl array idx $slice = [ @{$attr->{Columns}} ]; # take a copy for (@$slice) { $_-- } } } return $sth->fetchall_arrayref($slice, $attr->{MaxRows}); } sub selectall_hashref { my ($dbh, $stmt, $key_field, $attr, @bind) = @_; my $sth = (ref $stmt) ? $stmt : $dbh->prepare($stmt, $attr); return unless $sth; $sth->execute(@bind) || return; return $sth->fetchall_hashref($key_field); } sub selectcol_arrayref { my ($dbh, $stmt, $attr, @bind) = @_; my $sth = (ref $stmt) ? $stmt : $dbh->prepare($stmt, $attr); return unless $sth; $sth->execute(@bind) || return; my @columns = ($attr->{Columns}) ? @{$attr->{Columns}} : (1); my @values = (undef) x @columns; my $idx = 0; for (@columns) { $sth->bind_col($_, \$values[$idx++]) || return; } my @col; if (my $max = $attr->{MaxRows}) { push @col, @values while @col<$max && $sth->fetch; } else { push @col, @values while $sth->fetch; } return \@col; } sub prepare_cached { my ($dbh, $statement, $attr, $if_active) = @_; # Needs support at dbh level to clear cache before complaining about # active children. The XS template code does this. Drivers not using # the template must handle clearing the cache themselves. my $cache = $dbh->FETCH('CachedKids'); $dbh->STORE('CachedKids', $cache = {}) unless $cache; my @attr_keys = ($attr) ? sort keys %$attr : (); my $key = ($attr) ? join("~~", $statement, @attr_keys, @{$attr}{@attr_keys}) : $statement; my $sth = $cache->{$key}; if ($sth) { return $sth unless $sth->FETCH('Active'); Carp::carp("prepare_cached($statement) statement handle $sth still active") unless ($if_active ||= 0); $sth->finish if $if_active <= 1; return $sth if $if_active <= 2; } $sth = $dbh->prepare($statement, $attr); $cache->{$key} = $sth if $sth; return $sth; } sub ping { shift->_not_impl('ping'); "0 but true"; # special kind of true 0 } sub begin_work { my $dbh = shift; return $dbh->set_err(1, "Already in a transaction") unless $dbh->FETCH('AutoCommit'); $dbh->STORE('AutoCommit', 0); # will croak if driver doesn't support it $dbh->STORE('BegunWork', 1); # trigger post commit/rollback action return 1; } sub primary_key { my ($dbh, @args) = @_; my $sth = $dbh->primary_key_info(@args) or return; my ($row, @col); push @col, $row->[3] while ($row = $sth->fetch); Carp::croak("primary_key method not called in list context") unless wantarray; # leave us some elbow room return @col; } sub tables { my ($dbh, @args) = @_; my $sth = $dbh->table_info(@args[0,1,2,3,4]) or return; my $tables = $sth->fetchall_arrayref or return; my @tables; if ($dbh->get_info(29)) { # SQL_IDENTIFIER_QUOTE_CHAR @tables = map { $dbh->quote_identifier( @{$_}[0,1,2] ) } @$tables; } else { # temporary old style hack (yeach) @tables = map { my $name = $_->[2]; if ($_->[1]) { my $schema = $_->[1]; # a sad hack (mostly for Informix I recall) my $quote = ($schema eq uc($schema)) ? '' : '"'; $name = "$quote$schema$quote.$name" } $name; } @$tables; } return @tables; } sub type_info { # this should be sufficient for all drivers my ($dbh, $data_type) = @_; my $idx_hash; my $tia = $dbh->{dbi_type_info_row_cache}; if ($tia) { $idx_hash = $dbh->{dbi_type_info_idx_cache}; } else { my $temp = $dbh->type_info_all; return unless $temp && @$temp; # we cache here because type_info_all may be expensive to call $tia = $dbh->{dbi_type_info_row_cache} = $temp; $idx_hash = $dbh->{dbi_type_info_idx_cache} = shift @$tia; } my $dt_idx = $idx_hash->{DATA_TYPE} || $idx_hash->{data_type}; Carp::croak("type_info_all returned non-standard DATA_TYPE index value ($dt_idx != 1)") if $dt_idx && $dt_idx != 1; # --- simple DATA_TYPE match filter my @ti; my @data_type_list = (ref $data_type) ? @$data_type : ($data_type); foreach $data_type (@data_type_list) { if (defined($data_type) && $data_type != DBI::SQL_ALL_TYPES()) { push @ti, grep { $_->[$dt_idx] == $data_type } @$tia; } else { # SQL_ALL_TYPES push @ti, @$tia; } last if @ti; # found at least one match } # --- format results into list of hash refs my $idx_fields = keys %$idx_hash; my @idx_names = map { uc($_) } keys %$idx_hash; my @idx_values = values %$idx_hash; Carp::croak "type_info_all result has $idx_fields keys but ".(@{$ti[0]})." fields" if @ti && @{$ti[0]} != $idx_fields; my @out = map { my %h; @h{@idx_names} = @{$_}[ @idx_values ]; \%h; } @ti; return $out[0] unless wantarray; return @out; } sub data_sources { my ($dbh, @other) = @_; my $drh = $dbh->{Driver}; # XXX proxy issues? return $drh->data_sources(@other); } } { package # hide from PAUSE DBD::_::st; # ====== STATEMENT ====== @DBD::_::st::ISA = qw(DBD::_::common); use strict; sub bind_param { Carp::croak("Can't bind_param, not implement by driver") } # # ******************************************************** # # BEGIN ARRAY BINDING # # Array binding support for drivers which don't support # array binding, but have sufficient interfaces to fake it. # NOTE: mixing scalars and arrayrefs requires using bind_param_array # for *all* params...unless we modify bind_param for the default # case... # # 2002-Apr-10 D. Arnold sub bind_param_array { my $sth = shift; my ($p_id, $value_array, $attr) = @_; return $sth->set_err(1, "Value for parameter $p_id must be a scalar or an arrayref, not a ".ref($value_array)) if defined $value_array and ref $value_array and ref $value_array ne 'ARRAY'; return $sth->set_err(1, "Can't use named placeholders for non-driver supported bind_param_array") unless DBI::looks_like_number($p_id); # because we rely on execute(@ary) here # get/create arrayref to hold params my $hash_of_arrays = $sth->{ParamArrays} ||= { }; if (ref $value_array eq 'ARRAY') { # check that input has same length as existing # find first arrayref entry (if any) foreach (keys %$hash_of_arrays) { my $v = $$hash_of_arrays{$_}; next unless ref $v eq 'ARRAY'; return $sth->set_err(1, "Arrayref for parameter $p_id has ".@$value_array." elements" ." but parameter $_ has ".@$v) if @$value_array != @$v; } } # If the bind has attribs then we rely on the driver conforming to # the DBI spec in that a single bind_param() call with those attribs # makes them 'sticky' and apply to all later execute(@values) calls. # Since we only call bind_param() if we're given attribs then # applications using drivers that don't support bind_param can still # use bind_param_array() so long as they don't pass any attribs. $$hash_of_arrays{$p_id} = $value_array; return $sth->bind_param($p_id, undef, $attr) if $attr; 1; } sub bind_param_inout_array { my $sth = shift; # XXX not supported so we just call bind_param_array instead # and then return an error my ($p_num, $value_array, $attr) = @_; $sth->bind_param_array($p_num, $value_array, $attr); return $sth->set_err(1, "bind_param_inout_array not supported"); } sub bind_columns { my $sth = shift; my $fields = $sth->FETCH('NUM_OF_FIELDS') || 0; if ($fields <= 0 && !$sth->{Active}) { # XXX ought to be set_err die "Statement has no result columns to bind" ." (perhaps you need to successfully call execute first)"; } # Backwards compatibility for old-style call with attribute hash # ref as first arg. Skip arg if undef or a hash ref. my $attr = $_[0]; # maybe shift if !defined $attr or ref($attr) eq 'HASH'; die "bind_columns called with ".@_." refs when $fields needed." if @_ != $fields; my $idx = 0; $sth->bind_col(++$idx, shift) or return while (@_); return 1; } sub execute_array { my $sth = shift; my ($attr, @array_of_arrays) = @_; my $NUM_OF_PARAMS = $sth->FETCH('NUM_OF_PARAMS'); # may be undef at this point # get tuple status array or hash attribute my $tuple_sts = $attr->{ArrayTupleStatus}; return $sth->set_err(1, "ArrayTupleStatus attribute must be an arrayref") if $tuple_sts and ref $tuple_sts ne 'ARRAY'; # bind all supplied arrays if (@array_of_arrays) { $sth->{ParamArrays} = { }; # clear out old params return $sth->set_err(1, @array_of_arrays." bind values supplied but $NUM_OF_PARAMS expected") if defined ($NUM_OF_PARAMS) && @array_of_arrays != $NUM_OF_PARAMS; $sth->bind_param_array($_, $array_of_arrays[$_-1]) or return foreach (1..@array_of_arrays); } my $fetch_tuple_sub; if ($fetch_tuple_sub = $attr->{ArrayTupleFetch}) { # fetch on demand return $sth->set_err(1, "Can't use both ArrayTupleFetch and explicit bind values") if @array_of_arrays; # previous bind_param_array calls will simply be ignored if (UNIVERSAL::isa($fetch_tuple_sub,'DBI::st')) { my $fetch_sth = $fetch_tuple_sub; return $sth->set_err(1, "ArrayTupleFetch sth is not Active, need to execute() it first") unless $fetch_sth->{Active}; # check column count match to give more friendly message my $NUM_OF_FIELDS = $fetch_sth->{NUM_OF_FIELDS}; return $sth->set_err(1, "$NUM_OF_FIELDS columns from ArrayTupleFetch sth but $NUM_OF_PARAMS expected") if defined($NUM_OF_FIELDS) && defined($NUM_OF_PARAMS) && $NUM_OF_FIELDS != $NUM_OF_PARAMS; $fetch_tuple_sub = sub { $fetch_sth->fetchrow_arrayref }; } elsif (!UNIVERSAL::isa($fetch_tuple_sub,'CODE')) { return $sth->set_err(1, "ArrayTupleFetch '$fetch_tuple_sub' is not a code ref or statement handle"); } } else { my $NUM_OF_PARAMS_given = keys %{ $sth->{ParamArrays} || {} }; return $sth->set_err(1, "$NUM_OF_PARAMS_given bind values supplied but $NUM_OF_PARAMS expected") if defined($NUM_OF_PARAMS) && $NUM_OF_PARAMS != $NUM_OF_PARAMS_given; # get the length of a bound array my $len = 1; # in case all are scalars my %hash_of_arrays = %{$sth->{ParamArrays}}; foreach (keys(%hash_of_arrays)) { my $ary = $hash_of_arrays{$_}; $len = @$ary if ref $ary eq 'ARRAY'; } my @bind_ids = 1..keys(%hash_of_arrays); my $tuple_idx = 0; $fetch_tuple_sub = sub { return if $tuple_idx >= $len; my @tuple = map { my $a = $hash_of_arrays{$_}; ref($a) ? $a->[$tuple_idx] : $a } @bind_ids; ++$tuple_idx; return \@tuple; }; } return $sth->execute_for_fetch($fetch_tuple_sub, $tuple_sts); } sub execute_for_fetch { my ($sth, $fetch_tuple_sub, $tuple_status) = @_; # start with empty status array ($tuple_status) ? @$tuple_status = () : $tuple_status = []; my ($err_count, %errstr_cache); while ( my $tuple = &$fetch_tuple_sub() ) { if ( my $rc = $sth->execute(@$tuple) ) { push @$tuple_status, $rc; } else { $err_count++; my $err = $sth->err; push @$tuple_status, [ $err, $errstr_cache{$err} ||= $sth->errstr, $sth->state ]; } } return ($err_count) ? undef : scalar @$tuple_status; } sub fetchall_arrayref { # ALSO IN Driver.xst my ($sth, $slice, $max_rows) = @_; $max_rows = -1 unless defined $max_rows; my $mode = ref($slice) || 'ARRAY'; my @rows; my $row; if ($mode eq 'ARRAY') { # we copy the array here because fetch (currently) always # returns the same array ref. XXX if ($slice && @$slice) { $max_rows = -1 unless defined $max_rows; push @rows, [ @{$row}[ @$slice] ] while($max_rows-- and $row = $sth->fetch); } elsif (defined $max_rows) { $max_rows = -1 unless defined $max_rows; push @rows, [ @$row ] while($max_rows-- and $row = $sth->fetch); } else { push @rows, [ @$row ] while($row = $sth->fetch); } } elsif ($mode eq 'HASH') { $max_rows = -1 unless defined $max_rows; if (keys %$slice) { my @o_keys = keys %$slice; my @i_keys = map { lc } keys %$slice; while ($max_rows-- and $row = $sth->fetchrow_hashref('NAME_lc')) { my %hash; @hash{@o_keys} = @{$row}{@i_keys}; push @rows, \%hash; } } else { # XXX assumes new ref each fetchhash push @rows, $row while ($max_rows-- and $row = $sth->fetchrow_hashref()); } } else { Carp::croak("fetchall_arrayref($mode) invalid") } return \@rows; } sub fetchall_hashref { # XXX may be better to fetchall_arrayref then convert to hashes my ($sth, $key_field) = @_; my $hash_key_name = $sth->{FetchHashKeyName}; my $names_hash = $sth->FETCH("${hash_key_name}_hash"); my $index = $names_hash->{$key_field}; # perl index not column number ++$index if defined $index; # convert to column number $index ||= $key_field if DBI::looks_like_number($key_field) && $key_field>=1; return $sth->set_err(1, "Field '$key_field' does not exist (not one of @{[keys %$names_hash]})") unless defined $index; my $key_value; $sth->bind_col($index, \$key_value) or return; my %rows; while (my $row = $sth->fetchrow_hashref($hash_key_name)) { $rows{ $key_value } = $row; } return \%rows; } *dump_results = \&DBI::dump_results; sub blob_copy_to_file { # returns length or undef on error my($self, $field, $filename_or_handleref, $blocksize) = @_; my $fh = $filename_or_handleref; my($len, $buf) = (0, ""); $blocksize ||= 512; # not too ambitious local(*FH); unless(ref $fh) { open(FH, ">$fh") || return undef; $fh = \*FH; } while(defined($self->blob_read($field, $len, $blocksize, \$buf))) { print $fh $buf; $len += length $buf; } close(FH); $len; } sub more_results { shift->{syb_more_results}; # handy grandfathering } } unless ($DBI::PurePerl) { # See install_driver { @DBD::_mem::dr::ISA = qw(DBD::_mem::common); } { @DBD::_mem::db::ISA = qw(DBD::_mem::common); } { @DBD::_mem::st::ISA = qw(DBD::_mem::common); } # DBD::_mem::common::DESTROY is implemented in DBI.xs } 1; __END__ =head1 DESCRIPTION The DBI is a database access module for the Perl programming language. It defines a set of methods, variables, and conventions that provide a consistent database interface, independent of the actual database being used. It is important to remember that the DBI is just an interface. The DBI is a layer of "glue" between an application and one or more database I modules. It is the driver modules which do most of the real work. The DBI provides a standard interface and framework for the drivers to operate within. =head2 Architecture of a DBI Application |<- Scope of DBI ->| .-. .--------------. .-------------. .-------. | |---| XYZ Driver |---| XYZ Engine | | Perl | | | `--------------' `-------------' | script| |A| |D| .--------------. .-------------. | using |--|P|--|B|---|Oracle Driver |---|Oracle Engine| | DBI | |I| |I| `--------------' `-------------' | API | | |... |methods| | |... Other drivers `-------' | |... `-' The API, or Application Programming Interface, defines the call interface and variables for Perl scripts to use. The API is implemented by the Perl DBI extension. The DBI "dispatches" the method calls to the appropriate driver for actual execution. The DBI is also responsible for the dynamic loading of drivers, error checking and handling, providing default implementations for methods, and many other non-database specific duties. Each driver contains implementations of the DBI methods using the private interface functions of the corresponding database engine. Only authors of sophisticated/multi-database applications or generic library functions need be concerned with drivers. =head2 Notation and Conventions The following conventions are used in this document: $dbh Database handle object $sth Statement handle object $drh Driver handle object (rarely seen or used in applications) $h Any of the handle types above ($dbh, $sth, or $drh) $rc General Return Code (boolean: true=ok, false=error) $rv General Return Value (typically an integer) @ary List of values returned from the database, typically a row of data $rows Number of rows processed (if available, else -1) $fh A filehandle undef NULL values are represented by undefined values in Perl \%attr Reference to a hash of attribute values passed to methods Note that Perl will automatically destroy database and statement handle objects if all references to them are deleted. =head2 Outline Usage To use DBI, first you need to load the DBI module: use DBI; use strict; (The C isn't required but is strongly recommended.) Then you need to L to your data source and get a I for that connection: $dbh = DBI->connect($dsn, $user, $password, { RaiseError => 1, AutoCommit => 0 }); Since connecting can be expensive, you generally just connect at the start of your program and disconnect at the end. Explicitly defining the required C behaviour is strongly recommended and may become mandatory in a later version. This determines whether changes are automatically committed to the database when executed, or need to be explicitly committed later. The DBI allows an application to "prepare" statements for later execution. A prepared statement is identified by a statement handle held in a Perl variable. We'll call the Perl variable C<$sth> in our examples. The typical method call sequence for a C statement is: prepare, execute, execute, execute. for example: $sth = $dbh->prepare("INSERT INTO table(foo,bar,baz) VALUES (?,?,?)"); while() { chomp; my ($foo,$bar,$baz) = split /,/; $sth->execute( $foo, $bar, $baz ); } The C method can be used for non repeated I-C statement. Consider: SELECT description FROM products WHERE product_code = ? Binding an C (NULL) to the placeholder will I select rows which have a NULL C! Refer to the SQL manual for your database engine or any SQL book for the reasons for this. To explicitly select NULLs you have to say "C" and to make that general you have to say: ... WHERE (product_code = ? OR (? IS NULL AND product_code IS NULL)) and bind the same value to both placeholders. Sadly, that more general syntax doesn't work for Sybase and MS SQL Server. However on those two servers the original "C" syntax works for binding nulls. B Without using placeholders, the insert statement shown previously would have to contain the literal values to be inserted and would have to be re-prepared and re-executed for each row. With placeholders, the insert statement only needs to be prepared once. The bind values for each row can be given to the C method each time it's called. By avoiding the need to re-prepare the statement for each row, the application typically runs many times faster. Here's an example: my $sth = $dbh->prepare(q{ INSERT INTO sales (product_code, qty, price) VALUES (?, ?, ?) }) or die $dbh->errstr; while (<>) { chomp; my ($product_code, $qty, $price) = split /,/; $sth->execute($product_code, $qty, $price) or die $dbh->errstr; } $dbh->commit or die $dbh->errstr; See L and L for more details. The C style quoting used in this example avoids clashing with quotes that may be used in the SQL statement. Use the double-quote like C operator if you want to interpolate variables into the string. See L for more details. See also the L method, which is used to associate Perl variables with the output columns of a C that may have more data to fetch. (Fetching all the data or calling C<$sth-Efinish> sets C off.) =item C (boolean) The C attribute is true if the handle object has been "executed". Currently only the $dbh do() method and the $sth execute(), execute_array(), and execute_for_fetch() methods set the C attribute. When it's set on a handle it is also set on the parent handle at the same time. So calling execute() on a $sth also sets the C attribute on the parent $dbh. The C attribute for a database handle is cleared by the commit() and rollback() methods. The C attribute of a statement handle is not cleared by the DBI under any circumstances and so acts as a permanent record of whether the statement handle was ever used. The C attribute was added in DBI 1.41. =item C (integer, read-only) For a driver handle, C is the number of currently existing database handles that were created from that driver handle. For a database handle, C is the number of currently existing statement handles that were created from that database handle. For a statement handle, the value is zero. =item C (integer, read-only) Like C, but only counting those that are C (as above). =item C (hash ref) For a database handle, C returns a reference to the cache (hash) of statement handles created by the L method. For a driver handle, returns a reference to the cache (hash) of database handles created by the L method. =item C (boolean, inherited) The C attribute is used by emulation layers (such as Oraperl) to enable compatible behaviour in the underlying driver (e.g., DBD::Oracle) for this handle. Not normally set by application code. It also has the effect of disabling the 'quick FETCH' of attribute values from the handles attribute cache. So all attribute values are handled by the drivers own FETCH method. This makes them slightly slower but is useful for special-purpose drivers like DBD::Multiplex. =item C (boolean) The C attribute can be used to disable the I related effect of DESTROYing a handle (which would normally close a prepared statement or disconnect from the database etc). The default value, false, means a handle will be fully destroyed when it passes out of scope. For a database handle, this attribute does not disable an I call to the disconnect method, only the implicit call from DESTROY that happens if the handle is still marked as C. Think of the name as meaning 'treat the handle as not-Active in the DESTROY method'. This attribute is specifically designed for use in Unix applications that "fork" child processes. Either the parent or the child process, but not both, should set C on all their shared handles. Note that some databases, including Oracle, don't support passing a database connection across a fork. To help tracing applications using fork the process id is shown in the trace log whenever a DBI or handle trace() method is called. The process id also shown for I method call if the DBI trace level (not handle trace level) is set high enough to show the trace from the DBI's method dispatcher, e.g. >= 9. =item C (boolean, inherited) The C attribute controls the printing of warnings recorded by the driver. When set to a true value the DBI will check method calls to see if a warning condition has been set. If so, the DBI will effectively do a C where C<$class> is the driver class and C<$method> is the name of the method which failed. E.g., DBD::Oracle::db execute warning: ... warning text here ... By default, Cconnect> sets C "on" if $^W is true, i.e., perl is running with warnings enabled. If desired, the warnings can be caught and processed using a C<$SIG{__WARN__}> handler or modules like CGI::Carp and CGI::ErrorWrap. See also L for how warnings are recorded and L for how to influence it. Fetching the full details of warnings can require an extra round-trip to the database server for some drivers. In which case the driver may opt to only fetch the full details of warnings if the C attribute is true. If C is false then these drivers should still indicate the fact that there were warnings by setting the warning string to, for example: "3 warnings". =item C (boolean, inherited) The C attribute can be used to force errors to generate warnings (using C) in addition to returning error codes in the normal way. When set "on", any method which results in an error occuring will cause the DBI to effectively do a C where C<$class> is the driver class and C<$method> is the name of the method which failed. E.g., DBD::Oracle::db prepare failed: ... error text here ... By default, Cconnect> sets C "on". If desired, the warnings can be caught and processed using a C<$SIG{__WARN__}> handler or modules like CGI::Carp and CGI::ErrorWrap. =item C (boolean, inherited) The C attribute can be used to force errors to raise exceptions rather than simply return error codes in the normal way. It is "off" by default. When set "on", any method which results in an error will cause the DBI to effectively do a C, where C<$class> is the driver class and C<$method> is the name of the method that failed. E.g., DBD::Oracle::db prepare failed: ... error text here ... If you turn C on then you'd normally turn C off. If C is also on, then the C is done first (naturally). Typically C is used in conjunction with C to catch the exception that's been thrown and followed by an C block to handle the caught exception. In that eval block the $DBI::lasth variable can be useful for diagnosis and reporting. For example, $DBI::lasth->{Type} and $DBI::lasth->{Statement}. If you want to temporarily turn C off (inside a library function that is likely to fail, for example), the recommended way is like this: { local $h->{RaiseError}; # localize and turn off for this block ... } The original value will automatically and reliably be restored by Perl, regardless of how the block is exited. The same logic applies to other attributes, including C. =item C (code ref, inherited) The C attribute can be used to provide your own alternative behaviour in case of errors. If set to a reference to a subroutine then that subroutine is called when an error is detected (at the same point that C and C are handled). The subroutine is called with three parameters: the error message string that C and C would use, the DBI handle being used, and the first value being returned by the method that failed (typically undef). If the subroutine returns a false value then the C and/or C attributes are checked and acted upon as normal. For example, to C with a full stack trace for any error: use Carp; $h->{HandleError} = sub { confess(shift) }; Or to turn errors into exceptions: use Exception; # or your own favourite exception module $h->{HandleError} = sub { Exception->new('DBI')->raise($_[0]) }; It is possible to 'stack' multiple HandleError handlers by using closures: sub your_subroutine { my $previous_handler = $h->{HandleError}; $h->{HandleError} = sub { return 1 if $previous_handler and &$previous_handler(@_); ... your code here ... }; } Using a C inside a subroutine to store the previous C value is important. See L and L for more information about I. It is possible for C to alter the error message that will be used by C and C if it returns false. It can do that by altering the value of $_[0]. This example appends a stack trace to all errors and, unlike the previous example using Carp::confess, this will work C as well as C: $h->{HandleError} = sub { $_[0]=Carp::longmess($_[0]); 0; }; It is also possible for C to hide an error, to a limited degree, by using L to reset $DBI::err and $DBI::errstr, and altering the return value of the failed method. For example: $h->{HandleError} = sub { return 0 unless $_[0] =~ /^\S+ fetchrow_arrayref failed:/; return 0 unless $_[1]->err == 1234; # the error to 'hide' $h->set_err(undef,undef); # turn off the error $_[2] = [ ... ]; # supply alternative return value return 1; }; This only works for methods which return a single value and is hard to make reliable (avoiding infinite loops, for example) and so isn't recommended for general use! If you find a I use for it then please let me know. =item C (code ref, inherited) The C attribute can be used to intercept the setting of handle C, C, and C values. If set to a reference to a subroutine then that subroutine is called whenever set_err() is called, typically by the driver or a subclass. The subroutine is called with five arguments, the first five that were passed to set_err(): the handle, the C, C, and C values being set, and the method name. These can be altered by changing the values in the @_ array. The return value affects set_err() behaviour, see L for details. It is possible to 'stack' multiple HandleSetErr handlers by using closures. See L for an example. The C and C subroutines differ in subtle but significant ways. HandleError is only invoked at the point where the DBI is about to return to the application with C set true. It's not invoked by the failure of a method that's been called by another DBI method. HandleSetErr, on the other hand, is called whenever set_err() is called with a defined C value, even if false. So it's not just for errors, despite the name, but also warn and info states. The set_err() method, and thus HandleSetErr, may be called multiple times within a method and is usually invoked from deep within driver code. In theory a driver can use the return value from HandleSetErr via set_err() to decide whether to continue or not. If set_err() returns an empty list, indicating that the HandleSetErr code has 'handled' the 'error', the driver could then continue instead of failing (if that's a reasonable thing to do). This isn't excepted to be common and any such cases should be clearly marked in the driver documentation and discussed on the dbi-dev mailing list. The C attribute was added in DBI 1.41. =item C (unsigned integer) The C attribute is incremented whenever the set_err() method records an error. It isn't incremented by warnings or information states. It is not reset by the DBI at any time. The C attribute was added in DBI 1.41. Older drivers may not have been updated to use set_err() to record errors and so this attribute may not be incremented when using them. =item C (boolean, inherited) The C attribute can be used to cause the relevant Statement text to be appended to the error messages generated by the C, C, and C attributes. Only applies to errors on statement handles plus the prepare(), do(), and the various C database handle methods. (The exact format of the appended text is subject to change.) If C<$h-E{ParamValues}> returns a hash reference of parameter (placeholder) values then those are formatted and appended to the end of the Statement text in the error message. =item C (integer, inherited) The C attribute can be used as an alternative to the L method to set the DBI trace level and trace flags for a specific handle. See L for more details. =item C (string, inherited) The C attribute is used to specify whether the fetchrow_hashref() method should perform case conversion on the field names used for the hash keys. For historical reasons it defaults to 'C' but it is recommended to set it to 'C' (convert to lower case) or 'C' (convert to upper case) according to your preference. It can only be set for driver and database handles. For statement handles the value is frozen when prepare() is called. =item C (boolean, inherited) The C attribute can be used to control the trimming of trailing space characters from fixed width character (CHAR) fields. No other field types are affected, even where field values have trailing spaces. The default is false (although it is possible that the default may change). Applications that need specific behaviour should set the attribute as needed. Emulation interfaces should set the attribute to match the behaviour of the interface they are emulating. Drivers are not required to support this attribute, but any driver which does not support it must arrange to return C as the attribute value. =item C (unsigned integer, inherited) The C attribute may be used to control the maximum length of 'long' fields ("blob", "memo", etc.) which the driver will read from the database automatically when it fetches each row of data. The C attribute only relates to fetching and reading long values; it is not involved in inserting or updating them. A value of 0 means not to automatically fetch any long data. (C should return C for long fields when C is 0.) The default is typically 0 (zero) bytes but may vary between drivers. Applications fetching long fields should set this value to slightly larger than the longest long field value to be fetched. Some databases return some long types encoded as pairs of hex digits. For these types, C relates to the underlying data length and not the doubled-up length of the encoded string. Changing the value of C for a statement handle after it has been C'd will typically have no effect, so it's common to set C on the C<$dbh> before calling C. For most drivers the value used here has a direct effect on the memory used by the statement handle while it's active, so don't be too generous. If you can't be sure what value to use you could execute an extra select statement to determine the longest value. For example: $dbh->{LongReadLen} = $dbh->selectrow_array{qq{ SELECT MAX(long_column_name) FROM table WHERE ... }); $sth = $dbh->prepare(qq{ SELECT long_column_name, ... FROM table WHERE ... }); You may need to take extra care if the table can be modified between the first select and the second being executed. See L for more information on truncation behaviour. =item C (boolean, inherited) The C attribute may be used to control the effect of fetching a long field value which has been truncated (typically because it's longer than the value of the C attribute). By default, C is false and so fetching a long value that needs to be truncated will cause the fetch to fail. (Applications should always be sure to check for errors after a fetch loop in case an error, such as a divide by zero or long field truncation, caused the fetch to terminate prematurely.) If a fetch fails due to a long field truncation when C is false, many drivers will allow you to continue fetching further rows. See also L. =item C (boolean, inherited) If the C attribute is set to a true value I Perl is running in taint mode (e.g., started with the C<-T> option), then all the arguments to most DBI method calls are checked for being tainted. I The attribute defaults to off, even if Perl is in taint mode. See L for more about taint mode. If Perl is not running in taint mode, this attribute has no effect. When fetching data that you trust you can turn off the TaintIn attribute, for that statement handle, for the duration of the fetch loop. The C attribute was added in DBI 1.31. =item C (boolean, inherited) If the C attribute is set to a true value I Perl is running in taint mode (e.g., started with the C<-T> option), then most data fetched from the database is considered tainted. I The attribute defaults to off, even if Perl is in taint mode. See L for more about taint mode. If Perl is not running in taint mode, this attribute has no effect. When fetching data that you trust you can turn off the TaintOut attribute, for that statement handle, for the duration of the fetch loop. Currently only fetched data is tainted. It is possible that the results of other DBI method calls, and the value of fetched attributes, may also be tainted in future versions. That change may well break your applications unless you take great care now. If you use DBI Taint mode, please report your experience and any suggestions for changes. The C attribute was added in DBI 1.31. =item C (boolean, inherited) The C attribute is a shortcut for L and L (it is also present for backwards compatibility). Setting this attribute sets both L and L, and retrieving it returns a true value if and only if L and L are both set to true values. =item C (inherited) The C attribute enables the collection and reporting of method call timing statistics. See the L module documentation for I more detail. The C attribute was added in DBI 1.24. =item C The DBI provides a way to store extra information in a DBI handle as "private" attributes. The DBI will allow you to store and retrieve any attribute which has a name starting with "C". It is I recommended that you use just I private attribute (e.g., use a hash ref) I give it a long and unambiguous name that includes the module or application name that the attribute relates to (e.g., "C"). Because of the way the Perl tie mechanism works you cannot reliably use the C<||=> operator directly to initialise the attribute, like this: my $foo = $dbh->{private_yourmodname_foo} ||= { ... }; # WRONG you should use a two step approach like this: my $foo = $dbh->{private_yourmodname_foo}; $foo ||= $dbh->{private_yourmodname_foo} = { ... }; This attribute is primarily of interest to people sub-classing DBI. =back =head1 DBI DATABASE HANDLE OBJECTS This section covers the methods and attributes associated with database handles. =head2 Database Handle Methods The following methods are specified for DBI database handles: =over 4 =item C $new_dbh = $dbh->clone(); $new_dbh = $dbh->clone(\%attr); The C method duplicates the $dbh connection by connecting with the same parameters ($dsn, $user, $password) as originally used. The attributes for the cloned connect are the same as those used for the original connect, with some other attribute merged over them depending on the \%attr parameter. If \%attr is given then the attributes it contains are merged into the original attributes and override any with the same names. Effectively the same as doing: %attribues_used = ( %original_attributes, %attr ); If \%attr is not given then it defaults to a hash containing all the attributes in the attribute cache of $dbh excluding any non-code references, plus the main boolean attributes (RaiseError, PrintError, AutoCommit, etc.). This behaviour is subject to change. The clone method can be used even if the database handle is disconnected. The C method was added in DBI 1.33. It is very new and likely to change. =item C @ary = $dbh->data_sources(); @ary = $dbh->data_sources(\%attr); Returns a list of data sources (databases) available via the $dbh driver's data_sources() method, plus any extra data sources that the driver can discover via the connected $dbh. Typically the extra data sources are other databases managed by the same server process that the $dbh is connected to. Data sources are returned in a form suitable for passing to the L method (that is, they will include the "C" prefix). The data_sources() method, for a $dbh, was added in DBI 1.38. =item C $rows = $dbh->do($statement) or die $dbh->errstr; $rows = $dbh->do($statement, \%attr) or die $dbh->errstr; $rows = $dbh->do($statement, \%attr, @bind_values) or die ... Prepare and execute a single statement. Returns the number of rows affected or C on error. A return value of C<-1> means the number of rows is not known, not applicable, or not available. This method is typically most useful for I-C statements because it does not return a statement handle (so you can't fetch any data). The default C method is logically similar to: sub do { my($dbh, $statement, $attr, @bind_values) = @_; my $sth = $dbh->prepare($statement, $attr) or return undef; $sth->execute(@bind_values) or return undef; my $rows = $sth->rows; ($rows == 0) ? "0E0" : $rows; # always return true if no error } For example: my $rows_deleted = $dbh->do(q{ DELETE FROM table WHERE status = ? }, undef, 'DONE') or die $dbh->errstr; Using placeholders and C<@bind_values> with the C method can be useful because it avoids the need to correctly quote any variables in the C<$statement>. But if you'll be executing the statement many times then it's more efficient to C it once and call C many times instead. The C style quoting used in this example avoids clashing with quotes that may be used in the SQL statement. Use the double-quote-like C operator if you want to interpolate variables into the string. See L for more details. =item C $rv = $dbh->last_insert_id($catalog, $schema, $table, $field); $rv = $dbh->last_insert_id($catalog, $schema, $table, $field, \%attr); Returns a value 'identifying' the row just inserted, if possible. Typically this would be a value assigned by the database server to a column with an I or I type. Returns undef if the driver does not support the method or can't determine the value. The $catalog, $schema, $table, and $field parameters may be required for some drivers (see below). If you don't know the parameter values and your driver does not need them, then use C for each. There are several caveats to be aware of with this method if you want to use it for portable applications: B<*> For some drivers the value may only available immediately after the insert statement has executed (e.g., mysql, Informix). B<*> For some drivers the $catalog, $schema, $table, and $field parameters are required (e.g., Pg), for others they are ignored (e.g., mysql). B<*> Drivers may return an indeterminate value if no insert has been performed yet. B<*> For some drivers the value may only be available if placeholders have I been used (e.g., Sybase, MS SQL). In this case the value returned would be from the last non-placeholder insert statement. B<*> Some drivers may need driver-specific hints about how to get the value. For example, being told the name of the database 'sequence' object that holds the value. Any such hints are passed as driver-specific attributes in the \%attr parameter. B<*> If the underlying database offers nothing better, then some drivers may attempt to implement this method by executing "C statements. If a row cache is not implemented, then setting C is ignored and getting the value returns C. Some C values have special meaning, as follows: 0 - Automatically determine a reasonable cache size for each C. Note that large cache sizes may require a very large amount of memory (I). Also, a large cache will cause a longer delay not only for the first fetch, but also whenever the cache needs refilling. See also the L statement handle attribute. =item C (string) Returns the username used to connect to the database. =back =head1 DBI STATEMENT HANDLE OBJECTS This section lists the methods and attributes associated with DBI statement handles. =head2 Statement Handle Methods The DBI defines the following methods for use on DBI statement handles: =over 4 =item C $sth->bind_param($p_num, $bind_value) $sth->bind_param($p_num, $bind_value, \%attr) $sth->bind_param($p_num, $bind_value, $bind_type) The C method takes a copy of $bind_value and associates it (binds it) with a placeholder, identified by $p_num, embedded in the prepared statement. Placeholders are indicated with question mark character (C). For example: $dbh->{RaiseError} = 1; # save having to check each method call $sth = $dbh->prepare("SELECT name, age FROM people WHERE name LIKE ?"); $sth->bind_param(1, "John%"); # placeholders are numbered from 1 $sth->execute; DBI::dump_results($sth); See L for more information. B The C<\%attr> parameter can be used to hint at the data type the placeholder should have. Typically, the driver is only interested in knowing if the placeholder should be bound as a number or a string. $sth->bind_param(1, $value, { TYPE => SQL_INTEGER }); As a short-cut for the common case, the data type can be passed directly, in place of the C<\%attr> hash reference. This example is equivalent to the one above: $sth->bind_param(1, $value, SQL_INTEGER); The C value indicates the standard (non-driver-specific) type for this parameter. To specify the driver-specific type, the driver may support a driver-specific attribute, such as C<{ ora_type =E 97 }>. The SQL_INTEGER and other related constants can be imported using use DBI qw(:sql_types); See L for more information. The data type for a placeholder cannot be changed after the first C call. In fact the whole \%attr parameter is 'sticky' in the sense that a driver only needs to consider the \%attr parameter for the first call, for a given $sth and parameter. After that the driver may ignore the \%attr parameter for that placeholder. Perl only has string and number scalar data types. All database types that aren't numbers are bound as strings and must be in a format the database will understand except where the bind_param() TYPE attribute specifies a type that implies a particular format. For example, given: $sth->bind_param(1, $value, SQL_DATETIME); the driver should expect $value to be in the ODBC standard SQL_DATETIME format, which is 'YYYY-MM-DD HH:MM:SS'. Similarly for SQL_DATE, SQL_TIME etc. As an alternative to specifying the data type in the C call, you can let the driver pass the value as the default type (C). You can then use an SQL function to convert the type within the statement. For example: INSERT INTO price(code, price) VALUES (?, CONVERT(MONEY,?)) The C function used here is just an example. The actual function and syntax will vary between different databases and is non-portable. See also L for more information. =item C $rc = $sth->bind_param_inout($p_num, \$bind_value, $max_len) or die $sth->errstr; $rv = $sth->bind_param_inout($p_num, \$bind_value, $max_len, \%attr) or ... $rv = $sth->bind_param_inout($p_num, \$bind_value, $max_len, $bind_type) or ... This method acts like L, but also enables values to be updated by the statement. The statement is typically a call to a stored procedure. The C<$bind_value> must be passed as a reference to the actual value to be used. Note that unlike L, the C<$bind_value> variable is not copied when C is called. Instead, the value in the variable is read at the time L is called. The additional C<$max_len> parameter specifies the minimum amount of memory to allocate to C<$bind_value> for the new value. If the value returned from the database is too big to fit, then the execution should fail. If unsure what value to use, pick a generous length, i.e., a length larger than the longest value that would ever be returned. The only cost of using a larger value than needed is wasted memory. It is expected that few drivers will support this method. The only driver currently known to do so is DBD::Oracle (DBD::ODBC may support it in a future release). Therefore it should not be used for database independent applications. Undefined values or C are used to indicate null values. See also L for more information. =item C $rc = $sth->bind_param_array($p_num, $array_ref_or_value) $rc = $sth->bind_param_array($p_num, $array_ref_or_value, \%attr) $rc = $sth->bind_param_array($p_num, $array_ref_or_value, $bind_type) The C method is used to bind an array of values to a placeholder embedded in the prepared statement which is to be executed with L. For example: $dbh->{RaiseError} = 1; # save having to check each method call $sth = $dbh->prepare("INSERT INTO staff (first_name, last_name, dept) VALUES(?, ?, ?)"); $sth->bind_param_array(1, [ 'John', 'Mary', 'Tim' ]); $sth->bind_param_array(2, [ 'Booth', 'Todd', 'Robinson' ]); $sth->bind_param_array(3, "SALES"); # scalar will be reused for each row $sth->execute_array( { ArrayTupleStatus => \my @tuple_status } ); The C<%attr> ($bind_type) argument is the same as defined for L. Refer to L for general details on using placeholders. (Note that bind_param_array() can I be used to expand a placeholder into a list of values for a statement like "SELECT foo WHERE bar IN (?)". A placeholder can only ever represent one value per execution.) Each array bound to the statement must have the same number of elements. Some drivers may define a method attribute to relax this safety check. Scalar values, including C, may also be bound by C. In which case the same value will be used for each L call. Driver-specific implementations may behave differently, e.g., when binding to a stored procedure call, some databases may permit mixing scalars and arrays as arguments. The default implementation provided by DBI (for drivers that have not implemented array binding) is to iteratively call L for each parameter tuple provided in the bound arrays. Drivers may provide more optimized implementations using whatever bulk operation support the database API provides. The default driver behaviour should match the default DBI behaviour, but always consult your driver documentation as there may be driver specific issues to consider. Note that the default implementation currently only supports non-data returning statements (insert, update, but not select). Also, C and L cannot be mixed in the same statement execution, and C must be used with L; using C will have no effect for L. The C method was added in DBI 1.22. =item C $rv = $sth->execute or die $sth->errstr; $rv = $sth->execute(@bind_values) or die $sth->errstr; Perform whatever processing is necessary to execute the prepared statement. An C is returned if an error occurs. A successful C always returns true regardless of the number of rows affected, even if it's zero (see below). It is always important to check the return status of C (and most other DBI methods) for errors if you're not using L. For a I-C statements, execute simply "starts" the query within the database engine. Use one of the fetch methods to retrieve the data after calling C. The C method does I return the number of rows that will be returned by the query (because most databases can't tell in advance), it simply returns a true value. If any arguments are given, then C will effectively call L for each value before executing the statement. Values bound in this way are usually treated as C types unless the driver can determine the correct type (which is rare), or unless C (or C) has already been used to specify the type. If execute() is called on a statement handle that's still active ($sth->{Active} is true) then it should effectively call finish() to tidy up the previous execution results before starting this new execution. =item C $rv = $sth->execute_array(\%attr) or die $sth->errstr; $rv = $sth->execute_array(\%attr, @bind_values) or die $sth->errstr; Execute the prepared statement once for each parameter tuple (group of values) provided either in the @bind_values, or by prior calls to L, or via a reference passed in \%attr. The execute_array() method returns the number of tuples executed, or C if an error occured. Like execute(), a successful execute_array() always returns true regardless of the number of tuples executed, even if it's zero. See the C attribute below for how to determine the execution status for each tuple. Bind values for the tuples to be executed may be supplied by an C attribute, or else in the C<@bind_values> argument, or else by prior calls to L. The C attribute can be used to specify a reference to a subroutine that will be called to provide the bind values for each tuple execution. The subroutine should return an reference to an array which contains the appropriate number of bind values, or return an undef if there is no more data to execute. As a convienience, the C attribute can also be used to specify a statement handle. In which case the fetchrow_arrayref() method will be called on the given statement handle in order to provide the bind values for each tuple execution. The values specified via bind_param_array() or the @bind_values parameter may be either scalars, or arrayrefs. If any C<@bind_values> are given, then C will effectively call L for each value before executing the statement. Values bound in this way are usually treated as C types unless the driver can determine the correct type (which is rare), or unless C, C, C, or C has already been used to specify the type. See L for details. The mandatory C attribute is used to specify a reference to an array which will receive the execute status of each executed parameter tuple. For tuples which are successfully executed, the element at the same ordinal position in the status array is the resulting rowcount. If the execution of a tuple causes an error, then the corresponding status array element will be set to a reference to an array containing the error code and error string set by the failed execution. If B tuple execution returns an error, C will return C. In that case, the application should inspect the status array to determine which parameter tuples failed. Some databases may not continue executing tuples beyond the first failure. In this case the status array will either hold fewer elements, or the elements beyond the failure will be undef. If all parameter tuples are successfully executed, C returns the number tuples executed. If no tuples were executed, then execute_array() returns "C<0E0>", just like execute() does, which Perl will treat as 0 but will regard as true. For example: $sth = $dbh->prepare("INSERT INTO staff (first_name, last_name) VALUES (?, ?)"); my $tuples = $sth->execute_array( { ArrayTupleStatus => \my @tuple_status }, \@first_names, \@last_names, ); if ($tuples) { print "Successfully inserted $tuples records\n"; } else { for my $tuple (0..@last_names-1) { my $status = $tuple_status[$tuple]; $status = [0, "Skipped"] unless defined $status; next unless ref $status; printf "Failed to insert (%s, %s): %s\n", $first_names[$tuple], $last_names[$tuple], $status->[1]; } } Support for data returning statements, i.e., select, is driver-specific and subject to change. At present, the default implementation provided by DBI only supports non-data returning statements. Transaction semantics when using array binding are driver and database specific. If C is on, the default DBI implementation will cause each parameter tuple to be inidividually committed (or rolled back in the event of an error). If C is off, the application is responsible for explicitly committing the entire set of bound parameter tuples. Note that different drivers and databases may have different behaviours when some parameter tuples cause failures. In some cases, the driver or database may automatically rollback the effect of all prior parameter tuples that succeeded in the transaction; other drivers or databases may retain the effect of prior successfully executed parameter tuples. Be sure to check your driver and database for its specific behaviour. Note that, in general, performance will usually be better with C turned off, and using explicit C after each C call. The C method was added in DBI 1.22, and ArrayTupleFetch was added in 1.36. =item C $rc = $sth->execute_for_fetch($fetch_tuple_sub); $rc = $sth->execute_for_fetch($fetch_tuple_sub, \@tuple_status); The execute_for_fetch() method is used to perform bulk operations and is most often used via the execute_array() method, not directly. The fetch subroutine, referenced by $fetch_tuple_sub, is expected to return a reference to an array (known as a 'tuple') or undef. The execute_for_fetch() method calls $fetch_tuple_sub, without any parameters, until it returns a false value. Each tuple returned is used to provide bind values for an $sth->execute(@$tuple) call. The number of tuples executed is returned I there were no errors. If there were any errors then C is returned and the @tuple_status array can be used to discover which tuples failed and with what errors. If \@tuple_status is passed then the execute_for_fetch method uses it to return status information. The tuple_status array holds one element per tuple. If the corresponding execute() did not fail then the element holds the return value from execute(), which is typically a row count. If the execute() did fail then the element holds a reference to an array containing ($sth->err, $sth->errstr, $sth->state). Although each tuple returned by $fetch_tuple_sub is effectively used to call $sth->execute(@$tuple_array_ref) the exact timing may vary. Drivers are free to accumulate sets of tuples to pass to the database server in bulk group operations for more efficient execution. However, the $fetch_tuple_sub is specifically allowed to return the same array reference each time (which is what fetchrow_arrayref() usually does). For example: my $sel = $dbh1->prepare("select foo, bar from table1"); $sel->execute; my $ins = $dbh2->prepare("insert into table2 (foo, bar) values (?,?)"); my $fetch_tuple_sub = sub { $sel->fetchrow_arrayref }; my @tuple_status; $rc = $ins->execute_for_fetch($fetch_tuple_sub, \@tuple_status); my @errors = grep { ref $_ } @tuple_status; Similarly, if you already have an array containing the data rows to be processed you'd use a subroutine to shift off and return each array ref in turn: $ins->execute_for_fetch( sub { shift @array_of_arrays }, \@tuple_status); The C method was added in DBI 1.38. =item C $ary_ref = $sth->fetchrow_arrayref; $ary_ref = $sth->fetch; # alias Fetches the next row of data and returns a reference to an array holding the field values. Null fields are returned as C values in the array. This is the fastest way to fetch data, particularly if used with C<$sth-Ebind_columns>. If there are no more rows or if an error occurs, then C returns an C. You should check C<$sth-Eerr> afterwards (or use the C attribute) to discover if the C returned was due to an error. Note that the same array reference is returned for each fetch, so don't store the reference and then use it after a later fetch. Also, the elements of the array are also reused for each row, so take care if you want to take a reference to an element. See also L. =item C @ary = $sth->fetchrow_array; An alternative to C. Fetches the next row of data and returns it as a list containing the field values. Null fields are returned as C values in the list. If there are no more rows or if an error occurs, then C returns an empty list. You should check C<$sth-Eerr> afterwards (or use the C attribute) to discover if the empty list returned was due to an error. If called in a scalar context for a statement handle that has more than one column, it is undefined whether the driver will return the value of the first column or the last. So don't do that. Also, in a scalar context, an C is returned if there are no more rows or if an error occurred. That C can't be distinguished from an C returned because the first field value was NULL. For these reasons you should exercise some caution if you use C in a scalar context. =item C $hash_ref = $sth->fetchrow_hashref; $hash_ref = $sth->fetchrow_hashref($name); An alternative to C. Fetches the next row of data and returns it as a reference to a hash containing field name and field value pairs. Null fields are returned as C values in the hash. If there are no more rows or if an error occurs, then C returns an C. You should check C<$sth-Eerr> afterwards (or use the C attribute) to discover if the C returned was due to an error. The optional C<$name> parameter specifies the name of the statement handle attribute. For historical reasons it defaults to "C", however using either "C" or "C" is recomended for portability. The keys of the hash are the same names returned by C<$sth-E{$name}>. If more than one field has the same name, there will only be one entry in the returned hash for those fields. Because of the extra work C and Perl have to perform, it is not as efficient as C or C. Currently, a new hash reference is returned for each row. I in the future to return the same hash ref each time, so don't rely on the current behaviour. =item C $tbl_ary_ref = $sth->fetchall_arrayref; $tbl_ary_ref = $sth->fetchall_arrayref( $slice ); $tbl_ary_ref = $sth->fetchall_arrayref( $slice, $max_rows ); The C method can be used to fetch all the data to be returned from a prepared and executed statement handle. It returns a reference to an array that contains one reference per row. If there are no rows to return, C returns a reference to an empty array. If an error occurs, C returns the data fetched thus far, which may be none. You should check C<$sth-Eerr> afterwards (or use the C attribute) to discover if the data is complete or was truncated due to an error. If $slice is an array reference, C uses L to fetch each row as an array ref. If the $slice array is not empty then it is used as a slice to select individual columns by perl array index number (starting at 0, unlike column and parameter numbers which start at 1). With no parameters, or if $slice is undefined, C acts as if passed an empty array ref. If $slice is a hash reference, C uses L to fetch each row as a hash reference. If the $slice hash is empty then fetchrow_hashref() is simply called in a tight loop and the keys in the hashes have whatever name lettercase is returned by default from fetchrow_hashref. (See L attribute.) If the $slice hash is not empty, then it is used as a slice to select individual columns by name. The values of the hash should be set to 1. The key names of the returned hashes match the letter case of the names in the parameter hash, regardless of the L attribute. For example, to fetch just the first column of every row: $tbl_ary_ref = $sth->fetchall_arrayref([0]); To fetch the second to last and last column of every row: $tbl_ary_ref = $sth->fetchall_arrayref([-2,-1]); To fetch all fields of every row as a hash ref: $tbl_ary_ref = $sth->fetchall_arrayref({}); To fetch only the fields called "foo" and "bar" of every row as a hash ref (with keys named "foo" and "BAR"): $tbl_ary_ref = $sth->fetchall_arrayref({ foo=>1, BAR=>1 }); The first two examples return a reference to an array of array refs. The third and forth return a reference to an array of hash refs. If $max_rows is defined and greater than or equal to zero then it is used to limit the number of rows fetched before returning. fetchall_arrayref() can then be called again to fetch more rows. This is especially useful when you need the better performance of fetchall_arrayref() but don't have enough memory to fetch and return all the rows in one go. Here's an example: my $rows = []; # cache for batches of rows while( my $row = ( shift(@$rows) || # get row from cache, or reload cache: shift(@{$rows=$sth->fetchall_arrayref(undef,10_000)||[]) ) ) { ... } That is the fastest way to fetch and process lots of rows using the DBI. =item C $hash_ref = $sth->fetchall_hashref($key_field); The C method can be used to fetch all the data to be returned from a prepared and executed statement handle. It returns a reference to a hash that contains, at most, one entry per row. If there are no rows to return, C returns a reference to an empty hash. If an error occurs, C returns the data fetched thus far, which may be none. You should check C<$sth-Eerr> afterwards (or use the C attribute) to discover if the data is complete or was truncated due to an error. The $key_field parameter provides the name of the field that holds the value to be used for the key for the returned hash. For example: $dbh->{FetchHashKeyName} = 'NAME_lc'; $sth = $dbh->prepare("SELECT FOO, BAR, ID, NAME, BAZ FROM TABLE"); $sth->execute; $hash_ref = $sth->fetchall_hashref('id'); print "Name for id 42 is $hash_ref->{42}->{name}\n"; The $key_field parameter can also be specified as an integer column number (counting from 1). If $key_field doesn't match any column in the statement, as a name first then as a number, then an error is returned. This method is normally used only where the key field value for each row is unique. If multiple rows are returned with the same value for the key field then later rows overwrite earlier ones. =item C $rc = $sth->finish; Indicate that no more data will be fetched from this statement handle before it is either executed again or destroyed. The C method is rarely needed, and frequently overused, but can sometimes be helpful in a few very specific situations to allow the server to free up resources (such as sort buffers). When all the data has been fetched from a C C (for some specific operations like C and C), or after fetching all the rows of a C statements, it is generally not possible to know how many rows will be returned except by fetching them all. Some drivers will return the number of rows the application has fetched so far, but others may return -1 until all rows have been fetched. So use of the C method or C<$DBI::rows> with C is to execute a "SELECT COUNT(*) FROM ..." SQL statement with the same "..." as your query and then fetch the row count from that. =item C $rc = $sth->bind_col($column_number, \$var_to_bind); $rc = $sth->bind_col($column_number, \$var_to_bind, \%attr ); $rc = $sth->bind_col($column_number, \$var_to_bind, $bind_type ); Binds a Perl variable and/or some attributes to an output column (field) of a C statement. The C method will die if the number of references does not match the number of fields. For maximum portability between drivers, bind_columns() should be called after execute() and not before. For example: $dbh->{RaiseError} = 1; # do this, or check every call for errors $sth = $dbh->prepare(q{ SELECT region, sales FROM sales_by_region }); $sth->execute; my ($region, $sales); # Bind Perl variables to columns: $rv = $sth->bind_columns(\$region, \$sales); # you can also use Perl's \(...) syntax (see perlref docs): # $sth->bind_columns(\($region, $sales)); # Column binding is the most efficient way to fetch data while ($sth->fetch) { print "$region: $sales\n"; } For compatibility with old scripts, the first parameter will be ignored if it is C or a hash reference. Here's a more fancy example that binds columns to the values I a hash (thanks to H.Merijn Brand): $sth->execute; my %row; $sth->bind_columns( \( @row{ @{$sth->{NAME_lc} } } )); while ($sth->fetch) { print "$row{region}: $row{sales}\n"; } =item C $rows = $sth->dump_results($maxlen, $lsep, $fsep, $fh); Fetches all the rows from C<$sth>, calls C for each row, and prints the results to C<$fh> (defaults to C) separated by C<$lsep> (default C<"\n">). C<$fsep> defaults to C<", "> and C<$maxlen> defaults to 35. This method is designed as a handy utility for prototyping and testing queries. Since it uses L to format and edit the string for reading by humans, it is not recomended for data transfer applications. =back =head2 Statement Handle Attributes This section describes attributes specific to statement handles. Most of these attributes are read-only. Changes to these statement handle attributes do not affect any other existing or future statement handles. Attempting to set or get the value of an unknown attribute is I, except for private driver specific attributes (which all have names starting with a lowercase letter). Example: ... = $h->{NUM_OF_FIELDS}; # get/read Some drivers cannot provide valid values for some or all of these attributes until after C<$sth-Eexecute> has been successfully called. Typically the attribute will be C in these situations. Some attributes, like NAME, are not appropriate to some types of statement, like SELECT. Typically the attribute will be C in these situations. See also L to learn more about the effect it may have on some attributes. =over 4 =item C (integer, read-only) Number of fields (columns) in the data the prepared statement may return. Statements that don't return rows of data, like C and C set C to 0. =item C (integer, read-only) The number of parameters (placeholders) in the prepared statement. See SUBSTITUTION VARIABLES below for more details. =item C (array-ref, read-only) Returns a reference to an array of field names for each column. The names may contain spaces but should not be truncated or have any trailing space. Note that the names have the letter case (upper, lower or mixed) as returned by the driver being used. Portable applications should use L or L. print "First column name: $sth->{NAME}->[0]\n"; =item C (array-ref, read-only) Like L but always returns lowercase names. =item C (array-ref, read-only) Like L but always returns uppercase names. =item C (hash-ref, read-only) =item C (hash-ref, read-only) =item C (hash-ref, read-only) The C, C, and C attributes return column name information as a reference to a hash. The keys of the hash are the names of the columns. The letter case of the keys corresponds to the letter case returned by the C, C, and C attributes respectively (as described above). The value of each hash entry is the perl index number of the corresponding column (counting from 0). For example: $sth = $dbh->prepare("select Id, Name from table"); $sth->execute; @row = $sth->fetchrow_array; print "Name $row[ $sth->{NAME_lc_hash}{name} ]\n"; =item C (array-ref, read-only) Returns a reference to an array of integer values for each column. The value indicates the data type of the corresponding column. The values correspond to the international standards (ANSI X3.135 and ISO/IEC 9075) which, in general terms, means ODBC. Driver-specific types that don't exactly match standard types should generally return the same values as an ODBC driver supplied by the makers of the database. That might include private type numbers in ranges the vendor has officially registered with the ISO working group: ftp://sqlstandards.org/SC32/SQL_Registry/ Where there's no vendor-supplied ODBC driver to be compatible with, the DBI driver can use type numbers in the range that is now officially reserved for use by the DBI: -9999 to -9000. All possible values for C should have at least one entry in the output of the C method (see L). =item C (array-ref, read-only) Returns a reference to an array of integer values for each column. For numeric columns, the value is the maximum number of digits (without considering a sign character or decimal point). Note that the "display size" for floating point types (REAL, FLOAT, DOUBLE) can be up to 7 characters greater than the precision (for the sign + decimal point + the letter E + a sign + 2 or 3 digits). For any character type column the value is the OCTET_LENGTH, in other words the number of bytes, not characters. (More recent standards refer to this as COLUMN_SIZE but we stick with PRECISION for backwards compatibility.) =item C (array-ref, read-only) Returns a reference to an array of integer values for each column. NULL (C) values indicate columns where scale is not applicable. =item C (array-ref, read-only) Returns a reference to an array indicating the possibility of each column returning a null. Possible values are C<0> (or an empty string) = no, C<1> = yes, C<2> = unknown. print "First column may return NULL\n" if $sth->{NULLABLE}->[0]; =item C (string, read-only) Returns the name of the cursor associated with the statement handle, if available. If not available or if the database driver does not support the C<"where current of ..."> SQL syntax, then it returns C. =item C (dbh, read-only) Returns the parent $dbh of the statement handle. =item C (hash ref, read-only) Returns a reference to a hash containing the values currently bound to placeholders. The keys of the hash are the 'names' of the placeholders, typically integers starting at 1. Returns undef if not supported by the driver. See L for an example of how this is used. If the driver supports C but no values have been bound yet then the driver should return a hash with placeholders names in the keys but all the values undef, but some drivers may return a ref to an empty hash. It is possible that the values in the hash returned by C are not exactly the same as those passed to bind_param() or execute(). The driver may have modified the values in some way based on the TYPE the value was bound with. For example a floating point value bound as an SQL_INTEGER type may be returned as an integer. It is also possible that the keys in the hash returned by C are not exactly the same as those implied by the prepared statement. For example, DBD::Oracle translates 'C' placeholders into 'C<:pN>' where N is a sequence number starting at 1. The C attribute was added in DBI 1.28. =item C (string, read-only) Returns the statement string passed to the L method. =item C (integer, read-only) If the driver supports a local row cache for C statement handle that's a child of the same database handle. A typical way round this is to connect the the database twice and use one connection for C statement (unlike other data types), some special handling is required. In this situation, the value of the C<$h-E{LongReadLen}> attribute is used to determine how much buffer space to allocate when fetching such fields. The C<$h-E{LongTruncOk}> attribute is used to determine how to behave if a fetched value can't fit into the buffer. See the description of L for more information. When trying to insert long or binary values, placeholders should be used since there are often limits on the maximum size of an C statement and the L method generally can't cope with binary data. See L. =head2 Simple Examples Here's a complete example program to select and fetch some data: my $data_source = "dbi::DriverName:db_name"; my $dbh = DBI->connect($data_source, $user, $password) or die "Can't connect to $data_source: $DBI::errstr"; my $sth = $dbh->prepare( q{ SELECT name, phone FROM mytelbook }) or die "Can't prepare statement: $DBI::errstr"; my $rc = $sth->execute or die "Can't execute statement: $DBI::errstr"; print "Query will return $sth->{NUM_OF_FIELDS} fields.\n\n"; print "Field names: @{ $sth->{NAME} }\n"; while (($name, $phone) = $sth->fetchrow_array) { print "$name: $phone\n"; } # check for problems which may have terminated the fetch early die $sth->errstr if $sth->err; $dbh->disconnect; Here's a complete example program to insert some data from a file. (This example uses C to avoid needing to check each call). my $dbh = DBI->connect("dbi:DriverName:db_name", $user, $password, { RaiseError => 1, AutoCommit => 0 }); my $sth = $dbh->prepare( q{ INSERT INTO table (name, phone) VALUES (?, ?) }); open FH, ") { chomp; my ($name, $phone) = split /,/; $sth->execute($name, $phone); } close FH; $dbh->commit; $dbh->disconnect; Here's how to convert fetched NULLs (undefined values) into empty strings: while($row = $sth->fetchrow_arrayref) { # this is a fast and simple way to deal with nulls: foreach (@$row) { $_ = '' unless defined } print "@$row\n"; } The C style quoting used in these examples avoids clashing with quotes that may be used in the SQL statement. Use the double-quote like C operator if you want to interpolate variables into the string. See L for more details. =head2 Threads and Thread Safety Perl 5.7 and later support a new threading model called iThreads. (The old "5.005 style" threads are not supported by the DBI.) In the iThreads model each thread has it's own copy of the perl interpreter. When a new thread is created the original perl interpreter is 'cloned' to create a new copy for the new thread. If the DBI and drivers are loaded and handles created before the thread is created then it will get a cloned copy of the DBI, the drivers and the handles. However, the internal pointer data within the handles will refer to the DBI and drivers in the original interpreter. Using those handles in the new interpreter thread is not safe, so the DBI detects this and croaks on any method call using handles that don't belong to the current thread (except for DESTROY). Because of this (possibly temporary) restriction, newly created threads must make their own connctions to the database. Handles can't be shared across threads. But BEWARE, some underlying database APIs (the code the DBD driver uses to talk to the database, often supplied by the database vendor) are not thread safe. If it's not thread safe, then allowing more than one thread to enter the code at the same time may cause subtle/serious problems. In some cases allowing more than one thread to enter the code, even if I at the same time, can cause problems. You have been warned. Using DBI with perl threads is not yet recommended for production environments. For more information see L Note: There is a bug in perl 5.8.2 when configured with threads and debugging enabled (bug #24463) which causes a DBI test to fail. =head2 Signal Handling and Canceling Operations [The following only applies to systems with unix-like signal handling. I'd welcome additions for other systems, especially Windows.] The first thing to say is that signal handling in Perl versions less than 5.8 is I safe. There is always a small risk of Perl crashing and/or core dumping when, or after, handling a signal because the signal could arrive and be handled while internal data structures are being changed. If the signal handling code used those same internal data structures it could cause all manner of subtle and not-so-subtle problems. The risk was reduced with 5.4.4 but was still present in all perls up through 5.8.0. Beginning in perl 5.8.0 perl implements 'safe' signal handling if your system has the POSIX sigaction() routine. Now when a signal is delivered perl just makes a note of it but does I run the %SIG handler. The handling is 'defered' until a 'safe' moment. Although this change made signal handling safe, it also lead to a problem with signals being defered for longer than you'd like. If a signal arrived while executing a system call, such as waiting for data on a network connection, the signal is noted and then the system call that was executing returns with an EINTR error code to indicate that it was interrupted. All fine so far. The problem comes when the code that made the system call sees the EINTR code and decides it's going to call it again. Perl doesn't do that, but database code sometimes does. If that happens then the signal handler doesn't get called untill later. Maybe much later. Fortunately there are ways around this which we'll discuss below. Unfortunately they make signals unsafe again. The two most common uses of signals in relation to the DBI are for canceling operations when the user types Ctrl-C (interrupt), and for implementing a timeout using C and C<$SIG{ALRM}>. =over 4 =item Cancel The DBI provides a C method for statement handles. The C method should abort the current operation and is designed to be called from a signal handler. For example: $SIG{INT} = sub { $sth->cancel }; However, few drivers implement this (the DBI provides a default method that just returns C) and, even if implemented, there is still a possibility that the statement handle, and even the parent database handle, will not be usable afterwards. If C returns true, then it has successfully invoked the database engine's own cancel function. If it returns false, then C failed. If it returns C, then the database driver does not have cancel implemented. =item Timeout The traditional way to implement a timeout is to set C<$SIG{ALRM}> to refer to some code that will be executed when an ALRM signal arrives and then to call alarm($seconds) to schedule an ALRM signal to be delivered $seconds in the future. For example: eval { local $SIG{ALRM} = sub { die "TIMEOUT\n" }; alarm($seconds); ... code to execute with timeout here ... alarm(0); # cancel alarm (if code ran fast) }; alarm(0); # cancel alarm (if eval failed) if ( $@ eq "TIMEOUT" ) { ... } Unfortunately, as described above, this won't always work as expected, depending on your perl version and the underlying database code. With Oracle for instance (DBD::Oracle), if the system which hosts the database is down the DBI->connect() call will hang for several minutes before returning an error. =back The solution on these systems is to use the C routine to gain low level access to how the signal handler is installed. The code would look something like this (for the DBD-Oracle connect()): use POSIX ':signal_h'; my $mask = POSIX::SigSet->new( SIGALRM ); # signals to mask in the handler my $action = POSIX::SigAction->new( sub { die "connect timeout" }, # the handler code ref $mask, # not using (perl 5.8.2 and later) 'safe' switch or sa_flags ); my $oldaction = POSIX::SigAction->new(); sigaction( 'ALRM', $action, $oldaction ); my $dbh; eval { alarm(5); # seconds before time out $dbh = DBI->connect("dbi:Oracle:$dsn" ... ); alarm(0); # cancel alarm (if connect worked fast) }; alarm(0); # cancel alarm (if eval failed) sigaction( 'ALRM', $oldaction ); # restore original signal handler if ( $@ ) .... Similar techniques can be used for canceling statement execution. Unfortunately, this solution is somewhat messy, and it does I work with perl versions less than perl 5.8 where C appears to be broken. For a cleaner implementation that works across perl versions, see Lincoln Baxter's Sys::SigAction module at L. The documentation for Sys::SigAction includes an longer discussion of this problem, and a DBD::Oracle test script. Be sure to read all the signal handling sections of the L manual. And finally, two more points to keep firmly in mind. Firstly, remember that what we've done here is essentially revert to old style I handling of these signals. So do as little as possible in the handler. Ideally just die(). Secondly, the handles in use at the time the signal is handled may not be safe to use afterwards. =head2 Subclassing the DBI DBI can be subclassed and extended just like any other object oriented module. Before we talk about how to do that, it's important to be clear about how the DBI classes and how they work together. By default C<$dbh = DBI-Econnect(...)> returns a $dbh blessed into the C class. And the C<$dbh-Eprepare> method returns an $sth blessed into the C class (actually it simply changes the last four characters of the calling handle class to be C<::st>). The leading 'C' is known as the 'root class' and the extra 'C<::db>' or 'C<::st>' are the 'handle type suffixes'. If you want to subclass the DBI you'll need to put your overriding methods into the appropriate classes. For example, if you want to use a root class of C and override the do(), prepare() and execute() methods, then your do() and prepare() methods should be in the C class and the execute() method should be in the C class. To setup the inheritance hierarchy the @ISA variable in C should include C and the @ISA variable in C should include C. The C root class itself isn't currently used for anything visible and so, apart from setting @ISA to include C, it should be left empty. So, having put your overriding methods into the right classes, and setup the inheritance hierarchy, how do you get the DBI to use them? You have two choices, either a static method call using the name of your subclass: $dbh = MySubDBI->connect(...); or specifying a C attribute: $dbh = DBI->connect(..., { RootClass => 'MySubDBI' }); The only difference between the two is that using an explicit RootClass attribute will make the DBI automatically attempt to load a module by that name if the class doesn't exist. If both forms are used then the attribute takes precedence. When subclassing is being used then, after a successful new connect, the DBI->connect method automatically calls: $dbh->connected($dsn, $user, $pass, \%attr); The default method does nothing. The call is made just to simplify any post-connection setup that your subclass may want to perform. If your subclass supplies a connected method, it should be part of the MySubDBI::db package. Here's a brief example of a DBI subclass. A more thorough example can be found in t/subclass.t in the DBI distribution. package MySubDBI; use strict; use DBI; use vars qw(@ISA); @ISA = qw(DBI); package MySubDBI::db; use vars qw(@ISA); @ISA = qw(DBI::db); sub prepare { my ($dbh, @args) = @_; my $sth = $dbh->SUPER::prepare(@args) or return; $sth->{private_mysubdbi_info} = { foo => 'bar' }; return $sth; } package MySubDBI::st; use vars qw(@ISA); @ISA = qw(DBI::st); sub fetch { my ($sth, @args) = @_; my $row = $sth->SUPER::fetch(@args) or return; do_something_magical_with_row_data($row) or return $sth->set_err(1234, "The magic failed", undef, "fetch"); return $row; } When calling a SUPER::method that returns a handle, be careful to check the return value before trying to do other things with it in your overridden method. This is especially important if you want to set a hash attribute on the handle, as Perl's autovivification will bite you by (in)conveniently creating an unblessed hashref, which your method will then return with usually baffling results later on. It's best to check right after the call and return undef immediately on error, just like DBI would and just like the example above. If your method needs to record an error it should call the set_err() method with the error code and error string, as shown in the example above. The error code and error string will be recorded in the handle and available via C<$h-Eerr> and C<$DBI::errstr> etc. The set_err() method always returns an undef or empty list as approriate. Since your method should nearly always return an undef or empty list as soon as an error is detected it's handy to simply return what set_err() returns, as shown in the example above. If the handle has C, C, or C etc. set then the set_err() method will honour them. This means that if C is set then set_err() won't return in the normal way but will 'throw an exception' that can be caught with an C block. You can stash private data into DBI handles via C<$h-E{private_..._*}>. See the entry under L for info and important caveats. =head1 TRACING The DBI has a powerful tracing mechanism built in. It enables you to see what's going on 'behind the scenes', both within the DBI and the drivers you're using. =head2 Trace Settings Which details are written to the trace output is controlled by a combination of a I, an integer from 0 to 15, and a set of I that are either on or off. Together these are known as the I and are stored together in a single integer. For normal use you only need to set the trace level, and generally only to a value between 1 and 4. Each handle has it's own trace settings, and so does the DBI. When you call a method the DBI merges the handles settings into its own for the duration of the call: the trace flags of the handle are OR'd into the trace flags of the DBI, and if the handle has a higher trace level then the DBI trace level is raised to match it. The previous DBI trace setings are restored when the called method returns. =head1 Enabling Trace The C<$h-Etrace> method sets the trace settings for a handle and Ctrace> does the same for the DBI. In addition to the L method, you can enable the same trace information, and direct the output to a file, by setting the C environment variable before starting Perl. See L for more information. Finally, you can set, or get, the trace settings for a handle using the C attribute. =head2 Trace Levels Trace levels are as follows: 0 - Trace disabled. 1 - Trace DBI method calls returning with results or errors. 2 - Trace method entry with parameters and returning with results. 3 - As above, adding some high-level information from the driver and some internal information from the DBI. 4 - As above, adding more detailed information from the driver. 5 and above - As above but with more and more obscure information. Trace level 1 is best for a simple overview of what's happening. Trace level 2 is a good choice for general purpose tracing. Levels 3 and above are best reserved for investigating a specific problem, when you need to see "inside" the driver and DBI. The trace output is detailed and typically very useful. Much of the trace output is formatted using the L function, so strings in the trace output may be edited and truncated by that function. =head2 Trace Output Initially trace output is written to C. Both the C<$h-Etrace> and Ctrace> methods take an optional $trace_filename parameter. If specified, and can be opened in append mode, then I trace output (currently including that from other handles) is redirected to that file. A warning is generated if the file can't be opened. Further calls to trace() without a $trace_filename do not alter where the trace output is sent. If $trace_filename is undefined, then trace output is sent to C and the previous trace file is closed. Currently $trace_filename can't be a filehandle. But meanwhile you can use the special strings C<"STDERR"> and C<"STDOUT"> to select those filehandles. =head2 Tracing Tips You can add tracing to your own application code using the L method. It can sometimes be handy to compare trace files from two different runs of the same script. However using a tool like C doesn't work well because the trace file is full of object addresses that may differ each run. Here's a handy little command to strip those out: perl -pe 's/\b0x[\da-f]{6,}/0xNNNN/gi; s/\b[\da-f]{6,}//gi' =head1 DBI ENVIRONMENT VARIABLES The DBI module recognizes a number of environment variables, but most of them should not be used most of the time. It is better to be explicit about what you are doing to avoid the need for environment variables, especially in a web serving system where web servers are stingy about which environment variables are available. =head2 DBI_DSN The DBI_DSN environment variable is used by DBI->connect if you do not specify a data source when you issue the connect. It should have a format such as "dbi:Driver:databasename". =head2 DBI_DRIVER The DBI_DRIVER environment variable is used to fill in the database driver name in DBI->connect if the data source string starts "dbi::" (thereby omitting the driver). If DBI_DSN omits the driver name, DBI_DRIVER can fill the gap. =head2 DBI_AUTOPROXY The DBI_AUTOPROXY environment variable takes a string value that starts "dbi:Proxy:" and is typically followed by "hostname=...;port=...". It is used to alter the behaviour of DBI->connect. For full details, see DBI::Proxy documentation. =head2 DBI_USER The DBI_USER environment variable takes a string value that is used as the user name if the DBI->connect call is given undef (as distinct from an empty string) as the username argument. Be wary of the security implications of using this. =head2 DBI_PASS The DBI_PASS environment variable takes a string value that is used as the password if the DBI->connect call is given undef (as distinct from an empty string) as the password argument. Be extra wary of the security implications of using this. =head2 DBI_DBNAME (obsolete) The DBI_DBNAME environment variable takes a string value that is used only when the obsolescent style of DBI->connect (with driver name as fourth parameter) is used, and when no value is provided for the first (database name) argument. =head2 DBI_TRACE The DBI_TRACE environment variable specifies the global default trace settings for the DBI at startup. Can also be used to direct trace output to a file. When the DBI is loaded it does: DBI->trace(split '=', $ENV{DBI_TRACE}, 2) if $ENV{DBI_TRACE}; So if C contains an "C<=>" character then what follows it is used as the name of the file to append the trace to. output appended to that file. If the name begins with a number followed by an equal sign (C<=>), then the number and the equal sign are stripped off from the name, and the number is used to set the trace level. For example: DBI_TRACE=1=dbitrace.log perl your_test_script.pl On Unix-like systems using a Bourne-like shell, you can do this easily on the command line: DBI_TRACE=2 perl your_test_script.pl See L for more information. =head2 PERL_DBI_DEBUG (obsolete) An old variable that should no longer be used; equivalent to DBI_TRACE. =head2 DBI_PROFILE The DBI_PROFILE environment variable can be used to enable profiling of DBI method calls. See for more information. =head2 DBI_PUREPERL The DBI_PUREPERL environment variable can be used to enable the use of DBI::PurePerl. See for more information. =head1 WARNING AND ERROR MESSAGES =head2 Fatal Errors =over 4 =item Can't call method "prepare" without a package or object reference The C<$dbh> handle you're using to call C is probably undefined because the preceding C failed. You should always check the return status of DBI methods, or use the L attribute. =item Can't call method "execute" without a package or object reference The C<$sth> handle you're using to call C is probably undefined because the preceeding C failed. You should always check the return status of DBI methods, or use the L attribute. =item DBI/DBD internal version mismatch The DBD driver module was built with a different version of DBI than the one currently being used. You should rebuild the DBD module under the current version of DBI. (Some rare platforms require "static linking". On those platforms, there may be an old DBI or DBD driver version actually embedded in the Perl executable being used.) =item DBD driver has not implemented the AutoCommit attribute The DBD driver implementation is incomplete. Consult the author. =item Can't [sg]et %s->{%s}: unrecognised attribute You attempted to set or get an unknown attribute of a handle. Make sure you have spelled the attribute name correctly; case is significant (e.g., "Autocommit" is not the same as "AutoCommit"). =back =head1 Pure-Perl DBI A pure-perl emulation of the DBI is included in the distribution for people using pure-perl drivers who, for whatever reason, can't install the compiled DBI. See L. =head1 SEE ALSO =head2 Driver and Database Documentation Refer to the documentation for the DBD driver that you are using. Refer to the SQL Language Reference Manual for the database engine that you are using. =head2 ODBC and SQL/CLI Standards Reference Information More detailed information about the semantics of certain DBI methods that are based on ODBC and SQL/CLI standards is available on-line via microsoft.com, for ODBC, and www.jtc1sc32.org for the SQL/CLI standard: DBI method ODBC function SQL/CLI Working Draft ---------- ------------- --------------------- column_info SQLColumns Page 124 foreign_key_info SQLForeignKeys Page 163 get_info SQLGetInfo Page 214 primary_key_info SQLPrimaryKeys Page 254 table_info SQLTables Page 294 type_info SQLGetTypeInfo Page 239 For example, for ODBC information on SQLColumns you'd visit: http://msdn.microsoft.com/library/en-us/odbc/htm/odbcsqlcolumns.asp If that URL ceases to work then use the MSDN search facility at: http://search.microsoft.com/us/dev/ and search for C using the exact phrase option. The link you want will probably just be called C and will be part of the Data Access SDK. And for SQL/CLI standard information on SQLColumns you'd read page 124 of the (very large) SQL/CLI Working Draft available from: http://www.jtc1sc32.org/sc32/jtc1sc32.nsf/Attachments/7E3B41486BD99C3488256B410064C877/$FILE/32N0744T.PDF =head2 SQL Standards Reference Information A hyperlinked, browsable version of the BNF syntax for SQL92 (plus Oracle 7 SQL and PL/SQL) is available here: http://cui.unige.ch/db-research/Enseignement/analyseinfo/SQL92/BNFindex.html A BNF syntax for SQL3 is available here: http://www.sqlstandards.org/SC32/WG3/Progression_Documents/Informal_working_drafts/iso-9075-2-1999.bnf The following links provide further useful information about SQL. Some of these are rather dated now but may still be useful. http://www.jcc.com/SQLPages/jccs_sql.htm http://www.contrib.andrew.cmu.edu/~shadow/sql.html http://www.altavista.com/query?q=sql+tutorial =head2 Books and Articles Programming the Perl DBI, by Alligator Descartes and Tim Bunce. L Programming Perl 3rd Ed. by Larry Wall, Tom Christiansen & Jon Orwant. L Learning Perl by Randal Schwartz. L Details of many other books related to perl can be found at L =head2 Perl Modules Index of DBI related modules available from CPAN: http://search.cpan.org/search?mode=module&query=DBIx%3A%3A http://search.cpan.org/search?mode=doc&query=DBI For a good comparison of RDBMS-OO mappers and some OO-RDBMS mappers (including Class::DBI, Alzabo, and DBIx::RecordSet in the former category and Tangram and SPOPS in the latter) see the Perl Object-Oriented Persistence project pages at: http://poop.sourceforge.net A similar page for Java toolkits can be found at: http://c2.com/cgi-bin/wiki?ObjectRelationalToolComparison =head2 Manual Pages L, L, L =head2 Mailing List The I mailing list is the primary means of communication among users of the DBI and its related modules. For details send email to: dbi-users-help@perl.org There are typically between 700 and 900 messages per month. You have to subscribe in order to be able to post. However you can opt for a 'post-only' subscription. Mailing list archives (of variable quality) are held at: http://www.xray.mpe.mpg.de/mailing-lists/dbi/ http://groups.yahoo.com/group/dbi-users http://www.bitmechanic.com/mail-archives/dbi-users/ http://marc.theaimsgroup.com/?l=perl-dbi&r=1&w=2 http://www.mail-archive.com/dbi-users%40perl.org/ =head2 Assorted Related WWW Links The DBI "Home Page": http://dbi.perl.org/ Other DBI related links: http://tegan.deltanet.com/~phlip/DBUIdoc.html http://dc.pm.org/perl_db.html http://wdvl.com/Authoring/DB/Intro/toc.html http://www.hotwired.com/webmonkey/backend/tutorials/tutorial1.html http://bumppo.net/lists/macperl/1999/06/msg00197.html http://gmax.oltrelinux.com/dbirecipes.html Other database related links: http://www.jcc.com/sql_stnd.html http://cuiwww.unige.ch/OSG/info/FreeDB/FreeDB.home.html Security, especially the "SQL Injection" attack: http://www.ngssoftware.com/research/papers.html http://www.ngssoftware.com/papers/advanced_sql_injection.pdf http://www.ngssoftware.com/papers/more_advanced_sql_injection.pdf http://www.esecurityplanet.com/trends/article.php/2243461 http://www.spidynamics.com/papers/SQLInjectionWhitePaper.pdf http://www.webcohort.com/Blindfolded_SQL_Injection.pdf http://online.securityfocus.com/infocus/1644 Commercial and Data Warehouse Links http://www.dwinfocenter.org http://www.datawarehouse.com http://www.datamining.org http://www.olapcouncil.org http://www.idwa.org http://www.knowledgecenters.org/dwcenter.asp Recommended Perl Programming Links http://language.perl.com/style/ =head2 FAQ Please also read the DBI FAQ which is installed as a DBI::FAQ module. You can use I to read it by executing the C command. =head1 AUTHORS DBI by Tim Bunce. This pod text by Tim Bunce, J. Douglas Dunlop, Jonathan Leffler and others. Perl by Larry Wall and the C. =head1 COPYRIGHT The DBI module is Copyright (c) 1994-2003 Tim Bunce. Ireland. All rights reserved. You may distribute under the terms of either the GNU General Public License or the Artistic License, as specified in the Perl README file. =head1 ACKNOWLEDGEMENTS I would like to acknowledge the valuable contributions of the many people I have worked with on the DBI project, especially in the early years (1992-1994). In no particular order: Kevin Stock, Buzz Moschetti, Kurt Andersen, Ted Lemon, William Hails, Garth Kennedy, Michael Peppler, Neil S. Briscoe, Jeff Urlwin, David J. Hughes, Jeff Stander, Forrest D Whitcher, Larry Wall, Jeff Fried, Roy Johnson, Paul Hudson, Georg Rehfeld, Steve Sizemore, Ron Pool, Jon Meek, Tom Christiansen, Steve Baumgarten, Randal Schwartz, and a whole lot more. Then, of course, there are the poor souls who have struggled through untold and undocumented obstacles to actually implement DBI drivers. Among their ranks are Jochen Wiedmann, Alligator Descartes, Jonathan Leffler, Jeff Urlwin, Michael Peppler, Henrik Tougaard, Edwin Pratomo, Davide Migliavacca, Jan Pazdziora, Peter Haworth, Edmund Mergl, Steve Williams, Thomas Lowery, and Phlip Plumlee. Without them, the DBI would not be the practical reality it is today. I'm also especially grateful to Alligator Descartes for starting work on the first edition of the "Programming the Perl DBI" book and letting me jump on board. The DBI and DBD::Oracle were originally developed while I was Technical Director (CTO) of the Paul Ingram Group (www.ig.co.uk). So I'd especially like to thank Paul for his generosity and vision in supporting this work for many years. =head1 CONTRIBUTING As you can see above, many people have contributed to the DBI and drivers in many ways over many years. If you'd like the DBI to do something new or different the best way to make that happen is to do it yourself and send me a patch to the source code that shows the changes. =head2 How to create a patch using Subversion The DBI source code is maintained using Subversion (a replacement for CVS, see L). To access the source you'll need to install a Subversion client. Then, to get the source code, do: svn checkout http://svn.perl.org/modules/dbi/trunk If it prompts for a username and password use your perl.org account if you have one, else just 'guest' and 'guest'. The source code will be in a new subdirectory called C. To keep informed about changes to the source you can send an empty email to dbi-changes@perl.org after which you'll get an email with the change log message and diff of each change checked-in to the source. After making your changes you can generate a patch file, but before you do, make sure your source is still upto date using: svn update http://svn.perl.org/modules/dbi/trunk If you get any conflicts reported you'll need to fix them first. Then generate the patch file from within the C directory using: svn diff > foo.patch Read the patch file, as a sanity check, and then email it to dbi-dev@perl.org. =head2 How to create a patch without Subversion Unpack a fresh copy of the distribution: tar xfz DBI-1.40.tar.gz Rename the newly created top level directory: mv DBI-1.40 DBI-1.40.your_foo Edit the contents of DBI-1.40.your_foo/* till it does what you want. Test your changes and then remove all temporary files: make test && make distclean Go back to the directory you originally unpacked the distribution: cd .. Unpack I copy of the original distribution you started with: tar xfz DBI-1.40.tar.gz Then create a patch file by performing a recursive C on the two top level directories: diff -r -u DBI-1.40 DBI-1.40.your_foo > DBI-1.40.your_foo.patch =head2 Speak before you patch For anything non-trivial or possibly controversial it's a good idea to discuss (on dbi-dev@perl.org) the changes you propose before actually spending time working on them. Otherwise you run the risk of them being rejected because they don't fit into some larger plans you may not be aware of. =head1 TRANSLATIONS A German translation of this manual (possibly slightly out of date) is available, thanks to O'Reilly, at: http://www.oreilly.de/catalog/perldbiger/ Some other translations: http://cronopio.net/perl/ - Spanish http://member.nifty.ne.jp/hippo2000/dbimemo.htm - Japanese =head1 SUPPORT / WARRANTY The DBI is free software. IT COMES WITHOUT WARRANTY OF ANY KIND. Commercial support for Perl and the DBI, DBD::Oracle and Oraperl modules can be arranged via The Perl Clinic. For more details visit: http://www.perlclinic.com For direct DBI and DBD::Oracle support, enhancement, and related work I am available for consultancy on standard commercial terms. =head1 TRAINING References to DBI related training resources. No recommendation implied. http://www.treepax.co.uk/ http://www.keller.com/dbweb/ =head1 FREQUENTLY ASKED QUESTIONS See the DBI FAQ for a more comprehensive list of FAQs. Use the C command to read it. =head2 How fast is the DBI? To measure the speed of the DBI and DBD::Oracle code, I modified DBD::Oracle so you can set an attribute that will cause the same row to be fetched from the row cache over and over again (without involving Oracle code but exercising *all* the DBI and DBD::Oracle code in the code path for a fetch). The results (on my lightly loaded old Sparc 10) fetching 50000 rows using: 1 while $csr->fetch; were: one field: 5300 fetches per cpu second (approx) ten fields: 4000 fetches per cpu second (approx) Obviously results will vary between platforms (newer faster platforms can reach around 50000 fetches per second), but it does give a feel for the maximum performance: fast. By way of comparison, using the code: 1 while @row = $csr->fetchrow_array; (C is roughly the same as C) gives: one field: 3100 fetches per cpu second (approx) ten fields: 1000 fetches per cpu second (approx) Notice the slowdown and the more dramatic impact of extra fields. (The fields were all one char long. The impact would be even bigger for longer strings.) Changing that slightly to represent actually doing something in Perl with the fetched data: while(@row = $csr->fetchrow_array) { $hash{++$i} = [ @row ]; } gives: ten fields: 500 fetches per cpu second (approx) That simple addition has *halved* the performance. I therefore conclude that DBI and DBD::Oracle overheads are small compared with Perl language overheads (and probably database overheads). So, if you think the DBI or your driver is slow, try replacing your fetch loop with just: 1 while $csr->fetch; and time that. If that helps then point the finger at your own code. If that doesn't help much then point the finger at the database, the platform, the network etc. But think carefully before pointing it at the DBI or your driver. (Having said all that, if anyone can show me how to make the DBI or drivers even more efficient, I'm all ears.) =head2 Why doesn't my CGI script work right? Read the information in the references below. Please do I post CGI related questions to the I mailing list (or to me). http://www.perl.com/cgi-bin/pace/pub/doc/FAQs/cgi/perl-cgi-faq.html http://www3.pair.com/webthing/docs/cgi/faqs/cgifaq.shtml http://www-genome.wi.mit.edu/WWW/faqs/www-security-faq.html http://www.boutell.com/faq/ http://www.perl.com/perl/faq/ =head2 How can I maintain a WWW connection to a database? For information on the Apache httpd server and the C module see http://perl.apache.org/ =head2 What about ODBC? A DBD::ODBC driver module for ODBC is available and works well. =head2 Does the DBI have a year 2000 problem? No. The DBI has no knowledge or understanding of dates at all. Individual drivers (DBD::*) may have some date handling code but are unlikely to have year 2000 related problems within their code. However, your application code which I the DBI and DBD drivers may have year 2000 related problems if it has not been designed and written well. See also the "Does Perl have a year 2000 problem?" section of the Perl FAQ: http://www.perl.com/CPAN/doc/FAQs/FAQ/PerlFAQ.html =head1 OTHER RELATED WORK AND PERL MODULES =over 4 =item Apache::DBI by E.Mergl@bawue.de To be used with the Apache daemon together with an embedded Perl interpreter like C. Establishes a database connection which remains open for the lifetime of the HTTP daemon. This way the CGI connect and disconnect for every database access becomes superfluous. =item JDBC Server by Stuart 'Zen' Bishop zen@bf.rmit.edu.au The server is written in Perl. The client classes that talk to it are of course in Java. Thus, a Java applet or application will be able to comunicate via the JDBC API with any database that has a DBI driver installed. The URL used is in the form C. It seems to be very similar to some commercial products, such as jdbcKona. =item Remote Proxy DBD support As of DBI 1.02, a complete implementation of a DBD::Proxy driver and the DBI::ProxyServer are part of the DBI distribution. =item SQL Parser See also the SQL::Statement module, SQL parser and engine. =back =cut