File Coverage

blib/lib/DBI.pm
Criterion Covered Total %
statement 743 904 82.1
branch 373 562 66.3
condition 192 354 54.2
subroutine 87 109 79.8
pod 16 24 66.6
total 1411 1953 72.2


line stmt bran cond sub pod time code
1             # $Id$
2             # vim: ts=8:sw=4:et
3             #
4             # Copyright (c) 1994-2012 Tim Bunce Ireland
5             #
6             # See COPYRIGHT section in pod text below for usage and distribution rights.
7             #
8              
9             package DBI;
10              
11             require 5.008_001;
12              
13             BEGIN {
14 192     192   7370207 our $XS_VERSION = our $VERSION = "1.637"; # ==> ALSO update the version in the pod text below!
15 192         8397 $VERSION = eval $VERSION;
16             }
17              
18             =head1 NAME
19              
20             DBI - Database independent interface for Perl
21              
22             =head1 SYNOPSIS
23              
24             use DBI;
25              
26             @driver_names = DBI->available_drivers;
27             %drivers = DBI->installed_drivers;
28             @data_sources = DBI->data_sources($driver_name, \%attr);
29              
30             $dbh = DBI->connect($data_source, $username, $auth, \%attr);
31              
32             $rv = $dbh->do($statement);
33             $rv = $dbh->do($statement, \%attr);
34             $rv = $dbh->do($statement, \%attr, @bind_values);
35              
36             $ary_ref = $dbh->selectall_arrayref($statement);
37             $hash_ref = $dbh->selectall_hashref($statement, $key_field);
38              
39             $ary_ref = $dbh->selectcol_arrayref($statement);
40             $ary_ref = $dbh->selectcol_arrayref($statement, \%attr);
41              
42             @row_ary = $dbh->selectrow_array($statement);
43             $ary_ref = $dbh->selectrow_arrayref($statement);
44             $hash_ref = $dbh->selectrow_hashref($statement);
45              
46             $sth = $dbh->prepare($statement);
47             $sth = $dbh->prepare_cached($statement);
48              
49             $rc = $sth->bind_param($p_num, $bind_value);
50             $rc = $sth->bind_param($p_num, $bind_value, $bind_type);
51             $rc = $sth->bind_param($p_num, $bind_value, \%attr);
52              
53             $rv = $sth->execute;
54             $rv = $sth->execute(@bind_values);
55             $rv = $sth->execute_array(\%attr, ...);
56              
57             $rc = $sth->bind_col($col_num, \$col_variable);
58             $rc = $sth->bind_columns(@list_of_refs_to_vars_to_bind);
59              
60             @row_ary = $sth->fetchrow_array;
61             $ary_ref = $sth->fetchrow_arrayref;
62             $hash_ref = $sth->fetchrow_hashref;
63              
64             $ary_ref = $sth->fetchall_arrayref;
65             $ary_ref = $sth->fetchall_arrayref( $slice, $max_rows );
66              
67             $hash_ref = $sth->fetchall_hashref( $key_field );
68              
69             $rv = $sth->rows;
70              
71             $rc = $dbh->begin_work;
72             $rc = $dbh->commit;
73             $rc = $dbh->rollback;
74              
75             $quoted_string = $dbh->quote($string);
76              
77             $rc = $h->err;
78             $str = $h->errstr;
79             $rv = $h->state;
80              
81             $rc = $dbh->disconnect;
82              
83             I
84              
85              
86             =head2 GETTING HELP
87              
88             =head3 General
89              
90             Before asking any questions, reread this document, consult the
91             archives and read the DBI FAQ. The archives are listed
92             at the end of this document and on the DBI home page L
93              
94             You might also like to read the Advanced DBI Tutorial at
95             L
96              
97             To help you make the best use of the dbi-users mailing list,
98             and any other lists or forums you may use, I recommend that you read
99             "Getting Answers" by Mike Ash: L.
100              
101             =head3 Mailing Lists
102              
103             If you have questions about DBI, or DBD driver modules, you can get
104             help from the I mailing list. This is the best way to get
105             help. You don't have to subscribe to the list in order to post, though I'd
106             recommend it. You can get help on subscribing and using the list by emailing
107             I.
108              
109             Please note that Tim Bunce does not maintain the mailing lists or the
110             web pages (generous volunteers do that). So please don't send mail
111             directly to him; he just doesn't have the time to answer questions
112             personally. The I mailing list has lots of experienced
113             people who should be able to help you if you need it. If you do email
114             Tim he is very likely to just forward it to the mailing list.
115              
116             =head3 IRC
117              
118             DBI IRC Channel: #dbi on irc.perl.org (L)
119              
120             =for html (click for instant chatroom login)
121              
122             =head3 Online
123              
124             StackOverflow has a DBI tag L
125             with over 800 questions.
126              
127             The DBI home page at L and the DBI FAQ
128             at L may be worth a visit.
129             They include links to other resources, but I.
130              
131             =head3 Reporting a Bug
132              
133             If you think you've found a bug then please read
134             "How to Report Bugs Effectively" by Simon Tatham:
135             L.
136              
137             If you think you've found a memory leak then read L.
138              
139             Your problem is most likely related to the specific DBD driver module you're
140             using. If that's the case then click on the 'Bugs' link on the L
141             page for your driver. Only submit a bug report against the DBI itself if you're
142             sure that your issue isn't related to the driver you're using.
143              
144             =head2 NOTES
145              
146             This is the DBI specification that corresponds to DBI version 1.637
147             (see L for details).
148              
149             The DBI is evolving at a steady pace, so it's good to check that
150             you have the latest copy.
151              
152             The significant user-visible changes in each release are documented
153             in the L module so you can read them by executing
154             C.
155              
156             Some DBI changes require changes in the drivers, but the drivers
157             can take some time to catch up. Newer versions of the DBI have
158             added features that may not yet be supported by the drivers you
159             use. Talk to the authors of your drivers if you need a new feature
160             that is not yet supported.
161              
162             Features added after DBI 1.21 (February 2002) are marked in the
163             text with the version number of the DBI release they first appeared in.
164              
165             Extensions to the DBI API often use the C namespace.
166             See L. DBI extension modules
167             can be found at L. And all modules
168             related to the DBI can be found at L.
169              
170             =cut
171              
172             # The POD text continues at the end of the file.
173              
174 192     192   1485 use Scalar::Util ();
  192         374  
  192         2653  
175 192     192   880 use Carp();
  192         344  
  192         2549  
176 192     192   971 use DynaLoader ();
  192         377  
  192         2593  
177 192     192   882 use Exporter ();
  192         359  
  192         54349  
178              
179             BEGIN {
180 192     192   3244 @ISA = qw(Exporter DynaLoader);
181              
182             # Make some utility functions available if asked for
183 192         670 @EXPORT = (); # we export nothing by default
184 192         499 @EXPORT_OK = qw(%DBI %DBI_methods hash); # also populated by export_ok_tags:
185 192         2611 %EXPORT_TAGS = (
186             sql_types => [ qw(
187             SQL_GUID
188             SQL_WLONGVARCHAR
189             SQL_WVARCHAR
190             SQL_WCHAR
191             SQL_BIGINT
192             SQL_BIT
193             SQL_TINYINT
194             SQL_LONGVARBINARY
195             SQL_VARBINARY
196             SQL_BINARY
197             SQL_LONGVARCHAR
198             SQL_UNKNOWN_TYPE
199             SQL_ALL_TYPES
200             SQL_CHAR
201             SQL_NUMERIC
202             SQL_DECIMAL
203             SQL_INTEGER
204             SQL_SMALLINT
205             SQL_FLOAT
206             SQL_REAL
207             SQL_DOUBLE
208             SQL_DATETIME
209             SQL_DATE
210             SQL_INTERVAL
211             SQL_TIME
212             SQL_TIMESTAMP
213             SQL_VARCHAR
214             SQL_BOOLEAN
215             SQL_UDT
216             SQL_UDT_LOCATOR
217             SQL_ROW
218             SQL_REF
219             SQL_BLOB
220             SQL_BLOB_LOCATOR
221             SQL_CLOB
222             SQL_CLOB_LOCATOR
223             SQL_ARRAY
224             SQL_ARRAY_LOCATOR
225             SQL_MULTISET
226             SQL_MULTISET_LOCATOR
227             SQL_TYPE_DATE
228             SQL_TYPE_TIME
229             SQL_TYPE_TIMESTAMP
230             SQL_TYPE_TIME_WITH_TIMEZONE
231             SQL_TYPE_TIMESTAMP_WITH_TIMEZONE
232             SQL_INTERVAL_YEAR
233             SQL_INTERVAL_MONTH
234             SQL_INTERVAL_DAY
235             SQL_INTERVAL_HOUR
236             SQL_INTERVAL_MINUTE
237             SQL_INTERVAL_SECOND
238             SQL_INTERVAL_YEAR_TO_MONTH
239             SQL_INTERVAL_DAY_TO_HOUR
240             SQL_INTERVAL_DAY_TO_MINUTE
241             SQL_INTERVAL_DAY_TO_SECOND
242             SQL_INTERVAL_HOUR_TO_MINUTE
243             SQL_INTERVAL_HOUR_TO_SECOND
244             SQL_INTERVAL_MINUTE_TO_SECOND
245             ) ],
246             sql_cursor_types => [ qw(
247             SQL_CURSOR_FORWARD_ONLY
248             SQL_CURSOR_KEYSET_DRIVEN
249             SQL_CURSOR_DYNAMIC
250             SQL_CURSOR_STATIC
251             SQL_CURSOR_TYPE_DEFAULT
252             ) ], # for ODBC cursor types
253             utils => [ qw(
254             neat neat_list $neat_maxlen dump_results looks_like_number
255             data_string_diff data_string_desc data_diff sql_type_cast
256             DBIstcf_DISCARD_STRING
257             DBIstcf_STRICT
258             ) ],
259             profile => [ qw(
260             dbi_profile dbi_profile_merge dbi_profile_merge_nodes dbi_time
261             ) ], # notionally "in" DBI::Profile and normally imported from there
262             );
263              
264 192         434 $DBI::dbi_debug = 0; # mixture of bit fields and int sub-fields
265 192         309 $DBI::neat_maxlen = 1000;
266 192         315 $DBI::stderr = 2_000_000_000; # a very round number below 2**31
267              
268             # If you get an error here like "Can't find loadable object ..."
269             # then you haven't installed the DBI correctly. Read the README
270             # then install it again.
271 192 100       805 if ( $ENV{DBI_PUREPERL} ) {
272 96 50       449 eval { bootstrap DBI $XS_VERSION } if $ENV{DBI_PUREPERL} == 1;
  0         0  
273 96 50 33     34892 require DBI::PurePerl if $@ or $ENV{DBI_PUREPERL} >= 2;
274 96   50     543 $DBI::PurePerl ||= 0; # just to silence "only used once" warnings
275             }
276             else {
277 96         52595 bootstrap DBI $XS_VERSION;
278             }
279              
280 192         721 $EXPORT_TAGS{preparse_flags} = [ grep { /^DBIpp_\w\w_/ } keys %{__PACKAGE__."::"} ];
  24580         34895  
  192         3677  
281              
282 192         19083 Exporter::export_ok_tags(keys %EXPORT_TAGS);
283              
284             }
285              
286             # Alias some handle methods to also be DBI class methods
287             for (qw(trace_msg set_err parse_trace_flag parse_trace_flags)) {
288 192     192   1308 no strict;
  192         343  
  192         9573  
289             *$_ = \&{"DBD::_::common::$_"};
290             }
291              
292 192     192   975 use strict;
  192         361  
  192         211261  
293              
294             DBI->trace(split /=/, $ENV{DBI_TRACE}, 2) if $ENV{DBI_TRACE};
295              
296             $DBI::connect_via ||= "connect";
297              
298             # check if user wants a persistent database connection ( Apache + mod_perl )
299             if ($INC{'Apache/DBI.pm'} && $ENV{MOD_PERL}) {
300             $DBI::connect_via = "Apache::DBI::connect";
301             DBI->trace_msg("DBI connect via $DBI::connect_via in $INC{'Apache/DBI.pm'}\n");
302             }
303              
304             %DBI::installed_drh = (); # maps driver names to installed driver handles
305 24     24 1 13393 sub installed_drivers { %DBI::installed_drh }
306             %DBI::installed_methods = (); # XXX undocumented, may change
307 3428     3428 0 23070 sub installed_methods { %DBI::installed_methods }
308              
309             # Setup special DBI dynamic variables. See DBI::var::FETCH for details.
310             # These are dynamically associated with the last handle used.
311             tie $DBI::err, 'DBI::var', '*err'; # special case: referenced via IHA list
312             tie $DBI::state, 'DBI::var', '"state'; # special case: referenced via IHA list
313             tie $DBI::lasth, 'DBI::var', '!lasth'; # special case: return boolean
314             tie $DBI::errstr, 'DBI::var', '&errstr'; # call &errstr in last used pkg
315             tie $DBI::rows, 'DBI::var', '&rows'; # call &rows in last used pkg
316 960     960   1571 sub DBI::var::TIESCALAR{ my $var = $_[1]; bless \$var, 'DBI::var'; }
  960         2219  
317 2     2   3628 sub DBI::var::STORE { Carp::croak("Can't modify \$DBI::${$_[0]} special variable") }
  2         371  
