Filename | /usr/lib/x86_64-linux-gnu/perl5/5.20/DBI.pm |
Statements | Executed 0 statements in 0s |
Line | State ments |
Time on line |
Calls | Time in subs |
Code |
---|---|---|---|---|---|
1 | # $Id$ | ||||
2 | # vim: ts=8:sw=4:et | ||||
3 | # | ||||
4 | # Copyright (c) 1994-2012 Tim Bunce Ireland | ||||
5 | # | ||||
6 | # See COPYRIGHT section in pod text below for usage and distribution rights. | ||||
7 | # | ||||
8 | |||||
9 | package DBI; | ||||
10 | |||||
11 | require 5.008_001; | ||||
12 | |||||
13 | BEGIN { | ||||
14 | our $XS_VERSION = our $VERSION = "1.631"; # ==> ALSO update the version in the pod text below! | ||||
15 | $VERSION = eval $VERSION; | ||||
16 | } | ||||
17 | |||||
18 | =head1 NAME | ||||
19 | |||||
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<The synopsis above only lists the major methods and parameters.> | ||||
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<http://dbi.perl.org/support/> | ||||
93 | |||||
94 | You might also like to read the Advanced DBI Tutorial at | ||||
95 | L<http://www.slideshare.net/Tim.Bunce/dbi-advanced-tutorial-2007> | ||||
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<http://mikeash.com/getting_answers.html>. | ||||
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<dbi-users@perl.org> 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<dbi-users-help@perl.org>. | ||||
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<dbi-users> 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 Online | ||||
117 | |||||
118 | StackOverflow has a DBI tag L<http://stackoverflow.com/questions/tagged/dbi> | ||||
119 | with over 400 questions. | ||||
120 | |||||
121 | The DBI home page at L<http://dbi.perl.org/> and the DBI FAQ | ||||
122 | at L<http://faq.dbi-support.com/> may be worth a visit. | ||||
123 | They include links to other resources, but I<are rather out-dated>. | ||||
124 | |||||
125 | I don't recommend the DBI cpanforum (at http://www.cpanforum.com/dist/DBI) | ||||
126 | because relatively few people read it compared with dbi-users@perl.org. | ||||
127 | |||||
128 | =head3 Reporting a Bug | ||||
129 | |||||
130 | If you think you've found a bug then please read | ||||
131 | "How to Report Bugs Effectively" by Simon Tatham: | ||||
132 | L<http://www.chiark.greenend.org.uk/~sgtatham/bugs.html>. | ||||
133 | |||||
134 | Your problem is most likely related to the specific DBD driver module you're | ||||
135 | using. If that's the case then click on the 'Bugs' link on the L<http://metacpan.org> | ||||
136 | page for your driver. Only submit a bug report against the DBI itself if you're | ||||
137 | sure that your issue isn't related to the driver you're using. | ||||
138 | |||||
139 | =head2 NOTES | ||||
140 | |||||
141 | This is the DBI specification that corresponds to DBI version 1.631 | ||||
142 | (see L<DBI::Changes> for details). | ||||
143 | |||||
144 | The DBI is evolving at a steady pace, so it's good to check that | ||||
145 | you have the latest copy. | ||||
146 | |||||
147 | The significant user-visible changes in each release are documented | ||||
148 | in the L<DBI::Changes> module so you can read them by executing | ||||
149 | C<perldoc DBI::Changes>. | ||||
150 | |||||
151 | Some DBI changes require changes in the drivers, but the drivers | ||||
152 | can take some time to catch up. Newer versions of the DBI have | ||||
153 | added features that may not yet be supported by the drivers you | ||||
154 | use. Talk to the authors of your drivers if you need a new feature | ||||
155 | that is not yet supported. | ||||
156 | |||||
157 | Features added after DBI 1.21 (February 2002) are marked in the | ||||
158 | text with the version number of the DBI release they first appeared in. | ||||
159 | |||||
160 | Extensions to the DBI API often use the C<DBIx::*> namespace. | ||||
161 | See L</Naming Conventions and Name Space>. DBI extension modules | ||||
162 | can be found at L<https://metacpan.org/search?q=DBIx>. And all modules | ||||
163 | related to the DBI can be found at L<https://metacpan.org/search?q=DBI>. | ||||
164 | |||||
165 | =cut | ||||
166 | |||||
167 | # The POD text continues at the end of the file. | ||||
168 | |||||
169 | use Carp(); | ||||
170 | use DynaLoader (); | ||||
171 | use Exporter (); | ||||
172 | |||||
173 | BEGIN { | ||||
174 | @ISA = qw(Exporter DynaLoader); | ||||
175 | |||||
176 | # Make some utility functions available if asked for | ||||
177 | @EXPORT = (); # we export nothing by default | ||||
178 | @EXPORT_OK = qw(%DBI %DBI_methods hash); # also populated by export_ok_tags: | ||||
179 | %EXPORT_TAGS = ( | ||||
180 | sql_types => [ qw( | ||||
181 | SQL_GUID | ||||
182 | SQL_WLONGVARCHAR | ||||
183 | SQL_WVARCHAR | ||||
184 | SQL_WCHAR | ||||
185 | SQL_BIGINT | ||||
186 | SQL_BIT | ||||
187 | SQL_TINYINT | ||||
188 | SQL_LONGVARBINARY | ||||
189 | SQL_VARBINARY | ||||
190 | SQL_BINARY | ||||
191 | SQL_LONGVARCHAR | ||||
192 | SQL_UNKNOWN_TYPE | ||||
193 | SQL_ALL_TYPES | ||||
194 | SQL_CHAR | ||||
195 | SQL_NUMERIC | ||||
196 | SQL_DECIMAL | ||||
197 | SQL_INTEGER | ||||
198 | SQL_SMALLINT | ||||
199 | SQL_FLOAT | ||||
200 | SQL_REAL | ||||
201 | SQL_DOUBLE | ||||
202 | SQL_DATETIME | ||||
203 | SQL_DATE | ||||
204 | SQL_INTERVAL | ||||
205 | SQL_TIME | ||||
206 | SQL_TIMESTAMP | ||||
207 | SQL_VARCHAR | ||||
208 | SQL_BOOLEAN | ||||
209 | SQL_UDT | ||||
210 | SQL_UDT_LOCATOR | ||||
211 | SQL_ROW | ||||
212 | SQL_REF | ||||
213 | SQL_BLOB | ||||
214 | SQL_BLOB_LOCATOR | ||||
215 | SQL_CLOB | ||||
216 | SQL_CLOB_LOCATOR | ||||
217 | SQL_ARRAY | ||||
218 | SQL_ARRAY_LOCATOR | ||||
219 | SQL_MULTISET | ||||
220 | SQL_MULTISET_LOCATOR | ||||
221 | SQL_TYPE_DATE | ||||
222 | SQL_TYPE_TIME | ||||
223 | SQL_TYPE_TIMESTAMP | ||||
224 | SQL_TYPE_TIME_WITH_TIMEZONE | ||||
225 | SQL_TYPE_TIMESTAMP_WITH_TIMEZONE | ||||
226 | SQL_INTERVAL_YEAR | ||||
227 | SQL_INTERVAL_MONTH | ||||
228 | SQL_INTERVAL_DAY | ||||
229 | SQL_INTERVAL_HOUR | ||||
230 | SQL_INTERVAL_MINUTE | ||||
231 | SQL_INTERVAL_SECOND | ||||
232 | SQL_INTERVAL_YEAR_TO_MONTH | ||||
233 | SQL_INTERVAL_DAY_TO_HOUR | ||||
234 | SQL_INTERVAL_DAY_TO_MINUTE | ||||
235 | SQL_INTERVAL_DAY_TO_SECOND | ||||
236 | SQL_INTERVAL_HOUR_TO_MINUTE | ||||
237 | SQL_INTERVAL_HOUR_TO_SECOND | ||||
238 | SQL_INTERVAL_MINUTE_TO_SECOND | ||||
239 | ) ], | ||||
240 | sql_cursor_types => [ qw( | ||||
241 | SQL_CURSOR_FORWARD_ONLY | ||||
242 | SQL_CURSOR_KEYSET_DRIVEN | ||||
243 | SQL_CURSOR_DYNAMIC | ||||
244 | SQL_CURSOR_STATIC | ||||
245 | SQL_CURSOR_TYPE_DEFAULT | ||||
246 | ) ], # for ODBC cursor types | ||||
247 | utils => [ qw( | ||||
248 | neat neat_list $neat_maxlen dump_results looks_like_number | ||||
249 | data_string_diff data_string_desc data_diff sql_type_cast | ||||
250 | DBIstcf_DISCARD_STRING | ||||
251 | DBIstcf_STRICT | ||||
252 | ) ], | ||||
253 | profile => [ qw( | ||||
254 | dbi_profile dbi_profile_merge dbi_profile_merge_nodes dbi_time | ||||
255 | ) ], # notionally "in" DBI::Profile and normally imported from there | ||||
256 | ); | ||||
257 | |||||
258 | $DBI::dbi_debug = 0; # mixture of bit fields and int sub-fields | ||||
259 | $DBI::neat_maxlen = 1000; | ||||
260 | $DBI::stderr = 2_000_000_000; # a very round number below 2**31 | ||||
261 | |||||
262 | # If you get an error here like "Can't find loadable object ..." | ||||
263 | # then you haven't installed the DBI correctly. Read the README | ||||
264 | # then install it again. | ||||
265 | if ( $ENV{DBI_PUREPERL} ) { | ||||
266 | eval { bootstrap DBI $XS_VERSION } if $ENV{DBI_PUREPERL} == 1; | ||||
267 | require DBI::PurePerl if $@ or $ENV{DBI_PUREPERL} >= 2; | ||||
268 | $DBI::PurePerl ||= 0; # just to silence "only used once" warnings | ||||
269 | } | ||||
270 | else { | ||||
271 | bootstrap DBI $XS_VERSION; | ||||
272 | } | ||||
273 | |||||
274 | $EXPORT_TAGS{preparse_flags} = [ grep { /^DBIpp_\w\w_/ } keys %{__PACKAGE__."::"} ]; | ||||
275 | |||||
276 | Exporter::export_ok_tags(keys %EXPORT_TAGS); | ||||
277 | |||||
278 | } | ||||
279 | |||||
280 | # Alias some handle methods to also be DBI class methods | ||||
281 | for (qw(trace_msg set_err parse_trace_flag parse_trace_flags)) { | ||||
282 | no strict; | ||||
283 | *$_ = \&{"DBD::_::common::$_"}; | ||||
284 | } | ||||
285 | |||||
286 | use strict; | ||||
287 | |||||
288 | DBI->trace(split /=/, $ENV{DBI_TRACE}, 2) if $ENV{DBI_TRACE}; | ||||
289 | |||||
290 | $DBI::connect_via ||= "connect"; | ||||
291 | |||||
292 | # check if user wants a persistent database connection ( Apache + mod_perl ) | ||||
293 | if ($INC{'Apache/DBI.pm'} && $ENV{MOD_PERL}) { | ||||
294 | $DBI::connect_via = "Apache::DBI::connect"; | ||||
295 | DBI->trace_msg("DBI connect via $DBI::connect_via in $INC{'Apache/DBI.pm'}\n"); | ||||
296 | } | ||||
297 | |||||
298 | # check for weaken support, used by ChildHandles | ||||
299 | my $HAS_WEAKEN = eval { | ||||
300 | require Scalar::Util; | ||||
301 | # this will croak() if this Scalar::Util doesn't have a working weaken(). | ||||
302 | Scalar::Util::weaken( \my $test ); # same test as in t/72childhandles.t | ||||
303 | 1; | ||||
304 | }; | ||||
305 | |||||
306 | %DBI::installed_drh = (); # maps driver names to installed driver handles | ||||
307 | sub installed_drivers { %DBI::installed_drh } | ||||
308 | %DBI::installed_methods = (); # XXX undocumented, may change | ||||
309 | sub installed_methods { %DBI::installed_methods } | ||||
310 | |||||
311 | # Setup special DBI dynamic variables. See DBI::var::FETCH for details. | ||||
312 | # These are dynamically associated with the last handle used. | ||||
313 | tie $DBI::err, 'DBI::var', '*err'; # special case: referenced via IHA list | ||||
314 | tie $DBI::state, 'DBI::var', '"state'; # special case: referenced via IHA list | ||||
315 | tie $DBI::lasth, 'DBI::var', '!lasth'; # special case: return boolean | ||||
316 | tie $DBI::errstr, 'DBI::var', '&errstr'; # call &errstr in last used pkg | ||||
317 | tie $DBI::rows, 'DBI::var', '&rows'; # call &rows in last used pkg | ||||
318 | sub DBI::var::TIESCALAR{ my $var = $_[1]; bless \$var, 'DBI::var'; } | ||||
319 | sub DBI::var::STORE { Carp::croak("Can't modify \$DBI::${$_[0]} special variable") } | ||||
320 | |||||
321 | # --- Driver Specific Prefix Registry --- | ||||
322 | |||||
323 | my $dbd_prefix_registry = { | ||||
324 | ad_ => { class => 'DBD::AnyData', }, | ||||
325 | ado_ => { class => 'DBD::ADO', }, | ||||
326 | amzn_ => { class => 'DBD::Amazon', }, | ||||
327 | best_ => { class => 'DBD::BestWins', }, | ||||
328 | csv_ => { class => 'DBD::CSV', }, | ||||
329 | cubrid_ => { class => 'DBD::cubrid', }, | ||||
330 | db2_ => { class => 'DBD::DB2', }, | ||||
331 | dbi_ => { class => 'DBI', }, | ||||
332 | dbm_ => { class => 'DBD::DBM', }, | ||||
333 | df_ => { class => 'DBD::DF', }, | ||||
334 | examplep_ => { class => 'DBD::ExampleP', }, | ||||
335 | f_ => { class => 'DBD::File', }, | ||||
336 | file_ => { class => 'DBD::TextFile', }, | ||||
337 | go_ => { class => 'DBD::Gofer', }, | ||||
338 | ib_ => { class => 'DBD::InterBase', }, | ||||
339 | ing_ => { class => 'DBD::Ingres', }, | ||||
340 | ix_ => { class => 'DBD::Informix', }, | ||||
341 | jdbc_ => { class => 'DBD::JDBC', }, | ||||
342 | mo_ => { class => 'DBD::MO', }, | ||||
343 | monetdb_ => { class => 'DBD::monetdb', }, | ||||
344 | msql_ => { class => 'DBD::mSQL', }, | ||||
345 | mvsftp_ => { class => 'DBD::MVS_FTPSQL', }, | ||||
346 | mysql_ => { class => 'DBD::mysql', }, | ||||
347 | mx_ => { class => 'DBD::Multiplex', }, | ||||
348 | nullp_ => { class => 'DBD::NullP', }, | ||||
349 | odbc_ => { class => 'DBD::ODBC', }, | ||||
350 | ora_ => { class => 'DBD::Oracle', }, | ||||
351 | pg_ => { class => 'DBD::Pg', }, | ||||
352 | pgpp_ => { class => 'DBD::PgPP', }, | ||||
353 | plb_ => { class => 'DBD::Plibdata', }, | ||||
354 | po_ => { class => 'DBD::PO', }, | ||||
355 | proxy_ => { class => 'DBD::Proxy', }, | ||||
356 | ram_ => { class => 'DBD::RAM', }, | ||||
357 | rdb_ => { class => 'DBD::RDB', }, | ||||
358 | sapdb_ => { class => 'DBD::SAP_DB', }, | ||||
359 | snmp_ => { class => 'DBD::SNMP', }, | ||||
360 | solid_ => { class => 'DBD::Solid', }, | ||||
361 | spatialite_ => { class => 'DBD::Spatialite', }, | ||||
362 | sponge_ => { class => 'DBD::Sponge', }, | ||||
363 | sql_ => { class => 'DBI::DBD::SqlEngine', }, | ||||
364 | sqlite_ => { class => 'DBD::SQLite', }, | ||||
365 | syb_ => { class => 'DBD::Sybase', }, | ||||
366 | sys_ => { class => 'DBD::Sys', }, | ||||
367 | tdat_ => { class => 'DBD::Teradata', }, | ||||
368 | tmpl_ => { class => 'DBD::Template', }, | ||||
369 | tmplss_ => { class => 'DBD::TemplateSS', }, | ||||
370 | tree_ => { class => 'DBD::TreeData', }, | ||||
371 | tuber_ => { class => 'DBD::Tuber', }, | ||||
372 | uni_ => { class => 'DBD::Unify', }, | ||||
373 | vt_ => { class => 'DBD::Vt', }, | ||||
374 | wmi_ => { class => 'DBD::WMI', }, | ||||
375 | x_ => { }, # for private use | ||||
376 | xbase_ => { class => 'DBD::XBase', }, | ||||
377 | xl_ => { class => 'DBD::Excel', }, | ||||
378 | yaswi_ => { class => 'DBD::Yaswi', }, | ||||
379 | }; | ||||
380 | |||||
381 | my %dbd_class_registry = map { $dbd_prefix_registry->{$_}->{class} => { prefix => $_ } } | ||||
382 | grep { exists $dbd_prefix_registry->{$_}->{class} } | ||||
383 | keys %{$dbd_prefix_registry}; | ||||
384 | |||||
385 | sub dump_dbd_registry { | ||||
386 | require Data::Dumper; | ||||
387 | local $Data::Dumper::Sortkeys=1; | ||||
388 | local $Data::Dumper::Indent=1; | ||||
389 | print Data::Dumper->Dump([$dbd_prefix_registry], [qw($dbd_prefix_registry)]); | ||||
390 | } | ||||
391 | |||||
392 | # --- Dynamically create the DBI Standard Interface | ||||
393 | |||||
394 | my $keeperr = { O=>0x0004 }; | ||||
395 | |||||
396 | %DBI::DBI_methods = ( # Define the DBI interface methods per class: | ||||
397 | |||||
398 | common => { # Interface methods common to all DBI handle classes | ||||
399 | 'DESTROY' => { O=>0x004|0x10000 }, | ||||
400 | 'CLEAR' => $keeperr, | ||||
401 | 'EXISTS' => $keeperr, | ||||
402 | 'FETCH' => { O=>0x0404 }, | ||||
403 | 'FETCH_many' => { O=>0x0404 }, | ||||
404 | 'FIRSTKEY' => $keeperr, | ||||
405 | 'NEXTKEY' => $keeperr, | ||||
406 | 'STORE' => { O=>0x0418 | 0x4 }, | ||||
407 | can => { O=>0x0100 }, # special case, see dispatch | ||||
408 | debug => { U =>[1,2,'[$debug_level]'], O=>0x0004 }, # old name for trace | ||||
409 | dump_handle => { U =>[1,3,'[$message [, $level]]'], O=>0x0004 }, | ||||
410 | err => $keeperr, | ||||
411 | errstr => $keeperr, | ||||
412 | state => $keeperr, | ||||
413 | func => { O=>0x0006 }, | ||||
414 | parse_trace_flag => { U =>[2,2,'$name'], O=>0x0404, T=>8 }, | ||||
415 | parse_trace_flags => { U =>[2,2,'$flags'], O=>0x0404, T=>8 }, | ||||
416 | private_data => { U =>[1,1], O=>0x0004 }, | ||||
417 | set_err => { U =>[3,6,'$err, $errmsg [, $state, $method, $rv]'], O=>0x0010 }, | ||||
418 | trace => { U =>[1,3,'[$trace_level, [$filename]]'], O=>0x0004 }, | ||||
419 | trace_msg => { U =>[2,3,'$message_text [, $min_level ]' ], O=>0x0004, T=>8 }, | ||||
420 | swap_inner_handle => { U =>[2,3,'$h [, $allow_reparent ]'] }, | ||||
421 | private_attribute_info => { }, | ||||
422 | visit_child_handles => { U => [2,3,'$coderef [, $info ]'], O=>0x0404, T=>4 }, | ||||
423 | }, | ||||
424 | dr => { # Database Driver Interface | ||||
425 | 'connect' => { U =>[1,5,'[$db [,$user [,$passwd [,\%attr]]]]'], H=>3, O=>0x8000, T=>0x200 }, | ||||
426 | 'connect_cached'=>{U=>[1,5,'[$db [,$user [,$passwd [,\%attr]]]]'], H=>3, O=>0x8000, T=>0x200 }, | ||||
427 | 'disconnect_all'=>{ U =>[1,1], O=>0x0800, T=>0x200 }, | ||||
428 | data_sources => { U =>[1,2,'[\%attr]' ], O=>0x0800, T=>0x200 }, | ||||
429 | default_user => { U =>[3,4,'$user, $pass [, \%attr]' ], T=>0x200 }, | ||||
430 | dbixs_revision => $keeperr, | ||||
431 | }, | ||||
432 | db => { # Database Session Class Interface | ||||
433 | data_sources => { U =>[1,2,'[\%attr]' ], O=>0x0200 }, | ||||
434 | take_imp_data => { U =>[1,1], O=>0x10000 }, | ||||
435 | clone => { U =>[1,2,'[\%attr]'], T=>0x200 }, | ||||
436 | connected => { U =>[1,0], O => 0x0004, T=>0x200, H=>3 }, | ||||
437 | begin_work => { U =>[1,2,'[ \%attr ]'], O=>0x0400, T=>0x1000 }, | ||||
438 | commit => { U =>[1,1], O=>0x0480|0x0800, T=>0x1000 }, | ||||
439 | rollback => { U =>[1,1], O=>0x0480|0x0800, T=>0x1000 }, | ||||
440 | 'do' => { U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'], O=>0x3200 }, | ||||
441 | last_insert_id => { U =>[5,6,'$catalog, $schema, $table_name, $field_name [, \%attr ]'], O=>0x2800 }, | ||||
442 | preparse => { }, # XXX | ||||
443 | prepare => { U =>[2,3,'$statement [, \%attr]'], O=>0xA200 }, | ||||
444 | prepare_cached => { U =>[2,4,'$statement [, \%attr [, $if_active ] ]'], O=>0xA200 }, | ||||
445 | selectrow_array => { U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'], O=>0x2000 }, | ||||
446 | selectrow_arrayref=>{U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'], O=>0x2000 }, | ||||
447 | selectrow_hashref=>{ U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'], O=>0x2000 }, | ||||
448 | selectall_arrayref=>{U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'], O=>0x2000 }, | ||||
449 | selectall_hashref=>{ U =>[3,0,'$statement, $keyfield [, \%attr [, @bind_params ] ]'], O=>0x2000 }, | ||||
450 | selectcol_arrayref=>{U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'], O=>0x2000 }, | ||||
451 | ping => { U =>[1,1], O=>0x0404 }, | ||||
452 | disconnect => { U =>[1,1], O=>0x0400|0x0800|0x10000, T=>0x200 }, | ||||
453 | quote => { U =>[2,3, '$string [, $data_type ]' ], O=>0x0430, T=>2 }, | ||||
454 | quote_identifier=> { U =>[2,6, '$name [, ...] [, \%attr ]' ], O=>0x0430, T=>2 }, | ||||
455 | rows => $keeperr, | ||||
456 | |||||
457 | tables => { U =>[1,6,'$catalog, $schema, $table, $type [, \%attr ]' ], O=>0x2200 }, | ||||
458 | table_info => { U =>[1,6,'$catalog, $schema, $table, $type [, \%attr ]' ], O=>0x2200|0x8800 }, | ||||
459 | column_info => { U =>[5,6,'$catalog, $schema, $table, $column [, \%attr ]'],O=>0x2200|0x8800 }, | ||||
460 | primary_key_info=> { U =>[4,5,'$catalog, $schema, $table [, \%attr ]' ], O=>0x2200|0x8800 }, | ||||
461 | primary_key => { U =>[4,5,'$catalog, $schema, $table [, \%attr ]' ], O=>0x2200 }, | ||||
462 | foreign_key_info=> { U =>[7,8,'$pk_catalog, $pk_schema, $pk_table, $fk_catalog, $fk_schema, $fk_table [, \%attr ]' ], O=>0x2200|0x8800 }, | ||||
463 | statistics_info => { U =>[6,7,'$catalog, $schema, $table, $unique_only, $quick, [, \%attr ]' ], O=>0x2200|0x8800 }, | ||||
464 | type_info_all => { U =>[1,1], O=>0x2200|0x0800 }, | ||||
465 | type_info => { U =>[1,2,'$data_type'], O=>0x2200 }, | ||||
466 | get_info => { U =>[2,2,'$info_type'], O=>0x2200|0x0800 }, | ||||
467 | }, | ||||
468 | st => { # Statement Class Interface | ||||
469 | bind_col => { U =>[3,4,'$column, \\$var [, \%attr]'] }, | ||||
470 | bind_columns => { U =>[2,0,'\\$var1 [, \\$var2, ...]'] }, | ||||
471 | bind_param => { U =>[3,4,'$parameter, $var [, \%attr]'] }, | ||||
472 | bind_param_inout=> { U =>[4,5,'$parameter, \\$var, $maxlen, [, \%attr]'] }, | ||||
473 | execute => { U =>[1,0,'[@args]'], O=>0x1040 }, | ||||
474 | |||||
475 | bind_param_array => { U =>[3,4,'$parameter, $var [, \%attr]'] }, | ||||
476 | bind_param_inout_array => { U =>[4,5,'$parameter, \\@var, $maxlen, [, \%attr]'] }, | ||||
477 | execute_array => { U =>[2,0,'\\%attribs [, @args]'], O=>0x1040|0x4000 }, | ||||
478 | execute_for_fetch => { U =>[2,3,'$fetch_sub [, $tuple_status]'], O=>0x1040|0x4000 }, | ||||
479 | |||||
480 | fetch => undef, # alias for fetchrow_arrayref | ||||
481 | fetchrow_arrayref => undef, | ||||
482 | fetchrow_hashref => undef, | ||||
483 | fetchrow_array => undef, | ||||
484 | fetchrow => undef, # old alias for fetchrow_array | ||||
485 | |||||
486 | fetchall_arrayref => { U =>[1,3, '[ $slice [, $max_rows]]'] }, | ||||
487 | fetchall_hashref => { U =>[2,2,'$key_field'] }, | ||||
488 | |||||
489 | blob_read => { U =>[4,5,'$field, $offset, $len [, \\$buf [, $bufoffset]]'] }, | ||||
490 | blob_copy_to_file => { U =>[3,3,'$field, $filename_or_handleref'] }, | ||||
491 | dump_results => { U =>[1,5,'$maxfieldlen, $linesep, $fieldsep, $filehandle'] }, | ||||
492 | more_results => { U =>[1,1] }, | ||||
493 | finish => { U =>[1,1] }, | ||||
494 | cancel => { U =>[1,1], O=>0x0800 }, | ||||
495 | rows => $keeperr, | ||||
496 | |||||
497 | _get_fbav => undef, | ||||
498 | _set_fbav => { T=>6 }, | ||||
499 | }, | ||||
500 | ); | ||||
501 | |||||
502 | while ( my ($class, $meths) = each %DBI::DBI_methods ) { | ||||
503 | my $ima_trace = 0+($ENV{DBI_IMA_TRACE}||0); | ||||
504 | while ( my ($method, $info) = each %$meths ) { | ||||
505 | my $fullmeth = "DBI::${class}::$method"; | ||||
506 | if (($DBI::dbi_debug & 0xF) == 15) { # quick hack to list DBI methods | ||||
507 | # and optionally filter by IMA flags | ||||
508 | my $O = $info->{O}||0; | ||||
509 | printf "0x%04x %-20s\n", $O, $fullmeth | ||||
510 | unless $ima_trace && !($O & $ima_trace); | ||||
511 | } | ||||
512 | DBI->_install_method($fullmeth, 'DBI.pm', $info); | ||||
513 | } | ||||
514 | } | ||||
515 | |||||
516 | { | ||||
517 | package DBI::common; | ||||
518 | @DBI::dr::ISA = ('DBI::common'); | ||||
519 | @DBI::db::ISA = ('DBI::common'); | ||||
520 | @DBI::st::ISA = ('DBI::common'); | ||||
521 | } | ||||
522 | |||||
523 | # End of init code | ||||
524 | |||||
525 | |||||
526 | END { | ||||
527 | return unless defined &DBI::trace_msg; # return unless bootstrap'd ok | ||||
528 | local ($!,$?); | ||||
529 | DBI->trace_msg(sprintf(" -- DBI::END (\$\@: %s, \$!: %s)\n", $@||'', $!||''), 2); | ||||
530 | # Let drivers know why we are calling disconnect_all: | ||||
531 | $DBI::PERL_ENDING = $DBI::PERL_ENDING = 1; # avoid typo warning | ||||
532 | DBI->disconnect_all() if %DBI::installed_drh; | ||||
533 | } | ||||
534 | |||||
535 | |||||
536 | sub CLONE { | ||||
537 | _clone_dbis() unless $DBI::PurePerl; # clone the DBIS structure | ||||
538 | DBI->trace_msg("CLONE DBI for new thread\n"); | ||||
539 | while ( my ($driver, $drh) = each %DBI::installed_drh) { | ||||
540 | no strict 'refs'; | ||||
541 | next if defined &{"DBD::${driver}::CLONE"}; | ||||
542 | warn("$driver has no driver CLONE() function so is unsafe threaded\n"); | ||||
543 | } | ||||
544 | %DBI::installed_drh = (); # clear loaded drivers so they have a chance to reinitialize | ||||
545 | } | ||||
546 | |||||
547 | sub parse_dsn { | ||||
548 | my ($class, $dsn) = @_; | ||||
549 | $dsn =~ s/^(dbi):(\w*?)(?:\((.*?)\))?://i or return; | ||||
550 | my ($scheme, $driver, $attr, $attr_hash) = (lc($1), $2, $3); | ||||
551 | $driver ||= $ENV{DBI_DRIVER} || ''; | ||||
552 | $attr_hash = { split /\s*=>?\s*|\s*,\s*/, $attr, -1 } if $attr; | ||||
553 | return ($scheme, $driver, $attr, $attr_hash, $dsn); | ||||
554 | } | ||||
555 | |||||
556 | sub visit_handles { | ||||
557 | my ($class, $code, $outer_info) = @_; | ||||
558 | $outer_info = {} if not defined $outer_info; | ||||
559 | my %drh = DBI->installed_drivers; | ||||
560 | for my $h (values %drh) { | ||||
561 | my $child_info = $code->($h, $outer_info) | ||||
562 | or next; | ||||
563 | $h->visit_child_handles($code, $child_info); | ||||
564 | } | ||||
565 | return $outer_info; | ||||
566 | } | ||||
567 | |||||
568 | |||||
569 | # --- The DBI->connect Front Door methods | ||||
570 | |||||
571 | sub connect_cached { | ||||
572 | # For library code using connect_cached() with mod_perl | ||||
573 | # we redirect those calls to Apache::DBI::connect() as well | ||||
574 | my ($class, $dsn, $user, $pass, $attr) = @_; | ||||
575 | my $dbi_connect_method = ($DBI::connect_via eq "Apache::DBI::connect") | ||||
576 | ? 'Apache::DBI::connect' : 'connect_cached'; | ||||
577 | $attr = { | ||||
578 | $attr ? %$attr : (), # clone, don't modify callers data | ||||
579 | dbi_connect_method => $dbi_connect_method, | ||||
580 | }; | ||||
581 | return $class->connect($dsn, $user, $pass, $attr); | ||||
582 | } | ||||
583 | |||||
584 | sub connect { | ||||
585 | my $class = shift; | ||||
586 | my ($dsn, $user, $pass, $attr, $old_driver) = my @orig_args = @_; | ||||
587 | my $driver; | ||||
588 | |||||
589 | if ($attr and !ref($attr)) { # switch $old_driver<->$attr if called in old style | ||||
590 | Carp::carp("DBI->connect using 'old-style' syntax is deprecated and will be an error in future versions"); | ||||
591 | ($old_driver, $attr) = ($attr, $old_driver); | ||||
592 | } | ||||
593 | |||||
594 | my $connect_meth = $attr->{dbi_connect_method}; | ||||
595 | $connect_meth ||= $DBI::connect_via; # fallback to default | ||||
596 | |||||
597 | $dsn ||= $ENV{DBI_DSN} || $ENV{DBI_DBNAME} || '' unless $old_driver; | ||||
598 | |||||
599 | if ($DBI::dbi_debug) { | ||||
600 | local $^W = 0; | ||||
601 | pop @_ if $connect_meth ne 'connect'; | ||||
602 | my @args = @_; $args[2] = '****'; # hide password | ||||
603 | DBI->trace_msg(" -> $class->$connect_meth(".join(", ",@args).")\n"); | ||||
604 | } | ||||
605 | Carp::croak('Usage: $class->connect([$dsn [,$user [,$passwd [,\%attr]]]])') | ||||
606 | if (ref $old_driver or ($attr and not ref $attr) or ref $pass); | ||||
607 | |||||
608 | # extract dbi:driver prefix from $dsn into $1 | ||||
609 | $dsn =~ s/^dbi:(\w*?)(?:\((.*?)\))?://i | ||||
610 | or '' =~ /()/; # ensure $1 etc are empty if match fails | ||||
611 | my $driver_attrib_spec = $2 || ''; | ||||
612 | |||||
613 | # Set $driver. Old style driver, if specified, overrides new dsn style. | ||||
614 | $driver = $old_driver || $1 || $ENV{DBI_DRIVER} | ||||
615 | or Carp::croak("Can't connect to data source '$dsn' " | ||||
616 | ."because I can't work out what driver to use " | ||||
617 | ."(it doesn't seem to contain a 'dbi:driver:' prefix " | ||||
618 | ."and the DBI_DRIVER env var is not set)"); | ||||
619 | |||||
620 | my $proxy; | ||||
621 | if ($ENV{DBI_AUTOPROXY} && $driver ne 'Proxy' && $driver ne 'Sponge' && $driver ne 'Switch') { | ||||
622 | my $dbi_autoproxy = $ENV{DBI_AUTOPROXY}; | ||||
623 | $proxy = 'Proxy'; | ||||
624 | if ($dbi_autoproxy =~ s/^dbi:(\w*?)(?:\((.*?)\))?://i) { | ||||
625 | $proxy = $1; | ||||
626 | $driver_attrib_spec = join ",", | ||||
627 | ($driver_attrib_spec) ? $driver_attrib_spec : (), | ||||
628 | ($2 ) ? $2 : (); | ||||
629 | } | ||||
630 | $dsn = "$dbi_autoproxy;dsn=dbi:$driver:$dsn"; | ||||
631 | $driver = $proxy; | ||||
632 | DBI->trace_msg(" DBI_AUTOPROXY: dbi:$driver($driver_attrib_spec):$dsn\n"); | ||||
633 | } | ||||
634 | # avoid recursion if proxy calls DBI->connect itself | ||||
635 | local $ENV{DBI_AUTOPROXY} if $ENV{DBI_AUTOPROXY}; | ||||
636 | |||||
637 | my %attributes; # take a copy we can delete from | ||||
638 | if ($old_driver) { | ||||
639 | %attributes = %$attr if $attr; | ||||
640 | } | ||||
641 | else { # new-style connect so new default semantics | ||||
642 | %attributes = ( | ||||
643 | PrintError => 1, | ||||
644 | AutoCommit => 1, | ||||
645 | ref $attr ? %$attr : (), | ||||
646 | # attributes in DSN take precedence over \%attr connect parameter | ||||
647 | $driver_attrib_spec ? (split /\s*=>?\s*|\s*,\s*/, $driver_attrib_spec, -1) : (), | ||||
648 | ); | ||||
649 | } | ||||
650 | $attr = \%attributes; # now set $attr to refer to our local copy | ||||
651 | |||||
652 | my $drh = $DBI::installed_drh{$driver} || $class->install_driver($driver) | ||||
653 | or die "panic: $class->install_driver($driver) failed"; | ||||
654 | |||||
655 | # attributes in DSN take precedence over \%attr connect parameter | ||||
656 | $user = $attr->{Username} if defined $attr->{Username}; | ||||
657 | $pass = $attr->{Password} if defined $attr->{Password}; | ||||
658 | delete $attr->{Password}; # always delete Password as closure stores it securely | ||||
659 | if ( !(defined $user && defined $pass) ) { | ||||
660 | ($user, $pass) = $drh->default_user($user, $pass, $attr); | ||||
661 | } | ||||
662 | $attr->{Username} = $user; # force the Username to be the actual one used | ||||
663 | |||||
664 | my $connect_closure = sub { | ||||
665 | my ($old_dbh, $override_attr) = @_; | ||||
666 | |||||
667 | #use Data::Dumper; | ||||
668 | #warn "connect_closure: ".Data::Dumper::Dumper([$attr,\%attributes, $override_attr]); | ||||
669 | |||||
670 | my $dbh; | ||||
671 | 1 | 14.5ms | unless ($dbh = $drh->$connect_meth($dsn, $user, $pass, $attr)) { # spent 14.5ms making 1 call to DBD::mysql::dr::connect | ||
672 | $user = '' if !defined $user; | ||||
673 | $dsn = '' if !defined $dsn; | ||||
674 | # $drh->errstr isn't safe here because $dbh->DESTROY may not have | ||||
675 | # been called yet and so the dbh errstr would not have been copied | ||||
676 | # up to the drh errstr. Certainly true for connect_cached! | ||||
677 | my $errstr = $DBI::errstr; | ||||
678 | # Getting '(no error string)' here is a symptom of a ref loop | ||||
679 | $errstr = '(no error string)' if !defined $errstr; | ||||
680 | my $msg = "$class connect('$dsn','$user',...) failed: $errstr"; | ||||
681 | DBI->trace_msg(" $msg\n"); | ||||
682 | # XXX HandleWarn | ||||
683 | unless ($attr->{HandleError} && $attr->{HandleError}->($msg, $drh, $dbh)) { | ||||
684 | Carp::croak($msg) if $attr->{RaiseError}; | ||||
685 | Carp::carp ($msg) if $attr->{PrintError}; | ||||
686 | } | ||||
687 | $! = 0; # for the daft people who do DBI->connect(...) || die "$!"; | ||||
688 | return $dbh; # normally undef, but HandleError could change it | ||||
689 | } | ||||
690 | |||||
691 | # merge any attribute overrides but don't change $attr itself (for closure) | ||||
692 | my $apply = { ($override_attr) ? (%$attr, %$override_attr ) : %$attr }; | ||||
693 | |||||
694 | # handle basic RootClass subclassing: | ||||
695 | my $rebless_class = $apply->{RootClass} || ($class ne 'DBI' ? $class : ''); | ||||
696 | if ($rebless_class) { | ||||
697 | no strict 'refs'; | ||||
698 | if ($apply->{RootClass}) { # explicit attribute (ie not static method call class) | ||||
699 | delete $apply->{RootClass}; | ||||
700 | DBI::_load_class($rebless_class, 0); | ||||
701 | } | ||||
702 | unless (@{"$rebless_class\::db::ISA"} && @{"$rebless_class\::st::ISA"}) { | ||||
703 | Carp::carp("DBI subclasses '$rebless_class\::db' and ::st are not setup, RootClass ignored"); | ||||
704 | $rebless_class = undef; | ||||
705 | $class = 'DBI'; | ||||
706 | } | ||||
707 | else { | ||||
708 | $dbh->{RootClass} = $rebless_class; # $dbh->STORE called via plain DBI::db | ||||
709 | DBI::_set_isa([$rebless_class], 'DBI'); # sets up both '::db' and '::st' | ||||
710 | DBI::_rebless($dbh, $rebless_class); # appends '::db' | ||||
711 | } | ||||
712 | } | ||||
713 | |||||
714 | if (%$apply) { | ||||
715 | |||||
716 | if ($apply->{DbTypeSubclass}) { | ||||
717 | my $DbTypeSubclass = delete $apply->{DbTypeSubclass}; | ||||
718 | DBI::_rebless_dbtype_subclass($dbh, $rebless_class||$class, $DbTypeSubclass); | ||||
719 | } | ||||
720 | my $a; | ||||
721 | foreach $a (qw(Profile RaiseError PrintError AutoCommit)) { # do these first | ||||
722 | next unless exists $apply->{$a}; | ||||
723 | 3 | 9µs | $dbh->{$a} = delete $apply->{$a}; # spent 9µs making 3 calls to DBI::common::STORE, avg 3µs/call | ||
724 | } | ||||
725 | while ( my ($a, $v) = each %$apply) { | ||||
726 | 3 | 6µs | eval { $dbh->{$a} = $v }; # assign in void context to avoid re-FETCH # spent 6µs making 3 calls to DBI::common::STORE, avg 2µs/call | ||
727 | warn $@ if $@; | ||||
728 | } | ||||
729 | } | ||||
730 | |||||
731 | # confirm to driver (ie if subclassed) that we've connected successfully | ||||
732 | # and finished the attribute setup. pass in the original arguments | ||||
733 | $dbh->connected(@orig_args); #if ref $dbh ne 'DBI::db' or $proxy; | ||||
734 | |||||
735 | DBI->trace_msg(" <- connect= $dbh\n") if $DBI::dbi_debug & 0xF; | ||||
736 | |||||
737 | return $dbh; | ||||
738 | }; | ||||
739 | |||||
740 | my $dbh = &$connect_closure(undef, undef); | ||||
741 | |||||
742 | 1 | 10µs | $dbh->{dbi_connect_closure} = $connect_closure if $dbh; # spent 10µs making 1 call to DBI::common::STORE | ||
743 | |||||
744 | return $dbh; | ||||
745 | } | ||||
746 | |||||
747 | |||||
748 | sub disconnect_all { | ||||
749 | keys %DBI::installed_drh; # reset iterator | ||||
750 | while ( my ($name, $drh) = each %DBI::installed_drh ) { | ||||
751 | $drh->disconnect_all() if ref $drh; | ||||
752 | } | ||||
753 | } | ||||
754 | |||||
755 | |||||
756 | sub disconnect { # a regular beginners bug | ||||
757 | Carp::croak("DBI->disconnect is not a DBI method (read the DBI manual)"); | ||||
758 | } | ||||
759 | |||||
760 | |||||
761 | sub install_driver { # croaks on failure | ||||
762 | my $class = shift; | ||||
763 | my($driver, $attr) = @_; | ||||
764 | my $drh; | ||||
765 | |||||
766 | $driver ||= $ENV{DBI_DRIVER} || ''; | ||||
767 | |||||
768 | # allow driver to be specified as a 'dbi:driver:' string | ||||
769 | $driver = $1 if $driver =~ s/^DBI:(.*?)://i; | ||||
770 | |||||
771 | Carp::croak("usage: $class->install_driver(\$driver [, \%attr])") | ||||
772 | unless ($driver and @_<=3); | ||||
773 | |||||
774 | # already installed | ||||
775 | return $drh if $drh = $DBI::installed_drh{$driver}; | ||||
776 | |||||
777 | $class->trace_msg(" -> $class->install_driver($driver" | ||||
778 | .") for $^O perl=$] pid=$$ ruid=$< euid=$>\n") | ||||
779 | if $DBI::dbi_debug & 0xF; | ||||
780 | |||||
781 | # --- load the code | ||||
782 | my $driver_class = "DBD::$driver"; | ||||
783 | eval qq{package # hide from PAUSE | ||||
784 | DBI::_firesafe; # just in case | ||||
785 | require $driver_class; # load the driver | ||||
786 | }; | ||||
787 | if ($@) { | ||||
788 | my $err = $@; | ||||
789 | my $advice = ""; | ||||
790 | if ($err =~ /Can't find loadable object/) { | ||||
791 | $advice = "Perhaps DBD::$driver was statically linked into a new perl binary." | ||||
792 | ."\nIn which case you need to use that new perl binary." | ||||
793 | ."\nOr perhaps only the .pm file was installed but not the shared object file." | ||||
794 | } | ||||
795 | elsif ($err =~ /Can't locate.*?DBD\/$driver\.pm in \@INC/) { | ||||
796 | my @drv = $class->available_drivers(1); | ||||
797 | $advice = "Perhaps the DBD::$driver perl module hasn't been fully installed,\n" | ||||
798 | ."or perhaps the capitalisation of '$driver' isn't right.\n" | ||||
799 | ."Available drivers: ".join(", ", @drv)."."; | ||||
800 | } | ||||
801 | elsif ($err =~ /Can't load .*? for module DBD::/) { | ||||
802 | $advice = "Perhaps a required shared library or dll isn't installed where expected"; | ||||
803 | } | ||||
804 | elsif ($err =~ /Can't locate .*? in \@INC/) { | ||||
805 | $advice = "Perhaps a module that DBD::$driver requires hasn't been fully installed"; | ||||
806 | } | ||||
807 | Carp::croak("install_driver($driver) failed: $err$advice\n"); | ||||
808 | } | ||||
809 | if ($DBI::dbi_debug & 0xF) { | ||||
810 | no strict 'refs'; | ||||
811 | (my $driver_file = $driver_class) =~ s/::/\//g; | ||||
812 | my $dbd_ver = ${"$driver_class\::VERSION"} || "undef"; | ||||
813 | $class->trace_msg(" install_driver: $driver_class version $dbd_ver" | ||||
814 | ." loaded from $INC{qq($driver_file.pm)}\n"); | ||||
815 | } | ||||
816 | |||||
817 | # --- do some behind-the-scenes checks and setups on the driver | ||||
818 | $class->setup_driver($driver_class); | ||||
819 | |||||
820 | # --- run the driver function | ||||
821 | $drh = eval { $driver_class->driver($attr || {}) }; | ||||
822 | unless ($drh && ref $drh && !$@) { | ||||
823 | my $advice = ""; | ||||
824 | $@ ||= "$driver_class->driver didn't return a handle"; | ||||
825 | # catch people on case in-sensitive systems using the wrong case | ||||
826 | $advice = "\nPerhaps the capitalisation of DBD '$driver' isn't right." | ||||
827 | if $@ =~ /locate object method/; | ||||
828 | Carp::croak("$driver_class initialisation failed: $@$advice"); | ||||
829 | } | ||||
830 | |||||
831 | $DBI::installed_drh{$driver} = $drh; | ||||
832 | $class->trace_msg(" <- install_driver= $drh\n") if $DBI::dbi_debug & 0xF; | ||||
833 | $drh; | ||||
834 | } | ||||
835 | |||||
836 | *driver = \&install_driver; # currently an alias, may change | ||||
837 | |||||
838 | |||||
839 | sub setup_driver { | ||||
840 | my ($class, $driver_class) = @_; | ||||
841 | my $h_type; | ||||
842 | foreach $h_type (qw(dr db st)){ | ||||
843 | my $h_class = $driver_class."::$h_type"; | ||||
844 | no strict 'refs'; | ||||
845 | push @{"${h_class}::ISA"}, "DBD::_::$h_type" | ||||
846 | unless UNIVERSAL::isa($h_class, "DBD::_::$h_type"); | ||||
847 | # The _mem class stuff is (IIRC) a crufty hack for global destruction | ||||
848 | # timing issues in early versions of perl5 and possibly no longer needed. | ||||
849 | my $mem_class = "DBD::_mem::$h_type"; | ||||
850 | push @{"${h_class}_mem::ISA"}, $mem_class | ||||
851 | unless UNIVERSAL::isa("${h_class}_mem", $mem_class) | ||||
852 | or $DBI::PurePerl; | ||||
853 | } | ||||
854 | } | ||||
855 | |||||
856 | |||||
857 | sub _rebless { | ||||
858 | my $dbh = shift; | ||||
859 | my ($outer, $inner) = DBI::_handles($dbh); | ||||
860 | my $class = shift(@_).'::db'; | ||||
861 | bless $inner => $class; | ||||
862 | bless $outer => $class; # outer last for return | ||||
863 | } | ||||
864 | |||||
865 | |||||
866 | sub _set_isa { | ||||
867 | my ($classes, $topclass) = @_; | ||||
868 | my $trace = DBI->trace_msg(" _set_isa([@$classes])\n"); | ||||
869 | foreach my $suffix ('::db','::st') { | ||||
870 | my $previous = $topclass || 'DBI'; # trees are rooted here | ||||
871 | foreach my $class (@$classes) { | ||||
872 | my $base_class = $previous.$suffix; | ||||
873 | my $sub_class = $class.$suffix; | ||||
874 | my $sub_class_isa = "${sub_class}::ISA"; | ||||
875 | no strict 'refs'; | ||||
876 | if (@$sub_class_isa) { | ||||
877 | DBI->trace_msg(" $sub_class_isa skipped (already set to @$sub_class_isa)\n") | ||||
878 | if $trace; | ||||
879 | } | ||||
880 | else { | ||||
881 | @$sub_class_isa = ($base_class) unless @$sub_class_isa; | ||||
882 | DBI->trace_msg(" $sub_class_isa = $base_class\n") | ||||
883 | if $trace; | ||||
884 | } | ||||
885 | $previous = $class; | ||||
886 | } | ||||
887 | } | ||||
888 | } | ||||
889 | |||||
890 | |||||
891 | sub _rebless_dbtype_subclass { | ||||
892 | my ($dbh, $rootclass, $DbTypeSubclass) = @_; | ||||
893 | # determine the db type names for class hierarchy | ||||
894 | my @hierarchy = DBI::_dbtype_names($dbh, $DbTypeSubclass); | ||||
895 | # add the rootclass prefix to each ('DBI::' or 'MyDBI::' etc) | ||||
896 | $_ = $rootclass.'::'.$_ foreach (@hierarchy); | ||||
897 | # load the modules from the 'top down' | ||||
898 | DBI::_load_class($_, 1) foreach (reverse @hierarchy); | ||||
899 | # setup class hierarchy if needed, does both '::db' and '::st' | ||||
900 | DBI::_set_isa(\@hierarchy, $rootclass); | ||||
901 | # finally bless the handle into the subclass | ||||
902 | DBI::_rebless($dbh, $hierarchy[0]); | ||||
903 | } | ||||
904 | |||||
905 | |||||
906 | sub _dbtype_names { # list dbtypes for hierarchy, ie Informix=>ADO=>ODBC | ||||
907 | my ($dbh, $DbTypeSubclass) = @_; | ||||
908 | |||||
909 | if ($DbTypeSubclass && $DbTypeSubclass ne '1' && ref $DbTypeSubclass ne 'CODE') { | ||||
910 | # treat $DbTypeSubclass as a comma separated list of names | ||||
911 | my @dbtypes = split /\s*,\s*/, $DbTypeSubclass; | ||||
912 | $dbh->trace_msg(" DbTypeSubclass($DbTypeSubclass)=@dbtypes (explicit)\n"); | ||||
913 | return @dbtypes; | ||||
914 | } | ||||
915 | |||||
916 | # XXX will call $dbh->get_info(17) (=SQL_DBMS_NAME) in future? | ||||
917 | |||||
918 | my $driver = $dbh->{Driver}->{Name}; | ||||
919 | if ( $driver eq 'Proxy' ) { | ||||
920 | # XXX Looking into the internals of DBD::Proxy is questionable! | ||||
921 | ($driver) = $dbh->{proxy_client}->{application} =~ /^DBI:(.+?):/i | ||||
922 | or die "Can't determine driver name from proxy"; | ||||
923 | } | ||||
924 | |||||
925 | my @dbtypes = (ucfirst($driver)); | ||||
926 | if ($driver eq 'ODBC' || $driver eq 'ADO') { | ||||
927 | # XXX will move these out and make extensible later: | ||||
928 | my $_dbtype_name_regexp = 'Oracle'; # eg 'Oracle|Foo|Bar' | ||||
929 | my %_dbtype_name_map = ( | ||||
930 | 'Microsoft SQL Server' => 'MSSQL', | ||||
931 | 'SQL Server' => 'Sybase', | ||||
932 | 'Adaptive Server Anywhere' => 'ASAny', | ||||
933 | 'ADABAS D' => 'AdabasD', | ||||
934 | ); | ||||
935 | |||||
936 | my $name; | ||||
937 | $name = $dbh->func(17, 'GetInfo') # SQL_DBMS_NAME | ||||
938 | if $driver eq 'ODBC'; | ||||
939 | $name = $dbh->{ado_conn}->Properties->Item('DBMS Name')->Value | ||||
940 | if $driver eq 'ADO'; | ||||
941 | die "Can't determine driver name! ($DBI::errstr)\n" | ||||
942 | unless $name; | ||||
943 | |||||
944 | my $dbtype; | ||||
945 | if ($_dbtype_name_map{$name}) { | ||||
946 | $dbtype = $_dbtype_name_map{$name}; | ||||
947 | } | ||||
948 | else { | ||||
949 | if ($name =~ /($_dbtype_name_regexp)/) { | ||||
950 | $dbtype = lc($1); | ||||
951 | } | ||||
952 | else { # generic mangling for other names: | ||||
953 | $dbtype = lc($name); | ||||
954 | } | ||||
955 | $dbtype =~ s/\b(\w)/\U$1/g; | ||||
956 | $dbtype =~ s/\W+/_/g; | ||||
957 | } | ||||
958 | # add ODBC 'behind' ADO | ||||
959 | push @dbtypes, 'ODBC' if $driver eq 'ADO'; | ||||
960 | # add discovered dbtype in front of ADO/ODBC | ||||
961 | unshift @dbtypes, $dbtype; | ||||
962 | } | ||||
963 | @dbtypes = &$DbTypeSubclass($dbh, \@dbtypes) | ||||
964 | if (ref $DbTypeSubclass eq 'CODE'); | ||||
965 | $dbh->trace_msg(" DbTypeSubclass($DbTypeSubclass)=@dbtypes\n"); | ||||
966 | return @dbtypes; | ||||
967 | } | ||||
968 | |||||
969 | sub _load_class { | ||||
970 | my ($load_class, $missing_ok) = @_; | ||||
971 | DBI->trace_msg(" _load_class($load_class, $missing_ok)\n", 2); | ||||
972 | no strict 'refs'; | ||||
973 | return 1 if @{"$load_class\::ISA"}; # already loaded/exists | ||||
974 | (my $module = $load_class) =~ s!::!/!g; | ||||
975 | DBI->trace_msg(" _load_class require $module\n", 2); | ||||
976 | eval { require "$module.pm"; }; | ||||
977 | return 1 unless $@; | ||||
978 | return 0 if $missing_ok && $@ =~ /^Can't locate \Q$module.pm\E/; | ||||
979 | die $@; | ||||
980 | } | ||||
981 | |||||
982 | |||||
983 | sub init_rootclass { # deprecated | ||||
984 | return 1; | ||||
985 | } | ||||
986 | |||||
987 | |||||
988 | *internal = \&DBD::Switch::dr::driver; | ||||
989 | |||||
990 | sub driver_prefix { | ||||
991 | my ($class, $driver) = @_; | ||||
992 | return $dbd_class_registry{$driver}->{prefix} if exists $dbd_class_registry{$driver}; | ||||
993 | return; | ||||
994 | } | ||||
995 | |||||
996 | sub available_drivers { | ||||
997 | my($quiet) = @_; | ||||
998 | my(@drivers, $d, $f); | ||||
999 | local(*DBI::DIR, $@); | ||||
1000 | my(%seen_dir, %seen_dbd); | ||||
1001 | my $haveFileSpec = eval { require File::Spec }; | ||||
1002 | foreach $d (@INC){ | ||||
1003 | chomp($d); # Perl 5 beta 3 bug in #!./perl -Ilib from Test::Harness | ||||
1004 | my $dbd_dir = | ||||
1005 | ($haveFileSpec ? File::Spec->catdir($d, 'DBD') : "$d/DBD"); | ||||
1006 | next unless -d $dbd_dir; | ||||
1007 | next if $seen_dir{$d}; | ||||
1008 | $seen_dir{$d} = 1; | ||||
1009 | # XXX we have a problem here with case insensitive file systems | ||||
1010 | # XXX since we can't tell what case must be used when loading. | ||||
1011 | opendir(DBI::DIR, $dbd_dir) || Carp::carp "opendir $dbd_dir: $!\n"; | ||||
1012 | foreach $f (readdir(DBI::DIR)){ | ||||
1013 | next unless $f =~ s/\.pm$//; | ||||
1014 | next if $f eq 'NullP'; | ||||
1015 | if ($seen_dbd{$f}){ | ||||
1016 | Carp::carp "DBD::$f in $d is hidden by DBD::$f in $seen_dbd{$f}\n" | ||||
1017 | unless $quiet; | ||||
1018 | } else { | ||||
1019 | push(@drivers, $f); | ||||
1020 | } | ||||
1021 | $seen_dbd{$f} = $d; | ||||
1022 | } | ||||
1023 | closedir(DBI::DIR); | ||||
1024 | } | ||||
1025 | |||||
1026 | # "return sort @drivers" will not DWIM in scalar context. | ||||
1027 | return wantarray ? sort @drivers : @drivers; | ||||
1028 | } | ||||
1029 | |||||
1030 | sub installed_versions { | ||||
1031 | my ($class, $quiet) = @_; | ||||
1032 | my %error; | ||||
1033 | my %version; | ||||
1034 | for my $driver ($class->available_drivers($quiet)) { | ||||
1035 | next if $DBI::PurePerl && grep { -d "$_/auto/DBD/$driver" } @INC; | ||||
1036 | my $drh = eval { | ||||
1037 | local $SIG{__WARN__} = sub {}; | ||||
1038 | $class->install_driver($driver); | ||||
1039 | }; | ||||
1040 | ($error{"DBD::$driver"}=$@),next if $@; | ||||
1041 | no strict 'refs'; | ||||
1042 | my $vers = ${"DBD::$driver" . '::VERSION'}; | ||||
1043 | $version{"DBD::$driver"} = $vers || '?'; | ||||
1044 | } | ||||
1045 | if (wantarray) { | ||||
1046 | return map { m/^DBD::(\w+)/ ? ($1) : () } sort keys %version; | ||||
1047 | } | ||||
1048 | $version{"DBI"} = $DBI::VERSION; | ||||
1049 | $version{"DBI::PurePerl"} = $DBI::PurePerl::VERSION if $DBI::PurePerl; | ||||
1050 | if (!defined wantarray) { # void context | ||||
1051 | require Config; # add more detail | ||||
1052 | $version{OS} = "$^O\t($Config::Config{osvers})"; | ||||
1053 | $version{Perl} = "$]\t($Config::Config{archname})"; | ||||
1054 | $version{$_} = (($error{$_} =~ s/ \(\@INC.*//s),$error{$_}) | ||||
1055 | for keys %error; | ||||
1056 | printf " %-16s: %s\n",$_,$version{$_} | ||||
1057 | for reverse sort keys %version; | ||||
1058 | } | ||||
1059 | return \%version; | ||||
1060 | } | ||||
1061 | |||||
1062 | |||||
1063 | sub data_sources { | ||||
1064 | my ($class, $driver, @other) = @_; | ||||
1065 | my $drh = $class->install_driver($driver); | ||||
1066 | my @ds = $drh->data_sources(@other); | ||||
1067 | return @ds; | ||||
1068 | } | ||||
1069 | |||||
1070 | |||||
1071 | sub neat_list { | ||||
1072 | my ($listref, $maxlen, $sep) = @_; | ||||
1073 | $maxlen = 0 unless defined $maxlen; # 0 == use internal default | ||||
1074 | $sep = ", " unless defined $sep; | ||||
1075 | join($sep, map { neat($_,$maxlen) } @$listref); | ||||
1076 | } | ||||
1077 | |||||
1078 | |||||
1079 | sub dump_results { # also aliased as a method in DBD::_::st | ||||
1080 | my ($sth, $maxlen, $lsep, $fsep, $fh) = @_; | ||||
1081 | return 0 unless $sth; | ||||
1082 | $maxlen ||= 35; | ||||
1083 | $lsep ||= "\n"; | ||||
1084 | $fh ||= \*STDOUT; | ||||
1085 | my $rows = 0; | ||||
1086 | my $ref; | ||||
1087 | while($ref = $sth->fetch) { | ||||
1088 | print $fh $lsep if $rows++ and $lsep; | ||||
1089 | my $str = neat_list($ref,$maxlen,$fsep); | ||||
1090 | print $fh $str; # done on two lines to avoid 5.003 errors | ||||
1091 | } | ||||
1092 | print $fh "\n$rows rows".($DBI::err ? " ($DBI::err: $DBI::errstr)" : "")."\n"; | ||||
1093 | $rows; | ||||
1094 | } | ||||
1095 | |||||
1096 | |||||
1097 | sub data_diff { | ||||
1098 | my ($a, $b, $logical) = @_; | ||||
1099 | |||||
1100 | my $diff = data_string_diff($a, $b); | ||||
1101 | return "" if $logical and !$diff; | ||||
1102 | |||||
1103 | my $a_desc = data_string_desc($a); | ||||
1104 | my $b_desc = data_string_desc($b); | ||||
1105 | return "" if !$diff and $a_desc eq $b_desc; | ||||
1106 | |||||
1107 | $diff ||= "Strings contain the same sequence of characters" | ||||
1108 | if length($a); | ||||
1109 | $diff .= "\n" if $diff; | ||||
1110 | return "a: $a_desc\nb: $b_desc\n$diff"; | ||||
1111 | } | ||||
1112 | |||||
1113 | |||||
1114 | sub data_string_diff { | ||||
1115 | # Compares 'logical' characters, not bytes, so a latin1 string and an | ||||
1116 | # an equivalent Unicode string will compare as equal even though their | ||||
1117 | # byte encodings are different. | ||||
1118 | my ($a, $b) = @_; | ||||
1119 | unless (defined $a and defined $b) { # one undef | ||||
1120 | return "" | ||||
1121 | if !defined $a and !defined $b; | ||||
1122 | return "String a is undef, string b has ".length($b)." characters" | ||||
1123 | if !defined $a; | ||||
1124 | return "String b is undef, string a has ".length($a)." characters" | ||||
1125 | if !defined $b; | ||||
1126 | } | ||||
1127 | |||||
1128 | require utf8; | ||||
1129 | # hack to cater for perl 5.6 | ||||
1130 | *utf8::is_utf8 = sub { (DBI::neat(shift)=~/^"/) } unless defined &utf8::is_utf8; | ||||
1131 | |||||
1132 | my @a_chars = (utf8::is_utf8($a)) ? unpack("U*", $a) : unpack("C*", $a); | ||||
1133 | my @b_chars = (utf8::is_utf8($b)) ? unpack("U*", $b) : unpack("C*", $b); | ||||
1134 | my $i = 0; | ||||
1135 | while (@a_chars && @b_chars) { | ||||
1136 | ++$i, shift(@a_chars), shift(@b_chars), next | ||||
1137 | if $a_chars[0] == $b_chars[0];# compare ordinal values | ||||
1138 | my @desc = map { | ||||
1139 | $_ > 255 ? # if wide character... | ||||
1140 | sprintf("\\x{%04X}", $_) : # \x{...} | ||||
1141 | chr($_) =~ /[[:cntrl:]]/ ? # else if control character ... | ||||
1142 | sprintf("\\x%02X", $_) : # \x.. | ||||
1143 | chr($_) # else as themselves | ||||
1144 | } ($a_chars[0], $b_chars[0]); | ||||
1145 | # highlight probable double-encoding? | ||||
1146 | foreach my $c ( @desc ) { | ||||
1147 | next unless $c =~ m/\\x\{08(..)}/; | ||||
1148 | $c .= "='" .chr(hex($1)) ."'" | ||||
1149 | } | ||||
1150 | return sprintf "Strings differ at index $i: a[$i]=$desc[0], b[$i]=$desc[1]"; | ||||
1151 | } | ||||
1152 | return "String a truncated after $i characters" if @b_chars; | ||||
1153 | return "String b truncated after $i characters" if @a_chars; | ||||
1154 | return ""; | ||||
1155 | } | ||||
1156 | |||||
1157 | |||||
1158 | sub data_string_desc { # describe a data string | ||||
1159 | my ($a) = @_; | ||||
1160 | require bytes; | ||||
1161 | require utf8; | ||||
1162 | |||||
1163 | # hacks to cater for perl 5.6 | ||||
1164 | *utf8::is_utf8 = sub { (DBI::neat(shift)=~/^"/) } unless defined &utf8::is_utf8; | ||||
1165 | *utf8::valid = sub { 1 } unless defined &utf8::valid; | ||||
1166 | |||||
1167 | # Give sufficient info to help diagnose at least these kinds of situations: | ||||
1168 | # - valid UTF8 byte sequence but UTF8 flag not set | ||||
1169 | # (might be ascii so also need to check for hibit to make it worthwhile) | ||||
1170 | # - UTF8 flag set but invalid UTF8 byte sequence | ||||
1171 | # could do better here, but this'll do for now | ||||
1172 | my $utf8 = sprintf "UTF8 %s%s", | ||||
1173 | utf8::is_utf8($a) ? "on" : "off", | ||||
1174 | utf8::valid($a||'') ? "" : " but INVALID encoding"; | ||||
1175 | return "$utf8, undef" unless defined $a; | ||||
1176 | my $is_ascii = $a =~ m/^[\000-\177]*$/; | ||||
1177 | return sprintf "%s, %s, %d characters %d bytes", | ||||
1178 | $utf8, $is_ascii ? "ASCII" : "non-ASCII", | ||||
1179 | length($a), bytes::length($a); | ||||
1180 | } | ||||
1181 | |||||
1182 | |||||
1183 | sub connect_test_perf { | ||||
1184 | my($class, $dsn,$dbuser,$dbpass, $attr) = @_; | ||||
1185 | Carp::croak("connect_test_perf needs hash ref as fourth arg") unless ref $attr; | ||||
1186 | # these are non standard attributes just for this special method | ||||
1187 | my $loops ||= $attr->{dbi_loops} || 5; | ||||
1188 | my $par ||= $attr->{dbi_par} || 1; # parallelism | ||||
1189 | my $verb ||= $attr->{dbi_verb} || 1; | ||||
1190 | my $meth ||= $attr->{dbi_meth} || 'connect'; | ||||
1191 | print "$dsn: testing $loops sets of $par connections:\n"; | ||||
1192 | require "FileHandle.pm"; # don't let toke.c create empty FileHandle package | ||||
1193 | local $| = 1; | ||||
1194 | my $drh = $class->install_driver($dsn) or Carp::croak("Can't install $dsn driver\n"); | ||||
1195 | # test the connection and warm up caches etc | ||||
1196 | $drh->connect($dsn,$dbuser,$dbpass) or Carp::croak("connect failed: $DBI::errstr"); | ||||
1197 | my $t1 = dbi_time(); | ||||
1198 | my $loop; | ||||
1199 | for $loop (1..$loops) { | ||||
1200 | my @cons; | ||||
1201 | print "Connecting... " if $verb; | ||||
1202 | for (1..$par) { | ||||
1203 | print "$_ "; | ||||
1204 | push @cons, ($drh->connect($dsn,$dbuser,$dbpass) | ||||
1205 | or Carp::croak("connect failed: $DBI::errstr\n")); | ||||
1206 | } | ||||
1207 | print "\nDisconnecting...\n" if $verb; | ||||
1208 | for (@cons) { | ||||
1209 | $_->disconnect or warn "disconnect failed: $DBI::errstr" | ||||
1210 | } | ||||
1211 | } | ||||
1212 | my $t2 = dbi_time(); | ||||
1213 | my $td = $t2 - $t1; | ||||
1214 | printf "$meth %d and disconnect them, %d times: %.4fs / %d = %.4fs\n", | ||||
1215 | $par, $loops, $td, $loops*$par, $td/($loops*$par); | ||||
1216 | return $td; | ||||
1217 | } | ||||
1218 | |||||
1219 | |||||
1220 | # Help people doing DBI->errstr, might even document it one day | ||||
1221 | # XXX probably best moved to cheaper XS code if this gets documented | ||||
1222 | sub err { $DBI::err } | ||||
1223 | sub errstr { $DBI::errstr } | ||||
1224 | |||||
1225 | |||||
1226 | # --- Private Internal Function for Creating New DBI Handles | ||||
1227 | |||||
1228 | # XXX move to PurePerl? | ||||
1229 | *DBI::dr::TIEHASH = \&DBI::st::TIEHASH; | ||||
1230 | *DBI::db::TIEHASH = \&DBI::st::TIEHASH; | ||||
1231 | |||||
1232 | |||||
1233 | # These three special constructors are called by the drivers | ||||
1234 | # The way they are called is likely to change. | ||||
1235 | |||||
1236 | our $shared_profile; | ||||
1237 | |||||
1238 | sub _new_drh { # called by DBD::<drivername>::driver() | ||||
1239 | my ($class, $initial_attr, $imp_data) = @_; | ||||
1240 | # Provide default storage for State,Err and Errstr. | ||||
1241 | # Note that these are shared by all child handles by default! XXX | ||||
1242 | # State must be undef to get automatic faking in DBI::var::FETCH | ||||
1243 | my ($h_state_store, $h_err_store, $h_errstr_store) = (undef, undef, ''); | ||||
1244 | my $attr = { | ||||
1245 | # these attributes get copied down to child handles by default | ||||
1246 | 'State' => \$h_state_store, # Holder for DBI::state | ||||
1247 | 'Err' => \$h_err_store, # Holder for DBI::err | ||||
1248 | 'Errstr' => \$h_errstr_store, # Holder for DBI::errstr | ||||
1249 | 'TraceLevel' => 0, | ||||
1250 | FetchHashKeyName=> 'NAME', | ||||
1251 | %$initial_attr, | ||||
1252 | }; | ||||
1253 | my ($h, $i) = _new_handle('DBI::dr', '', $attr, $imp_data, $class); | ||||
1254 | |||||
1255 | # XXX DBI_PROFILE unless DBI::PurePerl because for some reason | ||||
1256 | # it kills the t/zz_*_pp.t tests (they silently exit early) | ||||
1257 | if (($ENV{DBI_PROFILE} && !$DBI::PurePerl) || $shared_profile) { | ||||
1258 | # The profile object created here when the first driver is loaded | ||||
1259 | # is shared by all drivers so we end up with just one set of profile | ||||
1260 | # data and thus the 'total time in DBI' is really the true total. | ||||
1261 | if (!$shared_profile) { # first time | ||||
1262 | $h->{Profile} = $ENV{DBI_PROFILE}; # write string | ||||
1263 | $shared_profile = $h->{Profile}; # read and record object | ||||
1264 | } | ||||
1265 | else { | ||||
1266 | $h->{Profile} = $shared_profile; | ||||
1267 | } | ||||
1268 | } | ||||
1269 | return $h unless wantarray; | ||||
1270 | ($h, $i); | ||||
1271 | } | ||||
1272 | |||||
1273 | sub _new_dbh { # called by DBD::<drivername>::dr::connect() | ||||
1274 | my ($drh, $attr, $imp_data) = @_; | ||||
1275 | my $imp_class = $drh->{ImplementorClass} | ||||
1276 | or Carp::croak("DBI _new_dbh: $drh has no ImplementorClass"); | ||||
1277 | substr($imp_class,-4,4) = '::db'; | ||||
1278 | my $app_class = ref $drh; | ||||
1279 | substr($app_class,-4,4) = '::db'; | ||||
1280 | $attr->{Err} ||= \my $err; | ||||
1281 | $attr->{Errstr} ||= \my $errstr; | ||||
1282 | $attr->{State} ||= \my $state; | ||||
1283 | _new_handle($app_class, $drh, $attr, $imp_data, $imp_class); | ||||
1284 | } | ||||
1285 | |||||
1286 | sub _new_sth { # called by DBD::<drivername>::db::prepare) | ||||
1287 | my ($dbh, $attr, $imp_data) = @_; | ||||
1288 | my $imp_class = $dbh->{ImplementorClass} | ||||
1289 | or Carp::croak("DBI _new_sth: $dbh has no ImplementorClass"); | ||||
1290 | substr($imp_class,-4,4) = '::st'; | ||||
1291 | my $app_class = ref $dbh; | ||||
1292 | substr($app_class,-4,4) = '::st'; | ||||
1293 | _new_handle($app_class, $dbh, $attr, $imp_data, $imp_class); | ||||
1294 | } | ||||
1295 | |||||
1296 | |||||
1297 | # end of DBI package | ||||
1298 | |||||
- - | |||||
1301 | # -------------------------------------------------------------------- | ||||
1302 | # === The internal DBI Switch pseudo 'driver' class === | ||||
1303 | |||||
1304 | { package # hide from PAUSE | ||||
1305 | DBD::Switch::dr; | ||||
1306 | DBI->setup_driver('DBD::Switch'); # sets up @ISA | ||||
1307 | |||||
1308 | $DBD::Switch::dr::imp_data_size = 0; | ||||
1309 | $DBD::Switch::dr::imp_data_size = 0; # avoid typo warning | ||||
1310 | my $drh; | ||||
1311 | |||||
1312 | sub driver { | ||||
1313 | return $drh if $drh; # a package global | ||||
1314 | |||||
1315 | my $inner; | ||||
1316 | ($drh, $inner) = DBI::_new_drh('DBD::Switch::dr', { | ||||
1317 | 'Name' => 'Switch', | ||||
1318 | 'Version' => $DBI::VERSION, | ||||
1319 | 'Attribution' => "DBI $DBI::VERSION by Tim Bunce", | ||||
1320 | }); | ||||
1321 | Carp::croak("DBD::Switch init failed!") unless ($drh && $inner); | ||||
1322 | return $drh; | ||||
1323 | } | ||||
1324 | sub CLONE { | ||||
1325 | undef $drh; | ||||
1326 | } | ||||
1327 | |||||
1328 | sub FETCH { | ||||
1329 | my($drh, $key) = @_; | ||||
1330 | return DBI->trace if $key eq 'DebugDispatch'; | ||||
1331 | return undef if $key eq 'DebugLog'; # not worth fetching, sorry | ||||
1332 | return $drh->DBD::_::dr::FETCH($key); | ||||
1333 | undef; | ||||
1334 | } | ||||
1335 | sub STORE { | ||||
1336 | my($drh, $key, $value) = @_; | ||||
1337 | if ($key eq 'DebugDispatch') { | ||||
1338 | DBI->trace($value); | ||||
1339 | } elsif ($key eq 'DebugLog') { | ||||
1340 | DBI->trace(-1, $value); | ||||
1341 | } else { | ||||
1342 | $drh->DBD::_::dr::STORE($key, $value); | ||||
1343 | } | ||||
1344 | } | ||||
1345 | } | ||||
1346 | |||||
1347 | |||||
1348 | # -------------------------------------------------------------------- | ||||
1349 | # === OPTIONAL MINIMAL BASE CLASSES FOR DBI SUBCLASSES === | ||||
1350 | |||||
1351 | # We only define default methods for harmless functions. | ||||
1352 | # We don't, for example, define a DBD::_::st::prepare() | ||||
1353 | |||||
1354 | { package # hide from PAUSE | ||||
1355 | DBD::_::common; # ====== Common base class methods ====== | ||||
1356 | use strict; | ||||
1357 | |||||
1358 | # methods common to all handle types: | ||||
1359 | |||||
1360 | # generic TIEHASH default methods: | ||||
1361 | sub FIRSTKEY { } | ||||
1362 | sub NEXTKEY { } | ||||
1363 | sub EXISTS { defined($_[0]->FETCH($_[1])) } # XXX undef? | ||||
1364 | sub CLEAR { Carp::carp "Can't CLEAR $_[0] (DBI)" } | ||||
1365 | |||||
1366 | sub FETCH_many { # XXX should move to C one day | ||||
1367 | my $h = shift; | ||||
1368 | # scalar is needed to workaround drivers that return an empty list | ||||
1369 | # for some attributes | ||||
1370 | return map { scalar $h->FETCH($_) } @_; | ||||
1371 | } | ||||
1372 | |||||
1373 | *dump_handle = \&DBI::dump_handle; | ||||
1374 | |||||
1375 | sub install_method { | ||||
1376 | # special class method called directly by apps and/or drivers | ||||
1377 | # to install new methods into the DBI dispatcher | ||||
1378 | # DBD::Foo::db->install_method("foo_mumble", { usage => [...], options => '...' }); | ||||
1379 | my ($class, $method, $attr) = @_; | ||||
1380 | Carp::croak("Class '$class' must begin with DBD:: and end with ::db or ::st") | ||||
1381 | unless $class =~ /^DBD::(\w+)::(dr|db|st)$/; | ||||
1382 | my ($driver, $subtype) = ($1, $2); | ||||
1383 | Carp::croak("invalid method name '$method'") | ||||
1384 | unless $method =~ m/^([a-z]+_)\w+$/; | ||||
1385 | my $prefix = $1; | ||||
1386 | my $reg_info = $dbd_prefix_registry->{$prefix}; | ||||
1387 | Carp::carp("method name prefix '$prefix' is not associated with a registered driver") unless $reg_info; | ||||
1388 | |||||
1389 | my $full_method = "DBI::${subtype}::$method"; | ||||
1390 | $DBI::installed_methods{$full_method} = $attr; | ||||
1391 | |||||
1392 | my (undef, $filename, $line) = caller; | ||||
1393 | # XXX reformat $attr as needed for _install_method | ||||
1394 | my %attr = %{$attr||{}}; # copy so we can edit | ||||
1395 | DBI->_install_method("DBI::${subtype}::$method", "$filename at line $line", \%attr); | ||||
1396 | } | ||||
1397 | |||||
1398 | sub parse_trace_flags { | ||||
1399 | my ($h, $spec) = @_; | ||||
1400 | my $level = 0; | ||||
1401 | my $flags = 0; | ||||
1402 | my @unknown; | ||||
1403 | for my $word (split /\s*[|&,]\s*/, $spec) { | ||||
1404 | if (DBI::looks_like_number($word) && $word <= 0xF && $word >= 0) { | ||||
1405 | $level = $word; | ||||
1406 | } elsif ($word eq 'ALL') { | ||||
1407 | $flags = 0x7FFFFFFF; # XXX last bit causes negative headaches | ||||
1408 | last; | ||||
1409 | } elsif (my $flag = $h->parse_trace_flag($word)) { | ||||
1410 | $flags |= $flag; | ||||
1411 | } | ||||
1412 | else { | ||||
1413 | push @unknown, $word; | ||||
1414 | } | ||||
1415 | } | ||||
1416 | if (@unknown && (ref $h ? $h->FETCH('Warn') : 1)) { | ||||
1417 | Carp::carp("$h->parse_trace_flags($spec) ignored unknown trace flags: ". | ||||
1418 | join(" ", map { DBI::neat($_) } @unknown)); | ||||
1419 | } | ||||
1420 | $flags |= $level; | ||||
1421 | return $flags; | ||||
1422 | } | ||||
1423 | |||||
1424 | sub parse_trace_flag { | ||||
1425 | my ($h, $name) = @_; | ||||
1426 | # 0xddDDDDrL (driver, DBI, reserved, Level) | ||||
1427 | return 0x00000100 if $name eq 'SQL'; | ||||
1428 | return 0x00000200 if $name eq 'CON'; | ||||
1429 | return 0x00000400 if $name eq 'ENC'; | ||||
1430 | return 0x00000800 if $name eq 'DBD'; | ||||
1431 | return 0x00001000 if $name eq 'TXN'; | ||||
1432 | return; | ||||
1433 | } | ||||
1434 | |||||
1435 | sub private_attribute_info { | ||||
1436 | return undef; | ||||
1437 | } | ||||
1438 | |||||
1439 | sub visit_child_handles { | ||||
1440 | my ($h, $code, $info) = @_; | ||||
1441 | $info = {} if not defined $info; | ||||
1442 | for my $ch (@{ $h->{ChildHandles} || []}) { | ||||
1443 | next unless $ch; | ||||
1444 | my $child_info = $code->($ch, $info) | ||||
1445 | or next; | ||||
1446 | $ch->visit_child_handles($code, $child_info); | ||||
1447 | } | ||||
1448 | return $info; | ||||
1449 | } | ||||
1450 | } | ||||
1451 | |||||
1452 | |||||
1453 | { package # hide from PAUSE | ||||
1454 | DBD::_::dr; # ====== DRIVER ====== | ||||
1455 | @DBD::_::dr::ISA = qw(DBD::_::common); | ||||
1456 | use strict; | ||||
1457 | |||||
1458 | sub default_user { | ||||
1459 | my ($drh, $user, $pass, $attr) = @_; | ||||
1460 | $user = $ENV{DBI_USER} unless defined $user; | ||||
1461 | $pass = $ENV{DBI_PASS} unless defined $pass; | ||||
1462 | return ($user, $pass); | ||||
1463 | } | ||||
1464 | |||||
1465 | sub connect { # normally overridden, but a handy default | ||||
1466 | my ($drh, $dsn, $user, $auth) = @_; | ||||
1467 | my ($this) = DBI::_new_dbh($drh, { | ||||
1468 | 'Name' => $dsn, | ||||
1469 | }); | ||||
1470 | # XXX debatable as there's no "server side" here | ||||
1471 | # (and now many uses would trigger warnings on DESTROY) | ||||
1472 | # $this->STORE(Active => 1); | ||||
1473 | # so drivers should set it in their own connect | ||||
1474 | $this; | ||||
1475 | } | ||||
1476 | |||||
1477 | |||||
1478 | sub connect_cached { | ||||
1479 | my $drh = shift; | ||||
1480 | my ($dsn, $user, $auth, $attr) = @_; | ||||
1481 | |||||
1482 | my $cache = $drh->{CachedKids} ||= {}; | ||||
1483 | my $key = do { local $^W; | ||||
1484 | join "!\001", $dsn, $user, $auth, DBI::_concat_hash_sorted($attr, "=\001", ",\001", 0, 0) | ||||
1485 | }; | ||||
1486 | my $dbh = $cache->{$key}; | ||||
1487 | $drh->trace_msg(sprintf(" connect_cached: key '$key', cached dbh $dbh\n", DBI::neat($key), DBI::neat($dbh))) | ||||
1488 | if (($DBI::dbi_debug & 0xF) >= 4); | ||||
1489 | |||||
1490 | my $cb = $attr->{Callbacks}; # take care not to autovivify | ||||
1491 | if ($dbh && $dbh->FETCH('Active') && eval { $dbh->ping }) { | ||||
1492 | # If the caller has provided a callback then call it | ||||
1493 | if ($cb and $cb = $cb->{"connect_cached.reused"}) { | ||||
1494 | local $_ = "connect_cached.reused"; | ||||
1495 | $cb->($dbh, $dsn, $user, $auth, $attr); | ||||
1496 | } | ||||
1497 | return $dbh; | ||||
1498 | } | ||||
1499 | |||||
1500 | # If the caller has provided a callback then call it | ||||
1501 | if ($cb and (my $new_cb = $cb->{"connect_cached.new"})) { | ||||
1502 | local $_ = "connect_cached.new"; | ||||
1503 | $new_cb->($dbh, $dsn, $user, $auth, $attr); # $dbh is dead or undef | ||||
1504 | } | ||||
1505 | |||||
1506 | $dbh = $drh->connect(@_); | ||||
1507 | $cache->{$key} = $dbh; # replace prev entry, even if connect failed | ||||
1508 | if ($cb and (my $conn_cb = $cb->{"connect_cached.connected"})) { | ||||
1509 | local $_ = "connect_cached.connected"; | ||||
1510 | $conn_cb->($dbh, $dsn, $user, $auth, $attr); | ||||
1511 | } | ||||
1512 | return $dbh; | ||||
1513 | } | ||||
1514 | |||||
1515 | } | ||||
1516 | |||||
1517 | |||||
1518 | { package # hide from PAUSE | ||||
1519 | DBD::_::db; # ====== DATABASE ====== | ||||
1520 | @DBD::_::db::ISA = qw(DBD::_::common); | ||||
1521 | use strict; | ||||
1522 | |||||
1523 | sub clone { | ||||
1524 | my ($old_dbh, $attr) = @_; | ||||
1525 | |||||
1526 | my $closure = $old_dbh->{dbi_connect_closure} | ||||
1527 | or return $old_dbh->set_err($DBI::stderr, "Can't clone handle"); | ||||
1528 | |||||
1529 | unless ($attr) { # XXX deprecated, caller should always pass a hash ref | ||||
1530 | # copy attributes visible in the attribute cache | ||||
1531 | keys %$old_dbh; # reset iterator | ||||
1532 | while ( my ($k, $v) = each %$old_dbh ) { | ||||
1533 | # ignore non-code refs, i.e., caches, handles, Err etc | ||||
1534 | next if ref $v && ref $v ne 'CODE'; # HandleError etc | ||||
1535 | $attr->{$k} = $v; | ||||
1536 | } | ||||
1537 | # explicitly set attributes which are unlikely to be in the | ||||
1538 | # attribute cache, i.e., boolean's and some others | ||||
1539 | $attr->{$_} = $old_dbh->FETCH($_) for (qw( | ||||
1540 | AutoCommit ChopBlanks InactiveDestroy AutoInactiveDestroy | ||||
1541 | LongTruncOk PrintError PrintWarn Profile RaiseError | ||||
1542 | ShowErrorStatement TaintIn TaintOut | ||||
1543 | )); | ||||
1544 | } | ||||
1545 | |||||
1546 | # use Data::Dumper; warn Dumper([$old_dbh, $attr]); | ||||
1547 | my $new_dbh = &$closure($old_dbh, $attr); | ||||
1548 | unless ($new_dbh) { | ||||
1549 | # need to copy err/errstr from driver back into $old_dbh | ||||
1550 | my $drh = $old_dbh->{Driver}; | ||||
1551 | return $old_dbh->set_err($drh->err, $drh->errstr, $drh->state); | ||||
1552 | } | ||||
1553 | $new_dbh->{dbi_connect_closure} = $closure; | ||||
1554 | return $new_dbh; | ||||
1555 | } | ||||
1556 | |||||
1557 | sub quote_identifier { | ||||
1558 | my ($dbh, @id) = @_; | ||||
1559 | my $attr = (@id > 3 && ref($id[-1])) ? pop @id : undef; | ||||
1560 | |||||
1561 | my $info = $dbh->{dbi_quote_identifier_cache} ||= [ | ||||
1562 | $dbh->get_info(29) || '"', # SQL_IDENTIFIER_QUOTE_CHAR | ||||
1563 | $dbh->get_info(41) || '.', # SQL_CATALOG_NAME_SEPARATOR | ||||
1564 | $dbh->get_info(114) || 1, # SQL_CATALOG_LOCATION | ||||
1565 | ]; | ||||
1566 | |||||
1567 | my $quote = $info->[0]; | ||||
1568 | foreach (@id) { # quote the elements | ||||
1569 | next unless defined; | ||||
1570 | s/$quote/$quote$quote/g; # escape embedded quotes | ||||
1571 | $_ = qq{$quote$_$quote}; | ||||
1572 | } | ||||
1573 | |||||
1574 | # strip out catalog if present for special handling | ||||
1575 | my $catalog = (@id >= 3) ? shift @id : undef; | ||||
1576 | |||||
1577 | # join the dots, ignoring any null/undef elements (ie schema) | ||||
1578 | my $quoted_id = join '.', grep { defined } @id; | ||||
1579 | |||||
1580 | if ($catalog) { # add catalog correctly | ||||
1581 | $quoted_id = ($info->[2] == 2) # SQL_CL_END | ||||
1582 | ? $quoted_id . $info->[1] . $catalog | ||||
1583 | : $catalog . $info->[1] . $quoted_id; | ||||
1584 | } | ||||
1585 | return $quoted_id; | ||||
1586 | } | ||||
1587 | |||||
1588 | sub quote { | ||||
1589 | my ($dbh, $str, $data_type) = @_; | ||||
1590 | |||||
1591 | return "NULL" unless defined $str; | ||||
1592 | unless ($data_type) { | ||||
1593 | $str =~ s/'/''/g; # ISO SQL2 | ||||
1594 | return "'$str'"; | ||||
1595 | } | ||||
1596 | |||||
1597 | my $dbi_literal_quote_cache = $dbh->{'dbi_literal_quote_cache'} ||= [ {} , {} ]; | ||||
1598 | my ($prefixes, $suffixes) = @$dbi_literal_quote_cache; | ||||
1599 | |||||
1600 | my $lp = $prefixes->{$data_type}; | ||||
1601 | my $ls = $suffixes->{$data_type}; | ||||
1602 | |||||
1603 | if ( ! defined $lp || ! defined $ls ) { | ||||
1604 | my $ti = $dbh->type_info($data_type); | ||||
1605 | $lp = $prefixes->{$data_type} = $ti ? $ti->{LITERAL_PREFIX} || "" : "'"; | ||||
1606 | $ls = $suffixes->{$data_type} = $ti ? $ti->{LITERAL_SUFFIX} || "" : "'"; | ||||
1607 | } | ||||
1608 | return $str unless $lp || $ls; # no quoting required | ||||
1609 | |||||
1610 | # XXX don't know what the standard says about escaping | ||||
1611 | # in the 'general case' (where $lp != "'"). | ||||
1612 | # So we just do this and hope: | ||||
1613 | $str =~ s/$lp/$lp$lp/g | ||||
1614 | if $lp && $lp eq $ls && ($lp eq "'" || $lp eq '"'); | ||||
1615 | return "$lp$str$ls"; | ||||
1616 | } | ||||
1617 | |||||
1618 | sub rows { -1 } # here so $DBI::rows 'works' after using $dbh | ||||
1619 | |||||
1620 | sub do { | ||||
1621 | my($dbh, $statement, $attr, @params) = @_; | ||||
1622 | my $sth = $dbh->prepare($statement, $attr) or return undef; | ||||
1623 | $sth->execute(@params) or return undef; | ||||
1624 | my $rows = $sth->rows; | ||||
1625 | ($rows == 0) ? "0E0" : $rows; | ||||
1626 | } | ||||
1627 | |||||
1628 | sub _do_selectrow { | ||||
1629 | my ($method, $dbh, $stmt, $attr, @bind) = @_; | ||||
1630 | my $sth = ((ref $stmt) ? $stmt : $dbh->prepare($stmt, $attr)) | ||||
1631 | or return; | ||||
1632 | $sth->execute(@bind) | ||||
1633 | or return; | ||||
1634 | my $row = $sth->$method() | ||||
1635 | and $sth->finish; | ||||
1636 | return $row; | ||||
1637 | } | ||||
1638 | |||||
1639 | sub selectrow_hashref { return _do_selectrow('fetchrow_hashref', @_); } | ||||
1640 | |||||
1641 | # XXX selectrow_array/ref also have C implementations in Driver.xst | ||||
1642 | sub selectrow_arrayref { return _do_selectrow('fetchrow_arrayref', @_); } | ||||
1643 | sub selectrow_array { | ||||
1644 | my $row = _do_selectrow('fetchrow_arrayref', @_) or return; | ||||
1645 | return $row->[0] unless wantarray; | ||||
1646 | return @$row; | ||||
1647 | } | ||||
1648 | |||||
1649 | # XXX selectall_arrayref also has C implementation in Driver.xst | ||||
1650 | # which fallsback to this if a slice is given | ||||
1651 | sub selectall_arrayref { | ||||
1652 | my ($dbh, $stmt, $attr, @bind) = @_; | ||||
1653 | my $sth = (ref $stmt) ? $stmt : $dbh->prepare($stmt, $attr) | ||||
1654 | or return; | ||||
1655 | $sth->execute(@bind) || return; | ||||
1656 | my $slice = $attr->{Slice}; # typically undef, else hash or array ref | ||||
1657 | if (!$slice and $slice=$attr->{Columns}) { | ||||
1658 | if (ref $slice eq 'ARRAY') { # map col idx to perl array idx | ||||
1659 | $slice = [ @{$attr->{Columns}} ]; # take a copy | ||||
1660 | for (@$slice) { $_-- } | ||||
1661 | } | ||||
1662 | } | ||||
1663 | my $rows = $sth->fetchall_arrayref($slice, my $MaxRows = $attr->{MaxRows}); | ||||
1664 | $sth->finish if defined $MaxRows; | ||||
1665 | return $rows; | ||||
1666 | } | ||||
1667 | |||||
1668 | sub selectall_hashref { | ||||
1669 | my ($dbh, $stmt, $key_field, $attr, @bind) = @_; | ||||
1670 | my $sth = (ref $stmt) ? $stmt : $dbh->prepare($stmt, $attr); | ||||
1671 | return unless $sth; | ||||
1672 | $sth->execute(@bind) || return; | ||||
1673 | return $sth->fetchall_hashref($key_field); | ||||
1674 | } | ||||
1675 | |||||
1676 | sub selectcol_arrayref { | ||||
1677 | my ($dbh, $stmt, $attr, @bind) = @_; | ||||
1678 | my $sth = (ref $stmt) ? $stmt : $dbh->prepare($stmt, $attr); | ||||
1679 | return unless $sth; | ||||
1680 | $sth->execute(@bind) || return; | ||||
1681 | my @columns = ($attr->{Columns}) ? @{$attr->{Columns}} : (1); | ||||
1682 | my @values = (undef) x @columns; | ||||
1683 | my $idx = 0; | ||||
1684 | for (@columns) { | ||||
1685 | $sth->bind_col($_, \$values[$idx++]) || return; | ||||
1686 | } | ||||
1687 | my @col; | ||||
1688 | if (my $max = $attr->{MaxRows}) { | ||||
1689 | push @col, @values while 0 < $max-- && $sth->fetch; | ||||
1690 | } | ||||
1691 | else { | ||||
1692 | push @col, @values while $sth->fetch; | ||||
1693 | } | ||||
1694 | return \@col; | ||||
1695 | } | ||||
1696 | |||||
1697 | sub prepare_cached { | ||||
1698 | my ($dbh, $statement, $attr, $if_active) = @_; | ||||
1699 | |||||
1700 | # Needs support at dbh level to clear cache before complaining about | ||||
1701 | # active children. The XS template code does this. Drivers not using | ||||
1702 | # the template must handle clearing the cache themselves. | ||||
1703 | my $cache = $dbh->{CachedKids} ||= {}; | ||||
1704 | my $key = do { local $^W; | ||||
1705 | join "!\001", $statement, DBI::_concat_hash_sorted($attr, "=\001", ",\001", 0, 0) | ||||
1706 | }; | ||||
1707 | my $sth = $cache->{$key}; | ||||
1708 | |||||
1709 | if ($sth) { | ||||
1710 | return $sth unless $sth->FETCH('Active'); | ||||
1711 | Carp::carp("prepare_cached($statement) statement handle $sth still Active") | ||||
1712 | unless ($if_active ||= 0); | ||||
1713 | $sth->finish if $if_active <= 1; | ||||
1714 | return $sth if $if_active <= 2; | ||||
1715 | } | ||||
1716 | |||||
1717 | $sth = $dbh->prepare($statement, $attr); | ||||
1718 | $cache->{$key} = $sth if $sth; | ||||
1719 | |||||
1720 | return $sth; | ||||
1721 | } | ||||
1722 | |||||
1723 | sub ping { | ||||
1724 | my $dbh = shift; | ||||
1725 | # "0 but true" is a special kind of true 0 that is used here so | ||||
1726 | # applications can check if the ping was a real ping or not | ||||
1727 | ($dbh->FETCH('Active')) ? "0 but true" : 0; | ||||
1728 | } | ||||
1729 | |||||
1730 | sub begin_work { | ||||
1731 | my $dbh = shift; | ||||
1732 | return $dbh->set_err($DBI::stderr, "Already in a transaction") | ||||
1733 | unless $dbh->FETCH('AutoCommit'); | ||||
1734 | $dbh->STORE('AutoCommit', 0); # will croak if driver doesn't support it | ||||
1735 | $dbh->STORE('BegunWork', 1); # trigger post commit/rollback action | ||||
1736 | return 1; | ||||
1737 | } | ||||
1738 | |||||
1739 | sub primary_key { | ||||
1740 | my ($dbh, @args) = @_; | ||||
1741 | my $sth = $dbh->primary_key_info(@args) or return; | ||||
1742 | my ($row, @col); | ||||
1743 | push @col, $row->[3] while ($row = $sth->fetch); | ||||
1744 | Carp::croak("primary_key method not called in list context") | ||||
1745 | unless wantarray; # leave us some elbow room | ||||
1746 | return @col; | ||||
1747 | } | ||||
1748 | |||||
1749 | sub tables { | ||||
1750 | my ($dbh, @args) = @_; | ||||
1751 | my $sth = $dbh->table_info(@args[0,1,2,3,4]) or return; | ||||
1752 | my $tables = $sth->fetchall_arrayref or return; | ||||
1753 | my @tables; | ||||
1754 | if ($dbh->get_info(29)) { # SQL_IDENTIFIER_QUOTE_CHAR | ||||
1755 | @tables = map { $dbh->quote_identifier( @{$_}[0,1,2] ) } @$tables; | ||||
1756 | } | ||||
1757 | else { # temporary old style hack (yeach) | ||||
1758 | @tables = map { | ||||
1759 | my $name = $_->[2]; | ||||
1760 | if ($_->[1]) { | ||||
1761 | my $schema = $_->[1]; | ||||
1762 | # a sad hack (mostly for Informix I recall) | ||||
1763 | my $quote = ($schema eq uc($schema)) ? '' : '"'; | ||||
1764 | $name = "$quote$schema$quote.$name" | ||||
1765 | } | ||||
1766 | $name; | ||||
1767 | } @$tables; | ||||
1768 | } | ||||
1769 | return @tables; | ||||
1770 | } | ||||
1771 | |||||
1772 | sub type_info { # this should be sufficient for all drivers | ||||
1773 | my ($dbh, $data_type) = @_; | ||||
1774 | my $idx_hash; | ||||
1775 | my $tia = $dbh->{dbi_type_info_row_cache}; | ||||
1776 | if ($tia) { | ||||
1777 | $idx_hash = $dbh->{dbi_type_info_idx_cache}; | ||||
1778 | } | ||||
1779 | else { | ||||
1780 | my $temp = $dbh->type_info_all; | ||||
1781 | return unless $temp && @$temp; | ||||
1782 | # we cache here because type_info_all may be expensive to call | ||||
1783 | # (and we take a copy so the following shift can't corrupt | ||||
1784 | # the data that may be returned by future calls to type_info_all) | ||||
1785 | $tia = $dbh->{dbi_type_info_row_cache} = [ @$temp ]; | ||||
1786 | $idx_hash = $dbh->{dbi_type_info_idx_cache} = shift @$tia; | ||||
1787 | } | ||||
1788 | |||||
1789 | my $dt_idx = $idx_hash->{DATA_TYPE} || $idx_hash->{data_type}; | ||||
1790 | Carp::croak("type_info_all returned non-standard DATA_TYPE index value ($dt_idx != 1)") | ||||
1791 | if $dt_idx && $dt_idx != 1; | ||||
1792 | |||||
1793 | # --- simple DATA_TYPE match filter | ||||
1794 | my @ti; | ||||
1795 | my @data_type_list = (ref $data_type) ? @$data_type : ($data_type); | ||||
1796 | foreach $data_type (@data_type_list) { | ||||
1797 | if (defined($data_type) && $data_type != DBI::SQL_ALL_TYPES()) { | ||||
1798 | push @ti, grep { $_->[$dt_idx] == $data_type } @$tia; | ||||
1799 | } | ||||
1800 | else { # SQL_ALL_TYPES | ||||
1801 | push @ti, @$tia; | ||||
1802 | } | ||||
1803 | last if @ti; # found at least one match | ||||
1804 | } | ||||
1805 | |||||
1806 | # --- format results into list of hash refs | ||||
1807 | my $idx_fields = keys %$idx_hash; | ||||
1808 | my @idx_names = map { uc($_) } keys %$idx_hash; | ||||
1809 | my @idx_values = values %$idx_hash; | ||||
1810 | Carp::croak "type_info_all result has $idx_fields keys but ".(@{$ti[0]})." fields" | ||||
1811 | if @ti && @{$ti[0]} != $idx_fields; | ||||
1812 | my @out = map { | ||||
1813 | my %h; @h{@idx_names} = @{$_}[ @idx_values ]; \%h; | ||||
1814 | } @ti; | ||||
1815 | return $out[0] unless wantarray; | ||||
1816 | return @out; | ||||
1817 | } | ||||
1818 | |||||
1819 | sub data_sources { | ||||
1820 | my ($dbh, @other) = @_; | ||||
1821 | my $drh = $dbh->{Driver}; # XXX proxy issues? | ||||
1822 | return $drh->data_sources(@other); | ||||
1823 | } | ||||
1824 | |||||
1825 | } | ||||
1826 | |||||
1827 | |||||
1828 | { package # hide from PAUSE | ||||
1829 | DBD::_::st; # ====== STATEMENT ====== | ||||
1830 | @DBD::_::st::ISA = qw(DBD::_::common); | ||||
1831 | use strict; | ||||
1832 | |||||
1833 | sub bind_param { Carp::croak("Can't bind_param, not implement by driver") } | ||||
1834 | |||||
1835 | # | ||||
1836 | # ******************************************************** | ||||
1837 | # | ||||
1838 | # BEGIN ARRAY BINDING | ||||
1839 | # | ||||
1840 | # Array binding support for drivers which don't support | ||||
1841 | # array binding, but have sufficient interfaces to fake it. | ||||
1842 | # NOTE: mixing scalars and arrayrefs requires using bind_param_array | ||||
1843 | # for *all* params...unless we modify bind_param for the default | ||||
1844 | # case... | ||||
1845 | # | ||||
1846 | # 2002-Apr-10 D. Arnold | ||||
1847 | |||||
1848 | sub bind_param_array { | ||||
1849 | my $sth = shift; | ||||
1850 | my ($p_id, $value_array, $attr) = @_; | ||||
1851 | |||||
1852 | return $sth->set_err($DBI::stderr, "Value for parameter $p_id must be a scalar or an arrayref, not a ".ref($value_array)) | ||||
1853 | if defined $value_array and ref $value_array and ref $value_array ne 'ARRAY'; | ||||
1854 | |||||
1855 | return $sth->set_err($DBI::stderr, "Can't use named placeholder '$p_id' for non-driver supported bind_param_array") | ||||
1856 | unless DBI::looks_like_number($p_id); # because we rely on execute(@ary) here | ||||
1857 | |||||
1858 | return $sth->set_err($DBI::stderr, "Placeholder '$p_id' is out of range") | ||||
1859 | if $p_id <= 0; # can't easily/reliably test for too big | ||||
1860 | |||||
1861 | # get/create arrayref to hold params | ||||
1862 | my $hash_of_arrays = $sth->{ParamArrays} ||= { }; | ||||
1863 | |||||
1864 | # If the bind has attribs then we rely on the driver conforming to | ||||
1865 | # the DBI spec in that a single bind_param() call with those attribs | ||||
1866 | # makes them 'sticky' and apply to all later execute(@values) calls. | ||||
1867 | # Since we only call bind_param() if we're given attribs then | ||||
1868 | # applications using drivers that don't support bind_param can still | ||||
1869 | # use bind_param_array() so long as they don't pass any attribs. | ||||
1870 | |||||
1871 | $$hash_of_arrays{$p_id} = $value_array; | ||||
1872 | return $sth->bind_param($p_id, undef, $attr) | ||||
1873 | if $attr; | ||||
1874 | 1; | ||||
1875 | } | ||||
1876 | |||||
1877 | sub bind_param_inout_array { | ||||
1878 | my $sth = shift; | ||||
1879 | # XXX not supported so we just call bind_param_array instead | ||||
1880 | # and then return an error | ||||
1881 | my ($p_num, $value_array, $attr) = @_; | ||||
1882 | $sth->bind_param_array($p_num, $value_array, $attr); | ||||
1883 | return $sth->set_err($DBI::stderr, "bind_param_inout_array not supported"); | ||||
1884 | } | ||||
1885 | |||||
1886 | sub bind_columns { | ||||
1887 | my $sth = shift; | ||||
1888 | my $fields = $sth->FETCH('NUM_OF_FIELDS') || 0; | ||||
1889 | if ($fields <= 0 && !$sth->{Active}) { | ||||
1890 | return $sth->set_err($DBI::stderr, "Statement has no result columns to bind" | ||||
1891 | ." (perhaps you need to successfully call execute first)"); | ||||
1892 | } | ||||
1893 | # Backwards compatibility for old-style call with attribute hash | ||||
1894 | # ref as first arg. Skip arg if undef or a hash ref. | ||||
1895 | my $attr; | ||||
1896 | $attr = shift if !defined $_[0] or ref($_[0]) eq 'HASH'; | ||||
1897 | |||||
1898 | my $idx = 0; | ||||
1899 | $sth->bind_col(++$idx, shift, $attr) or return | ||||
1900 | while (@_ and $idx < $fields); | ||||
1901 | |||||
1902 | return $sth->set_err($DBI::stderr, "bind_columns called with ".($idx+@_)." values but $fields are needed") | ||||
1903 | if @_ or $idx != $fields; | ||||
1904 | |||||
1905 | return 1; | ||||
1906 | } | ||||
1907 | |||||
1908 | sub execute_array { | ||||
1909 | my $sth = shift; | ||||
1910 | my ($attr, @array_of_arrays) = @_; | ||||
1911 | my $NUM_OF_PARAMS = $sth->FETCH('NUM_OF_PARAMS'); # may be undef at this point | ||||
1912 | |||||
1913 | # get tuple status array or hash attribute | ||||
1914 | my $tuple_sts = $attr->{ArrayTupleStatus}; | ||||
1915 | return $sth->set_err($DBI::stderr, "ArrayTupleStatus attribute must be an arrayref") | ||||
1916 | if $tuple_sts and ref $tuple_sts ne 'ARRAY'; | ||||
1917 | |||||
1918 | # bind all supplied arrays | ||||
1919 | if (@array_of_arrays) { | ||||
1920 | $sth->{ParamArrays} = { }; # clear out old params | ||||
1921 | return $sth->set_err($DBI::stderr, | ||||
1922 | @array_of_arrays." bind values supplied but $NUM_OF_PARAMS expected") | ||||
1923 | if defined ($NUM_OF_PARAMS) && @array_of_arrays != $NUM_OF_PARAMS; | ||||
1924 | $sth->bind_param_array($_, $array_of_arrays[$_-1]) or return | ||||
1925 | foreach (1..@array_of_arrays); | ||||
1926 | } | ||||
1927 | |||||
1928 | my $fetch_tuple_sub; | ||||
1929 | |||||
1930 | if ($fetch_tuple_sub = $attr->{ArrayTupleFetch}) { # fetch on demand | ||||
1931 | |||||
1932 | return $sth->set_err($DBI::stderr, | ||||
1933 | "Can't use both ArrayTupleFetch and explicit bind values") | ||||
1934 | if @array_of_arrays; # previous bind_param_array calls will simply be ignored | ||||
1935 | |||||
1936 | if (UNIVERSAL::isa($fetch_tuple_sub,'DBI::st')) { | ||||
1937 | my $fetch_sth = $fetch_tuple_sub; | ||||
1938 | return $sth->set_err($DBI::stderr, | ||||
1939 | "ArrayTupleFetch sth is not Active, need to execute() it first") | ||||
1940 | unless $fetch_sth->{Active}; | ||||
1941 | # check column count match to give more friendly message | ||||
1942 | my $NUM_OF_FIELDS = $fetch_sth->{NUM_OF_FIELDS}; | ||||
1943 | return $sth->set_err($DBI::stderr, | ||||
1944 | "$NUM_OF_FIELDS columns from ArrayTupleFetch sth but $NUM_OF_PARAMS expected") | ||||
1945 | if defined($NUM_OF_FIELDS) && defined($NUM_OF_PARAMS) | ||||
1946 | && $NUM_OF_FIELDS != $NUM_OF_PARAMS; | ||||
1947 | $fetch_tuple_sub = sub { $fetch_sth->fetchrow_arrayref }; | ||||
1948 | } | ||||
1949 | elsif (!UNIVERSAL::isa($fetch_tuple_sub,'CODE')) { | ||||
1950 | return $sth->set_err($DBI::stderr, "ArrayTupleFetch '$fetch_tuple_sub' is not a code ref or statement handle"); | ||||
1951 | } | ||||
1952 | |||||
1953 | } | ||||
1954 | else { | ||||
1955 | my $NUM_OF_PARAMS_given = keys %{ $sth->{ParamArrays} || {} }; | ||||
1956 | return $sth->set_err($DBI::stderr, | ||||
1957 | "$NUM_OF_PARAMS_given bind values supplied but $NUM_OF_PARAMS expected") | ||||
1958 | if defined($NUM_OF_PARAMS) && $NUM_OF_PARAMS != $NUM_OF_PARAMS_given; | ||||
1959 | |||||
1960 | # get the length of a bound array | ||||
1961 | my $maxlen; | ||||
1962 | my %hash_of_arrays = %{$sth->{ParamArrays}}; | ||||
1963 | foreach (keys(%hash_of_arrays)) { | ||||
1964 | my $ary = $hash_of_arrays{$_}; | ||||
1965 | next unless ref $ary eq 'ARRAY'; | ||||
1966 | $maxlen = @$ary if !$maxlen || @$ary > $maxlen; | ||||
1967 | } | ||||
1968 | # if there are no arrays then execute scalars once | ||||
1969 | $maxlen = 1 unless defined $maxlen; | ||||
1970 | my @bind_ids = 1..keys(%hash_of_arrays); | ||||
1971 | |||||
1972 | my $tuple_idx = 0; | ||||
1973 | $fetch_tuple_sub = sub { | ||||
1974 | return if $tuple_idx >= $maxlen; | ||||
1975 | my @tuple = map { | ||||
1976 | my $a = $hash_of_arrays{$_}; | ||||
1977 | ref($a) ? $a->[$tuple_idx] : $a | ||||
1978 | } @bind_ids; | ||||
1979 | ++$tuple_idx; | ||||
1980 | return \@tuple; | ||||
1981 | }; | ||||
1982 | } | ||||
1983 | # pass thru the callers scalar or list context | ||||
1984 | return $sth->execute_for_fetch($fetch_tuple_sub, $tuple_sts); | ||||
1985 | } | ||||
1986 | |||||
1987 | sub execute_for_fetch { | ||||
1988 | my ($sth, $fetch_tuple_sub, $tuple_status) = @_; | ||||
1989 | # start with empty status array | ||||
1990 | ($tuple_status) ? @$tuple_status = () : $tuple_status = []; | ||||
1991 | |||||
1992 | my $rc_total = 0; | ||||
1993 | my $err_count; | ||||
1994 | while ( my $tuple = &$fetch_tuple_sub() ) { | ||||
1995 | if ( my $rc = $sth->execute(@$tuple) ) { | ||||
1996 | push @$tuple_status, $rc; | ||||
1997 | $rc_total = ($rc >= 0 && $rc_total >= 0) ? $rc_total + $rc : -1; | ||||
1998 | } | ||||
1999 | else { | ||||
2000 | $err_count++; | ||||
2001 | push @$tuple_status, [ $sth->err, $sth->errstr, $sth->state ]; | ||||
2002 | # XXX drivers implementing execute_for_fetch could opt to "last;" here | ||||
2003 | # if they know the error code means no further executes will work. | ||||
2004 | } | ||||
2005 | } | ||||
2006 | my $tuples = @$tuple_status; | ||||
2007 | return $sth->set_err($DBI::stderr, "executing $tuples generated $err_count errors") | ||||
2008 | if $err_count; | ||||
2009 | $tuples ||= "0E0"; | ||||
2010 | return $tuples unless wantarray; | ||||
2011 | return ($tuples, $rc_total); | ||||
2012 | } | ||||
2013 | |||||
2014 | |||||
2015 | sub fetchall_arrayref { # ALSO IN Driver.xst | ||||
2016 | my ($sth, $slice, $max_rows) = @_; | ||||
2017 | |||||
2018 | # when batch fetching with $max_rows were very likely to try to | ||||
2019 | # fetch the 'next batch' after the previous batch returned | ||||
2020 | # <=$max_rows. So don't treat that as an error. | ||||
2021 | return undef if $max_rows and not $sth->FETCH('Active'); | ||||
2022 | |||||
2023 | my $mode = ref($slice) || 'ARRAY'; | ||||
2024 | my @rows; | ||||
2025 | |||||
2026 | if ($mode eq 'ARRAY') { | ||||
2027 | my $row; | ||||
2028 | # we copy the array here because fetch (currently) always | ||||
2029 | # returns the same array ref. XXX | ||||
2030 | if ($slice && @$slice) { | ||||
2031 | $max_rows = -1 unless defined $max_rows; | ||||
2032 | push @rows, [ @{$row}[ @$slice] ] | ||||
2033 | while($max_rows-- and $row = $sth->fetch); | ||||
2034 | } | ||||
2035 | elsif (defined $max_rows) { | ||||
2036 | push @rows, [ @$row ] | ||||
2037 | while($max_rows-- and $row = $sth->fetch); | ||||
2038 | } | ||||
2039 | else { | ||||
2040 | push @rows, [ @$row ] while($row = $sth->fetch); | ||||
2041 | } | ||||
2042 | return \@rows | ||||
2043 | } | ||||
2044 | |||||
2045 | my %row; | ||||
2046 | if ($mode eq 'REF' && ref($$slice) eq 'HASH') { # \{ $idx => $name } | ||||
2047 | keys %$$slice; # reset the iterator | ||||
2048 | while ( my ($idx, $name) = each %$$slice ) { | ||||
2049 | $sth->bind_col($idx+1, \$row{$name}); | ||||
2050 | } | ||||
2051 | } | ||||
2052 | elsif ($mode eq 'HASH') { | ||||
2053 | if (keys %$slice) { | ||||
2054 | keys %$slice; # reset the iterator | ||||
2055 | my $name2idx = $sth->FETCH('NAME_lc_hash'); | ||||
2056 | while ( my ($name, $unused) = each %$slice ) { | ||||
2057 | my $idx = $name2idx->{lc $name}; | ||||
2058 | return $sth->set_err($DBI::stderr, "Invalid column name '$name' for slice") | ||||
2059 | if not defined $idx; | ||||
2060 | $sth->bind_col($idx+1, \$row{$name}); | ||||
2061 | } | ||||
2062 | } | ||||
2063 | else { | ||||
2064 | $sth->bind_columns( \( @row{ @{$sth->FETCH($sth->FETCH('FetchHashKeyName')) } } ) ); | ||||
2065 | } | ||||
2066 | } | ||||
2067 | else { | ||||
2068 | return $sth->set_err($DBI::stderr, "fetchall_arrayref($mode) invalid"); | ||||
2069 | } | ||||
2070 | |||||
2071 | if (not defined $max_rows) { | ||||
2072 | push @rows, { %row } while ($sth->fetch); # full speed ahead! | ||||
2073 | } | ||||
2074 | else { | ||||
2075 | push @rows, { %row } while ($max_rows-- and $sth->fetch); | ||||
2076 | } | ||||
2077 | |||||
2078 | return \@rows; | ||||
2079 | } | ||||
2080 | |||||
2081 | sub fetchall_hashref { | ||||
2082 | my ($sth, $key_field) = @_; | ||||
2083 | |||||
2084 | my $hash_key_name = $sth->{FetchHashKeyName} || 'NAME'; | ||||
2085 | my $names_hash = $sth->FETCH("${hash_key_name}_hash"); | ||||
2086 | my @key_fields = (ref $key_field) ? @$key_field : ($key_field); | ||||
2087 | my @key_indexes; | ||||
2088 | my $num_of_fields = $sth->FETCH('NUM_OF_FIELDS'); | ||||
2089 | foreach (@key_fields) { | ||||
2090 | my $index = $names_hash->{$_}; # perl index not column | ||||
2091 | $index = $_ - 1 if !defined $index && DBI::looks_like_number($_) && $_>=1 && $_ <= $num_of_fields; | ||||
2092 | return $sth->set_err($DBI::stderr, "Field '$_' does not exist (not one of @{[keys %$names_hash]})") | ||||
2093 | unless defined $index; | ||||
2094 | push @key_indexes, $index; | ||||
2095 | } | ||||
2096 | my $rows = {}; | ||||
2097 | my $NAME = $sth->FETCH($hash_key_name); | ||||
2098 | my @row = (undef) x $num_of_fields; | ||||
2099 | $sth->bind_columns(\(@row)); | ||||
2100 | while ($sth->fetch) { | ||||
2101 | my $ref = $rows; | ||||
2102 | $ref = $ref->{$row[$_]} ||= {} for @key_indexes; | ||||
2103 | @{$ref}{@$NAME} = @row; | ||||
2104 | } | ||||
2105 | return $rows; | ||||
2106 | } | ||||
2107 | |||||
2108 | *dump_results = \&DBI::dump_results; | ||||
2109 | |||||
2110 | sub blob_copy_to_file { # returns length or undef on error | ||||
2111 | my($self, $field, $filename_or_handleref, $blocksize) = @_; | ||||
2112 | my $fh = $filename_or_handleref; | ||||
2113 | my($len, $buf) = (0, ""); | ||||
2114 | $blocksize ||= 512; # not too ambitious | ||||
2115 | local(*FH); | ||||
2116 | unless(ref $fh) { | ||||
2117 | open(FH, ">$fh") || return undef; | ||||
2118 | $fh = \*FH; | ||||
2119 | } | ||||
2120 | while(defined($self->blob_read($field, $len, $blocksize, \$buf))) { | ||||
2121 | print $fh $buf; | ||||
2122 | $len += length $buf; | ||||
2123 | } | ||||
2124 | close(FH); | ||||
2125 | $len; | ||||
2126 | } | ||||
2127 | |||||
2128 | sub more_results { | ||||
2129 | shift->{syb_more_results}; # handy grandfathering | ||||
2130 | } | ||||
2131 | |||||
2132 | } | ||||
2133 | |||||
2134 | unless ($DBI::PurePerl) { # See install_driver | ||||
2135 | { @DBD::_mem::dr::ISA = qw(DBD::_mem::common); } | ||||
2136 | { @DBD::_mem::db::ISA = qw(DBD::_mem::common); } | ||||
2137 | { @DBD::_mem::st::ISA = qw(DBD::_mem::common); } | ||||
2138 | # DBD::_mem::common::DESTROY is implemented in DBI.xs | ||||
2139 | } | ||||
2140 | |||||
2141 | 1; | ||||
2142 | __END__ | ||||
2143 | |||||
2144 | =head1 DESCRIPTION | ||||
2145 | |||||
2146 | The DBI is a database access module for the Perl programming language. It defines | ||||
2147 | a set of methods, variables, and conventions that provide a consistent | ||||
2148 | database interface, independent of the actual database being used. | ||||
2149 | |||||
2150 | It is important to remember that the DBI is just an interface. | ||||
2151 | The DBI is a layer | ||||
2152 | of "glue" between an application and one or more database I<driver> | ||||
2153 | modules. It is the driver modules which do most of the real work. The DBI | ||||
2154 | provides a standard interface and framework for the drivers to operate | ||||
2155 | within. | ||||
2156 | |||||
2157 | This document often uses terms like I<references>, I<objects>, | ||||
2158 | I<methods>. If you're not familiar with those terms then it would | ||||
2159 | be a good idea to read at least the following perl manuals first: | ||||
2160 | L<perlreftut>, L<perldsc>, L<perllol>, and L<perlboot>. | ||||
2161 | |||||
2162 | |||||
2163 | =head2 Architecture of a DBI Application | ||||
2164 | |||||
2165 | |<- Scope of DBI ->| | ||||
2166 | .-. .--------------. .-------------. | ||||
2167 | .-------. | |---| XYZ Driver |---| XYZ Engine | | ||||
2168 | | Perl | | | `--------------' `-------------' | ||||
2169 | | script| |A| |D| .--------------. .-------------. | ||||
2170 | | using |--|P|--|B|---|Oracle Driver |---|Oracle Engine| | ||||
2171 | | DBI | |I| |I| `--------------' `-------------' | ||||
2172 | | API | | |... | ||||
2173 | |methods| | |... Other drivers | ||||
2174 | `-------' | |... | ||||
2175 | `-' | ||||
2176 | |||||
2177 | The API, or Application Programming Interface, defines the | ||||
2178 | call interface and variables for Perl scripts to use. The API | ||||
2179 | is implemented by the Perl DBI extension. | ||||
2180 | |||||
2181 | The DBI "dispatches" the method calls to the appropriate driver for | ||||
2182 | actual execution. The DBI is also responsible for the dynamic loading | ||||
2183 | of drivers, error checking and handling, providing default | ||||
2184 | implementations for methods, and many other non-database specific duties. | ||||
2185 | |||||
2186 | Each driver | ||||
2187 | contains implementations of the DBI methods using the | ||||
2188 | private interface functions of the corresponding database engine. Only authors | ||||
2189 | of sophisticated/multi-database applications or generic library | ||||
2190 | functions need be concerned with drivers. | ||||
2191 | |||||
2192 | =head2 Notation and Conventions | ||||
2193 | |||||
2194 | The following conventions are used in this document: | ||||
2195 | |||||
2196 | $dbh Database handle object | ||||
2197 | $sth Statement handle object | ||||
2198 | $drh Driver handle object (rarely seen or used in applications) | ||||
2199 | $h Any of the handle types above ($dbh, $sth, or $drh) | ||||
2200 | $rc General Return Code (boolean: true=ok, false=error) | ||||
2201 | $rv General Return Value (typically an integer) | ||||
2202 | @ary List of values returned from the database, typically a row of data | ||||
2203 | $rows Number of rows processed (if available, else -1) | ||||
2204 | $fh A filehandle | ||||
2205 | undef NULL values are represented by undefined values in Perl | ||||
2206 | \%attr Reference to a hash of attribute values passed to methods | ||||
2207 | |||||
2208 | Note that Perl will automatically destroy database and statement handle objects | ||||
2209 | if all references to them are deleted. | ||||
2210 | |||||
2211 | |||||
2212 | =head2 Outline Usage | ||||
2213 | |||||
2214 | To use DBI, | ||||
2215 | first you need to load the DBI module: | ||||
2216 | |||||
2217 | use DBI; | ||||
2218 | use strict; | ||||
2219 | |||||
2220 | (The C<use strict;> isn't required but is strongly recommended.) | ||||
2221 | |||||
2222 | Then you need to L</connect> to your data source and get a I<handle> for that | ||||
2223 | connection: | ||||
2224 | |||||
2225 | $dbh = DBI->connect($dsn, $user, $password, | ||||
2226 | { RaiseError => 1, AutoCommit => 0 }); | ||||
2227 | |||||
2228 | Since connecting can be expensive, you generally just connect at the | ||||
2229 | start of your program and disconnect at the end. | ||||
2230 | |||||
2231 | Explicitly defining the required C<AutoCommit> behaviour is strongly | ||||
2232 | recommended and may become mandatory in a later version. This | ||||
2233 | determines whether changes are automatically committed to the | ||||
2234 | database when executed, or need to be explicitly committed later. | ||||
2235 | |||||
2236 | The DBI allows an application to "prepare" statements for later | ||||
2237 | execution. A prepared statement is identified by a statement handle | ||||
2238 | held in a Perl variable. | ||||
2239 | We'll call the Perl variable C<$sth> in our examples. | ||||
2240 | |||||
2241 | The typical method call sequence for a C<SELECT> statement is: | ||||
2242 | |||||
2243 | prepare, | ||||
2244 | execute, fetch, fetch, ... | ||||
2245 | execute, fetch, fetch, ... | ||||
2246 | execute, fetch, fetch, ... | ||||
2247 | |||||
2248 | for example: | ||||
2249 | |||||
2250 | $sth = $dbh->prepare("SELECT foo, bar FROM table WHERE baz=?"); | ||||
2251 | |||||
2252 | $sth->execute( $baz ); | ||||
2253 | |||||
2254 | while ( @row = $sth->fetchrow_array ) { | ||||
2255 | print "@row\n"; | ||||
2256 | } | ||||
2257 | |||||
2258 | The typical method call sequence for a I<non>-C<SELECT> statement is: | ||||
2259 | |||||
2260 | prepare, | ||||
2261 | execute, | ||||
2262 | execute, | ||||
2263 | execute. | ||||
2264 | |||||
2265 | for example: | ||||
2266 | |||||
2267 | $sth = $dbh->prepare("INSERT INTO table(foo,bar,baz) VALUES (?,?,?)"); | ||||
2268 | |||||
2269 | while(<CSV>) { | ||||
2270 | chomp; | ||||
2271 | my ($foo,$bar,$baz) = split /,/; | ||||
2272 | $sth->execute( $foo, $bar, $baz ); | ||||
2273 | } | ||||
2274 | |||||
2275 | The C<do()> method can be used for non repeated I<non>-C<SELECT> statement | ||||
2276 | (or with drivers that don't support placeholders): | ||||
2277 | |||||
2278 | $rows_affected = $dbh->do("UPDATE your_table SET foo = foo + 1"); | ||||
2279 | |||||
2280 | To commit your changes to the database (when L</AutoCommit> is off): | ||||
2281 | |||||
2282 | $dbh->commit; # or call $dbh->rollback; to undo changes | ||||
2283 | |||||
2284 | Finally, when you have finished working with the data source, you should | ||||
2285 | L</disconnect> from it: | ||||
2286 | |||||
2287 | $dbh->disconnect; | ||||
2288 | |||||
2289 | |||||
2290 | =head2 General Interface Rules & Caveats | ||||
2291 | |||||
2292 | The DBI does not have a concept of a "current session". Every session | ||||
2293 | has a handle object (i.e., a C<$dbh>) returned from the C<connect> method. | ||||
2294 | That handle object is used to invoke database related methods. | ||||
2295 | |||||
2296 | Most data is returned to the Perl script as strings. (Null values are | ||||
2297 | returned as C<undef>.) This allows arbitrary precision numeric data to be | ||||
2298 | handled without loss of accuracy. Beware that Perl may not preserve | ||||
2299 | the same accuracy when the string is used as a number. | ||||
2300 | |||||
2301 | Dates and times are returned as character strings in the current | ||||
2302 | default format of the corresponding database engine. Time zone effects | ||||
2303 | are database/driver dependent. | ||||
2304 | |||||
2305 | Perl supports binary data in Perl strings, and the DBI will pass binary | ||||
2306 | data to and from the driver without change. It is up to the driver | ||||
2307 | implementors to decide how they wish to handle such binary data. | ||||
2308 | |||||
2309 | Perl supports two kinds of strings: Unicode (utf8 internally) and non-Unicode | ||||
2310 | (defaults to iso-8859-1 if forced to assume an encoding). Drivers should | ||||
2311 | accept both kinds of strings and, if required, convert them to the character | ||||
2312 | set of the database being used. Similarly, when fetching from the database | ||||
2313 | character data that isn't iso-8859-1 the driver should convert it into utf8. | ||||
2314 | |||||
2315 | Multiple SQL statements may not be combined in a single statement | ||||
2316 | handle (C<$sth>), although some databases and drivers do support this | ||||
2317 | (notably Sybase and SQL Server). | ||||
2318 | |||||
2319 | Non-sequential record reads are not supported in this version of the DBI. | ||||
2320 | In other words, records can only be fetched in the order that the | ||||
2321 | database returned them, and once fetched they are forgotten. | ||||
2322 | |||||
2323 | Positioned updates and deletes are not directly supported by the DBI. | ||||
2324 | See the description of the C<CursorName> attribute for an alternative. | ||||
2325 | |||||
2326 | Individual driver implementors are free to provide any private | ||||
2327 | functions and/or handle attributes that they feel are useful. | ||||
2328 | Private driver functions can be invoked using the DBI C<func()> method. | ||||
2329 | Private driver attributes are accessed just like standard attributes. | ||||
2330 | |||||
2331 | Many methods have an optional C<\%attr> parameter which can be used to | ||||
2332 | pass information to the driver implementing the method. Except where | ||||
2333 | specifically documented, the C<\%attr> parameter can only be used to pass | ||||
2334 | driver specific hints. In general, you can ignore C<\%attr> parameters | ||||
2335 | or pass it as C<undef>. | ||||
2336 | |||||
2337 | |||||
2338 | =head2 Naming Conventions and Name Space | ||||
2339 | |||||
2340 | The DBI package and all packages below it (C<DBI::*>) are reserved for | ||||
2341 | use by the DBI. Extensions and related modules use the C<DBIx::> | ||||
2342 | namespace (see L<http://www.perl.com/CPAN/modules/by-module/DBIx/>). | ||||
2343 | Package names beginning with C<DBD::> are reserved for use | ||||
2344 | by DBI database drivers. All environment variables used by the DBI | ||||
2345 | or by individual DBDs begin with "C<DBI_>" or "C<DBD_>". | ||||
2346 | |||||
2347 | The letter case used for attribute names is significant and plays an | ||||
2348 | important part in the portability of DBI scripts. The case of the | ||||
2349 | attribute name is used to signify who defined the meaning of that name | ||||
2350 | and its values. | ||||
2351 | |||||
2352 | Case of name Has a meaning defined by | ||||
2353 | ------------ ------------------------ | ||||
2354 | UPPER_CASE Standards, e.g., X/Open, ISO SQL92 etc (portable) | ||||
2355 | MixedCase DBI API (portable), underscores are not used. | ||||
2356 | lower_case Driver or database engine specific (non-portable) | ||||
2357 | |||||
2358 | It is of the utmost importance that Driver developers only use | ||||
2359 | lowercase attribute names when defining private attributes. Private | ||||
2360 | attribute names must be prefixed with the driver name or suitable | ||||
2361 | abbreviation (e.g., "C<ora_>" for Oracle, "C<ing_>" for Ingres, etc). | ||||
2362 | |||||
2363 | |||||
2364 | =head2 SQL - A Query Language | ||||
2365 | |||||
2366 | Most DBI drivers require applications to use a dialect of SQL | ||||
2367 | (Structured Query Language) to interact with the database engine. | ||||
2368 | The L</"Standards Reference Information"> section provides links | ||||
2369 | to useful information about SQL. | ||||
2370 | |||||
2371 | The DBI itself does not mandate or require any particular language to | ||||
2372 | be used; it is language independent. In ODBC terms, the DBI is in | ||||
2373 | "pass-thru" mode, although individual drivers might not be. The only requirement | ||||
2374 | is that queries and other statements must be expressed as a single | ||||
2375 | string of characters passed as the first argument to the L</prepare> or | ||||
2376 | L</do> methods. | ||||
2377 | |||||
2378 | For an interesting diversion on the I<real> history of RDBMS and SQL, | ||||
2379 | from the people who made it happen, see: | ||||
2380 | |||||
2381 | http://www.mcjones.org/System_R/SQL_Reunion_95/sqlr95.html | ||||
2382 | |||||
2383 | Follow the "Full Contents" then "Intergalactic dataspeak" links for the | ||||
2384 | SQL history. | ||||
2385 | |||||
2386 | =head2 Placeholders and Bind Values | ||||
2387 | |||||
2388 | Some drivers support placeholders and bind values. | ||||
2389 | I<Placeholders>, also called parameter markers, are used to indicate | ||||
2390 | values in a database statement that will be supplied later, | ||||
2391 | before the prepared statement is executed. For example, an application | ||||
2392 | might use the following to insert a row of data into the SALES table: | ||||
2393 | |||||
2394 | INSERT INTO sales (product_code, qty, price) VALUES (?, ?, ?) | ||||
2395 | |||||
2396 | or the following, to select the description for a product: | ||||
2397 | |||||
2398 | SELECT description FROM products WHERE product_code = ? | ||||
2399 | |||||
2400 | The C<?> characters are the placeholders. The association of actual | ||||
2401 | values with placeholders is known as I<binding>, and the values are | ||||
2402 | referred to as I<bind values>. | ||||
2403 | Note that the C<?> is not enclosed in quotation marks, even when the | ||||
2404 | placeholder represents a string. | ||||
2405 | |||||
2406 | Some drivers also allow placeholders like C<:>I<name> and C<:>I<N> (e.g., | ||||
2407 | C<:1>, C<:2>, and so on) in addition to C<?>, but their use is not portable. | ||||
2408 | |||||
2409 | If the C<:>I<N> form of placeholder is supported by the driver you're using, | ||||
2410 | then you should be able to use either L</bind_param> or L</execute> to bind | ||||
2411 | values. Check your driver documentation. | ||||
2412 | |||||
2413 | With most drivers, placeholders can't be used for any element of a | ||||
2414 | statement that would prevent the database server from validating the | ||||
2415 | statement and creating a query execution plan for it. For example: | ||||
2416 | |||||
2417 | "SELECT name, age FROM ?" # wrong (will probably fail) | ||||
2418 | "SELECT name, ? FROM people" # wrong (but may not 'fail') | ||||
2419 | |||||
2420 | Also, placeholders can only represent single scalar values. | ||||
2421 | For example, the following | ||||
2422 | statement won't work as expected for more than one value: | ||||
2423 | |||||
2424 | "SELECT name, age FROM people WHERE name IN (?)" # wrong | ||||
2425 | "SELECT name, age FROM people WHERE name IN (?,?)" # two names | ||||
2426 | |||||
2427 | When using placeholders with the SQL C<LIKE> qualifier, you must | ||||
2428 | remember that the placeholder substitutes for the whole string. | ||||
2429 | So you should use "C<... LIKE ? ...>" and include any wildcard | ||||
2430 | characters in the value that you bind to the placeholder. | ||||
2431 | |||||
2432 | B<NULL Values> | ||||
2433 | |||||
2434 | Undefined values, or C<undef>, are used to indicate NULL values. | ||||
2435 | You can insert and update columns with a NULL value as you would a | ||||
2436 | non-NULL value. These examples insert and update the column | ||||
2437 | C<age> with a NULL value: | ||||
2438 | |||||
2439 | $sth = $dbh->prepare(qq{ | ||||
2440 | INSERT INTO people (fullname, age) VALUES (?, ?) | ||||
2441 | }); | ||||
2442 | $sth->execute("Joe Bloggs", undef); | ||||
2443 | |||||
2444 | $sth = $dbh->prepare(qq{ | ||||
2445 | UPDATE people SET age = ? WHERE fullname = ? | ||||
2446 | }); | ||||
2447 | $sth->execute(undef, "Joe Bloggs"); | ||||
2448 | |||||
2449 | However, care must be taken when trying to use NULL values in a | ||||
2450 | C<WHERE> clause. Consider: | ||||
2451 | |||||
2452 | SELECT fullname FROM people WHERE age = ? | ||||
2453 | |||||
2454 | Binding an C<undef> (NULL) to the placeholder will I<not> select rows | ||||
2455 | which have a NULL C<age>! At least for database engines that | ||||
2456 | conform to the SQL standard. Refer to the SQL manual for your database | ||||
2457 | engine or any SQL book for the reasons for this. To explicitly select | ||||
2458 | NULLs you have to say "C<WHERE age IS NULL>". | ||||
2459 | |||||
2460 | A common issue is to have a code fragment handle a value that could be | ||||
2461 | either C<defined> or C<undef> (non-NULL or NULL) at runtime. | ||||
2462 | A simple technique is to prepare the appropriate statement as needed, | ||||
2463 | and substitute the placeholder for non-NULL cases: | ||||
2464 | |||||
2465 | $sql_clause = defined $age? "age = ?" : "age IS NULL"; | ||||
2466 | $sth = $dbh->prepare(qq{ | ||||
2467 | SELECT fullname FROM people WHERE $sql_clause | ||||
2468 | }); | ||||
2469 | $sth->execute(defined $age ? $age : ()); | ||||
2470 | |||||
2471 | The following technique illustrates qualifying a C<WHERE> clause with | ||||
2472 | several columns, whose associated values (C<defined> or C<undef>) are | ||||
2473 | in a hash %h: | ||||
2474 | |||||
2475 | for my $col ("age", "phone", "email") { | ||||
2476 | if (defined $h{$col}) { | ||||
2477 | push @sql_qual, "$col = ?"; | ||||
2478 | push @sql_bind, $h{$col}; | ||||
2479 | } | ||||
2480 | else { | ||||
2481 | push @sql_qual, "$col IS NULL"; | ||||
2482 | } | ||||
2483 | } | ||||
2484 | $sql_clause = join(" AND ", @sql_qual); | ||||
2485 | $sth = $dbh->prepare(qq{ | ||||
2486 | SELECT fullname FROM people WHERE $sql_clause | ||||
2487 | }); | ||||
2488 | $sth->execute(@sql_bind); | ||||
2489 | |||||
2490 | The techniques above call prepare for the SQL statement with each call to | ||||
2491 | execute. Because calls to prepare() can be expensive, performance | ||||
2492 | can suffer when an application iterates many times over statements | ||||
2493 | like the above. | ||||
2494 | |||||
2495 | A better solution is a single C<WHERE> clause that supports both | ||||
2496 | NULL and non-NULL comparisons. Its SQL statement would need to be | ||||
2497 | prepared only once for all cases, thus improving performance. | ||||
2498 | Several examples of C<WHERE> clauses that support this are presented | ||||
2499 | below. But each example lacks portability, robustness, or simplicity. | ||||
2500 | Whether an example is supported on your database engine depends on | ||||
2501 | what SQL extensions it provides, and where it supports the C<?> | ||||
2502 | placeholder in a statement. | ||||
2503 | |||||
2504 | 0) age = ? | ||||
2505 | 1) NVL(age, xx) = NVL(?, xx) | ||||
2506 | 2) ISNULL(age, xx) = ISNULL(?, xx) | ||||
2507 | 3) DECODE(age, ?, 1, 0) = 1 | ||||
2508 | 4) age = ? OR (age IS NULL AND ? IS NULL) | ||||
2509 | 5) age = ? OR (age IS NULL AND SP_ISNULL(?) = 1) | ||||
2510 | 6) age = ? OR (age IS NULL AND ? = 1) | ||||
2511 | |||||
2512 | Statements formed with the above C<WHERE> clauses require execute | ||||
2513 | statements as follows. The arguments are required, whether their | ||||
2514 | values are C<defined> or C<undef>. | ||||
2515 | |||||
2516 | 0,1,2,3) $sth->execute($age); | ||||
2517 | 4,5) $sth->execute($age, $age); | ||||
2518 | 6) $sth->execute($age, defined($age) ? 0 : 1); | ||||
2519 | |||||
2520 | Example 0 should not work (as mentioned earlier), but may work on | ||||
2521 | a few database engines anyway (e.g. Sybase). Example 0 is part | ||||
2522 | of examples 4, 5, and 6, so if example 0 works, these other | ||||
2523 | examples may work, even if the engine does not properly support | ||||
2524 | the right hand side of the C<OR> expression. | ||||
2525 | |||||
2526 | Examples 1 and 2 are not robust: they require that you provide a | ||||
2527 | valid column value xx (e.g. '~') which is not present in any row. | ||||
2528 | That means you must have some notion of what data won't be stored | ||||
2529 | in the column, and expect clients to adhere to that. | ||||
2530 | |||||
2531 | Example 5 requires that you provide a stored procedure (SP_ISNULL | ||||
2532 | in this example) that acts as a function: it checks whether a value | ||||
2533 | is null, and returns 1 if it is, or 0 if not. | ||||
2534 | |||||
2535 | Example 6, the least simple, is probably the most portable, i.e., it | ||||
2536 | should work with most, if not all, database engines. | ||||
2537 | |||||
2538 | Here is a table that indicates which examples above are known to | ||||
2539 | work on various database engines: | ||||
2540 | |||||
2541 | -----Examples------ | ||||
2542 | 0 1 2 3 4 5 6 | ||||
2543 | - - - - - - - | ||||
2544 | Oracle 9 N Y N Y Y ? Y | ||||
2545 | Informix IDS 9 N N N Y N Y Y | ||||
2546 | MS SQL N N Y N Y ? Y | ||||
2547 | Sybase Y N N N N N Y | ||||
2548 | AnyData,DBM,CSV Y N N N Y Y* Y | ||||
2549 | SQLite 3.3 N N N N Y N N | ||||
2550 | MSAccess N N N N Y N Y | ||||
2551 | |||||
2552 | * Works only because Example 0 works. | ||||
2553 | |||||
2554 | DBI provides a sample perl script that will test the examples above | ||||
2555 | on your database engine and tell you which ones work. It is located | ||||
2556 | in the F<ex/> subdirectory of the DBI source distribution, or here: | ||||
2557 | L<https://github.com/perl5-dbi/dbi/blob/master/ex/perl_dbi_nulls_test.pl> | ||||
2558 | Please use the script to help us fill-in and maintain this table. | ||||
2559 | |||||
2560 | B<Performance> | ||||
2561 | |||||
2562 | Without using placeholders, the insert statement shown previously would have to | ||||
2563 | contain the literal values to be inserted and would have to be | ||||
2564 | re-prepared and re-executed for each row. With placeholders, the insert | ||||
2565 | statement only needs to be prepared once. The bind values for each row | ||||
2566 | can be given to the C<execute> method each time it's called. By avoiding | ||||
2567 | the need to re-prepare the statement for each row, the application | ||||
2568 | typically runs many times faster. Here's an example: | ||||
2569 | |||||
2570 | my $sth = $dbh->prepare(q{ | ||||
2571 | INSERT INTO sales (product_code, qty, price) VALUES (?, ?, ?) | ||||
2572 | }) or die $dbh->errstr; | ||||
2573 | while (<>) { | ||||
2574 | chomp; | ||||
2575 | my ($product_code, $qty, $price) = split /,/; | ||||
2576 | $sth->execute($product_code, $qty, $price) or die $dbh->errstr; | ||||
2577 | } | ||||
2578 | $dbh->commit or die $dbh->errstr; | ||||
2579 | |||||
2580 | See L</execute> and L</bind_param> for more details. | ||||
2581 | |||||
2582 | The C<q{...}> style quoting used in this example avoids clashing with | ||||
2583 | quotes that may be used in the SQL statement. Use the double-quote like | ||||
2584 | C<qq{...}> operator if you want to interpolate variables into the string. | ||||
2585 | See L<perlop/"Quote and Quote-like Operators"> for more details. | ||||
2586 | |||||
2587 | See also the L</bind_columns> method, which is used to associate Perl | ||||
2588 | variables with the output columns of a C<SELECT> statement. | ||||
2589 | |||||
2590 | =head1 THE DBI PACKAGE AND CLASS | ||||
2591 | |||||
2592 | In this section, we cover the DBI class methods, utility functions, | ||||
2593 | and the dynamic attributes associated with generic DBI handles. | ||||
2594 | |||||
2595 | =head2 DBI Constants | ||||
2596 | |||||
2597 | Constants representing the values of the SQL standard types can be | ||||
2598 | imported individually by name, or all together by importing the | ||||
2599 | special C<:sql_types> tag. | ||||
2600 | |||||
2601 | The names and values of all the defined SQL standard types can be | ||||
2602 | produced like this: | ||||
2603 | |||||
2604 | foreach (@{ $DBI::EXPORT_TAGS{sql_types} }) { | ||||
2605 | printf "%s=%d\n", $_, &{"DBI::$_"}; | ||||
2606 | } | ||||
2607 | |||||
2608 | These constants are defined by SQL/CLI, ODBC or both. | ||||
2609 | C<SQL_BIGINT> has conflicting codes in SQL/CLI and ODBC, | ||||
2610 | DBI uses the ODBC one. | ||||
2611 | |||||
2612 | See the L</type_info>, L</type_info_all>, and L</bind_param> methods | ||||
2613 | for possible uses. | ||||
2614 | |||||
2615 | Note that just because the DBI defines a named constant for a given | ||||
2616 | data type doesn't mean that drivers will support that data type. | ||||
2617 | |||||
2618 | |||||
2619 | =head2 DBI Class Methods | ||||
2620 | |||||
2621 | The following methods are provided by the DBI class: | ||||
2622 | |||||
2623 | =head3 C<parse_dsn> | ||||
2624 | |||||
2625 | ($scheme, $driver, $attr_string, $attr_hash, $driver_dsn) = DBI->parse_dsn($dsn) | ||||
2626 | or die "Can't parse DBI DSN '$dsn'"; | ||||
2627 | |||||
2628 | Breaks apart a DBI Data Source Name (DSN) and returns the individual | ||||
2629 | parts. If $dsn doesn't contain a valid DSN then parse_dsn() returns | ||||
2630 | an empty list. | ||||
2631 | |||||
2632 | $scheme is the first part of the DSN and is currently always 'dbi'. | ||||
2633 | $driver is the driver name, possibly defaulted to $ENV{DBI_DRIVER}, | ||||
2634 | and may be undefined. $attr_string is the contents of the optional attribute | ||||
2635 | string, which may be undefined. If $attr_string is not empty then $attr_hash | ||||
2636 | is a reference to a hash containing the parsed attribute names and values. | ||||
2637 | $driver_dsn is the last part of the DBI DSN string. For example: | ||||
2638 | |||||
2639 | ($scheme, $driver, $attr_string, $attr_hash, $driver_dsn) | ||||
2640 | = DBI->parse_dsn("DBI:MyDriver(RaiseError=>1):db=test;port=42"); | ||||
2641 | $scheme = 'dbi'; | ||||
2642 | $driver = 'MyDriver'; | ||||
2643 | $attr_string = 'RaiseError=>1'; | ||||
2644 | $attr_hash = { 'RaiseError' => '1' }; | ||||
2645 | $driver_dsn = 'db=test;port=42'; | ||||
2646 | |||||
2647 | The parse_dsn() method was added in DBI 1.43. | ||||
2648 | |||||
2649 | =head3 C<connect> | ||||
2650 | |||||
2651 | $dbh = DBI->connect($data_source, $username, $password) | ||||
2652 | or die $DBI::errstr; | ||||
2653 | $dbh = DBI->connect($data_source, $username, $password, \%attr) | ||||
2654 | or die $DBI::errstr; | ||||
2655 | |||||
2656 | Establishes a database connection, or session, to the requested C<$data_source>. | ||||
2657 | Returns a database handle object if the connection succeeds. Use | ||||
2658 | C<$dbh-E<gt>disconnect> to terminate the connection. | ||||
2659 | |||||
2660 | If the connect fails (see below), it returns C<undef> and sets both C<$DBI::err> | ||||
2661 | and C<$DBI::errstr>. (It does I<not> explicitly set C<$!>.) You should generally | ||||
2662 | test the return status of C<connect> and C<print $DBI::errstr> if it has failed. | ||||
2663 | |||||
2664 | Multiple simultaneous connections to multiple databases through multiple | ||||
2665 | drivers can be made via the DBI. Simply make one C<connect> call for each | ||||
2666 | database and keep a copy of each returned database handle. | ||||
2667 | |||||
2668 | The C<$data_source> value must begin with "C<dbi:>I<driver_name>C<:>". | ||||
2669 | The I<driver_name> specifies the driver that will be used to make the | ||||
2670 | connection. (Letter case is significant.) | ||||
2671 | |||||
2672 | As a convenience, if the C<$data_source> parameter is undefined or empty, | ||||
2673 | the DBI will substitute the value of the environment variable C<DBI_DSN>. | ||||
2674 | If just the I<driver_name> part is empty (i.e., the C<$data_source> | ||||
2675 | prefix is "C<dbi::>"), the environment variable C<DBI_DRIVER> is | ||||
2676 | used. If neither variable is set, then C<connect> dies. | ||||
2677 | |||||
2678 | Examples of C<$data_source> values are: | ||||
2679 | |||||
2680 | dbi:DriverName:database_name | ||||
2681 | dbi:DriverName:database_name@hostname:port | ||||
2682 | dbi:DriverName:database=database_name;host=hostname;port=port | ||||
2683 | |||||
2684 | There is I<no standard> for the text following the driver name. Each | ||||
2685 | driver is free to use whatever syntax it wants. The only requirement the | ||||
2686 | DBI makes is that all the information is supplied in a single string. | ||||
2687 | You must consult the documentation for the drivers you are using for a | ||||
2688 | description of the syntax they require. | ||||
2689 | |||||
2690 | It is recommended that drivers support the ODBC style, shown in the | ||||
2691 | last example above. It is also recommended that they support the | ||||
2692 | three common names 'C<host>', 'C<port>', and 'C<database>' (plus 'C<db>' | ||||
2693 | as an alias for C<database>). This simplifies automatic construction | ||||
2694 | of basic DSNs: C<"dbi:$driver:database=$db;host=$host;port=$port">. | ||||
2695 | Drivers should aim to 'do something reasonable' when given a DSN | ||||
2696 | in this form, but if any part is meaningless for that driver (such | ||||
2697 | as 'port' for Informix) it should generate an error if that part | ||||
2698 | is not empty. | ||||
2699 | |||||
2700 | If the environment variable C<DBI_AUTOPROXY> is defined (and the | ||||
2701 | driver in C<$data_source> is not "C<Proxy>") then the connect request | ||||
2702 | will automatically be changed to: | ||||
2703 | |||||
2704 | $ENV{DBI_AUTOPROXY};dsn=$data_source | ||||
2705 | |||||
2706 | C<DBI_AUTOPROXY> is typically set as "C<dbi:Proxy:hostname=...;port=...>". | ||||
2707 | If $ENV{DBI_AUTOPROXY} doesn't begin with 'C<dbi:>' then "dbi:Proxy:" | ||||
2708 | will be prepended to it first. See the DBD::Proxy documentation | ||||
2709 | for more details. | ||||
2710 | |||||
2711 | If C<$username> or C<$password> are undefined (rather than just empty), | ||||
2712 | then the DBI will substitute the values of the C<DBI_USER> and C<DBI_PASS> | ||||
2713 | environment variables, respectively. The DBI will warn if the | ||||
2714 | environment variables are not defined. However, the everyday use | ||||
2715 | of these environment variables is not recommended for security | ||||
2716 | reasons. The mechanism is primarily intended to simplify testing. | ||||
2717 | See below for alternative way to specify the username and password. | ||||
2718 | |||||
2719 | C<DBI-E<gt>connect> automatically installs the driver if it has not been | ||||
2720 | installed yet. Driver installation either returns a valid driver | ||||
2721 | handle, or it I<dies> with an error message that includes the string | ||||
2722 | "C<install_driver>" and the underlying problem. So C<DBI-E<gt>connect> | ||||
2723 | will die | ||||
2724 | on a driver installation failure and will only return C<undef> on a | ||||
2725 | connect failure, in which case C<$DBI::errstr> will hold the error message. | ||||
2726 | Use C<eval { ... }> if you need to catch the "C<install_driver>" error. | ||||
2727 | |||||
2728 | The C<$data_source> argument (with the "C<dbi:...:>" prefix removed) and the | ||||
2729 | C<$username> and C<$password> arguments are then passed to the driver for | ||||
2730 | processing. The DBI does not define any interpretation for the | ||||
2731 | contents of these fields. The driver is free to interpret the | ||||
2732 | C<$data_source>, C<$username>, and C<$password> fields in any way, and supply | ||||
2733 | whatever defaults are appropriate for the engine being accessed. | ||||
2734 | (Oracle, for example, uses the ORACLE_SID and TWO_TASK environment | ||||
2735 | variables if no C<$data_source> is specified.) | ||||
2736 | |||||
2737 | The C<AutoCommit> and C<PrintError> attributes for each connection | ||||
2738 | default to "on". (See L</AutoCommit> and L</PrintError> for more information.) | ||||
2739 | However, it is strongly recommended that you explicitly define C<AutoCommit> | ||||
2740 | rather than rely on the default. The C<PrintWarn> attribute defaults to true. | ||||
2741 | |||||
2742 | The C<\%attr> parameter can be used to alter the default settings of | ||||
2743 | C<PrintError>, C<RaiseError>, C<AutoCommit>, and other attributes. For example: | ||||
2744 | |||||
2745 | $dbh = DBI->connect($data_source, $user, $pass, { | ||||
2746 | PrintError => 0, | ||||
2747 | AutoCommit => 0 | ||||
2748 | }); | ||||
2749 | |||||
2750 | The username and password can also be specified using the attributes | ||||
2751 | C<Username> and C<Password>, in which case they take precedence | ||||
2752 | over the C<$username> and C<$password> parameters. | ||||
2753 | |||||
2754 | You can also define connection attribute values within the C<$data_source> | ||||
2755 | parameter. For example: | ||||
2756 | |||||
2757 | dbi:DriverName(PrintWarn=>0,PrintError=>0,Taint=>1):... | ||||
2758 | |||||
2759 | Individual attributes values specified in this way take precedence over | ||||
2760 | any conflicting values specified via the C<\%attr> parameter to C<connect>. | ||||
2761 | |||||
2762 | The C<dbi_connect_method> attribute can be used to specify which driver | ||||
2763 | method should be called to establish the connection. The only useful | ||||
2764 | values are 'connect', 'connect_cached', or some specialized case like | ||||
2765 | 'Apache::DBI::connect' (which is automatically the default when running | ||||
2766 | within Apache). | ||||
2767 | |||||
2768 | Where possible, each session (C<$dbh>) is independent from the transactions | ||||
2769 | in other sessions. This is useful when you need to hold cursors open | ||||
2770 | across transactions--for example, if you use one session for your long lifespan | ||||
2771 | cursors (typically read-only) and another for your short update | ||||
2772 | transactions. | ||||
2773 | |||||
2774 | For compatibility with old DBI scripts, the driver can be specified by | ||||
2775 | passing its name as the fourth argument to C<connect> (instead of C<\%attr>): | ||||
2776 | |||||
2777 | $dbh = DBI->connect($data_source, $user, $pass, $driver); | ||||
2778 | |||||
2779 | In this "old-style" form of C<connect>, the C<$data_source> should not start | ||||
2780 | with "C<dbi:driver_name:>". (If it does, the embedded driver_name | ||||
2781 | will be ignored). Also note that in this older form of C<connect>, | ||||
2782 | the C<$dbh-E<gt>{AutoCommit}> attribute is I<undefined>, the | ||||
2783 | C<$dbh-E<gt>{PrintError}> attribute is off, and the old C<DBI_DBNAME> | ||||
2784 | environment variable is | ||||
2785 | checked if C<DBI_DSN> is not defined. Beware that this "old-style" | ||||
2786 | C<connect> will soon be withdrawn in a future version of DBI. | ||||
2787 | |||||
2788 | =head3 C<connect_cached> | ||||
2789 | |||||
2790 | $dbh = DBI->connect_cached($data_source, $username, $password) | ||||
2791 | or die $DBI::errstr; | ||||
2792 | $dbh = DBI->connect_cached($data_source, $username, $password, \%attr) | ||||
2793 | or die $DBI::errstr; | ||||
2794 | |||||
2795 | C<connect_cached> is like L</connect>, except that the database handle | ||||
2796 | returned is also | ||||
2797 | stored in a hash associated with the given parameters. If another call | ||||
2798 | is made to C<connect_cached> with the same parameter values, then the | ||||
2799 | corresponding cached C<$dbh> will be returned if it is still valid. | ||||
2800 | The cached database handle is replaced with a new connection if it | ||||
2801 | has been disconnected or if the C<ping> method fails. | ||||
2802 | |||||
2803 | Note that the behaviour of this method differs in several respects from the | ||||
2804 | behaviour of persistent connections implemented by Apache::DBI. | ||||
2805 | However, if Apache::DBI is loaded then C<connect_cached> will use it. | ||||
2806 | |||||
2807 | Caching connections can be useful in some applications, but it can | ||||
2808 | also cause problems, such as too many connections, and so should | ||||
2809 | be used with care. In particular, avoid changing the attributes of | ||||
2810 | a database handle created via connect_cached() because it will affect | ||||
2811 | other code that may be using the same handle. When connect_cached() | ||||
2812 | returns a handle the attributes will be reset to their initial values. | ||||
2813 | This can cause problems, especially with the C<AutoCommit> attribute. | ||||
2814 | |||||
2815 | Also, to ensure that the attributes passed are always the same, avoid passing | ||||
2816 | references inline. For example, the C<Callbacks> attribute is specified as a | ||||
2817 | hash reference. Be sure to declare it external to the call to | ||||
2818 | connect_cached(), such that the hash reference is not re-created on every | ||||
2819 | call. A package-level lexical works well: | ||||
2820 | |||||
2821 | package MyDBH; | ||||
2822 | my $cb = { | ||||
2823 | 'connect_cached.reused' => sub { delete $_[4]->{AutoCommit} }, | ||||
2824 | }; | ||||
2825 | |||||
2826 | sub dbh { | ||||
2827 | DBI->connect_cached( $dsn, $username, $auth, { Callbacks => $cb }); | ||||
2828 | } | ||||
2829 | |||||
2830 | Where multiple separate parts of a program are using connect_cached() | ||||
2831 | to connect to the same database with the same (initial) attributes | ||||
2832 | it is a good idea to add a private attribute to the connect_cached() | ||||
2833 | call to effectively limit the scope of the caching. For example: | ||||
2834 | |||||
2835 | DBI->connect_cached(..., { private_foo_cachekey => "Bar", ... }); | ||||
2836 | |||||
2837 | Handles returned from that connect_cached() call will only be returned | ||||
2838 | by other connect_cached() call elsewhere in the code if those other | ||||
2839 | calls also pass in the same attribute values, including the private one. | ||||
2840 | (I've used C<private_foo_cachekey> here as an example, you can use | ||||
2841 | any attribute name with a C<private_> prefix.) | ||||
2842 | |||||
2843 | Taking that one step further, you can limit a particular connect_cached() | ||||
2844 | call to return handles unique to that one place in the code by setting the | ||||
2845 | private attribute to a unique value for that place: | ||||
2846 | |||||
2847 | DBI->connect_cached(..., { private_foo_cachekey => __FILE__.__LINE__, ... }); | ||||
2848 | |||||
2849 | By using a private attribute you still get connection caching for | ||||
2850 | the individual calls to connect_cached() but, by making separate | ||||
2851 | database connections for separate parts of the code, the database | ||||
2852 | handles are isolated from any attribute changes made to other handles. | ||||
2853 | |||||
2854 | The cache can be accessed (and cleared) via the L</CachedKids> attribute: | ||||
2855 | |||||
2856 | my $CachedKids_hashref = $dbh->{Driver}->{CachedKids}; | ||||
2857 | %$CachedKids_hashref = () if $CachedKids_hashref; | ||||
2858 | |||||
2859 | |||||
2860 | =head3 C<available_drivers> | ||||
2861 | |||||
2862 | @ary = DBI->available_drivers; | ||||
2863 | @ary = DBI->available_drivers($quiet); | ||||
2864 | |||||
2865 | Returns a list of all available drivers by searching for C<DBD::*> modules | ||||
2866 | through the directories in C<@INC>. By default, a warning is given if | ||||
2867 | some drivers are hidden by others of the same name in earlier | ||||
2868 | directories. Passing a true value for C<$quiet> will inhibit the warning. | ||||
2869 | |||||
2870 | =head3 C<installed_drivers> | ||||
2871 | |||||
2872 | %drivers = DBI->installed_drivers(); | ||||
2873 | |||||
2874 | Returns a list of driver name and driver handle pairs for all drivers | ||||
2875 | 'installed' (loaded) into the current process. The driver name does not | ||||
2876 | include the 'DBD::' prefix. | ||||
2877 | |||||
2878 | To get a list of all drivers available in your perl installation you can use | ||||
2879 | L</available_drivers>. | ||||
2880 | |||||
2881 | Added in DBI 1.49. | ||||
2882 | |||||
2883 | =head3 C<installed_versions> | ||||
2884 | |||||
2885 | DBI->installed_versions; | ||||
2886 | @ary = DBI->installed_versions; | ||||
2887 | $hash = DBI->installed_versions; | ||||
2888 | |||||
2889 | Calls available_drivers() and attempts to load each of them in turn | ||||
2890 | using install_driver(). For each load that succeeds the driver | ||||
2891 | name and version number are added to a hash. When running under | ||||
2892 | L<DBI::PurePerl> drivers which appear not be pure-perl are ignored. | ||||
2893 | |||||
2894 | When called in array context the list of successfully loaded drivers | ||||
2895 | is returned (without the 'DBD::' prefix). | ||||
2896 | |||||
2897 | When called in scalar context an extra entry for the C<DBI> is added (and | ||||
2898 | C<DBI::PurePerl> if appropriate) and a reference to the hash is returned. | ||||
2899 | |||||
2900 | When called in a void context the installed_versions() method will | ||||
2901 | print out a formatted list of the hash contents, one per line, along with some | ||||
2902 | other information about the DBI version and OS. | ||||
2903 | |||||
2904 | Due to the potentially high memory cost and unknown risks of loading | ||||
2905 | in an unknown number of drivers that just happen to be installed | ||||
2906 | on the system, this method is not recommended for general use. | ||||
2907 | Use available_drivers() instead. | ||||
2908 | |||||
2909 | The installed_versions() method is primarily intended as a quick | ||||
2910 | way to see from the command line what's installed. For example: | ||||
2911 | |||||
2912 | perl -MDBI -e 'DBI->installed_versions' | ||||
2913 | |||||
2914 | The installed_versions() method was added in DBI 1.38. | ||||
2915 | |||||
2916 | =head3 C<data_sources> | ||||
2917 | |||||
2918 | @ary = DBI->data_sources($driver); | ||||
2919 | @ary = DBI->data_sources($driver, \%attr); | ||||
2920 | |||||
2921 | Returns a list of data sources (databases) available via the named | ||||
2922 | driver. If C<$driver> is empty or C<undef>, then the value of the | ||||
2923 | C<DBI_DRIVER> environment variable is used. | ||||
2924 | |||||
2925 | The driver will be loaded if it hasn't been already. Note that if the | ||||
2926 | driver loading fails then data_sources() I<dies> with an error message | ||||
2927 | that includes the string "C<install_driver>" and the underlying problem. | ||||
2928 | |||||
2929 | Data sources are returned in a form suitable for passing to the | ||||
2930 | L</connect> method (that is, they will include the "C<dbi:$driver:>" prefix). | ||||
2931 | |||||
2932 | Note that many drivers have no way of knowing what data sources might | ||||
2933 | be available for it. These drivers return an empty or incomplete list | ||||
2934 | or may require driver-specific attributes. | ||||
2935 | |||||
2936 | There is also a data_sources() method defined for database handles. | ||||
2937 | |||||
2938 | |||||
2939 | =head3 C<trace> | ||||
2940 | |||||
2941 | DBI->trace($trace_setting) | ||||
2942 | DBI->trace($trace_setting, $trace_filename) | ||||
2943 | DBI->trace($trace_setting, $trace_filehandle) | ||||
2944 | $trace_setting = DBI->trace; | ||||
2945 | |||||
2946 | The C<DBI-E<gt>trace> method sets the I<global default> trace | ||||
2947 | settings and returns the I<previous> trace settings. It can also | ||||
2948 | be used to change where the trace output is sent. | ||||
2949 | |||||
2950 | There's a similar method, C<$h-E<gt>trace>, which sets the trace | ||||
2951 | settings for the specific handle it's called on. | ||||
2952 | |||||
2953 | See the L</TRACING> section for full details about the DBI's powerful | ||||
2954 | tracing facilities. | ||||
2955 | |||||
2956 | |||||
2957 | =head3 C<visit_handles> | ||||
2958 | |||||
2959 | DBI->visit_handles( $coderef ); | ||||
2960 | DBI->visit_handles( $coderef, $info ); | ||||
2961 | |||||
2962 | Where $coderef is a reference to a subroutine and $info is an arbitrary value | ||||
2963 | which, if undefined, defaults to a reference to an empty hash. Returns $info. | ||||
2964 | |||||
2965 | For each installed driver handle, if any, $coderef is invoked as: | ||||
2966 | |||||
2967 | $coderef->($driver_handle, $info); | ||||
2968 | |||||
2969 | If the execution of $coderef returns a true value then L</visit_child_handles> | ||||
2970 | is called on that child handle and passed the returned value as $info. | ||||
2971 | |||||
2972 | For example: | ||||
2973 | |||||
2974 | my $info = $dbh->{Driver}->visit_child_handles(sub { | ||||
2975 | my ($h, $info) = @_; | ||||
2976 | ++$info->{ $h->{Type} }; # count types of handles (dr/db/st) | ||||
2977 | return $info; # visit kids | ||||
2978 | }); | ||||
2979 | |||||
2980 | See also L</visit_child_handles>. | ||||
2981 | |||||
2982 | =head2 DBI Utility Functions | ||||
2983 | |||||
2984 | In addition to the DBI methods listed in the previous section, | ||||
2985 | the DBI package also provides several utility functions. | ||||
2986 | |||||
2987 | These can be imported into your code by listing them in | ||||
2988 | the C<use> statement. For example: | ||||
2989 | |||||
2990 | use DBI qw(neat data_diff); | ||||
2991 | |||||
2992 | Alternatively, all these utility functions (except hash) can be | ||||
2993 | imported using the C<:utils> import tag. For example: | ||||
2994 | |||||
2995 | use DBI qw(:utils); | ||||
2996 | |||||
2997 | =head3 C<data_string_desc> | ||||
2998 | |||||
2999 | $description = data_string_desc($string); | ||||
3000 | |||||
3001 | Returns an informal description of the string. For example: | ||||
3002 | |||||
3003 | UTF8 off, ASCII, 42 characters 42 bytes | ||||
3004 | UTF8 off, non-ASCII, 42 characters 42 bytes | ||||
3005 | UTF8 on, non-ASCII, 4 characters 6 bytes | ||||
3006 | UTF8 on but INVALID encoding, non-ASCII, 4 characters 6 bytes | ||||
3007 | UTF8 off, undef | ||||
3008 | |||||
3009 | The initial C<UTF8> on/off refers to Perl's internal SvUTF8 flag. | ||||
3010 | If $string has the SvUTF8 flag set but the sequence of bytes it | ||||
3011 | contains are not a valid UTF-8 encoding then data_string_desc() | ||||
3012 | will report C<UTF8 on but INVALID encoding>. | ||||
3013 | |||||
3014 | The C<ASCII> vs C<non-ASCII> portion shows C<ASCII> if I<all> the | ||||
3015 | characters in the string are ASCII (have code points <= 127). | ||||
3016 | |||||
3017 | The data_string_desc() function was added in DBI 1.46. | ||||
3018 | |||||
3019 | =head3 C<data_string_diff> | ||||
3020 | |||||
3021 | $diff = data_string_diff($a, $b); | ||||
3022 | |||||
3023 | Returns an informal description of the first character difference | ||||
3024 | between the strings. If both $a and $b contain the same sequence | ||||
3025 | of characters then data_string_diff() returns an empty string. | ||||
3026 | For example: | ||||
3027 | |||||
3028 | Params a & b Result | ||||
3029 | ------------ ------ | ||||
3030 | 'aaa', 'aaa' '' | ||||
3031 | 'aaa', 'abc' 'Strings differ at index 2: a[2]=a, b[2]=b' | ||||
3032 | 'aaa', undef 'String b is undef, string a has 3 characters' | ||||
3033 | 'aaa', 'aa' 'String b truncated after 2 characters' | ||||
3034 | |||||
3035 | Unicode characters are reported in C<\x{XXXX}> format. Unicode | ||||
3036 | code points in the range U+0800 to U+08FF are unassigned and most | ||||
3037 | likely to occur due to double-encoding. Characters in this range | ||||
3038 | are reported as C<\x{08XX}='C'> where C<C> is the corresponding | ||||
3039 | latin-1 character. | ||||
3040 | |||||
3041 | The data_string_diff() function only considers logical I<characters> | ||||
3042 | and not the underlying encoding. See L</data_diff> for an alternative. | ||||
3043 | |||||
3044 | The data_string_diff() function was added in DBI 1.46. | ||||
3045 | |||||
3046 | =head3 C<data_diff> | ||||
3047 | |||||
3048 | $diff = data_diff($a, $b); | ||||
3049 | $diff = data_diff($a, $b, $logical); | ||||
3050 | |||||
3051 | Returns an informal description of the difference between two strings. | ||||
3052 | It calls L</data_string_desc> and L</data_string_diff> | ||||
3053 | and returns the combined results as a multi-line string. | ||||
3054 | |||||
3055 | For example, C<data_diff("abc", "ab\x{263a}")> will return: | ||||
3056 | |||||
3057 | a: UTF8 off, ASCII, 3 characters 3 bytes | ||||
3058 | b: UTF8 on, non-ASCII, 3 characters 5 bytes | ||||
3059 | Strings differ at index 2: a[2]=c, b[2]=\x{263A} | ||||
3060 | |||||
3061 | If $a and $b are identical in both the characters they contain I<and> | ||||
3062 | their physical encoding then data_diff() returns an empty string. | ||||
3063 | If $logical is true then physical encoding differences are ignored | ||||
3064 | (but are still reported if there is a difference in the characters). | ||||
3065 | |||||
3066 | The data_diff() function was added in DBI 1.46. | ||||
3067 | |||||
3068 | =head3 C<neat> | ||||
3069 | |||||
3070 | $str = neat($value); | ||||
3071 | $str = neat($value, $maxlen); | ||||
3072 | |||||
3073 | Return a string containing a neat (and tidy) representation of the | ||||
3074 | supplied value. | ||||
3075 | |||||
3076 | Strings will be quoted, although internal quotes will I<not> be escaped. | ||||
3077 | Values known to be numeric will be unquoted. Undefined (NULL) values | ||||
3078 | will be shown as C<undef> (without quotes). | ||||
3079 | |||||
3080 | If the string is flagged internally as utf8 then double quotes will | ||||
3081 | be used, otherwise single quotes are used and unprintable characters | ||||
3082 | will be replaced by dot (.). | ||||
3083 | |||||
3084 | For result strings longer than C<$maxlen> the result string will be | ||||
3085 | truncated to C<$maxlen-4> and "C<...'>" will be appended. If C<$maxlen> is 0 | ||||
3086 | or C<undef>, it defaults to C<$DBI::neat_maxlen> which, in turn, defaults to 400. | ||||
3087 | |||||
3088 | This function is designed to format values for human consumption. | ||||
3089 | It is used internally by the DBI for L</trace> output. It should | ||||
3090 | typically I<not> be used for formatting values for database use. | ||||
3091 | (See also L</quote>.) | ||||
3092 | |||||
3093 | =head3 C<neat_list> | ||||
3094 | |||||
3095 | $str = neat_list(\@listref, $maxlen, $field_sep); | ||||
3096 | |||||
3097 | Calls C<neat> on each element of the list and returns a string | ||||
3098 | containing the results joined with C<$field_sep>. C<$field_sep> defaults | ||||
3099 | to C<", ">. | ||||
3100 | |||||
3101 | =head3 C<looks_like_number> | ||||
3102 | |||||
3103 | @bool = looks_like_number(@array); | ||||
3104 | |||||
3105 | Returns true for each element that looks like a number. | ||||
3106 | Returns false for each element that does not look like a number. | ||||
3107 | Returns C<undef> for each element that is undefined or empty. | ||||
3108 | |||||
3109 | =head3 C<hash> | ||||
3110 | |||||
3111 | $hash_value = DBI::hash($buffer, $type); | ||||
3112 | |||||
3113 | Return a 32-bit integer 'hash' value corresponding to the contents of $buffer. | ||||
3114 | The $type parameter selects which kind of hash algorithm should be used. | ||||
3115 | |||||
3116 | For the technically curious, type 0 (which is the default if $type | ||||
3117 | isn't specified) is based on the Perl 5.1 hash except that the value | ||||
3118 | is forced to be negative (for obscure historical reasons). | ||||
3119 | Type 1 is the better "Fowler / Noll / Vo" (FNV) hash. See | ||||
3120 | L<http://www.isthe.com/chongo/tech/comp/fnv/> for more information. | ||||
3121 | Both types are implemented in C and are very fast. | ||||
3122 | |||||
3123 | This function doesn't have much to do with databases, except that | ||||
3124 | it can be handy to store hash values in a database. | ||||
3125 | |||||
3126 | =head3 C<sql_type_cast> | ||||
3127 | |||||
3128 | $sts = DBI::sql_type_cast($sv, $sql_type, $flags); | ||||
3129 | |||||
3130 | sql_type_cast attempts to cast C<$sv> to the SQL type (see L<DBI | ||||
3131 | Constants>) specified in C<$sql_type>. At present only the SQL types | ||||
3132 | C<SQL_INTEGER>, C<SQL_DOUBLE> and C<SQL_NUMERIC> are supported. | ||||
3133 | |||||
3134 | For C<SQL_INTEGER> the effect is similar to using the value in an expression | ||||
3135 | that requires an integer. It gives the perl scalar an 'integer aspect'. | ||||
3136 | (Technically the value gains an IV, or possibly a UV or NV if the value is too | ||||
3137 | large for an IV.) | ||||
3138 | |||||
3139 | For C<SQL_DOUBLE> the effect is similar to using the value in an expression | ||||
3140 | that requires a general numeric value. It gives the perl scalar a 'numeric | ||||
3141 | aspect'. (Technically the value gains an NV.) | ||||
3142 | |||||
3143 | C<SQL_NUMERIC> is similar to C<SQL_INTEGER> or C<SQL_DOUBLE> but more | ||||
3144 | general and more cautious. It will look at the string first and if it | ||||
3145 | looks like an integer (that will fit in an IV or UV) it will act like | ||||
3146 | C<SQL_INTEGER>, if it looks like a floating point value it will act | ||||
3147 | like C<SQL_DOUBLE>, if it looks like neither then it will do nothing - | ||||
3148 | and thereby avoid the warnings that would be generated by | ||||
3149 | C<SQL_INTEGER> and C<SQL_DOUBLE> when given non-numeric data. | ||||
3150 | |||||
3151 | C<$flags> may be: | ||||
3152 | |||||
3153 | =over 4 | ||||
3154 | |||||
3155 | =item C<DBIstcf_DISCARD_STRING> | ||||
3156 | |||||
3157 | If this flag is specified then when the driver successfully casts the | ||||
3158 | bound perl scalar to a non-string type then the string portion of the | ||||
3159 | scalar will be discarded. | ||||
3160 | |||||
3161 | =item C<DBIstcf_STRICT> | ||||
3162 | |||||
3163 | If C<$sv> cannot be cast to the requested C<$sql_type> then by default | ||||
3164 | it is left untouched and no error is generated. If you specify | ||||
3165 | C<DBIstcf_STRICT> and the cast fails, this will generate an error. | ||||
3166 | |||||
3167 | =back | ||||
3168 | |||||
3169 | The returned C<$sts> value is: | ||||
3170 | |||||
3171 | -2 sql_type is not handled | ||||
3172 | -1 sv is undef so unchanged | ||||
3173 | 0 sv could not be cast cleanly and DBIstcf_STRICT was used | ||||
3174 | 1 sv could not be cast and DBIstcf_STRICT was not used | ||||
3175 | 2 sv was cast successfully | ||||
3176 | |||||
3177 | This method is exported by the :utils tag and was introduced in DBI | ||||
3178 | 1.611. | ||||
3179 | |||||
3180 | =head2 DBI Dynamic Attributes | ||||
3181 | |||||
3182 | Dynamic attributes are always associated with the I<last handle used> | ||||
3183 | (that handle is represented by C<$h> in the descriptions below). | ||||
3184 | |||||
3185 | Where an attribute is equivalent to a method call, then refer to | ||||
3186 | the method call for all related documentation. | ||||
3187 | |||||
3188 | Warning: these attributes are provided as a convenience but they | ||||
3189 | do have limitations. Specifically, they have a short lifespan: | ||||
3190 | because they are associated with | ||||
3191 | the last handle used, they should only be used I<immediately> after | ||||
3192 | calling the method that "sets" them. | ||||
3193 | If in any doubt, use the corresponding method call. | ||||
3194 | |||||
3195 | =head3 C<$DBI::err> | ||||
3196 | |||||
3197 | Equivalent to C<$h-E<gt>err>. | ||||
3198 | |||||
3199 | =head3 C<$DBI::errstr> | ||||
3200 | |||||
3201 | Equivalent to C<$h-E<gt>errstr>. | ||||
3202 | |||||
3203 | =head3 C<$DBI::state> | ||||
3204 | |||||
3205 | Equivalent to C<$h-E<gt>state>. | ||||
3206 | |||||
3207 | =head3 C<$DBI::rows> | ||||
3208 | |||||
3209 | Equivalent to C<$h-E<gt>rows>. Please refer to the documentation | ||||
3210 | for the L</rows> method. | ||||
3211 | |||||
3212 | =head3 C<$DBI::lasth> | ||||
3213 | |||||
3214 | Returns the DBI object handle used for the most recent DBI method call. | ||||
3215 | If the last DBI method call was a DESTROY then $DBI::lasth will return | ||||
3216 | the handle of the parent of the destroyed handle, if there is one. | ||||
3217 | |||||
3218 | |||||
3219 | =head1 METHODS COMMON TO ALL HANDLES | ||||
3220 | |||||
3221 | The following methods can be used by all types of DBI handles. | ||||
3222 | |||||
3223 | =head3 C<err> | ||||
3224 | |||||
3225 | $rv = $h->err; | ||||
3226 | |||||
3227 | Returns the I<native> database engine error code from the last driver | ||||
3228 | method called. The code is typically an integer but you should not | ||||
3229 | assume that. | ||||
3230 | |||||
3231 | The DBI resets $h->err to undef before almost all DBI method calls, so the | ||||
3232 | value only has a short lifespan. Also, for most drivers, the statement | ||||
3233 | handles share the same error variable as the parent database handle, | ||||
3234 | so calling a method on one handle may reset the error on the | ||||
3235 | related handles. | ||||
3236 | |||||
3237 | (Methods which don't reset err before being called include err() and errstr(), | ||||
3238 | obviously, state(), rows(), func(), trace(), trace_msg(), ping(), and the | ||||
3239 | tied hash attribute FETCH() and STORE() methods.) | ||||
3240 | |||||
3241 | If you need to test for specific error conditions I<and> have your program be | ||||
3242 | portable to different database engines, then you'll need to determine what the | ||||
3243 | corresponding error codes are for all those engines and test for all of them. | ||||
3244 | |||||
3245 | The DBI uses the value of $DBI::stderr as the C<err> value for internal errors. | ||||
3246 | Drivers should also do likewise. The default value for $DBI::stderr is 2000000000. | ||||
3247 | |||||
3248 | A driver may return C<0> from err() to indicate a warning condition | ||||
3249 | after a method call. Similarly, a driver may return an empty string | ||||
3250 | to indicate a 'success with information' condition. In both these | ||||
3251 | cases the value is false but not undef. The errstr() and state() | ||||
3252 | methods may be used to retrieve extra information in these cases. | ||||
3253 | |||||
3254 | See L</set_err> for more information. | ||||
3255 | |||||
3256 | =head3 C<errstr> | ||||
3257 | |||||
3258 | $str = $h->errstr; | ||||
3259 | |||||
3260 | Returns the native database engine error message from the last DBI | ||||
3261 | method called. This has the same lifespan issues as the L</err> method | ||||
3262 | described above. | ||||
3263 | |||||
3264 | The returned string may contain multiple messages separated by | ||||
3265 | newline characters. | ||||
3266 | |||||
3267 | The errstr() method should not be used to test for errors, use err() | ||||
3268 | for that, because drivers may return 'success with information' or | ||||
3269 | warning messages via errstr() for methods that have not 'failed'. | ||||
3270 | |||||
3271 | See L</set_err> for more information. | ||||
3272 | |||||
3273 | =head3 C<state> | ||||
3274 | |||||
3275 | $str = $h->state; | ||||
3276 | |||||
3277 | Returns a state code in the standard SQLSTATE five character format. | ||||
3278 | Note that the specific success code C<00000> is translated to any empty string | ||||
3279 | (false). If the driver does not support SQLSTATE (and most don't), | ||||
3280 | then state() will return C<S1000> (General Error) for all errors. | ||||
3281 | |||||
3282 | The driver is free to return any value via C<state>, e.g., warning | ||||
3283 | codes, even if it has not declared an error by returning a true value | ||||
3284 | via the L</err> method described above. | ||||
3285 | |||||
3286 | The state() method should not be used to test for errors, use err() | ||||
3287 | for that, because drivers may return a 'success with information' or | ||||
3288 | warning state code via state() for methods that have not 'failed'. | ||||
3289 | |||||
3290 | =head3 C<set_err> | ||||
3291 | |||||
3292 | $rv = $h->set_err($err, $errstr); | ||||
3293 | $rv = $h->set_err($err, $errstr, $state); | ||||
3294 | $rv = $h->set_err($err, $errstr, $state, $method); | ||||
3295 | $rv = $h->set_err($err, $errstr, $state, $method, $rv); | ||||
3296 | |||||
3297 | Set the C<err>, C<errstr>, and C<state> values for the handle. | ||||
3298 | This method is typically only used by DBI drivers and DBI subclasses. | ||||
3299 | |||||
3300 | If the L</HandleSetErr> attribute holds a reference to a subroutine | ||||
3301 | it is called first. The subroutine can alter the $err, $errstr, $state, | ||||
3302 | and $method values. See L</HandleSetErr> for full details. | ||||
3303 | If the subroutine returns a true value then the handle C<err>, | ||||
3304 | C<errstr>, and C<state> values are not altered and set_err() returns | ||||
3305 | an empty list (it normally returns $rv which defaults to undef, see below). | ||||
3306 | |||||
3307 | Setting C<err> to a I<true> value indicates an error and will trigger | ||||
3308 | the normal DBI error handling mechanisms, such as C<RaiseError> and | ||||
3309 | C<HandleError>, if they are enabled, when execution returns from | ||||
3310 | the DBI back to the application. | ||||
3311 | |||||
3312 | Setting C<err> to C<""> indicates an 'information' state, and setting | ||||
3313 | it to C<"0"> indicates a 'warning' state. Setting C<err> to C<undef> | ||||
3314 | also sets C<errstr> to undef, and C<state> to C<"">, irrespective | ||||
3315 | of the values of the $errstr and $state parameters. | ||||
3316 | |||||
3317 | The $method parameter provides an alternate method name for the | ||||
3318 | C<RaiseError>/C<PrintError>/C<PrintWarn> error string instead of | ||||
3319 | the fairly unhelpful 'C<set_err>'. | ||||
3320 | |||||
3321 | The C<set_err> method normally returns undef. The $rv parameter | ||||
3322 | provides an alternate return value. | ||||
3323 | |||||
3324 | Some special rules apply if the C<err> or C<errstr> | ||||
3325 | values for the handle are I<already> set... | ||||
3326 | |||||
3327 | If C<errstr> is true then: "C< [err was %s now %s]>" is appended if $err is | ||||
3328 | true and C<err> is already true and the new err value differs from the original | ||||
3329 | one. Similarly "C< [state was %s now %s]>" is appended if $state is true and C<state> is | ||||
3330 | already true and the new state value differs from the original one. Finally | ||||
3331 | "C<\n>" and the new $errstr are appended if $errstr differs from the existing | ||||
3332 | errstr value. Obviously the C<%s>'s above are replaced by the corresponding values. | ||||
3333 | |||||
3334 | The handle C<err> value is set to $err if: $err is true; or handle | ||||
3335 | C<err> value is undef; or $err is defined and the length is greater | ||||
3336 | than the handle C<err> length. The effect is that an 'information' | ||||
3337 | state only overrides undef; a 'warning' overrides undef or 'information', | ||||
3338 | and an 'error' state overrides anything. | ||||
3339 | |||||
3340 | The handle C<state> value is set to $state if $state is true and | ||||
3341 | the handle C<err> value was set (by the rules above). | ||||
3342 | |||||
3343 | Support for warning and information states was added in DBI 1.41. | ||||
3344 | |||||
3345 | =head3 C<trace> | ||||
3346 | |||||
3347 | $h->trace($trace_settings); | ||||
3348 | $h->trace($trace_settings, $trace_filename); | ||||
3349 | $trace_settings = $h->trace; | ||||
3350 | |||||
3351 | The trace() method is used to alter the trace settings for a handle | ||||
3352 | (and any future children of that handle). It can also be used to | ||||
3353 | change where the trace output is sent. | ||||
3354 | |||||
3355 | There's a similar method, C<DBI-E<gt>trace>, which sets the global | ||||
3356 | default trace settings. | ||||
3357 | |||||
3358 | See the L</TRACING> section for full details about the DBI's powerful | ||||
3359 | tracing facilities. | ||||
3360 | |||||
3361 | =head3 C<trace_msg> | ||||
3362 | |||||
3363 | $h->trace_msg($message_text); | ||||
3364 | $h->trace_msg($message_text, $min_level); | ||||
3365 | |||||
3366 | Writes C<$message_text> to the trace file if the trace level is | ||||
3367 | greater than or equal to $min_level (which defaults to 1). | ||||
3368 | Can also be called as C<DBI-E<gt>trace_msg($msg)>. | ||||
3369 | |||||
3370 | See L</TRACING> for more details. | ||||
3371 | |||||
3372 | =head3 C<func> | ||||
3373 | |||||
3374 | $h->func(@func_arguments, $func_name) or die ...; | ||||
3375 | |||||
3376 | The C<func> method can be used to call private non-standard and | ||||
3377 | non-portable methods implemented by the driver. Note that the function | ||||
3378 | name is given as the I<last> argument. | ||||
3379 | |||||
3380 | It's also important to note that the func() method does not clear | ||||
3381 | a previous error ($DBI::err etc.) and it does not trigger automatic | ||||
3382 | error detection (RaiseError etc.) so you must check the return | ||||
3383 | status and/or $h->err to detect errors. | ||||
3384 | |||||
3385 | (This method is not directly related to calling stored procedures. | ||||
3386 | Calling stored procedures is currently not defined by the DBI. | ||||
3387 | Some drivers, such as DBD::Oracle, support it in non-portable ways. | ||||
3388 | See driver documentation for more details.) | ||||
3389 | |||||
3390 | See also install_method() in L<DBI::DBD> for how you can avoid needing to | ||||
3391 | use func() and gain direct access to driver-private methods. | ||||
3392 | |||||
3393 | =head3 C<can> | ||||
3394 | |||||
3395 | $is_implemented = $h->can($method_name); | ||||
3396 | |||||
3397 | Returns true if $method_name is implemented by the driver or a | ||||
3398 | default method is provided by the DBI's driver base class. | ||||
3399 | It returns false where a driver hasn't implemented a method and the | ||||
3400 | default method is provided by the DBI's driver base class is just an empty stub. | ||||
3401 | |||||
3402 | =head3 C<parse_trace_flags> | ||||
3403 | |||||
3404 | $trace_settings_integer = $h->parse_trace_flags($trace_settings); | ||||
3405 | |||||
3406 | Parses a string containing trace settings and returns the corresponding | ||||
3407 | integer value used internally by the DBI and drivers. | ||||
3408 | |||||
3409 | The $trace_settings argument is a string containing a trace level | ||||
3410 | between 0 and 15 and/or trace flag names separated by vertical bar | ||||
3411 | ("C<|>") or comma ("C<,>") characters. For example: C<"SQL|3|foo">. | ||||
3412 | |||||
3413 | It uses the parse_trace_flag() method, described below, to process | ||||
3414 | the individual trace flag names. | ||||
3415 | |||||
3416 | The parse_trace_flags() method was added in DBI 1.42. | ||||
3417 | |||||
3418 | =head3 C<parse_trace_flag> | ||||
3419 | |||||
3420 | $bit_flag = $h->parse_trace_flag($trace_flag_name); | ||||
3421 | |||||
3422 | Returns the bit flag corresponding to the trace flag name in | ||||
3423 | $trace_flag_name. Drivers are expected to override this method and | ||||
3424 | check if $trace_flag_name is a driver specific trace flags and, if | ||||
3425 | not, then call the DBI's default parse_trace_flag(). | ||||
3426 | |||||
3427 | The parse_trace_flag() method was added in DBI 1.42. | ||||
3428 | |||||
3429 | =head3 C<private_attribute_info> | ||||
3430 | |||||
3431 | $hash_ref = $h->private_attribute_info(); | ||||
3432 | |||||
3433 | Returns a reference to a hash whose keys are the names of driver-private | ||||
3434 | handle attributes available for the kind of handle (driver, database, statement) | ||||
3435 | that the method was called on. | ||||
3436 | |||||
3437 | For example, the return value when called with a DBD::Sybase $dbh could look like this: | ||||
3438 | |||||
3439 | { | ||||
3440 | syb_dynamic_supported => undef, | ||||
3441 | syb_oc_version => undef, | ||||
3442 | syb_server_version => undef, | ||||
3443 | syb_server_version_string => undef, | ||||
3444 | } | ||||
3445 | |||||
3446 | and when called with a DBD::Sybase $sth they could look like this: | ||||
3447 | |||||
3448 | { | ||||
3449 | syb_types => undef, | ||||
3450 | syb_proc_status => undef, | ||||
3451 | syb_result_type => undef, | ||||
3452 | } | ||||
3453 | |||||
3454 | The values should be undef. Meanings may be assigned to particular values in future. | ||||
3455 | |||||
3456 | =head3 C<swap_inner_handle> | ||||
3457 | |||||
3458 | $rc = $h1->swap_inner_handle( $h2 ); | ||||
3459 | $rc = $h1->swap_inner_handle( $h2, $allow_reparent ); | ||||
3460 | |||||
3461 | Brain transplants for handles. You don't need to know about this | ||||
3462 | unless you want to become a handle surgeon. | ||||
3463 | |||||
3464 | A DBI handle is a reference to a tied hash. A tied hash has an | ||||
3465 | I<inner> hash that actually holds the contents. The swap_inner_handle() | ||||
3466 | method swaps the inner hashes between two handles. The $h1 and $h2 | ||||
3467 | handles still point to the same tied hashes, but what those hashes | ||||
3468 | are tied to has been swapped. In effect $h1 I<becomes> $h2 and | ||||
3469 | vice-versa. This is powerful stuff, expect problems. Use with care. | ||||
3470 | |||||
3471 | As a small safety measure, the two handles, $h1 and $h2, have to | ||||
3472 | share the same parent unless $allow_reparent is true. | ||||
3473 | |||||
3474 | The swap_inner_handle() method was added in DBI 1.44. | ||||
3475 | |||||
3476 | Here's a quick kind of 'diagram' as a worked example to help think about what's | ||||
3477 | happening: | ||||
3478 | |||||
3479 | Original state: | ||||
3480 | dbh1o -> dbh1i | ||||
3481 | sthAo -> sthAi(dbh1i) | ||||
3482 | dbh2o -> dbh2i | ||||
3483 | |||||
3484 | swap_inner_handle dbh1o with dbh2o: | ||||
3485 | dbh2o -> dbh1i | ||||
3486 | sthAo -> sthAi(dbh1i) | ||||
3487 | dbh1o -> dbh2i | ||||
3488 | |||||
3489 | create new sth from dbh1o: | ||||
3490 | dbh2o -> dbh1i | ||||
3491 | sthAo -> sthAi(dbh1i) | ||||
3492 | dbh1o -> dbh2i | ||||
3493 | sthBo -> sthBi(dbh2i) | ||||
3494 | |||||
3495 | swap_inner_handle sthAo with sthBo: | ||||
3496 | dbh2o -> dbh1i | ||||
3497 | sthBo -> sthAi(dbh1i) | ||||
3498 | dbh1o -> dbh2i | ||||
3499 | sthAo -> sthBi(dbh2i) | ||||
3500 | |||||
3501 | =head3 C<visit_child_handles> | ||||
3502 | |||||
3503 | $h->visit_child_handles( $coderef ); | ||||
3504 | $h->visit_child_handles( $coderef, $info ); | ||||
3505 | |||||
3506 | Where $coderef is a reference to a subroutine and $info is an arbitrary value | ||||
3507 | which, if undefined, defaults to a reference to an empty hash. Returns $info. | ||||
3508 | |||||
3509 | For each child handle of $h, if any, $coderef is invoked as: | ||||
3510 | |||||
3511 | $coderef->($child_handle, $info); | ||||
3512 | |||||
3513 | If the execution of $coderef returns a true value then C<visit_child_handles> | ||||
3514 | is called on that child handle and passed the returned value as $info. | ||||
3515 | |||||
3516 | For example: | ||||
3517 | |||||
3518 | # count database connections with names (DSN) matching a pattern | ||||
3519 | my $connections = 0; | ||||
3520 | $dbh->{Driver}->visit_child_handles(sub { | ||||
3521 | my ($h, $info) = @_; | ||||
3522 | ++$connections if $h->{Name} =~ /foo/; | ||||
3523 | return 0; # don't visit kids | ||||
3524 | }) | ||||
3525 | |||||
3526 | See also L</visit_handles>. | ||||
3527 | |||||
3528 | =head1 ATTRIBUTES COMMON TO ALL HANDLES | ||||
3529 | |||||
3530 | These attributes are common to all types of DBI handles. | ||||
3531 | |||||
3532 | Some attributes are inherited by child handles. That is, the value | ||||
3533 | of an inherited attribute in a newly created statement handle is the | ||||
3534 | same as the value in the parent database handle. Changes to attributes | ||||
3535 | in the new statement handle do not affect the parent database handle | ||||
3536 | and changes to the database handle do not affect existing statement | ||||
3537 | handles, only future ones. | ||||
3538 | |||||
3539 | Attempting to set or get the value of an unknown attribute generates a warning, | ||||
3540 | except for private driver specific attributes (which all have names | ||||
3541 | starting with a lowercase letter). | ||||
3542 | |||||
3543 | Example: | ||||
3544 | |||||
3545 | $h->{AttributeName} = ...; # set/write | ||||
3546 | ... = $h->{AttributeName}; # get/read | ||||
3547 | |||||
3548 | =head3 C<Warn> | ||||
3549 | |||||
3550 | Type: boolean, inherited | ||||
3551 | |||||
3552 | The C<Warn> attribute enables useful warnings for certain bad | ||||
3553 | practices. It is enabled by default and should only be disabled in | ||||
3554 | rare circumstances. Since warnings are generated using the Perl | ||||
3555 | C<warn> function, they can be intercepted using the Perl C<$SIG{__WARN__}> | ||||
3556 | hook. | ||||
3557 | |||||
3558 | The C<Warn> attribute is not related to the C<PrintWarn> attribute. | ||||
3559 | |||||
3560 | =head3 C<Active> | ||||
3561 | |||||
3562 | Type: boolean, read-only | ||||
3563 | |||||
3564 | The C<Active> attribute is true if the handle object is "active". This is rarely used in | ||||
3565 | applications. The exact meaning of active is somewhat vague at the | ||||
3566 | moment. For a database handle it typically means that the handle is | ||||
3567 | connected to a database (C<$dbh-E<gt>disconnect> sets C<Active> off). For | ||||
3568 | a statement handle it typically means that the handle is a C<SELECT> | ||||
3569 | that may have more data to fetch. (Fetching all the data or calling C<$sth-E<gt>finish> | ||||
3570 | sets C<Active> off.) | ||||
3571 | |||||
3572 | =head3 C<Executed> | ||||
3573 | |||||
3574 | Type: boolean | ||||
3575 | |||||
3576 | The C<Executed> attribute is true if the handle object has been "executed". | ||||
3577 | Currently only the $dbh do() method and the $sth execute(), execute_array(), | ||||
3578 | and execute_for_fetch() methods set the C<Executed> attribute. | ||||
3579 | |||||
3580 | When it's set on a handle it is also set on the parent handle at the | ||||
3581 | same time. So calling execute() on a $sth also sets the C<Executed> | ||||
3582 | attribute on the parent $dbh. | ||||
3583 | |||||
3584 | The C<Executed> attribute for a database handle is cleared by the commit() and | ||||
3585 | rollback() methods (even if they fail). The C<Executed> attribute of a | ||||
3586 | statement handle is not cleared by the DBI under any circumstances and so acts | ||||
3587 | as a permanent record of whether the statement handle was ever used. | ||||
3588 | |||||
3589 | The C<Executed> attribute was added in DBI 1.41. | ||||
3590 | |||||
3591 | =head3 C<Kids> | ||||
3592 | |||||
3593 | Type: integer, read-only | ||||
3594 | |||||
3595 | For a driver handle, C<Kids> is the number of currently existing database | ||||
3596 | handles that were created from that driver handle. For a database | ||||
3597 | handle, C<Kids> is the number of currently existing statement handles that | ||||
3598 | were created from that database handle. | ||||
3599 | For a statement handle, the value is zero. | ||||
3600 | |||||
3601 | =head3 C<ActiveKids> | ||||
3602 | |||||
3603 | Type: integer, read-only | ||||
3604 | |||||
3605 | Like C<Kids>, but only counting those that are C<Active> (as above). | ||||
3606 | |||||
3607 | =head3 C<CachedKids> | ||||
3608 | |||||
3609 | Type: hash ref | ||||
3610 | |||||
3611 | For a database handle, C<CachedKids> returns a reference to the cache (hash) of | ||||
3612 | statement handles created by the L</prepare_cached> method. For a | ||||
3613 | driver handle, returns a reference to the cache (hash) of | ||||
3614 | database handles created by the L</connect_cached> method. | ||||
3615 | |||||
3616 | =head3 C<Type> | ||||
3617 | |||||
3618 | Type: scalar, read-only | ||||
3619 | |||||
3620 | The C<Type> attribute identifies the type of a DBI handle. Returns | ||||
3621 | "dr" for driver handles, "db" for database handles and "st" for | ||||
3622 | statement handles. | ||||
3623 | |||||
3624 | =head3 C<ChildHandles> | ||||
3625 | |||||
3626 | Type: array ref | ||||
3627 | |||||
3628 | The ChildHandles attribute contains a reference to an array of all the | ||||
3629 | handles created by this handle which are still accessible. The | ||||
3630 | contents of the array are weak-refs and will become undef when the | ||||
3631 | handle goes out of scope. | ||||
3632 | |||||
3633 | C<ChildHandles> returns undef if your perl version does not support weak | ||||
3634 | references (check the L<Scalar::Util|Scalar::Util> module). The referenced | ||||
3635 | array returned should be treated as read-only. | ||||
3636 | |||||
3637 | For example, to enumerate all driver handles, database handles and | ||||
3638 | statement handles: | ||||
3639 | |||||
3640 | sub show_child_handles { | ||||
3641 | my ($h, $level) = @_; | ||||
3642 | printf "%sh %s %s\n", $h->{Type}, "\t" x $level, $h; | ||||
3643 | show_child_handles($_, $level + 1) | ||||
3644 | for (grep { defined } @{$h->{ChildHandles}}); | ||||
3645 | } | ||||
3646 | |||||
3647 | my %drivers = DBI->installed_drivers(); | ||||
3648 | show_child_handles($_, 0) for (values %drivers); | ||||
3649 | |||||
3650 | =head3 C<CompatMode> | ||||
3651 | |||||
3652 | Type: boolean, inherited | ||||
3653 | |||||
3654 | The C<CompatMode> attribute is used by emulation layers (such as | ||||
3655 | Oraperl) to enable compatible behaviour in the underlying driver | ||||
3656 | (e.g., DBD::Oracle) for this handle. Not normally set by application code. | ||||
3657 | |||||
3658 | It also has the effect of disabling the 'quick FETCH' of attribute | ||||
3659 | values from the handles attribute cache. So all attribute values | ||||
3660 | are handled by the drivers own FETCH method. This makes them slightly | ||||
3661 | slower but is useful for special-purpose drivers like DBD::Multiplex. | ||||
3662 | |||||
3663 | =head3 C<InactiveDestroy> | ||||
3664 | |||||
3665 | Type: boolean | ||||
3666 | |||||
3667 | The default value, false, means a handle will be fully destroyed | ||||
3668 | as normal when the last reference to it is removed, just as you'd expect. | ||||
3669 | |||||
3670 | If set true then the handle will be treated by the DESTROY as if it was no | ||||
3671 | longer Active, and so the I<database engine> related effects of DESTROYing a | ||||
3672 | handle will be skipped. Think of the name as meaning 'treat the handle as | ||||
3673 | not-Active in the DESTROY method'. | ||||
3674 | |||||
3675 | For a database handle, this attribute does not disable an I<explicit> | ||||
3676 | call to the disconnect method, only the implicit call from DESTROY | ||||
3677 | that happens if the handle is still marked as C<Active>. | ||||
3678 | |||||
3679 | This attribute is specifically designed for use in Unix applications | ||||
3680 | that "fork" child processes. For some drivers, when the child process exits | ||||
3681 | the destruction of inherited handles cause the corresponding handles in the | ||||
3682 | parent process to cease working. | ||||
3683 | |||||
3684 | Either the parent or the child process, but not both, should set | ||||
3685 | C<InactiveDestroy> true on all their shared handles. Alternatively the | ||||
3686 | L</AutoInactiveDestroy> can be set in the parent on connect. | ||||
3687 | |||||
3688 | To help tracing applications using fork the process id is shown in | ||||
3689 | the trace log whenever a DBI or handle trace() method is called. | ||||
3690 | The process id also shown for I<every> method call if the DBI trace | ||||
3691 | level (not handle trace level) is set high enough to show the trace | ||||
3692 | from the DBI's method dispatcher, e.g. >= 9. | ||||
3693 | |||||
3694 | =head3 C<AutoInactiveDestroy> | ||||
3695 | |||||
3696 | Type: boolean, inherited | ||||
3697 | |||||
3698 | The L</InactiveDestroy> attribute, described above, needs to be explicitly set | ||||
3699 | in the child process after a fork(). This is a problem if the code that performs | ||||
3700 | the fork() is not under your control, perhaps in a third-party module. | ||||
3701 | Use C<AutoInactiveDestroy> to get around this situation. | ||||
3702 | |||||
3703 | If set true, the DESTROY method will check the process id of the handle and, if | ||||
3704 | different from the current process id, it will set the I<InactiveDestroy> attribute. | ||||
3705 | |||||
3706 | This is the example it's designed to deal with: | ||||
3707 | |||||
3708 | my $dbh = DBI->connect(...); | ||||
3709 | some_code_that_forks(); # Perhaps without your knowledge | ||||
3710 | # Child process dies, destroying the inherited dbh | ||||
3711 | $dbh->do(...); # Breaks because parent $dbh is now broken | ||||
3712 | |||||
3713 | The C<AutoInactiveDestroy> attribute was added in DBI 1.614. | ||||
3714 | |||||
3715 | =head3 C<PrintWarn> | ||||
3716 | |||||
3717 | Type: boolean, inherited | ||||
3718 | |||||
3719 | The C<PrintWarn> attribute controls the printing of warnings recorded | ||||
3720 | by the driver. When set to a true value (the default) the DBI will check method | ||||
3721 | calls to see if a warning condition has been set. If so, the DBI | ||||
3722 | will effectively do a C<warn("$class $method warning: $DBI::errstr")> | ||||
3723 | where C<$class> is the driver class and C<$method> is the name of | ||||
3724 | the method which failed. E.g., | ||||
3725 | |||||
3726 | DBD::Oracle::db execute warning: ... warning text here ... | ||||
3727 | |||||
3728 | If desired, the warnings can be caught and processed using a C<$SIG{__WARN__}> | ||||
3729 | handler or modules like CGI::Carp and CGI::ErrorWrap. | ||||
3730 | |||||
3731 | See also L</set_err> for how warnings are recorded and L</HandleSetErr> | ||||
3732 | for how to influence it. | ||||
3733 | |||||
3734 | Fetching the full details of warnings can require an extra round-trip | ||||
3735 | to the database server for some drivers. In which case the driver | ||||
3736 | may opt to only fetch the full details of warnings if the C<PrintWarn> | ||||
3737 | attribute is true. If C<PrintWarn> is false then these drivers should | ||||
3738 | still indicate the fact that there were warnings by setting the | ||||
3739 | warning string to, for example: "3 warnings". | ||||
3740 | |||||
3741 | =head3 C<PrintError> | ||||
3742 | |||||
3743 | Type: boolean, inherited | ||||
3744 | |||||
3745 | The C<PrintError> attribute can be used to force errors to generate warnings (using | ||||
3746 | C<warn>) in addition to returning error codes in the normal way. When set | ||||
3747 | "on", any method which results in an error occurring will cause the DBI to | ||||
3748 | effectively do a C<warn("$class $method failed: $DBI::errstr")> where C<$class> | ||||
3749 | is the driver class and C<$method> is the name of the method which failed. E.g., | ||||
3750 | |||||
3751 | DBD::Oracle::db prepare failed: ... error text here ... | ||||
3752 | |||||
3753 | By default, C<DBI-E<gt>connect> sets C<PrintError> "on". | ||||
3754 | |||||
3755 | If desired, the warnings can be caught and processed using a C<$SIG{__WARN__}> | ||||
3756 | handler or modules like CGI::Carp and CGI::ErrorWrap. | ||||
3757 | |||||
3758 | =head3 C<RaiseError> | ||||
3759 | |||||
3760 | Type: boolean, inherited | ||||
3761 | |||||
3762 | The C<RaiseError> attribute can be used to force errors to raise exceptions rather | ||||
3763 | than simply return error codes in the normal way. It is "off" by default. | ||||
3764 | When set "on", any method which results in an error will cause | ||||
3765 | the DBI to effectively do a C<die("$class $method failed: $DBI::errstr")>, | ||||
3766 | where C<$class> is the driver class and C<$method> is the name of the method | ||||
3767 | that failed. E.g., | ||||
3768 | |||||
3769 | DBD::Oracle::db prepare failed: ... error text here ... | ||||
3770 | |||||
3771 | If you turn C<RaiseError> on then you'd normally turn C<PrintError> off. | ||||
3772 | If C<PrintError> is also on, then the C<PrintError> is done first (naturally). | ||||
3773 | |||||
3774 | Typically C<RaiseError> is used in conjunction with C<eval { ... }> | ||||
3775 | to catch the exception that's been thrown and followed by an | ||||
3776 | C<if ($@) { ... }> block to handle the caught exception. | ||||
3777 | For example: | ||||
3778 | |||||
3779 | eval { | ||||
3780 | ... | ||||
3781 | $sth->execute(); | ||||
3782 | ... | ||||
3783 | }; | ||||
3784 | if ($@) { | ||||
3785 | # $sth->err and $DBI::err will be true if error was from DBI | ||||
3786 | warn $@; # print the error | ||||
3787 | ... # do whatever you need to deal with the error | ||||
3788 | } | ||||
3789 | |||||
3790 | In that eval block the $DBI::lasth variable can be useful for | ||||
3791 | diagnosis and reporting if you can't be sure which handle triggered | ||||
3792 | the error. For example, $DBI::lasth->{Type} and $DBI::lasth->{Statement}. | ||||
3793 | |||||
3794 | See also L</Transactions>. | ||||
3795 | |||||
3796 | If you want to temporarily turn C<RaiseError> off (inside a library function | ||||
3797 | that is likely to fail, for example), the recommended way is like this: | ||||
3798 | |||||
3799 | { | ||||
3800 | local $h->{RaiseError}; # localize and turn off for this block | ||||
3801 | ... | ||||
3802 | } | ||||
3803 | |||||
3804 | The original value will automatically and reliably be restored by Perl, | ||||
3805 | regardless of how the block is exited. | ||||
3806 | The same logic applies to other attributes, including C<PrintError>. | ||||
3807 | |||||
3808 | =head3 C<HandleError> | ||||
3809 | |||||
3810 | Type: code ref, inherited | ||||
3811 | |||||
3812 | The C<HandleError> attribute can be used to provide your own alternative behaviour | ||||
3813 | in case of errors. If set to a reference to a subroutine then that | ||||
3814 | subroutine is called when an error is detected (at the same point that | ||||
3815 | C<RaiseError> and C<PrintError> are handled). | ||||
3816 | |||||
3817 | The subroutine is called with three parameters: the error message | ||||
3818 | string that C<RaiseError> and C<PrintError> would use, | ||||
3819 | the DBI handle being used, and the first value being returned by | ||||
3820 | the method that failed (typically undef). | ||||
3821 | |||||
3822 | If the subroutine returns a false value then the C<RaiseError> | ||||
3823 | and/or C<PrintError> attributes are checked and acted upon as normal. | ||||
3824 | |||||
3825 | For example, to C<die> with a full stack trace for any error: | ||||
3826 | |||||
3827 | use Carp; | ||||
3828 | $h->{HandleError} = sub { confess(shift) }; | ||||
3829 | |||||
3830 | Or to turn errors into exceptions: | ||||
3831 | |||||
3832 | use Exception; # or your own favourite exception module | ||||
3833 | $h->{HandleError} = sub { Exception->new('DBI')->raise($_[0]) }; | ||||
3834 | |||||
3835 | It is possible to 'stack' multiple HandleError handlers by using | ||||
3836 | closures: | ||||
3837 | |||||
3838 | sub your_subroutine { | ||||
3839 | my $previous_handler = $h->{HandleError}; | ||||
3840 | $h->{HandleError} = sub { | ||||
3841 | return 1 if $previous_handler and &$previous_handler(@_); | ||||
3842 | ... your code here ... | ||||
3843 | }; | ||||
3844 | } | ||||
3845 | |||||
3846 | Using a C<my> inside a subroutine to store the previous C<HandleError> | ||||
3847 | value is important. See L<perlsub> and L<perlref> for more information | ||||
3848 | about I<closures>. | ||||
3849 | |||||
3850 | It is possible for C<HandleError> to alter the error message that | ||||
3851 | will be used by C<RaiseError> and C<PrintError> if it returns false. | ||||
3852 | It can do that by altering the value of $_[0]. This example appends | ||||
3853 | a stack trace to all errors and, unlike the previous example using | ||||
3854 | Carp::confess, this will work C<PrintError> as well as C<RaiseError>: | ||||
3855 | |||||
3856 | $h->{HandleError} = sub { $_[0]=Carp::longmess($_[0]); 0; }; | ||||
3857 | |||||
3858 | It is also possible for C<HandleError> to hide an error, to a limited | ||||
3859 | degree, by using L</set_err> to reset $DBI::err and $DBI::errstr, | ||||
3860 | and altering the return value of the failed method. For example: | ||||
3861 | |||||
3862 | $h->{HandleError} = sub { | ||||
3863 | return 0 unless $_[0] =~ /^\S+ fetchrow_arrayref failed:/; | ||||
3864 | return 0 unless $_[1]->err == 1234; # the error to 'hide' | ||||
3865 | $h->set_err(undef,undef); # turn off the error | ||||
3866 | $_[2] = [ ... ]; # supply alternative return value | ||||
3867 | return 1; | ||||
3868 | }; | ||||
3869 | |||||
3870 | This only works for methods which return a single value and is hard | ||||
3871 | to make reliable (avoiding infinite loops, for example) and so isn't | ||||
3872 | recommended for general use! If you find a I<good> use for it then | ||||
3873 | please let me know. | ||||
3874 | |||||
3875 | =head3 C<HandleSetErr> | ||||
3876 | |||||
3877 | Type: code ref, inherited | ||||
3878 | |||||
3879 | The C<HandleSetErr> attribute can be used to intercept | ||||
3880 | the setting of handle C<err>, C<errstr>, and C<state> values. | ||||
3881 | If set to a reference to a subroutine then that subroutine is called | ||||
3882 | whenever set_err() is called, typically by the driver or a subclass. | ||||
3883 | |||||
3884 | The subroutine is called with five arguments, the first five that | ||||
3885 | were passed to set_err(): the handle, the C<err>, C<errstr>, and | ||||
3886 | C<state> values being set, and the method name. These can be altered | ||||
3887 | by changing the values in the @_ array. The return value affects | ||||
3888 | set_err() behaviour, see L</set_err> for details. | ||||
3889 | |||||
3890 | It is possible to 'stack' multiple HandleSetErr handlers by using | ||||
3891 | closures. See L</HandleError> for an example. | ||||
3892 | |||||
3893 | The C<HandleSetErr> and C<HandleError> subroutines differ in subtle | ||||
3894 | but significant ways. HandleError is only invoked at the point where | ||||
3895 | the DBI is about to return to the application with C<err> set true. | ||||
3896 | It's not invoked by the failure of a method that's been called by | ||||
3897 | another DBI method. HandleSetErr, on the other hand, is called | ||||
3898 | whenever set_err() is called with a defined C<err> value, even if false. | ||||
3899 | So it's not just for errors, despite the name, but also warn and info states. | ||||
3900 | The set_err() method, and thus HandleSetErr, may be called multiple | ||||
3901 | times within a method and is usually invoked from deep within driver code. | ||||
3902 | |||||
3903 | In theory a driver can use the return value from HandleSetErr via | ||||
3904 | set_err() to decide whether to continue or not. If set_err() returns | ||||
3905 | an empty list, indicating that the HandleSetErr code has 'handled' | ||||
3906 | the 'error', the driver could then continue instead of failing (if | ||||
3907 | that's a reasonable thing to do). This isn't excepted to be | ||||
3908 | common and any such cases should be clearly marked in the driver | ||||
3909 | documentation and discussed on the dbi-dev mailing list. | ||||
3910 | |||||
3911 | The C<HandleSetErr> attribute was added in DBI 1.41. | ||||
3912 | |||||
3913 | =head3 C<ErrCount> | ||||
3914 | |||||
3915 | Type: unsigned integer | ||||
3916 | |||||
3917 | The C<ErrCount> attribute is incremented whenever the set_err() | ||||
3918 | method records an error. It isn't incremented by warnings or | ||||
3919 | information states. It is not reset by the DBI at any time. | ||||
3920 | |||||
3921 | The C<ErrCount> attribute was added in DBI 1.41. Older drivers may | ||||
3922 | not have been updated to use set_err() to record errors and so this | ||||
3923 | attribute may not be incremented when using them. | ||||
3924 | |||||
3925 | |||||
3926 | =head3 C<ShowErrorStatement> | ||||
3927 | |||||
3928 | Type: boolean, inherited | ||||
3929 | |||||
3930 | The C<ShowErrorStatement> attribute can be used to cause the relevant | ||||
3931 | Statement text to be appended to the error messages generated by | ||||
3932 | the C<RaiseError>, C<PrintError>, and C<PrintWarn> attributes. | ||||
3933 | Only applies to errors on statement handles | ||||
3934 | plus the prepare(), do(), and the various C<select*()> database handle methods. | ||||
3935 | (The exact format of the appended text is subject to change.) | ||||
3936 | |||||
3937 | If C<$h-E<gt>{ParamValues}> returns a hash reference of parameter | ||||
3938 | (placeholder) values then those are formatted and appended to the | ||||
3939 | end of the Statement text in the error message. | ||||
3940 | |||||
3941 | =head3 C<TraceLevel> | ||||
3942 | |||||
3943 | Type: integer, inherited | ||||
3944 | |||||
3945 | The C<TraceLevel> attribute can be used as an alternative to the | ||||
3946 | L</trace> method to set the DBI trace level and trace flags for a | ||||
3947 | specific handle. See L</TRACING> for more details. | ||||
3948 | |||||
3949 | The C<TraceLevel> attribute is especially useful combined with | ||||
3950 | C<local> to alter the trace settings for just a single block of code. | ||||
3951 | |||||
3952 | =head3 C<FetchHashKeyName> | ||||
3953 | |||||
3954 | Type: string, inherited | ||||
3955 | |||||
3956 | The C<FetchHashKeyName> attribute is used to specify whether the fetchrow_hashref() | ||||
3957 | method should perform case conversion on the field names used for | ||||
3958 | the hash keys. For historical reasons it defaults to 'C<NAME>' but | ||||
3959 | it is recommended to set it to 'C<NAME_lc>' (convert to lower case) | ||||
3960 | or 'C<NAME_uc>' (convert to upper case) according to your preference. | ||||
3961 | It can only be set for driver and database handles. For statement | ||||
3962 | handles the value is frozen when prepare() is called. | ||||
3963 | |||||
3964 | |||||
3965 | =head3 C<ChopBlanks> | ||||
3966 | |||||
3967 | Type: boolean, inherited | ||||
3968 | |||||
3969 | The C<ChopBlanks> attribute can be used to control the trimming of trailing space | ||||
3970 | characters from fixed width character (CHAR) fields. No other field | ||||
3971 | types are affected, even where field values have trailing spaces. | ||||
3972 | |||||
3973 | The default is false (although it is possible that the default may change). | ||||
3974 | Applications that need specific behaviour should set the attribute as | ||||
3975 | needed. | ||||
3976 | |||||
3977 | Drivers are not required to support this attribute, but any driver which | ||||
3978 | does not support it must arrange to return C<undef> as the attribute value. | ||||
3979 | |||||
3980 | |||||
3981 | =head3 C<LongReadLen> | ||||
3982 | |||||
3983 | Type: unsigned integer, inherited | ||||
3984 | |||||
3985 | The C<LongReadLen> attribute may be used to control the maximum | ||||
3986 | length of 'long' type fields (LONG, BLOB, CLOB, MEMO, etc.) which the driver will | ||||
3987 | read from the database automatically when it fetches each row of data. | ||||
3988 | |||||
3989 | The C<LongReadLen> attribute only relates to fetching and reading | ||||
3990 | long values; it is not involved in inserting or updating them. | ||||
3991 | |||||
3992 | A value of 0 means not to automatically fetch any long data. | ||||
3993 | Drivers may return undef or an empty string for long fields when | ||||
3994 | C<LongReadLen> is 0. | ||||
3995 | |||||
3996 | The default is typically 0 (zero) or 80 bytes but may vary between drivers. | ||||
3997 | Applications fetching long fields should set this value to slightly | ||||
3998 | larger than the longest long field value to be fetched. | ||||
3999 | |||||
4000 | Some databases return some long types encoded as pairs of hex digits. | ||||
4001 | For these types, C<LongReadLen> relates to the underlying data | ||||
4002 | length and not the doubled-up length of the encoded string. | ||||
4003 | |||||
4004 | Changing the value of C<LongReadLen> for a statement handle after it | ||||
4005 | has been C<prepare>'d will typically have no effect, so it's common to | ||||
4006 | set C<LongReadLen> on the C<$dbh> before calling C<prepare>. | ||||
4007 | |||||
4008 | For most drivers the value used here has a direct effect on the | ||||
4009 | memory used by the statement handle while it's active, so don't be | ||||
4010 | too generous. If you can't be sure what value to use you could | ||||
4011 | execute an extra select statement to determine the longest value. | ||||
4012 | For example: | ||||
4013 | |||||
4014 | $dbh->{LongReadLen} = $dbh->selectrow_array(qq{ | ||||
4015 | SELECT MAX(OCTET_LENGTH(long_column_name)) | ||||
4016 | FROM table WHERE ... | ||||
4017 | }); | ||||
4018 | $sth = $dbh->prepare(qq{ | ||||
4019 | SELECT long_column_name, ... FROM table WHERE ... | ||||
4020 | }); | ||||
4021 | |||||
4022 | You may need to take extra care if the table can be modified between | ||||
4023 | the first select and the second being executed. You may also need to | ||||
4024 | use a different function if OCTET_LENGTH() does not work for long | ||||
4025 | types in your database. For example, for Sybase use DATALENGTH() and | ||||
4026 | for Oracle use LENGTHB(). | ||||
4027 | |||||
4028 | See also L</LongTruncOk> for information on truncation of long types. | ||||
4029 | |||||
4030 | =head3 C<LongTruncOk> | ||||
4031 | |||||
4032 | Type: boolean, inherited | ||||
4033 | |||||
4034 | The C<LongTruncOk> attribute may be used to control the effect of | ||||
4035 | fetching a long field value which has been truncated (typically | ||||
4036 | because it's longer than the value of the C<LongReadLen> attribute). | ||||
4037 | |||||
4038 | By default, C<LongTruncOk> is false and so fetching a long value that | ||||
4039 | needs to be truncated will cause the fetch to fail. | ||||
4040 | (Applications should always be sure to | ||||
4041 | check for errors after a fetch loop in case an error, such as a divide | ||||
4042 | by zero or long field truncation, caused the fetch to terminate | ||||
4043 | prematurely.) | ||||
4044 | |||||
4045 | If a fetch fails due to a long field truncation when C<LongTruncOk> is | ||||
4046 | false, many drivers will allow you to continue fetching further rows. | ||||
4047 | |||||
4048 | See also L</LongReadLen>. | ||||
4049 | |||||
4050 | =head3 C<TaintIn> | ||||
4051 | |||||
4052 | Type: boolean, inherited | ||||
4053 | |||||
4054 | If the C<TaintIn> attribute is set to a true value I<and> Perl is running in | ||||
4055 | taint mode (e.g., started with the C<-T> option), then all the arguments | ||||
4056 | to most DBI method calls are checked for being tainted. I<This may change.> | ||||
4057 | |||||
4058 | The attribute defaults to off, even if Perl is in taint mode. | ||||
4059 | See L<perlsec> for more about taint mode. If Perl is not | ||||
4060 | running in taint mode, this attribute has no effect. | ||||
4061 | |||||
4062 | When fetching data that you trust you can turn off the TaintIn attribute, | ||||
4063 | for that statement handle, for the duration of the fetch loop. | ||||
4064 | |||||
4065 | The C<TaintIn> attribute was added in DBI 1.31. | ||||
4066 | |||||
4067 | =head3 C<TaintOut> | ||||
4068 | |||||
4069 | Type: boolean, inherited | ||||
4070 | |||||
4071 | If the C<TaintOut> attribute is set to a true value I<and> Perl is running in | ||||
4072 | taint mode (e.g., started with the C<-T> option), then most data fetched | ||||
4073 | from the database is considered tainted. I<This may change.> | ||||
4074 | |||||
4075 | The attribute defaults to off, even if Perl is in taint mode. | ||||
4076 | See L<perlsec> for more about taint mode. If Perl is not | ||||
4077 | running in taint mode, this attribute has no effect. | ||||
4078 | |||||
4079 | When fetching data that you trust you can turn off the TaintOut attribute, | ||||
4080 | for that statement handle, for the duration of the fetch loop. | ||||
4081 | |||||
4082 | Currently only fetched data is tainted. It is possible that the results | ||||
4083 | of other DBI method calls, and the value of fetched attributes, may | ||||
4084 | also be tainted in future versions. That change may well break your | ||||
4085 | applications unless you take great care now. If you use DBI Taint mode, | ||||
4086 | please report your experience and any suggestions for changes. | ||||
4087 | |||||
4088 | The C<TaintOut> attribute was added in DBI 1.31. | ||||
4089 | |||||
4090 | =head3 C<Taint> | ||||
4091 | |||||
4092 | Type: boolean, inherited | ||||
4093 | |||||
4094 | The C<Taint> attribute is a shortcut for L</TaintIn> and L</TaintOut> (it is also present | ||||
4095 | for backwards compatibility). | ||||
4096 | |||||
4097 | Setting this attribute sets both L</TaintIn> and L</TaintOut>, and retrieving | ||||
4098 | it returns a true value if and only if L</TaintIn> and L</TaintOut> are | ||||
4099 | both set to true values. | ||||
4100 | |||||
4101 | =head3 C<Profile> | ||||
4102 | |||||
4103 | Type: inherited | ||||
4104 | |||||
4105 | The C<Profile> attribute enables the collection and reporting of | ||||
4106 | method call timing statistics. See the L<DBI::Profile> module | ||||
4107 | documentation for I<much> more detail. | ||||
4108 | |||||
4109 | The C<Profile> attribute was added in DBI 1.24. | ||||
4110 | |||||
4111 | =head3 C<ReadOnly> | ||||
4112 | |||||
4113 | Type: boolean, inherited | ||||
4114 | |||||
4115 | An application can set the C<ReadOnly> attribute of a handle to a true value to | ||||
4116 | indicate that it will not be attempting to make any changes using that handle | ||||
4117 | or any children of it. | ||||
4118 | |||||
4119 | Note that the exact definition of 'read only' is rather fuzzy. | ||||
4120 | For more details see the documentation for the driver you're using. | ||||
4121 | |||||
4122 | If the driver can make the handle truly read-only then it should | ||||
4123 | (unless doing so would have unpleasant side effect, like changing the | ||||
4124 | consistency level from per-statement to per-session). | ||||
4125 | Otherwise the attribute is simply advisory. | ||||
4126 | |||||
4127 | A driver can set the C<ReadOnly> attribute itself to indicate that the data it | ||||
4128 | is connected to cannot be changed for some reason. | ||||
4129 | |||||
4130 | If the driver cannot ensure the C<ReadOnly> attribute is adhered to it | ||||
4131 | will record a warning. In this case reading the C<ReadOnly> attribute | ||||
4132 | back after it is set true will return true even if the underlying | ||||
4133 | driver cannot ensure this (so any application knows the application | ||||
4134 | declared itself ReadOnly). | ||||
4135 | |||||
4136 | Library modules and proxy drivers can use the attribute to influence | ||||
4137 | their behavior. For example, the DBD::Gofer driver considers the | ||||
4138 | C<ReadOnly> attribute when making a decision about whether to retry an | ||||
4139 | operation that failed. | ||||
4140 | |||||
4141 | The attribute should be set to 1 or 0 (or undef). Other values are reserved. | ||||
4142 | |||||
4143 | =head3 C<Callbacks> | ||||
4144 | |||||
4145 | Type: hash ref | ||||
4146 | |||||
4147 | The DBI callback mechanism lets you intercept, and optionally replace, any | ||||
4148 | method call on a DBI handle. At the extreme, it lets you become a puppet | ||||
4149 | master, deceiving the application in any way you want. | ||||
4150 | |||||
4151 | The C<Callbacks> attribute is a hash reference where the keys are DBI method | ||||
4152 | names and the values are code references. For each key naming a method, the | ||||
4153 | DBI will execute the associated code reference before executing the method. | ||||
4154 | |||||
4155 | The arguments to the code reference will be the same as to the method, | ||||
4156 | including the invocant (a database handle or statement handle). For example, | ||||
4157 | say that to callback to some code on a call to C<prepare()>: | ||||
4158 | |||||
4159 | $dbh->{Callbacks} = { | ||||
4160 | prepare => sub { | ||||
4161 | my ($dbh, $query, $attrs) = @_; | ||||
4162 | print "Preparing q{$query}\n" | ||||
4163 | }, | ||||
4164 | }; | ||||
4165 | |||||
4166 | The callback would then be executed when you called the C<prepare()> method: | ||||
4167 | |||||
4168 | $dbh->prepare('SELECT 1'); | ||||
4169 | |||||
4170 | And the output of course would be: | ||||
4171 | |||||
4172 | Preparing q{SELECT 1} | ||||
4173 | |||||
4174 | Because callbacks are executed I<before> the methods | ||||
4175 | they're associated with, you can modify the arguments before they're passed on | ||||
4176 | to the method call. For example, to make sure that all calls to C<prepare()> | ||||
4177 | are immediately prepared by L<DBD::Pg>, add a callback that makes sure that | ||||
4178 | the C<pg_prepare_now> attribute is always set: | ||||
4179 | |||||
4180 | my $dbh = DBI->connect($dsn, $username, $auth, { | ||||
4181 | Callbacks => { | ||||
4182 | prepare => sub { | ||||
4183 | $_[2] ||= {}; | ||||
4184 | $_[2]->{pg_prepare_now} = 1; | ||||
4185 | return; # must return nothing | ||||
4186 | }, | ||||
4187 | } | ||||
4188 | }); | ||||
4189 | |||||
4190 | Note that we are editing the contents of C<@_> directly. In this case we've | ||||
4191 | created the attributes hash if it's not passed to the C<prepare> call. | ||||
4192 | |||||
4193 | You can also prevent the associated method from ever executing. While a | ||||
4194 | callback executes, C<$_> holds the method name. (This allows multiple callbacks | ||||
4195 | to share the same code reference and still know what method was called.) | ||||
4196 | To prevent the method from | ||||
4197 | executing, simply C<undef $_>. For example, if you wanted to disable calls to | ||||
4198 | C<ping()>, you could do this: | ||||
4199 | |||||
4200 | $dbh->{Callbacks} = { | ||||
4201 | ping => sub { | ||||
4202 | # tell dispatch to not call the method: | ||||
4203 | undef $_; | ||||
4204 | # return this value instead: | ||||
4205 | return "42 bells"; | ||||
4206 | } | ||||
4207 | }; | ||||
4208 | |||||
4209 | As with other attributes, Callbacks can be specified on a handle or via the | ||||
4210 | attributes to C<connect()>. Callbacks can also be applied to a statement | ||||
4211 | methods on a statement handle. For example: | ||||
4212 | |||||
4213 | $sth->{Callbacks} = { | ||||
4214 | execute => sub { | ||||
4215 | print "Executing ", shift->{Statement}, "\n"; | ||||
4216 | } | ||||
4217 | }; | ||||
4218 | |||||
4219 | The C<Callbacks> attribute of a database handle isn't copied to any statement | ||||
4220 | handles it creates. So setting callbacks for a statement handle requires you to | ||||
4221 | set the C<Callbacks> attribute on the statement handle yourself, as in the | ||||
4222 | example above, or use the special C<ChildCallbacks> key described below. | ||||
4223 | |||||
4224 | B<Special Keys in Callbacks Attribute> | ||||
4225 | |||||
4226 | In addition to DBI handle method names, the C<Callbacks> hash reference | ||||
4227 | supports four additional keys. | ||||
4228 | |||||
4229 | The first is the C<ChildCallbacks> key. When a statement handle is created from | ||||
4230 | a database handle the C<ChildCallbacks> key of the database handle's | ||||
4231 | C<Callbacks> attribute, if any, becomes the new C<Callbacks> attribute of the | ||||
4232 | statement handle. | ||||
4233 | This allows you to define callbacks for all statement handles created from a | ||||
4234 | database handle. For example, if you wanted to count how many times C<execute> | ||||
4235 | was called in your application, you could write: | ||||
4236 | |||||
4237 | my $exec_count = 0; | ||||
4238 | my $dbh = DBI->connect( $dsn, $username, $auth, { | ||||
4239 | Callbacks => { | ||||
4240 | ChildCallbacks => { | ||||
4241 | execute => sub { $exec_count++; return; } | ||||
4242 | } | ||||
4243 | } | ||||
4244 | }); | ||||
4245 | |||||
4246 | END { | ||||
4247 | print "The execute method was called $exec_count times\n"; | ||||
4248 | } | ||||
4249 | |||||
4250 | The other three special keys are C<connect_cached.new>, | ||||
4251 | C<connect_cached.connected>, and C<connect_cached.reused>. These keys define | ||||
4252 | callbacks that are called when C<connect_cached()> is called, but allow | ||||
4253 | different behaviors depending on whether a new handle is created or a handle | ||||
4254 | is returned. The callback is invoked with these arguments: | ||||
4255 | C<$dbh, $dsn, $user, $auth, $attr>. | ||||
4256 | |||||
4257 | For example, some applications uses C<connect_cached()> to connect with | ||||
4258 | C<AutoCommit> enabled and then disable C<AutoCommit> temporarily for | ||||
4259 | transactions. If C<connect_cached()> is called during a transaction, perhaps in | ||||
4260 | a utility method, then it might select the same cached handle and then force | ||||
4261 | C<AutoCommit> on, forcing a commit of the transaction. See the L</connect_cached> | ||||
4262 | documentation for one way to deal with that. Here we'll describe an alternative | ||||
4263 | approach using a callback. | ||||
4264 | |||||
4265 | Because the C<connect_cached.new> and C<connect_cached.reused> callbacks are | ||||
4266 | invoked before C<connect_cached()> has applied the connect attributes, you can | ||||
4267 | use them to edit the attributes that will be applied. To prevent a cached | ||||
4268 | handle from having its transactions committed before it's returned, you can | ||||
4269 | eliminate the C<AutoCommit> attribute in a C<connect_cached.reused> callback, | ||||
4270 | like so: | ||||
4271 | |||||
4272 | my $cb = { | ||||
4273 | 'connect_cached.reused' => sub { delete $_[4]->{AutoCommit} }, | ||||
4274 | }; | ||||
4275 | |||||
4276 | sub dbh { | ||||
4277 | my $self = shift; | ||||
4278 | DBI->connect_cached( $dsn, $username, $auth, { | ||||
4279 | PrintError => 0, | ||||
4280 | RaiseError => 1, | ||||
4281 | AutoCommit => 1, | ||||
4282 | Callbacks => $cb, | ||||
4283 | }); | ||||
4284 | } | ||||
4285 | |||||
4286 | The upshot is that new database handles are created with C<AutoCommit> | ||||
4287 | enabled, while cached database handles are left in whatever transaction state | ||||
4288 | they happened to be in when retrieved from the cache. | ||||
4289 | |||||
4290 | Note that we've also used a lexical for the callbacks hash reference. This is | ||||
4291 | because C<connect_cached()> returns a new database handle if any of the | ||||
4292 | attributes passed to is have changed. If we used an inline hash reference, | ||||
4293 | C<connect_cached()> would return a new database handle every time. Which would | ||||
4294 | rather defeat the purpose. | ||||
4295 | |||||
4296 | A more common application for callbacks is setting connection state only when | ||||
4297 | a new connection is made (by connect() or connect_cached()). Adding a callback | ||||
4298 | to the connected method (when using C<connect>) or via | ||||
4299 | C<connect_cached.connected> (when useing connect_cached()>) makes this easy. | ||||
4300 | The connected() method is a no-op by default (unless you subclass the DBI and | ||||
4301 | change it). The DBI calls it to indicate that a new connection has been made | ||||
4302 | and the connection attributes have all been set. You can give it a bit of | ||||
4303 | added functionality by applying a callback to it. For example, to make sure | ||||
4304 | that MySQL understands your application's ANSI-compliant SQL, set it up like | ||||
4305 | so: | ||||
4306 | |||||
4307 | my $dbh = DBI->connect($dsn, $username, $auth, { | ||||
4308 | Callbacks => { | ||||
4309 | connected => sub { | ||||
4310 | shift->do(q{ | ||||
4311 | SET SESSION sql_mode='ansi,strict_trans_tables,no_auto_value_on_zero'; | ||||
4312 | }); | ||||
4313 | return; | ||||
4314 | }, | ||||
4315 | } | ||||
4316 | }); | ||||
4317 | |||||
4318 | If you're using C<connect_cached()>, use the C<connect_cached.connected> | ||||
4319 | callback, instead. This is because C<connected()> is called for both new and | ||||
4320 | reused database handles, but you want to execute a callback only the when a | ||||
4321 | new database handle is returned. For example, to set the time zone on | ||||
4322 | connection to a PostgreSQL database, try this: | ||||
4323 | |||||
4324 | my $cb = { | ||||
4325 | 'connect_cached.connected' => sub { | ||||
4326 | shift->do('SET timezone = UTC'); | ||||
4327 | } | ||||
4328 | }; | ||||
4329 | |||||
4330 | sub dbh { | ||||
4331 | my $self = shift; | ||||
4332 | DBI->connect_cached( $dsn, $username, $auth, { Callbacks => $cb }); | ||||
4333 | } | ||||
4334 | |||||
4335 | One significant limitation with callbacks is that there can only be one per | ||||
4336 | method per handle. This means it's easy for one use of callbacks to interfere | ||||
4337 | with, or typically simply overwrite, another use of callbacks. For this reason | ||||
4338 | modules using callbacks should document the fact clearly so application authors | ||||
4339 | can tell if use of callbacks by the module will clash with use of callbacks by | ||||
4340 | the application. | ||||
4341 | |||||
4342 | You might be able to work around this issue by taking a copy of the original | ||||
4343 | callback and calling it within your own. For example: | ||||
4344 | |||||
4345 | my $prev_cb = $h->{Callbacks}{method_name}; | ||||
4346 | $h->{Callbacks}{method_name} = sub { | ||||
4347 | if ($prev_cb) { | ||||
4348 | my @result = $prev_cb->(@_); | ||||
4349 | return @result if not $_; # $prev_cb vetoed call | ||||
4350 | } | ||||
4351 | ... your callback logic here ... | ||||
4352 | }; | ||||
4353 | |||||
4354 | =head3 C<private_your_module_name_*> | ||||
4355 | |||||
4356 | The DBI provides a way to store extra information in a DBI handle as | ||||
4357 | "private" attributes. The DBI will allow you to store and retrieve any | ||||
4358 | attribute which has a name starting with "C<private_>". | ||||
4359 | |||||
4360 | It is I<strongly> recommended that you use just I<one> private | ||||
4361 | attribute (e.g., use a hash ref) I<and> give it a long and unambiguous | ||||
4362 | name that includes the module or application name that the attribute | ||||
4363 | relates to (e.g., "C<private_YourFullModuleName_thingy>"). | ||||
4364 | |||||
4365 | Because of the way the Perl tie mechanism works you cannot reliably | ||||
4366 | use the C<||=> operator directly to initialise the attribute, like this: | ||||
4367 | |||||
4368 | my $foo = $dbh->{private_yourmodname_foo} ||= { ... }; # WRONG | ||||
4369 | |||||
4370 | you should use a two step approach like this: | ||||
4371 | |||||
4372 | my $foo = $dbh->{private_yourmodname_foo}; | ||||
4373 | $foo ||= $dbh->{private_yourmodname_foo} = { ... }; | ||||
4374 | |||||
4375 | This attribute is primarily of interest to people sub-classing DBI, | ||||
4376 | or for applications to piggy-back extra information onto DBI handles. | ||||
4377 | |||||
4378 | =head1 DBI DATABASE HANDLE OBJECTS | ||||
4379 | |||||
4380 | This section covers the methods and attributes associated with | ||||
4381 | database handles. | ||||
4382 | |||||
4383 | =head2 Database Handle Methods | ||||
4384 | |||||
4385 | The following methods are specified for DBI database handles: | ||||
4386 | |||||
4387 | =head3 C<clone> | ||||
4388 | |||||
4389 | $new_dbh = $dbh->clone(\%attr); | ||||
4390 | |||||
4391 | The C<clone> method duplicates the $dbh connection by connecting | ||||
4392 | with the same parameters ($dsn, $user, $password) as originally used. | ||||
4393 | |||||
4394 | The attributes for the cloned connect are the same as those used | ||||
4395 | for the I<original> connect, with any other attributes in C<\%attr> | ||||
4396 | merged over them. Effectively the same as doing: | ||||
4397 | |||||
4398 | %attributes_used = ( %original_attributes, %attr ); | ||||
4399 | |||||
4400 | If \%attr is not given then it defaults to a hash containing all | ||||
4401 | the attributes in the attribute cache of $dbh excluding any non-code | ||||
4402 | references, plus the main boolean attributes (RaiseError, PrintError, | ||||
4403 | AutoCommit, etc.). I<This behaviour is unreliable and so use of clone without | ||||
4404 | an argument is deprecated and may cause a warning in a future release.> | ||||
4405 | |||||
4406 | The clone method can be used even if the database handle is disconnected. | ||||
4407 | |||||
4408 | The C<clone> method was added in DBI 1.33. | ||||
4409 | |||||
4410 | =head3 C<data_sources> | ||||
4411 | |||||
4412 | @ary = $dbh->data_sources(); | ||||
4413 | @ary = $dbh->data_sources(\%attr); | ||||
4414 | |||||
4415 | Returns a list of data sources (databases) available via the $dbh | ||||
4416 | driver's data_sources() method, plus any extra data sources that | ||||
4417 | the driver can discover via the connected $dbh. Typically the extra | ||||
4418 | data sources are other databases managed by the same server process | ||||
4419 | that the $dbh is connected to. | ||||
4420 | |||||
4421 | Data sources are returned in a form suitable for passing to the | ||||
4422 | L</connect> method (that is, they will include the "C<dbi:$driver:>" prefix). | ||||
4423 | |||||
4424 | The data_sources() method, for a $dbh, was added in DBI 1.38. | ||||
4425 | |||||
4426 | =head3 C<do> | ||||
4427 | |||||
4428 | $rows = $dbh->do($statement) or die $dbh->errstr; | ||||
4429 | $rows = $dbh->do($statement, \%attr) or die $dbh->errstr; | ||||
4430 | $rows = $dbh->do($statement, \%attr, @bind_values) or die ... | ||||
4431 | |||||
4432 | Prepare and execute a single statement. Returns the number of rows | ||||
4433 | affected or C<undef> on error. A return value of C<-1> means the | ||||
4434 | number of rows is not known, not applicable, or not available. | ||||
4435 | |||||
4436 | This method is typically most useful for I<non>-C<SELECT> statements that | ||||
4437 | either cannot be prepared in advance (due to a limitation of the | ||||
4438 | driver) or do not need to be executed repeatedly. It should not | ||||
4439 | be used for C<SELECT> statements because it does not return a statement | ||||
4440 | handle (so you can't fetch any data). | ||||
4441 | |||||
4442 | The default C<do> method is logically similar to: | ||||
4443 | |||||
4444 | sub do { | ||||
4445 | my($dbh, $statement, $attr, @bind_values) = @_; | ||||
4446 | my $sth = $dbh->prepare($statement, $attr) or return undef; | ||||
4447 | $sth->execute(@bind_values) or return undef; | ||||
4448 | my $rows = $sth->rows; | ||||
4449 | ($rows == 0) ? "0E0" : $rows; # always return true if no error | ||||
4450 | } | ||||
4451 | |||||
4452 | For example: | ||||
4453 | |||||
4454 | my $rows_deleted = $dbh->do(q{ | ||||
4455 | DELETE FROM table | ||||
4456 | WHERE status = ? | ||||
4457 | }, undef, 'DONE') or die $dbh->errstr; | ||||
4458 | |||||
4459 | Using placeholders and C<@bind_values> with the C<do> method can be | ||||
4460 | useful because it avoids the need to correctly quote any variables | ||||
4461 | in the C<$statement>. But if you'll be executing the statement many | ||||
4462 | times then it's more efficient to C<prepare> it once and call | ||||
4463 | C<execute> many times instead. | ||||
4464 | |||||
4465 | The C<q{...}> style quoting used in this example avoids clashing with | ||||
4466 | quotes that may be used in the SQL statement. Use the double-quote-like | ||||
4467 | C<qq{...}> operator if you want to interpolate variables into the string. | ||||
4468 | See L<perlop/"Quote and Quote-like Operators"> for more details. | ||||
4469 | |||||
4470 | Note drivers are free to avoid the overhead of creating an DBI | ||||
4471 | statement handle for do(), especially if there are no parameters. In | ||||
4472 | this case error handlers, if invoked during do(), will be passed the | ||||
4473 | database handle. | ||||
4474 | |||||
4475 | =head3 C<last_insert_id> | ||||
4476 | |||||
4477 | $rv = $dbh->last_insert_id($catalog, $schema, $table, $field); | ||||
4478 | $rv = $dbh->last_insert_id($catalog, $schema, $table, $field, \%attr); | ||||
4479 | |||||
4480 | Returns a value 'identifying' the row just inserted, if possible. | ||||
4481 | Typically this would be a value assigned by the database server | ||||
4482 | to a column with an I<auto_increment> or I<serial> type. | ||||
4483 | Returns undef if the driver does not support the method or can't | ||||
4484 | determine the value. | ||||
4485 | |||||
4486 | The $catalog, $schema, $table, and $field parameters may be required | ||||
4487 | for some drivers (see below). If you don't know the parameter values | ||||
4488 | and your driver does not need them, then use C<undef> for each. | ||||
4489 | |||||
4490 | There are several caveats to be aware of with this method if you want | ||||
4491 | to use it for portable applications: | ||||
4492 | |||||
4493 | B<*> For some drivers the value may only available immediately after | ||||
4494 | the insert statement has executed (e.g., mysql, Informix). | ||||
4495 | |||||
4496 | B<*> For some drivers the $catalog, $schema, $table, and $field parameters | ||||
4497 | are required, for others they are ignored (e.g., mysql). | ||||
4498 | |||||
4499 | B<*> Drivers may return an indeterminate value if no insert has | ||||
4500 | been performed yet. | ||||
4501 | |||||
4502 | B<*> For some drivers the value may only be available if placeholders | ||||
4503 | have I<not> been used (e.g., Sybase, MS SQL). In this case the value | ||||
4504 | returned would be from the last non-placeholder insert statement. | ||||
4505 | |||||
4506 | B<*> Some drivers may need driver-specific hints about how to get | ||||
4507 | the value. For example, being told the name of the database 'sequence' | ||||
4508 | object that holds the value. Any such hints are passed as driver-specific | ||||
4509 | attributes in the \%attr parameter. | ||||
4510 | |||||
4511 | B<*> If the underlying database offers nothing better, then some | ||||
4512 | drivers may attempt to implement this method by executing | ||||
4513 | "C<select max($field) from $table>". Drivers using any approach | ||||
4514 | like this should issue a warning if C<AutoCommit> is true because | ||||
4515 | it is generally unsafe - another process may have modified the table | ||||
4516 | between your insert and the select. For situations where you know | ||||
4517 | it is safe, such as when you have locked the table, you can silence | ||||
4518 | the warning by passing C<Warn> => 0 in \%attr. | ||||
4519 | |||||
4520 | B<*> If no insert has been performed yet, or the last insert failed, | ||||
4521 | then the value is implementation defined. | ||||
4522 | |||||
4523 | Given all the caveats above, it's clear that this method must be | ||||
4524 | used with care. | ||||
4525 | |||||
4526 | The C<last_insert_id> method was added in DBI 1.38. | ||||
4527 | |||||
4528 | =head3 C<selectrow_array> | ||||
4529 | |||||
4530 | @row_ary = $dbh->selectrow_array($statement); | ||||
4531 | @row_ary = $dbh->selectrow_array($statement, \%attr); | ||||
4532 | @row_ary = $dbh->selectrow_array($statement, \%attr, @bind_values); | ||||
4533 | |||||
4534 | This utility method combines L</prepare>, L</execute> and | ||||
4535 | L</fetchrow_array> into a single call. If called in a list context, it | ||||
4536 | returns the first row of data from the statement. The C<$statement> | ||||
4537 | parameter can be a previously prepared statement handle, in which case | ||||
4538 | the C<prepare> is skipped. | ||||
4539 | |||||
4540 | If any method fails, and L</RaiseError> is not set, C<selectrow_array> | ||||
4541 | will return an empty list. | ||||
4542 | |||||
4543 | If called in a scalar context for a statement handle that has more | ||||
4544 | than one column, it is undefined whether the driver will return | ||||
4545 | the value of the first column or the last. So don't do that. | ||||
4546 | Also, in a scalar context, an C<undef> is returned if there are no | ||||
4547 | more rows or if an error occurred. That C<undef> can't be distinguished | ||||
4548 | from an C<undef> returned because the first field value was NULL. | ||||
4549 | For these reasons you should exercise some caution if you use | ||||
4550 | C<selectrow_array> in a scalar context, or just don't do that. | ||||
4551 | |||||
4552 | |||||
4553 | =head3 C<selectrow_arrayref> | ||||
4554 | |||||
4555 | $ary_ref = $dbh->selectrow_arrayref($statement); | ||||
4556 | $ary_ref = $dbh->selectrow_arrayref($statement, \%attr); | ||||
4557 | $ary_ref = $dbh->selectrow_arrayref($statement, \%attr, @bind_values); | ||||
4558 | |||||
4559 | This utility method combines L</prepare>, L</execute> and | ||||
4560 | L</fetchrow_arrayref> into a single call. It returns the first row of | ||||
4561 | data from the statement. The C<$statement> parameter can be a previously | ||||
4562 | prepared statement handle, in which case the C<prepare> is skipped. | ||||
4563 | |||||
4564 | If any method fails, and L</RaiseError> is not set, C<selectrow_array> | ||||
4565 | will return undef. | ||||
4566 | |||||
4567 | |||||
4568 | =head3 C<selectrow_hashref> | ||||
4569 | |||||
4570 | $hash_ref = $dbh->selectrow_hashref($statement); | ||||
4571 | $hash_ref = $dbh->selectrow_hashref($statement, \%attr); | ||||
4572 | $hash_ref = $dbh->selectrow_hashref($statement, \%attr, @bind_values); | ||||
4573 | |||||
4574 | This utility method combines L</prepare>, L</execute> and | ||||
4575 | L</fetchrow_hashref> into a single call. It returns the first row of | ||||
4576 | data from the statement. The C<$statement> parameter can be a previously | ||||
4577 | prepared statement handle, in which case the C<prepare> is skipped. | ||||
4578 | |||||
4579 | If any method fails, and L</RaiseError> is not set, C<selectrow_hashref> | ||||
4580 | will return undef. | ||||
4581 | |||||
4582 | |||||
4583 | =head3 C<selectall_arrayref> | ||||
4584 | |||||
4585 | $ary_ref = $dbh->selectall_arrayref($statement); | ||||
4586 | $ary_ref = $dbh->selectall_arrayref($statement, \%attr); | ||||
4587 | $ary_ref = $dbh->selectall_arrayref($statement, \%attr, @bind_values); | ||||
4588 | |||||
4589 | This utility method combines L</prepare>, L</execute> and | ||||
4590 | L</fetchall_arrayref> into a single call. It returns a reference to an | ||||
4591 | array containing a reference to an array (or hash, see below) for each row of | ||||
4592 | data fetched. | ||||
4593 | |||||
4594 | The C<$statement> parameter can be a previously prepared statement handle, | ||||
4595 | in which case the C<prepare> is skipped. This is recommended if the | ||||
4596 | statement is going to be executed many times. | ||||
4597 | |||||
4598 | If L</RaiseError> is not set and any method except C<fetchall_arrayref> | ||||
4599 | fails then C<selectall_arrayref> will return C<undef>; if | ||||
4600 | C<fetchall_arrayref> fails then it will return with whatever data | ||||
4601 | has been fetched thus far. You should check C<$dbh-E<gt>err> | ||||
4602 | afterwards (or use the C<RaiseError> attribute) to discover if the data is | ||||
4603 | complete or was truncated due to an error. | ||||
4604 | |||||
4605 | The L</fetchall_arrayref> method called by C<selectall_arrayref> | ||||
4606 | supports a $max_rows parameter. You can specify a value for $max_rows | ||||
4607 | by including a 'C<MaxRows>' attribute in \%attr. In which case finish() | ||||
4608 | is called for you after fetchall_arrayref() returns. | ||||
4609 | |||||
4610 | The L</fetchall_arrayref> method called by C<selectall_arrayref> | ||||
4611 | also supports a $slice parameter. You can specify a value for $slice by | ||||
4612 | including a 'C<Slice>' or 'C<Columns>' attribute in \%attr. The only | ||||
4613 | difference between the two is that if C<Slice> is not defined and | ||||
4614 | C<Columns> is an array ref, then the array is assumed to contain column | ||||
4615 | index values (which count from 1), rather than perl array index values. | ||||
4616 | In which case the array is copied and each value decremented before | ||||
4617 | passing to C</fetchall_arrayref>. | ||||
4618 | |||||
4619 | You may often want to fetch an array of rows where each row is stored as a | ||||
4620 | hash. That can be done simple using: | ||||
4621 | |||||
4622 | my $emps = $dbh->selectall_arrayref( | ||||
4623 | "SELECT ename FROM emp ORDER BY ename", | ||||
4624 | { Slice => {} } | ||||
4625 | ); | ||||
4626 | foreach my $emp ( @$emps ) { | ||||
4627 | print "Employee: $emp->{ename}\n"; | ||||
4628 | } | ||||
4629 | |||||
4630 | Or, to fetch into an array instead of an array ref: | ||||
4631 | |||||
4632 | @result = @{ $dbh->selectall_arrayref($sql, { Slice => {} }) }; | ||||
4633 | |||||
4634 | See L</fetchall_arrayref> method for more details. | ||||
4635 | |||||
4636 | =head3 C<selectall_hashref> | ||||
4637 | |||||
4638 | $hash_ref = $dbh->selectall_hashref($statement, $key_field); | ||||
4639 | $hash_ref = $dbh->selectall_hashref($statement, $key_field, \%attr); | ||||
4640 | $hash_ref = $dbh->selectall_hashref($statement, $key_field, \%attr, @bind_values); | ||||
4641 | |||||
4642 | This utility method combines L</prepare>, L</execute> and | ||||
4643 | L</fetchall_hashref> into a single call. It returns a reference to a | ||||
4644 | hash containing one entry, at most, for each row, as returned by fetchall_hashref(). | ||||
4645 | |||||
4646 | The C<$statement> parameter can be a previously prepared statement handle, | ||||
4647 | in which case the C<prepare> is skipped. This is recommended if the | ||||
4648 | statement is going to be executed many times. | ||||
4649 | |||||
4650 | The C<$key_field> parameter defines which column, or columns, are used as keys | ||||
4651 | in the returned hash. It can either be the name of a single field, or a | ||||
4652 | reference to an array containing multiple field names. Using multiple names | ||||
4653 | yields a tree of nested hashes. | ||||
4654 | |||||
4655 | If a row has the same key as an earlier row then it replaces the earlier row. | ||||
4656 | |||||
4657 | If any method except C<fetchrow_hashref> fails, and L</RaiseError> is not set, | ||||
4658 | C<selectall_hashref> will return C<undef>. If C<fetchrow_hashref> fails and | ||||
4659 | L</RaiseError> is not set, then it will return with whatever data it | ||||
4660 | has fetched thus far. $DBI::err should be checked to catch that. | ||||
4661 | |||||
4662 | See fetchall_hashref() for more details. | ||||
4663 | |||||
4664 | =head3 C<selectcol_arrayref> | ||||
4665 | |||||
4666 | $ary_ref = $dbh->selectcol_arrayref($statement); | ||||
4667 | $ary_ref = $dbh->selectcol_arrayref($statement, \%attr); | ||||
4668 | $ary_ref = $dbh->selectcol_arrayref($statement, \%attr, @bind_values); | ||||
4669 | |||||
4670 | This utility method combines L</prepare>, L</execute>, and fetching one | ||||
4671 | column from all the rows, into a single call. It returns a reference to | ||||
4672 | an array containing the values of the first column from each row. | ||||
4673 | |||||
4674 | The C<$statement> parameter can be a previously prepared statement handle, | ||||
4675 | in which case the C<prepare> is skipped. This is recommended if the | ||||
4676 | statement is going to be executed many times. | ||||
4677 | |||||
4678 | If any method except C<fetch> fails, and L</RaiseError> is not set, | ||||
4679 | C<selectcol_arrayref> will return C<undef>. If C<fetch> fails and | ||||
4680 | L</RaiseError> is not set, then it will return with whatever data it | ||||
4681 | has fetched thus far. $DBI::err should be checked to catch that. | ||||
4682 | |||||
4683 | The C<selectcol_arrayref> method defaults to pushing a single column | ||||
4684 | value (the first) from each row into the result array. However, it can | ||||
4685 | also push another column, or even multiple columns per row, into the | ||||
4686 | result array. This behaviour can be specified via a 'C<Columns>' | ||||
4687 | attribute which must be a ref to an array containing the column number | ||||
4688 | or numbers to use. For example: | ||||
4689 | |||||
4690 | # get array of id and name pairs: | ||||
4691 | my $ary_ref = $dbh->selectcol_arrayref("select id, name from table", { Columns=>[1,2] }); | ||||
4692 | my %hash = @$ary_ref; # build hash from key-value pairs so $hash{$id} => name | ||||
4693 | |||||
4694 | You can specify a maximum number of rows to fetch by including a | ||||
4695 | 'C<MaxRows>' attribute in \%attr. | ||||
4696 | |||||
4697 | =head3 C<prepare> | ||||
4698 | |||||
4699 | $sth = $dbh->prepare($statement) or die $dbh->errstr; | ||||
4700 | $sth = $dbh->prepare($statement, \%attr) or die $dbh->errstr; | ||||
4701 | |||||
4702 | Prepares a statement for later execution by the database | ||||
4703 | engine and returns a reference to a statement handle object. | ||||
4704 | |||||
4705 | The returned statement handle can be used to get attributes of the | ||||
4706 | statement and invoke the L</execute> method. See L</Statement Handle Methods>. | ||||
4707 | |||||
4708 | Drivers for engines without the concept of preparing a | ||||
4709 | statement will typically just store the statement in the returned | ||||
4710 | handle and process it when C<$sth-E<gt>execute> is called. Such drivers are | ||||
4711 | unlikely to give much useful information about the | ||||
4712 | statement, such as C<$sth-E<gt>{NUM_OF_FIELDS}>, until after C<$sth-E<gt>execute> | ||||
4713 | has been called. Portable applications should take this into account. | ||||
4714 | |||||
4715 | In general, DBI drivers do not parse the contents of the statement | ||||
4716 | (other than simply counting any L</Placeholders>). The statement is | ||||
4717 | passed directly to the database engine, sometimes known as pass-thru | ||||
4718 | mode. This has advantages and disadvantages. On the plus side, you can | ||||
4719 | access all the functionality of the engine being used. On the downside, | ||||
4720 | you're limited if you're using a simple engine, and you need to take extra care if | ||||
4721 | writing applications intended to be portable between engines. | ||||
4722 | |||||
4723 | Portable applications should not assume that a new statement can be | ||||
4724 | prepared and/or executed while still fetching results from a previous | ||||
4725 | statement. | ||||
4726 | |||||
4727 | Some command-line SQL tools use statement terminators, like a semicolon, | ||||
4728 | to indicate the end of a statement. Such terminators should not normally | ||||
4729 | be used with the DBI. | ||||
4730 | |||||
4731 | |||||
4732 | =head3 C<prepare_cached> | ||||
4733 | |||||
4734 | $sth = $dbh->prepare_cached($statement) | ||||
4735 | $sth = $dbh->prepare_cached($statement, \%attr) | ||||
4736 | $sth = $dbh->prepare_cached($statement, \%attr, $if_active) | ||||
4737 | |||||
4738 | Like L</prepare> except that the statement handle returned will be | ||||
4739 | stored in a hash associated with the C<$dbh>. If another call is made to | ||||
4740 | C<prepare_cached> with the same C<$statement> and C<%attr> parameter values, | ||||
4741 | then the corresponding cached C<$sth> will be returned without contacting the | ||||
4742 | database server. | ||||
4743 | |||||
4744 | The C<$if_active> parameter lets you adjust the behaviour if an | ||||
4745 | already cached statement handle is still Active. There are several | ||||
4746 | alternatives: | ||||
4747 | |||||
4748 | =over 4 | ||||
4749 | |||||
4750 | =item B<0>: A warning will be generated, and finish() will be called on | ||||
4751 | the statement handle before it is returned. This is the default | ||||
4752 | behaviour if $if_active is not passed. | ||||
4753 | |||||
4754 | =item B<1>: finish() will be called on the statement handle, but the | ||||
4755 | warning is suppressed. | ||||
4756 | |||||
4757 | =item B<2>: Disables any checking. | ||||
4758 | |||||
4759 | =item B<3>: The existing active statement handle will be removed from the | ||||
4760 | cache and a new statement handle prepared and cached in its place. | ||||
4761 | This is the safest option because it doesn't affect the state of the | ||||
4762 | old handle, it just removes it from the cache. [Added in DBI 1.40] | ||||
4763 | |||||
4764 | =back | ||||
4765 | |||||
4766 | Here are some examples of C<prepare_cached>: | ||||
4767 | |||||
4768 | sub insert_hash { | ||||
4769 | my ($table, $field_values) = @_; | ||||
4770 | # sort to keep field order, and thus sql, stable for prepare_cached | ||||
4771 | my @fields = sort keys %$field_values; | ||||
4772 | my @values = @{$field_values}{@fields}; | ||||
4773 | my $sql = sprintf "insert into %s (%s) values (%s)", | ||||
4774 | $table, join(",", @fields), join(",", ("?")x@fields); | ||||
4775 | my $sth = $dbh->prepare_cached($sql); | ||||
4776 | return $sth->execute(@values); | ||||
4777 | } | ||||
4778 | |||||
4779 | sub search_hash { | ||||
4780 | my ($table, $field_values) = @_; | ||||
4781 | # sort to keep field order, and thus sql, stable for prepare_cached | ||||
4782 | my @fields = sort keys %$field_values; | ||||
4783 | my @values = @{$field_values}{@fields}; | ||||
4784 | my $qualifier = ""; | ||||
4785 | $qualifier = "where ".join(" and ", map { "$_=?" } @fields) if @fields; | ||||
4786 | $sth = $dbh->prepare_cached("SELECT * FROM $table $qualifier"); | ||||
4787 | return $dbh->selectall_arrayref($sth, {}, @values); | ||||
4788 | } | ||||
4789 | |||||
4790 | I<Caveat emptor:> This caching can be useful in some applications, | ||||
4791 | but it can also cause problems and should be used with care. Here | ||||
4792 | is a contrived case where caching would cause a significant problem: | ||||
4793 | |||||
4794 | my $sth = $dbh->prepare_cached('SELECT * FROM foo WHERE bar=?'); | ||||
4795 | $sth->execute(...); | ||||
4796 | while (my $data = $sth->fetchrow_hashref) { | ||||
4797 | |||||
4798 | # later, in some other code called within the loop... | ||||
4799 | my $sth2 = $dbh->prepare_cached('SELECT * FROM foo WHERE bar=?'); | ||||
4800 | $sth2->execute(...); | ||||
4801 | while (my $data2 = $sth2->fetchrow_arrayref) { | ||||
4802 | do_stuff(...); | ||||
4803 | } | ||||
4804 | } | ||||
4805 | |||||
4806 | In this example, since both handles are preparing the exact same statement, | ||||
4807 | C<$sth2> will not be its own statement handle, but a duplicate of C<$sth> | ||||
4808 | returned from the cache. The results will certainly not be what you expect. | ||||
4809 | Typically the inner fetch loop will work normally, fetching all | ||||
4810 | the records and terminating when there are no more, but now that $sth | ||||
4811 | is the same as $sth2 the outer fetch loop will also terminate. | ||||
4812 | |||||
4813 | You'll know if you run into this problem because prepare_cached() | ||||
4814 | will generate a warning by default (when $if_active is false). | ||||
4815 | |||||
4816 | The cache used by prepare_cached() is keyed by both the statement | ||||
4817 | and any attributes so you can also avoid this issue by doing something | ||||
4818 | like: | ||||
4819 | |||||
4820 | $sth = $dbh->prepare_cached("...", { dbi_dummy => __FILE__.__LINE__ }); | ||||
4821 | |||||
4822 | which will ensure that prepare_cached only returns statements cached | ||||
4823 | by that line of code in that source file. | ||||
4824 | |||||
4825 | If you'd like the cache to managed intelligently, you can tie the | ||||
4826 | hashref returned by C<CachedKids> to an appropriate caching module, | ||||
4827 | such as L<Tie::Cache::LRU>: | ||||
4828 | |||||
4829 | my $cache; | ||||
4830 | tie %$cache, 'Tie::Cache::LRU', 500; | ||||
4831 | $dbh->{CachedKids} = $cache; | ||||
4832 | |||||
4833 | =head3 C<commit> | ||||
4834 | |||||
4835 | $rc = $dbh->commit or die $dbh->errstr; | ||||
4836 | |||||
4837 | Commit (make permanent) the most recent series of database changes | ||||
4838 | if the database supports transactions and AutoCommit is off. | ||||
4839 | |||||
4840 | If C<AutoCommit> is on, then calling | ||||
4841 | C<commit> will issue a "commit ineffective with AutoCommit" warning. | ||||
4842 | |||||
4843 | See also L</Transactions> in the L</FURTHER INFORMATION> section below. | ||||
4844 | |||||
4845 | =head3 C<rollback> | ||||
4846 | |||||
4847 | $rc = $dbh->rollback or die $dbh->errstr; | ||||
4848 | |||||
4849 | Rollback (undo) the most recent series of uncommitted database | ||||
4850 | changes if the database supports transactions and AutoCommit is off. | ||||
4851 | |||||
4852 | If C<AutoCommit> is on, then calling | ||||
4853 | C<rollback> will issue a "rollback ineffective with AutoCommit" warning. | ||||
4854 | |||||
4855 | See also L</Transactions> in the L</FURTHER INFORMATION> section below. | ||||
4856 | |||||
4857 | =head3 C<begin_work> | ||||
4858 | |||||
4859 | $rc = $dbh->begin_work or die $dbh->errstr; | ||||
4860 | |||||
4861 | Enable transactions (by turning C<AutoCommit> off) until the next call | ||||
4862 | to C<commit> or C<rollback>. After the next C<commit> or C<rollback>, | ||||
4863 | C<AutoCommit> will automatically be turned on again. | ||||
4864 | |||||
4865 | If C<AutoCommit> is already off when C<begin_work> is called then | ||||
4866 | it does nothing except return an error. If the driver does not support | ||||
4867 | transactions then when C<begin_work> attempts to set C<AutoCommit> off | ||||
4868 | the driver will trigger a fatal error. | ||||
4869 | |||||
4870 | See also L</Transactions> in the L</FURTHER INFORMATION> section below. | ||||
4871 | |||||
4872 | |||||
4873 | =head3 C<disconnect> | ||||
4874 | |||||
4875 | $rc = $dbh->disconnect or warn $dbh->errstr; | ||||
4876 | |||||
4877 | Disconnects the database from the database handle. C<disconnect> is typically only used | ||||
4878 | before exiting the program. The handle is of little use after disconnecting. | ||||
4879 | |||||
4880 | The transaction behaviour of the C<disconnect> method is, sadly, | ||||
4881 | undefined. Some database systems (such as Oracle and Ingres) will | ||||
4882 | automatically commit any outstanding changes, but others (such as | ||||
4883 | Informix) will rollback any outstanding changes. Applications not | ||||
4884 | using C<AutoCommit> should explicitly call C<commit> or C<rollback> before | ||||
4885 | calling C<disconnect>. | ||||
4886 | |||||
4887 | The database is automatically disconnected by the C<DESTROY> method if | ||||
4888 | still connected when there are no longer any references to the handle. | ||||
4889 | The C<DESTROY> method for each driver should implicitly call C<rollback> to | ||||
4890 | undo any uncommitted changes. This is vital behaviour to ensure that | ||||
4891 | incomplete transactions don't get committed simply because Perl calls | ||||
4892 | C<DESTROY> on every object before exiting. Also, do not rely on the order | ||||
4893 | of object destruction during "global destruction", as it is undefined. | ||||
4894 | |||||
4895 | Generally, if you want your changes to be committed or rolled back when | ||||
4896 | you disconnect, then you should explicitly call L</commit> or L</rollback> | ||||
4897 | before disconnecting. | ||||
4898 | |||||
4899 | If you disconnect from a database while you still have active | ||||
4900 | statement handles (e.g., SELECT statement handles that may have | ||||
4901 | more data to fetch), you will get a warning. The warning may indicate | ||||
4902 | that a fetch loop terminated early, perhaps due to an uncaught error. | ||||
4903 | To avoid the warning call the C<finish> method on the active handles. | ||||
4904 | |||||
4905 | |||||
4906 | =head3 C<ping> | ||||
4907 | |||||
4908 | $rc = $dbh->ping; | ||||
4909 | |||||
4910 | Attempts to determine, in a reasonably efficient way, if the database | ||||
4911 | server is still running and the connection to it is still working. | ||||
4912 | Individual drivers should implement this function in the most suitable | ||||
4913 | manner for their database engine. | ||||
4914 | |||||
4915 | The current I<default> implementation always returns true without | ||||
4916 | actually doing anything. Actually, it returns "C<0 but true>" which is | ||||
4917 | true but zero. That way you can tell if the return value is genuine or | ||||
4918 | just the default. Drivers should override this method with one that | ||||
4919 | does the right thing for their type of database. | ||||
4920 | |||||
4921 | Few applications would have direct use for this method. See the specialized | ||||
4922 | Apache::DBI module for one example usage. | ||||
4923 | |||||
4924 | |||||
4925 | =head3 C<get_info> | ||||
4926 | |||||
4927 | $value = $dbh->get_info( $info_type ); | ||||
4928 | |||||
4929 | Returns information about the implementation, i.e. driver and data | ||||
4930 | source capabilities, restrictions etc. It returns C<undef> for | ||||
4931 | unknown or unimplemented information types. For example: | ||||
4932 | |||||
4933 | $database_version = $dbh->get_info( 18 ); # SQL_DBMS_VER | ||||
4934 | $max_select_tables = $dbh->get_info( 106 ); # SQL_MAXIMUM_TABLES_IN_SELECT | ||||
4935 | |||||
4936 | See L</"Standards Reference Information"> for more detailed information | ||||
4937 | about the information types and their meanings and possible return values. | ||||
4938 | |||||
4939 | The DBI::Const::GetInfoType module exports a %GetInfoType hash that | ||||
4940 | can be used to map info type names to numbers. For example: | ||||
4941 | |||||
4942 | $database_version = $dbh->get_info( $GetInfoType{SQL_DBMS_VER} ); | ||||
4943 | |||||
4944 | The names are a merging of the ANSI and ODBC standards (which differ | ||||
4945 | in some cases). See L<DBI::Const::GetInfoType> for more details. | ||||
4946 | |||||
4947 | Because some DBI methods make use of get_info(), drivers are strongly | ||||
4948 | encouraged to support I<at least> the following very minimal set | ||||
4949 | of information types to ensure the DBI itself works properly: | ||||
4950 | |||||
4951 | Type Name Example A Example B | ||||
4952 | ---- -------------------------- ------------ ---------------- | ||||
4953 | 17 SQL_DBMS_NAME 'ACCESS' 'Oracle' | ||||
4954 | 18 SQL_DBMS_VER '03.50.0000' '08.01.0721 ...' | ||||
4955 | 29 SQL_IDENTIFIER_QUOTE_CHAR '`' '"' | ||||
4956 | 41 SQL_CATALOG_NAME_SEPARATOR '.' '@' | ||||
4957 | 114 SQL_CATALOG_LOCATION 1 2 | ||||
4958 | |||||
4959 | =head3 C<table_info> | ||||
4960 | |||||
4961 | $sth = $dbh->table_info( $catalog, $schema, $table, $type ); | ||||
4962 | $sth = $dbh->table_info( $catalog, $schema, $table, $type, \%attr ); | ||||
4963 | |||||
4964 | # then $sth->fetchall_arrayref or $sth->fetchall_hashref etc | ||||
4965 | |||||
4966 | Returns an active statement handle that can be used to fetch | ||||
4967 | information about tables and views that exist in the database. | ||||
4968 | |||||
4969 | The arguments $catalog, $schema and $table may accept search patterns | ||||
4970 | according to the database/driver, for example: $table = '%FOO%'; | ||||
4971 | Remember that the underscore character ('C<_>') is a search pattern | ||||
4972 | that means match any character, so 'FOO_%' is the same as 'FOO%' | ||||
4973 | and 'FOO_BAR%' will match names like 'FOO1BAR'. | ||||
4974 | |||||
4975 | The value of $type is a comma-separated list of one or more types of | ||||
4976 | tables to be returned in the result set. Each value may optionally be | ||||
4977 | quoted, e.g.: | ||||
4978 | |||||
4979 | $type = "TABLE"; | ||||
4980 | $type = "'TABLE','VIEW'"; | ||||
4981 | |||||
4982 | In addition the following special cases may also be supported by some drivers: | ||||
4983 | |||||
4984 | =over 4 | ||||
4985 | |||||
4986 | =item * | ||||
4987 | If the value of $catalog is '%' and $schema and $table name | ||||
4988 | are empty strings, the result set contains a list of catalog names. | ||||
4989 | For example: | ||||
4990 | |||||
4991 | $sth = $dbh->table_info('%', '', ''); | ||||
4992 | |||||
4993 | =item * | ||||
4994 | If the value of $schema is '%' and $catalog and $table are empty | ||||
4995 | strings, the result set contains a list of schema names. | ||||
4996 | |||||
4997 | =item * | ||||
4998 | If the value of $type is '%' and $catalog, $schema, and $table are all | ||||
4999 | empty strings, the result set contains a list of table types. | ||||
5000 | |||||
5001 | =back | ||||
5002 | |||||
5003 | If your driver doesn't support one or more of the selection filter | ||||
5004 | parameters then you may get back more than you asked for and can | ||||
5005 | do the filtering yourself. | ||||
5006 | |||||
5007 | This method can be expensive, and can return a large amount of data. | ||||
5008 | (For example, small Oracle installation returns over 2000 rows.) | ||||
5009 | So it's a good idea to use the filters to limit the data as much as possible. | ||||
5010 | |||||
5011 | The statement handle returned has at least the following fields in the | ||||
5012 | order show below. Other fields, after these, may also be present. | ||||
5013 | |||||
5014 | B<TABLE_CAT>: Table catalog identifier. This field is NULL (C<undef>) if not | ||||
5015 | applicable to the data source, which is usually the case. This field | ||||
5016 | is empty if not applicable to the table. | ||||
5017 | |||||
5018 | B<TABLE_SCHEM>: The name of the schema containing the TABLE_NAME value. | ||||
5019 | This field is NULL (C<undef>) if not applicable to data source, and | ||||
5020 | empty if not applicable to the table. | ||||
5021 | |||||
5022 | B<TABLE_NAME>: Name of the table (or view, synonym, etc). | ||||
5023 | |||||
5024 | B<TABLE_TYPE>: One of the following: "TABLE", "VIEW", "SYSTEM TABLE", | ||||
5025 | "GLOBAL TEMPORARY", "LOCAL TEMPORARY", "ALIAS", "SYNONYM" or a type | ||||
5026 | identifier that is specific to the data | ||||
5027 | source. | ||||
5028 | |||||
5029 | B<REMARKS>: A description of the table. May be NULL (C<undef>). | ||||
5030 | |||||
5031 | Note that C<table_info> might not return records for all tables. | ||||
5032 | Applications can use any valid table regardless of whether it's | ||||
5033 | returned by C<table_info>. | ||||
5034 | |||||
5035 | See also L</tables>, L</"Catalog Methods"> and | ||||
5036 | L</"Standards Reference Information">. | ||||
5037 | |||||
5038 | =head3 C<column_info> | ||||
5039 | |||||
5040 | $sth = $dbh->column_info( $catalog, $schema, $table, $column ); | ||||
5041 | |||||
5042 | # then $sth->fetchall_arrayref or $sth->fetchall_hashref etc | ||||
5043 | |||||
5044 | Returns an active statement handle that can be used to fetch | ||||
5045 | information about columns in specified tables. | ||||
5046 | |||||
5047 | The arguments $schema, $table and $column may accept search patterns | ||||
5048 | according to the database/driver, for example: $table = '%FOO%'; | ||||
5049 | |||||
5050 | Note: The support for the selection criteria is driver specific. If the | ||||
5051 | driver doesn't support one or more of them then you may get back more | ||||
5052 | than you asked for and can do the filtering yourself. | ||||
5053 | |||||
5054 | Note: If your driver does not support column_info an undef is | ||||
5055 | returned. This is distinct from asking for something which does not | ||||
5056 | exist in a driver which supports column_info as a valid statement | ||||
5057 | handle to an empty result-set will be returned in this case. | ||||
5058 | |||||
5059 | If the arguments don't match any tables then you'll still get a statement | ||||
5060 | handle, it'll just return no rows. | ||||
5061 | |||||
5062 | The statement handle returned has at least the following fields in the | ||||
5063 | order shown below. Other fields, after these, may also be present. | ||||
5064 | |||||
5065 | B<TABLE_CAT>: The catalog identifier. | ||||
5066 | This field is NULL (C<undef>) if not applicable to the data source, | ||||
5067 | which is often the case. This field is empty if not applicable to the | ||||
5068 | table. | ||||
5069 | |||||
5070 | B<TABLE_SCHEM>: The schema identifier. | ||||
5071 | This field is NULL (C<undef>) if not applicable to the data source, | ||||
5072 | and empty if not applicable to the table. | ||||
5073 | |||||
5074 | B<TABLE_NAME>: The table identifier. | ||||
5075 | Note: A driver may provide column metadata not only for base tables, but | ||||
5076 | also for derived objects like SYNONYMS etc. | ||||
5077 | |||||
5078 | B<COLUMN_NAME>: The column identifier. | ||||
5079 | |||||
5080 | B<DATA_TYPE>: The concise data type code. | ||||
5081 | |||||
5082 | B<TYPE_NAME>: A data source dependent data type name. | ||||
5083 | |||||
5084 | B<COLUMN_SIZE>: The column size. | ||||
5085 | This is the maximum length in characters for character data types, | ||||
5086 | the number of digits or bits for numeric data types or the length | ||||
5087 | in the representation of temporal types. | ||||
5088 | See the relevant specifications for detailed information. | ||||
5089 | |||||
5090 | B<BUFFER_LENGTH>: The length in bytes of transferred data. | ||||
5091 | |||||
5092 | B<DECIMAL_DIGITS>: The total number of significant digits to the right of | ||||
5093 | the decimal point. | ||||
5094 | |||||
5095 | B<NUM_PREC_RADIX>: The radix for numeric precision. | ||||
5096 | The value is 10 or 2 for numeric data types and NULL (C<undef>) if not | ||||
5097 | applicable. | ||||
5098 | |||||
5099 | B<NULLABLE>: Indicates if a column can accept NULLs. | ||||
5100 | The following values are defined: | ||||
5101 | |||||
5102 | SQL_NO_NULLS 0 | ||||
5103 | SQL_NULLABLE 1 | ||||
5104 | SQL_NULLABLE_UNKNOWN 2 | ||||
5105 | |||||
5106 | B<REMARKS>: A description of the column. | ||||
5107 | |||||
5108 | B<COLUMN_DEF>: The default value of the column, in a format that can be used | ||||
5109 | directly in an SQL statement. | ||||
5110 | |||||
5111 | Note that this may be an expression and not simply the text used for the | ||||
5112 | default value in the original CREATE TABLE statement. For example, given: | ||||
5113 | |||||
5114 | col1 char(30) default current_user -- a 'function' | ||||
5115 | col2 char(30) default 'string' -- a string literal | ||||
5116 | |||||
5117 | where "current_user" is the name of a function, the corresponding C<COLUMN_DEF> | ||||
5118 | values would be: | ||||
5119 | |||||
5120 | Database col1 col2 | ||||
5121 | -------- ---- ---- | ||||
5122 | Oracle: current_user 'string' | ||||
5123 | Postgres: "current_user"() 'string'::text | ||||
5124 | MS SQL: (user_name()) ('string') | ||||
5125 | |||||
5126 | B<SQL_DATA_TYPE>: The SQL data type. | ||||
5127 | |||||
5128 | B<SQL_DATETIME_SUB>: The subtype code for datetime and interval data types. | ||||
5129 | |||||
5130 | B<CHAR_OCTET_LENGTH>: The maximum length in bytes of a character or binary | ||||
5131 | data type column. | ||||
5132 | |||||
5133 | B<ORDINAL_POSITION>: The column sequence number (starting with 1). | ||||
5134 | |||||
5135 | B<IS_NULLABLE>: Indicates if the column can accept NULLs. | ||||
5136 | Possible values are: 'NO', 'YES' and ''. | ||||
5137 | |||||
5138 | SQL/CLI defines the following additional columns: | ||||
5139 | |||||
5140 | CHAR_SET_CAT | ||||
5141 | CHAR_SET_SCHEM | ||||
5142 | CHAR_SET_NAME | ||||
5143 | COLLATION_CAT | ||||
5144 | COLLATION_SCHEM | ||||
5145 | COLLATION_NAME | ||||
5146 | UDT_CAT | ||||
5147 | UDT_SCHEM | ||||
5148 | UDT_NAME | ||||
5149 | DOMAIN_CAT | ||||
5150 | DOMAIN_SCHEM | ||||
5151 | DOMAIN_NAME | ||||
5152 | SCOPE_CAT | ||||
5153 | SCOPE_SCHEM | ||||
5154 | SCOPE_NAME | ||||
5155 | MAX_CARDINALITY | ||||
5156 | DTD_IDENTIFIER | ||||
5157 | IS_SELF_REF | ||||
5158 | |||||
5159 | Drivers capable of supplying any of those values should do so in | ||||
5160 | the corresponding column and supply undef values for the others. | ||||
5161 | |||||
5162 | Drivers wishing to provide extra database/driver specific information | ||||
5163 | should do so in extra columns beyond all those listed above, and | ||||
5164 | use lowercase field names with the driver-specific prefix (i.e., | ||||
5165 | 'ora_...'). Applications accessing such fields should do so by name | ||||
5166 | and not by column number. | ||||
5167 | |||||
5168 | The result set is ordered by TABLE_CAT, TABLE_SCHEM, TABLE_NAME | ||||
5169 | and ORDINAL_POSITION. | ||||
5170 | |||||
5171 | Note: There is some overlap with statement handle attributes (in perl) and | ||||
5172 | SQLDescribeCol (in ODBC). However, SQLColumns provides more metadata. | ||||
5173 | |||||
5174 | See also L</"Catalog Methods"> and L</"Standards Reference Information">. | ||||
5175 | |||||
5176 | =head3 C<primary_key_info> | ||||
5177 | |||||
5178 | $sth = $dbh->primary_key_info( $catalog, $schema, $table ); | ||||
5179 | |||||
5180 | # then $sth->fetchall_arrayref or $sth->fetchall_hashref etc | ||||
5181 | |||||
5182 | Returns an active statement handle that can be used to fetch information | ||||
5183 | about columns that make up the primary key for a table. | ||||
5184 | The arguments don't accept search patterns (unlike table_info()). | ||||
5185 | |||||
5186 | The statement handle will return one row per column, ordered by | ||||
5187 | TABLE_CAT, TABLE_SCHEM, TABLE_NAME, and KEY_SEQ. | ||||
5188 | If there is no primary key then the statement handle will fetch no rows. | ||||
5189 | |||||
5190 | Note: The support for the selection criteria, such as $catalog, is | ||||
5191 | driver specific. If the driver doesn't support catalogs and/or | ||||
5192 | schemas, it may ignore these criteria. | ||||
5193 | |||||
5194 | The statement handle returned has at least the following fields in the | ||||
5195 | order shown below. Other fields, after these, may also be present. | ||||
5196 | |||||
5197 | B<TABLE_CAT>: The catalog identifier. | ||||
5198 | This field is NULL (C<undef>) if not applicable to the data source, | ||||
5199 | which is often the case. This field is empty if not applicable to the | ||||
5200 | table. | ||||
5201 | |||||
5202 | B<TABLE_SCHEM>: The schema identifier. | ||||
5203 | This field is NULL (C<undef>) if not applicable to the data source, | ||||
5204 | and empty if not applicable to the table. | ||||
5205 | |||||
5206 | B<TABLE_NAME>: The table identifier. | ||||
5207 | |||||
5208 | B<COLUMN_NAME>: The column identifier. | ||||
5209 | |||||
5210 | B<KEY_SEQ>: The column sequence number (starting with 1). | ||||
5211 | Note: This field is named B<ORDINAL_POSITION> in SQL/CLI. | ||||
5212 | |||||
5213 | B<PK_NAME>: The primary key constraint identifier. | ||||
5214 | This field is NULL (C<undef>) if not applicable to the data source. | ||||
5215 | |||||
5216 | See also L</"Catalog Methods"> and L</"Standards Reference Information">. | ||||
5217 | |||||
5218 | =head3 C<primary_key> | ||||
5219 | |||||
5220 | @key_column_names = $dbh->primary_key( $catalog, $schema, $table ); | ||||
5221 | |||||
5222 | Simple interface to the primary_key_info() method. Returns a list of | ||||
5223 | the column names that comprise the primary key of the specified table. | ||||
5224 | The list is in primary key column sequence order. | ||||
5225 | If there is no primary key then an empty list is returned. | ||||
5226 | |||||
5227 | =head3 C<foreign_key_info> | ||||
5228 | |||||
5229 | $sth = $dbh->foreign_key_info( $pk_catalog, $pk_schema, $pk_table | ||||
5230 | , $fk_catalog, $fk_schema, $fk_table ); | ||||
5231 | |||||
5232 | $sth = $dbh->foreign_key_info( $pk_catalog, $pk_schema, $pk_table | ||||
5233 | , $fk_catalog, $fk_schema, $fk_table | ||||
5234 | , \%attr ); | ||||
5235 | |||||
5236 | # then $sth->fetchall_arrayref or $sth->fetchall_hashref etc | ||||
5237 | |||||
5238 | Returns an active statement handle that can be used to fetch information | ||||
5239 | about foreign keys in and/or referencing the specified table(s). | ||||
5240 | The arguments don't accept search patterns (unlike table_info()). | ||||
5241 | |||||
5242 | C<$pk_catalog>, C<$pk_schema>, C<$pk_table> | ||||
5243 | identify the primary (unique) key table (B<PKT>). | ||||
5244 | |||||
5245 | C<$fk_catalog>, C<$fk_schema>, C<$fk_table> | ||||
5246 | identify the foreign key table (B<FKT>). | ||||
5247 | |||||
5248 | If both B<PKT> and B<FKT> are given, the function returns the foreign key, if | ||||
5249 | any, in table B<FKT> that refers to the primary (unique) key of table B<PKT>. | ||||
5250 | (Note: In SQL/CLI, the result is implementation-defined.) | ||||
5251 | |||||
5252 | If only B<PKT> is given, then the result set contains the primary key | ||||
5253 | of that table and all foreign keys that refer to it. | ||||
5254 | |||||
5255 | If only B<FKT> is given, then the result set contains all foreign keys | ||||
5256 | in that table and the primary keys to which they refer. | ||||
5257 | (Note: In SQL/CLI, the result includes unique keys too.) | ||||
5258 | |||||
5259 | For example: | ||||
5260 | |||||
5261 | $sth = $dbh->foreign_key_info( undef, $user, 'master'); | ||||
5262 | $sth = $dbh->foreign_key_info( undef, undef, undef , undef, $user, 'detail'); | ||||
5263 | $sth = $dbh->foreign_key_info( undef, $user, 'master', undef, $user, 'detail'); | ||||
5264 | |||||
5265 | # then $sth->fetchall_arrayref or $sth->fetchall_hashref etc | ||||
5266 | |||||
5267 | Note: The support for the selection criteria, such as C<$catalog>, is | ||||
5268 | driver specific. If the driver doesn't support catalogs and/or | ||||
5269 | schemas, it may ignore these criteria. | ||||
5270 | |||||
5271 | The statement handle returned has the following fields in the order shown below. | ||||
5272 | Because ODBC never includes unique keys, they define different columns in the | ||||
5273 | result set than SQL/CLI. SQL/CLI column names are shown in parentheses. | ||||
5274 | |||||
5275 | B<PKTABLE_CAT ( UK_TABLE_CAT )>: | ||||
5276 | The primary (unique) key table catalog identifier. | ||||
5277 | This field is NULL (C<undef>) if not applicable to the data source, | ||||
5278 | which is often the case. This field is empty if not applicable to the | ||||
5279 | table. | ||||
5280 | |||||
5281 | B<PKTABLE_SCHEM ( UK_TABLE_SCHEM )>: | ||||
5282 | The primary (unique) key table schema identifier. | ||||
5283 | This field is NULL (C<undef>) if not applicable to the data source, | ||||
5284 | and empty if not applicable to the table. | ||||
5285 | |||||
5286 | B<PKTABLE_NAME ( UK_TABLE_NAME )>: | ||||
5287 | The primary (unique) key table identifier. | ||||
5288 | |||||
5289 | B<PKCOLUMN_NAME (UK_COLUMN_NAME )>: | ||||
5290 | The primary (unique) key column identifier. | ||||
5291 | |||||
5292 | B<FKTABLE_CAT ( FK_TABLE_CAT )>: | ||||
5293 | The foreign key table catalog identifier. | ||||
5294 | This field is NULL (C<undef>) if not applicable to the data source, | ||||
5295 | which is often the case. This field is empty if not applicable to the | ||||
5296 | table. | ||||
5297 | |||||
5298 | B<FKTABLE_SCHEM ( FK_TABLE_SCHEM )>: | ||||
5299 | The foreign key table schema identifier. | ||||
5300 | This field is NULL (C<undef>) if not applicable to the data source, | ||||
5301 | and empty if not applicable to the table. | ||||
5302 | |||||
5303 | B<FKTABLE_NAME ( FK_TABLE_NAME )>: | ||||
5304 | The foreign key table identifier. | ||||
5305 | |||||
5306 | B<FKCOLUMN_NAME ( FK_COLUMN_NAME )>: | ||||
5307 | The foreign key column identifier. | ||||
5308 | |||||
5309 | B<KEY_SEQ ( ORDINAL_POSITION )>: | ||||
5310 | The column sequence number (starting with 1). | ||||
5311 | |||||
5312 | B<UPDATE_RULE ( UPDATE_RULE )>: | ||||
5313 | The referential action for the UPDATE rule. | ||||
5314 | The following codes are defined: | ||||
5315 | |||||
5316 | CASCADE 0 | ||||
5317 | RESTRICT 1 | ||||
5318 | SET NULL 2 | ||||
5319 | NO ACTION 3 | ||||
5320 | SET DEFAULT 4 | ||||
5321 | |||||
5322 | B<DELETE_RULE ( DELETE_RULE )>: | ||||
5323 | The referential action for the DELETE rule. | ||||
5324 | The codes are the same as for UPDATE_RULE. | ||||
5325 | |||||
5326 | B<FK_NAME ( FK_NAME )>: | ||||
5327 | The foreign key name. | ||||
5328 | |||||
5329 | B<PK_NAME ( UK_NAME )>: | ||||
5330 | The primary (unique) key name. | ||||
5331 | |||||
5332 | B<DEFERRABILITY ( DEFERABILITY )>: | ||||
5333 | The deferrability of the foreign key constraint. | ||||
5334 | The following codes are defined: | ||||
5335 | |||||
5336 | INITIALLY DEFERRED 5 | ||||
5337 | INITIALLY IMMEDIATE 6 | ||||
5338 | NOT DEFERRABLE 7 | ||||
5339 | |||||
5340 | B< ( UNIQUE_OR_PRIMARY )>: | ||||
5341 | This column is necessary if a driver includes all candidate (i.e. primary and | ||||
5342 | alternate) keys in the result set (as specified by SQL/CLI). | ||||
5343 | The value of this column is UNIQUE if the foreign key references an alternate | ||||
5344 | key and PRIMARY if the foreign key references a primary key, or it | ||||
5345 | may be undefined if the driver doesn't have access to the information. | ||||
5346 | |||||
5347 | See also L</"Catalog Methods"> and L</"Standards Reference Information">. | ||||
5348 | |||||
5349 | =head3 C<statistics_info> | ||||
5350 | |||||
5351 | B<Warning:> This method is experimental and may change. | ||||
5352 | |||||
5353 | $sth = $dbh->statistics_info( $catalog, $schema, $table, $unique_only, $quick ); | ||||
5354 | |||||
5355 | # then $sth->fetchall_arrayref or $sth->fetchall_hashref etc | ||||
5356 | |||||
5357 | Returns an active statement handle that can be used to fetch statistical | ||||
5358 | information about a table and its indexes. | ||||
5359 | |||||
5360 | The arguments don't accept search patterns (unlike L</table_info>). | ||||
5361 | |||||
5362 | If the boolean argument $unique_only is true, only UNIQUE indexes will be | ||||
5363 | returned in the result set, otherwise all indexes will be returned. | ||||
5364 | |||||
5365 | If the boolean argument $quick is set, the actual statistical information | ||||
5366 | columns (CARDINALITY and PAGES) will only be returned if they are readily | ||||
5367 | available from the server, and might not be current. Some databases may | ||||
5368 | return stale statistics or no statistics at all with this flag set. | ||||
5369 | |||||
5370 | The statement handle will return at most one row per column name per index, | ||||
5371 | plus at most one row for the entire table itself, ordered by NON_UNIQUE, TYPE, | ||||
5372 | INDEX_QUALIFIER, INDEX_NAME, and ORDINAL_POSITION. | ||||
5373 | |||||
5374 | Note: The support for the selection criteria, such as $catalog, is | ||||
5375 | driver specific. If the driver doesn't support catalogs and/or | ||||
5376 | schemas, it may ignore these criteria. | ||||
5377 | |||||
5378 | The statement handle returned has at least the following fields in the | ||||
5379 | order shown below. Other fields, after these, may also be present. | ||||
5380 | |||||
5381 | B<TABLE_CAT>: The catalog identifier. | ||||
5382 | This field is NULL (C<undef>) if not applicable to the data source, | ||||
5383 | which is often the case. This field is empty if not applicable to the | ||||
5384 | table. | ||||
5385 | |||||
5386 | B<TABLE_SCHEM>: The schema identifier. | ||||
5387 | This field is NULL (C<undef>) if not applicable to the data source, | ||||
5388 | and empty if not applicable to the table. | ||||
5389 | |||||
5390 | B<TABLE_NAME>: The table identifier. | ||||
5391 | |||||
5392 | B<NON_UNIQUE>: Unique index indicator. | ||||
5393 | Returns 0 for unique indexes, 1 for non-unique indexes | ||||
5394 | |||||
5395 | B<INDEX_QUALIFIER>: Index qualifier identifier. | ||||
5396 | The identifier that is used to qualify the index name when doing a | ||||
5397 | C<DROP INDEX>; NULL (C<undef>) is returned if an index qualifier is not | ||||
5398 | supported by the data source. | ||||
5399 | If a non-NULL (defined) value is returned in this column, it must be used | ||||
5400 | to qualify the index name on a C<DROP INDEX> statement; otherwise, | ||||
5401 | the TABLE_SCHEM should be used to qualify the index name. | ||||
5402 | |||||
5403 | B<INDEX_NAME>: The index identifier. | ||||
5404 | |||||
5405 | B<TYPE>: The type of information being returned. Can be any of the | ||||
5406 | following values: 'table', 'btree', 'clustered', 'content', 'hashed', | ||||
5407 | or 'other'. | ||||
5408 | |||||
5409 | In the case that this field is 'table', all fields | ||||
5410 | other than TABLE_CAT, TABLE_SCHEM, TABLE_NAME, TYPE, | ||||
5411 | CARDINALITY, and PAGES will be NULL (C<undef>). | ||||
5412 | |||||
5413 | B<ORDINAL_POSITION>: Column sequence number (starting with 1). | ||||
5414 | |||||
5415 | B<COLUMN_NAME>: The column identifier. | ||||
5416 | |||||
5417 | B<ASC_OR_DESC>: Column sort sequence. | ||||
5418 | C<A> for Ascending, C<D> for Descending, or NULL (C<undef>) if | ||||
5419 | not supported for this index. | ||||
5420 | |||||
5421 | B<CARDINALITY>: Cardinality of the table or index. | ||||
5422 | For indexes, this is the number of unique values in the index. | ||||
5423 | For tables, this is the number of rows in the table. | ||||
5424 | If not supported, the value will be NULL (C<undef>). | ||||
5425 | |||||
5426 | B<PAGES>: Number of storage pages used by this table or index. | ||||
5427 | If not supported, the value will be NULL (C<undef>). | ||||
5428 | |||||
5429 | B<FILTER_CONDITION>: The index filter condition as a string. | ||||
5430 | If the index is not a filtered index, or it cannot be determined | ||||
5431 | whether the index is a filtered index, this value is NULL (C<undef>). | ||||
5432 | If the index is a filtered index, but the filter condition | ||||
5433 | cannot be determined, this value is the empty string C<''>. | ||||
5434 | Otherwise it will be the literal filter condition as a string, | ||||
5435 | such as C<SALARY <= 4500>. | ||||
5436 | |||||
5437 | See also L</"Catalog Methods"> and L</"Standards Reference Information">. | ||||
5438 | |||||
5439 | =head3 C<tables> | ||||
5440 | |||||
5441 | @names = $dbh->tables( $catalog, $schema, $table, $type ); | ||||
5442 | @names = $dbh->tables; # deprecated | ||||
5443 | |||||
5444 | Simple interface to table_info(). Returns a list of matching | ||||
5445 | table names, possibly including a catalog/schema prefix. | ||||
5446 | |||||
5447 | See L</table_info> for a description of the parameters. | ||||
5448 | |||||
5449 | If C<$dbh-E<gt>get_info(29)> returns true (29 is SQL_IDENTIFIER_QUOTE_CHAR) | ||||
5450 | then the table names are constructed and quoted by L</quote_identifier> | ||||
5451 | to ensure they are usable even if they contain whitespace or reserved | ||||
5452 | words etc. This means that the table names returned will include | ||||
5453 | quote characters. | ||||
5454 | |||||
5455 | =head3 C<type_info_all> | ||||
5456 | |||||
5457 | $type_info_all = $dbh->type_info_all; | ||||
5458 | |||||
5459 | Returns a reference to an array which holds information about each data | ||||
5460 | type variant supported by the database and driver. The array and its | ||||
5461 | contents should be treated as read-only. | ||||
5462 | |||||
5463 | The first item is a reference to an 'index' hash of C<Name =>E<gt> C<Index> pairs. | ||||
5464 | The items following that are references to arrays, one per supported data | ||||
5465 | type variant. The leading index hash defines the names and order of the | ||||
5466 | fields within the arrays that follow it. | ||||
5467 | For example: | ||||
5468 | |||||
5469 | $type_info_all = [ | ||||
5470 | { TYPE_NAME => 0, | ||||
5471 | DATA_TYPE => 1, | ||||
5472 | COLUMN_SIZE => 2, # was PRECISION originally | ||||
5473 | LITERAL_PREFIX => 3, | ||||
5474 | LITERAL_SUFFIX => 4, | ||||
5475 | CREATE_PARAMS => 5, | ||||
5476 | NULLABLE => 6, | ||||
5477 | CASE_SENSITIVE => 7, | ||||
5478 | SEARCHABLE => 8, | ||||
5479 | UNSIGNED_ATTRIBUTE=> 9, | ||||
5480 | FIXED_PREC_SCALE => 10, # was MONEY originally | ||||
5481 | AUTO_UNIQUE_VALUE => 11, # was AUTO_INCREMENT originally | ||||
5482 | LOCAL_TYPE_NAME => 12, | ||||
5483 | MINIMUM_SCALE => 13, | ||||
5484 | MAXIMUM_SCALE => 14, | ||||
5485 | SQL_DATA_TYPE => 15, | ||||
5486 | SQL_DATETIME_SUB => 16, | ||||
5487 | NUM_PREC_RADIX => 17, | ||||
5488 | INTERVAL_PRECISION=> 18, | ||||
5489 | }, | ||||
5490 | [ 'VARCHAR', SQL_VARCHAR, | ||||
5491 | undef, "'","'", undef,0, 1,1,0,0,0,undef,1,255, undef | ||||
5492 | ], | ||||
5493 | [ 'INTEGER', SQL_INTEGER, | ||||
5494 | undef, "", "", undef,0, 0,1,0,0,0,undef,0, 0, 10 | ||||
5495 | ], | ||||
5496 | ]; | ||||
5497 | |||||
5498 | More than one row may have the same value in the C<DATA_TYPE> | ||||
5499 | field if there are different ways to spell the type name and/or there | ||||
5500 | are variants of the type with different attributes (e.g., with and | ||||
5501 | without C<AUTO_UNIQUE_VALUE> set, with and without C<UNSIGNED_ATTRIBUTE>, etc). | ||||
5502 | |||||
5503 | The rows are ordered by C<DATA_TYPE> first and then by how closely each | ||||
5504 | type maps to the corresponding ODBC SQL data type, closest first. | ||||
5505 | |||||
5506 | The meaning of the fields is described in the documentation for | ||||
5507 | the L</type_info> method. | ||||
5508 | |||||
5509 | An 'index' hash is provided so you don't need to rely on index | ||||
5510 | values defined above. However, using DBD::ODBC with some old ODBC | ||||
5511 | drivers may return older names, shown as comments in the example above. | ||||
5512 | Another issue with the index hash is that the lettercase of the | ||||
5513 | keys is not defined. It is usually uppercase, as show here, but | ||||
5514 | drivers may return names with any lettercase. | ||||
5515 | |||||
5516 | Drivers are also free to return extra driver-specific columns of | ||||
5517 | information - though it's recommended that they start at column | ||||
5518 | index 50 to leave room for expansion of the DBI/ODBC specification. | ||||
5519 | |||||
5520 | The type_info_all() method is not normally used directly. | ||||
5521 | The L</type_info> method provides a more usable and useful interface | ||||
5522 | to the data. | ||||
5523 | |||||
5524 | =head3 C<type_info> | ||||
5525 | |||||
5526 | @type_info = $dbh->type_info($data_type); | ||||
5527 | |||||
5528 | Returns a list of hash references holding information about one or more | ||||
5529 | variants of $data_type. The list is ordered by C<DATA_TYPE> first and | ||||
5530 | then by how closely each type maps to the corresponding ODBC SQL data | ||||
5531 | type, closest first. If called in a scalar context then only the first | ||||
5532 | (best) element is returned. | ||||
5533 | |||||
5534 | If $data_type is undefined or C<SQL_ALL_TYPES>, then the list will | ||||
5535 | contain hashes for all data type variants supported by the database and driver. | ||||
5536 | |||||
5537 | If $data_type is an array reference then C<type_info> returns the | ||||
5538 | information for the I<first> type in the array that has any matches. | ||||
5539 | |||||
5540 | The keys of the hash follow the same letter case conventions as the | ||||
5541 | rest of the DBI (see L</Naming Conventions and Name Space>). The | ||||
5542 | following uppercase items should always exist, though may be undef: | ||||
5543 | |||||
5544 | =over 4 | ||||
5545 | |||||
5546 | =item TYPE_NAME (string) | ||||
5547 | |||||
5548 | Data type name for use in CREATE TABLE statements etc. | ||||
5549 | |||||
5550 | =item DATA_TYPE (integer) | ||||
5551 | |||||
5552 | SQL data type number. | ||||
5553 | |||||
5554 | =item COLUMN_SIZE (integer) | ||||
5555 | |||||
5556 | For numeric types, this is either the total number of digits (if the | ||||
5557 | NUM_PREC_RADIX value is 10) or the total number of bits allowed in the | ||||
5558 | column (if NUM_PREC_RADIX is 2). | ||||
5559 | |||||
5560 | For string types, this is the maximum size of the string in characters. | ||||
5561 | |||||
5562 | For date and interval types, this is the maximum number of characters | ||||
5563 | needed to display the value. | ||||
5564 | |||||
5565 | =item LITERAL_PREFIX (string) | ||||
5566 | |||||
5567 | Characters used to prefix a literal. A typical prefix is "C<'>" for characters, | ||||
5568 | or possibly "C<0x>" for binary values passed as hexadecimal. NULL (C<undef>) is | ||||
5569 | returned for data types for which this is not applicable. | ||||
5570 | |||||
5571 | |||||
5572 | =item LITERAL_SUFFIX (string) | ||||
5573 | |||||
5574 | Characters used to suffix a literal. Typically "C<'>" for characters. | ||||
5575 | NULL (C<undef>) is returned for data types where this is not applicable. | ||||
5576 | |||||
5577 | =item CREATE_PARAMS (string) | ||||
5578 | |||||
5579 | Parameter names for data type definition. For example, C<CREATE_PARAMS> for a | ||||
5580 | C<DECIMAL> would be "C<precision,scale>" if the DECIMAL type should be | ||||
5581 | declared as C<DECIMAL(>I<precision,scale>C<)> where I<precision> and I<scale> | ||||
5582 | are integer values. For a C<VARCHAR> it would be "C<max length>". | ||||
5583 | NULL (C<undef>) is returned for data types for which this is not applicable. | ||||
5584 | |||||
5585 | =item NULLABLE (integer) | ||||
5586 | |||||
5587 | Indicates whether the data type accepts a NULL value: | ||||
5588 | C<0> or an empty string = no, C<1> = yes, C<2> = unknown. | ||||
5589 | |||||
5590 | =item CASE_SENSITIVE (boolean) | ||||
5591 | |||||
5592 | Indicates whether the data type is case sensitive in collations and | ||||
5593 | comparisons. | ||||
5594 | |||||
5595 | =item SEARCHABLE (integer) | ||||
5596 | |||||
5597 | Indicates how the data type can be used in a WHERE clause, as | ||||
5598 | follows: | ||||
5599 | |||||
5600 | 0 - Cannot be used in a WHERE clause | ||||
5601 | 1 - Only with a LIKE predicate | ||||
5602 | 2 - All comparison operators except LIKE | ||||
5603 | 3 - Can be used in a WHERE clause with any comparison operator | ||||
5604 | |||||
5605 | =item UNSIGNED_ATTRIBUTE (boolean) | ||||
5606 | |||||
5607 | Indicates whether the data type is unsigned. NULL (C<undef>) is returned | ||||
5608 | for data types for which this is not applicable. | ||||
5609 | |||||
5610 | =item FIXED_PREC_SCALE (boolean) | ||||
5611 | |||||
5612 | Indicates whether the data type always has the same precision and scale | ||||
5613 | (such as a money type). NULL (C<undef>) is returned for data types | ||||
5614 | for which | ||||
5615 | this is not applicable. | ||||
5616 | |||||
5617 | =item AUTO_UNIQUE_VALUE (boolean) | ||||
5618 | |||||
5619 | Indicates whether a column of this data type is automatically set to a | ||||
5620 | unique value whenever a new row is inserted. NULL (C<undef>) is returned | ||||
5621 | for data types for which this is not applicable. | ||||
5622 | |||||
5623 | =item LOCAL_TYPE_NAME (string) | ||||
5624 | |||||
5625 | Localized version of the C<TYPE_NAME> for use in dialog with users. | ||||
5626 | NULL (C<undef>) is returned if a localized name is not available (in which | ||||
5627 | case C<TYPE_NAME> should be used). | ||||
5628 | |||||
5629 | =item MINIMUM_SCALE (integer) | ||||
5630 | |||||
5631 | The minimum scale of the data type. If a data type has a fixed scale, | ||||
5632 | then C<MAXIMUM_SCALE> holds the same value. NULL (C<undef>) is returned for | ||||
5633 | data types for which this is not applicable. | ||||
5634 | |||||
5635 | =item MAXIMUM_SCALE (integer) | ||||
5636 | |||||
5637 | The maximum scale of the data type. If a data type has a fixed scale, | ||||
5638 | then C<MINIMUM_SCALE> holds the same value. NULL (C<undef>) is returned for | ||||
5639 | data types for which this is not applicable. | ||||
5640 | |||||
5641 | =item SQL_DATA_TYPE (integer) | ||||
5642 | |||||
5643 | This column is the same as the C<DATA_TYPE> column, except for interval | ||||
5644 | and datetime data types. For interval and datetime data types, the | ||||
5645 | C<SQL_DATA_TYPE> field will return C<SQL_INTERVAL> or C<SQL_DATETIME>, and the | ||||
5646 | C<SQL_DATETIME_SUB> field below will return the subcode for the specific | ||||
5647 | interval or datetime data type. If this field is NULL, then the driver | ||||
5648 | does not support or report on interval or datetime subtypes. | ||||
5649 | |||||
5650 | =item SQL_DATETIME_SUB (integer) | ||||
5651 | |||||
5652 | For interval or datetime data types, where the C<SQL_DATA_TYPE> | ||||
5653 | field above is C<SQL_INTERVAL> or C<SQL_DATETIME>, this field will | ||||
5654 | hold the I<subcode> for the specific interval or datetime data type. | ||||
5655 | Otherwise it will be NULL (C<undef>). | ||||
5656 | |||||
5657 | Although not mentioned explicitly in the standards, it seems there | ||||
5658 | is a simple relationship between these values: | ||||
5659 | |||||
5660 | DATA_TYPE == (10 * SQL_DATA_TYPE) + SQL_DATETIME_SUB | ||||
5661 | |||||
5662 | =item NUM_PREC_RADIX (integer) | ||||
5663 | |||||
5664 | The radix value of the data type. For approximate numeric types, | ||||
5665 | C<NUM_PREC_RADIX> | ||||
5666 | contains the value 2 and C<COLUMN_SIZE> holds the number of bits. For | ||||
5667 | exact numeric types, C<NUM_PREC_RADIX> contains the value 10 and C<COLUMN_SIZE> holds | ||||
5668 | the number of decimal digits. NULL (C<undef>) is returned either for data types | ||||
5669 | for which this is not applicable or if the driver cannot report this information. | ||||
5670 | |||||
5671 | =item INTERVAL_PRECISION (integer) | ||||
5672 | |||||
5673 | The interval leading precision for interval types. NULL is returned | ||||
5674 | either for data types for which this is not applicable or if the driver | ||||
5675 | cannot report this information. | ||||
5676 | |||||
5677 | =back | ||||
5678 | |||||
5679 | For example, to find the type name for the fields in a select statement | ||||
5680 | you can do: | ||||
5681 | |||||
5682 | @names = map { scalar $dbh->type_info($_)->{TYPE_NAME} } @{ $sth->{TYPE} } | ||||
5683 | |||||
5684 | Since DBI and ODBC drivers vary in how they map their types into the | ||||
5685 | ISO standard types you may need to search for more than one type. | ||||
5686 | Here's an example looking for a usable type to store a date: | ||||
5687 | |||||
5688 | $my_date_type = $dbh->type_info( [ SQL_DATE, SQL_TIMESTAMP ] ); | ||||
5689 | |||||
5690 | Similarly, to more reliably find a type to store small integers, you could | ||||
5691 | use a list starting with C<SQL_SMALLINT>, C<SQL_INTEGER>, C<SQL_DECIMAL>, etc. | ||||
5692 | |||||
5693 | See also L</"Standards Reference Information">. | ||||
5694 | |||||
5695 | |||||
5696 | =head3 C<quote> | ||||
5697 | |||||
5698 | $sql = $dbh->quote($value); | ||||
5699 | $sql = $dbh->quote($value, $data_type); | ||||
5700 | |||||
5701 | Quote a string literal for use as a literal value in an SQL statement, | ||||
5702 | by escaping any special characters (such as quotation marks) | ||||
5703 | contained within the string and adding the required type of outer | ||||
5704 | quotation marks. | ||||
5705 | |||||
5706 | $sql = sprintf "SELECT foo FROM bar WHERE baz = %s", | ||||
5707 | $dbh->quote("Don't"); | ||||
5708 | |||||
5709 | For most database types, at least those that conform to SQL standards, quote | ||||
5710 | would return C<'Don''t'> (including the outer quotation marks). For others it | ||||
5711 | may return something like C<'Don\'t'> | ||||
5712 | |||||
5713 | An undefined C<$value> value will be returned as the string C<NULL> (without | ||||
5714 | single quotation marks) to match how NULLs are represented in SQL. | ||||
5715 | |||||
5716 | If C<$data_type> is supplied, it is used to try to determine the required | ||||
5717 | quoting behaviour by using the information returned by L</type_info>. | ||||
5718 | As a special case, the standard numeric types are optimized to return | ||||
5719 | C<$value> without calling C<type_info>. | ||||
5720 | |||||
5721 | Quote will probably I<not> be able to deal with all possible input | ||||
5722 | (such as binary data or data containing newlines), and is not related in | ||||
5723 | any way with escaping or quoting shell meta-characters. | ||||
5724 | |||||
5725 | It is valid for the quote() method to return an SQL expression that | ||||
5726 | evaluates to the desired string. For example: | ||||
5727 | |||||
5728 | $quoted = $dbh->quote("one\ntwo\0three") | ||||
5729 | |||||
5730 | may return something like: | ||||
5731 | |||||
5732 | CONCAT('one', CHAR(12), 'two', CHAR(0), 'three') | ||||
5733 | |||||
5734 | The quote() method should I<not> be used with L</"Placeholders and | ||||
5735 | Bind Values">. | ||||
5736 | |||||
5737 | =head3 C<quote_identifier> | ||||
5738 | |||||
5739 | $sql = $dbh->quote_identifier( $name ); | ||||
5740 | $sql = $dbh->quote_identifier( $catalog, $schema, $table, \%attr ); | ||||
5741 | |||||
5742 | Quote an identifier (table name etc.) for use in an SQL statement, | ||||
5743 | by escaping any special characters (such as double quotation marks) | ||||
5744 | it contains and adding the required type of outer quotation marks. | ||||
5745 | |||||
5746 | Undefined names are ignored and the remainder are quoted and then | ||||
5747 | joined together, typically with a dot (C<.>) character. For example: | ||||
5748 | |||||
5749 | $id = $dbh->quote_identifier( undef, 'Her schema', 'My table' ); | ||||
5750 | |||||
5751 | would, for most database types, return C<"Her schema"."My table"> | ||||
5752 | (including all the double quotation marks). | ||||
5753 | |||||
5754 | If three names are supplied then the first is assumed to be a | ||||
5755 | catalog name and special rules may be applied based on what L</get_info> | ||||
5756 | returns for SQL_CATALOG_NAME_SEPARATOR (41) and SQL_CATALOG_LOCATION (114). | ||||
5757 | For example, for Oracle: | ||||
5758 | |||||
5759 | $id = $dbh->quote_identifier( 'link', 'schema', 'table' ); | ||||
5760 | |||||
5761 | would return C<"schema"."table"@"link">. | ||||
5762 | |||||
5763 | =head3 C<take_imp_data> | ||||
5764 | |||||
5765 | $imp_data = $dbh->take_imp_data; | ||||
5766 | |||||
5767 | Leaves the $dbh in an almost dead, zombie-like, state and returns | ||||
5768 | a binary string of raw implementation data from the driver which | ||||
5769 | describes the current database connection. Effectively it detaches | ||||
5770 | the underlying database API connection data from the DBI handle. | ||||
5771 | After calling take_imp_data(), all other methods except C<DESTROY> | ||||
5772 | will generate a warning and return undef. | ||||
5773 | |||||
5774 | Why would you want to do this? You don't, forget I even mentioned it. | ||||
5775 | Unless, that is, you're implementing something advanced like a | ||||
5776 | multi-threaded connection pool. See L<DBI::Pool>. | ||||
5777 | |||||
5778 | The returned $imp_data can be passed as a C<dbi_imp_data> attribute | ||||
5779 | to a later connect() call, even in a separate thread in the same | ||||
5780 | process, where the driver can use it to 'adopt' the existing | ||||
5781 | connection that the implementation data was taken from. | ||||
5782 | |||||
5783 | Some things to keep in mind... | ||||
5784 | |||||
5785 | B<*> the $imp_data holds the only reference to the underlying | ||||
5786 | database API connection data. That connection is still 'live' and | ||||
5787 | won't be cleaned up properly unless the $imp_data is used to create | ||||
5788 | a new $dbh which is then allowed to disconnect() normally. | ||||
5789 | |||||
5790 | B<*> using the same $imp_data to create more than one other new | ||||
5791 | $dbh at a time may well lead to unpleasant problems. Don't do that. | ||||
5792 | |||||
5793 | Any child statement handles are effectively destroyed when take_imp_data() is | ||||
5794 | called. | ||||
5795 | |||||
5796 | The C<take_imp_data> method was added in DBI 1.36 but wasn't useful till 1.49. | ||||
5797 | |||||
5798 | |||||
5799 | =head2 Database Handle Attributes | ||||
5800 | |||||
5801 | This section describes attributes specific to database handles. | ||||
5802 | |||||
5803 | Changes to these database handle attributes do not affect any other | ||||
5804 | existing or future database handles. | ||||
5805 | |||||
5806 | Attempting to set or get the value of an unknown attribute generates a warning, | ||||
5807 | except for private driver-specific attributes (which all have names | ||||
5808 | starting with a lowercase letter). | ||||
5809 | |||||
5810 | Example: | ||||
5811 | |||||
5812 | $h->{AutoCommit} = ...; # set/write | ||||
5813 | ... = $h->{AutoCommit}; # get/read | ||||
5814 | |||||
5815 | =head3 C<AutoCommit> | ||||
5816 | |||||
5817 | Type: boolean | ||||
5818 | |||||
5819 | If true, then database changes cannot be rolled-back (undone). If false, | ||||
5820 | then database changes automatically occur within a "transaction", which | ||||
5821 | must either be committed or rolled back using the C<commit> or C<rollback> | ||||
5822 | methods. | ||||
5823 | |||||
5824 | Drivers should always default to C<AutoCommit> mode (an unfortunate | ||||
5825 | choice largely forced on the DBI by ODBC and JDBC conventions.) | ||||
5826 | |||||
5827 | Attempting to set C<AutoCommit> to an unsupported value is a fatal error. | ||||
5828 | This is an important feature of the DBI. Applications that need | ||||
5829 | full transaction behaviour can set C<$dbh-E<gt>{AutoCommit} = 0> (or | ||||
5830 | set C<AutoCommit> to 0 via L</connect>) | ||||
5831 | without having to check that the value was assigned successfully. | ||||
5832 | |||||
5833 | For the purposes of this description, we can divide databases into three | ||||
5834 | categories: | ||||
5835 | |||||
5836 | Databases which don't support transactions at all. | ||||
5837 | Databases in which a transaction is always active. | ||||
5838 | Databases in which a transaction must be explicitly started (C<'BEGIN WORK'>). | ||||
5839 | |||||
5840 | B<* Databases which don't support transactions at all> | ||||
5841 | |||||
5842 | For these databases, attempting to turn C<AutoCommit> off is a fatal error. | ||||
5843 | C<commit> and C<rollback> both issue warnings about being ineffective while | ||||
5844 | C<AutoCommit> is in effect. | ||||
5845 | |||||
5846 | B<* Databases in which a transaction is always active> | ||||
5847 | |||||
5848 | These are typically mainstream commercial relational databases with | ||||
5849 | "ANSI standard" transaction behaviour. | ||||
5850 | If C<AutoCommit> is off, then changes to the database won't have any | ||||
5851 | lasting effect unless L</commit> is called (but see also | ||||
5852 | L</disconnect>). If L</rollback> is called then any changes since the | ||||
5853 | last commit are undone. | ||||
5854 | |||||
5855 | If C<AutoCommit> is on, then the effect is the same as if the DBI | ||||
5856 | called C<commit> automatically after every successful database | ||||
5857 | operation. So calling C<commit> or C<rollback> explicitly while | ||||
5858 | C<AutoCommit> is on would be ineffective because the changes would | ||||
5859 | have already been committed. | ||||
5860 | |||||
5861 | Changing C<AutoCommit> from off to on will trigger a L</commit>. | ||||
5862 | |||||
5863 | For databases which don't support a specific auto-commit mode, the | ||||
5864 | driver has to commit each statement automatically using an explicit | ||||
5865 | C<COMMIT> after it completes successfully (and roll it back using an | ||||
5866 | explicit C<ROLLBACK> if it fails). The error information reported to the | ||||
5867 | application will correspond to the statement which was executed, unless | ||||
5868 | it succeeded and the commit or rollback failed. | ||||
5869 | |||||
5870 | B<* Databases in which a transaction must be explicitly started> | ||||
5871 | |||||
5872 | For these databases, the intention is to have them act like databases in | ||||
5873 | which a transaction is always active (as described above). | ||||
5874 | |||||
5875 | To do this, the driver will automatically begin an explicit transaction | ||||
5876 | when C<AutoCommit> is turned off, or after a L</commit> or | ||||
5877 | L</rollback> (or when the application issues the next database | ||||
5878 | operation after one of those events). | ||||
5879 | |||||
5880 | In this way, the application does not have to treat these databases | ||||
5881 | as a special case. | ||||
5882 | |||||
5883 | See L</commit>, L</disconnect> and L</Transactions> for other important | ||||
5884 | notes about transactions. | ||||
5885 | |||||
5886 | |||||
5887 | =head3 C<Driver> | ||||
5888 | |||||
5889 | Type: handle | ||||
5890 | |||||
5891 | Holds the handle of the parent driver. The only recommended use for this | ||||
5892 | is to find the name of the driver using: | ||||
5893 | |||||
5894 | $dbh->{Driver}->{Name} | ||||
5895 | |||||
5896 | |||||
5897 | =head3 C<Name> | ||||
5898 | |||||
5899 | Type: string | ||||
5900 | |||||
5901 | Holds the "name" of the database. Usually (and recommended to be) the | ||||
5902 | same as the "C<dbi:DriverName:...>" string used to connect to the database, | ||||
5903 | but with the leading "C<dbi:DriverName:>" removed. | ||||
5904 | |||||
5905 | |||||
5906 | =head3 C<Statement> | ||||
5907 | |||||
5908 | Type: string, read-only | ||||
5909 | |||||
5910 | Returns the statement string passed to the most recent L</prepare> or | ||||
5911 | L</do> method called in this database handle, even if that method | ||||
5912 | failed. This is especially useful where C<RaiseError> is enabled and | ||||
5913 | the exception handler checks $@ and sees that a 'prepare' method call | ||||
5914 | failed. | ||||
5915 | |||||
5916 | |||||
5917 | =head3 C<RowCacheSize> | ||||
5918 | |||||
5919 | Type: integer | ||||
5920 | |||||
5921 | A hint to the driver indicating the size of the local row cache that the | ||||
5922 | application would like the driver to use for future C<SELECT> statements. | ||||
5923 | If a row cache is not implemented, then setting C<RowCacheSize> is ignored | ||||
5924 | and getting the value returns C<undef>. | ||||
5925 | |||||
5926 | Some C<RowCacheSize> values have special meaning, as follows: | ||||
5927 | |||||
5928 | 0 - Automatically determine a reasonable cache size for each C<SELECT> | ||||
5929 | 1 - Disable the local row cache | ||||
5930 | >1 - Cache this many rows | ||||
5931 | <0 - Cache as many rows that will fit into this much memory for each C<SELECT>. | ||||
5932 | |||||
5933 | Note that large cache sizes may require a very large amount of memory | ||||
5934 | (I<cached rows * maximum size of row>). Also, a large cache will cause | ||||
5935 | a longer delay not only for the first fetch, but also whenever the | ||||
5936 | cache needs refilling. | ||||
5937 | |||||
5938 | See also the L</RowsInCache> statement handle attribute. | ||||
5939 | |||||
5940 | =head3 C<Username> | ||||
5941 | |||||
5942 | Type: string | ||||
5943 | |||||
5944 | Returns the username used to connect to the database. | ||||
5945 | |||||
5946 | |||||
5947 | =head1 DBI STATEMENT HANDLE OBJECTS | ||||
5948 | |||||
5949 | This section lists the methods and attributes associated with DBI | ||||
5950 | statement handles. | ||||
5951 | |||||
5952 | =head2 Statement Handle Methods | ||||
5953 | |||||
5954 | The DBI defines the following methods for use on DBI statement handles: | ||||
5955 | |||||
5956 | =head3 C<bind_param> | ||||
5957 | |||||
5958 | $sth->bind_param($p_num, $bind_value) | ||||
5959 | $sth->bind_param($p_num, $bind_value, \%attr) | ||||
5960 | $sth->bind_param($p_num, $bind_value, $bind_type) | ||||
5961 | |||||
5962 | The C<bind_param> method takes a copy of $bind_value and associates it | ||||
5963 | (binds it) with a placeholder, identified by $p_num, embedded in | ||||
5964 | the prepared statement. Placeholders are indicated with question | ||||
5965 | mark character (C<?>). For example: | ||||
5966 | |||||
5967 | $dbh->{RaiseError} = 1; # save having to check each method call | ||||
5968 | $sth = $dbh->prepare("SELECT name, age FROM people WHERE name LIKE ?"); | ||||
5969 | $sth->bind_param(1, "John%"); # placeholders are numbered from 1 | ||||
5970 | $sth->execute; | ||||
5971 | DBI::dump_results($sth); | ||||
5972 | |||||
5973 | See L</"Placeholders and Bind Values"> for more information. | ||||
5974 | |||||
5975 | |||||
5976 | B<Data Types for Placeholders> | ||||
5977 | |||||
5978 | The C<\%attr> parameter can be used to hint at the data type the | ||||
5979 | placeholder should have. This is rarely needed. Typically, the driver is only | ||||
5980 | interested in knowing if the placeholder should be bound as a number or a string. | ||||
5981 | |||||
5982 | $sth->bind_param(1, $value, { TYPE => SQL_INTEGER }); | ||||
5983 | |||||
5984 | As a short-cut for the common case, the data type can be passed | ||||
5985 | directly, in place of the C<\%attr> hash reference. This example is | ||||
5986 | equivalent to the one above: | ||||
5987 | |||||
5988 | $sth->bind_param(1, $value, SQL_INTEGER); | ||||
5989 | |||||
5990 | The C<TYPE> value indicates the standard (non-driver-specific) type for | ||||
5991 | this parameter. To specify the driver-specific type, the driver may | ||||
5992 | support a driver-specific attribute, such as C<{ ora_type =E<gt> 97 }>. | ||||
5993 | |||||
5994 | The SQL_INTEGER and other related constants can be imported using | ||||
5995 | |||||
5996 | use DBI qw(:sql_types); | ||||
5997 | |||||
5998 | See L</"DBI Constants"> for more information. | ||||
5999 | |||||
6000 | The data type is 'sticky' in that bind values passed to execute() are bound | ||||
6001 | with the data type specified by earlier bind_param() calls, if any. | ||||
6002 | Portable applications should not rely on being able to change the data type | ||||
6003 | after the first C<bind_param> call. | ||||
6004 | |||||
6005 | Perl only has string and number scalar data types. All database types | ||||
6006 | that aren't numbers are bound as strings and must be in a format the | ||||
6007 | database will understand except where the bind_param() TYPE attribute | ||||
6008 | specifies a type that implies a particular format. For example, given: | ||||
6009 | |||||
6010 | $sth->bind_param(1, $value, SQL_DATETIME); | ||||
6011 | |||||
6012 | the driver should expect $value to be in the ODBC standard SQL_DATETIME | ||||
6013 | format, which is 'YYYY-MM-DD HH:MM:SS'. Similarly for SQL_DATE, SQL_TIME etc. | ||||
6014 | |||||
6015 | As an alternative to specifying the data type in the C<bind_param> call, | ||||
6016 | you can let the driver pass the value as the default type (C<VARCHAR>). | ||||
6017 | You can then use an SQL function to convert the type within the statement. | ||||
6018 | For example: | ||||
6019 | |||||
6020 | INSERT INTO price(code, price) VALUES (?, CONVERT(MONEY,?)) | ||||
6021 | |||||
6022 | The C<CONVERT> function used here is just an example. The actual function | ||||
6023 | and syntax will vary between different databases and is non-portable. | ||||
6024 | |||||
6025 | See also L</"Placeholders and Bind Values"> for more information. | ||||
6026 | |||||
6027 | |||||
6028 | =head3 C<bind_param_inout> | ||||
6029 | |||||
6030 | $rc = $sth->bind_param_inout($p_num, \$bind_value, $max_len) or die $sth->errstr; | ||||
6031 | $rv = $sth->bind_param_inout($p_num, \$bind_value, $max_len, \%attr) or ... | ||||
6032 | $rv = $sth->bind_param_inout($p_num, \$bind_value, $max_len, $bind_type) or ... | ||||
6033 | |||||
6034 | This method acts like L</bind_param>, but also enables values to be | ||||
6035 | updated by the statement. The statement is typically | ||||
6036 | a call to a stored procedure. The C<$bind_value> must be passed as a | ||||
6037 | reference to the actual value to be used. | ||||
6038 | |||||
6039 | Note that unlike L</bind_param>, the C<$bind_value> variable is not | ||||
6040 | copied when C<bind_param_inout> is called. Instead, the value in the | ||||
6041 | variable is read at the time L</execute> is called. | ||||
6042 | |||||
6043 | The additional C<$max_len> parameter specifies the minimum amount of | ||||
6044 | memory to allocate to C<$bind_value> for the new value. If the value | ||||
6045 | returned from the database is too | ||||
6046 | big to fit, then the execution should fail. If unsure what value to use, | ||||
6047 | pick a generous length, i.e., a length larger than the longest value that would ever be | ||||
6048 | returned. The only cost of using a larger value than needed is wasted memory. | ||||
6049 | |||||
6050 | Undefined values or C<undef> are used to indicate null values. | ||||
6051 | See also L</"Placeholders and Bind Values"> for more information. | ||||
6052 | |||||
6053 | |||||
6054 | =head3 C<bind_param_array> | ||||
6055 | |||||
6056 | $rc = $sth->bind_param_array($p_num, $array_ref_or_value) | ||||
6057 | $rc = $sth->bind_param_array($p_num, $array_ref_or_value, \%attr) | ||||
6058 | $rc = $sth->bind_param_array($p_num, $array_ref_or_value, $bind_type) | ||||
6059 | |||||
6060 | The C<bind_param_array> method is used to bind an array of values | ||||
6061 | to a placeholder embedded in the prepared statement which is to be executed | ||||
6062 | with L</execute_array>. For example: | ||||
6063 | |||||
6064 | $dbh->{RaiseError} = 1; # save having to check each method call | ||||
6065 | $sth = $dbh->prepare("INSERT INTO staff (first_name, last_name, dept) VALUES(?, ?, ?)"); | ||||
6066 | $sth->bind_param_array(1, [ 'John', 'Mary', 'Tim' ]); | ||||
6067 | $sth->bind_param_array(2, [ 'Booth', 'Todd', 'Robinson' ]); | ||||
6068 | $sth->bind_param_array(3, "SALES"); # scalar will be reused for each row | ||||
6069 | $sth->execute_array( { ArrayTupleStatus => \my @tuple_status } ); | ||||
6070 | |||||
6071 | The C<%attr> ($bind_type) argument is the same as defined for L</bind_param>. | ||||
6072 | Refer to L</bind_param> for general details on using placeholders. | ||||
6073 | |||||
6074 | (Note that bind_param_array() can I<not> be used to expand a | ||||
6075 | placeholder into a list of values for a statement like "SELECT foo | ||||
6076 | WHERE bar IN (?)". A placeholder can only ever represent one value | ||||
6077 | per execution.) | ||||
6078 | |||||
6079 | Scalar values, including C<undef>, may also be bound by | ||||
6080 | C<bind_param_array>. In which case the same value will be used for each | ||||
6081 | L</execute> call. Driver-specific implementations may behave | ||||
6082 | differently, e.g., when binding to a stored procedure call, some | ||||
6083 | databases may permit mixing scalars and arrays as arguments. | ||||
6084 | |||||
6085 | The default implementation provided by DBI (for drivers that have | ||||
6086 | not implemented array binding) is to iteratively call L</execute> for | ||||
6087 | each parameter tuple provided in the bound arrays. Drivers may | ||||
6088 | provide more optimized implementations using whatever bulk operation | ||||
6089 | support the database API provides. The default driver behaviour should | ||||
6090 | match the default DBI behaviour, but always consult your driver | ||||
6091 | documentation as there may be driver specific issues to consider. | ||||
6092 | |||||
6093 | Note that the default implementation currently only supports non-data | ||||
6094 | returning statements (INSERT, UPDATE, but not SELECT). Also, | ||||
6095 | C<bind_param_array> and L</bind_param> cannot be mixed in the same | ||||
6096 | statement execution, and C<bind_param_array> must be used with | ||||
6097 | L</execute_array>; using C<bind_param_array> will have no effect | ||||
6098 | for L</execute>. | ||||
6099 | |||||
6100 | The C<bind_param_array> method was added in DBI 1.22. | ||||
6101 | |||||
6102 | =head3 C<execute> | ||||
6103 | |||||
6104 | $rv = $sth->execute or die $sth->errstr; | ||||
6105 | $rv = $sth->execute(@bind_values) or die $sth->errstr; | ||||
6106 | |||||
6107 | Perform whatever processing is necessary to execute the prepared | ||||
6108 | statement. An C<undef> is returned if an error occurs. A successful | ||||
6109 | C<execute> always returns true regardless of the number of rows affected, | ||||
6110 | even if it's zero (see below). It is always important to check the | ||||
6111 | return status of C<execute> (and most other DBI methods) for errors | ||||
6112 | if you're not using L</RaiseError>. | ||||
6113 | |||||
6114 | For a I<non>-C<SELECT> statement, C<execute> returns the number of rows | ||||
6115 | affected, if known. If no rows were affected, then C<execute> returns | ||||
6116 | "C<0E0>", which Perl will treat as 0 but will regard as true. Note that it | ||||
6117 | is I<not> an error for no rows to be affected by a statement. If the | ||||
6118 | number of rows affected is not known, then C<execute> returns -1. | ||||
6119 | |||||
6120 | For C<SELECT> statements, execute simply "starts" the query within the | ||||
6121 | database engine. Use one of the fetch methods to retrieve the data after | ||||
6122 | calling C<execute>. The C<execute> method does I<not> return the number of | ||||
6123 | rows that will be returned by the query (because most databases can't | ||||
6124 | tell in advance), it simply returns a true value. | ||||
6125 | |||||
6126 | You can tell if the statement was a C<SELECT> statement by checking if | ||||
6127 | C<$sth-E<gt>{NUM_OF_FIELDS}> is greater than zero after calling C<execute>. | ||||
6128 | |||||
6129 | If any arguments are given, then C<execute> will effectively call | ||||
6130 | L</bind_param> for each value before executing the statement. Values | ||||
6131 | bound in this way are usually treated as C<SQL_VARCHAR> types unless | ||||
6132 | the driver can determine the correct type (which is rare), or unless | ||||
6133 | C<bind_param> (or C<bind_param_inout>) has already been used to | ||||
6134 | specify the type. | ||||
6135 | |||||
6136 | Note that passing C<execute> an empty array is the same as passing no arguments | ||||
6137 | at all, which will execute the statement with previously bound values. | ||||
6138 | That's probably not what you want. | ||||
6139 | |||||
6140 | If execute() is called on a statement handle that's still active | ||||
6141 | ($sth->{Active} is true) then it should effectively call finish() | ||||
6142 | to tidy up the previous execution results before starting this new | ||||
6143 | execution. | ||||
6144 | |||||
6145 | =head3 C<execute_array> | ||||
6146 | |||||
6147 | $tuples = $sth->execute_array(\%attr) or die $sth->errstr; | ||||
6148 | $tuples = $sth->execute_array(\%attr, @bind_values) or die $sth->errstr; | ||||
6149 | |||||
6150 | ($tuples, $rows) = $sth->execute_array(\%attr) or die $sth->errstr; | ||||
6151 | ($tuples, $rows) = $sth->execute_array(\%attr, @bind_values) or die $sth->errstr; | ||||
6152 | |||||
6153 | Execute the prepared statement once for each parameter tuple | ||||
6154 | (group of values) provided either in the @bind_values, or by prior | ||||
6155 | calls to L</bind_param_array>, or via a reference passed in \%attr. | ||||
6156 | |||||
6157 | When called in scalar context the execute_array() method returns the | ||||
6158 | number of tuples executed, or C<undef> if an error occurred. Like | ||||
6159 | execute(), a successful execute_array() always returns true regardless | ||||
6160 | of the number of tuples executed, even if it's zero. If there were any | ||||
6161 | errors the ArrayTupleStatus array can be used to discover which tuples | ||||
6162 | failed and with what errors. | ||||
6163 | |||||
6164 | When called in list context the execute_array() method returns two scalars; | ||||
6165 | $tuples is the same as calling execute_array() in scalar context and $rows is | ||||
6166 | the number of rows affected for each tuple, if available or | ||||
6167 | -1 if the driver cannot determine this. NOTE, some drivers cannot determine | ||||
6168 | the number of rows affected per tuple but can provide the number of rows | ||||
6169 | affected for the batch. | ||||
6170 | If you are doing an update operation the returned rows affected may not be what | ||||
6171 | you expect if, for instance, one or more of the tuples affected the same row | ||||
6172 | multiple times. Some drivers may not yet support list context, in which case | ||||
6173 | $rows will be undef, or may not be able to provide the number of rows affected | ||||
6174 | when performing this batch operation, in which case $rows will be -1. | ||||
6175 | |||||
6176 | Bind values for the tuples to be executed may be supplied row-wise | ||||
6177 | by an C<ArrayTupleFetch> attribute, or else column-wise in the | ||||
6178 | C<@bind_values> argument, or else column-wise by prior calls to | ||||
6179 | L</bind_param_array>. | ||||
6180 | |||||
6181 | Where column-wise binding is used (via the C<@bind_values> argument | ||||
6182 | or calls to bind_param_array()) the maximum number of elements in | ||||
6183 | any one of the bound value arrays determines the number of tuples | ||||
6184 | executed. Placeholders with fewer values in their parameter arrays | ||||
6185 | are treated as if padded with undef (NULL) values. | ||||
6186 | |||||
6187 | If a scalar value is bound, instead of an array reference, it is | ||||
6188 | treated as a I<variable> length array with all elements having the | ||||
6189 | same value. It does not influence the number of tuples executed, | ||||
6190 | so if all bound arrays have zero elements then zero tuples will | ||||
6191 | be executed. If I<all> bound values are scalars then one tuple | ||||
6192 | will be executed, making execute_array() act just like execute(). | ||||
6193 | |||||
6194 | The C<ArrayTupleFetch> attribute can be used to specify a reference | ||||
6195 | to a subroutine that will be called to provide the bind values for | ||||
6196 | each tuple execution. The subroutine should return an reference to | ||||
6197 | an array which contains the appropriate number of bind values, or | ||||
6198 | return an undef if there is no more data to execute. | ||||
6199 | |||||
6200 | As a convenience, the C<ArrayTupleFetch> attribute can also be | ||||
6201 | used to specify a statement handle. In which case the fetchrow_arrayref() | ||||
6202 | method will be called on the given statement handle in order to | ||||
6203 | provide the bind values for each tuple execution. | ||||
6204 | |||||
6205 | The values specified via bind_param_array() or the @bind_values | ||||
6206 | parameter may be either scalars, or arrayrefs. If any C<@bind_values> | ||||
6207 | are given, then C<execute_array> will effectively call L</bind_param_array> | ||||
6208 | for each value before executing the statement. Values bound in | ||||
6209 | this way are usually treated as C<SQL_VARCHAR> types unless the | ||||
6210 | driver can determine the correct type (which is rare), or unless | ||||
6211 | C<bind_param>, C<bind_param_inout>, C<bind_param_array>, or | ||||
6212 | C<bind_param_inout_array> has already been used to specify the type. | ||||
6213 | See L</bind_param_array> for details. | ||||
6214 | |||||
6215 | The C<ArrayTupleStatus> attribute can be used to specify a | ||||
6216 | reference to an array which will receive the execute status of each | ||||
6217 | executed parameter tuple. Note the C<ArrayTupleStatus> attribute was | ||||
6218 | mandatory until DBI 1.38. | ||||
6219 | |||||
6220 | For tuples which are successfully executed, the element at the same | ||||
6221 | ordinal position in the status array is the resulting rowcount (or -1 | ||||
6222 | if unknown). | ||||
6223 | If the execution of a tuple causes an error, then the corresponding | ||||
6224 | status array element will be set to a reference to an array containing | ||||
6225 | L</err>, L</errstr> and L</state> set by the failed execution. | ||||
6226 | |||||
6227 | If B<any> tuple execution returns an error, C<execute_array> will | ||||
6228 | return C<undef>. In that case, the application should inspect the | ||||
6229 | status array to determine which parameter tuples failed. | ||||
6230 | Some databases may not continue executing tuples beyond the first | ||||
6231 | failure. In this case the status array will either hold fewer | ||||
6232 | elements, or the elements beyond the failure will be undef. | ||||
6233 | |||||
6234 | If all parameter tuples are successfully executed, C<execute_array> | ||||
6235 | returns the number tuples executed. If no tuples were executed, | ||||
6236 | then execute_array() returns "C<0E0>", just like execute() does, | ||||
6237 | which Perl will treat as 0 but will regard as true. | ||||
6238 | |||||
6239 | For example: | ||||
6240 | |||||
6241 | $sth = $dbh->prepare("INSERT INTO staff (first_name, last_name) VALUES (?, ?)"); | ||||
6242 | my $tuples = $sth->execute_array( | ||||
6243 | { ArrayTupleStatus => \my @tuple_status }, | ||||
6244 | \@first_names, | ||||
6245 | \@last_names, | ||||
6246 | ); | ||||
6247 | if ($tuples) { | ||||
6248 | print "Successfully inserted $tuples records\n"; | ||||
6249 | } | ||||
6250 | else { | ||||
6251 | for my $tuple (0..@last_names-1) { | ||||
6252 | my $status = $tuple_status[$tuple]; | ||||
6253 | $status = [0, "Skipped"] unless defined $status; | ||||
6254 | next unless ref $status; | ||||
6255 | printf "Failed to insert (%s, %s): %s\n", | ||||
6256 | $first_names[$tuple], $last_names[$tuple], $status->[1]; | ||||
6257 | } | ||||
6258 | } | ||||
6259 | |||||
6260 | Support for data returning statements such as SELECT is driver-specific | ||||
6261 | and subject to change. At present, the default implementation | ||||
6262 | provided by DBI only supports non-data returning statements. | ||||
6263 | |||||
6264 | Transaction semantics when using array binding are driver and | ||||
6265 | database specific. If C<AutoCommit> is on, the default DBI | ||||
6266 | implementation will cause each parameter tuple to be individually | ||||
6267 | committed (or rolled back in the event of an error). If C<AutoCommit> | ||||
6268 | is off, the application is responsible for explicitly committing | ||||
6269 | the entire set of bound parameter tuples. Note that different | ||||
6270 | drivers and databases may have different behaviours when some | ||||
6271 | parameter tuples cause failures. In some cases, the driver or | ||||
6272 | database may automatically rollback the effect of all prior parameter | ||||
6273 | tuples that succeeded in the transaction; other drivers or databases | ||||
6274 | may retain the effect of prior successfully executed parameter | ||||
6275 | tuples. Be sure to check your driver and database for its specific | ||||
6276 | behaviour. | ||||
6277 | |||||
6278 | Note that, in general, performance will usually be better with | ||||
6279 | C<AutoCommit> turned off, and using explicit C<commit> after each | ||||
6280 | C<execute_array> call. | ||||
6281 | |||||
6282 | The C<execute_array> method was added in DBI 1.22, and ArrayTupleFetch | ||||
6283 | was added in 1.36. | ||||
6284 | |||||
6285 | =head3 C<execute_for_fetch> | ||||
6286 | |||||
6287 | $tuples = $sth->execute_for_fetch($fetch_tuple_sub); | ||||
6288 | $tuples = $sth->execute_for_fetch($fetch_tuple_sub, \@tuple_status); | ||||
6289 | |||||
6290 | ($tuples, $rows) = $sth->execute_for_fetch($fetch_tuple_sub); | ||||
6291 | ($tuples, $rows) = $sth->execute_for_fetch($fetch_tuple_sub, \@tuple_status); | ||||
6292 | |||||
6293 | The execute_for_fetch() method is used to perform bulk operations and | ||||
6294 | although it is most often used via the execute_array() method you can | ||||
6295 | use it directly. The main difference between execute_array and | ||||
6296 | execute_for_fetch is the former does column or row-wise binding and | ||||
6297 | the latter uses row-wise binding. | ||||
6298 | |||||
6299 | The fetch subroutine, referenced by $fetch_tuple_sub, is expected | ||||
6300 | to return a reference to an array (known as a 'tuple') or undef. | ||||
6301 | |||||
6302 | The execute_for_fetch() method calls $fetch_tuple_sub, without any | ||||
6303 | parameters, until it returns a false value. Each tuple returned is | ||||
6304 | used to provide bind values for an $sth->execute(@$tuple) call. | ||||
6305 | |||||
6306 | In scalar context execute_for_fetch() returns C<undef> if there were any | ||||
6307 | errors and the number of tuples executed otherwise. Like execute() and | ||||
6308 | execute_array() a zero is returned as "0E0" so execute_for_fetch() is | ||||
6309 | only false on error. If there were any errors the @tuple_status array | ||||
6310 | can be used to discover which tuples failed and with what errors. | ||||
6311 | |||||
6312 | When called in list context execute_for_fetch() returns two scalars; | ||||
6313 | $tuples is the same as calling execute_for_fetch() in scalar context and $rows is | ||||
6314 | the sum of the number of rows affected for each tuple, if available or -1 | ||||
6315 | if the driver cannot determine this. | ||||
6316 | If you are doing an update operation the returned rows affected may not be what | ||||
6317 | you expect if, for instance, one or more of the tuples affected the same row | ||||
6318 | multiple times. Some drivers may not yet support list context, in which case | ||||
6319 | $rows will be undef, or may not be able to provide the number of rows affected | ||||
6320 | when performing this batch operation, in which case $rows will be -1. | ||||
6321 | |||||
6322 | If \@tuple_status is passed then the execute_for_fetch method uses | ||||
6323 | it to return status information. The tuple_status array holds one | ||||
6324 | element per tuple. If the corresponding execute() did not fail then | ||||
6325 | the element holds the return value from execute(), which is typically | ||||
6326 | a row count. If the execute() did fail then the element holds a | ||||
6327 | reference to an array containing ($sth->err, $sth->errstr, $sth->state). | ||||
6328 | |||||
6329 | If the driver detects an error that it knows means no further tuples can be | ||||
6330 | executed then it may return, with an error status, even though $fetch_tuple_sub | ||||
6331 | may still have more tuples to be executed. | ||||
6332 | |||||
6333 | Although each tuple returned by $fetch_tuple_sub is effectively used | ||||
6334 | to call $sth->execute(@$tuple_array_ref) the exact timing may vary. | ||||
6335 | Drivers are free to accumulate sets of tuples to pass to the | ||||
6336 | database server in bulk group operations for more efficient execution. | ||||
6337 | However, the $fetch_tuple_sub is specifically allowed to return | ||||
6338 | the same array reference each time (which is what fetchrow_arrayref() | ||||
6339 | usually does). | ||||
6340 | |||||
6341 | For example: | ||||
6342 | |||||
6343 | my $sel = $dbh1->prepare("select foo, bar from table1"); | ||||
6344 | $sel->execute; | ||||
6345 | |||||
6346 | my $ins = $dbh2->prepare("insert into table2 (foo, bar) values (?,?)"); | ||||
6347 | my $fetch_tuple_sub = sub { $sel->fetchrow_arrayref }; | ||||
6348 | |||||
6349 | my @tuple_status; | ||||
6350 | $rc = $ins->execute_for_fetch($fetch_tuple_sub, \@tuple_status); | ||||
6351 | my @errors = grep { ref $_ } @tuple_status; | ||||
6352 | |||||
6353 | Similarly, if you already have an array containing the data rows | ||||
6354 | to be processed you'd use a subroutine to shift off and return | ||||
6355 | each array ref in turn: | ||||
6356 | |||||
6357 | $ins->execute_for_fetch( sub { shift @array_of_arrays }, \@tuple_status); | ||||
6358 | |||||
6359 | The C<execute_for_fetch> method was added in DBI 1.38. | ||||
6360 | |||||
6361 | |||||
6362 | =head3 C<fetchrow_arrayref> | ||||
6363 | |||||
6364 | $ary_ref = $sth->fetchrow_arrayref; | ||||
6365 | $ary_ref = $sth->fetch; # alias | ||||
6366 | |||||
6367 | Fetches the next row of data and returns a reference to an array | ||||
6368 | holding the field values. Null fields are returned as C<undef> | ||||
6369 | values in the array. | ||||
6370 | This is the fastest way to fetch data, particularly if used with | ||||
6371 | C<$sth-E<gt>bind_columns>. | ||||
6372 | |||||
6373 | If there are no more rows or if an error occurs, then C<fetchrow_arrayref> | ||||
6374 | returns an C<undef>. You should check C<$sth-E<gt>err> afterwards (or use the | ||||
6375 | C<RaiseError> attribute) to discover if the C<undef> returned was due to an | ||||
6376 | error. | ||||
6377 | |||||
6378 | Note that the same array reference is returned for each fetch, so don't | ||||
6379 | store the reference and then use it after a later fetch. Also, the | ||||
6380 | elements of the array are also reused for each row, so take care if you | ||||
6381 | want to take a reference to an element. See also L</bind_columns>. | ||||
6382 | |||||
6383 | =head3 C<fetchrow_array> | ||||
6384 | |||||
6385 | @ary = $sth->fetchrow_array; | ||||
6386 | |||||
6387 | An alternative to C<fetchrow_arrayref>. Fetches the next row of data | ||||
6388 | and returns it as a list containing the field values. Null fields | ||||
6389 | are returned as C<undef> values in the list. | ||||
6390 | |||||
6391 | If there are no more rows or if an error occurs, then C<fetchrow_array> | ||||
6392 | returns an empty list. You should check C<$sth-E<gt>err> afterwards (or use | ||||
6393 | the C<RaiseError> attribute) to discover if the empty list returned was | ||||
6394 | due to an error. | ||||
6395 | |||||
6396 | If called in a scalar context for a statement handle that has more | ||||
6397 | than one column, it is undefined whether the driver will return | ||||
6398 | the value of the first column or the last. So don't do that. | ||||
6399 | Also, in a scalar context, an C<undef> is returned if there are no | ||||
6400 | more rows or if an error occurred. That C<undef> can't be distinguished | ||||
6401 | from an C<undef> returned because the first field value was NULL. | ||||
6402 | For these reasons you should exercise some caution if you use | ||||
6403 | C<fetchrow_array> in a scalar context. | ||||
6404 | |||||
6405 | =head3 C<fetchrow_hashref> | ||||
6406 | |||||
6407 | $hash_ref = $sth->fetchrow_hashref; | ||||
6408 | $hash_ref = $sth->fetchrow_hashref($name); | ||||
6409 | |||||
6410 | An alternative to C<fetchrow_arrayref>. Fetches the next row of data | ||||
6411 | and returns it as a reference to a hash containing field name and field | ||||
6412 | value pairs. Null fields are returned as C<undef> values in the hash. | ||||
6413 | |||||
6414 | If there are no more rows or if an error occurs, then C<fetchrow_hashref> | ||||
6415 | returns an C<undef>. You should check C<$sth-E<gt>err> afterwards (or use the | ||||
6416 | C<RaiseError> attribute) to discover if the C<undef> returned was due to an | ||||
6417 | error. | ||||
6418 | |||||
6419 | The optional C<$name> parameter specifies the name of the statement handle | ||||
6420 | attribute. For historical reasons it defaults to "C<NAME>", however using | ||||
6421 | either "C<NAME_lc>" or "C<NAME_uc>" is recommended for portability. | ||||
6422 | |||||
6423 | The keys of the hash are the same names returned by C<$sth-E<gt>{$name}>. If | ||||
6424 | more than one field has the same name, there will only be one entry in the | ||||
6425 | returned hash for those fields, so statements like "C<select foo, foo from bar>" | ||||
6426 | will return only a single key from C<fetchrow_hashref>. In these cases use | ||||
6427 | column aliases or C<fetchrow_arrayref>. Note that it is the database server | ||||
6428 | (and not the DBD implementation) which provides the I<name> for fields | ||||
6429 | containing functions like "C<count(*)>" or "C<max(c_foo)>" and they may clash | ||||
6430 | with existing column names (most databases don't care about duplicate column | ||||
6431 | names in a result-set). If you want these to return as unique names that are | ||||
6432 | the same across databases, use I<aliases>, as in "C<select count(*) as cnt>" | ||||
6433 | or "C<select max(c_foo) mx_foo, ...>" depending on the syntax your database | ||||
6434 | supports. | ||||
6435 | |||||
6436 | Because of the extra work C<fetchrow_hashref> and Perl have to perform, it | ||||
6437 | is not as efficient as C<fetchrow_arrayref> or C<fetchrow_array>. | ||||
6438 | |||||
6439 | By default a reference to a new hash is returned for each row. | ||||
6440 | It is likely that a future version of the DBI will support an | ||||
6441 | attribute which will enable the same hash to be reused for each | ||||
6442 | row. This will give a significant performance boost, but it won't | ||||
6443 | be enabled by default because of the risk of breaking old code. | ||||
6444 | |||||
6445 | |||||
6446 | =head3 C<fetchall_arrayref> | ||||
6447 | |||||
6448 | $tbl_ary_ref = $sth->fetchall_arrayref; | ||||
6449 | $tbl_ary_ref = $sth->fetchall_arrayref( $slice ); | ||||
6450 | $tbl_ary_ref = $sth->fetchall_arrayref( $slice, $max_rows ); | ||||
6451 | |||||
6452 | The C<fetchall_arrayref> method can be used to fetch all the data to be | ||||
6453 | returned from a prepared and executed statement handle. It returns a | ||||
6454 | reference to an array that contains one reference per row. | ||||
6455 | |||||
6456 | If called on an I<inactive> statement handle, C<fetchall_arrayref> returns undef. | ||||
6457 | |||||
6458 | If there are no rows left to return from an I<active> statement handle, C<fetchall_arrayref> returns a reference | ||||
6459 | to an empty array. If an error occurs, C<fetchall_arrayref> returns the | ||||
6460 | data fetched thus far, which may be none. You should check C<$sth-E<gt>err> | ||||
6461 | afterwards (or use the C<RaiseError> attribute) to discover if the data is | ||||
6462 | complete or was truncated due to an error. | ||||
6463 | |||||
6464 | If $slice is an array reference, C<fetchall_arrayref> uses L</fetchrow_arrayref> | ||||
6465 | to fetch each row as an array ref. If the $slice array is not empty | ||||
6466 | then it is used as a slice to select individual columns by perl array | ||||
6467 | index number (starting at 0, unlike column and parameter numbers which | ||||
6468 | start at 1). | ||||
6469 | |||||
6470 | With no parameters, or if $slice is undefined, C<fetchall_arrayref> | ||||
6471 | acts as if passed an empty array ref. | ||||
6472 | |||||
6473 | For example, to fetch just the first column of every row: | ||||
6474 | |||||
6475 | $tbl_ary_ref = $sth->fetchall_arrayref([0]); | ||||
6476 | |||||
6477 | To fetch the second to last and last column of every row: | ||||
6478 | |||||
6479 | $tbl_ary_ref = $sth->fetchall_arrayref([-2,-1]); | ||||
6480 | |||||
6481 | Those two examples both return a reference to an array of array refs. | ||||
6482 | |||||
6483 | If $slice is a hash reference, C<fetchall_arrayref> fetches each row as a hash | ||||
6484 | reference. If the $slice hash is empty then the keys in the hashes have | ||||
6485 | whatever name lettercase is returned by default. (See L</FetchHashKeyName> | ||||
6486 | attribute.) If the $slice hash is I<not> empty, then it is used as a slice to | ||||
6487 | select individual columns by name. The values of the hash should be set to 1. | ||||
6488 | The key names of the returned hashes match the letter case of the names in the | ||||
6489 | parameter hash, regardless of the L</FetchHashKeyName> attribute. | ||||
6490 | |||||
6491 | For example, to fetch all fields of every row as a hash ref: | ||||
6492 | |||||
6493 | $tbl_ary_ref = $sth->fetchall_arrayref({}); | ||||
6494 | |||||
6495 | To fetch only the fields called "foo" and "bar" of every row as a hash ref | ||||
6496 | (with keys named "foo" and "BAR", regardless of the original capitalization): | ||||
6497 | |||||
6498 | $tbl_ary_ref = $sth->fetchall_arrayref({ foo=>1, BAR=>1 }); | ||||
6499 | |||||
6500 | Those two examples both return a reference to an array of hash refs. | ||||
6501 | |||||
6502 | If $slice is a I<reference to a hash reference>, that hash is used to select | ||||
6503 | and rename columns. The keys are 0-based column index numbers and the values | ||||
6504 | are the corresponding keys for the returned row hashes. | ||||
6505 | |||||
6506 | For example, to fetch only the first and second columns of every row as a hash | ||||
6507 | ref (with keys named "k" and "v" regardless of their original names): | ||||
6508 | |||||
6509 | $tbl_ary_ref = $sth->fetchall_arrayref( \{ 0 => 'k', 1 => 'v' } ); | ||||
6510 | |||||
6511 | If $max_rows is defined and greater than or equal to zero then it | ||||
6512 | is used to limit the number of rows fetched before returning. | ||||
6513 | fetchall_arrayref() can then be called again to fetch more rows. | ||||
6514 | This is especially useful when you need the better performance of | ||||
6515 | fetchall_arrayref() but don't have enough memory to fetch and return | ||||
6516 | all the rows in one go. | ||||
6517 | |||||
6518 | Here's an example (assumes RaiseError is enabled): | ||||
6519 | |||||
6520 | my $rows = []; # cache for batches of rows | ||||
6521 | while( my $row = ( shift(@$rows) || # get row from cache, or reload cache: | ||||
6522 | shift(@{$rows=$sth->fetchall_arrayref(undef,10_000)||[]}) ) | ||||
6523 | ) { | ||||
6524 | ... | ||||
6525 | } | ||||
6526 | |||||
6527 | That I<might> be the fastest way to fetch and process lots of rows using the DBI, | ||||
6528 | but it depends on the relative cost of method calls vs memory allocation. | ||||
6529 | |||||
6530 | A standard C<while> loop with column binding is often faster because | ||||
6531 | the cost of allocating memory for the batch of rows is greater than | ||||
6532 | the saving by reducing method calls. It's possible that the DBI may | ||||
6533 | provide a way to reuse the memory of a previous batch in future, which | ||||
6534 | would then shift the balance back towards fetchall_arrayref(). | ||||
6535 | |||||
6536 | |||||
6537 | =head3 C<fetchall_hashref> | ||||
6538 | |||||
6539 | $hash_ref = $sth->fetchall_hashref($key_field); | ||||
6540 | |||||
6541 | The C<fetchall_hashref> method can be used to fetch all the data to be | ||||
6542 | returned from a prepared and executed statement handle. It returns a reference | ||||
6543 | to a hash containing a key for each distinct value of the $key_field column | ||||
6544 | that was fetched. For each key the corresponding value is a reference to a hash | ||||
6545 | containing all the selected columns and their values, as returned by | ||||
6546 | C<fetchrow_hashref()>. | ||||
6547 | |||||
6548 | If there are no rows to return, C<fetchall_hashref> returns a reference | ||||
6549 | to an empty hash. If an error occurs, C<fetchall_hashref> returns the | ||||
6550 | data fetched thus far, which may be none. You should check | ||||
6551 | C<$sth-E<gt>err> afterwards (or use the C<RaiseError> attribute) to | ||||
6552 | discover if the data is complete or was truncated due to an error. | ||||
6553 | |||||
6554 | The $key_field parameter provides the name of the field that holds the | ||||
6555 | value to be used for the key for the returned hash. For example: | ||||
6556 | |||||
6557 | $dbh->{FetchHashKeyName} = 'NAME_lc'; | ||||
6558 | $sth = $dbh->prepare("SELECT FOO, BAR, ID, NAME, BAZ FROM TABLE"); | ||||
6559 | $sth->execute; | ||||
6560 | $hash_ref = $sth->fetchall_hashref('id'); | ||||
6561 | print "Name for id 42 is $hash_ref->{42}->{name}\n"; | ||||
6562 | |||||
6563 | The $key_field parameter can also be specified as an integer column | ||||
6564 | number (counting from 1). If $key_field doesn't match any column in | ||||
6565 | the statement, as a name first then as a number, then an error is | ||||
6566 | returned. | ||||
6567 | |||||
6568 | For queries returning more than one 'key' column, you can specify | ||||
6569 | multiple column names by passing $key_field as a reference to an | ||||
6570 | array containing one or more key column names (or index numbers). | ||||
6571 | For example: | ||||
6572 | |||||
6573 | $sth = $dbh->prepare("SELECT foo, bar, baz FROM table"); | ||||
6574 | $sth->execute; | ||||
6575 | $hash_ref = $sth->fetchall_hashref( [ qw(foo bar) ] ); | ||||
6576 | print "For foo 42 and bar 38, baz is $hash_ref->{42}->{38}->{baz}\n"; | ||||
6577 | |||||
6578 | The fetchall_hashref() method is normally used only where the key | ||||
6579 | fields values for each row are unique. If multiple rows are returned | ||||
6580 | with the same values for the key fields then later rows overwrite | ||||
6581 | earlier ones. | ||||
6582 | |||||
6583 | =head3 C<finish> | ||||
6584 | |||||
6585 | $rc = $sth->finish; | ||||
6586 | |||||
6587 | Indicate that no more data will be fetched from this statement handle | ||||
6588 | before it is either executed again or destroyed. You almost certainly | ||||
6589 | do I<not> need to call this method. | ||||
6590 | |||||
6591 | Adding calls to C<finish> after loop that fetches all rows is a common mistake, | ||||
6592 | don't do it, it can mask genuine problems like uncaught fetch errors. | ||||
6593 | |||||
6594 | When all the data has been fetched from a C<SELECT> statement, the driver will | ||||
6595 | automatically call C<finish> for you. So you should I<not> call it explicitly | ||||
6596 | I<except> when you know that you've not fetched all the data from a statement | ||||
6597 | handle I<and> the handle won't be destroyed soon. | ||||
6598 | |||||
6599 | The most common example is when you only want to fetch just one row, | ||||
6600 | but in that case the C<selectrow_*> methods are usually better anyway. | ||||
6601 | |||||
6602 | Consider a query like: | ||||
6603 | |||||
6604 | SELECT foo FROM table WHERE bar=? ORDER BY baz | ||||
6605 | |||||
6606 | on a very large table. When executed, the database server will have to use | ||||
6607 | temporary buffer space to store the sorted rows. If, after executing | ||||
6608 | the handle and selecting just a few rows, the handle won't be re-executed for | ||||
6609 | some time and won't be destroyed, the C<finish> method can be used to tell | ||||
6610 | the server that the buffer space can be freed. | ||||
6611 | |||||
6612 | Calling C<finish> resets the L</Active> attribute for the statement. It | ||||
6613 | may also make some statement handle attributes (such as C<NAME> and C<TYPE>) | ||||
6614 | unavailable if they have not already been accessed (and thus cached). | ||||
6615 | |||||
6616 | The C<finish> method does not affect the transaction status of the | ||||
6617 | database connection. It has nothing to do with transactions. It's mostly an | ||||
6618 | internal "housekeeping" method that is rarely needed. | ||||
6619 | See also L</disconnect> and the L</Active> attribute. | ||||
6620 | |||||
6621 | The C<finish> method should have been called C<discard_pending_rows>. | ||||
6622 | |||||
6623 | |||||
6624 | =head3 C<rows> | ||||
6625 | |||||
6626 | $rv = $sth->rows; | ||||
6627 | |||||
6628 | Returns the number of rows affected by the last row affecting command, | ||||
6629 | or -1 if the number of rows is not known or not available. | ||||
6630 | |||||
6631 | Generally, you can only rely on a row count after a I<non>-C<SELECT> | ||||
6632 | C<execute> (for some specific operations like C<UPDATE> and C<DELETE>), or | ||||
6633 | after fetching all the rows of a C<SELECT> statement. | ||||
6634 | |||||
6635 | For C<SELECT> statements, it is generally not possible to know how many | ||||
6636 | rows will be returned except by fetching them all. Some drivers will | ||||
6637 | return the number of rows the application has fetched so far, but | ||||
6638 | others may return -1 until all rows have been fetched. So use of the | ||||
6639 | C<rows> method or C<$DBI::rows> with C<SELECT> statements is not | ||||
6640 | recommended. | ||||
6641 | |||||
6642 | One alternative method to get a row count for a C<SELECT> is to execute a | ||||
6643 | "SELECT COUNT(*) FROM ..." SQL statement with the same "..." as your | ||||
6644 | query and then fetch the row count from that. | ||||
6645 | |||||
6646 | |||||
6647 | =head3 C<bind_col> | ||||
6648 | |||||
6649 | $rc = $sth->bind_col($column_number, \$var_to_bind); | ||||
6650 | $rc = $sth->bind_col($column_number, \$var_to_bind, \%attr ); | ||||
6651 | $rc = $sth->bind_col($column_number, \$var_to_bind, $bind_type ); | ||||
6652 | |||||
6653 | Binds a Perl variable and/or some attributes to an output column | ||||
6654 | (field) of a C<SELECT> statement. Column numbers count up from 1. | ||||
6655 | You do not need to bind output columns in order to fetch data. | ||||
6656 | For maximum portability between drivers, bind_col() should be called | ||||
6657 | after execute() and not before. | ||||
6658 | See also L</bind_columns> for an example. | ||||
6659 | |||||
6660 | The binding is performed at a low level using Perl aliasing. | ||||
6661 | Whenever a row is fetched from the database $var_to_bind appears | ||||
6662 | to be automatically updated simply because it now refers to the same | ||||
6663 | memory location as the corresponding column value. This makes using | ||||
6664 | bound variables very efficient. | ||||
6665 | Binding a tied variable doesn't work, currently. | ||||
6666 | |||||
6667 | The L</bind_param> method | ||||
6668 | performs a similar, but opposite, function for input variables. | ||||
6669 | |||||
6670 | B<Data Types for Column Binding> | ||||
6671 | |||||
6672 | The C<\%attr> parameter can be used to hint at the data type | ||||
6673 | formatting the column should have. For example, you can use: | ||||
6674 | |||||
6675 | $sth->bind_col(1, undef, { TYPE => SQL_DATETIME }); | ||||
6676 | |||||
6677 | to specify that you'd like the column (which presumably is some | ||||
6678 | kind of datetime type) to be returned in the standard format for | ||||
6679 | SQL_DATETIME, which is 'YYYY-MM-DD HH:MM:SS', rather than the | ||||
6680 | native formatting the database would normally use. | ||||
6681 | |||||
6682 | There's no $var_to_bind in that example to emphasize the point | ||||
6683 | that bind_col() works on the underlying column and not just | ||||
6684 | a particular bound variable. | ||||
6685 | |||||
6686 | As a short-cut for the common case, the data type can be passed | ||||
6687 | directly, in place of the C<\%attr> hash reference. This example is | ||||
6688 | equivalent to the one above: | ||||
6689 | |||||
6690 | $sth->bind_col(1, undef, SQL_DATETIME); | ||||
6691 | |||||
6692 | The C<TYPE> value indicates the standard (non-driver-specific) type for | ||||
6693 | this parameter. To specify the driver-specific type, the driver may | ||||
6694 | support a driver-specific attribute, such as C<{ ora_type =E<gt> 97 }>. | ||||
6695 | |||||
6696 | The SQL_DATETIME and other related constants can be imported using | ||||
6697 | |||||
6698 | use DBI qw(:sql_types); | ||||
6699 | |||||
6700 | See L</"DBI Constants"> for more information. | ||||
6701 | |||||
6702 | Few drivers support specifying a data type via a C<bind_col> call | ||||
6703 | (most will simply ignore the data type). Fewer still allow the data | ||||
6704 | type to be altered once set. If you do set a column type the type | ||||
6705 | should remain sticky through further calls to bind_col for the same | ||||
6706 | column if the type is not overridden (this is important for instance | ||||
6707 | when you are using a slice in fetchall_arrayref). | ||||
6708 | |||||
6709 | The TYPE attribute for bind_col() was first specified in DBI 1.41. | ||||
6710 | |||||
6711 | From DBI 1.611, drivers can use the C<TYPE> attribute to attempt to | ||||
6712 | cast the bound scalar to a perl type which more closely matches | ||||
6713 | C<TYPE>. At present DBI supports C<SQL_INTEGER>, C<SQL_DOUBLE> and | ||||
6714 | C<SQL_NUMERIC>. See L</sql_type_cast> for details of how types are | ||||
6715 | cast. | ||||
6716 | |||||
6717 | B<Other attributes for Column Binding> | ||||
6718 | |||||
6719 | The C<\%attr> parameter may also contain the following attributes: | ||||
6720 | |||||
6721 | =over | ||||
6722 | |||||
6723 | =item C<StrictlyTyped> | ||||
6724 | |||||
6725 | If a C<TYPE> attribute is passed to bind_col, then the driver will | ||||
6726 | attempt to change the bound perl scalar to match the type more | ||||
6727 | closely. If the bound value cannot be cast to the requested C<TYPE> | ||||
6728 | then by default it is left untouched and no error is generated. If you | ||||
6729 | specify C<StrictlyTyped> as 1 and the cast fails, this will generate | ||||
6730 | an error. | ||||
6731 | |||||
6732 | This attribute was first added in DBI 1.611. When 1.611 was released | ||||
6733 | few drivers actually supported this attribute but DBD::Oracle and | ||||
6734 | DBD::ODBC should from versions 1.24. | ||||
6735 | |||||
6736 | =item C<DiscardString> | ||||
6737 | |||||
6738 | When the C<TYPE> attribute is passed to L</bind_col> and the driver | ||||
6739 | successfully casts the bound perl scalar to a non-string type | ||||
6740 | then if C<DiscardString> is set to 1, the string portion of the | ||||
6741 | scalar will be discarded. By default, C<DiscardString> is not set. | ||||
6742 | |||||
6743 | This attribute was first added in DBI 1.611. When 1.611 was released | ||||
6744 | few drivers actually supported this attribute but DBD::Oracle and | ||||
6745 | DBD::ODBC should from versions 1.24. | ||||
6746 | |||||
6747 | =back | ||||
6748 | |||||
6749 | |||||
6750 | =head3 C<bind_columns> | ||||
6751 | |||||
6752 | $rc = $sth->bind_columns(@list_of_refs_to_vars_to_bind); | ||||
6753 | |||||
6754 | Calls L</bind_col> for each column of the C<SELECT> statement. | ||||
6755 | |||||
6756 | The list of references should have the same number of elements as the number of | ||||
6757 | columns in the C<SELECT> statement. If it doesn't then C<bind_columns> will | ||||
6758 | bind the elements given, up to the number of columns, and then return an error. | ||||
6759 | |||||
6760 | For maximum portability between drivers, bind_columns() should be called | ||||
6761 | after execute() and not before. | ||||
6762 | |||||
6763 | For example: | ||||
6764 | |||||
6765 | $dbh->{RaiseError} = 1; # do this, or check every call for errors | ||||
6766 | $sth = $dbh->prepare(q{ SELECT region, sales FROM sales_by_region }); | ||||
6767 | $sth->execute; | ||||
6768 | my ($region, $sales); | ||||
6769 | |||||
6770 | # Bind Perl variables to columns: | ||||
6771 | $rv = $sth->bind_columns(\$region, \$sales); | ||||
6772 | |||||
6773 | # you can also use Perl's \(...) syntax (see perlref docs): | ||||
6774 | # $sth->bind_columns(\($region, $sales)); | ||||
6775 | |||||
6776 | # Column binding is the most efficient way to fetch data | ||||
6777 | while ($sth->fetch) { | ||||
6778 | print "$region: $sales\n"; | ||||
6779 | } | ||||
6780 | |||||
6781 | For compatibility with old scripts, the first parameter will be | ||||
6782 | ignored if it is C<undef> or a hash reference. | ||||
6783 | |||||
6784 | Here's a more fancy example that binds columns to the values I<inside> | ||||
6785 | a hash (thanks to H.Merijn Brand): | ||||
6786 | |||||
6787 | $sth->execute; | ||||
6788 | my %row; | ||||
6789 | $sth->bind_columns( \( @row{ @{$sth->{NAME_lc} } } )); | ||||
6790 | while ($sth->fetch) { | ||||
6791 | print "$row{region}: $row{sales}\n"; | ||||
6792 | } | ||||
6793 | |||||
6794 | |||||
6795 | =head3 C<dump_results> | ||||
6796 | |||||
6797 | $rows = $sth->dump_results($maxlen, $lsep, $fsep, $fh); | ||||
6798 | |||||
6799 | Fetches all the rows from C<$sth>, calls C<DBI::neat_list> for each row, and | ||||
6800 | prints the results to C<$fh> (defaults to C<STDOUT>) separated by C<$lsep> | ||||
6801 | (default C<"\n">). C<$fsep> defaults to C<", "> and C<$maxlen> defaults to 35. | ||||
6802 | |||||
6803 | This method is designed as a handy utility for prototyping and | ||||
6804 | testing queries. Since it uses L</neat_list> to | ||||
6805 | format and edit the string for reading by humans, it is not recommended | ||||
6806 | for data transfer applications. | ||||
6807 | |||||
6808 | |||||
6809 | =head2 Statement Handle Attributes | ||||
6810 | |||||
6811 | This section describes attributes specific to statement handles. Most | ||||
6812 | of these attributes are read-only. | ||||
6813 | |||||
6814 | Changes to these statement handle attributes do not affect any other | ||||
6815 | existing or future statement handles. | ||||
6816 | |||||
6817 | Attempting to set or get the value of an unknown attribute generates a warning, | ||||
6818 | except for private driver specific attributes (which all have names | ||||
6819 | starting with a lowercase letter). | ||||
6820 | |||||
6821 | Example: | ||||
6822 | |||||
6823 | ... = $h->{NUM_OF_FIELDS}; # get/read | ||||
6824 | |||||
6825 | Some drivers cannot provide valid values for some or all of these | ||||
6826 | attributes until after C<$sth-E<gt>execute> has been successfully | ||||
6827 | called. Typically the attribute will be C<undef> in these situations. | ||||
6828 | |||||
6829 | Some attributes, like NAME, are not appropriate to some types of | ||||
6830 | statement, like SELECT. Typically the attribute will be C<undef> | ||||
6831 | in these situations. | ||||
6832 | |||||
6833 | For drivers which support stored procedures and multiple result sets | ||||
6834 | (see L</more_results>) these attributes relate to the I<current> result set. | ||||
6835 | |||||
6836 | See also L</finish> to learn more about the effect it | ||||
6837 | may have on some attributes. | ||||
6838 | |||||
6839 | =head3 C<NUM_OF_FIELDS> | ||||
6840 | |||||
6841 | Type: integer, read-only | ||||
6842 | |||||
6843 | Number of fields (columns) in the data the prepared statement may return. | ||||
6844 | Statements that don't return rows of data, like C<DELETE> and C<CREATE> | ||||
6845 | set C<NUM_OF_FIELDS> to 0 (though it may be undef in some drivers). | ||||
6846 | |||||
6847 | |||||
6848 | =head3 C<NUM_OF_PARAMS> | ||||
6849 | |||||
6850 | Type: integer, read-only | ||||
6851 | |||||
6852 | The number of parameters (placeholders) in the prepared statement. | ||||
6853 | See SUBSTITUTION VARIABLES below for more details. | ||||
6854 | |||||
6855 | |||||
6856 | =head3 C<NAME> | ||||
6857 | |||||
6858 | Type: array-ref, read-only | ||||
6859 | |||||
6860 | Returns a reference to an array of field names for each column. The | ||||
6861 | names may contain spaces but should not be truncated or have any | ||||
6862 | trailing space. Note that the names have the letter case (upper, lower | ||||
6863 | or mixed) as returned by the driver being used. Portable applications | ||||
6864 | should use L</NAME_lc> or L</NAME_uc>. | ||||
6865 | |||||
6866 | print "First column name: $sth->{NAME}->[0]\n"; | ||||
6867 | |||||
6868 | Also note that the name returned for (aggregate) functions like C<count(*)> | ||||
6869 | or C<max(c_foo)> is determined by the database server and not by C<DBI> or | ||||
6870 | the C<DBD> backend. | ||||
6871 | |||||
6872 | =head3 C<NAME_lc> | ||||
6873 | |||||
6874 | Type: array-ref, read-only | ||||
6875 | |||||
6876 | Like C</NAME> but always returns lowercase names. | ||||
6877 | |||||
6878 | =head3 C<NAME_uc> | ||||
6879 | |||||
6880 | Type: array-ref, read-only | ||||
6881 | |||||
6882 | Like C</NAME> but always returns uppercase names. | ||||
6883 | |||||
6884 | =head3 C<NAME_hash> | ||||
6885 | |||||
6886 | Type: hash-ref, read-only | ||||
6887 | |||||
6888 | =head3 C<NAME_lc_hash> | ||||
6889 | |||||
6890 | Type: hash-ref, read-only | ||||
6891 | |||||
6892 | =head3 C<NAME_uc_hash> | ||||
6893 | |||||
6894 | Type: hash-ref, read-only | ||||
6895 | |||||
6896 | The C<NAME_hash>, C<NAME_lc_hash>, and C<NAME_uc_hash> attributes | ||||
6897 | return column name information as a reference to a hash. | ||||
6898 | |||||
6899 | The keys of the hash are the names of the columns. The letter case of | ||||
6900 | the keys corresponds to the letter case returned by the C<NAME>, | ||||
6901 | C<NAME_lc>, and C<NAME_uc> attributes respectively (as described above). | ||||
6902 | |||||
6903 | The value of each hash entry is the perl index number of the | ||||
6904 | corresponding column (counting from 0). For example: | ||||
6905 | |||||
6906 | $sth = $dbh->prepare("select Id, Name from table"); | ||||
6907 | $sth->execute; | ||||
6908 | @row = $sth->fetchrow_array; | ||||
6909 | print "Name $row[ $sth->{NAME_lc_hash}{name} ]\n"; | ||||
6910 | |||||
6911 | |||||
6912 | =head3 C<TYPE> | ||||
6913 | |||||
6914 | Type: array-ref, read-only | ||||
6915 | |||||
6916 | Returns a reference to an array of integer values for each | ||||
6917 | column. The value indicates the data type of the corresponding column. | ||||
6918 | |||||
6919 | The values correspond to the international standards (ANSI X3.135 | ||||
6920 | and ISO/IEC 9075) which, in general terms, means ODBC. Driver-specific | ||||
6921 | types that don't exactly match standard types should generally return | ||||
6922 | the same values as an ODBC driver supplied by the makers of the | ||||
6923 | database. That might include private type numbers in ranges the vendor | ||||
6924 | has officially registered with the ISO working group: | ||||
6925 | |||||
6926 | ftp://sqlstandards.org/SC32/SQL_Registry/ | ||||
6927 | |||||
6928 | Where there's no vendor-supplied ODBC driver to be compatible with, | ||||
6929 | the DBI driver can use type numbers in the range that is now | ||||
6930 | officially reserved for use by the DBI: -9999 to -9000. | ||||
6931 | |||||
6932 | All possible values for C<TYPE> should have at least one entry in the | ||||
6933 | output of the C<type_info_all> method (see L</type_info_all>). | ||||
6934 | |||||
6935 | =head3 C<PRECISION> | ||||
6936 | |||||
6937 | Type: array-ref, read-only | ||||
6938 | |||||
6939 | Returns a reference to an array of integer values for each column. | ||||
6940 | |||||
6941 | For numeric columns, the value is the maximum number of digits | ||||
6942 | (without considering a sign character or decimal point). Note that | ||||
6943 | the "display size" for floating point types (REAL, FLOAT, DOUBLE) | ||||
6944 | can be up to 7 characters greater than the precision (for the | ||||
6945 | sign + decimal point + the letter E + a sign + 2 or 3 digits). | ||||
6946 | |||||
6947 | For any character type column the value is the OCTET_LENGTH, | ||||
6948 | in other words the number of bytes, not characters. | ||||
6949 | |||||
6950 | (More recent standards refer to this as COLUMN_SIZE but we stick | ||||
6951 | with PRECISION for backwards compatibility.) | ||||
6952 | |||||
6953 | =head3 C<SCALE> | ||||
6954 | |||||
6955 | Type: array-ref, read-only | ||||
6956 | |||||
6957 | Returns a reference to an array of integer values for each column. | ||||
6958 | NULL (C<undef>) values indicate columns where scale is not applicable. | ||||
6959 | |||||
6960 | =head3 C<NULLABLE> | ||||
6961 | |||||
6962 | Type: array-ref, read-only | ||||
6963 | |||||
6964 | Returns a reference to an array indicating the possibility of each | ||||
6965 | column returning a null. Possible values are C<0> | ||||
6966 | (or an empty string) = no, C<1> = yes, C<2> = unknown. | ||||
6967 | |||||
6968 | print "First column may return NULL\n" if $sth->{NULLABLE}->[0]; | ||||
6969 | |||||
6970 | |||||
6971 | =head3 C<CursorName> | ||||
6972 | |||||
6973 | Type: string, read-only | ||||
6974 | |||||
6975 | Returns the name of the cursor associated with the statement handle, if | ||||
6976 | available. If not available or if the database driver does not support the | ||||
6977 | C<"where current of ..."> SQL syntax, then it returns C<undef>. | ||||
6978 | |||||
6979 | |||||
6980 | =head3 C<Database> | ||||
6981 | |||||
6982 | Type: dbh, read-only | ||||
6983 | |||||
6984 | Returns the parent $dbh of the statement handle. | ||||
6985 | |||||
6986 | |||||
6987 | =head3 C<Statement> | ||||
6988 | |||||
6989 | Type: string, read-only | ||||
6990 | |||||
6991 | Returns the statement string passed to the L</prepare> method. | ||||
6992 | |||||
6993 | |||||
6994 | =head3 C<ParamValues> | ||||
6995 | |||||
6996 | Type: hash ref, read-only | ||||
6997 | |||||
6998 | Returns a reference to a hash containing the values currently bound | ||||
6999 | to placeholders. The keys of the hash are the 'names' of the | ||||
7000 | placeholders, typically integers starting at 1. Returns undef if | ||||
7001 | not supported by the driver. | ||||
7002 | |||||
7003 | See L</ShowErrorStatement> for an example of how this is used. | ||||
7004 | |||||
7005 | * Keys: | ||||
7006 | |||||
7007 | If the driver supports C<ParamValues> but no values have been bound | ||||
7008 | yet then the driver should return a hash with placeholders names | ||||
7009 | in the keys but all the values undef, but some drivers may return | ||||
7010 | a ref to an empty hash because they can't pre-determine the names. | ||||
7011 | |||||
7012 | It is possible that the keys in the hash returned by C<ParamValues> | ||||
7013 | are not exactly the same as those implied by the prepared statement. | ||||
7014 | For example, DBD::Oracle translates 'C<?>' placeholders into 'C<:pN>' | ||||
7015 | where N is a sequence number starting at 1. | ||||
7016 | |||||
7017 | * Values: | ||||
7018 | |||||
7019 | It is possible that the values in the hash returned by C<ParamValues> | ||||
7020 | are not I<exactly> the same as those passed to bind_param() or execute(). | ||||
7021 | The driver may have slightly modified values in some way based on the | ||||
7022 | TYPE the value was bound with. For example a floating point value | ||||
7023 | bound as an SQL_INTEGER type may be returned as an integer. | ||||
7024 | The values returned by C<ParamValues> can be passed to another | ||||
7025 | bind_param() method with the same TYPE and will be seen by the | ||||
7026 | database as the same value. See also L</ParamTypes> below. | ||||
7027 | |||||
7028 | The C<ParamValues> attribute was added in DBI 1.28. | ||||
7029 | |||||
7030 | =head3 C<ParamTypes> | ||||
7031 | |||||
7032 | Type: hash ref, read-only | ||||
7033 | |||||
7034 | Returns a reference to a hash containing the type information | ||||
7035 | currently bound to placeholders. | ||||
7036 | Returns undef if not supported by the driver. | ||||
7037 | |||||
7038 | * Keys: | ||||
7039 | |||||
7040 | See L</ParamValues> above. | ||||
7041 | |||||
7042 | * Values: | ||||
7043 | |||||
7044 | The hash values are hashrefs of type information in the same form as that | ||||
7045 | passed to the various bind_param() methods (See L</bind_param> for the format | ||||
7046 | and values). | ||||
7047 | |||||
7048 | It is possible that the values in the hash returned by C<ParamTypes> | ||||
7049 | are not exactly the same as those passed to bind_param() or execute(). | ||||
7050 | Param attributes specified using the abbreviated form, like this: | ||||
7051 | |||||
7052 | $sth->bind_param(1, SQL_INTEGER); | ||||
7053 | |||||
7054 | are returned in the expanded form, as if called like this: | ||||
7055 | |||||
7056 | $sth->bind_param(1, { TYPE => SQL_INTEGER }); | ||||
7057 | |||||
7058 | The driver may have modified the type information in some way based | ||||
7059 | on the bound values, other hints provided by the prepare()'d | ||||
7060 | SQL statement, or alternate type mappings required by the driver or target | ||||
7061 | database system. The driver may also add private keys (with names beginning | ||||
7062 | with the drivers reserved prefix, e.g., odbc_xxx). | ||||
7063 | |||||
7064 | * Example: | ||||
7065 | |||||
7066 | The keys and values in the returned hash can be passed to the various | ||||
7067 | bind_param() methods to effectively reproduce a previous param binding. | ||||
7068 | For example: | ||||
7069 | |||||
7070 | # assuming $sth1 is a previously prepared statement handle | ||||
7071 | my $sth2 = $dbh->prepare( $sth1->{Statement} ); | ||||
7072 | my $ParamValues = $sth1->{ParamValues} || {}; | ||||
7073 | my $ParamTypes = $sth1->{ParamTypes} || {}; | ||||
7074 | $sth2->bind_param($_, $ParamValues->{$_} $ParamTypes->{$_}) | ||||
7075 | for keys %{ {%$ParamValues, %$ParamTypes} }; | ||||
7076 | $sth2->execute(); | ||||
7077 | |||||
7078 | The C<ParamTypes> attribute was added in DBI 1.49. Implementation | ||||
7079 | is the responsibility of individual drivers; the DBI layer default | ||||
7080 | implementation simply returns undef. | ||||
7081 | |||||
7082 | |||||
7083 | =head3 C<ParamArrays> | ||||
7084 | |||||
7085 | Type: hash ref, read-only | ||||
7086 | |||||
7087 | Returns a reference to a hash containing the values currently bound to | ||||
7088 | placeholders with L</execute_array> or L</bind_param_array>. The | ||||
7089 | keys of the hash are the 'names' of the placeholders, typically | ||||
7090 | integers starting at 1. Returns undef if not supported by the driver | ||||
7091 | or no arrays of parameters are bound. | ||||
7092 | |||||
7093 | Each key value is an array reference containing a list of the bound | ||||
7094 | parameters for that column. | ||||
7095 | |||||
7096 | For example: | ||||
7097 | |||||
7098 | $sth = $dbh->prepare("INSERT INTO staff (id, name) values (?,?)"); | ||||
7099 | $sth->execute_array({},[1,2], ['fred','dave']); | ||||
7100 | if ($sth->{ParamArrays}) { | ||||
7101 | foreach $param (keys %{$sth->{ParamArrays}}) { | ||||
7102 | printf "Parameters for %s : %s\n", $param, | ||||
7103 | join(",", @{$sth->{ParamArrays}->{$param}}); | ||||
7104 | } | ||||
7105 | } | ||||
7106 | |||||
7107 | It is possible that the values in the hash returned by C<ParamArrays> | ||||
7108 | are not I<exactly> the same as those passed to L</bind_param_array> or | ||||
7109 | L</execute_array>. The driver may have slightly modified values in some | ||||
7110 | way based on the TYPE the value was bound with. For example a floating | ||||
7111 | point value bound as an SQL_INTEGER type may be returned as an | ||||
7112 | integer. | ||||
7113 | |||||
7114 | It is also possible that the keys in the hash returned by | ||||
7115 | C<ParamArrays> are not exactly the same as those implied by the | ||||
7116 | prepared statement. For example, DBD::Oracle translates 'C<?>' | ||||
7117 | placeholders into 'C<:pN>' where N is a sequence number starting at 1. | ||||
7118 | |||||
7119 | =head3 C<RowsInCache> | ||||
7120 | |||||
7121 | Type: integer, read-only | ||||
7122 | |||||
7123 | If the driver supports a local row cache for C<SELECT> statements, then | ||||
7124 | this attribute holds the number of un-fetched rows in the cache. If the | ||||
7125 | driver doesn't, then it returns C<undef>. Note that some drivers pre-fetch | ||||
7126 | rows on execute, whereas others wait till the first fetch. | ||||
7127 | |||||
7128 | See also the L</RowCacheSize> database handle attribute. | ||||
7129 | |||||
7130 | =head1 FURTHER INFORMATION | ||||
7131 | |||||
7132 | =head2 Catalog Methods | ||||
7133 | |||||
7134 | An application can retrieve metadata information from the DBMS by issuing | ||||
7135 | appropriate queries on the views of the Information Schema. Unfortunately, | ||||
7136 | C<INFORMATION_SCHEMA> views are seldom supported by the DBMS. | ||||
7137 | Special methods (catalog methods) are available to return result sets | ||||
7138 | for a small but important portion of that metadata: | ||||
7139 | |||||
7140 | column_info | ||||
7141 | foreign_key_info | ||||
7142 | primary_key_info | ||||
7143 | table_info | ||||
7144 | statistics_info | ||||
7145 | |||||
7146 | All catalog methods accept arguments in order to restrict the result sets. | ||||
7147 | Passing C<undef> to an optional argument does not constrain the search for | ||||
7148 | that argument. | ||||
7149 | However, an empty string ('') is treated as a regular search criteria | ||||
7150 | and will only match an empty value. | ||||
7151 | |||||
7152 | B<Note>: SQL/CLI and ODBC differ in the handling of empty strings. An | ||||
7153 | empty string will not restrict the result set in SQL/CLI. | ||||
7154 | |||||
7155 | Most arguments in the catalog methods accept only I<ordinary values>, e.g. | ||||
7156 | the arguments of C<primary_key_info()>. | ||||
7157 | Such arguments are treated as a literal string, i.e. the case is significant | ||||
7158 | and quote characters are taken literally. | ||||
7159 | |||||
7160 | Some arguments in the catalog methods accept I<search patterns> (strings | ||||
7161 | containing '_' and/or '%'), e.g. the C<$table> argument of C<column_info()>. | ||||
7162 | Passing '%' is equivalent to leaving the argument C<undef>. | ||||
7163 | |||||
7164 | B<Caveat>: The underscore ('_') is valid and often used in SQL identifiers. | ||||
7165 | Passing such a value to a search pattern argument may return more rows than | ||||
7166 | expected! | ||||
7167 | To include pattern characters as literals, they must be preceded by an | ||||
7168 | escape character which can be achieved with | ||||
7169 | |||||
7170 | $esc = $dbh->get_info( 14 ); # SQL_SEARCH_PATTERN_ESCAPE | ||||
7171 | $search_pattern =~ s/([_%])/$esc$1/g; | ||||
7172 | |||||
7173 | The ODBC and SQL/CLI specifications define a way to change the default | ||||
7174 | behaviour described above: All arguments (except I<list value arguments>) | ||||
7175 | are treated as I<identifier> if the C<SQL_ATTR_METADATA_ID> attribute is | ||||
7176 | set to C<SQL_TRUE>. | ||||
7177 | I<Quoted identifiers> are very similar to I<ordinary values>, i.e. their | ||||
7178 | body (the string within the quotes) is interpreted literally. | ||||
7179 | I<Unquoted identifiers> are compared in UPPERCASE. | ||||
7180 | |||||
7181 | The DBI (currently) does not support the C<SQL_ATTR_METADATA_ID> attribute, | ||||
7182 | i.e. it behaves like an ODBC driver where C<SQL_ATTR_METADATA_ID> is set to | ||||
7183 | C<SQL_FALSE>. | ||||
7184 | |||||
7185 | |||||
7186 | =head2 Transactions | ||||
7187 | |||||
7188 | Transactions are a fundamental part of any robust database system. They | ||||
7189 | protect against errors and database corruption by ensuring that sets of | ||||
7190 | related changes to the database take place in atomic (indivisible, | ||||
7191 | all-or-nothing) units. | ||||
7192 | |||||
7193 | This section applies to databases that support transactions and where | ||||
7194 | C<AutoCommit> is off. See L</AutoCommit> for details of using C<AutoCommit> | ||||
7195 | with various types of databases. | ||||
7196 | |||||
7197 | The recommended way to implement robust transactions in Perl | ||||
7198 | applications is to use C<RaiseError> and S<C<eval { ... }>> | ||||
7199 | (which is very fast, unlike S<C<eval "...">>). For example: | ||||
7200 | |||||
7201 | $dbh->{AutoCommit} = 0; # enable transactions, if possible | ||||
7202 | $dbh->{RaiseError} = 1; | ||||
7203 | eval { | ||||
7204 | foo(...) # do lots of work here | ||||
7205 | bar(...) # including inserts | ||||
7206 | baz(...) # and updates | ||||
7207 | $dbh->commit; # commit the changes if we get this far | ||||
7208 | }; | ||||
7209 | if ($@) { | ||||
7210 | warn "Transaction aborted because $@"; | ||||
7211 | # now rollback to undo the incomplete changes | ||||
7212 | # but do it in an eval{} as it may also fail | ||||
7213 | eval { $dbh->rollback }; | ||||
7214 | # add other application on-error-clean-up code here | ||||
7215 | } | ||||
7216 | |||||
7217 | If the C<RaiseError> attribute is not set, then DBI calls would need to be | ||||
7218 | manually checked for errors, typically like this: | ||||
7219 | |||||
7220 | $h->method(@args) or die $h->errstr; | ||||
7221 | |||||
7222 | With C<RaiseError> set, the DBI will automatically C<die> if any DBI method | ||||
7223 | call on that handle (or a child handle) fails, so you don't have to | ||||
7224 | test the return value of each method call. See L</RaiseError> for more | ||||
7225 | details. | ||||
7226 | |||||
7227 | A major advantage of the C<eval> approach is that the transaction will be | ||||
7228 | properly rolled back if I<any> code (not just DBI calls) in the inner | ||||
7229 | application dies for any reason. The major advantage of using the | ||||
7230 | C<$h-E<gt>{RaiseError}> attribute is that all DBI calls will be checked | ||||
7231 | automatically. Both techniques are strongly recommended. | ||||
7232 | |||||
7233 | After calling C<commit> or C<rollback> many drivers will not let you | ||||
7234 | fetch from a previously active C<SELECT> statement handle that's a child | ||||
7235 | of the same database handle. A typical way round this is to connect the | ||||
7236 | the database twice and use one connection for C<SELECT> statements. | ||||
7237 | |||||
7238 | See L</AutoCommit> and L</disconnect> for other important information | ||||
7239 | about transactions. | ||||
7240 | |||||
7241 | |||||
7242 | =head2 Handling BLOB / LONG / Memo Fields | ||||
7243 | |||||
7244 | Many databases support "blob" (binary large objects), "long", or similar | ||||
7245 | datatypes for holding very long strings or large amounts of binary | ||||
7246 | data in a single field. Some databases support variable length long | ||||
7247 | values over 2,000,000,000 bytes in length. | ||||
7248 | |||||
7249 | Since values of that size can't usually be held in memory, and because | ||||
7250 | databases can't usually know in advance the length of the longest long | ||||
7251 | that will be returned from a C<SELECT> statement (unlike other data | ||||
7252 | types), some special handling is required. | ||||
7253 | |||||
7254 | In this situation, the value of the C<$h-E<gt>{LongReadLen}> | ||||
7255 | attribute is used to determine how much buffer space to allocate | ||||
7256 | when fetching such fields. The C<$h-E<gt>{LongTruncOk}> attribute | ||||
7257 | is used to determine how to behave if a fetched value can't fit | ||||
7258 | into the buffer. | ||||
7259 | |||||
7260 | See the description of L</LongReadLen> for more information. | ||||
7261 | |||||
7262 | When trying to insert long or binary values, placeholders should be used | ||||
7263 | since there are often limits on the maximum size of an C<INSERT> | ||||
7264 | statement and the L</quote> method generally can't cope with binary | ||||
7265 | data. See L</Placeholders and Bind Values>. | ||||
7266 | |||||
7267 | |||||
7268 | =head2 Simple Examples | ||||
7269 | |||||
7270 | Here's a complete example program to select and fetch some data: | ||||
7271 | |||||
7272 | my $data_source = "dbi::DriverName:db_name"; | ||||
7273 | my $dbh = DBI->connect($data_source, $user, $password) | ||||
7274 | or die "Can't connect to $data_source: $DBI::errstr"; | ||||
7275 | |||||
7276 | my $sth = $dbh->prepare( q{ | ||||
7277 | SELECT name, phone | ||||
7278 | FROM mytelbook | ||||
7279 | }) or die "Can't prepare statement: $DBI::errstr"; | ||||
7280 | |||||
7281 | my $rc = $sth->execute | ||||
7282 | or die "Can't execute statement: $DBI::errstr"; | ||||
7283 | |||||
7284 | print "Query will return $sth->{NUM_OF_FIELDS} fields.\n\n"; | ||||
7285 | print "Field names: @{ $sth->{NAME} }\n"; | ||||
7286 | |||||
7287 | while (($name, $phone) = $sth->fetchrow_array) { | ||||
7288 | print "$name: $phone\n"; | ||||
7289 | } | ||||
7290 | # check for problems which may have terminated the fetch early | ||||
7291 | die $sth->errstr if $sth->err; | ||||
7292 | |||||
7293 | $dbh->disconnect; | ||||
7294 | |||||
7295 | Here's a complete example program to insert some data from a file. | ||||
7296 | (This example uses C<RaiseError> to avoid needing to check each call). | ||||
7297 | |||||
7298 | my $dbh = DBI->connect("dbi:DriverName:db_name", $user, $password, { | ||||
7299 | RaiseError => 1, AutoCommit => 0 | ||||
7300 | }); | ||||
7301 | |||||
7302 | my $sth = $dbh->prepare( q{ | ||||
7303 | INSERT INTO table (name, phone) VALUES (?, ?) | ||||
7304 | }); | ||||
7305 | |||||
7306 | open FH, "<phone.csv" or die "Unable to open phone.csv: $!"; | ||||
7307 | while (<FH>) { | ||||
7308 | chomp; | ||||
7309 | my ($name, $phone) = split /,/; | ||||
7310 | $sth->execute($name, $phone); | ||||
7311 | } | ||||
7312 | close FH; | ||||
7313 | |||||
7314 | $dbh->commit; | ||||
7315 | $dbh->disconnect; | ||||
7316 | |||||
7317 | Here's how to convert fetched NULLs (undefined values) into empty strings: | ||||
7318 | |||||
7319 | while($row = $sth->fetchrow_arrayref) { | ||||
7320 | # this is a fast and simple way to deal with nulls: | ||||
7321 | foreach (@$row) { $_ = '' unless defined } | ||||
7322 | print "@$row\n"; | ||||
7323 | } | ||||
7324 | |||||
7325 | The C<q{...}> style quoting used in these examples avoids clashing with | ||||
7326 | quotes that may be used in the SQL statement. Use the double-quote like | ||||
7327 | C<qq{...}> operator if you want to interpolate variables into the string. | ||||
7328 | See L<perlop/"Quote and Quote-like Operators"> for more details. | ||||
7329 | |||||
7330 | =head2 Threads and Thread Safety | ||||
7331 | |||||
7332 | Perl 5.7 and later support a new threading model called iThreads. | ||||
7333 | (The old "5.005 style" threads are not supported by the DBI.) | ||||
7334 | |||||
7335 | In the iThreads model each thread has its own copy of the perl | ||||
7336 | interpreter. When a new thread is created the original perl | ||||
7337 | interpreter is 'cloned' to create a new copy for the new thread. | ||||
7338 | |||||
7339 | If the DBI and drivers are loaded and handles created before the | ||||
7340 | thread is created then it will get a cloned copy of the DBI, the | ||||
7341 | drivers and the handles. | ||||
7342 | |||||
7343 | However, the internal pointer data within the handles will refer | ||||
7344 | to the DBI and drivers in the original interpreter. Using those | ||||
7345 | handles in the new interpreter thread is not safe, so the DBI detects | ||||
7346 | this and croaks on any method call using handles that don't belong | ||||
7347 | to the current thread (except for DESTROY). | ||||
7348 | |||||
7349 | Because of this (possibly temporary) restriction, newly created | ||||
7350 | threads must make their own connections to the database. Handles | ||||
7351 | can't be shared across threads. | ||||
7352 | |||||
7353 | But BEWARE, some underlying database APIs (the code the DBD driver | ||||
7354 | uses to talk to the database, often supplied by the database vendor) | ||||
7355 | are not thread safe. If it's not thread safe, then allowing more | ||||
7356 | than one thread to enter the code at the same time may cause | ||||
7357 | subtle/serious problems. In some cases allowing more than | ||||
7358 | one thread to enter the code, even if I<not> at the same time, | ||||
7359 | can cause problems. You have been warned. | ||||
7360 | |||||
7361 | Using DBI with perl threads is not yet recommended for production | ||||
7362 | environments. For more information see | ||||
7363 | L<http://www.perlmonks.org/index.pl?node_id=288022> | ||||
7364 | |||||
7365 | Note: There is a bug in perl 5.8.2 when configured with threads | ||||
7366 | and debugging enabled (bug #24463) which causes a DBI test to fail. | ||||
7367 | |||||
7368 | =head2 Signal Handling and Canceling Operations | ||||
7369 | |||||
7370 | [The following only applies to systems with unix-like signal handling. | ||||
7371 | I'd welcome additions for other systems, especially Windows.] | ||||
7372 | |||||
7373 | The first thing to say is that signal handling in Perl versions less | ||||
7374 | than 5.8 is I<not> safe. There is always a small risk of Perl | ||||
7375 | crashing and/or core dumping when, or after, handling a signal | ||||
7376 | because the signal could arrive and be handled while internal data | ||||
7377 | structures are being changed. If the signal handling code | ||||
7378 | used those same internal data structures it could cause all manner | ||||
7379 | of subtle and not-so-subtle problems. The risk was reduced with | ||||
7380 | 5.4.4 but was still present in all perls up through 5.8.0. | ||||
7381 | |||||
7382 | Beginning in perl 5.8.0 perl implements 'safe' signal handling if | ||||
7383 | your system has the POSIX sigaction() routine. Now when a signal | ||||
7384 | is delivered perl just makes a note of it but does I<not> run the | ||||
7385 | %SIG handler. The handling is 'deferred' until a 'safe' moment. | ||||
7386 | |||||
7387 | Although this change made signal handling safe, it also lead to | ||||
7388 | a problem with signals being deferred for longer than you'd like. | ||||
7389 | If a signal arrived while executing a system call, such as waiting | ||||
7390 | for data on a network connection, the signal is noted and then the | ||||
7391 | system call that was executing returns with an EINTR error code | ||||
7392 | to indicate that it was interrupted. All fine so far. | ||||
7393 | |||||
7394 | The problem comes when the code that made the system call sees the | ||||
7395 | EINTR code and decides it's going to call it again. Perl doesn't | ||||
7396 | do that, but database code sometimes does. If that happens then the | ||||
7397 | signal handler doesn't get called until later. Maybe much later. | ||||
7398 | |||||
7399 | Fortunately there are ways around this which we'll discuss below. | ||||
7400 | Unfortunately they make signals unsafe again. | ||||
7401 | |||||
7402 | The two most common uses of signals in relation to the DBI are for | ||||
7403 | canceling operations when the user types Ctrl-C (interrupt), and for | ||||
7404 | implementing a timeout using C<alarm()> and C<$SIG{ALRM}>. | ||||
7405 | |||||
7406 | =over 4 | ||||
7407 | |||||
7408 | =item Cancel | ||||
7409 | |||||
7410 | The DBI provides a C<cancel> method for statement handles. The | ||||
7411 | C<cancel> method should abort the current operation and is designed | ||||
7412 | to be called from a signal handler. For example: | ||||
7413 | |||||
7414 | $SIG{INT} = sub { $sth->cancel }; | ||||
7415 | |||||
7416 | However, few drivers implement this (the DBI provides a default | ||||
7417 | method that just returns C<undef>) and, even if implemented, there | ||||
7418 | is still a possibility that the statement handle, and even the | ||||
7419 | parent database handle, will not be usable afterwards. | ||||
7420 | |||||
7421 | If C<cancel> returns true, then it has successfully | ||||
7422 | invoked the database engine's own cancel function. If it returns false, | ||||
7423 | then C<cancel> failed. If it returns C<undef>, then the database | ||||
7424 | driver does not have cancel implemented - very few do. | ||||
7425 | |||||
7426 | =item Timeout | ||||
7427 | |||||
7428 | The traditional way to implement a timeout is to set C<$SIG{ALRM}> | ||||
7429 | to refer to some code that will be executed when an ALRM signal | ||||
7430 | arrives and then to call alarm($seconds) to schedule an ALRM signal | ||||
7431 | to be delivered $seconds in the future. For example: | ||||
7432 | |||||
7433 | eval { | ||||
7434 | local $SIG{ALRM} = sub { die "TIMEOUT\n" }; # N.B. \n required | ||||
7435 | eval { | ||||
7436 | alarm($seconds); | ||||
7437 | ... code to execute with timeout here (which may die) ... | ||||
7438 | }; | ||||
7439 | # outer eval catches alarm that might fire JUST before this alarm(0) | ||||
7440 | alarm(0); # cancel alarm (if code ran fast) | ||||
7441 | die "$@" if $@; | ||||
7442 | }; | ||||
7443 | if ( $@ eq "TIMEOUT\n" ) { ... } | ||||
7444 | elsif ($@) { ... } # some other error | ||||
7445 | |||||
7446 | The first (outer) eval is used to avoid the unlikely but possible | ||||
7447 | chance that the "code to execute" dies and the alarm fires before it | ||||
7448 | is cancelled. Without the outer eval, if this happened your program | ||||
7449 | will die if you have no ALRM handler or a non-local alarm handler | ||||
7450 | will be called. | ||||
7451 | |||||
7452 | Unfortunately, as described above, this won't always work as expected, | ||||
7453 | depending on your perl version and the underlying database code. | ||||
7454 | |||||
7455 | With Oracle for instance (DBD::Oracle), if the system which hosts | ||||
7456 | the database is down the DBI->connect() call will hang for several | ||||
7457 | minutes before returning an error. | ||||
7458 | |||||
7459 | =back | ||||
7460 | |||||
7461 | The solution on these systems is to use the C<POSIX::sigaction()> | ||||
7462 | routine to gain low level access to how the signal handler is installed. | ||||
7463 | |||||
7464 | The code would look something like this (for the DBD-Oracle connect()): | ||||
7465 | |||||
7466 | use POSIX qw(:signal_h); | ||||
7467 | |||||
7468 | my $mask = POSIX::SigSet->new( SIGALRM ); # signals to mask in the handler | ||||
7469 | my $action = POSIX::SigAction->new( | ||||
7470 | sub { die "connect timeout\n" }, # the handler code ref | ||||
7471 | $mask, | ||||
7472 | # not using (perl 5.8.2 and later) 'safe' switch or sa_flags | ||||
7473 | ); | ||||
7474 | my $oldaction = POSIX::SigAction->new(); | ||||
7475 | sigaction( SIGALRM, $action, $oldaction ); | ||||
7476 | my $dbh; | ||||
7477 | eval { | ||||
7478 | eval { | ||||
7479 | alarm(5); # seconds before time out | ||||
7480 | $dbh = DBI->connect("dbi:Oracle:$dsn" ... ); | ||||
7481 | }; | ||||
7482 | alarm(0); # cancel alarm (if connect worked fast) | ||||
7483 | die "$@\n" if $@; # connect died | ||||
7484 | }; | ||||
7485 | sigaction( SIGALRM, $oldaction ); # restore original signal handler | ||||
7486 | if ( $@ ) { | ||||
7487 | if ($@ eq "connect timeout\n") {...} | ||||
7488 | else { # connect died } | ||||
7489 | } | ||||
7490 | |||||
7491 | See previous example for the reasoning around the double eval. | ||||
7492 | |||||
7493 | Similar techniques can be used for canceling statement execution. | ||||
7494 | |||||
7495 | Unfortunately, this solution is somewhat messy, and it does I<not> work with | ||||
7496 | perl versions less than perl 5.8 where C<POSIX::sigaction()> appears to be broken. | ||||
7497 | |||||
7498 | For a cleaner implementation that works across perl versions, see Lincoln Baxter's | ||||
7499 | Sys::SigAction module at L<http://search.cpan.org/~lbaxter/Sys-SigAction/>. | ||||
7500 | The documentation for Sys::SigAction includes an longer discussion | ||||
7501 | of this problem, and a DBD::Oracle test script. | ||||
7502 | |||||
7503 | Be sure to read all the signal handling sections of the L<perlipc> manual. | ||||
7504 | |||||
7505 | And finally, two more points to keep firmly in mind. Firstly, | ||||
7506 | remember that what we've done here is essentially revert to old | ||||
7507 | style I<unsafe> handling of these signals. So do as little as | ||||
7508 | possible in the handler. Ideally just die(). Secondly, the handles | ||||
7509 | in use at the time the signal is handled may not be safe to use | ||||
7510 | afterwards. | ||||
7511 | |||||
7512 | |||||
7513 | =head2 Subclassing the DBI | ||||
7514 | |||||
7515 | DBI can be subclassed and extended just like any other object | ||||
7516 | oriented module. Before we talk about how to do that, it's important | ||||
7517 | to be clear about the various DBI classes and how they work together. | ||||
7518 | |||||
7519 | By default C<$dbh = DBI-E<gt>connect(...)> returns a $dbh blessed | ||||
7520 | into the C<DBI::db> class. And the C<$dbh-E<gt>prepare> method | ||||
7521 | returns an $sth blessed into the C<DBI::st> class (actually it | ||||
7522 | simply changes the last four characters of the calling handle class | ||||
7523 | to be C<::st>). | ||||
7524 | |||||
7525 | The leading 'C<DBI>' is known as the 'root class' and the extra | ||||
7526 | 'C<::db>' or 'C<::st>' are the 'handle type suffixes'. If you want | ||||
7527 | to subclass the DBI you'll need to put your overriding methods into | ||||
7528 | the appropriate classes. For example, if you want to use a root class | ||||
7529 | of C<MySubDBI> and override the do(), prepare() and execute() methods, | ||||
7530 | then your do() and prepare() methods should be in the C<MySubDBI::db> | ||||
7531 | class and the execute() method should be in the C<MySubDBI::st> class. | ||||
7532 | |||||
7533 | To setup the inheritance hierarchy the @ISA variable in C<MySubDBI::db> | ||||
7534 | should include C<DBI::db> and the @ISA variable in C<MySubDBI::st> | ||||
7535 | should include C<DBI::st>. The C<MySubDBI> root class itself isn't | ||||
7536 | currently used for anything visible and so, apart from setting @ISA | ||||
7537 | to include C<DBI>, it can be left empty. | ||||
7538 | |||||
7539 | So, having put your overriding methods into the right classes, and | ||||
7540 | setup the inheritance hierarchy, how do you get the DBI to use them? | ||||
7541 | You have two choices, either a static method call using the name | ||||
7542 | of your subclass: | ||||
7543 | |||||
7544 | $dbh = MySubDBI->connect(...); | ||||
7545 | |||||
7546 | or specifying a C<RootClass> attribute: | ||||
7547 | |||||
7548 | $dbh = DBI->connect(..., { RootClass => 'MySubDBI' }); | ||||
7549 | |||||
7550 | If both forms are used then the attribute takes precedence. | ||||
7551 | |||||
7552 | The only differences between the two are that using an explicit | ||||
7553 | RootClass attribute will a) make the DBI automatically attempt to load | ||||
7554 | a module by that name if the class doesn't exist, and b) won't call | ||||
7555 | your MySubDBI::connect() method, if you have one. | ||||
7556 | |||||
7557 | When subclassing is being used then, after a successful new | ||||
7558 | connect, the DBI->connect method automatically calls: | ||||
7559 | |||||
7560 | $dbh->connected($dsn, $user, $pass, \%attr); | ||||
7561 | |||||
7562 | The default method does nothing. The call is made just to simplify | ||||
7563 | any post-connection setup that your subclass may want to perform. | ||||
7564 | The parameters are the same as passed to DBI->connect. | ||||
7565 | If your subclass supplies a connected method, it should be part of the | ||||
7566 | MySubDBI::db package. | ||||
7567 | |||||
7568 | One more thing to note: you must let the DBI do the handle creation. If you | ||||
7569 | want to override the connect() method in your *::dr class then it must still | ||||
7570 | call SUPER::connect to get a $dbh to work with. Similarly, an overridden | ||||
7571 | prepare() method in *::db must still call SUPER::prepare to get a $sth. | ||||
7572 | If you try to create your own handles using bless() then you'll find the DBI | ||||
7573 | will reject them with an "is not a DBI handle (has no magic)" error. | ||||
7574 | |||||
7575 | Here's a brief example of a DBI subclass. A more thorough example | ||||
7576 | can be found in F<t/subclass.t> in the DBI distribution. | ||||
7577 | |||||
7578 | package MySubDBI; | ||||
7579 | |||||
7580 | use strict; | ||||
7581 | |||||
7582 | use DBI; | ||||
7583 | use vars qw(@ISA); | ||||
7584 | @ISA = qw(DBI); | ||||
7585 | |||||
7586 | package MySubDBI::db; | ||||
7587 | use vars qw(@ISA); | ||||
7588 | @ISA = qw(DBI::db); | ||||
7589 | |||||
7590 | sub prepare { | ||||
7591 | my ($dbh, @args) = @_; | ||||
7592 | my $sth = $dbh->SUPER::prepare(@args) | ||||
7593 | or return; | ||||
7594 | $sth->{private_mysubdbi_info} = { foo => 'bar' }; | ||||
7595 | return $sth; | ||||
7596 | } | ||||
7597 | |||||
7598 | package MySubDBI::st; | ||||
7599 | use vars qw(@ISA); | ||||
7600 | @ISA = qw(DBI::st); | ||||
7601 | |||||
7602 | sub fetch { | ||||
7603 | my ($sth, @args) = @_; | ||||
7604 | my $row = $sth->SUPER::fetch(@args) | ||||
7605 | or return; | ||||
7606 | do_something_magical_with_row_data($row) | ||||
7607 | or return $sth->set_err(1234, "The magic failed", undef, "fetch"); | ||||
7608 | return $row; | ||||
7609 | } | ||||
7610 | |||||
7611 | When calling a SUPER::method that returns a handle, be careful to | ||||
7612 | check the return value before trying to do other things with it in | ||||
7613 | your overridden method. This is especially important if you want to | ||||
7614 | set a hash attribute on the handle, as Perl's autovivification will | ||||
7615 | bite you by (in)conveniently creating an unblessed hashref, which your | ||||
7616 | method will then return with usually baffling results later on like | ||||
7617 | the error "dbih_getcom handle HASH(0xa4451a8) is not a DBI handle (has | ||||
7618 | no magic". It's best to check right after the call and return undef | ||||
7619 | immediately on error, just like DBI would and just like the example | ||||
7620 | above. | ||||
7621 | |||||
7622 | If your method needs to record an error it should call the set_err() | ||||
7623 | method with the error code and error string, as shown in the example | ||||
7624 | above. The error code and error string will be recorded in the | ||||
7625 | handle and available via C<$h-E<gt>err> and C<$DBI::errstr> etc. | ||||
7626 | The set_err() method always returns an undef or empty list as | ||||
7627 | appropriate. Since your method should nearly always return an undef | ||||
7628 | or empty list as soon as an error is detected it's handy to simply | ||||
7629 | return what set_err() returns, as shown in the example above. | ||||
7630 | |||||
7631 | If the handle has C<RaiseError>, C<PrintError>, or C<HandleError> | ||||
7632 | etc. set then the set_err() method will honour them. This means | ||||
7633 | that if C<RaiseError> is set then set_err() won't return in the | ||||
7634 | normal way but will 'throw an exception' that can be caught with | ||||
7635 | an C<eval> block. | ||||
7636 | |||||
7637 | You can stash private data into DBI handles | ||||
7638 | via C<$h-E<gt>{private_..._*}>. See the entry under L</ATTRIBUTES | ||||
7639 | COMMON TO ALL HANDLES> for info and important caveats. | ||||
7640 | |||||
7641 | |||||
7642 | =head1 TRACING | ||||
7643 | |||||
7644 | The DBI has a powerful tracing mechanism built in. It enables you | ||||
7645 | to see what's going on 'behind the scenes', both within the DBI and | ||||
7646 | the drivers you're using. | ||||
7647 | |||||
7648 | =head2 Trace Settings | ||||
7649 | |||||
7650 | Which details are written to the trace output is controlled by a | ||||
7651 | combination of a I<trace level>, an integer from 0 to 15, and a set | ||||
7652 | of I<trace flags> that are either on or off. Together these are known | ||||
7653 | as the I<trace settings> and are stored together in a single integer. | ||||
7654 | For normal use you only need to set the trace level, and generally | ||||
7655 | only to a value between 1 and 4. | ||||
7656 | |||||
7657 | Each handle has its own trace settings, and so does the DBI. | ||||
7658 | When you call a method the DBI merges the handles settings into its | ||||
7659 | own for the duration of the call: the trace flags of the handle are | ||||
7660 | OR'd into the trace flags of the DBI, and if the handle has a higher | ||||
7661 | trace level then the DBI trace level is raised to match it. | ||||
7662 | The previous DBI trace settings are restored when the called method | ||||
7663 | returns. | ||||
7664 | |||||
7665 | =head2 Trace Levels | ||||
7666 | |||||
7667 | Trace I<levels> are as follows: | ||||
7668 | |||||
7669 | 0 - Trace disabled. | ||||
7670 | 1 - Trace top-level DBI method calls returning with results or errors. | ||||
7671 | 2 - As above, adding tracing of top-level method entry with parameters. | ||||
7672 | 3 - As above, adding some high-level information from the driver | ||||
7673 | and some internal information from the DBI. | ||||
7674 | 4 - As above, adding more detailed information from the driver. | ||||
7675 | This is the first level to trace all the rows being fetched. | ||||
7676 | 5 to 15 - As above but with more and more internal information. | ||||
7677 | |||||
7678 | Trace level 1 is best for a simple overview of what's happening. | ||||
7679 | Trace levels 2 thru 4 a good choice for general purpose tracing. | ||||
7680 | Levels 5 and above are best reserved for investigating a specific | ||||
7681 | problem, when you need to see "inside" the driver and DBI. | ||||
7682 | |||||
7683 | The trace output is detailed and typically very useful. Much of the | ||||
7684 | trace output is formatted using the L</neat> function, so strings | ||||
7685 | in the trace output may be edited and truncated by that function. | ||||
7686 | |||||
7687 | =head2 Trace Flags | ||||
7688 | |||||
7689 | Trace I<flags> are used to enable tracing of specific activities | ||||
7690 | within the DBI and drivers. The DBI defines some trace flags and | ||||
7691 | drivers can define others. DBI trace flag names begin with a capital | ||||
7692 | letter and driver specific names begin with a lowercase letter, as | ||||
7693 | usual. | ||||
7694 | |||||
7695 | Currently the DBI defines these trace flags: | ||||
7696 | |||||
7697 | ALL - turn on all DBI and driver flags (not recommended) | ||||
7698 | SQL - trace SQL statements executed | ||||
7699 | (not yet implemented in DBI but implemented in some DBDs) | ||||
7700 | CON - trace connection process | ||||
7701 | ENC - trace encoding (unicode translations etc) | ||||
7702 | (not yet implemented in DBI but implemented in some DBDs) | ||||
7703 | DBD - trace only DBD messages | ||||
7704 | (not implemented by all DBDs yet) | ||||
7705 | TXN - trace transactions | ||||
7706 | (not implemented in all DBDs yet) | ||||
7707 | |||||
7708 | The L</parse_trace_flags> and L</parse_trace_flag> methods are used | ||||
7709 | to convert trace flag names into the corresponding integer bit flags. | ||||
7710 | |||||
7711 | =head2 Enabling Trace | ||||
7712 | |||||
7713 | The C<$h-E<gt>trace> method sets the trace settings for a handle | ||||
7714 | and C<DBI-E<gt>trace> does the same for the DBI. | ||||
7715 | |||||
7716 | In addition to the L</trace> method, you can enable the same trace | ||||
7717 | information, and direct the output to a file, by setting the | ||||
7718 | C<DBI_TRACE> environment variable before starting Perl. | ||||
7719 | See L</DBI_TRACE> for more information. | ||||
7720 | |||||
7721 | Finally, you can set, or get, the trace settings for a handle using | ||||
7722 | the C<TraceLevel> attribute. | ||||
7723 | |||||
7724 | All of those methods use parse_trace_flags() and so allow you set | ||||
7725 | both the trace level and multiple trace flags by using a string | ||||
7726 | containing the trace level and/or flag names separated by vertical | ||||
7727 | bar ("C<|>") or comma ("C<,>") characters. For example: | ||||
7728 | |||||
7729 | local $h->{TraceLevel} = "3|SQL|foo"; | ||||
7730 | |||||
7731 | =head2 Trace Output | ||||
7732 | |||||
7733 | Initially trace output is written to C<STDERR>. Both the | ||||
7734 | C<$h-E<gt>trace> and C<DBI-E<gt>trace> methods take an optional | ||||
7735 | $trace_file parameter, which may be either the name of a file to be | ||||
7736 | opened by DBI in append mode, or a reference to an existing writable | ||||
7737 | (possibly layered) filehandle. If $trace_file is a filename, | ||||
7738 | and can be opened in append mode, or $trace_file is a writable | ||||
7739 | filehandle, then I<all> trace output (currently including that from | ||||
7740 | other handles) is redirected to that file. A warning is generated | ||||
7741 | if $trace_file can't be opened or is not writable. | ||||
7742 | |||||
7743 | Further calls to trace() without $trace_file do not alter where | ||||
7744 | the trace output is sent. If $trace_file is undefined, then | ||||
7745 | trace output is sent to C<STDERR> and, if the prior trace was opened with | ||||
7746 | $trace_file as a filename, the previous trace file is closed; if $trace_file was | ||||
7747 | a filehandle, the filehandle is B<not> closed. | ||||
7748 | |||||
7749 | B<NOTE>: If $trace_file is specified as a filehandle, the filehandle | ||||
7750 | should not be closed until all DBI operations are completed, or the | ||||
7751 | application has reset the trace file via another call to | ||||
7752 | C<trace()> that changes the trace file. | ||||
7753 | |||||
7754 | =head2 Tracing to Layered Filehandles | ||||
7755 | |||||
7756 | B<NOTE>: | ||||
7757 | |||||
7758 | =over 4 | ||||
7759 | |||||
7760 | =item * | ||||
7761 | Tied filehandles are not currently supported, as | ||||
7762 | tie operations are not available to the PerlIO | ||||
7763 | methods used by the DBI. | ||||
7764 | |||||
7765 | =item * | ||||
7766 | PerlIO layer support requires Perl version 5.8 or higher. | ||||
7767 | |||||
7768 | =back | ||||
7769 | |||||
7770 | As of version 5.8, Perl provides the ability to layer various | ||||
7771 | "disciplines" on an open filehandle via the L<PerlIO> module. | ||||
7772 | |||||
7773 | A simple example of using PerlIO layers is to use a scalar as the output: | ||||
7774 | |||||
7775 | my $scalar = ''; | ||||
7776 | open( my $fh, "+>:scalar", \$scalar ); | ||||
7777 | $dbh->trace( 2, $fh ); | ||||
7778 | |||||
7779 | Now all trace output is simply appended to $scalar. | ||||
7780 | |||||
7781 | A more complex application of tracing to a layered filehandle is the | ||||
7782 | use of a custom layer (I<Refer to >L<Perlio::via> I<for details | ||||
7783 | on creating custom PerlIO layers.>). Consider an application with the | ||||
7784 | following logger module: | ||||
7785 | |||||
7786 | package MyFancyLogger; | ||||
7787 | |||||
7788 | sub new | ||||
7789 | { | ||||
7790 | my $self = {}; | ||||
7791 | my $fh; | ||||
7792 | open $fh, '>', 'fancylog.log'; | ||||
7793 | $self->{_fh} = $fh; | ||||
7794 | $self->{_buf} = ''; | ||||
7795 | return bless $self, shift; | ||||
7796 | } | ||||
7797 | |||||
7798 | sub log | ||||
7799 | { | ||||
7800 | my $self = shift; | ||||
7801 | return unless exists $self->{_fh}; | ||||
7802 | my $fh = $self->{_fh}; | ||||
7803 | $self->{_buf} .= shift; | ||||
7804 | # | ||||
7805 | # DBI feeds us pieces at a time, so accumulate a complete line | ||||
7806 | # before outputing | ||||
7807 | # | ||||
7808 | print $fh "At ", scalar localtime(), ':', $self->{_buf}, "\n" and | ||||
7809 | $self->{_buf} = '' | ||||
7810 | if $self->{_buf}=~tr/\n//; | ||||
7811 | } | ||||
7812 | |||||
7813 | sub close { | ||||
7814 | my $self = shift; | ||||
7815 | return unless exists $self->{_fh}; | ||||
7816 | my $fh = $self->{_fh}; | ||||
7817 | print $fh "At ", scalar localtime(), ':', $self->{_buf}, "\n" and | ||||
7818 | $self->{_buf} = '' | ||||
7819 | if $self->{_buf}; | ||||
7820 | close $fh; | ||||
7821 | delete $self->{_fh}; | ||||
7822 | } | ||||
7823 | |||||
7824 | 1; | ||||
7825 | |||||
7826 | To redirect DBI traces to this logger requires creating | ||||
7827 | a package for the layer: | ||||
7828 | |||||
7829 | package PerlIO::via::MyFancyLogLayer; | ||||
7830 | |||||
7831 | sub PUSHED | ||||
7832 | { | ||||
7833 | my ($class,$mode,$fh) = @_; | ||||
7834 | my $logger; | ||||
7835 | return bless \$logger,$class; | ||||
7836 | } | ||||
7837 | |||||
7838 | sub OPEN { | ||||
7839 | my ($self, $path, $mode, $fh) = @_; | ||||
7840 | # | ||||
7841 | # $path is actually our logger object | ||||
7842 | # | ||||
7843 | $$self = $path; | ||||
7844 | return 1; | ||||
7845 | } | ||||
7846 | |||||
7847 | sub WRITE | ||||
7848 | { | ||||
7849 | my ($self, $buf, $fh) = @_; | ||||
7850 | $$self->log($buf); | ||||
7851 | return length($buf); | ||||
7852 | } | ||||
7853 | |||||
7854 | sub CLOSE { | ||||
7855 | my $self = shift; | ||||
7856 | $$self->close(); | ||||
7857 | return 0; | ||||
7858 | } | ||||
7859 | |||||
7860 | 1; | ||||
7861 | |||||
7862 | |||||
7863 | The application can then cause DBI traces to be routed to the | ||||
7864 | logger using | ||||
7865 | |||||
7866 | use PerlIO::via::MyFancyLogLayer; | ||||
7867 | |||||
7868 | open my $fh, '>:via(MyFancyLogLayer)', MyFancyLogger->new(); | ||||
7869 | |||||
7870 | $dbh->trace('SQL', $fh); | ||||
7871 | |||||
7872 | Now all trace output will be processed by MyFancyLogger's | ||||
7873 | log() method. | ||||
7874 | |||||
7875 | =head2 Trace Content | ||||
7876 | |||||
7877 | Many of the values embedded in trace output are formatted using the neat() | ||||
7878 | utility function. This means they may be quoted, sanitized, and possibly | ||||
7879 | truncated if longer than C<$DBI::neat_maxlen>. See L</neat> for more details. | ||||
7880 | |||||
7881 | =head2 Tracing Tips | ||||
7882 | |||||
7883 | You can add tracing to your own application code using the L</trace_msg> method. | ||||
7884 | |||||
7885 | It can sometimes be handy to compare trace files from two different runs of the | ||||
7886 | same script. However using a tool like C<diff> on the original log output | ||||
7887 | doesn't work well because the trace file is full of object addresses that may | ||||
7888 | differ on each run. | ||||
7889 | |||||
7890 | The DBI includes a handy utility called dbilogstrip that can be used to | ||||
7891 | 'normalize' the log content. It can be used as a filter like this: | ||||
7892 | |||||
7893 | DBI_TRACE=2 perl yourscript.pl ...args1... 2>&1 | dbilogstrip > dbitrace1.log | ||||
7894 | DBI_TRACE=2 perl yourscript.pl ...args2... 2>&1 | dbilogstrip > dbitrace2.log | ||||
7895 | diff -u dbitrace1.log dbitrace2.log | ||||
7896 | |||||
7897 | See L<dbilogstrip> for more information. | ||||
7898 | |||||
7899 | =head1 DBI ENVIRONMENT VARIABLES | ||||
7900 | |||||
7901 | The DBI module recognizes a number of environment variables, but most of | ||||
7902 | them should not be used most of the time. | ||||
7903 | It is better to be explicit about what you are doing to avoid the need | ||||
7904 | for environment variables, especially in a web serving system where web | ||||
7905 | servers are stingy about which environment variables are available. | ||||
7906 | |||||
7907 | =head2 DBI_DSN | ||||
7908 | |||||
7909 | The DBI_DSN environment variable is used by DBI->connect if you do not | ||||
7910 | specify a data source when you issue the connect. | ||||
7911 | It should have a format such as "dbi:Driver:databasename". | ||||
7912 | |||||
7913 | =head2 DBI_DRIVER | ||||
7914 | |||||
7915 | The DBI_DRIVER environment variable is used to fill in the database | ||||
7916 | driver name in DBI->connect if the data source string starts "dbi::" | ||||
7917 | (thereby omitting the driver). | ||||
7918 | If DBI_DSN omits the driver name, DBI_DRIVER can fill the gap. | ||||
7919 | |||||
7920 | =head2 DBI_AUTOPROXY | ||||
7921 | |||||
7922 | The DBI_AUTOPROXY environment variable takes a string value that starts | ||||
7923 | "dbi:Proxy:" and is typically followed by "hostname=...;port=...". | ||||
7924 | It is used to alter the behaviour of DBI->connect. | ||||
7925 | For full details, see DBI::Proxy documentation. | ||||
7926 | |||||
7927 | =head2 DBI_USER | ||||
7928 | |||||
7929 | The DBI_USER environment variable takes a string value that is used as | ||||
7930 | the user name if the DBI->connect call is given undef (as distinct from | ||||
7931 | an empty string) as the username argument. | ||||
7932 | Be wary of the security implications of using this. | ||||
7933 | |||||
7934 | =head2 DBI_PASS | ||||
7935 | |||||
7936 | The DBI_PASS environment variable takes a string value that is used as | ||||
7937 | the password if the DBI->connect call is given undef (as distinct from | ||||
7938 | an empty string) as the password argument. | ||||
7939 | Be extra wary of the security implications of using this. | ||||
7940 | |||||
7941 | =head2 DBI_DBNAME (obsolete) | ||||
7942 | |||||
7943 | The DBI_DBNAME environment variable takes a string value that is used only when the | ||||
7944 | obsolescent style of DBI->connect (with driver name as fourth parameter) is used, and | ||||
7945 | when no value is provided for the first (database name) argument. | ||||
7946 | |||||
7947 | =head2 DBI_TRACE | ||||
7948 | |||||
7949 | The DBI_TRACE environment variable specifies the global default | ||||
7950 | trace settings for the DBI at startup. Can also be used to direct | ||||
7951 | trace output to a file. When the DBI is loaded it does: | ||||
7952 | |||||
7953 | DBI->trace(split /=/, $ENV{DBI_TRACE}, 2) if $ENV{DBI_TRACE}; | ||||
7954 | |||||
7955 | So if C<DBI_TRACE> contains an "C<=>" character then what follows | ||||
7956 | it is used as the name of the file to append the trace to. | ||||
7957 | |||||
7958 | output appended to that file. If the name begins with a number | ||||
7959 | followed by an equal sign (C<=>), then the number and the equal sign are | ||||
7960 | stripped off from the name, and the number is used to set the trace | ||||
7961 | level. For example: | ||||
7962 | |||||
7963 | DBI_TRACE=1=dbitrace.log perl your_test_script.pl | ||||
7964 | |||||
7965 | On Unix-like systems using a Bourne-like shell, you can do this easily | ||||
7966 | on the command line: | ||||
7967 | |||||
7968 | DBI_TRACE=2 perl your_test_script.pl | ||||
7969 | |||||
7970 | See L</TRACING> for more information. | ||||
7971 | |||||
7972 | =head2 PERL_DBI_DEBUG (obsolete) | ||||
7973 | |||||
7974 | An old variable that should no longer be used; equivalent to DBI_TRACE. | ||||
7975 | |||||
7976 | =head2 DBI_PROFILE | ||||
7977 | |||||
7978 | The DBI_PROFILE environment variable can be used to enable profiling | ||||
7979 | of DBI method calls. See L<DBI::Profile> for more information. | ||||
7980 | |||||
7981 | =head2 DBI_PUREPERL | ||||
7982 | |||||
7983 | The DBI_PUREPERL environment variable can be used to enable the | ||||
7984 | use of DBI::PurePerl. See L<DBI::PurePerl> for more information. | ||||
7985 | |||||
7986 | =head1 WARNING AND ERROR MESSAGES | ||||
7987 | |||||
7988 | =head2 Fatal Errors | ||||
7989 | |||||
7990 | =over 4 | ||||
7991 | |||||
7992 | =item Can't call method "prepare" without a package or object reference | ||||
7993 | |||||
7994 | The C<$dbh> handle you're using to call C<prepare> is probably undefined because | ||||
7995 | the preceding C<connect> failed. You should always check the return status of | ||||
7996 | DBI methods, or use the L</RaiseError> attribute. | ||||
7997 | |||||
7998 | =item Can't call method "execute" without a package or object reference | ||||
7999 | |||||
8000 | The C<$sth> handle you're using to call C<execute> is probably undefined because | ||||
8001 | the preceding C<prepare> failed. You should always check the return status of | ||||
8002 | DBI methods, or use the L</RaiseError> attribute. | ||||
8003 | |||||
8004 | =item DBI/DBD internal version mismatch | ||||
8005 | |||||
8006 | The DBD driver module was built with a different version of DBI than | ||||
8007 | the one currently being used. You should rebuild the DBD module under | ||||
8008 | the current version of DBI. | ||||
8009 | |||||
8010 | (Some rare platforms require "static linking". On those platforms, there | ||||
8011 | may be an old DBI or DBD driver version actually embedded in the Perl | ||||
8012 | executable being used.) | ||||
8013 | |||||
8014 | =item DBD driver has not implemented the AutoCommit attribute | ||||
8015 | |||||
8016 | The DBD driver implementation is incomplete. Consult the author. | ||||
8017 | |||||
8018 | =item Can't [sg]et %s->{%s}: unrecognised attribute | ||||
8019 | |||||
8020 | You attempted to set or get an unknown attribute of a handle. Make | ||||
8021 | sure you have spelled the attribute name correctly; case is significant | ||||
8022 | (e.g., "Autocommit" is not the same as "AutoCommit"). | ||||
8023 | |||||
8024 | =back | ||||
8025 | |||||
8026 | =head1 Pure-Perl DBI | ||||
8027 | |||||
8028 | A pure-perl emulation of the DBI is included in the distribution | ||||
8029 | for people using pure-perl drivers who, for whatever reason, can't | ||||
8030 | install the compiled DBI. See L<DBI::PurePerl>. | ||||
8031 | |||||
8032 | =head1 SEE ALSO | ||||
8033 | |||||
8034 | =head2 Driver and Database Documentation | ||||
8035 | |||||
8036 | Refer to the documentation for the DBD driver that you are using. | ||||
8037 | |||||
8038 | Refer to the SQL Language Reference Manual for the database engine that you are using. | ||||
8039 | |||||
8040 | =head2 ODBC and SQL/CLI Standards Reference Information | ||||
8041 | |||||
8042 | More detailed information about the semantics of certain DBI methods | ||||
8043 | that are based on ODBC and SQL/CLI standards is available on-line | ||||
8044 | via microsoft.com, for ODBC, and www.jtc1sc32.org for the SQL/CLI | ||||
8045 | standard: | ||||
8046 | |||||
8047 | DBI method ODBC function SQL/CLI Working Draft | ||||
8048 | ---------- ------------- --------------------- | ||||
8049 | column_info SQLColumns Page 124 | ||||
8050 | foreign_key_info SQLForeignKeys Page 163 | ||||
8051 | get_info SQLGetInfo Page 214 | ||||
8052 | primary_key_info SQLPrimaryKeys Page 254 | ||||
8053 | table_info SQLTables Page 294 | ||||
8054 | type_info SQLGetTypeInfo Page 239 | ||||
8055 | statistics_info SQLStatistics | ||||
8056 | |||||
8057 | To find documentation on the ODBC function you can use | ||||
8058 | the MSDN search facility at: | ||||
8059 | |||||
8060 | http://msdn.microsoft.com/Search | ||||
8061 | |||||
8062 | and search for something like C<"SQLColumns returns">. | ||||
8063 | |||||
8064 | And for SQL/CLI standard information on SQLColumns you'd read page 124 of | ||||
8065 | the (very large) SQL/CLI Working Draft available from: | ||||
8066 | |||||
8067 | http://jtc1sc32.org/doc/N0701-0750/32N0744T.pdf | ||||
8068 | |||||
8069 | =head2 Standards Reference Information | ||||
8070 | |||||
8071 | A hyperlinked, browsable version of the BNF syntax for SQL92 (plus | ||||
8072 | Oracle 7 SQL and PL/SQL) is available here: | ||||
8073 | |||||
8074 | http://cui.unige.ch/db-research/Enseignement/analyseinfo/SQL92/BNFindex.html | ||||
8075 | |||||
8076 | A BNF syntax for SQL3 is available here: | ||||
8077 | |||||
8078 | http://www.sqlstandards.org/SC32/WG3/Progression_Documents/Informal_working_drafts/iso-9075-2-1999.bnf | ||||
8079 | |||||
8080 | The following links provide further useful information about SQL. | ||||
8081 | Some of these are rather dated now but may still be useful. | ||||
8082 | |||||
8083 | http://www.jcc.com/SQLPages/jccs_sql.htm | ||||
8084 | http://www.contrib.andrew.cmu.edu/~shadow/sql.html | ||||
8085 | http://www.altavista.com/query?q=sql+tutorial | ||||
8086 | |||||
8087 | |||||
8088 | =head2 Books and Articles | ||||
8089 | |||||
8090 | Programming the Perl DBI, by Alligator Descartes and Tim Bunce. | ||||
8091 | L<http://books.perl.org/book/154> | ||||
8092 | |||||
8093 | Programming Perl 3rd Ed. by Larry Wall, Tom Christiansen & Jon Orwant. | ||||
8094 | L<http://books.perl.org/book/134> | ||||
8095 | |||||
8096 | Learning Perl by Randal Schwartz. | ||||
8097 | L<http://books.perl.org/book/101> | ||||
8098 | |||||
8099 | Details of many other books related to perl can be found at L<http://books.perl.org> | ||||
8100 | |||||
8101 | =head2 Perl Modules | ||||
8102 | |||||
8103 | Index of DBI related modules available from CPAN: | ||||
8104 | |||||
8105 | https://metacpan.org/search?q=DBD%3A%3A | ||||
8106 | https://metacpan.org/search?q=DBIx%3A%3A | ||||
8107 | https://metacpan.org/search?q=DBI | ||||
8108 | |||||
8109 | For a good comparison of RDBMS-OO mappers and some OO-RDBMS mappers | ||||
8110 | (including Class::DBI, Alzabo, and DBIx::RecordSet in the former | ||||
8111 | category and Tangram and SPOPS in the latter) see the Perl | ||||
8112 | Object-Oriented Persistence project pages at: | ||||
8113 | |||||
8114 | http://poop.sourceforge.net | ||||
8115 | |||||
8116 | A similar page for Java toolkits can be found at: | ||||
8117 | |||||
8118 | http://c2.com/cgi-bin/wiki?ObjectRelationalToolComparison | ||||
8119 | |||||
8120 | =head2 Mailing List | ||||
8121 | |||||
8122 | The I<dbi-users> mailing list is the primary means of communication among | ||||
8123 | users of the DBI and its related modules. For details send email to: | ||||
8124 | |||||
8125 | dbi-users-help@perl.org | ||||
8126 | |||||
8127 | There are typically between 700 and 900 messages per month. You have | ||||
8128 | to subscribe in order to be able to post. However you can opt for a | ||||
8129 | 'post-only' subscription. | ||||
8130 | |||||
8131 | Mailing list archives (of variable quality) are held at: | ||||
8132 | |||||
8133 | http://groups.google.com/groups?group=perl.dbi.users | ||||
8134 | http://www.xray.mpe.mpg.de/mailing-lists/dbi/ | ||||
8135 | http://www.mail-archive.com/dbi-users%40perl.org/ | ||||
8136 | |||||
8137 | =head2 Assorted Related WWW Links | ||||
8138 | |||||
8139 | The DBI "Home Page": | ||||
8140 | |||||
8141 | http://dbi.perl.org/ | ||||
8142 | |||||
8143 | Other DBI related links: | ||||
8144 | |||||
8145 | http://tegan.deltanet.com/~phlip/DBUIdoc.html | ||||
8146 | http://dc.pm.org/perl_db.html | ||||
8147 | http://wdvl.com/Authoring/DB/Intro/toc.html | ||||
8148 | http://www.hotwired.com/webmonkey/backend/tutorials/tutorial1.html | ||||
8149 | http://bumppo.net/lists/macperl/1999/06/msg00197.html | ||||
8150 | http://www.perlmonks.org/?node=DBI%20recipes | ||||
8151 | http://www.perlmonks.org/?node=Speeding%20up%20the%20DBI | ||||
8152 | |||||
8153 | Other database related links: | ||||
8154 | |||||
8155 | http://www.jcc.com/sql_stnd.html | ||||
8156 | http://cuiwww.unige.ch/OSG/info/FreeDB/FreeDB.home.html | ||||
8157 | http://www.connectionstrings.com/ | ||||
8158 | |||||
8159 | Security, especially the "SQL Injection" attack: | ||||
8160 | |||||
8161 | http://www.ngssoftware.com/research/papers.html | ||||
8162 | http://www.ngssoftware.com/papers/advanced_sql_injection.pdf | ||||
8163 | http://www.ngssoftware.com/papers/more_advanced_sql_injection.pdf | ||||
8164 | http://www.esecurityplanet.com/trends/article.php/2243461 | ||||
8165 | http://www.spidynamics.com/papers/SQLInjectionWhitePaper.pdf | ||||
8166 | http://www.imperva.com/application_defense_center/white_papers/blind_sql_server_injection.html | ||||
8167 | http://online.securityfocus.com/infocus/1644 | ||||
8168 | |||||
8169 | Commercial and Data Warehouse Links | ||||
8170 | |||||
8171 | http://www.dwinfocenter.org | ||||
8172 | http://www.datawarehouse.com | ||||
8173 | http://www.datamining.org | ||||
8174 | http://www.olapcouncil.org | ||||
8175 | http://www.idwa.org | ||||
8176 | http://www.knowledgecenters.org/dwcenter.asp | ||||
8177 | |||||
8178 | Recommended Perl Programming Links | ||||
8179 | |||||
8180 | http://language.perl.com/style/ | ||||
8181 | |||||
8182 | |||||
8183 | =head2 FAQ | ||||
8184 | |||||
8185 | See L<http://faq.dbi-support.com/> | ||||
8186 | |||||
8187 | =head1 AUTHORS | ||||
8188 | |||||
8189 | DBI by Tim Bunce, L<http://www.tim.bunce.name> | ||||
8190 | |||||
8191 | This pod text by Tim Bunce, J. Douglas Dunlop, Jonathan Leffler and others. | ||||
8192 | Perl by Larry Wall and the C<perl5-porters>. | ||||
8193 | |||||
8194 | =head1 COPYRIGHT | ||||
8195 | |||||
8196 | The DBI module is Copyright (c) 1994-2012 Tim Bunce. Ireland. | ||||
8197 | All rights reserved. | ||||
8198 | |||||
8199 | You may distribute under the terms of either the GNU General Public | ||||
8200 | License or the Artistic License, as specified in the Perl 5.10.0 README file. | ||||
8201 | |||||
8202 | =head1 SUPPORT / WARRANTY | ||||
8203 | |||||
8204 | The DBI is free Open Source software. IT COMES WITHOUT WARRANTY OF ANY KIND. | ||||
8205 | |||||
8206 | =head2 Support | ||||
8207 | |||||
8208 | My consulting company, Data Plan Services, offers annual and | ||||
8209 | multi-annual support contracts for the DBI. These provide sustained | ||||
8210 | support for DBI development, and sustained value for you in return. | ||||
8211 | Contact me for details. | ||||
8212 | |||||
8213 | =head2 Sponsor Enhancements | ||||
8214 | |||||
8215 | If your company would benefit from a specific new DBI feature, | ||||
8216 | please consider sponsoring its development. Work is performed | ||||
8217 | rapidly, and usually on a fixed-price payment-on-delivery basis. | ||||
8218 | Contact me for details. | ||||
8219 | |||||
8220 | Using such targeted financing allows you to contribute to DBI | ||||
8221 | development, and rapidly get something specific and valuable in return. | ||||
8222 | |||||
8223 | =head1 ACKNOWLEDGEMENTS | ||||
8224 | |||||
8225 | I would like to acknowledge the valuable contributions of the many | ||||
8226 | people I have worked with on the DBI project, especially in the early | ||||
8227 | years (1992-1994). In no particular order: Kevin Stock, Buzz Moschetti, | ||||
8228 | Kurt Andersen, Ted Lemon, William Hails, Garth Kennedy, Michael Peppler, | ||||
8229 | Neil S. Briscoe, Jeff Urlwin, David J. Hughes, Jeff Stander, | ||||
8230 | Forrest D Whitcher, Larry Wall, Jeff Fried, Roy Johnson, Paul Hudson, | ||||
8231 | Georg Rehfeld, Steve Sizemore, Ron Pool, Jon Meek, Tom Christiansen, | ||||
8232 | Steve Baumgarten, Randal Schwartz, and a whole lot more. | ||||
8233 | |||||
8234 | Then, of course, there are the poor souls who have struggled through | ||||
8235 | untold and undocumented obstacles to actually implement DBI drivers. | ||||
8236 | Among their ranks are Jochen Wiedmann, Alligator Descartes, Jonathan | ||||
8237 | Leffler, Jeff Urlwin, Michael Peppler, Henrik Tougaard, Edwin Pratomo, | ||||
8238 | Davide Migliavacca, Jan Pazdziora, Peter Haworth, Edmund Mergl, Steve | ||||
8239 | Williams, Thomas Lowery, and Phlip Plumlee. Without them, the DBI would | ||||
8240 | not be the practical reality it is today. I'm also especially grateful | ||||
8241 | to Alligator Descartes for starting work on the first edition of the | ||||
8242 | "Programming the Perl DBI" book and letting me jump on board. | ||||
8243 | |||||
8244 | The DBI and DBD::Oracle were originally developed while I was Technical | ||||
8245 | Director (CTO) of the Paul Ingram Group in the UK. So I'd especially like | ||||
8246 | to thank Paul for his generosity and vision in supporting this work for many years. | ||||
8247 | |||||
8248 | A couple of specific DBI features have been sponsored by enlightened companies: | ||||
8249 | |||||
8250 | The development of the swap_inner_handle() method was sponsored by BizRate.com (L<http://BizRate.com>) | ||||
8251 | |||||
8252 | The development of DBD::Gofer and related modules was sponsored by | ||||
8253 | Shopzilla.com (L<http://Shopzilla.com>), where I currently work. | ||||
8254 | |||||
8255 | =head1 CONTRIBUTING | ||||
8256 | |||||
8257 | As you can see above, many people have contributed to the DBI and | ||||
8258 | drivers in many ways over many years. | ||||
8259 | |||||
8260 | If you'd like to help then see L<http://dbi.perl.org/contributing>. | ||||
8261 | |||||
8262 | If you'd like the DBI to do something new or different then a good way | ||||
8263 | to make that happen is to do it yourself and send me a patch to the | ||||
8264 | source code that shows the changes. (But read "Speak before you patch" | ||||
8265 | below.) | ||||
8266 | |||||
8267 | =head2 Browsing the source code repository | ||||
8268 | |||||
8269 | Use https://github.com/perl5-dbi/dbi | ||||
8270 | |||||
8271 | =head2 How to create a patch using Git | ||||
8272 | |||||
8273 | The DBI source code is maintained using Git. To access the source | ||||
8274 | you'll need to install a Git client. Then, to get the source code, do: | ||||
8275 | |||||
8276 | git clone https://github.com/perl5-dbi/dbi.git DBI-git | ||||
8277 | |||||
8278 | The source code will now be available in the new subdirectory C<DBI-git>. | ||||
8279 | |||||
8280 | When you want to synchronize later, issue the command | ||||
8281 | |||||
8282 | git pull --all | ||||
8283 | |||||
8284 | Make your changes, test them, test them again until everything passes. | ||||
8285 | If there are no tests for the new feature you added or a behaviour change, | ||||
8286 | the change should include a new test. Then commit the changes. Either use | ||||
8287 | |||||
8288 | git gui | ||||
8289 | |||||
8290 | or | ||||
8291 | |||||
8292 | git commit -a -m 'Message to my changes' | ||||
8293 | |||||
8294 | If you get any conflicts reported you'll need to fix them first. | ||||
8295 | |||||
8296 | Then generate the patch file to be mailed: | ||||
8297 | |||||
8298 | git format-patch -1 --attach | ||||
8299 | |||||
8300 | which will create a file 0001-*.patch (where * relates to the commit message). | ||||
8301 | Read the patch file, as a sanity check, and then email it to dbi-dev@perl.org. | ||||
8302 | |||||
8303 | If you have a L<github|https://github.com> account, you can also fork the | ||||
8304 | repository, commit your changes to the forked repository and then do a | ||||
8305 | pull request. | ||||
8306 | |||||
8307 | =head2 How to create a patch without Git | ||||
8308 | |||||
8309 | Unpack a fresh copy of the distribution: | ||||
8310 | |||||
8311 | wget http://cpan.metacpan.org/authors/id/T/TI/TIMB/DBI-1.627.tar.gz | ||||
8312 | tar xfz DBI-1.627.tar.gz | ||||
8313 | |||||
8314 | Rename the newly created top level directory: | ||||
8315 | |||||
8316 | mv DBI-1.627 DBI-1.627.your_foo | ||||
8317 | |||||
8318 | Edit the contents of DBI-1.627.your_foo/* till it does what you want. | ||||
8319 | |||||
8320 | Test your changes and then remove all temporary files: | ||||
8321 | |||||
8322 | make test && make distclean | ||||
8323 | |||||
8324 | Go back to the directory you originally unpacked the distribution: | ||||
8325 | |||||
8326 | cd .. | ||||
8327 | |||||
8328 | Unpack I<another> copy of the original distribution you started with: | ||||
8329 | |||||
8330 | tar xfz DBI-1.627.tar.gz | ||||
8331 | |||||
8332 | Then create a patch file by performing a recursive C<diff> on the two | ||||
8333 | top level directories: | ||||
8334 | |||||
8335 | diff -purd DBI-1.627 DBI-1.627.your_foo > DBI-1.627.your_foo.patch | ||||
8336 | |||||
8337 | =head2 Speak before you patch | ||||
8338 | |||||
8339 | For anything non-trivial or possibly controversial it's a good idea | ||||
8340 | to discuss (on dbi-dev@perl.org) the changes you propose before | ||||
8341 | actually spending time working on them. Otherwise you run the risk | ||||
8342 | of them being rejected because they don't fit into some larger plans | ||||
8343 | you may not be aware of. | ||||
8344 | |||||
8345 | You can also reach the developers on IRC (chat). If they are on-line, | ||||
8346 | the most likely place to talk to them is the #dbi channel on irc.perl.org | ||||
8347 | |||||
8348 | =head1 TRANSLATIONS | ||||
8349 | |||||
8350 | A German translation of this manual (possibly slightly out of date) is | ||||
8351 | available, thanks to O'Reilly, at: | ||||
8352 | |||||
8353 | http://www.oreilly.de/catalog/perldbiger/ | ||||
8354 | |||||
8355 | Some other translations: | ||||
8356 | |||||
8357 | http://cronopio.net/perl/ - Spanish | ||||
8358 | http://member.nifty.ne.jp/hippo2000/dbimemo.htm - Japanese | ||||
8359 | |||||
8360 | =head1 TRAINING | ||||
8361 | |||||
8362 | References to DBI related training resources. No recommendation implied. | ||||
8363 | |||||
8364 | http://www.treepax.co.uk/ | ||||
8365 | http://www.keller.com/dbweb/ | ||||
8366 | |||||
8367 | (If you offer professional DBI related training services, | ||||
8368 | please send me your details so I can add them here.) | ||||
8369 | |||||
8370 | =head1 OTHER RELATED WORK AND PERL MODULES | ||||
8371 | |||||
8372 | =over 4 | ||||
8373 | |||||
8374 | =item Apache::DBI by E.Mergl@bawue.de | ||||
8375 | |||||
8376 | To be used with the Apache daemon together with an embedded Perl | ||||
8377 | interpreter like C<mod_perl>. Establishes a database connection which | ||||
8378 | remains open for the lifetime of the HTTP daemon. This way the CGI | ||||
8379 | connect and disconnect for every database access becomes superfluous. | ||||
8380 | |||||
8381 | =item SQL Parser | ||||
8382 | |||||
8383 | See also the L<SQL::Statement> module, SQL parser and engine. | ||||
8384 | |||||
8385 | =back | ||||
8386 | |||||
8387 | =cut | ||||
8388 | |||||
8389 | # LocalWords: DBI |