← Index
Performance Profile   « block view • line view • sub view »
For opac/opac-main.pl
  Run on Mon Aug 24 11:28:47 2009
Reported on Mon Aug 24 11:29:08 2009

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