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   7044274 our $XS_VERSION = our $VERSION = "1.637"; # ==> ALSO update the version in the pod text below!
15 192         7763 $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   1332 use Scalar::Util ();
  192         361  
  192         2450  
175 192     192   804 use Carp();
  192         330  
  192         2376  
176 192     192   785 use DynaLoader ();
  192         356  
  192         2315  
177 192     192   800 use Exporter ();
  192         350  
  192         50279  
178              
179             BEGIN {
180 192     192   2900 @ISA = qw(Exporter DynaLoader);
181              
182             # Make some utility functions available if asked for
183 192         450 @EXPORT = (); # we export nothing by default
184 192         549 @EXPORT_OK = qw(%DBI %DBI_methods hash); # also populated by export_ok_tags:
185 192         2531 %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         381 $DBI::dbi_debug = 0; # mixture of bit fields and int sub-fields
265 192         300 $DBI::neat_maxlen = 1000;
266 192         334 $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       812 if ( $ENV{DBI_PUREPERL} ) {
272 96 50       404 eval { bootstrap DBI $XS_VERSION } if $ENV{DBI_PUREPERL} == 1;
  0         0  
273 96 50 33     33014 require DBI::PurePerl if $@ or $ENV{DBI_PUREPERL} >= 2;
274 96   50     442 $DBI::PurePerl ||= 0; # just to silence "only used once" warnings
275             }
276             else {
277 96         50809 bootstrap DBI $XS_VERSION;
278             }
279              
280 192         705 $EXPORT_TAGS{preparse_flags} = [ grep { /^DBIpp_\w\w_/ } keys %{__PACKAGE__."::"} ];
  24580         34885  
  192         3552  
281              
282 192         18600 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   1234 no strict;
  192         336  
  192         9204  
289             *$_ = \&{"DBD::_::common::$_"};
290             }
291              
292 192     192   947 use strict;
  192         335  
  192         211010  
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 12876 sub installed_drivers { %DBI::installed_drh }
306             %DBI::installed_methods = (); # XXX undocumented, may change
307 3428     3428 0 22086 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   1449 sub DBI::var::TIESCALAR{ my $var = $_[1]; bless \$var, 'DBI::var'; }
  960         2250  
317 2     2   2508 sub DBI::var::STORE { Carp::croak("Can't modify \$DBI::${$_[0]} special variable") }
  2         290  
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   2689682 return unless defined &DBI::trace_msg; # return unless bootstrap'd ok
531 192         2262 local ($!,$?);
532 192   50     3516 DBI->trace_msg(sprintf(" -- DBI::END (\$\@: %s, \$!: %s)\n", $@||'', $!||''), 2);
      50        
533             # Let drivers know why we are calling disconnect_all:
534 192         472 $DBI::PERL_ENDING = $DBI::PERL_ENDING = 1; # avoid typo warning
535 192 100       2054 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   1408 no strict 'refs';
  192         388  
  192         182554  
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 1218 my ($class, $dsn) = @_;
552 630 100       2819 $dsn =~ s/^(dbi):(\w*?)(?:\((.*?)\))?://i or return;
553 2         11 my ($scheme, $driver, $attr, $attr_hash) = (lc($1), $2, $3);
554 2   0     7 $driver ||= $ENV{DBI_DRIVER} || '';
      33        
