Initial commit of OpenSPARC T2 design and verification files.
[OpenSPARC-T2-DV] / tools / perl-5.8.0 / lib / site_perl / 5.8.0 / sun4-solaris / DBI.pm
CommitLineData
86530b38
AT
1# $Id: DBI.pm,v 10.37 2001/06/04 17:20:21 timbo Exp $
2#
3# Copyright (c) 1994-2000 Tim Bunce England
4#
5# See COPYRIGHT section in pod text below for usage and distribution rights.
6#
7
8require 5.004;
9
10BEGIN {
11$DBI::VERSION = "1.18"; # ==> ALSO update the version in the pod text below!
12}
13
14=head1 NAME
15
16DBI - Database independent interface for Perl
17
18=head1 SYNOPSIS
19
20 use DBI;
21
22 @driver_names = DBI->available_drivers;
23 @data_sources = DBI->data_sources($driver_name, \%attr);
24
25 $dbh = DBI->connect($data_source, $username, $auth, \%attr);
26
27 $rv = $dbh->do($statement);
28 $rv = $dbh->do($statement, \%attr);
29 $rv = $dbh->do($statement, \%attr, @bind_values);
30
31 $ary_ref = $dbh->selectall_arrayref($statement);
32 $ary_ref = $dbh->selectall_hashref($statement);
33
34 $ary_ref = $dbh->selectcol_arrayref($statement);
35
36 $ary_ref = $dbh->selectrow_arrayref($statement);
37 @row_ary = $dbh->selectrow_array($statement);
38
39 $sth = $dbh->prepare($statement);
40 $sth = $dbh->prepare_cached($statement);
41
42 $rv = $sth->bind_param($p_num, $bind_value);
43 $rv = $sth->bind_param($p_num, $bind_value, $bind_type);
44 $rv = $sth->bind_param($p_num, $bind_value, \%attr);
45
46 $rv = $sth->execute;
47 $rv = $sth->execute(@bind_values);
48
49 $rc = $sth->bind_col($col_num, \$col_variable);
50 $rc = $sth->bind_columns(@list_of_refs_to_vars_to_bind);
51
52 @row_ary = $sth->fetchrow_array;
53 $ary_ref = $sth->fetchrow_arrayref;
54 $hash_ref = $sth->fetchrow_hashref;
55
56 $ary_ref = $sth->fetchall_arrayref;
57
58 $rv = $sth->rows;
59
60 $rc = $dbh->commit;
61 $rc = $dbh->rollback;
62
63 $sql = $dbh->quote($string);
64
65 $rc = $h->err;
66 $str = $h->errstr;
67 $rv = $h->state;
68
69 $rc = $dbh->disconnect;
70
71I<This synopsis above only lists the major methods.>
72
73
74=head2 GETTING HELP
75
76If you have questions about DBI, you can get help from
77the I<dbi-users@perl.org> mailing list.
78You can subscribe to the list by emailing:
79
80 dbi-users-help@perl.org
81
82Also worth a visit is the DBI home page at:
83
84 http://dbi.perl.org/
85
86Before asking any questions, reread this document, consult the
87archives and read the DBI FAQ. The archives are listed
88at the end of this document.
89The FAQ is installed as a DBI::FAQ module so
90you can read it by executing C<perldoc DBI::FAQ>.
91
92Please note that Tim Bunce does not maintain the mailing lists or the
93web page (generous volunteers do that). So please don't send mail
94directly to him; he just doesn't have the time to answer questions
95personally. The I<dbi-users> mailing list has lots of experienced
96people who should be able to help you if you need it.
97
98=head2 NOTE
99
100This is the DBI specification that corresponds to the DBI version 1.17
101(C<$Date: 2001/06/04 17:20:21 $>).
102
103The DBI specification is evolving at a steady pace, so it's
104important to check that you have the latest copy. The RECENT CHANGES
105section below has a summary of user-visible changes. The F<Changes>
106file supplied with the DBI holds more detailed change information.
107
108Note also that whenever the DBI changes, the drivers take some time to
109catch up. Recent versions of the DBI have added new features
110(marked I<NEW> in the text) that may not yet be supported by the drivers
111you use. Talk to the authors of those drivers if you need the features.
112
113Extensions to the DBI and other DBI related modules use the C<DBIx::*>
114namespace. See L</Naming Conventions and Name Space> and:
115
116 http://www.perl.com/CPAN/modules/by-module/DBIx/
117
118=head2 RECENT CHANGES
119
120Here is a brief summary of significant user-visible changes in recent versions.
121(If a recent version isn't mentioned, it simply means that there were no
122significant user-visible changes in that version.)
123
124=over 4
125
126=item DBI 1.15
127
128Added selectall_hashref, selectrow_hashref, selectrow_arrayref methods.
129
130=back
131
132=cut
133
134# The POD text continues at the end of the file.
135
136# DBI file-private variables
137my %installed_rootclass;
138
139
140{
141package DBI;
142
143my $Revision = substr(q$Revision: 10.37 $, 10);
144
145use Carp;
146use DynaLoader ();
147use Exporter ();
148
149BEGIN {
150@ISA = qw(Exporter DynaLoader);
151
152# Make some utility functions available if asked for
153@EXPORT = (); # we export nothing by default
154@EXPORT_OK = qw(%DBI %DBI_methods); # also populated by export_ok_tags:
155%EXPORT_TAGS = (
156 sql_types => [ qw(
157 SQL_ALL_TYPES
158 SQL_CHAR SQL_NUMERIC SQL_DECIMAL SQL_INTEGER SQL_SMALLINT
159 SQL_FLOAT SQL_REAL SQL_DOUBLE SQL_VARCHAR
160 SQL_DATE SQL_TIME SQL_TIMESTAMP
161 SQL_LONGVARCHAR SQL_BINARY SQL_VARBINARY SQL_LONGVARBINARY
162 SQL_BIGINT SQL_TINYINT
163 SQL_WCHAR SQL_WVARCHAR SQL_WLONGVARCHAR
164 SQL_BIT
165 ) ],
166 preparse_flags => [ qw(
167 DBIpp_cm_cs DBIpp_cm_hs DBIpp_cm_dd DBIpp_cm_br
168 DBIpp_ph_qm DBIpp_ph_cn DBIpp_ph_cs DBIpp_ph_sp
169 ) ],
170 utils => [ qw(
171 neat neat_list dump_results looks_like_number
172 ) ],
173);
174Exporter::export_ok_tags('sql_types', 'utils');
175
176$DBI::dbi_debug = $ENV{DBI_TRACE} || $ENV{PERL_DBI_DEBUG} || 0;
177
178# If you get an error here like "Can't find loadable object ..."
179# then you haven't installed the DBI correctly. Read the README
180# then install it again.
181bootstrap DBI;
182
183}
184*trace_msg = \&DBD::_::common::trace_msg;
185
186use strict;
187
188my $connect_via = "connect";
189
190# check if user wants a persistent database connection ( Apache + mod_perl )
191if ($INC{'Apache/DBI.pm'} && substr($ENV{GATEWAY_INTERFACE}||'',0,8) eq 'CGI-Perl') {
192 $connect_via = "Apache::DBI::connect";
193 DBI->trace_msg("DBI connect via $INC{'Apache/DBI.pm'}\n");
194}
195
196
197if ($DBI::dbi_debug) {
198 @DBI::dbi_debug = ($DBI::dbi_debug);
199
200 if ($DBI::dbi_debug !~ m/^\d$/) {
201 # dbi_debug is a file name to write trace log to.
202 # Default level is 2 but if file starts with "digits=" then the
203 # digits (and equals) are stripped off and used as the level
204 unshift @DBI::dbi_debug, 2;
205 @DBI::dbi_debug = ($1,$2) if $DBI::dbi_debug =~ m/^(\d+)=(.*)/;
206 }
207 DBI->trace(@DBI::dbi_debug);
208}
209
210%DBI::installed_drh = (); # maps driver names to installed driver handles
211
212
213# Setup special DBI dynamic variables. See DBI::var::FETCH for details.
214# These are dynamically associated with the last handle used.
215tie $DBI::err, 'DBI::var', '*err'; # special case: referenced via IHA list
216tie $DBI::state, 'DBI::var', '"state'; # special case: referenced via IHA list
217tie $DBI::lasth, 'DBI::var', '!lasth'; # special case: return boolean
218tie $DBI::errstr, 'DBI::var', '&errstr'; # call &errstr in last used pkg
219tie $DBI::rows, 'DBI::var', '&rows'; # call &rows in last used pkg
220sub DBI::var::TIESCALAR{ my $var = $_[1]; bless \$var, 'DBI::var'; }
221sub DBI::var::STORE { Carp::croak("Can't modify \$DBI::${$_[0]} special variable") }
222sub DBI::var::DESTROY { }
223
224{ package DBI::DBI_tie; # used to catch DBI->{Attrib} mistake
225 sub TIEHASH { bless {} }
226 sub STORE { Carp::carp("DBI->{$_[1]} is invalid syntax (you probably want \$h->{$_[1]})");}
227 *FETCH = \&STORE;
228}
229tie %DBI::DBI => 'DBI::DBI_tie';
230
231
232# --- Dynamically create the DBI Standard Interface
233
234my $std = undef;
235my $keeperr = { O=>0x04 };
236
237my @TieHash_IF = ( # Generic Tied Hash Interface
238 'STORE' => { O=>0x10 },
239 'FETCH' => $keeperr,
240 'FIRSTKEY'=> $keeperr,
241 'NEXTKEY' => $keeperr,
242 'EXISTS' => $keeperr,
243 'CLEAR' => $keeperr,
244 'DESTROY' => undef, # hardwired internally
245);
246my @Common_IF = ( # Interface functions common to all DBI classes
247 func => { O=>0x06 },
248 event => { U =>[2,0,'$type, @args'], O=>0x04 },
249 'trace' => { U =>[1,3,'[$trace_level, [$filename]]'], O=>0x04 },
250 trace_msg => { U =>[2,3,'$message_text [, $min_level ]' ], O=>0x04, T=>8 },
251 debug => { U =>[1,2,'[$debug_level]'], O=>0x04 }, # old name for trace
252 private_data => { U =>[1,1], O=>0x04 },
253 err => $keeperr,
254 errstr => $keeperr,
255 state => { U =>[1,1], O=>0x04 },
256 _not_impl => $std,
257);
258
259%DBI::DBI_methods = ( # Define the DBI interface methods per class:
260
261 dr => { # Database Driver Interface
262 @Common_IF,
263 @TieHash_IF,
264 'connect' => { U =>[1,5,'[$db [,$user [,$passwd [,\%attr]]]]'], H=>3 },
265 'connect_cached'=>{U=>[1,5,'[$db [,$user [,$passwd [,\%attr]]]]'], H=>3 },
266 'disconnect_all'=>{ U =>[1,1] },
267 data_sources => { U =>[1,2,'[\%attr]' ] },
268 default_user => { U =>[3,4,'$user, $pass [, \%attr]' ] },
269 },
270 db => { # Database Session Class Interface
271 @Common_IF,
272 @TieHash_IF,
273 commit => { U =>[1,1] },
274 rollback => { U =>[1,1] },
275 'do' => { U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'] },
276 prepare => { U =>[2,3,'$statement [, \%attr]'] },
277 prepare_cached => { U =>[2,4,'$statement [, \%attr [, $allow_active ] ]'] },
278 selectrow_array => { U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'] },
279 selectrow_arrayref=>{U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'] },
280 selectrow_hashref=>{ U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'] },
281 selectall_arrayref=>{U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'] },
282 selectall_hashref=>{ U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'] },
283 selectcol_arrayref=>{U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'] },
284 handler => { U =>[2,2,'\&handler'] },
285 ping => { U =>[1,1] },
286 disconnect => { U =>[1,1] },
287 quote => { U =>[2,3, '$string [, $data_type ]' ], O=>0x30 },
288 rows => $keeperr,
289
290 tables => { U =>[1,2,'[ \%attr ]' ] },
291 table_info => { U =>[1,2,'[ \%attr ]' ] },
292 type_info_all => { U =>[1,1] },
293 type_info => { U =>[1,2] },
294 get_info => { U =>[2,2] },
295 },
296 st => { # Statement Class Interface
297 @Common_IF,
298 @TieHash_IF,
299 bind_col => { U =>[3,4,'$column, \\$var [, \%attr]'] },
300 bind_columns => { U =>[2,0,'\\$var1 [, \\$var2, ...]'] },
301 bind_param => { U =>[3,4,'$parameter, $var [, \%attr]'] },
302 bind_param_inout=> { U =>[4,5,'$parameter, \\$var, $maxlen, [, \%attr]'] },
303 execute => { U =>[1,0,'[@args]'] },
304
305 fetch => undef, # alias for fetchrow_arrayref
306 fetchrow_arrayref => undef,
307 fetchrow_hashref => undef,
308 fetchrow_array => undef,
309 fetchrow => undef, # old alias for fetchrow_array
310
311 fetchall_arrayref => { U =>[1,2] },
312
313 blob_read => { U =>[4,5,'$field, $offset, $len [, \\$buf [, $bufoffset]]'] },
314 blob_copy_to_file => { U =>[3,3,'$field, $filename_or_handleref'] },
315 dump_results => { U =>[1,5,'$maxfieldlen, $linesep, $fieldsep, $filehandle'] },
316 more_results => { U =>[1,1] },
317 finish => { U =>[1,1] },
318 cancel => { U =>[1,1] },
319 rows => $keeperr,
320
321 _get_fbav => undef,
322 _set_fbav => { T=>6 },
323 },
324);
325
326my($class, $method);
327foreach $class (keys %DBI::DBI_methods){
328 my %pkgif = %{ $DBI::DBI_methods{$class} };
329 foreach $method (keys %pkgif){
330 DBI->_install_method("DBI::${class}::$method", 'DBI.pm',
331 $pkgif{$method});
332 }
333}
334
335# End of init code
336
337
338END {
339 return unless defined &DBI::trace_msg; # return unless bootstrap'd ok
340 local ($!,$?);
341 DBI->trace_msg(" -- DBI::END\n", 2);
342 # Let drivers know why we are calling disconnect_all:
343 $DBI::PERL_ENDING = $DBI::PERL_ENDING = 1; # avoid typo warning
344 DBI->disconnect_all() if %DBI::installed_drh;
345}
346
347
348
349# --- The DBI->connect Front Door methods
350
351sub connect_cached {
352 # XXX we expect Apache::DBI users to still call connect()
353 my ($class, $dsn, $user, $pass, $attr) = @_;
354 ($attr ||= {})->{dbi_connect_method} = 'connect_cached';
355 return $class->connect($dsn, $user, $pass, $attr);
356}
357
358sub connect {
359 my $class = shift;
360 my($dsn, $user, $pass, $attr, $old_driver) = @_;
361 my $driver;
362 my $dbh;
363
364 # switch $old_driver<->$attr if called in old style
365 ($old_driver, $attr) = ($attr, $old_driver) if $attr and !ref($attr);
366
367 my $connect_meth = (ref $attr) ? $attr->{dbi_connect_method} : undef;
368 $connect_meth ||= $connect_via; # fallback to default
369
370 $dsn ||= $ENV{DBI_DSN} || $ENV{DBI_DBNAME} || '' unless $old_driver;
371
372 if ($DBI::dbi_debug) {
373 local $^W = 0;
374 pop @_ if $connect_meth ne 'connect';
375 my @args = @_; $args[2] = '****'; # hide password
376 DBI->trace_msg(" -> $class->$connect_meth(".join(", ",@args).")\n");
377 }
378 Carp::croak('Usage: $class->connect([$dsn [,$user [,$passwd [,\%attr]]]])')
379 if (ref $old_driver or ($attr and not ref $attr) or ref $pass);
380
381 # extract dbi:driver prefix from $dsn into $1
382 $dsn =~ s/^dbi:(\w*?)(?:\((.*?)\))?://i
383 or '' =~ /()/; # ensure $1 etc are empty if match fails
384 my $driver_attrib_spec = $2;
385
386 # Set $driver. Old style driver, if specified, overrides new dsn style.
387 $driver = $old_driver || $1 || $ENV{DBI_DRIVER}
388 or Carp::croak("Can't connect(@_), no database driver specified "
389 ."and DBI_DSN env var not set");
390
391 if ($ENV{DBI_AUTOPROXY} && $driver ne 'Proxy' && $driver ne 'Switch') {
392 $dsn = "$ENV{DBI_AUTOPROXY};dsn=dbi:$driver:$dsn";
393 $driver = 'Proxy';
394 DBI->trace_msg(" DBI_AUTOPROXY: dbi:$driver:$dsn\n");
395 }
396
397 unless ($old_driver) { # new-style connect so new default semantics
398 $driver_attrib_spec = { split /\s*=>?\s*|\s*,\s*/, $driver_attrib_spec }
399 if $driver_attrib_spec;
400 $attr = {
401 PrintError=>1, AutoCommit=>1,
402 ref $attr ? %$attr : (),
403 ref $driver_attrib_spec ? %$driver_attrib_spec : (),
404 };
405 # XXX to be enabled for DBI v2.0
406 #Carp::carp("AutoCommit attribute not specified in DBI->connect")
407 # if $^W && !defined($attr->{AutoCommit});
408 }
409
410 my $drh = $class->install_driver($driver)
411 || die "panic: install_driver($driver) failed";
412
413 ($user, $pass) = $drh->default_user($user, $pass, $attr)
414 if !(defined $user && defined $pass);
415
416 unless ($dbh = $drh->$connect_meth($dsn, $user, $pass, $attr)) {
417 my $msg = "$class->connect($dsn) failed: ".$drh->errstr;
418 if (ref $attr) {
419 Carp::croak($msg) if $attr->{RaiseError};
420 Carp::carp ($msg) if $attr->{PrintError};
421 }
422 DBI->trace_msg(" $msg\n");
423 $! = 0; # for the daft people who do DBI->connect(...) || die "$!";
424 return undef;
425 }
426
427 # XXX this is inelegant but practical in the short term, sigh.
428 if ($installed_rootclass{$class}) {
429 $dbh->{RootClass} = $class;
430 bless $dbh => $class.'::db';
431 my ($outer, $inner) = DBI::_handles($dbh);
432 bless $inner => $class.'::db';
433 }
434
435 if (ref $attr) {
436 my %a = %$attr;
437 my $a;
438 # handle these attributes first
439 foreach $a (qw(RaiseError PrintError AutoCommit)) {
440 next unless exists $a{$a};
441 $dbh->{$a} = $a{$a};
442 delete $a{$a};
443 }
444 foreach $a (keys %a) {
445 $dbh->{$a} = $a{$a};
446 }
447 }
448 DBI->trace_msg(" <- connect= $dbh\n") if $DBI::dbi_debug;
449
450 $dbh;
451}
452
453
454sub disconnect_all {
455 foreach(keys %DBI::installed_drh){
456 my $drh = $DBI::installed_drh{$_};
457 next unless ref $drh; # avoid problems on premature death
458 $drh->disconnect_all();
459 }
460}
461
462
463sub disconnect { # a regular beginners bug
464 Carp::croak("DBI->disconnect is not a DBI method. Read the DBI manual.");
465}
466
467
468sub install_driver { # croaks on failure
469 my $class = shift;
470 my($driver, $attr) = @_;
471 my $drh;
472 local $@;
473
474 $driver ||= $ENV{DBI_DRIVER} || '';
475
476 # allow driver to be specified as a 'dbi:driver:' string
477 $driver = $1 if $driver =~ s/^DBI:(.*?)://i;
478
479 Carp::croak("usage: $class->install_driver(\$driver [, \%attr])")
480 unless ($driver and @_<=3);
481
482 # already installed
483 return $drh if $drh = $DBI::installed_drh{$driver};
484
485 DBI->trace_msg(" -> $class->install_driver($driver"
486 .") for perl=$] pid=$$ ruid=$< euid=$>\n")
487 if $DBI::dbi_debug;
488
489 # --- load the code
490 my $driver_class = "DBD::$driver";
491 eval "package DBI::_firesafe; require $driver_class";
492 if ($@) {
493 my $err = $@;
494 my $advice = "";
495 if ($err =~ /Can't find loadable object/) {
496 $advice = "Perhaps DBD::$driver was statically linked into a new perl binary."
497 ."\nIn which case you need to use that new perl binary."
498 ."\nOr perhaps only the .pm file was installed but not the shared object file."
499 }
500 elsif ($err =~ /Can't locate.*?DBD\/$driver\.pm in \@INC/) {
501 my @drv = DBI->available_drivers(1);
502 $advice = "Perhaps the DBD::$driver perl module hasn't been fully installed,\n"
503 ."or perhaps the capitalisation of '$driver' isn't right.\n"
504 ."Available drivers: ".join(", ", @drv).".";
505 }
506 elsif ($err =~ /Can't load .*? for module DBD::/) {
507 $advice = "Perhaps a required shared library or dll isn't installed where expected";
508 }
509 elsif ($err =~ /Can't locate .*? in \@INC/) {
510 $advice = "Perhaps a module that DBD::$driver requires hasn't been fully installed";
511 }
512 Carp::croak("install_driver($driver) failed: $err$advice\n");
513 }
514 if ($DBI::dbi_debug) {
515 no strict 'refs';
516 (my $driver_file = $driver_class) =~ s/::/\//g;
517 my $dbd_ver = ${"$driver_class\::VERSION"} || "undef";
518 DBI->trace_msg(" install_driver: $driver_class version $dbd_ver"
519 ." loaded from $INC{qq($driver_file.pm)}\n");
520 }
521
522 # --- do some behind-the-scenes checks and setups on the driver
523 _setup_driver($driver_class);
524
525 # --- run the driver function
526 $drh = eval { $driver_class->driver($attr || {}) };
527 unless ($drh && ref $drh && !$@) {
528 my $advice = "";
529 # catch people on case in-sensitive systems using the wrong case
530 $advice = "\nPerhaps the capitalisation of DBD '$driver' isn't right."
531 if $@ =~ /locate object method/;
532 croak("$driver_class initialisation failed: $@$advice");
533 }
534
535 $DBI::installed_drh{$driver} = $drh;
536 DBI->trace_msg(" <- install_driver= $drh\n") if $DBI::dbi_debug;
537 $drh;
538}
539
540*driver = \&install_driver; # currently an alias, may change
541
542
543sub _setup_driver {
544 my $driver_class = shift;
545 my $type;
546 foreach $type (qw(dr db st)){
547 my $class = $driver_class."::$type";
548 no strict 'refs';
549 push @{"${class}::ISA"}, "DBD::_::$type";
550 push @{"${class}_mem::ISA"}, "DBD::_mem::$type";
551 }
552}
553
554
555sub init_rootclass {
556 my $rootclass = shift;
557 no strict 'refs';
558 croak("Can't init '$rootclass' without '$rootclass\::db' class.")
559 unless defined ${"$rootclass\::db::"}{ISA};
560
561 $installed_rootclass{$rootclass} = 1;
562 # may do checks on ::db and ::st classes later
563 return 1;
564}
565
566
567*internal = \&DBD::Switch::dr::driver;
568#sub internal { return DBD::Switch::dr::driver(@_); }
569
570
571sub available_drivers {
572 my($quiet) = @_;
573 my(@drivers, $d, $f);
574 local(*DBI::DIR, $@);
575 my(%seen_dir, %seen_dbd);
576 my $haveFileSpec = eval { require File::Spec };
577 foreach $d (@INC){
578 chomp($d); # Perl 5 beta 3 bug in #!./perl -Ilib from Test::Harness
579 my $dbd_dir =
580 ($haveFileSpec ? File::Spec->catdir($d, 'DBD') : "$d/DBD");
581 next unless -d $dbd_dir;
582 next if $seen_dir{$d};
583 $seen_dir{$d} = 1;
584 # XXX we have a problem here with case insensitive file systems
585 # XXX since we can't tell what case must be used when loading.
586 opendir(DBI::DIR, $dbd_dir) || Carp::carp "opendir $dbd_dir: $!\n";
587 foreach $f (readdir(DBI::DIR)){
588 next unless $f =~ s/\.pm$//;
589 next if $f eq 'NullP' || $f eq 'Sponge';
590 if ($seen_dbd{$f}){
591 Carp::carp "DBD::$f in $d is hidden by DBD::$f in $seen_dbd{$f}\n"
592 unless $quiet;
593 } else {
594 push(@drivers, $f);
595 }
596 $seen_dbd{$f} = $d;
597 }
598 closedir(DBI::DIR);
599 }
600 return sort @drivers;
601}
602
603sub data_sources {
604 my ($class, $driver, @attr) = @_;
605 my $drh = $class->install_driver($driver);
606 my @ds = $drh->data_sources(@attr);
607 return @ds;
608}
609
610sub neat_list {
611 my ($listref, $maxlen, $sep) = @_;
612 $maxlen = 0 unless defined $maxlen; # 0 == use internal default
613 $sep = ", " unless defined $sep;
614 join($sep, map { neat($_,$maxlen) } @$listref);
615}
616
617
618sub dump_results { # also aliased as a method in DBD::_::st
619 my ($sth, $maxlen, $lsep, $fsep, $fh) = @_;
620 return 0 unless $sth;
621 $maxlen ||= 35;
622 $lsep ||= "\n";
623 $fh ||= \*STDOUT;
624 my $rows = 0;
625 my $ref;
626 while($ref = $sth->fetch) {
627 print $fh $lsep if $rows++ and $lsep;
628 my $str = neat_list($ref,$maxlen,$fsep);
629 print $fh $str; # done on two lines to avoid 5.003 errors
630 }
631 print $fh "\n$rows rows".($DBI::err ? " ($DBI::err: $DBI::errstr)" : "")."\n";
632 $rows;
633}
634
635
636
637sub connect_test_perf {
638 my($class, $dsn,$dbuser,$dbpass, $attr) = @_;
639 croak("connect_test_perf needs hash ref as fourth arg") unless ref $attr;
640 # these are non standard attributes just for this special method
641 my $loops ||= $attr->{dbi_loops} || 5;
642 my $par ||= $attr->{dbi_par} || 1; # parallelism
643 my $verb ||= $attr->{dbi_verb} || 1;
644 print "$dsn: testing $loops sets of $par connections:\n";
645 require Benchmark;
646 require "FileHandle.pm"; # don't let toke.c create empty FileHandle package
647 $| = 1;
648 my $t0 = new Benchmark; # not currently used
649 my $drh = $class->install_driver($dsn) or Carp::croak("Can't install $dsn driver\n");
650 my $t1 = new Benchmark;
651 my $loop;
652 for $loop (1..$loops) {
653 my @cons;
654 print "Connecting... " if $verb;
655 for (1..$par) {
656 print "$_ ";
657 push @cons, ($drh->connect($dsn,$dbuser,$dbpass)
658 or Carp::croak("Can't connect # $_: $DBI::errstr\n"));
659 }
660 print "\nDisconnecting...\n" if $verb;
661 for (@cons) {
662 $_->disconnect or warn "bad disconnect $DBI::errstr"
663 }
664 }
665 my $t2 = new Benchmark;
666 my $td = Benchmark::timediff($t2, $t1);
667 printf "Made %2d connections in %s\n", $loops*$par, Benchmark::timestr($td);
668 print "\n";
669 return $td;
670}
671
672
673# Help people doing DBI->errstr, might even document it one day
674# XXX probably best moved to cheaper XS code
675sub err { $DBI::err }
676sub errstr { $DBI::errstr }
677
678
679# --- Private Internal Function for Creating New DBI Handles
680
681sub _new_handle {
682 my ($class, $parent, $attr, $imp_data, $imp_class) = @_;
683
684 Carp::croak('Usage: DBI::_new_handle'
685 .'($class_name, parent_handle, \%attr, $imp_data)'."\n"
686 .'got: ('.join(", ",$class, $parent, $attr, $imp_data).")\n")
687 unless (@_ == 5 and (!$parent or ref $parent)
688 and ref $attr eq 'HASH'
689 and $imp_class);
690
691 $attr->{ImplementorClass} = $imp_class
692 or Carp::croak("_new_handle($class): 'ImplementorClass' attribute not given");
693
694 DBI->trace_msg(" New $class (for $imp_class, parent=$parent, id=".($imp_data||'').")\n")
695 if $DBI::dbi_debug >= 3;
696
697 # This is how we create a DBI style Object:
698 my(%hash, $i, $h);
699 $i = tie %hash, $class, $attr; # ref to inner hash (for driver)
700 $h = bless \%hash, $class; # ref to outer hash (for application)
701 # The above tie and bless may migrate down into _setup_handle()...
702 # Now add magic so DBI method dispatch works
703 DBI::_setup_handle($h, $imp_class, $parent, $imp_data);
704
705 return $h unless wantarray;
706 ($h, $i);
707}
708# minimum constructors for the tie's (alias to XS version)
709sub DBI::st::TIEHASH { bless $_[1] => $_[0] };
710*DBI::dr::TIEHASH = \&DBI::st::TIEHASH;
711*DBI::db::TIEHASH = \&DBI::st::TIEHASH;
712
713
714# These three special constructors are called by the drivers
715# The way they are called is likey to change.
716
717sub _new_drh { # called by DBD::<drivername>::driver()
718 my ($class, $initial_attr, $imp_data) = @_;
719 # Provide default storage for State,Err and Errstr.
720 # Note that these are shared by all child handles by default! XXX
721 # State must be undef to get automatic faking in DBI::var::FETCH
722 my ($h_state_store, $h_err_store, $h_errstr_store) = (undef, 0, '');
723 my $attr = {
724 # these attributes get copied down to child handles by default
725 'Handlers' => [],
726 'State' => \$h_state_store, # Holder for DBI::state
727 'Err' => \$h_err_store, # Holder for DBI::err
728 'Errstr' => \$h_errstr_store, # Holder for DBI::errstr
729 'Debug' => 0,
730 %$initial_attr,
731 };
732 _new_handle('DBI::dr', '', $attr, $imp_data, $class);
733}
734
735sub _new_dbh { # called by DBD::<drivername>::dr::connect()
736 my ($drh, $attr, $imp_data) = @_;
737 my $imp_class = $drh->{ImplementorClass}
738 or Carp::croak("DBI _new_dbh: $drh has no ImplementorClass");
739 substr($imp_class,-4,4) = '::db';
740 my $app_class = ref $drh;
741 substr($app_class,-4,4) = '::db';
742 _new_handle($app_class, $drh, $attr||{}, $imp_data, $imp_class);
743}
744
745sub _new_sth { # called by DBD::<drivername>::db::prepare)
746 my ($dbh, $attr, $imp_data) = @_;
747 my $imp_class = $dbh->{ImplementorClass}
748 or Carp::croak("DBI _new_sth: $dbh has no ImplementorClass");
749 substr($imp_class,-4,4) = '::st';
750 my $app_class = ref $dbh;
751 substr($app_class,-4,4) = '::st';
752 _new_handle($app_class, $dbh, $attr, $imp_data, $imp_class);
753}
754
755
756} # end of DBI package scope
757
758
759
760# --------------------------------------------------------------------
761# === The internal DBI Switch pseudo 'driver' class ===
762
763{ package DBD::Switch::dr;
764 DBI::_setup_driver('DBD::Switch'); # sets up @ISA
765 require Carp;
766
767 $imp_data_size = 0;
768 $imp_data_size = 0; # avoid typo warning
769 $err = 0;
770
771 sub driver {
772 return $drh if $drh; # a package global
773
774 my $inner;
775 ($drh, $inner) = DBI::_new_drh('DBD::Switch::dr', {
776 'Name' => 'Switch',
777 'Version' => $DBI::VERSION,
778 # the Attribution is defined as a sub as an example
779 'Attribution' => sub { "DBI $DBI::VERSION by Tim Bunce" },
780 }, \$err);
781 Carp::croak("DBD::Switch init failed!") unless ($drh && $inner);
782 return $drh;
783 }
784
785 sub FETCH {
786 my($drh, $key) = @_;
787 return DBI->trace if $key eq 'DebugDispatch';
788 return undef if $key eq 'DebugLog'; # not worth fetching, sorry
789 return $drh->DBD::_::dr::FETCH($key);
790 undef;
791 }
792 sub STORE {
793 my($drh, $key, $value) = @_;
794 if ($key eq 'DebugDispatch') {
795 DBI->trace($value);
796 } elsif ($key eq 'DebugLog') {
797 DBI->trace(-1, $value);
798 } else {
799 $drh->DBD::_::dr::STORE($key, $value);
800 }
801 }
802}
803
804
805# --------------------------------------------------------------------
806# === OPTIONAL MINIMAL BASE CLASSES FOR DBI SUBCLASSES ===
807
808# We only define default methods for harmless functions.
809# We don't, for example, define a DBD::_::st::prepare()
810
811{ package DBD::_::common; # ====== Common base class methods ======
812 use strict;
813
814 # methods common to all handle types:
815
816 sub _not_impl {
817 my ($h, $method) = @_;
818 $h->trace_msg("Driver does not implement the $method method.\n");
819 return; # empty list / undef
820 }
821
822 # generic TIEHASH default methods:
823 sub FIRSTKEY { }
824 sub NEXTKEY { }
825 sub EXISTS { defined($_[0]->FETCH($_[1])) } # XXX undef?
826 sub CLEAR { Carp::carp "Can't CLEAR $_[0] (DBI)" }
827
828 *dump_handle = \&DBI::dump_handle;
829}
830
831
832{ package DBD::_::dr; # ====== DRIVER ======
833 @ISA = qw(DBD::_::common);
834 use strict;
835
836 sub default_user {
837 my ($drh, $user, $pass) = @_;
838 unless (defined $user) {
839 $user = $ENV{DBI_USER};
840 carp("DBI connect: user not defined and DBI_USER env var not set")
841 if 0 && !defined $user && $drh->{Warn}; # XXX enable later
842 }
843 unless (defined $pass) {
844 $pass = $ENV{DBI_PASS};
845 carp("DBI connect: password not defined and DBI_PASS env var not set")
846 if 0 && !defined $pass && $drh->{Warn}; # XXX enable later
847 }
848 return ($user, $pass);
849 }
850
851 sub connect { # normally overridden, but a handy default
852 my ($drh, $dsn, $user, $auth) = @_;
853 my ($this) = DBI::_new_dbh($drh, {
854 'Name' => $dsn,
855 'User' => $user,
856 });
857 $this;
858 }
859
860
861 sub connect_cached {
862 my $drh = shift;
863 my ($dsn, $user, $auth, $attr)= @_;
864
865 # Needs support at dbh level to clear cache before complaining about
866 # active children. The XS template code does this. Drivers not using
867 # the template must handle clearing the cache themselves.
868 my $cache = $drh->FETCH('CachedKids');
869 $drh->STORE('CachedKids', $cache = {}) unless $cache;
870
871 my @attr_keys = $attr ? sort keys %$attr : ();
872 my $key = join "~~", $dsn, $user||'', $auth||'',
873 $attr ? (@attr_keys,@{$attr}{@attr_keys}) : ();
874 my $dbh = $cache->{$key};
875 return $dbh if $dbh && $dbh->FETCH('Active') && eval { $dbh->ping };
876 $dbh = $drh->connect(@_);
877 $cache->{$key} = $dbh; # replace prev entry, even if connect failed
878 return $dbh;
879 }
880
881
882 sub disconnect_all { # Driver must take responsibility for this
883 # XXX Umm, may change later.
884 Carp::croak("Driver has not implemented the disconnect_all method.");
885 }
886
887 sub data_sources {
888 shift->_not_impl('data_sources');
889 }
890
891}
892
893
894{ package DBD::_::db; # ====== DATABASE ======
895 @ISA = qw(DBD::_::common);
896 use strict;
897
898 sub disconnect {
899 shift->_not_impl('disconnect');
900 }
901
902 # Drivers are required to implement *::db::DESTROY to encourage tidy-up
903 sub DESTROY { Carp::croak("Driver has not implemented DESTROY for @_") }
904
905 sub quote {
906 my ($dbh, $str, $data_type) = @_;
907 return "NULL" unless defined $str;
908 unless ($data_type) {
909 $str =~ s/'/''/g; # ISO SQL2
910 return "'$str'";
911 }
912 # Optimise for standard numerics which need no quotes
913 return $str if $data_type == DBI::SQL_INTEGER
914 || $data_type == DBI::SQL_SMALLINT
915 || $data_type == DBI::SQL_DECIMAL
916 || $data_type == DBI::SQL_FLOAT
917 || $data_type == DBI::SQL_REAL
918 || $data_type == DBI::SQL_DOUBLE
919 || $data_type == DBI::SQL_NUMERIC;
920 my $ti = $dbh->type_info($data_type);
921 # XXX needs checking
922 my $lp = $ti ? $ti->{LITERAL_PREFIX} || "" : "'";
923 my $ls = $ti ? $ti->{LITERAL_SUFFIX} || "" : "'";
924 # XXX don't know what the standard says about escaping
925 # in the 'general case' (where $lp != "'").
926 # So we just do this and hope:
927 $str =~ s/$lp/$lp$lp/g
928 if $lp && $lp eq $ls && ($lp eq "'" || $lp eq '"');
929 return "$lp$str$ls";
930 }
931
932 sub rows { -1 } # here so $DBI::rows 'works' after using $dbh
933
934 sub do {
935 my($dbh, $statement, $attr, @params) = @_;
936 my $sth = $dbh->prepare($statement, $attr) or return undef;
937 $sth->execute(@params) or return undef;
938 my $rows = $sth->rows;
939 ($rows == 0) ? "0E0" : $rows;
940 }
941
942 sub _do_selectrow {
943 my ($method, $dbh, $stmt, $attr, @bind) = @_;
944 my $sth = (ref $stmt) ? $stmt
945 : $dbh->prepare($stmt, $attr);
946 return unless $sth;
947 $sth->execute(@bind) || return;
948 my $row = $sth->$method();
949 $sth->finish if $row;
950 return $row;
951 }
952
953 sub selectrow_arrayref { return _do_selectrow('fetchrow_arrayref', @_); }
954 sub selectrow_hashref { return _do_selectrow('fetchrow_hashref', @_); }
955
956 sub selectrow_array {
957 my ($dbh, $stmt, $attr, @bind) = @_;
958 my $sth = (ref $stmt) ? $stmt
959 : $dbh->prepare($stmt, $attr);
960 return unless $sth;
961 $sth->execute(@bind) || return;
962 my @row = $sth->fetchrow_array;
963 $sth->finish if @row;
964 return $row[0] unless wantarray;
965 return @row;
966 }
967
968 sub selectall_arrayref {
969 my ($dbh, $stmt, $attr, @bind) = @_;
970 my $sth = (ref $stmt) ? $stmt
971 : $dbh->prepare($stmt, $attr);
972 return unless $sth;
973 $sth->execute(@bind) || return;
974 my $slice = $attr->{dbi_fetchall_arrayref_attr}; # typically undef
975 return $sth->fetchall_arrayref($slice);
976 }
977
978 sub selectall_hashref {
979 my ($dbh, $stmt, $attr, @bind) = @_;
980 my $sth = (ref $stmt) ? $stmt
981 : $dbh->prepare($stmt, $attr);
982 return unless $sth;
983 $sth->execute(@bind) || return;
984 my ($row, @rows);
985 push @rows, $row while ($row = $sth->fetchrow_hashref());
986 return \@rows;
987 }
988
989 sub selectcol_arrayref {
990 my ($dbh, $stmt, $attr, @bind) = @_;
991 my $sth = (ref $stmt) ? $stmt
992 : $dbh->prepare($stmt, $attr);
993 return unless $sth;
994 $sth->execute(@bind) || return;
995 my $column = 1;
996 my $value;
997 $sth->bind_col($column, \$value) || return;
998 my @col;
999 push @col, $value while $sth->fetch;
1000 return \@col;
1001 }
1002
1003 sub prepare_cached {
1004 my ($dbh, $statement, $attr, $allow_active) = @_;
1005 # Needs support at dbh level to clear cache before complaining about
1006 # active children. The XS template code does this. Drivers not using
1007 # the template must handle clearing the cache themselves.
1008 my $cache = $dbh->FETCH('CachedKids');
1009 $dbh->STORE('CachedKids', $cache = {}) unless $cache;
1010 my @attr_keys = ($attr) ? sort keys %$attr : ();
1011 my $key = ($attr) ? join("~~", $statement, @attr_keys, @{$attr}{@attr_keys}) : $statement;
1012 my $sth = $cache->{$key};
1013 if ($sth) {
1014 if ($sth->FETCH('Active')) {
1015 Carp::carp("prepare_cached($statement) statement handle $sth was still active")
1016 if !$allow_active;
1017 $sth->finish;
1018 }
1019 return $sth;
1020 }
1021 $sth = $dbh->prepare($statement, $attr);
1022 $cache->{$key} = $sth if $sth;
1023 return $sth;
1024 }
1025
1026 sub ping {
1027 shift->_not_impl('ping');
1028 "0 but true"; # special kind of true 0
1029 }
1030
1031 sub commit {
1032 shift->_not_impl('commit');
1033 }
1034 sub rollback {
1035 shift->_not_impl('rollback');
1036 }
1037
1038 sub get_info {
1039 shift->_not_impl("get_info @_");
1040 }
1041
1042 sub table_info {
1043 shift->_not_impl('table_info');
1044 }
1045
1046 sub tables {
1047 my ($dbh, @args) = @_;
1048 my $sth = $dbh->table_info(@args);
1049 return unless $sth;
1050 my ($row, @tables);
1051 while($row = $sth->fetch) {
1052 my $name = $row->[2];
1053 if ($row->[1]) {
1054 my $schema = $row->[1];
1055 # a little hack
1056 my $quote = ($schema eq uc($schema)) ? '' : '"';
1057 $name = "$quote$schema$quote.$name"
1058 }
1059 push @tables, $name;
1060 }
1061 return @tables;
1062 }
1063
1064 sub type_info_all {
1065 my ($dbh) = @_;
1066 $dbh->_not_impl('type_info_all');
1067 my $ti = [ {} ];
1068 return $ti;
1069 }
1070
1071 sub type_info {
1072 my ($dbh, $data_type) = @_;
1073 my $tia = $dbh->type_info_all;
1074 return unless @$tia;
1075 my $idx_hash = shift @$tia;
1076
1077 my $dt_idx = $idx_hash->{DATA_TYPE} || $idx_hash->{data_type};
1078 Carp::croak("type_info_all returned non-standard DATA_TYPE index value ($dt_idx != 1)")
1079 if $dt_idx && $dt_idx != 1;
1080
1081 # --- simple DATA_TYPE match filter
1082 my @ti;
1083 my @data_type_list = (ref $data_type) ? @$data_type : ($data_type);
1084 foreach $data_type (@data_type_list) {
1085 if (defined($data_type) && $data_type != DBI::SQL_ALL_TYPES()) {
1086 push @ti, grep { $_->[$dt_idx] == $data_type } @$tia;
1087 }
1088 else { # SQL_ALL_TYPES
1089 push @ti, @$tia;
1090 }
1091 last if @ti; # found at least one match
1092 }
1093
1094 # --- format results into list of hash refs
1095 my $idx_fields = keys %$idx_hash;
1096 my @idx_names = map { uc($_) } keys %$idx_hash;
1097 my @idx_values = values %$idx_hash;
1098 Carp::croak "type_info_all result has $idx_fields keys but ".(@{$ti[0]})." fields"
1099 if @ti && @{$ti[0]} != $idx_fields;
1100 my @out = map {
1101 my %h; @h{@idx_names} = @{$_}[ @idx_values ]; \%h;
1102 } @ti;
1103 return $out[0] unless wantarray;
1104 return @out;
1105 }
1106}
1107
1108
1109{ package DBD::_::st; # ====== STATEMENT ======
1110 @ISA = qw(DBD::_::common);
1111 use strict;
1112
1113 sub cancel { undef }
1114 sub bind_param { Carp::croak("Can't bind_param, not implement by driver") }
1115
1116 sub fetchall_arrayref {
1117 my $sth = shift;
1118 my $slice= shift || [];
1119 my $mode = ref $slice;
1120 my @rows;
1121 my $row;
1122 if ($mode eq 'ARRAY') {
1123 # we copy the array here because fetch (currently) always
1124 # returns the same array ref. XXX
1125 if (@$slice) {
1126 push @rows, [ @{$row}[ @$slice] ] while($row = $sth->fetch);
1127 }
1128 else {
1129 push @rows, [ @$row ] while($row = $sth->fetch);
1130 }
1131 }
1132 elsif ($mode eq 'HASH') {
1133 my @o_keys = keys %$slice;
1134 if (@o_keys) {
1135 my %i_names = map { (lc($_)=>$_) } @{ $sth->FETCH('NAME') };
1136 my @i_keys = map { $i_names{lc($_)} } @o_keys;
1137 while ($row = $sth->fetchrow_hashref) {
1138 my %hash;
1139 @hash{@o_keys} = @{$row}{@i_keys};
1140 push @rows, \%hash;
1141 }
1142 }
1143 else {
1144 # XXX assumes new ref each fetchhash
1145 push @rows, $row while ($row = $sth->fetchrow_hashref);
1146 }
1147 }
1148 else { Carp::croak("fetchall_arrayref($mode) invalid") }
1149 return \@rows;
1150 }
1151
1152 *dump_results = \&DBI::dump_results;
1153
1154 sub blob_copy_to_file { # returns length or undef on error
1155 my($self, $field, $filename_or_handleref, $blocksize) = @_;
1156 my $fh = $filename_or_handleref;
1157 my($len, $buf) = (0, "");
1158 $blocksize ||= 512; # not too ambitious
1159 local(*FH);
1160 unless(ref $fh) {
1161 open(FH, ">$fh") || return undef;
1162 $fh = \*FH;
1163 }
1164 while(defined($self->blob_read($field, $len, $blocksize, \$buf))) {
1165 print $fh $buf;
1166 $len += length $buf;
1167 }
1168 close(FH);
1169 $len;
1170 }
1171
1172 sub more_results {
1173 shift->{syb_more_results}; # handy grandfathering
1174 }
1175
1176 # Drivers are required to implement *::st::DESTROY to encourage tidy-up
1177 sub DESTROY { Carp::croak("Driver has not implemented DESTROY for @_") }
1178}
1179
1180{ # See install_driver
1181 { package DBD::_mem::dr; @ISA = qw(DBD::_mem::common); }
1182 { package DBD::_mem::db; @ISA = qw(DBD::_mem::common); }
1183 { package DBD::_mem::st; @ISA = qw(DBD::_mem::common); }
1184 # DBD::_mem::common::DESTROY is implemented in DBI.xs
1185}
1186
11871;
1188__END__
1189
1190=head1 DESCRIPTION
1191
1192The DBI is a database access module for the Perl programming language. It defines
1193a set of methods, variables, and conventions that provide a consistent
1194database interface, independent of the actual database being used.
1195
1196It is important to remember that the DBI is just an interface.
1197The DBI is a layer
1198of "glue" between an application and one or more database I<driver>
1199modules. It is the driver modules which do most of the real work. The DBI
1200provides a standard interface and framework for the drivers to operate
1201within.
1202
1203
1204=head2 Architecture of a DBI Application
1205
1206 |<- Scope of DBI ->|
1207 .-. .--------------. .-------------.
1208 .-------. | |---| XYZ Driver |---| XYZ Engine |
1209 | Perl | | | `--------------' `-------------'
1210 | script| |A| |D| .--------------. .-------------.
1211 | using |--|P|--|B|---|Oracle Driver |---|Oracle Engine|
1212 | DBI | |I| |I| `--------------' `-------------'
1213 | API | | |...
1214 |methods| | |... Other drivers
1215 `-------' | |...
1216 `-'
1217
1218The API, or Application Programming Interface, defines the
1219call interface and variables for Perl scripts to use. The API
1220is implemented by the Perl DBI extension.
1221
1222The DBI "dispatches" the method calls to the appropriate driver for
1223actual execution. The DBI is also responsible for the dynamic loading
1224of drivers, error checking and handling, providing default
1225implementations for methods, and many other non-database specific duties.
1226
1227Each driver
1228contains implementations of the DBI methods using the
1229private interface functions of the corresponding database engine. Only authors
1230of sophisticated/multi-database applications or generic library
1231functions need be concerned with drivers.
1232
1233=head2 Notation and Conventions
1234
1235The following conventions are used in this document:
1236
1237 $dbh Database handle object
1238 $sth Statement handle object
1239 $drh Driver handle object (rarely seen or used in applications)
1240 $h Any of the handle types above ($dbh, $sth, or $drh)
1241 $rc General Return Code (boolean: true=ok, false=error)
1242 $rv General Return Value (typically an integer)
1243 @ary List of values returned from the database, typically a row of data
1244 $rows Number of rows processed (if available, else -1)
1245 $fh A filehandle
1246 undef NULL values are represented by undefined values in Perl
1247 \%attr Reference to a hash of attribute values passed to methods
1248
1249Note that Perl will automatically destroy database and statement handle objects
1250if all references to them are deleted.
1251
1252
1253=head2 Outline Usage
1254
1255To use DBI,
1256first you need to load the DBI module:
1257
1258 use DBI;
1259 use strict;
1260
1261(The C<use strict;> isn't required but is strongly recommended.)
1262
1263Then you need to L</connect> to your data source and get a I<handle> for that
1264connection:
1265
1266 $dbh = DBI->connect($dsn, $user, $password,
1267 { RaiseError => 1, AutoCommit => 0 });
1268
1269Since connecting can be expensive, you generally just connect at the
1270start of your program and disconnect at the end.
1271
1272Explicitly defining the required C<AutoCommit> behavior is strongly
1273recommended and may become mandatory in a later version. This
1274determines whether changes are automatically committed to the
1275database when executed, or need to be explicitly committed later.
1276
1277The DBI allows an application to "prepare" statements for later
1278execution. A prepared statement is identified by a statement handle
1279held in a Perl variable.
1280We'll call the Perl variable C<$sth> in our examples.
1281
1282The typical method call sequence for a C<SELECT> statement is:
1283
1284 prepare,
1285 execute, fetch, fetch, ...
1286 execute, fetch, fetch, ...
1287 execute, fetch, fetch, ...
1288
1289for example:
1290
1291 $sth = $dbh->prepare("SELECT foo, bar FROM table WHERE baz=?");
1292
1293 $sth->execute( $baz );
1294
1295 while ( @row = $sth->fetchrow_array ) {
1296 print "@row\n";
1297 }
1298
1299The typical method call sequence for a I<non>-C<SELECT> statement is:
1300
1301 prepare,
1302 execute,
1303 execute,
1304 execute.
1305
1306for example:
1307
1308 $sth = $dbh->prepare("INSERT INTO table(foo,bar,baz) VALUES (?,?,?)");
1309
1310 while(<CSV>) {
1311 chomp;
1312 my ($foo,$bar,$baz) = split /,/;
1313 $sth->execute( $foo, $bar, $baz );
1314 }
1315
1316The C<do()> method can be used for non repeated I<non>-C<SELECT> statement
1317(or with drivers that don't support placeholders):
1318
1319 $rows_affected = $dbh->do("UPDATE your_table SET foo = foo + 1");
1320
1321To commit your changes to the database (when L</AutoCommit> is off):
1322
1323 $dbh->commit; # or call $dbh->rollback; to undo changes
1324
1325Finally, when you have finished working with the data source, you should
1326L</disconnect> from it:
1327
1328 $dbh->disconnect;
1329
1330
1331=head2 General Interface Rules & Caveats
1332
1333The DBI does not have a concept of a "current session". Every session
1334has a handle object (i.e., a C<$dbh>) returned from the C<connect> method.
1335That handle object is used to invoke database related methods.
1336
1337Most data is returned to the Perl script as strings. (Null values are
1338returned as C<undef>.) This allows arbitrary precision numeric data to be
1339handled without loss of accuracy. Beware that Perl may not preserve
1340the same accuracy when the string is used as a number.
1341
1342Dates and times are returned as character strings in the current
1343default format of the corresponding database engine. Time zone effects
1344are database/driver dependent.
1345
1346Perl supports binary data in Perl strings, and the DBI will pass binary
1347data to and from the driver without change. It is up to the driver
1348implementors to decide how they wish to handle such binary data.
1349
1350Most databases that understand multiple character sets have a
1351default global charset. Text stored in the database is, or should
1352be, stored in that charset; if not, then that's the fault of either
1353the database or the application that inserted the data. When text is
1354fetched it should be automatically converted to the charset of the
1355client, presumably based on the locale. If a driver needs to set a
1356flag to get that behavior, then it should do so; it should not require
1357the application to do that.
1358
1359Multiple SQL statements may not be combined in a single statement
1360handle (C<$sth>), although some databases and drivers do support this
1361(notably Sybase and SQL Server).
1362
1363Non-sequential record reads are not supported in this version of the DBI.
1364In other words, records can only be fetched in the order that the
1365database returned them, and once fetched they are forgotten.
1366
1367Positioned updates and deletes are not directly supported by the DBI.
1368See the description of the C<CursorName> attribute for an alternative.
1369
1370Individual driver implementors are free to provide any private
1371functions and/or handle attributes that they feel are useful.
1372Private driver functions can be invoked using the DBI C<func()> method.
1373Private driver attributes are accessed just like standard attributes.
1374
1375Many methods have an optional C<\%attr> parameter which can be used to
1376pass information to the driver implementing the method. Except where
1377specifically documented, the C<\%attr> parameter can only be used to pass
1378driver specific hints. In general, you can ignore C<\%attr> parameters
1379or pass it as C<undef>.
1380
1381
1382=head2 Naming Conventions and Name Space
1383
1384The DBI package and all packages below it (C<DBI::*>) are reserved for
1385use by the DBI. Extensions and related modules use the C<DBIx::>
1386namespace (see C<http://www.perl.com/CPAN/modules/by-module/DBIx/>).
1387Package names beginning with C<DBD::> are reserved for use
1388by DBI database drivers. All environment variables used by the DBI
1389or by individual DBDs begin with "C<DBI_>" or "C<DBD_>".
1390
1391The letter case used for attribute names is significant and plays an
1392important part in the portability of DBI scripts. The case of the
1393attribute name is used to signify who defined the meaning of that name
1394and its values.
1395
1396 Case of name Has a meaning defined by
1397 ------------ ------------------------
1398 UPPER_CASE Standards, e.g., X/Open, ISO SQL92 etc (portable)
1399 MixedCase DBI API (portable), underscores are not used.
1400 lower_case Driver or database engine specific (non-portable)
1401
1402It is of the utmost importance that Driver developers only use
1403lowercase attribute names when defining private attributes. Private
1404attribute names must be prefixed with the driver name or suitable
1405abbreviation (e.g., "C<ora_>" for Oracle, "C<ing_>" for Ingres, etc).
1406
1407Driver Specific Prefix Registry:
1408
1409 ad_ DBD::AnyData
1410 ado_ DBD::ADO
1411 best_ DBD::BestWins
1412 csv_ DBD::CSV
1413 db2_ DBD::DB2
1414 f_ DBD::File
1415 file_ DBD::TextFile
1416 ib_ DBD::InterBase
1417 ing_ DBD::Ingres
1418 ix_ DBD::Informix
1419 msql_ DBD::mSQL
1420 mysql_ DBD::mysql
1421 odbc_ DBD::ODBC
1422 ora_ DBD::Oracle
1423 pg_ DBD::Pg
1424 proxy_ DBD::Proxy
1425 rdb_ DBD::RDB
1426 sapdb_ DBD::SAP_DB
1427 solid_ DBD::Solid
1428 syb_ DBD::Sybase
1429 tdat_ DBD::Teradata
1430 tuber_ DBD::Tuber
1431 uni_ DBD::Unify
1432 xbase_ DBD::XBase
1433
1434
1435=head2 SQL - A Query Language
1436
1437Most DBI drivers require applications to use a dialect of SQL
1438(Structured Query Language) to interact with the database engine.
1439The following links provide useful information and further links about
1440SQL:
1441
1442 http://www.altavista.com/query?q=sql+tutorial
1443 http://www.jcc.com/sql_stnd.html
1444 http://www.contrib.andrew.cmu.edu/~shadow/sql.html
1445
1446The DBI itself does not mandate or require any particular language to
1447be used; it is language independent. In ODBC terms, the DBI is in
1448"pass-thru" mode, although individual drivers might not be. The only requirement
1449is that queries and other statements must be expressed as a single
1450string of characters passed as the first argument to the L</prepare> or
1451L</do> methods.
1452
1453For an interesting diversion on the I<real> history of RDBMS and SQL,
1454from the people who made it happen, see:
1455
1456 http://ftp.digital.com/pub/DEC/SRC/technical-notes/SRC-1997-018-html/sqlr95.html
1457
1458Follow the "And the rest" and "Intergalactic dataspeak" links for the
1459SQL history.
1460
1461=head2 Placeholders and Bind Values
1462
1463Some drivers support placeholders and bind values.
1464I<Placeholders>, also called parameter markers, are used to indicate
1465values in a database statement that will be supplied later,
1466before the prepared statement is executed. For example, an application
1467might use the following to insert a row of data into the SALES table:
1468
1469 INSERT INTO sales (product_code, qty, price) VALUES (?, ?, ?)
1470
1471or the following, to select the description for a product:
1472
1473 SELECT description FROM products WHERE product_code = ?
1474
1475The C<?> characters are the placeholders. The association of actual
1476values with placeholders is known as I<binding>, and the values are
1477referred to as I<bind values>.
1478
1479When using placeholders with the SQL C<LIKE> qualifier, you must
1480remember that the placeholder substitutes for the whole string.
1481So you should use "C<... LIKE ? ...>" and include any wildcard
1482characters in the value that you bind to the placeholder.
1483
1484B<Null Values>
1485
1486Undefined values, or C<undef>, can be used to indicate null values.
1487However, care must be taken in the particular case of trying to use
1488null values to qualify a C<SELECT> statement. Consider:
1489
1490 SELECT description FROM products WHERE product_code = ?
1491
1492Binding an C<undef> (NULL) to the placeholder will I<not> select rows
1493which have a NULL C<product_code>! Refer to the SQL manual for your database
1494engine or any SQL book for the reasons for this. To explicitly select
1495NULLs you have to say "C<WHERE product_code IS NULL>" and to make that
1496general you have to say:
1497
1498 ... WHERE (product_code = ? OR (? IS NULL AND product_code IS NULL))
1499
1500and bind the same value to both placeholders.
1501
1502B<Performance>
1503
1504Without using placeholders, the insert statement shown previously would have to
1505contain the literal values to be inserted and would have to be
1506re-prepared and re-executed for each row. With placeholders, the insert
1507statement only needs to be prepared once. The bind values for each row
1508can be given to the C<execute> method each time it's called. By avoiding
1509the need to re-prepare the statement for each row, the application
1510typically runs many times faster. Here's an example:
1511
1512 my $sth = $dbh->prepare(q{
1513 INSERT INTO sales (product_code, qty, price) VALUES (?, ?, ?)
1514 }) or die $dbh->errstr;
1515 while (<>) {
1516 chomp;
1517 my ($product_code, $qty, $price) = split /,/;
1518 $sth->execute($product_code, $qty, $price) or die $dbh->errstr;
1519 }
1520 $dbh->commit or die $dbh->errstr;
1521
1522See L</execute> and L</bind_param> for more details.
1523
1524The C<q{...}> style quoting used in this example avoids clashing with
1525quotes that may be used in the SQL statement. Use the double-quote like
1526C<qq{...}> operator if you want to interpolate variables into the string.
1527See L<perlop/"Quote and Quote-like Operators"> for more details.
1528
1529See also the L</bind_column> method, which is used to associate Perl
1530variables with the output columns of a C<SELECT> statement.
1531
1532=head1 THE DBI PACKAGE AND CLASS
1533
1534In this section, we cover the DBI class methods, utility functions,
1535and the dynamic attributes associated with generic DBI handles.
1536
1537=head2 DBI Constants
1538
1539The following SQL standard type constants can be imported individually
1540or, by importing the special C<:sql_types> tag, all together:
1541
1542 SQL_CHAR SQL_NUMERIC SQL_DECIMAL SQL_INTEGER SQL_SMALLINT
1543 SQL_FLOAT SQL_REAL SQL_DOUBLE SQL_VARCHAR
1544 SQL_DATE SQL_TIME SQL_TIMESTAMP
1545 SQL_LONGVARCHAR SQL_BINARY SQL_VARBINARY SQL_LONGVARBINARY
1546 SQL_BIGINT SQL_TINYINT
1547 SQL_WCHAR SQL_WVARCHAR SQL_WLONGVARCHAR
1548 SQL_BIT
1549 SQL_ALL_TYPES
1550
1551See the L</type_info>, L</type_info_all>, and L</bind_param> methods
1552for possible uses.
1553
1554=head2 DBI Class Methods
1555
1556The following methods are provided by the DBI class:
1557
1558=over 4
1559
1560=item C<connect>
1561
1562 $dbh = DBI->connect($data_source, $username, $password)
1563 or die $DBI::errstr;
1564 $dbh = DBI->connect($data_source, $username, $password, \%attr)
1565 or die $DBI::errstr;
1566
1567Establishes a database connection, or session, to the requested C<$data_source>.
1568Returns a database handle object if the connection succeeds. Use
1569C<$dbh->E<gt>C<disconnect> to terminate the connection.
1570
1571If the connect fails (see below), it returns C<undef> and sets both C<$DBI::err>
1572and C<$DBI::errstr>. (It does I<not> set C<$!>, etc.) You should generally
1573test the return status of C<connect> and C<print $DBI::errstr> if it has failed.
1574
1575Multiple simultaneous connections to multiple databases through multiple
1576drivers can be made via the DBI. Simply make one C<connect> call for each
1577database and keep a copy of each returned database handle.
1578
1579The C<$data_source> value should begin with "C<dbi:>I<driver_name>C<:>". The
1580I<driver_name> specifies the driver that will be used to make the
1581connection. (Letter case is significant.)
1582
1583As a convenience, if the C<$data_source> parameter is undefined or empty, the
1584DBI will substitute the value of the environment variable C<DBI_DSN>.
1585If just the I<driver_name> part is empty (i.e., the C<$data_source> prefix is "C<dbi::>"),
1586the environment variable C<DBI_DRIVER> is used. If neither variable is set,
1587then C<connect> dies.
1588
1589Examples of C<$data_source> values are:
1590
1591 dbi:DriverName:database_name
1592 dbi:DriverName:database_name@hostname:port
1593 dbi:DriverName:database=database_name;host=hostname;port=port
1594
1595There is I<no standard> for the text following the driver name. Each
1596driver is free to use whatever syntax it wants. The only requirement the
1597DBI makes is that all the information is supplied in a single string.
1598You must consult the documentation for the drivers you are using for a
1599description of the syntax they require. (Where a driver author needs
1600to define a syntax for the C<$data_source>, it is recommended that
1601they follow the ODBC style, shown in the last example above.)
1602
1603If the environment variable C<DBI_AUTOPROXY> is defined (and the driver in
1604C<$data_source> is not "C<Proxy>") then the connect request will
1605automatically be changed to:
1606
1607 dbi:Proxy:$ENV{DBI_AUTOPROXY};dsn=$data_source
1608
1609and passed to the DBD::Proxy module. C<DBI_AUTOPROXY> is typically set as
1610"C<hostname=...;port=...>". See the DBD::Proxy documentation for more details.
1611
1612If C<$username> or C<$password> are undefined (rather than just empty),
1613then the DBI will substitute the values of the C<DBI_USER> and C<DBI_PASS>
1614environment variables, respectively. The DBI will warn if the
1615environment variables are not defined. However, the everyday use of
1616these environment
1617variables is not recommended for security reasons. The mechanism is
1618primarily intended to simplify testing.
1619
1620C<DBI->E<gt>C<connect> automatically installs the driver if it has not been
1621installed yet. Driver installation either returns a valid driver
1622handle, or it I<dies> with an error message that includes the string
1623"C<install_driver>" and the underlying problem. So C<DBI->E<gt>C<connect>
1624will die
1625on a driver installation failure and will only return C<undef> on a
1626connect failure, in which case C<$DBI::errstr> will hold the error message.
1627
1628The C<$data_source> argument (with the "C<dbi:...:>" prefix removed) and the
1629C<$username> and C<$password> arguments are then passed to the driver for
1630processing. The DBI does not define any interpretation for the
1631contents of these fields. The driver is free to interpret the
1632C<$data_source>, C<$username>, and C<$password> fields in any way, and supply
1633whatever defaults are appropriate for the engine being accessed.
1634(Oracle, for example, uses the ORACLE_SID and TWO_TASK environment
1635variables if no C<$data_source> is specified.)
1636
1637The C<AutoCommit> and C<PrintError> attributes for each connection default to
1638"on". (See L</AutoCommit> and L</PrintError> for more information.)
1639However, it is strongly recommended that you explicitly define C<AutoCommit>
1640rather than rely on the default. Future versions of
1641the DBI may issue a warning if C<AutoCommit> is not explicitly defined.
1642
1643The C<\%attr> parameter can be used to alter the default settings of
1644C<PrintError>, C<RaiseError>, C<AutoCommit>, and other attributes. For example:
1645
1646 $dbh = DBI->connect($data_source, $user, $pass, {
1647 PrintError => 0,
1648 AutoCommit => 0
1649 });
1650
1651You can also define connection attribute values within the C<$data_source>
1652parameter. For example:
1653
1654 dbi:DriverName(PrintError=>0,Taint=>1):...
1655
1656Individual attributes values specified in this way take precedence over
1657any conflicting values specified via the C<\%attr> parameter to C<connect>.
1658
1659The C<dbi_connect_method> attribute can be used to specify which driver
1660method should be called to establish the connection. The only useful
1661values are 'connect', 'connect_cached', or some specialized case like
1662'Apache::DBI::connect' (which is automatically the default when running
1663within Apache).
1664
1665Where possible, each session (C<$dbh>) is independent from the transactions
1666in other sessions. This is useful when you need to hold cursors open
1667across transactions--for example, if you use one session for your long lifespan
1668cursors (typically read-only) and another for your short update
1669transactions.
1670
1671For compatibility with old DBI scripts, the driver can be specified by
1672passing its name as the fourth argument to C<connect> (instead of C<\%attr>):
1673
1674 $dbh = DBI->connect($data_source, $user, $pass, $driver);
1675
1676In this "old-style" form of C<connect>, the C<$data_source> should not start
1677with "C<dbi:driver_name:>". (If it does, the embedded driver_name
1678will be ignored). Also note that in this older form of C<connect>,
1679the C<$dbh->E<gt>C<{AutoCommit}> attribute is I<undefined>, the
1680C<$dbh->E<gt>C<{PrintError}> attribute is off, and the old C<DBI_DBNAME>
1681environment variable is
1682checked if C<DBI_DSN> is not defined. Beware that this "old-style"
1683C<connect> will be withdrawn in a future version of DBI.
1684
1685=item C<connect_cached> I<NEW>
1686
1687 $dbh = DBI->connect_cached($data_source, $username, $password)
1688 or die $DBI::errstr;
1689 $dbh = DBI->connect_cached($data_source, $username, $password, \%attr)
1690 or die $DBI::errstr;
1691
1692C<connect_cached> is like L</connect>, except that the database handle
1693returned is also
1694stored in a hash associated with the given parameters. If another call
1695is made to C<connect_cached> with the same parameter values, then the
1696corresponding cached C<$dbh> will be returned if it is still valid.
1697The cached database handle is replaced with a new connection if it
1698has been disconnected or if the C<ping> method fails.
1699
1700Note that the behavior of this method differs in several respects from the
1701behavior of presistent connections implemented by Apache::DBI.
1702
1703Caching can be useful in some applications, but it can also cause
1704problems and should be used with care. The exact behavior of this
1705method is liable to change, so if you intend to use it in any production
1706applications you should discuss your needs on the I<dbi-users> mailing list.
1707
1708The cache can be accessed (and cleared) via the L</CachedKids> attribute.
1709
1710
1711=item C<available_drivers>
1712
1713 @ary = DBI->available_drivers;
1714 @ary = DBI->available_drivers($quiet);
1715
1716Returns a list of all available drivers by searching for C<DBD::*> modules
1717through the directories in C<@INC>. By default, a warning is given if
1718some drivers are hidden by others of the same name in earlier
1719directories. Passing a true value for C<$quiet> will inhibit the warning.
1720
1721
1722=item C<data_sources>
1723
1724 @ary = DBI->data_sources($driver);
1725 @ary = DBI->data_sources($driver, \%attr);
1726
1727Returns a list of all data sources (databases) available via the named
1728driver. If C<$driver> is empty or C<undef>, then the value of the
1729C<DBI_DRIVER> environment variable is used.
1730
1731The driver will be loaded if it hasn't been already. Note that if the
1732driver loading fails then it I<dies> with an error message that
1733includes the string "C<install_driver>" and the underlying problem.
1734
1735Data sources are returned in a form suitable for passing to the
1736L</connect> method (that is, they will include the "C<dbi:$driver:>" prefix).
1737
1738Note that many drivers have no way of knowing what data sources might
1739be available for it. These drivers return an empty or incomplete list
1740or may require driver-specific attributes, such as a connected database
1741handle, to be supplied.
1742
1743
1744=item C<trace>
1745
1746 DBI->trace($trace_level)
1747 DBI->trace($trace_level, $trace_filename)
1748
1749DBI trace information can be enabled for all handles using the C<trace>
1750DBI class method. To enable trace information for a specific handle, use
1751the similar C<$h->E<gt>C<trace> method described elsewhere.
1752
1753Trace levels are as follows:
1754
1755 0 - Trace disabled.
1756 1 - Trace DBI method calls returning with results or errors.
1757 2 - Trace method entry with parameters and returning with results.
1758 3 - As above, adding some high-level information from the driver
1759 and some internal information from the DBI.
1760 4 - As above, adding more detailed information from the driver.
1761 Also includes DBI mutex information when using threaded Perl.
1762 5 and above - As above but with more and more obscure information.
1763
1764Trace level 1 is best for a simple overview of what's happening.
1765Trace level 2 is a good choice for general purpose tracing. Levels 3
1766and above (up to 9) are best reserved for investigating a
1767specific problem, when you need to see "inside" the driver and DBI.
1768
1769The trace output is detailed and typically very useful. Much of the
1770trace output is formatted using the L</neat> function, so strings
1771in the trace output may be edited and truncated.
1772
1773Initially trace output is written to C<STDERR>. If C<$trace_filename> is
1774specified and can be opened in append mode then all trace
1775output (including that from other handles) is redirected to that file.
1776A warning is generated is the file can't be opened.
1777Further calls to C<trace> without a C<$trace_filename> do not alter where
1778the trace output is sent. If C<$trace_filename> is undefined, then
1779trace output is sent to C<STDERR> and the previous trace file is closed.
1780The C<trace> method returns the I<previous> tracelevel.
1781
1782See also the C<$h->E<gt>C<trace> and C<$h->E<gt>C<trace_msg> methods and the
1783L</DEBUGGING> section
1784for information about the C<DBI_TRACE> environment variable.
1785
1786
1787=back
1788
1789
1790=head2 DBI Utility Functions
1791
1792In addition to the methods listed in the previous section,
1793the DBI package also provides these utility functions:
1794
1795=over 4
1796
1797=item C<neat>
1798
1799 $str = DBI::neat($value, $maxlen);
1800
1801Return a string containing a neat (and tidy) representation of the
1802supplied value.
1803
1804Strings will be quoted, although internal quotes will I<not> be escaped.
1805Values known to be numeric will be unquoted. Undefined (NULL) values
1806will be shown as C<undef> (without quotes). Unprintable characters will
1807be replaced by dot (.).
1808
1809For result strings longer than C<$maxlen> the result string will be
1810truncated to C<$maxlen-4> and "C<...'>" will be appended. If C<$maxlen> is 0
1811or C<undef>, it defaults to C<$DBI::neat_maxlen> which, in turn, defaults to 400.
1812
1813This function is designed to format values for human consumption.
1814It is used internally by the DBI for L</trace> output. It should
1815typically I<not> be used for formatting values for database use.
1816(See also L</quote>.)
1817
1818=item C<neat_list>
1819
1820 $str = DBI::neat_list(\@listref, $maxlen, $field_sep);
1821
1822Calls C<DBI::neat> on each element of the list and returns a string
1823containing the results joined with C<$field_sep>. C<$field_sep> defaults
1824to C<", ">.
1825
1826=item C<looks_like_number>
1827
1828 @bool = DBI::looks_like_number(@array);
1829
1830Returns true for each element that looks like a number.
1831Returns false for each element that does not look like a number.
1832Returns C<undef> for each element that is undefined or empty.
1833
1834=back
1835
1836
1837=head2 DBI Dynamic Attributes
1838
1839Dynamic attributes are always associated with the I<last handle used>
1840(that handle is represented by C<$h> in the descriptions below).
1841
1842Where an attribute is equivalent to a method call, then refer to
1843the method call for all related documentation.
1844
1845Warning: these attributes are provided as a convenience but they
1846do have limitations. Specifically, they have a short lifespan:
1847because they are associated with
1848the last handle used, they should only be used I<immediately> after
1849calling the method that "sets" them.
1850If in any doubt, use the corresponding method call.
1851
1852=over 4
1853
1854=item C<$DBI::err>
1855
1856Equivalent to C<$h->E<gt>C<err>.
1857
1858=item C<$DBI::errstr>
1859
1860Equivalent to C<$h->E<gt>C<errstr>.
1861
1862=item C<$DBI::state>
1863
1864Equivalent to C<$h->E<gt>C<state>.
1865
1866=item C<$DBI::rows>
1867
1868Equivalent to C<$h->E<gt>C<rows>. Please refer to the documentation
1869for the L</rows> method.
1870
1871=item C<$DBI::lasth>
1872
1873Returns the DBI object handle used for the most recent DBI method call.
1874If the last DBI method call was a DESTROY then $DBI::lasth will return
1875the handle of the parent of the destroyed handle, if there is one.
1876
1877=back
1878
1879
1880=head1 METHODS COMMON TO ALL HANDLES
1881
1882The following methods can be used by all types of DBI handles.
1883
1884=over 4
1885
1886=item C<err>
1887
1888 $rv = $h->err;
1889
1890Returns the I<native> database engine error code from the last driver
1891method called. The code is typically an integer but you should not
1892assume that.
1893
1894The DBI resets $h->err to undef before most DBI method calls, so the
1895value only has a short lifespan. Also, most drivers share the same
1896error variables across all their handles, so calling a method on
1897one handle will typically reset the error on all the other handles
1898that are children of that driver.
1899
1900If you need to test for individual errors I<and> have your program be
1901portable to different database engines, then you'll need to determine
1902what the corresponding error codes are for all those engines and test for
1903all of them.
1904
1905=item C<errstr>
1906
1907 $str = $h->errstr;
1908
1909Returns the native database engine error message from the last driver
1910method called. This has the same lifespan issues as the L</err> method
1911described above.
1912
1913=item C<state>
1914
1915 $str = $h->state;
1916
1917Returns an error code in the standard SQLSTATE five character format.
1918Note that the specific success code C<00000> is translated to 'C<>'
1919(false). If the driver does not support SQLSTATE (and most don't),
1920then state will return C<S1000> (General Error) for all errors.
1921
1922The driver is free to return any value via C<state>, e.g., warning
1923codes, even if it has not declared an error by returning a true value
1924via the L</err> method described above.
1925
1926=item C<trace>
1927
1928 $h->trace($trace_level);
1929 $h->trace($trace_level, $trace_filename);
1930
1931DBI trace information can be enabled for a specific handle (and any
1932future children of that handle) by setting the trace level using the
1933C<trace> method.
1934
1935Trace level 1 is best for a simple overview of what's happening.
1936Trace level 2 is a good choice for general purpose tracing. Levels 3
1937and above (up to 9) are best reserved for investigating a
1938specific problem, when you need to see "inside" the driver and DBI.
1939Set C<$trace_level> to 0 to disable the trace.
1940
1941The trace output is detailed and typically very useful. Much of the
1942trace output is formatted using the L</neat> function, so strings
1943in the trace output may be edited and truncated.
1944
1945Initially, trace output is written to C<STDERR>. If C<$trace_filename> is
1946specified, then the file is opened in append mode and I<all> trace
1947output (including that from other handles) is redirected to that file.
1948Further calls to trace without a C<$trace_filename> do not alter where
1949the trace output is sent. If C<$trace_filename> is undefined, then
1950trace output is sent to C<STDERR> and the previous trace file is closed.
1951
1952See also the C<DBI->E<gt>C<trace> method and L</DEBUGGING> for information
1953about the C<DBI_TRACE> environment variable.
1954
1955
1956=item C<trace_msg>
1957
1958 $h->trace_msg($message_text);
1959 $h->trace_msg($message_text, $min_level);
1960
1961Writes C<$message_text> to the trace file if trace is enabled for C<$h> or
1962for the DBI as a whole. Can also be called as C<DBI->E<gt>C<trace_msg($msg)>.
1963See L</trace>.
1964
1965If C<$min_level> is defined, then the message is output only if the trace
1966level is equal to or greater than that level. C<$min_level> defaults to 1.
1967
1968
1969=item C<func>
1970
1971 $h->func(@func_arguments, $func_name);
1972
1973The C<func> method can be used to call private non-standard and
1974non-portable methods implemented by the driver. Note that the function
1975name is given as the last argument.
1976
1977This method is not directly related to calling stored procedures.
1978Calling stored procedures is currently not defined by the DBI.
1979Some drivers, such as DBD::Oracle, support it in non-portable ways.
1980See driver documentation for more details.
1981
1982=back
1983
1984
1985=head1 ATTRIBUTES COMMON TO ALL HANDLES
1986
1987These attributes are common to all types of DBI handles.
1988
1989Some attributes are inherited by child handles. That is, the value
1990of an inherited attribute in a newly created statement handle is the
1991same as the value in the parent database handle. Changes to attributes
1992in the new statement handle do not affect the parent database handle
1993and changes to the database handle do not affect existing statement
1994handles, only future ones.
1995
1996Attempting to set or get the value of an unknown attribute is fatal,
1997except for private driver specific attributes (which all have names
1998starting with a lowercase letter).
1999
2000Example:
2001
2002 $h->{AttributeName} = ...; # set/write
2003 ... = $h->{AttributeName}; # get/read
2004
2005=over 4
2006
2007=item C<Warn> (boolean, inherited)
2008
2009Enables useful warnings for certain bad practices. Enabled by default. Some
2010emulation layers, especially those for Perl 4 interfaces, disable warnings.
2011Since warnings are generated using the Perl C<warn> function, they can be
2012intercepted using the Perl C<$SIG{__WARN__}> hook.
2013
2014=item C<Active> (boolean, read-only)
2015
2016True if the handle object is "active". This is rarely used in
2017applications. The exact meaning of active is somewhat vague at the
2018moment. For a database handle it typically means that the handle is
2019connected to a database (C<$dbh->E<gt>C<disconnect> sets C<Active> off). For
2020a statement handle it typically means that the handle is a C<SELECT>
2021that may have more data to fetch. (Fetching all the data or calling C<$sth->E<gt>C<finish>
2022sets C<Active> off.)
2023
2024=item C<Kids> (integer, read-only)
2025
2026For a driver handle, C<Kids> is the number of currently existing database
2027handles that were created from that driver handle. For a database
2028handle, C<Kids> is the number of currently existing statement handles that
2029were created from that database handle.
2030
2031=item C<ActiveKids> (integer, read-only)
2032
2033Like C<Kids>, but only counting those that are C<Active> (as above).
2034
2035=item C<CachedKids> (hash ref)
2036
2037For a database handle, returns a reference to the cache (hash) of
2038statement handles created by the L</prepare_cached> method. For a
2039driver handle, returns a reference to the cache (hash) of
2040database handles created by the L</connect_cached> method.
2041
2042=item C<CompatMode> (boolean, inherited)
2043
2044Used by emulation layers (such as Oraperl) to enable compatible behavior
2045in the underlying driver (e.g., DBD::Oracle) for this handle. Not normally
2046set by application code.
2047
2048=item C<InactiveDestroy> (boolean)
2049
2050This attribute can be used to disable the I<database engine> related
2051effect of DESTROYing a handle (which would normally close a prepared
2052statement or disconnect from the database etc).
2053
2054For a database handle, this attribute does not disable an I<explicit>
2055call to the disconnect method, only the implicit call from DESTROY.
2056
2057This attribute is specifically designed for use in Unix applications
2058that "fork" child processes. Either the parent or the child process,
2059but not both, should set C<InactiveDestroy> on all their shared handles.
2060Note that some databases, including Oracle, don't support passing a
2061database connection across a fork.
2062
2063=item C<PrintError> (boolean, inherited)
2064
2065This attribute can be used to force errors to generate warnings (using
2066C<warn>) in addition to returning error codes in the normal way. When set
2067"on", any method which results in an error occuring will cause the DBI to
2068effectively do a C<warn("$class $method failed: $DBI::errstr")> where C<$class>
2069is the driver class and C<$method> is the name of the method which failed. E.g.,
2070
2071 DBD::Oracle::db prepare failed: ... error text here ...
2072
2073By default, C<DBI->E<gt>C<connect> sets C<PrintError> "on".
2074
2075If desired, the warnings can be caught and processed using a C<$SIG{__WARN__}>
2076handler or modules like CGI::Carp and CGI::ErrorWrap.
2077
2078=item C<RaiseError> (boolean, inherited)
2079
2080This attribute can be used to force errors to raise exceptions rather
2081than simply return error codes in the normal way. It is "off" by default.
2082When set "on", any method which results in an error will cause
2083the DBI to effectively do a C<die("$class $method failed: $DBI::errstr")>,
2084where C<$class> is the driver class and C<$method> is the name of the method
2085that failed. E.g.,
2086
2087 DBD::Oracle::db prepare failed: ... error text here ...
2088
2089If you turn C<RaiseError> on then you'd normally turn C<PrintError> off.
2090If C<PrintError> is also on, then the C<PrintError> is done first (naturally).
2091
2092Typically C<RaiseError> is used in conjunction with C<eval { ... }>
2093to catch the exception that's been thrown and followed by an
2094C<if ($@) { ... }> block to handle the caught exception. In that eval
2095block the $DBI::lasth variable can be useful for diagnosis and reporting.
2096For example, $DBI::lasth->{Type} and $DBI::lasth->{Statement}.
2097
2098If you want to temporarily turn C<RaiseError> off (inside a library function
2099that is likely to fail, for example), the recommended way is like this:
2100
2101 {
2102 local $h->{RaiseError}; # localize and turn off for this block
2103 ...
2104 }
2105
2106The original value will automatically and reliably be restored by Perl,
2107regardless of how the block is exited.
2108The same logic applies to other attributes, including C<PrintError>.
2109
2110Sadly, this doesn't work for Perl versions up to and including 5.004_04.
2111Even more sadly, for Perl 5.5 and 5.6.0 it does work but leaks memory!
2112For backwards compatibility, you could just use C<eval { ... }> instead.
2113
2114
2115=item C<ShowErrorStatement> (boolean, inherited) I<NEW>
2116
2117This attribute can be used to cause the relevant Statement text to be
2118appended to the error messages generated by the C<RaiseError> and
2119C<PrintError> attributes. Only applies to errors on statement handles
2120plus the prepare() and do() database handle methods.
2121(The exact format of the appended text is subject to change.)
2122
2123
2124=item C<ChopBlanks> (boolean, inherited)
2125
2126This attribute can be used to control the trimming of trailing space
2127characters from fixed width character (CHAR) fields. No other field
2128types are affected, even where field values have trailing spaces.
2129
2130The default is false (although it is possible that the default may change).
2131Applications that need specific behavior should set the attribute as
2132needed. Emulation interfaces should set the attribute to match the
2133behavior of the interface they are emulating.
2134
2135Drivers are not required to support this attribute, but any driver which
2136does not support it must arrange to return C<undef> as the attribute value.
2137
2138
2139=item C<LongReadLen> (unsigned integer, inherited)
2140
2141This attribute may be used to control the maximum length of long fields
2142("blob", "memo", etc.) which the driver will read from the
2143database automatically when it fetches each row of data. The
2144C<LongReadLen> attribute only relates to fetching and reading long values; it
2145is not involved in inserting or updating them.
2146
2147A value of 0 means not to automatically fetch any long data. (C<fetch>
2148should return C<undef> for long fields when C<LongReadLen> is 0.)
2149
2150The default is typically 0 (zero) bytes but may vary between drivers.
2151Applications fetching long fields should set this value to slightly
2152larger than the longest long field value to be fetched.
2153
2154Some databases return some long types encoded as pairs of hex digits.
2155For these types, C<LongReadLen> relates to the underlying data length and not the
2156doubled-up length of the encoded string.
2157
2158Changing the value of C<LongReadLen> for a statement handle after it
2159has been C<prepare>'d will typically have no effect, so it's common to
2160set C<LongReadLen> on the C<$dbh> before calling C<prepare>.
2161
2162Note that the value used here has a direct effect on the memory used
2163by the application, so don't be too generous.
2164
2165See L</LongTruncOk> for more information on truncation behavior.
2166
2167=item C<LongTruncOk> (boolean, inherited)
2168
2169This attribute may be used to control the effect of fetching a long
2170field value which has been truncated (typically because it's longer
2171than the value of the C<LongReadLen> attribute).
2172
2173By default, C<LongTruncOk> is false and so fetching a long value that
2174needs to be truncated will cause the fetch to fail.
2175(Applications should always be sure to
2176check for errors after a fetch loop in case an error, such as a divide
2177by zero or long field truncation, caused the fetch to terminate
2178prematurely.)
2179
2180If a fetch fails due to a long field truncation when C<LongTruncOk> is
2181false, many drivers will allow you to continue fetching further rows.
2182
2183See also L</LongReadLen>.
2184
2185=item C<Taint> (boolean, inherited)
2186
2187If this attribute is set to a true value I<and> Perl is running in
2188taint mode (e.g., started with the C<-T> option), then all data
2189fetched from the database is tainted, and the arguments to most DBI
2190method calls are checked for being tainted. I<This may change.>
2191
2192The attribute defaults to off, even if Perl is in taint mode.
2193See L<perlsec> for more about taint mode. If Perl is not
2194running in taint mode, this attribute has no effect.
2195
2196When fetching data that you trust you can turn off the Taint attribute,
2197for that statement handle, for the duration of the fetch loop.
2198
2199Currently only fetched data is tainted. It is possible that the results
2200of other DBI method calls, and the value of fetched attributes, may
2201also be tainted in future versions. That change may well break your
2202applications unless you take great care now. If you use DBI Taint mode,
2203please report your experience and any suggestions for changes.
2204
2205
2206=item C<private_*>
2207
2208The DBI provides a way to store extra information in a DBI handle as
2209"private" attributes. The DBI will allow you to store and retreive any
2210attribute which has a name starting with "C<private_>". It is strongly
2211recommended that you use just I<one> private attribute (e.g., use a
2212hash ref) and give it a long and unambiguous name that includes the
2213module or application name that the attribute relates to (e.g.,
2214"C<private_YourFullModuleName_thingy>").
2215
2216=back
2217
2218
2219=head1 DBI DATABASE HANDLE OBJECTS
2220
2221This section covers the methods and attributes associated with
2222database handles.
2223
2224=head2 Database Handle Methods
2225
2226The following methods are specified for DBI database handles:
2227
2228=over 4
2229
2230=item C<do>
2231
2232 $rc = $dbh->do($statement) or die $dbh->errstr;
2233 $rc = $dbh->do($statement, \%attr) or die $dbh->errstr;
2234 $rv = $dbh->do($statement, \%attr, @bind_values) or ...
2235
2236Prepare and execute a single statement. Returns the number of rows
2237affected or C<undef> on error. A return value of C<-1> means the
2238number of rows is not known or is not available.
2239
2240This method is typically most useful for I<non>-C<SELECT> statements that
2241either cannot be prepared in advance (due to a limitation of the
2242driver) or do not need to be executed repeatedly. It should not
2243be used for C<SELECT> statements because it does not return a statement
2244handle (so you can't fetch any data).
2245
2246The default C<do> method is logically similar to:
2247
2248 sub do {
2249 my($dbh, $statement, $attr, @bind_values) = @_;
2250 my $sth = $dbh->prepare($statement, $attr) or return undef;
2251 $sth->execute(@bind_values) or return undef;
2252 my $rows = $sth->rows;
2253 ($rows == 0) ? "0E0" : $rows; # always return true if no error
2254 }
2255
2256For example:
2257
2258 my $rows_deleted = $dbh->do(q{
2259 DELETE FROM table
2260 WHERE status = ?
2261 }, undef, 'DONE') or die $dbh->errstr;
2262
2263Using placeholders and C<@bind_values> with the C<do> method can be
2264useful because it avoids the need to correctly quote any variables
2265in the C<$statement>. But if you'll be executing the statement many
2266times then it's more efficient to C<prepare> it once and call
2267C<execute> many times instead.
2268
2269The C<q{...}> style quoting used in this example avoids clashing with
2270quotes that may be used in the SQL statement. Use the double-quote-like
2271C<qq{...}> operator if you want to interpolate variables into the string.
2272See L<perlop/"Quote and Quote-like Operators"> for more details.
2273
2274=item C<selectrow_array>
2275
2276 @row_ary = $dbh->selectrow_array($statement);
2277 @row_ary = $dbh->selectrow_array($statement, \%attr);
2278 @row_ary = $dbh->selectrow_array($statement, \%attr, @bind_values);
2279
2280This utility method combines L</prepare>, L</execute> and
2281L</fetchrow_array> into a single call. If called in a list context, it
2282returns the first row of data from the statement. If called in a scalar
2283context, it returns the first field of the first row. The C<$statement>
2284parameter can be a previously prepared statement handle, in which case
2285the C<prepare> is skipped.
2286
2287If any method fails, and L</RaiseError> is not set, C<selectrow_array>
2288will return an empty list.
2289
2290In a scalar context, C<selectrow_array> returns the value of the first
2291field. An C<undef> is returned if there are no matching rows or an error
2292occurred. Since that C<undef> can't be distinguished from an C<undef> returned
2293because the first field value was NULL, calling C<selectrow_array> in
2294a scalar context should be used with caution.
2295
2296
2297=item C<selectall_arrayref>
2298
2299 $ary_ref = $dbh->selectall_arrayref($statement);
2300 $ary_ref = $dbh->selectall_arrayref($statement, \%attr);
2301 $ary_ref = $dbh->selectall_arrayref($statement, \%attr, @bind_values);
2302
2303This utility method combines L</prepare>, L</execute> and
2304L</fetchall_arrayref> into a single call. It returns a reference to an
2305array containing a reference to an array for each row of data fetched.
2306
2307The C<$statement> parameter can be a previously prepared statement handle,
2308in which case the C<prepare> is skipped. This is recommended if the
2309statement is going to be executed many times.
2310
2311If L</RaiseError> is not set and any method except C<fetchall_arrayref>
2312fails then C<selectall_arrayref> will return C<undef>; if
2313C<fetchall_arrayref> fails then it will return with whatever data it
2314has been fetched thus far. $DBI::err should be checked to catch that.
2315
2316
2317=item C<selectall_hashref>
2318
2319 $ary_ref = $dbh->selectall_hashref($statement);
2320 $ary_ref = $dbh->selectall_hashref($statement, \%attr);
2321 $ary_ref = $dbh->selectall_hashref($statement, \%attr, @bind_values);
2322
2323This utility method combines L</prepare>, L</execute> and
2324L</fetchrow_hashref> into a single call. It returns a reference to an
2325array containing, for each row of data fetched, a reference to a hash
2326containing field name and value pairs for that row.
2327
2328The C<$statement> parameter can be a previously prepared statement handle,
2329in which case the C<prepare> is skipped. This is recommended if the
2330statement is going to be executed many times.
2331
2332If any method except C<fetchrow_hashref> fails, and L</RaiseError> is not set,
2333C<selectall_hashref> will return C<undef>. If C<fetchrow_hashref> fails and
2334L</RaiseError> is not set, then it will return with whatever data it
2335has fetched thus far. $DBI::err should be checked to catch that.
2336
2337
2338=item C<selectcol_arrayref>
2339
2340 $ary_ref = $dbh->selectcol_arrayref($statement);
2341 $ary_ref = $dbh->selectcol_arrayref($statement, \%attr);
2342 $ary_ref = $dbh->selectcol_arrayref($statement, \%attr, @bind_values);
2343
2344This utility method combines L</prepare>, L</execute>, and fetching one
2345column from all the rows, into a single call. It returns a reference to
2346an array containing the values of the first column from each row.
2347
2348The C<$statement> parameter can be a previously prepared statement handle,
2349in which case the C<prepare> is skipped. This is recommended if the
2350statement is going to be executed many times.
2351
2352If any method except C<fetch> fails, and L</RaiseError> is not set,
2353C<selectcol_arrayref> will return C<undef>. If C<fetch> fails and
2354L</RaiseError> is not set, then it will return with whatever data it
2355has fetched thus far. $DBI::err should be checked to catch that.
2356
2357
2358=item C<prepare>
2359
2360 $sth = $dbh->prepare($statement) or die $dbh->errstr;
2361 $sth = $dbh->prepare($statement, \%attr) or die $dbh->errstr;
2362
2363Prepares a single statement for later execution by the database
2364engine and returns a reference to a statement handle object.
2365
2366The returned statement handle can be used to get attributes of the
2367statement and invoke the L</execute> method. See L</Statement Handle Methods>.
2368
2369Drivers for engines without the concept of preparing a
2370statement will typically just store the statement in the returned
2371handle and process it when C<$sth->E<gt>C<execute> is called. Such drivers are
2372unlikely to give much useful information about the
2373statement, such as C<$sth->E<gt>C<{NUM_OF_FIELDS}>, until after C<$sth->E<gt>C<execute>
2374has been called. Portable applications should take this into account.
2375
2376In general, DBI drivers do not parse the contents of the statement
2377(other than simply counting any L</Placeholders>). The statement is
2378passed directly to the database engine, sometimes known as pass-thru
2379mode. This has advantages and disadvantages. On the plus side, you can
2380access all the functionality of the engine being used. On the downside,
2381you're limited if you're using a simple engine, and you need to take extra care if
2382writing applications intended to be portable between engines.
2383
2384Portable applications should not assume that a new statement can be
2385prepared and/or executed while still fetching results from a previous
2386statement.
2387
2388Some command-line SQL tools use statement terminators, like a semicolon,
2389to indicate the end of a statement. Such terminators should not normally
2390be used with the DBI.
2391
2392
2393=item C<prepare_cached>
2394
2395 $sth = $dbh->prepare_cached($statement)
2396 $sth = $dbh->prepare_cached($statement, \%attr)
2397 $sth = $dbh->prepare_cached($statement, \%attr, $allow_active)
2398
2399Like L</prepare> except that the statement handle returned will be
2400stored in a hash associated with the C<$dbh>. If another call is made to
2401C<prepare_cached> with the same C<$statement> and C<%attr> values, then the
2402corresponding cached C<$sth> will be returned without contacting the
2403database server.
2404
2405This caching can be useful in some applications, but it can also cause
2406problems and should be used with care. If the cached C<$sth> being
2407returned is active (i.e., is a C<SELECT> that may still have data to be
2408fetched) then a warning will be generated and C<finish> will be called
2409for you. The warning can be suppressed by setting C<$allow_active> to
2410true. The cache can be accessed (and cleared) via the L</CachedKids>
2411attribute.
2412
2413Here's an example of one possible use of C<prepare_cached>:
2414
2415 while ( ($field, $value) = each %search_fields ) {
2416 push @sql, "$field = ?";
2417 push @values, $value;
2418 }
2419 $qualifier = "";
2420 $qualifier = "where ".join(" and ", @sql) if @sql;
2421 $sth = $dbh->prepare_cached("SELECT * FROM table $qualifier");
2422 $sth->execute(@values);
2423
2424
2425=item C<commit>
2426
2427 $rc = $dbh->commit or die $dbh->errstr;
2428
2429Commit (make permanent) the most recent series of database changes
2430if the database supports transactions and AutoCommit is off.
2431
2432If C<AutoCommit> is on, then calling
2433C<commit> will issue a "commit ineffective with AutoCommit" warning.
2434
2435See also L</Transactions> in the L</FURTHER INFORMATION> section below.
2436
2437=item C<rollback>
2438
2439 $rc = $dbh->rollback or die $dbh->errstr;
2440
2441Rollback (undo) the most recent series of uncommitted database
2442changes if the database supports transactions and AutoCommit is off.
2443
2444If C<AutoCommit> is on, then calling
2445C<rollback> will issue a "rollback ineffective with AutoCommit" warning.
2446
2447See also L</Transactions> in the L</FURTHER INFORMATION> section below.
2448
2449
2450=item C<disconnect>
2451
2452 $rc = $dbh->disconnect or warn $dbh->errstr;
2453
2454Disconnects the database from the database handle. C<disconnect> is typically only used
2455before exiting the program. The handle is of little use after disconnecting.
2456
2457The transaction behavior of the C<disconnect> method is, sadly,
2458undefined. Some database systems (such as Oracle and Ingres) will
2459automatically commit any outstanding changes, but others (such as
2460Informix) will rollback any outstanding changes. Applications not
2461using C<AutoCommit> should explicitly call C<commit> or C<rollback> before
2462calling C<disconnect>.
2463
2464The database is automatically disconnected by the C<DESTROY> method if
2465still connected when there are no longer any references to the handle.
2466The C<DESTROY> method for each driver should implicitly call C<rollback> to
2467undo any uncommitted changes. This is vital behavior to ensure that
2468incomplete transactions don't get committed simply because Perl calls
2469C<DESTROY> on every object before exiting. Also, do not rely on the order
2470of object destruction during "global destruction", as it is undefined.
2471
2472Generally, if you want your changes to be commited or rolled back when
2473you disconnect, then you should explicitly call L</commit> or L</rollback>
2474before disconnecting.
2475
2476If you disconnect from a database while you still have active statement
2477handles, you will get a warning. The statement handles should either be
2478cleared (destroyed) before disconnecting, or the C<finish> method
2479should be called on
2480each one.
2481
2482
2483=item C<ping>
2484
2485 $rc = $dbh->ping;
2486
2487Attempts to determine, in a reasonably efficient way, if the database
2488server is still running and the connection to it is still working.
2489Individual drivers should implement this function in the most suitable
2490manner for their database engine.
2491
2492The current I<default> implementation always returns true without
2493actually doing anything. Actually, it returns "C<0 but true>" which is
2494true but zero. That way you can tell if the return value is genuine or
2495just the default. Drivers should override this method with one that
2496does the right thing for their type of database.
2497
2498Few applications would have direct use for this method. See the specialized
2499Apache::DBI module for one example usage.
2500
2501
2502=item C<table_info> I<NEW>
2503
2504B<Warning:> This method is experimental and may change.
2505
2506 $sth = $dbh->table_info;
2507 $sth = $dbh->table_info( \%attr );
2508
2509Returns an active statement handle that can be used to fetch
2510information about tables and views that exist in the database.
2511
2512The following attributes (all or separate) may be used as selection criteria:
2513
2514 %attr = (
2515 TABLE_CAT => $CatVal # String value of the catalog name
2516 , TABLE_SCHEM => $SchVal # String value of the schema name
2517 , TABLE_NAME => $TblVal # String value of the table name
2518 , TABLE_TYPE => $TypVal # String value of the table type(s)
2519 );
2520
2521Note: The support for the selection criteria is driver specific. If the
2522driver doesn't support one or more then them then you'll get back more
2523than you asked for and can do the filtering yourself.
2524
2525The arguments TABLE_CAT, TABLE_SCHEM and TABLE_NAME may accept search
2526patterns according to the database/driver, for example:
2527
2528 $sth = $dbh->table_info( { TABLE_NAME => '%TAB%'} );
2529
2530The value of TABLE_TYPE is a comma-separated list of one or more types
2531of tables to be returned in the result set. Each value may optionally be
2532quoted, e.g.:
2533
2534 $sth = $dbh->table_info( { TABLE_TYPE => "TABLE" } );
2535 $sth = $dbh->table_info( { TABLE_TYPE => "'TABLE', 'VIEW'" } );
2536
2537In addition the following special cases may also be supported by some drivers:
2538
2539=over 4
2540
2541=item *
2542If the value of TABLE_CAT is '%' and TABLE_SCHEM and TABLE_NAME name
2543are empty strings, the result set contains a list of catalog names.
2544For example:
2545
2546 $sth = $dbh->table_info({ TABLE_CAT=>'%', TABLE_SCHEM=>'', TABLE_NAME=>'' });
2547
2548=item *
2549If the value of TABLE_SCHEM is '%' and TABLE_CAT and TABLE_NAME are
2550empty strings, the result set contains a list of schema names.
2551
2552=item *
2553If the value of TABLE_TYPE is '%' and TABLE_CAT, TABLE_SCHEM, and
2554TABLE_NAME are all empty strings, the result set contains a list of
2555table types.
2556
2557=back
2558
2559The statement handle returned has at least the following fields in the
2560order show below. Other fields, after these, may also be present.
2561
2562B<TABLE_CAT>: Table catalog identifier. This field is NULL (C<undef>) if not
2563applicable to the data source, which is usually the case. This field
2564is empty if not applicable to the table.
2565
2566B<TABLE_SCHEM>: The name of the schema containing the TABLE_NAME value.
2567This field is NULL (C<undef>) if not applicable to data source, and
2568empty if not applicable to the table.
2569
2570B<TABLE_NAME>: Name of the table (or view, synonym, etc).
2571
2572B<TABLE_TYPE>: One of the following: "TABLE", "VIEW", "SYSTEM TABLE",
2573"GLOBAL TEMPORARY", "LOCAL TEMPORARY", "ALIAS", "SYNONYM" or a type
2574identifier that is specific to the data
2575source.
2576
2577B<REMARKS>: A description of the table. May be NULL (C<undef>).
2578
2579Note that C<table_info> might not return records for all tables.
2580Applications can use any valid table regardless of whether it's
2581returned by C<table_info>. See also L</tables>.
2582
2583For more detailed information about the fields and their meanings,
2584you can refer to:
2585
2586 http://msdn.microsoft.com/library/psdk/dasdk/odch6wqb.htm
2587
2588If that URL ceases to work then use the MSDN search facility at:
2589
2590 http://search.microsoft.com/us/dev/
2591
2592and search for C<SQLTables returns> using the exact phrase option.
2593The link you want will probably just be called C<SQLTables> and will
2594be part of the Data Access SDK.
2595
2596See also page 306 of the (very large) SQL/CLI specification:
2597
2598 http://www.jtc1sc32.org/sc32/jtc1sc32.nsf/Attachments/DF86E81BE70151D58525699800643F56/$FILE/32N0595T.PDF
2599
2600=item C<tables> I<NEW>
2601
2602B<Warning:> This method is experimental and may change.
2603
2604 @names = $dbh->tables;
2605 @names = $dbh->tables( \%attr );
2606
2607Returns a list of table and view names, possibly including a schema prefix.
2608This list should include all
2609tables that can be used in a C<SELECT> statement without further
2610qualification.
2611
2612Note that C<table_info> might not return records for all tables.
2613Applications can use any valid table regardless of whether it's
2614returned by tables. See also L</table_info>.
2615
2616
2617=item C<type_info_all> I<NEW>
2618
2619B<Warning:> This method is experimental and may change.
2620
2621 $type_info_all = $dbh->type_info_all;
2622
2623Returns a reference to an array which holds information about each data
2624type variant supported by the database and driver. The array and its
2625contents should be treated as read-only.
2626
2627The first item is a reference to an 'index' hash of C<Name =>E<gt> C<Index> pairs.
2628The items following that are references to arrays, one per supported data
2629type variant. The leading index hash defines the names and order of the
2630fields within the arrays that follow it.
2631For example:
2632
2633 $type_info_all = [
2634 { TYPE_NAME => 0,
2635 DATA_TYPE => 1,
2636 COLUMN_SIZE => 2, # was PRECISION originally
2637 LITERAL_PREFIX => 3,
2638 LITERAL_SUFFIX => 4,
2639 CREATE_PARAMS => 5,
2640 NULLABLE => 6,
2641 CASE_SENSITIVE => 7,
2642 SEARCHABLE => 8,
2643 UNSIGNED_ATTRIBUTE=> 9,
2644 FIXED_PREC_SCALE => 10, # was MONEY originally
2645 AUTO_UNIQUE_VALUE => 11, # was AUTO_INCREMENT originally
2646 LOCAL_TYPE_NAME => 12,
2647 MINIMUM_SCALE => 13,
2648 MAXIMUM_SCALE => 14,
2649 NUM_PREC_RADIX => 15,
2650 },
2651 [ 'VARCHAR', SQL_VARCHAR,
2652 undef, "'","'", undef,0, 1,1,0,0,0,undef,1,255, undef
2653 ],
2654 [ 'INTEGER', SQL_INTEGER,
2655 undef, "", "", undef,0, 0,1,0,0,0,undef,0, 0, 10
2656 ],
2657 ];
2658
2659Note that more than one row may have the same value in the C<DATA_TYPE>
2660field if there are different ways to spell the type name and/or there
2661are variants of the type with different attributes (e.g., with and
2662without C<AUTO_UNIQUE_VALUE> set, with and without C<UNSIGNED_ATTRIBUTE>, etc).
2663
2664The rows are ordered by C<DATA_TYPE> first and then by how closely each
2665type maps to the corresponding ODBC SQL data type, closest first.
2666
2667The meaning of the fields is described in the documentation for
2668the L</type_info> method. The index values shown above (e.g.,
2669C<NULLABLE =>E<gt> C<6>) are for illustration only. Drivers may define the
2670fields with a different order.
2671
2672This method is not normally used directly. The L</type_info> method
2673provides a more useful interface to the data.
2674
2675Even though an 'index' hash is provided, all the field names in the
2676index hash defined above will always have the index values defined
2677above. This is defined behaviour so that you don't need to rely on the
2678index hash, which is handy because the lettercase of the keys is not
2679defined. It is usually uppercase, as show here, but drivers are free to
2680return names with any lettercase. Drivers are also free to return extra
2681driver-specific columns of information - though it's recommended that
2682they start at column index 50 to leave room for expansion of the
2683DBI/ODBC specification.
2684
2685
2686=item C<type_info> I<NEW>
2687
2688B<Warning:> This method is experimental and may change.
2689
2690 @type_info = $dbh->type_info($data_type);
2691
2692Returns a list of hash references holding information about one or more
2693variants of C<$data_type>. The list is ordered by C<DATA_TYPE> first and
2694then by how closely each type maps to the corresponding ODBC SQL data
2695type, closest first. If called in a scalar context then only the first
2696(best) element is returned.
2697
2698If C<$data_type> is undefined or C<SQL_ALL_TYPES>, then the list will
2699contain hashes for all data type variants supported by the database and driver.
2700
2701If C<$data_type> is an array reference then C<type_info> returns the
2702information for the I<first> type in the array that has any matches.
2703
2704The keys of the hash follow the same letter case conventions as the
2705rest of the DBI (see L</Naming Conventions and Name Space>). The
2706following items should exist:
2707
2708=over 4
2709
2710=item TYPE_NAME (string)
2711
2712Data type name for use in CREATE TABLE statements etc.
2713
2714=item DATA_TYPE (integer)
2715
2716SQL data type number.
2717
2718=item COLUMN_SIZE (integer)
2719
2720For numeric types, this is either the total number of digits (if the
2721NUM_PREC_RADIX value is 10) or the total number of bits allowed in the
2722column (if NUM_PREC_RADIX is 2).
2723
2724For string types, this is the maximum size of the string in bytes.
2725
2726For date and interval types, this is the maximum number of characters
2727needed to display the value.
2728
2729=item LITERAL_PREFIX (string)
2730
2731Characters used to prefix a literal. A typical prefix is "C<'>" for characters,
2732or possibly "C<0x>" for binary values passed as hexadecimal. NULL (C<undef>) is
2733returned for data types for which this is not applicable.
2734
2735
2736=item LITERAL_SUFFIX (string)
2737
2738Characters used to suffix a literal. Typically "C<'>" for characters.
2739NULL (C<undef>) is returned for data types where this is not applicable.
2740
2741=item CREATE_PARAMS (string)
2742
2743Parameter names for data type definition. For example, C<CREATE_PARAMS> for a
2744C<DECIMAL> would be "C<precision,scale>" if the DECIMAL type should be
2745declared as C<DECIMAL(>I<precision,scale>C<)> where I<precision> and I<scale>
2746are integer values. For a C<VARCHAR> it would be "C<max length>".
2747NULL (C<undef>) is returned for data types for which this is not applicable.
2748
2749=item NULLABLE (integer)
2750
2751Indicates whether the data type accepts a NULL value:
2752C<0> or an empty string = no, C<1> = yes, C<2> = unknown.
2753
2754=item CASE_SENSITIVE (boolean)
2755
2756Indicates whether the data type is case sensitive in collations and
2757comparisons.
2758
2759=item SEARCHABLE (integer)
2760
2761Indicates how the data type can be used in a WHERE clause, as
2762follows:
2763
2764 0 - Cannot be used in a WHERE clause
2765 1 - Only with a LIKE predicate
2766 2 - All comparison operators except LIKE
2767 3 - Can be used in a WHERE clause with any comparison operator
2768
2769=item UNSIGNED_ATTRIBUTE (boolean)
2770
2771Indicates whether the data type is unsigned. NULL (C<undef>) is returned
2772for data types for which this is not applicable.
2773
2774=item FIXED_PREC_SCALE (boolean)
2775
2776Indicates whether the data type always has the same precision and scale
2777(such as a money type). NULL (C<undef>) is returned for data types
2778for which
2779this is not applicable.
2780
2781=item AUTO_UNIQUE_VALUE (boolean)
2782
2783Indicates whether a column of this data type is automatically set to a
2784unique value whenever a new row is inserted. NULL (C<undef>) is returned
2785for data types for which this is not applicable.
2786
2787=item LOCAL_TYPE_NAME (string)
2788
2789Localized version of the C<TYPE_NAME> for use in dialog with users.
2790NULL (C<undef>) is returned if a localized name is not available (in which
2791case C<TYPE_NAME> should be used).
2792
2793=item MINIMUM_SCALE (integer)
2794
2795The minimum scale of the data type. If a data type has a fixed scale,
2796then C<MAXIMUM_SCALE> holds the same value. NULL (C<undef>) is returned for
2797data types for which this is not applicable.
2798
2799=item MAXIMUM_SCALE (integer)
2800
2801The maximum scale of the data type. If a data type has a fixed scale,
2802then C<MINIMUM_SCALE> holds the same value. NULL (C<undef>) is returned for
2803data types for which this is not applicable.
2804
2805=item SQL_DATA_TYPE (integer)
2806
2807This column is the same as the C<DATA_TYPE> column, except for interval
2808and datetime data types. For interval and datetime data types, the
2809C<SQL_DATA_TYPE> field will return C<SQL_INTERVAL> or C<SQL_DATETIME>, and the
2810C<SQL_DATETIME_SUB> field below will return the subcode for the specific
2811interval or datetime data type. If this field is NULL, then the driver
2812does not support or report on interval or date subtypes.
2813
2814=item SQL_DATETIME_SUB (integer)
2815
2816For interval or datetime data types, where the C<SQL_DATA_TYPE> field
2817above is C<SQL_INTERVAL> or C<SQL_DATETIME>, this field will hold the subcode
2818for the specific interval or datetime data type. Otherwise it will be
2819NULL (C<undef>).
2820
2821=item NUM_PREC_RADIX (integer)
2822
2823The radix value of the data type. For approximate numeric types,
2824C<NUM_PREC_RADIX>
2825contains the value 2 and C<COLUMN_SIZE> holds the number of bits. For
2826exact numeric types, C<NUM_PREC_RADIX> contains the value 10 and C<COLUMN_SIZE> holds
2827the number of decimal digits. NULL (C<undef>) is returned either for data types
2828for which this is not applicable or if the driver cannot report this information.
2829
2830=item INTERVAL_PRECISION (integer)
2831
2832The interval leading precision for interval types. NULL is returned
2833either for data types for which this is not applicable or if the driver
2834cannot report this information.
2835
2836=back
2837
2838For example, to find the type name for the fields in a select statement
2839you can do:
2840
2841 @names = map { scalar $dbh->type_info($_)->{TYPE_NAME} } @{ $sth->{TYPE} }
2842
2843Since DBI and ODBC drivers vary in how they map their types into the
2844ISO standard types you may need to search for more than one type.
2845Here's an example looking for a usable type to store a date:
2846
2847 $my_date_type = $dbh->type_info( [ SQL_DATE, SQL_TIMESTAMP ] );
2848
2849Similarly, to more reliably find a type to store small integers, you could
2850use a list starting with C<SQL_SMALLINT>, C<SQL_INTEGER>, C<SQL_DECIMAL>, etc.
2851
2852For more detailed information about these fields and their meanings, you
2853can refer to:
2854
2855 http://msdn.microsoft.com/library/psdk/dasdk/odch6yy7.htm
2856
2857If that URL ceases to work then use the MSDN search facility at
2858
2859 http://search.microsoft.com/us/dev/
2860
2861and search the MSDN Library for C<SQLGetTypeInfo returns> using the exact phrase option.
2862The link you want will probably just be called C<SQLGetTypeInfo> (there
2863may be more than one).
2864
2865The individual data types are currently described here:
2866
2867 http://msdn.microsoft.com/library/psdk/dasdk/odap8fcj.htm
2868
2869If that URL ceases to work, or to get more general information, use the
2870MSDN search facility as described above and search for C<SQL Data Types>.
2871
2872=item C<quote>
2873
2874 $sql = $dbh->quote($value);
2875 $sql = $dbh->quote($value, $data_type);
2876
2877Quote a string literal for use as a literal value in an SQL statement,
2878by escaping any special characters (such as quotation marks)
2879contained within the string and adding the required type of outer
2880quotation marks.
2881
2882 $sql = sprintf "SELECT foo FROM bar WHERE baz = %s",
2883 $dbh->quote("Don't");
2884
2885For most database types, quote would return C<'Don''t'> (including the
2886outer quotation marks).
2887
2888An undefined C<$value> value will be returned as the string C<NULL> (without
2889quotation marks) to match how NULLs are represented in SQL.
2890
2891If C<$data_type> is supplied, it is used to try to determine the required
2892quoting behavior by using the information returned by L</type_info>.
2893As a special case, the standard numeric types are optimized to return
2894C<$value> without calling C<type_info>.
2895
2896Quote will probably I<not> be able to deal with all possible input
2897(such as binary data or data containing newlines), and is not related in
2898any way with escaping or quoting shell meta-characters. There is no
2899need to quote values being used with L</"Placeholders and Bind Values">.
2900
2901=back
2902
2903
2904=head2 Database Handle Attributes
2905
2906This section describes attributes specific to database handles.
2907
2908Changes to these database handle attributes do not affect any other
2909existing or future database handles.
2910
2911Attempting to set or get the value of an unknown attribute is fatal,
2912except for private driver-specific attributes (which all have names
2913starting with a lowercase letter).
2914
2915Example:
2916
2917 $h->{AutoCommit} = ...; # set/write
2918 ... = $h->{AutoCommit}; # get/read
2919
2920=over 4
2921
2922=item C<AutoCommit> (boolean)
2923
2924If true, then database changes cannot be rolled-back (undone). If false,
2925then database changes automatically occur within a "transaction", which
2926must either be committed or rolled back using the C<commit> or C<rollback>
2927methods.
2928
2929Drivers should always default to C<AutoCommit> mode (an unfortunate
2930choice largely forced on the DBI by ODBC and JDBC conventions.)
2931
2932Attempting to set C<AutoCommit> to an unsupported value is a fatal error.
2933This is an important feature of the DBI. Applications that need
2934full transaction behavior can set C<$dbh->E<gt>C<{AutoCommit} = 0> (or
2935set C<AutoCommit> to 0 via L</connect>)
2936without having to check that the value was assigned successfully.
2937
2938For the purposes of this description, we can divide databases into three
2939categories:
2940
2941 Databases which don't support transactions at all.
2942 Databases in which a transaction is always active.
2943 Databases in which a transaction must be explicitly started (C<'BEGIN WORK'>).
2944
2945B<* Databases which don't support transactions at all>
2946
2947For these databases, attempting to turn C<AutoCommit> off is a fatal error.
2948C<commit> and C<rollback> both issue warnings about being ineffective while
2949C<AutoCommit> is in effect.
2950
2951B<* Databases in which a transaction is always active>
2952
2953These are typically mainstream commercial relational databases with
2954"ANSI standard" transaction behavior.
2955If C<AutoCommit> is off, then changes to the database won't have any
2956lasting effect unless L</commit> is called (but see also
2957L</disconnect>). If L</rollback> is called then any changes since the
2958last commit are undone.
2959
2960If C<AutoCommit> is on, then the effect is the same as if the DBI
2961called C<commit> automatically after every successful database
2962operation. In other words, calling C<commit> or C<rollback> explicitly while
2963C<AutoCommit> is on would be ineffective because the changes would
2964have already been commited.
2965
2966Changing C<AutoCommit> from off to on should issue a L</commit> in most drivers.
2967
2968Changing C<AutoCommit> from on to off should have no immediate effect.
2969
2970For databases which don't support a specific auto-commit mode, the
2971driver has to commit each statement automatically using an explicit
2972C<COMMIT> after it completes successfully (and roll it back using an
2973explicit C<ROLLBACK> if it fails). The error information reported to the
2974application will correspond to the statement which was executed, unless
2975it succeeded and the commit or rollback failed.
2976
2977B<* Databases in which a transaction must be explicitly started>
2978
2979For these databases, the intention is to have them act like databases in
2980which a transaction is always active (as described above).
2981
2982To do this, the DBI driver will automatically begin a transaction when
2983C<AutoCommit> is turned off (from the default "on" state) and will
2984automatically begin another transaction after a L</commit> or L</rollback>.
2985In this way, the application does not have to treat these databases as a
2986special case.
2987
2988See L</commit>, L</disconnect> and L</Transactions> for other important
2989notes about transactions.
2990
2991
2992=item C<Driver> (handle)
2993
2994Holds the handle of the parent driver. The only recommended use for this
2995is to find the name of the driver using:
2996
2997 $dbh->{Driver}->{Name}
2998
2999
3000=item C<Name> (string)
3001
3002Holds the "name" of the database. Usually (and recommended to be) the
3003same as the "C<dbi:DriverName:...>" string used to connect to the database,
3004but with the leading "C<dbi:DriverName:>" removed.
3005
3006
3007=item C<Statement> (string, read-only)
3008
3009Returns the statement string passed to the most recent L</prepare> method
3010called in this database handle, even if that method failed. This is especially
3011useful where C<RaiseError> is enabled and the exception handler checks $@
3012and sees that a 'prepare' method call failed.
3013
3014
3015=item C<RowCacheSize> (integer)
3016
3017A hint to the driver indicating the size of the local row cache that the
3018application would like the driver to use for future C<SELECT> statements.
3019If a row cache is not implemented, then setting C<RowCacheSize> is ignored
3020and getting the value returns C<undef>.
3021
3022Some C<RowCacheSize> values have special meaning, as follows:
3023
3024 0 - Automatically determine a reasonable cache size for each C<SELECT>
3025 1 - Disable the local row cache
3026 >1 - Cache this many rows
3027 <0 - Cache as many rows that will fit into this much memory for each C<SELECT>.
3028
3029Note that large cache sizes may require a very large amount of memory
3030(I<cached rows * maximum size of row>). Also, a large cache will cause
3031a longer delay not only for the first fetch, but also whenever the
3032cache needs refilling.
3033
3034See also the L</RowsInCache> statement handle attribute.
3035
3036=back
3037
3038
3039=head1 DBI STATEMENT HANDLE OBJECTS
3040
3041This section lists the methods and attributes associated with DBI
3042statement handles.
3043
3044=head2 Statement Handle Methods
3045
3046The DBI defines the following methods for use on DBI statement handles:
3047
3048=over 4
3049
3050=item C<bind_param>
3051
3052 $rc = $sth->bind_param($p_num, $bind_value) or die $sth->errstr;
3053 $rv = $sth->bind_param($p_num, $bind_value, \%attr) or ...
3054 $rv = $sth->bind_param($p_num, $bind_value, $bind_type) or ...
3055
3056The C<bind_param> method can be used to bind a value
3057with a placeholder embedded in the prepared statement. Placeholders
3058are indicated with question mark character (C<?>). For example:
3059
3060 $dbh->{RaiseError} = 1; # save having to check each method call
3061 $sth = $dbh->prepare("SELECT name, age FROM people WHERE name LIKE ?");
3062 $sth->bind_param(1, "John%"); # placeholders are numbered from 1
3063 $sth->execute;
3064 DBI::dump_results($sth);
3065
3066Note that the C<?> is not enclosed in quotation marks, even when the
3067placeholder represents a string. Some drivers also allow placeholders
3068like C<:>I<name> and C<:>I<n> (e.g., C<:1>, C<:2>, and so on)
3069in addition to C<?>, but their use
3070is not portable. Undefined bind values or C<undef> can be used to
3071indicate null values.
3072
3073Some drivers do not support placeholders.
3074
3075With most drivers, placeholders can't be used for any element of a
3076statement that would prevent the database server from validating the
3077statement and creating a query execution plan for it. For example:
3078
3079 "SELECT name, age FROM ?" # wrong (will probably fail)
3080 "SELECT name, ? FROM people" # wrong (but may not 'fail')
3081
3082Also, placeholders can only represent single scalar values.
3083For example, the following
3084statement won't work as expected for more than one value:
3085
3086 "SELECT name, age FROM people WHERE name IN (?)" # wrong
3087
3088B<Data Types for Placeholders>
3089
3090The C<\%attr> parameter can be used to hint at the data type the
3091placeholder should have. Typically, the driver is only interested in
3092knowing if the placeholder should be bound as a number or a string.
3093
3094 $sth->bind_param(1, $value, { TYPE => SQL_INTEGER });
3095
3096As a short-cut for this common case, the data type can be passed
3097directly, in place of the C<\%attr> hash reference. This example is
3098equivalent to the one above:
3099
3100 $sth->bind_param(1, $value, SQL_INTEGER);
3101
3102The C<TYPE> value indicates the standard (non-driver-specific) type for
3103this parameter. To specify the driver-specific type, the driver may
3104support a driver-specific attribute, such as C<{ ora_type =>E<gt>C< 97 }>. The
3105data type for a placeholder cannot be changed after the first
3106C<bind_param> call. However, it can be left unspecified, in which case it
3107defaults to the previous value.
3108
3109The SQL_INTEGER and other related constants can be imported using
3110
3111 use DBI qw(:sql_types);
3112
3113See L</"DBI Constants"> for more information.
3114
3115Perl only has string and number scalar data types. All database types
3116that aren't numbers are bound as strings and must be in a format the
3117database will understand.
3118
3119As an alternative to specifying the data type in the C<bind_param> call,
3120you can let the driver pass the value as the default type (C<VARCHAR>).
3121You can then use an SQL function to convert the type within the statement.
3122For example:
3123
3124 INSERT INTO price(code, price) VALUES (?, CONVERT(MONEY,?))
3125
3126The C<CONVERT> function used here is just an example. The actual function
3127and syntax will vary between different databases and is non-portable.
3128
3129See also L</"Placeholders and Bind Values"> for more information.
3130
3131
3132=item C<bind_param_inout>
3133
3134 $rc = $sth->bind_param_inout($p_num, \$bind_value, $max_len) or die $sth->errstr;
3135 $rv = $sth->bind_param_inout($p_num, \$bind_value, $max_len, \%attr) or ...
3136 $rv = $sth->bind_param_inout($p_num, \$bind_value, $max_len, $bind_type) or ...
3137
3138This method acts like L</bind_param>, but also enables values to be
3139updated by the statement. The statement is typically
3140a call to a stored procedure. The C<$bind_value> must be passed as a
3141reference to the actual value to be used.
3142
3143Note that unlike L</bind_param>, the C<$bind_value> variable is not
3144read when C<bind_param_inout> is called. Instead, the value in the
3145variable is read at the time L</execute> is called.
3146
3147The additional C<$max_len> parameter specifies the minimum amount of
3148memory to allocate to C<$bind_value> for the new value. If the value
3149returned from the database is too
3150big to fit, then the execution should fail. If unsure what value to use,
3151pick a generous length, i.e., a length larger than the longest value that would ever be
3152returned. The only cost of using a larger value than needed is wasted memory.
3153
3154It is expected that few drivers will support this method. The only
3155driver currently known to do so is DBD::Oracle (DBD::ODBC may support
3156it in a future release). Therefore it should not be used for database
3157independent applications.
3158
3159Undefined values or C<undef> are used to indicate null values.
3160See also L</"Placeholders and Bind Values"> for more information.
3161
3162
3163=item C<execute>
3164
3165 $rv = $sth->execute or die $sth->errstr;
3166 $rv = $sth->execute(@bind_values) or die $sth->errstr;
3167
3168Perform whatever processing is necessary to execute the prepared
3169statement. An C<undef> is returned if an error occurs. A successful
3170C<execute> always returns true regardless of the number of rows affected,
3171even if it's zero (see below). It is always important to check the
3172return status of C<execute> (and most other DBI methods) for errors.
3173
3174For a I<non>-C<SELECT> statement, C<execute> returns the number of rows
3175affected, if known. If no rows were affected, then C<execute> returns
3176"C<0E0>", which Perl will treat as 0 but will regard as true. Note that it
3177is I<not> an error for no rows to be affected by a statement. If the
3178number of rows affected is not known, then C<execute> returns -1.
3179
3180For C<SELECT> statements, execute simply "starts" the query within the
3181database engine. Use one of the fetch methods to retreive the data after
3182calling C<execute>. The C<execute> method does I<not> return the number of
3183rows that will be returned by the query (because most databases can't
3184tell in advance), it simply returns a true value.
3185
3186If any arguments are given, then C<execute> will effectively call
3187L</bind_param> for each value before executing the statement.
3188Values bound in this way are usually treated as C<SQL_VARCHAR> types
3189unless the driver can determine the correct type (which is rare), or
3190unless
3191C<bind_param> (or C<bind_param_inout>) has already been used to specify the
3192type.
3193
3194
3195=item C<fetchrow_arrayref>
3196
3197 $ary_ref = $sth->fetchrow_arrayref;
3198 $ary_ref = $sth->fetch; # alias
3199
3200Fetches the next row of data and returns a reference to an array
3201holding the field values. Null fields are returned as C<undef>
3202values in the array.
3203This is the fastest way to fetch data, particularly if used with
3204C<$sth->E<gt>C<bind_columns>.
3205
3206If there are no more rows or if an error occurs, then C<fetchrow_arrayref>
3207returns an C<undef>. You should check C<$sth->E<gt>C<err> afterwards (or use the
3208C<RaiseError> attribute) to discover if the C<undef> returned was due to an
3209error.
3210
3211Note that the same array reference is returned for each fetch, so don't
3212store the reference and then use it after a later fetch. Also, the
3213elements of the array are also reused for each row, so take care if you
3214want to take a reference to an element. See also L</bind_columns>.
3215
3216=item C<fetchrow_array>
3217
3218 @ary = $sth->fetchrow_array;
3219
3220An alternative to C<fetchrow_arrayref>. Fetches the next row of data
3221and returns it as a list containing the field values. Null fields
3222are returned as C<undef> values in the list.
3223
3224If there are no more rows or if an error occurs, then C<fetchrow_array>
3225returns an empty list. You should check C<$sth->E<gt>C<err> afterwards (or use
3226the C<RaiseError> attribute) to discover if the empty list returned was
3227due to an error.
3228
3229In a scalar context, C<fetchrow_array> returns the value of the first
3230field. An C<undef> is returned if there are no more rows or if an error
3231occurred. Since that C<undef> can't be distinguished from an C<undef> returned
3232because the first field value was NULL, you should exercise some
3233caution if you use C<fetchrow_array> in a scalar context.
3234
3235=item C<fetchrow_hashref>
3236
3237 $hash_ref = $sth->fetchrow_hashref;
3238 $hash_ref = $sth->fetchrow_hashref($name);
3239
3240An alternative to C<fetchrow_arrayref>. Fetches the next row of data
3241and returns it as a reference to a hash containing field name and field
3242value pairs. Null fields are returned as C<undef> values in the hash.
3243
3244If there are no more rows or if an error occurs, then C<fetchrow_hashref>
3245returns an C<undef>. You should check C<$sth->E<gt>C<err> afterwards (or use the
3246C<RaiseError> attribute) to discover if the C<undef> returned was due to an
3247error.
3248
3249The optional C<$name> parameter specifies the name of the statement handle
3250attribute. For historical reasons it defaults to "C<NAME>", however using either
3251"C<NAME_lc>" or "C<NAME_uc>" is recomended for portability.
3252
3253The keys of the hash are the same names returned by C<$sth->E<gt>C<{$name}>. If
3254more than one field has the same name, there will only be one entry in
3255the returned hash for those fields.
3256
3257Because of the extra work C<fetchrow_hashref> and Perl have to perform, it
3258is not as efficient as C<fetchrow_arrayref> or C<fetchrow_array>.
3259
3260Currently, a new hash reference is returned for each row. I<This will
3261change> in the future to return the same hash ref each time, so don't
3262rely on the current behaviour.
3263
3264
3265=item C<fetchall_arrayref>
3266
3267 $tbl_ary_ref = $sth->fetchall_arrayref;
3268 $tbl_ary_ref = $sth->fetchall_arrayref( $slice_array_ref );
3269 $tbl_ary_ref = $sth->fetchall_arrayref( $slice_hash_ref );
3270
3271The C<fetchall_arrayref> method can be used to fetch all the data to be
3272returned from a prepared and executed statement handle. It returns a
3273reference to an array that contains one reference per row.
3274
3275If there are no rows to return, C<fetchall_arrayref> returns a reference
3276to an empty array. If an error occurs, C<fetchall_arrayref> returns the
3277data fetched thus far, which may be none. You should check C<$sth->E<gt>C<err>
3278afterwards (or use the C<RaiseError> attribute) to discover if the data is
3279complete or was truncated due to an error.
3280
3281When passed an array reference, C<fetchall_arrayref> uses L</fetchrow_arrayref>
3282to fetch each row as an array ref. If the parameter array is not empty
3283then it is used as a slice to select individual columns by index number.
3284
3285With no parameters, C<fetchall_arrayref> acts as if passed an empty array ref.
3286
3287When passed a hash reference, C<fetchall_arrayref> uses L</fetchrow_hashref>
3288to fetch each row as a hash reference. If the parameter hash is empty then
3289fetchrow_hashref is simply called in a tight loop and the keys in the hashes
3290have whatever name lettercase is returned by default from fetchrow_hashref.
3291
3292If the parameter hash is not empty, then it is used as a slice to
3293select individual columns by name. The names should be lower case
3294regardless of the letter case in C<$sth->E<gt>C<{NAME}>. The values of
3295the hash should be set to 1.
3296
3297For example, to fetch just the first column of every row:
3298
3299 $tbl_ary_ref = $sth->fetchall_arrayref([0]);
3300
3301To fetch the second to last and last column of every row:
3302
3303 $tbl_ary_ref = $sth->fetchall_arrayref([-2,-1]);
3304
3305To fetch all fields of every row as a hash ref:
3306
3307 $tbl_ary_ref = $sth->fetchall_arrayref({});
3308
3309To fetch only the fields called "foo" and "bar" of every row as a hash ref:
3310
3311 $tbl_ary_ref = $sth->fetchall_arrayref({ foo=>1, bar=>1 });
3312
3313The first two examples return a reference to an array of array refs. The last
3314returns a reference to an array of hash refs.
3315
3316
3317=item C<fetchall_hashref>
3318
3319 $tbl_ary_ref = $sth->fetchall_hashref;
3320
3321The C<fetchall_hashref> method can be used to fetch all the data to be
3322returned from a prepared and executed statement handle. It returns a
3323reference to an array that contains one hash of field name and value
3324pairs per row.
3325
3326If there are no rows to return, C<fetchall_hashref> returns a reference
3327to an empty array. If an error occurs, C<fetchall_hashref> returns the
3328data fetched thus far, which may be none. You should check C<$sth->E<gt>C<err>
3329afterwards (or use the C<RaiseError> attribute) to discover if the data is
3330complete or was truncated due to an error.
3331
3332
3333=item C<finish>
3334
3335 $rc = $sth->finish;
3336
3337Indicates that no more data will be fetched from this statement handle
3338before it is either executed again or destroyed. The C<finish> method
3339is rarely needed, but can sometimes be helpful in very specific
3340situations to allow the server to free up resources (such as sort
3341buffers).
3342
3343When all the data has been fetched from a C<SELECT> statement, the driver
3344should automatically call C<finish> for you. So you should not normally
3345need to call it explicitly.
3346
3347Consider a query like:
3348
3349 SELECT foo FROM table WHERE bar=? ORDER BY foo
3350
3351where you want to select just the first (smallest) "foo" value from a
3352very large table. When executed, the database server will have to use
3353temporary buffer space to store the sorted rows. If, after executing
3354the handle and selecting one row, the handle won't be re-executed for
3355some time and won't be destroyed, the C<finish> method can be used to tell
3356the server that the buffer space can be freed.
3357
3358Calling C<finish> resets the L</Active> attribute for the statement. It
3359may also make some statement handle attributes (such as C<NAME> and C<TYPE>)
3360unavailable if they have not already been accessed (and thus cached).
3361
3362The C<finish> method does not affect the transaction status of the
3363database connection. It has nothing to do with transactions. It's mostly an
3364internal "housekeeping" method that is rarely needed. There's no need
3365to call C<finish> if you're about to destroy or re-execute the statement
3366handle. See also L</disconnect> and the L</Active> attribute.
3367
3368The C<finish> method should have been called C<cancel_select>.
3369
3370
3371=item C<rows>
3372
3373 $rv = $sth->rows;
3374
3375Returns the number of rows affected by the last row affecting command,
3376or -1 if the number of rows is not known or not available.
3377
3378Generally, you can only rely on a row count after a I<non>-C<SELECT>
3379C<execute> (for some specific operations like C<UPDATE> and C<DELETE>), or
3380after fetching all the rows of a C<SELECT> statement.
3381
3382For C<SELECT> statements, it is generally not possible to know how many
3383rows will be returned except by fetching them all. Some drivers will
3384return the number of rows the application has fetched so far, but
3385others may return -1 until all rows have been fetched. So use of the
3386C<rows> method or C<$DBI::rows> with C<SELECT> statements is not
3387recommended.
3388
3389One alternative method to get a row count for a C<SELECT> is to execute a
3390"SELECT COUNT(*) FROM ..." SQL statement with the same "..." as your
3391query and then fetch the row count from that.
3392
3393
3394=item C<bind_col>
3395
3396 $rc = $sth->bind_col($column_number, \$var_to_bind);
3397
3398Binds an output column (field) of a C<SELECT> statement to a Perl variable.
3399See C<bind_columns> below for an example. Note that column numbers count
3400up from 1.
3401
3402Whenever a row is fetched from the database, the corresponding Perl
3403variable is automatically updated. There is no need to fetch and assign
3404the values manually. The binding is performed at a very low level
3405using Perl aliasing so there is no extra copying taking place. This
3406makes using bound variables very efficient.
3407
3408For maximum portability between drivers, C<bind_col> should be called after
3409C<execute>. This restriction may be removed in a later version of the DBI.
3410
3411You do not need to bind output columns in order to fetch data, but it
3412can be useful for some applications which need either maximum performance
3413or greater clarity of code. The L</bind_param> method
3414performs a similar but opposite function for input variables.
3415
3416=item C<bind_columns>
3417
3418 $rc = $sth->bind_columns(@list_of_refs_to_vars_to_bind);
3419
3420Calls L</bind_col> for each column of the C<SELECT> statement.
3421The C<bind_columns> method will die if the number of references does not
3422match the number of fields.
3423
3424For maximum portability between drivers, C<bind_columns> should be called
3425after C<execute>.
3426
3427For example:
3428
3429 $dbh->{RaiseError} = 1; # do this, or check every call for errors
3430 $sth = $dbh->prepare(q{ SELECT region, sales FROM sales_by_region });
3431 $sth->execute;
3432 my ($region, $sales);
3433
3434 # Bind Perl variables to columns:
3435 $rv = $sth->bind_columns(\$region, \$sales);
3436
3437 # you can also use Perl's \(...) syntax (see perlref docs):
3438 # $sth->bind_columns(\($region, $sales));
3439
3440 # Column binding is the most efficient way to fetch data
3441 while ($sth->fetch) {
3442 print "$region: $sales\n";
3443 }
3444
3445For compatibility with old scripts, the first parameter will be
3446ignored if it is C<undef> or a hash reference.
3447
3448Here's a more fancy example that binds columns to the values I<inside>
3449a hash (thanks to H.Merijn Brand):
3450
3451 $sth->execute;
3452 my %row;
3453 $sth->bind_columns( \( @row{ @{$sth->{NAME_lc} } } ));
3454 while ($sth->fetch) {
3455 print "$row{region}: $row{sales}\n";
3456 }
3457
3458
3459=item C<dump_results>
3460
3461 $rows = $sth->dump_results($maxlen, $lsep, $fsep, $fh);
3462
3463Fetches all the rows from C<$sth>, calls C<DBI::neat_list> for each row, and
3464prints the results to C<$fh> (defaults to C<STDOUT>) separated by C<$lsep>
3465(default C<"\n">). C<$fsep> defaults to C<", "> and C<$maxlen> defaults to 35.
3466
3467This method is designed as a handy utility for prototyping and
3468testing queries. Since it uses L</neat_list> to
3469format and edit the string for reading by humans, it is not recomended
3470for data transfer applications.
3471
3472=back
3473
3474
3475=head2 Statement Handle Attributes
3476
3477This section describes attributes specific to statement handles. Most
3478of these attributes are read-only.
3479
3480Changes to these statement handle attributes do not affect any other
3481existing or future statement handles.
3482
3483Attempting to set or get the value of an unknown attribute is fatal,
3484except for private driver specific attributes (which all have names
3485starting with a lowercase letter).
3486
3487Example:
3488
3489 ... = $h->{NUM_OF_FIELDS}; # get/read
3490
3491Note that some drivers cannot provide valid values for some or all of
3492these attributes until after C<$sth->E<gt>C<execute> has been called.
3493
3494See also L</finish> to learn more about the effect it
3495may have on some attributes.
3496
3497=over 4
3498
3499=item C<NUM_OF_FIELDS> (integer, read-only)
3500
3501Number of fields (columns) the prepared statement will return. Non-C<SELECT>
3502statements will have C<NUM_OF_FIELDS == 0>.
3503
3504
3505=item C<NUM_OF_PARAMS> (integer, read-only)
3506
3507The number of parameters (placeholders) in the prepared statement.
3508See SUBSTITUTION VARIABLES below for more details.
3509
3510
3511=item C<NAME> (array-ref, read-only)
3512
3513Returns a reference to an array of field names for each column. The
3514names may contain spaces but should not be truncated or have any
3515trailing space. Note that the names have the letter case (upper, lower
3516or mixed) as returned by the driver being used. Portable applications
3517should use L</NAME_lc> or L</NAME_uc>.
3518
3519 print "First column name: $sth->{NAME}->[0]\n";
3520
3521=item C<NAME_lc> (array-ref, read-only)
3522
3523Like L</NAME> but always returns lowercase names.
3524
3525=item C<NAME_uc> (array-ref, read-only)
3526
3527Like L</NAME> but always returns uppercase names.
3528
3529=item C<TYPE> (array-ref, read-only)
3530
3531Returns a reference to an array of integer values for each
3532column. The value indicates the data type of the corresponding column.
3533
3534The values correspond to the international standards (ANSI X3.135
3535and ISO/IEC 9075) which, in general terms, means ODBC. Driver-specific
3536types that don't exactly match standard types should generally return
3537the same values as an ODBC driver supplied by the makers of the
3538database. That might include private type numbers in ranges the vendor
3539has officially registered with the ISO working group:
3540
3541 ftp://jerry.ece.umassd.edu/isowg3/dbl/SQL_Registry
3542
3543Where there's no vendor-supplied ODBC driver to be compatible with, the
3544DBI driver can use type numbers in the range that is now officially reserved
3545for use by the DBI: -9999 to -9000.
3546
3547All possible values for C<TYPE> should have at least one entry in the
3548output of the C<type_info_all> method (see L</type_info_all>).
3549
3550=item C<PRECISION> (array-ref, read-only)
3551
3552Returns a reference to an array of integer values for each
3553column. For non-numeric columns, the value generally refers to either
3554the maximum length or the defined length of the column. For numeric
3555columns, the value refers to the maximum number of significant digits
3556used by the data type (without considering a sign character or decimal
3557point). Note that for floating point types (REAL, FLOAT, DOUBLE), the
3558"display size" can be up to 7 characters greater than the precision.
3559(for the sign + decimal point + the letter E + a sign + 2 or 3 digits).
3560
3561=item C<SCALE> (array-ref, read-only)
3562
3563Returns a reference to an array of integer values for each column.
3564NULL (C<undef>) values indicate columns where scale is not applicable.
3565
3566=item C<NULLABLE> (array-ref, read-only)
3567
3568Returns a reference to an array indicating the possibility of each
3569column returning a null. Possible values are C<0>
3570(or an empty string) = no, C<1> = yes, C<2> = unknown.
3571
3572 print "First column may return NULL\n" if $sth->{NULLABLE}->[0];
3573
3574
3575=item C<CursorName> (string, read-only)
3576
3577Returns the name of the cursor associated with the statement handle, if
3578available. If not available or if the database driver does not support the
3579C<"where current of ..."> SQL syntax, then it returns C<undef>.
3580
3581
3582=item C<Statement> (string, read-only)
3583
3584Returns the statement string passed to the L</prepare> method.
3585
3586
3587=item C<RowsInCache> (integer, read-only)
3588
3589If the driver supports a local row cache for C<SELECT> statements, then
3590this attribute holds the number of un-fetched rows in the cache. If the
3591driver doesn't, then it returns C<undef>. Note that some drivers pre-fetch
3592rows on execute, whereas others wait till the first fetch.
3593
3594See also the L</RowCacheSize> database handle attribute.
3595
3596=back
3597
3598
3599=head1 FURTHER INFORMATION
3600
3601=head2 Transactions
3602
3603Transactions are a fundamental part of any robust database system. They
3604protect against errors and database corruption by ensuring that sets of
3605related changes to the database take place in atomic (indivisible,
3606all-or-nothing) units.
3607
3608This section applies to databases that support transactions and where
3609C<AutoCommit> is off. See L</AutoCommit> for details of using C<AutoCommit>
3610with various types of databases.
3611
3612The recommended way to implement robust transactions in Perl
3613applications is to use C<RaiseError> and S<C<eval { ... }>>
3614(which is very fast, unlike S<C<eval "...">>). For example:
3615
3616 $dbh->{AutoCommit} = 0; # enable transactions, if possible
3617 $dbh->{RaiseError} = 1;
3618 eval {
3619 foo(...) # do lots of work here
3620 bar(...) # including inserts
3621 baz(...) # and updates
3622 $dbh->commit; # commit the changes if we get this far
3623 };
3624 if ($@) {
3625 warn "Transaction aborted because $@";
3626 $dbh->rollback; # undo the incomplete changes
3627 # add other application on-error-clean-up code here
3628 }
3629
3630If the C<RaiseError> attribute is not set, then DBI calls would need to be
3631manually checked for errors, typically like this:
3632
3633 $h->method(@args) or die $h->errstr;
3634
3635With C<RaiseError> set, the DBI will automatically C<die> if any DBI method
3636call on that handle (or a child handle) fails, so you don't have to
3637test the return value of each method call. See L</RaiseError> for more
3638details.
3639
3640A major advantage of the C<eval> approach is that the transaction will be
3641properly rolled back if I<any> code (not just DBI calls) in the inner
3642application dies for any reason. The major advantage of using the
3643C<$h->E<gt>C<{RaiseError}> attribute is that all DBI calls will be checked
3644automatically. Both techniques are strongly recommended.
3645
3646After calling C<commit> or C<rollback> many drivers will not let you
3647fetch from a previously active C<SELECT> statement handle that's a child
3648of the same database handle. A typical way round this is to connect the
3649the database twice and use one connection for C<SELECT> statements.
3650
3651
3652=head2 Handling BLOB / LONG / Memo Fields
3653
3654Many databases support "blob" (binary large objects), "long", or similar
3655datatypes for holding very long strings or large amounts of binary
3656data in a single field. Some databases support variable length long
3657values over 2,000,000,000 bytes in length.
3658
3659Since values of that size can't usually be held in memory, and because
3660databases can't usually know in advance the length of the longest long
3661that will be returned from a C<SELECT> statement (unlike other data
3662types), some special handling is required.
3663
3664In this situation, the value of the C<$h->E<gt>C<{LongReadLen}> attribute is used
3665to determine how much buffer space to allocate when fetching such
3666fields. The C<$h->E<gt>C<{LongTruncOk}> attribute is used to determine how to
3667behave if a fetched value can't fit into the buffer.
3668
3669When trying to insert long or binary values, placeholders should be used
3670since there are often limits on the maximum size of an C<INSERT>
3671statement and the L</quote> method generally can't cope with binary
3672data. See L</Placeholders and Bind Values>.
3673
3674
3675=head2 Simple Examples
3676
3677Here's a complete example program to select and fetch some data:
3678
3679 my $dbh = DBI->connect("dbi:DriverName:db_name", $user, $password)
3680 or die "Can't connect to $data_source: $DBI::errstr";
3681
3682 my $sth = $dbh->prepare( q{
3683 SELECT name, phone
3684 FROM mytelbook
3685 }) or die "Can't prepare statement: $DBI::errstr";
3686
3687 my $rc = $sth->execute
3688 or die "Can't execute statement: $DBI::errstr";
3689
3690 print "Query will return $sth->{NUM_OF_FIELDS} fields.\n\n";
3691 print "Field names: @{ $sth->{NAME} }\n";
3692
3693 while (($name, $phone) = $sth->fetchrow_array) {
3694 print "$name: $phone\n";
3695 }
3696 # check for problems which may have terminated the fetch early
3697 die $sth->errstr if $sth->err;
3698
3699 $dbh->disconnect;
3700
3701Here's a complete example program to insert some data from a file.
3702(This example uses C<RaiseError> to avoid needing to check each call).
3703
3704 my $dbh = DBI->connect("dbi:DriverName:db_name", $user, $password, {
3705 RaiseError => 1, AutoCommit => 0
3706 });
3707
3708 my $sth = $dbh->prepare( q{
3709 INSERT INTO table (name, phone) VALUES (?, ?)
3710 });
3711
3712 open FH, "<phone.csv" or die "Unable to open phone.csv: $!";
3713 while (<FH>) {
3714 chomp;
3715 my ($name, $phone) = split /,/;
3716 $sth->execute($name, $phone);
3717 }
3718 close FH;
3719
3720 $dbh->commit;
3721 $dbh->disconnect;
3722
3723Here's how to convert fetched NULLs (undefined values) into empty strings:
3724
3725 while($row = $sth->fetchrow_arrayref) {
3726 # this is a fast and simple way to deal with nulls:
3727 foreach (@$row) { $_ = '' unless defined }
3728 print "@$row\n";
3729 }
3730
3731The C<q{...}> style quoting used in these examples avoids clashing with
3732quotes that may be used in the SQL statement. Use the double-quote like
3733C<qq{...}> operator if you want to interpolate variables into the string.
3734See L<perlop/"Quote and Quote-like Operators"> for more details.
3735
3736
3737=head2 Threads and Thread Safety
3738
3739Perl versions 5.004_50 and later include optional experimental support
3740for multiple threads on many platforms. If the DBI is built using a
3741Perl that has threads enabled then it will use a per-driver mutex to
3742ensure that only one thread is with a driver at any one time.
3743Please note that support for threads in Perl is still experimental and
3744is known to have some significant problems. It's use is not recommended.
3745
3746
3747=head2 Signal Handling and Canceling Operations
3748
3749The first thing to say is that signal handling in Perl is currently
3750I<not> safe. There is always a small risk of Perl crashing and/or
3751core dumping when, or after, handling a signal. (The risk was reduced
3752with 5.004_04 but is still present.)
3753
3754The two most common uses of signals in relation to the DBI are for
3755canceling operations when the user types Ctrl-C (interrupt), and for
3756implementing a timeout using C<alarm()> and C<$SIG{ALRM}>.
3757
3758To assist in implementing these operations, the DBI provides a C<cancel>
3759method for statement handles. The C<cancel> method should abort the current
3760operation and is designed to be called from a signal handler.
3761
3762However, it must be stressed that: a) few drivers implement this at
3763the moment (the DBI provides a default method that just returns C<undef>);
3764and b) even if implemented, there is still a possibility that the statement
3765handle, and possibly the parent database handle, will not be usable
3766afterwards.
3767
3768If C<cancel> returns true, then it has successfully
3769invoked the database engine's own cancel function. If it returns false,
3770then C<cancel> failed. If it returns C<undef>, then the database
3771engine does not have cancel implemented.
3772
3773
3774=head1 DEBUGGING
3775
3776In addition to the L</trace> method, you can enable the same trace
3777information by setting the C<DBI_TRACE> environment variable before
3778starting Perl.
3779
3780On Unix-like systems using a Bourne-like shell, you can do this easily
3781on the command line:
3782
3783 DBI_TRACE=2 perl your_test_script.pl
3784
3785If C<DBI_TRACE> is set to a non-numeric value, then it is assumed to
3786be a file name and the trace level will be set to 2 with all trace
3787output appended to that file. If the name begins with a number
3788followed by an equal sign (C<=>), then the number and the equal sign are
3789stripped off from the name, and the number is used to set the trace
3790level. For example:
3791
3792 DBI_TRACE=1=dbitrace.log perl your_test_script.pl
3793
3794See also the L</trace> method.
3795
3796It can sometimes be handy to compare trace files from two different
3797runs of the same script. However using a tool like C<diff> doesn't work
3798well because the trace file is full of object addresses that may
3799differ each run. Here's a handy little command to strip those out:
3800
3801 perl -pe 's/\b0x[\da-f]{6,}/0xNNNN/gi; s/\b[\da-f]{6,}/<long number>/gi'
3802
3803
3804=head1 WARNING AND ERROR MESSAGES
3805
3806=head2 Fatal Errors
3807
3808=over 4
3809
3810=item Can't call method "prepare" without a package or object reference
3811
3812The C<$dbh> handle you're using to call C<prepare> is probably undefined because
3813the preceding C<connect> failed. You should always check the return status of
3814DBI methods, or use the L</RaiseError> attribute.
3815
3816=item Can't call method "execute" without a package or object reference
3817
3818The C<$sth> handle you're using to call C<execute> is probably undefined because
3819the preceeding C<prepare> failed. You should always check the return status of
3820DBI methods, or use the L</RaiseError> attribute.
3821
3822=item DBI/DBD internal version mismatch
3823
3824The DBD driver module was built with a different version of DBI than
3825the one currently being used. You should rebuild the DBD module under
3826the current version of DBI.
3827
3828(Some rare platforms require "static linking". On those platforms, there
3829may be an old DBI or DBD driver version actually embedded in the Perl
3830executable being used.)
3831
3832=item DBD driver has not implemented the AutoCommit attribute
3833
3834The DBD driver implementation is incomplete. Consult the author.
3835
3836=item Can't [sg]et %s->{%s}: unrecognised attribute
3837
3838You attempted to set or get an unknown attribute of a handle. Make
3839sure you have spelled the attribute name correctly; case is significant
3840(e.g., "Autocommit" is not the same as "AutoCommit").
3841
3842=back
3843
3844=head2 Warnings
3845
3846=over 4
3847
3848=item Database handle destroyed without explicit disconnect
3849
3850A C<$dbh> handle went out of scope or the program ended before the handle
3851was disconnected from the database. You should always explicitly call
3852C<disconnect> when you are finished using a database handle. If using
3853transactions then you should also explicitly call C<commit> or C<rollback>
3854before C<disconnect>.
3855
3856=item DBI Handle cleared whilst still holding %d cached kids!
3857
3858Most probably due to a DBI bug. Possibly a DBD driver bug. Please report it.
3859
3860=item DBI Handle cleared whilst still active!
3861
3862Most probably due to a DBI bug. Possibly a DBD driver bug. Please report it.
3863
3864=item DBI Handle has uncleared implementors data
3865
3866Most probably a DBD driver bug. Please report it.
3867
3868=item DBI Handle has %d uncleared child handles
3869
3870Most probably due to a DBI bug. Possibly a DBD driver bug. Please report it.
3871
3872=back
3873
3874=head1 SEE ALSO
3875
3876=head2 Driver and Database Documentation
3877
3878Refer to the documentation for the DBD driver that you are using.
3879
3880Refer to the SQL Language Reference Manual for the database engine that you are using.
3881
3882=head2 Books and Journals
3883
3884 Programming the Perl DBI, by Alligator Descartes and Tim Bunce.
3885
3886 Programming Perl 2nd Ed. by Larry Wall, Tom Christiansen & Randal Schwartz.
3887
3888 Learning Perl by Randal Schwartz.
3889
3890 Dr Dobb's Journal, November 1996.
3891
3892 The Perl Journal, April 1997.
3893
3894=head2 Manual Pages
3895
3896L<perl(1)>, L<perlmod(1)>, L<perlbook(1)>
3897
3898=head2 Mailing List
3899
3900The I<dbi-users> mailing list is the primary means of communication among
3901users of the DBI and its related modules. For details send email to:
3902
3903 dbi-users-help@perl.org
3904
3905There are typically between 700 and 900 messages per month. You have
3906to subscribe in order to be able to post. However you can opt for a
3907'post-only' subscription.
3908
3909Mailing list archives are held at:
3910
3911 http://www.xray.mpe.mpg.de/mailing-lists/dbi/
3912 http://groups.yahoo.com/group/dbi-users
3913 http://www.bitmechanic.com/mail-archives/dbi-users/
3914 http://marc.theaimsgroup.com/?l=perl-dbi&r=1&w=2
3915 http://www.mail-archive.com/dbi-users%40perl.org/
3916 http://www.mail-archive.com/dbi-users%40perl.org/
3917
3918=head2 Assorted Related WWW Links
3919
3920The DBI "Home Page":
3921
3922 http://dbi.perl.org/
3923
3924Other DBI related links:
3925
3926 http://tegan.deltanet.com/~phlip/DBUIdoc.html
3927 http://dc.pm.org/perl_db.html
3928 http://wdvl.com/Authoring/DB/Intro/toc.html
3929 http://www.hotwired.com/webmonkey/backend/tutorials/tutorial1.html
3930 http://bumppo.net/lists/macperl/1999/06/msg00197.html
3931
3932Other database related links:
3933
3934 http://www.jcc.com/sql_stnd.html
3935 http://cuiwww.unige.ch/OSG/info/FreeDB/FreeDB.home.html
3936
3937Commercial and Data Warehouse Links
3938
3939 http://www.dwinfocenter.org
3940 http://www.datawarehouse.com
3941 http://www.datamining.org
3942 http://www.olapcouncil.org
3943 http://www.idwa.org
3944 http://www.knowledgecenters.org/dwcenter.asp
3945
3946Recommended Perl Programming Links
3947
3948 http://language.perl.com/style/
3949
3950=head2 FAQ
3951
3952Please also read the DBI FAQ which is installed as a DBI::FAQ module.
3953You can use I<perldoc> to read it by executing the C<perldoc DBI::FAQ> command.
3954
3955=head1 AUTHORS
3956
3957DBI by Tim Bunce. This pod text by Tim Bunce, J. Douglas Dunlop,
3958Jonathan Leffler and others. Perl by Larry Wall and the
3959C<perl5-porters>.
3960
3961=head1 COPYRIGHT
3962
3963The DBI module is Copyright (c) 1994-2000 Tim Bunce. England.
3964All rights reserved.
3965
3966You may distribute under the terms of either the GNU General Public
3967License or the Artistic License, as specified in the Perl README file.
3968
3969=head1 ACKNOWLEDGEMENTS
3970
3971I would like to acknowledge the valuable contributions of the many
3972people I have worked with on the DBI project, especially in the early
3973years (1992-1994). In no particular order: Kevin Stock, Buzz Moschetti,
3974Kurt Andersen, Ted Lemon, William Hails, Garth Kennedy, Michael Peppler,
3975Neil S. Briscoe, Jeff Urlwin, David J. Hughes, Jeff Stander,
3976Forrest D Whitcher, Larry Wall, Jeff Fried, Roy Johnson, Paul Hudson,
3977Georg Rehfeld, Steve Sizemore, Ron Pool, Jon Meek, Tom Christiansen,
3978Steve Baumgarten, Randal Schwartz, and a whole lot more.
3979
3980Then, of course, there are the poor souls who have struggled through
3981untold and undocumented obstacles to actually implement DBI drivers.
3982Among their ranks are Jochen Wiedmann, Alligator Descartes, Jonathan
3983Leffler, Jeff Urlwin, Michael Peppler, Henrik Tougaard, Edwin Pratomo,
3984Davide Migliavacca, Jan Pazdziora, Peter Haworth, Edmund Mergl, Steve
3985Williams, Thomas Lowery, and Phlip Plumlee. Without them, the DBI would
3986not be the practical reality it is today. I'm also especially grateful
3987to Alligator Descartes for starting work on the "Programming the Perl
3988DBI" book and letting me jump on board.
3989
3990=head1 TRANSLATIONS
3991
3992A German translation of this manual (possibly slightly out of date) is
3993available, thanks to O'Reilly, at:
3994
3995 http://www.oreilly.de/catalog/perldbiger/
3996
3997Some other translations:
3998
3999 http://cronopio.net/perl/ - Spanish
4000 http://member.nifty.ne.jp/hippo2000/dbimemo.htm - Japanese
4001
4002
4003=head1 SUPPORT / WARRANTY
4004
4005The DBI is free software. IT COMES WITHOUT WARRANTY OF ANY KIND.
4006
4007Commercial support for Perl and the DBI, DBD::Oracle and
4008Oraperl modules can be arranged via The Perl Clinic.
4009For more details visit:
4010
4011 http://www.perlclinic.com
4012
4013=head1 TRAINING
4014
4015References to DBI related training resources. No recommendation implied.
4016
4017 http://www.treepax.co.uk/
4018 http://www.keller.com/dbweb/
4019
4020=head1 FREQUENTLY ASKED QUESTIONS
4021
4022See the DBI FAQ for a more comprehensive list of FAQs. Use the
4023C<perldoc DBI::FAQ> command to read it.
4024
4025=head2 How fast is the DBI?
4026
4027To measure the speed of the DBI and DBD::Oracle code, I modified
4028DBD::Oracle so you can set an attribute that will cause the
4029same row to be fetched from the row cache over and over again (without
4030involving Oracle code but exercising *all* the DBI and DBD::Oracle code
4031in the code path for a fetch).
4032
4033The results (on my lightly loaded old Sparc 10) fetching 50000 rows using:
4034
4035 1 while $csr->fetch;
4036
4037were:
4038 one field: 5300 fetches per cpu second (approx)
4039 ten fields: 4000 fetches per cpu second (approx)
4040
4041Obviously results will vary between platforms (newer faster platforms
4042can reach around 50000 fetches per second), but it does give a feel for
4043the maximum performance: fast. By way of comparison, using the code:
4044
4045 1 while @row = $csr->fetchrow_array;
4046
4047(C<fetchrow_array> is roughly the same as C<ora_fetch>) gives:
4048
4049 one field: 3100 fetches per cpu second (approx)
4050 ten fields: 1000 fetches per cpu second (approx)
4051
4052Notice the slowdown and the more dramatic impact of extra fields.
4053(The fields were all one char long. The impact would be even bigger for
4054longer strings.)
4055
4056Changing that slightly to represent actually doing something in Perl
4057with the fetched data:
4058
4059 while(@row = $csr->fetchrow_array) {
4060 $hash{++$i} = [ @row ];
4061 }
4062
4063gives: ten fields: 500 fetches per cpu second (approx)
4064
4065That simple addition has *halved* the performance.
4066
4067I therefore conclude that DBI and DBD::Oracle overheads are small
4068compared with Perl language overheads (and probably database overheads).
4069
4070So, if you think the DBI or your driver is slow, try replacing your
4071fetch loop with just:
4072
4073 1 while $csr->fetch;
4074
4075and time that. If that helps then point the finger at your own code. If
4076that doesn't help much then point the finger at the database, the
4077platform, the network etc. But think carefully before pointing it at
4078the DBI or your driver.
4079
4080(Having said all that, if anyone can show me how to make the DBI or
4081drivers even more efficient, I'm all ears.)
4082
4083
4084=head2 Why doesn't my CGI script work right?
4085
4086Read the information in the references below. Please do I<not> post
4087CGI related questions to the I<dbi-users> mailing list (or to me).
4088
4089 http://www.perl.com/cgi-bin/pace/pub/doc/FAQs/cgi/perl-cgi-faq.html
4090 http://www3.pair.com/webthing/docs/cgi/faqs/cgifaq.shtml
4091 http://www-genome.wi.mit.edu/WWW/faqs/www-security-faq.html
4092 http://www.boutell.com/faq/
4093 http://www.perl.com/perl/faq/
4094
4095General problems and good ideas:
4096
4097 Use the CGI::ErrorWrap module.
4098 Remember that many env vars won't be set for CGI scripts.
4099
4100=head2 How can I maintain a WWW connection to a database?
4101
4102For information on the Apache httpd server and the C<mod_perl> module see
4103
4104 http://perl.apache.org/
4105
4106=head2 What about ODBC?
4107
4108A DBD::ODBC module is available.
4109
4110=head2 Does the DBI have a year 2000 problem?
4111
4112No. The DBI has no knowledge or understanding of dates at all.
4113
4114Individual drivers (DBD::*) may have some date handling code but are
4115unlikely to have year 2000 related problems within their code. However,
4116your application code which I<uses> the DBI and DBD drivers may have
4117year 2000 related problems if it has not been designed and written well.
4118
4119See also the "Does Perl have a year 2000 problem?" section of the Perl FAQ:
4120
4121 http://www.perl.com/CPAN/doc/FAQs/FAQ/PerlFAQ.html
4122
4123=head1 OTHER RELATED WORK AND PERL MODULES
4124
4125=over 4
4126
4127=item Apache::DBI by E.Mergl@bawue.de
4128
4129To be used with the Apache daemon together with an embedded Perl
4130interpreter like C<mod_perl>. Establishes a database connection which
4131remains open for the lifetime of the HTTP daemon. This way the CGI
4132connect and disconnect for every database access becomes superfluous.
4133
4134=item JDBC Server by Stuart 'Zen' Bishop zen@bf.rmit.edu.au
4135
4136The server is written in Perl. The client classes that talk to it are
4137of course in Java. Thus, a Java applet or application will be able to
4138comunicate via the JDBC API with any database that has a DBI driver installed.
4139The URL used is in the form C<jdbc:dbi://host.domain.etc:999/Driver/DBName>.
4140It seems to be very similar to some commercial products, such as jdbcKona.
4141
4142=item Remote Proxy DBD support
4143
4144As of DBI 1.02, a complete implementation of a DBD::Proxy driver and the
4145DBI::ProxyServer are part of the DBI distribution.
4146
4147=item SQL Parser
4148
4149 Hugo van der Sanden <hv@crypt.compulink.co.uk>
4150 Stephen Zander <stephen.zander@mckesson.com>
4151
4152Based on the O'Reilly lex/yacc book examples and C<byacc>.
4153
4154See also the SQL::Statement module, a very simple SQL parser and engine,
4155base of the DBD::CSV driver.
4156
4157=back
4158
4159=cut