# $Id: DBI.pm 9678 2007-06-25 21:49:03Z timbo $
# vim: ts=8:sw=4
#
# Copyright (c) 1994-2007 Tim Bunce Ireland
#
# See COPYRIGHT section in pod text below for usage and distribution rights.
#
require 5.006_00;
BEGIN {
$DBI::VERSION = "1.58"; # ==> ALSO update the version in the pod text below!
}
=pod
=begin classdoc
Perl Database Interface. Base class for Perl's standard database access
API.
@author Tim Bunce
@since 1994-01-01
@see DBI Homepage
@see Programming the Perl DBI by Alligator Descartes and Tim Bunce.
@exports :sql_types List of standard SQL type names, mapped to their ISO-XXX values
@exports :sql_cursor_types List of standard SQL cursor types, mapped to the ISO-XXX values
@member $DBI::err Equivalent to $h->err.
@member $DBI::errstr Equivalent to $h->errstr.
@member $DBI::state Equivalent to $h->state.
@member $DBI::rows Equivalent to $h->rows.
@member $DBI::lasth DBI object handle used for the most recent DBI method call.
If the last DBI method call was DESTROY, returns the destroyed handle's parent.
=end classdoc
=cut
package DBI;
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
) ],
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
) ],
profile => [ qw(
dbi_profile dbi_profile_merge dbi_profile_merge_nodes dbi_time
) ], # notionally "in" DBI::Profile and normally imported from there
);
$DBI::dbi_debug = 0;
$DBI::neat_maxlen = 400;
# If you get an error here like "Can't find loadable object ..."
# then you haven't installed the DBI correctly. Read the README
# then install it again.
if ( $ENV{DBI_PUREPERL} ) {
eval { bootstrap DBI } if $ENV{DBI_PUREPERL} == 1;
require DBI::PurePerl if $@ or $ENV{DBI_PUREPERL} >= 2;
$DBI::PurePerl ||= 0; # just to silence "only used once" warnings
}
else {
bootstrap DBI;
}
$EXPORT_TAGS{preparse_flags} = [ grep { /^DBIpp_\w\w_/ } keys %{__PACKAGE__."::"} ];
Exporter::export_ok_tags(keys %EXPORT_TAGS);
}
=pod
=begin classdoc
@xs trace
Set the global default trace settings.
Also can be used to change where trace output is sent.
A similar method, $h->trace, sets the trace
settings for the specific handle it's called on.
@see
STDOUT.
@return the previous $trace_setting value
=end classdoc
=begin classdoc
@xs trace_msg
Write a message to the trace output.
@param $message_text message to be written
$optional $min_level the minimum trace level at which the message is written; default 1
@see
Strings will be quoted, although internal quotes will not be escaped.
Values known to be numeric will be unquoted. Undefined (NULL) values
will be shown as undef (without quotes).
If the string is flagged internally as UTF-8 then double quotes will be used, otherwise single quotes are used and unprintable characters will be replaced by dot (.).
This function is designed to format values for human consumption.
It is used internally by the DBI for $maxlen-4 and "...'" will be appended. If $maxlen is 0
or undef, it defaults to $DBI::neat_maxlen which, in turn, defaults to 400.
@return the neatly formatted string
=end classdoc
=begin classdoc
@xs looks_like_number
Do the parameter values look like numbers ?
@static
@param @array array of values to check for numbers
@returnlist true for each element that looks like a number,
false for each element that does not look like a number, and
undef for each element that is undefined or empty.
=end classdoc
=begin classdoc
@xs hash
Return a 32-bit integer 'hash' value computed over the contents of $buffer
using the $type hash algorithm.
@static
@param $buffer buffer over which the hash is computed
@optional $type hash algorithm to use. Valid values are
($scheme, $driver, $attr_string, $attr_hash, $driver_dsn),
where
connect_cached with the same parameter and attribute values, a
corresponding cached $dbh will be returned if it is still valid.
The cached database handle is replaced with a new connection if it
has been disconnected or if the ping method fails.
Caching connections can be useful in some applications, but it can also cause problems, such as too many connections, and so should be used with care. In particular, avoid changing the attributes of a database handle created via connect_cached() because it will affect other code that may be using the same handle.
The connection cache can be accessed (and cleared) via the CachedKids attribute:
my $CachedKids_hashref = $dbh->{Driver}->{CachedKids};
%$CachedKids_hashref = () if $CachedKids_hashref;
@param $data_source a Data Source String aka DSN specifying the driver and
associated driver-specific attributes to use for the connection. There is no standard
for the text following the driver name in the $data_source
DSN string. Refer to each driver's documentation for its DSN syntax.
@param $username the username to connect with; some drivers may accept an empty string
@param $password the password used to authenticate the user; some drivers may accept an empty string
@optional \%attr hashref of DBI and driver-specific attributes to be applied to the connection. Supported attributes include
$username parameter
$password parameter
Connection attributes may also be specified within the $data_source
parameter. For example:
dbi:DriverName(PrintWarn=>1,PrintError=>0,Taint=>1):...@return a DBI::_::db object (aka database handle) if the connection succeeds; otherwise, undef and sets both
$DBI::err and $DBI::errstr.
=end classdoc
=cut
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);
}
=pod
=begin classdoc
Establishes a database connection.
If $username or $password are undefined (rather than just empty),
then the DBI will substitute the values of the DBI_USER and DBI_PASS
environment variables, respectively. The DBI will warn if the
environment variables are not defined. However, the everyday use
of these environment variables is not recommended for security
reasons. The mechanism is primarily intended to simplify testing.
See below for alternative way to specify the username and password.
@param $data_source a Data Source String aka DSN specifying the driver and
associated driver-specific attributes to use for the connection. There is no standard
for the text following the driver name in the $data_source
DSN string. Refer to each driver's documentation for its DSN syntax.
@param $username the username to connect with; some drivers may accept an empty string
@param $password the password used to authenticate the user; some drivers may accept an empty string
@optional \%attr hashref of DBI and driver-specific attributes to be applied to the connection. Supported attributes include
$username parameter
$password parameter
Connection attributes may also be specified within the $data_source
parameter. For example:
dbi:DriverName(PrintWarn=>1,PrintError=>0,Taint=>1):...@return a DBI::_::db object (aka database handle) if the connection succeeds; otherwise, undef and sets both
$DBI::err and $DBI::errstr.
=end classdoc
=cut
sub connect {
my $class = shift;
my ($dsn, $user, $pass, $attr, $old_driver) = my @orig_args = @_;
my $driver;
if ($attr and !ref($attr)) { # switch $old_driver<->$attr if called in old style
Carp::carp("DBI->connect using 'old-style' syntax is deprecated and will be an error in future versions");
($old_driver, $attr) = ($attr, $old_driver);
}
my $connect_meth = $attr->{dbi_connect_method};
$connect_meth ||= $DBI::connect_via; # fallback to default
$dsn ||= $ENV{DBI_DSN} || $ENV{DBI_DBNAME} || '' unless $old_driver;
if ($DBI::dbi_debug) {
local $^W = 0;
pop @_ if $connect_meth ne 'connect';
my @args = @_; $args[2] = '****'; # hide password
DBI->trace_msg(" -> $class->$connect_meth(".join(", ",@args).")\n");
}
Carp::croak('Usage: $class->connect([$dsn [,$user [,$passwd [,\%attr]]]])')
if (ref $old_driver or ($attr and not ref $attr) or ref $pass);
# extract dbi:driver prefix from $dsn into $1
$dsn =~ s/^dbi:(\w*?)(?:\((.*?)\))?://i
or '' =~ /()/; # ensure $1 etc are empty if match fails
my $driver_attrib_spec = $2 || '';
# Set $driver. Old style driver, if specified, overrides new dsn style.
$driver = $old_driver || $1 || $ENV{DBI_DRIVER}
or Carp::croak("Can't connect to data source '$dsn' "
."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};
my %attributes; # take a copy we can delete from
if ($old_driver) {
%attributes = %$attr if $attr;
}
else { # new-style connect so new default semantics
%attributes = (
PrintError => 1,
AutoCommit => 1,
ref $attr ? %$attr : (),
# attributes in DSN take precedence over \%attr connect parameter
$driver_attrib_spec ? (split /\s*=>?\s*|\s*,\s*/, $driver_attrib_spec, -1) : (),
);
}
$attr = \%attributes; # now set $attr to refer to our local copy
my $drh = $DBI::installed_drh{$driver} || $class->install_driver($driver)
or die "panic: $class->install_driver($driver) failed";
# attributes in DSN take precedence over \%attr connect parameter
$user = $attr->{Username} if defined $attr->{Username};
$pass = $attr->{Password} if defined $attr->{Password};
delete $attr->{Password}; # always delete Password as closure stores it securely
if ( !(defined $user && defined $pass) ) {
($user, $pass) = $drh->default_user($user, $pass, $attr);
}
$attr->{Username} = $user; # force the Username to be the actual one used
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 };
# handle basic RootClass subclassing:
my $rebless_class = $apply->{RootClass} || ($class ne 'DBI' ? $class : '');
if ($rebless_class) {
no strict 'refs';
if ($apply->{RootClass}) { # explicit attribute (ie not static methd call class)
delete $apply->{RootClass};
DBI::_load_class($rebless_class, 0);
}
unless (@{"$rebless_class\::db::ISA"} && @{"$rebless_class\::st::ISA"}) {
Carp::carp("DBI subclasses '$rebless_class\::db' and ::st are not setup, RootClass ignored");
$rebless_class = undef;
$class = 'DBI';
}
else {
$dbh->{RootClass} = $rebless_class; # $dbh->STORE called via plain DBI::db
DBI::_set_isa([$rebless_class], 'DBI'); # sets up both '::db' and '::st'
DBI::_rebless($dbh, $rebless_class); # appends '::db'
}
}
if (%$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 } or $@ && warn $@;
}
}
# confirm to driver (ie if subclassed) that we've connected sucessfully
# and finished the attribute setup. pass in the original arguments
$dbh->connected(@orig_args); #if ref $dbh ne 'DBI::db' or $proxy;
DBI->trace_msg(" <- connect= $dbh\n") if $DBI::dbi_debug;
return $dbh;
};
my $dbh = &$connect_closure(undef, undef);
$dbh->{dbi_connect_closure} = $connect_closure if $dbh;
return $dbh;
}
=pod
=begin classdoc
Disconnect all connections on all installed DBI drivers.
=end classdoc
=cut
sub disconnect_all {
keys %DBI::installed_drh; # reset iterator
while ( my ($name, $drh) = each %DBI::installed_drh ) {
$drh->disconnect_all() if ref $drh;
}
}
sub disconnect { # a regular beginners bug
Carp::croak("DBI->disconnect is not a DBI method (read the DBI manual)");
}
sub install_driver { # croaks on failure
my $class = shift;
my($driver, $attr) = @_;
my $drh;
$driver ||= $ENV{DBI_DRIVER} || '';
# allow driver to be specified as a 'dbi:driver:' string
$driver = $1 if $driver =~ s/^DBI:(.*?)://i;
Carp::croak("usage: $class->install_driver(\$driver [, \%attr])")
unless ($driver and @_<=3);
# already installed
return $drh if $drh = $DBI::installed_drh{$driver};
$class->trace_msg(" -> $class->install_driver($driver"
.") for $^O perl=$] pid=$$ ruid=$< euid=$>\n")
if $DBI::dbi_debug;
# --- load the code
my $driver_class = "DBD::$driver";
eval qq{package # hide from PAUSE
DBI::_firesafe; # just in case
require $driver_class; # load the driver
};
if ($@) {
my $err = $@;
my $advice = "";
if ($err =~ /Can't find loadable object/) {
$advice = "Perhaps DBD::$driver was statically linked into a new perl binary."
."\nIn which case you need to use that new perl binary."
."\nOr perhaps only the .pm file was installed but not the shared object file."
}
elsif ($err =~ /Can't locate.*?DBD\/$driver\.pm in \@INC/) {
my @drv = $class->available_drivers(1);
$advice = "Perhaps the DBD::$driver perl module hasn't been fully installed,\n"
."or perhaps the capitalisation of '$driver' isn't right.\n"
."Available drivers: ".join(", ", @drv).".";
}
elsif ($err =~ /Can't load .*? for module DBD::/) {
$advice = "Perhaps a required shared library or dll isn't installed where expected";
}
elsif ($err =~ /Can't locate .*? in \@INC/) {
$advice = "Perhaps a module that DBD::$driver requires hasn't been fully installed";
}
Carp::croak("install_driver($driver) failed: $err$advice\n");
}
if ($DBI::dbi_debug) {
no strict 'refs';
(my $driver_file = $driver_class) =~ s/::/\//g;
my $dbd_ver = ${"$driver_class\::VERSION"} || "undef";
$class->trace_msg(" install_driver: $driver_class version $dbd_ver"
." loaded from $INC{qq($driver_file.pm)}\n");
}
# --- do some behind-the-scenes checks and setups on the driver
$class->setup_driver($driver_class);
# --- run the driver function
$drh = eval { $driver_class->driver($attr || {}) };
unless ($drh && ref $drh && !$@) {
my $advice = "";
$@ ||= "$driver_class->driver didn't return a handle";
# catch people on case in-sensitive systems using the wrong case
$advice = "\nPerhaps the capitalisation of DBD '$driver' isn't right."
if $@ =~ /locate object method/;
Carp::croak("$driver_class initialisation failed: $@$advice");
}
$DBI::installed_drh{$driver} = $drh;
$class->trace_msg(" <- install_driver= $drh\n") if $DBI::dbi_debug;
$drh;
}
*driver = \&install_driver; # currently an alias, may change
sub setup_driver {
my ($class, $driver_class) = @_;
my $type;
foreach $type (qw(dr db st)){
my $class = $driver_class."::$type";
no strict 'refs';
push @{"${class}::ISA"}, "DBD::_::$type"
unless UNIVERSAL::isa($class, "DBD::_::$type");
my $mem_class = "DBD::_mem::$type";
push @{"${class}_mem::ISA"}, $mem_class
unless UNIVERSAL::isa("${class}_mem", $mem_class)
or $DBI::PurePerl;
}
}
sub _rebless {
my $dbh = shift;
my ($outer, $inner) = DBI::_handles($dbh);
my $class = shift(@_).'::db';
bless $inner => $class;
bless $outer => $class; # outer last for return
}
sub _set_isa {
my ($classes, $topclass) = @_;
my $trace = DBI->trace_msg(" _set_isa([@$classes])\n");
foreach my $suffix ('::db','::st') {
my $previous = $topclass || 'DBI'; # trees are rooted here
foreach my $class (@$classes) {
my $base_class = $previous.$suffix;
my $sub_class = $class.$suffix;
my $sub_class_isa = "${sub_class}::ISA";
no strict 'refs';
if (@$sub_class_isa) {
DBI->trace_msg(" $sub_class_isa skipped (already set to @$sub_class_isa)\n")
if $trace;
}
else {
@$sub_class_isa = ($base_class) unless @$sub_class_isa;
DBI->trace_msg(" $sub_class_isa = $base_class\n")
if $trace;
}
$previous = $class;
}
}
}
sub _rebless_dbtype_subclass {
my ($dbh, $rootclass, $DbTypeSubclass) = @_;
# 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]);
}
sub _dbtype_names { # list dbtypes for hierarchy, ie Informix=>ADO=>ODBC
my ($dbh, $DbTypeSubclass) = @_;
if ($DbTypeSubclass && $DbTypeSubclass ne '1' && ref $DbTypeSubclass ne 'CODE') {
# treat $DbTypeSubclass as a comma separated list of names
my @dbtypes = split /\s*,\s*/, $DbTypeSubclass;
$dbh->trace_msg(" DbTypeSubclass($DbTypeSubclass)=@dbtypes (explicit)\n");
return @dbtypes;
}
# XXX will call $dbh->get_info(17) (=SQL_DBMS_NAME) in future?
my $driver = $dbh->{Driver}->{Name};
if ( $driver eq 'Proxy' ) {
# XXX Looking into the internals of DBD::Proxy is questionable!
($driver) = $dbh->{proxy_client}->{application} =~ /^DBI:(.+?):/i
or die "Can't determine driver name from proxy";
}
my @dbtypes = (ucfirst($driver));
if ($driver eq 'ODBC' || $driver eq 'ADO') {
# XXX will move these out and make extensible later:
my $_dbtype_name_regexp = 'Oracle'; # eg 'Oracle|Foo|Bar'
my %_dbtype_name_map = (
'Microsoft SQL Server' => 'MSSQL',
'SQL Server' => 'Sybase',
'Adaptive Server Anywhere' => 'ASAny',
'ADABAS D' => 'AdabasD',
);
my $name;
$name = $dbh->func(17, 'GetInfo') # SQL_DBMS_NAME
if $driver eq 'ODBC';
$name = $dbh->{ado_conn}->Properties->Item('DBMS Name')->Value
if $driver eq 'ADO';
die "Can't determine driver name! ($DBI::errstr)\n"
unless $name;
my $dbtype;
if ($_dbtype_name_map{$name}) {
$dbtype = $_dbtype_name_map{$name};
}
else {
if ($name =~ /($_dbtype_name_regexp)/) {
$dbtype = lc($1);
}
else { # generic mangling for other names:
$dbtype = lc($name);
}
$dbtype =~ s/\b(\w)/\U$1/g;
$dbtype =~ s/\W+/_/g;
}
# add ODBC 'behind' ADO
push @dbtypes, 'ODBC' if $driver eq 'ADO';
# add discovered dbtype in front of ADO/ODBC
unshift @dbtypes, $dbtype;
}
@dbtypes = &$DbTypeSubclass($dbh, \@dbtypes)
if (ref $DbTypeSubclass eq 'CODE');
$dbh->trace_msg(" DbTypeSubclass($DbTypeSubclass)=@dbtypes\n");
return @dbtypes;
}
sub _load_class {
my ($load_class, $missing_ok) = @_;
DBI->trace_msg(" _load_class($load_class, $missing_ok)\n", 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 $@;
}
sub init_rootclass { # deprecated
return 1;
}
*internal = \&DBD::Switch::dr::driver;
=pod
=begin classdoc
Return a list of all available drivers.
Searches for DBD::* modules
within the directories in @INC.
By default, a warning is issued if some drivers are hidden by others of the same name in earlier
directories. Passing a true value for $quiet will inhibit the warning.
@optional $quiet if true, silences the duplicate driver name warning.
@returnlist a list of all available DBI driver modules.
=end classdoc
=cut
sub available_drivers {
my($quiet) = @_;
my(@drivers, $d, $f);
local(*DBI::DIR, $@);
my(%seen_dir, %seen_dbd);
my $haveFileSpec = eval { require File::Spec };
foreach $d (@INC){
chomp($d); # Perl 5 beta 3 bug in #!./perl -Ilib from Test::Harness
my $dbd_dir =
($haveFileSpec ? File::Spec->catdir($d, 'DBD') : "$d/DBD");
next unless -d $dbd_dir;
next if $seen_dir{$d};
$seen_dir{$d} = 1;
# XXX we have a problem here with case insensitive file systems
# XXX since we can't tell what case must be used when loading.
opendir(DBI::DIR, $dbd_dir) || Carp::carp "opendir $dbd_dir: $!\n";
foreach $f (readdir(DBI::DIR)){
next unless $f =~ s/\.pm$//;
next if $f eq 'NullP';
if ($seen_dbd{$f}){
Carp::carp "DBD::$f in $d is hidden by DBD::$f in $seen_dbd{$f}\n"
unless $quiet;
} else {
push(@drivers, $f);
}
$seen_dbd{$f} = $d;
}
closedir(DBI::DIR);
}
# "return sort @drivers" will not DWIM in scalar context.
return wantarray ? sort @drivers : @drivers;
}
=pod
=begin classdoc
Returns a list of available drivers and their current installed versions.
Note that this loads all available drivers.
When called in a void context the installed_versions() method will print out a formatted list of the hash contents, one per line.
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
The installed_versions() method is primarily intended as a quick way to see from the command line what's installed. For example:
perl -MDBI -e 'DBI->installed_versions'@return in scalar context, a hash reference mapping driver names (without the 'DBD::' prefix) to versions, as well as other entries for the
DBI version, OS name, etc.
@returnlist the list of successfully loaded drivers (without the 'DBD::' prefix)
@since 1.38.
=end classdoc
=cut
sub installed_versions {
my ($class, $quiet) = @_;
my %error;
my %version = ( DBI => $DBI::VERSION );
$version{"DBI::PurePerl"} = $DBI::PurePerl::VERSION
if $DBI::PurePerl;
for my $driver ($class->available_drivers($quiet)) {
next if $DBI::PurePerl && grep { -d "$_/auto/DBD/$driver" } @INC;
my $drh = eval {
local $SIG{__WARN__} = sub {};
$class->install_driver($driver);
};
($error{"DBD::$driver"}=$@),next if $@;
no strict 'refs';
my $vers = ${"DBD::$driver" . '::VERSION'};
$version{"DBD::$driver"} = $vers || '?';
}
if (wantarray) {
return map { m/^DBD::(\w+)/ ? ($1) : () } sort keys %version;
}
if (!defined wantarray) { # void context
require Config; # add more detail
$version{OS} = "$^O\t($Config::Config{osvers})";
$version{Perl} = "$]\t($Config::Config{archname})";
$version{$_} = (($error{$_} =~ s/ \(\@INC.*//s),$error{$_})
for keys %error;
printf " %-16s: %s\n",$_,$version{$_}
for reverse sort keys %version;
}
return \%version;
}
=pod
=begin classdoc
Return a list of data sources (databases) available via the named
driver.
Data sources are returned in a form suitable for passing to the
dbi:$driver:" prefix.
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.
@see $driver is empty or undef,
then the value of the DBI_DRIVER environment variable is used.
@optional \%attr any supporting attributes required to locate databases for the specified driver.
@returnlist a list of complete DSN strings available via the specified driver.
=end classdoc
=cut
sub data_sources {
my ($class, $driver, @other) = @_;
my $drh = $class->install_driver($driver);
my @ds = $drh->data_sources(@other);
return @ds;
}
=pod
=begin classdoc
Calls neat() on each element of a list,
returning a single string of the results joined with $field_sep.
@static
@param \@listref arrayref of strings to "neaten"
@optional $maxlen the maximum length of each neaten'ed string; default 400
@optional $field_sep the string separator used to join the neatened strings; default ", "
@return a single string of the neatened strings joined with $field_sep.
=end classdoc
=cut
sub neat_list {
my ($listref, $maxlen, $sep) = @_;
$maxlen = 0 unless defined $maxlen; # 0 == use internal default
$sep = ", " unless defined $sep;
join($sep, map { neat($_,$maxlen) } @$listref);
}
sub dump_results { # also aliased as a method in DBD::_::st
my ($sth, $maxlen, $lsep, $fsep, $fh) = @_;
return 0 unless $sth;
$maxlen ||= 35;
$lsep ||= "\n";
$fh ||= \*STDOUT;
my $rows = 0;
my $ref;
while($ref = $sth->fetch) {
print $fh $lsep if $rows++ and $lsep;
my $str = neat_list($ref,$maxlen,$fsep);
print $fh $str; # done on two lines to avoid 5.003 errors
}
print $fh "\n$rows rows".($DBI::err ? " ($DBI::err: $DBI::errstr)" : "")."\n";
$rows;
}
=pod
=begin classdoc
Return an informal description of the difference between two strings.
Calls
For example, data_diff("abc", "ab\x{263a}") will return:
a: UTF8 off, ASCII, 3 characters 3 bytes
b: UTF8 on, non-ASCII, 3 characters 5 bytes
Strings differ at index 2: a[2]=c, b[2]=\x{263A}
If $a and $b are identical in both the characters they contain and
their physical encoding then data_diff() returns an empty string.
If $logical is true then physical encoding differences are ignored
(but are still reported if there is a difference in the characters).
@since 1.46
@static
@param $a first string
@param $b string to compare to the first string
@optional $logical if true, ignore physical encoding differences
@returns a string describing the differences between the input strings
=end classdoc
=cut
sub data_diff {
my ($a, $b, $logical) = @_;
my $diff = data_string_diff($a, $b);
return "" if $logical and !$diff;
my $a_desc = data_string_desc($a);
my $b_desc = data_string_desc($b);
return "" if !$diff and $a_desc eq $b_desc;
$diff ||= "Strings contain the same sequence of characters"
if length($a);
$diff .= "\n" if $diff;
return "a: $a_desc\nb: $b_desc\n$diff";
}
=pod
=begin classdoc
Return an informal description of the first character difference
between two strings. For example:
Params a & b Result ------------ ------ 'aaa', 'aaa' '' 'aaa', 'abc' 'Strings differ at index 2: a[2]=a, b[2]=b' 'aaa', undef 'String b is undef, string a has 3 characters' 'aaa', 'aa' 'String b truncated after 2 characters'Unicode characters are reported in
\x{XXXX} format. Unicode
code points in the range U+0800 to U+08FF are unassigned and most
likely to occur due to double-encoding. Characters in this range
are reported as \x{08XX}='C' where C is the corresponding
latin-1 character.
The data_string_diff() function only considers logical characters
and not the underlying encoding. See
UTF8 off, ASCII, 42 characters 42 bytes UTF8 off, non-ASCII, 42 characters 42 bytes UTF8 on, non-ASCII, 4 characters 6 bytes UTF8 on but INVALID encoding, non-ASCII, 4 characters 6 bytes UTF8 off, undefThe initial
UTF8 on/off refers to Perl's internal UTF8 flag.
If $string has the UTF8 flag set but the sequence of bytes it
contains are not a valid UTF-8 encoding then data_string_desc()
will report UTF8 on but INVALID encoding.
The
By default,
Warnings can be caught and processed using a
See also
By default,
If desired, the warnings can be caught and processed using a
By default,
If desired, the warnings can be caught and processed using a
If
Typically
The subroutine is called with three parameters: the error message
string, this handle object, and the first value returned by
the method that failed (typically undef).
If the subroutine returns a false value, the
For example, to
Errors may be suppressed, to a limited extent, by using
The subroutine is called the arguments that were passed to set_err(): the handle,
the
It is possible to 'stack' multiple HandleSetErr handlers by using
closures. See
The
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 might continue instead of failing.
@member ErrCount (unsigned integer) the count of calls to set_err() on this handle that recorded an error
(excluding warnings or information states). It is not reset by the DBI at any time.
@member TraceLevel (integer, inherited) the trace level and flags for this handle. May be used
to set the trace level and flags.
@member FetchHashKeyName (string, inherited) Specifies the case conversion applied to the
the field names used for the hash keys returned by fetchrow_hashref().
Defaults to '
A value of 0 means not to automatically fetch any long data.
Drivers may return undef or an empty string for long fields when
The default is typically 0 (zero) bytes but may vary between drivers.
Applications fetching long fields should set this value to slightly
larger than the longest long field value to be fetched.
Some databases return some long types encoded as pairs of hex digits.
For these types,
Changing the value of
If a fetch fails due to a long field truncation when
Currently only fetched data is tainted. It is possible that the results
of other DBI method calls, and the value of fetched attributes, may
also be tainted in future versions.
@member Taint (boolean, inherited) Sets both
The exact definition of 'read only' is rather fuzzy. See individual driver documentation for specific details.
If the driver can make the handle truly read-only (by issuing a statement like
"
A driver can set the
Library modules and proxy drivers can use the attribute to influence their behavior.
For example, the DBD::Gofer driver considers the
The attribute should be set to 1 or 0 (or undef). Other values are reserved.
=end classdoc
=cut
package # hide from PAUSE
DBD::_::dr; # ====== DRIVER ======
@DBD::_::dr::ISA = qw(DBD::_::common);
use strict;
=pod
=begin classdoc
@xs err
Return the error code from the last driver method called.
@return the native database engine error code; may be zero
to indicate a warning condition. May be an empty string
to indicate a 'success with information' condition. In both these
cases the value is false but not undef. The errstr() and state()
methods may be used to retrieve extra information in these cases.
@see
Should not be used to test for errors as some drivers may return
'success with information' or warning messages via errstr() for
methods that have not 'failed'.
@return One or more native database engine error messages as a single string;
multiple messages are separated by newline characters.
May be an empty string if the prior driver method returned successfully.
@see
The driver is free to return any value via
Should not be used to test for errors as drivers may return a
'success with information' or warning state code via state() for
methods that have not 'failed'.
@return if state is currently successful, an empty string; else,
a five character SQLSTATE code.
=end classdoc
=begin classdoc
@xs set_err
Set the
Setting
Setting
The $method parameter provides an alternate method name for the
Some special rules apply if the
If
The handle
The handle
This method is typically only used by DBI drivers and DBI subclasses.
@param $err an error code, or "" to indicate success with information, or 0 to indicate warning
@param $errstr a descriptive error message
@optional $state an associated five character SQLSTATE code; defaults to "S1000" if $err is true.
@optional \&method method name included in the
A similar method,
Note that the function
name is given as the last argument.
Also note that this method does not clear
a previous error ($DBI::err etc.), nor does it trigger automatic
error detection (RaiseError etc.), so the return
status and/or $h->err must be checked to detect errors.
@param @func_arguments any arguments to be passed to the function
@param $func the name of the function to be called
@see
Drivers should override this method and
check if $trace_flag_name is a driver specific trace flag and, if
not, then call the DBI's default parse_trace_flag().
@param $trace_flag_name the name of a (possibly driver-specific) trace flag as a string
@return if $trace_flag_name is a valid flag name, the corresponding bit flag; otherwise, undef
@since 1.42
=end classdoc
=begin classdoc
@xs swap_inner_handle
Swap the internals of 2 handle objects.
Brain transplants for handles. You don't need to know about this
unless you want to become a handle surgeon.
A DBI handle is a reference to a tied hash. A tied hash has an
inner hash that actually holds the contents. This
method swaps the inner hashes between two handles. The $h1 and $h2
handles still point to the same tied hashes, but what those hashes
are tied to is swapped. In effect $h1 becomes $h2 and
vice-versa. This is powerful stuff, expect problems. Use with care.
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:
To help tracing applications using fork the process id is shown in
the trace log whenever a DBI or handle trace() method is called.
The process id also shown for every method call if the DBI trace
level (not handle trace level) is set high enough to show the trace
from the DBI's method dispatcher, e.g. >= 9.
@member PrintWarn (boolean, inherited) controls printing of warnings issued
by this handle. When true, DBI checks method calls to see if a warning condition has
been set. If so, DBI effectively does a
By default,
Warnings can be caught and processed using a
See also
By default,
If desired, the warnings can be caught and processed using a
If
Typically
The subroutine is called with three parameters: the error message
string, this handle object, and the first value returned by
the method that failed (typically undef).
If the subroutine returns a false value, the
For example, to
Errors may be suppressed, to a limited extent, by using
The subroutine is called the arguments that were passed to set_err(): the handle,
the
It is possible to 'stack' multiple HandleSetErr handlers by using
closures. See
The
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 might continue instead of failing.
@member ErrCount (unsigned integer) the count of calls to set_err() on this handle that recorded an error
(excluding warnings or information states). It is not reset by the DBI at any time.
@member ShowErrorStatement (boolean, inherited) When true, causes the relevant
Statement text to be appended to the error messages generated by
If
A value of 0 means not to automatically fetch any long data.
Drivers may return undef or an empty string for long fields when
The default is typically 0 (zero) bytes but may vary between drivers.
Applications fetching long fields should set this value to slightly
larger than the longest long field value to be fetched.
Some databases return some long types encoded as pairs of hex digits.
For these types,
Changing the value of
If a fetch fails due to a long field truncation when
Currently only fetched data is tainted. It is possible that the results
of other DBI method calls, and the value of fetched attributes, may
also be tainted in future versions.
@member Taint (boolean, inherited) Sets both
The exact definition of 'read only' is rather fuzzy. See individual driver documentation for specific details.
If the driver can make the handle truly read-only (by issuing a statement like
"
A driver can set the
Library modules and proxy drivers can use the attribute to influence their behavior.
For example, the DBD::Gofer driver considers the
The attribute should be set to 1 or 0 (or undef). Other values are reserved.
@member AutoCommit (boolean) When true (the usual default), database changes executed by this handle
cannot be rolled-back (undone). If false, database changes automatically occur within a "transaction", which
must explicitly be committed or rolled back using the
See
The following values have special meaning:
See
Should not be used to test for errors as some drivers may return
'success with information' or warning messages via errstr() for
methods that have not 'failed'.
@return One or more native database engine error messages as a single string;
multiple messages are separated by newline characters.
May be an empty string if the prior driver method returned successfully.
@see
The driver is free to return any value via
Should not be used to test for errors as drivers may return a
'success with information' or warning state code via state() for
methods that have not 'failed'.
@return if state is currently successful, an empty string; else,
a five character SQLSTATE code.
=end classdoc
=begin classdoc
@xs set_err
Set the
Setting
Setting
The $method parameter provides an alternate method name for the
Some special rules apply if the
If
The handle
The handle
This method is typically only used by DBI drivers and DBI subclasses.
@param $err an error code, or "" to indicate success with information, or 0 to indicate warning
@param $errstr a descriptive error message
@optional $state an associated five character SQLSTATE code; defaults to "S1000" if $err is true.
@optional \&method method name included in the
A similar method,
Note that the function
name is given as the last argument.
Also note that this method does not clear
a previous error ($DBI::err etc.), nor does it trigger automatic
error detection (RaiseError etc.), so the return
status and/or $h->err must be checked to detect errors.
@param @func_arguments any arguments to be passed to the function
@param $func the name of the function to be called
@see
Drivers should override this method and
check if $trace_flag_name is a driver specific trace flag and, if
not, then call the DBI's default parse_trace_flag().
@param $trace_flag_name the name of a (possibly driver-specific) trace flag as a string
@return if $trace_flag_name is a valid flag name, the corresponding bit flag; otherwise, undef
@since 1.42
=end classdoc
=begin classdoc
@xs swap_inner_handle
Swap the internals of 2 handle objects.
Brain transplants for handles. You don't need to know about this
unless you want to become a handle surgeon.
A DBI handle is a reference to a tied hash. A tied hash has an
inner hash that actually holds the contents. This
method swaps the inner hashes between two handles. The $h1 and $h2
handles still point to the same tied hashes, but what those hashes
are tied to is swapped. In effect $h1 becomes $h2 and
vice-versa. This is powerful stuff, expect problems. Use with care.
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:
NOTE:
Drivers for databases which cannot prepare a
statement will typically store the statement in the returned
handle and process it when on a later Statement handle
Portable applications should not assume that a new statement can be
prepared and/or executed while still fetching results from a previous
statement.
Some command-line SQL tools require statement terminators, like a semicolon,
to indicate the end of a statement; such terminators should not normally
be required with the DBI.
The returned statement handle can be used to get the
statement metadata and invoke the
If
If
The transaction behaviour of the
The database is automatically disconnected by the
A warning is issued if called while some statement handles are active
(e.g., SELECT statement handles that have more data to fetch),
The warning may indicate that a fetch loop terminated early, perhaps due to an uncaught error.
To avoid the warning, call the
The arguments $catalog, $schema and $table may accept search patterns
according to the database/driver, for example: $table = '%FOO%';
The underscore character ('
Some drivers may return additional information:
Note that this method can be expensive, and may return a large amount of data.
Best practice is to apply the most specific filters possible.
Also, some database might not return rows for all tables, and,
if the search criteria do not match any tables, the returned statement handle may return no rows.
@param $catalog search pattern for catalogs to be queried;
The arguments $catalog, $schema, $table, and column may accept search patterns
according to the database/driver, for example: $table = '%FOO%';
The underscore character ('
Drivers which do not support one or more of the selection filter
parameters may return metadata for more tables than requested, which may
require additional filtering by the application.
If the search criteria do not match any columns, the returned statement handle may return no rows.
Some drivers may provide additional metadata beyond that listed below.
using lowercase field names with the driver-specific prefix.
Such fields should be accessed by name, not by column number.
Note: There is some overlap with statement attributes (in Perl) and
SQLDescribeCol (in ODBC). However, SQLColumns provides more metadata.
@param $catalog search pattern for catalogs to be queried;
The statement handle will return one row per column.
If there is no primary key, the statement handle will fetch no rows.
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.
@param $catalog the catalog name string for the table to be queried;
If both the primary key and foreign key table parameters are specified,
the resultset contains the foreign key metadata, if
any, in foreign key table that refers to the primary (unique) key of primary key table.
(Note: In SQL/CLI, the result is implementation-defined.)
If only primary key table parameters are specified, the result set contains
the primary key metadata of that table and all foreign keys that refer to it.
If only foreign key table parameters are specified, the result set contains
all foreign keys metadata in that table and the primary keys to which they refer.
(Note: In SQL/CLI, the result includes unique keys too.)
Note: The support for the selection criteria, such as
Warning: This method is experimental and may change.
The arguments don't accept search patterns (unlike
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.
@param $catalog the catalog name string for the table to be queried;
The type_info_all() method is not normally used directly.
The
The datatype entries are ordered by
The meaning of the fields is described in the documentation for
the
An 'index' hash is provided so you don't need to rely on index
values defined above. However, using DBD::ODBC with some old ODBC
drivers may return older names, shown as comments in the example above.
Another issue with the index hash is that the lettercase of the
keys is not defined. It is usually uppercase, as show here, but
drivers may return names with any lettercase.
Drivers may return extra driver-specific data type entries.
=end classdoc
=begin classdoc
@xs take_imp_data
Leaves this Database handle object in an almost dead, zombie-like, state.
Detaches the underlying database API connection data from the DBI handle.
After calling this method, all other methods except
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
The returned value can be passed as a
Some things to keep in mind...
The attributes for the cloned connect are the same as those used
for the original connect, with some other attribute merged over
them depending on the \%attr parameter.
If \%attr is given then the attributes it contains are merged into
the original attributes and override any with the same names.
If \%attr is not given then it defaults to a hash containing all
the attributes in the attribute cache of this database handle object,
excluding any non-code references, plus the main boolean attributes (RaiseError, PrintError,
AutoCommit, etc.). This behaviour is subject to change.
This method can be used even if the database handle is disconnected.
@optional \%attr hash reference of attribute values to merge with or override
this object's connection attributes
@since 1.33
=end classdoc
=cut
sub clone {
my ($old_dbh, $attr) = @_;
my $closure = $old_dbh->{dbi_connect_closure} or return;
unless ($attr) {
# copy attributes visible in the attribute cache
keys %$old_dbh; # reset iterator
while ( my ($k, $v) = each %$old_dbh ) {
# ignore non-code refs, i.e., caches, handles, Err etc
next if ref $v && ref $v ne 'CODE'; # HandleError etc
$attr->{$k} = $v;
}
# explicitly set attributes which are unlikely to be in the
# attribute cache, i.e., boolean's and some others
$attr->{$_} = $old_dbh->FETCH($_) for (qw(
AutoCommit ChopBlanks InactiveDestroy
LongTruncOk PrintError PrintWarn Profile RaiseError
ShowErrorStatement TaintIn TaintOut
));
}
# use Data::Dumper; warn Dumper([$old_dbh, $attr]);
my $new_dbh = &$closure($old_dbh, $attr);
unless ($new_dbh) {
# need to copy err/errstr from driver back into $old_dbh
my $drh = $old_dbh->{Driver};
return $old_dbh->set_err($drh->err, $drh->errstr, $drh->state);
}
return $new_dbh;
}
=pod
=begin classdoc
Quote a database object identifier (table name etc.) for use in an SQL statement.
Special characters (such as double quotation marks) are escaped,
and the required type of outer quotation mark are added.
Undefined names are ignored and the remainder are quoted and then
joined together, typically with a dot (
If three names are supplied, the first is assumed to be a
catalog name and special rules may be applied based on what
Quote will probably 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.
It is valid for the quote() method to return an SQL expression that
evaluates to the desired string. For example:
Using placeholders and
If the
This method defaults to pushing a single column
value (the first) from each row into the result array. However,
if the '
If another call is made to
Caveat emptor: This caching can be useful in some applications,
but it can also cause problems and should be used with care.
@param $statement the SQL statement text to be prepared
@optional \%attr a hash reference of any desired statement attributes to apply to the $statement.
@optional $if_active adjusts the behaviour if an already cached statement handle is still
Attempts to determine, in a reasonably efficient way, if the database
server is still running and the connection to it is still working.
Individual drivers should implement this function in the most suitable
manner for their database engine.
The default implementation always returns true without
actually doing anything. Actually, it returns "
@return
If
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.
Although not mentioned explicitly in the standards, it seems there
is a simple relationship between these values:
To help tracing applications using fork the process id is shown in
the trace log whenever a DBI or handle trace() method is called.
The process id also shown for every method call if the DBI trace
level (not handle trace level) is set high enough to show the trace
from the DBI's method dispatcher, e.g. >= 9.
@member PrintWarn (boolean, inherited) controls printing of warnings issued
by this handle. When true, DBI checks method calls to see if a warning condition has
been set. If so, DBI effectively does a
By default,
Warnings can be caught and processed using a
See also
By default,
If desired, the warnings can be caught and processed using a
If
Typically
The subroutine is called with three parameters: the error message
string, this handle object, and the first value returned by
the method that failed (typically undef).
If the subroutine returns a false value, the
For example, to
Errors may be suppressed, to a limited extent, by using
The subroutine is called the arguments that were passed to set_err(): the handle,
the
It is possible to 'stack' multiple HandleSetErr handlers by using
closures. See
The
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 might continue instead of failing.
@member ErrCount (unsigned integer) the count of calls to set_err() on this handle that recorded an error
(excluding warnings or information states). It is not reset by the DBI at any time.
@member ShowErrorStatement (boolean, inherited) When true, causes the relevant
Statement text to be appended to the error messages generated by
If
A value of 0 means not to automatically fetch any long data.
Drivers may return undef or an empty string for long fields when
The default is typically 0 (zero) bytes but may vary between drivers.
Applications fetching long fields should set this value to slightly
larger than the longest long field value to be fetched.
Some databases return some long types encoded as pairs of hex digits.
For these types,
Changing the value of
If a fetch fails due to a long field truncation when
Currently only fetched data is tainted. It is possible that the results
of other DBI method calls, and the value of fetched attributes, may
also be tainted in future versions.
@member Taint (boolean, inherited) Sets both
The exact definition of 'read only' is rather fuzzy. See individual driver documentation for specific details.
If the driver can make the handle truly read-only (by issuing a statement like
"
A driver can set the
Library modules and proxy drivers can use the attribute to influence their behavior.
For example, the DBD::Gofer driver considers the
The attribute should be set to 1 or 0 (or undef). Other values are reserved.
@member NUM_OF_FIELDS (integer, read-only) number of fields (columns) the prepared statement may return.
Returns zero for statements that don't return data (e.g.,
If there is no compatible vendor-supplied ODBC driver,
the driver may return type numbers in the range
reserved for use by the DBI: -9999 to -9000.
All
For character type columns, the value is the OCTET_LENGTH,
in other words the number of bytes, not characters.
@member SCALE (array-ref, read-only) an array reference containing the integer scale values for each column.
Values in the hash may not be exactly the same as those passed to bind_param() or execute(),
as the driver may modify values based on the bound TYPE specificication.
The hash values can be passed to another bind_param() method with the same TYPE and will be seen by the
database as the same value.
Similary, depending on the driver's parameter naming requirements, keys in the hash may not
be exactly the same as those implied by the prepared statement.
@member ParamArrays (hash ref, read-only) a reference to a hash containing the values currently bound to
placeholders via
Each key value is an array reference containing a list of the bound
parameters for that column. For example:
If no values have been bound yet, returns a hash with the placeholder name
keys, but all the values undef (some drivers may return
a ref to an empty hash, or, provide type information supplied by the database.
If not supported by the driver, returns
The values in the hash may not be exactly the same as those passed to bind_param() or execute(),
as the driver may modify type information 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.
Similarly, depending on the driver's parameter naming requirements, keys in the hash may not be
exactly the same as those implied by the prepared statement
@member Statement (string, read-only) the statement string passed to the
The data type for a placeholder cannot be changed after the first
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.
As an alternative to specifying the data type in the
Placeholders within a statement string are normally indicated with
a question mark character (
The data type for a placeholder cannot be changed after the first
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.
As an alternative to specifying the data type in the
Note that bind_param_array() can not be used to expand a
placeholder into a list of values for a statement like "SELECT foo
WHERE bar IN (?)". A placeholder can only ever represent one value
per execution.
Scalar values, including
The default implementation provided by DBI (for drivers that have
not implemented array binding) is to iteratively call
The default implementation currently only supports non-data
returning statements (e.g., INSERT, UPDATE, but not SELECT). Also,
For maximum portability between drivers, this method should be called
after
Bind values are supplied column-wise in the
Where column-wise binding is used, the maximum number of elements in
any one of the bound value arrays determines the number of tuples
executed. Placeholders with fewer values in their parameter arrays
are treated as if padded with undef (NULL) values.
If a scalar value (rather than array reference) is bound, it is
treated as a variable length array with all elements having the
same value. It does not influence the number of tuples executed;
if all bound arrays have zero elements then zero tuples will
be executed. If all bound values are scalars, one tuple
will be executed, making execute_array() act like execute().
The
As a convienience, the
The values specified via
The
For tuples which are successfully executed, the element at the same
ordinal position in the status array is the resulting rowcount.
If the execution of a tuple causes an error, the corresponding
status array element will be set to an array reference containing
the error code and error string set by the failed execution.
If any tuple execution returns an error,
Support for data returning statements such as SELECT is driver-specific
and subject to change. At present, the default implementation
provided by DBI only supports non-data returning statements.
Transaction semantics when using array binding are driver and
database specific. If
Note that performance will usually be better with
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.
Although each tuple returned by $fetch_tuple_sub is effectively used
to call
A standard
If $slice is a hash reference, this method uses
Should not be used to test for errors as some drivers may return
'success with information' or warning messages via errstr() for
methods that have not 'failed'.
@return One or more native database engine error messages as a single string;
multiple messages are separated by newline characters.
May be an empty string if the prior driver method returned successfully.
@see
The driver is free to return any value via
Should not be used to test for errors as drivers may return a
'success with information' or warning state code via state() for
methods that have not 'failed'.
@return if state is currently successful, an empty string; else,
a five character SQLSTATE code.
=end classdoc
=begin classdoc
@xs set_err
Set the
Setting
Setting
The $method parameter provides an alternate method name for the
Some special rules apply if the
If
The handle
The handle
This method is typically only used by DBI drivers and DBI subclasses.
@param $err an error code, or "" to indicate success with information, or 0 to indicate warning
@param $errstr a descriptive error message
@optional $state an associated five character SQLSTATE code; defaults to "S1000" if $err is true.
@optional \&method method name included in the
A similar method,
Note that the function
name is given as the last argument.
Also note that this method does not clear
a previous error ($DBI::err etc.), nor does it trigger automatic
error detection (RaiseError etc.), so the return
status and/or $h->err must be checked to detect errors.
@param @func_arguments any arguments to be passed to the function
@param $func the name of the function to be called
@see
Drivers should override this method and
check if $trace_flag_name is a driver specific trace flag and, if
not, then call the DBI's default parse_trace_flag().
@param $trace_flag_name the name of a (possibly driver-specific) trace flag as a string
@return if $trace_flag_name is a valid flag name, the corresponding bit flag; otherwise, undef
@since 1.42
=end classdoc
=begin classdoc
@xs private_attribute_info
Return the list of driver private attributes for this handle object.
@return a hash reference mapping attribute name as keys to
A DBI handle is a reference to a tied hash. A tied hash has an
inner hash that actually holds the contents. This
method swaps the inner hashes between two handles. The $h1 and $h2
handles still point to the same tied hashes, but what those hashes
are tied to is swapped. In effect $h1 becomes $h2 and
vice-versa. This is powerful stuff, expect problems. Use with care.
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:
This method acts like
Note that unlike
The data type for a placeholder cannot be changed after the first
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.
As an alternative to specifying the data type in this call,
consider using the default type (
If any
If called on a statement handle that's still active,
(
For data returning statements, this method starts the query within the
database engine. Use one of the fetch methods to retrieve the data after
calling
The
The error, warning, or informational status of this method is available
via the
Note that the same array reference is returned for each fetch, and so
should not be stores and reused 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.
@return an array reference containing the current row's field values.
Null fields are returned as
This is a deprecated alias for
This method is not as efficient as
The keys of the hash are the same names returned by
By default a reference to a new hash is returned for each row.
It is likely that a future version of the DBI will support an
attribute which will enable the same hash to be reused for each
row. This will give a significant performance boost, but it won't
be enabled by default because of the risk of breaking old code.
=end classdoc
=begin classdoc
@xs finish
Indicate that no more data will be fetched from this statement handle
before it is either executed again or destroyed. This method
is rarely needed, and frequently overused, but can sometimes be
helpful in a few very specific situations to allow the server to free
up resources (such as sort buffers).
When all the data has been fetched from a data returning statement, the
driver should automatically call this method; therefore, calling this
method explicitly should not be needed, except when all rows
have not benn fetched from this statement handle.
Resets the
This method does not affect the transaction status of the
parent database connection.
@see
For data returning statements, it is generally not possible to know how many
rows will be returned except by fetching them all. Some drivers will
return the number of rows the application has fetched so far, but
others may return -1 until all rows have been fetched; therefore, use of this
method (or
An alternative method to get a row count for a data returning statement is to execute a
Note that columns do not need to be bound in order to fetch data.
For maximum portability between drivers, bind_col() should be called
after execute().
Whenever a row is fetched from this statement handle,
Binding a tied variable is not currently supported.
The data type for a bind variable cannot be changed after the first
This method is a handy utility for prototyping and
testing queries. Since it uses ASCII vs non-ASCII portion shows ASCII if all the
characters in the string are ASCII (have code points <= 127).
@param $string string to be described
@return a string describing the properties of the string
@since 1.46
@static
=end classdoc
=cut
sub data_string_desc { # describe a data string
my ($a) = @_;
require bytes;
require utf8;
# hacks to cater for perl 5.6
*utf8::is_utf8 = sub { (DBI::neat(shift)=~/^"/) } unless defined &utf8::is_utf8;
*utf8::valid = sub { 1 } unless defined &utf8::valid;
# Give sufficient info to help diagnose at least these kinds of situations:
# - valid UTF8 byte sequence but UTF8 flag not set
# (might be ascii so also need to check for hibit to make it worthwhile)
# - UTF8 flag set but invalid UTF8 byte sequence
# could do better here, but this'll do for now
my $utf8 = sprintf "UTF8 %s%s",
utf8::is_utf8($a) ? "on" : "off",
utf8::valid($a||'') ? "" : " but INVALID encoding";
return "$utf8, undef" unless defined $a;
my $is_ascii = $a =~ m/^[\000-\177]*$/;
return sprintf "%s, %s, %d characters %d bytes",
$utf8, $is_ascii ? "ASCII" : "non-ASCII",
length($a), bytes::length($a);
}
sub connect_test_perf {
my($class, $dsn,$dbuser,$dbpass, $attr) = @_;
Carp::croak("connect_test_perf needs hash ref as fourth arg") unless ref $attr;
# these are non standard attributes just for this special method
my $loops ||= $attr->{dbi_loops} || 5;
my $par ||= $attr->{dbi_par} || 1; # parallelism
my $verb ||= $attr->{dbi_verb} || 1;
my $meth ||= $attr->{dbi_meth} || 'connect';
print "$dsn: testing $loops sets of $par connections:\n";
require "FileHandle.pm"; # don't let toke.c create empty FileHandle package
local $| = 1;
my $drh = $class->install_driver($dsn) or Carp::croak("Can't install $dsn driver\n");
# test the connection and warm up caches etc
$drh->connect($dsn,$dbuser,$dbpass) or Carp::croak("connect failed: $DBI::errstr");
my $t1 = dbi_time();
my $loop;
for $loop (1..$loops) {
my @cons;
print "Connecting... " if $verb;
for (1..$par) {
print "$_ ";
push @cons, ($drh->connect($dsn,$dbuser,$dbpass)
or Carp::croak("connect failed: $DBI::errstr\n"));
}
print "\nDisconnecting...\n" if $verb;
for (@cons) {
$_->disconnect or warn "disconnect failed: $DBI::errstr"
}
}
my $t2 = dbi_time();
my $td = $t2 - $t1;
printf "$meth %d and disconnect them, %d times: %.4fs / %d = %.4fs\n",
$par, $loops, $td, $loops*$par, $td/($loops*$par);
return $td;
}
# Help people doing DBI->errstr, might even document it one day
# XXX probably best moved to cheaper XS code if this gets documented
sub err { $DBI::err }
sub errstr { $DBI::errstr }
# --- Private Internal Function for Creating New DBI Handles
# XXX move to PurePerl?
*DBI::dr::TIEHASH = \&DBI::st::TIEHASH;
*DBI::db::TIEHASH = \&DBI::st::TIEHASH;
# These three special constructors are called by the drivers
# The way they are called is likely to change.
our $shared_profile;
sub _new_drh { # called by DBD::$SIG{__WARN__} hook) for certain bad practices;
@member Type (scalar, read-only) "dr" (the type of this handle object)
@member ChildHandles (array ref, read-only) a reference to an array of all
connection handles created by this handle which are still accessible. The
contents of the array are weak-refs and will become undef when the
handle goes out of scope. undef if your Perl version does not support weak
references (check the warn("$class $method warning: $DBI::errstr")
where $class is the driver class and $method is the name of
the method which failed.
DBI->connect sets PrintWarn "on" if $^W is true.
$SIG{__WARN__}
handler or modules like CGI::Carp and CGI::ErrorWrap.
warn) in addition to returning error codes in the normal way. When true,
any method which results in an error causes DBI to effectively do a
warn("$class $method failed: $DBI::errstr") where $class
is the driver class and $method is the name of the method which failed.
DBI->connect sets PrintError "on".
$SIG{__WARN__}
handler or modules like CGI::Carp and CGI::ErrorWrap.
@member PrintError (boolean, inherited) When true, forces errors to generate warnings
(in addition to returning error codes in the normal way)
via a warn("$class $method failed: $DBI::errstr"), where $class
is the driver class and $method is the name of the method which failed.
DBI->connect sets PrintError "on".
$SIG{__WARN__}
handler or modules like CGI::Carp and CGI::ErrorWrap.
@member RaiseError (boolean, inherited) When true (default false), errors raise exceptions rather
than simply returning error codes in the normal way.
Exceptions are raised via a die("$class $method failed: $DBI::errstr"),
where $class is the driver class and $method is the name of the method
that failed.
PrintError is also on, the PrintError is done first.
RaiseError is used in conjunction with eval { ... }
to catch the exception that's been thrown and followed by an
if ($@) { ... } block to handle the caught exception.
For example:
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
}
@member HandleError (code ref, inherited) When set to a subroutine reference, provides
alternative behaviour in case of errors. The subroutine reference is called when an
error is detected (at the same point that RaiseError and PrintError are handled).
RaiseError
and/or PrintError attributes are checked and acted upon as normal.
die with a full stack trace for any error:
use Carp;
$h->{HandleError} = sub { confess(shift) };
Or to turn errors into exceptions:
use Exception; # or your own favourite exception module
$h->{HandleError} = sub { Exception->new('DBI')->raise($_[0]) };
It is possible to 'stack' multiple HandleError handlers by using closures:
sub your_subroutine {
my $previous_handler = $h->{HandleError};
$h->{HandleError} = sub {
return 1 if $previous_handler and &$previous_handler(@_);
... your code here ...
};
}
The error message that will be used by RaiseError and PrintError
can be altered by changing the value of $_[0].
$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;
};
@member HandleSetErr (code ref, inherited) When set to a subroutien reference, intercepts
the setting of this handle's err, errstr, and state values.
err, errstr, and 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 HandleSetErr and HandleError subroutines differ in that
HandleError is only invoked at the point where DBI is about to return to the application
with err set true; it is not invoked by the failure of a method that's
been called by another DBI method. HandleSetErr is called
whenever set_err() is called with a defined err value, even if false.
Thus, the HandleSetErr subroutine may be called multiple
times within a method and is usually invoked from deep within driver code.
NAME' but it is recommended to set it to either 'NAME_lc'
or 'NAME_uc'.
@member ChopBlanks (boolean, inherited) When true (default false), trailing space characters are
trimmed from returned fixed width character (CHAR) fields. No other field types are affected,
even where field values have trailing spaces.
@member LongReadLen (unsigned integer, inherited) Sets the maximum
length of 'long' type fields (LONG, BLOB, CLOB, MEMO, etc.) which the driver will
read from the database automatically when it fetches each row of data.
The LongReadLen attribute only relates to fetching and reading
long values; it is not involved in inserting or updating them.
LongReadLen is 0.
LongReadLen relates to the underlying data
length and not the doubled-up length of the encoded string.
LongReadLen for a statement handle after it
has been prepare'd will typically have no effect, so it's common to
set LongReadLen on the database or driver handle before calling prepare.
@member LongTruncOk (boolean, inherited) When false (the default), fetching a long value that
needs to be truncated (usually due to exceeding LongReadLen) will cause the fetch to fail.
(Applications should always be sure to
check for errors after a fetch loop in case an error, such as a divide
by zero or long field truncation, caused the fetch to terminate
prematurely.)
LongTruncOk is
false, many drivers will allow you to continue fetching further rows.
@member TaintIn (boolean, inherited) When true (default false), and Perl is running in
taint mode (e.g., started with the -T option), then all the arguments
to most DBI method calls are checked for being tainted. This may change.
If Perl is not running in taint mode, this attribute has no effect.
@member TaintOut (boolean, inherited) When true (default false), and Perl is running in
taint mode (e.g., started with the -T option), then most data fetched
from the database is considered tainted. This may change.
If Perl is not running in taint mode, this attribute has no effect.
set transaction read only", for example) then it should.
Otherwise the attribute is simply advisory.
ReadOnly attribute itself to indicate that the data it
is connected to cannot be changed for some reason.
ReadOnly attribute when
making a decison about whether to retry an operation that failed.
00000 is translated to any empty string
(false). If the driver does not support SQLSTATE (and most don't),
then state() will return S1000 (General Error) for all errors.
state, e.g., warning
codes, even if it has not declared an error by returning a true value
via the err() method described above.
err, errstr, and state values for the handle.
If the err,
errstr, and state values are not altered and set_err() returns
an empty list (it normally returns $rv which defaults to undef, see below).
$err to a true value indicates an error and will trigger
the normal DBI error handling mechanisms, such as RaiseError and
HandleError, if they are enabled, when execution returns from
the DBI back to the application.
$err to "" indicates an 'information' state, and setting
it to "0" indicates a 'warning' state. Setting $err to undef
also sets $errstr to undef, and $state to "", irrespective
of the values of the $errstr and $state parameters.
RaiseError/PrintError/PrintWarn error string instead of
the fairly unhelpful 'set_err'.
err or errstr
values for the handle are already set.
errstr is true then: " [err was %s now %s]" is appended if $err is
true and err is already true and the new err value differs from the original
one. Similarly " [state was %s now %s]" is appended if $state is true and state is
already true and the new state value differs from the original one. Finally
"\n" and the new $errstr are appended if $errstr differs from the existing
errstr value. Obviously the %s's above are replaced by the corresponding values.
err value is set to $err if: $err is true; or handle
err value is undef; or $err is defined and the length is greater
than the handle err length. The effect is that an 'information'
state only overrides undef; a 'warning' overrides undef or 'information',
and an 'error' state overrides anything.
state value is set to $state if $state is true and
the handle err value was set (by the rules above).
RaiseError/PrintError/PrintWarn error string
@optional $rv the value to return from this method; default undef
@return the $rv value, if specified; else undef.
=end classdoc
=begin classdoc
@xs trace
Set the trace settings for the handle object.
Also can be used to change where trace output is sent.
DBI->trace, sets the global default trace
settings.
@see
@optional $trace_file either a string filename, or a Perl filehandle reference, to which
trace output is to be appended. If not spcified, traces are sent to STDOUT.
@return the previous $trace_setting value
=end classdoc
=begin classdoc
@xs trace_msg
Write a trace message to the handle object's current trace output.
@param $message_text message to be written
$optional $min_level the minimum trace level at which the message is written; default 1
@see install_method() in |") or comma
(",") characters. For example: "SQL|3|foo".
@return the corresponding integer value used internally by the DBI and drivers.
@since 1.42
=end classdoc
=begin classdoc
@xs parse_trace_flag
Return the bit flag value for the specified trace flag name.
Original state:
dbh1o -> dbh1i
sthAo -> sthAi(dbh1i)
dbh2o -> dbh2i
swap_inner_handle dbh1o with dbh2o:
dbh2o -> dbh1i
sthAo -> sthAi(dbh1i)
dbh1o -> dbh2i
create new sth from dbh1o:
dbh2o -> dbh1i
sthAo -> sthAi(dbh1i)
dbh1o -> dbh2i
sthBo -> sthBi(dbh2i)
swap_inner_handle sthAo with sthBo:
dbh2o -> dbh1i
sthBo -> sthAi(dbh1i)
dbh1o -> dbh2i
sthAo -> sthBi(dbh2i)
@param $h2 the handle object to swap with this handle
@optional $allow_reparent if true, permits the two handles to have
different parent objects; default is false
@return true if the swap succeeded; otherwise, undef
@since 1.44
=end classdoc
=cut
sub default_user {
my ($drh, $user, $pass, $attr) = @_;
$user = $ENV{DBI_USER} unless defined $user;
$pass = $ENV{DBI_PASS} unless defined $pass;
return ($user, $pass);
}
sub connect { # normally overridden, but a handy default
my ($drh, $dsn, $user, $auth) = @_;
my ($this) = DBI::_new_dbh($drh, {
'Name' => $dsn,
});
# XXX debatable as there's no "server side" here
# (and now many uses would trigger warnings on DESTROY)
# $this->STORE(Active => 1);
# so drivers should set it in their own connect
$this;
}
sub connect_cached {
my $drh = shift;
my ($dsn, $user, $auth, $attr) = @_;
my $cache = $drh->{CachedKids} ||= {};
my @attr_keys = $attr ? sort keys %$attr : ();
my $key = do { local $^W; # silence undef warnings
join "~~", $dsn, $user, $auth, $attr ? (@attr_keys,@{$attr}{@attr_keys}) : ()
};
my $dbh = $cache->{$key};
$drh->trace_msg(sprintf(" connect_cached: key '$key', cached dbh $dbh\n", DBI::neat($key), DBI::neat($dbh)))
if $DBI::dbi_debug >= 4;
my $cb = $attr->{Callbacks}; # take care not to autovivify
if ($dbh && $dbh->FETCH('Active') && eval { $dbh->ping }) {
# If the caller has provided a callback then call it
if ($cb and $cb = $cb->{"connect_cached.reused"}) {
local $_ = "connect_cached.reused";
$cb->($dbh, $dsn, $user, $auth, $attr);
}
return $dbh;
}
# If the caller has provided a callback then call it
if ($cb and $cb = $cb->{"connect_cached.new"}) {
local $_ = "connect_cached.new";
$cb->($dbh, $dsn, $user, $auth, $attr);
}
$dbh = $drh->connect(@_);
$cache->{$key} = $dbh; # replace prev entry, even if connect failed
return $dbh;
}
}
{
=pod
=begin classdoc
Database (aka Connection) handle. Represents a single logical connection
to a database. Acts as a factory for Statement handle objects. Provides
methods for
@member Active (boolean, read-only) when true, indicates this handle object is "active".
The exact meaning of active is somewhat vague at the moment. Typically means that this handle is
connected to a database
@member Executed (boolean) when true, this handle object has been "executed".
Only the do() method sets this attribute. When set, also sets the parent driver
handle's Executed attribute. Cleared by commit() and rollback() methods (even if they fail).
@member Kids (integer, read-only) the number of currently existing statement handles
created from this handle.
@member ActiveKids (integer, read-only) the number of currently existing statement handles
created from this handle that are Active.
@member CachedKids (hash ref) a reference to the cache (hash) of
statement handles created by the $SIG{__WARN__} hook) for certain bad practices;
@member Type (scalar, read-only) "db" (the type of this handle object)
@member ChildHandles (array ref, read-only) a reference to an array of all
statement handles created by this handle which are still accessible. The
contents of the array are weak-refs and will become undef when the
handle goes out of scope. undef if your Perl version does not support weak
references (check the Active. Designed for use in Unix applications
that "fork" child processes: Either the parent or the child process
(but not both) should set InactiveDestroy true on all their shared handles.
(Note that some databases, including Oracle, don't support passing a
database connection across a fork.)
warn("$class $method warning: $DBI::errstr")
where $class is the driver class and $method is the name of
the method which failed.
DBI->connect sets PrintWarn "on" if $^W is true.
$SIG{__WARN__}
handler or modules like CGI::Carp and CGI::ErrorWrap.
warn("$class $method failed: $DBI::errstr"), where $class
is the driver class and $method is the name of the method which failed.
DBI->connect sets PrintError "on".
$SIG{__WARN__}
handler or modules like CGI::Carp and CGI::ErrorWrap.
@member RaiseError (boolean, inherited) When true (default false), errors raise exceptions rather
than simply returning error codes in the normal way.
Exceptions are raised via a die("$class $method failed: $DBI::errstr"),
where $class is the driver class and $method is the name of the method
that failed.
PrintError is also on, the PrintError is done first.
RaiseError is used in conjunction with eval { ... }
to catch the exception that's been thrown and followed by an
if ($@) { ... } block to handle the caught exception.
For example:
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
}
@member HandleError (code ref, inherited) When set to a subroutine reference, provides
alternative behaviour in case of errors. The subroutine reference is called when an
error is detected (at the same point that RaiseError and PrintError are handled).
RaiseError
and/or PrintError attributes are checked and acted upon as normal.
die with a full stack trace for any error:
use Carp;
$h->{HandleError} = sub { confess(shift) };
Or to turn errors into exceptions:
use Exception; # or your own favourite exception module
$h->{HandleError} = sub { Exception->new('DBI')->raise($_[0]) };
It is possible to 'stack' multiple HandleError handlers by using closures:
sub your_subroutine {
my $previous_handler = $h->{HandleError};
$h->{HandleError} = sub {
return 1 if $previous_handler and &$previous_handler(@_);
... your code here ...
};
}
The error message that will be used by RaiseError and PrintError
can be altered by changing the value of $_[0].
$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;
};
@member HandleSetErr (code ref, inherited) When set to a subroutien reference, intercepts
the setting of this handle's err, errstr, and state values.
err, errstr, and 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 HandleSetErr and HandleError subroutines differ in that
HandleError is only invoked at the point where DBI is about to return to the application
with err set true; it is not invoked by the failure of a method that's
been called by another DBI method. HandleSetErr is called
whenever set_err() is called with a defined err value, even if false.
Thus, the HandleSetErr subroutine may be called multiple
times within a method and is usually invoked from deep within driver code.
RaiseError, PrintError,
and PrintWarn attributes. Only applies to errors occuring on
the prepare(), do(), and the various select*() methods.
$h->{ParamValues} returns a hash reference of parameter
(placeholder) values then those are formatted and appended to the
end of the Statement text in the error message.
@member TraceLevel (integer, inherited) the trace level and flags for this handle. May be used
to set the trace level and flags.
@member FetchHashKeyName (string, inherited) Specifies the case conversion applied to the
the field names used for the hash keys returned by fetchrow_hashref().
Defaults to 'NAME' but it is recommended to set it to either 'NAME_lc'
or 'NAME_uc'.
@member ChopBlanks (boolean, inherited) When true (default false), trailing space characters are
trimmed from returned fixed width character (CHAR) fields. No other field types are affected,
even where field values have trailing spaces.
@member LongReadLen (unsigned integer, inherited) Sets the maximum
length of 'long' type fields (LONG, BLOB, CLOB, MEMO, etc.) which the driver will
read from the database automatically when it fetches each row of data.
The LongReadLen attribute only relates to fetching and reading
long values; it is not involved in inserting or updating them.
LongReadLen is 0.
LongReadLen relates to the underlying data
length and not the doubled-up length of the encoded string.
LongReadLen for a statement handle after it
has been prepare'd will typically have no effect, so it's common to
set LongReadLen on the database or driver handle before calling prepare.
@member LongTruncOk (boolean, inherited) When false (the default), fetching a long value that
needs to be truncated (usually due to exceeding LongReadLen) will cause the fetch to fail.
(Applications should always be sure to
check for errors after a fetch loop in case an error, such as a divide
by zero or long field truncation, caused the fetch to terminate
prematurely.)
LongTruncOk is
false, many drivers will allow you to continue fetching further rows.
@member TaintIn (boolean, inherited) When true (default false), and Perl is running in
taint mode (e.g., started with the -T option), then all the arguments
to most DBI method calls are checked for being tainted. This may change.
If Perl is not running in taint mode, this attribute has no effect.
@member TaintOut (boolean, inherited) When true (default false), and Perl is running in
taint mode (e.g., started with the -T option), then most data fetched
from the database is considered tainted. This may change.
If Perl is not running in taint mode, this attribute has no effect.
set transaction read only", for example) then it should.
Otherwise the attribute is simply advisory.
ReadOnly attribute itself to indicate that the data it
is connected to cannot be changed for some reason.
ReadOnly attribute when
making a decison about whether to retry an operation that failed.
commit or rollback
methods.
dbi:DriverName:" removed.
@member Statement (string, read-only) the statement string passed to the most
recent undef) if a row cache is not implemented.
Note that large cache sizes may require a very large amount of memory
(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.
00000 is translated to any empty string
(false). If the driver does not support SQLSTATE (and most don't),
then state() will return S1000 (General Error) for all errors.
state, e.g., warning
codes, even if it has not declared an error by returning a true value
via the err() method described above.
err, errstr, and state values for the handle.
If the err,
errstr, and state values are not altered and set_err() returns
an empty list (it normally returns $rv which defaults to undef, see below).
$err to a true value indicates an error and will trigger
the normal DBI error handling mechanisms, such as RaiseError and
HandleError, if they are enabled, when execution returns from
the DBI back to the application.
$err to "" indicates an 'information' state, and setting
it to "0" indicates a 'warning' state. Setting $err to undef
also sets $errstr to undef, and $state to "", irrespective
of the values of the $errstr and $state parameters.
RaiseError/PrintError/PrintWarn error string instead of
the fairly unhelpful 'set_err'.
err or errstr
values for the handle are already set.
errstr is true then: " [err was %s now %s]" is appended if $err is
true and err is already true and the new err value differs from the original
one. Similarly " [state was %s now %s]" is appended if $state is true and state is
already true and the new state value differs from the original one. Finally
"\n" and the new $errstr are appended if $errstr differs from the existing
errstr value. Obviously the %s's above are replaced by the corresponding values.
err value is set to $err if: $err is true; or handle
err value is undef; or $err is defined and the length is greater
than the handle err length. The effect is that an 'information'
state only overrides undef; a 'warning' overrides undef or 'information',
and an 'error' state overrides anything.
state value is set to $state if $state is true and
the handle err value was set (by the rules above).
RaiseError/PrintError/PrintWarn error string
@optional $rv the value to return from this method; default undef
@return the $rv value, if specified; else undef.
=end classdoc
=begin classdoc
@xs trace
Set the trace settings for the handle object.
Also can be used to change where trace output is sent.
DBI->trace, sets the global default trace
settings.
@see
@optional $trace_file either a string filename, or a Perl filehandle reference, to which
trace output is to be appended. If not spcified, traces are sent to STDOUT.
@return the previous $trace_setting value
=end classdoc
=begin classdoc
@xs trace_msg
Write a trace message to the handle object's current trace output.
@param $message_text message to be written
$optional $min_level the minimum trace level at which the message is written; default 1
@see install_method in |") or comma
(",") characters. For example: "SQL|3|foo".
@return the corresponding integer value used internally by the DBI and drivers.
@since 1.42
=end classdoc
=begin classdoc
@xs parse_trace_flag
Return the bit flag value for the specified trace flag name.
Original state:
dbh1o -> dbh1i
sthAo -> sthAi(dbh1i)
dbh2o -> dbh2i
swap_inner_handle dbh1o with dbh2o:
dbh2o -> dbh1i
sthAo -> sthAi(dbh1i)
dbh1o -> dbh2i
create new sth from dbh1o:
dbh2o -> dbh1i
sthAo -> sthAi(dbh1i)
dbh1o -> dbh2i
sthBo -> sthBi(dbh2i)
swap_inner_handle sthAo with sthBo:
dbh2o -> dbh1i
sthBo -> sthAi(dbh1i)
dbh1o -> dbh2i
sthAo -> sthBi(dbh2i)
@param $h2 the handle object to swap with this handle
@optional $allow_reparent if true, permits the two handles to have
different parent objects; default is false
@return true if the swap succeeded; otherwise, undef
@since 1.44
=end classdoc
=begin classdoc
@xs last_insert_id
Return the database server assigned unique identifier for the
prior inserted row.
@param $catalog the catalog name string for the inserted row; select max($field) from $table". Drivers using any approach
like this should issue a warning if AutoCommit is true because
it is generally unsafe - another process may have modified the table
between your insert and the select. For situations where you know
it is safe, such as when you have locked the table, you can silence
the warning by passing Warn => 0 in \%attr.
undef if not required
@param $schema the schema name string for the inserted row; undef if not required
@param $table the table name string for the inserted row; undef if not required
@param $field the column name string containing the insert identifier field for the inserted row; undef if not required
@optional \%attr any required attributes. DBI specifies the Warn => 0
attribute to silence possible warnings emitted as described above.
@return a value 'identifying' the row just inserted. Typically a value assigned by
the database server to a column with an auto_increment or serial type.
Returns undef if the driver does not support the method or can't determine the value.
@since 1.38.
=end classdoc
=begin classdoc
@xs prepare
Prepare a statement for later execution by the database
engine. Creates a Statement handle object ot be used to execute and
manage the resulting query.
execute call. Such drivers are
unlikely to provide statement metadata until after execute()
has been called.
undef, with error information
available via the err(), errstr(), and state() methods.
=end classdoc
=begin classdoc
@xs commit
Commit (make permanent) the most recent series of database changes
if the database supports transactions and AutoCommit is off.
AutoCommit is on, issues
a "commit ineffective with AutoCommit" warning.
@return true on success, undef on failure.
@see Transactions in the DBI manual.
=end classdoc
=begin classdoc
@xs rollback
Rollback (undo) the most recent series of uncommitted database
changes if the database supports transactions and AutoCommit is off.
AutoCommit is on, issues a "rollback ineffective with AutoCommit" warning.
@return true on success, undef on failure.
@see Transactions in the DBI manual.
=end classdoc
=begin classdoc
@xs disconnect
Disconnects the database from the database handle. Typically only used
before exiting the program. The handle is of little use after disconnecting.
disconnect method is
undefined. Some database systems will
automatically commit any outstanding changes; others will rollback any outstanding changes.
Applications not using AutoCommit should explicitly call commit or
rollback before calling disconnect.
DESTROY method if
still connected when there are no longer any references to the handle.
finish method on the active handles.
@return true on success, undef on failure.
=end classdoc
=begin classdoc
@xs get_info
Return metadata about the driver and data source capabilities, restrictions etc.
For example
$database_version = $dbh->get_info( 18 ); # SQL_DBMS_VER
$max_select_tables = $dbh->get_info( 106 ); # SQL_MAXIMUM_TABLES_IN_SELECT
The %GetInfoType
hash that can be used to map info type names to numbers. For example:
use DBI::Const::GetInfoType qw(%GetInfoType);
$database_version = $dbh->get_info( $GetInfoType{SQL_DBMS_VER} );
The names are a merging of the ANSI and ODBC standards (which differ
in some cases).
@param $info_type the type code for the information to be returned
@return a type and driver specific value, or undef for
unknown or unimplemented information types.
@see Standards Reference Information
@see _') matches any single character,
while the percent character ('%') matches zero or more
characters.
Drivers which do not support one or more of the selection filter
parameters may return metadata for more tables than requested, which may
require additional filtering by the application.
$sth = $dbh->table_info('%', '', '');
undef if not required
@param $schema search pattern for schemas to be queried; undef if not required
@param $table search pattern for tables to be queried; undef if not required
@param $type a comma-separated list of one or more types of tables for which metadata is to be returned.
Each value may optionally be quoted.
@optional \%attr any required additional attributes
@return undef on failure; on success, a Statement handle object. The returned statement handle
has at least the following fields (other fields, following these, may also be present):
@see undef) if not
applicable to the data source, which is usually the case. This field
is empty if not applicable to the table.
undef) if not applicable to data source, and
empty if not applicable to the table.
undef).
_') matches any single character,
while the percent character ('%') matches zero or more
characters.
undef if not required
@param $schema search pattern for schemas to be queried; undef if not required
@param $table search pattern for tables to be queried; undef if not required
@param $column search pattern for columns to be queried; undef if not required
@return undef on failure; on success, a Statement handle object. The returned statement handle
has at least the following fields (other fields, following these, may also be present),
ordered by TABLE_CAT, TABLE_SCHEM, TABLE_NAME, and ORDINAL_POSITION:
SQL/CLI defines the following additional columns:
undef) if not applicable to the data source,
which is often the case. This field is empty if not applicable to the
table.
undef) if not applicable to the data source,
and empty if not applicable to the table.
undef) if not
applicable.
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
Drivers capable of supplying any of those values should do so in
the corresponding column and supply undef values for the others.
@see Catalog Methods in the DBI manual
@see Standards Reference Information in the DBI manual
=end classdoc
=begin classdoc
@xs primary_key_info
Create an active statement handle to return metadata about columns that
make up the primary key for a table.
The arguments don't accept search patterns (unlike table_info()).
undef if not required
@param $schema the schema name string for the table to be queried; undef if not required
@param $table the name string of the table to be queried
@return undef on failure; on success, a Statement handle object. The returned statement handle
has at least the following fields (other fields, following these, may also be present),
ordered by TABLE_CAT, TABLE_SCHEM, TABLE_NAME, and KEY_SEQ:
@see Catalog Methods
@see Standards Reference Information
=end classdoc
=begin classdoc
@xs foreign_key_info
Create an active statement handle to return metadata
about foreign keys in and/or referencing the specified table(s).
The arguments don't accept search patterns (unlike table_info()).
undef) if not applicable to the data source,
which is often the case. This field is empty if not applicable to the
table.
undef) if not applicable to the data source,
and empty if not applicable to the table.
undef) if not applicable to the data source.
$catalog, is
driver specific. If the driver doesn't support catalogs and/or
schemas, it may ignore these criteria.
@param $pk_catalog name of the primary key table's catalog; may be undef
@param $pk_schema name of the primary key table's schema; may be undef
@param $pk_table name of the primary key table; may be undef
@param $fk_catalog name of the foreign key table's catalog; may be undef
@param $fk_schema name of the foreign key table's schema; may be undef
@param $fk_table name of the foreign key table; may be undef
@optional \%attr a hash reference of any attributes required by the driver or database
@return undef on failure; on success, a Statement handle object. The returned statement handle
has at least the following fields (other fields, following these, may also be present):
(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)
@see Catalog Methods
@see Standards Reference Information
=end classdoc
=begin classdoc
@xs statistics_info
Create an active statement handle returning statistical
information about a table and its indexes.
undef) if not applicable to the data source,
which is often the case. This field is empty if not applicable to the
table.
undef) if not applicable to the data source,
and empty if not applicable to the table.
undef) if not applicable to the data source,
which is often the case. This field is empty if not applicable to the
table.
undef) if not applicable to the data source,
and empty if not applicable to the table.
undef if not required
@param $schema the schema name string for the table to be queried; undef if not required
@param $table the name string of the table to be queried
@param $unique_only if true, only UNIQUE indexes will be
returned in the result set; otherwise all indexes will be returned.
@param $quick if true, the actual statistical information
columns (CARDINALITY and PAGES) will only be returned if they are readily
available from the server, and might not be current. Some databases may
return stale statistics or no statistics at all with this flag set true.
@return undef on failure; on success, a Statement handle object. The returned statement handle
has at least the following fields (other fields, following these, may also be present):
@see Catalog Methods
@see Standards Reference Information
=end classdoc
=begin classdoc
@xs type_info_all
Return metadata for all supported data types.
undef) if not applicable to the data source,
which is often the case. This field is empty if not applicable to the
table.
undef) if not applicable to the data source,
and empty if not applicable to the table.
DROP INDEX; NULL (undef) is returned if an index qualifier is not
supported by the data source.
If a non-NULL (defined) value is returned in this column, it must be used
to qualify the index name on a DROP INDEX statement; otherwise,
the TABLE_SCHEM should be used to qualify the index name.
undef).
A for Ascending, D for Descending, or NULL (undef) if
not supported for this index.
undef).
undef).
undef).
If the index is a filtered index, but the filter condition
cannot be determined, this value is the empty string ''.
Otherwise it will be the literal filter condition as a string,
such as SALARY <= 4500.
Name => Index pairs.
Subsequent array elements 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
],
];
Multiple elements may use the same DATA_TYPE value
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 AUTO_UNIQUE_VALUE set, with and without UNSIGNED_ATTRIBUTE, etc).
DATA_TYPE value first, then by how closely each
type maps to the corresponding ODBC SQL data type, closest first.
DESTROY
will generate a warning and return undef.
dbi_imp_data attribute
to a later
@return a binary string of raw implementation data from the driver which
describes the current database connection.
@since 1.36
=end classdoc
=begin classdoc
Duplicate this database handle object's connection by connecting
with the same parameters as used to create this database handle object.
.) character.
$quoted = $dbh->quote("one\ntwo\0three")
may return something like:
CONCAT('one', CHAR(12), 'two', CHAR(0), 'three')
The quote() method should not be used with placeholders and bind values.
@param $value the value to be escaped/quoted
@optional $data_type an SQL type code value to be used to determine the required
quoting behaviour by using the information returned by $value without calling type_info().
@return the properly quoted/escaped version of hte input parameter; if the input
parameter was undef, the string NULL (without
single quotation marks)
=end classdoc
=cut
sub quote {
my ($dbh, $str, $data_type) = @_;
return "NULL" unless defined $str;
unless ($data_type) {
$str =~ s/'/''/g; # ISO SQL2
return "'$str'";
}
my $dbi_literal_quote_cache = $dbh->{'dbi_literal_quote_cache'} ||= [ {} , {} ];
my ($prefixes, $suffixes) = @$dbi_literal_quote_cache;
my $lp = $prefixes->{$data_type};
my $ls = $suffixes->{$data_type};
if ( ! defined $lp || ! defined $ls ) {
my $ti = $dbh->type_info($data_type);
$lp = $prefixes->{$data_type} = $ti ? $ti->{LITERAL_PREFIX} || "" : "'";
$ls = $suffixes->{$data_type} = $ti ? $ti->{LITERAL_SUFFIX} || "" : "'";
}
return $str unless $lp || $ls; # no quoting required
# XXX don't know what the standard says about escaping
# in the 'general case' (where $lp != "'").
# So we just do this and hope:
$str =~ s/$lp/$lp$lp/g
if $lp && $lp eq $ls && ($lp eq "'" || $lp eq '"');
return "$lp$str$ls";
}
sub rows { -1 } # here so $DBI::rows 'works' after using $dbh
=pod
=begin classdoc
Prepare and immediately execute a single statement.
Typically used for non-data returning statements that
either cannot be prepared in advance (due to a limitation of the
driver) or do not need to be executed repeatedly. It should not
be used for data returning statements because it does not return a statement
handle (so you can't fetch any data).
@bind_values with the do method can be
useful because it avoids the need to correctly quote any variables
in the $statement. Statements that will be executed many
times should prepare() it once and call
execute() many times instead.
@param $statement the SQL statement to be executed immediately. Either a string, or a Statement handle object
previously returned from a prepare() on this database handle object.
@optional \%attr a hash reference of any desired statement attributes to apply to the $statement
@optional @bind_values any bind values to be supplied for placeholders within the $statement
@return the number of rows affected by the statement execution,
or undef on error. A return value of -1 means the
number of rows is not known, not applicable, or not available.
=end classdoc
=cut
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;
}
=pod
=begin classdoc
Immediately execute a data returning statement, returning the first row of results
as a hash reference.
Combines prepare() on this database handle object.
@optional \%attr a hash reference of any desired statement attributes to apply to the $statement
@optional @bind_values any bind values to be supplied for placeholders within the $statement
@return on failure, undef; otherwise, a hash reference mapping field names to their row values.
Note that the hash may be empty if no rows were returned.
=end classdoc
=cut
sub selectrow_hashref { return _do_selectrow('fetchrow_hashref', @_); }
# XXX selectrow_array/ref also have C implementations in Driver.xst
=pod
=begin classdoc
Immediately execute a data returning statement, returning the first row of results
as an array reference.
Combines prepare() on this database handle object.
@optional \%attr a hash reference of any desired statement attributes to apply to the $statement
@optional @bind_values any bind values to be supplied for placeholders within the $statement
@return on failure, undef; otherwise, an array reference of the row values.
Note that the array may be empty if no rows were returned.
=end classdoc
=cut
sub selectrow_arrayref { return _do_selectrow('fetchrow_arrayref', @_); }
=pod
=begin classdoc
Immediately execute a data returning statement, returning the first row of results
as an array.
Combines prepare() on this database handle object.
@optional \%attr a hash reference of any desired statement attributes to apply to the $statement
@optional @bind_values any bind values to be supplied for placeholders within the $statement
@returnlist on failure, undef; otherwise, an array reference of the row values.
Note that the array may be empty if no rows were returned.
@return either the value of the first or last column of the first returned row (don't do that);
undef if there are no more rows OR if an error occurred.
As those undef cases can't be distinguished from an undef returned as
a NULL first(or last) field value, this method should not be used in scalar context.
=end classdoc
=cut
sub selectrow_array {
my $row = _do_selectrow('fetchrow_arrayref', @_) or return;
return $row->[0] unless wantarray;
return @$row;
}
# XXX selectall_arrayref also has C implementation in Driver.xst
# which fallsback to this if a slice is given
=pod
=begin classdoc
Immediately execute a data returning statement, returning all result rows
as an array reference.
Combines prepare() on this database handle object.
@optional \%attr a hash reference of any desired statement attributes to apply to the $statement.
In addition, the following attributes may be supplied:
@optional @bind_values any bind values to be supplied for placeholders within the $statement
@return MaxRows => $max_rows
Specifies a $max_rows value to supply to the
Slice => $slice or Columns => $slice
Specifies a $slice value to supply to the
Slice is not defined and Columns is an array ref,
the array is assumed to contain column index values (which count from 1), rather than
Perl array index values, so that the array is copied and each value decremented before
passing to Slice attribute is specified as an empty hash reference,
the results will be returned as a hash reference mapping column names as keys to
arrayrefs of their associated values.
undef on failure; otherwise, an array reference containing an array reference
(or hash reference, if the Slice attribute is specified as an empty hash reference)
for each row of data fetched. If $sth->err
afterwards (or use the prepare() on this database handle object.
@param $key_field a scalar key field name, or an array reference of key field names,
Specifies which column(s) are used as keys in the returned hash.
@optional \%attr a hash reference of any desired statement attributes to apply to the $statement.
@optional @bind_values any bind values to be supplied for placeholders within the $statement
@return undef on failure; on success, a hash reference containing one entry,
at most, for each row, as returned by $DBI::err.
If multiple $key_fields were specified, the returned hash is a tree of
nested hashes.
@see Columns' attribute is specified, it can
also push additional columns per row into the result array.
@param $statement the SQL statement to be executed as either a string, or a Statement handle object
previously returned from a prepare() on this database handle object.
@optional \%attr a hash reference of any desired statement attributes to apply to the $statement.
In addition, the following attributes may be supplied:
@optional @bind_values any bind values to be supplied for placeholders within the $statement
@return MaxRows => $max_rows
Specifies the maximum number of rows to fetch.
Columns => \@columns
Specifies an array reference containing the column number(s) to be fetched into the result array.
undef on failure; on success, an array reference containing the values
of the first column from each row. If $DBI::err.
=end classdoc
=cut
sub selectcol_arrayref {
my ($dbh, $stmt, $attr, @bind) = @_;
my $sth = (ref $stmt) ? $stmt : $dbh->prepare($stmt, $attr);
return unless $sth;
$sth->execute(@bind) || return;
my @columns = ($attr->{Columns}) ? @{$attr->{Columns}} : (1);
my @values = (undef) x @columns;
my $idx = 0;
for (@columns) {
$sth->bind_col($_, \$values[$idx++]) || return;
}
my @col;
if (my $max = $attr->{MaxRows}) {
push @col, @values while @col<$max && $sth->fetch;
}
else {
push @col, @values while $sth->fetch;
}
return \@col;
}
=pod
=begin classdoc
Locate a matching statement handle object in this object's
statement handle cache; if no match is found, prepare the statement
and store the resulting statement handle object in
this database handle's statement cache.
prepare_cached with the same
$statement and %attr parameter values,
the corresponding cached statement handle object will be returned without
contacting the database server.
@return on success, a statement handle object; on failure, undef, with the error
indication available via 0 but true" which is
true but zero. That way you can tell if the return value is genuine or
just the default.
@return true if the connection is still usable; otherwise, false.
@see undef if undef if not required
@param $schema the schema name string for the table to be queried; undef if not required
@param $table the name string of the table to be queried
@returnlist the column names that comprise the primary key of the specified table.
The list is in primary key column sequence order.
If there is no primary key, an empty list is returned.
=end classdoc
=cut
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;
}
=pod
=begin classdoc
Get the list of matching table names.
A simple interface to $dbh->get_info(SQL_IDENTIFIER_QUOTE_CHAR) returns true,
the table names are constructed and quoted by undef if not required
@param $schema search pattern for schemas to be queried; undef if not required
@param $table search pattern for tables to be queried; undef if not required
@param $type a comma-separated list of one or more types of tables for which metadata is to be returned.
Each value may optionally be quoted.
@returnlist the matching table names, possibly including a catalog/schema prefix.
=end classdoc
=cut
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;
}
=pod
=begin classdoc
Get the data type metadata for the specified $data_type.
@param $data_type either a scalar data type code, or
an array reference of type codes
@return the first (best) matching metadata element is returned as a hash reference
@returnlist the hash references containing metadata about one or more
variants of the specified type. The list is ordered by DATA_TYPE first and
then by how closely each type maps to the corresponding ODBC SQL data
type, closest first. If $data_type is undef or SQL_ALL_TYPES,
all data type variants supported by the database and driver are returned.
If $data_type is an array reference, returns the metadata for the first
type in the array that has any matches.
The keys of the returned hash follow the same letter case conventions as the
rest of the DBI
(see Naming Conventions and Name Space). The
following uppercase items should always exist, though may be undef:
@see Standards Reference Information in the DBI manual
=end classdoc
=cut
sub type_info { # this should be sufficient for all drivers
my ($dbh, $data_type) = @_;
my $idx_hash;
my $tia = $dbh->{dbi_type_info_row_cache};
if ($tia) {
$idx_hash = $dbh->{dbi_type_info_idx_cache};
}
else {
my $temp = $dbh->type_info_all;
return unless $temp && @$temp;
# we cache here because type_info_all may be expensive to call
# (and we take a copy so the following shift can't corrupt
# the data that may be returned by future calls to type_info_all)
$tia = $dbh->{dbi_type_info_row_cache} = [ @$temp ];
$idx_hash = $dbh->{dbi_type_info_idx_cache} = shift @$tia;
}
my $dt_idx = $idx_hash->{DATA_TYPE} || $idx_hash->{data_type};
Carp::croak("type_info_all returned non-standard DATA_TYPE index value ($dt_idx != 1)")
if $dt_idx && $dt_idx != 1;
# --- simple DATA_TYPE match filter
my @ti;
my @data_type_list = (ref $data_type) ? @$data_type : ($data_type);
foreach $data_type (@data_type_list) {
if (defined($data_type) && $data_type != DBI::SQL_ALL_TYPES()) {
push @ti, grep { $_->[$dt_idx] == $data_type } @$tia;
}
else { # SQL_ALL_TYPES
push @ti, @$tia;
}
last if @ti; # found at least one match
}
# --- format results into list of hash refs
my $idx_fields = keys %$idx_hash;
my @idx_names = map { uc($_) } keys %$idx_hash;
my @idx_values = values %$idx_hash;
Carp::croak "type_info_all result has $idx_fields keys but ".(@{$ti[0]})." fields"
if @ti && @{$ti[0]} != $idx_fields;
my @out = map {
my %h; @h{@idx_names} = @{$_}[ @idx_values ]; \%h;
} @ti;
return $out[0] unless wantarray;
return @out;
}
=pod
=begin classdoc
Get the list of data sources (databases) available via this database
handle object.
@returnlist the names of data sources (databases) in a form suitable for passing to the
'" for characters,
or possibly "0x" for binary values passed as hexadecimal. NULL (undef) is
returned for data types for which this is not applicable.
'" for characters.
NULL (undef) is returned for data types where this is not applicable.
CREATE_PARAMS for a
DECIMAL would be "precision,scale" if the DECIMAL type should be
declared as DECIMAL(precision,scale) where precision and scale
are integer values. For a VARCHAR it would be "max length".
NULL (undef) is returned for data types for which this is not applicable.
undef) is returned
for data types for which this is not applicable.
undef) is returned for data types
for which this is not applicable.
undef) is returned
for data types for which this is not applicable.
TYPE_NAME for use in dialog with users.
NULL (undef) is returned if a localized name is not available (in which
case TYPE_NAME should be used).
MAXIMUM_SCALE holds the same value. NULL (undef) is returned for
data types for which this is not applicable.
MINIMUM_SCALE holds the same value. NULL (undef) is returned for
data types for which this is not applicable.
DATA_TYPE column, except for interval
and datetime data types. For interval and datetime data types, the
SQL_DATA_TYPE field will return SQL_INTERVAL or SQL_DATETIME, and the
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.
SQL_DATA_TYPE
field above is SQL_INTERVAL or SQL_DATETIME, this field will
hold the subcode for the specific interval or datetime data type.
Otherwise it will be NULL (undef).
DATA_TYPE == (10 * SQL_DATA_TYPE) + SQL_DATETIME_SUB
NUM_PREC_RADIX
contains the value 2 and COLUMN_SIZE holds the number of bits. For
exact numeric types, NUM_PREC_RADIX contains the value 10 and COLUMN_SIZE holds
the number of decimal digits. NULL (undef) is returned either for data types
for which this is not applicable or if the driver cannot report this information.
dbi:$driver:" prefix).
The list is the result of the parent driver object's $SIG{__WARN__} hook) for certain bad practices;
@member Type (scalar, read-only) "st" (the type of this handle object)
@member CompatMode (boolean, inherited) used by emulation layers (such as
Oraperl) to enable compatible behaviour in the underlying driver (e.g., DBD::Oracle) for this handle.
Not normally set by application code. Disables the 'quick FETCH' of attribute
values from this handle's attribute cache so all attribute values
are handled by the drivers own FETCH method.
@member InactiveDestroy (boolean) when false (the default),this handle will be fully destroyed
as normal when the last reference to it is removed. If true, this handle will be treated by
DESTROY as if it was no longer Active, and so the database engine related effects of
DESTROYing this handle will be skipped. Designed for use in Unix applications
that "fork" child processes: Either the parent or the child process
(but not both) should set InactiveDestroy true on all their shared handles.
(Note that some databases, including Oracle, don't support passing a
database connection across a fork.)
warn("$class $method warning: $DBI::errstr")
where $class is the driver class and $method is the name of
the method which failed.
DBI->connect sets PrintWarn "on" if $^W is true.
$SIG{__WARN__}
handler or modules like CGI::Carp and CGI::ErrorWrap.
warn("$class $method failed: $DBI::errstr"), where $class
is the driver class and $method is the name of the method which failed.
DBI->connect sets PrintError "on".
$SIG{__WARN__}
handler or modules like CGI::Carp and CGI::ErrorWrap.
@member RaiseError (boolean, inherited) When true (default false), errors raise exceptions rather
than simply returning error codes in the normal way.
Exceptions are raised via a die("$class $method failed: $DBI::errstr"),
where $class is the driver class and $method is the name of the method
that failed.
PrintError is also on, the PrintError is done first.
RaiseError is used in conjunction with eval { ... }
to catch the exception that's been thrown and followed by an
if ($@) { ... } block to handle the caught exception.
For example:
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
}
@member HandleError (code ref, inherited) When set to a subroutine reference, provides
alternative behaviour in case of errors. The subroutine reference is called when an
error is detected (at the same point that RaiseError and PrintError are handled).
RaiseError
and/or PrintError attributes are checked and acted upon as normal.
die with a full stack trace for any error:
use Carp;
$h->{HandleError} = sub { confess(shift) };
Or to turn errors into exceptions:
use Exception; # or your own favourite exception module
$h->{HandleError} = sub { Exception->new('DBI')->raise($_[0]) };
It is possible to 'stack' multiple HandleError handlers by using closures:
sub your_subroutine {
my $previous_handler = $h->{HandleError};
$h->{HandleError} = sub {
return 1 if $previous_handler and &$previous_handler(@_);
... your code here ...
};
}
The error message that will be used by RaiseError and PrintError
can be altered by changing the value of $_[0].
$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;
};
@member HandleSetErr (code ref, inherited) When set to a subroutien reference, intercepts
the setting of this handle's err, errstr, and state values.
err, errstr, and 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 HandleSetErr and HandleError subroutines differ in that
HandleError is only invoked at the point where DBI is about to return to the application
with err set true; it is not invoked by the failure of a method that's
been called by another DBI method. HandleSetErr is called
whenever set_err() is called with a defined err value, even if false.
Thus, the HandleSetErr subroutine may be called multiple
times within a method and is usually invoked from deep within driver code.
RaiseError, PrintError,
and PrintWarn attributes.
$h->{ParamValues} returns a hash reference of parameter
(placeholder) values then those are formatted and appended to the
end of the Statement text in the error message.
@member TraceLevel (integer, inherited) the trace level and flags for this handle. May be used
to set the trace level and flags.
@member FetchHashKeyName (string, inherited, read-only) Specifies the case conversion applied to the
the field names used for the hash keys returned by fetchrow_hashref().
Defaults to 'NAME' but it is recommended to set it to either 'NAME_lc'
or 'NAME_uc'.
@member ChopBlanks (boolean, inherited) When true (default false), trailing space characters are
trimmed from returned fixed width character (CHAR) fields. No other field types are affected,
even where field values have trailing spaces.
@member LongReadLen (unsigned integer, inherited) Sets the maximum
length of 'long' type fields (LONG, BLOB, CLOB, MEMO, etc.) which the driver will
read from the database automatically when it fetches each row of data.
The LongReadLen attribute only relates to fetching and reading
long values; it is not involved in inserting or updating them.
LongReadLen is 0.
LongReadLen relates to the underlying data
length and not the doubled-up length of the encoded string.
LongReadLen on this handle will typically have no effect, so it's common to
set LongReadLen on the database or driver handle before calling prepare.
@member LongTruncOk (boolean, inherited) When false (the default), fetching a long value that
needs to be truncated (usually due to exceeding LongReadLen) will cause the fetch to fail.
(Applications should always be sure to
check for errors after a fetch loop in case an error, such as a divide
by zero or long field truncation, caused the fetch to terminate
prematurely.)
LongTruncOk is
false, many drivers will allow you to continue fetching further rows.
@member TaintIn (boolean, inherited) When true (default false), and Perl is running in
taint mode (e.g., started with the -T option), then all the arguments
to most DBI method calls are checked for being tainted. This may change.
If Perl is not running in taint mode, this attribute has no effect.
@member TaintOut (boolean, inherited) When true (default false), and Perl is running in
taint mode (e.g., started with the -T option), then most data fetched
from the database is considered tainted. This may change.
If Perl is not running in taint mode, this attribute has no effect.
set transaction read only", for example) then it should.
Otherwise the attribute is simply advisory.
ReadOnly attribute itself to indicate that the data it
is connected to cannot be changed for some reason.
ReadOnly attribute when
making a decison about whether to retry an operation that failed.
DELETE, CREATE, etc. statements)
(some drivers may return undef).
@member NUM_OF_PARAMS (integer, read-only) number of parameters (placeholders) in the prepared statement.
@member NAME (array-ref, read-only) an array reference of names for each returned column. The
names may contain spaces but should not be truncated or have any
trailing space. Note that the names have the letter case (upper, lower
or mixed) as returned by the driver being used. Portable applications
should use TYPE values returned by a driver should be described in the
output of the undef values indicate columns where scale is not applicable.
@member NULLABLE (array-ref, read-only) an array reference indicating the "nullability" of each
column returning a null. Possible values are
@member CursorName (string, read-only) the name of the cursor associated with this statement handle
(if available); undef if not available or if the database driver does not support the
"where current of ..." SQL syntax.
@member Database (dbh, read-only) the parent database handle of this statement handle.
@member ParamValues (hash ref, read-only) a hash reference containing values currently bound
to placeholders (or undef if not supported by the driver).
The keys of the hash are the 'names' of the placeholders, typically integers starting at 1.
When no values have been bound, all the values will be undef
(some drivers may return a ref to an empty hash in that instance).
$sth = $dbh->prepare("INSERT INTO staff (id, name) values (?,?)");
$sth->execute_array({},[1,2], ['fred','dave']);
if ($sth->{ParamArrays}) {
foreach $param (keys %{$sth->{ParamArrays}}) {
printf "Parameters for %s : %s\n", $param,
join(",", @{$sth->{ParamArrays}->{$param}});
}
}
The values in the hash may not be exactly the same as those passed to
undef.
undef
if the driver doesn't support a local row cache. See $bind_value
to the specified placeholder in this statement object.
Placeholders within a statement string are normally indicated with
a question mark character (?); some drivers may support alternate
placeholder syntax.
bind_param call, after which the driver
may ignore the $bind_type parameter for that placeholder.
bind_param call,
consider using the default type (VARCHAR) and
use an SQL function to convert the type within the statement.
For example:
INSERT INTO price(code, price) VALUES (?, CONVERT(MONEY,?))
@param $p_num a positional placeholder number; some drivers may support
alternate "named" placeholder syntax
@param $bind_value the value to be bound; undef is used for NULL. The bound value
may be overridden by values provided to the $bind_type specified by this method call will still apply.
@optional $bind_type either a scalar SQL type code (from the DBI :sql_types export list),
or a hash reference of type information, which may include the following keys:
If not specified, the default VARCHAR type will be assumed.
@see DBI Constants
@see Placeholders and Bind Values for more information.
=end classdoc
=cut
sub bind_param { Carp::croak("Can't bind_param, not implement by driver") }
#
# ********************************************************
#
# BEGIN ARRAY BINDING
#
# Array binding support for drivers which don't support
# array binding, but have sufficient interfaces to fake it.
# NOTE: mixing scalars and arrayrefs requires using bind_param_array
# for *all* params...unless we modify bind_param for the default
# case...
#
# 2002-Apr-10 D. Arnold
=pod
=begin classdoc
Bind an array of values to the specified placeholder in this statement object
for use with a subsequent ?); some drivers may support alternate
placeholder syntax.
bind_param_array call, after which the driver
may ignore the $bind_type parameter for that placeholder.
bind_param call,
consider using the default type (VARCHAR) and
use an SQL function to convert the type within the statement.
For example:
INSERT INTO price(code, price) VALUES (?, CONVERT(MONEY,?))
undef, may also be bound by
bind_param_array, in which case the same value will be used for each
bind_param_array and bind_param_array must be used with
bind_param_array will have no effect
for undef is used for NULL. The bound variable
may be overridden by values provided to the $bind_type specified by this method call will still apply.
@optional $bind_type either a scalar SQL type code (from the DBI :sql_types export list),
or a hash reference of type information, which may include the following keys:
If not specified, the default VARCHAR type will be assumed.
@see bind_columns will
bind the elements given, upto the number of columns, and then return an error.
For compatibility with old scripts, the first parameter will be
ignored if it is undef or a hash reference.
=end classdoc
=cut
sub bind_columns {
my $sth = shift;
my $fields = $sth->FETCH('NUM_OF_FIELDS') || 0;
if ($fields <= 0 && !$sth->{Active}) {
return $sth->set_err(1, "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 $sth->set_err(1, "bind_columns called with ".($idx+@_)." values but $fields are needed")
if @_ or $idx != $fields;
return 1;
}
=pod
=begin classdoc
Execute the prepared statement once for each parameter tuple
(group of values) provided either in @bind_values, or by prior
calls to \%attr.
@bind_values argument, or via prior calls to
ArrayTupleFetch attribute.
ArrayTupleFetch attribute can be used to specify a reference
to a subroutine that will be called to provide the bind values for
each tuple execution. The subroutine should return a reference to
an array which contains the appropriate number of bind values, or
return an undef if there is no more data to execute.
ArrayTupleFetch attribute can also
specify a statement handle, in which case the @bind_values
are given, then execute_array will effectively call SQL_VARCHAR types unless the
driver can determine the correct type, or unless
ArrayTupleStatus attribute can be used to specify a
reference to an array which will receive the execute status of each
executed parameter tuple. Note the ArrayTupleStatus attribute was
mandatory until DBI 1.38.
undef. In that case, the application should inspect the
status array to determine which parameter tuples failed.
Some databases may not continue executing tuples beyond the first
failure, in which case the status array will either hold fewer
elements, or the elements beyond the failure will be undef.
At present, both attributes are considered optional.
@optional @bind_values a list of placeholder values, either as scalars, or array references,
similar to those provided to ArrayTupleStatus => \@status - an array reference to receive
the execution status of each parameter tuple.
ArrayTupleFetch => \$sub_or_sth - provides either a
subroutine reference, or a statement handle, from which parameter tuples
are retrieved in row-wise fashion, as an alternative to the column-wise
@bind_values parameter specification.
undef if an error occured.
Like ArrayTupleStatus array.
@returnlist the number of tuples executed (as for calling in scalar context),
and the sum of the number of rows affected for each tuple, if available, or -1
if the driver cannot determine this.
Note that certain operations (e.g., UPDATE, DELETE) may report multiple
affected rows for one or more of the supplied parameter tuples.
Some drivers may not yet support the list context
call, in which case the reported rowcount will be undef;
if a driver is not be able to provide
the number of rows affected when performing this batch operation,
the returned rowcount will be -1.
@see undef if there were any errors; otherwise,
the number of tuples executed. Like while loop with column binding is often faster because
the cost of allocating memory for the batch of rows is greater than
the saving by reducing method calls. It's possible that the DBI may
provide a way to reuse the memory of a previous batch in future, which
would then shift the balance back towards this method.
@optional $slice either an array or hash reference.
If an array reference, this method uses 00000 is translated to any empty string
(false). If the driver does not support SQLSTATE (and most don't),
then state() will return S1000 (General Error) for all errors.
state, e.g., warning
codes, even if it has not declared an error by returning a true value
via the err() method described above.
err, errstr, and state values for the handle.
If the err,
errstr, and state values are not altered and set_err() returns
an empty list (it normally returns $rv which defaults to undef, see below).
$err to a true value indicates an error and will trigger
the normal DBI error handling mechanisms, such as RaiseError and
HandleError, if they are enabled, when execution returns from
the DBI back to the application.
$err to "" indicates an 'information' state, and setting
it to "0" indicates a 'warning' state. Setting $err to undef
also sets $errstr to undef, and $state to "", irrespective
of the values of the $errstr and $state parameters.
RaiseError/PrintError/PrintWarn error string instead of
the fairly unhelpful 'set_err'.
err or errstr
values for the handle are already set.
errstr is true then: " [err was %s now %s]" is appended if $err is
true and err is already true and the new err value differs from the original
one. Similarly " [state was %s now %s]" is appended if $state is true and state is
already true and the new state value differs from the original one. Finally
"\n" and the new $errstr are appended if $errstr differs from the existing
errstr value. Obviously the %s's above are replaced by the corresponding values.
err value is set to $err if: $err is true; or handle
err value is undef; or $err is defined and the length is greater
than the handle err length. The effect is that an 'information'
state only overrides undef; a 'warning' overrides undef or 'information',
and an 'error' state overrides anything.
state value is set to $state if $state is true and
the handle err value was set (by the rules above).
RaiseError/PrintError/PrintWarn error string
@optional $rv the value to return from this method; default undef
@return the $rv value, if specified; else undef.
=end classdoc
=begin classdoc
@xs trace
Set the trace settings for the handle object.
Also can be used to change where trace output is sent.
DBI->trace, sets the global default trace
settings.
@see
@optional $trace_file either a string filename, or a Perl filehandle reference, to which
trace output is to be appended. If not spcified, traces are sent to STDOUT.
@return the previous $trace_setting value
=end classdoc
=begin classdoc
@xs trace_msg
Write a trace message to the handle object's current trace output.
@param $message_text message to be written
$optional $min_level the minimum trace level at which the message is written; default 1
@see install_method in |") or comma
(",") characters. For example: "SQL|3|foo".
@return the corresponding integer value used internally by the DBI and drivers.
@since 1.42
=end classdoc
=begin classdoc
@xs parse_trace_flag
$bit_flag = $h->parse_trace_flag($trace_flag_name);
Return the bit flag value for the specified trace flag name.
undef
(the attribute's current values may be supplied in future)
=end classdoc
=begin classdoc
@xs swap_inner_handle
Swap the internals of 2 handle objects.
Brain transplants for handles. You don't need to know about this
unless you want to become a handle surgeon.
Original state:
dbh1o -> dbh1i
sthAo -> sthAi(dbh1i)
dbh2o -> dbh2i
swap_inner_handle dbh1o with dbh2o:
dbh2o -> dbh1i
sthAo -> sthAi(dbh1i)
dbh1o -> dbh2i
create new sth from dbh1o:
dbh2o -> dbh1i
sthAo -> sthAi(dbh1i)
dbh1o -> dbh2i
sthBo -> sthBi(dbh2i)
swap_inner_handle sthAo with sthBo:
dbh2o -> dbh1i
sthBo -> sthAi(dbh1i)
dbh1o -> dbh2i
sthAo -> sthBi(dbh2i)
@param $h2 the handle object to swap with this handle
@optional $allow_reparent if true, permits the two handles to have
different parent objects; default is false
@return true if the swap succeeded; otherwise, undef
@since 1.44
=end classdoc
=begin classdoc
@xs bind_param_inout
Bind (aka, associate) a scalar reference of $bind_value
to the specified placeholder in this statement object.
Placeholders within a statement string are normally indicated with question
mark character (?); some drivers permit alternate placeholder
syntax.
$bind_value must be passed as a
reference to the actual value to be used.
Undefined values or undef are used to indicate null values.
$bind_value variable is not
copied when bind_param_inout is called. Instead, the value in the
variable is read at the time bind_param call, after which the driver
may ignore the $bind_type parameter for that placeholder.
VARCHAR) and
use an SQL function to convert the type within the statement.
For example:
INSERT INTO price(code, price) VALUES (?, CONVERT(MONEY,?))
@param $p_num the number of the placeholder to be bound. Some drivers support an alternate
named placeholder syntax, in which case $p_num may be a string.
@param \$bind_value scalar reference bound to the placeholder
@optional $max_len the minimum amount of memory to allocate to $bind_value for
the output value. If the size of the output value exceeds this value, the subsequent
DBI :sql_types export list),
or a hash reference of type information, which may include the following keys:
If not specified, the default VARCHAR type will be assumed.
@see DBI Constants
@see Placeholders and Bind Values for more information.
=end classdoc
=begin classdoc
@xs execute
Execute this statement object's statement.
@bind_value arguments are given, this method will effectively call
SQL_VARCHAR types unless
the driver can determine the correct type, or unless a prior call to
bind_param (or bind_param_inout) has been used to
specify the type.
execute. This method does not return the number of
rows that will be returned by the query, because most databases can't
tell in advance.
undef on failure. On success, returns true regardless of the
number of rows affected, even if it's zero. For a non-data returning statement,
returns the number of rows affected, if known. If no rows were affected, returns
"0E0", which Perl will treat as 0 but will regard as true.
If the number of rows affected is not known, returns -1.
For data returning statements, returns a true (but not meaningful) value.
undef values in the array.
If there are no more rows or if an error occurs, returns undef.
Any error indication is available via the undef values in the list.
If there are no more rows or if an error occurs, returns an empty list.
Any error indication is available via the undef if there are no more rows or if an error occurred,
which is indistinguishable from a NULL returned field value.
For these reasons, avoid calling this method in scalar context.
=end classdoc
=begin classdoc
@xs fetchrow_hashref
Fetch the next row of data.
An alternative to fetchrow_arrayref.
fetchrow_arrayref or fetchrow_array.
@optional $name the name of the statement handle attribute to use as the source for the
field names used as keys in the returned hash.
For historical reasons it defaults to "NAME", however using either
"NAME_lc" or "NAME_uc" is recomended for portability.
@return a hash reference mapping the statement's field names to the row's field
values. Null fields are returned as undef values in the hash.
If there are no more rows or if an error occurs, returns undef.
Any error indication is available via the $sth->{$name}. If
more than one field has the same name, there will only be one entry in
the returned hash for those fields.
UPDATE and DELETE), or
after fetching all the rows of a data returning statement.
$DBI::rows) with data returning statements is not
recommended.
"SELECT COUNT(*) FROM ..." SQL statement with the same predicate, grouping, etc.
as this statement's query.
@return the number of rows affected by the last row affecting command.
=end classdoc
=begin classdoc
@xs bind_col
Bind a Perl variable to an output column(field) of a data returning statement.
$var_to_bind appears
to be automatically updated,
The binding is performed at a low level using Perl aliasing,
so that the bound variable refers to the same
memory location as the corresponding column value, thereby making
bound variables very efficient.
bind_col call.
@param $column_number the positional column number (counting from 1) to which the variable
is to be bound
@param \$var_to_bind the scalar reference to receive the specified column's return value.
May also be undef, which causes the corresponding column to be
returned (via future fetch method calls) in a format compatible with the specifed $bind_type.
@optional $bind_type either a scalar SQL type code, or a hash reference of detailed
type information. Supported type information includes
If not specified, defaults to the driver's default return type (usually
the same as specified in the corresponding $fh separated by $lsep, with
fields separated by $fsep.
"\n")
@optional $fsep the field separator string (defaults to ", ")
@optional $fh the filehandle to which to print the formatted rows (defaults to STDOUT)
@return the number of rows dumped
=end classdoc
=cut
}
unless ($DBI::PurePerl) { # See install_driver
{ @DBD::_mem::dr::ISA = qw(DBD::_mem::common); }
{ @DBD::_mem::db::ISA = qw(DBD::_mem::common); }
{ @DBD::_mem::st::ISA = qw(DBD::_mem::common); }
# DBD::_mem::common::DESTROY is implemented in DBI.xs
}
1;
__END__