555 2 50       7 $attr_hash = { split /\s*=>?\s*|\s*,\s*/, $attr, -1 } if $attr;
556 2         7 return ($scheme, $driver, $attr, $attr_hash, $dsn);
557             }
558              
559             sub visit_handles {
560 8     8 1 7293 my ($class, $code, $outer_info) = @_;
561 8 50       25 $outer_info = {} if not defined $outer_info;
562 8         27 my %drh = DBI->installed_drivers;
563 8         23 for my $h (values %drh) {
564 12 50       45 my $child_info = $code->($h, $outer_info)
565             or next;
566 12         353 $h->visit_child_handles($code, $child_info);
567             }
568 8         53 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 7560 my ($class, $dsn, $user, $pass, $attr) = @_;
578 3146 50       5584 my $dbi_connect_method = ($DBI::connect_via eq "Apache::DBI::connect")
579             ? 'Apache::DBI::connect' : 'connect_cached';
580 3146 50       15032 $attr = {
581             $attr ? %$attr : (), # clone, don't modify callers data
582             dbi_connect_method => $dbi_connect_method,
583             };
584 3146         7912 return $class->connect($dsn, $user, $pass, $attr);
585             }
586              
587             sub connect {
588 6971     6971 1 1064974 my $class = shift;
589 6971         19850 my ($dsn, $user, $pass, $attr, $old_driver) = my @orig_args = @_;
590 6971         9886 my $driver;
591              
592 6971 50 66     26256 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         11436 my $connect_meth = $attr->{dbi_connect_method};
598 6971   66     18516 $connect_meth ||= $DBI::connect_via; # fallback to default
599              
600 6971 50 0     15596 $dsn ||= $ENV{DBI_DSN} || $ENV{DBI_DBNAME} || '' unless $old_driver;
      33        
601              
602 6971 100       12844 if ($DBI::dbi_debug) {
603 29         88 local $^W = 0;
604 29 50       63 pop @_ if $connect_meth ne 'connect';
605 29         54 my @args = @_; $args[2] = '****'; # hide password
  29         45  
606 29         181 DBI->trace_msg(" -> $class->$connect_meth(".join(", ",@args).")\n");
607             }
608 6971 100 33     34583 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       54904 $dsn =~ s/^dbi:(\w*?)(?:\((.*?)\))?://i
614             or '' =~ /()/; # ensure $1 etc are empty if match fails
615 6967   100     28073 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     29834 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         9062 my $proxy;
625 6967 100 66     17155 if ($ENV{DBI_AUTOPROXY} && $driver ne 'Proxy' && $driver ne 'Sponge' && $driver ne 'Switch') {
      100        
      66        
626 194         421 my $dbi_autoproxy = $ENV{DBI_AUTOPROXY};
627 194         327 $proxy = 'Proxy';
628 194 50       1168 if ($dbi_autoproxy =~ s/^dbi:(\w*?)(?:\((.*?)\))?://i) {
629 194         494 $proxy = $1;
630 194 100       813 $driver_attrib_spec = join ",",
    50          
631             ($driver_attrib_spec) ? $driver_attrib_spec : (),
632             ($2 ) ? $2 : ();
633             }
634 194         649 $dsn = "$dbi_autoproxy;dsn=dbi:$driver:$dsn";
635 194         332 $driver = $proxy;
636 194         1075 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       12880 local $ENV{DBI_AUTOPROXY} if $ENV{DBI_AUTOPROXY};
640              
641 6967         8294 my %attributes; # take a copy we can delete from
642 6967 50       11175 if ($old_driver) {
643 0 0       0 %attributes = %$attr if $attr;
644             }
645             else { # new-style connect so new default semantics
646 6967 50       46557 %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         14390 $attr = \%attributes; # now set $attr to refer to our local copy
655              
656 6967 50 66     22616 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       14851 $user = $attr->{Username} if defined $attr->{Username};
661 6963 100       12575 $pass = $attr->{Password} if defined $attr->{Password};
662 6963         10027 delete $attr->{Password}; # always delete Password as closure stores it securely
663 6963 100 66     18584 if ( !(defined $user && defined $pass) ) {
664 1604         8687 ($user, $pass) = $drh->default_user($user, $pass, $attr);
665             }
666 6963         19333 $attr->{Username} = $user; # force the Username to be the actual one used
667              
668             my $connect_closure = sub {
669 6979     6979   11034 my ($old_dbh, $override_attr) = @_;
670              
671             #use Data::Dumper;
672             #warn "connect_closure: ".Data::Dumper::Dumper([$attr,\%attributes, $override_attr]);
673              
674 6979         7761 my $dbh;
675 6979 100       32395 unless ($dbh = $drh->$connect_meth($dsn, $user, $pass, $attr)) {
676 38 100       668 $user = '' if !defined $user;
677 38 50       82 $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         171 my $errstr = $DBI::errstr;
682             # Getting '(no error string)' here is a symptom of a ref loop
683 38 50       92 $errstr = '(no error string)' if !defined $errstr;
684 38         128 my $msg = "$class connect('$dsn','$user',...) failed: $errstr";
685 38         156 DBI->trace_msg(" $msg\n");
686             # XXX HandleWarn
687 38 50 33     118 unless ($attr->{HandleError} && $attr->{HandleError}->($msg, $drh, $dbh)) {
688 38 100       1596 Carp::croak($msg) if $attr->{RaiseError};
689 24 50       54 Carp::carp ($msg) if $attr->{PrintError};
690             }
691 24         58 $! = 0; # for the daft people who do DBI->connect(...) || die "$!";
692 24         68 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       54967 my $apply = { ($override_attr) ? (%$attr, %$override_attr ) : %$attr };
697              
698             # handle basic RootClass subclassing:
699 6905   100     28323 my $rebless_class = $apply->{RootClass} || ($class ne 'DBI' ? $class : '');
700 6905 100       12228 if ($rebless_class) {
701 192     192   1370 no strict 'refs';
  192         380  
  192         137709  
702 32 100       75 if ($apply->{RootClass}) { # explicit attribute (ie not static method call class)
703 24         51 delete $apply->{RootClass};
704 24         58 DBI::_load_class($rebless_class, 0);
705             }
706 28 50 33     52 unless (@{"$rebless_class\::db::ISA"} && @{"$rebless_class\::st::ISA"}) {
  28         119  
  28         112  
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         219 $dbh->{RootClass} = $rebless_class; # $dbh->STORE called via plain DBI::db
713 28         218 DBI::_set_isa([$rebless_class], 'DBI'); # sets up both '::db' and '::st'
714 28         78 DBI::_rebless($dbh, $rebless_class); # appends '::db'
715             }
716             }
717              
718 6901 100       12529 if (%$apply) {
719              
720 6321 50       11221 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         6791 my $a;
725 6321         9695 foreach $a (qw(Profile RaiseError PrintError AutoCommit)) { # do these first
726 25284 100       55979 next unless exists $apply->{$a};
727 18856         78916 $dbh->{$a} = delete $apply->{$a};
728             }
729 6321         29140 while ( my ($a, $v) = each %$apply) {
730 28547         35181 eval { $dbh->{$a} = $v }; # assign in void context to avoid re-FETCH
  28547         92939  
731 28547 50       115340 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         26804 $dbh->connected(@orig_args); #if ref $dbh ne 'DBI::db' or $proxy;
738              
739 6901 100       22510 DBI->trace_msg(" <- connect= $dbh\n") if $DBI::dbi_debug & 0xF;
740              
741 6901         19480 return $dbh;
742 6963         33790 };
743              
744 6963         14275 my $dbh = &$connect_closure(undef, undef);
745              
746 6909 100       29920 $dbh->{dbi_connect_closure} = $connect_closure if $dbh;
747              
748 6909         35020 return $dbh;
749             }
750              
751              
752             sub disconnect_all {
753 138     138 0 417 keys %DBI::installed_drh; # reset iterator
754 138         766 while ( my ($name, $drh) = each %DBI::installed_drh ) {
755 234 50       5493 $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 61302 my $class = shift;
767 246         639 my($driver, $attr) = @_;
768 246         411 my $drh;
769              
770 246   0     652 $driver ||= $ENV{DBI_DRIVER} || '';
      33        
771              
772             # allow driver to be specified as a 'dbi:driver:' string
773 246 100       902 $driver = $1 if $driver =~ s/^DBI:(.*?)://i;
774              
775 246 50 33     1367 Carp::croak("usage: $class->install_driver(\$driver [, \%attr])")
776             unless ($driver and @_<=3);
777              
778             # already installed
779 246 100       833 return $drh if $drh = $DBI::installed_drh{$driver};
780              
781 238 100       878 $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         623 my $driver_class = "DBD::$driver";
787 238         15462 eval qq{package # hide from PAUSE
788             DBI::_firesafe; # just in case
789             require $driver_class; # load the driver
790             };
791 238 100       1322 if ($@) {
792 4         8 my $err = $@;
793 4         8 my $advice = "";
794 4 50       103 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         24 my @drv = $class->available_drivers(1);
801 4         37 $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         1039 Carp::croak("install_driver($driver) failed: $err$advice\n");
812             }
813 234 100       863 if ($DBI::dbi_debug & 0xF) {
814 192     192   1313 no strict 'refs';
  192         359  
  192         50721  
815 6         36 (my $driver_file = $driver_class) =~ s/::/\//g;
816 6   50     12 my $dbd_ver = ${"$driver_class\::VERSION"} || "undef";
817 6         113 $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         1309 $class->setup_driver($driver_class);
823              
824             # --- run the driver function
825 234   50     497 $drh = eval { $driver_class->driver($attr || {}) };
  234         1709  
826 234 50 33     4728 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         694 $DBI::installed_drh{$driver} = $drh;
836 234 100       813 $class->trace_msg(" <- install_driver= $drh\n") if $DBI::dbi_debug & 0xF;
837 234         1155 $drh;
838             }
839              
840             *driver = \&install_driver; # currently an alias, may change
841              
842              
843             sub setup_driver {
844 534     534 0 1537 my ($class, $driver_class) = @_;
845 534         845 my $h_type;
846 534         1290 foreach $h_type (qw(dr db st)){
847 1602         3450 my $h_class = $driver_class."::$h_type";
848 192     192   1217 no strict 'refs';
  192         364  
  192         44792  
849 1602 100       10214 push @{"${h_class}::ISA"}, "DBD::_::$h_type"
  1302         12722  
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         4426 my $mem_class = "DBD::_mem::$h_type";
854 1602 100 100     11106 push @{"${h_class}_mem::ISA"}, $mem_class
  756         7505  
855             unless UNIVERSAL::isa("${h_class}_mem", $mem_class)
856             or $DBI::PurePerl;
857             }
858             }
859              
860              
861             sub _rebless {
862 28     28   41 my $dbh = shift;
863 28         83 my ($outer, $inner) = DBI::_handles($dbh);
864 28         67 my $class = shift(@_).'::db';
865 28         54 bless $inner => $class;
866 28         53 bless $outer => $class; # outer last for return
867             }
868              
869              
870             sub _set_isa {
871 28     28   58 my ($classes, $topclass) = @_;
872 28         137 my $trace = DBI->trace_msg(" _set_isa([@$classes])\n");
873 28         70 foreach my $suffix ('::db','::st') {
874 56   50     112 my $previous = $topclass || 'DBI'; # trees are rooted here
875 56         82 foreach my $class (@$classes) {
876 56         92 my $base_class = $previous.$suffix;
877 56         75 my $sub_class = $class.$suffix;
878 56         111 my $sub_class_isa = "${sub_class}::ISA";
879 192     192   1187 no strict 'refs';
  192         609  
  192         107858  
880 56 50       140 if (@$sub_class_isa) {
881 56 50       106 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         136 $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   51 my ($load_class, $missing_ok) = @_;
975 24         130 DBI->trace_msg(" _load_class($load_class, $missing_ok)\n", 2);
976 192     192   1308 no strict 'refs';
  192         376  
  192         95699  
977 24 100       32 return 1 if @{"$load_class\::ISA"}; # already loaded/exists
  24         123  
978 4         16 (my $module = $load_class) =~ s!::!/!g;
979 4         21 DBI->trace_msg(" _load_class require $module\n", 2);
980 4         7 eval { require "$module.pm"; };
  4         598  
981 4 50       26 return 1 unless $@;
982 4 50 33     22 return 0 if $missing_ok && $@ =~ /^Can't locate \Q$module.pm\E/;
983 4         139 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 8932 my ($class, $driver) = @_;
996 5316 50       16712 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 4815 my($quiet) = @_;
1002 12         25 my(@drivers, $d, $f);
1003 12         39 local(*DBI::DIR, $@);
1004 12         23 my(%seen_dir, %seen_dbd);
1005 12         25 my $haveFileSpec = eval { require File::Spec };
  12         75  
1006 12         35 foreach $d (@INC){
1007 132         217 chomp($d); # Perl 5 beta 3 bug in #!./perl -Ilib from Test::Harness
1008 132 50       733 my $dbd_dir =
1009             ($haveFileSpec ? File::Spec->catdir($d, 'DBD') : "$d/DBD");
1010 132 100       988 next unless -d $dbd_dir;
1011 36 100       100 next if $seen_dir{$d};
1012 28         56 $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       534 opendir(DBI::DIR, $dbd_dir) || Carp::carp "opendir $dbd_dir: $!\n";
1016 28         507 foreach $f (readdir(DBI::DIR)){
1017 308 100       846 next unless $f =~ s/\.pm$//;
1018 196 100       394 next if $f eq 'NullP';
1019 168 100       286 if ($seen_dbd{$f}){
1020 96 50       148 Carp::carp "DBD::$f in $d is hidden by DBD::$f in $seen_dbd{$f}\n"
1021             unless $quiet;
1022             } else {
1023 72         119 push(@drivers, $f);
1024             }
1025 168         329 $seen_dbd{$f} = $d;
1026             }
1027 28         257 closedir(DBI::DIR);
1028             }
1029              
1030             # "return sort @drivers" will not DWIM in scalar context.
1031 12 100       139 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   1266 no strict 'refs';
  192         339  
  192         394883  
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 37034 my ($class, $driver, @other) = @_;
1069 12         48 my $drh = $class->install_driver($driver);
1070 12         108 my @ds = $drh->data_sources(@other);
1071 12         3101 return @ds;
1072             }
1073              
1074              
1075             sub neat_list {
1076 128     128 1 60545 my ($listref, $maxlen, $sep) = @_;
1077 128 100       333 $maxlen = 0 unless defined $maxlen; # 0 == use internal default
1078 128 100       292 $sep = ", " unless defined $sep;
1079 128         265 join($sep, map { neat($_,$maxlen) } @$listref);
  284         1370  
1080             }
1081              
1082              
1083             sub dump_results { # also aliased as a method in DBD::_::st
1084 4     4 1 2150 my ($sth, $maxlen, $lsep, $fsep, $fh) = @_;
1085 4 50       19 return 0 unless $sth;
1086 4   50     15 $maxlen ||= 35;
1087 4   50     13 $lsep ||= "\n";
1088 4   50     12 $fh ||= \*STDOUT;
1089 4         9 my $rows = 0;
1090 4         8 my $ref;
1091 4         56 while($ref = $sth->fetch) {
1092 12 100 66     168 print $fh $lsep if $rows++ and $lsep;
1093 12         40 my $str = neat_list($ref,$maxlen,$fsep);
1094 12         72 print $fh $str; # done on two lines to avoid 5.003 errors
1095             }
1096 4 50       60 print $fh "\n$rows rows".($DBI::err ? " ($DBI::err: $DBI::errstr)" : "")."\n";
1097 4         23 $rows;
1098             }
1099              
1100              
1101             sub data_diff {
1102 28     28 1 67 my ($a, $b, $logical) = @_;
1103              
1104 28         55 my $diff = data_string_diff($a, $b);
1105 28 100 66     81 return "" if $logical and !$diff;
1106              
1107 24         44 my $a_desc = data_string_desc($a);
1108 24         112 my $b_desc = data_string_desc($b);
1109 24 100 100     156 return "" if !$diff and $a_desc eq $b_desc;
1110              
1111 12 100 100     46 $diff ||= "Strings contain the same sequence of characters"
1112             if length($a);
1113 12 50       35 $diff .= "\n" if $diff;
1114 12         72 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 1855 my ($a, $b) = @_;
1123 60 100 100     224 unless (defined $a and defined $b) { # one undef
1124 16 50 66     67 return ""
1125             if !defined $a and !defined $b;
1126 8 50       18 return "String a is undef, string b has ".length($b)." characters"
1127             if !defined $a;
1128 8 50       54 return "String b is undef, string a has ".length($a)." characters"
1129             if !defined $b;
1130             }
1131              
1132 44         215 require utf8;
1133             # hack to cater for perl 5.6
1134 44 50   0   95 *utf8::is_utf8 = sub { (DBI::neat(shift)=~/^"/) } unless defined &utf8::is_utf8;
  0         0  
1135              
1136 44 50       162 my @a_chars = (utf8::is_utf8($a)) ? unpack("U*", $a) : unpack("C*", $a);
1137 44 100       110 my @b_chars = (utf8::is_utf8($b)) ? unpack("U*", $b) : unpack("C*", $b);
1138 44         59 my $i = 0;
1139 44   100     151 while (@a_chars && @b_chars) {
1140 72 100       212 ++$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       24 $_ > 255 ? # if wide character...
  24 50       109  
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         27 foreach my $c ( @desc ) {
1151 24 50       51 next unless $c =~ m/\\x\{08(..)}/;
1152 0         0 $c .= "='" .chr(hex($1)) ."'"
1153             }
1154 12         87 return sprintf "Strings differ at index $i: a[$i]=$desc[0], b[$i]=$desc[1]";
1155             }
1156 32 100       81 return "String a truncated after $i characters" if @b_chars;
1157 28 100       61 return "String b truncated after $i characters" if @a_chars;
1158 24         60 return "";
1159             }
1160              
1161              
1162             sub data_string_desc { # describe a data string
1163 72     72 1 15822 my ($a) = @_;
1164 72         1920 require bytes;
1165 72         839 require utf8;
1166              
1167             # hacks to cater for perl 5.6
1168 72 50   0   164 *utf8::is_utf8 = sub { (DBI::neat(shift)=~/^"/) } unless defined &utf8::is_utf8;
  0         0  
1169 72 50   0   135 *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     365 my $utf8 = sprintf "UTF8 %s%s",
    50          
1177             utf8::is_utf8($a) ? "on" : "off",
1178             utf8::valid($a||'') ? "" : " but INVALID encoding";
1179 72 100       154 return "$utf8, undef" unless defined $a;
1180 56         195 my $is_ascii = $a =~ m/^[\000-\177]*$/;
1181 56 100       155 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   1867 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         674 my ($h_state_store, $h_err_store, $h_errstr_store) = (undef, undef, '');
1248 238         1745 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         3539 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     1969 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       16 if (!$shared_profile) { # first time
1266 2         216 $h->{Profile} = $ENV{DBI_PROFILE}; # write string
1267 2         28 $shared_profile = $h->{Profile}; # read and record object
1268             }
1269             else {
1270 1         16 $h->{Profile} = $shared_profile;
1271             }
1272             }
1273 238 100       823 return $h unless wantarray;
1274 194         692 ($h, $i);
1275             }
1276              
1277             sub _new_dbh { # called by DBD::::dr::connect()
1278 3854     3854   24137 my ($drh, $attr, $imp_data) = @_;
1279             my $imp_class = $drh->{ImplementorClass}
1280 3854 50       8978 or Carp::croak("DBI _new_dbh: $drh has no ImplementorClass");
1281 3854         9571 substr($imp_class,-4,4) = '::db';
1282 3854         6692 my $app_class = ref $drh;
1283 3854         5815 substr($app_class,-4,4) = '::db';
1284 3854   50     15229 $attr->{Err} ||= \my $err;
1285 3854   50     14081 $attr->{Errstr} ||= \my $errstr;
1286 3854   50     13732 $attr->{State} ||= \my $state;
1287 3854         52752 _new_handle($app_class, $drh, $attr, $imp_data, $imp_class);
1288             }
1289              
1290             sub _new_sth { # called by DBD::::db::prepare)
1291 7701     7701   15678 my ($dbh, $attr, $imp_data) = @_;
1292             my $imp_class = $dbh->{ImplementorClass}
1293 7701 50       17475 or Carp::croak("DBI _new_sth: $dbh has no ImplementorClass");
1294 7701         16270 substr($imp_class,-4,4) = '::st';
1295 7701         12912 my $app_class = ref $dbh;
1296 7701         10854 substr($app_class,-4,4) = '::st';
1297 7701         96561 _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   16 return $drh if $drh; # a package global
1318              
1319 4         6 my $inner;
1320 4         54 ($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     36 Carp::croak("DBD::Switch init failed!") unless ($drh && $inner);
1326 4         12 return $drh;
1327             }
1328             sub CLONE {
1329 0     0   0 undef $drh;
1330             }
1331              
1332             sub FETCH {
1333 26     26   4714 my($drh, $key) = @_;
1334 26 50       63 return DBI->trace if $key eq 'DebugDispatch';
1335 26 50       42 return undef if $key eq 'DebugLog'; # not worth fetching, sorry
1336 26         140 return $drh->DBD::_::dr::FETCH($key);
1337 0         0 undef;
1338             }
1339             sub STORE {
1340 20     20   5142 my($drh, $key, $value) = @_;
1341 20 100       64 if ($key eq 'DebugDispatch') {
    50          
1342 4         33 DBI->trace($value);
1343             } elsif ($key eq 'DebugLog') {
1344 0         0 DBI->trace(-1, $value);
1345             } else {
1346 16         145 $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   1540 use strict;
  192         410  
  192         137820  
1361              
1362             # methods common to all handle types:
1363              
1364             # generic TIEHASH default methods:
1365       66     sub FIRSTKEY { }
1366       0     sub NEXTKEY { }
1367 122     122   21908 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   30452 my $h = shift;
1372             # scalar is needed to workaround drivers that return an empty list
1373             # for some attributes
1374 8268         12697 return map { scalar $h->FETCH($_) } @_;
  42764         148339  
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   1464 my ($class, $method, $attr) = @_;
1384 616 50       3666 Carp::croak("Class '$class' must begin with DBD:: and end with ::db or ::st")
1385             unless $class =~ /^DBD::(\w+)::(dr|db|st)$/;
1386 616         1928 my ($driver, $subtype) = ($1, $2);
1387 616 50       2661 Carp::croak("invalid method name '$method'")
1388             unless $method =~ m/^([a-z][a-z0-9]*_)\w+$/;
1389 616         1130 my $prefix = $1;
1390 616         1511 my $reg_info = $dbd_prefix_registry->{$prefix};
1391 616 50       1369 Carp::carp("method name prefix '$prefix' is not associated with a registered driver") unless $reg_info;
1392              
1393 616         1321 my $full_method = "DBI::${subtype}::$method";
1394 616         1416 $DBI::installed_methods{$full_method} = $attr;
1395              
1396 616         1844 my (undef, $filename, $line) = caller;
1397             # XXX reformat $attr as needed for _install_method
1398 616 100       955 my %attr = %{$attr||{}}; # copy so we can edit
  616         2546  
1399 616         5654 DBI->_install_method("DBI::${subtype}::$method", "$filename at line $line", \%attr);
1400             }
1401              
1402             sub parse_trace_flags {
1403 80     80   9730 my ($h, $spec) = @_;
1404 80         144 my $level = 0;
1405 80         106 my $flags = 0;
1406 80         115 my @unknown;
1407 80         398 for my $word (split /\s*[|&,]\s*/, $spec) {
1408 124 50 33     845 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         10 $flags = 0x7FFFFFFF; # XXX last bit causes negative headaches
1412 4         10 last;
1413             } elsif (my $flag = $h->parse_trace_flag($word)) {
1414 108         612 $flags |= $flag;
1415             }
1416             else {
1417 12         91 push @unknown, $word;
1418             }
1419             }
1420 80 50 66     338 if (@unknown && (ref $h ? $h->FETCH('Warn') : 1)) {
    50          
1421             Carp::carp("$h->parse_trace_flags($spec) ignored unknown trace flags: ".
1422 8         75 join(" ", map { DBI::neat($_) } @unknown));
  12         783  
1423             }
1424 80         415 $flags |= $level;
1425 80         486 return $flags;
1426             }
1427              
1428             sub parse_trace_flag {
1429 96     96   190 my ($h, $name) = @_;
1430             # 0xddDDDDrL (driver, DBI, reserved, Level)
1431 96 100       289 return 0x00000100 if $name eq 'SQL';
1432 72 100       170 return 0x00000200 if $name eq 'CON';
1433 58 100       145 return 0x00000400 if $name eq 'ENC';
1434 44 100       122 return 0x00000800 if $name eq 'DBD';
1435 30 100       95 return 0x00001000 if $name eq 'TXN';
1436 16         172 return;
1437             }
1438              
1439             sub private_attribute_info {
1440 3668     3668   38625 return undef;
1441             }
1442              
1443             sub visit_child_handles {
1444 28     28   268 my ($h, $code, $info) = @_;
1445 28 50       55 $info = {} if not defined $info;
1446 28 100       34 for my $ch (@{ $h->{ChildHandles} || []}) {
  28         83  
1447 384 100       553 next unless $ch;
1448 16 50       33 my $child_info = $code->($ch, $info)
1449             or next;
1450 16         382 $ch->visit_child_handles($code, $child_info);
1451             }
1452 28         104 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   1434 use strict;
  192         370  
  192         71315  
1461              
1462             sub default_user {
1463 1608     1608   45646 my ($drh, $user, $pass, $attr) = @_;
1464 1608 100       4163 $user = $ENV{DBI_USER} unless defined $user;
1465 1608 100       4088 $pass = $ENV{DBI_PASS} unless defined $pass;
1466 1608         5128 return ($user, $pass);
1467             }
1468              
1469             sub connect { # normally overridden, but a handy default
1470 118     118   5109 my ($drh, $dsn, $user, $auth) = @_;
1471 118         512 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         683 $this;
1479             }
1480              
1481              
1482             sub connect_cached {
1483 3146     3146   7314 my $drh = shift;
1484 3146         5474 my ($dsn, $user, $auth, $attr) = @_;
1485              
1486 3146   100     6368 my $cache = $drh->{CachedKids} ||= {};
1487 3146         3495 my $key = do { local $^W;
  3146         8627  
1488 3146         39705 join "!\001", $dsn, $user, $auth, DBI::_concat_hash_sorted($attr, "=\001", ",\001", 0, 0)
1489             };
1490 3146         6395 my $dbh = $cache->{$key};
1491 3146 50       7492 $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         4031 my $cb = $attr->{Callbacks}; # take care not to autovivify
1495 3146 50 66     15086 if ($dbh && $dbh->FETCH('Active') && eval { $dbh->ping }) {
  3114   66     10471  
1496             # If the caller has provided a callback then call it
1497 3114 100 66     7348 if ($cb and $cb = $cb->{"connect_cached.reused"}) {
1498 2         4 local $_ = "connect_cached.reused";
1499 2         6 $cb->($dbh, $dsn, $user, $auth, $attr);
1500             }
1501 3114         14240 return $dbh;
1502             }
1503              
1504             # If the caller has provided a callback then call it
1505 32 100 66     105 if ($cb and (my $new_cb = $cb->{"connect_cached.new"})) {
1506 2         5 local $_ = "connect_cached.new";
1507 2         6 $new_cb->($dbh, $dsn, $user, $auth, $attr); # $dbh is dead or undef
1508             }
1509              
1510 32         3253 $dbh = $drh->connect(@_);
1511 32         268 $cache->{$key} = $dbh; # replace prev entry, even if connect failed
1512 32 100 66     118 if ($cb and (my $conn_cb = $cb->{"connect_cached.connected"})) {
1513 2         5 local $_ = "connect_cached.connected";
1514 2         8 $conn_cb->($dbh, $dsn, $user, $auth, $attr);
1515             }
1516 32         4145 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   1306 use strict;
  192         1243  
  192         353723  
1526              
1527             sub clone {
1528 16     16   22708 my ($old_dbh, $attr) = @_;
1529              
1530             my $closure = $old_dbh->{dbi_connect_closure}
1531 16 50       55 or return $old_dbh->set_err($DBI::stderr, "Can't clone handle");
1532              
1533 16 100       37 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         37 while ( my ($k, $v) = each %$old_dbh ) {
1537             # ignore non-code refs, i.e., caches, handles, Err etc
1538 198 100 100     435 next if ref $v && ref $v ne 'CODE'; # HandleError etc
1539 158         369 $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         60 $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         214 my $new_dbh = &$closure($old_dbh, $attr);
1552 16 50       42 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         59 $new_dbh->{dbi_connect_closure} = $closure;
1558 16         116 return $new_dbh;
1559             }
1560              
1561             sub quote_identifier {
1562 114     114   5160 my ($dbh, @id) = @_;
1563 114 50 33     282 my $attr = (@id > 3 && ref($id[-1])) ? pop @id : undef;
1564              
1565             my $info = $dbh->{dbi_quote_identifier_cache} ||= [
1566 114   50     311 $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         299 my $quote = $info->[0];
1572 114         173 foreach (@id) { # quote the elements
1573 322 100       450 next unless defined;
1574 208         778 s/$quote/$quote$quote/g; # escape embedded quotes
1575 208         383 $_ = qq{$quote$_$quote};
1576             }
1577              
1578             # strip out catalog if present for special handling
1579 114 100       220 my $catalog = (@id >= 3) ? shift @id : undef;
1580              
1581             # join the dots, ignoring any null/undef elements (ie schema)
1582 114         179 my $quoted_id = join '.', grep { defined } @id;
  220         439  
1583              
1584 114 100       234 if ($catalog) { # add catalog correctly
1585 78 100       121 if ($quoted_id) {
1586 70 100       163 $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         326 return $quoted_id;
1594             }
1595              
1596             sub quote {
1597 16     16   2162 my ($dbh, $str, $data_type) = @_;
1598              
1599 16 100       44 return "NULL" unless defined $str;
1600 12 100       25 unless ($data_type) {
1601 4         19 $str =~ s/'/''/g; # ISO SQL2
1602 4         32 return "'$str'";
1603             }
1604              
1605 8   100     34 my $dbi_literal_quote_cache = $dbh->{'dbi_literal_quote_cache'} ||= [ {} , {} ];
1606 8         19 my ($prefixes, $suffixes) = @$dbi_literal_quote_cache;
1607              
1608 8         11 my $lp = $prefixes->{$data_type};
1609 8         12 my $ls = $suffixes->{$data_type};
1610              
1611 8 50 33     19 if ( ! defined $lp || ! defined $ls ) {
1612 8         31 my $ti = $dbh->type_info($data_type);
1613 8 50 100     73 $lp = $prefixes->{$data_type} = $ti ? $ti->{LITERAL_PREFIX} || "" : "'";
1614 8 50 100     40 $ls = $suffixes->{$data_type} = $ti ? $ti->{LITERAL_SUFFIX} || "" : "'";
1615             }
1616 8 100 66     33 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     69 $str =~ s/$lp/$lp$lp/g
      33        
      33        
1622             if $lp && $lp eq $ls && ($lp eq "'" || $lp eq '"');
1623 4         21 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   25481 my($dbh, $statement, $attr, @params) = @_;
1630 1675 100       5852 my $sth = $dbh->prepare($statement, $attr) or return undef;
1631 1671 100       7353 $sth->execute(@params) or return undef;
1632 202         2276 my $rows = $sth->rows;
1633 202 100       2093 ($rows == 0) ? "0E0" : $rows;
1634             }
1635              
1636             sub _do_selectrow {
1637 16     16   64 my ($method, $dbh, $stmt, $attr, @bind) = @_;
1638 16 50       110 my $sth = ((ref $stmt) ? $stmt : $dbh->prepare($stmt, $attr))
    50          
1639             or return undef;
1640 16 100       217 $sth->execute(@bind)
1641             or return undef;
1642 8 50       125 my $row = $sth->$method()
1643             and $sth->finish;
1644 8         111 return $row;
1645             }
1646              
1647 4     4   3132 sub selectrow_hashref { return _do_selectrow('fetchrow_hashref', @_); }
1648              
1649             # XXX selectrow_array/ref also have C implementations in Driver.xst
1650 8     8   232 sub selectrow_arrayref { return _do_selectrow('fetchrow_arrayref', @_); }
1651             sub selectrow_array {
1652 4 50   4   1966 my $row = _do_selectrow('fetchrow_arrayref', @_) or return;
1653 4 50       95 return $row->[0] unless wantarray;
1654 4         25 return @$row;
1655             }
1656              
1657             sub selectall_array {
1658 4 50   4   9074 return @{ shift->selectall_arrayref(@_) || [] };
  4         20  
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   53214 my ($dbh, $stmt, $attr, @bind) = @_;
1665 126 100       916 my $sth = (ref $stmt) ? $stmt : $dbh->prepare($stmt, $attr)
    100          
1666             or return;
1667 122 50       1701 $sth->execute(@bind) || return;
1668 122         1659 my $slice = $attr->{Slice}; # typically undef, else hash or array ref
1669 122 100 100     934 if (!$slice and $slice=$attr->{Columns}) {
1670 8 100       28 if (ref $slice eq 'ARRAY') { # map col idx to perl array idx
1671 4         9 $slice = [ @{$attr->{Columns}} ]; # take a copy
  4         10  
1672 4         11 for (@$slice) { $_-- }
  8         13  
1673             }
1674             }
1675 122         702 my $rows = $sth->fetchall_arrayref($slice, my $MaxRows = $attr->{MaxRows});
1676 122 50       967 $sth->finish if defined $MaxRows;
1677 122         1529 return $rows;
1678             }
1679              
1680             sub selectall_hashref {
1681 8     8   14781 my ($dbh, $stmt, $key_field, $attr, @bind) = @_;
1682 8 50       70 my $sth = (ref $stmt) ? $stmt : $dbh->prepare($stmt, $attr);
1683 8 50       79 return unless $sth;
1684 8 50       49 $sth->execute(@bind) || return;
1685 8         104 return $sth->fetchall_hashref($key_field);
1686             }
1687              
1688             sub selectcol_arrayref {
1689 8     8   7272 my ($dbh, $stmt, $attr, @bind) = @_;
1690 8 50       48 my $sth = (ref $stmt) ? $stmt : $dbh->prepare($stmt, $attr);
1691 8 50       80 return unless $sth;
1692 8 50       38 $sth->execute(@bind) || return;
1693 8 100       77 my @columns = ($attr->{Columns}) ? @{$attr->{Columns}} : (1);
  4         12  
1694 8         21 my @values = (undef) x @columns;
1695 8         16 my $idx = 0;
1696 8         17 for (@columns) {
1697 12 50       76 $sth->bind_col($_, \$values[$idx++]) || return;
1698             }
1699 8         45 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         29 push @col, @values while $sth->fetch;
1705             }
1706 8         107 return \@col;
1707             }
1708              
1709             sub prepare_cached {
1710 48     48   9168 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     182 my $cache = $dbh->{CachedKids} ||= {};
1716 48         69 my $key = do { local $^W;
  48         175  
1717 48         223 join "!\001", $statement, DBI::_concat_hash_sorted($attr, "=\001", ",\001", 0, 0)
1718             };
1719 48         90 my $sth = $cache->{$key};
1720              
1721 48 100       98 if ($sth) {
1722 12 50       51 return $sth unless $sth->FETCH('Active');
1723 12 100 100     871 Carp::carp("prepare_cached($statement) statement handle $sth still Active")
1724             unless ($if_active ||= 0);
1725 12 100       288 $sth->finish if $if_active <= 1;
1726 12 100       85 return $sth if $if_active <= 2;
1727             }
1728              
1729 40         161 $sth = $dbh->prepare($statement, $attr);
1730 40 50       396 $cache->{$key} = $sth if $sth;
1731              
1732 40         125 return $sth;
1733             }
1734              
1735             sub ping {
1736 12     12   2358 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       55 ($dbh->FETCH('Active')) ? "0 but true" : 0;
1740             }
1741              
1742             sub begin_work {
1743 4     4   1670 my $dbh = shift;
1744 4 50       15 return $dbh->set_err($DBI::stderr, "Already in a transaction")
1745             unless $dbh->FETCH('AutoCommit');
1746 4         36 $dbh->STORE('AutoCommit', 0); # will croak if driver doesn't support it
1747 4         25 $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   6887 my ($dbh, @args) = @_;
1763 32 50       186 my $sth = $dbh->table_info(@args[0,1,2,3,4]) or return;
1764 32 50       385 my $tables = $sth->fetchall_arrayref or return;
1765 32         252 my @tables;
1766 32 100 100     257 if (defined($args[3]) && $args[3] eq '%' # special case for tables('','','','%')
    100 66        
1767 12 50       64 && grep {defined($_) && $_ eq ''} @args[0,1,2]
1768             ) {
1769 4         11 @tables = map { $_->[3] } @$tables;
  12         34  
1770             } elsif ($dbh->get_info(29)) { # SQL_IDENTIFIER_QUOTE_CHAR
1771 16         120 @tables = map { $dbh->quote_identifier( @{$_}[0,1,2] ) } @$tables;
  92         412  
  92         316  
1772             }
1773             else { # temporary old style hack (yeach)
1774             @tables = map {
1775 12         236 my $name = $_->[2];
  16         31  
1776 16 50       31 if ($_->[1]) {
1777 16         25 my $schema = $_->[1];
1778             # a sad hack (mostly for Informix I recall)
1779 16 50       78 my $quote = ($schema eq uc($schema)) ? '' : '"';
1780 16         42 $name = "$quote$schema$quote.$name"
1781             }
1782 16         46 $name;
1783             } @$tables;
1784             }
1785 32         537 return @tables;
1786             }
1787              
1788             sub type_info { # this should be sufficient for all drivers
1789 28     28   6544 my ($dbh, $data_type) = @_;
1790 28         37 my $idx_hash;
1791 28         42 my $tia = $dbh->{dbi_type_info_row_cache};
1792 28 100       61 if ($tia) {
1793 18         27 $idx_hash = $dbh->{dbi_type_info_idx_cache};
1794             }
1795             else {
1796 10         39 my $temp = $dbh->type_info_all;
1797 10 50 33     89 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         27 $tia = $dbh->{dbi_type_info_row_cache} = [ @$temp ];
1802 10         33 $idx_hash = $dbh->{dbi_type_info_idx_cache} = shift @$tia;
1803             }
1804              
1805 28   33     81 my $dt_idx = $idx_hash->{DATA_TYPE} || $idx_hash->{data_type};
1806 28 50 33     105 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       61 my @data_type_list = (ref $data_type) ? @$data_type : ($data_type);
1812 28         51 foreach $data_type (@data_type_list) {
1813 28 100 66     92 if (defined($data_type) && $data_type != DBI::SQL_ALL_TYPES()) {
1814 24         41 push @ti, grep { $_->[$dt_idx] == $data_type } @$tia;
  48         108  
1815             }
1816             else { # SQL_ALL_TYPES
1817 4         9 push @ti, @$tia;
1818             }
1819 28 50       60 last if @ti; # found at least one match
1820             }
1821              
1822             # --- format results into list of hash refs
1823 28         54 my $idx_fields = keys %$idx_hash;
1824 28         73 my @idx_names = map { uc($_) } keys %$idx_hash;
  420         577  
1825 28         75 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     72 if @ti && @{$ti[0]} != $idx_fields;
  28         70  
1828             my @out = map {
1829 28         47 my %h; @h{@idx_names} = @{$_}[ @idx_values ]; \%h;
  32         39  
  32         40  
  32         195  
  32         73  
1830             } @ti;
1831 28 100       146 return $out[0] unless wantarray;
1832 4         27 return @out;
1833             }
1834              
1835             sub data_sources {
1836 4     4   3487 my ($dbh, @other) = @_;
1837 4         13 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   1493 use strict;
  192         435  
  192         329263  
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   10031 my $sth = shift;
1866 84         126 my ($p_id, $value_array, $attr) = @_;
1867              
1868 84 100 100     344 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       227 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       121 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     138 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         130 $$hash_of_arrays{$p_id} = $value_array;
1888 76 50       104 return $sth->bind_param($p_id, undef, $attr)
1889             if $attr;
1890 76         221 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   20258 my $sth = shift;
1904 116   50     529 my $fields = $sth->FETCH('NUM_OF_FIELDS') || 0;
1905 116 50 33     990 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         190 my $attr;
1912 116 100 66     800 $attr = shift if !defined $_[0] or ref($_[0]) eq 'HASH';
1913              
1914 116         223 my $idx = 0;
1915 116   100     1517 $sth->bind_col(++$idx, shift, $attr) or return
      50        
1916             while (@_ and $idx < $fields);
1917              
1918 116 100 100     1258 return $sth->set_err($DBI::stderr, "bind_columns called with ".($idx+@_)." values but $fields are needed")
1919             if @_ or $idx != $fields;
1920              
1921 108         292 return 1;
1922             }
1923              
1924             sub execute_array {
1925 48     48   35156 my $sth = shift;
1926 48         86 my ($attr, @array_of_arrays) = @_;
1927 48         134 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         256 my $tuple_sts = $attr->{ArrayTupleStatus};
1931 48 100 100     225 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       95 if (@array_of_arrays) {
1936 28         64 $sth->{ParamArrays} = { }; # clear out old params
1937 28 100 66     152 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     122 foreach (1..@array_of_arrays);
1942             }
1943              
1944 36         118 my $fetch_tuple_sub;
1945              
1946 36 100       71 if ($fetch_tuple_sub = $attr->{ArrayTupleFetch}) { # fetch on demand
1947              
1948 8 50       22 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       40 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       23 unless $fetch_sth->{Active};
1957             # check column count match to give more friendly message
1958 4         35 my $NUM_OF_FIELDS = $fetch_sth->{NUM_OF_FIELDS};
1959 4 50 33     63 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   23 $fetch_tuple_sub = sub { $fetch_sth->fetchrow_arrayref };
  16         52  
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       35 my $NUM_OF_PARAMS_given = keys %{ $sth->{ParamArrays} || {} };
  28         78  
1972 28 50 33     84 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         33 my $maxlen;
1978 28         34 my %hash_of_arrays = %{$sth->{ParamArrays}};
  28         90  
1979 28         82 foreach (keys(%hash_of_arrays)) {
1980 100         114 my $ary = $hash_of_arrays{$_};
1981 100 100       159 next unless ref $ary eq 'ARRAY';
1982 48 100 66     118 $maxlen = @$ary if !$maxlen || @$ary > $maxlen;
1983             }
1984             # if there are no arrays then execute scalars once
1985 28 100       62 $maxlen = 1 unless defined $maxlen;
1986 28         66 my @bind_ids = 1..keys(%hash_of_arrays);
1987              
1988 28         36 my $tuple_idx = 0;
1989             $fetch_tuple_sub = sub {
1990 68 100   68   164 return if $tuple_idx >= $maxlen;
1991             my @tuple = map {
1992 40         55 my $a = $hash_of_arrays{$_};
  160         203  
1993 160 100       279 ref($a) ? $a->[$tuple_idx] : $a
1994             } @bind_ids;
1995 40         56 ++$tuple_idx;
1996 40         84 return \@tuple;
1997 28         125 };
1998             }
1999             # pass thru the callers scalar or list context
2000 36         125 return $sth->execute_for_fetch($fetch_tuple_sub, $tuple_sts);
2001             }
2002              
2003             sub execute_for_fetch {
2004 36     36   551 my ($sth, $fetch_tuple_sub, $tuple_status) = @_;
2005             # start with empty status array
2006 36 100       103 ($tuple_status) ? @$tuple_status = () : $tuple_status = [];
2007              
2008 36         47 my $rc_total = 0;
2009 36         42 my $err_count;
2010 36         79 while ( my $tuple = &$fetch_tuple_sub() ) {
2011 60 100       317 if ( my $rc = $sth->execute(@$tuple) ) {
2012 56         297 push @$tuple_status, $rc;
2013 56 50 33     227 $rc_total = ($rc >= 0 && $rc_total >= 0) ? $rc_total + $rc : -1;
2014             }
2015             else {
2016 4         92 $err_count++;
2017 4         65 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         72 my $tuples = @$tuple_status;
2023 36 100       119 return $sth->set_err($DBI::stderr, "executing $tuples generated $err_count errors")
2024             if $err_count;
2025 32   100     80 $tuples ||= "0E0";
2026 32 100       155 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   25207 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     5110 return undef if $max_rows and not $sth->FETCH('Active');
2038              
2039 2354   100     7159 my $mode = ref($slice) || 'ARRAY';
2040 2354         2809 my @rows;
2041              
2042 2354 100       5462 if ($mode eq 'ARRAY') {
2043 2322         2684 my $row;
2044             # we copy the array here because fetch (currently) always
2045             # returns the same array ref. XXX
2046 2322 100 100     5740 if ($slice && @$slice) {
    100          
2047 16 100       96 $max_rows = -1 unless defined $max_rows;
2048 16   100     80 push @rows, [ @{$row}[ @$slice] ]
  40         468  
2049             while($max_rows-- and $row = $sth->fetch);
2050             }
2051             elsif (defined $max_rows) {
2052 8   100     40 push @rows, [ @$row ]
2053             while($max_rows-- and $row = $sth->fetch);
2054             }
2055             else {
2056 2298         7145 push @rows, [ @$row ] while($row = $sth->fetch);
2057             }
2058             return \@rows
2059 2321         13032 }
2060              
2061 32         45 my %row;
2062 32 100 100     153 if ($mode eq 'REF' && ref($$slice) eq 'HASH') { # \{ $idx => $name }
    100          
2063 12         32 keys %$$slice; # reset the iterator
2064 12         50 while ( my ($idx, $name) = each %$$slice ) {
2065 12         134 $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         52 my $name2idx = $sth->FETCH('NAME_lc_hash');
2071 12         93 while ( my ($name, $unused) = each %$slice ) {
2072 20         97 my $idx = $name2idx->{lc $name};
2073 20 100       151 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         8 my @column_names = @{ $sth->FETCH($sth->FETCH('FetchHashKeyName')) };
  4         27  
2080 4 50       48 return [] if !@column_names;
2081              
2082 4         29 $sth->bind_columns( \( @row{@column_names} ) );
2083             }
2084             }
2085             else {
2086 4         69 return $sth->set_err($DBI::stderr, "fetchall_arrayref($mode) invalid");
2087             }
2088              
2089 20 50       117 if (not defined $max_rows) {
2090 20         77 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         167 return \@rows;
2097             }
2098              
2099             sub fetchall_hashref {
2100 96     96   23190 my ($sth, $key_field) = @_;
2101              
2102 96   50     509 my $hash_key_name = $sth->{FetchHashKeyName} || 'NAME';
2103 96         1040 my $names_hash = $sth->FETCH("${hash_key_name}_hash");
2104 96 100       910 my @key_fields = (ref $key_field) ? @$key_field : ($key_field);
2105 96         213 my @key_indexes;
2106 96         345 my $num_of_fields = $sth->FETCH('NUM_OF_FIELDS');
2107 96         683 foreach (@key_fields) {
2108 100         229 my $index = $names_hash->{$_}; # perl index not column
2109 100 50 66     463 $index = $_ - 1 if !defined $index && DBI::looks_like_number($_) && $_>=1 && $_ <= $num_of_fields;
      66        
      33        
2110 100 50       313 return $sth->set_err($DBI::stderr, "Field '$_' does not exist (not one of @{[keys %$names_hash]})")
  0         0  
2111             unless defined $index;
2112 100         289 push @key_indexes, $index;
2113             }
2114 96         207 my $rows = {};
2115 96         309 my $NAME = $sth->FETCH($hash_key_name);
2116 96         661 my @row = (undef) x $num_of_fields;
2117 96         602 $sth->bind_columns(\(@row));
2118 96         921 while ($sth->fetch) {
2119 248         2511 my $ref = $rows;
2120 248   100     1375 $ref = $ref->{$row[$_]} ||= {} for @key_indexes;
2121 248         433 @{$ref}{@$NAME} = @row;
  248         990  
2122             }
2123 96         902 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   23690 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__