DBI
DBI
package DBI;
require 5.008_001;
BEGIN {
$VERSION = "1.625"; # ==> ALSO update the version in the pod text below!
}
=head1 NAME
=head1 SYNOPSIS
use DBI;
@driver_names = DBI->available_drivers;
%drivers = DBI->installed_drivers;
@data_sources = DBI->data_sources($driver_name, \%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);
$rv = $sth->execute;
$rv = $sth->execute(@bind_values);
$rv = $sth->execute_array(\%attr, ...);
@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 );
$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<The synopsis above only lists the major methods and parameters.>
=head3 General
To help you make the best use of the dbi-users mailing list,
and any other lists or forums you may use, I recommend that you read
"Getting Answers" by Mike Ash: L<http://mikeash.com/getting_answers.html>.
If you have questions about DBI, or DBD driver modules, you can get
help from the I<[email protected]> mailing list. This is the best way to get
help. You don't have to subscribe to the list in order to post, though I'd
recommend it. You can get help on subscribing and using the list by emailing
I<[email protected]>.
Please note that Tim Bunce does not maintain the mailing lists or the
web pages (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<dbi-users> mailing list has lots of experienced
people who should be able to help you if you need it. If you do email
Tim he is very likely to just forward it to the mailing list.
=head3 Online
Your problem is most likely related to the specific DBD driver module you're
using. If that's the case then click on the 'Bugs' link on the
L<http://metacpan.org>
page for your driver. Only submit a bug report against the DBI itself if you're
sure that your issue isn't related to the driver you're using.
=head2 NOTES
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 is 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.
=cut
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_BIGINT
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
DBIstcf_DISCARD_STRING
DBIstcf_STRICT
) ],
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 $neat_maxlen dump_results looks_like_number
data_string_diff data_string_desc data_diff sql_type_cast
) ],
profile => [ qw(
dbi_profile dbi_profile_merge dbi_profile_merge_nodes dbi_time
) ], # notionally "in" DBI::Profile and normally imported from there
);
# 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;
}
Exporter::export_ok_tags(keys %EXPORT_TAGS);
use strict;
my $dbd_prefix_registry = {
ad_ => { class => 'DBD::AnyData', },
ado_ => { class => 'DBD::ADO', },
amzn_ => { class => 'DBD::Amazon', },
best_ => { class => 'DBD::BestWins', },
csv_ => { class => 'DBD::CSV', },
cubrid_ => { class => 'DBD::cubrid', },
db2_ => { class => 'DBD::DB2', },
dbi_ => { class => 'DBI', },
dbm_ => { class => 'DBD::DBM', },
df_ => { class => 'DBD::DF', },
f_ => { class => 'DBD::File', },
file_ => { class => 'DBD::TextFile', },
go_ => { class => 'DBD::Gofer', },
ib_ => { class => 'DBD::InterBase', },
ing_ => { class => 'DBD::Ingres', },
ix_ => { class => 'DBD::Informix', },
jdbc_ => { class => 'DBD::JDBC', },
mo_ => { class => 'DBD::MO', },
monetdb_ => { class => 'DBD::monetdb', },
msql_ => { class => 'DBD::mSQL', },
mvsftp_ => { class => 'DBD::MVS_FTPSQL', },
mysql_ => { class => 'DBD::mysql', },
mx_ => { class => 'DBD::Multiplex', },
nullp_ => { class => 'DBD::NullP', },
odbc_ => { class => 'DBD::ODBC', },
ora_ => { class => 'DBD::Oracle', },
pg_ => { class => 'DBD::Pg', },
pgpp_ => { class => 'DBD::PgPP', },
plb_ => { class => 'DBD::Plibdata', },
po_ => { class => 'DBD::PO', },
proxy_ => { class => 'DBD::Proxy', },
ram_ => { class => 'DBD::RAM', },
rdb_ => { class => 'DBD::RDB', },
sapdb_ => { class => 'DBD::SAP_DB', },
snmp_ => { class => 'DBD::SNMP', },
solid_ => { class => 'DBD::Solid', },
spatialite_ => { class => 'DBD::Spatialite', },
sponge_ => { class => 'DBD::Sponge', },
sql_ => { class => 'DBI::DBD::SqlEngine', },
sqlite_ => { class => 'DBD::SQLite', },
syb_ => { class => 'DBD::Sybase', },
sys_ => { class => 'DBD::Sys', },
tdat_ => { class => 'DBD::Teradata', },
tmpl_ => { class => 'DBD::Template', },
tmplss_ => { class => 'DBD::TemplateSS', },
tree_ => { class => 'DBD::TreeData', },
tuber_ => { class => 'DBD::Tuber', },
uni_ => { class => 'DBD::Unify', },
vt_ => { class => 'DBD::Vt', },
wmi_ => { class => 'DBD::WMI', },
x_ => { }, # for private use
xbase_ => { class => 'DBD::XBase', },
xl_ => { class => 'DBD::Excel', },
yaswi_ => { class => 'DBD::Yaswi', },
};
sub dump_dbd_registry {
require Data::Dumper;
local $Data::Dumper::Sortkeys=1;
local $Data::Dumper::Indent=1;
print Data::Dumper->Dump([$dbd_prefix_registry], [qw($dbd_prefix_registry)]);
}
my $keeperr = { O=>0x0004 };
{
package DBI::common;
@DBI::dr::ISA = ('DBI::common');
@DBI::db::ISA = ('DBI::common');
@DBI::st::ISA = ('DBI::common');
}
END {
return unless defined &DBI::trace_msg; # return unless bootstrap'd ok
local ($!,$?);
DBI->trace_msg(sprintf(" -- DBI::END (\$\@: %s, \$!: %s)\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 {
_clone_dbis() unless $DBI::PurePerl; # clone the DBIS structure
DBI->trace_msg("CLONE DBI for new thread\n");
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
}
sub parse_dsn {
my ($class, $dsn) = @_;
$dsn =~ s/^(dbi):(\w*?)(?:\((.*?)\))?://i or return;
my ($scheme, $driver, $attr, $attr_hash) = (lc($1), $2, $3);
$driver ||= $ENV{DBI_DRIVER} || '';
$attr_hash = { split /\s*=>?\s*|\s*,\s*/, $attr, -1 } if $attr;
return ($scheme, $driver, $attr, $attr_hash, $dsn);
}
sub visit_handles {
my ($class, $code, $outer_info) = @_;
$outer_info = {} if not defined $outer_info;
my %drh = DBI->installed_drivers;
for my $h (values %drh) {
my $child_info = $code->($h, $outer_info)
or next;
$h->visit_child_handles($code, $child_info);
}
return $outer_info;
}
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) = @_;
my $dbi_connect_method = ($DBI::connect_via eq "Apache::DBI::connect")
? 'Apache::DBI::connect' : 'connect_cached';
$attr = {
$attr ? %$attr : (), # clone, don't modify callers data
dbi_connect_method => $dbi_connect_method,
};
return $class->connect($dsn, $user, $pass, $attr);
}
sub connect {
my $class = shift;
my ($dsn, $user, $pass, $attr, $old_driver) = my @orig_args = @_;
my $driver;
my $connect_meth = $attr->{dbi_connect_method};
$connect_meth ||= $DBI::connect_via; # fallback to default
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);
# 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' "
."because I can't work out what driver to use "
."(it doesn't seem to contain a 'dbi:driver:' prefix "
."and the DBI_DRIVER env var is not set)");
my $proxy;
if ($ENV{DBI_AUTOPROXY} && $driver ne 'Proxy' && $driver ne 'Sponge' && $driver
ne 'Switch') {
my $dbi_autoproxy = $ENV{DBI_AUTOPROXY};
$proxy = 'Proxy';
if ($dbi_autoproxy =~ s/^dbi:(\w*?)(?:\((.*?)\))?://i) {
$proxy = $1;
$driver_attrib_spec = join ",",
($driver_attrib_spec) ? $driver_attrib_spec : (),
($2 ) ? $2 : ();
}
$dsn = "$dbi_autoproxy;dsn=dbi:$driver:$dsn";
$driver = $proxy;
DBI->trace_msg(" DBI_AUTOPROXY: dbi:$driver($driver_attrib_spec):$dsn\
n");
}
# avoid recursion if proxy calls DBI->connect itself
local $ENV{DBI_AUTOPROXY} if $ENV{DBI_AUTOPROXY};
my $connect_closure = sub {
my ($old_dbh, $override_attr) = @_;
#use Data::Dumper;
#warn "connect_closure: ".Data::Dumper::Dumper([$attr,\%attributes,
$override_attr]);
my $dbh;
unless ($dbh = $drh->$connect_meth($dsn, $user, $pass, $attr)) {
$user = '' if !defined $user;
$dsn = '' if !defined $dsn;
# $drh->errstr isn't safe here because $dbh->DESTROY may not have
# been called yet and so the dbh errstr would not have been copied
# up to the drh errstr. Certainly true for connect_cached!
my $errstr = $DBI::errstr;
# Getting '(no error string)' here is a symptom of a ref loop
$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
}
# merge any attribute overrides but don't change $attr itself (for closure)
my $apply = { ($override_attr) ? (%$attr, %$override_attr ) : %$attr };
if (%$apply) {
if ($apply->{DbTypeSubclass}) {
my $DbTypeSubclass = delete $apply->{DbTypeSubclass};
DBI::_rebless_dbtype_subclass($dbh, $rebless_class||$class,
$DbTypeSubclass);
}
my $a;
foreach $a (qw(Profile RaiseError PrintError AutoCommit)) { # do these
first
next unless exists $apply->{$a};
$dbh->{$a} = delete $apply->{$a};
}
while ( my ($a, $v) = each %$apply) {
eval { $dbh->{$a} = $v }; # assign in void context to avoid re-FETCH
warn $@ if $@;
}
}
return $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;
}
}
# already installed
return $drh if $drh = $DBI::installed_drh{$driver};
$DBI::installed_drh{$driver} = $drh;
$class->trace_msg(" <- install_driver= $drh\n") if $DBI::dbi_debug & 0xF;
$drh;
}
sub setup_driver {
my ($class, $driver_class) = @_;
my $h_type;
foreach $h_type (qw(dr db st)){
my $h_class = $driver_class."::$h_type";
no strict 'refs';
push @{"${h_class}::ISA"}, "DBD::_::$h_type"
unless UNIVERSAL::isa($h_class, "DBD::_::$h_type");
# The _mem class stuff is (IIRC) a crufty hack for global destruction
# timing issues in early versions of perl5 and possibly no longer needed.
my $mem_class = "DBD::_mem::$h_type";
push @{"${h_class}_mem::ISA"}, $mem_class
unless UNIVERSAL::isa("${h_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) = @_;
# determine the db type names for class hierarchy
my @hierarchy = DBI::_dbtype_names($dbh, $DbTypeSubclass);
# 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]);
}
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", 2);
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", 2);
eval { require "$module.pm"; };
return 1 unless $@;
return 0 if $missing_ok && $@ =~ /^Can't locate \Q$module.pm\E/;
die $@;
}
*internal = \&DBD::Switch::dr::driver;
sub driver_prefix {
my ($class, $driver) = @_;
return $dbd_class_registry{$driver}->{prefix} if exists
$dbd_class_registry{$driver};
return;
}
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);
}
sub installed_versions {
my ($class, $quiet) = @_;
my %error;
my %version;
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;
}
$version{"DBI"} = $DBI::VERSION;
$version{"DBI::PurePerl"} = $DBI::PurePerl::VERSION if $DBI::PurePerl;
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 data_diff {
my ($a, $b, $logical) = @_;
my $a_desc = data_string_desc($a);
my $b_desc = data_string_desc($b);
return "" if !$diff and $a_desc eq $b_desc;
sub data_string_diff {
# Compares 'logical' characters, not bytes, so a latin1 string and an
# an equivalent Unicode string will compare as equal even though their
# byte encodings are different.
my ($a, $b) = @_;
unless (defined $a and defined $b) { # one undef
return ""
if !defined $a and !defined $b;
return "String a is undef, string b has ".length($b)." characters"
if !defined $a;
return "String b is undef, string a has ".length($a)." characters"
if !defined $b;
}
require utf8;
# hack to cater for perl 5.6
*utf8::is_utf8 = sub { (DBI::neat(shift)=~/^"/) } unless defined
&utf8::is_utf8;
our $shared_profile;
sub _new_drh { # called by DBD::<drivername>::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);
# --------------------------------------------------------------------
# === The internal DBI Switch pseudo 'driver' class ===
$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 ===
*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::carp("method name prefix '$prefix' is not associated with a registered
driver") unless $reg_info;
my $full_method = "DBI::${subtype}::$method";
$DBI::installed_methods{$full_method} = $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 0x00000200 if $name eq 'CON';
return 0x00000400 if $name eq 'ENC';
return 0x00000800 if $name eq 'DBD';
return 0x00001000 if $name eq 'TXN';
return;
}
sub private_attribute_info {
return undef;
}
sub visit_child_handles {
my ($h, $code, $info) = @_;
$info = {} if not defined $info;
for my $ch (@{ $h->{ChildHandles} || []}) {
next unless $ch;
my $child_info = $code->($ch, $info)
or next;
$ch->visit_child_handles($code, $child_info);
}
return $info;
}
}
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_cached {
my $drh = shift;
my ($dsn, $user, $auth, $attr) = @_;
$dbh = $drh->connect(@_);
$cache->{$key} = $dbh; # replace prev entry, even if connect failed
return $dbh;
}
sub clone {
my ($old_dbh, $attr) = @_;
my $closure = $old_dbh->{dbi_connect_closure}
or return $old_dbh->set_err($DBI::stderr, "Can't clone handle");
unless ($attr) { # XXX deprecated, caller should always pass a hash ref
# 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 AutoInactiveDestroy
LongTruncOk PrintError PrintWarn Profile RaiseError
ShowErrorStatement TaintIn TaintOut
));
}
sub quote_identifier {
my ($dbh, @id) = @_;
my $attr = (@id > 3 && ref($id[-1])) ? pop @id : undef;
my $quote = $info->[0];
foreach (@id) { # quote the elements
next unless defined;
s/$quote/$quote$quote/g; # escape embedded quotes
$_ = qq{$quote$_$quote};
}
sub quote {
my ($dbh, $str, $data_type) = @_;
return "NULL" unless defined $str;
unless ($data_type) {
$str =~ s/'/''/g; # ISO SQL2
return "'$str'";
}
my $lp = $prefixes->{$data_type};
my $ls = $suffixes->{$data_type};
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 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 0 < $max-- && $sth->fetch;
}
else {
push @col, @values while $sth->fetch;
}
return \@col;
}
sub prepare_cached {
my ($dbh, $statement, $attr, $if_active) = @_;
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;
}
return $sth;
}
sub ping {
my $dbh = shift;
# "0 but true" is a special kind of true 0 that is used here so
# applications can check if the ping was a real ping or not
($dbh->FETCH('Active')) ? "0 but true" : 0;
}
sub begin_work {
my $dbh = shift;
return $dbh->set_err($DBI::stderr, "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 data_sources {
my ($dbh, @other) = @_;
my $drh = $dbh->{Driver}; # XXX proxy issues?
return $drh->data_sources(@other);
}
#
# ********************************************************
#
# 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) = @_;
$$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($DBI::stderr, "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}) {
return $sth->set_err($DBI::stderr, "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;
$attr = shift if !defined $_[0] or ref($_[0]) eq 'HASH';
my $idx = 0;
$sth->bind_col(++$idx, shift, $attr) or return
while (@_ and $idx < $fields);
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
my $fetch_tuple_sub;
if ($fetch_tuple_sub = $attr->{ArrayTupleFetch}) { # fetch on demand
return $sth->set_err($DBI::stderr,
"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($DBI::stderr,
"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($DBI::stderr,
"$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($DBI::stderr, "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($DBI::stderr,
"$NUM_OF_PARAMS_given bind values supplied but $NUM_OF_PARAMS
expected")
if defined($NUM_OF_PARAMS) && $NUM_OF_PARAMS != $NUM_OF_PARAMS_given;
my $tuple_idx = 0;
$fetch_tuple_sub = sub {
return if $tuple_idx >= $maxlen;
my @tuple = map {
my $a = $hash_of_arrays{$_};
ref($a) ? $a->[$tuple_idx] : $a
} @bind_ids;
++$tuple_idx;
return \@tuple;
};
}
# pass thru the callers scalar or list context
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 $rc_total = 0;
my $err_count;
while ( my $tuple = &$fetch_tuple_sub() ) {
if ( my $rc = $sth->execute(@$tuple) ) {
push @$tuple_status, $rc;
$rc_total = ($rc >= 0 && $rc_total >= 0) ? $rc_total + $rc : -1;
}
else {
$err_count++;
push @$tuple_status, [ $sth->err, $sth->errstr, $sth->state ];
# XXX drivers implementing execute_for_fetch could opt to "last;"
here
# if they know the error code means no further executes will work.
}
}
my $tuples = @$tuple_status;
return $sth->set_err($DBI::stderr, "executing $tuples generated $err_count
errors")
if $err_count;
$tuples ||= "0E0";
return $tuples unless wantarray;
return ($tuples, $rc_total);
}
if ($mode eq 'ARRAY') {
my $row;
# 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) {
push @rows, [ @$row ]
while($max_rows-- and $row = $sth->fetch);
}
else {
push @rows, [ @$row ] while($row = $sth->fetch);
}
return \@rows
}
my %row;
if ($mode eq 'REF' && ref($$slice) eq 'HASH') { # \{ $idx => $name }
keys %$$slice; # reset the iterator
while ( my ($idx, $name) = each %$$slice ) {
$sth->bind_col($idx+1, \$row{$name});
}
}
elsif ($mode eq 'HASH') {
if (keys %$slice) {
keys %$slice; # reset the iterator
my $name2idx = $sth->FETCH('NAME_lc_hash');
while ( my ($name, $unused) = each %$slice ) {
my $idx = $name2idx->{lc $name};
return $sth->set_err($DBI::stderr, "Invalid column name '$name'
for slice")
if not defined $idx;
$sth->bind_col($idx+1, \$row{$name});
}
}
else {
$sth->bind_columns( \( @row{ @{$sth->FETCH($sth-
>FETCH('FetchHashKeyName')) } } ) );
}
}
else {
return $sth->set_err($DBI::stderr, "fetchall_arrayref($mode) invalid");
}
return \@rows;
}
sub fetchall_hashref {
my ($sth, $key_field) = @_;
*dump_results = \&DBI::dump_results;
sub more_results {
shift->{syb_more_results}; # handy grandfathering
}
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.
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.
Note that Perl will automatically destroy database and statement handle objects
if all references to them are deleted.
To use DBI,
first you need to load the DBI module:
use DBI;
use strict;
Then you need to L</connect> to your data source and get a I<handle> for that
connection:
prepare,
execute, fetch, fetch, ...
execute, fetch, fetch, ...
execute, fetch, fetch, ...
for example:
$sth->execute( $baz );
prepare,
execute,
execute,
execute.
for example:
while(<CSV>) {
chomp;
my ($foo,$bar,$baz) = split /,/;
$sth->execute( $foo, $bar, $baz );
}
The C<do()> method can be used for non repeated I<non>-C<SELECT> statement
(or with drivers that don't support placeholders):
Finally, when you have finished working with the data source, you should
L</disconnect> from it:
$dbh->disconnect;
The DBI does not have a concept of a "current session". Every session
has a handle object (i.e., a C<$dbh>) returned from the C<connect> method.
That handle object is used to invoke database related methods.
Most data is returned to the Perl script as strings. (Null values are
returned as C<undef>.) This allows arbitrary precision numeric data to be
handled without loss of accuracy. Beware that Perl may not preserve
the same accuracy when the string is used as a number.
Perl supports binary data in Perl strings, and the DBI will pass binary
data to and from the driver without change. It is up to the driver
implementors to decide how they wish to handle such binary data.
Perl supports two kinds of strings: Unicode (utf8 internally) and non-Unicode
(defaults to iso-8859-1 if forced to assume an encoding). Drivers should
accept both kinds of strings and, if required, convert them to the character
set of the database being used. Similarly, when fetching from the database
character data that isn't iso-8859-1 the driver should convert it into utf8.
Non-sequential record reads are not supported in this version of the DBI.
In other words, records can only be fetched in the order that the
database returned them, and once fetched they are forgotten.
Positioned updates and deletes are not directly supported by the DBI.
See the description of the C<CursorName> attribute for an alternative.
The DBI package and all packages below it (C<DBI::*>) are reserved for
use by the DBI. Extensions and related modules use the C<DBIx::>
namespace (see L<http://www.perl.com/CPAN/modules/by-module/DBIx/>).
Package names beginning with C<DBD::> are reserved for use
by DBI database drivers. All environment variables used by the DBI
or by individual DBDs begin with "C<DBI_>" or "C<DBD_>".
The letter case used for attribute names is significant and plays an
important part in the portability of DBI scripts. The case of the
attribute name is used to signify who defined the meaning of that name
and its values.
The DBI itself does not mandate or require any particular language to
be used; it is language independent. In ODBC terms, the DBI is in
"pass-thru" mode, although individual drivers might not be. The only requirement
is that queries and other statements must be expressed as a single
string of characters passed as the first argument to the L</prepare> or
L</do> methods.
http://www.mcjones.org/System_R/SQL_Reunion_95/sqlr95.html
Follow the "Full Contents" then "Intergalactic dataspeak" links for the
SQL history.
Some drivers also allow placeholders like C<:>I<name> and C<:>I<N> (e.g.,
C<:1>, C<:2>, and so on) in addition to C<?>, but their use is not portable.
When using placeholders with the SQL C<LIKE> qualifier, you must
remember that the placeholder substitutes for the whole string.
So you should use "C<... LIKE ? ...>" and include any wildcard
characters in the value that you bind to the placeholder.
B<NULL Values>
$sth = $dbh->prepare(qq{
INSERT INTO people (fullname, age) VALUES (?, ?)
});
$sth->execute("Joe Bloggs", undef);
$sth = $dbh->prepare(qq{
UPDATE people SET age = ? WHERE fullname = ?
});
$sth->execute(undef, "Joe Bloggs");
The techniques above call prepare for the SQL statement with each call to
execute. Because calls to prepare() can be expensive, performance
can suffer when an application iterates many times over statements
like the above.
0) age = ?
1) NVL(age, xx) = NVL(?, xx)
2) ISNULL(age, xx) = ISNULL(?, xx)
3) DECODE(age, ?, 1, 0) = 1
4) age = ? OR (age IS NULL AND ? IS NULL)
5) age = ? OR (age IS NULL AND SP_ISNULL(?) = 1)
6) age = ? OR (age IS NULL AND ? = 1)
0,1,2,3) $sth->execute($age);
4,5) $sth->execute($age, $age);
6) $sth->execute($age, defined($age) ? 0 : 1);
Example 0 should not work (as mentioned earlier), but may work on
a few database engines anyway (e.g. Sybase). Example 0 is part
of examples 4, 5, and 6, so if example 0 works, these other
examples may work, even if the engine does not properly support
the right hand side of the C<OR> expression.
Examples 1 and 2 are not robust: they require that you provide a
valid column value xx (e.g. '~') which is not present in any row.
That means you must have some notion of what data won't be stored
in the column, and expect clients to adhere to that.
-----Examples------
0 1 2 3 4 5 6
- - - - - - -
Oracle 9 N Y N Y Y ? Y
Informix IDS 9 N N N Y N Y Y
MS SQL N N Y N Y ? Y
Sybase Y N N N N N Y
AnyData,DBM,CSV Y N N N Y Y* Y
SQLite 3.3 N N N N Y N N
MSAccess N N N N Y N Y
DBI provides a sample perl script that will test the examples above
on your database engine and tell you which ones work. It is located
in the F<ex/> subdirectory of the DBI source distribution, or here:
L<http://svn.perl.org/modules/dbi/trunk/ex/perl_dbi_nulls_test.pl>
Please use the script to help us fill-in and maintain this table.
B<Performance>
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<execute> 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;
The C<q{...}> style quoting used in this example avoids clashing with
quotes that may be used in the SQL statement. Use the double-quote like
C<qq{...}> operator if you want to interpolate variables into the string.
See L<perlop/"Quote and Quote-like Operators"> for more details.
The names and values of all the defined SQL standard types can be
produced like this:
Note that just because the DBI defines a named constant for a given
data type doesn't mean that drivers will support that data type.
=head3 C<parse_dsn>
$scheme is the first part of the DSN and is currently always 'dbi'.
$driver is the driver name, possibly defaulted to $ENV{DBI_DRIVER},
and may be undefined. $attr_string is the contents of the optional attribute
string, which may be undefined. If $attr_string is not empty then $attr_hash
is a reference to a hash containing the parsed attribute names and values.
$driver_dsn is the last part of the DBI DSN string. For example:
=head3 C<connect>
If the connect fails (see below), it returns C<undef> and sets both C<$DBI::err>
and C<$DBI::errstr>. (It does I<not> explicitly set C<$!>.) You should generally
test the return status of C<connect> and C<print $DBI::errstr> if it has failed.
dbi:DriverName:database_name
dbi:DriverName:database_name@hostname:port
dbi:DriverName:database=database_name;host=hostname;port=port
There is I<no standard> for the text following the driver name. Each
driver is free to use whatever syntax it wants. The only requirement the
DBI makes is that all the information is supplied in a single string.
You must consult the documentation for the drivers you are using for a
description of the syntax they require.
$ENV{DBI_AUTOPROXY};dsn=$data_source
The C<$data_source> argument (with the "C<dbi:...:>" prefix removed) and the
C<$username> and C<$password> arguments are then passed to the driver for
processing. The DBI does not define any interpretation for the
contents of these fields. The driver is free to interpret the
C<$data_source>, C<$username>, and C<$password> fields in any way, and supply
whatever defaults are appropriate for the engine being accessed.
(Oracle, for example, uses the ORACLE_SID and TWO_TASK environment
variables if no C<$data_source> is specified.)
The username and password can also be specified using the attributes
C<Username> and C<Password>, in which case they take precedence
over the C<$username> and C<$password> parameters.
You can also define connection attribute values within the C<$data_source>
parameter. For example:
dbi:DriverName(PrintWarn=>1,PrintError=>0,Taint=>1):...
For compatibility with old DBI scripts, the driver can be specified by
passing its name as the fourth argument to C<connect> (instead of C<\%attr>):
=head3 C<connect_cached>
Note that the behaviour of this method differs in several respects from the
behaviour of persistent connections implemented by Apache::DBI.
However, if Apache::DBI is loaded then C<connect_cached> will use it.
Taking that one step further, you can limit a particular connect_cached()
call to return handles unique to that one place in the code by setting the
private attribute to a unique value for that place:
The cache can be accessed (and cleared) via the L</CachedKids> attribute:
my $CachedKids_hashref = $dbh->{Driver}->{CachedKids};
%$CachedKids_hashref = () if $CachedKids_hashref;
=head3 C<available_drivers>
@ary = DBI->available_drivers;
@ary = DBI->available_drivers($quiet);
=head3 C<installed_drivers>
%drivers = DBI->installed_drivers();
Returns a list of driver name and driver handle pairs for all drivers
'installed' (loaded) into the current process. The driver name does not
include the 'DBD::' prefix.
To get a list of all drivers available in your perl installation you can use
L</available_drivers>.
=head3 C<installed_versions>
DBI->installed_versions;
@ary = DBI->installed_versions;
$hash = DBI->installed_versions;
When called in scalar context an extra entry for the C<DBI> is added (and
C<DBI::PurePerl> if appropriate) and a reference to the hash is returned.
Due to the potentially high memory cost and unknown risks of loading
in an unknown number of drivers that just happen to be installed
on the system, this method is not recommended for general use.
Use available_drivers() instead.
=head3 C<data_sources>
@ary = DBI->data_sources($driver);
@ary = DBI->data_sources($driver, \%attr);
The driver will be loaded if it hasn't been already. Note that if the
driver loading fails then data_sources() I<dies> with an error message
that includes the string "C<install_driver>" and the underlying problem.
Note that many drivers have no way of knowing what data sources might
be available for it. These drivers return an empty or incomplete list
or may require driver-specific attributes.
DBI->trace($trace_setting)
DBI->trace($trace_setting, $trace_filename)
DBI->trace($trace_setting, $trace_filehandle)
$trace_setting = DBI->trace;
See the L</TRACING> section for full details about the DBI's powerful
tracing facilities.
=head3 C<visit_handles>
DBI->visit_handles( $coderef );
DBI->visit_handles( $coderef, $info );
$coderef->($driver_handle, $info);
For example:
my $info = $dbh->{Driver}->visit_child_handles(sub {
my ($h, $info) = @_;
++$info->{ $h->{Type} }; # count types of handles (dr/db/st)
return $info; # visit kids
});
$description = data_string_desc($string);
=head3 C<data_string_diff>
=head3 C<data_diff>
=head3 C<neat>
$str = neat($value);
$str = neat($value, $maxlen);
For result strings longer than C<$maxlen> the result string will be
truncated to C<$maxlen-4> and "C<...'>" will be appended. If C<$maxlen> is 0
or C<undef>, it defaults to C<$DBI::neat_maxlen> which, in turn, defaults to 400.
=head3 C<neat_list>
=head3 C<looks_like_number>
@bool = looks_like_number(@array);
=head3 C<hash>
=head3 C<sql_type_cast>
=over 4
=item C<DBIstcf_DISCARD_STRING>
If this flag is specified then when the driver successfully casts the
bound perl scalar to a non-string type then the string portion of the
scalar will be discarded.
=item C<DBIstcf_STRICT>
=back
This method is exported by the :utils tag and was introduced in DBI
1.611.
Dynamic attributes are always associated with the I<last handle used>
(that handle is represented by C<$h> in the descriptions below).
=head3 C<$DBI::err>
Equivalent to C<$h-E<gt>err>.
=head3 C<$DBI::errstr>
Equivalent to C<$h-E<gt>errstr>.
=head3 C<$DBI::state>
Equivalent to C<$h-E<gt>state>.
=head3 C<$DBI::rows>
=head3 C<$DBI::lasth>
Returns the DBI object handle used for the most recent DBI method call.
If the last DBI method call was a DESTROY then $DBI::lasth will return
the handle of the parent of the destroyed handle, if there is one.
=head3 C<err>
$rv = $h->err;
Returns the I<native> database engine error code from the last driver
method called. The code is typically an integer but you should not
assume that.
The DBI resets $h->err to undef before almost all DBI method calls, so the
value only has a short lifespan. Also, for most drivers, the statement
handles share the same error variable as the parent database handle,
so calling a method on one handle may reset the error on the
related handles.
(Methods which don't reset err before being called include err() and errstr(),
obviously, state(), rows(), func(), trace(), trace_msg(), ping(), and the
tied hash attribute FETCH() and STORE() methods.)
If you need to test for specific error conditions I<and> have your program be
portable to different database engines, then you'll need to determine what the
corresponding error codes are for all those engines and test for all of them.
The DBI uses the value of $DBI::stderr as the C<err> value for internal errors.
Drivers should also do likewise. The default value for $DBI::stderr is 2000000000.
=head3 C<errstr>
$str = $h->errstr;
Returns the native database engine error message from the last DBI
method called. This has the same lifespan issues as the L</err> method
described above.
The errstr() method should not be used to test for errors, use err()
for that, because drivers may return 'success with information' or
warning messages via errstr() for methods that have not 'failed'.
=head3 C<state>
$str = $h->state;
The driver is free to return any value via C<state>, e.g., warning
codes, even if it has not declared an error by returning a true value
via the L</err> method described above.
The state() method should not be used to test for errors, use err()
for that, because drivers may return a 'success with information' or
warning state code via state() for methods that have not 'failed'.
=head3 C<set_err>
$rv = $h->set_err($err, $errstr);
$rv = $h->set_err($err, $errstr, $state);
$rv = $h->set_err($err, $errstr, $state, $method);
$rv = $h->set_err($err, $errstr, $state, $method, $rv);
Set the C<err>, C<errstr>, and C<state> values for the handle.
This method is typically only used by DBI drivers and DBI subclasses.
If C<errstr> is true then: "C< [err was %s now %s]>" is appended if $err is
true and C<err> is already true and the new err value differs from the original
one. Similarly "C< [state was %s now %s]>" is appended if $state is true and
C<state> is
already true and the new state value differs from the original one. Finally
"C<\n>" and the new $errstr are appended if $errstr differs from the existing
errstr value. Obviously the C<%s>'s above are replaced by the corresponding values.
The handle C<err> value is set to $err if: $err is true; or handle
C<err> value is undef; or $err is defined and the length is greater
than the handle C<err> length. The effect is that an 'information'
state only overrides undef; a 'warning' overrides undef or 'information',
and an 'error' state overrides anything.
Support for warning and information states was added in DBI 1.41.
=head3 C<trace>
$h->trace($trace_settings);
$h->trace($trace_settings, $trace_filename);
$trace_settings = $h->trace;
The trace() method is used to alter the trace settings for a handle
(and any future children of that handle). It can also be used to
change where the trace output is sent.
See the L</TRACING> section for full details about the DBI's powerful
tracing facilities.
=head3 C<trace_msg>
$h->trace_msg($message_text);
$h->trace_msg($message_text, $min_level);
=head3 C<func>
It's also important to note that the func() method does not clear
a previous error ($DBI::err etc.) and it does not trigger automatic
error detection (RaiseError etc.) so you must check the return
status and/or $h->err to detect errors.
See also install_method() in L<DBI::DBD> for how you can avoid needing to
use func() and gain direct access to driver-private methods.
=head3 C<can>
$is_implemented = $h->can($method_name);
=head3 C<parse_trace_flags>
$trace_settings_integer = $h->parse_trace_flags($trace_settings);
=head3 C<parse_trace_flag>
$bit_flag = $h->parse_trace_flag($trace_flag_name);
=head3 C<private_attribute_info>
$hash_ref = $h->private_attribute_info();
For example, the return value when called with a DBD::Sybase $dbh could look like
this:
{
syb_dynamic_supported => undef,
syb_oc_version => undef,
syb_server_version => undef,
syb_server_version_string => undef,
}
and when called with a DBD::Sybase $sth they could look like this:
{
syb_types => undef,
syb_proc_status => undef,
syb_result_type => undef,
}
=head3 C<swap_inner_handle>
Brain transplants for handles. You don't need to know about this
unless you want to become a handle surgeon.
As a small safety measure, the two handles, $h1 and $h2, have to
share the same parent unless $allow_reparent is true.
Here's a quick kind of 'diagram' as a worked example to help think about what's
happening:
Original state:
dbh1o -> dbh1i
sthAo -> sthAi(dbh1i)
dbh2o -> dbh2i
=head3 C<visit_child_handles>
$h->visit_child_handles( $coderef );
$h->visit_child_handles( $coderef, $info );
$coderef->($child_handle, $info);
For example:
Some attributes are inherited by child handles. That is, the value
of an inherited attribute in a newly created statement handle is the
same as the value in the parent database handle. Changes to attributes
in the new statement handle do not affect the parent database handle
and changes to the database handle do not affect existing statement
handles, only future ones.
Example:
=head3 C<Warn>
=head3 C<Active>
The C<Active> attribute is true if the handle object is "active". This is rarely
used in
applications. The exact meaning of active is somewhat vague at the
moment. For a database handle it typically means that the handle is
connected to a database (C<$dbh-E<gt>disconnect> sets C<Active> off). For
a statement handle it typically means that the handle is a C<SELECT>
that may have more data to fetch. (Fetching all the data or calling C<$sth-
E<gt>finish>
sets C<Active> off.)
=head3 C<Executed>
Type: boolean
The C<Executed> 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<Executed> 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<Executed>
attribute on the parent $dbh.
The C<Executed> attribute for a database handle is cleared by the commit() and
rollback() methods (even if they fail). The C<Executed> 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.
=head3 C<Kids>
=head3 C<ActiveKids>
Like C<Kids>, but only counting those that are C<Active> (as above).
=head3 C<CachedKids>
=head3 C<Type>
=head3 C<ChildHandles>
C<ChildHandles> returns undef if your perl version does not support weak
references (check the L<Scalar::Util|Scalar::Util> module). The referenced
array returned should be treated as read-only.
my %drivers = DBI->installed_drivers();
show_child_handles($_, 0) for (values %drivers);
=head3 C<CompatMode>
=head3 C<InactiveDestroy>
Type: boolean
If set true then the handle will be treated by the DESTROY as if it was no
longer Active, and so the I<database engine> related effects of DESTROYing a
handle will be skipped. Think of the name as meaning 'treat the handle as
not-Active in the DESTROY method'.
Either the parent or the child process, but not both, should set
C<InactiveDestroy> true on all their shared handles. Alternatively the
L</AutoInactiveDestroy> can be set in the parent on connect.
=head3 C<AutoInactiveDestroy>
If set true, the DESTROY method will check the process id of the handle and, if
different from the current process id, it will set the I<InactiveDestroy>
attribute.
my $dbh = DBI->connect(...);
some_code_that_forks(); # Perhaps without your knowledge
# Child process dies, destroying the inherited dbh
$dbh->do(...); # Breaks because parent $dbh is now broken
=head3 C<PrintWarn>
See also L</set_err> for how warnings are recorded and L</HandleSetErr>
for how to influence it.
=head3 C<PrintError>
The C<PrintError> attribute can be used to force errors to generate warnings (using
C<warn>) in addition to returning error codes in the normal way. When set
"on", any method which results in an error occurring will cause the DBI to
effectively do a C<warn("$class $method failed: $DBI::errstr")> where C<$class>
is the driver class and C<$method> is the name of the method which failed. E.g.,
=head3 C<RaiseError>
The C<RaiseError> 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<die("$class $method failed: $DBI::errstr")>,
where C<$class> is the driver class and C<$method> is the name of the method
that failed. E.g.,
eval {
...
$sth->execute();
...
};
if ($@) {
# $sth->err and $DBI::err will be true if error was from DBI
warn $@; # print the error
... # do whatever you need to deal with the error
}
{
local $h->{RaiseError}; # localize and turn off for this block
...
}
=head3 C<HandleError>
The C<HandleError> 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<RaiseError> and C<PrintError> are handled).
For example, to C<die> with a full stack trace for any error:
use Carp;
$h->{HandleError} = sub { confess(shift) };
sub your_subroutine {
my $previous_handler = $h->{HandleError};
$h->{HandleError} = sub {
return 1 if $previous_handler and &$previous_handler(@_);
... your code here ...
};
}
$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<good> use for it then
please let me know.
=head3 C<HandleSetErr>
The subroutine is called with five arguments, the first five that
were passed to set_err(): the handle, the C<err>, C<errstr>, and
C<state> 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</set_err> for details.
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.
=head3 C<ErrCount>
The C<ErrCount> 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.
=head3 C<ShowErrorStatement>
=head3 C<TraceLevel>
=head3 C<FetchHashKeyName>
=head3 C<ChopBlanks>
The C<ChopBlanks> 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.
Drivers are not required to support this attribute, but any driver which
does not support it must arrange to return C<undef> as the attribute value.
=head3 C<LongReadLen>
The default is typically 0 (zero) or 80 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<LongReadLen> relates to the underlying data
length and not the doubled-up length of the encoded string.
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(OCTET_LENGTH(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. You may also need to
use a different function if OCTET_LENGTH() does not work for long
types in your database. For example, for Sybase use DATALENGTH() and
for Oracle use LENGTHB().
=head3 C<LongTruncOk>
When fetching data that you trust you can turn off the TaintIn attribute,
for that statement handle, for the duration of the fetch loop.
=head3 C<TaintOut>
When fetching data that you trust you can turn off the TaintOut attribute,
for that statement handle, for the duration of the fetch loop.
=head3 C<Taint>
The C<Taint> attribute is a shortcut for L</TaintIn> and L</TaintOut> (it is also
present
for backwards compatibility).
Setting this attribute sets both L</TaintIn> and L</TaintOut>, and retrieving
it returns a true value if and only if L</TaintIn> and L</TaintOut> are
both set to true values.
=head3 C<Profile>
Type: inherited
=head3 C<ReadOnly>
If the driver can make the handle truly read-only then it should
(unless doing so would have unpleasant side effect, like changing the
consistency level from per-statement to per-session).
Otherwise the attribute is simply advisory.
A driver can set the C<ReadOnly> attribute itself to indicate that the data it
is connected to cannot be changed for some reason.
Library modules and proxy drivers can use the attribute to influence
their behavior. For example, the DBD::Gofer driver considers the
C<ReadOnly> attribute when making a decision about whether to retry an
operation that failed.
The attribute should be set to 1 or 0 (or undef). Other values are reserved.
=head3 C<Callbacks>
The DBI callback mechanism lets you intercept, and optionally replace, any
method call on a DBI handle. At the extreme, it lets you become a puppet
master, deceiving the application in any way you want.
The C<Callbacks> attribute is a hash reference where the keys are DBI method
names and the values are code references. For each key naming a method, the
DBI will execute the associated code reference before executing the method.
The arguments to the code reference will be the same as to the method,
including the invocant (a database handle or statement handle). For example,
say that to callback to some code on a call to C<prepare()>:
$dbh->{Callbacks} = {
prepare => sub {
my ($dbh, $query, $attrs) = @_;
print "Preparing q{$query}\n"
},
};
The callback would then be executed when you called the C<prepare()> method:
$dbh->prepare('SELECT 1');
Note that we are editing the contents of C<@_> directly. In this case we've
created the attributes hash if it's not passed to the C<prepare> call.
You can also prevent the associated method from ever executing. While a
callback executes, C<$_> holds the method name. (This allows multiple callbacks
to share the same code reference and still know what method was called.)
To prevent the method from
executing, simply C<undef $_>. For example, if you wanted to disable calls to
C<ping()>, you could do this:
$dbh->{Callbacks} = {
ping => sub {
# tell dispatch to not call the method:
undef $_;
# return this value instead:
return "42 bells";
}
};
$sth->{Callbacks} = {
execute => sub {
print "Executing ", shift->{Statement}, "\n";
}
};
The first is the C<ChildCallbacks> key. When a statement handle is created from
a database handle the C<ChildCallbacks> key of the database handle's
C<Callbacks> attribute, if any, becomes the new C<Callbacks> attribute of the
statement handle.
This allows you to define callbacks for all statement handles created from a
database handle. For example, if you wanted to count how many times C<execute>
was called in your application, you could write:
my $exec_count = 0;
my $dbh = DBI->connect( $dsn, $username, $auth, {
Callbacks => {
ChildCallbacks => {
execute => sub { $exec_count++; return; }
}
}
});
END {
print "The execute method was called $exec_count times\n";
}
my $cb = {
'connect_cached.reused' => sub { delete $_[4]->{AutoCommit} },
};
sub dbh {
my $self = shift;
DBI->connect_cached( $dsn, $username, $auth, {
PrintError => 0,
RaiseError => 1,
AutoCommit => 1,
Callbacks => $cb,
});
}
The upshot is that new database handles are created with C<AutoCommit>
enabled, while cached database handles are left in whatever transaction state
they happened to be in when retrieved from the cache.
A more common application for callbacks is setting connection state only when a
new connection is made (by connect() or connect_cached()). Adding a callback to
the connected method makes this easy.
This method is a no-op by default (unless you subclass the DBI and change it).
The DBI calls it to indicate that a new connection has been made and the connection
attributes have all been set. You can
give it a bit of added functionality by applying a callback to it. For
example, to make sure that MySQL understands your application's ANSI-compliant
SQL, set it up like so:
One significant limitation with callbacks is that there can only be one per
method per handle. This means it's easy for one use of callbacks to interfere
with, or typically simply overwrite, another use of callbacks. For this reason
modules using callbacks should document the fact clearly so application authors
can tell if use of callbacks by the module will clash with use of callbacks by
the application.
You might be able to work around this issue by taking a copy of the original
callback and calling it within your own. For example:
my $prev_cb = $h->{Callbacks}{method_name};
$h->{Callbacks}{method_name} = sub {
if ($prev_cb) {
my @result = $prev_cb->(@_);
return @result if not $_; # $prev_cb vetoed call
}
... your callback logic here ...
};
=head3 C<private_your_module_name_*>
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};
$foo ||= $dbh->{private_yourmodname_foo} = { ... };
This attribute is primarily of interest to people sub-classing DBI,
or for applications to piggy-back extra information onto DBI handles.
=head3 C<clone>
$new_dbh = $dbh->clone(\%attr);
The attributes for the cloned connect are the same as those used
for the I<original> connect, with any other attributes in C<\%attr>
merged over them. Effectively the same as doing:
The clone method can be used even if the database handle is disconnected.
=head3 C<data_sources>
@ary = $dbh->data_sources();
@ary = $dbh->data_sources(\%attr);
=head3 C<do>
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;
The C<q{...}> style quoting used in this example avoids clashing with
quotes that may be used in the SQL statement. Use the double-quote-like
C<qq{...}> operator if you want to interpolate variables into the string.
See L<perlop/"Quote and Quote-like Operators"> for more details.
=head3 C<last_insert_id>
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, for others they are ignored (e.g., mysql).
B<*> For some drivers the value may only be available if placeholders
have I<not> 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 no insert has been performed yet, or the last insert failed,
then the value is implementation defined.
Given all the caveats above, it's clear that this method must be
used with care.
=head3 C<selectrow_array>
@row_ary = $dbh->selectrow_array($statement);
@row_ary = $dbh->selectrow_array($statement, \%attr);
@row_ary = $dbh->selectrow_array($statement, \%attr, @bind_values);
$ary_ref = $dbh->selectrow_arrayref($statement);
$ary_ref = $dbh->selectrow_arrayref($statement, \%attr);
$ary_ref = $dbh->selectrow_arrayref($statement, \%attr, @bind_values);
=head3 C<selectrow_hashref>
$hash_ref = $dbh->selectrow_hashref($statement);
$hash_ref = $dbh->selectrow_hashref($statement, \%attr);
$hash_ref = $dbh->selectrow_hashref($statement, \%attr, @bind_values);
=head3 C<selectall_arrayref>
$ary_ref = $dbh->selectall_arrayref($statement);
$ary_ref = $dbh->selectall_arrayref($statement, \%attr);
$ary_ref = $dbh->selectall_arrayref($statement, \%attr, @bind_values);
You may often want to fetch an array of rows where each row is stored as a
hash. That can be done simple using:
my $emps = $dbh->selectall_arrayref(
"SELECT ename FROM emp ORDER BY ename",
{ Slice => {} }
);
foreach my $emp ( @$emps ) {
print "Employee: $emp->{ename}\n";
}
=head3 C<selectall_hashref>
The C<$key_field> parameter defines which column, or columns, are used as keys
in the returned hash. It can either be the name of a single field, or a
reference to an array containing multiple field names. Using multiple names
yields a tree of nested hashes.
If a row has the same key as an earlier row then it replaces the earlier row.
=head3 C<selectcol_arrayref>
$ary_ref = $dbh->selectcol_arrayref($statement);
$ary_ref = $dbh->selectcol_arrayref($statement, \%attr);
$ary_ref = $dbh->selectcol_arrayref($statement, \%attr, @bind_values);
=head3 C<prepare>
=head3 C<prepare_cached>
$sth = $dbh->prepare_cached($statement)
$sth = $dbh->prepare_cached($statement, \%attr)
$sth = $dbh->prepare_cached($statement, \%attr, $if_active)
=over 4
=item B<1>: finish() will be called on the statement handle, but the
warning is suppressed.
=item B<3>: The existing active statement handle will be removed from the
cache and a new statement handle prepared and cached in its place.
This is the safest option because it doesn't affect the state of the
old handle, it just removes it from the cache. [Added in DBI 1.40]
=back
sub insert_hash {
my ($table, $field_values) = @_;
# sort to keep field order, and thus sql, stable for prepare_cached
my @fields = sort keys %$field_values;
my @values = @{$field_values}{@fields};
my $sql = sprintf "insert into %s (%s) values (%s)",
$table, join(",", @fields), join(",", ("?")x@fields);
my $sth = $dbh->prepare_cached($sql);
return $sth->execute(@values);
}
sub search_hash {
my ($table, $field_values) = @_;
# sort to keep field order, and thus sql, stable for prepare_cached
my @fields = sort keys %$field_values;
my @values = @{$field_values}{@fields};
my $qualifier = "";
$qualifier = "where ".join(" and ", map { "$_=?" } @fields) if @fields;
$sth = $dbh->prepare_cached("SELECT * FROM $table $qualifier");
return $dbh->selectall_arrayref($sth, {}, @values);
}
In this example, since both handles are preparing the exact same statement,
C<$sth2> will not be its own statement handle, but a duplicate of C<$sth>
returned from the cache. The results will certainly not be what you expect.
Typically the inner fetch loop will work normally, fetching all
the records and terminating when there are no more, but now that $sth
is the same as $sth2 the outer fetch loop will also terminate.
If you'd like the cache to managed intelligently, you can tie the
hashref returned by C<CachedKids> to an appropriate caching module,
such as L<Tie::Cache::LRU>:
my $cache;
tie %$cache, 'Tie::Cache::LRU', 500;
$dbh->{CachedKids} = $cache;
=head3 C<commit>
=head3 C<rollback>
=head3 C<begin_work>
Enable transactions (by turning C<AutoCommit> off) until the next call
to C<commit> or C<rollback>. After the next C<commit> or C<rollback>,
C<AutoCommit> will automatically be turned on again.
=head3 C<disconnect>
Disconnects the database from the database handle. C<disconnect> is typically only
used
before exiting the program. The handle is of little use after disconnecting.
=head3 C<ping>
$rc = $dbh->ping;
Few applications would have direct use for this method. See the specialized
Apache::DBI module for one example usage.
=head3 C<get_info>
The names are a merging of the ANSI and ODBC standards (which differ
in some cases). See L<DBI::Const::GetInfoType> for more details.
Because some DBI methods make use of get_info(), drivers are strongly
encouraged to support I<at least> the following very minimal set
of information types to ensure the DBI itself works properly:
=head3 C<table_info>
$sth = $dbh->table_info( $catalog, $schema, $table, $type );
$sth = $dbh->table_info( $catalog, $schema, $table, $type, \%attr );
The arguments $catalog, $schema and $table may accept search patterns
according to the database/driver, for example: $table = '%FOO%';
Remember that the underscore character ('C<_>') is a search pattern
that means match any character, so 'FOO_%' is the same as 'FOO%'
and 'FOO_BAR%' will match names like 'FOO1BAR'.
$type = "TABLE";
$type = "'TABLE','VIEW'";
In addition the following special cases may also be supported by some drivers:
=over 4
=item *
If the value of $catalog is '%' and $schema and $table name
are empty strings, the result set contains a list of catalog names.
For example:
=item *
If the value of $schema is '%' and $catalog and $table are empty
strings, the result set contains a list of schema names.
=item *
If the value of $type is '%' and $catalog, $schema, and $table are all
empty strings, the result set contains a list of table types.
=back
This method can be expensive, and can return a large amount of data.
(For example, small Oracle installation returns over 2000 rows.)
So it's a good idea to use the filters to limit the data as much as possible.
The statement handle returned has at least the following fields in the
order show below. Other fields, after these, may also be present.
Note that C<table_info> might not return records for all tables.
Applications can use any valid table regardless of whether it's
returned by C<table_info>.
=head3 C<column_info>
The arguments $schema, $table and $column may accept search patterns
according to the database/driver, for example: $table = '%FOO%';
Note: The support for the selection criteria is driver specific. If the
driver doesn't support one or more of them then you may get back more
than you asked for and can do the filtering yourself.
If the arguments don't match any tables then you'll still get a statement
handle, it'll just return no rows.
The statement handle returned has at least the following fields in the
order shown below. Other fields, after these, may also be present.
SQL_NO_NULLS 0
SQL_NULLABLE 1
SQL_NULLABLE_UNKNOWN 2
B<COLUMN_DEF>: The default value of the column, in a format that can be used
directly in an SQL statement.
Note that this may be an expression and not simply the text used for the
default value in the original CREATE TABLE statement. For example, given:
B<SQL_DATETIME_SUB>: The subtype code for datetime and interval data types.
CHAR_SET_CAT
CHAR_SET_SCHEM
CHAR_SET_NAME
COLLATION_CAT
COLLATION_SCHEM
COLLATION_NAME
UDT_CAT
UDT_SCHEM
UDT_NAME
DOMAIN_CAT
DOMAIN_SCHEM
DOMAIN_NAME
SCOPE_CAT
SCOPE_SCHEM
SCOPE_NAME
MAX_CARDINALITY
DTD_IDENTIFIER
IS_SELF_REF
Note: There is some overlap with statement handle attributes (in perl) and
SQLDescribeCol (in ODBC). However, SQLColumns provides more metadata.
=head3 C<primary_key_info>
The statement handle will return one row per column, ordered by
TABLE_CAT, TABLE_SCHEM, TABLE_NAME, and KEY_SEQ.
If there is no primary key then the statement handle will fetch no rows.
The statement handle returned has at least the following fields in the
order shown below. Other fields, after these, may also be present.
B<TABLE_CAT>: The catalog identifier.
This field is NULL (C<undef>) if not applicable to the data source,
which is often the case. This field is empty if not applicable to the
table.
=head3 C<primary_key>
=head3 C<foreign_key_info>
If both B<PKT> and B<FKT> are given, the function returns the foreign key, if
any, in table B<FKT> that refers to the primary (unique) key of table B<PKT>.
(Note: In SQL/CLI, the result is implementation-defined.)
If only B<PKT> is given, then the result set contains the primary key
of that table and all foreign keys that refer to it.
If only B<FKT> is given, then the result set contains all foreign keys
in that table and the primary keys to which they refer.
(Note: In SQL/CLI, the result includes unique keys too.)
For example:
The statement handle returned has the following fields in the order shown below.
Because ODBC never includes unique keys, they define different columns in the
result set than SQL/CLI. SQL/CLI column names are shown in parentheses.
CASCADE 0
RESTRICT 1
SET NULL 2
NO ACTION 3
SET DEFAULT 4
INITIALLY DEFERRED 5
INITIALLY IMMEDIATE 6
NOT DEFERRABLE 7
=head3 C<statistics_info>
The statement handle will return at most one row per column name per index,
plus at most one row for the entire table itself, ordered by NON_UNIQUE, TYPE,
INDEX_QUALIFIER, INDEX_NAME, and ORDINAL_POSITION.
Note: The support for the selection criteria, such as $catalog, is
driver specific. If the driver doesn't support catalogs and/or
schemas, it may ignore these criteria.
The statement handle returned has at least the following fields in the
order shown below. Other fields, after these, may also be present.
=head3 C<tables>
=head3 C<type_info_all>
$type_info_all = $dbh->type_info_all;
The first item is a reference to an 'index' hash of C<Name =>E<gt> C<Index> pairs.
The items following that are references to arrays, one per supported data
type variant. The leading index hash defines the names and order of the
fields within the arrays that follow it.
For example:
$type_info_all = [
{ TYPE_NAME => 0,
DATA_TYPE => 1,
COLUMN_SIZE => 2, # was PRECISION originally
LITERAL_PREFIX => 3,
LITERAL_SUFFIX => 4,
CREATE_PARAMS => 5,
NULLABLE => 6,
CASE_SENSITIVE => 7,
SEARCHABLE => 8,
UNSIGNED_ATTRIBUTE=> 9,
FIXED_PREC_SCALE => 10, # was MONEY originally
AUTO_UNIQUE_VALUE => 11, # was AUTO_INCREMENT originally
LOCAL_TYPE_NAME => 12,
MINIMUM_SCALE => 13,
MAXIMUM_SCALE => 14,
SQL_DATA_TYPE => 15,
SQL_DATETIME_SUB => 16,
NUM_PREC_RADIX => 17,
INTERVAL_PRECISION=> 18,
},
[ 'VARCHAR', SQL_VARCHAR,
undef, "'","'", undef,0, 1,1,0,0,0,undef,1,255, undef
],
[ 'INTEGER', SQL_INTEGER,
undef, "", "", undef,0, 0,1,0,0,0,undef,0, 0, 10
],
];
More than one row may have the same value in the C<DATA_TYPE>
field if there are different ways to spell the type name and/or there
are variants of the type with different attributes (e.g., with and
without C<AUTO_UNIQUE_VALUE> set, with and without C<UNSIGNED_ATTRIBUTE>, etc).
The rows are ordered by C<DATA_TYPE> first and then by how closely each
type maps to the corresponding ODBC SQL data type, closest first.
=head3 C<type_info>
@type_info = $dbh->type_info($data_type);
The keys of the hash follow the same letter case conventions as the
rest of the DBI (see L</Naming Conventions and Name Space>). The
following uppercase items should always exist, though may be undef:
=over 4
For numeric types, this is either the total number of digits (if the
NUM_PREC_RADIX value is 10) or the total number of bits allowed in the
column (if NUM_PREC_RADIX is 2).
For string types, this is the maximum size of the string in characters.
For date and interval types, this is the maximum number of characters
needed to display the value.
Parameter names for data type definition. For example, C<CREATE_PARAMS> for a
C<DECIMAL> would be "C<precision,scale>" if the DECIMAL type should be
declared as C<DECIMAL(>I<precision,scale>C<)> where I<precision> and I<scale>
are integer values. For a C<VARCHAR> it would be "C<max length>".
NULL (C<undef>) is returned for data types for which this is not applicable.
Indicates whether the data type always has the same precision and scale
(such as a money type). NULL (C<undef>) is returned for data types
for which
this is not applicable.
The minimum scale of the data type. If a data type has a fixed scale,
then C<MAXIMUM_SCALE> holds the same value. NULL (C<undef>) is returned for
data types for which this is not applicable.
The maximum scale of the data type. If a data type has a fixed scale,
then C<MINIMUM_SCALE> holds the same value. NULL (C<undef>) is returned for
data types for which this is not applicable.
This column is the same as the C<DATA_TYPE> column, except for interval
and datetime data types. For interval and datetime data types, the
C<SQL_DATA_TYPE> field will return C<SQL_INTERVAL> or C<SQL_DATETIME>, and the
C<SQL_DATETIME_SUB> field below will return the subcode for the specific
interval or datetime data type. If this field is NULL, then the driver
does not support or report on interval or datetime subtypes.
The radix value of the data type. For approximate numeric types,
C<NUM_PREC_RADIX>
contains the value 2 and C<COLUMN_SIZE> holds the number of bits. For
exact numeric types, C<NUM_PREC_RADIX> contains the value 10 and C<COLUMN_SIZE>
holds
the number of decimal digits. NULL (C<undef>) is returned either for data types
for which this is not applicable or if the driver cannot report this information.
=back
For example, to find the type name for the fields in a select statement
you can do:
Since DBI and ODBC drivers vary in how they map their types into the
ISO standard types you may need to search for more than one type.
Here's an example looking for a usable type to store a date:
Similarly, to more reliably find a type to store small integers, you could
use a list starting with C<SQL_SMALLINT>, C<SQL_INTEGER>, C<SQL_DECIMAL>, etc.
=head3 C<quote>
$sql = $dbh->quote($value);
$sql = $dbh->quote($value, $data_type);
For most database types, at least those that conform to SQL standards, quote
would return C<'Don''t'> (including the outer quotation marks). For others it
may return something like C<'Don\'t'>
Quote will probably I<not> be able to deal with all possible input
(such as binary data or data containing newlines), and is not related in
any way with escaping or quoting shell meta-characters.
$quoted = $dbh->quote("one\ntwo\0three")
=head3 C<quote_identifier>
Undefined names are ignored and the remainder are quoted and then
joined together, typically with a dot (C<.>) character. For example:
=head3 C<take_imp_data>
$imp_data = $dbh->take_imp_data;
Why would you want to do this? You don't, forget I even mentioned it.
Unless, that is, you're implementing something advanced like a
multi-threaded connection pool. See L<DBI::Pool>.
B<*> using the same $imp_data to create more than one other new
$dbh at a time may well lead to unpleasant problems. Don't do that.
The C<take_imp_data> method was added in DBI 1.36 but wasn't useful till 1.49.
Example:
=head3 C<AutoCommit>
Type: boolean
For the purposes of this description, we can divide databases into three
categories:
For these databases, the intention is to have them act like databases in
which a transaction is always active (as described above).
In this way, the application does not have to treat these databases
as a special case.
=head3 C<Driver>
Type: handle
Holds the handle of the parent driver. The only recommended use for this
is to find the name of the driver using:
$dbh->{Driver}->{Name}
=head3 C<Name>
Type: string
Holds the "name" of the database. Usually (and recommended to be) the
same as the "C<dbi:DriverName:...>" string used to connect to the database,
but with the leading "C<dbi:DriverName:>" removed.
=head3 C<Statement>
=head3 C<RowCacheSize>
Type: integer
A hint to the driver indicating the size of the local row cache that the
application would like the driver to use for future C<SELECT> statements.
If a row cache is not implemented, then setting C<RowCacheSize> is ignored
and getting the value returns C<undef>.
Note that large cache sizes may require a very large amount of memory
(I<cached rows * maximum size of row>). Also, a large cache will cause
a longer delay not only for the first fetch, but also whenever the
cache needs refilling.
=head3 C<Username>
Type: string
This section lists the methods and attributes associated with DBI
statement handles.
The DBI defines the following methods for use on DBI statement handles:
=head3 C<bind_param>
$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<bind_param> 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:
The C<\%attr> parameter can be used to hint at the data type the
placeholder should have. This is rarely needed. Typically, the driver is only
interested in knowing if the placeholder should be bound as a number or a string.
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:
The data type is 'sticky' in that bind values passed to execute() are bound
with the data type specified by earlier bind_param() calls, if any.
Portable applications should not rely on being able to change the data type
after the first C<bind_param> call.
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:
=head3 C<bind_param_inout>
=head3 C<bind_param_array>
=head3 C<execute>
For C<SELECT> statements, execute simply "starts" the query within the
database engine. Use one of the fetch methods to retrieve the data after
calling C<execute>. The C<execute> method does I<not> 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.
=head3 C<execute_array>
When called in list context the execute_array() method returns two scalars;
$tuples is the same as calling execute_array() in scalar context and $rows is
the number of rows affected for each tuple, if available or
-1 if the driver cannot determine this. NOTE, some drivers cannot determine
the number of rows affected per tuple but can provide the number of rows
affected for the batch.
If you are doing an update operation the returned rows affected may not be what
you expect if, for instance, one or more of the tuples affected the same row
multiple times. Some drivers may not yet support list context, in which case
$rows will be undef, or may not be able to provide the number of rows affected
when performing this batch operation, in which case $rows will be -1.
For tuples which are successfully executed, the element at the same
ordinal position in the status array is the resulting rowcount (or -1
if unknown).
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
L</err>, L</errstr> and L</state> set by the failed execution.
For example:
=head3 C<execute_for_fetch>
$tuples = $sth->execute_for_fetch($fetch_tuple_sub);
$tuples = $sth->execute_for_fetch($fetch_tuple_sub, \@tuple_status);
If the driver detects an error that it knows means no further tuples can be
executed then it may return, with an error status, even though $fetch_tuple_sub
may still have more tuples to be executed.
For example:
my @tuple_status;
$rc = $ins->execute_for_fetch($fetch_tuple_sub, \@tuple_status);
my @errors = grep { ref $_ } @tuple_status;
=head3 C<fetchrow_arrayref>
$ary_ref = $sth->fetchrow_arrayref;
$ary_ref = $sth->fetch; # alias
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</bind_columns>.
=head3 C<fetchrow_array>
@ary = $sth->fetchrow_array;
=head3 C<fetchrow_hashref>
$hash_ref = $sth->fetchrow_hashref;
$hash_ref = $sth->fetchrow_hashref($name);
The optional C<$name> parameter specifies the name of the statement handle
attribute. For historical reasons it defaults to "C<NAME>", however using
either "C<NAME_lc>" or "C<NAME_uc>" is recommended for portability.
The keys of the hash are the same names returned by C<$sth-E<gt>{$name}>. If
more than one field has the same name, there will only be one entry in the
returned hash for those fields, so statements like "C<select foo, foo from bar>"
will return only a single key from C<fetchrow_hashref>. In these cases use
column aliases or C<fetchrow_arrayref>. Note that it is the database server
(and not the DBD implementation) which provides the I<name> for fields
containing functions like "C<count(*)>" or "C<max(c_foo)>" and they may clash
with existing column names (most databases don't care about duplicate column
names in a result-set). If you want these to return as unique names that are
the same across databases, use I<aliases>, as in "C<select count(*) as cnt>"
or "C<select max(c_foo) mx_foo, ...>" depending on the syntax your database
supports.
=head3 C<fetchall_arrayref>
$tbl_ary_ref = $sth->fetchall_arrayref;
$tbl_ary_ref = $sth->fetchall_arrayref( $slice );
$tbl_ary_ref = $sth->fetchall_arrayref( $slice, $max_rows );
$tbl_ary_ref = $sth->fetchall_arrayref([0]);
$tbl_ary_ref = $sth->fetchall_arrayref([-2,-1]);
$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", regardless of the original capitalization):
For example, to fetch only the first and second columns of every row as a hash
ref (with keys named "k" and "v" regardless of their original names):
That I<might> be the fastest way to fetch and process lots of rows using the DBI,
but it depends on the relative cost of method calls vs memory allocation.
=head3 C<fetchall_hashref>
$hash_ref = $sth->fetchall_hashref($key_field);
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";
For queries returning more than one 'key' column, you can specify
multiple column names by passing $key_field as a reference to an
array containing one or more key column names (or index numbers).
For example:
=head3 C<finish>
$rc = $sth->finish;
Indicate that no more data will be fetched from this statement handle
before it is either executed again or destroyed. You almost certainly
do I<not> need to call this method.
Adding calls to C<finish> after loop that fetches all rows is a common mistake,
don't do it, it can mask genuine problems like uncaught fetch errors.
When all the data has been fetched from a C<SELECT> statement, the driver will
automatically call C<finish> for you. So you should I<not> call it explicitly
I<except> when you know that you've not fetched all the data from a statement
handle I<and> the handle won't be destroyed soon.
The most common example is when you only want to fetch just one row,
but in that case the C<selectrow_*> methods are usually better anyway.
on a very large table. When executed, the database server will have to use
temporary buffer space to store the sorted rows. If, after executing
the handle and selecting just a few rows, the handle won't be re-executed for
some time and won't be destroyed, the C<finish> method can be used to tell
the server that the buffer space can be freed.
The C<finish> method does not affect the transaction status of the
database connection. It has nothing to do with transactions. It's mostly an
internal "housekeeping" method that is rarely needed.
See also L</disconnect> and the L</Active> attribute.
=head3 C<rows>
$rv = $sth->rows;
Returns the number of rows affected by the last row affecting command,
or -1 if the number of rows is not known or not available.
=head3 C<bind_col>
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:
The TYPE attribute for bind_col() was first specified in DBI 1.41.
From DBI 1.611, drivers can use the C<TYPE> attribute to attempt to
cast the bound scalar to a perl type which more closely matches
C<TYPE>. At present DBI supports C<SQL_INTEGER>, C<SQL_DOUBLE> and
C<SQL_NUMERIC>. See L</sql_type_cast> for details of how types are
cast.
=over
=item C<StrictlyTyped>
This attribute was first added in DBI 1.611. When 1.611 was released
few drivers actually supported this attribute but DBD::Oracle and
DBD::ODBC should from versions 1.24.
=item C<DiscardString>
This attribute was first added in DBI 1.611. When 1.611 was released
few drivers actually supported this attribute but DBD::Oracle and
DBD::ODBC should from versions 1.24.
=back
=head3 C<bind_columns>
$rc = $sth->bind_columns(@list_of_refs_to_vars_to_bind);
The list of references should have the same number of elements as the number of
columns in the C<SELECT> statement. If it doesn't then C<bind_columns> will
bind the elements given, up to the number of columns, and then return an error.
For example:
# you can also use Perl's \(...) syntax (see perlref docs):
# $sth->bind_columns(\($region, $sales));
Here's a more fancy example that binds columns to the values I<inside>
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";
}
=head3 C<dump_results>
Fetches all the rows from C<$sth>, calls C<DBI::neat_list> for each row, and
prints the results to C<$fh> (defaults to C<STDOUT>) separated by C<$lsep>
(default C<"\n">). C<$fsep> defaults to C<", "> and C<$maxlen> defaults to 35.
Example:
Some drivers cannot provide valid values for some or all of these
attributes until after C<$sth-E<gt>execute> has been successfully
called. Typically the attribute will be C<undef> in these situations.
For drivers which support stored procedures and multiple result sets
(see L</more_results>) these attributes relate to the I<current> result set.
=head3 C<NUM_OF_FIELDS>
Number of fields (columns) in the data the prepared statement may return.
Statements that don't return rows of data, like C<DELETE> and C<CREATE>
set C<NUM_OF_FIELDS> to 0 (though it may be undef in some drivers).
=head3 C<NUM_OF_PARAMS>
=head3 C<NAME>
Also note that the name returned for (aggregate) functions like C<count(*)>
or C<max(c_foo)> is determined by the database server and not by C<DBI> or
the C<DBD> backend.
=head3 C<NAME_lc>
=head3 C<NAME_uc>
=head3 C<NAME_hash>
=head3 C<NAME_lc_hash>
=head3 C<NAME_uc_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<NAME>,
C<NAME_lc>, and C<NAME_uc> 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";
=head3 C<TYPE>
ftp://sqlstandards.org/SC32/SQL_Registry/
All possible values for C<TYPE> should have at least one entry in the
output of the C<type_info_all> method (see L</type_info_all>).
=head3 C<PRECISION>
=head3 C<SCALE>
=head3 C<NULLABLE>
=head3 C<CursorName>
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<undef>.
=head3 C<Database>
=head3 C<Statement>
=head3 C<ParamValues>
* Keys:
* Values:
=head3 C<ParamTypes>
* Keys:
* Values:
The hash values are hashrefs of type information in the same form as that
passed to the various bind_param() methods (See L</bind_param> for the format
and values).
$sth->bind_param(1, SQL_INTEGER);
The driver may have modified the type information in some way based
on the bound values, other hints provided by the prepare()'d
SQL statement, or alternate type mappings required by the driver or target
database system. The driver may also add private keys (with names beginning
with the drivers reserved prefix, e.g., odbc_xxx).
* Example:
The keys and values in the returned hash can be passed to the various
bind_param() methods to effectively reproduce a previous param binding.
For example:
For example:
=head3 C<RowsInCache>
If the driver supports a local row cache for C<SELECT> statements, then
this attribute holds the number of un-fetched rows in the cache. If the
driver doesn't, then it returns C<undef>. Note that some drivers pre-fetch
rows on execute, whereas others wait till the first fetch.
column_info
foreign_key_info
primary_key_info
table_info
statistics_info
All catalog methods accept arguments in order to restrict the result sets.
Passing C<undef> to an optional argument does not constrain the search for
that argument.
However, an empty string ('') is treated as a regular search criteria
and will only match an empty value.
Most arguments in the catalog methods accept only I<ordinary values>, e.g.
the arguments of C<primary_key_info()>.
Such arguments are treated as a literal string, i.e. the case is significant
and quote characters are taken literally.
B<Caveat>: The underscore ('_') is valid and often used in SQL identifiers.
Passing such a value to a search pattern argument may return more rows than
expected!
To include pattern characters as literals, they must be preceded by an
escape character which can be achieved with
The ODBC and SQL/CLI specifications define a way to change the default
behaviour described above: All arguments (except I<list value arguments>)
are treated as I<identifier> if the C<SQL_ATTR_METADATA_ID> attribute is
set to C<SQL_TRUE>.
I<Quoted identifiers> are very similar to I<ordinary values>, i.e. their
body (the string within the quotes) is interpreted literally.
I<Unquoted identifiers> are compared in UPPERCASE.
=head2 Transactions
If the C<RaiseError> attribute is not set, then DBI calls would need to be
manually checked for errors, typically like this:
With C<RaiseError> set, the DBI will automatically C<die> if any DBI method
call on that handle (or a child handle) fails, so you don't have to
test the return value of each method call. See L</RaiseError> for more
details.
After calling C<commit> or C<rollback> many drivers will not let you
fetch from a previously active C<SELECT> 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<SELECT> statements.
Since values of that size can't usually be held in memory, and because
databases can't usually know in advance the length of the longest long
that will be returned from a C<SELECT> statement (unlike other data
types), some special handling is required.
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";
$dbh->disconnect;
my $sth = $dbh->prepare( q{
INSERT INTO table (name, phone) VALUES (?, ?)
});
$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<q{...}> style quoting used in these examples avoids clashing with
quotes that may be used in the SQL statement. Use the double-quote like
C<qq{...}> operator if you want to interpolate variables into the string.
See L<perlop/"Quote and Quote-like Operators"> for more details.
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 its 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).
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<not> 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<http://www.perlmonks.org/index.pl?node_id=288022>
The first thing to say is that signal handling in Perl versions less
than 5.8 is I<not> 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.
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 until 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<alarm()> and C<$SIG{ALRM}>.
=over 4
=item Cancel
=item Timeout
eval {
local $SIG{ALRM} = sub { die "TIMEOUT\n" }; # N.B. \n required
eval {
alarm($seconds);
... code to execute with timeout here (which may die) ...
};
# outer eval catches alarm that might fire JUST before this alarm(0)
alarm(0); # cancel alarm (if code ran fast)
die "$@" if $@;
};
if ( $@ eq "TIMEOUT\n" ) { ... }
elsif ($@) { ... } # some other error
The first (outer) eval is used to avoid the unlikely but possible
chance that the "code to execute" dies and the alarm fires before it
is cancelled. Without the outer eval, if this happened your program
will die if you have no ALRM handler or a non-local alarm handler
will be called.
=back
The code would look something like this (for the DBD-Oracle connect()):
See previous example for the reasoning around the double eval.
For a cleaner implementation that works across perl versions, see Lincoln Baxter's
Sys::SigAction module at L<http://search.cpan.org/~lbaxter/Sys-SigAction/>.
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<perlipc> manual.
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 the various DBI classes and how they work together.
The leading 'C<DBI>' 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<MySubDBI> and override the do(), prepare() and execute() methods,
then your do() and prepare() methods should be in the C<MySubDBI::db>
class and the execute() method should be in the C<MySubDBI::st> class.
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(...);
The only differences between the two are that using an explicit
RootClass attribute will a) make the DBI automatically attempt to load
a module by that name if the class doesn't exist, and b) won't call
your MySubDBI::connect() method, if you have one.
The default method does nothing. The call is made just to simplify
any post-connection setup that your subclass may want to perform.
The parameters are the same as passed to DBI->connect.
If your subclass supplies a connected method, it should be part of the
MySubDBI::db package.
One more thing to note: you must let the DBI do the handle creation. If you
want to override the connect() method in your *::dr class then it must still
call SUPER::connect to get a $dbh to work with. Similarly, an overridden
prepare() method in *::db must still call SUPER::prepare to get a $sth.
If you try to create your own handles using bless() then you'll find the DBI
will reject them with an "is not a DBI handle (has no magic)" error.
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;
}
=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.
Each handle has its 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 settings are restored when the called method
returns.
0 - Trace disabled.
1 - Trace top-level DBI method calls returning with results or errors.
2 - As above, adding tracing of top-level method entry with parameters.
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.
This is the first level to trace all the rows being fetched.
5 to 15 - As above but with more and more internal information.
The trace output is detailed and typically very useful. Much of the
trace output is formatted using the L</neat> function, so strings
in the trace output may be edited and truncated by that function.
In addition to the L</trace> method, you can enable the same trace
information, and direct the output to a file, by setting the
C<DBI_TRACE> environment variable before starting Perl.
See L</DBI_TRACE> for more information.
Finally, you can set, or get, the trace settings for a handle using
the C<TraceLevel> attribute.
B<NOTE>:
=over 4
=item *
Tied filehandles are not currently supported, as
tie operations are not available to the PerlIO
methods used by the DBI.
=item *
PerlIO layer support requires Perl version 5.8 or higher.
=back
my $scalar = '';
open( my $fh, "+>:scalar", \$scalar );
$dbh->trace( 2, $fh );
package MyFancyLogger;
sub new
{
my $self = {};
my $fh;
open $fh, '>', 'fancylog.log';
$self->{_fh} = $fh;
$self->{_buf} = '';
return bless $self, shift;
}
sub log
{
my $self = shift;
return unless exists $self->{_fh};
my $fh = $self->{_fh};
$self->{_buf} .= shift;
#
# DBI feeds us pieces at a time, so accumulate a complete line
# before outputing
#
print $fh "At ", scalar localtime(), ':', $self->{_buf}, "\n" and
$self->{_buf} = ''
if $self->{_buf}=~tr/\n//;
}
sub close {
my $self = shift;
return unless exists $self->{_fh};
my $fh = $self->{_fh};
print $fh "At ", scalar localtime(), ':', $self->{_buf}, "\n" and
$self->{_buf} = ''
if $self->{_buf};
close $fh;
delete $self->{_fh};
}
1;
package PerlIO::via::MyFancyLogLayer;
sub PUSHED
{
my ($class,$mode,$fh) = @_;
my $logger;
return bless \$logger,$class;
}
sub OPEN {
my ($self, $path, $mode, $fh) = @_;
#
# $path is actually our logger object
#
$$self = $path;
return 1;
}
sub WRITE
{
my ($self, $buf, $fh) = @_;
$$self->log($buf);
return length($buf);
}
sub CLOSE {
my $self = shift;
$$self->close();
return 0;
}
1;
use PerlIO::via::MyFancyLogLayer;
$dbh->trace('SQL', $fh);
Many of the values embedded in trace output are formatted using the neat()
utility function. This means they may be quoted, sanitized, and possibly
truncated if longer than C<$DBI::neat_maxlen>. See L</neat> for more details.
You can add tracing to your own application code using the L</trace_msg> method.
It can sometimes be handy to compare trace files from two different runs of the
same script. However using a tool like C<diff> on the original log output
doesn't work well because the trace file is full of object addresses that may
differ on each run.
The DBI includes a handy utility called dbilogstrip that can be used to
'normalize' the log content. It can be used as a filter like this:
=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
=head2 DBI_AUTOPROXY
=head2 DBI_USER
=head2 DBI_PASS
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
=head2 DBI_PROFILE
=head2 DBI_PUREPERL
=over 4
The C<$dbh> handle you're using to call C<prepare> is probably undefined because
the preceding C<connect> failed. You should always check the return status of
DBI methods, or use the L</RaiseError> attribute.
The C<$sth> handle you're using to call C<execute> is probably undefined because
the preceding C<prepare> failed. You should always check the return status of
DBI methods, or use the L</RaiseError> attribute.
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.
=back
=head1 Pure-Perl DBI
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.
http://msdn.microsoft.com/Search
And for SQL/CLI standard information on SQLColumns you'd read page 124 of
the (very large) SQL/CLI Working Draft available from:
http://jtc1sc32.org/doc/N0701-0750/32N0744T.pdf
http://cui.unige.ch/db-research/Enseignement/analyseinfo/SQL92/BNFindex.html
http://www.sqlstandards.org/SC32/WG3/Progression_Documents/Informal_working_drafts/
iso-9075-2-1999.bnf
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
Programming Perl 3rd Ed. by Larry Wall, Tom Christiansen & Jon Orwant.
L<http://books.perl.org/book/134>
http://search.cpan.org/search?mode=module&query=DBIx%3A%3A
http://search.cpan.org/search?mode=doc&query=DBI
http://poop.sourceforge.net
http://c2.com/cgi-bin/wiki?ObjectRelationalToolComparison
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.
http://groups.google.com/groups?group=perl.dbi.users
http://www.xray.mpe.mpg.de/mailing-lists/dbi/
http://www.mail-archive.com/dbi-users%40perl.org/
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://www.perlmonks.org/?node=DBI%20recipes
http://www.perlmonks.org/?node=Speeding%20up%20the%20DBI
http://www.jcc.com/sql_stnd.html
http://cuiwww.unige.ch/OSG/info/FreeDB/FreeDB.home.html
http://www.connectionstrings.com/
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.imperva.com/application_defense_center/white_papers/blind_sql_server_inj
ection.html
http://online.securityfocus.com/infocus/1644
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
http://language.perl.com/style/
=head2 FAQ
See L<http://faq.dbi-support.com/>
=head1 AUTHORS
This pod text by Tim Bunce, J. Douglas Dunlop, Jonathan Leffler and others.
Perl by Larry Wall and the C<perl5-porters>.
=head1 COPYRIGHT
You may distribute under the terms of either the GNU General Public
License or the Artistic License, as specified in the Perl 5.10.0 README file.
The DBI is free Open Source software. IT COMES WITHOUT WARRANTY OF ANY KIND.
=head2 Support
=head1 ACKNOWLEDGEMENTS
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 Ingeneering in the UK (L<http://www.ig.co.uk>) (formerly known as
the
Paul Ingram Group). 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 then a good way
to make that happen is to do it yourself and send me a patch to the
source code that shows the changes. (But read "Speak before you patch"
below.)
To keep informed about changes to the source you can send an empty email
to [email protected] 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 up to date using:
svn update
If you get any conflicts reported you'll need to fix them first.
Then generate the patch file from within the C<trunk> directory using:
Read the patch file, as a sanity check, and then email it to [email protected].
cd ..
=head1 TRANSLATIONS
http://www.oreilly.de/catalog/perldbiger/
http://cronopio.net/perl/ - Spanish
http://member.nifty.ne.jp/hippo2000/dbimemo.htm - Japanese
=head1 TRAINING
http://www.treepax.co.uk/
http://www.keller.com/dbweb/
=over 4
=back
=cut
# LocalWords: DBI