← Index
Performance Profile   « block view • line view • sub view »
For opac/opac-main.pl
  Run on Fri Jul 18 13:58:34 2008
Reported on Fri Jul 18 13:58:41 2008

File/usr/lib/perl5/DBI.pm
Statements Executed1194
Total Time0.00556000000000001 seconds

Subroutines — ordered by inclusive time then name
CallsInclusive
Time
Subroutine
1960.00670DBI::_new_sth
10.00007DBD::_::st::fetchall_arrayref
10.00004DBI::disconnect_all
00DBD::Switch::dr::CLONE
00DBD::Switch::dr::FETCH
00DBD::Switch::dr::STORE
00DBD::Switch::dr::driver
00DBD::_::common::BEGIN
00DBD::_::common::CLEAR
00DBD::_::common::EXISTS
00DBD::_::common::FETCH_many
00DBD::_::common::FIRSTKEY
00DBD::_::common::NEXTKEY
00DBD::_::common::_not_impl
00DBD::_::common::install_method
00DBD::_::common::parse_trace_flag
00DBD::_::common::parse_trace_flags
00DBD::_::common::private_attribute_info
00DBD::_::db::BEGIN
00DBD::_::db::_do_selectrow
00DBD::_::db::begin_work
00DBD::_::db::clone
00DBD::_::db::data_sources
00DBD::_::db::do
00DBD::_::db::ping
00DBD::_::db::prepare_cached
00DBD::_::db::primary_key
00DBD::_::db::quote
00DBD::_::db::quote_identifier
00DBD::_::db::rows
00DBD::_::db::selectall_arrayref
00DBD::_::db::selectall_hashref
00DBD::_::db::selectcol_arrayref
00DBD::_::db::selectrow_array
00DBD::_::db::selectrow_arrayref
00DBD::_::db::selectrow_hashref
00DBD::_::db::tables
00DBD::_::db::type_info
00DBD::_::dr::BEGIN
00DBD::_::dr::connect
00DBD::_::dr::connect_cached
00DBD::_::dr::default_user
00DBD::_::st::BEGIN
00DBD::_::st::__ANON__[:1884]
00DBD::_::st::__ANON__[:1918]
00DBD::_::st::bind_columns
00DBD::_::st::bind_param
00DBD::_::st::bind_param_array
00DBD::_::st::bind_param_inout_array
00DBD::_::st::blob_copy_to_file
00DBD::_::st::execute_array
00DBD::_::st::execute_for_fetch
00DBD::_::st::fetchall_hashref
00DBD::_::st::more_results
00DBI::BEGIN
00DBI::CLONE
00DBI::DBI_tie::STORE
00DBI::DBI_tie::TIEHASH
00DBI::END
00DBI::__ANON__[:1090]
00DBI::__ANON__[:1124]
00DBI::__ANON__[:1125]
00DBI::__ANON__[:705]
00DBI::__ANON__[:999]
00DBI::_dbtype_names
00DBI::_load_class
00DBI::_new_dbh
00DBI::_new_drh
00DBI::_rebless
00DBI::_rebless_dbtype_subclass
00DBI::_set_isa
00DBI::available_drivers
00DBI::connect
00DBI::connect_cached
00DBI::connect_test_perf
00DBI::data_diff
00DBI::data_sources
00DBI::data_string_desc
00DBI::data_string_diff
00DBI::disconnect
00DBI::dump_dbd_registry
00DBI::dump_results
00DBI::err
00DBI::errstr
00DBI::init_rootclass
00DBI::install_driver
00DBI::installed_drivers
00DBI::installed_methods
00DBI::installed_versions
00DBI::neat_list
00DBI::parse_dsn
00DBI::setup_driver
00DBI::var::STORE
00DBI::var::TIESCALAR

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