318              
319             # --- Driver Specific Prefix Registry ---
320              
321             my $dbd_prefix_registry = {
322             ad_ => { class => 'DBD::AnyData', },
323             ad2_ => { class => 'DBD::AnyData2', },
324             ado_ => { class => 'DBD::ADO', },
325             amzn_ => { class => 'DBD::Amazon', },
326             best_ => { class => 'DBD::BestWins', },
327             csv_ => { class => 'DBD::CSV', },
328             cubrid_ => { class => 'DBD::cubrid', },
329             db2_ => { class => 'DBD::DB2', },
330             dbi_ => { class => 'DBI', },
331             dbm_ => { class => 'DBD::DBM', },
332             df_ => { class => 'DBD::DF', },
333             examplep_ => { class => 'DBD::ExampleP', },
334             f_ => { class => 'DBD::File', },
335             file_ => { class => 'DBD::TextFile', },
336             go_ => { class => 'DBD::Gofer', },
337             ib_ => { class => 'DBD::InterBase', },
338             ing_ => { class => 'DBD::Ingres', },
339             ix_ => { class => 'DBD::Informix', },
340             jdbc_ => { class => 'DBD::JDBC', },
341             mo_ => { class => 'DBD::MO', },
342             monetdb_ => { class => 'DBD::monetdb', },
343             msql_ => { class => 'DBD::mSQL', },
344             mvsftp_ => { class => 'DBD::MVS_FTPSQL', },
345             mysql_ => { class => 'DBD::mysql', },
346             multi_ => { class => 'DBD::Multi' },
347             mx_ => { class => 'DBD::Multiplex', },
348             neo_ => { class => 'DBD::Neo4p', },
349             nullp_ => { class => 'DBD::NullP', },
350             odbc_ => { class => 'DBD::ODBC', },
351             ora_ => { class => 'DBD::Oracle', },
352             pg_ => { class => 'DBD::Pg', },
353             pgpp_ => { class => 'DBD::PgPP', },
354             plb_ => { class => 'DBD::Plibdata', },
355             po_ => { class => 'DBD::PO', },
356             proxy_ => { class => 'DBD::Proxy', },
357             ram_ => { class => 'DBD::RAM', },
358             rdb_ => { class => 'DBD::RDB', },
359             sapdb_ => { class => 'DBD::SAP_DB', },
360             snmp_ => { class => 'DBD::SNMP', },
361             solid_ => { class => 'DBD::Solid', },
362             spatialite_ => { class => 'DBD::Spatialite', },
363             sponge_ => { class => 'DBD::Sponge', },
364             sql_ => { class => 'DBI::DBD::SqlEngine', },
365             sqlite_ => { class => 'DBD::SQLite', },
366             syb_ => { class => 'DBD::Sybase', },
367             sys_ => { class => 'DBD::Sys', },
368             tdat_ => { class => 'DBD::Teradata', },
369             tmpl_ => { class => 'DBD::Template', },
370             tmplss_ => { class => 'DBD::TemplateSS', },
371             tree_ => { class => 'DBD::TreeData', },
372             tuber_ => { class => 'DBD::Tuber', },
373             uni_ => { class => 'DBD::Unify', },
374             vt_ => { class => 'DBD::Vt', },
375             wmi_ => { class => 'DBD::WMI', },
376             x_ => { }, # for private use
377             xbase_ => { class => 'DBD::XBase', },
378             xmlsimple_ => { class => 'DBD::XMLSimple', },
379             xl_ => { class => 'DBD::Excel', },
380             yaswi_ => { class => 'DBD::Yaswi', },
381             };
382              
383             my %dbd_class_registry = map { $dbd_prefix_registry->{$_}->{class} => { prefix => $_ } }
384             grep { exists $dbd_prefix_registry->{$_}->{class} }
385             keys %{$dbd_prefix_registry};
386              
387             sub dump_dbd_registry {
388 0     0 0 0 require Data::Dumper;
389 0         0 local $Data::Dumper::Sortkeys=1;
390 0         0 local $Data::Dumper::Indent=1;
391 0         0 print Data::Dumper->Dump([$dbd_prefix_registry], [qw($dbd_prefix_registry)]);
392             }
393              
394             # --- Dynamically create the DBI Standard Interface
395              
396             my $keeperr = { O=>0x0004 };
397              
398             %DBI::DBI_methods = ( # Define the DBI interface methods per class:
399              
400             common => { # Interface methods common to all DBI handle classes
401             'DESTROY' => { O=>0x004|0x10000 },
402             'CLEAR' => $keeperr,
403             'EXISTS' => $keeperr,
404             'FETCH' => { O=>0x0404 },
405             'FETCH_many' => { O=>0x0404 },
406             'FIRSTKEY' => $keeperr,
407             'NEXTKEY' => $keeperr,
408             'STORE' => { O=>0x0418 | 0x4 },
409             'DELETE' => { O=>0x0404 },
410             can => { O=>0x0100 }, # special case, see dispatch
411             debug => { U =>[1,2,'[$debug_level]'], O=>0x0004 }, # old name for trace
412             dump_handle => { U =>[1,3,'[$message [, $level]]'], O=>0x0004 },
413             err => $keeperr,
414             errstr => $keeperr,
415             state => $keeperr,
416             func => { O=>0x0006 },
417             parse_trace_flag => { U =>[2,2,'$name'], O=>0x0404, T=>8 },
418             parse_trace_flags => { U =>[2,2,'$flags'], O=>0x0404, T=>8 },
419             private_data => { U =>[1,1], O=>0x0004 },
420             set_err => { U =>[3,6,'$err, $errmsg [, $state, $method, $rv]'], O=>0x0010 },
421             trace => { U =>[1,3,'[$trace_level, [$filename]]'], O=>0x0004 },
422             trace_msg => { U =>[2,3,'$message_text [, $min_level ]' ], O=>0x0004, T=>8 },
423             swap_inner_handle => { U =>[2,3,'$h [, $allow_reparent ]'] },
424             private_attribute_info => { },
425             visit_child_handles => { U => [2,3,'$coderef [, $info ]'], O=>0x0404, T=>4 },
426             },
427             dr => { # Database Driver Interface
428             'connect' => { U =>[1,5,'[$db [,$user [,$passwd [,\%attr]]]]'], H=>3, O=>0x8000, T=>0x200 },
429             'connect_cached'=>{U=>[1,5,'[$db [,$user [,$passwd [,\%attr]]]]'], H=>3, O=>0x8000, T=>0x200 },
430             'disconnect_all'=>{ U =>[1,1], O=>0x0800, T=>0x200 },
431             data_sources => { U =>[1,2,'[\%attr]' ], O=>0x0800, T=>0x200 },
432             default_user => { U =>[3,4,'$user, $pass [, \%attr]' ], T=>0x200 },
433             dbixs_revision => $keeperr,
434             },
435             db => { # Database Session Class Interface
436             data_sources => { U =>[1,2,'[\%attr]' ], O=>0x0200 },
437             take_imp_data => { U =>[1,1], O=>0x10000 },
438             clone => { U =>[1,2,'[\%attr]'], T=>0x200 },
439             connected => { U =>[1,0], O => 0x0004, T=>0x200, H=>3 },
440             begin_work => { U =>[1,2,'[ \%attr ]'], O=>0x0400, T=>0x1000 },
441             commit => { U =>[1,1], O=>0x0480|0x0800, T=>0x1000 },
442             rollback => { U =>[1,1], O=>0x0480|0x0800, T=>0x1000 },
443             'do' => { U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'], O=>0x3200 },
444             last_insert_id => { U =>[5,6,'$catalog, $schema, $table_name, $field_name [, \%attr ]'], O=>0x2800 },
445             preparse => { }, # XXX
446             prepare => { U =>[2,3,'$statement [, \%attr]'], O=>0xA200 },
447             prepare_cached => { U =>[2,4,'$statement [, \%attr [, $if_active ] ]'], O=>0xA200 },
448             selectrow_array => { U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'], O=>0x2000 },
449             selectrow_arrayref=>{U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'], O=>0x2000 },
450             selectrow_hashref=>{ U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'], O=>0x2000 },
451             selectall_arrayref=>{U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'], O=>0x2000 },
452             selectall_array =>{U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'], O=>0x2000 },
453             selectall_hashref=>{ U =>[3,0,'$statement, $keyfield [, \%attr [, @bind_params ] ]'], O=>0x2000 },
454             selectcol_arrayref=>{U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'], O=>0x2000 },
455             ping => { U =>[1,1], O=>0x0404 },
456             disconnect => { U =>[1,1], O=>0x0400|0x0800|0x10000, T=>0x200 },
457             quote => { U =>[2,3, '$string [, $data_type ]' ], O=>0x0430, T=>2 },
458             quote_identifier=> { U =>[2,6, '$name [, ...] [, \%attr ]' ], O=>0x0430, T=>2 },
459             rows => $keeperr,
460              
461             tables => { U =>[1,6,'$catalog, $schema, $table, $type [, \%attr ]' ], O=>0x2200 },
462             table_info => { U =>[1,6,'$catalog, $schema, $table, $type [, \%attr ]' ], O=>0x2200|0x8800 },
463             column_info => { U =>[5,6,'$catalog, $schema, $table, $column [, \%attr ]'],O=>0x2200|0x8800 },
464             primary_key_info=> { U =>[4,5,'$catalog, $schema, $table [, \%attr ]' ], O=>0x2200|0x8800 },
465             primary_key => { U =>[4,5,'$catalog, $schema, $table [, \%attr ]' ], O=>0x2200 },
466             foreign_key_info=> { U =>[7,8,'$pk_catalog, $pk_schema, $pk_table, $fk_catalog, $fk_schema, $fk_table [, \%attr ]' ], O=>0x2200|0x8800 },
467             statistics_info => { U =>[6,7,'$catalog, $schema, $table, $unique_only, $quick, [, \%attr ]' ], O=>0x2200|0x8800 },
468             type_info_all => { U =>[1,1], O=>0x2200|0x0800 },
469             type_info => { U =>[1,2,'$data_type'], O=>0x2200 },
470             get_info => { U =>[2,2,'$info_type'], O=>0x2200|0x0800 },
471             },
472             st => { # Statement Class Interface
473             bind_col => { U =>[3,4,'$column, \\$var [, \%attr]'] },
474             bind_columns => { U =>[2,0,'\\$var1 [, \\$var2, ...]'] },
475             bind_param => { U =>[3,4,'$parameter, $var [, \%attr]'] },
476             bind_param_inout=> { U =>[4,5,'$parameter, \\$var, $maxlen, [, \%attr]'] },
477             execute => { U =>[1,0,'[@args]'], O=>0x1040 },
478              
479             bind_param_array => { U =>[3,4,'$parameter, $var [, \%attr]'] },
480             bind_param_inout_array => { U =>[4,5,'$parameter, \\@var, $maxlen, [, \%attr]'] },
481             execute_array => { U =>[2,0,'\\%attribs [, @args]'], O=>0x1040|0x4000 },
482             execute_for_fetch => { U =>[2,3,'$fetch_sub [, $tuple_status]'], O=>0x1040|0x4000 },
483              
484             fetch => undef, # alias for fetchrow_arrayref
485             fetchrow_arrayref => undef,
486             fetchrow_hashref => undef,
487             fetchrow_array => undef,
488             fetchrow => undef, # old alias for fetchrow_array
489              
490             fetchall_arrayref => { U =>[1,3, '[ $slice [, $max_rows]]'] },
491             fetchall_hashref => { U =>[2,2,'$key_field'] },
492              
493             blob_read => { U =>[4,5,'$field, $offset, $len [, \\$buf [, $bufoffset]]'] },
494             blob_copy_to_file => { U =>[3,3,'$field, $filename_or_handleref'] },
495             dump_results => { U =>[1,5,'$maxfieldlen, $linesep, $fieldsep, $filehandle'] },
496             more_results => { U =>[1,1] },
497             finish => { U =>[1,1] },
498             cancel => { U =>[1,1], O=>0x0800 },
499             rows => $keeperr,
500              
501             _get_fbav => undef,
502             _set_fbav => { T=>6 },
503             },
504             );
505              
506             while ( my ($class, $meths) = each %DBI::DBI_methods ) {
507             my $ima_trace = 0+($ENV{DBI_IMA_TRACE}||0);
508             while ( my ($method, $info) = each %$meths ) {
509             my $fullmeth = "DBI::${class}::$method";
510             if (($DBI::dbi_debug & 0xF) == 15) { # quick hack to list DBI methods
511             # and optionally filter by IMA flags
512             my $O = $info->{O}||0;
513             printf "0x%04x %-20s\n", $O, $fullmeth
514             unless $ima_trace && !($O & $ima_trace);
515             }
516             DBI->_install_method($fullmeth, 'DBI.pm', $info);
517             }
518             }
519              
520             {
521             package DBI::common;
522             @DBI::dr::ISA = ('DBI::common');
523             @DBI::db::ISA = ('DBI::common');
524             @DBI::st::ISA = ('DBI::common');
525             }
526              
527             # End of init code
528              
529             END {
530 192 50   192   2741080 return unless defined &DBI::trace_msg; # return unless bootstrap'd ok
531 192         2464 local ($!,$?);
532 192   50     3800 DBI->trace_msg(sprintf(" -- DBI::END (\$\@: %s, \$!: %s)\n", $@||'', $!||''), 2);
      50        
533             # Let drivers know why we are calling disconnect_all:
534 192         511 $DBI::PERL_ENDING = $DBI::PERL_ENDING = 1; # avoid typo warning
535 192 100       2237 DBI->disconnect_all() if %DBI::installed_drh;
536             }
537              
538              
539             sub CLONE {
540 0 0   0   0 _clone_dbis() unless $DBI::PurePerl; # clone the DBIS structure
541 0         0 DBI->trace_msg("CLONE DBI for new thread\n");
542 0         0 while ( my ($driver, $drh) = each %DBI::installed_drh) {
543 192     192   1489 no strict 'refs';
  192         395  
  192         188236  
544 0 0       0 next if defined &{"DBD::${driver}::CLONE"};
  0         0  
545 0         0 warn("$driver has no driver CLONE() function so is unsafe threaded\n");
546             }
547 0         0 %DBI::installed_drh = (); # clear loaded drivers so they have a chance to reinitialize
548             }
549              
550             sub parse_dsn {
551 630     630 1 1299 my ($class, $dsn) = @_;
552 630 100       3164 $dsn =~ s/^(dbi):(\w*?)(?:\((.*?)\))?://i or return;
553 2         15 my ($scheme, $driver, $attr, $attr_hash) = (lc($1), $2, $3);
554 2   0     8 $driver ||= $ENV{DBI_DRIVER} || '';
      33        
555 2 50       8 $attr_hash = { split /\s*=>?\s*|\s*,\s*/, $attr, -1 } if $attr;
556 2         8 return ($scheme, $driver, $attr, $attr_hash, $dsn);
557             }
558              
559             sub visit_handles {
560 8     8 1 7342 my ($class, $code, $outer_info) = @_;
561 8 50       29 $outer_info = {} if not defined $outer_info;
562 8         32 my %drh = DBI->installed_drivers;
563 8         30 for my $h (values %drh) {
564 12 50       58 my $child_info = $code->($h, $outer_info)
565             or next;
566 12         466 $h->visit_child_handles($code, $child_info);
567             }
568 8         56 return $outer_info;
569             }
570              
571              
572             # --- The DBI->connect Front Door methods
573              
574             sub connect_cached {
575             # For library code using connect_cached() with mod_perl
576             # we redirect those calls to Apache::DBI::connect() as well
577 3146     3146 1 7294 my ($class, $dsn, $user, $pass, $attr) = @_;
578 3146 50       5983 my $dbi_connect_method = ($DBI::connect_via eq "Apache::DBI::connect")
579             ? 'Apache::DBI::connect' : 'connect_cached';
580 3146 50       14534 $attr = {
581             $attr ? %$attr : (), # clone, don't modify callers data
582             dbi_connect_method => $dbi_connect_method,
583             };
584 3146         8754 return $class->connect($dsn, $user, $pass, $attr);
585             }
586              
587             sub connect {
588 6971     6971 1 1071802 my $class = shift;
589 6971         19843 my ($dsn, $user, $pass, $attr, $old_driver) = my @orig_args = @_;
590 6971         9588 my $driver;
591              
592 6971 50 66     26853 if ($attr and !ref($attr)) { # switch $old_driver<->$attr if called in old style
593 0         0 Carp::carp("DBI->connect using 'old-style' syntax is deprecated and will be an error in future versions");
594 0         0 ($old_driver, $attr) = ($attr, $old_driver);
595             }
596              
597 6971         11084 my $connect_meth = $attr->{dbi_connect_method};
598 6971   66     19806 $connect_meth ||= $DBI::connect_via; # fallback to default
599              
600 6971 50 0     15575 $dsn ||= $ENV{DBI_DSN} || $ENV{DBI_DBNAME} || '' unless $old_driver;
      33        
601              
602 6971 100       12986 if ($DBI::dbi_debug) {
603 29         101 local $^W = 0;
604 29 50       73 pop @_ if $connect_meth ne 'connect';
605 29         77 my @args = @_; $args[2] = '****'; # hide password
  29         51  
606 29         512 DBI->trace_msg(" -> $class->$connect_meth(".join(", ",@args).")\n");
607             }
608 6971 100 33     36274 Carp::croak('Usage: $class->connect([$dsn [,$user [,$passwd [,\%attr]]]])')
      33        
      100        
      66        
609             if (ref $old_driver or ($attr and not ref $attr) or
610             (ref $pass and not defined Scalar::Util::blessed($pass)));
611              
612             # extract dbi:driver prefix from $dsn into $1
613 6967 50       56699 $dsn =~ s/^dbi:(\w*?)(?:\((.*?)\))?://i
614             or '' =~ /()/; # ensure $1 etc are empty if match fails
615 6967   100     28277 my $driver_attrib_spec = $2 || '';
616              
617             # Set $driver. Old style driver, if specified, overrides new dsn style.
618             $driver = $old_driver || $1 || $ENV{DBI_DRIVER}
619 6967 50 33     30883 or Carp::croak("Can't connect to data source '$dsn' "
620             ."because I can't work out what driver to use "
621             ."(it doesn't seem to contain a 'dbi:driver:' prefix "
622             ."and the DBI_DRIVER env var is not set)");
623              
624 6967         8726 my $proxy;
625 6967 100 66     17714 if ($ENV{DBI_AUTOPROXY} && $driver ne 'Proxy' && $driver ne 'Sponge' && $driver ne 'Switch') {
      100        
      66        
626 194         467 my $dbi_autoproxy = $ENV{DBI_AUTOPROXY};
627 194         362 $proxy = 'Proxy';
628 194 50       1352 if ($dbi_autoproxy =~ s/^dbi:(\w*?)(?:\((.*?)\))?://i) {
629 194         557 $proxy = $1;
630 194 100       882 $driver_attrib_spec = join ",",
    50          
631             ($driver_attrib_spec) ? $driver_attrib_spec : (),
632             ($2 ) ? $2 : ();
633             }
634 194         695 $dsn = "$dbi_autoproxy;dsn=dbi:$driver:$dsn";
635 194         347 $driver = $proxy;
636 194         1091 DBI->trace_msg(" DBI_AUTOPROXY: dbi:$driver($driver_attrib_spec):$dsn\n");
637             }
638             # avoid recursion if proxy calls DBI->connect itself
639 6967 100       13658 local $ENV{DBI_AUTOPROXY} if $ENV{DBI_AUTOPROXY};
640              
641 6967         8532 my %attributes; # take a copy we can delete from
642 6967 50       11293 if ($old_driver) {
643 0 0       0 %attributes = %$attr if $attr;
644             }
645             else { # new-style connect so new default semantics
646 6967 50       48290 %attributes = (
    100          
647             PrintError => 1,
648             AutoCommit => 1,
649             ref $attr ? %$attr : (),
650             # attributes in DSN take precedence over \%attr connect parameter
651             $driver_attrib_spec ? (split /\s*=>?\s*|\s*,\s*/, $driver_attrib_spec, -1) : (),
652             );
653             }
654 6967         14349 $attr = \%attributes; # now set $attr to refer to our local copy
655              
656 6967 50 66     23339 my $drh = $DBI::installed_drh{$driver} || $class->install_driver($driver)
657             or die "panic: $class->install_driver($driver) failed";
658              
659             # attributes in DSN take precedence over \%attr connect parameter
660 6963 100       16023 $user = $attr->{Username} if defined $attr->{Username};
661 6963 100       14117 $pass = $attr->{Password} if defined $attr->{Password};
662 6963         10316 delete $attr->{Password}; # always delete Password as closure stores it securely
663 6963 100 66     19419 if ( !(defined $user && defined $pass) ) {
664 1604         9591 ($user, $pass) = $drh->default_user($user, $pass, $attr);
665             }
666 6963         19671 $attr->{Username} = $user; # force the Username to be the actual one used
667              
668             my $connect_closure = sub {
669 6979     6979   10792 my ($old_dbh, $override_attr) = @_;
670              
671             #use Data::Dumper;
672             #warn "connect_closure: ".Data::Dumper::Dumper([$attr,\%attributes, $override_attr]);
673              
674 6979         8301 my $dbh;
675 6979 100       35089 unless ($dbh = $drh->$connect_meth($dsn, $user, $pass, $attr)) {
676 38 100       810 $user = '' if !defined $user;
677 38 50       83 $dsn = '' if !defined $dsn;
678             # $drh->errstr isn't safe here because $dbh->DESTROY may not have
679             # been called yet and so the dbh errstr would not have been copied
680             # up to the drh errstr. Certainly true for connect_cached!
681 38         160 my $errstr = $DBI::errstr;
682             # Getting '(no error string)' here is a symptom of a ref loop
683 38 50       90 $errstr = '(no error string)' if !defined $errstr;
684 38         132 my $msg = "$class connect('$dsn','$user',...) failed: $errstr";
685 38         161 DBI->trace_msg(" $msg\n");
686             # XXX HandleWarn
687 38 50 33     116 unless ($attr->{HandleError} && $attr->{HandleError}->($msg, $drh, $dbh)) {
688 38 100       1678 Carp::croak($msg) if $attr->{RaiseError};
689 24 50       52 Carp::carp ($msg) if $attr->{PrintError};
690             }
691 24         54 $! = 0; # for the daft people who do DBI->connect(...) || die "$!";
692 24         56 return $dbh; # normally undef, but HandleError could change it
693             }
694              
695             # merge any attribute overrides but don't change $attr itself (for closure)
696 6905 100       56945 my $apply = { ($override_attr) ? (%$attr, %$override_attr ) : %$attr };
697              
698             # handle basic RootClass subclassing:
699 6905   100     29431 my $rebless_class = $apply->{RootClass} || ($class ne 'DBI' ? $class : '');
700 6905 100       12359 if ($rebless_class) {
701 192     192   1401 no strict 'refs';
  192         367  
  192         142311  
702 32 100       75 if ($apply->{RootClass}) { # explicit attribute (ie not static method call class)
703 24         45 delete $apply->{RootClass};
704 24         62 DBI::_load_class($rebless_class, 0);
705             }
706 28 50 33     43 unless (@{"$rebless_class\::db::ISA"} && @{"$rebless_class\::st::ISA"}) {
  28         117  
  28         108  
707 0         0 Carp::carp("DBI subclasses '$rebless_class\::db' and ::st are not setup, RootClass ignored");
708 0         0 $rebless_class = undef;
709 0         0 $class = 'DBI';
710             }
711             else {
712 28         194 $dbh->{RootClass} = $rebless_class; # $dbh->STORE called via plain DBI::db
713 28         254 DBI::_set_isa([$rebless_class], 'DBI'); # sets up both '::db' and '::st'
714 28         73 DBI::_rebless($dbh, $rebless_class); # appends '::db'
715             }
716             }
717              
718 6901 100       12900 if (%$apply) {
719              
720 6321 50       10946 if ($apply->{DbTypeSubclass}) {
721 0         0 my $DbTypeSubclass = delete $apply->{DbTypeSubclass};
722 0   0     0 DBI::_rebless_dbtype_subclass($dbh, $rebless_class||$class, $DbTypeSubclass);
723             }
724 6321         7061 my $a;
725 6321         10530 foreach $a (qw(Profile RaiseError PrintError AutoCommit)) { # do these first
726 25284 100       57897 next unless exists $apply->{$a};
727 18856         84034 $dbh->{$a} = delete $apply->{$a};
728             }
729 6321         30507 while ( my ($a, $v) = each %$apply) {
730 28547         35532 eval { $dbh->{$a} = $v }; # assign in void context to avoid re-FETCH
  28547         98400  
731 28547 50       119776 warn $@ if $@;
732             }
733             }
734              
735             # confirm to driver (ie if subclassed) that we've connected successfully
736             # and finished the attribute setup. pass in the original arguments
737 6901         27945 $dbh->connected(@orig_args); #if ref $dbh ne 'DBI::db' or $proxy;
738              
739 6901 100       22369 DBI->trace_msg(" <- connect= $dbh\n") if $DBI::dbi_debug & 0xF;
740              
741 6901         20774 return $dbh;
742 6963         36312 };
743              
744 6963         15323 my $dbh = &$connect_closure(undef, undef);
745              
746 6909 100       32246 $dbh->{dbi_connect_closure} = $connect_closure if $dbh;
747              
748 6909         36520 return $dbh;
749             }
750              
751              
752             sub disconnect_all {
753 138     138 0 447 keys %DBI::installed_drh; # reset iterator
754 138         852 while ( my ($name, $drh) = each %DBI::installed_drh ) {
755 234 50       6010 $drh->disconnect_all() if ref $drh;
756             }
757             }
758              
759              
760             sub disconnect { # a regular beginners bug
761 0     0 1 0 Carp::croak("DBI->disconnect is not a DBI method (read the DBI manual)");
762             }
763              
764              
765             sub install_driver { # croaks on failure
766 246     246 0 63542 my $class = shift;
767 246         635 my($driver, $attr) = @_;
768 246         415 my $drh;
769              
770 246   0     689 $driver ||= $ENV{DBI_DRIVER} || '';
      33        
771              
772             # allow driver to be specified as a 'dbi:driver:' string
773 246 100       939 $driver = $1 if $driver =~ s/^DBI:(.*?)://i;
774              
775 246 50 33     1396 Carp::croak("usage: $class->install_driver(\$driver [, \%attr])")
776             unless ($driver and @_<=3);
777              
778             # already installed
779 246 100       843 return $drh if $drh = $DBI::installed_drh{$driver};
780              
781 238 100       899 $class->trace_msg(" -> $class->install_driver($driver"
782             .") for $^O perl=$] pid=$$ ruid=$< euid=$>\n")
783             if $DBI::dbi_debug & 0xF;
784              
785             # --- load the code
786 238         695 my $driver_class = "DBD::$driver";
787 238         16121 eval qq{package # hide from PAUSE
788             DBI::_firesafe; # just in case
789             require $driver_class; # load the driver
790             };
791 238 100       1350 if ($@) {
792 4         10 my $err = $@;
793 4         7 my $advice = "";
794 4 50       98 if ($err =~ /Can't find loadable object/) {
    50          
    0          
    0          
795 0         0 $advice = "Perhaps DBD::$driver was statically linked into a new perl binary."
796             ."\nIn which case you need to use that new perl binary."
797             ."\nOr perhaps only the .pm file was installed but not the shared object file."
798             }
799             elsif ($err =~ /Can't locate.*?DBD\/$driver\.pm in \@INC/) {
800 4         22 my @drv = $class->available_drivers(1);
801 4         29 $advice = "Perhaps the DBD::$driver perl module hasn't been fully installed,\n"
802             ."or perhaps the capitalisation of '$driver' isn't right.\n"
803             ."Available drivers: ".join(", ", @drv).".";
804             }
805             elsif ($err =~ /Can't load .*? for module DBD::/) {
806 0         0 $advice = "Perhaps a required shared library or dll isn't installed where expected";
807             }
808             elsif ($err =~ /Can't locate .*? in \@INC/) {
809 0         0 $advice = "Perhaps a module that DBD::$driver requires hasn't been fully installed";
810             }
811 4         856 Carp::croak("install_driver($driver) failed: $err$advice\n");
812             }
813 234 100       895 if ($DBI::dbi_debug & 0xF) {
814 192     192   1392 no strict 'refs';
  192         389  
  192         52250  
815 6         39 (my $driver_file = $driver_class) =~ s/::/\//g;
816 6   50     11 my $dbd_ver = ${"$driver_class\::VERSION"} || "undef";
817 6         119 $class->trace_msg(" install_driver: $driver_class version $dbd_ver"
818             ." loaded from $INC{qq($driver_file.pm)}\n");
819             }
820              
821             # --- do some behind-the-scenes checks and setups on the driver
822 234         1386 $class->setup_driver($driver_class);
823              
824             # --- run the driver function
825 234   50     503 $drh = eval { $driver_class->driver($attr || {}) };
  234         1814  
826 234 50 33     4960 unless ($drh && ref $drh && !$@) {
      33        
827 0         0 my $advice = "";
828 0   0     0 $@ ||= "$driver_class->driver didn't return a handle";
829             # catch people on case in-sensitive systems using the wrong case
830 0 0       0 $advice = "\nPerhaps the capitalisation of DBD '$driver' isn't right."
831             if $@ =~ /locate object method/;
832 0         0 Carp::croak("$driver_class initialisation failed: $@$advice");
833             }
834              
835 234         715 $DBI::installed_drh{$driver} = $drh;
836 234 100       816 $class->trace_msg(" <- install_driver= $drh\n") if $DBI::dbi_debug & 0xF;
837 234         1216 $drh;
838             }
839              
840             *driver = \&install_driver; # currently an alias, may change
841              
842              
843             sub setup_driver {
844 534     534 0 1631 my ($class, $driver_class) = @_;
845 534         896 my $h_type;
846 534         1412 foreach $h_type (qw(dr db st)){
847 1602         3614 my $h_class = $driver_class."::$h_type";
848 192     192   1303 no strict 'refs';
  192         554  
  192         46664  
849 1602 100       10969 push @{"${h_class}::ISA"}, "DBD::_::$h_type"
  1302         13425  
850             unless UNIVERSAL::isa($h_class, "DBD::_::$h_type");
851             # The _mem class stuff is (IIRC) a crufty hack for global destruction
852             # timing issues in early versions of perl5 and possibly no longer needed.
853 1602         4650 my $mem_class = "DBD::_mem::$h_type";
854 1602 100 100     11547 push @{"${h_class}_mem::ISA"}, $mem_class
  756         8069  
855             unless UNIVERSAL::isa("${h_class}_mem", $mem_class)
856             or $DBI::PurePerl;
857             }
858             }
859              
860              
861             sub _rebless {
862 28     28   39 my $dbh = shift;
863 28         88 my ($outer, $inner) = DBI::_handles($dbh);
864 28         61 my $class = shift(@_).'::db';
865 28         51 bless $inner => $class;
866 28         51 bless $outer => $class; # outer last for return
867             }
868              
869              
870             sub _set_isa {
871 28     28   57 my ($classes, $topclass) = @_;
872 28         134 my $trace = DBI->trace_msg(" _set_isa([@$classes])\n");
873 28         60 foreach my $suffix ('::db','::st') {
874 56   50     106 my $previous = $topclass || 'DBI'; # trees are rooted here
875 56         90 foreach my $class (@$classes) {
876 56         92 my $base_class = $previous.$suffix;
877 56         80 my $sub_class = $class.$suffix;
878 56         91 my $sub_class_isa = "${sub_class}::ISA";
879 192     192   1245 no strict 'refs';
  192         411  
  192         110447  
880 56 50       153 if (@$sub_class_isa) {
881 56 50       97 DBI->trace_msg(" $sub_class_isa skipped (already set to @$sub_class_isa)\n")
882             if $trace;
883             }
884             else {
885 0 0       0 @$sub_class_isa = ($base_class) unless @$sub_class_isa;
886 0 0       0 DBI->trace_msg(" $sub_class_isa = $base_class\n")
887             if $trace;
888             }
889 56         126 $previous = $class;
890             }
891             }
892             }
893              
894              
895             sub _rebless_dbtype_subclass {
896 0     0   0 my ($dbh, $rootclass, $DbTypeSubclass) = @_;
897             # determine the db type names for class hierarchy
898 0         0 my @hierarchy = DBI::_dbtype_names($dbh, $DbTypeSubclass);
899             # add the rootclass prefix to each ('DBI::' or 'MyDBI::' etc)
900 0         0 $_ = $rootclass.'::'.$_ foreach (@hierarchy);
901             # load the modules from the 'top down'
902 0         0 DBI::_load_class($_, 1) foreach (reverse @hierarchy);
903             # setup class hierarchy if needed, does both '::db' and '::st'
904 0         0 DBI::_set_isa(\@hierarchy, $rootclass);
905             # finally bless the handle into the subclass
906 0         0 DBI::_rebless($dbh, $hierarchy[0]);
907             }
908              
909              
910             sub _dbtype_names { # list dbtypes for hierarchy, ie Informix=>ADO=>ODBC
911 0     0   0 my ($dbh, $DbTypeSubclass) = @_;
912              
913 0 0 0     0 if ($DbTypeSubclass && $DbTypeSubclass ne '1' && ref $DbTypeSubclass ne 'CODE') {
      0        
914             # treat $DbTypeSubclass as a comma separated list of names
915 0         0 my @dbtypes = split /\s*,\s*/, $DbTypeSubclass;
916 0         0 $dbh->trace_msg(" DbTypeSubclass($DbTypeSubclass)=@dbtypes (explicit)\n");
917 0         0 return @dbtypes;
918             }
919              
920             # XXX will call $dbh->get_info(17) (=SQL_DBMS_NAME) in future?
921              
922 0         0 my $driver = $dbh->{Driver}->{Name};
923 0 0       0 if ( $driver eq 'Proxy' ) {
924             # XXX Looking into the internals of DBD::Proxy is questionable!
925 0 0       0 ($driver) = $dbh->{proxy_client}->{application} =~ /^DBI:(.+?):/i
926             or die "Can't determine driver name from proxy";
927             }
928              
929 0         0 my @dbtypes = (ucfirst($driver));
930 0 0 0     0 if ($driver eq 'ODBC' || $driver eq 'ADO') {
931             # XXX will move these out and make extensible later:
932 0         0 my $_dbtype_name_regexp = 'Oracle'; # eg 'Oracle|Foo|Bar'
933 0         0 my %_dbtype_name_map = (
934             'Microsoft SQL Server' => 'MSSQL',
935             'SQL Server' => 'Sybase',
936             'Adaptive Server Anywhere' => 'ASAny',
937             'ADABAS D' => 'AdabasD',
938             );
939              
940 0         0 my $name;
941 0 0       0 $name = $dbh->func(17, 'GetInfo') # SQL_DBMS_NAME
942             if $driver eq 'ODBC';
943 0 0       0 $name = $dbh->{ado_conn}->Properties->Item('DBMS Name')->Value
944             if $driver eq 'ADO';
945 0 0       0 die "Can't determine driver name! ($DBI::errstr)\n"
946             unless $name;
947              
948 0         0 my $dbtype;
949 0 0       0 if ($_dbtype_name_map{$name}) {
950 0         0 $dbtype = $_dbtype_name_map{$name};
951             }
952             else {
953 0 0       0 if ($name =~ /($_dbtype_name_regexp)/) {
954 0         0 $dbtype = lc($1);
955             }
956             else { # generic mangling for other names:
957 0         0 $dbtype = lc($name);
958             }
959 0         0 $dbtype =~ s/\b(\w)/\U$1/g;
960 0         0 $dbtype =~ s/\W+/_/g;
961             }
962             # add ODBC 'behind' ADO
963 0 0       0 push @dbtypes, 'ODBC' if $driver eq 'ADO';
964             # add discovered dbtype in front of ADO/ODBC
965 0         0 unshift @dbtypes, $dbtype;
966             }
967 0 0       0 @dbtypes = &$DbTypeSubclass($dbh, \@dbtypes)
968             if (ref $DbTypeSubclass eq 'CODE');
969 0         0 $dbh->trace_msg(" DbTypeSubclass($DbTypeSubclass)=@dbtypes\n");
970 0         0 return @dbtypes;
971             }
972              
973             sub _load_class {
974 24     24   52 my ($load_class, $missing_ok) = @_;
975 24         130 DBI->trace_msg(" _load_class($load_class, $missing_ok)\n", 2);
976 192     192   1348 no strict 'refs';
  192         429  
  192         103969  
977 24 100       36 return 1 if @{"$load_class\::ISA"}; # already loaded/exists
  24         124  
978 4         15 (my $module = $load_class) =~ s!::!/!g;
979 4         22 DBI->trace_msg(" _load_class require $module\n", 2);
980 4         7 eval { require "$module.pm"; };
  4         544  
981 4 50       30 return 1 unless $@;
982 4 50 33     22 return 0 if $missing_ok && $@ =~ /^Can't locate \Q$module.pm\E/;
983 4         146 die $@;
984             }
985              
986              
987             sub init_rootclass { # deprecated
988 0     0 0 0 return 1;
989             }
990              
991              
992             *internal = \&DBD::Switch::dr::driver;
993              
994             sub driver_prefix {
995 5316     5316 0 9218 my ($class, $driver) = @_;
996 5316 50       17026 return $dbd_class_registry{$driver}->{prefix} if exists $dbd_class_registry{$driver};
997 0         0 return;
998             }
999              
1000             sub available_drivers {
1001 12     12 1 5014 my($quiet) = @_;
1002 12         29 my(@drivers, $d, $f);
1003 12         35 local(*DBI::DIR, $@);
1004 12         22 my(%seen_dir, %seen_dbd);
1005 12         26 my $haveFileSpec = eval { require File::Spec };
  12         82  
1006 12         34 foreach $d (@INC){
1007 132         205 chomp($d); # Perl 5 beta 3 bug in #!./perl -Ilib from Test::Harness
1008 132 50       762 my $dbd_dir =
1009             ($haveFileSpec ? File::Spec->catdir($d, 'DBD') : "$d/DBD");
1010 132 100       1060 next unless -d $dbd_dir;
1011 36 100       116 next if $seen_dir{$d};
1012 28         63 $seen_dir{$d} = 1;
1013             # XXX we have a problem here with case insensitive file systems
1014             # XXX since we can't tell what case must be used when loading.
1015 28 50       585 opendir(DBI::DIR, $dbd_dir) || Carp::carp "opendir $dbd_dir: $!\n";
1016 28         525 foreach $f (readdir(DBI::DIR)){
1017 308 100       812 next unless $f =~ s/\.pm$//;
1018 196 100       362 next if $f eq 'NullP';
1019 168 100       324 if ($seen_dbd{$f}){
1020 96 50       147 Carp::carp "DBD::$f in $d is hidden by DBD::$f in $seen_dbd{$f}\n"
1021             unless $quiet;
1022             } else {
1023 72         112 push(@drivers, $f);
1024             }
1025 168         310 $seen_dbd{$f} = $d;
1026             }
1027 28         273 closedir(DBI::DIR);
1028             }
1029              
1030             # "return sort @drivers" will not DWIM in scalar context.
1031 12 100       140 return wantarray ? sort @drivers : @drivers;
1032             }
1033              
1034             sub installed_versions {
1035 0     0 1 0 my ($class, $quiet) = @_;
1036 0         0 my %error;
1037             my %version;
1038 0         0 for my $driver ($class->available_drivers($quiet)) {
1039 0 0 0     0 next if $DBI::PurePerl && grep { -d "$_/auto/DBD/$driver" } @INC;
  0         0  
1040 0         0 my $drh = eval {
1041 0     0   0 local $SIG{__WARN__} = sub {};
1042 0         0 $class->install_driver($driver);
1043             };
1044 0 0       0 ($error{"DBD::$driver"}=$@),next if $@;
1045 192     192   1312 no strict 'refs';
  192         377  
  192         380518  
1046 0         0 my $vers = ${"DBD::$driver" . '::VERSION'};
  0         0  
1047 0   0     0 $version{"DBD::$driver"} = $vers || '?';
1048             }
1049 0 0       0 if (wantarray) {
1050 0 0       0 return map { m/^DBD::(\w+)/ ? ($1) : () } sort keys %version;
  0         0  
1051             }
1052 0         0 $version{"DBI"} = $DBI::VERSION;
1053 0 0       0 $version{"DBI::PurePerl"} = $DBI::PurePerl::VERSION if $DBI::PurePerl;
1054 0 0       0 if (!defined wantarray) { # void context
1055 0         0 require Config; # add more detail
1056 0         0 $version{OS} = "$^O\t($Config::Config{osvers})";
1057 0         0 $version{Perl} = "$]\t($Config::Config{archname})";
1058             $version{$_} = (($error{$_} =~ s/ \(\@INC.*//s),$error{$_})
1059 0         0 for keys %error;
1060             printf " %-16s: %s\n",$_,$version{$_}
1061 0         0 for reverse sort keys %version;
1062             }
1063 0         0 return \%version;
1064             }
1065              
1066              
1067             sub data_sources {
1068 12     12 1 39457 my ($class, $driver, @other) = @_;
1069 12         57 my $drh = $class->install_driver($driver);
1070 12         127 my @ds = $drh->data_sources(@other);
1071 12         3208 return @ds;
1072             }
1073              
1074              
1075             sub neat_list {
1076 128     128 1 58016 my ($listref, $maxlen, $sep) = @_;
1077 128 100       355 $maxlen = 0 unless defined $maxlen; # 0 == use internal default
1078 128 100       306 $sep = ", " unless defined $sep;
1079 128         283 join($sep, map { neat($_,$maxlen) } @$listref);
  284         1774  
1080             }
1081              
1082              
1083             sub dump_results { # also aliased as a method in DBD::_::st
1084 4     4 1 1863 my ($sth, $maxlen, $lsep, $fsep, $fh) = @_;
1085 4 50       18 return 0 unless $sth;
1086 4   50     12 $maxlen ||= 35;
1087 4   50     12 $lsep ||= "\n";
1088 4   50     12 $fh ||= \*STDOUT;
1089 4         9 my $rows = 0;
1090 4         7 my $ref;
1091 4         38 while($ref = $sth->fetch) {
1092 12 100 66     209 print $fh $lsep if $rows++ and $lsep;
1093 12         33 my $str = neat_list($ref,$maxlen,$fsep);
1094 12         75 print $fh $str; # done on two lines to avoid 5.003 errors
1095             }
1096 4 50       50 print $fh "\n$rows rows".($DBI::err ? " ($DBI::err: $DBI::errstr)" : "")."\n";
1097 4         19 $rows;
1098             }
1099              
1100              
1101             sub data_diff {
1102 28     28 1 85 my ($a, $b, $logical) = @_;
1103              
1104 28         65 my $diff = data_string_diff($a, $b);
1105 28 100 66     113 return "" if $logical and !$diff;
1106              
1107 24         54 my $a_desc = data_string_desc($a);
1108 24         151 my $b_desc = data_string_desc($b);
1109 24 100 100     211 return "" if !$diff and $a_desc eq $b_desc;
1110              
1111 12 100 100     65 $diff ||= "Strings contain the same sequence of characters"
1112             if length($a);
1113 12 50       40 $diff .= "\n" if $diff;
1114 12         90 return "a: $a_desc\nb: $b_desc\n$diff";
1115             }
1116              
1117              
1118             sub data_string_diff {
1119             # Compares 'logical' characters, not bytes, so a latin1 string and an
1120             # an equivalent Unicode string will compare as equal even though their
1121             # byte encodings are different.
1122 60     60 1 2416 my ($a, $b) = @_;
1123 60 100 100     309 unless (defined $a and defined $b) { # one undef
1124 16 50 66     95 return ""
1125             if !defined $a and !defined $b;
1126 8 50       23 return "String a is undef, string b has ".length($b)." characters"
1127             if !defined $a;
1128 8 50       60 return "String b is undef, string a has ".length($a)." characters"
1129             if !defined $b;
1130             }
1131              
1132 44         289 require utf8;
1133             # hack to cater for perl 5.6
1134 44 50   0   137 *utf8::is_utf8 = sub { (DBI::neat(shift)=~/^"/) } unless defined &utf8::is_utf8;
  0         0  
1135              
1136 44 50       221 my @a_chars = (utf8::is_utf8($a)) ? unpack("U*", $a) : unpack("C*", $a);
1137 44 100       143 my @b_chars = (utf8::is_utf8($b)) ? unpack("U*", $b) : unpack("C*", $b);
1138 44         74 my $i = 0;
1139 44   100     191 while (@a_chars && @b_chars) {
1140 72 100       270 ++$i, shift(@a_chars), shift(@b_chars), next
1141             if $a_chars[0] == $b_chars[0];# compare ordinal values
1142             my @desc = map {
1143 12 50       34 $_ > 255 ? # if wide character...
  24 50       146  
1144             sprintf("\\x{%04X}", $_) : # \x{...}
1145             chr($_) =~ /[[:cntrl:]]/ ? # else if control character ...
1146             sprintf("\\x%02X", $_) : # \x..
1147             chr($_) # else as themselves
1148             } ($a_chars[0], $b_chars[0]);
1149             # highlight probable double-encoding?
1150 12         32 foreach my $c ( @desc ) {
1151 24 50       62 next unless $c =~ m/\\x\{08(..)}/;
1152 0         0 $c .= "='" .chr(hex($1)) ."'"
1153             }
1154 12         116 return sprintf "Strings differ at index $i: a[$i]=$desc[0], b[$i]=$desc[1]";
1155             }
1156 32 100       96 return "String a truncated after $i characters" if @b_chars;
1157 28 100       91 return "String b truncated after $i characters" if @a_chars;
1158 24         78 return "";
1159             }
1160              
1161              
1162             sub data_string_desc { # describe a data string
1163 72     72 1 20855 my ($a) = @_;
1164 72         2695 require bytes;
1165 72         1101 require utf8;
1166              
1167             # hacks to cater for perl 5.6
1168 72 50   0   217 *utf8::is_utf8 = sub { (DBI::neat(shift)=~/^"/) } unless defined &utf8::is_utf8;
  0         0  
1169 72 50   0   179 *utf8::valid = sub { 1 } unless defined &utf8::valid;
  0         0  
1170              
1171             # Give sufficient info to help diagnose at least these kinds of situations:
1172             # - valid UTF8 byte sequence but UTF8 flag not set
1173             # (might be ascii so also need to check for hibit to make it worthwhile)
1174             # - UTF8 flag set but invalid UTF8 byte sequence
1175             # could do better here, but this'll do for now
1176 72 100 100     503 my $utf8 = sprintf "UTF8 %s%s",
    50          
1177             utf8::is_utf8($a) ? "on" : "off",
1178             utf8::valid($a||'') ? "" : " but INVALID encoding";
1179 72 100       209 return "$utf8, undef" unless defined $a;
1180 56         266 my $is_ascii = $a =~ m/^[\000-\177]*$/;
1181 56 100       225 return sprintf "%s, %s, %d characters %d bytes",
1182             $utf8, $is_ascii ? "ASCII" : "non-ASCII",
1183             length($a), bytes::length($a);
1184             }
1185              
1186              
1187             sub connect_test_perf {
1188 0     0 0 0 my($class, $dsn,$dbuser,$dbpass, $attr) = @_;
1189 0 0       0 Carp::croak("connect_test_perf needs hash ref as fourth arg") unless ref $attr;
1190             # these are non standard attributes just for this special method
1191 0   0     0 my $loops ||= $attr->{dbi_loops} || 5;
      0        
1192 0   0     0 my $par ||= $attr->{dbi_par} || 1; # parallelism
      0        
1193 0   0     0 my $verb ||= $attr->{dbi_verb} || 1;
      0        
1194 0   0     0 my $meth ||= $attr->{dbi_meth} || 'connect';
      0        
1195 0         0 print "$dsn: testing $loops sets of $par connections:\n";
1196 0         0 require "FileHandle.pm"; # don't let toke.c create empty FileHandle package
1197 0         0 local $| = 1;
1198 0 0       0 my $drh = $class->install_driver($dsn) or Carp::croak("Can't install $dsn driver\n");
1199             # test the connection and warm up caches etc
1200 0 0       0 $drh->connect($dsn,$dbuser,$dbpass) or Carp::croak("connect failed: $DBI::errstr");
1201 0         0 my $t1 = dbi_time();
1202 0         0 my $loop;
1203 0         0 for $loop (1..$loops) {
1204 0         0 my @cons;
1205 0 0       0 print "Connecting... " if $verb;
1206 0         0 for (1..$par) {
1207 0         0 print "$_ ";
1208 0   0     0 push @cons, ($drh->connect($dsn,$dbuser,$dbpass)
1209             or Carp::croak("connect failed: $DBI::errstr\n"));
1210             }
1211 0 0       0 print "\nDisconnecting...\n" if $verb;
1212 0         0 for (@cons) {
1213 0 0       0 $_->disconnect or warn "disconnect failed: $DBI::errstr"
1214             }
1215             }
1216 0         0 my $t2 = dbi_time();
1217 0         0 my $td = $t2 - $t1;
1218 0         0 printf "$meth %d and disconnect them, %d times: %.4fs / %d = %.4fs\n",
1219             $par, $loops, $td, $loops*$par, $td/($loops*$par);
1220 0         0 return $td;
1221             }
1222              
1223              
1224             # Help people doing DBI->errstr, might even document it one day
1225             # XXX probably best moved to cheaper XS code if this gets documented
1226 0     0 1 0 sub err { $DBI::err }
1227 0     0 1 0 sub errstr { $DBI::errstr }
1228              
1229              
1230             # --- Private Internal Function for Creating New DBI Handles
1231              
1232             # XXX move to PurePerl?
1233             *DBI::dr::TIEHASH = \&DBI::st::TIEHASH;
1234             *DBI::db::TIEHASH = \&DBI::st::TIEHASH;
1235              
1236              
1237             # These three special constructors are called by the drivers
1238             # The way they are called is likely to change.
1239              
1240             our $shared_profile;
1241              
1242             sub _new_drh { # called by DBD::::driver()
1243 238     238   1850 my ($class, $initial_attr, $imp_data) = @_;
1244             # Provide default storage for State,Err and Errstr.
1245             # Note that these are shared by all child handles by default! XXX
1246             # State must be undef to get automatic faking in DBI::var::FETCH
1247 238         692 my ($h_state_store, $h_err_store, $h_errstr_store) = (undef, undef, '');
1248 238         1864 my $attr = {
1249             # these attributes get copied down to child handles by default
1250             'State' => \$h_state_store, # Holder for DBI::state
1251             'Err' => \$h_err_store, # Holder for DBI::err
1252             'Errstr' => \$h_errstr_store, # Holder for DBI::errstr
1253             'TraceLevel' => 0,
1254             FetchHashKeyName=> 'NAME',
1255             %$initial_attr,
1256             };
1257 238         3831 my ($h, $i) = _new_handle('DBI::dr', '', $attr, $imp_data, $class);
1258              
1259             # XXX DBI_PROFILE unless DBI::PurePerl because for some reason
1260             # it kills the t/zz_*_pp.t tests (they silently exit early)
1261 238 100 66     2124 if (($ENV{DBI_PROFILE} && !$DBI::PurePerl) || $shared_profile) {
      66        
1262             # The profile object created here when the first driver is loaded
1263             # is shared by all drivers so we end up with just one set of profile
1264             # data and thus the 'total time in DBI' is really the true total.
1265 3 100       11 if (!$shared_profile) { # first time
1266 2         176 $h->{Profile} = $ENV{DBI_PROFILE}; # write string
1267 2         21 $shared_profile = $h->{Profile}; # read and record object
1268             }
1269             else {
1270 1         14 $h->{Profile} = $shared_profile;
1271             }
1272             }
1273 238 100       830 return $h unless wantarray;
1274 194         734 ($h, $i);
1275             }
1276              
1277             sub _new_dbh { # called by DBD::::dr::connect()
1278 3854     3854   20028 my ($drh, $attr, $imp_data) = @_;
1279             my $imp_class = $drh->{ImplementorClass}
1280 3854 50       9460 or Carp::croak("DBI _new_dbh: $drh has no ImplementorClass");
1281 3854         9867 substr($imp_class,-4,4) = '::db';
1282 3854         7178 my $app_class = ref $drh;
1283 3854         6535 substr($app_class,-4,4) = '::db';
1284 3854   50     15677 $attr->{Err} ||= \my $err;
1285 3854   50     13821 $attr->{Errstr} ||= \my $errstr;
1286 3854   50     13811 $attr->{State} ||= \my $state;
1287 3854         55709 _new_handle($app_class, $drh, $attr, $imp_data, $imp_class);
1288             }
1289              
1290             sub _new_sth { # called by DBD::::db::prepare)
1291 7701     7701   13925 my ($dbh, $attr, $imp_data) = @_;
1292             my $imp_class = $dbh->{ImplementorClass}
1293 7701 50       17424 or Carp::croak("DBI _new_sth: $dbh has no ImplementorClass");
1294 7701         16347 substr($imp_class,-4,4) = '::st';
1295 7701         12868 my $app_class = ref $dbh;
1296 7701         10782 substr($app_class,-4,4) = '::st';
1297 7701         101929 _new_handle($app_class, $dbh, $attr, $imp_data, $imp_class);
1298             }
1299              
1300              
1301             # end of DBI package
1302              
1303              
1304              
1305             # --------------------------------------------------------------------
1306             # === The internal DBI Switch pseudo 'driver' class ===
1307              
1308             { package # hide from PAUSE
1309             DBD::Switch::dr;
1310             DBI->setup_driver('DBD::Switch'); # sets up @ISA
1311              
1312             $DBD::Switch::dr::imp_data_size = 0;
1313             $DBD::Switch::dr::imp_data_size = 0; # avoid typo warning
1314             my $drh;
1315              
1316             sub driver {
1317 4 50   4   19 return $drh if $drh; # a package global
1318              
1319 4         12 my $inner;
1320 4         69 ($drh, $inner) = DBI::_new_drh('DBD::Switch::dr', {
1321             'Name' => 'Switch',
1322             'Version' => $DBI::VERSION,
1323             'Attribution' => "DBI $DBI::VERSION by Tim Bunce",
1324             });
1325 4 50 33     44 Carp::croak("DBD::Switch init failed!") unless ($drh && $inner);
1326 4         13 return $drh;
1327             }
1328             sub CLONE {
1329 0     0   0 undef $drh;
1330             }
1331              
1332             sub FETCH {
1333 26     26   4618 my($drh, $key) = @_;
1334 26 50       66 return DBI->trace if $key eq 'DebugDispatch';
1335 26 50       43 return undef if $key eq 'DebugLog'; # not worth fetching, sorry
1336 26         142 return $drh->DBD::_::dr::FETCH($key);
1337 0         0 undef;
1338             }
1339             sub STORE {
1340 20     20   5065 my($drh, $key, $value) = @_;
1341 20 100       67 if ($key eq 'DebugDispatch') {
    50          
1342 4         35 DBI->trace($value);
1343             } elsif ($key eq 'DebugLog') {
1344 0         0 DBI->trace(-1, $value);
1345             } else {
1346 16         167 $drh->DBD::_::dr::STORE($key, $value);
1347             }
1348             }
1349             }
1350              
1351              
1352             # --------------------------------------------------------------------
1353             # === OPTIONAL MINIMAL BASE CLASSES FOR DBI SUBCLASSES ===
1354              
1355             # We only define default methods for harmless functions.
1356             # We don't, for example, define a DBD::_::st::prepare()
1357              
1358             { package # hide from PAUSE
1359             DBD::_::common; # ====== Common base class methods ======
1360 192     192   1660 use strict;
  192         456  
  192         134879  
1361              
1362             # methods common to all handle types:
1363              
1364             # generic TIEHASH default methods:
1365       60     sub FIRSTKEY { }
1366       0     sub NEXTKEY { }
1367 122     122   20743 sub EXISTS { defined($_[0]->FETCH($_[1])) } # XXX undef?
1368 0     0   0 sub CLEAR { Carp::carp "Can't CLEAR $_[0] (DBI)" }
1369              
1370             sub FETCH_many { # XXX should move to C one day
1371 8268     8268   30974 my $h = shift;
1372             # scalar is needed to workaround drivers that return an empty list
1373             # for some attributes
1374 8268         13208 return map { scalar $h->FETCH($_) } @_;
  42764         151588  
1375             }
1376              
1377             *dump_handle = \&DBI::dump_handle;
1378              
1379             sub install_method {
1380             # special class method called directly by apps and/or drivers
1381             # to install new methods into the DBI dispatcher
1382             # DBD::Foo::db->install_method("foo_mumble", { usage => [...], options => '...' });
1383 616     616   1583 my ($class, $method, $attr) = @_;
1384 616 50       3700 Carp::croak("Class '$class' must begin with DBD:: and end with ::db or ::st")
1385             unless $class =~ /^DBD::(\w+)::(dr|db|st)$/;
1386 616         2020 my ($driver, $subtype) = ($1, $2);
1387 616 50       2465 Carp::croak("invalid method name '$method'")
1388             unless $method =~ m/^([a-z][a-z0-9]*_)\w+$/;
1389 616         1182 my $prefix = $1;
1390 616         1550 my $reg_info = $dbd_prefix_registry->{$prefix};
1391 616 50       1399 Carp::carp("method name prefix '$prefix' is not associated with a registered driver") unless $reg_info;
1392              
1393 616         1380 my $full_method = "DBI::${subtype}::$method";
1394 616         1467 $DBI::installed_methods{$full_method} = $attr;
1395              
1396 616         1912 my (undef, $filename, $line) = caller;
1397             # XXX reformat $attr as needed for _install_method
1398 616 100       1008 my %attr = %{$attr||{}}; # copy so we can edit
  616         2686  
1399 616         6108 DBI->_install_method("DBI::${subtype}::$method", "$filename at line $line", \%attr);
1400             }
1401              
1402             sub parse_trace_flags {
1403 80     80   10158 my ($h, $spec) = @_;
1404 80         147 my $level = 0;
1405 80         138 my $flags = 0;
1406 80         123 my @unknown;
1407 80         438 for my $word (split /\s*[|&,]\s*/, $spec) {
1408 124 50 33     875 if (DBI::looks_like_number($word) && $word <= 0xF && $word >= 0) {
    100 33        
    100          
1409 0         0 $level = $word;
1410             } elsif ($word eq 'ALL') {
1411 4         14 $flags = 0x7FFFFFFF; # XXX last bit causes negative headaches
1412 4         13 last;
1413             } elsif (my $flag = $h->parse_trace_flag($word)) {
1414 108         626 $flags |= $flag;
1415             }
1416             else {
1417 12         97 push @unknown, $word;
1418             }
1419             }
1420 80 50 66     349 if (@unknown && (ref $h ? $h->FETCH('Warn') : 1)) {
    50          
1421             Carp::carp("$h->parse_trace_flags($spec) ignored unknown trace flags: ".
1422 8         89 join(" ", map { DBI::neat($_) } @unknown));
  12         777  
1423             }
1424 80         689 $flags |= $level;
1425 80         469 return $flags;
1426             }
1427              
1428             sub parse_trace_flag {
1429 96     96   189 my ($h, $name) = @_;
1430             # 0xddDDDDrL (driver, DBI, reserved, Level)
1431 96 100       307 return 0x00000100 if $name eq 'SQL';
1432 72 100       205 return 0x00000200 if $name eq 'CON';
1433 58 100       168 return 0x00000400 if $name eq 'ENC';
1434 44 100       136 return 0x00000800 if $name eq 'DBD';
1435 30 100       104 return 0x00001000 if $name eq 'TXN';
1436 16         192 return;
1437             }
1438              
1439             sub private_attribute_info {
1440 3668     3668   37835 return undef;
1441             }
1442              
1443             sub visit_child_handles {
1444 28     28   350 my ($h, $code, $info) = @_;
1445 28 50       62 $info = {} if not defined $info;
1446 28 100       44 for my $ch (@{ $h->{ChildHandles} || []}) {
  28         104  
1447 384 100       666 next unless $ch;
1448 16 50       40 my $child_info = $code->($ch, $info)
1449             or next;
1450 16         477 $ch->visit_child_handles($code, $child_info);
1451             }
1452 28         130 return $info;
1453             }
1454             }
1455              
1456              
1457             { package # hide from PAUSE
1458             DBD::_::dr; # ====== DRIVER ======
1459             @DBD::_::dr::ISA = qw(DBD::_::common);
1460 192     192   1474 use strict;
  192         394  
  192         73430  
1461              
1462             sub default_user {
1463 1608     1608   51454 my ($drh, $user, $pass, $attr) = @_;
1464 1608 100       4719 $user = $ENV{DBI_USER} unless defined $user;
1465 1608 100       3957 $pass = $ENV{DBI_PASS} unless defined $pass;
1466 1608         5067 return ($user, $pass);
1467             }
1468              
1469             sub connect { # normally overridden, but a handy default
1470 118     118   5775 my ($drh, $dsn, $user, $auth) = @_;
1471 118         504 my ($this) = DBI::_new_dbh($drh, {
1472             'Name' => $dsn,
1473             });
1474             # XXX debatable as there's no "server side" here
1475             # (and now many uses would trigger warnings on DESTROY)
1476             # $this->STORE(Active => 1);
1477             # so drivers should set it in their own connect
1478 118         662 $this;
1479             }
1480              
1481              
1482             sub connect_cached {
1483 3146     3146   7658 my $drh = shift;
1484 3146         5523 my ($dsn, $user, $auth, $attr) = @_;
1485              
1486 3146   100     6734 my $cache = $drh->{CachedKids} ||= {};
1487 3146         3421 my $key = do { local $^W;
  3146         9236  
1488 3146         41957 join "!\001", $dsn, $user, $auth, DBI::_concat_hash_sorted($attr, "=\001", ",\001", 0, 0)
1489             };
1490 3146         6750 my $dbh = $cache->{$key};
1491 3146 50       6245 $drh->trace_msg(sprintf(" connect_cached: key '$key', cached dbh $dbh\n", DBI::neat($key), DBI::neat($dbh)))
1492             if (($DBI::dbi_debug & 0xF) >= 4);
1493              
1494 3146         4963 my $cb = $attr->{Callbacks}; # take care not to autovivify
1495 3146 50 66     16372 if ($dbh && $dbh->FETCH('Active') && eval { $dbh->ping }) {
  3114   66     11336  
1496             # If the caller has provided a callback then call it
1497 3114 100 66     7166 if ($cb and $cb = $cb->{"connect_cached.reused"}) {
1498 2         4 local $_ = "connect_cached.reused";
1499 2         7 $cb->($dbh, $dsn, $user, $auth, $attr);
1500             }
1501 3114         15542 return $dbh;
1502             }
1503              
1504             # If the caller has provided a callback then call it
1505 32 100 66     114 if ($cb and (my $new_cb = $cb->{"connect_cached.new"})) {
1506 2         4 local $_ = "connect_cached.new";
1507 2         6 $new_cb->($dbh, $dsn, $user, $auth, $attr); # $dbh is dead or undef
1508             }
1509              
1510 32         3020 $dbh = $drh->connect(@_);
1511 32         264 $cache->{$key} = $dbh; # replace prev entry, even if connect failed
1512 32 100 66     119 if ($cb and (my $conn_cb = $cb->{"connect_cached.connected"})) {
1513 2         4 local $_ = "connect_cached.connected";
1514 2         8 $conn_cb->($dbh, $dsn, $user, $auth, $attr);
1515             }
1516 32         3393 return $dbh;
1517             }
1518              
1519             }
1520              
1521              
1522             { package # hide from PAUSE
1523             DBD::_::db; # ====== DATABASE ======
1524             @DBD::_::db::ISA = qw(DBD::_::common);
1525 192     192   1337 use strict;
  192         1405  
  192         363447  
1526              
1527             sub clone {
1528 16     16   22084 my ($old_dbh, $attr) = @_;
1529              
1530             my $closure = $old_dbh->{dbi_connect_closure}
1531 16 50       54 or return $old_dbh->set_err($DBI::stderr, "Can't clone handle");
1532              
1533 16 100       34 unless ($attr) { # XXX deprecated, caller should always pass a hash ref
1534             # copy attributes visible in the attribute cache
1535 8         22 keys %$old_dbh; # reset iterator
1536 8         34 while ( my ($k, $v) = each %$old_dbh ) {
1537             # ignore non-code refs, i.e., caches, handles, Err etc
1538 198 100 100     433 next if ref $v && ref $v ne 'CODE'; # HandleError etc
1539 158         384 $attr->{$k} = $v;
1540             }
1541             # explicitly set attributes which are unlikely to be in the
1542             # attribute cache, i.e., boolean's and some others
1543 8         52 $attr->{$_} = $old_dbh->FETCH($_) for (qw(
1544             AutoCommit ChopBlanks InactiveDestroy AutoInactiveDestroy
1545             LongTruncOk PrintError PrintWarn Profile RaiseError
1546             ShowErrorStatement TaintIn TaintOut
1547             ));
1548             }
1549              
1550             # use Data::Dumper; warn Dumper([$old_dbh, $attr]);
1551 16         220 my $new_dbh = &$closure($old_dbh, $attr);
1552 16 50       43 unless ($new_dbh) {
1553             # need to copy err/errstr from driver back into $old_dbh
1554 0         0 my $drh = $old_dbh->{Driver};
1555 0         0 return $old_dbh->set_err($drh->err, $drh->errstr, $drh->state);
1556             }
1557 16         54 $new_dbh->{dbi_connect_closure} = $closure;
1558 16         115 return $new_dbh;
1559             }
1560              
1561             sub quote_identifier {
1562 114     114   5669 my ($dbh, @id) = @_;
1563 114 50 33     279 my $attr = (@id > 3 && ref($id[-1])) ? pop @id : undef;
1564              
1565             my $info = $dbh->{dbi_quote_identifier_cache} ||= [
1566 114   50     324 $dbh->get_info(29) || '"', # SQL_IDENTIFIER_QUOTE_CHAR
      100        
      100        
      100        
1567             $dbh->get_info(41) || '.', # SQL_CATALOG_NAME_SEPARATOR
1568             $dbh->get_info(114) || 1, # SQL_CATALOG_LOCATION
1569             ];
1570              
1571 114         263 my $quote = $info->[0];
1572 114         179 foreach (@id) { # quote the elements
1573 322 100       506 next unless defined;
1574 208         470 s/$quote/$quote$quote/g; # escape embedded quotes
1575 208         346 $_ = qq{$quote$_$quote};
1576             }
1577              
1578             # strip out catalog if present for special handling
1579 114 100       218 my $catalog = (@id >= 3) ? shift @id : undef;
1580              
1581             # join the dots, ignoring any null/undef elements (ie schema)
1582 114         180 my $quoted_id = join '.', grep { defined } @id;
  220         462  
1583              
1584 114 100       191 if ($catalog) { # add catalog correctly
1585 78 100       120 if ($quoted_id) {
1586 70 100       154 $quoted_id = ($info->[2] == 2) # SQL_CL_END
1587             ? $quoted_id . $info->[1] . $catalog
1588             : $catalog . $info->[1] . $quoted_id;
1589             } else {
1590 8         11 $quoted_id = $catalog;
1591             }
1592             }
1593 114         327 return $quoted_id;
1594             }
1595              
1596             sub quote {
1597 16     16   2585 my ($dbh, $str, $data_type) = @_;
1598              
1599 16 100       51 return "NULL" unless defined $str;
1600 12 100       27 unless ($data_type) {
1601 4         20 $str =~ s/'/''/g; # ISO SQL2
1602 4         21 return "'$str'";
1603             }
1604              
1605 8   100     44 my $dbi_literal_quote_cache = $dbh->{'dbi_literal_quote_cache'} ||= [ {} , {} ];
1606 8         18 my ($prefixes, $suffixes) = @$dbi_literal_quote_cache;
1607              
1608 8         17 my $lp = $prefixes->{$data_type};
1609 8         13 my $ls = $suffixes->{$data_type};
1610              
1611 8 50 33     25 if ( ! defined $lp || ! defined $ls ) {
1612 8         37 my $ti = $dbh->type_info($data_type);
1613 8 50 100     80 $lp = $prefixes->{$data_type} = $ti ? $ti->{LITERAL_PREFIX} || "" : "'";
1614 8 50 100     51 $ls = $suffixes->{$data_type} = $ti ? $ti->{LITERAL_SUFFIX} || "" : "'";
1615             }
1616 8 100 66     39 return $str unless $lp || $ls; # no quoting required
1617              
1618             # XXX don't know what the standard says about escaping
1619             # in the 'general case' (where $lp != "'").
1620             # So we just do this and hope:
1621 4 50 33     88 $str =~ s/$lp/$lp$lp/g
      33        
      33        
1622             if $lp && $lp eq $ls && ($lp eq "'" || $lp eq '"');
1623 4         29 return "$lp$str$ls";
1624             }
1625              
1626 0     0   0 sub rows { -1 } # here so $DBI::rows 'works' after using $dbh
1627              
1628             sub do {
1629 1675     1675   28204 my($dbh, $statement, $attr, @params) = @_;
1630 1675 100       6079 my $sth = $dbh->prepare($statement, $attr) or return undef;
1631 1671 100       8550 $sth->execute(@params) or return undef;
1632 202         2429 my $rows = $sth->rows;
1633 202 100       2324 ($rows == 0) ? "0E0" : $rows;
1634             }
1635              
1636             sub _do_selectrow {
1637 16     16   62 my ($method, $dbh, $stmt, $attr, @bind) = @_;
1638 16 50       138 my $sth = ((ref $stmt) ? $stmt : $dbh->prepare($stmt, $attr))
    50          
1639             or return undef;
1640 16 100       215 $sth->execute(@bind)
1641             or return undef;
1642 8 50       133 my $row = $sth->$method()
1643             and $sth->finish;
1644 8         125 return $row;
1645             }
1646              
1647 4     4   3281 sub selectrow_hashref { return _do_selectrow('fetchrow_hashref', @_); }
1648              
1649             # XXX selectrow_array/ref also have C implementations in Driver.xst
1650 8     8   236 sub selectrow_arrayref { return _do_selectrow('fetchrow_arrayref', @_); }
1651             sub selectrow_array {
1652 4 50   4   1868 my $row = _do_selectrow('fetchrow_arrayref', @_) or return;
1653 4 50       83 return $row->[0] unless wantarray;
1654 4         27 return @$row;
1655             }
1656              
1657             sub selectall_array {
1658 4 50   4   9154 return @{ shift->selectall_arrayref(@_) || [] };
  4         22  
1659             }
1660              
1661             # XXX selectall_arrayref also has C implementation in Driver.xst
1662             # which fallsback to this if a slice is given
1663             sub selectall_arrayref {
1664 126     126   53358 my ($dbh, $stmt, $attr, @bind) = @_;
1665 126 100       1102 my $sth = (ref $stmt) ? $stmt : $dbh->prepare($stmt, $attr)
    100          
1666             or return;
1667 122 50       1864 $sth->execute(@bind) || return;
1668 122         1700 my $slice = $attr->{Slice}; # typically undef, else hash or array ref
1669 122 100 100     974 if (!$slice and $slice=$attr->{Columns}) {
1670 8 100       31 if (ref $slice eq 'ARRAY') { # map col idx to perl array idx
1671 4         10 $slice = [ @{$attr->{Columns}} ]; # take a copy
  4         15  
1672 4         10 for (@$slice) { $_-- }
  8         15  
1673             }
1674             }
1675 122         750 my $rows = $sth->fetchall_arrayref($slice, my $MaxRows = $attr->{MaxRows});
1676 122 50       1016 $sth->finish if defined $MaxRows;
1677 122         1619 return $rows;
1678             }
1679              
1680             sub selectall_hashref {
1681 8     8   14678 my ($dbh, $stmt, $key_field, $attr, @bind) = @_;
1682 8 50       60 my $sth = (ref $stmt) ? $stmt : $dbh->prepare($stmt, $attr);
1683 8 50       82 return unless $sth;
1684 8 50       50 $sth->execute(@bind) || return;
1685 8         136 return $sth->fetchall_hashref($key_field);
1686             }
1687              
1688             sub selectcol_arrayref {
1689 8     8   7567 my ($dbh, $stmt, $attr, @bind) = @_;
1690 8 50       64 my $sth = (ref $stmt) ? $stmt : $dbh->prepare($stmt, $attr);
1691 8 50       81 return unless $sth;
1692 8 50       40 $sth->execute(@bind) || return;
1693 8 100       91 my @columns = ($attr->{Columns}) ? @{$attr->{Columns}} : (1);
  4         13  
1694 8         23 my @values = (undef) x @columns;
1695 8         16 my $idx = 0;
1696 8         17 for (@columns) {
1697 12 50       82 $sth->bind_col($_, \$values[$idx++]) || return;
1698             }
1699 8         49 my @col;
1700 8 50       21 if (my $max = $attr->{MaxRows}) {
1701 0   0     0 push @col, @values while 0 < $max-- && $sth->fetch;
1702             }
1703             else {
1704 8         31 push @col, @values while $sth->fetch;
1705             }
1706 8         113 return \@col;
1707             }
1708              
1709             sub prepare_cached {
1710 48     48   9438 my ($dbh, $statement, $attr, $if_active) = @_;
1711              
1712             # Needs support at dbh level to clear cache before complaining about
1713             # active children. The XS template code does this. Drivers not using
1714             # the template must handle clearing the cache themselves.
1715 48   100     169 my $cache = $dbh->{CachedKids} ||= {};
1716 48         65 my $key = do { local $^W;
  48         144  
1717 48         216 join "!\001", $statement, DBI::_concat_hash_sorted($attr, "=\001", ",\001", 0, 0)
1718             };
1719 48         83 my $sth = $cache->{$key};
1720              
1721 48 100       89 if ($sth) {
1722 12 50       47 return $sth unless $sth->FETCH('Active');
1723 12 100 100     750 Carp::carp("prepare_cached($statement) statement handle $sth still Active")
1724             unless ($if_active ||= 0);
1725 12 100       253 $sth->finish if $if_active <= 1;
1726 12 100       74 return $sth if $if_active <= 2;
1727             }
1728              
1729 40         154 $sth = $dbh->prepare($statement, $attr);
1730 40 50       355 $cache->{$key} = $sth if $sth;
1731              
1732 40         112 return $sth;
1733             }
1734              
1735             sub ping {
1736 12     12   2507 my $dbh = shift;
1737             # "0 but true" is a special kind of true 0 that is used here so
1738             # applications can check if the ping was a real ping or not
1739 12 100       50 ($dbh->FETCH('Active')) ? "0 but true" : 0;
1740             }
1741              
1742             sub begin_work {
1743 4     4   2117 my $dbh = shift;
1744 4 50       13 return $dbh->set_err($DBI::stderr, "Already in a transaction")
1745             unless $dbh->FETCH('AutoCommit');
1746 4         31 $dbh->STORE('AutoCommit', 0); # will croak if driver doesn't support it
1747 4         24 $dbh->STORE('BegunWork', 1); # trigger post commit/rollback action
1748 4         23 return 1;
1749             }
1750              
1751             sub primary_key {
1752 0     0   0 my ($dbh, @args) = @_;
1753 0 0       0 my $sth = $dbh->primary_key_info(@args) or return;
1754 0         0 my ($row, @col);
1755 0         0 push @col, $row->[3] while ($row = $sth->fetch);
1756 0 0       0 Carp::croak("primary_key method not called in list context")
1757             unless wantarray; # leave us some elbow room
1758 0         0 return @col;
1759             }
1760              
1761             sub tables {
1762 32     32   5080 my ($dbh, @args) = @_;
1763 32 50       160 my $sth = $dbh->table_info(@args[0,1,2,3,4]) or return;
1764 32 50       391 my $tables = $sth->fetchall_arrayref or return;
1765 32         276 my @tables;
1766 32 100 100     291 if (defined($args[3]) && $args[3] eq '%' # special case for tables('','','','%')
    100 66        
1767 12 50       46 && grep {defined($_) && $_ eq ''} @args[0,1,2]
1768             ) {
1769 4         11 @tables = map { $_->[3] } @$tables;
  12         22  
1770             } elsif ($dbh->get_info(29)) { # SQL_IDENTIFIER_QUOTE_CHAR
1771 16         118 @tables = map { $dbh->quote_identifier( @{$_}[0,1,2] ) } @$tables;
  92         439  
  92         245  
1772             }
1773             else { # temporary old style hack (yeach)
1774             @tables = map {
1775 12         340 my $name = $_->[2];
  16         33  
1776 16 50       37 if ($_->[1]) {
1777 16         28 my $schema = $_->[1];
1778             # a sad hack (mostly for Informix I recall)
1779 16 50       51 my $quote = ($schema eq uc($schema)) ? '' : '"';
1780 16         49 $name = "$quote$schema$quote.$name"
1781             }
1782 16         42 $name;
1783             } @$tables;
1784             }
1785 32         466 return @tables;
1786             }
1787              
1788             sub type_info { # this should be sufficient for all drivers
1789 28     28   7611 my ($dbh, $data_type) = @_;
1790 28         40 my $idx_hash;
1791 28         44 my $tia = $dbh->{dbi_type_info_row_cache};
1792 28 100       68 if ($tia) {
1793 18         27 $idx_hash = $dbh->{dbi_type_info_idx_cache};
1794             }
1795             else {
1796 10         50 my $temp = $dbh->type_info_all;
1797 10 50 33     103 return unless $temp && @$temp;
1798             # we cache here because type_info_all may be expensive to call
1799             # (and we take a copy so the following shift can't corrupt
1800             # the data that may be returned by future calls to type_info_all)
1801 10         36 $tia = $dbh->{dbi_type_info_row_cache} = [ @$temp ];
1802 10         34 $idx_hash = $dbh->{dbi_type_info_idx_cache} = shift @$tia;
1803             }
1804              
1805 28   33     98 my $dt_idx = $idx_hash->{DATA_TYPE} || $idx_hash->{data_type};
1806 28 50 33     113 Carp::croak("type_info_all returned non-standard DATA_TYPE index value ($dt_idx != 1)")
1807             if $dt_idx && $dt_idx != 1;
1808              
1809             # --- simple DATA_TYPE match filter
1810 28         37 my @ti;
1811 28 50       70 my @data_type_list = (ref $data_type) ? @$data_type : ($data_type);
1812 28         50 foreach $data_type (@data_type_list) {
1813 28 100 66     109 if (defined($data_type) && $data_type != DBI::SQL_ALL_TYPES()) {
1814 24         48 push @ti, grep { $_->[$dt_idx] == $data_type } @$tia;
  48         120  
1815             }
1816             else { # SQL_ALL_TYPES
1817 4         10 push @ti, @$tia;
1818             }
1819 28 50       72 last if @ti; # found at least one match
1820             }
1821              
1822             # --- format results into list of hash refs
1823 28         59 my $idx_fields = keys %$idx_hash;
1824 28         88 my @idx_names = map { uc($_) } keys %$idx_hash;
  420         682  
1825 28         104 my @idx_values = values %$idx_hash;
1826 0         0 Carp::croak "type_info_all result has $idx_fields keys but ".(@{$ti[0]})." fields"
1827 28 50 33     76 if @ti && @{$ti[0]} != $idx_fields;
  28         83  
1828             my @out = map {
1829 28         52 my %h; @h{@idx_names} = @{$_}[ @idx_values ]; \%h;
  32         44  
  32         41  
  32         207  
  32         82  
1830             } @ti;
1831 28 100       172 return $out[0] unless wantarray;
1832 4         24 return @out;
1833             }
1834              
1835             sub data_sources {
1836 4     4   3658 my ($dbh, @other) = @_;
1837 4         12 my $drh = $dbh->{Driver}; # XXX proxy issues?
1838 4         18 return $drh->data_sources(@other);
1839             }
1840              
1841             }
1842              
1843              
1844             { package # hide from PAUSE
1845             DBD::_::st; # ====== STATEMENT ======
1846             @DBD::_::st::ISA = qw(DBD::_::common);
1847 192     192   1620 use strict;
  192         424  
  192         346914  
1848              
1849 0     0   0 sub bind_param { Carp::croak("Can't bind_param, not implement by driver") }
1850              
1851             #
1852             # ********************************************************
1853             #
1854             # BEGIN ARRAY BINDING
1855             #
1856             # Array binding support for drivers which don't support
1857             # array binding, but have sufficient interfaces to fake it.
1858             # NOTE: mixing scalars and arrayrefs requires using bind_param_array
1859             # for *all* params...unless we modify bind_param for the default
1860             # case...
1861             #
1862             # 2002-Apr-10 D. Arnold
1863              
1864             sub bind_param_array {
1865 84     84   10835 my $sth = shift;
1866 84         135 my ($p_id, $value_array, $attr) = @_;
1867              
1868 84 100 100     351 return $sth->set_err($DBI::stderr, "Value for parameter $p_id must be a scalar or an arrayref, not a ".ref($value_array))
      100        
1869             if defined $value_array and ref $value_array and ref $value_array ne 'ARRAY';
1870              
1871 80 100       236 return $sth->set_err($DBI::stderr, "Can't use named placeholder '$p_id' for non-driver supported bind_param_array")
1872             unless DBI::looks_like_number($p_id); # because we rely on execute(@ary) here
1873              
1874 76 50       128 return $sth->set_err($DBI::stderr, "Placeholder '$p_id' is out of range")
1875             if $p_id <= 0; # can't easily/reliably test for too big
1876              
1877             # get/create arrayref to hold params
1878 76   50     157 my $hash_of_arrays = $sth->{ParamArrays} ||= { };
1879              
1880             # If the bind has attribs then we rely on the driver conforming to
1881             # the DBI spec in that a single bind_param() call with those attribs
1882             # makes them 'sticky' and apply to all later execute(@values) calls.
1883             # Since we only call bind_param() if we're given attribs then
1884             # applications using drivers that don't support bind_param can still
1885             # use bind_param_array() so long as they don't pass any attribs.
1886              
1887 76         129 $$hash_of_arrays{$p_id} = $value_array;
1888 76 50       112 return $sth->bind_param($p_id, undef, $attr)
1889             if $attr;
1890 76         197 1;
1891             }
1892              
1893             sub bind_param_inout_array {
1894 0     0   0 my $sth = shift;
1895             # XXX not supported so we just call bind_param_array instead
1896             # and then return an error
1897 0         0 my ($p_num, $value_array, $attr) = @_;
1898 0         0 $sth->bind_param_array($p_num, $value_array, $attr);
1899 0         0 return $sth->set_err($DBI::stderr, "bind_param_inout_array not supported");
1900             }
1901              
1902             sub bind_columns {
1903 116     116   19414 my $sth = shift;
1904 116   50     517 my $fields = $sth->FETCH('NUM_OF_FIELDS') || 0;
1905 116 50 33     1088 if ($fields <= 0 && !$sth->{Active}) {
1906 0         0 return $sth->set_err($DBI::stderr, "Statement has no result columns to bind"
1907             ." (perhaps you need to successfully call execute first, or again)");
1908             }
1909             # Backwards compatibility for old-style call with attribute hash
1910             # ref as first arg. Skip arg if undef or a hash ref.
1911 116         210 my $attr;
1912 116 100 66     806 $attr = shift if !defined $_[0] or ref($_[0]) eq 'HASH';
1913              
1914 116         230 my $idx = 0;
1915 116   100     1627 $sth->bind_col(++$idx, shift, $attr) or return
      50        
1916             while (@_ and $idx < $fields);
1917              
1918 116 100 100     1299 return $sth->set_err($DBI::stderr, "bind_columns called with ".($idx+@_)." values but $fields are needed")
1919             if @_ or $idx != $fields;
1920              
1921 108         302 return 1;
1922             }
1923              
1924             sub execute_array {
1925 48     48   35290 my $sth = shift;
1926 48         102 my ($attr, @array_of_arrays) = @_;
1927 48         158 my $NUM_OF_PARAMS = $sth->FETCH('NUM_OF_PARAMS'); # may be undef at this point
1928              
1929             # get tuple status array or hash attribute
1930 48         278 my $tuple_sts = $attr->{ArrayTupleStatus};
1931 48 100 100     238 return $sth->set_err($DBI::stderr, "ArrayTupleStatus attribute must be an arrayref")
1932             if $tuple_sts and ref $tuple_sts ne 'ARRAY';
1933              
1934             # bind all supplied arrays
1935 44 100       97 if (@array_of_arrays) {
1936 28         71 $sth->{ParamArrays} = { }; # clear out old params
1937 28 100 66     169 return $sth->set_err($DBI::stderr,
1938             @array_of_arrays." bind values supplied but $NUM_OF_PARAMS expected")
1939             if defined ($NUM_OF_PARAMS) && @array_of_arrays != $NUM_OF_PARAMS;
1940             $sth->bind_param_array($_, $array_of_arrays[$_-1]) or return
1941 24   100     136 foreach (1..@array_of_arrays);
1942             }
1943              
1944 36         129 my $fetch_tuple_sub;
1945              
1946 36 100       77 if ($fetch_tuple_sub = $attr->{ArrayTupleFetch}) { # fetch on demand
1947              
1948 8 50       25 return $sth->set_err($DBI::stderr,
1949             "Can't use both ArrayTupleFetch and explicit bind values")
1950             if @array_of_arrays; # previous bind_param_array calls will simply be ignored
1951              
1952 8 100       41 if (UNIVERSAL::isa($fetch_tuple_sub,'DBI::st')) {
    50          
1953 4         10 my $fetch_sth = $fetch_tuple_sub;
1954             return $sth->set_err($DBI::stderr,
1955             "ArrayTupleFetch sth is not Active, need to execute() it first")
1956 4 50       25 unless $fetch_sth->{Active};
1957             # check column count match to give more friendly message
1958 4         37 my $NUM_OF_FIELDS = $fetch_sth->{NUM_OF_FIELDS};
1959 4 50 33     61 return $sth->set_err($DBI::stderr,
      33        
1960             "$NUM_OF_FIELDS columns from ArrayTupleFetch sth but $NUM_OF_PARAMS expected")
1961             if defined($NUM_OF_FIELDS) && defined($NUM_OF_PARAMS)
1962             && $NUM_OF_FIELDS != $NUM_OF_PARAMS;
1963 4     16   20 $fetch_tuple_sub = sub { $fetch_sth->fetchrow_arrayref };
  16         54  
1964             }
1965             elsif (!UNIVERSAL::isa($fetch_tuple_sub,'CODE')) {
1966 0         0 return $sth->set_err($DBI::stderr, "ArrayTupleFetch '$fetch_tuple_sub' is not a code ref or statement handle");
1967             }
1968              
1969             }
1970             else {
1971 28 50       36 my $NUM_OF_PARAMS_given = keys %{ $sth->{ParamArrays} || {} };
  28         84  
1972 28 50 33     103 return $sth->set_err($DBI::stderr,
1973             "$NUM_OF_PARAMS_given bind values supplied but $NUM_OF_PARAMS expected")
1974             if defined($NUM_OF_PARAMS) && $NUM_OF_PARAMS != $NUM_OF_PARAMS_given;
1975              
1976             # get the length of a bound array
1977 28         38 my $maxlen;
1978 28         37 my %hash_of_arrays = %{$sth->{ParamArrays}};
  28         104  
1979 28         85 foreach (keys(%hash_of_arrays)) {
1980 100         123 my $ary = $hash_of_arrays{$_};
1981 100 100       182 next unless ref $ary eq 'ARRAY';
1982 48 100 66     136 $maxlen = @$ary if !$maxlen || @$ary > $maxlen;
1983             }
1984             # if there are no arrays then execute scalars once
1985 28 100       73 $maxlen = 1 unless defined $maxlen;
1986 28         74 my @bind_ids = 1..keys(%hash_of_arrays);
1987              
1988 28         39 my $tuple_idx = 0;
1989             $fetch_tuple_sub = sub {
1990 68 100   68   176 return if $tuple_idx >= $maxlen;
1991             my @tuple = map {
1992 40         58 my $a = $hash_of_arrays{$_};
  160         205  
1993 160 100       299 ref($a) ? $a->[$tuple_idx] : $a
1994             } @bind_ids;
1995 40         53 ++$tuple_idx;
1996 40         86 return \@tuple;
1997 28         136 };
1998             }
1999             # pass thru the callers scalar or list context
2000 36         143 return $sth->execute_for_fetch($fetch_tuple_sub, $tuple_sts);
2001             }
2002              
2003             sub execute_for_fetch {
2004 36     36   588 my ($sth, $fetch_tuple_sub, $tuple_status) = @_;
2005             # start with empty status array
2006 36 100       107 ($tuple_status) ? @$tuple_status = () : $tuple_status = [];
2007              
2008 36         56 my $rc_total = 0;
2009 36         45 my $err_count;
2010 36         57 while ( my $tuple = &$fetch_tuple_sub() ) {
2011 60 100       353 if ( my $rc = $sth->execute(@$tuple) ) {
2012 56         289 push @$tuple_status, $rc;
2013 56 50 33     233 $rc_total = ($rc >= 0 && $rc_total >= 0) ? $rc_total + $rc : -1;
2014             }
2015             else {
2016 4         100 $err_count++;
2017 4         66 push @$tuple_status, [ $sth->err, $sth->errstr, $sth->state ];
2018             # XXX drivers implementing execute_for_fetch could opt to "last;" here
2019             # if they know the error code means no further executes will work.
2020             }
2021             }
2022 36         83 my $tuples = @$tuple_status;
2023 36 100       139 return $sth->set_err($DBI::stderr, "executing $tuples generated $err_count errors")
2024             if $err_count;
2025 32   100     98 $tuples ||= "0E0";
2026 32 100       162 return $tuples unless wantarray;
2027 4         23 return ($tuples, $rc_total);
2028             }
2029              
2030              
2031             sub fetchall_arrayref { # ALSO IN Driver.xst
2032 2358     2358   27289 my ($sth, $slice, $max_rows) = @_;
2033              
2034             # when batch fetching with $max_rows were very likely to try to
2035             # fetch the 'next batch' after the previous batch returned
2036             # <=$max_rows. So don't treat that as an error.
2037 2358 100 100     4959 return undef if $max_rows and not $sth->FETCH('Active');
2038              
2039 2354   100     6530 my $mode = ref($slice) || 'ARRAY';
2040 2354         2772 my @rows;
2041              
2042 2354 100       4147 if ($mode eq 'ARRAY') {
2043 2322         2533 my $row;
2044             # we copy the array here because fetch (currently) always
2045             # returns the same array ref. XXX
2046 2322 100 100     5860 if ($slice && @$slice) {
    100          
2047 16 100       97 $max_rows = -1 unless defined $max_rows;
2048 16   100     95 push @rows, [ @{$row}[ @$slice] ]
  40         619  
2049             while($max_rows-- and $row = $sth->fetch);
2050             }
2051             elsif (defined $max_rows) {
2052 8   100     53 push @rows, [ @$row ]
2053             while($max_rows-- and $row = $sth->fetch);
2054             }
2055             else {
2056 2298         7340 push @rows, [ @$row ] while($row = $sth->fetch);
2057             }
2058             return \@rows
2059 2321         13187 }
2060              
2061 32         49 my %row;
2062 32 100 100     155 if ($mode eq 'REF' && ref($$slice) eq 'HASH') { # \{ $idx => $name }
    100          
2063 12         32 keys %$$slice; # reset the iterator
2064 12         52 while ( my ($idx, $name) = each %$$slice ) {
2065 12         119 $sth->bind_col($idx+1, \$row{$name});
2066             }
2067             }
2068             elsif ($mode eq 'HASH') {
2069 16 100       49 if (keys %$slice) { # resets the iterator
2070 12         57 my $name2idx = $sth->FETCH('NAME_lc_hash');
2071 12         102 while ( my ($name, $unused) = each %$slice ) {
2072 20         100 my $idx = $name2idx->{lc $name};
2073 20 100       91 return $sth->set_err($DBI::stderr, "Invalid column name '$name' for slice")
2074             if not defined $idx;
2075 16         93 $sth->bind_col($idx+1, \$row{$name});
2076             }
2077             }
2078             else {
2079 4         10 my @column_names = @{ $sth->FETCH($sth->FETCH('FetchHashKeyName')) };
  4         33  
2080 4 50       49 return [] if !@column_names;
2081              
2082 4         32 $sth->bind_columns( \( @row{@column_names} ) );
2083             }
2084             }
2085             else {
2086 4         60 return $sth->set_err($DBI::stderr, "fetchall_arrayref($mode) invalid");
2087             }
2088              
2089 20 50       120 if (not defined $max_rows) {
2090 20         79 push @rows, { %row } while ($sth->fetch); # full speed ahead!
2091             }
2092             else {
2093 0   0     0 push @rows, { %row } while ($max_rows-- and $sth->fetch);
2094             }
2095              
2096 20         169 return \@rows;
2097             }
2098              
2099             sub fetchall_hashref {
2100 96     96   26211 my ($sth, $key_field) = @_;
2101              
2102 96   50     509 my $hash_key_name = $sth->{FetchHashKeyName} || 'NAME';
2103 96         1125 my $names_hash = $sth->FETCH("${hash_key_name}_hash");
2104 96 100       937 my @key_fields = (ref $key_field) ? @$key_field : ($key_field);
2105 96         197 my @key_indexes;
2106 96         366 my $num_of_fields = $sth->FETCH('NUM_OF_FIELDS');
2107 96         792 foreach (@key_fields) {
2108 100         255 my $index = $names_hash->{$_}; # perl index not column
2109 100 50 66     473 $index = $_ - 1 if !defined $index && DBI::looks_like_number($_) && $_>=1 && $_ <= $num_of_fields;
      66        
      33        
2110 100 50       326 return $sth->set_err($DBI::stderr, "Field '$_' does not exist (not one of @{[keys %$names_hash]})")
  0         0  
2111             unless defined $index;
2112 100         308 push @key_indexes, $index;
2113             }
2114 96         213 my $rows = {};
2115 96         348 my $NAME = $sth->FETCH($hash_key_name);
2116 96         691 my @row = (undef) x $num_of_fields;
2117 96         869 $sth->bind_columns(\(@row));
2118 96         1016 while ($sth->fetch) {
2119 248         2584 my $ref = $rows;
2120 248   100     1542 $ref = $ref->{$row[$_]} ||= {} for @key_indexes;
2121 248         488 @{$ref}{@$NAME} = @row;
  248         1135  
2122             }
2123 96         980 return $rows;
2124             }
2125              
2126             *dump_results = \&DBI::dump_results;
2127              
2128             sub blob_copy_to_file { # returns length or undef on error
2129 0     0   0 my($self, $field, $filename_or_handleref, $blocksize) = @_;
2130 0         0 my $fh = $filename_or_handleref;
2131 0         0 my($len, $buf) = (0, "");
2132 0   0     0 $blocksize ||= 512; # not too ambitious
2133 0         0 local(*FH);
2134 0 0       0 unless(ref $fh) {
2135 0 0       0 open(FH, ">$fh") || return undef;
2136 0         0 $fh = \*FH;
2137             }
2138 0         0 while(defined($self->blob_read($field, $len, $blocksize, \$buf))) {
2139 0         0 print $fh $buf;
2140 0         0 $len += length $buf;
2141             }
2142 0         0 close(FH);
2143 0         0 $len;
2144             }
2145              
2146             sub more_results {
2147 2447     2447   23776 shift->{syb_more_results}; # handy grandfathering
2148             }
2149              
2150             }
2151              
2152             unless ($DBI::PurePerl) { # See install_driver
2153             { @DBD::_mem::dr::ISA = qw(DBD::_mem::common); }
2154             { @DBD::_mem::db::ISA = qw(DBD::_mem::common); }
2155             { @DBD::_mem::st::ISA = qw(DBD::_mem::common); }
2156             # DBD::_mem::common::DESTROY is implemented in DBI.xs
2157             }
2158              
2159             1;
2160             __END__