← Index
Performance Profile   « block view • line view • sub view »
For /wise/base/deliv/dev/bin/getfix
  Run on Thu May 20 15:30:03 2010
Reported on Thu May 20 16:25:34 2010

File/wise/base/static/lib/perl5/site_perl/5.10.0/x86_64-linux-thread-multi/DBI.pm
Statements Executed711
Total Time0.017077 seconds

Subroutines — ordered by exclusive time
Calls P F Exclusive
Time
Inclusive
Time
Subroutine
1110.003580.00659DBI::install_driver
88120.000620.00062DBI::_install_method (xsub)
2120.000420.00042DBI::bootstrap (xsub)
6320.000220.00022DBI::_new_handle (xsub)
2210.000210.00028DBI::setup_driver
1110.000160.00500DBI::__ANON__[:703]
1110.000120.01175DBI::connect
3116.2e-50.00018DBI::_new_sth
1113.1e-56.0e-5DBI::disconnect_all
1112.4e-58.5e-5DBI::_new_drh
1112.3e-56.0e-5DBI::_new_dbh
2121.2e-51.2e-5DBD::_::common::trace_msg (xsub)
00000DBD::Switch::dr::CLONE
00000DBD::Switch::dr::FETCH
00000DBD::Switch::dr::STORE
00000DBD::Switch::dr::driver
00000DBD::_::common::BEGIN
00000DBD::_::common::CLEAR
00000DBD::_::common::EXISTS
00000DBD::_::common::FETCH_many
00000DBD::_::common::FIRSTKEY
00000DBD::_::common::NEXTKEY
00000DBD::_::common::_not_impl
00000DBD::_::common::install_method
00000DBD::_::common::parse_trace_flag
00000DBD::_::common::parse_trace_flags
00000DBD::_::common::private_attribute_info
00000DBD::_::db::BEGIN
00000DBD::_::db::_do_selectrow
00000DBD::_::db::begin_work
00000DBD::_::db::clone
00000DBD::_::db::data_sources
00000DBD::_::db::do
00000DBD::_::db::ping
00000DBD::_::db::prepare_cached
00000DBD::_::db::primary_key
00000DBD::_::db::quote
00000DBD::_::db::quote_identifier
00000DBD::_::db::rows
00000DBD::_::db::selectall_arrayref
00000DBD::_::db::selectall_hashref
00000DBD::_::db::selectcol_arrayref
00000DBD::_::db::selectrow_array
00000DBD::_::db::selectrow_arrayref
00000DBD::_::db::selectrow_hashref
00000DBD::_::db::tables
00000DBD::_::db::type_info
00000DBD::_::dr::BEGIN
00000DBD::_::dr::connect
00000DBD::_::dr::connect_cached
00000DBD::_::dr::default_user
00000DBD::_::st::BEGIN
00000DBD::_::st::__ANON__[:1882]
00000DBD::_::st::__ANON__[:1916]
00000DBD::_::st::bind_columns
00000DBD::_::st::bind_param
00000DBD::_::st::bind_param_array
00000DBD::_::st::bind_param_inout_array
00000DBD::_::st::blob_copy_to_file
00000DBD::_::st::execute_array
00000DBD::_::st::execute_for_fetch
00000DBD::_::st::fetchall_arrayref
00000DBD::_::st::fetchall_hashref
00000DBD::_::st::more_results
00000DBI::BEGIN
00000DBI::CLONE
00000DBI::DBI_tie::STORE
00000DBI::DBI_tie::TIEHASH
00000DBI::END
00000DBI::__ANON__[:1088]
00000DBI::__ANON__[:1122]
00000DBI::__ANON__[:1123]
00000DBI::__ANON__[:997]
00000DBI::_dbtype_names
00000DBI::_load_class
00000DBI::_rebless
00000DBI::_rebless_dbtype_subclass
00000DBI::_set_isa
00000DBI::available_drivers
00000DBI::connect_cached
00000DBI::connect_test_perf
00000DBI::data_diff
00000DBI::data_sources
00000DBI::data_string_desc
00000DBI::data_string_diff
00000DBI::disconnect
00000DBI::dump_dbd_registry
00000DBI::dump_results
00000DBI::err
00000DBI::errstr
00000DBI::init_rootclass
00000DBI::installed_drivers
00000DBI::installed_methods
00000DBI::installed_versions
00000DBI::neat_list
00000DBI::parse_dsn
00000DBI::var::STORE
00000DBI::var::TIESCALAR

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