← Index
NYTProf Performance Profile   « block view • line view • sub view »
For ddd2.pl
  Run on Tue May 25 16:52:24 2010
Reported on Tue May 25 16:56:47 2010

File /project/perl/lib/DBI.pm
Statements Executed 1256
Statement Execution Time 67.4ms
Subroutines — ordered by exclusive time
Calls P F Exclusive
Time
Inclusive
Time
Subroutine
1212280ms280msDBI::st::::execute DBI::st::execute (xsub)
11125.2ms30.0msDBI::::_load_class DBI::_load_class
11116.3ms31.2msDBI::::install_driver DBI::install_driver
462124.20ms4.20msDBI::st::::fetchrow_arrayref DBI::st::fetchrow_arrayref (xsub)
313113.05ms4.99msDBD::_::common::::install_method DBD::_::common::install_method
117222.45ms2.45msDBI::::_install_method DBI::_install_method (xsub)
14311.54ms2.23msDBI::::_new_handle DBI::_new_handle
111820µs106msDBI::::__ANON__[:692] DBI::__ANON__[:692]
1412694µs694µsDBI::::_setup_handle DBI::_setup_handle (xsub)
1211688µs2.53msDBI::::_new_sth DBI::_new_sth
11212535µs535µsDBI::::CORE:match DBI::CORE:match (opcode)
6222515µs515µsDBD::_::common::::CORE:match DBD::_::common::CORE:match (opcode)
221427µs541µsDBI::::setup_driver DBI::setup_driver
112402µs402µsDBI::::bootstrap DBI::bootstrap (xsub)
111351µs138msDBI::::connect DBI::connect
943287µs287µsDBI::st::::fetchrow_array DBI::st::fetchrow_array (xsub)
111154µs161µsDBI::::_set_isa DBI::_set_isa
1153137µs137µsDBI::st::::finish DBI::st::finish (xsub)
112126µs155µsDBI::st::::bind_columns DBI::st::bind_columns (xsub)
11178µs278µsDBI::::_new_dbh DBI::_new_dbh
11177µs271µsDBI::::_new_drh DBI::_new_drh
11171µs84µsDBI::::_rebless DBI::_rebless
21270µs70µsDBI::st::::fetchall_arrayref DBI::st::fetchall_arrayref (xsub)
11169µs138msDBI::::connect_cached DBI::connect_cached
11163µs98µsDBI::::disconnect_all DBI::disconnect_all
33237µs37µsDBI::::CORE:subst DBI::CORE:subst (opcode)
44232µs32µsDBD::_::common::::trace_msg DBD::_::common::trace_msg (xsub)
11229µs29µsDBD::_::dr::::CORE:sort DBD::_::dr::CORE:sort (opcode)
11214µs14µsDBI::st::::bind_col DBI::st::bind_col (xsub)
11213µs13µsDBI::::_handles DBI::_handles (xsub)
1127µs7µsDBI::::SQL_INTEGER DBI::SQL_INTEGER (xsub)
1126µs6µsDBI::::SQL_DECIMAL DBI::SQL_DECIMAL (xsub)
1126µs6µsDBI::::SQL_DOUBLE DBI::SQL_DOUBLE (xsub)
1126µs6µsDBI::::SQL_FLOAT DBI::SQL_FLOAT (xsub)
1126µs6µsDBI::::SQL_REAL DBI::SQL_REAL (xsub)
1126µs6µsDBI::::SQL_SMALLINT DBI::SQL_SMALLINT (xsub)
1125µs5µsDBI::::SQL_NUMERIC DBI::SQL_NUMERIC (xsub)
0000s0sDBD::Switch::dr::::CLONEDBD::Switch::dr::CLONE
0000s0sDBD::Switch::dr::::FETCHDBD::Switch::dr::FETCH
0000s0sDBD::Switch::dr::::STOREDBD::Switch::dr::STORE
0000s0sDBD::Switch::dr::::driverDBD::Switch::dr::driver
0000s0sDBD::_::common::::BEGIN DBD::_::common::BEGIN
0000s0sDBD::_::common::::CLEAR DBD::_::common::CLEAR
0000s0sDBD::_::common::::EXISTS DBD::_::common::EXISTS
0000s0sDBD::_::common::::FIRSTKEY DBD::_::common::FIRSTKEY
0000s0sDBD::_::common::::NEXTKEY DBD::_::common::NEXTKEY
0000s0sDBD::_::common::::_not_impl DBD::_::common::_not_impl
0000s0sDBD::_::common::::parse_trace_flag DBD::_::common::parse_trace_flag
0000s0sDBD::_::common::::parse_trace_flags DBD::_::common::parse_trace_flags
0000s0sDBD::_::common::::private_attribute_info DBD::_::common::private_attribute_info
0000s0sDBD::_::db::::BEGIN DBD::_::db::BEGIN
0000s0sDBD::_::db::::_do_selectrow DBD::_::db::_do_selectrow
0000s0sDBD::_::db::::begin_work DBD::_::db::begin_work
0000s0sDBD::_::db::::clone DBD::_::db::clone
0000s0sDBD::_::db::::data_sources DBD::_::db::data_sources
0000s0sDBD::_::db::::do DBD::_::db::do
0000s0sDBD::_::db::::ping DBD::_::db::ping
0000s0sDBD::_::db::::prepare_cached DBD::_::db::prepare_cached
0000s0sDBD::_::db::::primary_key DBD::_::db::primary_key
0000s0sDBD::_::db::::quote DBD::_::db::quote
0000s0sDBD::_::db::::quote_identifier DBD::_::db::quote_identifier
0000s0sDBD::_::db::::rows DBD::_::db::rows
0000s0sDBD::_::db::::selectall_arrayref DBD::_::db::selectall_arrayref
0000s0sDBD::_::db::::selectall_hashref DBD::_::db::selectall_hashref
0000s0sDBD::_::db::::selectcol_arrayref DBD::_::db::selectcol_arrayref
0000s0sDBD::_::db::::selectrow_array DBD::_::db::selectrow_array
0000s0sDBD::_::db::::selectrow_arrayref DBD::_::db::selectrow_arrayref
0000s0sDBD::_::db::::selectrow_hashref DBD::_::db::selectrow_hashref
0000s0sDBD::_::db::::tables DBD::_::db::tables
0000s0sDBD::_::db::::type_info DBD::_::db::type_info
0000s0sDBD::_::dr::::BEGIN DBD::_::dr::BEGIN
0000s0sDBD::_::dr::::connect DBD::_::dr::connect
0000s0sDBD::_::dr::::connect_cached DBD::_::dr::connect_cached
0000s0sDBD::_::dr::::default_user DBD::_::dr::default_user
0000s0sDBD::_::st::::BEGIN DBD::_::st::BEGIN
0000s0sDBD::_::st::::__ANON__[:1891] DBD::_::st::__ANON__[:1891]
0000s0sDBD::_::st::::__ANON__[:1925] DBD::_::st::__ANON__[:1925]
0000s0sDBD::_::st::::bind_columns DBD::_::st::bind_columns
0000s0sDBD::_::st::::bind_param DBD::_::st::bind_param
0000s0sDBD::_::st::::bind_param_array DBD::_::st::bind_param_array
0000s0sDBD::_::st::::bind_param_inout_array DBD::_::st::bind_param_inout_array
0000s0sDBD::_::st::::blob_copy_to_file DBD::_::st::blob_copy_to_file
0000s0sDBD::_::st::::execute_array DBD::_::st::execute_array
0000s0sDBD::_::st::::execute_for_fetch DBD::_::st::execute_for_fetch
0000s0sDBD::_::st::::fetchall_arrayref DBD::_::st::fetchall_arrayref
0000s0sDBD::_::st::::fetchall_hashref DBD::_::st::fetchall_hashref
0000s0sDBD::_::st::::more_results DBD::_::st::more_results
0000s0sDBI::::BEGIN DBI::BEGIN
0000s0sDBI::::CLONE DBI::CLONE
0000s0sDBI::DBI_tie::::STORE DBI::DBI_tie::STORE
0000s0sDBI::DBI_tie::::TIEHASH DBI::DBI_tie::TIEHASH
0000s0sDBI::::END DBI::END
0000s0sDBI::::__ANON__[:1076] DBI::__ANON__[:1076]
0000s0sDBI::::__ANON__[:1110] DBI::__ANON__[:1110]
0000s0sDBI::::__ANON__[:1111] DBI::__ANON__[:1111]
0000s0sDBI::::__ANON__[:985] DBI::__ANON__[:985]
0000s0sDBI::::_dbtype_names DBI::_dbtype_names
0000s0sDBI::::_rebless_dbtype_subclass DBI::_rebless_dbtype_subclass
0000s0sDBI::::available_drivers DBI::available_drivers
0000s0sDBI::::connect_test_perf DBI::connect_test_perf
0000s0sDBI::::data_diff DBI::data_diff
0000s0sDBI::::data_sources DBI::data_sources
0000s0sDBI::::data_string_desc DBI::data_string_desc
0000s0sDBI::::data_string_diff DBI::data_string_diff
0000s0sDBI::::disconnect DBI::disconnect
0000s0sDBI::::dump_dbd_registry DBI::dump_dbd_registry
0000s0sDBI::::dump_results DBI::dump_results
0000s0sDBI::::err DBI::err
0000s0sDBI::::errstr DBI::errstr
0000s0sDBI::::init_rootclass DBI::init_rootclass
0000s0sDBI::::installed_drivers DBI::installed_drivers
0000s0sDBI::::installed_versions DBI::installed_versions
0000s0sDBI::::neat_list DBI::neat_list
0000s0sDBI::::parse_dsn DBI::parse_dsn
0000s0sDBI::st::::TIEHASH DBI::st::TIEHASH
0000s0sDBI::var::::STORE DBI::var::STORE
0000s0sDBI::var::::TIESCALAR DBI::var::TIESCALAR
Call graph for these subroutines as a Graphviz dot language file.
Line State
ments
Time
on line
Calls Time
in subs
Code
1# $Id: DBI.pm 9152 2007-02-22 01:44:25Z timbo $
2# vim: ts=8:sw=4
3#
4# Copyright (c) 1994-2007 Tim Bunce Ireland
5#
6# See COPYRIGHT section in pod text below for usage and distribution rights.
7#
8
915µsrequire 5.006_00;
10
11BEGIN {
1218µs$DBI::VERSION = "1.54"; # ==> ALSO update the version in the pod text below!
131113µs}
14
15=head1 NAME
16
17DBI - Database independent interface for Perl
18
19=head1 SYNOPSIS
20
21 use DBI;
22
23 @driver_names = DBI->available_drivers;
24 %drivers = DBI->installed_drivers;
25 @data_sources = DBI->data_sources($driver_name, \%attr);
26
27 $dbh = DBI->connect($data_source, $username, $auth, \%attr);
28
29 $rv = $dbh->do($statement);
30 $rv = $dbh->do($statement, \%attr);
31 $rv = $dbh->do($statement, \%attr, @bind_values);
32
33 $ary_ref = $dbh->selectall_arrayref($statement);
34 $hash_ref = $dbh->selectall_hashref($statement, $key_field);
35
36 $ary_ref = $dbh->selectcol_arrayref($statement);
37 $ary_ref = $dbh->selectcol_arrayref($statement, \%attr);
38
39 @row_ary = $dbh->selectrow_array($statement);
40 $ary_ref = $dbh->selectrow_arrayref($statement);
41 $hash_ref = $dbh->selectrow_hashref($statement);
42
43 $sth = $dbh->prepare($statement);
44 $sth = $dbh->prepare_cached($statement);
45
46 $rc = $sth->bind_param($p_num, $bind_value);
47 $rc = $sth->bind_param($p_num, $bind_value, $bind_type);
48 $rc = $sth->bind_param($p_num, $bind_value, \%attr);
49
50 $rv = $sth->execute;
51 $rv = $sth->execute(@bind_values);
52 $rv = $sth->execute_array(\%attr, ...);
53
54 $rc = $sth->bind_col($col_num, \$col_variable);
55 $rc = $sth->bind_columns(@list_of_refs_to_vars_to_bind);
56
57 @row_ary = $sth->fetchrow_array;
58 $ary_ref = $sth->fetchrow_arrayref;
59 $hash_ref = $sth->fetchrow_hashref;
60
61 $ary_ref = $sth->fetchall_arrayref;
62 $ary_ref = $sth->fetchall_arrayref( $slice, $max_rows );
63
64 $hash_ref = $sth->fetchall_hashref( $key_field );
65
66 $rv = $sth->rows;
67
68 $rc = $dbh->begin_work;
69 $rc = $dbh->commit;
70 $rc = $dbh->rollback;
71
72 $quoted_string = $dbh->quote($string);
73
74 $rc = $h->err;
75 $str = $h->errstr;
76 $rv = $h->state;
77
78 $rc = $dbh->disconnect;
79
80I<The synopsis above only lists the major methods and parameters.>
81
82
83=head2 GETTING HELP
84
85If you have questions about DBI, or DBD driver modules, you can get
86help from the I<dbi-users@perl.org> mailing list. You can get help
87on subscribing and using the list by emailing I<dbi-users-help@perl.org>.
88
89To help you make the best use of the dbi-users mailing list,
90and any other lists or forums you may use, I I<strongly>
91recommend that you read "How To Ask Questions The Smart Way"
92by Eric Raymond: L<http://www.catb.org/~esr/faqs/smart-questions.html>.
93
94If you think you've found a bug then please also read
95"How to Report Bugs Effectively" by Simon Tatham:
96L<http://www.chiark.greenend.org.uk/~sgtatham/bugs.html>.
97
98The DBI home page at L<http://dbi.perl.org/> is always worth a visit
99and includes an FAQ and links to other resources.
100
101Before asking any questions, reread this document, consult the
102archives and read the DBI FAQ. The archives are listed
103at the end of this document and on the DBI home page.
104An FAQ is installed as a L<DBI::FAQ> module so
105you can read it by executing C<perldoc DBI::FAQ>.
106However the DBI::FAQ module is currently (2004) outdated relative
107to the online FAQ on the DBI home page.
108
109This document often uses terms like I<references>, I<objects>,
110I<methods>. If you're not familar with those terms then it would
111be a good idea to read at least the following perl manuals first:
112L<perlreftut>, L<perldsc>, L<perllol>, and L<perlboot>.
113
114Please note that Tim Bunce does not maintain the mailing lists or the
115web page (generous volunteers do that). So please don't send mail
116directly to him; he just doesn't have the time to answer questions
117personally. The I<dbi-users> mailing list has lots of experienced
118people who should be able to help you if you need it. If you do email
119Tim he's very likely to just forward it to the mailing list.
120
121=head2 NOTES
122
123This is the DBI specification that corresponds to the DBI version 1.54
124($Revision: 9152 $).
125
126The DBI is evolving at a steady pace, so it's good to check that
127you have the latest copy.
128
129The significant user-visible changes in each release are documented
130in the L<DBI::Changes> module so you can read them by executing
131C<perldoc DBI::Changes>.
132
133Some DBI changes require changes in the drivers, but the drivers
134can take some time to catch up. Newer versions of the DBI have
135added features that may not yet be supported by the drivers you
136use. Talk to the authors of your drivers if you need a new feature
137that's not yet supported.
138
139Features added after DBI 1.21 (February 2002) are marked in the
140text with the version number of the DBI release they first appeared in.
141
142Extensions to the DBI API often use the C<DBIx::*> namespace.
143See L</Naming Conventions and Name Space>. DBI extension modules
144can be found at L<http://search.cpan.org/search?mode=module&query=DBIx>.
145And all modules related to the DBI can be found at
146L<http://search.cpan.org/search?query=DBI&mode=all>.
147
148=cut
149
150# The POD text continues at the end of the file.
151
152
153package DBI;
154
155348µsuse Carp();
1563302µsuse DynaLoader ();
1573553µsuse Exporter ();
158
159BEGIN {
1601222.49ms@ISA = qw(Exporter DynaLoader);
161
162# Make some utility functions available if asked for
163@EXPORT = (); # we export nothing by default
164@EXPORT_OK = qw(%DBI %DBI_methods hash); # also populated by export_ok_tags:
165%EXPORT_TAGS = (
166 sql_types => [ qw(
167 SQL_GUID
168 SQL_WLONGVARCHAR
169 SQL_WVARCHAR
170 SQL_WCHAR
171 SQL_BIGINT
172 SQL_BIT
173 SQL_TINYINT
174 SQL_LONGVARBINARY
175 SQL_VARBINARY
176 SQL_BINARY
177 SQL_LONGVARCHAR
178 SQL_UNKNOWN_TYPE
179 SQL_ALL_TYPES
180 SQL_CHAR
181 SQL_NUMERIC
182 SQL_DECIMAL
183 SQL_INTEGER
184 SQL_SMALLINT
185 SQL_FLOAT
186 SQL_REAL
187 SQL_DOUBLE
188 SQL_DATETIME
189 SQL_DATE
190 SQL_INTERVAL
191 SQL_TIME
192 SQL_TIMESTAMP
193 SQL_VARCHAR
194 SQL_BOOLEAN
195 SQL_UDT
196 SQL_UDT_LOCATOR
197 SQL_ROW
198 SQL_REF
199 SQL_BLOB
200 SQL_BLOB_LOCATOR
201 SQL_CLOB
202 SQL_CLOB_LOCATOR
203 SQL_ARRAY
204 SQL_ARRAY_LOCATOR
205 SQL_MULTISET
206 SQL_MULTISET_LOCATOR
207 SQL_TYPE_DATE
208 SQL_TYPE_TIME
209 SQL_TYPE_TIMESTAMP
210 SQL_TYPE_TIME_WITH_TIMEZONE
211 SQL_TYPE_TIMESTAMP_WITH_TIMEZONE
212 SQL_INTERVAL_YEAR
213 SQL_INTERVAL_MONTH
214 SQL_INTERVAL_DAY
215 SQL_INTERVAL_HOUR
216 SQL_INTERVAL_MINUTE
217 SQL_INTERVAL_SECOND
218 SQL_INTERVAL_YEAR_TO_MONTH
219 SQL_INTERVAL_DAY_TO_HOUR
220 SQL_INTERVAL_DAY_TO_MINUTE
221 SQL_INTERVAL_DAY_TO_SECOND
222 SQL_INTERVAL_HOUR_TO_MINUTE
223 SQL_INTERVAL_HOUR_TO_SECOND
224 SQL_INTERVAL_MINUTE_TO_SECOND
225 ) ],
226 sql_cursor_types => [ qw(
227 SQL_CURSOR_FORWARD_ONLY
228 SQL_CURSOR_KEYSET_DRIVEN
229 SQL_CURSOR_DYNAMIC
230 SQL_CURSOR_STATIC
231 SQL_CURSOR_TYPE_DEFAULT
232 ) ], # for ODBC cursor types
233 utils => [ qw(
234 neat neat_list $neat_maxlen dump_results looks_like_number
235 data_string_diff data_string_desc data_diff
236 ) ],
237 profile => [ qw(
238 dbi_profile dbi_profile_merge dbi_time
239 ) ], # notionally "in" DBI::Profile and normally imported from there
240);
241
242$DBI::dbi_debug = 0;
243$DBI::neat_maxlen = 400;
244
245# If you get an error here like "Can't find loadable object ..."
246# then you haven't installed the DBI correctly. Read the README
247# then install it again.
248if ( $ENV{DBI_PUREPERL} ) {
249 eval { bootstrap DBI } if $ENV{DBI_PUREPERL} == 1;
250 require DBI::PurePerl if $@ or $ENV{DBI_PUREPERL} >= 2;
251 $DBI::PurePerl ||= 0; # just to silence "only used once" warnings
252}
253else {
254 bootstrap DBI;
# spent 1.31ms making 1 call to DynaLoader::bootstrap
255}
256
257$EXPORT_TAGS{preparse_flags} = [ grep { /^DBIpp_\w\w_/ } keys %{__PACKAGE__."::"} ];
# spent 535µs making 112 calls to DBI::CORE:match, avg 5µs/call
258
259Exporter::export_ok_tags(keys %EXPORT_TAGS);
# spent 3.60ms making 1 call to Exporter::export_ok_tags
260
2611138µs}
262
263# Alias some handle methods to also be DBI class methods
264113µsfor (qw(trace_msg set_err parse_trace_flag parse_trace_flags)) {
2653139µs125µs no strict;
# spent 25µs making 1 call to strict::unimport
266472µs *$_ = \&{"DBD::_::common::$_"};
267}
268
26932.70ms121µsuse strict;
# spent 21µs making 1 call to strict::import
270
27117µsDBI->trace(split /=/, $ENV{DBI_TRACE}, 2) if $ENV{DBI_TRACE};
272
27315µs$DBI::connect_via ||= "connect";
274
275# check if user wants a persistent database connection ( Apache + mod_perl )
27615µsif ($INC{'Apache/DBI.pm'} && $ENV{MOD_PERL}) {
277 $DBI::connect_via = "Apache::DBI::connect";
278 DBI->trace_msg("DBI connect via $DBI::connect_via in $INC{'Apache/DBI.pm'}\n");
279}
280
281# check for weaken support, used by ChildHandles
282111µsmy $HAS_WEAKEN = eval {
2831239µs require Scalar::Util;
284 # this will croak() if this Scalar::Util doesn't have a working weaken().
285142µs115µs Scalar::Util::weaken( \my $test ); # same test as in t/72childhandles.t
# spent 15µs making 1 call to Scalar::Util::weaken
28617µs 1;
287};
288
28916µs%DBI::installed_drh = (); # maps driver names to installed driver handles
290sub installed_drivers { %DBI::installed_drh }
291
292# Setup special DBI dynamic variables. See DBI::var::FETCH for details.
293# These are dynamically associated with the last handle used.
294122µstie $DBI::err, 'DBI::var', '*err'; # special case: referenced via IHA list
295112µstie $DBI::state, 'DBI::var', '"state'; # special case: referenced via IHA list
296111µstie $DBI::lasth, 'DBI::var', '!lasth'; # special case: return boolean
297136µstie $DBI::errstr, 'DBI::var', '&errstr'; # call &errstr in last used pkg
298112µstie $DBI::rows, 'DBI::var', '&rows'; # call &rows in last used pkg
2991053µssub DBI::var::TIESCALAR{ my $var = $_[1]; bless \$var, 'DBI::var'; }
300sub DBI::var::STORE { Carp::croak("Can't modify \$DBI::${$_[0]} special variable") }
301
302{ # used to catch DBI->{Attrib} mistake
303216µs sub DBI::DBI_tie::TIEHASH { bless {} }
304 sub DBI::DBI_tie::STORE { Carp::carp("DBI->{$_[1]} is invalid syntax (you probably want \$h->{$_[1]})");}
30519µs *DBI::DBI_tie::FETCH = \&DBI::DBI_tie::STORE;
306}
307117µstie %DBI::DBI => 'DBI::DBI_tie';
308
309# --- Driver Specific Prefix Registry ---
310
3111112µsmy $dbd_prefix_registry = {
312 ad_ => { class => 'DBD::AnyData', },
313 ado_ => { class => 'DBD::ADO', },
314 amzn_ => { class => 'DBD::Amazon', },
315 best_ => { class => 'DBD::BestWins', },
316 csv_ => { class => 'DBD::CSV', },
317 db2_ => { class => 'DBD::DB2', },
318 dbi_ => { class => 'DBI', },
319 dbm_ => { class => 'DBD::DBM', },
320 df_ => { class => 'DBD::DF', },
321 f_ => { class => 'DBD::File', },
322 file_ => { class => 'DBD::TextFile', },
323 go_ => { class => 'DBD::Gofer', },
324 ib_ => { class => 'DBD::InterBase', },
325 ing_ => { class => 'DBD::Ingres', },
326 ix_ => { class => 'DBD::Informix', },
327 jdbc_ => { class => 'DBD::JDBC', },
328 monetdb_ => { class => 'DBD::monetdb', },
329 msql_ => { class => 'DBD::mSQL', },
330 mysql_ => { class => 'DBD::mysql', },
331 mx_ => { class => 'DBD::Multiplex', },
332 nullp_ => { class => 'DBD::NullP', },
333 odbc_ => { class => 'DBD::ODBC', },
334 ora_ => { class => 'DBD::Oracle', },
335 pg_ => { class => 'DBD::Pg', },
336 plb_ => { class => 'DBD::Plibdata', },
337 proxy_ => { class => 'DBD::Proxy', },
338 rdb_ => { class => 'DBD::RDB', },
339 sapdb_ => { class => 'DBD::SAP_DB', },
340 solid_ => { class => 'DBD::Solid', },
341 sponge_ => { class => 'DBD::Sponge', },
342 sql_ => { class => 'SQL::Statement', },
343 syb_ => { class => 'DBD::Sybase', },
344 tdat_ => { class => 'DBD::Teradata', },
345 tmpl_ => { class => 'DBD::Template', },
346 tmplss_ => { class => 'DBD::TemplateSS', },
347 tuber_ => { class => 'DBD::Tuber', },
348 uni_ => { class => 'DBD::Unify', },
349 wmi_ => { class => 'DBD::WMI', },
350 x_ => { }, # for private use
351 xbase_ => { class => 'DBD::XBase', },
352 xl_ => { class => 'DBD::Excel', },
353 yaswi_ => { class => 'DBD::Yaswi', },
354};
355
356sub dump_dbd_registry {
357 require Data::Dumper;
358 local $Data::Dumper::Sortkeys=1;
359 local $Data::Dumper::Indent=1;
360 print Data::Dumper->Dump([$dbd_prefix_registry], [qw($dbd_prefix_registry)]);
361}
362
363# --- Dynamically create the DBI Standard Interface
364
36517µsmy $keeperr = { O=>0x0004 };
366
3671223µs%DBI::DBI_methods = ( # Define the DBI interface methods per class:
368
369 common => { # Interface methods common to all DBI handle classes
370 'DESTROY' => $keeperr,
371 'CLEAR' => $keeperr,
372 'EXISTS' => $keeperr,
373 'FETCH' => { O=>0x0404 },
374 'FIRSTKEY' => $keeperr,
375 'NEXTKEY' => $keeperr,
376 'STORE' => { O=>0x0418 | 0x4 },
377 _not_impl => undef,
378 can => { O=>0x0100 }, # special case, see dispatch
379 debug => { U =>[1,2,'[$debug_level]'], O=>0x0004 }, # old name for trace
380 dump_handle => { U =>[1,3,'[$message [, $level]]'], O=>0x0004 },
381 err => $keeperr,
382 errstr => $keeperr,
383 state => $keeperr,
384 func => { O=>0x0006 },
385 parse_trace_flag => { U =>[2,2,'$name'], O=>0x0404, T=>8 },
386 parse_trace_flags => { U =>[2,2,'$flags'], O=>0x0404, T=>8 },
387 private_data => { U =>[1,1], O=>0x0004 },
388 set_err => { U =>[3,6,'$err, $errmsg [, $state, $method, $rv]'], O=>0x0010 },
389 trace => { U =>[1,3,'[$trace_level, [$filename]]'], O=>0x0004 },
390 trace_msg => { U =>[2,3,'$message_text [, $min_level ]' ], O=>0x0004, T=>8 },
391 swap_inner_handle => { U =>[2,3,'$h [, $allow_reparent ]'] },
392 private_attribute_info => { },
393 },
394 dr => { # Database Driver Interface
395 'connect' => { U =>[1,5,'[$db [,$user [,$passwd [,\%attr]]]]'], H=>3, O=>0x8000 },
396 'connect_cached'=>{U=>[1,5,'[$db [,$user [,$passwd [,\%attr]]]]'], H=>3, O=>0x8000 },
397 'disconnect_all'=>{ U =>[1,1], O=>0x0800 },
398 data_sources => { U =>[1,2,'[\%attr]' ], O=>0x0800 },
399 default_user => { U =>[3,4,'$user, $pass [, \%attr]' ] },
400 },
401 db => { # Database Session Class Interface
402 data_sources => { U =>[1,2,'[\%attr]' ], O=>0x0200 },
403 take_imp_data => { U =>[1,1], },
404 clone => { U =>[1,2,'[\%attr]'] },
405 connected => { U =>[1,0], O => 0x0004 },
406 begin_work => { U =>[1,2,'[ \%attr ]'], O=>0x0400 },
407 commit => { U =>[1,1], O=>0x0480|0x0800 },
408 rollback => { U =>[1,1], O=>0x0480|0x0800 },
409 'do' => { U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'], O=>0x3200 },
410 last_insert_id => { U =>[5,6,'$catalog, $schema, $table_name, $field_name [, \%attr ]'], O=>0x2800 },
411 preparse => { }, # XXX
412 prepare => { U =>[2,3,'$statement [, \%attr]'], O=>0xA200 },
413 prepare_cached => { U =>[2,4,'$statement [, \%attr [, $if_active ] ]'], O=>0xA200 },
414 selectrow_array => { U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'], O=>0x2000 },
415 selectrow_arrayref=>{U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'], O=>0x2000 },
416 selectrow_hashref=>{ U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'], O=>0x2000 },
417 selectall_arrayref=>{U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'], O=>0x2000 },
418 selectall_hashref=>{ U =>[3,0,'$statement, $keyfield [, \%attr [, @bind_params ] ]'], O=>0x2000 },
419 selectcol_arrayref=>{U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'], O=>0x2000 },
420 ping => { U =>[1,1], O=>0x0404 },
421 disconnect => { U =>[1,1], O=>0x0400|0x0800 },
422 quote => { U =>[2,3, '$string [, $data_type ]' ], O=>0x0430 },
423 quote_identifier=> { U =>[2,6, '$name [, ...] [, \%attr ]' ], O=>0x0430 },
424 rows => $keeperr,
425
426 tables => { U =>[1,6,'$catalog, $schema, $table, $type [, \%attr ]' ], O=>0x2200 },
427 table_info => { U =>[1,6,'$catalog, $schema, $table, $type [, \%attr ]' ], O=>0x2200|0x8800 },
428 column_info => { U =>[5,6,'$catalog, $schema, $table, $column [, \%attr ]'],O=>0x2200|0x8800 },
429 primary_key_info=> { U =>[4,5,'$catalog, $schema, $table [, \%attr ]' ], O=>0x2200|0x8800 },
430 primary_key => { U =>[4,5,'$catalog, $schema, $table [, \%attr ]' ], O=>0x2200 },
431 foreign_key_info=> { U =>[7,8,'$pk_catalog, $pk_schema, $pk_table, $fk_catalog, $fk_schema, $fk_table [, \%attr ]' ], O=>0x2200|0x8800 },
432 statistics_info => { U =>[6,7,'$catalog, $schema, $table, $unique_only, $quick, [, \%attr ]' ], O=>0x2200|0x8800 },
433 type_info_all => { U =>[1,1], O=>0x2200|0x0800 },
434 type_info => { U =>[1,2,'$data_type'], O=>0x2200 },
435 get_info => { U =>[2,2,'$info_type'], O=>0x2200|0x0800 },
436 },
437 st => { # Statement Class Interface
438 bind_col => { U =>[3,4,'$column, \\$var [, \%attr]'] },
439 bind_columns => { U =>[2,0,'\\$var1 [, \\$var2, ...]'] },
440 bind_param => { U =>[3,4,'$parameter, $var [, \%attr]'] },
441 bind_param_inout=> { U =>[4,5,'$parameter, \\$var, $maxlen, [, \%attr]'] },
442 execute => { U =>[1,0,'[@args]'], O=>0x1040 },
443
444 bind_param_array => { U =>[3,4,'$parameter, $var [, \%attr]'] },
445 bind_param_inout_array => { U =>[4,5,'$parameter, \\@var, $maxlen, [, \%attr]'] },
446 execute_array => { U =>[2,0,'\\%attribs [, @args]'], O=>0x1040|0x4000 },
447 execute_for_fetch => { U =>[2,3,'$fetch_sub [, $tuple_status]'], O=>0x1040|0x4000 },
448
449 fetch => undef, # alias for fetchrow_arrayref
450 fetchrow_arrayref => undef,
451 fetchrow_hashref => undef,
452 fetchrow_array => undef,
453 fetchrow => undef, # old alias for fetchrow_array
454
455 fetchall_arrayref => { U =>[1,3, '[ $slice [, $max_rows]]'] },
456 fetchall_hashref => { U =>[2,2,'$key_field'] },
457
458 blob_read => { U =>[4,5,'$field, $offset, $len [, \\$buf [, $bufoffset]]'] },
459 blob_copy_to_file => { U =>[3,3,'$field, $filename_or_handleref'] },
460 dump_results => { U =>[1,5,'$maxfieldlen, $linesep, $fieldsep, $filehandle'] },
461 more_results => { U =>[1,1] },
462 finish => { U =>[1,1] },
463 cancel => { U =>[1,1], O=>0x0800 },
464 rows => $keeperr,
465
466 _get_fbav => undef,
467 _set_fbav => { T=>6 },
468 },
469);
470
471114µswhile ( my ($class, $meths) = each %DBI::DBI_methods ) {
472430µs my $ima_trace = 0+($ENV{DBI_IMA_TRACE}||0);
473465µs while ( my ($method, $info) = each %$meths ) {
47486485µs my $fullmeth = "DBI::${class}::$method";
47586372µs if ($DBI::dbi_debug >= 15) { # quick hack to list DBI methods
476 # and optionally filter by IMA flags
477 my $O = $info->{O}||0;
478 printf "0x%04x %-20s\n", $O, $fullmeth
479 unless $ima_trace && !($O & $ima_trace);
480 }
481862.79ms861.03ms DBI->_install_method($fullmeth, 'DBI.pm', $info);
# spent 1.03ms making 86 calls to DBI::_install_method, avg 12µs/call
482 }
483}
484
485{
48619µs package DBI::common;
48719µs @DBI::dr::ISA = ('DBI::common');
48816µs @DBI::db::ISA = ('DBI::common');
48916µs @DBI::st::ISA = ('DBI::common');
490}
491
492# End of init code
493
494
495END {
4965106µs return unless defined &DBI::trace_msg; # return unless bootstrap'd ok
497 local ($!,$?);
498 DBI->trace_msg(" -- DBI::END\n", 2);
# spent 11µs making 1 call to DBD::_::common::trace_msg
499 # Let drivers know why we are calling disconnect_all:
500 $DBI::PERL_ENDING = $DBI::PERL_ENDING = 1; # avoid typo warning
501 DBI->disconnect_all() if %DBI::installed_drh;
# spent 98µs making 1 call to DBI::disconnect_all
502}
503
504
505sub CLONE {
506 my $olddbis = $DBI::_dbistate;
507 _clone_dbis() unless $DBI::PurePerl; # clone the DBIS structure
508 DBI->trace_msg(sprintf "CLONE DBI for new thread %s\n",
509 $DBI::PurePerl ? "" : sprintf("(dbis %x -> %x)",$olddbis, $DBI::_dbistate));
510 while ( my ($driver, $drh) = each %DBI::installed_drh) {
51131.84ms1103µs no strict 'refs';
# spent 103µs making 1 call to strict::unimport
512 next if defined &{"DBD::${driver}::CLONE"};
513 warn("$driver has no driver CLONE() function so is unsafe threaded\n");
514 }
515 %DBI::installed_drh = (); # clear loaded drivers so they have a chance to reinitialize
516}
517
518sub parse_dsn {
519 my ($class, $dsn) = @_;
520 $dsn =~ s/^(dbi):(\w*?)(?:\((.*?)\))?://i or return;
521 my ($scheme, $driver, $attr, $attr_hash) = (lc($1), $2, $3);
522 $driver ||= $ENV{DBI_DRIVER} || '';
523 $attr_hash = { split /\s*=>?\s*|\s*,\s*/, $attr, -1 } if $attr;
524 return ($scheme, $driver, $attr, $attr_hash, $dsn);
525}
526
527
528# --- The DBI->connect Front Door methods
529
530
# spent 138ms (69µs+138) within DBI::connect_cached which was called # once (69µs+138ms) by Ima::DBI::__ANON__[/project/perl/lib/Ima/DBI.pm:316] at line 312 of Ima/DBI.pm
sub connect_cached {
531 # For library code using connect_cached() with mod_perl
532 # we redirect those calls to Apache::DBI::connect() as well
533468µs my ($class, $dsn, $user, $pass, $attr) = @_;
534 my $dbi_connect_method = ($DBI::connect_via eq "Apache::DBI::connect")
535 ? 'Apache::DBI::connect' : 'connect_cached';
536 $attr = {
537 $attr ? %$attr : (), # clone, don't modify callers data
538 dbi_connect_method => $dbi_connect_method,
539 };
540 return $class->connect($dsn, $user, $pass, $attr);
# spent 138ms making 1 call to DBI::connect
541}
542
543
# spent 138ms (351µs+137) within DBI::connect which was called # once (351µs+137ms) by DBI::connect_cached at line 540
sub connect {
54428343µs my $class = shift;
545 my ($dsn, $user, $pass, $attr, $old_driver) = my @orig_args = @_;
546 my $driver;
547
548 if ($attr and !ref($attr)) { # switch $old_driver<->$attr if called in old style
549 Carp::carp("DBI->connect using 'old-style' syntax is deprecated and will be an error in future versions");
550 ($old_driver, $attr) = ($attr, $old_driver);
551 }
552
553 my $connect_meth = $attr->{dbi_connect_method};
554 $connect_meth ||= $DBI::connect_via; # fallback to default
555
556 $dsn ||= $ENV{DBI_DSN} || $ENV{DBI_DBNAME} || '' unless $old_driver;
557
558 if ($DBI::dbi_debug) {
559 local $^W = 0;
560 pop @_ if $connect_meth ne 'connect';
561 my @args = @_; $args[2] = '****'; # hide password
562 DBI->trace_msg(" -> $class->$connect_meth(".join(", ",@args).")\n");
563 }
564 Carp::croak('Usage: $class->connect([$dsn [,$user [,$passwd [,\%attr]]]])')
565 if (ref $old_driver or ($attr and not ref $attr) or ref $pass);
566
567 # extract dbi:driver prefix from $dsn into $1
568 $dsn =~ s/^dbi:(\w*?)(?:\((.*?)\))?://i
# spent 18µs making 1 call to DBI::CORE:subst
569 or '' =~ /()/; # ensure $1 etc are empty if match fails
570 my $driver_attrib_spec = $2 || '';
571
572 # Set $driver. Old style driver, if specified, overrides new dsn style.
573 $driver = $old_driver || $1 || $ENV{DBI_DRIVER}
574 or Carp::croak("Can't connect to data source $dsn, no database driver specified "
575 ."and DBI_DSN env var not set");
576
577 my $proxy;
578 if ($ENV{DBI_AUTOPROXY} && $driver ne 'Proxy' && $driver ne 'Sponge' && $driver ne 'Switch') {
579 my $dbi_autoproxy = $ENV{DBI_AUTOPROXY};
580 $proxy = 'Proxy';
581 if ($dbi_autoproxy =~ s/^dbi:(\w*?)(?:\((.*?)\))?://i) {
582 $proxy = $1;
583 $driver_attrib_spec = join ",",
584 ($driver_attrib_spec) ? $driver_attrib_spec : (),
585 ($2 ) ? $2 : ();
586 }
587 $dsn = "$dbi_autoproxy;dsn=dbi:$driver:$dsn";
588 $driver = $proxy;
589 DBI->trace_msg(" DBI_AUTOPROXY: dbi:$driver($driver_attrib_spec):$dsn\n");
590 }
591 # avoid recursion if proxy calls DBI->connect itself
592 local $ENV{DBI_AUTOPROXY};
593
594 my %attributes; # take a copy we can delete from
595 if ($old_driver) {
596 %attributes = %$attr if $attr;
597 }
598 else { # new-style connect so new default semantics
599 %attributes = (
600 PrintError => 1,
601 AutoCommit => 1,
602 ref $attr ? %$attr : (),
603 # attributes in DSN take precedence over \%attr connect parameter
604 $driver_attrib_spec ? (split /\s*=>?\s*|\s*,\s*/, $driver_attrib_spec, -1) : (),
605 );
606 }
607 $attr = \%attributes; # now set $attr to refer to our local copy
608
609 my $drh = $DBI::installed_drh{$driver} || $class->install_driver($driver)
# spent 31.2ms making 1 call to DBI::install_driver
610 or die "panic: $class->install_driver($driver) failed";
611
612 # attributes in DSN take precedence over \%attr connect parameter
613 $user = $attr->{Username} if defined $attr->{Username};
614 $pass = delete $attr->{Password} if defined $attr->{Password};
615 if ( !(defined $user && defined $pass) ) {
616 ($user, $pass) = $drh->default_user($user, $pass, $attr);
617 }
618 $attr->{Username} = $user; # force the Username to be the actual one used
619
620
# spent 106ms (820µs+105) within DBI::__ANON__[/project/perl/lib/DBI.pm:692] which was called # once (820µs+105ms) by DBI::connect at line 694
my $connect_closure = sub {
621421.03ms my ($old_dbh, $override_attr) = @_;
622
623 #use Data::Dumper;
624 #warn "connect_closure: ".Data::Dumper::Dumper([$attr,\%attributes, $override_attr]);
625
626 my $dbh;
627128µs174.9ms unless ($dbh = $drh->$connect_meth($dsn, $user, $pass, $attr)) {
# spent 74.9ms making 1 call to DBI::dr::connect_cached
628 $user = '' if !defined $user;
629 $dsn = '' if !defined $dsn;
630 # $drh->errstr isn't safe here because $dbh->DESTROY may not have
631 # been called yet and so the dbh errstr would not have been copied
632 # up to the drh errstr. Certainly true for connect_cached!
633 my $errstr = $DBI::errstr;
634 $errstr = '(no error string)' if !defined $errstr;
635 my $msg = "$class connect('$dsn','$user',...) failed: $errstr";
636 DBI->trace_msg(" $msg\n");
637 # XXX HandleWarn
638 unless ($attr->{HandleError} && $attr->{HandleError}->($msg, $drh, $dbh)) {
639 Carp::croak($msg) if $attr->{RaiseError};
640 Carp::carp ($msg) if $attr->{PrintError};
641 }
642 $! = 0; # for the daft people who do DBI->connect(...) || die "$!";
643 return $dbh; # normally undef, but HandleError could change it
644 }
645
646 # merge any attribute overrides but don't change $attr itself (for closure)
647 my $apply = { ($override_attr) ? (%$attr, %$override_attr ) : %$attr };
648
649 # handle basic RootClass subclassing:
650 my $rebless_class = $apply->{RootClass} || ($class ne 'DBI' ? $class : '');
651 if ($rebless_class) {
65231.49ms1102µs no strict 'refs';
# spent 102µs making 1 call to strict::unimport
653 if ($apply->{RootClass}) { # explicit attribute (ie not static methd call class)
654 delete $apply->{RootClass};
655 DBI::_load_class($rebless_class, 0);
# spent 30.0ms making 1 call to DBI::_load_class
656 }
657 unless (@{"$rebless_class\::db::ISA"} && @{"$rebless_class\::st::ISA"}) {
658 Carp::carp("DBI subclasses '$rebless_class\::db' and ::st are not setup, RootClass ignored");
659 $rebless_class = undef;
660 $class = 'DBI';
661 }
662 else {
663 $dbh->{RootClass} = $rebless_class; # $dbh->STORE called via plain DBI::db
# spent 21µs making 1 call to DBI::common::STORE
664 DBI::_set_isa([$rebless_class], 'DBI'); # sets up both '::db' and '::st'
# spent 161µs making 1 call to DBI::_set_isa
665 DBI::_rebless($dbh, $rebless_class); # appends '::db'
# spent 84µs making 1 call to DBI::_rebless
666 }
667 }
668
669 if (%$apply) {
670
671 if ($apply->{DbTypeSubclass}) {
672 my $DbTypeSubclass = delete $apply->{DbTypeSubclass};
673 DBI::_rebless_dbtype_subclass($dbh, $rebless_class||$class, $DbTypeSubclass);
674 }
675 my $a;
676 foreach $a (qw(Profile RaiseError PrintError AutoCommit)) { # do these first
677 next unless exists $apply->{$a};
678 $dbh->{$a} = delete $apply->{$a};
# spent 48µs making 3 calls to DBI::common::STORE, avg 16µs/call
679 }
680 while ( my ($a, $v) = each %$apply) {
681 eval { $dbh->{$a} = $v } or $@ && warn $@;
# spent 66µs making 7 calls to DBI::common::STORE, avg 9µs/call # spent 55µs making 7 calls to DBI::common::FETCH, avg 8µs/call
682 }
683 }
684
685 # confirm to driver (ie if subclassed) that we've connected sucessfully
686 # and finished the attribute setup. pass in the original arguments
687 $dbh->connected(@orig_args); #if ref $dbh ne 'DBI::db' or $proxy;
# spent 24µs making 1 call to DBI::db::connected
688
689 DBI->trace_msg(" <- connect= $dbh\n") if $DBI::dbi_debug;
690
691 return $dbh;
692 };
693
694 my $dbh = &$connect_closure(undef, undef);
# spent 106ms making 1 call to DBI::__ANON__[DBI.pm:692]
695
696 $dbh->{dbi_connect_closure} = $connect_closure if $dbh;
# spent 12µs making 1 call to DBI::common::STORE
697
698 return $dbh;
699}
700
701
702
# spent 98µs (63+35) within DBI::disconnect_all which was called # once (63µs+35µs) by DBI::END at line 501
sub disconnect_all {
7033101µs keys %DBI::installed_drh; # reset iterator
704 while ( my ($name, $drh) = each %DBI::installed_drh ) {
705 $drh->disconnect_all() if ref $drh;
# spent 35µs making 1 call to DBI::dr::disconnect_all
706 }
707}
708
709
710sub disconnect { # a regular beginners bug
711 Carp::croak("DBI->disconnect is not a DBI method (read the DBI manual)");
712}
713
714
715
# spent 31.2ms (16.3+14.9) within DBI::install_driver which was called # once (16.3ms+14.9ms) by DBI::connect at line 609
sub install_driver { # croaks on failure
71619318µs my $class = shift;
717 my($driver, $attr) = @_;
718 my $drh;
719
720 $driver ||= $ENV{DBI_DRIVER} || '';
721
722 # allow driver to be specified as a 'dbi:driver:' string
723 $driver = $1 if $driver =~ s/^DBI:(.*?)://i;
# spent 5µs making 1 call to DBI::CORE:subst
724
725 Carp::croak("usage: $class->install_driver(\$driver [, \%attr])")
726 unless ($driver and @_<=3);
727
728 # already installed
729 return $drh if $drh = $DBI::installed_drh{$driver};
730
731 $class->trace_msg(" -> $class->install_driver($driver"
732 .") for $^O perl=$] pid=$$ ruid=$< euid=$>\n")
733 if $DBI::dbi_debug;
734
735 # --- load the code
736 my $driver_class = "DBD::$driver";
7371208µs eval qq{package # hide from PAUSE
738 DBI::_firesafe; # just in case
739 require $driver_class; # load the driver
740 };
741 if ($@) {
742 my $err = $@;
743 my $advice = "";
744 if ($err =~ /Can't find loadable object/) {
745 $advice = "Perhaps DBD::$driver was statically linked into a new perl binary."
746 ."\nIn which case you need to use that new perl binary."
747 ."\nOr perhaps only the .pm file was installed but not the shared object file."
748 }
749 elsif ($err =~ /Can't locate.*?DBD\/$driver\.pm in \@INC/) {
750 my @drv = $class->available_drivers(1);
751 $advice = "Perhaps the DBD::$driver perl module hasn't been fully installed,\n"
752 ."or perhaps the capitalisation of '$driver' isn't right.\n"
753 ."Available drivers: ".join(", ", @drv).".";
754 }
755 elsif ($err =~ /Can't load .*? for module DBD::/) {
756 $advice = "Perhaps a required shared library or dll isn't installed where expected";
757 }
758 elsif ($err =~ /Can't locate .*? in \@INC/) {
759 $advice = "Perhaps a module that DBD::$driver requires hasn't been fully installed";
760 }
761 Carp::croak("install_driver($driver) failed: $err$advice\n");
762 }
763 if ($DBI::dbi_debug) {
7643609µs1102µs no strict 'refs';
# spent 102µs making 1 call to strict::unimport
765 (my $driver_file = $driver_class) =~ s/::/\//g;
766 my $dbd_ver = ${"$driver_class\::VERSION"} || "undef";
767 $class->trace_msg(" install_driver: $driver_class version $dbd_ver"
768 ." loaded from $INC{qq($driver_file.pm)}\n");
769 }
770
771 # --- do some behind-the-scenes checks and setups on the driver
772 $class->setup_driver($driver_class);
# spent 274µs making 1 call to DBI::setup_driver
773
774 # --- run the driver function
775 $drh = eval { $driver_class->driver($attr || {}) };
# spent 6.27ms making 1 call to DBD::Pg::driver
776 unless ($drh && ref $drh && !$@) {
777 my $advice = "";
778 # catch people on case in-sensitive systems using the wrong case
779 $advice = "\nPerhaps the capitalisation of DBD '$driver' isn't right."
780 if $@ =~ /locate object method/;
781 Carp::croak("$driver_class initialisation failed: $@$advice");
782 }
783
784 $DBI::installed_drh{$driver} = $drh;
785 $class->trace_msg(" <- install_driver= $drh\n") if $DBI::dbi_debug;
786 $drh;
787}
788
78918µs*driver = \&install_driver; # currently an alias, may change
790
791
792
# spent 541µs (427+114) within DBI::setup_driver which was called 2 times, avg 270µs/call: # once (215µs+59µs) by DBI::install_driver at line 772 # once (212µs+55µs) by base::import at line 1279
sub setup_driver {
79330550µs my ($class, $driver_class) = @_;
794 my $type;
795 foreach $type (qw(dr db st)){
796 my $class = $driver_class."::$type";
7973519µs198µs no strict 'refs';
# spent 98µs making 1 call to strict::unimport
798 push @{"${class}::ISA"}, "DBD::_::$type"
# spent 62µs making 6 calls to UNIVERSAL::isa, avg 10µs/call
799 unless UNIVERSAL::isa($class, "DBD::_::$type");
800 my $mem_class = "DBD::_mem::$type";
801 push @{"${class}_mem::ISA"}, $mem_class
# spent 52µs making 6 calls to UNIVERSAL::isa, avg 9µs/call
802 unless UNIVERSAL::isa("${class}_mem", $mem_class)
803 or $DBI::PurePerl;
804 }
805}
806
807
808
# spent 84µs (71+13) within DBI::_rebless which was called # once (71µs+13µs) by DBI::__ANON__[/project/perl/lib/DBI.pm:692] at line 665
sub _rebless {
809588µs my $dbh = shift;
810 my ($outer, $inner) = DBI::_handles($dbh);
# spent 13µs making 1 call to DBI::_handles
811 my $class = shift(@_).'::db';
812 bless $inner => $class;
813 bless $outer => $class; # outer last for return
814}
815
816
817
# spent 161µs (154+7) within DBI::_set_isa which was called # once (154µs+7µs) by DBI::__ANON__[/project/perl/lib/DBI.pm:692] at line 664
sub _set_isa {
81817177µs my ($classes, $topclass) = @_;
819 my $trace = DBI->trace_msg(" _set_isa([@$classes])\n");
# spent 7µs making 1 call to DBD::_::common::trace_msg
820 foreach my $suffix ('::db','::st') {
821 my $previous = $topclass || 'DBI'; # trees are rooted here
822 foreach my $class (@$classes) {
823 my $base_class = $previous.$suffix;
824 my $sub_class = $class.$suffix;
825 my $sub_class_isa = "${sub_class}::ISA";
82631.17ms192µs no strict 'refs';
# spent 92µs making 1 call to strict::unimport
827 if (@$sub_class_isa) {
828 DBI->trace_msg(" $sub_class_isa skipped (already set to @$sub_class_isa)\n")
829 if $trace;
830 }
831 else {
832 @$sub_class_isa = ($base_class) unless @$sub_class_isa;
833 DBI->trace_msg(" $sub_class_isa = $base_class\n")
834 if $trace;
835 }
836 $previous = $class;
837 }
838 }
839}
840
841
842sub _rebless_dbtype_subclass {
843 my ($dbh, $rootclass, $DbTypeSubclass) = @_;
844 # determine the db type names for class hierarchy
845 my @hierarchy = DBI::_dbtype_names($dbh, $DbTypeSubclass);
846 # add the rootclass prefix to each ('DBI::' or 'MyDBI::' etc)
847 $_ = $rootclass.'::'.$_ foreach (@hierarchy);
848 # load the modules from the 'top down'
849 DBI::_load_class($_, 1) foreach (reverse @hierarchy);
850 # setup class hierarchy if needed, does both '::db' and '::st'
851 DBI::_set_isa(\@hierarchy, $rootclass);
852 # finally bless the handle into the subclass
853 DBI::_rebless($dbh, $hierarchy[0]);
854}
855
856
857sub _dbtype_names { # list dbtypes for hierarchy, ie Informix=>ADO=>ODBC
858 my ($dbh, $DbTypeSubclass) = @_;
859
860 if ($DbTypeSubclass && $DbTypeSubclass ne '1' && ref $DbTypeSubclass ne 'CODE') {
861 # treat $DbTypeSubclass as a comma separated list of names
862 my @dbtypes = split /\s*,\s*/, $DbTypeSubclass;
863 $dbh->trace_msg(" DbTypeSubclass($DbTypeSubclass)=@dbtypes (explicit)\n");
864 return @dbtypes;
865 }
866
867 # XXX will call $dbh->get_info(17) (=SQL_DBMS_NAME) in future?
868
869 my $driver = $dbh->{Driver}->{Name};
870 if ( $driver eq 'Proxy' ) {
871 # XXX Looking into the internals of DBD::Proxy is questionable!
872 ($driver) = $dbh->{proxy_client}->{application} =~ /^DBI:(.+?):/i
873 or die "Can't determine driver name from proxy";
874 }
875
876 my @dbtypes = (ucfirst($driver));
877 if ($driver eq 'ODBC' || $driver eq 'ADO') {
878 # XXX will move these out and make extensible later:
879 my $_dbtype_name_regexp = 'Oracle'; # eg 'Oracle|Foo|Bar'
880 my %_dbtype_name_map = (
881 'Microsoft SQL Server' => 'MSSQL',
882 'SQL Server' => 'Sybase',
883 'Adaptive Server Anywhere' => 'ASAny',
884 'ADABAS D' => 'AdabasD',
885 );
886
887 my $name;
888 $name = $dbh->func(17, 'GetInfo') # SQL_DBMS_NAME
889 if $driver eq 'ODBC';
890 $name = $dbh->{ado_conn}->Properties->Item('DBMS Name')->Value
891 if $driver eq 'ADO';
892 die "Can't determine driver name! ($DBI::errstr)\n"
893 unless $name;
894
895 my $dbtype;
896 if ($_dbtype_name_map{$name}) {
897 $dbtype = $_dbtype_name_map{$name};
898 }
899 else {
900 if ($name =~ /($_dbtype_name_regexp)/) {
901 $dbtype = lc($1);
902 }
903 else { # generic mangling for other names:
904 $dbtype = lc($name);
905 }
906 $dbtype =~ s/\b(\w)/\U$1/g;
907 $dbtype =~ s/\W+/_/g;
908 }
909 # add ODBC 'behind' ADO
910 push @dbtypes, 'ODBC' if $driver eq 'ADO';
911 # add discovered dbtype in front of ADO/ODBC
912 unshift @dbtypes, $dbtype;
913 }
914 @dbtypes = &$DbTypeSubclass($dbh, \@dbtypes)
915 if (ref $DbTypeSubclass eq 'CODE');
916 $dbh->trace_msg(" DbTypeSubclass($DbTypeSubclass)=@dbtypes\n");
917 return @dbtypes;
918}
919
920
# spent 30.0ms (25.2+4.80) within DBI::_load_class which was called # once (25.2ms+4.80ms) by DBI::__ANON__[/project/perl/lib/DBI.pm:692] at line 655
sub _load_class {
921823.5ms my ($load_class, $missing_ok) = @_;
922 DBI->trace_msg(" _load_class($load_class, $missing_ok)\n", 2);
# spent 8µs making 1 call to DBD::_::common::trace_msg
92331.06ms198µs no strict 'refs';
# spent 98µs making 1 call to strict::unimport
924 return 1 if @{"$load_class\::ISA"}; # already loaded/exists
925 (my $module = $load_class) =~ s!::!/!g;
# spent 14µs making 1 call to DBI::CORE:subst
926 DBI->trace_msg(" _load_class require $module\n", 2);
# spent 6µs making 1 call to DBD::_::common::trace_msg
927 eval { require "$module.pm"; };
928 return 1 unless $@;
929 return 0 if $missing_ok && $@ =~ /^Can't locate \Q$module.pm\E/;
930 die $@;
931}
932
933
934sub init_rootclass { # deprecated
935 return 1;
936}
937
938
93917µs*internal = \&DBD::Switch::dr::driver;
940
941
942sub available_drivers {
943 my($quiet) = @_;
944 my(@drivers, $d, $f);
945 local(*DBI::DIR, $@);
946 my(%seen_dir, %seen_dbd);
947 my $haveFileSpec = eval { require File::Spec };
948 foreach $d (@INC){
949 chomp($d); # Perl 5 beta 3 bug in #!./perl -Ilib from Test::Harness
950 my $dbd_dir =
951 ($haveFileSpec ? File::Spec->catdir($d, 'DBD') : "$d/DBD");
952 next unless -d $dbd_dir;
953 next if $seen_dir{$d};
954 $seen_dir{$d} = 1;
955 # XXX we have a problem here with case insensitive file systems
956 # XXX since we can't tell what case must be used when loading.
957 opendir(DBI::DIR, $dbd_dir) || Carp::carp "opendir $dbd_dir: $!\n";
958 foreach $f (readdir(DBI::DIR)){
959 next unless $f =~ s/\.pm$//;
960 next if $f eq 'NullP';
961 if ($seen_dbd{$f}){
962 Carp::carp "DBD::$f in $d is hidden by DBD::$f in $seen_dbd{$f}\n"
963 unless $quiet;
964 } else {
965 push(@drivers, $f);
966 }
967 $seen_dbd{$f} = $d;
968 }
969 closedir(DBI::DIR);
970 }
971
972 # "return sort @drivers" will not DWIM in scalar context.
973 return wantarray ? sort @drivers : @drivers;
974}
975
976sub installed_versions {
977 my ($class, $quiet) = @_;
978 my %error;
979 my %version = ( DBI => $DBI::VERSION );
980 $version{"DBI::PurePerl"} = $DBI::PurePerl::VERSION
981 if $DBI::PurePerl;
982 for my $driver ($class->available_drivers($quiet)) {
983 next if $DBI::PurePerl && grep { -d "$_/auto/DBD/$driver" } @INC;
984 my $drh = eval {
985 local $SIG{__WARN__} = sub {};
986 $class->install_driver($driver);
987 };
988 ($error{"DBD::$driver"}=$@),next if $@;
98934.60ms199µs no strict 'refs';
# spent 99µs making 1 call to strict::unimport
990 my $vers = ${"DBD::$driver" . '::VERSION'};
991 $version{"DBD::$driver"} = $vers || '?';
992 }
993 if (wantarray) {
994 return map { m/^DBD::(\w+)/ ? ($1) : () } sort keys %version;
995 }
996 if (!defined wantarray) { # void context
997 require Config; # add more detail
998 $version{OS} = "$^O\t($Config::Config{osvers})";
999 $version{Perl} = "$]\t($Config::Config{archname})";
1000 $version{$_} = (($error{$_} =~ s/ \(\@INC.*//s),$error{$_})
1001 for keys %error;
1002 printf " %-16s: %s\n",$_,$version{$_}
1003 for reverse sort keys %version;
1004 }
1005 return \%version;
1006}
1007
1008
1009sub data_sources {
1010 my ($class, $driver, @other) = @_;
1011 my $drh = $class->install_driver($driver);
1012 my @ds = $drh->data_sources(@other);
1013 return @ds;
1014}
1015
1016
1017sub neat_list {
1018 my ($listref, $maxlen, $sep) = @_;
1019 $maxlen = 0 unless defined $maxlen; # 0 == use internal default
1020 $sep = ", " unless defined $sep;
1021 join($sep, map { neat($_,$maxlen) } @$listref);
1022}
1023
1024
1025sub dump_results { # also aliased as a method in DBD::_::st
1026 my ($sth, $maxlen, $lsep, $fsep, $fh) = @_;
1027 return 0 unless $sth;
1028 $maxlen ||= 35;
1029 $lsep ||= "\n";
1030 $fh ||= \*STDOUT;
1031 my $rows = 0;
1032 my $ref;
1033 while($ref = $sth->fetch) {
1034 print $fh $lsep if $rows++ and $lsep;
1035 my $str = neat_list($ref,$maxlen,$fsep);
1036 print $fh $str; # done on two lines to avoid 5.003 errors
1037 }
1038 print $fh "\n$rows rows".($DBI::err ? " ($DBI::err: $DBI::errstr)" : "")."\n";
1039 $rows;
1040}
1041
1042
1043sub data_diff {
1044 my ($a, $b, $logical) = @_;
1045
1046 my $diff = data_string_diff($a, $b);
1047 return "" if $logical and !$diff;
1048
1049 my $a_desc = data_string_desc($a);
1050 my $b_desc = data_string_desc($b);
1051 return "" if !$diff and $a_desc eq $b_desc;
1052
1053 $diff ||= "Strings contain the same sequence of characters"
1054 if length($a);
1055 $diff .= "\n" if $diff;
1056 return "a: $a_desc\nb: $b_desc\n$diff";
1057}
1058
1059
1060sub data_string_diff {
1061 # Compares 'logical' characters, not bytes, so a latin1 string and an
1062 # an equivalent unicode string will compare as equal even though their
1063 # byte encodings are different.
1064 my ($a, $b) = @_;
1065 unless (defined $a and defined $b) { # one undef
1066 return ""
1067 if !defined $a and !defined $b;
1068 return "String a is undef, string b has ".length($b)." characters"
1069 if !defined $a;
1070 return "String b is undef, string a has ".length($a)." characters"
1071 if !defined $b;
1072 }
1073
1074 require utf8;
1075 # hack to cater for perl 5.6
1076 *utf8::is_utf8 = sub { (DBI::neat(shift)=~/^"/) } unless defined &utf8::is_utf8;
1077
1078 my @a_chars = (utf8::is_utf8($a)) ? unpack("U*", $a) : unpack("C*", $a);
1079 my @b_chars = (utf8::is_utf8($b)) ? unpack("U*", $b) : unpack("C*", $b);
1080 my $i = 0;
1081 while (@a_chars && @b_chars) {
1082 ++$i, shift(@a_chars), shift(@b_chars), next
1083 if $a_chars[0] == $b_chars[0];# compare ordinal values
1084 my @desc = map {
1085 $_ > 255 ? # if wide character...
1086 sprintf("\\x{%04X}", $_) : # \x{...}
1087 chr($_) =~ /[[:cntrl:]]/ ? # else if control character ...
1088 sprintf("\\x%02X", $_) : # \x..
1089 chr($_) # else as themselves
1090 } ($a_chars[0], $b_chars[0]);
1091 # highlight probable double-encoding?
1092 foreach my $c ( @desc ) {
1093 next unless $c =~ m/\\x\{08(..)}/;
1094 $c .= "='" .chr(hex($1)) ."'"
1095 }
1096 return sprintf "Strings differ at index $i: a[$i]=$desc[0], b[$i]=$desc[1]";
1097 }
1098 return "String a truncated after $i characters" if @b_chars;
1099 return "String b truncated after $i characters" if @a_chars;
1100 return "";
1101}
1102
1103
1104sub data_string_desc { # describe a data string
1105 my ($a) = @_;
1106 require bytes;
1107 require utf8;
1108
1109 # hacks to cater for perl 5.6
1110 *utf8::is_utf8 = sub { (DBI::neat(shift)=~/^"/) } unless defined &utf8::is_utf8;
1111 *utf8::valid = sub { 1 } unless defined &utf8::valid;
1112
1113 # Give sufficient info to help diagnose at least these kinds of situations:
1114 # - valid UTF8 byte sequence but UTF8 flag not set
1115 # (might be ascii so also need to check for hibit to make it worthwhile)
1116 # - UTF8 flag set but invalid UTF8 byte sequence
1117 # could do better here, but this'll do for now
1118 my $utf8 = sprintf "UTF8 %s%s",
1119 utf8::is_utf8($a) ? "on" : "off",
1120 utf8::valid($a||'') ? "" : " but INVALID encoding";
1121 return "$utf8, undef" unless defined $a;
1122 my $is_ascii = $a =~ m/^[\000-\177]*$/;
1123 return sprintf "%s, %s, %d characters %d bytes",
1124 $utf8, $is_ascii ? "ASCII" : "non-ASCII",
1125 length($a), bytes::length($a);
1126}
1127
1128
1129sub connect_test_perf {
1130 my($class, $dsn,$dbuser,$dbpass, $attr) = @_;
1131 Carp::croak("connect_test_perf needs hash ref as fourth arg") unless ref $attr;
1132 # these are non standard attributes just for this special method
1133 my $loops ||= $attr->{dbi_loops} || 5;
1134 my $par ||= $attr->{dbi_par} || 1; # parallelism
1135 my $verb ||= $attr->{dbi_verb} || 1;
1136 print "$dsn: testing $loops sets of $par connections:\n";
1137 require Benchmark;
1138 require "FileHandle.pm"; # don't let toke.c create empty FileHandle package
1139 $| = 1;
1140 my $t0 = new Benchmark; # not currently used
1141 my $drh = $class->install_driver($dsn) or Carp::croak("Can't install $dsn driver\n");
1142 my $t1 = new Benchmark;
1143 my $loop;
1144 for $loop (1..$loops) {
1145 my @cons;
1146 print "Connecting... " if $verb;
1147 for (1..$par) {
1148 print "$_ ";
1149 push @cons, ($drh->connect($dsn,$dbuser,$dbpass)
1150 or Carp::croak("Can't connect # $_: $DBI::errstr\n"));
1151 }
1152 print "\nDisconnecting...\n" if $verb;
1153 for (@cons) {
1154 $_->disconnect or warn "bad disconnect $DBI::errstr"
1155 }
1156 }
1157 my $t2 = new Benchmark;
1158 my $td = Benchmark::timediff($t2, $t1);
1159 printf "Made %2d connections in %s\n", $loops*$par, Benchmark::timestr($td);
1160 print "\n";
1161 return $td;
1162}
1163
1164
1165# Help people doing DBI->errstr, might even document it one day
1166# XXX probably best moved to cheaper XS code
1167sub err { $DBI::err }
1168sub errstr { $DBI::errstr }
1169
1170
1171# --- Private Internal Function for Creating New DBI Handles
1172
1173
# spent 2.23ms (1.54+694µs) within DBI::_new_handle which was called 14 times, avg 160µs/call: # 12 times (1.28ms+557µs) by DBI::_new_sth at line 1266, avg 153µs/call # once (134µs+66µs) by DBI::_new_dbh at line 1256 # once (123µs+71µs) by DBI::_new_drh at line 1226
sub _new_handle {
11741281.96ms my ($class, $parent, $attr, $imp_data, $imp_class) = @_;
1175
1176 Carp::croak('Usage: DBI::_new_handle'
1177 .'($class_name, parent_handle, \%attr, $imp_data)'."\n"
1178 .'got: ('.join(", ",$class, $parent, $attr, $imp_data).")\n")
1179 unless (@_ == 5 and (!$parent or ref $parent)
1180 and ref $attr eq 'HASH'
1181 and $imp_class);
1182
1183 $attr->{ImplementorClass} = $imp_class
1184 or Carp::croak("_new_handle($class): 'ImplementorClass' attribute not given");
1185
1186 DBI->trace_msg(" New $class (for $imp_class, parent=$parent, id=".($imp_data||'').")\n")
1187 if $DBI::dbi_debug >= 3;
1188
1189 # This is how we create a DBI style Object:
1190 my (%hash, $i, $h);
1191186µs $i = tie %hash, $class, $attr; # ref to inner hash (for driver)
1192 $h = bless \%hash, $class; # ref to outer hash (for application)
1193 # The above tie and bless may migrate down into _setup_handle()...
1194 # Now add magic so DBI method dispatch works
1195 DBI::_setup_handle($h, $imp_class, $parent, $imp_data);
# spent 694µs making 14 calls to DBI::_setup_handle, avg 50µs/call
1196
1197 return $h unless wantarray;
1198 ($h, $i);
1199}
1200# XXX minimum constructors for the tie's (alias to XS version)
120114222µssub DBI::st::TIEHASH { bless $_[1] => $_[0] };
120215µs*DBI::dr::TIEHASH = \&DBI::st::TIEHASH;
120314µs*DBI::db::TIEHASH = \&DBI::st::TIEHASH;
1204
1205
1206# These three special constructors are called by the drivers
1207# The way they are called is likely to change.
1208
120914µsmy $profile;
1210
1211
# spent 271µs (77+194) within DBI::_new_drh which was called # once (77µs+194µs) by DBD::Pg::driver at line 113 of DBD/Pg.pm
sub _new_drh { # called by DBD::<drivername>::driver()
12126108µs my ($class, $initial_attr, $imp_data) = @_;
1213 # Provide default storage for State,Err and Errstr.
1214 # Note that these are shared by all child handles by default! XXX
1215 # State must be undef to get automatic faking in DBI::var::FETCH
1216 my ($h_state_store, $h_err_store, $h_errstr_store) = (undef, 0, '');
1217 my $attr = {
1218 # these attributes get copied down to child handles by default
1219 'State' => \$h_state_store, # Holder for DBI::state
1220 'Err' => \$h_err_store, # Holder for DBI::err
1221 'Errstr' => \$h_errstr_store, # Holder for DBI::errstr
1222 'TraceLevel' => 0,
1223 FetchHashKeyName=> 'NAME',
1224 %$initial_attr,
1225 };
1226 my ($h, $i) = _new_handle('DBI::dr', '', $attr, $imp_data, $class);
# spent 194µs making 1 call to DBI::_new_handle
1227
1228 # XXX DBI_PROFILE unless DBI::PurePerl because for some reason
1229 # it kills the t/zz_*_pp.t tests (they silently exit early)
1230 if ($ENV{DBI_PROFILE} && !$DBI::PurePerl) {
1231 # The profile object created here when the first driver is loaded
1232 # is shared by all drivers so we end up with just one set of profile
1233 # data and thus the 'total time in DBI' is really the true total.
1234 if (!$profile) { # first time
1235 $h->{Profile} = $ENV{DBI_PROFILE};
1236 $profile = $h->{Profile};
1237 }
1238 else {
1239 $h->{Profile} = $profile;
1240 }
1241 }
1242 return $h unless wantarray;
1243 ($h, $i);
1244}
1245
1246
# spent 278µs (78+200) within DBI::_new_dbh which was called # once (78µs+200µs) by DBI::dr::connect at line 216 of DBD/Pg.pm
sub _new_dbh { # called by DBD::<drivername>::dr::connect()
1247976µs my ($drh, $attr, $imp_data) = @_;
1248 my $imp_class = $drh->{ImplementorClass}
1249 or Carp::croak("DBI _new_dbh: $drh has no ImplementorClass");
1250 substr($imp_class,-4,4) = '::db';
1251 my $app_class = ref $drh;
1252 substr($app_class,-4,4) = '::db';
1253 $attr->{Err} ||= \my $err;
1254 $attr->{Errstr} ||= \my $errstr;
1255 $attr->{State} ||= \my $state;
1256 _new_handle($app_class, $drh, $attr, $imp_data, $imp_class);
# spent 200µs making 1 call to DBI::_new_handle
1257}
1258
1259
# spent 2.53ms (688µs+1.84) within DBI::_new_sth which was called 12 times, avg 211µs/call: # 12 times (688µs+1.84ms) by DBI::db::prepare at line 263 of DBD/Pg.pm, avg 211µs/call
sub _new_sth { # called by DBD::<drivername>::db::prepare)
126072672µs my ($dbh, $attr, $imp_data) = @_;
1261 my $imp_class = $dbh->{ImplementorClass}
1262 or Carp::croak("DBI _new_sth: $dbh has no ImplementorClass");
1263 substr($imp_class,-4,4) = '::st';
1264 my $app_class = ref $dbh;
1265 substr($app_class,-4,4) = '::st';
1266 _new_handle($app_class, $dbh, $attr, $imp_data, $imp_class);
# spent 1.84ms making 12 calls to DBI::_new_handle, avg 153µs/call
1267}
1268
1269
1270# end of DBI package
1271
1272
1273
1274# --------------------------------------------------------------------
1275# === The internal DBI Switch pseudo 'driver' class ===
1276
127718µs{ package # hide from PAUSE
1278 DBD::Switch::dr;
1279119µs1267µs DBI->setup_driver('DBD::Switch'); # sets up @ISA
# spent 267µs making 1 call to DBI::setup_driver
1280
128115µs $DBD::Switch::dr::imp_data_size = 0;
128214µs $DBD::Switch::dr::imp_data_size = 0; # avoid typo warning
128314µs my $drh;
1284
1285 sub driver {
1286 return $drh if $drh; # a package global
1287
1288 my $inner;
1289 ($drh, $inner) = DBI::_new_drh('DBD::Switch::dr', {
1290 'Name' => 'Switch',
1291 'Version' => $DBI::VERSION,
1292 'Attribution' => "DBI $DBI::VERSION by Tim Bunce",
1293 });
1294 Carp::croak("DBD::Switch init failed!") unless ($drh && $inner);
1295 return $drh;
1296 }
1297 sub CLONE {
1298 undef $drh;
1299 }
1300
1301 sub FETCH {
1302 my($drh, $key) = @_;
1303 return DBI->trace if $key eq 'DebugDispatch';
1304 return undef if $key eq 'DebugLog'; # not worth fetching, sorry
1305 return $drh->DBD::_::dr::FETCH($key);
1306 undef;
1307 }
1308 sub STORE {
1309 my($drh, $key, $value) = @_;
1310 if ($key eq 'DebugDispatch') {
1311 DBI->trace($value);
1312 } elsif ($key eq 'DebugLog') {
1313 DBI->trace(-1, $value);
1314 } else {
1315 $drh->DBD::_::dr::STORE($key, $value);
1316 }
1317 }
1318}
1319
1320
1321# --------------------------------------------------------------------
1322# === OPTIONAL MINIMAL BASE CLASSES FOR DBI SUBCLASSES ===
1323
1324# We only define default methods for harmless functions.
1325# We don't, for example, define a DBD::_::st::prepare()
1326
132718µs{ package # hide from PAUSE
1328 DBD::_::common; # ====== Common base class methods ======
132931.22ms124µs use strict;
# spent 24µs making 1 call to strict::import
1330
1331 # methods common to all handle types:
1332
1333 sub _not_impl {
1334 my ($h, $method) = @_;
1335 $h->trace_msg("Driver does not implement the $method method.\n");
1336 return; # empty list / undef
1337 }
1338
1339 # generic TIEHASH default methods:
1340 sub FIRSTKEY { }
1341 sub NEXTKEY { }
1342 sub EXISTS { defined($_[0]->FETCH($_[1])) } # XXX undef?
1343 sub CLEAR { Carp::carp "Can't CLEAR $_[0] (DBI)" }
1344
134517µs *dump_handle = \&DBI::dump_handle;
1346
1347
# spent 4.99ms (3.05+1.94) within DBD::_::common::install_method which was called 31 times, avg 161µs/call: # once (109µs+934µs) by DBD::Pg::driver at line 151 of DBD/Pg.pm # once (132µs+43µs) by DBD::Pg::driver at line 123 of DBD/Pg.pm # once (109µs+39µs) by DBD::Pg::driver at line 152 of DBD/Pg.pm # once (114µs+33µs) by DBD::Pg::driver at line 124 of DBD/Pg.pm # once (113µs+34µs) by DBD::Pg::driver at line 134 of DBD/Pg.pm # once (111µs+33µs) by DBD::Pg::driver at line 155 of DBD/Pg.pm # once (113µs+31µs) by DBD::Pg::driver at line 144 of DBD/Pg.pm # once (95µs+45µs) by DBD::Pg::driver at line 149 of DBD/Pg.pm # once (106µs+33µs) by DBD::Pg::driver at line 150 of DBD/Pg.pm # once (99µs+37µs) by DBD::Pg::driver at line 147 of DBD/Pg.pm # once (101µs+33µs) by DBD::Pg::driver at line 139 of DBD/Pg.pm # once (91µs+41µs) by DBD::Pg::driver at line 154 of DBD/Pg.pm # once (94µs+36µs) by DBD::Pg::driver at line 136 of DBD/Pg.pm # once (98µs+32µs) by DBD::Pg::driver at line 126 of DBD/Pg.pm # once (94µs+33µs) by DBD::Pg::driver at line 146 of DBD/Pg.pm # once (92µs+34µs) by DBD::Pg::driver at line 127 of DBD/Pg.pm # once (92µs+34µs) by DBD::Pg::driver at line 125 of DBD/Pg.pm # once (94µs+31µs) by DBD::Pg::driver at line 130 of DBD/Pg.pm # once (93µs+32µs) by DBD::Pg::driver at line 142 of DBD/Pg.pm # once (93µs+32µs) by DBD::Pg::driver at line 133 of DBD/Pg.pm # once (95µs+30µs) by DBD::Pg::driver at line 132 of DBD/Pg.pm # once (93µs+31µs) by DBD::Pg::driver at line 128 of DBD/Pg.pm # once (92µs+32µs) by DBD::Pg::driver at line 138 of DBD/Pg.pm # once (90µs+34µs) by DBD::Pg::driver at line 148 of DBD/Pg.pm # once (94µs+29µs) by DBD::Pg::driver at line 129 of DBD/Pg.pm # once (92µs+31µs) by DBD::Pg::driver at line 153 of DBD/Pg.pm # once (92µs+31µs) by DBD::Pg::driver at line 137 of DBD/Pg.pm # once (91µs+32µs) by DBD::Pg::driver at line 140 of DBD/Pg.pm # once (91µs+31µs) by DBD::Pg::driver at line 143 of DBD/Pg.pm # once (90µs+30µs) by DBD::Pg::driver at line 131 of DBD/Pg.pm # once (88µs+29µs) by DBD::Pg::driver at line 135 of DBD/Pg.pm
sub install_method {
1348 # special class method called directly by apps and/or drivers
1349 # to install new methods into the DBI dispatcher
1350 # DBD::Foo::db->install_method("foo_mumble", { usage => [...], options => '...' });
13513105.10ms my ($class, $method, $attr) = @_;
1352 Carp::croak("Class '$class' must begin with DBD:: and end with ::db or ::st")
# spent 275µs making 31 calls to DBD::_::common::CORE:match, avg 9µs/call
1353 unless $class =~ /^DBD::(\w+)::(dr|db|st)$/;
1354 my ($driver, $subtype) = ($1, $2);
1355 Carp::croak("invalid method name '$method'")
# spent 240µs making 31 calls to DBD::_::common::CORE:match, avg 8µs/call
1356 unless $method =~ m/^([a-z]+_)\w+$/;
1357 my $prefix = $1;
1358 my $reg_info = $dbd_prefix_registry->{$prefix};
1359 Carp::carp("method name prefix '$prefix' is not associated with a registered driver") unless $reg_info;
1360 my %attr = %{$attr||{}}; # copy so we can edit
1361 # XXX reformat $attr as needed for _install_method
1362 my ($caller_pkg, $filename, $line) = caller;
1363 DBI->_install_method("DBI::${subtype}::$method", "$filename at line $line", \%attr);
# spent 1.43ms making 31 calls to DBI::_install_method, avg 46µs/call
1364 }
1365
1366 sub parse_trace_flags {
1367 my ($h, $spec) = @_;
1368 my $level = 0;
1369 my $flags = 0;
1370 my @unknown;
1371 for my $word (split /\s*[|&,]\s*/, $spec) {
1372 if (DBI::looks_like_number($word) && $word <= 0xF && $word >= 0) {
1373 $level = $word;
1374 } elsif ($word eq 'ALL') {
1375 $flags = 0x7FFFFFFF; # XXX last bit causes negative headaches
1376 last;
1377 } elsif (my $flag = $h->parse_trace_flag($word)) {
1378 $flags |= $flag;
1379 }
1380 else {
1381 push @unknown, $word;
1382 }
1383 }
1384 if (@unknown && (ref $h ? $h->FETCH('Warn') : 1)) {
1385 Carp::carp("$h->parse_trace_flags($spec) ignored unknown trace flags: ".
1386 join(" ", map { DBI::neat($_) } @unknown));
1387 }
1388 $flags |= $level;
1389 return $flags;
1390 }
1391
1392 sub parse_trace_flag {
1393 my ($h, $name) = @_;
1394 # 0xddDDDDrL (driver, DBI, reserved, Level)
1395 return 0x00000100 if $name eq 'SQL';
1396 return;
1397 }
1398
1399 sub private_attribute_info {
1400 return undef;
1401 }
1402
1403}
1404
1405
140618µs{ package # hide from PAUSE
1407 DBD::_::dr; # ====== DRIVER ======
140817µs @DBD::_::dr::ISA = qw(DBD::_::common);
14093734µs124µs use strict;
# spent 24µs making 1 call to strict::import
1410
1411 sub default_user {
1412 my ($drh, $user, $pass, $attr) = @_;
1413 $user = $ENV{DBI_USER} unless defined $user;
1414 $pass = $ENV{DBI_PASS} unless defined $pass;
1415 return ($user, $pass);
1416 }
1417
1418 sub connect { # normally overridden, but a handy default
1419 my ($drh, $dsn, $user, $auth) = @_;
1420 my ($this) = DBI::_new_dbh($drh, {
1421 'Name' => $dsn,
1422 });
1423 # XXX debatable as there's no "server side" here
1424 # (and now many uses would trigger warnings on DESTROY)
1425 # $this->STORE(Active => 1);
1426 # so drivers should set it in their own connect
1427 $this;
1428 }
1429
1430
1431 sub connect_cached {
143215293µs my $drh = shift;
1433 my ($dsn, $user, $auth, $attr)= @_;
1434
1435 # Needs support at dbh level to clear cache before complaining about
1436 # active children. The XS template code does this. Drivers not using
1437 # the template must handle clearing the cache themselves.
1438 my $cache = $drh->FETCH('CachedKids');
# spent 26µs making 1 call to DBI::common::FETCH
1439 $drh->STORE('CachedKids', $cache = {}) unless $cache;
# spent 23µs making 1 call to DBI::common::STORE
1440
1441 my @attr_keys = $attr ? sort keys %$attr : ();
# spent 29µs making 1 call to DBD::_::dr::CORE:sort
1442 my $key = do { local $^W; # silence undef warnings
1443 join "~~", $dsn, $user||'', $auth||'', $attr ? (@attr_keys,@{$attr}{@attr_keys}) : ()
1444 };
1445 my $dbh = $cache->{$key};
1446 my $cb = $attr->{Callbacks}; # take care not to autovivify
1447 if ($dbh && $dbh->FETCH('Active') && eval { $dbh->ping }) {
1448 # If the caller has provided a callback then call it
1449 if ($cb and $cb = $cb->{"connect_cached.reused"}) {
1450 local $_ = "connect_cached.reused";
1451 $cb->($dbh, $dsn, $user, $auth, $attr);
1452 }
1453 return $dbh;
1454 }
1455
1456 # If the caller has provided a callback then call it
1457 if ($cb and $cb = $cb->{"connect_cached.new"}) {
1458 local $_ = "connect_cached.new";
1459 $cb->($dbh, $dsn, $user, $auth, $attr);
1460 }
1461
1462125µs174.6ms $dbh = $drh->connect(@_);
# spent 74.6ms making 1 call to DBI::dr::connect
1463 $cache->{$key} = $dbh; # replace prev entry, even if connect failed
1464 return $dbh;
1465 }
1466
1467}
1468
1469
147019µs{ package # hide from PAUSE
1471 DBD::_::db; # ====== DATABASE ======
147216µs @DBD::_::db::ISA = qw(DBD::_::common);
147333.68ms124µs use strict;
# spent 24µs making 1 call to strict::import
1474
1475 sub clone {
1476 my ($old_dbh, $attr) = @_;
1477 my $closure = $old_dbh->{dbi_connect_closure} or return;
1478 unless ($attr) {
1479 # copy attributes visible in the attribute cache
1480 keys %$old_dbh; # reset iterator
1481 while ( my ($k, $v) = each %$old_dbh ) {
1482 # ignore non-code refs, i.e., caches, handles, Err etc
1483 next if ref $v && ref $v ne 'CODE'; # HandleError etc
1484 $attr->{$k} = $v;
1485 }
1486 # explicitly set attributes which are unlikely to be in the
1487 # attribute cache, i.e., boolean's and some others
1488 $attr->{$_} = $old_dbh->FETCH($_) for (qw(
1489 AutoCommit ChopBlanks InactiveDestroy
1490 LongTruncOk PrintError PrintWarn Profile RaiseError
1491 ShowErrorStatement TaintIn TaintOut
1492 ));
1493 }
1494 # use Data::Dumper; warn Dumper([$old_dbh, $attr]);
1495 my $new_dbh = &$closure($old_dbh, $attr);
1496 unless ($new_dbh) {
1497 # need to copy err/errstr from driver back into $old_dbh
1498 my $drh = $old_dbh->{Driver};
1499 return $old_dbh->set_err($drh->err, $drh->errstr, $drh->state);
1500 }
1501 return $new_dbh;
1502 }
1503
1504 sub quote_identifier {
1505 my ($dbh, @id) = @_;
1506 my $attr = (@id > 3 && ref($id[-1])) ? pop @id : undef;
1507
1508 my $info = $dbh->{dbi_quote_identifier_cache} ||= [
1509 $dbh->get_info(29) || '"', # SQL_IDENTIFIER_QUOTE_CHAR
1510 $dbh->get_info(41) || '.', # SQL_CATALOG_NAME_SEPARATOR
1511 $dbh->get_info(114) || 1, # SQL_CATALOG_LOCATION
1512 ];
1513
1514 my $quote = $info->[0];
1515 foreach (@id) { # quote the elements
1516 next unless defined;
1517 s/$quote/$quote$quote/g; # escape embedded quotes
1518 $_ = qq{$quote$_$quote};
1519 }
1520
1521 # strip out catalog if present for special handling
1522 my $catalog = (@id >= 3) ? shift @id : undef;
1523
1524 # join the dots, ignoring any null/undef elements (ie schema)
1525 my $quoted_id = join '.', grep { defined } @id;
1526
1527 if ($catalog) { # add catalog correctly
1528 $quoted_id = ($info->[2] == 2) # SQL_CL_END
1529 ? $quoted_id . $info->[1] . $catalog
1530 : $catalog . $info->[1] . $quoted_id;
1531 }
1532 return $quoted_id;
1533 }
1534
1535 sub quote {
1536 my ($dbh, $str, $data_type) = @_;
1537
1538 return "NULL" unless defined $str;
1539 unless ($data_type) {
1540 $str =~ s/'/''/g; # ISO SQL2
1541 return "'$str'";
1542 }
1543
1544 my $dbi_literal_quote_cache = $dbh->{'dbi_literal_quote_cache'} ||= [ {} , {} ];
1545 my ($prefixes, $suffixes) = @$dbi_literal_quote_cache;
1546
1547 my $lp = $prefixes->{$data_type};
1548 my $ls = $suffixes->{$data_type};
1549
1550 if ( ! defined $lp || ! defined $ls ) {
1551 my $ti = $dbh->type_info($data_type);
1552 $lp = $prefixes->{$data_type} = $ti ? $ti->{LITERAL_PREFIX} || "" : "'";
1553 $ls = $suffixes->{$data_type} = $ti ? $ti->{LITERAL_SUFFIX} || "" : "'";
1554 }
1555 return $str unless $lp || $ls; # no quoting required
1556
1557 # XXX don't know what the standard says about escaping
1558 # in the 'general case' (where $lp != "'").
1559 # So we just do this and hope:
1560 $str =~ s/$lp/$lp$lp/g
1561 if $lp && $lp eq $ls && ($lp eq "'" || $lp eq '"');
1562 return "$lp$str$ls";
1563 }
1564
1565 sub rows { -1 } # here so $DBI::rows 'works' after using $dbh
1566
1567 sub do {
1568 my($dbh, $statement, $attr, @params) = @_;
1569 my $sth = $dbh->prepare($statement, $attr) or return undef;
1570 $sth->execute(@params) or return undef;
1571 my $rows = $sth->rows;
1572 ($rows == 0) ? "0E0" : $rows;
1573 }
1574
1575 sub _do_selectrow {
1576 my ($method, $dbh, $stmt, $attr, @bind) = @_;
1577 my $sth = ((ref $stmt) ? $stmt : $dbh->prepare($stmt, $attr))
1578 or return;
1579 $sth->execute(@bind)
1580 or return;
1581 my $row = $sth->$method()
1582 and $sth->finish;
1583 return $row;
1584 }
1585
1586 sub selectrow_hashref { return _do_selectrow('fetchrow_hashref', @_); }
1587
1588 # XXX selectrow_array/ref also have C implementations in Driver.xst
1589 sub selectrow_arrayref { return _do_selectrow('fetchrow_arrayref', @_); }
1590 sub selectrow_array {
1591 my $row = _do_selectrow('fetchrow_arrayref', @_) or return;
1592 return $row->[0] unless wantarray;
1593 return @$row;
1594 }
1595
1596 # XXX selectall_arrayref also has C implementation in Driver.xst
1597 # which fallsback to this if a slice is given
1598 sub selectall_arrayref {
1599 my ($dbh, $stmt, $attr, @bind) = @_;
1600 my $sth = (ref $stmt) ? $stmt : $dbh->prepare($stmt, $attr)
1601 or return;
1602 $sth->execute(@bind) || return;
1603 my $slice = $attr->{Slice}; # typically undef, else hash or array ref
1604 if (!$slice and $slice=$attr->{Columns}) {
1605 if (ref $slice eq 'ARRAY') { # map col idx to perl array idx
1606 $slice = [ @{$attr->{Columns}} ]; # take a copy
1607 for (@$slice) { $_-- }
1608 }
1609 }
1610 my $rows = $sth->fetchall_arrayref($slice, my $MaxRows = $attr->{MaxRows});
1611 $sth->finish if defined $MaxRows;
1612 return $rows;
1613 }
1614
1615 sub selectall_hashref {
1616 my ($dbh, $stmt, $key_field, $attr, @bind) = @_;
1617 my $sth = (ref $stmt) ? $stmt : $dbh->prepare($stmt, $attr);
1618 return unless $sth;
1619 $sth->execute(@bind) || return;
1620 return $sth->fetchall_hashref($key_field);
1621 }
1622
1623 sub selectcol_arrayref {
1624 my ($dbh, $stmt, $attr, @bind) = @_;
1625 my $sth = (ref $stmt) ? $stmt : $dbh->prepare($stmt, $attr);
1626 return unless $sth;
1627 $sth->execute(@bind) || return;
1628 my @columns = ($attr->{Columns}) ? @{$attr->{Columns}} : (1);
1629 my @values = (undef) x @columns;
1630 my $idx = 0;
1631 for (@columns) {
1632 $sth->bind_col($_, \$values[$idx++]) || return;
1633 }
1634 my @col;
1635 if (my $max = $attr->{MaxRows}) {
1636 push @col, @values while @col<$max && $sth->fetch;
1637 }
1638 else {
1639 push @col, @values while $sth->fetch;
1640 }
1641 return \@col;
1642 }
1643
1644 sub prepare_cached {
164520239µs my ($dbh, $statement, $attr, $if_active) = @_;
1646 # Needs support at dbh level to clear cache before complaining about
1647 # active children. The XS template code does this. Drivers not using
1648 # the template must handle clearing the cache themselves.
1649 my $cache = $dbh->FETCH('CachedKids');
# spent 30µs making 2 calls to DBI::common::FETCH, avg 15µs/call
1650 $dbh->STORE('CachedKids', $cache = {}) unless $cache;
# spent 14µs making 1 call to DBI::common::STORE
1651 my @attr_keys = ($attr) ? sort keys %$attr : ();
1652 my $key = ($attr) ? join("~~", $statement, @attr_keys, @{$attr}{@attr_keys}) : $statement;
1653 my $sth = $cache->{$key};
1654 if ($sth) {
1655 return $sth unless $sth->FETCH('Active');
1656 Carp::carp("prepare_cached($statement) statement handle $sth still Active")
1657 unless ($if_active ||= 0);
1658 $sth->finish if $if_active <= 1;
1659 return $sth if $if_active <= 2;
1660 }
1661139µs2651µs $sth = $dbh->prepare($statement, $attr);
# spent 651µs making 2 calls to DBI::db::prepare, avg 326µs/call
1662 $cache->{$key} = $sth if $sth;
1663 return $sth;
1664 }
1665
1666 sub ping {
1667 my $dbh = shift;
1668 $dbh->_not_impl('ping');
1669 # "0 but true" is a special kind of true 0 that is used here so
1670 # applications can check if the ping was a real ping or not
1671 ($dbh->FETCH('Active')) ? "0 but true" : 0;
1672 }
1673
1674 sub begin_work {
1675 my $dbh = shift;
1676 return $dbh->set_err(1, "Already in a transaction")
1677 unless $dbh->FETCH('AutoCommit');
1678 $dbh->STORE('AutoCommit', 0); # will croak if driver doesn't support it
1679 $dbh->STORE('BegunWork', 1); # trigger post commit/rollback action
1680 return 1;
1681 }
1682
1683 sub primary_key {
1684 my ($dbh, @args) = @_;
1685 my $sth = $dbh->primary_key_info(@args) or return;
1686 my ($row, @col);
1687 push @col, $row->[3] while ($row = $sth->fetch);
1688 Carp::croak("primary_key method not called in list context")
1689 unless wantarray; # leave us some elbow room
1690 return @col;
1691 }
1692
1693 sub tables {
1694 my ($dbh, @args) = @_;
1695 my $sth = $dbh->table_info(@args[0,1,2,3,4]) or return;
1696 my $tables = $sth->fetchall_arrayref or return;
1697 my @tables;
1698 if ($dbh->get_info(29)) { # SQL_IDENTIFIER_QUOTE_CHAR
1699 @tables = map { $dbh->quote_identifier( @{$_}[0,1,2] ) } @$tables;
1700 }
1701 else { # temporary old style hack (yeach)
1702 @tables = map {
1703 my $name = $_->[2];
1704 if ($_->[1]) {
1705 my $schema = $_->[1];
1706 # a sad hack (mostly for Informix I recall)
1707 my $quote = ($schema eq uc($schema)) ? '' : '"';
1708 $name = "$quote$schema$quote.$name"
1709 }
1710 $name;
1711 } @$tables;
1712 }
1713 return @tables;
1714 }
1715
1716 sub type_info { # this should be sufficient for all drivers
1717 my ($dbh, $data_type) = @_;
1718 my $idx_hash;
1719 my $tia = $dbh->{dbi_type_info_row_cache};
1720 if ($tia) {
1721 $idx_hash = $dbh->{dbi_type_info_idx_cache};
1722 }
1723 else {
1724 my $temp = $dbh->type_info_all;
1725 return unless $temp && @$temp;
1726 # we cache here because type_info_all may be expensive to call
1727 # (and we take a copy so the following shift can't corrupt
1728 # the data that may be returned by future calls to type_info_all)
1729 $tia = $dbh->{dbi_type_info_row_cache} = [ @$temp ];
1730 $idx_hash = $dbh->{dbi_type_info_idx_cache} = shift @$tia;
1731 }
1732
1733 my $dt_idx = $idx_hash->{DATA_TYPE} || $idx_hash->{data_type};
1734 Carp::croak("type_info_all returned non-standard DATA_TYPE index value ($dt_idx != 1)")
1735 if $dt_idx && $dt_idx != 1;
1736
1737 # --- simple DATA_TYPE match filter
1738 my @ti;
1739 my @data_type_list = (ref $data_type) ? @$data_type : ($data_type);
1740 foreach $data_type (@data_type_list) {
1741 if (defined($data_type) && $data_type != DBI::SQL_ALL_TYPES()) {
1742 push @ti, grep { $_->[$dt_idx] == $data_type } @$tia;
1743 }
1744 else { # SQL_ALL_TYPES
1745 push @ti, @$tia;
1746 }
1747 last if @ti; # found at least one match
1748 }
1749
1750 # --- format results into list of hash refs
1751 my $idx_fields = keys %$idx_hash;
1752 my @idx_names = map { uc($_) } keys %$idx_hash;
1753 my @idx_values = values %$idx_hash;
1754 Carp::croak "type_info_all result has $idx_fields keys but ".(@{$ti[0]})." fields"
1755 if @ti && @{$ti[0]} != $idx_fields;
1756 my @out = map {
1757 my %h; @h{@idx_names} = @{$_}[ @idx_values ]; \%h;
1758 } @ti;
1759 return $out[0] unless wantarray;
1760 return @out;
1761 }
1762
1763 sub data_sources {
1764 my ($dbh, @other) = @_;
1765 my $drh = $dbh->{Driver}; # XXX proxy issues?
1766 return $drh->data_sources(@other);
1767 }
1768
1769}
1770
1771
177219µs{ package # hide from PAUSE
1773 DBD::_::st; # ====== STATEMENT ======
177416µs @DBD::_::st::ISA = qw(DBD::_::common);
177533.28ms125µs use strict;
# spent 25µs making 1 call to strict::import
1776
1777 sub bind_param { Carp::croak("Can't bind_param, not implement by driver") }
1778
1779#
1780# ********************************************************
1781#
1782# BEGIN ARRAY BINDING
1783#
1784# Array binding support for drivers which don't support
1785# array binding, but have sufficient interfaces to fake it.
1786# NOTE: mixing scalars and arrayrefs requires using bind_param_array
1787# for *all* params...unless we modify bind_param for the default
1788# case...
1789#
1790# 2002-Apr-10 D. Arnold
1791
1792 sub bind_param_array {
1793 my $sth = shift;
1794 my ($p_id, $value_array, $attr) = @_;
1795
1796 return $sth->set_err(1, "Value for parameter $p_id must be a scalar or an arrayref, not a ".ref($value_array))
1797 if defined $value_array and ref $value_array and ref $value_array ne 'ARRAY';
1798
1799 return $sth->set_err(1, "Can't use named placeholder '$p_id' for non-driver supported bind_param_array")
1800 unless DBI::looks_like_number($p_id); # because we rely on execute(@ary) here
1801
1802 return $sth->set_err(1, "Placeholder '$p_id' is out of range")
1803 if $p_id <= 0; # can't easily/reliably test for too big
1804
1805 # get/create arrayref to hold params
1806 my $hash_of_arrays = $sth->{ParamArrays} ||= { };
1807
1808 # If the bind has attribs then we rely on the driver conforming to
1809 # the DBI spec in that a single bind_param() call with those attribs
1810 # makes them 'sticky' and apply to all later execute(@values) calls.
1811 # Since we only call bind_param() if we're given attribs then
1812 # applications using drivers that don't support bind_param can still
1813 # use bind_param_array() so long as they don't pass any attribs.
1814
1815 $$hash_of_arrays{$p_id} = $value_array;
1816 return $sth->bind_param($p_id, undef, $attr)
1817 if $attr;
1818 1;
1819 }
1820
1821 sub bind_param_inout_array {
1822 my $sth = shift;
1823 # XXX not supported so we just call bind_param_array instead
1824 # and then return an error
1825 my ($p_num, $value_array, $attr) = @_;
1826 $sth->bind_param_array($p_num, $value_array, $attr);
1827 return $sth->set_err(1, "bind_param_inout_array not supported");
1828 }
1829
1830 sub bind_columns {
18319130µs my $sth = shift;
1832 my $fields = $sth->FETCH('NUM_OF_FIELDS') || 0;
# spent 15µs making 1 call to DBI::common::FETCH
1833 if ($fields <= 0 && !$sth->{Active}) {
1834 return $sth->set_err(1, "Statement has no result columns to bind"
1835 ." (perhaps you need to successfully call execute first)");
1836 }
1837 # Backwards compatibility for old-style call with attribute hash
1838 # ref as first arg. Skip arg if undef or a hash ref.
1839 my $attr;
1840 $attr = shift if !defined $_[0] or ref($_[0]) eq 'HASH';
1841
1842 my $idx = 0;
1843 $sth->bind_col(++$idx, shift, $attr) or return
# spent 14µs making 1 call to DBI::st::bind_col
1844 while (@_ and $idx < $fields);
1845
1846 return $sth->set_err(1, "bind_columns called with ".($idx+@_)." values but $fields are needed")
1847 if @_ or $idx != $fields;
1848
1849 return 1;
1850 }
1851
1852 sub execute_array {
1853 my $sth = shift;
1854 my ($attr, @array_of_arrays) = @_;
1855 my $NUM_OF_PARAMS = $sth->FETCH('NUM_OF_PARAMS'); # may be undef at this point
1856
1857 # get tuple status array or hash attribute
1858 my $tuple_sts = $attr->{ArrayTupleStatus};
1859 return $sth->set_err(1, "ArrayTupleStatus attribute must be an arrayref")
1860 if $tuple_sts and ref $tuple_sts ne 'ARRAY';
1861
1862 # bind all supplied arrays
1863 if (@array_of_arrays) {
1864 $sth->{ParamArrays} = { }; # clear out old params
1865 return $sth->set_err(1,
1866 @array_of_arrays." bind values supplied but $NUM_OF_PARAMS expected")
1867 if defined ($NUM_OF_PARAMS) && @array_of_arrays != $NUM_OF_PARAMS;
1868 $sth->bind_param_array($_, $array_of_arrays[$_-1]) or return
1869 foreach (1..@array_of_arrays);
1870 }
1871
1872 my $fetch_tuple_sub;
1873
1874 if ($fetch_tuple_sub = $attr->{ArrayTupleFetch}) { # fetch on demand
1875
1876 return $sth->set_err(1,
1877 "Can't use both ArrayTupleFetch and explicit bind values")
1878 if @array_of_arrays; # previous bind_param_array calls will simply be ignored
1879
1880 if (UNIVERSAL::isa($fetch_tuple_sub,'DBI::st')) {
1881 my $fetch_sth = $fetch_tuple_sub;
1882 return $sth->set_err(1,
1883 "ArrayTupleFetch sth is not Active, need to execute() it first")
1884 unless $fetch_sth->{Active};
1885 # check column count match to give more friendly message
1886 my $NUM_OF_FIELDS = $fetch_sth->{NUM_OF_FIELDS};
1887 return $sth->set_err(1,
1888 "$NUM_OF_FIELDS columns from ArrayTupleFetch sth but $NUM_OF_PARAMS expected")
1889 if defined($NUM_OF_FIELDS) && defined($NUM_OF_PARAMS)
1890 && $NUM_OF_FIELDS != $NUM_OF_PARAMS;
1891 $fetch_tuple_sub = sub { $fetch_sth->fetchrow_arrayref };
1892 }
1893 elsif (!UNIVERSAL::isa($fetch_tuple_sub,'CODE')) {
1894 return $sth->set_err(1, "ArrayTupleFetch '$fetch_tuple_sub' is not a code ref or statement handle");
1895 }
1896
1897 }
1898 else {
1899 my $NUM_OF_PARAMS_given = keys %{ $sth->{ParamArrays} || {} };
1900 return $sth->set_err(1,
1901 "$NUM_OF_PARAMS_given bind values supplied but $NUM_OF_PARAMS expected")
1902 if defined($NUM_OF_PARAMS) && $NUM_OF_PARAMS != $NUM_OF_PARAMS_given;
1903
1904 # get the length of a bound array
1905 my $maxlen;
1906 my %hash_of_arrays = %{$sth->{ParamArrays}};
1907 foreach (keys(%hash_of_arrays)) {
1908 my $ary = $hash_of_arrays{$_};
1909 next unless ref $ary eq 'ARRAY';
1910 $maxlen = @$ary if !$maxlen || @$ary > $maxlen;
1911 }
1912 # if there are no arrays then execute scalars once
1913 $maxlen = 1 unless defined $maxlen;
1914 my @bind_ids = 1..keys(%hash_of_arrays);
1915
1916 my $tuple_idx = 0;
1917 $fetch_tuple_sub = sub {
1918 return if $tuple_idx >= $maxlen;
1919 my @tuple = map {
1920 my $a = $hash_of_arrays{$_};
1921 ref($a) ? $a->[$tuple_idx] : $a
1922 } @bind_ids;
1923 ++$tuple_idx;
1924 return \@tuple;
1925 };
1926 }
1927 # pass thru the callers scalar or list context
1928 return $sth->execute_for_fetch($fetch_tuple_sub, $tuple_sts);
1929 }
1930
1931 sub execute_for_fetch {
1932 my ($sth, $fetch_tuple_sub, $tuple_status) = @_;
1933 # start with empty status array
1934 ($tuple_status) ? @$tuple_status = () : $tuple_status = [];
1935
1936 my $rc_total = 0;
1937 my ($err_count, %errstr_cache);
1938 while ( my $tuple = &$fetch_tuple_sub() ) {
1939 if ( my $rc = $sth->execute(@$tuple) ) {
1940 push @$tuple_status, $rc;
1941 $rc_total = ($rc >= 0 && $rc_total >= 0) ? $rc_total + $rc : -1;
1942 }
1943 else {
1944 $err_count++;
1945 my $err = $sth->err;
1946 push @$tuple_status, [ $err, $errstr_cache{$err} ||= $sth->errstr, $sth->state ];
1947 # XXX drivers implementing execute_for_fetch could opt to "last;" here
1948 # if the know the error code means no further executes will work.
1949 }
1950 }
1951 my $tuples = @$tuple_status;
1952 return $sth->set_err(1, "executing $tuples generated $err_count errors")
1953 if $err_count;
1954 $tuples ||= "0E0";
1955 return $tuples unless wantarray;
1956 return ($tuples, $rc_total);
1957 }
1958
1959
1960 sub fetchall_arrayref { # ALSO IN Driver.xst
1961 my ($sth, $slice, $max_rows) = @_;
1962 $max_rows = -1 unless defined $max_rows;
1963 my $mode = ref($slice) || 'ARRAY';
1964 my @rows;
1965 my $row;
1966 if ($mode eq 'ARRAY') {
1967 # we copy the array here because fetch (currently) always
1968 # returns the same array ref. XXX
1969 if ($slice && @$slice) {
1970 $max_rows = -1 unless defined $max_rows;
1971 push @rows, [ @{$row}[ @$slice] ]
1972 while($max_rows-- and $row = $sth->fetch);
1973 }
1974 elsif (defined $max_rows) {
1975 $max_rows = -1 unless defined $max_rows;
1976 push @rows, [ @$row ]
1977 while($max_rows-- and $row = $sth->fetch);
1978 }
1979 else {
1980 push @rows, [ @$row ] while($row = $sth->fetch);
1981 }
1982 }
1983 elsif ($mode eq 'HASH') {
1984 $max_rows = -1 unless defined $max_rows;
1985 if (keys %$slice) {
1986 my @o_keys = keys %$slice;
1987 my @i_keys = map { lc } keys %$slice;
1988 while ($max_rows-- and $row = $sth->fetchrow_hashref('NAME_lc')) {
1989 my %hash;
1990 @hash{@o_keys} = @{$row}{@i_keys};
1991 push @rows, \%hash;
1992 }
1993 }
1994 else {
1995 # XXX assumes new ref each fetchhash
1996 push @rows, $row
1997 while ($max_rows-- and $row = $sth->fetchrow_hashref());
1998 }
1999 }
2000 else { Carp::croak("fetchall_arrayref($mode) invalid") }
2001 return \@rows;
2002 }
2003
2004 sub fetchall_hashref {
2005 my ($sth, $key_field) = @_;
2006
2007 my $hash_key_name = $sth->{FetchHashKeyName} || 'NAME';
2008 my $names_hash = $sth->FETCH("${hash_key_name}_hash");
2009 my @key_fields = (ref $key_field) ? @$key_field : ($key_field);
2010 my @key_indexes;
2011 my $num_of_fields = $sth->FETCH('NUM_OF_FIELDS');
2012 foreach (@key_fields) {
2013 my $index = $names_hash->{$_}; # perl index not column
2014 $index = $_ - 1 if !defined $index && DBI::looks_like_number($_) && $_>=1 && $_ <= $num_of_fields;
2015 return $sth->set_err(1, "Field '$_' does not exist (not one of @{[keys %$names_hash]})")
2016 unless defined $index;
2017 push @key_indexes, $index;
2018 }
2019 my $rows = {};
2020 my $NAME = $sth->FETCH($hash_key_name);
2021 my @row = (undef) x $num_of_fields;
2022 $sth->bind_columns(\(@row));
2023 while ($sth->fetch) {
2024 my $ref = $rows;
2025 $ref = $ref->{$row[$_]} ||= {} for @key_indexes;
2026 @{$ref}{@$NAME} = @row;
2027 }
2028 return $rows;
2029 }
2030
203116µs *dump_results = \&DBI::dump_results;
2032
2033 sub blob_copy_to_file { # returns length or undef on error
2034 my($self, $field, $filename_or_handleref, $blocksize) = @_;
2035 my $fh = $filename_or_handleref;
2036 my($len, $buf) = (0, "");
2037 $blocksize ||= 512; # not too ambitious
2038 local(*FH);
2039 unless(ref $fh) {
2040 open(FH, ">$fh") || return undef;
2041 $fh = \*FH;
2042 }
2043 while(defined($self->blob_read($field, $len, $blocksize, \$buf))) {
2044 print $fh $buf;
2045 $len += length $buf;
2046 }
2047 close(FH);
2048 $len;
2049 }
2050
2051 sub more_results {
2052 shift->{syb_more_results}; # handy grandfathering
2053 }
2054
2055}
2056
205719µsunless ($DBI::PurePerl) { # See install_driver
2058214µs { @DBD::_mem::dr::ISA = qw(DBD::_mem::common); }
2059213µs { @DBD::_mem::db::ISA = qw(DBD::_mem::common); }
2060214µs { @DBD::_mem::st::ISA = qw(DBD::_mem::common); }
2061 # DBD::_mem::common::DESTROY is implemented in DBI.xs
2062}
2063
20641296µs1;
2065__END__
2066
2067=head1 DESCRIPTION
2068
2069The DBI is a database access module for the Perl programming language. It defines
2070a set of methods, variables, and conventions that provide a consistent
2071database interface, independent of the actual database being used.
2072
2073It is important to remember that the DBI is just an interface.
2074The DBI is a layer
2075of "glue" between an application and one or more database I<driver>
2076modules. It is the driver modules which do most of the real work. The DBI
2077provides a standard interface and framework for the drivers to operate
2078within.
2079
2080
2081=head2 Architecture of a DBI Application
2082
2083 |<- Scope of DBI ->|
2084 .-. .--------------. .-------------.
2085 .-------. | |---| XYZ Driver |---| XYZ Engine |
2086 | Perl | | | `--------------' `-------------'
2087 | script| |A| |D| .--------------. .-------------.
2088 | using |--|P|--|B|---|Oracle Driver |---|Oracle Engine|
2089 | DBI | |I| |I| `--------------' `-------------'
2090 | API | | |...
2091 |methods| | |... Other drivers
2092 `-------' | |...
2093 `-'
2094
2095The API, or Application Programming Interface, defines the
2096call interface and variables for Perl scripts to use. The API
2097is implemented by the Perl DBI extension.
2098
2099The DBI "dispatches" the method calls to the appropriate driver for
2100actual execution. The DBI is also responsible for the dynamic loading
2101of drivers, error checking and handling, providing default
2102implementations for methods, and many other non-database specific duties.
2103
2104Each driver
2105contains implementations of the DBI methods using the
2106private interface functions of the corresponding database engine. Only authors
2107of sophisticated/multi-database applications or generic library
2108functions need be concerned with drivers.
2109
2110=head2 Notation and Conventions
2111
2112The following conventions are used in this document:
2113
2114 $dbh Database handle object
2115 $sth Statement handle object
2116 $drh Driver handle object (rarely seen or used in applications)
2117 $h Any of the handle types above ($dbh, $sth, or $drh)
2118 $rc General Return Code (boolean: true=ok, false=error)
2119 $rv General Return Value (typically an integer)
2120 @ary List of values returned from the database, typically a row of data
2121 $rows Number of rows processed (if available, else -1)
2122 $fh A filehandle
2123 undef NULL values are represented by undefined values in Perl
2124 \%attr Reference to a hash of attribute values passed to methods
2125
2126Note that Perl will automatically destroy database and statement handle objects
2127if all references to them are deleted.
2128
2129
2130=head2 Outline Usage
2131
2132To use DBI,
2133first you need to load the DBI module:
2134
2135 use DBI;
2136 use strict;
2137
2138(The C<use strict;> isn't required but is strongly recommended.)
2139
2140Then you need to L</connect> to your data source and get a I<handle> for that
2141connection:
2142
2143 $dbh = DBI->connect($dsn, $user, $password,
2144 { RaiseError => 1, AutoCommit => 0 });
2145
2146Since connecting can be expensive, you generally just connect at the
2147start of your program and disconnect at the end.
2148
2149Explicitly defining the required C<AutoCommit> behaviour is strongly
2150recommended and may become mandatory in a later version. This
2151determines whether changes are automatically committed to the
2152database when executed, or need to be explicitly committed later.
2153
2154The DBI allows an application to "prepare" statements for later
2155execution. A prepared statement is identified by a statement handle
2156held in a Perl variable.
2157We'll call the Perl variable C<$sth> in our examples.
2158
2159The typical method call sequence for a C<SELECT> statement is:
2160
2161 prepare,
2162 execute, fetch, fetch, ...
2163 execute, fetch, fetch, ...
2164 execute, fetch, fetch, ...
2165
2166for example:
2167
2168 $sth = $dbh->prepare("SELECT foo, bar FROM table WHERE baz=?");
2169
2170 $sth->execute( $baz );
2171
2172 while ( @row = $sth->fetchrow_array ) {
2173 print "@row\n";
2174 }
2175
2176The typical method call sequence for a I<non>-C<SELECT> statement is:
2177
2178 prepare,
2179 execute,
2180 execute,
2181 execute.
2182
2183for example:
2184
2185 $sth = $dbh->prepare("INSERT INTO table(foo,bar,baz) VALUES (?,?,?)");
2186
2187 while(<CSV>) {
2188 chomp;
2189 my ($foo,$bar,$baz) = split /,/;
2190 $sth->execute( $foo, $bar, $baz );
2191 }
2192
2193The C<do()> method can be used for non repeated I<non>-C<SELECT> statement
2194(or with drivers that don't support placeholders):
2195
2196 $rows_affected = $dbh->do("UPDATE your_table SET foo = foo + 1");
2197
2198To commit your changes to the database (when L</AutoCommit> is off):
2199
2200 $dbh->commit; # or call $dbh->rollback; to undo changes
2201
2202Finally, when you have finished working with the data source, you should
2203L</disconnect> from it:
2204
2205 $dbh->disconnect;
2206
2207
2208=head2 General Interface Rules & Caveats
2209
2210The DBI does not have a concept of a "current session". Every session
2211has a handle object (i.e., a C<$dbh>) returned from the C<connect> method.
2212That handle object is used to invoke database related methods.
2213
2214Most data is returned to the Perl script as strings. (Null values are
2215returned as C<undef>.) This allows arbitrary precision numeric data to be
2216handled without loss of accuracy. Beware that Perl may not preserve
2217the same accuracy when the string is used as a number.
2218
2219Dates and times are returned as character strings in the current
2220default format of the corresponding database engine. Time zone effects
2221are database/driver dependent.
2222
2223Perl supports binary data in Perl strings, and the DBI will pass binary
2224data to and from the driver without change. It is up to the driver
2225implementors to decide how they wish to handle such binary data.
2226
2227Perl supports two kinds of strings: unicode (utf8 internally) and non-unicode
2228(defaults to iso-8859-1 if forced to assume an encoding). Drivers should
2229accept both kinds of strings and, if required, convert them to the character
2230set of the database being used. Similarly, when fetching from the database
2231character data that isn't iso-8859-1 the driver should convert it into utf8.
2232
2233Multiple SQL statements may not be combined in a single statement
2234handle (C<$sth>), although some databases and drivers do support this
2235(notably Sybase and SQL Server).
2236
2237Non-sequential record reads are not supported in this version of the DBI.
2238In other words, records can only be fetched in the order that the
2239database returned them, and once fetched they are forgotten.
2240
2241Positioned updates and deletes are not directly supported by the DBI.
2242See the description of the C<CursorName> attribute for an alternative.
2243
2244Individual driver implementors are free to provide any private
2245functions and/or handle attributes that they feel are useful.
2246Private driver functions can be invoked using the DBI C<func()> method.
2247Private driver attributes are accessed just like standard attributes.
2248
2249Many methods have an optional C<\%attr> parameter which can be used to
2250pass information to the driver implementing the method. Except where
2251specifically documented, the C<\%attr> parameter can only be used to pass
2252driver specific hints. In general, you can ignore C<\%attr> parameters
2253or pass it as C<undef>.
2254
2255
2256=head2 Naming Conventions and Name Space
2257
2258The DBI package and all packages below it (C<DBI::*>) are reserved for
2259use by the DBI. Extensions and related modules use the C<DBIx::>
2260namespace (see L<http://www.perl.com/CPAN/modules/by-module/DBIx/>).
2261Package names beginning with C<DBD::> are reserved for use
2262by DBI database drivers. All environment variables used by the DBI
2263or by individual DBDs begin with "C<DBI_>" or "C<DBD_>".
2264
2265The letter case used for attribute names is significant and plays an
2266important part in the portability of DBI scripts. The case of the
2267attribute name is used to signify who defined the meaning of that name
2268and its values.
2269
2270 Case of name Has a meaning defined by
2271 ------------ ------------------------
2272 UPPER_CASE Standards, e.g., X/Open, ISO SQL92 etc (portable)
2273 MixedCase DBI API (portable), underscores are not used.
2274 lower_case Driver or database engine specific (non-portable)
2275
2276It is of the utmost importance that Driver developers only use
2277lowercase attribute names when defining private attributes. Private
2278attribute names must be prefixed with the driver name or suitable
2279abbreviation (e.g., "C<ora_>" for Oracle, "C<ing_>" for Ingres, etc).
2280
2281
2282=head2 SQL - A Query Language
2283
2284Most DBI drivers require applications to use a dialect of SQL
2285(Structured Query Language) to interact with the database engine.
2286The L</"Standards Reference Information"> section provides links
2287to useful information about SQL.
2288
2289The DBI itself does not mandate or require any particular language to
2290be used; it is language independent. In ODBC terms, the DBI is in
2291"pass-thru" mode, although individual drivers might not be. The only requirement
2292is that queries and other statements must be expressed as a single
2293string of characters passed as the first argument to the L</prepare> or
2294L</do> methods.
2295
2296For an interesting diversion on the I<real> history of RDBMS and SQL,
2297from the people who made it happen, see:
2298
2299 http://ftp.digital.com/pub/DEC/SRC/technical-notes/SRC-1997-018-html/sqlr95.html
2300
2301Follow the "Full Contents" then "Intergalactic dataspeak" links for the
2302SQL history.
2303
2304=head2 Placeholders and Bind Values
2305
2306Some drivers support placeholders and bind values.
2307I<Placeholders>, also called parameter markers, are used to indicate
2308values in a database statement that will be supplied later,
2309before the prepared statement is executed. For example, an application
2310might use the following to insert a row of data into the SALES table:
2311
2312 INSERT INTO sales (product_code, qty, price) VALUES (?, ?, ?)
2313
2314or the following, to select the description for a product:
2315
2316 SELECT description FROM products WHERE product_code = ?
2317
2318The C<?> characters are the placeholders. The association of actual
2319values with placeholders is known as I<binding>, and the values are
2320referred to as I<bind values>.
2321
2322Note that the C<?> is not enclosed in quotation marks, even when the
2323placeholder represents a string. Some drivers also allow placeholders
2324like C<:>I<name> and C<:>I<n> (e.g., C<:1>, C<:2>, and so on)
2325in addition to C<?>, but their use is not portable.
2326
2327With most drivers, placeholders can't be used for any element of a
2328statement that would prevent the database server from validating the
2329statement and creating a query execution plan for it. For example:
2330
2331 "SELECT name, age FROM ?" # wrong (will probably fail)
2332 "SELECT name, ? FROM people" # wrong (but may not 'fail')
2333
2334Also, placeholders can only represent single scalar values.
2335For example, the following
2336statement won't work as expected for more than one value:
2337
2338 "SELECT name, age FROM people WHERE name IN (?)" # wrong
2339 "SELECT name, age FROM people WHERE name IN (?,?)" # two names
2340
2341When using placeholders with the SQL C<LIKE> qualifier, you must
2342remember that the placeholder substitutes for the whole string.
2343So you should use "C<... LIKE ? ...>" and include any wildcard
2344characters in the value that you bind to the placeholder.
2345
2346B<NULL Values>
2347
2348Undefined values, or C<undef>, are used to indicate NULL values.
2349You can insert and update columns with a NULL value as you would a
2350non-NULL value. These examples insert and update the column
2351C<age> with a NULL value:
2352
2353 $sth = $dbh->prepare(qq{
2354 INSERT INTO people (fullname, age) VALUES (?, ?)
2355 });
2356 $sth->execute("Joe Bloggs", undef);
2357
2358 $sth = $dbh->prepare(qq{
2359 UPDATE people SET age = ? WHERE fullname = ?
2360 });
2361 $sth->execute(undef, "Joe Bloggs");
2362
2363However, care must be taken when trying to use NULL values in a
2364C<WHERE> clause. Consider:
2365
2366 SELECT fullname FROM people WHERE age = ?
2367
2368Binding an C<undef> (NULL) to the placeholder will I<not> select rows
2369which have a NULL C<age>! At least for database engines that
2370conform to the SQL standard. Refer to the SQL manual for your database
2371engine or any SQL book for the reasons for this. To explicitly select
2372NULLs you have to say "C<WHERE age IS NULL>".
2373
2374A common issue is to have a code fragment handle a value that could be
2375either C<defined> or C<undef> (non-NULL or NULL) at runtime.
2376A simple technique is to prepare the appropriate statement as needed,
2377and substitute the placeholder for non-NULL cases:
2378
2379 $sql_clause = defined $age? "age = ?" : "age IS NULL";
2380 $sth = $dbh->prepare(qq{
2381 SELECT fullname FROM people WHERE $sql_clause
2382 });
2383 $sth->execute(defined $age ? $age : ());
2384
2385The following technique illustrates qualifying a C<WHERE> clause with
2386several columns, whose associated values (C<defined> or C<undef>) are
2387in a hash %h:
2388
2389 for my $col ("age", "phone", "email") {
2390 if (defined $h{$col}) {
2391 push @sql_qual, "$col = ?";
2392 push @sql_bind, $h{$col};
2393 }
2394 else {
2395 push @sql_qual, "$col IS NULL";
2396 }
2397 }
2398 $sql_clause = join(" AND ", @sql_qual);
2399 $sth = $dbh->prepare(qq{
2400 SELECT fullname FROM people WHERE $sql_clause
2401 });
2402 $sth->execute(@sql_bind);
2403
2404The techniques above call prepare for the SQL statement with each call to
2405execute. Because calls to prepare() can be expensive, performance
2406can suffer when an application iterates many times over statements
2407like the above.
2408
2409A better solution is a single C<WHERE> clause that supports both
2410NULL and non-NULL comparisons. Its SQL statement would need to be
2411prepared only once for all cases, thus improving performance.
2412Several examples of C<WHERE> clauses that support this are presented
2413below. But each example lacks portability, robustness, or simplicity.
2414Whether an example is supported on your database engine depends on
2415what SQL extensions it provides, and where it supports the C<?>
2416placeholder in a statement.
2417
2418 0) age = ?
2419 1) NVL(age, xx) = NVL(?, xx)
2420 2) ISNULL(age, xx) = ISNULL(?, xx)
2421 3) DECODE(age, ?, 1, 0) = 1
2422 4) age = ? OR (age IS NULL AND ? IS NULL)
2423 5) age = ? OR (age IS NULL AND SP_ISNULL(?) = 1)
2424 6) age = ? OR (age IS NULL AND ? = 1)
2425
2426Statements formed with the above C<WHERE> clauses require execute
2427statements as follows. The arguments are required, whether their
2428values are C<defined> or C<undef>.
2429
2430 0,1,2,3) $sth->execute($age);
2431 4,5) $sth->execute($age, $age);
2432 6) $sth->execute($age, defined($age) ? 0 : 1);
2433
2434Example 0 should not work (as mentioned earlier), but may work on
2435a few database engines anyway (e.g. Sybase). Example 0 is part
2436of examples 4, 5, and 6, so if example 0 works, these other
2437examples may work, even if the engine does not properly support
2438the right hand side of the C<OR> expression.
2439
2440Examples 1 and 2 are not robust: they require that you provide a
2441valid column value xx (e.g. '~') which is not present in any row.
2442That means you must have some notion of what data won't be stored
2443in the column, and expect clients to adhere to that.
2444
2445Example 5 requires that you provide a stored procedure (SP_ISNULL
2446in this example) that acts as a function: it checks whether a value
2447is null, and returns 1 if it is, or 0 if not.
2448
2449Example 6, the least simple, is probably the most portable, i.e., it
2450should work with with most, if not all, database engines.
2451
2452Here is a table that indicates which examples above are known to
2453work on various database engines:
2454
2455 -----Examples------
2456 0 1 2 3 4 5 6
2457 - - - - - - -
2458 Oracle 9 N Y N Y Y ? Y
2459 Informix IDS 9 N N N Y N Y Y
2460 MS SQL N N Y N Y ? Y
2461 Sybase Y N N N N N Y
2462 AnyData,DBM,CSV Y N N N Y Y* Y
2463
2464* Works only because Example 0 works.
2465
2466DBI provides a sample perl script that will test the examples above
2467on your database engine and tell you which ones work. It is located
2468in the F<ex/> subdirectory of the DBI source distribution, or here:
2469L<http://svn.perl.org/modules/dbi/trunk/ex/perl_dbi_nulls_test.pl>
2470Please use the script to help us fill-in and maintain this table.
2471
2472B<Performance>
2473
2474Without using placeholders, the insert statement shown previously would have to
2475contain the literal values to be inserted and would have to be
2476re-prepared and re-executed for each row. With placeholders, the insert
2477statement only needs to be prepared once. The bind values for each row
2478can be given to the C<execute> method each time it's called. By avoiding
2479the need to re-prepare the statement for each row, the application
2480typically runs many times faster. Here's an example:
2481
2482 my $sth = $dbh->prepare(q{
2483 INSERT INTO sales (product_code, qty, price) VALUES (?, ?, ?)
2484 }) or die $dbh->errstr;
2485 while (<>) {
2486 chomp;
2487 my ($product_code, $qty, $price) = split /,/;
2488 $sth->execute($product_code, $qty, $price) or die $dbh->errstr;
2489 }
2490 $dbh->commit or die $dbh->errstr;
2491
2492See L</execute> and L</bind_param> for more details.
2493
2494The C<q{...}> style quoting used in this example avoids clashing with
2495quotes that may be used in the SQL statement. Use the double-quote like
2496C<qq{...}> operator if you want to interpolate variables into the string.
2497See L<perlop/"Quote and Quote-like Operators"> for more details.
2498
2499See also the L</bind_columns> method, which is used to associate Perl
2500variables with the output columns of a C<SELECT> statement.
2501
2502=head1 THE DBI PACKAGE AND CLASS
2503
2504In this section, we cover the DBI class methods, utility functions,
2505and the dynamic attributes associated with generic DBI handles.
2506
2507=head2 DBI Constants
2508
2509Constants representing the values of the SQL standard types can be
2510imported individually by name, or all together by importing the
2511special C<:sql_types> tag.
2512
2513The names and values of all the defined SQL standard types can be
2514produced like this:
2515
2516 foreach (@{ $DBI::EXPORT_TAGS{sql_types} }) {
2517 printf "%s=%d\n", $_, &{"DBI::$_"};
2518 }
2519
2520These constants are defined by SQL/CLI, ODBC or both.
2521C<SQL_BIGINT> is (currently) omitted, because SQL/CLI and ODBC provide
2522conflicting codes.
2523
2524See the L</type_info>, L</type_info_all>, and L</bind_param> methods
2525for possible uses.
2526
2527Note that just because the DBI defines a named constant for a given
2528data type doesn't mean that drivers will support that data type.
2529
2530
2531=head2 DBI Class Methods
2532
2533The following methods are provided by the DBI class:
2534
2535=over 4
2536
2537=item C<parse_dsn>
2538
2539 ($scheme, $driver, $attr_string, $attr_hash, $driver_dsn) = DBI->parse_dsn($dsn)
2540 or die "Can't parse DBI DSN '$dsn'";
2541
2542Breaks apart a DBI Data Source Name (DSN) and returns the individual
2543parts. If $dsn doesn't contain a valid DSN then parse_dsn() returns
2544an empty list.
2545
2546$scheme is the first part of the DSN and is currently always 'dbi'.
2547$driver is the driver name, possibly defaulted to $ENV{DBI_DRIVER},
2548and may be undefined. $attr_string is the contents of the optional attribute
2549string, which may be undefined. If $attr_string is not empty then $attr_hash
2550is a reference to a hash containing the parsed attribute names and values.
2551$driver_dsn is the last part of the DBI DSN string. For example:
2552
2553 ($scheme, $driver, $attr_string, $attr_hash, $driver_dsn)
2554 = DBI->parse_dsn("DBI:MyDriver(RaiseError=>1):db=test;port=42");
2555 $scheme = 'dbi';
2556 $driver = 'MyDriver';
2557 $attr_string = 'RaiseError=>1';
2558 $attr_hash = { 'RaiseError' => '1' };
2559 $driver_dsn = 'db=test;port=42';
2560
2561The parse_dsn() method was added in DBI 1.43.
2562
2563=item C<connect>
2564
2565 $dbh = DBI->connect($data_source, $username, $password)
2566 or die $DBI::errstr;
2567 $dbh = DBI->connect($data_source, $username, $password, \%attr)
2568 or die $DBI::errstr;
2569
2570Establishes a database connection, or session, to the requested C<$data_source>.
2571Returns a database handle object if the connection succeeds. Use
2572C<$dbh-E<gt>disconnect> to terminate the connection.
2573
2574If the connect fails (see below), it returns C<undef> and sets both C<$DBI::err>
2575and C<$DBI::errstr>. (It does I<not> explicitly set C<$!>.) You should generally
2576test the return status of C<connect> and C<print $DBI::errstr> if it has failed.
2577
2578Multiple simultaneous connections to multiple databases through multiple
2579drivers can be made via the DBI. Simply make one C<connect> call for each
2580database and keep a copy of each returned database handle.
2581
2582The C<$data_source> value must begin with "C<dbi:>I<driver_name>C<:>".
2583The I<driver_name> specifies the driver that will be used to make the
2584connection. (Letter case is significant.)
2585
2586As a convenience, if the C<$data_source> parameter is undefined or empty,
2587the DBI will substitute the value of the environment variable C<DBI_DSN>.
2588If just the I<driver_name> part is empty (i.e., the C<$data_source>
2589prefix is "C<dbi::>"), the environment variable C<DBI_DRIVER> is
2590used. If neither variable is set, then C<connect> dies.
2591
2592Examples of C<$data_source> values are:
2593
2594 dbi:DriverName:database_name
2595 dbi:DriverName:database_name@hostname:port
2596 dbi:DriverName:database=database_name;host=hostname;port=port
2597
2598There is I<no standard> for the text following the driver name. Each
2599driver is free to use whatever syntax it wants. The only requirement the
2600DBI makes is that all the information is supplied in a single string.
2601You must consult the documentation for the drivers you are using for a
2602description of the syntax they require.
2603
2604It is recommended that drivers support the ODBC style, shown in the
2605last example above. It is also recommended that that they support the
2606three common names 'C<host>', 'C<port>', and 'C<database>' (plus 'C<db>'
2607as an alias for C<database>). This simplifies automatic construction
2608of basic DSNs: C<"dbi:$driver:database=$db;host=$host;port=$port">.
2609Drivers should aim to 'do something reasonable' when given a DSN
2610in this form, but if any part is meaningless for that driver (such
2611as 'port' for Informix) it should generate an error if that part
2612is not empty.
2613
2614If the environment variable C<DBI_AUTOPROXY> is defined (and the
2615driver in C<$data_source> is not "C<Proxy>") then the connect request
2616will automatically be changed to:
2617
2618 $ENV{DBI_AUTOPROXY};dsn=$data_source
2619
2620C<DBI_AUTOPROXY> is typically set as "C<dbi:Proxy:hostname=...;port=...>".
2621If $ENV{DBI_AUTOPROXY} doesn't begin with 'C<dbi:>' then "dbi:Proxy:"
2622will be prepended to it first. See the DBD::Proxy documentation
2623for more details.
2624
2625If C<$username> or C<$password> are undefined (rather than just empty),
2626then the DBI will substitute the values of the C<DBI_USER> and C<DBI_PASS>
2627environment variables, respectively. The DBI will warn if the
2628environment variables are not defined. However, the everyday use
2629of these environment variables is not recommended for security
2630reasons. The mechanism is primarily intended to simplify testing.
2631See below for alternative way to specify the username and password.
2632
2633C<DBI-E<gt>connect> automatically installs the driver if it has not been
2634installed yet. Driver installation either returns a valid driver
2635handle, or it I<dies> with an error message that includes the string
2636"C<install_driver>" and the underlying problem. So C<DBI-E<gt>connect>
2637will die
2638on a driver installation failure and will only return C<undef> on a
2639connect failure, in which case C<$DBI::errstr> will hold the error message.
2640Use C<eval { ... }> if you need to catch the "C<install_driver>" error.
2641
2642The C<$data_source> argument (with the "C<dbi:...:>" prefix removed) and the
2643C<$username> and C<$password> arguments are then passed to the driver for
2644processing. The DBI does not define any interpretation for the
2645contents of these fields. The driver is free to interpret the
2646C<$data_source>, C<$username>, and C<$password> fields in any way, and supply
2647whatever defaults are appropriate for the engine being accessed.
2648(Oracle, for example, uses the ORACLE_SID and TWO_TASK environment
2649variables if no C<$data_source> is specified.)
2650
2651The C<AutoCommit> and C<PrintError> attributes for each connection
2652default to "on". (See L</AutoCommit> and L</PrintError> for more information.)
2653However, it is strongly recommended that you explicitly define C<AutoCommit>
2654rather than rely on the default. The C<PrintWarn> attribute defaults to
2655on if $^W is true, i.e., perl is running with warnings enabled.
2656
2657The C<\%attr> parameter can be used to alter the default settings of
2658C<PrintError>, C<RaiseError>, C<AutoCommit>, and other attributes. For example:
2659
2660 $dbh = DBI->connect($data_source, $user, $pass, {
2661 PrintError => 0,
2662 AutoCommit => 0
2663 });
2664
2665The username and password can also be specified using the attributes
2666C<Username> and C<Password>, in which case they take precedence
2667over the C<$username> and C<$password> parameters.
2668
2669You can also define connection attribute values within the C<$data_source>
2670parameter. For example:
2671
2672 dbi:DriverName(PrintWarn=>1,PrintError=>0,Taint=>1):...
2673
2674Individual attributes values specified in this way take precedence over
2675any conflicting values specified via the C<\%attr> parameter to C<connect>.
2676
2677The C<dbi_connect_method> attribute can be used to specify which driver
2678method should be called to establish the connection. The only useful
2679values are 'connect', 'connect_cached', or some specialized case like
2680'Apache::DBI::connect' (which is automatically the default when running
2681within Apache).
2682
2683Where possible, each session (C<$dbh>) is independent from the transactions
2684in other sessions. This is useful when you need to hold cursors open
2685across transactions--for example, if you use one session for your long lifespan
2686cursors (typically read-only) and another for your short update
2687transactions.
2688
2689For compatibility with old DBI scripts, the driver can be specified by
2690passing its name as the fourth argument to C<connect> (instead of C<\%attr>):
2691
2692 $dbh = DBI->connect($data_source, $user, $pass, $driver);
2693
2694In this "old-style" form of C<connect>, the C<$data_source> should not start
2695with "C<dbi:driver_name:>". (If it does, the embedded driver_name
2696will be ignored). Also note that in this older form of C<connect>,
2697the C<$dbh-E<gt>{AutoCommit}> attribute is I<undefined>, the
2698C<$dbh-E<gt>{PrintError}> attribute is off, and the old C<DBI_DBNAME>
2699environment variable is
2700checked if C<DBI_DSN> is not defined. Beware that this "old-style"
2701C<connect> will soon be withdrawn in a future version of DBI.
2702
2703=item C<connect_cached>
2704
2705 $dbh = DBI->connect_cached($data_source, $username, $password)
2706 or die $DBI::errstr;
2707 $dbh = DBI->connect_cached($data_source, $username, $password, \%attr)
2708 or die $DBI::errstr;
2709
2710C<connect_cached> is like L</connect>, except that the database handle
2711returned is also
2712stored in a hash associated with the given parameters. If another call
2713is made to C<connect_cached> with the same parameter values, then the
2714corresponding cached C<$dbh> will be returned if it is still valid.
2715The cached database handle is replaced with a new connection if it
2716has been disconnected or if the C<ping> method fails.
2717
2718That the behaviour of this method differs in several respects from the
2719behaviour of persistent connections implemented by Apache::DBI.
2720However, if Apache::DBI is loaded then C<connect_cached> will use it.
2721
2722Caching connections can be useful in some applications, but it can
2723also cause problems, such as too many connections, and so should
2724be used with care. In particular, avoid changing the attributes of
2725a database handle created via connect_cached() because it will affect
2726other code that may be using the same handle.
2727
2728Where multiple separate parts of a program are using connect_cached()
2729to connect to the same database with the same (initial) attributes
2730it is a good idea to add a private attribute to the connect_cached()
2731call to effectively limit the scope of the caching. For example:
2732
2733 DBI->connect_cached(..., { private_foo_cachekey => "Bar", ... });
2734
2735Handles returned from that connect_cached() call will only be returned
2736by other connect_cached() call elsewhere in the code if those other
2737calls also pass in the same attribute values, including the private one.
2738(I've used C<private_foo_cachekey> here as an example, you can use
2739any attribute name with a C<private_> prefix.)
2740
2741Taking that one step further, you can limit a particular connect_cached()
2742call to return handles unique to that one place in the code by setting the
2743private attribute to a unique value for that place:
2744
2745 DBI->connect_cached(..., { private_foo_cachekey => __FILE__.__LINE__, ... });
2746
2747By using a private attribute you still get connection caching for
2748the individual calls to connect_cached() but, by making separate
2749database conections for separate parts of the code, the database
2750handles are isolated from any attribute changes made to other handles.
2751
2752The cache can be accessed (and cleared) via the L</CachedKids> attribute:
2753
2754 my $CachedKids_hashref = $dbh->{Driver}->{CachedKids};
2755 %$CachedKids_hashref = () if $CachedKids_hashref;
2756
2757
2758=item C<available_drivers>
2759
2760 @ary = DBI->available_drivers;
2761 @ary = DBI->available_drivers($quiet);
2762
2763Returns a list of all available drivers by searching for C<DBD::*> modules
2764through the directories in C<@INC>. By default, a warning is given if
2765some drivers are hidden by others of the same name in earlier
2766directories. Passing a true value for C<$quiet> will inhibit the warning.
2767
2768=item C<installed_drivers>
2769
2770 %drivers = DBI->installed_drivers();
2771
2772Returns a list of driver name and driver handle pairs for all drivers
2773'installed' (loaded) into the current process. The driver name does not
2774include the 'DBD::' prefix.
2775
2776To get a list of all drivers available in your perl instalation you can use
2777L</available_drivers>.
2778
2779Added in DBI 1.49.
2780
2781=item C<installed_versions>
2782
2783 DBI->installed_versions;
2784 @ary = DBI->installed_versions;
2785 %hash = DBI->installed_versions;
2786
2787Calls available_drivers() and attempts to load each of them in turn
2788using install_driver(). For each load that succeeds the driver
2789name and version number are added to a hash. When running under
2790L<DBI::PurePerl> drivers which appear not be pure-perl are ignored.
2791
2792When called in array context the list of successfully loaded drivers
2793is returned (without the 'DBD::' prefix).
2794
2795When called in scalar context a reference to the hash is returned
2796and the hash will also contain other entries for the C<DBI> version,
2797C<OS> name, etc.
2798
2799When called in a void context the installed_versions() method will
2800print out a formatted list of the hash contents, one per line.
2801
2802Due to the potentially high memory cost and unknown risks of loading
2803in an unknown number of drivers that just happen to be installed
2804on the system, this method is not recommended for general use.
2805Use available_drivers() instead.
2806
2807The installed_versions() method is primarily intended as a quick
2808way to see from the command line what's installed. For example:
2809
2810 perl -MDBI -e 'DBI->installed_versions'
2811
2812The installed_versions() method was added in DBI 1.38.
2813
2814=item C<data_sources>
2815
2816 @ary = DBI->data_sources($driver);
2817 @ary = DBI->data_sources($driver, \%attr);
2818
2819Returns a list of data sources (databases) available via the named
2820driver. If C<$driver> is empty or C<undef>, then the value of the
2821C<DBI_DRIVER> environment variable is used.
2822
2823The driver will be loaded if it hasn't been already. Note that if the
2824driver loading fails then data_sources() I<dies> with an error message
2825that includes the string "C<install_driver>" and the underlying problem.
2826
2827Data sources are returned in a form suitable for passing to the
2828L</connect> method (that is, they will include the "C<dbi:$driver:>" prefix).
2829
2830Note that many drivers have no way of knowing what data sources might
2831be available for it. These drivers return an empty or incomplete list
2832or may require driver-specific attributes.
2833
2834There is also a data_sources() method defined for database handles.
2835
2836
2837=item C<trace>
2838
2839 DBI->trace($trace_setting)
2840 DBI->trace($trace_setting, $trace_filename)
2841 DBI->trace($trace_setting, $trace_filehandle)
2842 $trace_setting = DBI->trace;
2843
2844The C<DBI-E<gt>trace> method sets the I<global default> trace
2845settings and returns the I<previous> trace settings. It can also
2846be used to change where the trace output is sent.
2847
2848There's a similar method, C<$h-E<gt>trace>, which sets the trace
2849settings for the specific handle it's called on.
2850
2851See the L</TRACING> section for full details about the DBI's powerful
2852tracing facilities.
2853
2854=back
2855
2856
2857=head2 DBI Utility Functions
2858
2859In addition to the DBI methods listed in the previous section,
2860the DBI package also provides several utility functions.
2861
2862These can be imported into your code by listing them in
2863the C<use> statement. For example:
2864
2865 use DBI qw(neat data_diff);
2866
2867Alternatively, all these utility functions (except hash) can be
2868imported using the C<:utils> import tag. For example:
2869
2870 use DBI qw(:utils);
2871
2872=over 4
2873
2874=item C<data_string_desc>
2875
2876 $description = data_string_desc($string);
2877
2878Returns an informal description of the string. For example:
2879
2880 UTF8 off, ASCII, 42 characters 42 bytes
2881 UTF8 off, non-ASCII, 42 characters 42 bytes
2882 UTF8 on, non-ASCII, 4 characters 6 bytes
2883 UTF8 on but INVALID encoding, non-ASCII, 4 characters 6 bytes
2884 UTF8 off, undef
2885
2886The initial C<UTF8> on/off refers to Perl's internal SvUTF8 flag.
2887If $string has the SvUTF8 flag set but the sequence of bytes it
2888contains are not a valid UTF-8 encoding then data_string_desc()
2889will report C<UTF8 on but INVALID encoding>.
2890
2891The C<ASCII> vs C<non-ASCII> portion shows C<ASCII> if I<all> the
2892characters in the string are ASCII (have code points <= 127).
2893
2894The data_string_desc() function was added in DBI 1.46.
2895
2896=item C<data_string_diff>
2897
2898 $diff = data_string_diff($a, $b);
2899
2900Returns an informal description of the first character difference
2901between the strings. If both $a and $b contain the same sequence
2902of characters then data_string_diff() returns an empty string.
2903For example:
2904
2905 Params a & b Result
2906 ------------ ------
2907 'aaa', 'aaa' ''
2908 'aaa', 'abc' 'Strings differ at index 2: a[2]=a, b[2]=b'
2909 'aaa', undef 'String b is undef, string a has 3 characters'
2910 'aaa', 'aa' 'String b truncated after 2 characters'
2911
2912Unicode characters are reported in C<\x{XXXX}> format. Unicode
2913code points in the range U+0800 to U+08FF are unassigned and most
2914likely to occur due to double-encoding. Characters in this range
2915are reported as C<\x{08XX}='C'> where C<C> is the corresponding
2916latin-1 character.
2917
2918The data_string_diff() function only considers logical I<characters>
2919and not the underlying encoding. See L</data_diff> for an alternative.
2920
2921The data_string_diff() function was added in DBI 1.46.
2922
2923=item C<data_diff>
2924
2925 $diff = data_diff($a, $b);
2926 $diff = data_diff($a, $b, $logical);
2927
2928Returns an informal description of the difference between two strings.
2929It calls L</data_string_desc> and L</data_string_diff>
2930and returns the combined results as a multi-line string.
2931
2932For example, C<data_diff("abc", "ab\x{263a}")> will return:
2933
2934 a: UTF8 off, ASCII, 3 characters 3 bytes
2935 b: UTF8 on, non-ASCII, 3 characters 5 bytes
2936 Strings differ at index 2: a[2]=c, b[2]=\x{263A}
2937
2938If $a and $b are identical in both the characters they contain I<and>
2939their physical encoding then data_diff() returns an empty string.
2940If $logical is true then physical encoding differences are ignored
2941(but are still reported if there is a difference in the characters).
2942
2943The data_diff() function was added in DBI 1.46.
2944
2945=item C<neat>
2946
2947 $str = neat($value);
2948 $str = neat($value, $maxlen);
2949
2950Return a string containing a neat (and tidy) representation of the
2951supplied value.
2952
2953Strings will be quoted, although internal quotes will I<not> be escaped.
2954Values known to be numeric will be unquoted. Undefined (NULL) values
2955will be shown as C<undef> (without quotes).
2956
2957If the string is flagged internally as utf8 then double quotes will
2958be used, otherwise single quotes are used and unprintable characters
2959will be replaced by dot (.).
2960
2961For result strings longer than C<$maxlen> the result string will be
2962truncated to C<$maxlen-4> and "C<...'>" will be appended. If C<$maxlen> is 0
2963or C<undef>, it defaults to C<$DBI::neat_maxlen> which, in turn, defaults to 400.
2964
2965This function is designed to format values for human consumption.
2966It is used internally by the DBI for L</trace> output. It should
2967typically I<not> be used for formatting values for database use.
2968(See also L</quote>.)
2969
2970=item C<neat_list>
2971
2972 $str = neat_list(\@listref, $maxlen, $field_sep);
2973
2974Calls C<neat> on each element of the list and returns a string
2975containing the results joined with C<$field_sep>. C<$field_sep> defaults
2976to C<", ">.
2977
2978=item C<looks_like_number>
2979
2980 @bool = looks_like_number(@array);
2981
2982Returns true for each element that looks like a number.
2983Returns false for each element that does not look like a number.
2984Returns C<undef> for each element that is undefined or empty.
2985
2986=item C<hash>
2987
2988 $hash_value = DBI::hash($buffer, $type);
2989
2990Return a 32-bit integer 'hash' value corresponding to the contents of $buffer.
2991The $type parameter selects which kind of hash algorithm should be used.
2992
2993For the technically curious, type 0 (which is the default if $type
2994isn't specified) is based on the Perl 5.1 hash except that the value
2995is forced to be negative (for obscure historical reasons).
2996Type 1 is the better "Fowler / Noll / Vo" (FNV) hash. See
2997L<http://www.isthe.com/chongo/tech/comp/fnv/> for more information.
2998Both types are implemented in C and are very fast.
2999
3000This function doesn't have much to do with databases, except that
3001it can be handy to store hash values in a database.
3002
3003=back
3004
3005
3006=head2 DBI Dynamic Attributes
3007
3008Dynamic attributes are always associated with the I<last handle used>
3009(that handle is represented by C<$h> in the descriptions below).
3010
3011Where an attribute is equivalent to a method call, then refer to
3012the method call for all related documentation.
3013
3014Warning: these attributes are provided as a convenience but they
3015do have limitations. Specifically, they have a short lifespan:
3016because they are associated with
3017the last handle used, they should only be used I<immediately> after
3018calling the method that "sets" them.
3019If in any doubt, use the corresponding method call.
3020
3021=over 4
3022
3023=item C<$DBI::err>
3024
3025Equivalent to C<$h-E<gt>err>.
3026
3027=item C<$DBI::errstr>
3028
3029Equivalent to C<$h-E<gt>errstr>.
3030
3031=item C<$DBI::state>
3032
3033Equivalent to C<$h-E<gt>state>.
3034
3035=item C<$DBI::rows>
3036
3037Equivalent to C<$h-E<gt>rows>. Please refer to the documentation
3038for the L</rows> method.
3039
3040=item C<$DBI::lasth>
3041
3042Returns the DBI object handle used for the most recent DBI method call.
3043If the last DBI method call was a DESTROY then $DBI::lasth will return
3044the handle of the parent of the destroyed handle, if there is one.
3045
3046=back
3047
3048
3049=head1 METHODS COMMON TO ALL HANDLES
3050
3051The following methods can be used by all types of DBI handles.
3052
3053=over 4
3054
3055=item C<err>
3056
3057 $rv = $h->err;
3058
3059Returns the I<native> database engine error code from the last driver
3060method called. The code is typically an integer but you should not
3061assume that.
3062
3063The DBI resets $h->err to undef before almost all DBI method calls, so the
3064value only has a short lifespan. Also, for most drivers, the statement
3065handles share the same error variable as the parent database handle,
3066so calling a method on one handle may reset the error on the
3067related handles.
3068
3069(Methods which don't reset err before being called include err() and errstr(),
3070obviously, state(), rows(), func(), trace(), trace_msg(), ping(), and the
3071tied hash attribute FETCH() and STORE() methods.)
3072
3073If you need to test for specific error conditions I<and> have your program be
3074portable to different database engines, then you'll need to determine what the
3075corresponding error codes are for all those engines and test for all of them.
3076
3077A driver may return C<0> from err() to indicate a warning condition
3078after a method call. Similarly, a driver may return an empty string
3079to indicate a 'success with information' condition. In both these
3080cases the value is false but not undef. The errstr() and state()
3081methods may be used to retrieve extra information in these cases.
3082
3083See L</set_err> for more information.
3084
3085=item C<errstr>
3086
3087 $str = $h->errstr;
3088
3089Returns the native database engine error message from the last DBI
3090method called. This has the same lifespan issues as the L</err> method
3091described above.
3092
3093The returned string may contain multiple messages separated by
3094newline characters.
3095
3096The errstr() method should not be used to test for errors, use err()
3097for that, because drivers may return 'success with information' or
3098warning messages via errstr() for methods that have not 'failed'.
3099
3100See L</set_err> for more information.
3101
3102=item C<state>
3103
3104 $str = $h->state;
3105
3106Returns a state code in the standard SQLSTATE five character format.
3107Note that the specific success code C<00000> is translated to any empty string
3108(false). If the driver does not support SQLSTATE (and most don't),
3109then state will return C<S1000> (General Error) for all errors.
3110
3111The driver is free to return any value via C<state>, e.g., warning
3112codes, even if it has not declared an error by returning a true value
3113via the L</err> method described above.
3114
3115The state() method should not be used to test for errors, use err()
3116for that, because drivers may return a 'success with information' or
3117warning state code via errstr() for methods that have not 'failed'.
3118
3119=item C<set_err>
3120
3121 $rv = $h->set_err($err, $errstr);
3122 $rv = $h->set_err($err, $errstr, $state);
3123 $rv = $h->set_err($err, $errstr, $state, $method);
3124 $rv = $h->set_err($err, $errstr, $state, $method, $rv);
3125
3126Set the C<err>, C<errstr>, and C<state> values for the handle.
3127This method is typically only used by DBI drivers and DBI subclasses.
3128
3129If the L</HandleSetErr> attribute holds a reference to a subroutine
3130it is called first. The subroutine can alter the $err, $errstr, $state,
3131and $method values. See L</HandleSetErr> for full details.
3132If the subroutine returns a true value then the handle C<err>,
3133C<errstr>, and C<state> values are not altered and set_err() returns
3134an empty list (it normally returns $rv which defaults to undef, see below).
3135
3136Setting C<err> to a I<true> value indicates an error and will trigger
3137the normal DBI error handling mechanisms, such as C<RaiseError> and
3138C<HandleError>, if they are enabled, when execution returns from
3139the DBI back to the application.
3140
3141Setting C<err> to C<""> indicates an 'information' state, and setting
3142it to C<"0"> indicates a 'warning' state. Setting C<err> to C<undef>
3143also sets C<errstr> to undef, and C<state> to C<"">, irrespective
3144of the values of the $errstr and $state parameters.
3145
3146The $method parameter provides an alternate method name for the
3147C<RaiseError>/C<PrintError>/C<PrintWarn> error string instead of
3148the fairly unhelpful 'C<set_err>'.
3149
3150The C<set_err> method normally returns undef. The $rv parameter
3151provides an alternate return value.
3152
3153Some special rules apply if the C<err> or C<errstr>
3154values for the handle are I<already> set...
3155
3156If C<errstr> is true then: "C< [err was %s now %s]>" is appended if $err is
3157true and C<err> is already true and the new err value differs from the original
3158one. Similarly "C< [state was %s now %s]>" is appended if $state is true and C<state> is
3159already true and the new state value differs from the original one. Finally
3160"C<\n>" and the new $errstr are appended if $errstr differs from the existing
3161errstr value. Obviously the C<%s>'s above are replaced by the corresponding values.
3162
3163The handle C<err> value is set to $err if: $err is true; or handle
3164C<err> value is undef; or $err is defined and the length is greater
3165than the handle C<err> length. The effect is that an 'information'
3166state only overrides undef; a 'warning' overrides undef or 'information',
3167and an 'error' state overrides anything.
3168
3169The handle C<state> value is set to $state if $state is true and
3170the handle C<err> value was set (by the rules above).
3171
3172Support for warning and information states was added in DBI 1.41.
3173
3174=item C<trace>
3175
3176 $h->trace($trace_settings);
3177 $h->trace($trace_settings, $trace_filename);
3178 $trace_settings = $h->trace;
3179
3180The trace() method is used to alter the trace settings for a handle
3181(and any future children of that handle). It can also be used to
3182change where the trace output is sent.
3183
3184There's a similar method, C<DBI-E<gt>trace>, which sets the global
3185default trace settings.
3186
3187See the L</TRACING> section for full details about the DBI's powerful
3188tracing facilities.
3189
3190=item C<trace_msg>
3191
3192 $h->trace_msg($message_text);
3193 $h->trace_msg($message_text, $min_level);
3194
3195Writes C<$message_text> to the trace file if the trace level is
3196greater than or equal to $min_level (which defaults to 1).
3197Can also be called as C<DBI-E<gt>trace_msg($msg)>.
3198
3199See L</TRACING> for more details.
3200
3201=item C<func>
3202
3203 $h->func(@func_arguments, $func_name) or die ...;
3204
3205The C<func> method can be used to call private non-standard and
3206non-portable methods implemented by the driver. Note that the function
3207name is given as the I<last> argument.
3208
3209It's also important to note that the func() method does not clear
3210a previous error ($DBI::err etc.) and it does not trigger automatic
3211error detection (RaiseError etc.) so you must check the return
3212status and/or $h->err to detect errors.
3213
3214(This method is not directly related to calling stored procedures.
3215Calling stored procedures is currently not defined by the DBI.
3216Some drivers, such as DBD::Oracle, support it in non-portable ways.
3217See driver documentation for more details.)
3218
3219See also L</install_method> for how you can avoid needing to
3220use func() and gain.
3221
3222=item C<can>
3223
3224 $is_implemented = $h->can($method_name);
3225
3226Returns true if $method_name is implemented by the driver or a
3227default method is provided by the DBI.
3228It returns false where a driver hasn't implemented a method and the
3229default method is provided by the DBI is just an empty stub.
3230
3231=item C<parse_trace_flags>
3232
3233 $trace_settings_integer = $h->parse_trace_flags($trace_settings);
3234
3235Parses a string containing trace settings and returns the corresponding
3236integer value used internally by the DBI and drivers.
3237
3238The $trace_settings argument is a string containing a trace level
3239between 0 and 15 and/or trace flag names separated by vertical bar
3240("C<|>") or comma ("C<,>") characters. For example: C<"SQL|3|foo">.
3241
3242It uses the parse_trace_flag() method, described below, to process
3243the individual trage flag names.
3244
3245The parse_trace_flags() method was added in DBI 1.42.
3246
3247=item C<parse_trace_flag>
3248
3249 $bit_flag = $h->parse_trace_flag($trace_flag_name);
3250
3251Returns the bit flag corresponding to the trace flag name in
3252$trace_flag_name. Drivers are expected to override this method and
3253check if $trace_flag_name is a driver specific trace flags and, if
3254not, then call the DBIs default parse_trace_flag().
3255
3256The parse_trace_flag() method was added in DBI 1.42.
3257
3258=item C<private_attribute_info>
3259
3260 $hash_ref = $h->private_attribute_info();
3261
3262Returns a reference to a hash whose keys are the names of driver-private
3263attributes available for that kind of handle (driver, database, statement).
3264(The values should be undef. Meanings may be assigned to particular values in future.)
3265
3266=item C<swap_inner_handle>
3267
3268 $rc = $h1->swap_inner_handle( $h2 );
3269 $rc = $h1->swap_inner_handle( $h2, $allow_reparent );
3270
3271Brain transplants for handles. You don't need to know about this
3272unless you want to become a handle surgeon.
3273
3274A DBI handle is a reference to a tied hash. A tied hash has an
3275I<inner> hash that actually holds the contents. The swap_inner_handle()
3276method swaps the inner hashes between two handles. The $h1 and $h2
3277handles still point to the same tied hashes, but what those hashes
3278are tied to has been swapped. In effect $h1 I<becomes> $h2 and
3279vice-versa. This is powerful stuff, expect problems. Use with care.
3280
3281As a small safety measure, the two handles, $h1 and $h2, have to
3282share the same parent unless $allow_reparent is true.
3283
3284The swap_inner_handle() method was added in DBI 1.44.
3285
3286Here's a quick kind of 'diagram' as a worked example to help think about what's
3287happening:
3288
3289 Original state:
3290 dbh1o -> dbh1i
3291 sthAo -> sthAi(dbh1i)
3292 dbh2o -> dbh2i
3293
3294 swap_inner_handle dbh1o with dbh2o:
3295 dbh2o -> dbh1i
3296 sthAo -> sthAi(dbh1i)
3297 dbh1o -> dbh2i
3298
3299 create new sth from dbh1o:
3300 dbh2o -> dbh1i
3301 sthAo -> sthAi(dbh1i)
3302 dbh1o -> dbh2i
3303 sthBo -> sthBi(dbh2i)
3304
3305 swap_inner_handle sthAo with sthBo:
3306 dbh2o -> dbh1i
3307 sthBo -> sthAi(dbh1i)
3308 dbh1o -> dbh2i
3309 sthAo -> sthBi(dbh2i)
3310
3311=back
3312
3313
3314=head1 ATTRIBUTES COMMON TO ALL HANDLES
3315
3316These attributes are common to all types of DBI handles.
3317
3318Some attributes are inherited by child handles. That is, the value
3319of an inherited attribute in a newly created statement handle is the
3320same as the value in the parent database handle. Changes to attributes
3321in the new statement handle do not affect the parent database handle
3322and changes to the database handle do not affect existing statement
3323handles, only future ones.
3324
3325Attempting to set or get the value of an unknown attribute generates a warning,
3326except for private driver specific attributes (which all have names
3327starting with a lowercase letter).
3328
3329Example:
3330
3331 $h->{AttributeName} = ...; # set/write
3332 ... = $h->{AttributeName}; # get/read
3333
3334=over 4
3335
3336=item C<Warn> (boolean, inherited)
3337
3338The C<Warn> attribute enables useful warnings for certain bad
3339practices. It is enabled by default and should only be disabled in
3340rare circumstances. Since warnings are generated using the Perl
3341C<warn> function, they can be intercepted using the Perl C<$SIG{__WARN__}>
3342hook.
3343
3344The C<Warn> attribute is not related to the C<PrintWarn> attribute.
3345
3346=item C<Active> (boolean, read-only)
3347
3348The C<Active> attribute is true if the handle object is "active". This is rarely used in
3349applications. The exact meaning of active is somewhat vague at the
3350moment. For a database handle it typically means that the handle is
3351connected to a database (C<$dbh-E<gt>disconnect> sets C<Active> off). For
3352a statement handle it typically means that the handle is a C<SELECT>
3353that may have more data to fetch. (Fetching all the data or calling C<$sth-E<gt>finish>
3354sets C<Active> off.)
3355
3356=item C<Executed> (boolean)
3357
3358The C<Executed> attribute is true if the handle object has been "executed".
3359Currently only the $dbh do() method and the $sth execute(), execute_array(),
3360and execute_for_fetch() methods set the C<Executed> attribute.
3361
3362When it's set on a handle it is also set on the parent handle at the
3363same time. So calling execute() on a $sth also sets the C<Executed>
3364attribute on the parent $dbh.
3365
3366The C<Executed> attribute for a database handle is cleared by the
3367commit() and rollback() methods. The C<Executed> attribute of a
3368statement handle is not cleared by the DBI under any circumstances
3369and so acts as a permanent record of whether the statement handle
3370was ever used.
3371
3372The C<Executed> attribute was added in DBI 1.41.
3373
3374=item C<Kids> (integer, read-only)
3375
3376For a driver handle, C<Kids> is the number of currently existing database
3377handles that were created from that driver handle. For a database
3378handle, C<Kids> is the number of currently existing statement handles that
3379were created from that database handle.
3380For a statement handle, the value is zero.
3381
3382=item C<ActiveKids> (integer, read-only)
3383
3384Like C<Kids>, but only counting those that are C<Active> (as above).
3385
3386=item C<CachedKids> (hash ref)
3387
3388For a database handle, C<CachedKids> returns a reference to the cache (hash) of
3389statement handles created by the L</prepare_cached> method. For a
3390driver handle, returns a reference to the cache (hash) of
3391database handles created by the L</connect_cached> method.
3392
3393=item C<Type> (scalar, read-only)
3394
3395The C<Type> attribute identifies the type of a DBI handle. Returns
3396"dr" for driver handles, "db" for database handles and "st" for
3397statement handles.
3398
3399=item C<ChildHandles> (array ref)
3400
3401The ChildHandles attribute contains a reference to an array of all the
3402handles created by this handle which are still accessible. The
3403contents of the array are weak-refs and will become undef when the
3404handle goes out of scope.
3405
3406C<ChildHandles> returns undef if your perl version does not support weak
3407references (check the L<Scalar::Util|Scalar::Util> module). The referenced
3408array returned should be treated as read-only.
3409
3410For example, to enumerate all driver handles, database handles and
3411statement handles:
3412
3413 sub show_child_handles {
3414 my ($h, $level) = @_;
3415 $level ||= 0;
3416 printf "%sh %s %s\n", $h->{Type}, "\t" x $level, $h;
3417 show_child_handles($_, $level + 1)
3418 for (grep { defined } @{$h->{ChildHandles}});
3419 }
3420
3421 my %drivers = DBI->installed_drivers();
3422 show_child_handles($_) for (values %drivers);
3423
3424=item C<CompatMode> (boolean, inherited)
3425
3426The C<CompatMode> attribute is used by emulation layers (such as
3427Oraperl) to enable compatible behaviour in the underlying driver
3428(e.g., DBD::Oracle) for this handle. Not normally set by application code.
3429
3430It also has the effect of disabling the 'quick FETCH' of attribute
3431values from the handles attribute cache. So all attribute values
3432are handled by the drivers own FETCH method. This makes them slightly
3433slower but is useful for special-purpose drivers like DBD::Multiplex.
3434
3435=item C<InactiveDestroy> (boolean)
3436
3437The default value, false, means a handle will be fully destroyed
3438as normal when the last reference to it is removed, just as you'd expect.
3439
3440If set true then the handle will be treated by the DESTROY as if it was no
3441longer Active, and so the I<database engine> related effects of DESTROYing a
3442handle will be skipped.
3443
3444Think of the name as meaning 'treat the handle as not-Active in the DESTROY
3445method'.
3446
3447For a database handle, this attribute does not disable an I<explicit>
3448call to the disconnect method, only the implicit call from DESTROY
3449that happens if the handle is still marked as C<Active>.
3450
3451This attribute is specifically designed for use in Unix applications
3452that "fork" child processes. Either the parent or the child process,
3453but not both, should set C<InactiveDestroy> true on all their shared handles.
3454(Note that some databases, including Oracle, don't support passing a
3455database connection across a fork.)
3456
3457To help tracing applications using fork the process id is shown in
3458the trace log whenever a DBI or handle trace() method is called.
3459The process id also shown for I<every> method call if the DBI trace
3460level (not handle trace level) is set high enough to show the trace
3461from the DBI's method dispatcher, e.g. >= 9.
3462
3463=item C<PrintWarn> (boolean, inherited)
3464
3465The C<PrintWarn> attribute controls the printing of warnings recorded
3466by the driver. When set to a true value the DBI will check method
3467calls to see if a warning condition has been set. If so, the DBI
3468will effectively do a C<warn("$class $method warning: $DBI::errstr")>
3469where C<$class> is the driver class and C<$method> is the name of
3470the method which failed. E.g.,
3471
3472 DBD::Oracle::db execute warning: ... warning text here ...
3473
3474By default, C<DBI-E<gt>connect> sets C<PrintWarn> "on" if $^W is true,
3475i.e., perl is running with warnings enabled.
3476
3477If desired, the warnings can be caught and processed using a C<$SIG{__WARN__}>
3478handler or modules like CGI::Carp and CGI::ErrorWrap.
3479
3480See also L</set_err> for how warnings are recorded and L</HandleSetErr>
3481for how to influence it.
3482
3483Fetching the full details of warnings can require an extra round-trip
3484to the database server for some drivers. In which case the driver
3485may opt to only fetch the full details of warnings if the C<PrintWarn>
3486attribute is true. If C<PrintWarn> is false then these drivers should
3487still indicate the fact that there were warnings by setting the
3488warning string to, for example: "3 warnings".
3489
3490=item C<PrintError> (boolean, inherited)
3491
3492The C<PrintError> attribute can be used to force errors to generate warnings (using
3493C<warn>) in addition to returning error codes in the normal way. When set
3494"on", any method which results in an error occuring will cause the DBI to
3495effectively do a C<warn("$class $method failed: $DBI::errstr")> where C<$class>
3496is the driver class and C<$method> is the name of the method which failed. E.g.,
3497
3498 DBD::Oracle::db prepare failed: ... error text here ...
3499
3500By default, C<DBI-E<gt>connect> sets C<PrintError> "on".
3501
3502If desired, the warnings can be caught and processed using a C<$SIG{__WARN__}>
3503handler or modules like CGI::Carp and CGI::ErrorWrap.
3504
3505=item C<RaiseError> (boolean, inherited)
3506
3507The C<RaiseError> attribute can be used to force errors to raise exceptions rather
3508than simply return error codes in the normal way. It is "off" by default.
3509When set "on", any method which results in an error will cause
3510the DBI to effectively do a C<die("$class $method failed: $DBI::errstr")>,
3511where C<$class> is the driver class and C<$method> is the name of the method
3512that failed. E.g.,
3513
3514 DBD::Oracle::db prepare failed: ... error text here ...
3515
3516If you turn C<RaiseError> on then you'd normally turn C<PrintError> off.
3517If C<PrintError> is also on, then the C<PrintError> is done first (naturally).
3518
3519Typically C<RaiseError> is used in conjunction with C<eval { ... }>
3520to catch the exception that's been thrown and followed by an
3521C<if ($@) { ... }> block to handle the caught exception.
3522For example:
3523
3524 eval {
3525 ...
3526 $sth->execute();
3527 ...
3528 };
3529 if ($@) {
3530 # $sth->err and $DBI::err will be true if error was from DBI
3531 warn $@; # print the error
3532 ... # do whatever you need to deal with the error
3533 }
3534
3535In that eval block the $DBI::lasth variable can be useful for
3536diagnosis and reporting if you can't be sure which handle triggered
3537the error. For example, $DBI::lasth->{Type} and $DBI::lasth->{Statement}.
3538
3539See also L</Transactions>.
3540
3541If you want to temporarily turn C<RaiseError> off (inside a library function
3542that is likely to fail, for example), the recommended way is like this:
3543
3544 {
3545 local $h->{RaiseError}; # localize and turn off for this block
3546 ...
3547 }
3548
3549The original value will automatically and reliably be restored by Perl,
3550regardless of how the block is exited.
3551The same logic applies to other attributes, including C<PrintError>.
3552
3553=item C<HandleError> (code ref, inherited)
3554
3555The C<HandleError> attribute can be used to provide your own alternative behaviour
3556in case of errors. If set to a reference to a subroutine then that
3557subroutine is called when an error is detected (at the same point that
3558C<RaiseError> and C<PrintError> are handled).
3559
3560The subroutine is called with three parameters: the error message
3561string that C<RaiseError> and C<PrintError> would use,
3562the DBI handle being used, and the first value being returned by
3563the method that failed (typically undef).
3564
3565If the subroutine returns a false value then the C<RaiseError>
3566and/or C<PrintError> attributes are checked and acted upon as normal.
3567
3568For example, to C<die> with a full stack trace for any error:
3569
3570 use Carp;
3571 $h->{HandleError} = sub { confess(shift) };
3572
3573Or to turn errors into exceptions:
3574
3575 use Exception; # or your own favourite exception module
3576 $h->{HandleError} = sub { Exception->new('DBI')->raise($_[0]) };
3577
3578It is possible to 'stack' multiple HandleError handlers by using
3579closures:
3580
3581 sub your_subroutine {
3582 my $previous_handler = $h->{HandleError};
3583 $h->{HandleError} = sub {
3584 return 1 if $previous_handler and &$previous_handler(@_);
3585 ... your code here ...
3586 };
3587 }
3588
3589Using a C<my> inside a subroutine to store the previous C<HandleError>
3590value is important. See L<perlsub> and L<perlref> for more information
3591about I<closures>.
3592
3593It is possible for C<HandleError> to alter the error message that
3594will be used by C<RaiseError> and C<PrintError> if it returns false.
3595It can do that by altering the value of $_[0]. This example appends
3596a stack trace to all errors and, unlike the previous example using
3597Carp::confess, this will work C<PrintError> as well as C<RaiseError>:
3598
3599 $h->{HandleError} = sub { $_[0]=Carp::longmess($_[0]); 0; };
3600
3601It is also possible for C<HandleError> to hide an error, to a limited
3602degree, by using L</set_err> to reset $DBI::err and $DBI::errstr,
3603and altering the return value of the failed method. For example:
3604
3605 $h->{HandleError} = sub {
3606 return 0 unless $_[0] =~ /^\S+ fetchrow_arrayref failed:/;
3607 return 0 unless $_[1]->err == 1234; # the error to 'hide'
3608 $h->set_err(undef,undef); # turn off the error
3609 $_[2] = [ ... ]; # supply alternative return value
3610 return 1;
3611 };
3612
3613This only works for methods which return a single value and is hard
3614to make reliable (avoiding infinite loops, for example) and so isn't
3615recommended for general use! If you find a I<good> use for it then
3616please let me know.
3617
3618=item C<HandleSetErr> (code ref, inherited)
3619
3620The C<HandleSetErr> attribute can be used to intercept
3621the setting of handle C<err>, C<errstr>, and C<state> values.
3622If set to a reference to a subroutine then that subroutine is called
3623whenever set_err() is called, typically by the driver or a subclass.
3624
3625The subroutine is called with five arguments, the first five that
3626were passed to set_err(): the handle, the C<err>, C<errstr>, and
3627C<state> values being set, and the method name. These can be altered
3628by changing the values in the @_ array. The return value affects
3629set_err() behaviour, see L</set_err> for details.
3630
3631It is possible to 'stack' multiple HandleSetErr handlers by using
3632closures. See L</HandleError> for an example.
3633
3634The C<HandleSetErr> and C<HandleError> subroutines differ in subtle
3635but significant ways. HandleError is only invoked at the point where
3636the DBI is about to return to the application with C<err> set true.
3637It's not invoked by the failure of a method that's been called by
3638another DBI method. HandleSetErr, on the other hand, is called
3639whenever set_err() is called with a defined C<err> value, even if false.
3640So it's not just for errors, despite the name, but also warn and info states.
3641The set_err() method, and thus HandleSetErr, may be called multiple
3642times within a method and is usually invoked from deep within driver code.
3643
3644In theory a driver can use the return value from HandleSetErr via
3645set_err() to decide whether to continue or not. If set_err() returns
3646an empty list, indicating that the HandleSetErr code has 'handled'
3647the 'error', the driver could then continue instead of failing (if
3648that's a reasonable thing to do). This isn't excepted to be
3649common and any such cases should be clearly marked in the driver
3650documentation and discussed on the dbi-dev mailing list.
3651
3652The C<HandleSetErr> attribute was added in DBI 1.41.
3653
3654=item C<ErrCount> (unsigned integer)
3655
3656The C<ErrCount> attribute is incremented whenever the set_err()
3657method records an error. It isn't incremented by warnings or
3658information states. It is not reset by the DBI at any time.
3659
3660The C<ErrCount> attribute was added in DBI 1.41. Older drivers may
3661not have been updated to use set_err() to record errors and so this
3662attribute may not be incremented when using them.
3663
3664
3665=item C<ShowErrorStatement> (boolean, inherited)
3666
3667The C<ShowErrorStatement> attribute can be used to cause the relevant
3668Statement text to be appended to the error messages generated by
3669the C<RaiseError>, C<PrintError>, and C<PrintWarn> attributes.
3670Only applies to errors on statement handles
3671plus the prepare(), do(), and the various C<select*()> database handle methods.
3672(The exact format of the appended text is subject to change.)
3673
3674If C<$h-E<gt>{ParamValues}> returns a hash reference of parameter
3675(placeholder) values then those are formatted and appended to the
3676end of the Statement text in the error message.
3677
3678=item C<TraceLevel> (integer, inherited)
3679
3680The C<TraceLevel> attribute can be used as an alternative to the
3681L</trace> method to set the DBI trace level and trace flags for a
3682specific handle. See L</TRACING> for more details.
3683
3684The C<TraceLevel> attribute is especially useful combined with
3685C<local> to alter the trace settings for just a single block of code.
3686
3687=item C<FetchHashKeyName> (string, inherited)
3688
3689The C<FetchHashKeyName> attribute is used to specify whether the fetchrow_hashref()
3690method should perform case conversion on the field names used for
3691the hash keys. For historical reasons it defaults to 'C<NAME>' but
3692it is recommended to set it to 'C<NAME_lc>' (convert to lower case)
3693or 'C<NAME_uc>' (convert to upper case) according to your preference.
3694It can only be set for driver and database handles. For statement
3695handles the value is frozen when prepare() is called.
3696
3697
3698=item C<ChopBlanks> (boolean, inherited)
3699
3700The C<ChopBlanks> attribute can be used to control the trimming of trailing space
3701characters from fixed width character (CHAR) fields. No other field
3702types are affected, even where field values have trailing spaces.
3703
3704The default is false (although it is possible that the default may change).
3705Applications that need specific behaviour should set the attribute as
3706needed.
3707
3708Drivers are not required to support this attribute, but any driver which
3709does not support it must arrange to return C<undef> as the attribute value.
3710
3711
3712=item C<LongReadLen> (unsigned integer, inherited)
3713
3714The C<LongReadLen> attribute may be used to control the maximum
3715length of 'long' type fields (LONG, BLOB, CLOB, MEMO, etc.) which the driver will
3716read from the database automatically when it fetches each row of data.
3717
3718The C<LongReadLen> attribute only relates to fetching and reading
3719long values; it is not involved in inserting or updating them.
3720
3721A value of 0 means not to automatically fetch any long data.
3722Drivers may return undef or an empty string for long fields when
3723C<LongReadLen> is 0.
3724
3725The default is typically 0 (zero) bytes but may vary between drivers.
3726Applications fetching long fields should set this value to slightly
3727larger than the longest long field value to be fetched.
3728
3729Some databases return some long types encoded as pairs of hex digits.
3730For these types, C<LongReadLen> relates to the underlying data
3731length and not the doubled-up length of the encoded string.
3732
3733Changing the value of C<LongReadLen> for a statement handle after it
3734has been C<prepare>'d will typically have no effect, so it's common to
3735set C<LongReadLen> on the C<$dbh> before calling C<prepare>.
3736
3737For most drivers the value used here has a direct effect on the
3738memory used by the statement handle while it's active, so don't be
3739too generous. If you can't be sure what value to use you could
3740execute an extra select statement to determine the longest value.
3741For example:
3742
3743 $dbh->{LongReadLen} = $dbh->selectrow_array(qq{
3744 SELECT MAX(OCTET_LENGTH(long_column_name))
3745 FROM table WHERE ...
3746 });
3747 $sth = $dbh->prepare(qq{
3748 SELECT long_column_name, ... FROM table WHERE ...
3749 });
3750
3751You may need to take extra care if the table can be modified between
3752the first select and the second being executed. You may also need to
3753use a different function if OCTET_LENGTH() does not work for long
3754types in your database. For example, for Sybase use DATALENGTH() and
3755for Oracle use LENGTHB().
3756
3757See also L</LongTruncOk> for information on truncation of long types.
3758
3759=item C<LongTruncOk> (boolean, inherited)
3760
3761The C<LongTruncOk> attribute may be used to control the effect of
3762fetching a long field value which has been truncated (typically
3763because it's longer than the value of the C<LongReadLen> attribute).
3764
3765By default, C<LongTruncOk> is false and so fetching a long value that
3766needs to be truncated will cause the fetch to fail.
3767(Applications should always be sure to
3768check for errors after a fetch loop in case an error, such as a divide
3769by zero or long field truncation, caused the fetch to terminate
3770prematurely.)
3771
3772If a fetch fails due to a long field truncation when C<LongTruncOk> is
3773false, many drivers will allow you to continue fetching further rows.
3774
3775See also L</LongReadLen>.
3776
3777=item C<TaintIn> (boolean, inherited)
3778
3779If the C<TaintIn> attribute is set to a true value I<and> Perl is running in
3780taint mode (e.g., started with the C<-T> option), then all the arguments
3781to most DBI method calls are checked for being tainted. I<This may change.>
3782
3783The attribute defaults to off, even if Perl is in taint mode.
3784See L<perlsec> for more about taint mode. If Perl is not
3785running in taint mode, this attribute has no effect.
3786
3787When fetching data that you trust you can turn off the TaintIn attribute,
3788for that statement handle, for the duration of the fetch loop.
3789
3790The C<TaintIn> attribute was added in DBI 1.31.
3791
3792=item C<TaintOut> (boolean, inherited)
3793
3794If the C<TaintOut> attribute is set to a true value I<and> Perl is running in
3795taint mode (e.g., started with the C<-T> option), then most data fetched
3796from the database is considered tainted. I<This may change.>
3797
3798The attribute defaults to off, even if Perl is in taint mode.
3799See L<perlsec> for more about taint mode. If Perl is not
3800running in taint mode, this attribute has no effect.
3801
3802When fetching data that you trust you can turn off the TaintOut attribute,
3803for that statement handle, for the duration of the fetch loop.
3804
3805Currently only fetched data is tainted. It is possible that the results
3806of other DBI method calls, and the value of fetched attributes, may
3807also be tainted in future versions. That change may well break your
3808applications unless you take great care now. If you use DBI Taint mode,
3809please report your experience and any suggestions for changes.
3810
3811The C<TaintOut> attribute was added in DBI 1.31.
3812
3813=item C<Taint> (boolean, inherited)
3814
3815The C<Taint> attribute is a shortcut for L</TaintIn> and L</TaintOut> (it is also present
3816for backwards compatibility).
3817
3818Setting this attribute sets both L</TaintIn> and L</TaintOut>, and retrieving
3819it returns a true value if and only if L</TaintIn> and L</TaintOut> are
3820both set to true values.
3821
3822=item C<Profile> (inherited)
3823
3824The C<Profile> attribute enables the collection and reporting of method call timing statistics.
3825See the L<DBI::Profile> module documentation for I<much> more detail.
3826
3827The C<Profile> attribute was added in DBI 1.24.
3828
3829=item C<private_your_module_name_*>
3830
3831The DBI provides a way to store extra information in a DBI handle as
3832"private" attributes. The DBI will allow you to store and retrieve any
3833attribute which has a name starting with "C<private_>".
3834
3835It is I<strongly> recommended that you use just I<one> private
3836attribute (e.g., use a hash ref) I<and> give it a long and unambiguous
3837name that includes the module or application name that the attribute
3838relates to (e.g., "C<private_YourFullModuleName_thingy>").
3839
3840Because of the way the Perl tie mechanism works you cannot reliably
3841use the C<||=> operator directly to initialise the attribute, like this:
3842
3843 my $foo = $dbh->{private_yourmodname_foo} ||= { ... }; # WRONG
3844
3845you should use a two step approach like this:
3846
3847 my $foo = $dbh->{private_yourmodname_foo};
3848 $foo ||= $dbh->{private_yourmodname_foo} = { ... };
3849
3850This attribute is primarily of interest to people sub-classing DBI.
3851
3852=back
3853
3854
3855=head1 DBI DATABASE HANDLE OBJECTS
3856
3857This section covers the methods and attributes associated with
3858database handles.
3859
3860=head2 Database Handle Methods
3861
3862The following methods are specified for DBI database handles:
3863
3864=over 4
3865
3866=item C<clone>
3867
3868 $new_dbh = $dbh->clone();
3869 $new_dbh = $dbh->clone(\%attr);
3870
3871The C<clone> method duplicates the $dbh connection by connecting
3872with the same parameters ($dsn, $user, $password) as originally used.
3873
3874The attributes for the cloned connect are the same as those used
3875for the original connect, with some other attribute merged over
3876them depending on the \%attr parameter.
3877
3878If \%attr is given then the attributes it contains are merged into
3879the original attributes and override any with the same names.
3880Effectively the same as doing:
3881
3882 %attribues_used = ( %original_attributes, %attr );
3883
3884If \%attr is not given then it defaults to a hash containing all
3885the attributes in the attribute cache of $dbh excluding any non-code
3886references, plus the main boolean attributes (RaiseError, PrintError,
3887AutoCommit, etc.). This behaviour is subject to change.
3888
3889The clone method can be used even if the database handle is disconnected.
3890
3891The C<clone> method was added in DBI 1.33. It is very new and likely
3892to change.
3893
3894=item C<data_sources>
3895
3896 @ary = $dbh->data_sources();
3897 @ary = $dbh->data_sources(\%attr);
3898
3899Returns a list of data sources (databases) available via the $dbh
3900driver's data_sources() method, plus any extra data sources that
3901the driver can discover via the connected $dbh. Typically the extra
3902data sources are other databases managed by the same server process
3903that the $dbh is connected to.
3904
3905Data sources are returned in a form suitable for passing to the
3906L</connect> method (that is, they will include the "C<dbi:$driver:>" prefix).
3907
3908The data_sources() method, for a $dbh, was added in DBI 1.38.
3909
3910=item C<do>
3911
3912 $rows = $dbh->do($statement) or die $dbh->errstr;
3913 $rows = $dbh->do($statement, \%attr) or die $dbh->errstr;
3914 $rows = $dbh->do($statement, \%attr, @bind_values) or die ...
3915
3916Prepare and execute a single statement. Returns the number of rows
3917affected or C<undef> on error. A return value of C<-1> means the
3918number of rows is not known, not applicable, or not available.
3919
3920This method is typically most useful for I<non>-C<SELECT> statements that
3921either cannot be prepared in advance (due to a limitation of the
3922driver) or do not need to be executed repeatedly. It should not
3923be used for C<SELECT> statements because it does not return a statement
3924handle (so you can't fetch any data).
3925
3926The default C<do> method is logically similar to:
3927
3928 sub do {
3929 my($dbh, $statement, $attr, @bind_values) = @_;
3930 my $sth = $dbh->prepare($statement, $attr) or return undef;
3931 $sth->execute(@bind_values) or return undef;
3932 my $rows = $sth->rows;
3933 ($rows == 0) ? "0E0" : $rows; # always return true if no error
3934 }
3935
3936For example:
3937
3938 my $rows_deleted = $dbh->do(q{
3939 DELETE FROM table
3940 WHERE status = ?
3941 }, undef, 'DONE') or die $dbh->errstr;
3942
3943Using placeholders and C<@bind_values> with the C<do> method can be
3944useful because it avoids the need to correctly quote any variables
3945in the C<$statement>. But if you'll be executing the statement many
3946times then it's more efficient to C<prepare> it once and call
3947C<execute> many times instead.
3948
3949The C<q{...}> style quoting used in this example avoids clashing with
3950quotes that may be used in the SQL statement. Use the double-quote-like
3951C<qq{...}> operator if you want to interpolate variables into the string.
3952See L<perlop/"Quote and Quote-like Operators"> for more details.
3953
3954=item C<last_insert_id>
3955
3956 $rv = $dbh->last_insert_id($catalog, $schema, $table, $field);
3957 $rv = $dbh->last_insert_id($catalog, $schema, $table, $field, \%attr);
3958
3959Returns a value 'identifying' the row just inserted, if possible.
3960Typically this would be a value assigned by the database server
3961to a column with an I<auto_increment> or I<serial> type.
3962Returns undef if the driver does not support the method or can't
3963determine the value.
3964
3965The $catalog, $schema, $table, and $field parameters may be required
3966for some drivers (see below). If you don't know the parameter values
3967and your driver does not need them, then use C<undef> for each.
3968
3969There are several caveats to be aware of with this method if you want
3970to use it for portable applications:
3971
3972B<*> For some drivers the value may only available immediately after
3973the insert statement has executed (e.g., mysql, Informix).
3974
3975B<*> For some drivers the $catalog, $schema, $table, and $field parameters
3976are required, for others they are ignored (e.g., mysql).
3977
3978B<*> Drivers may return an indeterminate value if no insert has
3979been performed yet.
3980
3981B<*> For some drivers the value may only be available if placeholders
3982have I<not> been used (e.g., Sybase, MS SQL). In this case the value
3983returned would be from the last non-placeholder insert statement.
3984
3985B<*> Some drivers may need driver-specific hints about how to get
3986the value. For example, being told the name of the database 'sequence'
3987object that holds the value. Any such hints are passed as driver-specific
3988attributes in the \%attr parameter.
3989
3990B<*> If the underlying database offers nothing better, then some
3991drivers may attempt to implement this method by executing
3992"C<select max($field) from $table>". Drivers using any approach
3993like this should issue a warning if C<AutoCommit> is true because
3994it is generally unsafe - another process may have modified the table
3995between your insert and the select. For situations where you know
3996it is safe, such as when you have locked the table, you can silence
3997the warning by passing C<Warn> => 0 in \%attr.
3998
3999B<*> If no insert has been performed yet, or the last insert failed,
4000then the value is implementation defined.
4001
4002Given all the caveats above, it's clear that this method must be
4003used with care.
4004
4005The C<last_insert_id> method was added in DBI 1.38.
4006
4007=item C<selectrow_array>
4008
4009 @row_ary = $dbh->selectrow_array($statement);
4010 @row_ary = $dbh->selectrow_array($statement, \%attr);
4011 @row_ary = $dbh->selectrow_array($statement, \%attr, @bind_values);
4012
4013This utility method combines L</prepare>, L</execute> and
4014L</fetchrow_array> into a single call. If called in a list context, it
4015returns the first row of data from the statement. The C<$statement>
4016parameter can be a previously prepared statement handle, in which case
4017the C<prepare> is skipped.
4018
4019If any method fails, and L</RaiseError> is not set, C<selectrow_array>
4020will return an empty list.
4021
4022If called in a scalar context for a statement handle that has more
4023than one column, it is undefined whether the driver will return
4024the value of the first column or the last. So don't do that.
4025Also, in a scalar context, an C<undef> is returned if there are no
4026more rows or if an error occurred. That C<undef> can't be distinguished
4027from an C<undef> returned because the first field value was NULL.
4028For these reasons you should exercise some caution if you use
4029C<selectrow_array> in a scalar context, or just don't do that.
4030
4031
4032=item C<selectrow_arrayref>
4033
4034 $ary_ref = $dbh->selectrow_arrayref($statement);
4035 $ary_ref = $dbh->selectrow_arrayref($statement, \%attr);
4036 $ary_ref = $dbh->selectrow_arrayref($statement, \%attr, @bind_values);
4037
4038This utility method combines L</prepare>, L</execute> and
4039L</fetchrow_arrayref> into a single call. It returns the first row of
4040data from the statement. The C<$statement> parameter can be a previously
4041prepared statement handle, in which case the C<prepare> is skipped.
4042
4043If any method fails, and L</RaiseError> is not set, C<selectrow_array>
4044will return undef.
4045
4046
4047=item C<selectrow_hashref>
4048
4049 $hash_ref = $dbh->selectrow_hashref($statement);
4050 $hash_ref = $dbh->selectrow_hashref($statement, \%attr);
4051 $hash_ref = $dbh->selectrow_hashref($statement, \%attr, @bind_values);
4052
4053This utility method combines L</prepare>, L</execute> and
4054L</fetchrow_hashref> into a single call. It returns the first row of
4055data from the statement. The C<$statement> parameter can be a previously
4056prepared statement handle, in which case the C<prepare> is skipped.
4057
4058If any method fails, and L</RaiseError> is not set, C<selectrow_hashref>
4059will return undef.
4060
4061
4062=item C<selectall_arrayref>
4063
4064 $ary_ref = $dbh->selectall_arrayref($statement);
4065 $ary_ref = $dbh->selectall_arrayref($statement, \%attr);
4066 $ary_ref = $dbh->selectall_arrayref($statement, \%attr, @bind_values);
4067
4068This utility method combines L</prepare>, L</execute> and
4069L</fetchall_arrayref> into a single call. It returns a reference to an
4070array containing a reference to an array (or hash, see below) for each row of
4071data fetched.
4072
4073The C<$statement> parameter can be a previously prepared statement handle,
4074in which case the C<prepare> is skipped. This is recommended if the
4075statement is going to be executed many times.
4076
4077If L</RaiseError> is not set and any method except C<fetchall_arrayref>
4078fails then C<selectall_arrayref> will return C<undef>; if
4079C<fetchall_arrayref> fails then it will return with whatever data
4080has been fetched thus far. You should check C<$sth-E<gt>err>
4081afterwards (or use the C<RaiseError> attribute) to discover if the data is
4082complete or was truncated due to an error.
4083
4084The L</fetchall_arrayref> method called by C<selectall_arrayref>
4085supports a $max_rows parameter. You can specify a value for $max_rows
4086by including a 'C<MaxRows>' attribute in \%attr. In which case finish()
4087is called for you after fetchall_arrayref() returns.
4088
4089The L</fetchall_arrayref> method called by C<selectall_arrayref>
4090also supports a $slice parameter. You can specify a value for $slice by
4091including a 'C<Slice>' or 'C<Columns>' attribute in \%attr. The only
4092difference between the two is that if C<Slice> is not defined and
4093C<Columns> is an array ref, then the array is assumed to contain column
4094index values (which count from 1), rather than perl array index values.
4095In which case the array is copied and each value decremented before
4096passing to C</fetchall_arrayref>.
4097
4098You may often want to fetch an array of rows where each row is stored as a
4099hash. That can be done simple using:
4100
4101 my $emps = $dbh->selectall_arrayref(
4102 "SELECT ename FROM emp ORDER BY ename",
4103 { Slice => {} }
4104 );
4105 foreach my $emp ( @$emps ) {
4106 print "Employee: $emp->{ename}\n";
4107 }
4108
4109Or, to fetch into an array instead of an array ref:
4110
4111 @result = @{ $dbh->selectall_arrayref($sql, { Slice => {} }) };
4112
4113See L</fetchall_arrayref> method for more details.
4114
4115=item C<selectall_hashref>
4116
4117 $hash_ref = $dbh->selectall_hashref($statement, $key_field);
4118 $hash_ref = $dbh->selectall_hashref($statement, $key_field, \%attr);
4119 $hash_ref = $dbh->selectall_hashref($statement, $key_field, \%attr, @bind_values);
4120
4121This utility method combines L</prepare>, L</execute> and
4122L</fetchall_hashref> into a single call. It returns a reference to a
4123hash containing one entry, at most, for each row, as returned by fetchall_hashref().
4124
4125The C<$statement> parameter can be a previously prepared statement handle,
4126in which case the C<prepare> is skipped. This is recommended if the
4127statement is going to be executed many times.
4128
4129The C<$key_field> parameter defines which column, or columns, are used as keys
4130in the returned hash. It can either be the name of a single field, or a
4131reference to an array containing multiple field names. Using multiple names
4132yields a tree of nested hashes.
4133
4134If a row has the same key as an earlier row then it replaces the earlier row.
4135
4136If any method except C<fetchrow_hashref> fails, and L</RaiseError> is not set,
4137C<selectall_hashref> will return C<undef>. If C<fetchrow_hashref> fails and
4138L</RaiseError> is not set, then it will return with whatever data it
4139has fetched thus far. $DBI::err should be checked to catch that.
4140
4141See fetchall_hashref() for more details.
4142
4143=item C<selectcol_arrayref>
4144
4145 $ary_ref = $dbh->selectcol_arrayref($statement);
4146 $ary_ref = $dbh->selectcol_arrayref($statement, \%attr);
4147 $ary_ref = $dbh->selectcol_arrayref($statement, \%attr, @bind_values);
4148
4149This utility method combines L</prepare>, L</execute>, and fetching one
4150column from all the rows, into a single call. It returns a reference to
4151an array containing the values of the first column from each row.
4152
4153The C<$statement> parameter can be a previously prepared statement handle,
4154in which case the C<prepare> is skipped. This is recommended if the
4155statement is going to be executed many times.
4156
4157If any method except C<fetch> fails, and L</RaiseError> is not set,
4158C<selectcol_arrayref> will return C<undef>. If C<fetch> fails and
4159L</RaiseError> is not set, then it will return with whatever data it
4160has fetched thus far. $DBI::err should be checked to catch that.
4161
4162The C<selectcol_arrayref> method defaults to pushing a single column
4163value (the first) from each row into the result array. However, it can
4164also push another column, or even multiple columns per row, into the
4165result array. This behaviour can be specified via a 'C<Columns>'
4166attribute which must be a ref to an array containing the column number
4167or numbers to use. For example:
4168
4169 # get array of id and name pairs:
4170 my $ary_ref = $dbh->selectcol_arrayref("select id, name from table", { Columns=>[1,2] });
4171 my %hash = @$ary_ref; # build hash from key-value pairs so $hash{$id} => name
4172
4173You can specify a maximum number of rows to fetch by including a
4174'C<MaxRows>' attribute in \%attr.
4175
4176=item C<prepare>
4177
4178 $sth = $dbh->prepare($statement) or die $dbh->errstr;
4179 $sth = $dbh->prepare($statement, \%attr) or die $dbh->errstr;
4180
4181Prepares a statement for later execution by the database
4182engine and returns a reference to a statement handle object.
4183
4184The returned statement handle can be used to get attributes of the
4185statement and invoke the L</execute> method. See L</Statement Handle Methods>.
4186
4187Drivers for engines without the concept of preparing a
4188statement will typically just store the statement in the returned
4189handle and process it when C<$sth-E<gt>execute> is called. Such drivers are
4190unlikely to give much useful information about the
4191statement, such as C<$sth-E<gt>{NUM_OF_FIELDS}>, until after C<$sth-E<gt>execute>
4192has been called. Portable applications should take this into account.
4193
4194In general, DBI drivers do not parse the contents of the statement
4195(other than simply counting any L</Placeholders>). The statement is
4196passed directly to the database engine, sometimes known as pass-thru
4197mode. This has advantages and disadvantages. On the plus side, you can
4198access all the functionality of the engine being used. On the downside,
4199you're limited if you're using a simple engine, and you need to take extra care if
4200writing applications intended to be portable between engines.
4201
4202Portable applications should not assume that a new statement can be
4203prepared and/or executed while still fetching results from a previous
4204statement.
4205
4206Some command-line SQL tools use statement terminators, like a semicolon,
4207to indicate the end of a statement. Such terminators should not normally
4208be used with the DBI.
4209
4210
4211=item C<prepare_cached>
4212
4213 $sth = $dbh->prepare_cached($statement)
4214 $sth = $dbh->prepare_cached($statement, \%attr)
4215 $sth = $dbh->prepare_cached($statement, \%attr, $if_active)
4216
4217Like L</prepare> except that the statement handle returned will be
4218stored in a hash associated with the C<$dbh>. If another call is made to
4219C<prepare_cached> with the same C<$statement> and C<%attr> parameter values,
4220then the corresponding cached C<$sth> will be returned without contacting the
4221database server.
4222
4223The C<$if_active> parameter lets you adjust the behaviour if an
4224already cached statement handle is still Active. There are several
4225alternatives:
4226
4227=over 4
4228
4229=item B<0>: A warning will be generated, and finish() will be called on
4230the statement handle before it is returned. This is the default
4231behaviour if $if_active is not passed.
4232
4233=item B<1>: finish() will be called on the statement handle, but the
4234warning is suppressed.
4235
4236=item B<2>: Disables any checking.
4237
4238=item B<3>: The existing active statement handle will be removed from the
4239cache and a new statement handle prepared and cached in its place.
4240This is the safest option because it doesn't affect the state of the
4241old handle, it just removes it from the cache. [Added in DBI 1.40]
4242
4243=back
4244
4245Here are some examples of C<prepare_cached>:
4246
4247 sub insert_hash {
4248 my ($table, $field_values) = @_;
4249 # sort to keep field order, and thus sql, stable for prepare_cached
4250 my @fields = sort keys %$field_values;
4251 my @values = @{$field_values}{@fields};
4252 my $sql = sprintf "insert into %s (%s) values (%s)",
4253 $table, join(",", @fields), join(",", ("?")x@fields);
4254 my $sth = $dbh->prepare_cached($sql);
4255 return $sth->execute(@values);
4256 }
4257
4258 sub search_hash {
4259 my ($table, $field_values) = @_;
4260 # sort to keep field order, and thus sql, stable for prepare_cached
4261 my @fields = sort keys %$field_values;
4262 my @values = @{$field_values}{@fields};
4263 my $qualifier = "";
4264 $qualifier = "where ".join(" and ", map { "$_=?" } @fields) if @fields;
4265 $sth = $dbh->prepare_cached("SELECT * FROM $table $qualifier");
4266 return $dbh->selectall_arrayref($sth, {}, @values);
4267 }
4268
4269I<Caveat emptor:> This caching can be useful in some applications,
4270but it can also cause problems and should be used with care. Here
4271is a contrived case where caching would cause a significant problem:
4272
4273 my $sth = $dbh->prepare_cached('SELECT * FROM foo WHERE bar=?');
4274 $sth->execute(...);
4275 while (my $data = $sth->fetchrow_hashref) {
4276
4277 # later, in some other code called within the loop...
4278 my $sth2 = $dbh->prepare_cached('SELECT * FROM foo WHERE bar=?');
4279 $sth2->execute(...);
4280 while (my $data2 = $sth2->fetchrow_arrayref) {
4281 do_stuff(...);
4282 }
4283 }
4284
4285In this example, since both handles are preparing the exact same statement,
4286C<$sth2> will not be its own statement handle, but a duplicate of C<$sth>
4287returned from the cache. The results will certainly not be what you expect.
4288Typically the the inner fetch loop will work normally, fetching all
4289the records and terminating when there are no more, but now $sth
4290is the same as $sth2 the outer fetch loop will also terminate.
4291
4292You'll know if you run into this problem because prepare_cached()
4293will generate a warning by default (when $if_active is false).
4294
4295The cache used by prepare_cached() is keyed by both the statement
4296and any attributes so you can also avoid this issue by doing something
4297like:
4298
4299 $sth = $dbh->prepare_cached("...", { dbi_dummy => __FILE__.__LINE__ });
4300
4301which will ensure that prepare_cached only returns statements cached
4302by that line of code in that source file.
4303
4304If you'd like the cache to managed intelligently, you can tie the
4305hashref returned by C<CachedKids> to an appropriate caching module,
4306such as L<Tie::Cache::LRU>:
4307
4308 my $cache = $dbh->{CachedKids};
4309 tie %$cache, 'Tie::Cache::LRU', 500;
4310
4311=item C<commit>
4312
4313 $rc = $dbh->commit or die $dbh->errstr;
4314
4315Commit (make permanent) the most recent series of database changes
4316if the database supports transactions and AutoCommit is off.
4317
4318If C<AutoCommit> is on, then calling
4319C<commit> will issue a "commit ineffective with AutoCommit" warning.
4320
4321See also L</Transactions> in the L</FURTHER INFORMATION> section below.
4322
4323=item C<rollback>
4324
4325 $rc = $dbh->rollback or die $dbh->errstr;
4326
4327Rollback (undo) the most recent series of uncommitted database
4328changes if the database supports transactions and AutoCommit is off.
4329
4330If C<AutoCommit> is on, then calling
4331C<rollback> will issue a "rollback ineffective with AutoCommit" warning.
4332
4333See also L</Transactions> in the L</FURTHER INFORMATION> section below.
4334
4335=item C<begin_work>
4336
4337 $rc = $dbh->begin_work or die $dbh->errstr;
4338
4339Enable transactions (by turning C<AutoCommit> off) until the next call
4340to C<commit> or C<rollback>. After the next C<commit> or C<rollback>,
4341C<AutoCommit> will automatically be turned on again.
4342
4343If C<AutoCommit> is already off when C<begin_work> is called then
4344it does nothing except return an error. If the driver does not support
4345transactions then when C<begin_work> attempts to set C<AutoCommit> off
4346the driver will trigger a fatal error.
4347
4348See also L</Transactions> in the L</FURTHER INFORMATION> section below.
4349
4350
4351=item C<disconnect>
4352
4353 $rc = $dbh->disconnect or warn $dbh->errstr;
4354
4355Disconnects the database from the database handle. C<disconnect> is typically only used
4356before exiting the program. The handle is of little use after disconnecting.
4357
4358The transaction behaviour of the C<disconnect> method is, sadly,
4359undefined. Some database systems (such as Oracle and Ingres) will
4360automatically commit any outstanding changes, but others (such as
4361Informix) will rollback any outstanding changes. Applications not
4362using C<AutoCommit> should explicitly call C<commit> or C<rollback> before
4363calling C<disconnect>.
4364
4365The database is automatically disconnected by the C<DESTROY> method if
4366still connected when there are no longer any references to the handle.
4367The C<DESTROY> method for each driver should implicitly call C<rollback> to
4368undo any uncommitted changes. This is vital behaviour to ensure that
4369incomplete transactions don't get committed simply because Perl calls
4370C<DESTROY> on every object before exiting. Also, do not rely on the order
4371of object destruction during "global destruction", as it is undefined.
4372
4373Generally, if you want your changes to be commited or rolled back when
4374you disconnect, then you should explicitly call L</commit> or L</rollback>
4375before disconnecting.
4376
4377If you disconnect from a database while you still have active
4378statement handles (e.g., SELECT statement handles that may have
4379more data to fetch), you will get a warning. The warning may indicate
4380that a fetch loop terminated early, perhaps due to an uncaught error.
4381To avoid the warning call the C<finish> method on the active handles.
4382
4383
4384=item C<ping>
4385
4386 $rc = $dbh->ping;
4387
4388Attempts to determine, in a reasonably efficient way, if the database
4389server is still running and the connection to it is still working.
4390Individual drivers should implement this function in the most suitable
4391manner for their database engine.
4392
4393The current I<default> implementation always returns true without
4394actually doing anything. Actually, it returns "C<0 but true>" which is
4395true but zero. That way you can tell if the return value is genuine or
4396just the default. Drivers should override this method with one that
4397does the right thing for their type of database.
4398
4399Few applications would have direct use for this method. See the specialized
4400Apache::DBI module for one example usage.
4401
4402
4403=item C<get_info>
4404
4405 $value = $dbh->get_info( $info_type );
4406
4407Returns information about the implementation, i.e. driver and data
4408source capabilities, restrictions etc. It returns C<undef> for
4409unknown or unimplemented information types. For example:
4410
4411 $database_version = $dbh->get_info( 18 ); # SQL_DBMS_VER
4412 $max_select_tables = $dbh->get_info( 106 ); # SQL_MAXIMUM_TABLES_IN_SELECT
4413
4414See L</"Standards Reference Information"> for more detailed information
4415about the information types and their meanings and possible return values.
4416
4417The DBI::Const::GetInfoType module exports a %GetInfoType hash that
4418can be used to map info type names to numbers. For example:
4419
4420 $database_version = $dbh->get_info( $GetInfoType{SQL_DBMS_VER} );
4421
4422The names are a merging of the ANSI and ODBC standards (which differ
4423in some cases). See L<DBI::Const::GetInfoType> for more details.
4424
4425Because some DBI methods make use of get_info(), drivers are strongly
4426encouraged to support I<at least> the following very minimal set
4427of information types to ensure the DBI itself works properly:
4428
4429 Type Name Example A Example B
4430 ---- -------------------------- ------------ ----------------
4431 17 SQL_DBMS_NAME 'ACCESS' 'Oracle'
4432 18 SQL_DBMS_VER '03.50.0000' '08.01.0721 ...'
4433 29 SQL_IDENTIFIER_QUOTE_CHAR '`' '"'
4434 41 SQL_CATALOG_NAME_SEPARATOR '.' '@'
4435 114 SQL_CATALOG_LOCATION 1 2
4436
4437=item C<table_info>
4438
4439 $sth = $dbh->table_info( $catalog, $schema, $table, $type );
4440 $sth = $dbh->table_info( $catalog, $schema, $table, $type, \%attr );
4441
4442 # then $sth->fetchall_arrayref or $sth->fetchall_hashref etc
4443
4444Returns an active statement handle that can be used to fetch
4445information about tables and views that exist in the database.
4446
4447The arguments $catalog, $schema and $table may accept search patterns
4448according to the database/driver, for example: $table = '%FOO%';
4449Remember that the underscore character ('C<_>') is a search pattern
4450that means match any character, so 'FOO_%' is the same as 'FOO%'
4451and 'FOO_BAR%' will match names like 'FOO1BAR'.
4452
4453The value of $type is a comma-separated list of one or more types of
4454tables to be returned in the result set. Each value may optionally be
4455quoted, e.g.:
4456
4457 $type = "TABLE";
4458 $type = "'TABLE','VIEW'";
4459
4460In addition the following special cases may also be supported by some drivers:
4461
4462=over 4
4463
4464=item *
4465If the value of $catalog is '%' and $schema and $table name
4466are empty strings, the result set contains a list of catalog names.
4467For example:
4468
4469 $sth = $dbh->table_info('%', '', '');
4470
4471=item *
4472If the value of $schema is '%' and $catalog and $table are empty
4473strings, the result set contains a list of schema names.
4474
4475=item *
4476If the value of $type is '%' and $catalog, $schema, and $table are all
4477empty strings, the result set contains a list of table types.
4478
4479=back
4480
4481If your driver doesn't support one or more of the selection filter
4482parameters then you may get back more than you asked for and can
4483do the filtering yourself.
4484
4485This method can be expensive, and can return a large amount of data.
4486(For example, small Oracle installation returns over 2000 rows.)
4487So it's a good idea to use the filters to limit the data as much as possible.
4488
4489The statement handle returned has at least the following fields in the
4490order show below. Other fields, after these, may also be present.
4491
4492B<TABLE_CAT>: Table catalog identifier. This field is NULL (C<undef>) if not
4493applicable to the data source, which is usually the case. This field
4494is empty if not applicable to the table.
4495
4496B<TABLE_SCHEM>: The name of the schema containing the TABLE_NAME value.
4497This field is NULL (C<undef>) if not applicable to data source, and
4498empty if not applicable to the table.
4499
4500B<TABLE_NAME>: Name of the table (or view, synonym, etc).
4501
4502B<TABLE_TYPE>: One of the following: "TABLE", "VIEW", "SYSTEM TABLE",
4503"GLOBAL TEMPORARY", "LOCAL TEMPORARY", "ALIAS", "SYNONYM" or a type
4504identifier that is specific to the data
4505source.
4506
4507B<REMARKS>: A description of the table. May be NULL (C<undef>).
4508
4509Note that C<table_info> might not return records for all tables.
4510Applications can use any valid table regardless of whether it's
4511returned by C<table_info>.
4512
4513See also L</tables>, L</"Catalog Methods"> and
4514L</"Standards Reference Information">.
4515
4516=item C<column_info>
4517
4518 $sth = $dbh->column_info( $catalog, $schema, $table, $column );
4519
4520 # then $sth->fetchall_arrayref or $sth->fetchall_hashref etc
4521
4522Returns an active statement handle that can be used to fetch
4523information about columns in specified tables.
4524
4525The arguments $schema, $table and $column may accept search patterns
4526according to the database/driver, for example: $table = '%FOO%';
4527
4528Note: The support for the selection criteria is driver specific. If the
4529driver doesn't support one or more of them then you may get back more
4530than you asked for and can do the filtering yourself.
4531
4532If the arguments don't match any tables then you'll still get a statement
4533handle, it'll just return no rows.
4534
4535The statement handle returned has at least the following fields in the
4536order shown below. Other fields, after these, may also be present.
4537
4538B<TABLE_CAT>: The catalog identifier.
4539This field is NULL (C<undef>) if not applicable to the data source,
4540which is often the case. This field is empty if not applicable to the
4541table.
4542
4543B<TABLE_SCHEM>: The schema identifier.
4544This field is NULL (C<undef>) if not applicable to the data source,
4545and empty if not applicable to the table.
4546
4547B<TABLE_NAME>: The table identifier.
4548Note: A driver may provide column metadata not only for base tables, but
4549also for derived objects like SYNONYMS etc.
4550
4551B<COLUMN_NAME>: The column identifier.
4552
4553B<DATA_TYPE>: The concise data type code.
4554
4555B<TYPE_NAME>: A data source dependent data type name.
4556
4557B<COLUMN_SIZE>: The column size.
4558This is the maximum length in characters for character data types,
4559the number of digits or bits for numeric data types or the length
4560in the representation of temporal types.
4561See the relevant specifications for detailed information.
4562
4563B<BUFFER_LENGTH>: The length in bytes of transferred data.
4564
4565B<DECIMAL_DIGITS>: The total number of significant digits to the right of
4566the decimal point.
4567
4568B<NUM_PREC_RADIX>: The radix for numeric precision.
4569The value is 10 or 2 for numeric data types and NULL (C<undef>) if not
4570applicable.
4571
4572B<NULLABLE>: Indicates if a column can accept NULLs.
4573The following values are defined:
4574
4575 SQL_NO_NULLS 0
4576 SQL_NULLABLE 1
4577 SQL_NULLABLE_UNKNOWN 2
4578
4579B<REMARKS>: A description of the column.
4580
4581B<COLUMN_DEF>: The default value of the column.
4582
4583B<SQL_DATA_TYPE>: The SQL data type.
4584
4585B<SQL_DATETIME_SUB>: The subtype code for datetime and interval data types.
4586
4587B<CHAR_OCTET_LENGTH>: The maximum length in bytes of a character or binary
4588data type column.
4589
4590B<ORDINAL_POSITION>: The column sequence number (starting with 1).
4591
4592B<IS_NULLABLE>: Indicates if the column can accept NULLs.
4593Possible values are: 'NO', 'YES' and ''.
4594
4595SQL/CLI defines the following additional columns:
4596
4597 CHAR_SET_CAT
4598 CHAR_SET_SCHEM
4599 CHAR_SET_NAME
4600 COLLATION_CAT
4601 COLLATION_SCHEM
4602 COLLATION_NAME
4603 UDT_CAT
4604 UDT_SCHEM
4605 UDT_NAME
4606 DOMAIN_CAT
4607 DOMAIN_SCHEM
4608 DOMAIN_NAME
4609 SCOPE_CAT
4610 SCOPE_SCHEM
4611 SCOPE_NAME
4612 MAX_CARDINALITY
4613 DTD_IDENTIFIER
4614 IS_SELF_REF
4615
4616Drivers capable of supplying any of those values should do so in
4617the corresponding column and supply undef values for the others.
4618
4619Drivers wishing to provide extra database/driver specific information
4620should do so in extra columns beyond all those listed above, and
4621use lowercase field names with the driver-specific prefix (i.e.,
4622'ora_...'). Applications accessing such fields should do so by name
4623and not by column number.
4624
4625The result set is ordered by TABLE_CAT, TABLE_SCHEM, TABLE_NAME
4626and ORDINAL_POSITION.
4627
4628Note: There is some overlap with statement attributes (in perl) and
4629SQLDescribeCol (in ODBC). However, SQLColumns provides more metadata.
4630
4631See also L</"Catalog Methods"> and L</"Standards Reference Information">.
4632
4633=item C<primary_key_info>
4634
4635 $sth = $dbh->primary_key_info( $catalog, $schema, $table );
4636
4637 # then $sth->fetchall_arrayref or $sth->fetchall_hashref etc
4638
4639Returns an active statement handle that can be used to fetch information
4640about columns that make up the primary key for a table.
4641The arguments don't accept search patterns (unlike table_info()).
4642
4643The statement handle will return one row per column, ordered by
4644TABLE_CAT, TABLE_SCHEM, TABLE_NAME, and KEY_SEQ.
4645If there is no primary key then the statement handle will fetch no rows.
4646
4647Note: The support for the selection criteria, such as $catalog, is
4648driver specific. If the driver doesn't support catalogs and/or
4649schemas, it may ignore these criteria.
4650
4651The statement handle returned has at least the following fields in the
4652order shown below. Other fields, after these, may also be present.
4653
4654B<TABLE_CAT>: The catalog identifier.
4655This field is NULL (C<undef>) if not applicable to the data source,
4656which is often the case. This field is empty if not applicable to the
4657table.
4658
4659B<TABLE_SCHEM>: The schema identifier.
4660This field is NULL (C<undef>) if not applicable to the data source,
4661and empty if not applicable to the table.
4662
4663B<TABLE_NAME>: The table identifier.
4664
4665B<COLUMN_NAME>: The column identifier.
4666
4667B<KEY_SEQ>: The column sequence number (starting with 1).
4668Note: This field is named B<ORDINAL_POSITION> in SQL/CLI.
4669
4670B<PK_NAME>: The primary key constraint identifier.
4671This field is NULL (C<undef>) if not applicable to the data source.
4672
4673See also L</"Catalog Methods"> and L</"Standards Reference Information">.
4674
4675=item C<primary_key>
4676
4677 @key_column_names = $dbh->primary_key( $catalog, $schema, $table );
4678
4679Simple interface to the primary_key_info() method. Returns a list of
4680the column names that comprise the primary key of the specified table.
4681The list is in primary key column sequence order.
4682If there is no primary key then an empty list is returned.
4683
4684=item C<foreign_key_info>
4685
4686 $sth = $dbh->foreign_key_info( $pk_catalog, $pk_schema, $pk_table
4687 , $fk_catalog, $fk_schema, $fk_table );
4688
4689 $sth = $dbh->foreign_key_info( $pk_catalog, $pk_schema, $pk_table
4690 , $fk_catalog, $fk_schema, $fk_table
4691 , \%attr );
4692
4693 # then $sth->fetchall_arrayref or $sth->fetchall_hashref etc
4694
4695Returns an active statement handle that can be used to fetch information
4696about foreign keys in and/or referencing the specified table(s).
4697The arguments don't accept search patterns (unlike table_info()).
4698
4699C<$pk_catalog>, C<$pk_schema>, C<$pk_table>
4700identify the primary (unique) key table (B<PKT>).
4701
4702C<$fk_catalog>, C<$fk_schema>, C<$fk_table>
4703identify the foreign key table (B<FKT>).
4704
4705If both B<PKT> and B<FKT> are given, the function returns the foreign key, if
4706any, in table B<FKT> that refers to the primary (unique) key of table B<PKT>.
4707(Note: In SQL/CLI, the result is implementation-defined.)
4708
4709If only B<PKT> is given, then the result set contains the primary key
4710of that table and all foreign keys that refer to it.
4711
4712If only B<FKT> is given, then the result set contains all foreign keys
4713in that table and the primary keys to which they refer.
4714(Note: In SQL/CLI, the result includes unique keys too.)
4715
4716For example:
4717
4718 $sth = $dbh->foreign_key_info( undef, $user, 'master');
4719 $sth = $dbh->foreign_key_info( undef, undef, undef , undef, $user, 'detail');
4720 $sth = $dbh->foreign_key_info( undef, $user, 'master', undef, $user, 'detail');
4721
4722 # then $sth->fetchall_arrayref or $sth->fetchall_hashref etc
4723
4724Note: The support for the selection criteria, such as C<$catalog>, is
4725driver specific. If the driver doesn't support catalogs and/or
4726schemas, it may ignore these criteria.
4727
4728The statement handle returned has the following fields in the order shown below.
4729Because ODBC never includes unique keys, they define different columns in the
4730result set than SQL/CLI. SQL/CLI column names are shown in parentheses.
4731
4732B<PKTABLE_CAT ( UK_TABLE_CAT )>:
4733The primary (unique) key table catalog identifier.
4734This field is NULL (C<undef>) if not applicable to the data source,
4735which is often the case. This field is empty if not applicable to the
4736table.
4737
4738B<PKTABLE_SCHEM ( UK_TABLE_SCHEM )>:
4739The primary (unique) key table schema identifier.
4740This field is NULL (C<undef>) if not applicable to the data source,
4741and empty if not applicable to the table.
4742
4743B<PKTABLE_NAME ( UK_TABLE_NAME )>:
4744The primary (unique) key table identifier.
4745
4746B<PKCOLUMN_NAME (UK_COLUMN_NAME )>:
4747The primary (unique) key column identifier.
4748
4749B<FKTABLE_CAT ( FK_TABLE_CAT )>:
4750The foreign key table catalog identifier.
4751This field is NULL (C<undef>) if not applicable to the data source,
4752which is often the case. This field is empty if not applicable to the
4753table.
4754
4755B<FKTABLE_SCHEM ( FK_TABLE_SCHEM )>:
4756The foreign key table schema identifier.
4757This field is NULL (C<undef>) if not applicable to the data source,
4758and empty if not applicable to the table.
4759
4760B<FKTABLE_NAME ( FK_TABLE_NAME )>:
4761The foreign key table identifier.
4762
4763B<FKCOLUMN_NAME ( FK_COLUMN_NAME )>:
4764The foreign key column identifier.
4765
4766B<KEY_SEQ ( ORDINAL_POSITION )>:
4767The column sequence number (starting with 1).
4768
4769B<UPDATE_RULE ( UPDATE_RULE )>:
4770The referential action for the UPDATE rule.
4771The following codes are defined:
4772
4773 CASCADE 0
4774 RESTRICT 1
4775 SET NULL 2
4776 NO ACTION 3
4777 SET DEFAULT 4
4778
4779B<DELETE_RULE ( DELETE_RULE )>:
4780The referential action for the DELETE rule.
4781The codes are the same as for UPDATE_RULE.
4782
4783B<FK_NAME ( FK_NAME )>:
4784The foreign key name.
4785
4786B<PK_NAME ( UK_NAME )>:
4787The primary (unique) key name.
4788
4789B<DEFERRABILITY ( DEFERABILITY )>:
4790The deferrability of the foreign key constraint.
4791The following codes are defined:
4792
4793 INITIALLY DEFERRED 5
4794 INITIALLY IMMEDIATE 6
4795 NOT DEFERRABLE 7
4796
4797B< ( UNIQUE_OR_PRIMARY )>:
4798This column is necessary if a driver includes all candidate (i.e. primary and
4799alternate) keys in the result set (as specified by SQL/CLI).
4800The value of this column is UNIQUE if the foreign key references an alternate
4801key and PRIMARY if the foreign key references a primary key, or it
4802may be undefined if the driver doesn't have access to the information.
4803
4804See also L</"Catalog Methods"> and L</"Standards Reference Information">.
4805
4806=item C<statistics_info>
4807
4808B<Warning:> This method is experimental and may change.
4809
4810 $sth = $dbh->statistics_info( $catalog, $schema, $table, $unique_only, $quick );
4811
4812 # then $sth->fetchall_arrayref or $sth->fetchall_hashref etc
4813
4814Returns an active statement handle that can be used to fetch statistical
4815information about a table and its indexes.
4816
4817The arguments don't accept search patterns (unlike L</table_info>).
4818
4819If the boolean argument $unique_only is true, only UNIQUE indexes will be
4820returned in the result set, otherwise all indexes will be returned.
4821
4822If the boolean argument $quick is set, the actual statistical information
4823columns (CARDINALITY and PAGES) will only be returned if they are readily
4824available from the server, and might not be current. Some databases may
4825return stale statistics or no statistics at all with this flag set.
4826
4827The statement handle will return at most one row per column name per index,
4828plus at most one row for the entire table itself, ordered by NON_UNIQUE, TYPE,
4829INDEX_QUALIFIER, INDEX_NAME, and ORDINAL_POSITION.
4830
4831Note: The support for the selection criteria, such as $catalog, is
4832driver specific. If the driver doesn't support catalogs and/or
4833schemas, it may ignore these criteria.
4834
4835The statement handle returned has at least the following fields in the
4836order shown below. Other fields, after these, may also be present.
4837
4838B<TABLE_CAT>: The catalog identifier.
4839This field is NULL (C<undef>) if not applicable to the data source,
4840which is often the case. This field is empty if not applicable to the
4841table.
4842
4843B<TABLE_SCHEM>: The schema identifier.
4844This field is NULL (C<undef>) if not applicable to the data source,
4845and empty if not applicable to the table.
4846
4847B<TABLE_NAME>: The table identifier.
4848
4849B<NON_UNIQUE>: Unique index indicator.
4850Returns 0 for unique indexes, 1 for non-unique indexes
4851
4852B<INDEX_QUALIFIER>: Index qualifier identifier.
4853The identifier that is used to qualify the index name when doing a
4854C<DROP INDEX>; NULL (C<undef>) is returned if an index qualifier is not
4855supported by the data source.
4856If a non-NULL (defined) value is returned in this column, it must be used
4857to qualify the index name on a C<DROP INDEX> statement; otherwise,
4858the TABLE_SCHEM should be used to qualify the index name.
4859
4860B<INDEX_NAME>: The index identifier.
4861
4862B<TYPE>: The type of information being returned. Can be any of the
4863following values: 'table', 'btree', 'clustered', 'content', 'hashed',
4864or 'other'.
4865
4866In the case that this field is 'table', all fields
4867other than TABLE_CAT, TABLE_SCHEM, TABLE_NAME, TYPE,
4868CARDINALITY, and PAGES will be NULL (C<undef>).
4869
4870B<ORDINAL_POSITION>: Column sequence number (starting with 1).
4871
4872B<COLUMN_NAME>: The column identifier.
4873
4874B<ASC_OR_DESC>: Column sort sequence.
4875C<A> for Ascending, C<D> for Descending, or NULL (C<undef>) if
4876not supported for this index.
4877
4878B<CARDINALITY>: Cardinality of the table or index.
4879For indexes, this is the number of unique values in the index.
4880For tables, this is the number of rows in the table.
4881If not supported, the value will be NULL (C<undef>).
4882
4883B<PAGES>: Number of storage pages used by this table or index.
4884If not supported, the value will be NULL (C<undef>).
4885
4886B<FILTER_CONDITION>: The index filter condition as a string.
4887If the index is not a filtered index, or it cannot be determined
4888whether the index is a filtered index, this value is NULL (C<undef>).
4889If the index is a filtered index, but the filter condition
4890cannot be determined, this value is the empty string C<''>.
4891Otherwise it will be the literal filter condition as a string,
4892such as C<SALARY <= 4500>.
4893
4894See also L</"Catalog Methods"> and L</"Standards Reference Information">.
4895
4896=item C<tables>
4897
4898 @names = $dbh->tables( $catalog, $schema, $table, $type );
4899 @names = $dbh->tables; # deprecated
4900
4901Simple interface to table_info(). Returns a list of matching
4902table names, possibly including a catalog/schema prefix.
4903
4904See L</table_info> for a description of the parameters.
4905
4906If C<$dbh-E<gt>get_info(29)> returns true (29 is SQL_IDENTIFIER_QUOTE_CHAR)
4907then the table names are constructed and quoted by L</quote_identifier>
4908to ensure they are usable even if they contain whitespace or reserved
4909words etc. This means that the table names returned will include
4910quote characters.
4911
4912=item C<type_info_all>
4913
4914 $type_info_all = $dbh->type_info_all;
4915
4916Returns a reference to an array which holds information about each data
4917type variant supported by the database and driver. The array and its
4918contents should be treated as read-only.
4919
4920The first item is a reference to an 'index' hash of C<Name =>E<gt> C<Index> pairs.
4921The items following that are references to arrays, one per supported data
4922type variant. The leading index hash defines the names and order of the
4923fields within the arrays that follow it.
4924For example:
4925
4926 $type_info_all = [
4927 { TYPE_NAME => 0,
4928 DATA_TYPE => 1,
4929 COLUMN_SIZE => 2, # was PRECISION originally
4930 LITERAL_PREFIX => 3,
4931 LITERAL_SUFFIX => 4,
4932 CREATE_PARAMS => 5,
4933 NULLABLE => 6,
4934 CASE_SENSITIVE => 7,
4935 SEARCHABLE => 8,
4936 UNSIGNED_ATTRIBUTE=> 9,
4937 FIXED_PREC_SCALE => 10, # was MONEY originally
4938 AUTO_UNIQUE_VALUE => 11, # was AUTO_INCREMENT originally
4939 LOCAL_TYPE_NAME => 12,
4940 MINIMUM_SCALE => 13,
4941 MAXIMUM_SCALE => 14,
4942 SQL_DATA_TYPE => 15,
4943 SQL_DATETIME_SUB => 16,
4944 NUM_PREC_RADIX => 17,
4945 INTERVAL_PRECISION=> 18,
4946 },
4947 [ 'VARCHAR', SQL_VARCHAR,
4948 undef, "'","'", undef,0, 1,1,0,0,0,undef,1,255, undef
4949 ],
4950 [ 'INTEGER', SQL_INTEGER,
4951 undef, "", "", undef,0, 0,1,0,0,0,undef,0, 0, 10
4952 ],
4953 ];
4954
4955More than one row may have the same value in the C<DATA_TYPE>
4956field if there are different ways to spell the type name and/or there
4957are variants of the type with different attributes (e.g., with and
4958without C<AUTO_UNIQUE_VALUE> set, with and without C<UNSIGNED_ATTRIBUTE>, etc).
4959
4960The rows are ordered by C<DATA_TYPE> first and then by how closely each
4961type maps to the corresponding ODBC SQL data type, closest first.
4962
4963The meaning of the fields is described in the documentation for
4964the L</type_info> method.
4965
4966An 'index' hash is provided so you don't need to rely on index
4967values defined above. However, using DBD::ODBC with some old ODBC
4968drivers may return older names, shown as comments in the example above.
4969Another issue with the index hash is that the lettercase of the
4970keys is not defined. It is usually uppercase, as show here, but
4971drivers may return names with any lettercase.
4972
4973Drivers are also free to return extra driver-specific columns of
4974information - though it's recommended that they start at column
4975index 50 to leave room for expansion of the DBI/ODBC specification.
4976
4977The type_info_all() method is not normally used directly.
4978The L</type_info> method provides a more usable and useful interface
4979to the data.
4980
4981=item C<type_info>
4982
4983 @type_info = $dbh->type_info($data_type);
4984
4985Returns a list of hash references holding information about one or more
4986variants of $data_type. The list is ordered by C<DATA_TYPE> first and
4987then by how closely each type maps to the corresponding ODBC SQL data
4988type, closest first. If called in a scalar context then only the first
4989(best) element is returned.
4990
4991If $data_type is undefined or C<SQL_ALL_TYPES>, then the list will
4992contain hashes for all data type variants supported by the database and driver.
4993
4994If $data_type is an array reference then C<type_info> returns the
4995information for the I<first> type in the array that has any matches.
4996
4997The keys of the hash follow the same letter case conventions as the
4998rest of the DBI (see L</Naming Conventions and Name Space>). The
4999following uppercase items should always exist, though may be undef:
5000
5001=over 4
5002
5003=item TYPE_NAME (string)
5004
5005Data type name for use in CREATE TABLE statements etc.
5006
5007=item DATA_TYPE (integer)
5008
5009SQL data type number.
5010
5011=item COLUMN_SIZE (integer)
5012
5013For numeric types, this is either the total number of digits (if the
5014NUM_PREC_RADIX value is 10) or the total number of bits allowed in the
5015column (if NUM_PREC_RADIX is 2).
5016
5017For string types, this is the maximum size of the string in characters.
5018
5019For date and interval types, this is the maximum number of characters
5020needed to display the value.
5021
5022=item LITERAL_PREFIX (string)
5023
5024Characters used to prefix a literal. A typical prefix is "C<'>" for characters,
5025or possibly "C<0x>" for binary values passed as hexadecimal. NULL (C<undef>) is
5026returned for data types for which this is not applicable.
5027
5028
5029=item LITERAL_SUFFIX (string)
5030
5031Characters used to suffix a literal. Typically "C<'>" for characters.
5032NULL (C<undef>) is returned for data types where this is not applicable.
5033
5034=item CREATE_PARAMS (string)
5035
5036Parameter names for data type definition. For example, C<CREATE_PARAMS> for a
5037C<DECIMAL> would be "C<precision,scale>" if the DECIMAL type should be
5038declared as C<DECIMAL(>I<precision,scale>C<)> where I<precision> and I<scale>
5039are integer values. For a C<VARCHAR> it would be "C<max length>".
5040NULL (C<undef>) is returned for data types for which this is not applicable.
5041
5042=item NULLABLE (integer)
5043
5044Indicates whether the data type accepts a NULL value:
5045C<0> or an empty string = no, C<1> = yes, C<2> = unknown.
5046
5047=item CASE_SENSITIVE (boolean)
5048
5049Indicates whether the data type is case sensitive in collations and
5050comparisons.
5051
5052=item SEARCHABLE (integer)
5053
5054Indicates how the data type can be used in a WHERE clause, as
5055follows:
5056
5057 0 - Cannot be used in a WHERE clause
5058 1 - Only with a LIKE predicate
5059 2 - All comparison operators except LIKE
5060 3 - Can be used in a WHERE clause with any comparison operator
5061
5062=item UNSIGNED_ATTRIBUTE (boolean)
5063
5064Indicates whether the data type is unsigned. NULL (C<undef>) is returned
5065for data types for which this is not applicable.
5066
5067=item FIXED_PREC_SCALE (boolean)
5068
5069Indicates whether the data type always has the same precision and scale
5070(such as a money type). NULL (C<undef>) is returned for data types
5071for which
5072this is not applicable.
5073
5074=item AUTO_UNIQUE_VALUE (boolean)
5075
5076Indicates whether a column of this data type is automatically set to a
5077unique value whenever a new row is inserted. NULL (C<undef>) is returned
5078for data types for which this is not applicable.
5079
5080=item LOCAL_TYPE_NAME (string)
5081
5082Localized version of the C<TYPE_NAME> for use in dialog with users.
5083NULL (C<undef>) is returned if a localized name is not available (in which
5084case C<TYPE_NAME> should be used).
5085
5086=item MINIMUM_SCALE (integer)
5087
5088The minimum scale of the data type. If a data type has a fixed scale,
5089then C<MAXIMUM_SCALE> holds the same value. NULL (C<undef>) is returned for
5090data types for which this is not applicable.
5091
5092=item MAXIMUM_SCALE (integer)
5093
5094The maximum scale of the data type. If a data type has a fixed scale,
5095then C<MINIMUM_SCALE> holds the same value. NULL (C<undef>) is returned for
5096data types for which this is not applicable.
5097
5098=item SQL_DATA_TYPE (integer)
5099
5100This column is the same as the C<DATA_TYPE> column, except for interval
5101and datetime data types. For interval and datetime data types, the
5102C<SQL_DATA_TYPE> field will return C<SQL_INTERVAL> or C<SQL_DATETIME>, and the
5103C<SQL_DATETIME_SUB> field below will return the subcode for the specific
5104interval or datetime data type. If this field is NULL, then the driver
5105does not support or report on interval or datetime subtypes.
5106
5107=item SQL_DATETIME_SUB (integer)
5108
5109For interval or datetime data types, where the C<SQL_DATA_TYPE>
5110field above is C<SQL_INTERVAL> or C<SQL_DATETIME>, this field will
5111hold the I<subcode> for the specific interval or datetime data type.
5112Otherwise it will be NULL (C<undef>).
5113
5114Although not mentioned explicitly in the standards, it seems there
5115is a simple relationship between these values:
5116
5117 DATA_TYPE == (10 * SQL_DATA_TYPE) + SQL_DATETIME_SUB
5118
5119=item NUM_PREC_RADIX (integer)
5120
5121The radix value of the data type. For approximate numeric types,
5122C<NUM_PREC_RADIX>
5123contains the value 2 and C<COLUMN_SIZE> holds the number of bits. For
5124exact numeric types, C<NUM_PREC_RADIX> contains the value 10 and C<COLUMN_SIZE> holds
5125the number of decimal digits. NULL (C<undef>) is returned either for data types
5126for which this is not applicable or if the driver cannot report this information.
5127
5128=item INTERVAL_PRECISION (integer)
5129
5130The interval leading precision for interval types. NULL is returned
5131either for data types for which this is not applicable or if the driver
5132cannot report this information.
5133
5134=back
5135
5136For example, to find the type name for the fields in a select statement
5137you can do:
5138
5139 @names = map { scalar $dbh->type_info($_)->{TYPE_NAME} } @{ $sth->{TYPE} }
5140
5141Since DBI and ODBC drivers vary in how they map their types into the
5142ISO standard types you may need to search for more than one type.
5143Here's an example looking for a usable type to store a date:
5144
5145 $my_date_type = $dbh->type_info( [ SQL_DATE, SQL_TIMESTAMP ] );
5146
5147Similarly, to more reliably find a type to store small integers, you could
5148use a list starting with C<SQL_SMALLINT>, C<SQL_INTEGER>, C<SQL_DECIMAL>, etc.
5149
5150See also L</"Standards Reference Information">.
5151
5152
5153=item C<quote>
5154
5155 $sql = $dbh->quote($value);
5156 $sql = $dbh->quote($value, $data_type);
5157
5158Quote a string literal for use as a literal value in an SQL statement,
5159by escaping any special characters (such as quotation marks)
5160contained within the string and adding the required type of outer
5161quotation marks.
5162
5163 $sql = sprintf "SELECT foo FROM bar WHERE baz = %s",
5164 $dbh->quote("Don't");
5165
5166For most database types, quote would return C<'Don''t'> (including the
5167outer quotation marks).
5168
5169An undefined C<$value> value will be returned as the string C<NULL> (without
5170single quotation marks) to match how NULLs are represented in SQL.
5171
5172If C<$data_type> is supplied, it is used to try to determine the required
5173quoting behaviour by using the information returned by L</type_info>.
5174As a special case, the standard numeric types are optimized to return
5175C<$value> without calling C<type_info>.
5176
5177Quote will probably I<not> be able to deal with all possible input
5178(such as binary data or data containing newlines), and is not related in
5179any way with escaping or quoting shell meta-characters.
5180
5181It is valid for the quote() method to return an SQL expression that
5182evaluates to the desired string. For example:
5183
5184 $quoted = $dbh->quote("one\ntwo\0three")
5185
5186may return something like:
5187
5188 CONCAT('one', CHAR(12), 'two', CHAR(0), 'three')
5189
5190The quote() method should I<not> be used with L</"Placeholders and
5191Bind Values">.
5192
5193=item C<quote_identifier>
5194
5195 $sql = $dbh->quote_identifier( $name );
5196 $sql = $dbh->quote_identifier( $catalog, $schema, $table, \%attr );
5197
5198Quote an identifier (table name etc.) for use in an SQL statement,
5199by escaping any special characters (such as double quotation marks)
5200it contains and adding the required type of outer quotation marks.
5201
5202Undefined names are ignored and the remainder are quoted and then
5203joined together, typically with a dot (C<.>) character. For example:
5204
5205 $id = $dbh->quote_identifier( undef, 'Her schema', 'My table' );
5206
5207would, for most database types, return C<"Her schema"."My table">
5208(including all the double quotation marks).
5209
5210If three names are supplied then the first is assumed to be a
5211catalog name and special rules may be applied based on what L</get_info>
5212returns for SQL_CATALOG_NAME_SEPARATOR (41) and SQL_CATALOG_LOCATION (114).
5213For example, for Oracle:
5214
5215 $id = $dbh->quote_identifier( 'link', 'schema', 'table' );
5216
5217would return C<"schema"."table"@"link">.
5218
5219=item C<take_imp_data>
5220
5221 $imp_data = $dbh->take_imp_data;
5222
5223Leaves the $dbh in an almost dead, zombie-like, state and returns
5224a binary string of raw implementation data from the driver which
5225describes the current database connection. Effectively it detaches
5226the underlying database API connection data from the DBI handle.
5227After calling take_imp_data(), all other methods except C<DESTROY>
5228will generate a warning and return undef.
5229
5230Why would you want to do this? You don't, forget I even mentioned it.
5231Unless, that is, you're implementing something advanced like a
5232multi-threaded connection pool. See L<DBI::Pool>.
5233
5234The returned $imp_data can be passed as a C<dbi_imp_data> attribute
5235to a later connect() call, even in a separate thread in the same
5236process, where the driver can use it to 'adopt' the existing
5237connection that the implementation data was taken from.
5238
5239Some things to keep in mind...
5240
5241B<*> the $imp_data holds the only reference to the underlying
5242database API connection data. That connection is still 'live' and
5243won't be cleaned up properly unless the $imp_data is used to create
5244a new $dbh which is then allowed to disconnect() normally.
5245
5246B<*> using the same $imp_data to create more than one other new
5247$dbh at a time may well lead to unpleasant problems. Don't do that.
5248
5249Any child statement handles are effectively destroyed when take_imp_data() is
5250called.
5251
5252The C<take_imp_data> method was added in DBI 1.36 but wasn't useful till 1.49.
5253
5254=back
5255
5256
5257=head2 Database Handle Attributes
5258
5259This section describes attributes specific to database handles.
5260
5261Changes to these database handle attributes do not affect any other
5262existing or future database handles.
5263
5264Attempting to set or get the value of an unknown attribute generates a warning,
5265except for private driver-specific attributes (which all have names
5266starting with a lowercase letter).
5267
5268Example:
5269
5270 $h->{AutoCommit} = ...; # set/write
5271 ... = $h->{AutoCommit}; # get/read
5272
5273=over 4
5274
5275=item C<AutoCommit> (boolean)
5276
5277If true, then database changes cannot be rolled-back (undone). If false,
5278then database changes automatically occur within a "transaction", which
5279must either be committed or rolled back using the C<commit> or C<rollback>
5280methods.
5281
5282Drivers should always default to C<AutoCommit> mode (an unfortunate
5283choice largely forced on the DBI by ODBC and JDBC conventions.)
5284
5285Attempting to set C<AutoCommit> to an unsupported value is a fatal error.
5286This is an important feature of the DBI. Applications that need
5287full transaction behaviour can set C<$dbh-E<gt>{AutoCommit} = 0> (or
5288set C<AutoCommit> to 0 via L</connect>)
5289without having to check that the value was assigned successfully.
5290
5291For the purposes of this description, we can divide databases into three
5292categories:
5293
5294 Databases which don't support transactions at all.
5295 Databases in which a transaction is always active.
5296 Databases in which a transaction must be explicitly started (C<'BEGIN WORK'>).
5297
5298B<* Databases which don't support transactions at all>
5299
5300For these databases, attempting to turn C<AutoCommit> off is a fatal error.
5301C<commit> and C<rollback> both issue warnings about being ineffective while
5302C<AutoCommit> is in effect.
5303
5304B<* Databases in which a transaction is always active>
5305
5306These are typically mainstream commercial relational databases with
5307"ANSI standard" transaction behaviour.
5308If C<AutoCommit> is off, then changes to the database won't have any
5309lasting effect unless L</commit> is called (but see also
5310L</disconnect>). If L</rollback> is called then any changes since the
5311last commit are undone.
5312
5313If C<AutoCommit> is on, then the effect is the same as if the DBI
5314called C<commit> automatically after every successful database
5315operation. So calling C<commit> or C<rollback> explicitly while
5316C<AutoCommit> is on would be ineffective because the changes would
5317have already been commited.
5318
5319Changing C<AutoCommit> from off to on will trigger a L</commit>.
5320
5321For databases which don't support a specific auto-commit mode, the
5322driver has to commit each statement automatically using an explicit
5323C<COMMIT> after it completes successfully (and roll it back using an
5324explicit C<ROLLBACK> if it fails). The error information reported to the
5325application will correspond to the statement which was executed, unless
5326it succeeded and the commit or rollback failed.
5327
5328B<* Databases in which a transaction must be explicitly started>
5329
5330For these databases, the intention is to have them act like databases in
5331which a transaction is always active (as described above).
5332
5333To do this, the driver will automatically begin an explicit transaction
5334when C<AutoCommit> is turned off, or after a L</commit> or
5335L</rollback> (or when the application issues the next database
5336operation after one of those events).
5337
5338In this way, the application does not have to treat these databases
5339as a special case.
5340
5341See L</commit>, L</disconnect> and L</Transactions> for other important
5342notes about transactions.
5343
5344
5345=item C<Driver> (handle)
5346
5347Holds the handle of the parent driver. The only recommended use for this
5348is to find the name of the driver using:
5349
5350 $dbh->{Driver}->{Name}
5351
5352
5353=item C<Name> (string)
5354
5355Holds the "name" of the database. Usually (and recommended to be) the
5356same as the "C<dbi:DriverName:...>" string used to connect to the database,
5357but with the leading "C<dbi:DriverName:>" removed.
5358
5359
5360=item C<Statement> (string, read-only)
5361
5362Returns the statement string passed to the most recent L</prepare> method
5363called in this database handle, even if that method failed. This is especially
5364useful where C<RaiseError> is enabled and the exception handler checks $@
5365and sees that a 'prepare' method call failed.
5366
5367
5368=item C<RowCacheSize> (integer)
5369
5370A hint to the driver indicating the size of the local row cache that the
5371application would like the driver to use for future C<SELECT> statements.
5372If a row cache is not implemented, then setting C<RowCacheSize> is ignored
5373and getting the value returns C<undef>.
5374
5375Some C<RowCacheSize> values have special meaning, as follows:
5376
5377 0 - Automatically determine a reasonable cache size for each C<SELECT>
5378 1 - Disable the local row cache
5379 >1 - Cache this many rows
5380 <0 - Cache as many rows that will fit into this much memory for each C<SELECT>.
5381
5382Note that large cache sizes may require a very large amount of memory
5383(I<cached rows * maximum size of row>). Also, a large cache will cause
5384a longer delay not only for the first fetch, but also whenever the
5385cache needs refilling.
5386
5387See also the L</RowsInCache> statement handle attribute.
5388
5389=item C<Username> (string)
5390
5391Returns the username used to connect to the database.
5392
5393
5394=back
5395
5396
5397=head1 DBI STATEMENT HANDLE OBJECTS
5398
5399This section lists the methods and attributes associated with DBI
5400statement handles.
5401
5402=head2 Statement Handle Methods
5403
5404The DBI defines the following methods for use on DBI statement handles:
5405
5406=over 4
5407
5408=item C<bind_param>
5409
5410 $sth->bind_param($p_num, $bind_value)
5411 $sth->bind_param($p_num, $bind_value, \%attr)
5412 $sth->bind_param($p_num, $bind_value, $bind_type)
5413
5414The C<bind_param> method takes a copy of $bind_value and associates it
5415(binds it) with a placeholder, identified by $p_num, embedded in
5416the prepared statement. Placeholders are indicated with question
5417mark character (C<?>). For example:
5418
5419 $dbh->{RaiseError} = 1; # save having to check each method call
5420 $sth = $dbh->prepare("SELECT name, age FROM people WHERE name LIKE ?");
5421 $sth->bind_param(1, "John%"); # placeholders are numbered from 1
5422 $sth->execute;
5423 DBI::dump_results($sth);
5424
5425See L</"Placeholders and Bind Values"> for more information.
5426
5427
5428B<Data Types for Placeholders>
5429
5430The C<\%attr> parameter can be used to hint at the data type the
5431placeholder should have. This is rarely needed. Typically, the driver is only
5432interested in knowing if the placeholder should be bound as a number or a string.
5433
5434 $sth->bind_param(1, $value, { TYPE => SQL_INTEGER });
5435
5436As a short-cut for the common case, the data type can be passed
5437directly, in place of the C<\%attr> hash reference. This example is
5438equivalent to the one above:
5439
5440 $sth->bind_param(1, $value, SQL_INTEGER);
5441
5442The C<TYPE> value indicates the standard (non-driver-specific) type for
5443this parameter. To specify the driver-specific type, the driver may
5444support a driver-specific attribute, such as C<{ ora_type =E<gt> 97 }>.
5445
5446The SQL_INTEGER and other related constants can be imported using
5447
5448 use DBI qw(:sql_types);
5449
5450See L</"DBI Constants"> for more information.
5451
5452The data type for a placeholder cannot be changed after the first
5453C<bind_param> call. In fact the whole \%attr parameter is 'sticky'
5454in the sense that a driver only needs to consider the \%attr parameter
5455for the first call, for a given $sth and parameter. After that the driver
5456may ignore the \%attr parameter for that placeholder.
5457
5458Perl only has string and number scalar data types. All database types
5459that aren't numbers are bound as strings and must be in a format the
5460database will understand except where the bind_param() TYPE attribute
5461specifies a type that implies a particular format. For example, given:
5462
5463 $sth->bind_param(1, $value, SQL_DATETIME);
5464
5465the driver should expect $value to be in the ODBC standard SQL_DATETIME
5466format, which is 'YYYY-MM-DD HH:MM:SS'. Similarly for SQL_DATE, SQL_TIME etc.
5467
5468As an alternative to specifying the data type in the C<bind_param> call,
5469you can let the driver pass the value as the default type (C<VARCHAR>).
5470You can then use an SQL function to convert the type within the statement.
5471For example:
5472
5473 INSERT INTO price(code, price) VALUES (?, CONVERT(MONEY,?))
5474
5475The C<CONVERT> function used here is just an example. The actual function
5476and syntax will vary between different databases and is non-portable.
5477
5478See also L</"Placeholders and Bind Values"> for more information.
5479
5480
5481=item C<bind_param_inout>
5482
5483 $rc = $sth->bind_param_inout($p_num, \$bind_value, $max_len) or die $sth->errstr;
5484 $rv = $sth->bind_param_inout($p_num, \$bind_value, $max_len, \%attr) or ...
5485 $rv = $sth->bind_param_inout($p_num, \$bind_value, $max_len, $bind_type) or ...
5486
5487This method acts like L</bind_param>, but also enables values to be
5488updated by the statement. The statement is typically
5489a call to a stored procedure. The C<$bind_value> must be passed as a
5490reference to the actual value to be used.
5491
5492Note that unlike L</bind_param>, the C<$bind_value> variable is not
5493copied when C<bind_param_inout> is called. Instead, the value in the
5494variable is read at the time L</execute> is called.
5495
5496The additional C<$max_len> parameter specifies the minimum amount of
5497memory to allocate to C<$bind_value> for the new value. If the value
5498returned from the database is too
5499big to fit, then the execution should fail. If unsure what value to use,
5500pick a generous length, i.e., a length larger than the longest value that would ever be
5501returned. The only cost of using a larger value than needed is wasted memory.
5502
5503Undefined values or C<undef> are used to indicate null values.
5504See also L</"Placeholders and Bind Values"> for more information.
5505
5506
5507=item C<bind_param_array>
5508
5509 $rc = $sth->bind_param_array($p_num, $array_ref_or_value)
5510 $rc = $sth->bind_param_array($p_num, $array_ref_or_value, \%attr)
5511 $rc = $sth->bind_param_array($p_num, $array_ref_or_value, $bind_type)
5512
5513The C<bind_param_array> method is used to bind an array of values
5514to a placeholder embedded in the prepared statement which is to be executed
5515with L</execute_array>. For example:
5516
5517 $dbh->{RaiseError} = 1; # save having to check each method call
5518 $sth = $dbh->prepare("INSERT INTO staff (first_name, last_name, dept) VALUES(?, ?, ?)");
5519 $sth->bind_param_array(1, [ 'John', 'Mary', 'Tim' ]);
5520 $sth->bind_param_array(2, [ 'Booth', 'Todd', 'Robinson' ]);
5521 $sth->bind_param_array(3, "SALES"); # scalar will be reused for each row
5522 $sth->execute_array( { ArrayTupleStatus => \my @tuple_status } );
5523
5524The C<%attr> ($bind_type) argument is the same as defined for L</bind_param>.
5525Refer to L</bind_param> for general details on using placeholders.
5526
5527(Note that bind_param_array() can I<not> be used to expand a
5528placeholder into a list of values for a statement like "SELECT foo
5529WHERE bar IN (?)". A placeholder can only ever represent one value
5530per execution.)
5531
5532Scalar values, including C<undef>, may also be bound by
5533C<bind_param_array>. In which case the same value will be used for each
5534L</execute> call. Driver-specific implementations may behave
5535differently, e.g., when binding to a stored procedure call, some
5536databases may permit mixing scalars and arrays as arguments.
5537
5538The default implementation provided by DBI (for drivers that have
5539not implemented array binding) is to iteratively call L</execute> for
5540each parameter tuple provided in the bound arrays. Drivers may
5541provide more optimized implementations using whatever bulk operation
5542support the database API provides. The default driver behaviour should
5543match the default DBI behaviour, but always consult your driver
5544documentation as there may be driver specific issues to consider.
5545
5546Note that the default implementation currently only supports non-data
5547returning statements (INSERT, UPDATE, but not SELECT). Also,
5548C<bind_param_array> and L</bind_param> cannot be mixed in the same
5549statement execution, and C<bind_param_array> must be used with
5550L</execute_array>; using C<bind_param_array> will have no effect
5551for L</execute>.
5552
5553The C<bind_param_array> method was added in DBI 1.22.
5554
5555=item C<execute>
5556
5557 $rv = $sth->execute or die $sth->errstr;
5558 $rv = $sth->execute(@bind_values) or die $sth->errstr;
5559
5560Perform whatever processing is necessary to execute the prepared
5561statement. An C<undef> is returned if an error occurs. A successful
5562C<execute> always returns true regardless of the number of rows affected,
5563even if it's zero (see below). It is always important to check the
5564return status of C<execute> (and most other DBI methods) for errors
5565if you're not using L</RaiseError>.
5566
5567For a I<non>-C<SELECT> statement, C<execute> returns the number of rows
5568affected, if known. If no rows were affected, then C<execute> returns
5569"C<0E0>", which Perl will treat as 0 but will regard as true. Note that it
5570is I<not> an error for no rows to be affected by a statement. If the
5571number of rows affected is not known, then C<execute> returns -1.
5572
5573For C<SELECT> statements, execute simply "starts" the query within the
5574database engine. Use one of the fetch methods to retrieve the data after
5575calling C<execute>. The C<execute> method does I<not> return the number of
5576rows that will be returned by the query (because most databases can't
5577tell in advance), it simply returns a true value.
5578
5579You can tell if the statement was a C<SELECT> statement by checking if
5580C<$sth-E<gt>{NUM_OF_FIELDS}> is greater than zero after calling C<execute>.
5581
5582If any arguments are given, then C<execute> will effectively call
5583L</bind_param> for each value before executing the statement. Values
5584bound in this way are usually treated as C<SQL_VARCHAR> types unless
5585the driver can determine the correct type (which is rare), or unless
5586C<bind_param> (or C<bind_param_inout>) has already been used to
5587specify the type.
5588
5589If execute() is called on a statement handle that's still active
5590($sth->{Active} is true) then it should effectively call finish()
5591to tidy up the previous execution results before starting this new
5592execution.
5593
5594=item C<execute_array>
5595
5596 $tuples = $sth->execute_array(\%attr) or die $sth->errstr;
5597 $tuples = $sth->execute_array(\%attr, @bind_values) or die $sth->errstr;
5598
5599 ($tuples, $rows) = $sth->execute_array(\%attr) or die $sth->errstr;
5600 ($tuples, $rows) = $sth->execute_array(\%attr, @bind_values) or die $sth->errstr;
5601
5602Execute the prepared statement once for each parameter tuple
5603(group of values) provided either in the @bind_values, or by prior
5604calls to L</bind_param_array>, or via a reference passed in \%attr.
5605
5606When called in scalar context the execute_array() method returns the
5607number of tuples executed, or C<undef> if an error occured. Like
5608execute(), a successful execute_array() always returns true regardless
5609of the number of tuples executed, even if it's zero. If there were any
5610errors the ArrayTupleStatus array can be used to discover which tuples
5611failed and with what errors.
5612
5613When called in list context the execute_array() method returns two scalars;
5614$tuples is the same as calling execute_array() in scalar context and $rows is
5615the sum of the number of rows affected for each tuple, if available or
5616-1 if the driver cannot determine this.
5617If you are doing an update operation the returned rows affected may not be what
5618you expect if, for instance, one or more of the tuples affected the same row
5619multiple times. Some drivers may not yet support list context, in which case
5620$rows will be undef, or may not be able to provide the number of rows affected
5621when performing this batch operation, in which case $rows will be -1.
5622
5623Bind values for the tuples to be executed may be supplied row-wise
5624by an C<ArrayTupleFetch> attribute, or else column-wise in the
5625C<@bind_values> argument, or else column-wise by prior calls to
5626L</bind_param_array>.
5627
5628Where column-wise binding is used (via the C<@bind_values> argument
5629or calls to bind_param_array()) the maximum number of elements in
5630any one of the bound value arrays determines the number of tuples
5631executed. Placeholders with fewer values in their parameter arrays
5632are treated as if padded with undef (NULL) values.
5633
5634If a scalar value is bound, instead of an array reference, it is
5635treated as a I<variable> length array with all elements having the
5636same value. It's does not influence the number of tuples executed,
5637so if all bound arrays have zero elements then zero tuples will
5638be executed. If I<all> bound values are scalars then one tuple
5639will be executed, making execute_array() act just like execute().
5640
5641The C<ArrayTupleFetch> attribute can be used to specify a reference
5642to a subroutine that will be called to provide the bind values for
5643each tuple execution. The subroutine should return an reference to
5644an array which contains the appropriate number of bind values, or
5645return an undef if there is no more data to execute.
5646
5647As a convienience, the C<ArrayTupleFetch> attribute can also be
5648used to specify a statement handle. In which case the fetchrow_arrayref()
5649method will be called on the given statement handle in order to
5650provide the bind values for each tuple execution.
5651
5652The values specified via bind_param_array() or the @bind_values
5653parameter may be either scalars, or arrayrefs. If any C<@bind_values>
5654are given, then C<execute_array> will effectively call L</bind_param_array>
5655for each value before executing the statement. Values bound in
5656this way are usually treated as C<SQL_VARCHAR> types unless the
5657driver can determine the correct type (which is rare), or unless
5658C<bind_param>, C<bind_param_inout>, C<bind_param_array>, or
5659C<bind_param_inout_array> has already been used to specify the type.
5660See L</bind_param_array> for details.
5661
5662The C<ArrayTupleStatus> attribute can be used to specify a
5663reference to an array which will receive the execute status of each
5664executed parameter tuple. Note the C<ArrayTupleStatus> attribute was
5665mandatory until DBI 1.38.
5666
5667For tuples which are successfully executed, the element at the same
5668ordinal position in the status array is the resulting rowcount.
5669If the execution of a tuple causes an error, then the corresponding
5670status array element will be set to a reference to an array containing
5671the error code and error string set by the failed execution.
5672
5673If B<any> tuple execution returns an error, C<execute_array> will
5674return C<undef>. In that case, the application should inspect the
5675status array to determine which parameter tuples failed.
5676Some databases may not continue executing tuples beyond the first
5677failure. In this case the status array will either hold fewer
5678elements, or the elements beyond the failure will be undef.
5679
5680If all parameter tuples are successfully executed, C<execute_array>
5681returns the number tuples executed. If no tuples were executed,
5682then execute_array() returns "C<0E0>", just like execute() does,
5683which Perl will treat as 0 but will regard as true.
5684
5685For example:
5686
5687 $sth = $dbh->prepare("INSERT INTO staff (first_name, last_name) VALUES (?, ?)");
5688 my $tuples = $sth->execute_array(
5689 { ArrayTupleStatus => \my @tuple_status },
5690 \@first_names,
5691 \@last_names,
5692 );
5693 if ($tuples) {
5694 print "Successfully inserted $tuples records\n";
5695 }
5696 else {
5697 for my $tuple (0..@last_names-1) {
5698 my $status = $tuple_status[$tuple];
5699 $status = [0, "Skipped"] unless defined $status;
5700 next unless ref $status;
5701 printf "Failed to insert (%s, %s): %s\n",
5702 $first_names[$tuple], $last_names[$tuple], $status->[1];
5703 }
5704 }
5705
5706Support for data returning statements such as SELECT is driver-specific
5707and subject to change. At present, the default implementation
5708provided by DBI only supports non-data returning statements.
5709
5710Transaction semantics when using array binding are driver and
5711database specific. If C<AutoCommit> is on, the default DBI
5712implementation will cause each parameter tuple to be inidividually
5713committed (or rolled back in the event of an error). If C<AutoCommit>
5714is off, the application is responsible for explicitly committing
5715the entire set of bound parameter tuples. Note that different
5716drivers and databases may have different behaviours when some
5717parameter tuples cause failures. In some cases, the driver or
5718database may automatically rollback the effect of all prior parameter
5719tuples that succeeded in the transaction; other drivers or databases
5720may retain the effect of prior successfully executed parameter
5721tuples. Be sure to check your driver and database for its specific
5722behaviour.
5723
5724Note that, in general, performance will usually be better with
5725C<AutoCommit> turned off, and using explicit C<commit> after each
5726C<execute_array> call.
5727
5728The C<execute_array> method was added in DBI 1.22, and ArrayTupleFetch
5729was added in 1.36.
5730
5731=item C<execute_for_fetch>
5732
5733 $tuples = $sth->execute_for_fetch($fetch_tuple_sub);
5734 $tuples = $sth->execute_for_fetch($fetch_tuple_sub, \@tuple_status);
5735
5736 ($tuples, $rows) = $sth->execute_for_fetch($fetch_tuple_sub);
5737 ($tuples, $rows) = $sth->execute_for_fetch($fetch_tuple_sub, \@tuple_status);
5738
5739The execute_for_fetch() method is used to perform bulk operations
5740and is most often used via the execute_array() method, not directly.
5741
5742The fetch subroutine, referenced by $fetch_tuple_sub, is expected
5743to return a reference to an array (known as a 'tuple') or undef.
5744
5745The execute_for_fetch() method calls $fetch_tuple_sub, without any
5746parameters, until it returns a false value. Each tuple returned is
5747used to provide bind values for an $sth->execute(@$tuple) call.
5748
5749In scalar context execute_for_fetch() returns C<undef> if there were any
5750errors and the number of tuples executed otherwise. Like execute() and
5751execute_array() a zero is returned as "0E0" so execute_for_fetch() is
5752only false on error. If there were any errors the @tuple_status array
5753can be used to discover which tuples failed and with what errors.
5754
5755When called in list context execute_for_fetch() returns two scalars;
5756$tuples is the same as calling execute_for_fetch() in scalar context and $rows is
5757the sum of the number of rows affected for each tuple, if available or -1
5758if the driver cannot determine this.
5759If you are doing an update operation the returned rows affected may not be what
5760you expect if, for instance, one or more of the tuples affected the same row
5761multiple times. Some drivers may not yet support list context, in which case
5762$rows will be undef, or may not be able to provide the number of rows affected
5763when performing this batch operation, in which case $rows will be -1.
5764
5765If \@tuple_status is passed then the execute_for_fetch method uses
5766it to return status information. The tuple_status array holds one
5767element per tuple. If the corresponding execute() did not fail then
5768the element holds the return value from execute(), which is typically
5769a row count. If the execute() did fail then the element holds a
5770reference to an array containing ($sth->err, $sth->errstr, $sth->state).
5771
5772If the driver detects an error that it knows means no further tuples can be
5773executed then it may return, with an error status, even though $fetch_tuple_sub
5774may still have more tuples to be executed.
5775
5776Although each tuple returned by $fetch_tuple_sub is effectively used
5777to call $sth->execute(@$tuple_array_ref) the exact timing may vary.
5778Drivers are free to accumulate sets of tuples to pass to the
5779database server in bulk group operations for more efficient execution.
5780However, the $fetch_tuple_sub is specifically allowed to return
5781the same array reference each time (which is what fetchrow_arrayref()
5782usually does).
5783
5784For example:
5785
5786 my $sel = $dbh1->prepare("select foo, bar from table1");
5787 $sel->execute;
5788
5789 my $ins = $dbh2->prepare("insert into table2 (foo, bar) values (?,?)");
5790 my $fetch_tuple_sub = sub { $sel->fetchrow_arrayref };
5791
5792 my @tuple_status;
5793 $rc = $ins->execute_for_fetch($fetch_tuple_sub, \@tuple_status);
5794 my @errors = grep { ref $_ } @tuple_status;
5795
5796Similarly, if you already have an array containing the data rows
5797to be processed you'd use a subroutine to shift off and return
5798each array ref in turn:
5799
5800 $ins->execute_for_fetch( sub { shift @array_of_arrays }, \@tuple_status);
5801
5802The C<execute_for_fetch> method was added in DBI 1.38.
5803
5804
5805=item C<fetchrow_arrayref>
5806
5807 $ary_ref = $sth->fetchrow_arrayref;
5808 $ary_ref = $sth->fetch; # alias
5809
5810Fetches the next row of data and returns a reference to an array
5811holding the field values. Null fields are returned as C<undef>
5812values in the array.
5813This is the fastest way to fetch data, particularly if used with
5814C<$sth-E<gt>bind_columns>.
5815
5816If there are no more rows or if an error occurs, then C<fetchrow_arrayref>
5817returns an C<undef>. You should check C<$sth-E<gt>err> afterwards (or use the
5818C<RaiseError> attribute) to discover if the C<undef> returned was due to an
5819error.
5820
5821Note that the same array reference is returned for each fetch, so don't
5822store the reference and then use it after a later fetch. Also, the
5823elements of the array are also reused for each row, so take care if you
5824want to take a reference to an element. See also L</bind_columns>.
5825
5826=item C<fetchrow_array>
5827
5828 @ary = $sth->fetchrow_array;
5829
5830An alternative to C<fetchrow_arrayref>. Fetches the next row of data
5831and returns it as a list containing the field values. Null fields
5832are returned as C<undef> values in the list.
5833
5834If there are no more rows or if an error occurs, then C<fetchrow_array>
5835returns an empty list. You should check C<$sth-E<gt>err> afterwards (or use
5836the C<RaiseError> attribute) to discover if the empty list returned was
5837due to an error.
5838
5839If called in a scalar context for a statement handle that has more
5840than one column, it is undefined whether the driver will return
5841the value of the first column or the last. So don't do that.
5842Also, in a scalar context, an C<undef> is returned if there are no
5843more rows or if an error occurred. That C<undef> can't be distinguished
5844from an C<undef> returned because the first field value was NULL.
5845For these reasons you should exercise some caution if you use
5846C<fetchrow_array> in a scalar context.
5847
5848=item C<fetchrow_hashref>
5849
5850 $hash_ref = $sth->fetchrow_hashref;
5851 $hash_ref = $sth->fetchrow_hashref($name);
5852
5853An alternative to C<fetchrow_arrayref>. Fetches the next row of data
5854and returns it as a reference to a hash containing field name and field
5855value pairs. Null fields are returned as C<undef> values in the hash.
5856
5857If there are no more rows or if an error occurs, then C<fetchrow_hashref>
5858returns an C<undef>. You should check C<$sth-E<gt>err> afterwards (or use the
5859C<RaiseError> attribute) to discover if the C<undef> returned was due to an
5860error.
5861
5862The optional C<$name> parameter specifies the name of the statement handle
5863attribute. For historical reasons it defaults to "C<NAME>", however using either
5864"C<NAME_lc>" or "C<NAME_uc>" is recomended for portability.
5865
5866The keys of the hash are the same names returned by C<$sth-E<gt>{$name}>. If
5867more than one field has the same name, there will only be one entry in
5868the returned hash for those fields.
5869
5870Because of the extra work C<fetchrow_hashref> and Perl have to perform, it
5871is not as efficient as C<fetchrow_arrayref> or C<fetchrow_array>.
5872
5873By default a reference to a new hash is returned for each row.
5874It is likely that a future version of the DBI will support an
5875attribute which will enable the same hash to be reused for each
5876row. This will give a significant performance boost, but it won't
5877be enabled by default because of the risk of breaking old code.
5878
5879
5880=item C<fetchall_arrayref>
5881
5882 $tbl_ary_ref = $sth->fetchall_arrayref;
5883 $tbl_ary_ref = $sth->fetchall_arrayref( $slice );
5884 $tbl_ary_ref = $sth->fetchall_arrayref( $slice, $max_rows );
5885
5886The C<fetchall_arrayref> method can be used to fetch all the data to be
5887returned from a prepared and executed statement handle. It returns a
5888reference to an array that contains one reference per row.
5889
5890If there are no rows to return, C<fetchall_arrayref> returns a reference
5891to an empty array. If an error occurs, C<fetchall_arrayref> returns the
5892data fetched thus far, which may be none. You should check C<$sth-E<gt>err>
5893afterwards (or use the C<RaiseError> attribute) to discover if the data is
5894complete or was truncated due to an error.
5895
5896If $slice is an array reference, C<fetchall_arrayref> uses L</fetchrow_arrayref>
5897to fetch each row as an array ref. If the $slice array is not empty
5898then it is used as a slice to select individual columns by perl array
5899index number (starting at 0, unlike column and parameter numbers which
5900start at 1).
5901
5902With no parameters, or if $slice is undefined, C<fetchall_arrayref>
5903acts as if passed an empty array ref.
5904
5905If $slice is a hash reference, C<fetchall_arrayref> uses L</fetchrow_hashref>
5906to fetch each row as a hash reference. If the $slice hash is empty then
5907fetchrow_hashref() is simply called in a tight loop and the keys in the hashes
5908have whatever name lettercase is returned by default from fetchrow_hashref.
5909(See L</FetchHashKeyName> attribute.) If the $slice hash is not
5910empty, then it is used as a slice to select individual columns by
5911name. The values of the hash should be set to 1. The key names
5912of the returned hashes match the letter case of the names in the
5913parameter hash, regardless of the L</FetchHashKeyName> attribute.
5914
5915For example, to fetch just the first column of every row:
5916
5917 $tbl_ary_ref = $sth->fetchall_arrayref([0]);
5918
5919To fetch the second to last and last column of every row:
5920
5921 $tbl_ary_ref = $sth->fetchall_arrayref([-2,-1]);
5922
5923To fetch all fields of every row as a hash ref:
5924
5925 $tbl_ary_ref = $sth->fetchall_arrayref({});
5926
5927To fetch only the fields called "foo" and "bar" of every row as a hash ref
5928(with keys named "foo" and "BAR"):
5929
5930 $tbl_ary_ref = $sth->fetchall_arrayref({ foo=>1, BAR=>1 });
5931
5932The first two examples return a reference to an array of array refs.
5933The third and forth return a reference to an array of hash refs.
5934
5935If $max_rows is defined and greater than or equal to zero then it
5936is used to limit the number of rows fetched before returning.
5937fetchall_arrayref() can then be called again to fetch more rows.
5938This is especially useful when you need the better performance of
5939fetchall_arrayref() but don't have enough memory to fetch and return
5940all the rows in one go. Here's an example:
5941
5942 my $rows = []; # cache for batches of rows
5943 while( my $row = ( shift(@$rows) || # get row from cache, or reload cache:
5944 shift(@{$rows=$sth->fetchall_arrayref(undef,10_000)||[]}) )
5945 ) {
5946 ...
5947 }
5948
5949That can be the fastest way to fetch and process lots of rows using the DBI,
5950but it depends on the relative cost of method calls vs memory allocation.
5951
5952A standard C<while> loop with column binding is often faster because
5953the cost of allocating memory for the batch of rows is greater than
5954the saving by reducing method calls. It's possible that the DBI may
5955provide a way to reuse the memory of a previous batch in future, which
5956would then shift the balance back towards fetchall_arrayref().
5957
5958
5959=item C<fetchall_hashref>
5960
5961 $hash_ref = $sth->fetchall_hashref($key_field);
5962
5963The C<fetchall_hashref> method can be used to fetch all the data to be
5964returned from a prepared and executed statement handle. It returns a reference
5965to a hash containing a key for each distinct value of the $key_field column
5966that was fetched. For each key the corresponding value is a reference to a hash
5967containing all the selected columns and their values, as returned by fetchrow_hashref().
5968
5969If there are no rows to return, C<fetchall_hashref> returns a reference
5970to an empty hash. If an error occurs, C<fetchall_hashref> returns the
5971data fetched thus far, which may be none. You should check
5972C<$sth-E<gt>err> afterwards (or use the C<RaiseError> attribute) to
5973discover if the data is complete or was truncated due to an error.
5974
5975The $key_field parameter provides the name of the field that holds the
5976value to be used for the key for the returned hash. For example:
5977
5978 $dbh->{FetchHashKeyName} = 'NAME_lc';
5979 $sth = $dbh->prepare("SELECT FOO, BAR, ID, NAME, BAZ FROM TABLE");
5980 $sth->execute;
5981 $hash_ref = $sth->fetchall_hashref('id');
5982 print "Name for id 42 is $hash_ref->{42}->{name}\n";
5983
5984The $key_field parameter can also be specified as an integer column
5985number (counting from 1). If $key_field doesn't match any column in
5986the statement, as a name first then as a number, then an error is
5987returned.
5988
5989For queries returing more than one 'key' column, you can specify
5990multiple column names by passing $key_field as a reference to an
5991array containing one or more key column names (or index numbers).
5992For example:
5993
5994 $sth = $dbh->prepare("SELECT foo, bar, baz FROM table");
5995 $sth->execute;
5996 $hash_ref = $sth->fetchall_hashref( [ qw(foo bar) ] );
5997 print "For foo 42 and bar 38, baz is $hash_ref->{42}->{38}->{baz}\n";
5998
5999The fetchall_hashref() method is normally used only where the key
6000fields values for each row are unique. If multiple rows are returned
6001with the same values for the key fields then later rows overwrite
6002earlier ones.
6003
6004=item C<finish>
6005
6006 $rc = $sth->finish;
6007
6008Indicate that no more data will be fetched from this statement handle
6009before it is either executed again or destroyed. The C<finish> method
6010is rarely needed, and frequently overused, but can sometimes be
6011helpful in a few very specific situations to allow the server to free
6012up resources (such as sort buffers).
6013
6014When all the data has been fetched from a C<SELECT> statement, the
6015driver should automatically call C<finish> for you. So you should
6016I<not> normally need to call it explicitly I<except> when you know
6017that you've not fetched all the data from a statement handle.
6018The most common example is when you only want to fetch one row,
6019but in that case the C<selectrow_*> methods are usually better anyway.
6020Adding calls to C<finish> after each fetch loop is a common mistake,
6021don't do it, it can mask genuine problems like uncaught fetch errors.
6022
6023Consider a query like:
6024
6025 SELECT foo FROM table WHERE bar=? ORDER BY foo
6026
6027where you want to select just the first (smallest) "foo" value from a
6028very large table. When executed, the database server will have to use
6029temporary buffer space to store the sorted rows. If, after executing
6030the handle and selecting one row, the handle won't be re-executed for
6031some time and won't be destroyed, the C<finish> method can be used to tell
6032the server that the buffer space can be freed.
6033
6034Calling C<finish> resets the L</Active> attribute for the statement. It
6035may also make some statement handle attributes (such as C<NAME> and C<TYPE>)
6036unavailable if they have not already been accessed (and thus cached).
6037
6038The C<finish> method does not affect the transaction status of the
6039database connection. It has nothing to do with transactions. It's mostly an
6040internal "housekeeping" method that is rarely needed.
6041See also L</disconnect> and the L</Active> attribute.
6042
6043The C<finish> method should have been called C<discard_pending_rows>.
6044
6045
6046=item C<rows>
6047
6048 $rv = $sth->rows;
6049
6050Returns the number of rows affected by the last row affecting command,
6051or -1 if the number of rows is not known or not available.
6052
6053Generally, you can only rely on a row count after a I<non>-C<SELECT>
6054C<execute> (for some specific operations like C<UPDATE> and C<DELETE>), or
6055after fetching all the rows of a C<SELECT> statement.
6056
6057For C<SELECT> statements, it is generally not possible to know how many
6058rows will be returned except by fetching them all. Some drivers will
6059return the number of rows the application has fetched so far, but
6060others may return -1 until all rows have been fetched. So use of the
6061C<rows> method or C<$DBI::rows> with C<SELECT> statements is not
6062recommended.
6063
6064One alternative method to get a row count for a C<SELECT> is to execute a
6065"SELECT COUNT(*) FROM ..." SQL statement with the same "..." as your
6066query and then fetch the row count from that.
6067
6068
6069=item C<bind_col>
6070
6071 $rc = $sth->bind_col($column_number, \$var_to_bind);
6072 $rc = $sth->bind_col($column_number, \$var_to_bind, \%attr );
6073 $rc = $sth->bind_col($column_number, \$var_to_bind, $bind_type );
6074
6075Binds a Perl variable and/or some attributes to an output column
6076(field) of a C<SELECT> statement. Column numbers count up from 1.
6077You do not need to bind output columns in order to fetch data.
6078For maximum portability between drivers, bind_col() should be called
6079after execute() and not before.
6080See also C<bind_columns> for an example.
6081
6082The binding is performed at a low level using Perl aliasing.
6083Whenever a row is fetched from the database $var_to_bind appears
6084to be automatically updated simply because it now refers to the same
6085memory location as the corresponding column value. This makes using
6086bound variables very efficient.
6087Binding a tied variable doesn't work, currently.
6088
6089The L</bind_param> method
6090performs a similar, but opposite, function for input variables.
6091
6092B<Data Types for Column Binding>
6093
6094The C<\%attr> parameter can be used to hint at the data type
6095formatting the column should have. For example, you can use:
6096
6097 $sth->bind_col(1, undef, { TYPE => SQL_DATETIME });
6098
6099to specify that you'd like the column (which presumably is some
6100kind of datetime type) to be returned in the standard format for
6101SQL_DATETIME, which is 'YYYY-MM-DD HH:MM:SS', rather than the
6102native formatting the database would normally use.
6103
6104There's no $var_to_bind in that example to emphasize the point
6105that bind_col() works on the underlying column value and not just
6106a particular bound variable.
6107
6108As a short-cut for the common case, the data type can be passed
6109directly, in place of the C<\%attr> hash reference. This example is
6110equivalent to the one above:
6111
6112 $sth->bind_col(1, undef, SQL_DATETIME);
6113
6114The C<TYPE> value indicates the standard (non-driver-specific) type for
6115this parameter. To specify the driver-specific type, the driver may
6116support a driver-specific attribute, such as C<{ ora_type =E<gt> 97 }>.
6117
6118The SQL_DATETIME and other related constants can be imported using
6119
6120 use DBI qw(:sql_types);
6121
6122See L</"DBI Constants"> for more information.
6123
6124The data type for a bind variable cannot be changed after the first
6125C<bind_col> call. In fact the whole \%attr parameter is 'sticky'
6126in the sense that a driver only needs to consider the \%attr parameter
6127for the first call for a given $sth and column.
6128
6129The TYPE attribute for bind_col() was first specified in DBI 1.41.
6130
6131
6132=item C<bind_columns>
6133
6134 $rc = $sth->bind_columns(@list_of_refs_to_vars_to_bind);
6135
6136Calls L</bind_col> for each column of the C<SELECT> statement.
6137
6138The list of references should have the same number of elements as the number of
6139columns in the C<SELECT> statement. If it doesn't then C<bind_columns> will
6140bind the elements given, upto the number of columns, and then return an error.
6141
6142For maximum portability between drivers, bind_columns() should be called
6143after execute() and not before.
6144
6145For example:
6146
6147 $dbh->{RaiseError} = 1; # do this, or check every call for errors
6148 $sth = $dbh->prepare(q{ SELECT region, sales FROM sales_by_region });
6149 $sth->execute;
6150 my ($region, $sales);
6151
6152 # Bind Perl variables to columns:
6153 $rv = $sth->bind_columns(\$region, \$sales);
6154
6155 # you can also use Perl's \(...) syntax (see perlref docs):
6156 # $sth->bind_columns(\($region, $sales));
6157
6158 # Column binding is the most efficient way to fetch data
6159 while ($sth->fetch) {
6160 print "$region: $sales\n";
6161 }
6162
6163For compatibility with old scripts, the first parameter will be
6164ignored if it is C<undef> or a hash reference.
6165
6166Here's a more fancy example that binds columns to the values I<inside>
6167a hash (thanks to H.Merijn Brand):
6168
6169 $sth->execute;
6170 my %row;
6171 $sth->bind_columns( \( @row{ @{$sth->{NAME_lc} } } ));
6172 while ($sth->fetch) {
6173 print "$row{region}: $row{sales}\n";
6174 }
6175
6176
6177=item C<dump_results>
6178
6179 $rows = $sth->dump_results($maxlen, $lsep, $fsep, $fh);
6180
6181Fetches all the rows from C<$sth>, calls C<DBI::neat_list> for each row, and
6182prints the results to C<$fh> (defaults to C<STDOUT>) separated by C<$lsep>
6183(default C<"\n">). C<$fsep> defaults to C<", "> and C<$maxlen> defaults to 35.
6184
6185This method is designed as a handy utility for prototyping and
6186testing queries. Since it uses L</neat_list> to
6187format and edit the string for reading by humans, it is not recomended
6188for data transfer applications.
6189
6190=back
6191
6192
6193=head2 Statement Handle Attributes
6194
6195This section describes attributes specific to statement handles. Most
6196of these attributes are read-only.
6197
6198Changes to these statement handle attributes do not affect any other
6199existing or future statement handles.
6200
6201Attempting to set or get the value of an unknown attribute generates a warning,
6202except for private driver specific attributes (which all have names
6203starting with a lowercase letter).
6204
6205Example:
6206
6207 ... = $h->{NUM_OF_FIELDS}; # get/read
6208
6209Some drivers cannot provide valid values for some or all of these
6210attributes until after C<$sth-E<gt>execute> has been successfully
6211called. Typically the attribute will be C<undef> in these situations.
6212
6213Some attributes, like NAME, are not appropriate to some types of
6214statement, like SELECT. Typically the attribute will be C<undef>
6215in these situations.
6216
6217See also L</finish> to learn more about the effect it
6218may have on some attributes.
6219
6220=over 4
6221
6222=item C<NUM_OF_FIELDS> (integer, read-only)
6223
6224Number of fields (columns) in the data the prepared statement may return.
6225Statements that don't return rows of data, like C<DELETE> and C<CREATE>
6226set C<NUM_OF_FIELDS> to 0 (though it may be undef in some drivers).
6227
6228
6229=item C<NUM_OF_PARAMS> (integer, read-only)
6230
6231The number of parameters (placeholders) in the prepared statement.
6232See SUBSTITUTION VARIABLES below for more details.
6233
6234
6235=item C<NAME> (array-ref, read-only)
6236
6237Returns a reference to an array of field names for each column. The
6238names may contain spaces but should not be truncated or have any
6239trailing space. Note that the names have the letter case (upper, lower
6240or mixed) as returned by the driver being used. Portable applications
6241should use L</NAME_lc> or L</NAME_uc>.
6242
6243 print "First column name: $sth->{NAME}->[0]\n";
6244
6245=item C<NAME_lc> (array-ref, read-only)
6246
6247Like L</NAME> but always returns lowercase names.
6248
6249=item C<NAME_uc> (array-ref, read-only)
6250
6251Like L</NAME> but always returns uppercase names.
6252
6253=item C<NAME_hash> (hash-ref, read-only)
6254
6255=item C<NAME_lc_hash> (hash-ref, read-only)
6256
6257=item C<NAME_uc_hash> (hash-ref, read-only)
6258
6259The C<NAME_hash>, C<NAME_lc_hash>, and C<NAME_uc_hash> attributes
6260return column name information as a reference to a hash.
6261
6262The keys of the hash are the names of the columns. The letter case of
6263the keys corresponds to the letter case returned by the C<NAME>,
6264C<NAME_lc>, and C<NAME_uc> attributes respectively (as described above).
6265
6266The value of each hash entry is the perl index number of the
6267corresponding column (counting from 0). For example:
6268
6269 $sth = $dbh->prepare("select Id, Name from table");
6270 $sth->execute;
6271 @row = $sth->fetchrow_array;
6272 print "Name $row[ $sth->{NAME_lc_hash}{name} ]\n";
6273
6274
6275=item C<TYPE> (array-ref, read-only)
6276
6277Returns a reference to an array of integer values for each
6278column. The value indicates the data type of the corresponding column.
6279
6280The values correspond to the international standards (ANSI X3.135
6281and ISO/IEC 9075) which, in general terms, means ODBC. Driver-specific
6282types that don't exactly match standard types should generally return
6283the same values as an ODBC driver supplied by the makers of the
6284database. That might include private type numbers in ranges the vendor
6285has officially registered with the ISO working group:
6286
6287 ftp://sqlstandards.org/SC32/SQL_Registry/
6288
6289Where there's no vendor-supplied ODBC driver to be compatible with,
6290the DBI driver can use type numbers in the range that is now
6291officially reserved for use by the DBI: -9999 to -9000.
6292
6293All possible values for C<TYPE> should have at least one entry in the
6294output of the C<type_info_all> method (see L</type_info_all>).
6295
6296=item C<PRECISION> (array-ref, read-only)
6297
6298Returns a reference to an array of integer values for each column.
6299
6300For numeric columns, the value is the maximum number of digits
6301(without considering a sign character or decimal point). Note that
6302the "display size" for floating point types (REAL, FLOAT, DOUBLE)
6303can be up to 7 characters greater than the precision (for the
6304sign + decimal point + the letter E + a sign + 2 or 3 digits).
6305
6306For any character type column the value is the OCTET_LENGTH,
6307in other words the number of bytes, not characters.
6308
6309(More recent standards refer to this as COLUMN_SIZE but we stick
6310with PRECISION for backwards compatibility.)
6311
6312=item C<SCALE> (array-ref, read-only)
6313
6314Returns a reference to an array of integer values for each column.
6315NULL (C<undef>) values indicate columns where scale is not applicable.
6316
6317=item C<NULLABLE> (array-ref, read-only)
6318
6319Returns a reference to an array indicating the possibility of each
6320column returning a null. Possible values are C<0>
6321(or an empty string) = no, C<1> = yes, C<2> = unknown.
6322
6323 print "First column may return NULL\n" if $sth->{NULLABLE}->[0];
6324
6325
6326=item C<CursorName> (string, read-only)
6327
6328Returns the name of the cursor associated with the statement handle, if
6329available. If not available or if the database driver does not support the
6330C<"where current of ..."> SQL syntax, then it returns C<undef>.
6331
6332
6333=item C<Database> (dbh, read-only)
6334
6335Returns the parent $dbh of the statement handle.
6336
6337
6338=item C<ParamValues> (hash ref, read-only)
6339
6340Returns a reference to a hash containing the values currently bound
6341to placeholders. The keys of the hash are the 'names' of the
6342placeholders, typically integers starting at 1. Returns undef if
6343not supported by the driver.
6344
6345See L</ShowErrorStatement> for an example of how this is used.
6346
6347If the driver supports C<ParamValues> but no values have been bound
6348yet then the driver should return a hash with placeholders names
6349in the keys but all the values undef, but some drivers may return
6350a ref to an empty hash.
6351
6352It is possible that the values in the hash returned by C<ParamValues>
6353are not I<exactly> the same as those passed to bind_param() or execute().
6354The driver may have slightly modified values in some way based on the
6355TYPE the value was bound with. For example a floating point value
6356bound as an SQL_INTEGER type may be returned as an integer.
6357The values returned by C<ParamValues> can be passed to another
6358bind_param() method with the same TYPE and will be seen by the
6359database as the same value.
6360
6361It is also possible that the keys in the hash returned by C<ParamValues>
6362are not exactly the same as those implied by the prepared statement.
6363For example, DBD::Oracle translates 'C<?>' placeholders into 'C<:pN>'
6364where N is a sequence number starting at 1.
6365
6366The C<ParamValues> attribute was added in DBI 1.28.
6367
6368=item C<ParamArrays> (hash ref, read-only)
6369
6370Returns a reference to a hash containing the values currently bound to
6371placeholders with L</execute_array> or L</bind_param_array>. The
6372keys of the hash are the 'names' of the placeholders, typically
6373integers starting at 1. Returns undef if not supported by the driver
6374or no arrays of parameters are bound.
6375
6376Each key value is an array reference containing a list of the bound
6377parameters for that column.
6378
6379For example:
6380
6381 $sth = $dbh->prepare("INSERT INTO staff (id, name) values (?,?)");
6382 $sth->execute_array({},[1,2], ['fred','dave']);
6383 if ($sth->{ParamArrays}) {
6384 foreach $param (keys %{$sth->{ParamArrays}}) {
6385 printf "Parameters for %s : %s\n", $param,
6386 join(",", @{$sth->{ParamArrays}->{$param}});
6387 }
6388 }
6389
6390It is possible that the values in the hash returned by C<ParamArrays>
6391are not I<exactly> the same as those passed to L</bind_param_array> or
6392L</execute_array>. The driver may have slightly modified values in some
6393way based on the TYPE the value was bound with. For example a floating
6394point value bound as an SQL_INTEGER type may be returned as an
6395integer.
6396
6397It is also possible that the keys in the hash returned by
6398C<ParamArrays> are not exactly the same as those implied by the
6399prepared statement. For example, DBD::Oracle translates 'C<?>'
6400placeholders into 'C<:pN>' where N is a sequence number starting at 1.
6401
6402=item C<ParamTypes> (hash ref, read-only)
6403
6404Returns a reference to a hash containing the type information
6405currently bound to placeholders. The keys of the hash are the
6406'names' of the placeholders: either integers starting at 1, or,
6407for drivers that support named placeholders, the actual parameter
6408name string. The hash values are hashrefs of type information in
6409the same form as that provided to the various bind_param() methods
6410(See L</"Data Types for Placeholders"> for the format and values),
6411plus anything else that was passed as the third argument to bind_param().
6412Returns undef if not supported by the driver.
6413
6414If the driver supports C<ParamTypes>, but no values have been bound
6415yet, then the driver should return a hash with the placeholder name
6416keys, but all the values undef; however, some drivers may return
6417a ref to an empty hash, or, alternately, may provide type
6418information supplied by the database (only a few databases can do that).
6419
6420It is possible that the values in the hash returned by C<ParamTypes>
6421are not I<exactly> the same as those passed to bind_param() or execute().
6422The driver may have modified the type information in some way based
6423on the bound values, other hints provided by the prepare()'d
6424SQL statement, or alternate type mappings required by the driver or target
6425database system.
6426
6427It is also possible that the keys in the hash returned by C<ParamTypes>
6428are not exactly the same as those implied by the prepared statement.
6429For example, DBD::Oracle translates 'C<?>' placeholders into 'C<:pN>'
6430where N is a sequence number starting at 1.
6431
6432The C<ParamTypes> attribute was added in DBI 1.49. Implementation
6433is the responsibility of individual drivers; the DBI layer default
6434implementation simply returns undef.
6435
6436
6437=item C<Statement> (string, read-only)
6438
6439Returns the statement string passed to the L</prepare> method.
6440
6441
6442=item C<RowsInCache> (integer, read-only)
6443
6444If the driver supports a local row cache for C<SELECT> statements, then
6445this attribute holds the number of un-fetched rows in the cache. If the
6446driver doesn't, then it returns C<undef>. Note that some drivers pre-fetch
6447rows on execute, whereas others wait till the first fetch.
6448
6449See also the L</RowCacheSize> database handle attribute.
6450
6451=back
6452
6453=head1 OTHER METHODS
6454
6455=over 4
6456
6457=item C<install_method>
6458
6459 DBD::Foo::db->install_method($method_name, \%attr);
6460
6461Installs the driver-private method named by $method_name into the
6462DBI method dispatcher so it can be called directly, avoiding the
6463need to use the func() method.
6464
6465It is called as a static method on the driver class to which the
6466method belongs. The method name must begin with the corresponding
6467registered driver-private prefix. For example, for DBD::Oracle
6468$method_name must being with 'C<ora_>', and for DBD::AnyData it
6469must begin with 'C<ad_>'.
6470
6471The attributes can be used to provide fine control over how the DBI
6472dispatcher handles the dispatching of the method. However, at this
6473point, it's undocumented and very liable to change. (Volunteers to
6474polish up and document the interface are very welcome to get in
6475touch via dbi-dev@perl.org)
6476
6477Methods installed using install_method default to the standard error
6478handling behaviour for DBI methods: clearing err and errstr before
6479calling the method, and checking for errors to trigger RaiseError
6480etc. on return. This differs from the default behaviour of func().
6481
6482Note for driver authors: The DBD::Foo::xx->install_method call won't
6483work until the class-hierarchy has been setup. Normally the DBI
6484looks after that just after the driver is loaded. This means
6485install_method() can't be called at the time the driver is loaded
6486unless the class-hierarchy is set up first. The way to do that is
6487to call the setup_driver() method:
6488
6489 DBI->setup_driver('DBD::Foo');
6490
6491before using install_method().
6492
6493
6494=back
6495
6496=head1 FURTHER INFORMATION
6497
6498=head2 Catalog Methods
6499
6500An application can retrieve metadata information from the DBMS by issuing
6501appropriate queries on the views of the Information Schema. Unfortunately,
6502C<INFORMATION_SCHEMA> views are seldom supported by the DBMS.
6503Special methods (catalog methods) are available to return result sets
6504for a small but important portion of that metadata:
6505
6506 column_info
6507 foreign_key_info
6508 primary_key_info
6509 table_info
6510 statistics_info
6511
6512All catalog methods accept arguments in order to restrict the result sets.
6513Passing C<undef> to an optional argument does not constrain the search for
6514that argument.
6515However, an empty string ('') is treated as a regular search criteria
6516and will only match an empty value.
6517
6518B<Note>: SQL/CLI and ODBC differ in the handling of empty strings. An
6519empty string will not restrict the result set in SQL/CLI.
6520
6521Most arguments in the catalog methods accept only I<ordinary values>, e.g.
6522the arguments of C<primary_key_info()>.
6523Such arguments are treated as a literal string, i.e. the case is significant
6524and quote characters are taken literally.
6525
6526Some arguments in the catalog methods accept I<search patterns> (strings
6527containing '_' and/or '%'), e.g. the C<$table> argument of C<column_info()>.
6528Passing '%' is equivalent to leaving the argument C<undef>.
6529
6530B<Caveat>: The underscore ('_') is valid and often used in SQL identifiers.
6531Passing such a value to a search pattern argument may return more rows than
6532expected!
6533To include pattern characters as literals, they must be preceded by an
6534escape character which can be achieved with
6535
6536 $esc = $dbh->get_info( 14 ); # SQL_SEARCH_PATTERN_ESCAPE
6537 $search_pattern =~ s/([_%])/$esc$1/g;
6538
6539The ODBC and SQL/CLI specifications define a way to change the default
6540behaviour described above: All arguments (except I<list value arguments>)
6541are treated as I<identifier> if the C<SQL_ATTR_METADATA_ID> attribute is
6542set to C<SQL_TRUE>.
6543I<Quoted identifiers> are very similar to I<ordinary values>, i.e. their
6544body (the string within the quotes) is interpreted literally.
6545I<Unquoted identifiers> are compared in UPPERCASE.
6546
6547The DBI (currently) does not support the C<SQL_ATTR_METADATA_ID> attribute,
6548i.e. it behaves like an ODBC driver where C<SQL_ATTR_METADATA_ID> is set to
6549C<SQL_FALSE>.
6550
6551
6552=head2 Transactions
6553
6554Transactions are a fundamental part of any robust database system. They
6555protect against errors and database corruption by ensuring that sets of
6556related changes to the database take place in atomic (indivisible,
6557all-or-nothing) units.
6558
6559This section applies to databases that support transactions and where
6560C<AutoCommit> is off. See L</AutoCommit> for details of using C<AutoCommit>
6561with various types of databases.
6562
6563The recommended way to implement robust transactions in Perl
6564applications is to use C<RaiseError> and S<C<eval { ... }>>
6565(which is very fast, unlike S<C<eval "...">>). For example:
6566
6567 $dbh->{AutoCommit} = 0; # enable transactions, if possible
6568 $dbh->{RaiseError} = 1;
6569 eval {
6570 foo(...) # do lots of work here
6571 bar(...) # including inserts
6572 baz(...) # and updates
6573 $dbh->commit; # commit the changes if we get this far
6574 };
6575 if ($@) {
6576 warn "Transaction aborted because $@";
6577 # now rollback to undo the incomplete changes
6578 # but do it in an eval{} as it may also fail
6579 eval { $dbh->rollback };
6580 # add other application on-error-clean-up code here
6581 }
6582
6583If the C<RaiseError> attribute is not set, then DBI calls would need to be
6584manually checked for errors, typically like this:
6585
6586 $h->method(@args) or die $h->errstr;
6587
6588With C<RaiseError> set, the DBI will automatically C<die> if any DBI method
6589call on that handle (or a child handle) fails, so you don't have to
6590test the return value of each method call. See L</RaiseError> for more
6591details.
6592
6593A major advantage of the C<eval> approach is that the transaction will be
6594properly rolled back if I<any> code (not just DBI calls) in the inner
6595application dies for any reason. The major advantage of using the
6596C<$h-E<gt>{RaiseError}> attribute is that all DBI calls will be checked
6597automatically. Both techniques are strongly recommended.
6598
6599After calling C<commit> or C<rollback> many drivers will not let you
6600fetch from a previously active C<SELECT> statement handle that's a child
6601of the same database handle. A typical way round this is to connect the
6602the database twice and use one connection for C<SELECT> statements.
6603
6604See L</AutoCommit> and L</disconnect> for other important information
6605about transactions.
6606
6607
6608=head2 Handling BLOB / LONG / Memo Fields
6609
6610Many databases support "blob" (binary large objects), "long", or similar
6611datatypes for holding very long strings or large amounts of binary
6612data in a single field. Some databases support variable length long
6613values over 2,000,000,000 bytes in length.
6614
6615Since values of that size can't usually be held in memory, and because
6616databases can't usually know in advance the length of the longest long
6617that will be returned from a C<SELECT> statement (unlike other data
6618types), some special handling is required.
6619
6620In this situation, the value of the C<$h-E<gt>{LongReadLen}>
6621attribute is used to determine how much buffer space to allocate
6622when fetching such fields. The C<$h-E<gt>{LongTruncOk}> attribute
6623is used to determine how to behave if a fetched value can't fit
6624into the buffer.
6625
6626See the description of L</LongReadLen> for more information.
6627
6628When trying to insert long or binary values, placeholders should be used
6629since there are often limits on the maximum size of an C<INSERT>
6630statement and the L</quote> method generally can't cope with binary
6631data. See L</Placeholders and Bind Values>.
6632
6633
6634=head2 Simple Examples
6635
6636Here's a complete example program to select and fetch some data:
6637
6638 my $data_source = "dbi::DriverName:db_name";
6639 my $dbh = DBI->connect($data_source, $user, $password)
6640 or die "Can't connect to $data_source: $DBI::errstr";
6641
6642 my $sth = $dbh->prepare( q{
6643 SELECT name, phone
6644 FROM mytelbook
6645 }) or die "Can't prepare statement: $DBI::errstr";
6646
6647 my $rc = $sth->execute
6648 or die "Can't execute statement: $DBI::errstr";
6649
6650 print "Query will return $sth->{NUM_OF_FIELDS} fields.\n\n";
6651 print "Field names: @{ $sth->{NAME} }\n";
6652
6653 while (($name, $phone) = $sth->fetchrow_array) {
6654 print "$name: $phone\n";
6655 }
6656 # check for problems which may have terminated the fetch early
6657 die $sth->errstr if $sth->err;
6658
6659 $dbh->disconnect;
6660
6661Here's a complete example program to insert some data from a file.
6662(This example uses C<RaiseError> to avoid needing to check each call).
6663
6664 my $dbh = DBI->connect("dbi:DriverName:db_name", $user, $password, {
6665 RaiseError => 1, AutoCommit => 0
6666 });
6667
6668 my $sth = $dbh->prepare( q{
6669 INSERT INTO table (name, phone) VALUES (?, ?)
6670 });
6671
6672 open FH, "<phone.csv" or die "Unable to open phone.csv: $!";
6673 while (<FH>) {
6674 chomp;
6675 my ($name, $phone) = split /,/;
6676 $sth->execute($name, $phone);
6677 }
6678 close FH;
6679
6680 $dbh->commit;
6681 $dbh->disconnect;
6682
6683Here's how to convert fetched NULLs (undefined values) into empty strings:
6684
6685 while($row = $sth->fetchrow_arrayref) {
6686 # this is a fast and simple way to deal with nulls:
6687 foreach (@$row) { $_ = '' unless defined }
6688 print "@$row\n";
6689 }
6690
6691The C<q{...}> style quoting used in these examples avoids clashing with
6692quotes that may be used in the SQL statement. Use the double-quote like
6693C<qq{...}> operator if you want to interpolate variables into the string.
6694See L<perlop/"Quote and Quote-like Operators"> for more details.
6695
6696=head2 Threads and Thread Safety
6697
6698Perl 5.7 and later support a new threading model called iThreads.
6699(The old "5.005 style" threads are not supported by the DBI.)
6700
6701In the iThreads model each thread has it's own copy of the perl
6702interpreter. When a new thread is created the original perl
6703interpreter is 'cloned' to create a new copy for the new thread.
6704
6705If the DBI and drivers are loaded and handles created before the
6706thread is created then it will get a cloned copy of the DBI, the
6707drivers and the handles.
6708
6709However, the internal pointer data within the handles will refer
6710to the DBI and drivers in the original interpreter. Using those
6711handles in the new interpreter thread is not safe, so the DBI detects
6712this and croaks on any method call using handles that don't belong
6713to the current thread (except for DESTROY).
6714
6715Because of this (possibly temporary) restriction, newly created
6716threads must make their own connctions to the database. Handles
6717can't be shared across threads.
6718
6719But BEWARE, some underlying database APIs (the code the DBD driver
6720uses to talk to the database, often supplied by the database vendor)
6721are not thread safe. If it's not thread safe, then allowing more
6722than one thread to enter the code at the same time may cause
6723subtle/serious problems. In some cases allowing more than
6724one thread to enter the code, even if I<not> at the same time,
6725can cause problems. You have been warned.
6726
6727Using DBI with perl threads is not yet recommended for production
6728environments. For more information see
6729L<http://www.perlmonks.org/index.pl?node_id=288022>
6730
6731Note: There is a bug in perl 5.8.2 when configured with threads
6732and debugging enabled (bug #24463) which causes a DBI test to fail.
6733
6734=head2 Signal Handling and Canceling Operations
6735
6736[The following only applies to systems with unix-like signal handling.
6737I'd welcome additions for other systems, especially Windows.]
6738
6739The first thing to say is that signal handling in Perl versions less
6740than 5.8 is I<not> safe. There is always a small risk of Perl
6741crashing and/or core dumping when, or after, handling a signal
6742because the signal could arrive and be handled while internal data
6743structures are being changed. If the signal handling code
6744used those same internal data structures it could cause all manner
6745of subtle and not-so-subtle problems. The risk was reduced with
67465.4.4 but was still present in all perls up through 5.8.0.
6747
6748Beginning in perl 5.8.0 perl implements 'safe' signal handling if
6749your system has the POSIX sigaction() routine. Now when a signal
6750is delivered perl just makes a note of it but does I<not> run the
6751%SIG handler. The handling is 'defered' until a 'safe' moment.
6752
6753Although this change made signal handling safe, it also lead to
6754a problem with signals being defered for longer than you'd like.
6755If a signal arrived while executing a system call, such as waiting
6756for data on a network connection, the signal is noted and then the
6757system call that was executing returns with an EINTR error code
6758to indicate that it was interrupted. All fine so far.
6759
6760The problem comes when the code that made the system call sees the
6761EINTR code and decides it's going to call it again. Perl doesn't
6762do that, but database code sometimes does. If that happens then the
6763signal handler doesn't get called untill later. Maybe much later.
6764
6765Fortunately there are ways around this which we'll discuss below.
6766Unfortunately they make signals unsafe again.
6767
6768The two most common uses of signals in relation to the DBI are for
6769canceling operations when the user types Ctrl-C (interrupt), and for
6770implementing a timeout using C<alarm()> and C<$SIG{ALRM}>.
6771
6772=over 4
6773
6774=item Cancel
6775
6776The DBI provides a C<cancel> method for statement handles. The
6777C<cancel> method should abort the current operation and is designed
6778to be called from a signal handler. For example:
6779
6780 $SIG{INT} = sub { $sth->cancel };
6781
6782However, few drivers implement this (the DBI provides a default
6783method that just returns C<undef>) and, even if implemented, there
6784is still a possibility that the statement handle, and even the
6785parent database handle, will not be usable afterwards.
6786
6787If C<cancel> returns true, then it has successfully
6788invoked the database engine's own cancel function. If it returns false,
6789then C<cancel> failed. If it returns C<undef>, then the database
6790driver does not have cancel implemented.
6791
6792=item Timeout
6793
6794The traditional way to implement a timeout is to set C<$SIG{ALRM}>
6795to refer to some code that will be executed when an ALRM signal
6796arrives and then to call alarm($seconds) to schedule an ALRM signal
6797to be delivered $seconds in the future. For example:
6798
6799 eval {
6800 local $SIG{ALRM} = sub { die "TIMEOUT\n" };
6801 alarm($seconds);
6802 ... code to execute with timeout here ...
6803 alarm(0); # cancel alarm (if code ran fast)
6804 };
6805 alarm(0); # cancel alarm (if eval failed)
6806 if ( $@ eq "TIMEOUT" ) { ... }
6807
6808Unfortunately, as described above, this won't always work as expected,
6809depending on your perl version and the underlying database code.
6810
6811With Oracle for instance (DBD::Oracle), if the system which hosts
6812the database is down the DBI->connect() call will hang for several
6813minutes before returning an error.
6814
6815=back
6816
6817The solution on these systems is to use the C<POSIX::sigaction()>
6818routine to gain low level access to how the signal handler is installed.
6819
6820The code would look something like this (for the DBD-Oracle connect()):
6821
6822 use POSIX ':signal_h';
6823
6824 my $mask = POSIX::SigSet->new( SIGALRM ); # signals to mask in the handler
6825 my $action = POSIX::SigAction->new(
6826 sub { die "connect timeout" }, # the handler code ref
6827 $mask,
6828 # not using (perl 5.8.2 and later) 'safe' switch or sa_flags
6829 );
6830 my $oldaction = POSIX::SigAction->new();
6831 sigaction( 'ALRM', $action, $oldaction );
6832 my $dbh;
6833 eval {
6834 alarm(5); # seconds before time out
6835 $dbh = DBI->connect("dbi:Oracle:$dsn" ... );
6836 alarm(0); # cancel alarm (if connect worked fast)
6837 };
6838 alarm(0); # cancel alarm (if eval failed)
6839 sigaction( 'ALRM', $oldaction ); # restore original signal handler
6840 if ( $@ ) ....
6841
6842Similar techniques can be used for canceling statement execution.
6843
6844Unfortunately, this solution is somewhat messy, and it does I<not> work with
6845perl versions less than perl 5.8 where C<POSIX::sigaction()> appears to be broken.
6846
6847For a cleaner implementation that works across perl versions, see Lincoln Baxter's
6848Sys::SigAction module at L<http://search.cpan.org/~lbaxter/Sys-SigAction/>.
6849The documentation for Sys::SigAction includes an longer discussion
6850of this problem, and a DBD::Oracle test script.
6851
6852Be sure to read all the signal handling sections of the L<perlipc> manual.
6853
6854And finally, two more points to keep firmly in mind. Firstly,
6855remember that what we've done here is essentially revert to old
6856style I<unsafe> handling of these signals. So do as little as
6857possible in the handler. Ideally just die(). Secondly, the handles
6858in use at the time the signal is handled may not be safe to use
6859afterwards.
6860
6861
6862=head2 Subclassing the DBI
6863
6864DBI can be subclassed and extended just like any other object
6865oriented module. Before we talk about how to do that, it's important
6866to be clear about the various DBI classes and how they work together.
6867
6868By default C<$dbh = DBI-E<gt>connect(...)> returns a $dbh blessed
6869into the C<DBI::db> class. And the C<$dbh-E<gt>prepare> method
6870returns an $sth blessed into the C<DBI::st> class (actually it
6871simply changes the last four characters of the calling handle class
6872to be C<::st>).
6873
6874The leading 'C<DBI>' is known as the 'root class' and the extra
6875'C<::db>' or 'C<::st>' are the 'handle type suffixes'. If you want
6876to subclass the DBI you'll need to put your overriding methods into
6877the appropriate classes. For example, if you want to use a root class
6878of C<MySubDBI> and override the do(), prepare() and execute() methods,
6879then your do() and prepare() methods should be in the C<MySubDBI::db>
6880class and the execute() method should be in the C<MySubDBI::st> class.
6881
6882To setup the inheritance hierarchy the @ISA variable in C<MySubDBI::db>
6883should include C<DBI::db> and the @ISA variable in C<MySubDBI::st>
6884should include C<DBI::st>. The C<MySubDBI> root class itself isn't
6885currently used for anything visible and so, apart from setting @ISA
6886to include C<DBI>, it can be left empty.
6887
6888So, having put your overriding methods into the right classes, and
6889setup the inheritance hierarchy, how do you get the DBI to use them?
6890You have two choices, either a static method call using the name
6891of your subclass:
6892
6893 $dbh = MySubDBI->connect(...);
6894
6895or specifying a C<RootClass> attribute:
6896
6897 $dbh = DBI->connect(..., { RootClass => 'MySubDBI' });
6898
6899If both forms are used then the attribute takes precedence.
6900
6901The only differences between the two are that using an explicit
6902RootClass attribute will a) make the DBI automatically attempt to load
6903a module by that name if the class doesn't exist, and b) won't call
6904your MySubDBI::connect() method, if you have one.
6905
6906When subclassing is being used then, after a successful new
6907connect, the DBI->connect method automatically calls:
6908
6909 $dbh->connected($dsn, $user, $pass, \%attr);
6910
6911The default method does nothing. The call is made just to simplify
6912any post-connection setup that your subclass may want to perform.
6913The parameters are the same as passed to DBI->connect.
6914If your subclass supplies a connected method, it should be part of the
6915MySubDBI::db package.
6916
6917One more thing to note: you must let the DBI do the handle creation. If you
6918want to override the connect() method in your *::dr class then it must still
6919call SUPER::connect to get a $dbh to work with. Similarly, an overridden
6920prepare() method in *::db must still call SUPER::prepare to get a $sth.
6921If you try to create your own handles using bless() then you'll find the DBI
6922will reject them with an "is not a DBI handle (has no magic)" error.
6923
6924Here's a brief example of a DBI subclass. A more thorough example
6925can be found in F<t/subclass.t> in the DBI distribution.
6926
6927 package MySubDBI;
6928
6929 use strict;
6930
6931 use DBI;
6932 use vars qw(@ISA);
6933 @ISA = qw(DBI);
6934
6935 package MySubDBI::db;
6936 use vars qw(@ISA);
6937 @ISA = qw(DBI::db);
6938
6939 sub prepare {
6940 my ($dbh, @args) = @_;
6941 my $sth = $dbh->SUPER::prepare(@args)
6942 or return;
6943 $sth->{private_mysubdbi_info} = { foo => 'bar' };
6944 return $sth;
6945 }
6946
6947 package MySubDBI::st;
6948 use vars qw(@ISA);
6949 @ISA = qw(DBI::st);
6950
6951 sub fetch {
6952 my ($sth, @args) = @_;
6953 my $row = $sth->SUPER::fetch(@args)
6954 or return;
6955 do_something_magical_with_row_data($row)
6956 or return $sth->set_err(1234, "The magic failed", undef, "fetch");
6957 return $row;
6958 }
6959
6960When calling a SUPER::method that returns a handle, be careful to
6961check the return value before trying to do other things with it in
6962your overridden method. This is especially important if you want to
6963set a hash attribute on the handle, as Perl's autovivification will
6964bite you by (in)conveniently creating an unblessed hashref, which your
6965method will then return with usually baffling results later on like
6966the error "dbih_getcom handle HASH(0xa4451a8) is not a DBI handle (has
6967no magic". It's best to check right after the call and return undef
6968immediately on error, just like DBI would and just like the example
6969above.
6970
6971If your method needs to record an error it should call the set_err()
6972method with the error code and error string, as shown in the example
6973above. The error code and error string will be recorded in the
6974handle and available via C<$h-E<gt>err> and C<$DBI::errstr> etc.
6975The set_err() method always returns an undef or empty list as
6976approriate. Since your method should nearly always return an undef
6977or empty list as soon as an error is detected it's handy to simply
6978return what set_err() returns, as shown in the example above.
6979
6980If the handle has C<RaiseError>, C<PrintError>, or C<HandleError>
6981etc. set then the set_err() method will honour them. This means
6982that if C<RaiseError> is set then set_err() won't return in the
6983normal way but will 'throw an exception' that can be caught with
6984an C<eval> block.
6985
6986You can stash private data into DBI handles
6987via C<$h-E<gt>{private_..._*}>. See the entry under L</ATTRIBUTES
6988COMMON TO ALL HANDLES> for info and important caveats.
6989
6990
6991=head1 TRACING
6992
6993The DBI has a powerful tracing mechanism built in. It enables you
6994to see what's going on 'behind the scenes', both within the DBI and
6995the drivers you're using.
6996
6997=head2 Trace Settings
6998
6999Which details are written to the trace output is controlled by a
7000combination of a I<trace level>, an integer from 0 to 15, and a set
7001of I<trace flags> that are either on or off. Together these are known
7002as the I<trace settings> and are stored together in a single integer.
7003For normal use you only need to set the trace level, and generally
7004only to a value between 1 and 4.
7005
7006Each handle has it's own trace settings, and so does the DBI.
7007When you call a method the DBI merges the handles settings into its
7008own for the duration of the call: the trace flags of the handle are
7009OR'd into the trace flags of the DBI, and if the handle has a higher
7010trace level then the DBI trace level is raised to match it.
7011The previous DBI trace setings are restored when the called method
7012returns.
7013
7014=head2 Trace Levels
7015
7016Trace I<levels> are as follows:
7017
7018 0 - Trace disabled.
7019 1 - Trace DBI method calls returning with results or errors.
7020 2 - Trace method entry with parameters and returning with results.
7021 3 - As above, adding some high-level information from the driver
7022 and some internal information from the DBI.
7023 4 - As above, adding more detailed information from the driver.
7024 5 to 15 - As above but with more and more obscure information.
7025
7026Trace level 1 is best for a simple overview of what's happening.
7027Trace level 2 is a good choice for general purpose tracing.
7028Levels 3 and above are best reserved for investigating a specific
7029problem, when you need to see "inside" the driver and DBI.
7030
7031The trace output is detailed and typically very useful. Much of the
7032trace output is formatted using the L</neat> function, so strings
7033in the trace output may be edited and truncated by that function.
7034
7035=head2 Trace Flags
7036
7037Trace I<flags> are used to enable tracing of specific activities
7038within the DBI and drivers. The DBI defines some trace flags and
7039drivers can define others. DBI trace flag names begin with a capital
7040letter and driver specific names begin with a lowercase letter, as
7041usual.
7042
7043Curently the DBI only defines two trace flags:
7044
7045 ALL - turn on all DBI and driver flags (not recommended)
7046 SQL - trace SQL statements executed (not yet implemented)
7047
7048The L</parse_trace_flags> and L</parse_trace_flag> methods are used
7049to convert trace flag names into the coresponding integer bit flags.
7050
7051=head2 Enabling Trace
7052
7053The C<$h-E<gt>trace> method sets the trace settings for a handle
7054and C<DBI-E<gt>trace> does the same for the DBI.
7055
7056In addition to the L</trace> method, you can enable the same trace
7057information, and direct the output to a file, by setting the
7058C<DBI_TRACE> environment variable before starting Perl.
7059See L</DBI_TRACE> for more information.
7060
7061Finally, you can set, or get, the trace settings for a handle using
7062the C<TraceLevel> attribute.
7063
7064All of those methods use parse_trace_flags() and so allow you set
7065both the trace level and multiple trace flags by using a string
7066containing the trace level and/or flag names separated by vertical
7067bar ("C<|>") or comma ("C<,>") characters. For example:
7068
7069 local $h->{TraceLevel} = "3|SQL|foo";
7070
7071=head2 Trace Output
7072
7073Initially trace output is written to C<STDERR>. Both the
7074C<$h-E<gt>trace> and C<DBI-E<gt>trace> methods take an optional
7075$trace_file parameter, which may be either the name of a file to be
7076openned by DBI in append mode, or a reference to an existing writable
7077(possibly layered) filehandle. If $trace_file is a filename,
7078and can be opened in append mode, or $trace_file is a writable
7079filehandle, then I<all> trace output (currently including that from
7080other handles) is redirected to that file. A warning is generated
7081if $trace_file can't be opened or is not writable.
7082
7083Further calls to trace() without $trace_file do not alter where
7084the trace output is sent. If $trace_file is undefined, then
7085trace output is sent to C<STDERR> and, if the prior trace was openned with
7086$trace_file as a filename, the previous trace file is closed; if $trace_file was
7087a filehandle, the filehandle is B<not> closed.
7088
7089B<NOTE>: If $trace_file is specified as a filehandle, the filehandle
7090should not be closed until all DBI operations are completed, or the
7091application has reset the trace file via another call to
7092C<trace()> that changes the trace file.
7093
7094=head2 Tracing to Layered Filehandles
7095
7096B<NOTE>:
7097
7098=over 4
7099
7100=item *
7101Tied filehandles are not currently supported, as
7102tie operations are not available to the PerlIO
7103methods used by the DBI.
7104
7105=item *
7106PerlIO layer support requires Perl version 5.8 or higher.
7107
7108=back
7109
7110As of version 5.8, Perl provides the ability to layer various
7111"disciplines" on an open filehandle via the L<PerlIO> module.
7112
7113A simple example of using PerlIO layers is to use a scalar as the output:
7114
7115 my $scalar = '';
7116 open( my $fh, "+>:scalar", \$scalar );
7117 $dbh->trace( 2, $fh );
7118
7119Now all trace output is simply appended to $scalar.
7120
7121A more complex application of tracing to a layered filehandle is the
7122use of a custom layer (I<Refer to >L<Perlio::via> I<for details
7123on creating custom PerlIO layers.>). Consider an application with the
7124following logger module:
7125
7126 package MyFancyLogger;
7127
7128 sub new
7129 {
7130 my $self = {};
7131 my $fh;
7132 open $fh, '>', 'fancylog.log';
7133 $self->{_fh} = $fh;
7134 $self->{_buf} = '';
7135 return bless $self, shift;
7136 }
7137
7138 sub log
7139 {
7140 my $self = shift;
7141 return unless exists $self->{_fh};
7142 my $fh = $self->{_fh};
7143 $self->{_buf} .= shift;
7144 #
7145 # DBI feeds us pieces at a time, so accumulate a complete line
7146 # before outputing
7147 #
7148 print $fh "At ", scalar localtime(), ':', $self->{_buf}, "\n" and
7149 $self->{_buf} = ''
7150 if $self->{_buf}=~tr/\n//;
7151 }
7152
7153 sub close {
7154 my $self = shift;
7155 return unless exists $self->{_fh};
7156 my $fh = $self->{_fh};
7157 print $fh "At ", scalar localtime(), ':', $self->{_buf}, "\n" and
7158 $self->{_buf} = ''
7159 if $self->{_buf};
7160 close $fh;
7161 delete $self->{_fh};
7162 }
7163
7164 1;
7165
7166To redirect DBI traces to this logger requires creating
7167a package for the layer:
7168
7169 package PerlIO::via::MyFancyLogLayer;
7170
7171 sub PUSHED
7172 {
7173 my ($class,$mode,$fh) = @_;
7174 my $logger;
7175 return bless \$logger,$class;
7176 }
7177
7178 sub OPEN {
7179 my ($self, $path, $mode, $fh) = @_;
7180 #
7181 # $path is actually our logger object
7182 #
7183 $$self = $path;
7184 return 1;
7185 }
7186
7187 sub WRITE
7188 {
7189 my ($self, $buf, $fh) = @_;
7190 $$self->log($buf);
7191 return length($buf);
7192 }
7193
7194 sub CLOSE {
7195 my $self = shift;
7196 $$self->close();
7197 return 0;
7198 }
7199
7200 1;
7201
7202
7203The application can then cause DBI traces to be routed to the
7204logger using
7205
7206 use PerlIO::via::MyFancyLogLayer;
7207
7208 open my $fh, '>:via(MyFancyLogLayer)', MyFancyLogger->new();
7209
7210 $dbh->trace('SQL', $fh);
7211
7212Now all trace output will be processed by MyFancyLogger's
7213log() method.
7214
7215=head2 Trace Content
7216
7217Many of the values embeded in trace output are formatted using the neat()
7218utility function. This means they may be quoted, sanitized, and possibly
7219truncated if longer than C<$DBI::neat_maxlen>. See L</neat> for more details.
7220
7221=head2 Tracing Tips
7222
7223You can add tracing to your own application code using the
7224L</trace_msg> method.
7225
7226It can sometimes be handy to compare trace files from two different
7227runs of the same script. However using a tool like C<diff> doesn't work
7228well because the trace file is full of object addresses that may
7229differ each run. Here's a handy little command to strip those out:
7230
7231 perl -pe 's/\b0x[\da-f]{6,}/0xNNNN/gi; s/\b[\da-f]{6,}/<long number>/gi'
7232
7233
7234=head1 DBI ENVIRONMENT VARIABLES
7235
7236The DBI module recognizes a number of environment variables, but most of
7237them should not be used most of the time.
7238It is better to be explicit about what you are doing to avoid the need
7239for environment variables, especially in a web serving system where web
7240servers are stingy about which environment variables are available.
7241
7242=head2 DBI_DSN
7243
7244The DBI_DSN environment variable is used by DBI->connect if you do not
7245specify a data source when you issue the connect.
7246It should have a format such as "dbi:Driver:databasename".
7247
7248=head2 DBI_DRIVER
7249
7250The DBI_DRIVER environment variable is used to fill in the database
7251driver name in DBI->connect if the data source string starts "dbi::"
7252(thereby omitting the driver).
7253If DBI_DSN omits the driver name, DBI_DRIVER can fill the gap.
7254
7255=head2 DBI_AUTOPROXY
7256
7257The DBI_AUTOPROXY environment variable takes a string value that starts
7258"dbi:Proxy:" and is typically followed by "hostname=...;port=...".
7259It is used to alter the behaviour of DBI->connect.
7260For full details, see DBI::Proxy documentation.
7261
7262=head2 DBI_USER
7263
7264The DBI_USER environment variable takes a string value that is used as
7265the user name if the DBI->connect call is given undef (as distinct from
7266an empty string) as the username argument.
7267Be wary of the security implications of using this.
7268
7269=head2 DBI_PASS
7270
7271The DBI_PASS environment variable takes a string value that is used as
7272the password if the DBI->connect call is given undef (as distinct from
7273an empty string) as the password argument.
7274Be extra wary of the security implications of using this.
7275
7276=head2 DBI_DBNAME (obsolete)
7277
7278The DBI_DBNAME environment variable takes a string value that is used only when the
7279obsolescent style of DBI->connect (with driver name as fourth parameter) is used, and
7280when no value is provided for the first (database name) argument.
7281
7282=head2 DBI_TRACE
7283
7284The DBI_TRACE environment variable specifies the global default
7285trace settings for the DBI at startup. Can also be used to direct
7286trace output to a file. When the DBI is loaded it does:
7287
7288 DBI->trace(split /=/, $ENV{DBI_TRACE}, 2) if $ENV{DBI_TRACE};
7289
7290So if C<DBI_TRACE> contains an "C<=>" character then what follows
7291it is used as the name of the file to append the trace to.
7292
7293output appended to that file. If the name begins with a number
7294followed by an equal sign (C<=>), then the number and the equal sign are
7295stripped off from the name, and the number is used to set the trace
7296level. For example:
7297
7298 DBI_TRACE=1=dbitrace.log perl your_test_script.pl
7299
7300On Unix-like systems using a Bourne-like shell, you can do this easily
7301on the command line:
7302
7303 DBI_TRACE=2 perl your_test_script.pl
7304
7305See L</TRACING> for more information.
7306
7307=head2 PERL_DBI_DEBUG (obsolete)
7308
7309An old variable that should no longer be used; equivalent to DBI_TRACE.
7310
7311=head2 DBI_PROFILE
7312
7313The DBI_PROFILE environment variable can be used to enable profiling
7314of DBI method calls. See L<DBI::Profile> for more information.
7315
7316=head2 DBI_PUREPERL
7317
7318The DBI_PUREPERL environment variable can be used to enable the
7319use of DBI::PurePerl. See L<DBI::PurePerl> for more information.
7320
7321=head1 WARNING AND ERROR MESSAGES
7322
7323=head2 Fatal Errors
7324
7325=over 4
7326
7327=item Can't call method "prepare" without a package or object reference
7328
7329The C<$dbh> handle you're using to call C<prepare> is probably undefined because
7330the preceding C<connect> failed. You should always check the return status of
7331DBI methods, or use the L</RaiseError> attribute.
7332
7333=item Can't call method "execute" without a package or object reference
7334
7335The C<$sth> handle you're using to call C<execute> is probably undefined because
7336the preceeding C<prepare> failed. You should always check the return status of
7337DBI methods, or use the L</RaiseError> attribute.
7338
7339=item DBI/DBD internal version mismatch
7340
7341The DBD driver module was built with a different version of DBI than
7342the one currently being used. You should rebuild the DBD module under
7343the current version of DBI.
7344
7345(Some rare platforms require "static linking". On those platforms, there
7346may be an old DBI or DBD driver version actually embedded in the Perl
7347executable being used.)
7348
7349=item DBD driver has not implemented the AutoCommit attribute
7350
7351The DBD driver implementation is incomplete. Consult the author.
7352
7353=item Can't [sg]et %s->{%s}: unrecognised attribute
7354
7355You attempted to set or get an unknown attribute of a handle. Make
7356sure you have spelled the attribute name correctly; case is significant
7357(e.g., "Autocommit" is not the same as "AutoCommit").
7358
7359=back
7360
7361=head1 Pure-Perl DBI
7362
7363A pure-perl emulation of the DBI is included in the distribution
7364for people using pure-perl drivers who, for whatever reason, can't
7365install the compiled DBI. See L<DBI::PurePerl>.
7366
7367=head1 SEE ALSO
7368
7369=head2 Driver and Database Documentation
7370
7371Refer to the documentation for the DBD driver that you are using.
7372
7373Refer to the SQL Language Reference Manual for the database engine that you are using.
7374
7375=head2 ODBC and SQL/CLI Standards Reference Information
7376
7377More detailed information about the semantics of certain DBI methods
7378that are based on ODBC and SQL/CLI standards is available on-line
7379via microsoft.com, for ODBC, and www.jtc1sc32.org for the SQL/CLI
7380standard:
7381
7382 DBI method ODBC function SQL/CLI Working Draft
7383 ---------- ------------- ---------------------
7384 column_info SQLColumns Page 124
7385 foreign_key_info SQLForeignKeys Page 163
7386 get_info SQLGetInfo Page 214
7387 primary_key_info SQLPrimaryKeys Page 254
7388 table_info SQLTables Page 294
7389 type_info SQLGetTypeInfo Page 239
7390 statistics_info SQLStatistics
7391
7392For example, for ODBC information on SQLColumns you'd visit:
7393
7394 http://msdn.microsoft.com/library/en-us/odbc/htm/odbcsqlcolumns.asp
7395
7396If that URL ceases to work then use the MSDN search facility at:
7397
7398 http://search.microsoft.com/us/dev/
7399
7400and search for C<SQLColumns returns> using the exact phrase option.
7401The link you want will probably just be called C<SQLColumns> and will
7402be part of the Data Access SDK.
7403
7404And for SQL/CLI standard information on SQLColumns you'd read page 124 of
7405the (very large) SQL/CLI Working Draft available from:
7406
7407 http://jtc1sc32.org/doc/N0701-0750/32N0744T.pdf
7408
7409=head2 Standards Reference Information
7410
7411A hyperlinked, browsable version of the BNF syntax for SQL92 (plus
7412Oracle 7 SQL and PL/SQL) is available here:
7413
7414 http://cui.unige.ch/db-research/Enseignement/analyseinfo/SQL92/BNFindex.html
7415
7416A BNF syntax for SQL3 is available here:
7417
7418 http://www.sqlstandards.org/SC32/WG3/Progression_Documents/Informal_working_drafts/iso-9075-2-1999.bnf
7419
7420The following links provide further useful information about SQL.
7421Some of these are rather dated now but may still be useful.
7422
7423 http://www.jcc.com/SQLPages/jccs_sql.htm
7424 http://www.contrib.andrew.cmu.edu/~shadow/sql.html
7425 http://www.altavista.com/query?q=sql+tutorial
7426
7427
7428=head2 Books and Articles
7429
7430Programming the Perl DBI, by Alligator Descartes and Tim Bunce.
7431L<http://books.perl.org/book/154>
7432
7433Programming Perl 3rd Ed. by Larry Wall, Tom Christiansen & Jon Orwant.
7434L<http://books.perl.org/book/134>
7435
7436Learning Perl by Randal Schwartz.
7437L<http://books.perl.org/book/101>
7438
7439Details of many other books related to perl can be found at L<http://books.perl.org>
7440
7441=head2 Perl Modules
7442
7443Index of DBI related modules available from CPAN:
7444
7445 http://search.cpan.org/search?mode=module&query=DBIx%3A%3A
7446 http://search.cpan.org/search?mode=doc&query=DBI
7447
7448For a good comparison of RDBMS-OO mappers and some OO-RDBMS mappers
7449(including Class::DBI, Alzabo, and DBIx::RecordSet in the former
7450category and Tangram and SPOPS in the latter) see the Perl
7451Object-Oriented Persistence project pages at:
7452
7453 http://poop.sourceforge.net
7454
7455A similar page for Java toolkits can be found at:
7456
7457 http://c2.com/cgi-bin/wiki?ObjectRelationalToolComparison
7458
7459=head2 Mailing List
7460
7461The I<dbi-users> mailing list is the primary means of communication among
7462users of the DBI and its related modules. For details send email to:
7463
7464 dbi-users-help@perl.org
7465
7466There are typically between 700 and 900 messages per month. You have
7467to subscribe in order to be able to post. However you can opt for a
7468'post-only' subscription.
7469
7470Mailing list archives (of variable quality) are held at:
7471
7472 http://groups.google.com/groups?group=perl.dbi.users
7473 http://www.xray.mpe.mpg.de/mailing-lists/dbi/
7474 http://www.mail-archive.com/dbi-users%40perl.org/
7475
7476=head2 Assorted Related WWW Links
7477
7478The DBI "Home Page":
7479
7480 http://dbi.perl.org/
7481
7482Other DBI related links:
7483
7484 http://tegan.deltanet.com/~phlip/DBUIdoc.html
7485 http://dc.pm.org/perl_db.html
7486 http://wdvl.com/Authoring/DB/Intro/toc.html
7487 http://www.hotwired.com/webmonkey/backend/tutorials/tutorial1.html
7488 http://bumppo.net/lists/macperl/1999/06/msg00197.html
7489 http://gmax.oltrelinux.com/dbirecipes.html
7490
7491Other database related links:
7492
7493 http://www.jcc.com/sql_stnd.html
7494 http://cuiwww.unige.ch/OSG/info/FreeDB/FreeDB.home.html
7495 http://www.connectionstrings.com/
7496
7497Security, especially the "SQL Injection" attack:
7498
7499 http://www.ngssoftware.com/research/papers.html
7500 http://www.ngssoftware.com/papers/advanced_sql_injection.pdf
7501 http://www.ngssoftware.com/papers/more_advanced_sql_injection.pdf
7502 http://www.esecurityplanet.com/trends/article.php/2243461
7503 http://www.spidynamics.com/papers/SQLInjectionWhitePaper.pdf
7504 http://www.imperva.com/application_defense_center/white_papers/blind_sql_server_injection.html
7505 http://online.securityfocus.com/infocus/1644
7506
7507Commercial and Data Warehouse Links
7508
7509 http://www.dwinfocenter.org
7510 http://www.datawarehouse.com
7511 http://www.datamining.org
7512 http://www.olapcouncil.org
7513 http://www.idwa.org
7514 http://www.knowledgecenters.org/dwcenter.asp
7515
7516Recommended Perl Programming Links
7517
7518 http://language.perl.com/style/
7519
7520
7521=head2 FAQ
7522
7523Please also read the DBI FAQ which is installed as a DBI::FAQ module.
7524You can use I<perldoc> to read it by executing the C<perldoc DBI::FAQ> command.
7525
7526=head1 AUTHORS
7527
7528DBI by Tim Bunce, L<http://www.linkedin.com/in/timbunce>
7529
7530This pod text by Tim Bunce, J. Douglas Dunlop, Jonathan Leffler and others.
7531Perl by Larry Wall and the C<perl5-porters>.
7532
7533=head1 COPYRIGHT
7534
7535The DBI module is Copyright (c) 1994-2004 Tim Bunce. Ireland.
7536All rights reserved.
7537
7538You may distribute under the terms of either the GNU General Public
7539License or the Artistic License, as specified in the Perl README file.
7540
7541=head1 SUPPORT / WARRANTY
7542
7543The DBI is free Open Source software. IT COMES WITHOUT WARRANTY OF ANY KIND.
7544
7545=head2 Support
7546
7547My consulting company, Data Plan Services, offers annual and
7548multi-annual support contracts for the DBI. These provide sustained
7549support for DBI development, and sustained value for you in return.
7550Contact me for details.
7551
7552=head2 Sponsor Enhancements
7553
7554The DBI Roadmap is available at L<http://search.cpan.org/~timb/DBI/Roadmap.pod>
7555
7556If your company would benefit from a specific new DBI feature,
7557please consider sponsoring its development. Work is performed
7558rapidly, and usually on a fixed-price payment-on-delivery basis.
7559Contact me for details.
7560
7561Using such targeted financing allows you to contribute to DBI
7562development, and rapidly get something specific and valuable in return.
7563
7564=head1 ACKNOWLEDGEMENTS
7565
7566I would like to acknowledge the valuable contributions of the many
7567people I have worked with on the DBI project, especially in the early
7568years (1992-1994). In no particular order: Kevin Stock, Buzz Moschetti,
7569Kurt Andersen, Ted Lemon, William Hails, Garth Kennedy, Michael Peppler,
7570Neil S. Briscoe, Jeff Urlwin, David J. Hughes, Jeff Stander,
7571Forrest D Whitcher, Larry Wall, Jeff Fried, Roy Johnson, Paul Hudson,
7572Georg Rehfeld, Steve Sizemore, Ron Pool, Jon Meek, Tom Christiansen,
7573Steve Baumgarten, Randal Schwartz, and a whole lot more.
7574
7575Then, of course, there are the poor souls who have struggled through
7576untold and undocumented obstacles to actually implement DBI drivers.
7577Among their ranks are Jochen Wiedmann, Alligator Descartes, Jonathan
7578Leffler, Jeff Urlwin, Michael Peppler, Henrik Tougaard, Edwin Pratomo,
7579Davide Migliavacca, Jan Pazdziora, Peter Haworth, Edmund Mergl, Steve
7580Williams, Thomas Lowery, and Phlip Plumlee. Without them, the DBI would
7581not be the practical reality it is today. I'm also especially grateful
7582to Alligator Descartes for starting work on the first edition of the
7583"Programming the Perl DBI" book and letting me jump on board.
7584
7585The DBI and DBD::Oracle were originally developed while I was Technical
7586Director (CTO) of Ingeneering in the UK (L<http://www.ig.co.uk>) (formerly known as the
7587Paul Ingram Group). So I'd especially like to thank Paul for his generosity
7588and vision in supporting this work for many years.
7589
7590A couple of specific DBI features have been sponsored by enlightened companies:
7591
7592The development of the swap_inner_handle() method was sponsored by BizRate.com (L<http://BizRate.com>)
7593
7594The development of DBD::Gofer and related modules was sponsored by
7595Shopzilla.com (L<http://Shopzilla.com>), where I currently work.
7596
7597
7598=head1 CONTRIBUTING
7599
7600As you can see above, many people have contributed to the DBI and
7601drivers in many ways over many years.
7602
7603If you'd like to help then see L<http://dbi.perl.org/contributing>
7604and L<http://search.cpan.org/~timb/DBI/Roadmap.pod>
7605
7606If you'd like the DBI to do something new or different then a good way
7607to make that happen is to do it yourself and send me a patch to the
7608source code that shows the changes. (But read "Speak before you patch"
7609below.)
7610
7611=head2 Browsing the source code repository
7612
7613Use http://svn.perl.org/modules/dbi/trunk (basic)
7614or http://svn.perl.org/viewcvs/modules/ (more useful)
7615
7616=head2 How to create a patch using Subversion
7617
7618The DBI source code is maintained using Subversion (a replacement
7619for CVS, see L<http://subversion.tigris.org/>). To access the source
7620you'll need to install a Subversion client. Then, to get the source
7621code, do:
7622
7623 svn checkout http://svn.perl.org/modules/dbi/trunk
7624
7625If it prompts for a username and password use your perl.org account
7626if you have one, else just 'guest' and 'guest'. The source code will
7627be in a new subdirectory called C<trunk>.
7628
7629To keep informed about changes to the source you can send an empty email
7630to svn-commit-modules-dbi-subscribe@perl.org after which you'll get an email
7631with the change log message and diff of each change checked-in to the source.
7632
7633After making your changes you can generate a patch file, but before
7634you do, make sure your source is still upto date using:
7635
7636 svn update
7637
7638If you get any conflicts reported you'll need to fix them first.
7639Then generate the patch file from within the C<trunk> directory using:
7640
7641 svn diff > foo.patch
7642
7643Read the patch file, as a sanity check, and then email it to dbi-dev@perl.org.
7644
7645=head2 How to create a patch without Subversion
7646
7647Unpack a fresh copy of the distribution:
7648
7649 tar xfz DBI-1.40.tar.gz
7650
7651Rename the newly created top level directory:
7652
7653 mv DBI-1.40 DBI-1.40.your_foo
7654
7655Edit the contents of DBI-1.40.your_foo/* till it does what you want.
7656
7657Test your changes and then remove all temporary files:
7658
7659 make test && make distclean
7660
7661Go back to the directory you originally unpacked the distribution:
7662
7663 cd ..
7664
7665Unpack I<another> copy of the original distribution you started with:
7666
7667 tar xfz DBI-1.40.tar.gz
7668
7669Then create a patch file by performing a recursive C<diff> on the two
7670top level directories:
7671
7672 diff -r -u DBI-1.40 DBI-1.40.your_foo > DBI-1.40.your_foo.patch
7673
7674=head2 Speak before you patch
7675
7676For anything non-trivial or possibly controversial it's a good idea
7677to discuss (on dbi-dev@perl.org) the changes you propose before
7678actually spending time working on them. Otherwise you run the risk
7679of them being rejected because they don't fit into some larger plans
7680you may not be aware of.
7681
7682=head1 TRANSLATIONS
7683
7684A German translation of this manual (possibly slightly out of date) is
7685available, thanks to O'Reilly, at:
7686
7687 http://www.oreilly.de/catalog/perldbiger/
7688
7689Some other translations:
7690
7691 http://cronopio.net/perl/ - Spanish
7692 http://member.nifty.ne.jp/hippo2000/dbimemo.htm - Japanese
7693
7694
7695=head1 TRAINING
7696
7697References to DBI related training resources. No recommendation implied.
7698
7699 http://www.treepax.co.uk/
7700 http://www.keller.com/dbweb/
7701
7702(If you offer professional DBI related training services,
7703please send me your details so I can add them here.)
7704
7705=head1 OTHER RELATED WORK AND PERL MODULES
7706
7707=over 4
7708
7709=item Apache::DBI by E.Mergl@bawue.de
7710
7711To be used with the Apache daemon together with an embedded Perl
7712interpreter like C<mod_perl>. Establishes a database connection which
7713remains open for the lifetime of the HTTP daemon. This way the CGI
7714connect and disconnect for every database access becomes superfluous.
7715
7716=item SQL Parser
7717
7718See also the L<SQL::Statement> module, SQL parser and engine.
7719
7720=back
7721
7722=cut
# spent 515µs within DBD::_::common::CORE:match which was called 62 times, avg 8µs/call: # 31 times (275µs+0s) by DBD::_::common::install_method at line 1352 of DBI.pm, avg 9µs/call # 31 times (240µs+0s) by DBD::_::common::install_method at line 1355 of DBI.pm, avg 8µs/call
sub DBD::_::common::CORE:match; # xsub
# spent 32µs within DBD::_::common::trace_msg which was called 4 times, avg 8µs/call: # once (11µs+0s) by DBI::END at line 498 of DBI.pm # once (8µs+0s) by DBI::_load_class at line 922 of DBI.pm # once (7µs+0s) by DBI::_set_isa at line 819 of DBI.pm # once (6µs+0s) by DBI::_load_class at line 926 of DBI.pm
sub DBD::_::common::trace_msg; # xsub
# spent 29µs within DBD::_::dr::CORE:sort which was called # once (29µs+0s) by DBI::dr::connect_cached at line 1441 of DBI.pm
sub DBD::_::dr::CORE:sort; # xsub
# spent 535µs within DBI::CORE:match which was called 112 times, avg 5µs/call: # 112 times (535µs+0s) by base::import at line 257 of DBI.pm, avg 5µs/call
sub DBI::CORE:match; # xsub
# spent 37µs within DBI::CORE:subst which was called 3 times, avg 12µs/call: # once (18µs+0s) by DBI::connect at line 568 of DBI.pm # once (14µs+0s) by DBI::_load_class at line 925 of DBI.pm # once (5µs+0s) by DBI::install_driver at line 723 of DBI.pm
sub DBI::CORE:subst; # xsub
# spent 6µs within DBI::SQL_DECIMAL which was called # once (6µs+0s) by DBI::install_driver at line 1375 of DBD/Pg.pm
sub DBI::SQL_DECIMAL; # xsub
# spent 6µs within DBI::SQL_DOUBLE which was called # once (6µs+0s) by DBI::install_driver at line 1375 of DBD/Pg.pm
sub DBI::SQL_DOUBLE; # xsub
# spent 6µs within DBI::SQL_FLOAT which was called # once (6µs+0s) by DBI::install_driver at line 1375 of DBD/Pg.pm
sub DBI::SQL_FLOAT; # xsub
# spent 7µs within DBI::SQL_INTEGER which was called # once (7µs+0s) by DBI::install_driver at line 1375 of DBD/Pg.pm
sub DBI::SQL_INTEGER; # xsub
# spent 5µs within DBI::SQL_NUMERIC which was called # once (5µs+0s) by DBI::install_driver at line 1375 of DBD/Pg.pm
sub DBI::SQL_NUMERIC; # xsub
# spent 6µs within DBI::SQL_REAL which was called # once (6µs+0s) by DBI::install_driver at line 1375 of DBD/Pg.pm
sub DBI::SQL_REAL; # xsub
# spent 6µs within DBI::SQL_SMALLINT which was called # once (6µs+0s) by DBI::install_driver at line 1375 of DBD/Pg.pm
sub DBI::SQL_SMALLINT; # xsub
# spent 13µs within DBI::_handles which was called # once (13µs+0s) by DBI::_rebless at line 810 of DBI.pm
sub DBI::_handles; # xsub
# spent 2.45ms within DBI::_install_method which was called 117 times, avg 21µs/call: # 86 times (1.03ms+0s) by base::import at line 481 of DBI.pm, avg 12µs/call # 31 times (1.43ms+0s) by DBD::_::common::install_method at line 1363 of DBI.pm, avg 46µs/call
sub DBI::_install_method; # xsub
# spent 694µs within DBI::_setup_handle which was called 14 times, avg 50µs/call: # 14 times (694µs+0s) by DBI::_new_handle at line 1195 of DBI.pm, avg 50µs/call
sub DBI::_setup_handle; # xsub
# spent 402µs within DBI::bootstrap which was called # once (402µs+0s) by DynaLoader::bootstrap at line 253 of DynaLoader.pm
sub DBI::bootstrap; # xsub
# spent 14µs within DBI::st::bind_col which was called # once (14µs+0s) by DBI::st::bind_columns at line 1843 of DBI.pm
sub DBI::st::bind_col; # xsub
# spent 155µs (126+29) within DBI::st::bind_columns which was called # once (126µs+29µs) by Class::DBI::sth_to_objects at line 1140 of Class/DBI.pm
sub DBI::st::bind_columns; # xsub
# spent 280ms within DBI::st::execute which was called 12 times, avg 23.3ms/call: # 12 times (280ms+0s) by DBIx::ContextualFetch::st::_untaint_execute at line 52 of DBIx/ContextualFetch.pm, avg 23.3ms/call
sub DBI::st::execute; # xsub
# spent 70µs within DBI::st::fetchall_arrayref which was called 2 times, avg 35µs/call: # 2 times (70µs+0s) by Class::DBI::Pg::set_up_table at line 38 of Class/DBI/Pg.pm, avg 35µs/call
sub DBI::st::fetchall_arrayref; # xsub
# spent 287µs within DBI::st::fetchrow_array which was called 9 times, avg 32µs/call: # 4 times (116µs+0s) by Class::DBI::Pg::pg_version at line 93 of Class/DBI/Pg.pm, avg 29µs/call # 2 times (36µs+0s) by Class::DBI::Pg::set_up_table at line 49 of Class/DBI/Pg.pm, avg 18µs/call # 2 times (35µs+0s) by Class::DBI::Pg::set_up_table at line 26 of Class/DBI/Pg.pm, avg 18µs/call # once (100µs+0s) by DBIx::ContextualFetch::st::select_row at line 88 of DBIx/ContextualFetch.pm
sub DBI::st::fetchrow_array; # xsub
# spent 4.20ms within DBI::st::fetchrow_arrayref which was called 462 times, avg 9µs/call: # 462 times (4.20ms+0s) by DBIx::ContextualFetch::st::fetch at line 60 of DBIx/ContextualFetch.pm, avg 9µs/call
sub DBI::st::fetchrow_arrayref; # xsub
# spent 137µs within DBI::st::finish which was called 11 times, avg 12µs/call: # 4 times (55µs+0s) by Class::DBI::Pg::pg_version at line 94 of Class/DBI/Pg.pm, avg 14µs/call # 2 times (24µs+0s) by Class::DBI::Pg::set_up_table at line 27 of Class/DBI/Pg.pm, avg 12µs/call # 2 times (23µs+0s) by Class::DBI::Pg::set_up_table at line 50 of Class/DBI/Pg.pm, avg 12µs/call # 2 times (19µs+0s) by Class::DBI::Pg::set_up_table at line 39 of Class/DBI/Pg.pm, avg 10µs/call # once (16µs+0s) by DBIx::ContextualFetch::st::select_row at line 89 of DBIx/ContextualFetch.pm
sub DBI::st::finish; # xsub