← Index
NYTProf Performance Profile   « line view »
For starman worker -M FindBin --max-requests 50 --workers 2 --user=kohadev-koha --group kohadev-koha --pid /var/run/koha/kohadev/plack.pid --daemonize --access-log /var/log/koha/kohadev/plack.log --error-log /var/log/koha/kohadev/plack-error.log -E deployment --socket /var/run/koha/kohadev/plack.sock /etc/koha/sites/kohadev/plack.psgi
  Run on Fri Jan 8 14:16:49 2016
Reported on Fri Jan 8 14:23:09 2016

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