File | /wise/base/static/lib/perl5/site_perl/5.10.0/x86_64-linux-thread-multi/DBI.pm | Statements Executed | 711 | Total Time | 0.017077 seconds |
Calls | P | F | Exclusive Time |
Inclusive Time |
Subroutine | |
---|---|---|---|---|---|---|
1 | 1 | 1 | 0.00358 | 0.00659 | DBI:: | install_driver |
88 | 1 | 2 | 0.00062 | 0.00062 | DBI:: | _install_method (xsub) |
2 | 1 | 2 | 0.00042 | 0.00042 | DBI:: | bootstrap (xsub) |
6 | 3 | 2 | 0.00022 | 0.00022 | DBI:: | _new_handle (xsub) |
2 | 2 | 1 | 0.00021 | 0.00028 | DBI:: | setup_driver |
1 | 1 | 1 | 0.00016 | 0.00500 | DBI:: | __ANON__[:703] |
1 | 1 | 1 | 0.00012 | 0.01175 | DBI:: | connect |
3 | 1 | 1 | 6.2e-5 | 0.00018 | DBI:: | _new_sth |
1 | 1 | 1 | 3.1e-5 | 6.0e-5 | DBI:: | disconnect_all |
1 | 1 | 1 | 2.4e-5 | 8.5e-5 | DBI:: | _new_drh |
1 | 1 | 1 | 2.3e-5 | 6.0e-5 | DBI:: | _new_dbh |
2 | 1 | 2 | 1.2e-5 | 1.2e-5 | DBD::_::common:: | trace_msg (xsub) |
0 | 0 | 0 | 0 | 0 | DBD::Switch::dr:: | CLONE |
0 | 0 | 0 | 0 | 0 | DBD::Switch::dr:: | FETCH |
0 | 0 | 0 | 0 | 0 | DBD::Switch::dr:: | STORE |
0 | 0 | 0 | 0 | 0 | DBD::Switch::dr:: | driver |
0 | 0 | 0 | 0 | 0 | DBD::_::common:: | BEGIN |
0 | 0 | 0 | 0 | 0 | DBD::_::common:: | CLEAR |
0 | 0 | 0 | 0 | 0 | DBD::_::common:: | EXISTS |
0 | 0 | 0 | 0 | 0 | DBD::_::common:: | FETCH_many |
0 | 0 | 0 | 0 | 0 | DBD::_::common:: | FIRSTKEY |
0 | 0 | 0 | 0 | 0 | DBD::_::common:: | NEXTKEY |
0 | 0 | 0 | 0 | 0 | DBD::_::common:: | _not_impl |
0 | 0 | 0 | 0 | 0 | DBD::_::common:: | install_method |
0 | 0 | 0 | 0 | 0 | DBD::_::common:: | parse_trace_flag |
0 | 0 | 0 | 0 | 0 | DBD::_::common:: | parse_trace_flags |
0 | 0 | 0 | 0 | 0 | DBD::_::common:: | private_attribute_info |
0 | 0 | 0 | 0 | 0 | DBD::_::db:: | BEGIN |
0 | 0 | 0 | 0 | 0 | DBD::_::db:: | _do_selectrow |
0 | 0 | 0 | 0 | 0 | DBD::_::db:: | begin_work |
0 | 0 | 0 | 0 | 0 | DBD::_::db:: | clone |
0 | 0 | 0 | 0 | 0 | DBD::_::db:: | data_sources |
0 | 0 | 0 | 0 | 0 | DBD::_::db:: | do |
0 | 0 | 0 | 0 | 0 | DBD::_::db:: | ping |
0 | 0 | 0 | 0 | 0 | DBD::_::db:: | prepare_cached |
0 | 0 | 0 | 0 | 0 | DBD::_::db:: | primary_key |
0 | 0 | 0 | 0 | 0 | DBD::_::db:: | quote |
0 | 0 | 0 | 0 | 0 | DBD::_::db:: | quote_identifier |
0 | 0 | 0 | 0 | 0 | DBD::_::db:: | rows |
0 | 0 | 0 | 0 | 0 | DBD::_::db:: | selectall_arrayref |
0 | 0 | 0 | 0 | 0 | DBD::_::db:: | selectall_hashref |
0 | 0 | 0 | 0 | 0 | DBD::_::db:: | selectcol_arrayref |
0 | 0 | 0 | 0 | 0 | DBD::_::db:: | selectrow_array |
0 | 0 | 0 | 0 | 0 | DBD::_::db:: | selectrow_arrayref |
0 | 0 | 0 | 0 | 0 | DBD::_::db:: | selectrow_hashref |
0 | 0 | 0 | 0 | 0 | DBD::_::db:: | tables |
0 | 0 | 0 | 0 | 0 | DBD::_::db:: | type_info |
0 | 0 | 0 | 0 | 0 | DBD::_::dr:: | BEGIN |
0 | 0 | 0 | 0 | 0 | DBD::_::dr:: | connect |
0 | 0 | 0 | 0 | 0 | DBD::_::dr:: | connect_cached |
0 | 0 | 0 | 0 | 0 | DBD::_::dr:: | default_user |
0 | 0 | 0 | 0 | 0 | DBD::_::st:: | BEGIN |
0 | 0 | 0 | 0 | 0 | DBD::_::st:: | __ANON__[:1882] |
0 | 0 | 0 | 0 | 0 | DBD::_::st:: | __ANON__[:1916] |
0 | 0 | 0 | 0 | 0 | DBD::_::st:: | bind_columns |
0 | 0 | 0 | 0 | 0 | DBD::_::st:: | bind_param |
0 | 0 | 0 | 0 | 0 | DBD::_::st:: | bind_param_array |
0 | 0 | 0 | 0 | 0 | DBD::_::st:: | bind_param_inout_array |
0 | 0 | 0 | 0 | 0 | DBD::_::st:: | blob_copy_to_file |
0 | 0 | 0 | 0 | 0 | DBD::_::st:: | execute_array |
0 | 0 | 0 | 0 | 0 | DBD::_::st:: | execute_for_fetch |
0 | 0 | 0 | 0 | 0 | DBD::_::st:: | fetchall_arrayref |
0 | 0 | 0 | 0 | 0 | DBD::_::st:: | fetchall_hashref |
0 | 0 | 0 | 0 | 0 | DBD::_::st:: | more_results |
0 | 0 | 0 | 0 | 0 | DBI:: | BEGIN |
0 | 0 | 0 | 0 | 0 | DBI:: | CLONE |
0 | 0 | 0 | 0 | 0 | DBI::DBI_tie:: | STORE |
0 | 0 | 0 | 0 | 0 | DBI::DBI_tie:: | TIEHASH |
0 | 0 | 0 | 0 | 0 | DBI:: | END |
0 | 0 | 0 | 0 | 0 | DBI:: | __ANON__[:1088] |
0 | 0 | 0 | 0 | 0 | DBI:: | __ANON__[:1122] |
0 | 0 | 0 | 0 | 0 | DBI:: | __ANON__[:1123] |
0 | 0 | 0 | 0 | 0 | DBI:: | __ANON__[:997] |
0 | 0 | 0 | 0 | 0 | DBI:: | _dbtype_names |
0 | 0 | 0 | 0 | 0 | DBI:: | _load_class |
0 | 0 | 0 | 0 | 0 | DBI:: | _rebless |
0 | 0 | 0 | 0 | 0 | DBI:: | _rebless_dbtype_subclass |
0 | 0 | 0 | 0 | 0 | DBI:: | _set_isa |
0 | 0 | 0 | 0 | 0 | DBI:: | available_drivers |
0 | 0 | 0 | 0 | 0 | DBI:: | connect_cached |
0 | 0 | 0 | 0 | 0 | DBI:: | connect_test_perf |
0 | 0 | 0 | 0 | 0 | DBI:: | data_diff |
0 | 0 | 0 | 0 | 0 | DBI:: | data_sources |
0 | 0 | 0 | 0 | 0 | DBI:: | data_string_desc |
0 | 0 | 0 | 0 | 0 | DBI:: | data_string_diff |
0 | 0 | 0 | 0 | 0 | DBI:: | disconnect |
0 | 0 | 0 | 0 | 0 | DBI:: | dump_dbd_registry |
0 | 0 | 0 | 0 | 0 | DBI:: | dump_results |
0 | 0 | 0 | 0 | 0 | DBI:: | err |
0 | 0 | 0 | 0 | 0 | DBI:: | errstr |
0 | 0 | 0 | 0 | 0 | DBI:: | init_rootclass |
0 | 0 | 0 | 0 | 0 | DBI:: | installed_drivers |
0 | 0 | 0 | 0 | 0 | DBI:: | installed_methods |
0 | 0 | 0 | 0 | 0 | DBI:: | installed_versions |
0 | 0 | 0 | 0 | 0 | DBI:: | neat_list |
0 | 0 | 0 | 0 | 0 | DBI:: | parse_dsn |
0 | 0 | 0 | 0 | 0 | DBI::var:: | STORE |
0 | 0 | 0 | 0 | 0 | DBI::var:: | TIESCALAR |
Line | Stmts. | Exclusive Time | Avg. | Code |
---|---|---|---|---|
1 | # $Id: DBI.pm 10994 2008-03-24 14:06:48Z timbo $ | |||
2 | # vim: ts=8:sw=4 | |||
3 | # | |||
4 | # Copyright (c) 1994-2007 Tim Bunce Ireland | |||
5 | # | |||
6 | # See COPYRIGHT section in pod text below for usage and distribution rights. | |||
7 | # | |||
8 | ||||
9 | 1 | 3.4e-5 | 3.4e-5 | require 5.006_00; |
10 | ||||
11 | BEGIN { | |||
12 | 1 | 2.0e-6 | 2.0e-6 | $DBI::VERSION = "1.604"; # ==> ALSO update the version in the pod text below! |
13 | 1 | 5.7e-5 | 5.7e-5 | } |
14 | ||||
15 | =head1 NAME | |||
16 | ||||
17 | DBI - Database independent interface for Perl | |||
18 | ||||
19 | =head1 SYNOPSIS | |||
20 | ||||
21 | use DBI; | |||
22 | ||||
23 | @driver_names = DBI->available_drivers; | |||
24 | %drivers = DBI->installed_drivers; | |||
25 | @data_sources = DBI->data_sources($driver_name, \%attr); | |||
26 | ||||
27 | $dbh = DBI->connect($data_source, $username, $auth, \%attr); | |||
28 | ||||
29 | $rv = $dbh->do($statement); | |||
30 | $rv = $dbh->do($statement, \%attr); | |||
31 | $rv = $dbh->do($statement, \%attr, @bind_values); | |||
32 | ||||
33 | $ary_ref = $dbh->selectall_arrayref($statement); | |||
34 | $hash_ref = $dbh->selectall_hashref($statement, $key_field); | |||
35 | ||||
36 | $ary_ref = $dbh->selectcol_arrayref($statement); | |||
37 | $ary_ref = $dbh->selectcol_arrayref($statement, \%attr); | |||
38 | ||||
39 | @row_ary = $dbh->selectrow_array($statement); | |||
40 | $ary_ref = $dbh->selectrow_arrayref($statement); | |||
41 | $hash_ref = $dbh->selectrow_hashref($statement); | |||
42 | ||||
43 | $sth = $dbh->prepare($statement); | |||
44 | $sth = $dbh->prepare_cached($statement); | |||
45 | ||||
46 | $rc = $sth->bind_param($p_num, $bind_value); | |||
47 | $rc = $sth->bind_param($p_num, $bind_value, $bind_type); | |||
48 | $rc = $sth->bind_param($p_num, $bind_value, \%attr); | |||
49 | ||||
50 | $rv = $sth->execute; | |||
51 | $rv = $sth->execute(@bind_values); | |||
52 | $rv = $sth->execute_array(\%attr, ...); | |||
53 | ||||
54 | $rc = $sth->bind_col($col_num, \$col_variable); | |||
55 | $rc = $sth->bind_columns(@list_of_refs_to_vars_to_bind); | |||
56 | ||||
57 | @row_ary = $sth->fetchrow_array; | |||
58 | $ary_ref = $sth->fetchrow_arrayref; | |||
59 | $hash_ref = $sth->fetchrow_hashref; | |||
60 | ||||
61 | $ary_ref = $sth->fetchall_arrayref; | |||
62 | $ary_ref = $sth->fetchall_arrayref( $slice, $max_rows ); | |||
63 | ||||
64 | $hash_ref = $sth->fetchall_hashref( $key_field ); | |||
65 | ||||
66 | $rv = $sth->rows; | |||
67 | ||||
68 | $rc = $dbh->begin_work; | |||
69 | $rc = $dbh->commit; | |||
70 | $rc = $dbh->rollback; | |||
71 | ||||
72 | $quoted_string = $dbh->quote($string); | |||
73 | ||||
74 | $rc = $h->err; | |||
75 | $str = $h->errstr; | |||
76 | $rv = $h->state; | |||
77 | ||||
78 | $rc = $dbh->disconnect; | |||
79 | ||||
80 | I<The synopsis above only lists the major methods and parameters.> | |||
81 | ||||
82 | ||||
83 | =head2 GETTING HELP | |||
84 | ||||
85 | If you have questions about DBI, or DBD driver modules, you can get | |||
86 | help from the I<dbi-users@perl.org> mailing list. You don't have to subscribe | |||
87 | to the list in order to post, though I'd recommend it. You can get help on | |||
88 | subscribing and using the list by emailing I<dbi-users-help@perl.org>. | |||
89 | ||||
90 | I don't recommend the DBI cpanform (at http://www.cpanforum.com/dist/DBI) | |||
91 | because relatively few people read it compared with dbi-users@perl.org. | |||
92 | ||||
93 | To help you make the best use of the dbi-users mailing list, | |||
94 | and any other lists or forums you may use, I I<strongly> | |||
95 | recommend that you read "How To Ask Questions The Smart Way" | |||
96 | by Eric Raymond: L<http://www.catb.org/~esr/faqs/smart-questions.html>. | |||
97 | ||||
98 | If you think you've found a bug then please also read | |||
99 | "How to Report Bugs Effectively" by Simon Tatham: | |||
100 | L<http://www.chiark.greenend.org.uk/~sgtatham/bugs.html>. | |||
101 | ||||
102 | The DBI home page at L<http://dbi.perl.org/> and the DBI FAQ | |||
103 | at L<http://faq.dbi-support.com/> are always worth a visit. | |||
104 | They include links to other resources. | |||
105 | ||||
106 | Before asking any questions, reread this document, consult the | |||
107 | archives and read the DBI FAQ. The archives are listed | |||
108 | at the end of this document and on the DBI home page. | |||
109 | ||||
110 | This document often uses terms like I<references>, I<objects>, | |||
111 | I<methods>. If you're not familar with those terms then it would | |||
112 | be a good idea to read at least the following perl manuals first: | |||
113 | L<perlreftut>, L<perldsc>, L<perllol>, and L<perlboot>. | |||
114 | ||||
115 | Please note that Tim Bunce does not maintain the mailing lists or the | |||
116 | web page (generous volunteers do that). So please don't send mail | |||
117 | directly to him; he just doesn't have the time to answer questions | |||
118 | personally. The I<dbi-users> mailing list has lots of experienced | |||
119 | people who should be able to help you if you need it. If you do email | |||
120 | Tim he's very likely to just forward it to the mailing list. | |||
121 | ||||
122 | =head2 NOTES | |||
123 | ||||
124 | This is the DBI specification that corresponds to the DBI version 1.604 | |||
125 | ($Revision: 10994 $). | |||
126 | ||||
127 | The DBI is evolving at a steady pace, so it's good to check that | |||
128 | you have the latest copy. | |||
129 | ||||
130 | The significant user-visible changes in each release are documented | |||
131 | in the L<DBI::Changes> module so you can read them by executing | |||
132 | C<perldoc DBI::Changes>. | |||
133 | ||||
134 | Some DBI changes require changes in the drivers, but the drivers | |||
135 | can take some time to catch up. Newer versions of the DBI have | |||
136 | added features that may not yet be supported by the drivers you | |||
137 | use. Talk to the authors of your drivers if you need a new feature | |||
138 | that's not yet supported. | |||
139 | ||||
140 | Features added after DBI 1.21 (February 2002) are marked in the | |||
141 | text with the version number of the DBI release they first appeared in. | |||
142 | ||||
143 | Extensions to the DBI API often use the C<DBIx::*> namespace. | |||
144 | See L</Naming Conventions and Name Space>. DBI extension modules | |||
145 | can be found at L<http://search.cpan.org/search?mode=module&query=DBIx>. | |||
146 | And all modules related to the DBI can be found at | |||
147 | L<http://search.cpan.org/search?query=DBI&mode=all>. | |||
148 | ||||
149 | =cut | |||
150 | ||||
151 | # The POD text continues at the end of the file. | |||
152 | ||||
153 | ||||
154 | package DBI; | |||
155 | ||||
156 | 3 | 2.0e-5 | 6.7e-6 | use Carp(); |
157 | 3 | 2.0e-5 | 6.7e-6 | use DynaLoader (); |
158 | 3 | 0.00026 | 8.5e-5 | use Exporter (); |
159 | ||||
160 | BEGIN { | |||
161 | 10 | 0.00014 | 1.4e-5 | @ISA = qw(Exporter DynaLoader); |
162 | ||||
163 | # Make some utility functions available if asked for | |||
164 | @EXPORT = (); # we export nothing by default | |||
165 | @EXPORT_OK = qw(%DBI %DBI_methods hash); # also populated by export_ok_tags: | |||
166 | %EXPORT_TAGS = ( | |||
167 | sql_types => [ qw( | |||
168 | SQL_GUID | |||
169 | SQL_WLONGVARCHAR | |||
170 | SQL_WVARCHAR | |||
171 | SQL_WCHAR | |||
172 | SQL_BIGINT | |||
173 | SQL_BIT | |||
174 | SQL_TINYINT | |||
175 | SQL_LONGVARBINARY | |||
176 | SQL_VARBINARY | |||
177 | SQL_BINARY | |||
178 | SQL_LONGVARCHAR | |||
179 | SQL_UNKNOWN_TYPE | |||
180 | SQL_ALL_TYPES | |||
181 | SQL_CHAR | |||
182 | SQL_NUMERIC | |||
183 | SQL_DECIMAL | |||
184 | SQL_INTEGER | |||
185 | SQL_SMALLINT | |||
186 | SQL_FLOAT | |||
187 | SQL_REAL | |||
188 | SQL_DOUBLE | |||
189 | SQL_DATETIME | |||
190 | SQL_DATE | |||
191 | SQL_INTERVAL | |||
192 | SQL_TIME | |||
193 | SQL_TIMESTAMP | |||
194 | SQL_VARCHAR | |||
195 | SQL_BOOLEAN | |||
196 | SQL_UDT | |||
197 | SQL_UDT_LOCATOR | |||
198 | SQL_ROW | |||
199 | SQL_REF | |||
200 | SQL_BLOB | |||
201 | SQL_BLOB_LOCATOR | |||
202 | SQL_CLOB | |||
203 | SQL_CLOB_LOCATOR | |||
204 | SQL_ARRAY | |||
205 | SQL_ARRAY_LOCATOR | |||
206 | SQL_MULTISET | |||
207 | SQL_MULTISET_LOCATOR | |||
208 | SQL_TYPE_DATE | |||
209 | SQL_TYPE_TIME | |||
210 | SQL_TYPE_TIMESTAMP | |||
211 | SQL_TYPE_TIME_WITH_TIMEZONE | |||
212 | SQL_TYPE_TIMESTAMP_WITH_TIMEZONE | |||
213 | SQL_INTERVAL_YEAR | |||
214 | SQL_INTERVAL_MONTH | |||
215 | SQL_INTERVAL_DAY | |||
216 | SQL_INTERVAL_HOUR | |||
217 | SQL_INTERVAL_MINUTE | |||
218 | SQL_INTERVAL_SECOND | |||
219 | SQL_INTERVAL_YEAR_TO_MONTH | |||
220 | SQL_INTERVAL_DAY_TO_HOUR | |||
221 | SQL_INTERVAL_DAY_TO_MINUTE | |||
222 | SQL_INTERVAL_DAY_TO_SECOND | |||
223 | SQL_INTERVAL_HOUR_TO_MINUTE | |||
224 | SQL_INTERVAL_HOUR_TO_SECOND | |||
225 | SQL_INTERVAL_MINUTE_TO_SECOND | |||
226 | ) ], | |||
227 | sql_cursor_types => [ qw( | |||
228 | SQL_CURSOR_FORWARD_ONLY | |||
229 | SQL_CURSOR_KEYSET_DRIVEN | |||
230 | SQL_CURSOR_DYNAMIC | |||
231 | SQL_CURSOR_STATIC | |||
232 | SQL_CURSOR_TYPE_DEFAULT | |||
233 | ) ], # for ODBC cursor types | |||
234 | utils => [ qw( | |||
235 | neat neat_list $neat_maxlen dump_results looks_like_number | |||
236 | data_string_diff data_string_desc data_diff | |||
237 | ) ], | |||
238 | profile => [ qw( | |||
239 | dbi_profile dbi_profile_merge dbi_profile_merge_nodes dbi_time | |||
240 | ) ], # notionally "in" DBI::Profile and normally imported from there | |||
241 | ); | |||
242 | ||||
243 | $DBI::dbi_debug = 0; | |||
244 | $DBI::neat_maxlen = 400; | |||
245 | $DBI::stderr = 2_000_000_000; # a very round number below 2**31 | |||
246 | ||||
247 | # If you get an error here like "Can't find loadable object ..." | |||
248 | # then you haven't installed the DBI correctly. Read the README | |||
249 | # then install it again. | |||
250 | 1 | 1.2e-5 | 1.2e-5 | if ( $ENV{DBI_PUREPERL} ) { |
251 | eval { bootstrap DBI } if $ENV{DBI_PUREPERL} == 1; | |||
252 | require DBI::PurePerl if $@ or $ENV{DBI_PUREPERL} >= 2; | |||
253 | $DBI::PurePerl ||= 0; # just to silence "only used once" warnings | |||
254 | } | |||
255 | else { | |||
256 | bootstrap DBI; # spent 2.03ms making 1 call to DynaLoader::bootstrap | |||
257 | } | |||
258 | ||||
259 | 116 | 7.1e-5 | 6.1e-7 | $EXPORT_TAGS{preparse_flags} = [ grep { /^DBIpp_\w\w_/ } keys %{__PACKAGE__."::"} ]; |
260 | ||||
261 | Exporter::export_ok_tags(keys %EXPORT_TAGS); # spent 33µs making 1 call to Exporter::export_ok_tags | |||
262 | ||||
263 | 1 | 7.8e-5 | 7.8e-5 | } |
264 | ||||
265 | # Alias some handle methods to also be DBI class methods | |||
266 | 1 | 3.0e-6 | 3.0e-6 | for (qw(trace_msg set_err parse_trace_flag parse_trace_flags)) { |
267 | 3 | 6.2e-5 | 2.1e-5 | no strict; # spent 11µs making 1 call to strict::unimport |
268 | 4 | 5.3e-5 | 1.3e-5 | *$_ = \&{"DBD::_::common::$_"}; |
269 | } | |||
270 | ||||
271 | 3 | 0.00129 | 0.00043 | use strict; # spent 8µs making 1 call to strict::import |
272 | ||||
273 | 1 | 1.0e-6 | 1.0e-6 | DBI->trace(split /=/, $ENV{DBI_TRACE}, 2) if $ENV{DBI_TRACE}; |
274 | ||||
275 | 1 | 1.0e-6 | 1.0e-6 | $DBI::connect_via ||= "connect"; |
276 | ||||
277 | # check if user wants a persistent database connection ( Apache + mod_perl ) | |||
278 | 1 | 1.0e-6 | 1.0e-6 | if ($INC{'Apache/DBI.pm'} && $ENV{MOD_PERL}) { |
279 | $DBI::connect_via = "Apache::DBI::connect"; | |||
280 | DBI->trace_msg("DBI connect via $DBI::connect_via in $INC{'Apache/DBI.pm'}\n"); | |||
281 | } | |||
282 | ||||
283 | # check for weaken support, used by ChildHandles | |||
284 | 4 | 1.5e-5 | 3.8e-6 | my $HAS_WEAKEN = eval { |
285 | require Scalar::Util; | |||
286 | # this will croak() if this Scalar::Util doesn't have a working weaken(). | |||
287 | Scalar::Util::weaken( \my $test ); # same test as in t/72childhandles.t # spent 9µs making 1 call to Scalar::Util::weaken | |||
288 | 1; | |||
289 | }; | |||
290 | ||||
291 | 1 | 1.0e-6 | 1.0e-6 | %DBI::installed_drh = (); # maps driver names to installed driver handles |
292 | sub installed_drivers { %DBI::installed_drh } | |||
293 | 1 | 1.0e-6 | 1.0e-6 | %DBI::installed_methods = (); # XXX undocumented, may change |
294 | sub installed_methods { %DBI::installed_methods } | |||
295 | ||||
296 | # Setup special DBI dynamic variables. See DBI::var::FETCH for details. | |||
297 | # These are dynamically associated with the last handle used. | |||
298 | 1 | 5.0e-6 | 5.0e-6 | tie $DBI::err, 'DBI::var', '*err'; # special case: referenced via IHA list |
299 | 1 | 1.0e-6 | 1.0e-6 | tie $DBI::state, 'DBI::var', '"state'; # special case: referenced via IHA list |
300 | 1 | 2.0e-6 | 2.0e-6 | tie $DBI::lasth, 'DBI::var', '!lasth'; # special case: return boolean |
301 | 1 | 2.0e-6 | 2.0e-6 | tie $DBI::errstr, 'DBI::var', '&errstr'; # call &errstr in last used pkg |
302 | 1 | 2.0e-6 | 2.0e-6 | tie $DBI::rows, 'DBI::var', '&rows'; # call &rows in last used pkg |
303 | 10 | 1.6e-5 | 1.6e-6 | sub DBI::var::TIESCALAR{ my $var = $_[1]; bless \$var, 'DBI::var'; } |
304 | sub DBI::var::STORE { Carp::croak("Can't modify \$DBI::${$_[0]} special variable") } | |||
305 | ||||
306 | { # used to catch DBI->{Attrib} mistake | |||
307 | 2 | 1.4e-5 | 7.0e-6 | sub DBI::DBI_tie::TIEHASH { bless {} } |
308 | sub DBI::DBI_tie::STORE { Carp::carp("DBI->{$_[1]} is invalid syntax (you probably want \$h->{$_[1]})");} | |||
309 | 1 | 2.0e-6 | 2.0e-6 | *DBI::DBI_tie::FETCH = \&DBI::DBI_tie::STORE; |
310 | } | |||
311 | 1 | 3.0e-6 | 3.0e-6 | tie %DBI::DBI => 'DBI::DBI_tie'; |
312 | ||||
313 | # --- Driver Specific Prefix Registry --- | |||
314 | ||||
315 | 1 | 5.8e-5 | 5.8e-5 | my $dbd_prefix_registry = { |
316 | ad_ => { class => 'DBD::AnyData', }, | |||
317 | ado_ => { class => 'DBD::ADO', }, | |||
318 | amzn_ => { class => 'DBD::Amazon', }, | |||
319 | best_ => { class => 'DBD::BestWins', }, | |||
320 | csv_ => { class => 'DBD::CSV', }, | |||
321 | db2_ => { class => 'DBD::DB2', }, | |||
322 | dbi_ => { class => 'DBI', }, | |||
323 | dbm_ => { class => 'DBD::DBM', }, | |||
324 | df_ => { class => 'DBD::DF', }, | |||
325 | f_ => { class => 'DBD::File', }, | |||
326 | file_ => { class => 'DBD::TextFile', }, | |||
327 | go_ => { class => 'DBD::Gofer', }, | |||
328 | ib_ => { class => 'DBD::InterBase', }, | |||
329 | ing_ => { class => 'DBD::Ingres', }, | |||
330 | ix_ => { class => 'DBD::Informix', }, | |||
331 | jdbc_ => { class => 'DBD::JDBC', }, | |||
332 | monetdb_ => { class => 'DBD::monetdb', }, | |||
333 | msql_ => { class => 'DBD::mSQL', }, | |||
334 | mvsftp_ => { class => 'DBD::MVS_FTPSQL', }, | |||
335 | mysql_ => { class => 'DBD::mysql', }, | |||
336 | mx_ => { class => 'DBD::Multiplex', }, | |||
337 | nullp_ => { class => 'DBD::NullP', }, | |||
338 | odbc_ => { class => 'DBD::ODBC', }, | |||
339 | ora_ => { class => 'DBD::Oracle', }, | |||
340 | pg_ => { class => 'DBD::Pg', }, | |||
341 | plb_ => { class => 'DBD::Plibdata', }, | |||
342 | proxy_ => { class => 'DBD::Proxy', }, | |||
343 | rdb_ => { class => 'DBD::RDB', }, | |||
344 | sapdb_ => { class => 'DBD::SAP_DB', }, | |||
345 | solid_ => { class => 'DBD::Solid', }, | |||
346 | sponge_ => { class => 'DBD::Sponge', }, | |||
347 | sql_ => { class => 'SQL::Statement', }, | |||
348 | syb_ => { class => 'DBD::Sybase', }, | |||
349 | tdat_ => { class => 'DBD::Teradata', }, | |||
350 | tmpl_ => { class => 'DBD::Template', }, | |||
351 | tmplss_ => { class => 'DBD::TemplateSS', }, | |||
352 | tuber_ => { class => 'DBD::Tuber', }, | |||
353 | uni_ => { class => 'DBD::Unify', }, | |||
354 | vt_ => { class => 'DBD::Vt', }, | |||
355 | wmi_ => { class => 'DBD::WMI', }, | |||
356 | x_ => { }, # for private use | |||
357 | xbase_ => { class => 'DBD::XBase', }, | |||
358 | xl_ => { class => 'DBD::Excel', }, | |||
359 | yaswi_ => { class => 'DBD::Yaswi', }, | |||
360 | }; | |||
361 | ||||
362 | sub dump_dbd_registry { | |||
363 | require Data::Dumper; | |||
364 | local $Data::Dumper::Sortkeys=1; | |||
365 | local $Data::Dumper::Indent=1; | |||
366 | print Data::Dumper->Dump([$dbd_prefix_registry], [qw($dbd_prefix_registry)]); | |||
367 | } | |||
368 | ||||
369 | # --- Dynamically create the DBI Standard Interface | |||
370 | ||||
371 | 1 | 1.0e-6 | 1.0e-6 | my $keeperr = { O=>0x0004 }; |
372 | ||||
373 | 1 | 0.00016 | 0.00016 | %DBI::DBI_methods = ( # Define the DBI interface methods per class: |
374 | ||||
375 | common => { # Interface methods common to all DBI handle classes | |||
376 | 'DESTROY' => { O=>0x004|0x10000 }, | |||
377 | 'CLEAR' => $keeperr, | |||
378 | 'EXISTS' => $keeperr, | |||
379 | 'FETCH' => { O=>0x0404 }, | |||
380 | 'FETCH_many' => { O=>0x0404 }, | |||
381 | 'FIRSTKEY' => $keeperr, | |||
382 | 'NEXTKEY' => $keeperr, | |||
383 | 'STORE' => { O=>0x0418 | 0x4 }, | |||
384 | _not_impl => undef, | |||
385 | can => { O=>0x0100 }, # special case, see dispatch | |||
386 | debug => { U =>[1,2,'[$debug_level]'], O=>0x0004 }, # old name for trace | |||
387 | dump_handle => { U =>[1,3,'[$message [, $level]]'], O=>0x0004 }, | |||
388 | err => $keeperr, | |||
389 | errstr => $keeperr, | |||
390 | state => $keeperr, | |||
391 | func => { O=>0x0006 }, | |||
392 | parse_trace_flag => { U =>[2,2,'$name'], O=>0x0404, T=>8 }, | |||
393 | parse_trace_flags => { U =>[2,2,'$flags'], O=>0x0404, T=>8 }, | |||
394 | private_data => { U =>[1,1], O=>0x0004 }, | |||
395 | set_err => { U =>[3,6,'$err, $errmsg [, $state, $method, $rv]'], O=>0x0010 }, | |||
396 | trace => { U =>[1,3,'[$trace_level, [$filename]]'], O=>0x0004 }, | |||
397 | trace_msg => { U =>[2,3,'$message_text [, $min_level ]' ], O=>0x0004, T=>8 }, | |||
398 | swap_inner_handle => { U =>[2,3,'$h [, $allow_reparent ]'] }, | |||
399 | private_attribute_info => { }, | |||
400 | }, | |||
401 | dr => { # Database Driver Interface | |||
402 | 'connect' => { U =>[1,5,'[$db [,$user [,$passwd [,\%attr]]]]'], H=>3, O=>0x8000 }, | |||
403 | 'connect_cached'=>{U=>[1,5,'[$db [,$user [,$passwd [,\%attr]]]]'], H=>3, O=>0x8000 }, | |||
404 | 'disconnect_all'=>{ U =>[1,1], O=>0x0800 }, | |||
405 | data_sources => { U =>[1,2,'[\%attr]' ], O=>0x0800 }, | |||
406 | default_user => { U =>[3,4,'$user, $pass [, \%attr]' ] }, | |||
407 | }, | |||
408 | db => { # Database Session Class Interface | |||
409 | data_sources => { U =>[1,2,'[\%attr]' ], O=>0x0200 }, | |||
410 | take_imp_data => { U =>[1,1], O=>0x10000 }, | |||
411 | clone => { U =>[1,2,'[\%attr]'] }, | |||
412 | connected => { U =>[1,0], O => 0x0004 }, | |||
413 | begin_work => { U =>[1,2,'[ \%attr ]'], O=>0x0400 }, | |||
414 | commit => { U =>[1,1], O=>0x0480|0x0800 }, | |||
415 | rollback => { U =>[1,1], O=>0x0480|0x0800 }, | |||
416 | 'do' => { U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'], O=>0x3200 }, | |||
417 | last_insert_id => { U =>[5,6,'$catalog, $schema, $table_name, $field_name [, \%attr ]'], O=>0x2800 }, | |||
418 | preparse => { }, # XXX | |||
419 | prepare => { U =>[2,3,'$statement [, \%attr]'], O=>0xA200 }, | |||
420 | prepare_cached => { U =>[2,4,'$statement [, \%attr [, $if_active ] ]'], O=>0xA200 }, | |||
421 | selectrow_array => { U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'], O=>0x2000 }, | |||
422 | selectrow_arrayref=>{U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'], O=>0x2000 }, | |||
423 | selectrow_hashref=>{ U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'], O=>0x2000 }, | |||
424 | selectall_arrayref=>{U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'], O=>0x2000 }, | |||
425 | selectall_hashref=>{ U =>[3,0,'$statement, $keyfield [, \%attr [, @bind_params ] ]'], O=>0x2000 }, | |||
426 | selectcol_arrayref=>{U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'], O=>0x2000 }, | |||
427 | ping => { U =>[1,1], O=>0x0404 }, | |||
428 | disconnect => { U =>[1,1], O=>0x0400|0x0800|0x10000 }, | |||
429 | quote => { U =>[2,3, '$string [, $data_type ]' ], O=>0x0430 }, | |||
430 | quote_identifier=> { U =>[2,6, '$name [, ...] [, \%attr ]' ], O=>0x0430 }, | |||
431 | rows => $keeperr, | |||
432 | ||||
433 | tables => { U =>[1,6,'$catalog, $schema, $table, $type [, \%attr ]' ], O=>0x2200 }, | |||
434 | table_info => { U =>[1,6,'$catalog, $schema, $table, $type [, \%attr ]' ], O=>0x2200|0x8800 }, | |||
435 | column_info => { U =>[5,6,'$catalog, $schema, $table, $column [, \%attr ]'],O=>0x2200|0x8800 }, | |||
436 | primary_key_info=> { U =>[4,5,'$catalog, $schema, $table [, \%attr ]' ], O=>0x2200|0x8800 }, | |||
437 | primary_key => { U =>[4,5,'$catalog, $schema, $table [, \%attr ]' ], O=>0x2200 }, | |||
438 | foreign_key_info=> { U =>[7,8,'$pk_catalog, $pk_schema, $pk_table, $fk_catalog, $fk_schema, $fk_table [, \%attr ]' ], O=>0x2200|0x8800 }, | |||
439 | statistics_info => { U =>[6,7,'$catalog, $schema, $table, $unique_only, $quick, [, \%attr ]' ], O=>0x2200|0x8800 }, | |||
440 | type_info_all => { U =>[1,1], O=>0x2200|0x0800 }, | |||
441 | type_info => { U =>[1,2,'$data_type'], O=>0x2200 }, | |||
442 | get_info => { U =>[2,2,'$info_type'], O=>0x2200|0x0800 }, | |||
443 | }, | |||
444 | st => { # Statement Class Interface | |||
445 | bind_col => { U =>[3,4,'$column, \\$var [, \%attr]'] }, | |||
446 | bind_columns => { U =>[2,0,'\\$var1 [, \\$var2, ...]'] }, | |||
447 | bind_param => { U =>[3,4,'$parameter, $var [, \%attr]'] }, | |||
448 | bind_param_inout=> { U =>[4,5,'$parameter, \\$var, $maxlen, [, \%attr]'] }, | |||
449 | execute => { U =>[1,0,'[@args]'], O=>0x1040 }, | |||
450 | ||||
451 | bind_param_array => { U =>[3,4,'$parameter, $var [, \%attr]'] }, | |||
452 | bind_param_inout_array => { U =>[4,5,'$parameter, \\@var, $maxlen, [, \%attr]'] }, | |||
453 | execute_array => { U =>[2,0,'\\%attribs [, @args]'], O=>0x1040|0x4000 }, | |||
454 | execute_for_fetch => { U =>[2,3,'$fetch_sub [, $tuple_status]'], O=>0x1040|0x4000 }, | |||
455 | ||||
456 | fetch => undef, # alias for fetchrow_arrayref | |||
457 | fetchrow_arrayref => undef, | |||
458 | fetchrow_hashref => undef, | |||
459 | fetchrow_array => undef, | |||
460 | fetchrow => undef, # old alias for fetchrow_array | |||
461 | ||||
462 | fetchall_arrayref => { U =>[1,3, '[ $slice [, $max_rows]]'] }, | |||
463 | fetchall_hashref => { U =>[2,2,'$key_field'] }, | |||
464 | ||||
465 | blob_read => { U =>[4,5,'$field, $offset, $len [, \\$buf [, $bufoffset]]'] }, | |||
466 | blob_copy_to_file => { U =>[3,3,'$field, $filename_or_handleref'] }, | |||
467 | dump_results => { U =>[1,5,'$maxfieldlen, $linesep, $fieldsep, $filehandle'] }, | |||
468 | more_results => { U =>[1,1] }, | |||
469 | finish => { U =>[1,1] }, | |||
470 | cancel => { U =>[1,1], O=>0x0800 }, | |||
471 | rows => $keeperr, | |||
472 | ||||
473 | _get_fbav => undef, | |||
474 | _set_fbav => { T=>6 }, | |||
475 | }, | |||
476 | ); | |||
477 | ||||
478 | 9 | 2.1e-5 | 2.3e-6 | while ( my ($class, $meths) = each %DBI::DBI_methods ) { |
479 | 1 | 8.0e-6 | 8.0e-6 | my $ima_trace = 0+($ENV{DBI_IMA_TRACE}||0); |
480 | 261 | 0.00089 | 3.4e-6 | while ( my ($method, $info) = each %$meths ) { |
481 | 1 | 0.00024 | 0.00024 | my $fullmeth = "DBI::${class}::$method"; |
482 | if ($DBI::dbi_debug >= 15) { # quick hack to list DBI methods | |||
483 | # and optionally filter by IMA flags | |||
484 | my $O = $info->{O}||0; | |||
485 | printf "0x%04x %-20s\n", $O, $fullmeth | |||
486 | unless $ima_trace && !($O & $ima_trace); | |||
487 | } | |||
488 | DBI->_install_method($fullmeth, 'DBI.pm', $info); # spent 622µs making 87 calls to DBI::_install_method, avg 7µs/call | |||
489 | } | |||
490 | } | |||
491 | ||||
492 | { | |||
493 | 1 | 0 | 0 | package DBI::common; |
494 | 3 | 1.4e-5 | 4.7e-6 | @DBI::dr::ISA = ('DBI::common'); |
495 | @DBI::db::ISA = ('DBI::common'); | |||
496 | @DBI::st::ISA = ('DBI::common'); | |||
497 | } | |||
498 | ||||
499 | # End of init code | |||
500 | ||||
501 | ||||
502 | END { | |||
503 | 5 | 5.8e-5 | 1.2e-5 | return unless defined &DBI::trace_msg; # return unless bootstrap'd ok |
504 | local ($!,$?); | |||
505 | DBI->trace_msg(sprintf(" -- DBI::END (\$\@: %s, \$!: %s)\n", $@||'', $!||''), 2); # spent 12µs making 1 call to DBD::_::common::trace_msg | |||
506 | # Let drivers know why we are calling disconnect_all: | |||
507 | $DBI::PERL_ENDING = $DBI::PERL_ENDING = 1; # avoid typo warning | |||
508 | DBI->disconnect_all() if %DBI::installed_drh; # spent 60µs making 1 call to DBI::disconnect_all | |||
509 | } | |||
510 | ||||
511 | ||||
512 | sub CLONE { | |||
513 | my $olddbis = $DBI::_dbistate; | |||
514 | _clone_dbis() unless $DBI::PurePerl; # clone the DBIS structure | |||
515 | DBI->trace_msg(sprintf "CLONE DBI for new thread %s\n", | |||
516 | $DBI::PurePerl ? "" : sprintf("(dbis %x -> %x)",$olddbis, $DBI::_dbistate)); | |||
517 | while ( my ($driver, $drh) = each %DBI::installed_drh) { | |||
518 | 3 | 0.00098 | 0.00033 | no strict 'refs'; # spent 23µs making 1 call to strict::unimport |
519 | next if defined &{"DBD::${driver}::CLONE"}; | |||
520 | warn("$driver has no driver CLONE() function so is unsafe threaded\n"); | |||
521 | } | |||
522 | %DBI::installed_drh = (); # clear loaded drivers so they have a chance to reinitialize | |||
523 | } | |||
524 | ||||
525 | sub parse_dsn { | |||
526 | my ($class, $dsn) = @_; | |||
527 | $dsn =~ s/^(dbi):(\w*?)(?:\((.*?)\))?://i or return; | |||
528 | my ($scheme, $driver, $attr, $attr_hash) = (lc($1), $2, $3); | |||
529 | $driver ||= $ENV{DBI_DRIVER} || ''; | |||
530 | $attr_hash = { split /\s*=>?\s*|\s*,\s*/, $attr, -1 } if $attr; | |||
531 | return ($scheme, $driver, $attr, $attr_hash, $dsn); | |||
532 | } | |||
533 | ||||
534 | ||||
535 | # --- The DBI->connect Front Door methods | |||
536 | ||||
537 | sub connect_cached { | |||
538 | # For library code using connect_cached() with mod_perl | |||
539 | # we redirect those calls to Apache::DBI::connect() as well | |||
540 | my ($class, $dsn, $user, $pass, $attr) = @_; | |||
541 | my $dbi_connect_method = ($DBI::connect_via eq "Apache::DBI::connect") | |||
542 | ? 'Apache::DBI::connect' : 'connect_cached'; | |||
543 | $attr = { | |||
544 | $attr ? %$attr : (), # clone, don't modify callers data | |||
545 | dbi_connect_method => $dbi_connect_method, | |||
546 | }; | |||
547 | return $class->connect($dsn, $user, $pass, $attr); | |||
548 | } | |||
549 | ||||
550 | # spent 11.8ms (116µs+11.6) within DBI::connect which was called
# once (116µs+11.6ms) by DBIx::Class::Storage::DBI::_connect at line 839 of /wise/base/static/lib/perl5/site_perl/5.10.0/DBIx/Class/Storage/DBI.pm | |||
551 | 28 | 0.00015 | 5.4e-6 | my $class = shift; |
552 | my ($dsn, $user, $pass, $attr, $old_driver) = my @orig_args = @_; | |||
553 | my $driver; | |||
554 | ||||
555 | if ($attr and !ref($attr)) { # switch $old_driver<->$attr if called in old style | |||
556 | Carp::carp("DBI->connect using 'old-style' syntax is deprecated and will be an error in future versions"); | |||
557 | ($old_driver, $attr) = ($attr, $old_driver); | |||
558 | } | |||
559 | ||||
560 | my $connect_meth = $attr->{dbi_connect_method}; | |||
561 | $connect_meth ||= $DBI::connect_via; # fallback to default | |||
562 | ||||
563 | $dsn ||= $ENV{DBI_DSN} || $ENV{DBI_DBNAME} || '' unless $old_driver; | |||
564 | ||||
565 | if ($DBI::dbi_debug) { | |||
566 | local $^W = 0; | |||
567 | pop @_ if $connect_meth ne 'connect'; | |||
568 | my @args = @_; $args[2] = '****'; # hide password | |||
569 | DBI->trace_msg(" -> $class->$connect_meth(".join(", ",@args).")\n"); | |||
570 | } | |||
571 | Carp::croak('Usage: $class->connect([$dsn [,$user [,$passwd [,\%attr]]]])') | |||
572 | if (ref $old_driver or ($attr and not ref $attr) or ref $pass); | |||
573 | ||||
574 | # extract dbi:driver prefix from $dsn into $1 | |||
575 | $dsn =~ s/^dbi:(\w*?)(?:\((.*?)\))?://i | |||
576 | or '' =~ /()/; # ensure $1 etc are empty if match fails | |||
577 | my $driver_attrib_spec = $2 || ''; | |||
578 | ||||
579 | # Set $driver. Old style driver, if specified, overrides new dsn style. | |||
580 | $driver = $old_driver || $1 || $ENV{DBI_DRIVER} | |||
581 | or Carp::croak("Can't connect to data source '$dsn' " | |||
582 | ."because I can't work out what driver to use " | |||
583 | ."(it doesn't seem to contain a 'dbi:driver:' prefix " | |||
584 | ."and the DBI_DRIVER env var is not set)"); | |||
585 | ||||
586 | my $proxy; | |||
587 | if ($ENV{DBI_AUTOPROXY} && $driver ne 'Proxy' && $driver ne 'Sponge' && $driver ne 'Switch') { | |||
588 | my $dbi_autoproxy = $ENV{DBI_AUTOPROXY}; | |||
589 | $proxy = 'Proxy'; | |||
590 | if ($dbi_autoproxy =~ s/^dbi:(\w*?)(?:\((.*?)\))?://i) { | |||
591 | $proxy = $1; | |||
592 | $driver_attrib_spec = join ",", | |||
593 | ($driver_attrib_spec) ? $driver_attrib_spec : (), | |||
594 | ($2 ) ? $2 : (); | |||
595 | } | |||
596 | $dsn = "$dbi_autoproxy;dsn=dbi:$driver:$dsn"; | |||
597 | $driver = $proxy; | |||
598 | DBI->trace_msg(" DBI_AUTOPROXY: dbi:$driver($driver_attrib_spec):$dsn\n"); | |||
599 | } | |||
600 | # avoid recursion if proxy calls DBI->connect itself | |||
601 | local $ENV{DBI_AUTOPROXY}; | |||
602 | ||||
603 | my %attributes; # take a copy we can delete from | |||
604 | 1 | 4.0e-6 | 4.0e-6 | if ($old_driver) { |
605 | %attributes = %$attr if $attr; | |||
606 | } | |||
607 | else { # new-style connect so new default semantics | |||
608 | %attributes = ( | |||
609 | PrintError => 1, | |||
610 | AutoCommit => 1, | |||
611 | ref $attr ? %$attr : (), | |||
612 | # attributes in DSN take precedence over \%attr connect parameter | |||
613 | $driver_attrib_spec ? (split /\s*=>?\s*|\s*,\s*/, $driver_attrib_spec, -1) : (), | |||
614 | ); | |||
615 | } | |||
616 | $attr = \%attributes; # now set $attr to refer to our local copy | |||
617 | ||||
618 | my $drh = $DBI::installed_drh{$driver} || $class->install_driver($driver) # spent 6.59ms making 1 call to DBI::install_driver | |||
619 | or die "panic: $class->install_driver($driver) failed"; | |||
620 | ||||
621 | # attributes in DSN take precedence over \%attr connect parameter | |||
622 | $user = $attr->{Username} if defined $attr->{Username}; | |||
623 | $pass = $attr->{Password} if defined $attr->{Password}; | |||
624 | delete $attr->{Password}; # always delete Password as closure stores it securely | |||
625 | 1 | 1.3e-5 | 1.3e-5 | if ( !(defined $user && defined $pass) ) { # spent 39µs making 1 call to DBI::dr::default_user |
626 | ($user, $pass) = $drh->default_user($user, $pass, $attr); | |||
627 | } | |||
628 | $attr->{Username} = $user; # force the Username to be the actual one used | |||
629 | ||||
630 | # spent 5.00ms (157µs+4.84) within DBI::__ANON__[/wise/base/static/lib/perl5/site_perl/5.10.0/x86_64-linux-thread-multi/DBI.pm:703] which was called
# once (157µs+4.84ms) by DBI::connect at line 705 | |||
631 | 10 | 9.3e-5 | 9.3e-6 | my ($old_dbh, $override_attr) = @_; |
632 | ||||
633 | #use Data::Dumper; | |||
634 | #warn "connect_closure: ".Data::Dumper::Dumper([$attr,\%attributes, $override_attr]); | |||
635 | ||||
636 | my $dbh; | |||
637 | 1 | 1.2e-5 | 1.2e-5 | unless ($dbh = $drh->$connect_meth($dsn, $user, $pass, $attr)) { # spent 4.60ms making 1 call to DBI::dr::connect |
638 | $user = '' if !defined $user; | |||
639 | $dsn = '' if !defined $dsn; | |||
640 | # $drh->errstr isn't safe here because $dbh->DESTROY may not have | |||
641 | # been called yet and so the dbh errstr would not have been copied | |||
642 | # up to the drh errstr. Certainly true for connect_cached! | |||
643 | my $errstr = $DBI::errstr; | |||
644 | # Getting '(no error string)' here is a symptom of a ref loop | |||
645 | $errstr = '(no error string)' if !defined $errstr; | |||
646 | my $msg = "$class connect('$dsn','$user',...) failed: $errstr"; | |||
647 | DBI->trace_msg(" $msg\n"); | |||
648 | # XXX HandleWarn | |||
649 | unless ($attr->{HandleError} && $attr->{HandleError}->($msg, $drh, $dbh)) { | |||
650 | Carp::croak($msg) if $attr->{RaiseError}; | |||
651 | Carp::carp ($msg) if $attr->{PrintError}; | |||
652 | } | |||
653 | $! = 0; # for the daft people who do DBI->connect(...) || die "$!"; | |||
654 | return $dbh; # normally undef, but HandleError could change it | |||
655 | } | |||
656 | ||||
657 | # merge any attribute overrides but don't change $attr itself (for closure) | |||
658 | my $apply = { ($override_attr) ? (%$attr, %$override_attr ) : %$attr }; | |||
659 | ||||
660 | # handle basic RootClass subclassing: | |||
661 | my $rebless_class = $apply->{RootClass} || ($class ne 'DBI' ? $class : ''); | |||
662 | if ($rebless_class) { | |||
663 | 3 | 0.00077 | 0.00026 | no strict 'refs'; # spent 21µs making 1 call to strict::unimport |
664 | if ($apply->{RootClass}) { # explicit attribute (ie not static methd call class) | |||
665 | delete $apply->{RootClass}; | |||
666 | DBI::_load_class($rebless_class, 0); | |||
667 | } | |||
668 | unless (@{"$rebless_class\::db::ISA"} && @{"$rebless_class\::st::ISA"}) { | |||
669 | Carp::carp("DBI subclasses '$rebless_class\::db' and ::st are not setup, RootClass ignored"); | |||
670 | $rebless_class = undef; | |||
671 | $class = 'DBI'; | |||
672 | } | |||
673 | else { | |||
674 | $dbh->{RootClass} = $rebless_class; # $dbh->STORE called via plain DBI::db | |||
675 | DBI::_set_isa([$rebless_class], 'DBI'); # sets up both '::db' and '::st' | |||
676 | DBI::_rebless($dbh, $rebless_class); # appends '::db' | |||
677 | } | |||
678 | } | |||
679 | ||||
680 | 4 | 1.3e-5 | 3.2e-6 | if (%$apply) { |
681 | ||||
682 | if ($apply->{DbTypeSubclass}) { | |||
683 | my $DbTypeSubclass = delete $apply->{DbTypeSubclass}; | |||
684 | DBI::_rebless_dbtype_subclass($dbh, $rebless_class||$class, $DbTypeSubclass); | |||
685 | } | |||
686 | my $a; | |||
687 | foreach $a (qw(Profile RaiseError PrintError AutoCommit)) { # do these first | |||
688 | 6 | 8.5e-5 | 1.4e-5 | next unless exists $apply->{$a}; |
689 | $dbh->{$a} = delete $apply->{$a}; # spent 61µs making 2 calls to DBI::common::STORE, avg 31µs/call | |||
690 | } | |||
691 | 3 | 0.00010 | 3.3e-5 | while ( my ($a, $v) = each %$apply) { |
692 | 3 | 0.00010 | 3.4e-5 | eval { $dbh->{$a} = $v } or $@ && warn $@; # spent 79µs making 3 calls to DBI::common::STORE, avg 26µs/call
# spent 60µs making 3 calls to DBI::common::FETCH, avg 20µs/call |
693 | } | |||
694 | } | |||
695 | ||||
696 | # confirm to driver (ie if subclassed) that we've connected sucessfully | |||
697 | # and finished the attribute setup. pass in the original arguments | |||
698 | $dbh->connected(@orig_args); #if ref $dbh ne 'DBI::db' or $proxy; # spent 41µs making 1 call to DBI::db::connected | |||
699 | ||||
700 | DBI->trace_msg(" <- connect= $dbh\n") if $DBI::dbi_debug; | |||
701 | ||||
702 | return $dbh; | |||
703 | }; | |||
704 | ||||
705 | my $dbh = &$connect_closure(undef, undef); # spent 5.00ms making 1 call to DBI::__ANON__[/wise/base/static/lib/perl5/site_perl/5.10.0/x86_64-linux-thread-multi/DBI.pm:703] | |||
706 | ||||
707 | $dbh->{dbi_connect_closure} = $connect_closure if $dbh; # spent 11µs making 1 call to DBI::common::STORE | |||
708 | ||||
709 | return $dbh; | |||
710 | } | |||
711 | ||||
712 | ||||
713 | # spent 60µs (31+29) within DBI::disconnect_all which was called
# once (31µs+29µs) by DBI::END at line 508 | |||
714 | 2 | 5.4e-5 | 2.7e-5 | keys %DBI::installed_drh; # reset iterator |
715 | while ( my ($name, $drh) = each %DBI::installed_drh ) { # spent 29µs making 1 call to DBI::dr::disconnect_all | |||
716 | $drh->disconnect_all() if ref $drh; | |||
717 | } | |||
718 | } | |||
719 | ||||
720 | ||||
721 | sub disconnect { # a regular beginners bug | |||
722 | Carp::croak("DBI->disconnect is not a DBI method (read the DBI manual)"); | |||
723 | } | |||
724 | ||||
725 | ||||
726 | # spent 6.59ms (3.58+3.01) within DBI::install_driver which was called
# once (3.58ms+3.01ms) by DBI::connect at line 618 | |||
727 | 18 | 0.00011 | 5.9e-6 | my $class = shift; |
728 | my($driver, $attr) = @_; | |||
729 | my $drh; | |||
730 | ||||
731 | $driver ||= $ENV{DBI_DRIVER} || ''; | |||
732 | ||||
733 | # allow driver to be specified as a 'dbi:driver:' string | |||
734 | $driver = $1 if $driver =~ s/^DBI:(.*?)://i; | |||
735 | ||||
736 | Carp::croak("usage: $class->install_driver(\$driver [, \%attr])") | |||
737 | unless ($driver and @_<=3); | |||
738 | ||||
739 | # already installed | |||
740 | return $drh if $drh = $DBI::installed_drh{$driver}; | |||
741 | ||||
742 | $class->trace_msg(" -> $class->install_driver($driver" | |||
743 | .") for $^O perl=$] pid=$$ ruid=$< euid=$>\n") | |||
744 | if $DBI::dbi_debug; | |||
745 | ||||
746 | # --- load the code | |||
747 | my $driver_class = "DBD::$driver"; | |||
748 | 1 | 0.00121 | 0.00121 | eval qq{package # hide from PAUSE |
749 | DBI::_firesafe; # just in case | |||
750 | require $driver_class; # load the driver | |||
751 | }; | |||
752 | if ($@) { | |||
753 | my $err = $@; | |||
754 | my $advice = ""; | |||
755 | if ($err =~ /Can't find loadable object/) { | |||
756 | $advice = "Perhaps DBD::$driver was statically linked into a new perl binary." | |||
757 | ."\nIn which case you need to use that new perl binary." | |||
758 | ."\nOr perhaps only the .pm file was installed but not the shared object file." | |||
759 | } | |||
760 | elsif ($err =~ /Can't locate.*?DBD\/$driver\.pm in \@INC/) { | |||
761 | my @drv = $class->available_drivers(1); | |||
762 | $advice = "Perhaps the DBD::$driver perl module hasn't been fully installed,\n" | |||
763 | ."or perhaps the capitalisation of '$driver' isn't right.\n" | |||
764 | ."Available drivers: ".join(", ", @drv)."."; | |||
765 | } | |||
766 | elsif ($err =~ /Can't load .*? for module DBD::/) { | |||
767 | $advice = "Perhaps a required shared library or dll isn't installed where expected"; | |||
768 | } | |||
769 | elsif ($err =~ /Can't locate .*? in \@INC/) { | |||
770 | $advice = "Perhaps a module that DBD::$driver requires hasn't been fully installed"; | |||
771 | } | |||
772 | Carp::croak("install_driver($driver) failed: $err$advice\n"); | |||
773 | } | |||
774 | if ($DBI::dbi_debug) { | |||
775 | 3 | 0.00031 | 0.00010 | no strict 'refs'; # spent 24µs making 1 call to strict::unimport |
776 | (my $driver_file = $driver_class) =~ s/::/\//g; | |||
777 | my $dbd_ver = ${"$driver_class\::VERSION"} || "undef"; | |||
778 | $class->trace_msg(" install_driver: $driver_class version $dbd_ver" | |||
779 | ." loaded from $INC{qq($driver_file.pm)}\n"); | |||
780 | } | |||
781 | ||||
782 | # --- do some behind-the-scenes checks and setups on the driver | |||
783 | $class->setup_driver($driver_class); # spent 151µs making 1 call to DBI::setup_driver | |||
784 | ||||
785 | # --- run the driver function | |||
786 | 1 | 8.0e-6 | 8.0e-6 | $drh = eval { $driver_class->driver($attr || {}) }; # spent 96µs making 1 call to DBD::SQLite::driver |
787 | unless ($drh && ref $drh && !$@) { | |||
788 | my $advice = ""; | |||
789 | $@ ||= "$driver_class->driver didn't return a handle"; | |||
790 | # catch people on case in-sensitive systems using the wrong case | |||
791 | $advice = "\nPerhaps the capitalisation of DBD '$driver' isn't right." | |||
792 | if $@ =~ /locate object method/; | |||
793 | Carp::croak("$driver_class initialisation failed: $@$advice"); | |||
794 | } | |||
795 | ||||
796 | $DBI::installed_drh{$driver} = $drh; | |||
797 | $class->trace_msg(" <- install_driver= $drh\n") if $DBI::dbi_debug; | |||
798 | $drh; | |||
799 | } | |||
800 | ||||
801 | 1 | 2.0e-6 | 2.0e-6 | *driver = \&install_driver; # currently an alias, may change |
802 | ||||
803 | ||||
804 | sub setup_driver { | |||
805 | 6 | 1.1e-5 | 1.8e-6 | my ($class, $driver_class) = @_; |
806 | my $type; | |||
807 | foreach $type (qw(dr db st)){ | |||
808 | 24 | 0.00026 | 1.1e-5 | my $class = $driver_class."::$type"; |
809 | 3 | 0.00025 | 8.3e-5 | no strict 'refs'; # spent 20µs making 1 call to strict::unimport |
810 | push @{"${class}::ISA"}, "DBD::_::$type" # spent 35µs making 6 calls to UNIVERSAL::isa, avg 6µs/call | |||
811 | unless UNIVERSAL::isa($class, "DBD::_::$type"); | |||
812 | my $mem_class = "DBD::_mem::$type"; | |||
813 | push @{"${class}_mem::ISA"}, $mem_class # spent 35µs making 6 calls to UNIVERSAL::isa, avg 6µs/call | |||
814 | unless UNIVERSAL::isa("${class}_mem", $mem_class) | |||
815 | or $DBI::PurePerl; | |||
816 | } | |||
817 | } | |||
818 | ||||
819 | ||||
820 | sub _rebless { | |||
821 | my $dbh = shift; | |||
822 | my ($outer, $inner) = DBI::_handles($dbh); | |||
823 | my $class = shift(@_).'::db'; | |||
824 | bless $inner => $class; | |||
825 | bless $outer => $class; # outer last for return | |||
826 | } | |||
827 | ||||
828 | ||||
829 | sub _set_isa { | |||
830 | my ($classes, $topclass) = @_; | |||
831 | my $trace = DBI->trace_msg(" _set_isa([@$classes])\n"); | |||
832 | foreach my $suffix ('::db','::st') { | |||
833 | my $previous = $topclass || 'DBI'; # trees are rooted here | |||
834 | foreach my $class (@$classes) { | |||
835 | my $base_class = $previous.$suffix; | |||
836 | my $sub_class = $class.$suffix; | |||
837 | my $sub_class_isa = "${sub_class}::ISA"; | |||
838 | 3 | 0.00064 | 0.00021 | no strict 'refs'; # spent 55µs making 1 call to strict::unimport |
839 | if (@$sub_class_isa) { | |||
840 | DBI->trace_msg(" $sub_class_isa skipped (already set to @$sub_class_isa)\n") | |||
841 | if $trace; | |||
842 | } | |||
843 | else { | |||
844 | @$sub_class_isa = ($base_class) unless @$sub_class_isa; | |||
845 | DBI->trace_msg(" $sub_class_isa = $base_class\n") | |||
846 | if $trace; | |||
847 | } | |||
848 | $previous = $class; | |||
849 | } | |||
850 | } | |||
851 | } | |||
852 | ||||
853 | ||||
854 | sub _rebless_dbtype_subclass { | |||
855 | my ($dbh, $rootclass, $DbTypeSubclass) = @_; | |||
856 | # determine the db type names for class hierarchy | |||
857 | my @hierarchy = DBI::_dbtype_names($dbh, $DbTypeSubclass); | |||
858 | # add the rootclass prefix to each ('DBI::' or 'MyDBI::' etc) | |||
859 | $_ = $rootclass.'::'.$_ foreach (@hierarchy); | |||
860 | # load the modules from the 'top down' | |||
861 | DBI::_load_class($_, 1) foreach (reverse @hierarchy); | |||
862 | # setup class hierarchy if needed, does both '::db' and '::st' | |||
863 | DBI::_set_isa(\@hierarchy, $rootclass); | |||
864 | # finally bless the handle into the subclass | |||
865 | DBI::_rebless($dbh, $hierarchy[0]); | |||
866 | } | |||
867 | ||||
868 | ||||
869 | sub _dbtype_names { # list dbtypes for hierarchy, ie Informix=>ADO=>ODBC | |||
870 | my ($dbh, $DbTypeSubclass) = @_; | |||
871 | ||||
872 | if ($DbTypeSubclass && $DbTypeSubclass ne '1' && ref $DbTypeSubclass ne 'CODE') { | |||
873 | # treat $DbTypeSubclass as a comma separated list of names | |||
874 | my @dbtypes = split /\s*,\s*/, $DbTypeSubclass; | |||
875 | $dbh->trace_msg(" DbTypeSubclass($DbTypeSubclass)=@dbtypes (explicit)\n"); | |||
876 | return @dbtypes; | |||
877 | } | |||
878 | ||||
879 | # XXX will call $dbh->get_info(17) (=SQL_DBMS_NAME) in future? | |||
880 | ||||
881 | my $driver = $dbh->{Driver}->{Name}; | |||
882 | if ( $driver eq 'Proxy' ) { | |||
883 | # XXX Looking into the internals of DBD::Proxy is questionable! | |||
884 | ($driver) = $dbh->{proxy_client}->{application} =~ /^DBI:(.+?):/i | |||
885 | or die "Can't determine driver name from proxy"; | |||
886 | } | |||
887 | ||||
888 | my @dbtypes = (ucfirst($driver)); | |||
889 | if ($driver eq 'ODBC' || $driver eq 'ADO') { | |||
890 | # XXX will move these out and make extensible later: | |||
891 | my $_dbtype_name_regexp = 'Oracle'; # eg 'Oracle|Foo|Bar' | |||
892 | my %_dbtype_name_map = ( | |||
893 | 'Microsoft SQL Server' => 'MSSQL', | |||
894 | 'SQL Server' => 'Sybase', | |||
895 | 'Adaptive Server Anywhere' => 'ASAny', | |||
896 | 'ADABAS D' => 'AdabasD', | |||
897 | ); | |||
898 | ||||
899 | my $name; | |||
900 | $name = $dbh->func(17, 'GetInfo') # SQL_DBMS_NAME | |||
901 | if $driver eq 'ODBC'; | |||
902 | $name = $dbh->{ado_conn}->Properties->Item('DBMS Name')->Value | |||
903 | if $driver eq 'ADO'; | |||
904 | die "Can't determine driver name! ($DBI::errstr)\n" | |||
905 | unless $name; | |||
906 | ||||
907 | my $dbtype; | |||
908 | if ($_dbtype_name_map{$name}) { | |||
909 | $dbtype = $_dbtype_name_map{$name}; | |||
910 | } | |||
911 | else { | |||
912 | if ($name =~ /($_dbtype_name_regexp)/) { | |||
913 | $dbtype = lc($1); | |||
914 | } | |||
915 | else { # generic mangling for other names: | |||
916 | $dbtype = lc($name); | |||
917 | } | |||
918 | $dbtype =~ s/\b(\w)/\U$1/g; | |||
919 | $dbtype =~ s/\W+/_/g; | |||
920 | } | |||
921 | # add ODBC 'behind' ADO | |||
922 | push @dbtypes, 'ODBC' if $driver eq 'ADO'; | |||
923 | # add discovered dbtype in front of ADO/ODBC | |||
924 | unshift @dbtypes, $dbtype; | |||
925 | } | |||
926 | @dbtypes = &$DbTypeSubclass($dbh, \@dbtypes) | |||
927 | if (ref $DbTypeSubclass eq 'CODE'); | |||
928 | $dbh->trace_msg(" DbTypeSubclass($DbTypeSubclass)=@dbtypes\n"); | |||
929 | return @dbtypes; | |||
930 | } | |||
931 | ||||
932 | sub _load_class { | |||
933 | my ($load_class, $missing_ok) = @_; | |||
934 | DBI->trace_msg(" _load_class($load_class, $missing_ok)\n", 2); | |||
935 | 3 | 0.00053 | 0.00018 | no strict 'refs'; # spent 20µs making 1 call to strict::unimport |
936 | return 1 if @{"$load_class\::ISA"}; # already loaded/exists | |||
937 | (my $module = $load_class) =~ s!::!/!g; | |||
938 | DBI->trace_msg(" _load_class require $module\n", 2); | |||
939 | eval { require "$module.pm"; }; | |||
940 | return 1 unless $@; | |||
941 | return 0 if $missing_ok && $@ =~ /^Can't locate \Q$module.pm\E/; | |||
942 | die $@; | |||
943 | } | |||
944 | ||||
945 | ||||
946 | sub init_rootclass { # deprecated | |||
947 | return 1; | |||
948 | } | |||
949 | ||||
950 | ||||
951 | 1 | 1.0e-6 | 1.0e-6 | *internal = \&DBD::Switch::dr::driver; |
952 | ||||
953 | ||||
954 | sub available_drivers { | |||
955 | my($quiet) = @_; | |||
956 | my(@drivers, $d, $f); | |||
957 | local(*DBI::DIR, $@); | |||
958 | my(%seen_dir, %seen_dbd); | |||
959 | my $haveFileSpec = eval { require File::Spec }; | |||
960 | foreach $d (@INC){ | |||
961 | chomp($d); # Perl 5 beta 3 bug in #!./perl -Ilib from Test::Harness | |||
962 | my $dbd_dir = | |||
963 | ($haveFileSpec ? File::Spec->catdir($d, 'DBD') : "$d/DBD"); | |||
964 | next unless -d $dbd_dir; | |||
965 | next if $seen_dir{$d}; | |||
966 | $seen_dir{$d} = 1; | |||
967 | # XXX we have a problem here with case insensitive file systems | |||
968 | # XXX since we can't tell what case must be used when loading. | |||
969 | opendir(DBI::DIR, $dbd_dir) || Carp::carp "opendir $dbd_dir: $!\n"; | |||
970 | foreach $f (readdir(DBI::DIR)){ | |||
971 | next unless $f =~ s/\.pm$//; | |||
972 | next if $f eq 'NullP'; | |||
973 | if ($seen_dbd{$f}){ | |||
974 | Carp::carp "DBD::$f in $d is hidden by DBD::$f in $seen_dbd{$f}\n" | |||
975 | unless $quiet; | |||
976 | } else { | |||
977 | push(@drivers, $f); | |||
978 | } | |||
979 | $seen_dbd{$f} = $d; | |||
980 | } | |||
981 | closedir(DBI::DIR); | |||
982 | } | |||
983 | ||||
984 | # "return sort @drivers" will not DWIM in scalar context. | |||
985 | return wantarray ? sort @drivers : @drivers; | |||
986 | } | |||
987 | ||||
988 | sub installed_versions { | |||
989 | my ($class, $quiet) = @_; | |||
990 | my %error; | |||
991 | my %version = ( DBI => $DBI::VERSION ); | |||
992 | $version{"DBI::PurePerl"} = $DBI::PurePerl::VERSION | |||
993 | if $DBI::PurePerl; | |||
994 | for my $driver ($class->available_drivers($quiet)) { | |||
995 | next if $DBI::PurePerl && grep { -d "$_/auto/DBD/$driver" } @INC; | |||
996 | my $drh = eval { | |||
997 | local $SIG{__WARN__} = sub {}; | |||
998 | $class->install_driver($driver); | |||
999 | }; | |||
1000 | ($error{"DBD::$driver"}=$@),next if $@; | |||
1001 | 3 | 0.00209 | 0.00070 | no strict 'refs'; # spent 21µs making 1 call to strict::unimport |
1002 | my $vers = ${"DBD::$driver" . '::VERSION'}; | |||
1003 | $version{"DBD::$driver"} = $vers || '?'; | |||
1004 | } | |||
1005 | if (wantarray) { | |||
1006 | return map { m/^DBD::(\w+)/ ? ($1) : () } sort keys %version; | |||
1007 | } | |||
1008 | if (!defined wantarray) { # void context | |||
1009 | require Config; # add more detail | |||
1010 | $version{OS} = "$^O\t($Config::Config{osvers})"; | |||
1011 | $version{Perl} = "$]\t($Config::Config{archname})"; | |||
1012 | $version{$_} = (($error{$_} =~ s/ \(\@INC.*//s),$error{$_}) | |||
1013 | for keys %error; | |||
1014 | printf " %-16s: %s\n",$_,$version{$_} | |||
1015 | for reverse sort keys %version; | |||
1016 | } | |||
1017 | return \%version; | |||
1018 | } | |||
1019 | ||||
1020 | ||||
1021 | sub data_sources { | |||
1022 | my ($class, $driver, @other) = @_; | |||
1023 | my $drh = $class->install_driver($driver); | |||
1024 | my @ds = $drh->data_sources(@other); | |||
1025 | return @ds; | |||
1026 | } | |||
1027 | ||||
1028 | ||||
1029 | sub neat_list { | |||
1030 | my ($listref, $maxlen, $sep) = @_; | |||
1031 | $maxlen = 0 unless defined $maxlen; # 0 == use internal default | |||
1032 | $sep = ", " unless defined $sep; | |||
1033 | join($sep, map { neat($_,$maxlen) } @$listref); | |||
1034 | } | |||
1035 | ||||
1036 | ||||
1037 | sub dump_results { # also aliased as a method in DBD::_::st | |||
1038 | my ($sth, $maxlen, $lsep, $fsep, $fh) = @_; | |||
1039 | return 0 unless $sth; | |||
1040 | $maxlen ||= 35; | |||
1041 | $lsep ||= "\n"; | |||
1042 | $fh ||= \*STDOUT; | |||
1043 | my $rows = 0; | |||
1044 | my $ref; | |||
1045 | while($ref = $sth->fetch) { | |||
1046 | print $fh $lsep if $rows++ and $lsep; | |||
1047 | my $str = neat_list($ref,$maxlen,$fsep); | |||
1048 | print $fh $str; # done on two lines to avoid 5.003 errors | |||
1049 | } | |||
1050 | print $fh "\n$rows rows".($DBI::err ? " ($DBI::err: $DBI::errstr)" : "")."\n"; | |||
1051 | $rows; | |||
1052 | } | |||
1053 | ||||
1054 | ||||
1055 | sub data_diff { | |||
1056 | my ($a, $b, $logical) = @_; | |||
1057 | ||||
1058 | my $diff = data_string_diff($a, $b); | |||
1059 | return "" if $logical and !$diff; | |||
1060 | ||||
1061 | my $a_desc = data_string_desc($a); | |||
1062 | my $b_desc = data_string_desc($b); | |||
1063 | return "" if !$diff and $a_desc eq $b_desc; | |||
1064 | ||||
1065 | $diff ||= "Strings contain the same sequence of characters" | |||
1066 | if length($a); | |||
1067 | $diff .= "\n" if $diff; | |||
1068 | return "a: $a_desc\nb: $b_desc\n$diff"; | |||
1069 | } | |||
1070 | ||||
1071 | ||||
1072 | sub data_string_diff { | |||
1073 | # Compares 'logical' characters, not bytes, so a latin1 string and an | |||
1074 | # an equivalent unicode string will compare as equal even though their | |||
1075 | # byte encodings are different. | |||
1076 | my ($a, $b) = @_; | |||
1077 | unless (defined $a and defined $b) { # one undef | |||
1078 | return "" | |||
1079 | if !defined $a and !defined $b; | |||
1080 | return "String a is undef, string b has ".length($b)." characters" | |||
1081 | if !defined $a; | |||
1082 | return "String b is undef, string a has ".length($a)." characters" | |||
1083 | if !defined $b; | |||
1084 | } | |||
1085 | ||||
1086 | require utf8; | |||
1087 | # hack to cater for perl 5.6 | |||
1088 | *utf8::is_utf8 = sub { (DBI::neat(shift)=~/^"/) } unless defined &utf8::is_utf8; | |||
1089 | ||||
1090 | my @a_chars = (utf8::is_utf8($a)) ? unpack("U*", $a) : unpack("C*", $a); | |||
1091 | my @b_chars = (utf8::is_utf8($b)) ? unpack("U*", $b) : unpack("C*", $b); | |||
1092 | my $i = 0; | |||
1093 | while (@a_chars && @b_chars) { | |||
1094 | ++$i, shift(@a_chars), shift(@b_chars), next | |||
1095 | if $a_chars[0] == $b_chars[0];# compare ordinal values | |||
1096 | my @desc = map { | |||
1097 | $_ > 255 ? # if wide character... | |||
1098 | sprintf("\\x{%04X}", $_) : # \x{...} | |||
1099 | chr($_) =~ /[[:cntrl:]]/ ? # else if control character ... | |||
1100 | sprintf("\\x%02X", $_) : # \x.. | |||
1101 | chr($_) # else as themselves | |||
1102 | } ($a_chars[0], $b_chars[0]); | |||
1103 | # highlight probable double-encoding? | |||
1104 | foreach my $c ( @desc ) { | |||
1105 | next unless $c =~ m/\\x\{08(..)}/; | |||
1106 | $c .= "='" .chr(hex($1)) ."'" | |||
1107 | } | |||
1108 | return sprintf "Strings differ at index $i: a[$i]=$desc[0], b[$i]=$desc[1]"; | |||
1109 | } | |||
1110 | return "String a truncated after $i characters" if @b_chars; | |||
1111 | return "String b truncated after $i characters" if @a_chars; | |||
1112 | return ""; | |||
1113 | } | |||
1114 | ||||
1115 | ||||
1116 | sub data_string_desc { # describe a data string | |||
1117 | my ($a) = @_; | |||
1118 | require bytes; | |||
1119 | require utf8; | |||
1120 | ||||
1121 | # hacks to cater for perl 5.6 | |||
1122 | *utf8::is_utf8 = sub { (DBI::neat(shift)=~/^"/) } unless defined &utf8::is_utf8; | |||
1123 | *utf8::valid = sub { 1 } unless defined &utf8::valid; | |||
1124 | ||||
1125 | # Give sufficient info to help diagnose at least these kinds of situations: | |||
1126 | # - valid UTF8 byte sequence but UTF8 flag not set | |||
1127 | # (might be ascii so also need to check for hibit to make it worthwhile) | |||
1128 | # - UTF8 flag set but invalid UTF8 byte sequence | |||
1129 | # could do better here, but this'll do for now | |||
1130 | my $utf8 = sprintf "UTF8 %s%s", | |||
1131 | utf8::is_utf8($a) ? "on" : "off", | |||
1132 | utf8::valid($a||'') ? "" : " but INVALID encoding"; | |||
1133 | return "$utf8, undef" unless defined $a; | |||
1134 | my $is_ascii = $a =~ m/^[\000-\177]*$/; | |||
1135 | return sprintf "%s, %s, %d characters %d bytes", | |||
1136 | $utf8, $is_ascii ? "ASCII" : "non-ASCII", | |||
1137 | length($a), bytes::length($a); | |||
1138 | } | |||
1139 | ||||
1140 | ||||
1141 | sub connect_test_perf { | |||
1142 | my($class, $dsn,$dbuser,$dbpass, $attr) = @_; | |||
1143 | Carp::croak("connect_test_perf needs hash ref as fourth arg") unless ref $attr; | |||
1144 | # these are non standard attributes just for this special method | |||
1145 | my $loops ||= $attr->{dbi_loops} || 5; | |||
1146 | my $par ||= $attr->{dbi_par} || 1; # parallelism | |||
1147 | my $verb ||= $attr->{dbi_verb} || 1; | |||
1148 | my $meth ||= $attr->{dbi_meth} || 'connect'; | |||
1149 | print "$dsn: testing $loops sets of $par connections:\n"; | |||
1150 | require "FileHandle.pm"; # don't let toke.c create empty FileHandle package | |||
1151 | local $| = 1; | |||
1152 | my $drh = $class->install_driver($dsn) or Carp::croak("Can't install $dsn driver\n"); | |||
1153 | # test the connection and warm up caches etc | |||
1154 | $drh->connect($dsn,$dbuser,$dbpass) or Carp::croak("connect failed: $DBI::errstr"); | |||
1155 | my $t1 = dbi_time(); | |||
1156 | my $loop; | |||
1157 | for $loop (1..$loops) { | |||
1158 | my @cons; | |||
1159 | print "Connecting... " if $verb; | |||
1160 | for (1..$par) { | |||
1161 | print "$_ "; | |||
1162 | push @cons, ($drh->connect($dsn,$dbuser,$dbpass) | |||
1163 | or Carp::croak("connect failed: $DBI::errstr\n")); | |||
1164 | } | |||
1165 | print "\nDisconnecting...\n" if $verb; | |||
1166 | for (@cons) { | |||
1167 | $_->disconnect or warn "disconnect failed: $DBI::errstr" | |||
1168 | } | |||
1169 | } | |||
1170 | my $t2 = dbi_time(); | |||
1171 | my $td = $t2 - $t1; | |||
1172 | printf "$meth %d and disconnect them, %d times: %.4fs / %d = %.4fs\n", | |||
1173 | $par, $loops, $td, $loops*$par, $td/($loops*$par); | |||
1174 | return $td; | |||
1175 | } | |||
1176 | ||||
1177 | ||||
1178 | # Help people doing DBI->errstr, might even document it one day | |||
1179 | # XXX probably best moved to cheaper XS code if this gets documented | |||
1180 | sub err { $DBI::err } | |||
1181 | sub errstr { $DBI::errstr } | |||
1182 | ||||
1183 | ||||
1184 | # --- Private Internal Function for Creating New DBI Handles | |||
1185 | ||||
1186 | # XXX move to PurePerl? | |||
1187 | 1 | 0 | 0 | *DBI::dr::TIEHASH = \&DBI::st::TIEHASH; |
1188 | 1 | 0 | 0 | *DBI::db::TIEHASH = \&DBI::st::TIEHASH; |
1189 | ||||
1190 | ||||
1191 | # These three special constructors are called by the drivers | |||
1192 | # The way they are called is likely to change. | |||
1193 | ||||
1194 | 1 | 1.0e-6 | 1.0e-6 | our $shared_profile; |
1195 | ||||
1196 | # spent 85µs (24+61) within DBI::_new_drh which was called
# once (24µs+61µs) by DBD::SQLite::driver at line 28 of /wise/base/static/lib/perl5/site_perl/5.10.0/x86_64-linux-thread-multi/DBD/SQLite.pm | |||
1197 | 6 | 8.0e-5 | 1.3e-5 | my ($class, $initial_attr, $imp_data) = @_; |
1198 | # Provide default storage for State,Err and Errstr. | |||
1199 | # Note that these are shared by all child handles by default! XXX | |||
1200 | # State must be undef to get automatic faking in DBI::var::FETCH | |||
1201 | my ($h_state_store, $h_err_store, $h_errstr_store) = (undef, 0, ''); | |||
1202 | my $attr = { | |||
1203 | # these attributes get copied down to child handles by default | |||
1204 | 'State' => \$h_state_store, # Holder for DBI::state | |||
1205 | 'Err' => \$h_err_store, # Holder for DBI::err | |||
1206 | 'Errstr' => \$h_errstr_store, # Holder for DBI::errstr | |||
1207 | 'TraceLevel' => 0, | |||
1208 | FetchHashKeyName=> 'NAME', | |||
1209 | %$initial_attr, | |||
1210 | }; | |||
1211 | my ($h, $i) = _new_handle('DBI::dr', '', $attr, $imp_data, $class); # spent 61µs making 1 call to DBI::_new_handle | |||
1212 | ||||
1213 | # XXX DBI_PROFILE unless DBI::PurePerl because for some reason | |||
1214 | # it kills the t/zz_*_pp.t tests (they silently exit early) | |||
1215 | if ($ENV{DBI_PROFILE} && !$DBI::PurePerl) { | |||
1216 | # The profile object created here when the first driver is loaded | |||
1217 | # is shared by all drivers so we end up with just one set of profile | |||
1218 | # data and thus the 'total time in DBI' is really the true total. | |||
1219 | if (!$shared_profile) { # first time | |||
1220 | $h->{Profile} = $ENV{DBI_PROFILE}; | |||
1221 | $shared_profile = $h->{Profile}; | |||
1222 | } | |||
1223 | else { | |||
1224 | $h->{Profile} = $shared_profile; | |||
1225 | } | |||
1226 | } | |||
1227 | return $h unless wantarray; | |||
1228 | ($h, $i); | |||
1229 | } | |||
1230 | ||||
1231 | # spent 60µs (23+37) within DBI::_new_dbh which was called
# once (23µs+37µs) by DBD::SQLite::dr::connect at line 50 of /wise/base/static/lib/perl5/site_perl/5.10.0/x86_64-linux-thread-multi/DBD/SQLite.pm | |||
1232 | 9 | 5.4e-5 | 6.0e-6 | my ($drh, $attr, $imp_data) = @_; |
1233 | my $imp_class = $drh->{ImplementorClass} | |||
1234 | or Carp::croak("DBI _new_dbh: $drh has no ImplementorClass"); | |||
1235 | substr($imp_class,-4,4) = '::db'; | |||
1236 | my $app_class = ref $drh; | |||
1237 | substr($app_class,-4,4) = '::db'; | |||
1238 | $attr->{Err} ||= \my $err; | |||
1239 | $attr->{Errstr} ||= \my $errstr; | |||
1240 | $attr->{State} ||= \my $state; | |||
1241 | _new_handle($app_class, $drh, $attr, $imp_data, $imp_class); # spent 37µs making 1 call to DBI::_new_handle | |||
1242 | } | |||
1243 | ||||
1244 | # spent 183µs (62+121) within DBI::_new_sth which was called 3 times, avg 61µs/call:
# 3 times (62µs+121µs) by DBD::SQLite::db::prepare at line 110 of /wise/base/static/lib/perl5/site_perl/5.10.0/x86_64-linux-thread-multi/DBD/SQLite.pm, avg 61µs/call | |||
1245 | 18 | 0.00016 | 9.1e-6 | my ($dbh, $attr, $imp_data) = @_; |
1246 | my $imp_class = $dbh->{ImplementorClass} | |||
1247 | or Carp::croak("DBI _new_sth: $dbh has no ImplementorClass"); | |||
1248 | substr($imp_class,-4,4) = '::st'; | |||
1249 | my $app_class = ref $dbh; | |||
1250 | substr($app_class,-4,4) = '::st'; | |||
1251 | _new_handle($app_class, $dbh, $attr, $imp_data, $imp_class); # spent 121µs making 3 calls to DBI::_new_handle, avg 40µs/call | |||
1252 | } | |||
1253 | ||||
1254 | ||||
1255 | # end of DBI package | |||
1256 | ||||
1257 | ||||
1258 | ||||
1259 | # -------------------------------------------------------------------- | |||
1260 | # === The internal DBI Switch pseudo 'driver' class === | |||
1261 | ||||
1262 | 1 | 1.0e-6 | 1.0e-6 | { package # hide from PAUSE |
1263 | DBD::Switch::dr; | |||
1264 | 4 | 1.0e-5 | 2.5e-6 | DBI->setup_driver('DBD::Switch'); # sets up @ISA # spent 133µs making 1 call to DBI::setup_driver |
1265 | ||||
1266 | $DBD::Switch::dr::imp_data_size = 0; | |||
1267 | $DBD::Switch::dr::imp_data_size = 0; # avoid typo warning | |||
1268 | my $drh; | |||
1269 | ||||
1270 | sub driver { | |||
1271 | return $drh if $drh; # a package global | |||
1272 | ||||
1273 | my $inner; | |||
1274 | ($drh, $inner) = DBI::_new_drh('DBD::Switch::dr', { | |||
1275 | 'Name' => 'Switch', | |||
1276 | 'Version' => $DBI::VERSION, | |||
1277 | 'Attribution' => "DBI $DBI::VERSION by Tim Bunce", | |||
1278 | }); | |||
1279 | Carp::croak("DBD::Switch init failed!") unless ($drh && $inner); | |||
1280 | return $drh; | |||
1281 | } | |||
1282 | sub CLONE { | |||
1283 | undef $drh; | |||
1284 | } | |||
1285 | ||||
1286 | sub FETCH { | |||
1287 | my($drh, $key) = @_; | |||
1288 | return DBI->trace if $key eq 'DebugDispatch'; | |||
1289 | return undef if $key eq 'DebugLog'; # not worth fetching, sorry | |||
1290 | return $drh->DBD::_::dr::FETCH($key); | |||
1291 | undef; | |||
1292 | } | |||
1293 | sub STORE { | |||
1294 | my($drh, $key, $value) = @_; | |||
1295 | if ($key eq 'DebugDispatch') { | |||
1296 | DBI->trace($value); | |||
1297 | } elsif ($key eq 'DebugLog') { | |||
1298 | DBI->trace(-1, $value); | |||
1299 | } else { | |||
1300 | $drh->DBD::_::dr::STORE($key, $value); | |||
1301 | } | |||
1302 | } | |||
1303 | } | |||
1304 | ||||
1305 | ||||
1306 | # -------------------------------------------------------------------- | |||
1307 | # === OPTIONAL MINIMAL BASE CLASSES FOR DBI SUBCLASSES === | |||
1308 | ||||
1309 | # We only define default methods for harmless functions. | |||
1310 | # We don't, for example, define a DBD::_::st::prepare() | |||
1311 | ||||
1312 | 1 | 1.0e-6 | 1.0e-6 | { package # hide from PAUSE |
1313 | DBD::_::common; # ====== Common base class methods ====== | |||
1314 | 3 | 0.00069 | 0.00023 | use strict; # spent 11µs making 1 call to strict::import |
1315 | ||||
1316 | # methods common to all handle types: | |||
1317 | ||||
1318 | sub _not_impl { | |||
1319 | 3 | 2.2e-5 | 7.3e-6 | my ($h, $method) = @_; |
1320 | $h->trace_msg("Driver does not implement the $method method.\n"); # spent 13µs making 1 call to DBI::common::trace_msg | |||
1321 | return; # empty list / undef | |||
1322 | } | |||
1323 | ||||
1324 | # generic TIEHASH default methods: | |||
1325 | sub FIRSTKEY { } | |||
1326 | sub NEXTKEY { } | |||
1327 | sub EXISTS { defined($_[0]->FETCH($_[1])) } # XXX undef? | |||
1328 | sub CLEAR { Carp::carp "Can't CLEAR $_[0] (DBI)" } | |||
1329 | ||||
1330 | sub FETCH_many { # XXX should move to C one day | |||
1331 | my $h = shift; | |||
1332 | return map { $h->FETCH($_) } @_; | |||
1333 | } | |||
1334 | ||||
1335 | 1 | 1.0e-6 | 1.0e-6 | *dump_handle = \&DBI::dump_handle; |
1336 | ||||
1337 | sub install_method { | |||
1338 | # special class method called directly by apps and/or drivers | |||
1339 | # to install new methods into the DBI dispatcher | |||
1340 | # DBD::Foo::db->install_method("foo_mumble", { usage => [...], options => '...' }); | |||
1341 | my ($class, $method, $attr) = @_; | |||
1342 | Carp::croak("Class '$class' must begin with DBD:: and end with ::db or ::st") | |||
1343 | unless $class =~ /^DBD::(\w+)::(dr|db|st)$/; | |||
1344 | my ($driver, $subtype) = ($1, $2); | |||
1345 | Carp::croak("invalid method name '$method'") | |||
1346 | unless $method =~ m/^([a-z]+_)\w+$/; | |||
1347 | my $prefix = $1; | |||
1348 | my $reg_info = $dbd_prefix_registry->{$prefix}; | |||
1349 | Carp::carp("method name prefix '$prefix' is not associated with a registered driver") unless $reg_info; | |||
1350 | ||||
1351 | my $full_method = "DBI::${subtype}::$method"; | |||
1352 | $DBI::installed_methods{$full_method} = $attr; | |||
1353 | ||||
1354 | my (undef, $filename, $line) = caller; | |||
1355 | # XXX reformat $attr as needed for _install_method | |||
1356 | my %attr = %{$attr||{}}; # copy so we can edit | |||
1357 | DBI->_install_method("DBI::${subtype}::$method", "$filename at line $line", \%attr); | |||
1358 | } | |||
1359 | ||||
1360 | sub parse_trace_flags { | |||
1361 | my ($h, $spec) = @_; | |||
1362 | my $level = 0; | |||
1363 | my $flags = 0; | |||
1364 | my @unknown; | |||
1365 | for my $word (split /\s*[|&,]\s*/, $spec) { | |||
1366 | if (DBI::looks_like_number($word) && $word <= 0xF && $word >= 0) { | |||
1367 | $level = $word; | |||
1368 | } elsif ($word eq 'ALL') { | |||
1369 | $flags = 0x7FFFFFFF; # XXX last bit causes negative headaches | |||
1370 | last; | |||
1371 | } elsif (my $flag = $h->parse_trace_flag($word)) { | |||
1372 | $flags |= $flag; | |||
1373 | } | |||
1374 | else { | |||
1375 | push @unknown, $word; | |||
1376 | } | |||
1377 | } | |||
1378 | if (@unknown && (ref $h ? $h->FETCH('Warn') : 1)) { | |||
1379 | Carp::carp("$h->parse_trace_flags($spec) ignored unknown trace flags: ". | |||
1380 | join(" ", map { DBI::neat($_) } @unknown)); | |||
1381 | } | |||
1382 | $flags |= $level; | |||
1383 | return $flags; | |||
1384 | } | |||
1385 | ||||
1386 | sub parse_trace_flag { | |||
1387 | my ($h, $name) = @_; | |||
1388 | # 0xddDDDDrL (driver, DBI, reserved, Level) | |||
1389 | return 0x00000100 if $name eq 'SQL'; | |||
1390 | return; | |||
1391 | } | |||
1392 | ||||
1393 | sub private_attribute_info { | |||
1394 | return undef; | |||
1395 | } | |||
1396 | ||||
1397 | } | |||
1398 | ||||
1399 | ||||
1400 | 1 | 1.0e-6 | 1.0e-6 | { package # hide from PAUSE |
1401 | DBD::_::dr; # ====== DRIVER ====== | |||
1402 | 1 | 7.0e-6 | 7.0e-6 | @DBD::_::dr::ISA = qw(DBD::_::common); |
1403 | 3 | 0.00039 | 0.00013 | use strict; # spent 8µs making 1 call to strict::import |
1404 | ||||
1405 | sub default_user { | |||
1406 | 4 | 5.0e-6 | 1.2e-6 | my ($drh, $user, $pass, $attr) = @_; |
1407 | $user = $ENV{DBI_USER} unless defined $user; | |||
1408 | $pass = $ENV{DBI_PASS} unless defined $pass; | |||
1409 | return ($user, $pass); | |||
1410 | } | |||
1411 | ||||
1412 | sub connect { # normally overridden, but a handy default | |||
1413 | my ($drh, $dsn, $user, $auth) = @_; | |||
1414 | my ($this) = DBI::_new_dbh($drh, { | |||
1415 | 'Name' => $dsn, | |||
1416 | }); | |||
1417 | # XXX debatable as there's no "server side" here | |||
1418 | # (and now many uses would trigger warnings on DESTROY) | |||
1419 | # $this->STORE(Active => 1); | |||
1420 | # so drivers should set it in their own connect | |||
1421 | $this; | |||
1422 | } | |||
1423 | ||||
1424 | ||||
1425 | sub connect_cached { | |||
1426 | my $drh = shift; | |||
1427 | my ($dsn, $user, $auth, $attr) = @_; | |||
1428 | ||||
1429 | my $cache = $drh->{CachedKids} ||= {}; | |||
1430 | ||||
1431 | my @attr_keys = $attr ? sort keys %$attr : (); | |||
1432 | my $key = do { local $^W; # silence undef warnings | |||
1433 | join "~~", $dsn, $user, $auth, $attr ? (@attr_keys,@{$attr}{@attr_keys}) : () | |||
1434 | }; | |||
1435 | my $dbh = $cache->{$key}; | |||
1436 | $drh->trace_msg(sprintf(" connect_cached: key '$key', cached dbh $dbh\n", DBI::neat($key), DBI::neat($dbh))) | |||
1437 | if $DBI::dbi_debug >= 4; | |||
1438 | my $cb = $attr->{Callbacks}; # take care not to autovivify | |||
1439 | if ($dbh && $dbh->FETCH('Active') && eval { $dbh->ping }) { | |||
1440 | # If the caller has provided a callback then call it | |||
1441 | if ($cb and $cb = $cb->{"connect_cached.reused"}) { | |||
1442 | local $_ = "connect_cached.reused"; | |||
1443 | $cb->($dbh, $dsn, $user, $auth, $attr); | |||
1444 | } | |||
1445 | return $dbh; | |||
1446 | } | |||
1447 | ||||
1448 | # If the caller has provided a callback then call it | |||
1449 | if ($cb and $cb = $cb->{"connect_cached.new"}) { | |||
1450 | local $_ = "connect_cached.new"; | |||
1451 | $cb->($dbh, $dsn, $user, $auth, $attr); | |||
1452 | } | |||
1453 | ||||
1454 | $dbh = $drh->connect(@_); | |||
1455 | $cache->{$key} = $dbh; # replace prev entry, even if connect failed | |||
1456 | return $dbh; | |||
1457 | } | |||
1458 | ||||
1459 | } | |||
1460 | ||||
1461 | ||||
1462 | 1 | 1.0e-6 | 1.0e-6 | { package # hide from PAUSE |
1463 | DBD::_::db; # ====== DATABASE ====== | |||
1464 | 1 | 5.0e-6 | 5.0e-6 | @DBD::_::db::ISA = qw(DBD::_::common); |
1465 | 3 | 0.00194 | 0.00065 | use strict; # spent 25µs making 1 call to strict::import |
1466 | ||||
1467 | sub clone { | |||
1468 | my ($old_dbh, $attr) = @_; | |||
1469 | my $closure = $old_dbh->{dbi_connect_closure} or return; | |||
1470 | unless ($attr) { | |||
1471 | # copy attributes visible in the attribute cache | |||
1472 | keys %$old_dbh; # reset iterator | |||
1473 | while ( my ($k, $v) = each %$old_dbh ) { | |||
1474 | # ignore non-code refs, i.e., caches, handles, Err etc | |||
1475 | next if ref $v && ref $v ne 'CODE'; # HandleError etc | |||
1476 | $attr->{$k} = $v; | |||
1477 | } | |||
1478 | # explicitly set attributes which are unlikely to be in the | |||
1479 | # attribute cache, i.e., boolean's and some others | |||
1480 | $attr->{$_} = $old_dbh->FETCH($_) for (qw( | |||
1481 | AutoCommit ChopBlanks InactiveDestroy | |||
1482 | LongTruncOk PrintError PrintWarn Profile RaiseError | |||
1483 | ShowErrorStatement TaintIn TaintOut | |||
1484 | )); | |||
1485 | } | |||
1486 | # use Data::Dumper; warn Dumper([$old_dbh, $attr]); | |||
1487 | my $new_dbh = &$closure($old_dbh, $attr); | |||
1488 | unless ($new_dbh) { | |||
1489 | # need to copy err/errstr from driver back into $old_dbh | |||
1490 | my $drh = $old_dbh->{Driver}; | |||
1491 | return $old_dbh->set_err($drh->err, $drh->errstr, $drh->state); | |||
1492 | } | |||
1493 | return $new_dbh; | |||
1494 | } | |||
1495 | ||||
1496 | sub quote_identifier { | |||
1497 | my ($dbh, @id) = @_; | |||
1498 | my $attr = (@id > 3 && ref($id[-1])) ? pop @id : undef; | |||
1499 | ||||
1500 | my $info = $dbh->{dbi_quote_identifier_cache} ||= [ | |||
1501 | $dbh->get_info(29) || '"', # SQL_IDENTIFIER_QUOTE_CHAR | |||
1502 | $dbh->get_info(41) || '.', # SQL_CATALOG_NAME_SEPARATOR | |||
1503 | $dbh->get_info(114) || 1, # SQL_CATALOG_LOCATION | |||
1504 | ]; | |||
1505 | ||||
1506 | my $quote = $info->[0]; | |||
1507 | foreach (@id) { # quote the elements | |||
1508 | next unless defined; | |||
1509 | s/$quote/$quote$quote/g; # escape embedded quotes | |||
1510 | $_ = qq{$quote$_$quote}; | |||
1511 | } | |||
1512 | ||||
1513 | # strip out catalog if present for special handling | |||
1514 | my $catalog = (@id >= 3) ? shift @id : undef; | |||
1515 | ||||
1516 | # join the dots, ignoring any null/undef elements (ie schema) | |||
1517 | my $quoted_id = join '.', grep { defined } @id; | |||
1518 | ||||
1519 | if ($catalog) { # add catalog correctly | |||
1520 | $quoted_id = ($info->[2] == 2) # SQL_CL_END | |||
1521 | ? $quoted_id . $info->[1] . $catalog | |||
1522 | : $catalog . $info->[1] . $quoted_id; | |||
1523 | } | |||
1524 | return $quoted_id; | |||
1525 | } | |||
1526 | ||||
1527 | sub quote { | |||
1528 | my ($dbh, $str, $data_type) = @_; | |||
1529 | ||||
1530 | return "NULL" unless defined $str; | |||
1531 | unless ($data_type) { | |||
1532 | $str =~ s/'/''/g; # ISO SQL2 | |||
1533 | return "'$str'"; | |||
1534 | } | |||
1535 | ||||
1536 | my $dbi_literal_quote_cache = $dbh->{'dbi_literal_quote_cache'} ||= [ {} , {} ]; | |||
1537 | my ($prefixes, $suffixes) = @$dbi_literal_quote_cache; | |||
1538 | ||||
1539 | my $lp = $prefixes->{$data_type}; | |||
1540 | my $ls = $suffixes->{$data_type}; | |||
1541 | ||||
1542 | if ( ! defined $lp || ! defined $ls ) { | |||
1543 | my $ti = $dbh->type_info($data_type); | |||
1544 | $lp = $prefixes->{$data_type} = $ti ? $ti->{LITERAL_PREFIX} || "" : "'"; | |||
1545 | $ls = $suffixes->{$data_type} = $ti ? $ti->{LITERAL_SUFFIX} || "" : "'"; | |||
1546 | } | |||
1547 | return $str unless $lp || $ls; # no quoting required | |||
1548 | ||||
1549 | # XXX don't know what the standard says about escaping | |||
1550 | # in the 'general case' (where $lp != "'"). | |||
1551 | # So we just do this and hope: | |||
1552 | $str =~ s/$lp/$lp$lp/g | |||
1553 | if $lp && $lp eq $ls && ($lp eq "'" || $lp eq '"'); | |||
1554 | return "$lp$str$ls"; | |||
1555 | } | |||
1556 | ||||
1557 | sub rows { -1 } # here so $DBI::rows 'works' after using $dbh | |||
1558 | ||||
1559 | sub do { | |||
1560 | my($dbh, $statement, $attr, @params) = @_; | |||
1561 | my $sth = $dbh->prepare($statement, $attr) or return undef; | |||
1562 | $sth->execute(@params) or return undef; | |||
1563 | my $rows = $sth->rows; | |||
1564 | ($rows == 0) ? "0E0" : $rows; | |||
1565 | } | |||
1566 | ||||
1567 | sub _do_selectrow { | |||
1568 | my ($method, $dbh, $stmt, $attr, @bind) = @_; | |||
1569 | my $sth = ((ref $stmt) ? $stmt : $dbh->prepare($stmt, $attr)) | |||
1570 | or return; | |||
1571 | $sth->execute(@bind) | |||
1572 | or return; | |||
1573 | my $row = $sth->$method() | |||
1574 | and $sth->finish; | |||
1575 | return $row; | |||
1576 | } | |||
1577 | ||||
1578 | sub selectrow_hashref { return _do_selectrow('fetchrow_hashref', @_); } | |||
1579 | ||||
1580 | # XXX selectrow_array/ref also have C implementations in Driver.xst | |||
1581 | sub selectrow_arrayref { return _do_selectrow('fetchrow_arrayref', @_); } | |||
1582 | sub selectrow_array { | |||
1583 | my $row = _do_selectrow('fetchrow_arrayref', @_) or return; | |||
1584 | return $row->[0] unless wantarray; | |||
1585 | return @$row; | |||
1586 | } | |||
1587 | ||||
1588 | # XXX selectall_arrayref also has C implementation in Driver.xst | |||
1589 | # which fallsback to this if a slice is given | |||
1590 | sub selectall_arrayref { | |||
1591 | my ($dbh, $stmt, $attr, @bind) = @_; | |||
1592 | my $sth = (ref $stmt) ? $stmt : $dbh->prepare($stmt, $attr) | |||
1593 | or return; | |||
1594 | $sth->execute(@bind) || return; | |||
1595 | my $slice = $attr->{Slice}; # typically undef, else hash or array ref | |||
1596 | if (!$slice and $slice=$attr->{Columns}) { | |||
1597 | if (ref $slice eq 'ARRAY') { # map col idx to perl array idx | |||
1598 | $slice = [ @{$attr->{Columns}} ]; # take a copy | |||
1599 | for (@$slice) { $_-- } | |||
1600 | } | |||
1601 | } | |||
1602 | my $rows = $sth->fetchall_arrayref($slice, my $MaxRows = $attr->{MaxRows}); | |||
1603 | $sth->finish if defined $MaxRows; | |||
1604 | return $rows; | |||
1605 | } | |||
1606 | ||||
1607 | sub selectall_hashref { | |||
1608 | my ($dbh, $stmt, $key_field, $attr, @bind) = @_; | |||
1609 | my $sth = (ref $stmt) ? $stmt : $dbh->prepare($stmt, $attr); | |||
1610 | return unless $sth; | |||
1611 | $sth->execute(@bind) || return; | |||
1612 | return $sth->fetchall_hashref($key_field); | |||
1613 | } | |||
1614 | ||||
1615 | sub selectcol_arrayref { | |||
1616 | my ($dbh, $stmt, $attr, @bind) = @_; | |||
1617 | my $sth = (ref $stmt) ? $stmt : $dbh->prepare($stmt, $attr); | |||
1618 | return unless $sth; | |||
1619 | $sth->execute(@bind) || return; | |||
1620 | my @columns = ($attr->{Columns}) ? @{$attr->{Columns}} : (1); | |||
1621 | my @values = (undef) x @columns; | |||
1622 | my $idx = 0; | |||
1623 | for (@columns) { | |||
1624 | $sth->bind_col($_, \$values[$idx++]) || return; | |||
1625 | } | |||
1626 | my @col; | |||
1627 | if (my $max = $attr->{MaxRows}) { | |||
1628 | push @col, @values while @col<$max && $sth->fetch; | |||
1629 | } | |||
1630 | else { | |||
1631 | push @col, @values while $sth->fetch; | |||
1632 | } | |||
1633 | return \@col; | |||
1634 | } | |||
1635 | ||||
1636 | sub prepare_cached { | |||
1637 | 33 | 0.00015 | 4.5e-6 | my ($dbh, $statement, $attr, $if_active) = @_; |
1638 | # Needs support at dbh level to clear cache before complaining about | |||
1639 | # active children. The XS template code does this. Drivers not using | |||
1640 | # the template must handle clearing the cache themselves. | |||
1641 | my $cache = $dbh->{CachedKids} ||= {}; | |||
1642 | my @attr_keys = ($attr) ? sort keys %$attr : (); | |||
1643 | my $key = ($attr) ? join("~~", $statement, @attr_keys, @{$attr}{@attr_keys}) : $statement; | |||
1644 | my $sth = $cache->{$key}; | |||
1645 | 1 | 2.0e-5 | 2.0e-5 | if ($sth) { |
1646 | return $sth unless $sth->FETCH('Active'); # spent 16µs making 1 call to DBI::common::FETCH | |||
1647 | Carp::carp("prepare_cached($statement) statement handle $sth still Active") | |||
1648 | unless ($if_active ||= 0); | |||
1649 | $sth->finish if $if_active <= 1; | |||
1650 | return $sth if $if_active <= 2; | |||
1651 | } | |||
1652 | 1 | 2.9e-5 | 2.9e-5 | $sth = $dbh->prepare($statement, $attr); # spent 4.60ms making 3 calls to DBI::db::prepare, avg 1.53ms/call |
1653 | $cache->{$key} = $sth if $sth; | |||
1654 | return $sth; | |||
1655 | } | |||
1656 | ||||
1657 | sub ping { | |||
1658 | 3 | 3.6e-5 | 1.2e-5 | my $dbh = shift; |
1659 | 1 | 1.4e-5 | 1.4e-5 | $dbh->_not_impl('ping'); # spent 54µs making 1 call to DBI::common::_not_impl |
1660 | # "0 but true" is a special kind of true 0 that is used here so | |||
1661 | # applications can check if the ping was a real ping or not | |||
1662 | ($dbh->FETCH('Active')) ? "0 but true" : 0; # spent 8µs making 1 call to DBI::common::FETCH | |||
1663 | } | |||
1664 | ||||
1665 | sub begin_work { | |||
1666 | my $dbh = shift; | |||
1667 | return $dbh->set_err($DBI::stderr, "Already in a transaction") | |||
1668 | unless $dbh->FETCH('AutoCommit'); | |||
1669 | $dbh->STORE('AutoCommit', 0); # will croak if driver doesn't support it | |||
1670 | $dbh->STORE('BegunWork', 1); # trigger post commit/rollback action | |||
1671 | return 1; | |||
1672 | } | |||
1673 | ||||
1674 | sub primary_key { | |||
1675 | my ($dbh, @args) = @_; | |||
1676 | my $sth = $dbh->primary_key_info(@args) or return; | |||
1677 | my ($row, @col); | |||
1678 | push @col, $row->[3] while ($row = $sth->fetch); | |||
1679 | Carp::croak("primary_key method not called in list context") | |||
1680 | unless wantarray; # leave us some elbow room | |||
1681 | return @col; | |||
1682 | } | |||
1683 | ||||
1684 | sub tables { | |||
1685 | my ($dbh, @args) = @_; | |||
1686 | my $sth = $dbh->table_info(@args[0,1,2,3,4]) or return; | |||
1687 | my $tables = $sth->fetchall_arrayref or return; | |||
1688 | my @tables; | |||
1689 | if ($dbh->get_info(29)) { # SQL_IDENTIFIER_QUOTE_CHAR | |||
1690 | @tables = map { $dbh->quote_identifier( @{$_}[0,1,2] ) } @$tables; | |||
1691 | } | |||
1692 | else { # temporary old style hack (yeach) | |||
1693 | @tables = map { | |||
1694 | my $name = $_->[2]; | |||
1695 | if ($_->[1]) { | |||
1696 | my $schema = $_->[1]; | |||
1697 | # a sad hack (mostly for Informix I recall) | |||
1698 | my $quote = ($schema eq uc($schema)) ? '' : '"'; | |||
1699 | $name = "$quote$schema$quote.$name" | |||
1700 | } | |||
1701 | $name; | |||
1702 | } @$tables; | |||
1703 | } | |||
1704 | return @tables; | |||
1705 | } | |||
1706 | ||||
1707 | sub type_info { # this should be sufficient for all drivers | |||
1708 | my ($dbh, $data_type) = @_; | |||
1709 | my $idx_hash; | |||
1710 | my $tia = $dbh->{dbi_type_info_row_cache}; | |||
1711 | if ($tia) { | |||
1712 | $idx_hash = $dbh->{dbi_type_info_idx_cache}; | |||
1713 | } | |||
1714 | else { | |||
1715 | my $temp = $dbh->type_info_all; | |||
1716 | return unless $temp && @$temp; | |||
1717 | # we cache here because type_info_all may be expensive to call | |||
1718 | # (and we take a copy so the following shift can't corrupt | |||
1719 | # the data that may be returned by future calls to type_info_all) | |||
1720 | $tia = $dbh->{dbi_type_info_row_cache} = [ @$temp ]; | |||
1721 | $idx_hash = $dbh->{dbi_type_info_idx_cache} = shift @$tia; | |||
1722 | } | |||
1723 | ||||
1724 | my $dt_idx = $idx_hash->{DATA_TYPE} || $idx_hash->{data_type}; | |||
1725 | Carp::croak("type_info_all returned non-standard DATA_TYPE index value ($dt_idx != 1)") | |||
1726 | if $dt_idx && $dt_idx != 1; | |||
1727 | ||||
1728 | # --- simple DATA_TYPE match filter | |||
1729 | my @ti; | |||
1730 | my @data_type_list = (ref $data_type) ? @$data_type : ($data_type); | |||
1731 | foreach $data_type (@data_type_list) { | |||
1732 | if (defined($data_type) && $data_type != DBI::SQL_ALL_TYPES()) { | |||
1733 | push @ti, grep { $_->[$dt_idx] == $data_type } @$tia; | |||
1734 | } | |||
1735 | else { # SQL_ALL_TYPES | |||
1736 | push @ti, @$tia; | |||
1737 | } | |||
1738 | last if @ti; # found at least one match | |||
1739 | } | |||
1740 | ||||
1741 | # --- format results into list of hash refs | |||
1742 | my $idx_fields = keys %$idx_hash; | |||
1743 | my @idx_names = map { uc($_) } keys %$idx_hash; | |||
1744 | my @idx_values = values %$idx_hash; | |||
1745 | Carp::croak "type_info_all result has $idx_fields keys but ".(@{$ti[0]})." fields" | |||
1746 | if @ti && @{$ti[0]} != $idx_fields; | |||
1747 | my @out = map { | |||
1748 | my %h; @h{@idx_names} = @{$_}[ @idx_values ]; \%h; | |||
1749 | } @ti; | |||
1750 | return $out[0] unless wantarray; | |||
1751 | return @out; | |||
1752 | } | |||
1753 | ||||
1754 | sub data_sources { | |||
1755 | my ($dbh, @other) = @_; | |||
1756 | my $drh = $dbh->{Driver}; # XXX proxy issues? | |||
1757 | return $drh->data_sources(@other); | |||
1758 | } | |||
1759 | ||||
1760 | } | |||
1761 | ||||
1762 | ||||
1763 | 1 | 2.0e-6 | 2.0e-6 | { package # hide from PAUSE |
1764 | DBD::_::st; # ====== STATEMENT ====== | |||
1765 | 2 | 7.0e-6 | 3.5e-6 | @DBD::_::st::ISA = qw(DBD::_::common); |
1766 | 3 | 0.00185 | 0.00062 | use strict; # spent 9µs making 1 call to strict::import |
1767 | ||||
1768 | sub bind_param { Carp::croak("Can't bind_param, not implement by driver") } | |||
1769 | ||||
1770 | # | |||
1771 | # ******************************************************** | |||
1772 | # | |||
1773 | # BEGIN ARRAY BINDING | |||
1774 | # | |||
1775 | # Array binding support for drivers which don't support | |||
1776 | # array binding, but have sufficient interfaces to fake it. | |||
1777 | # NOTE: mixing scalars and arrayrefs requires using bind_param_array | |||
1778 | # for *all* params...unless we modify bind_param for the default | |||
1779 | # case... | |||
1780 | # | |||
1781 | # 2002-Apr-10 D. Arnold | |||
1782 | ||||
1783 | sub bind_param_array { | |||
1784 | my $sth = shift; | |||
1785 | my ($p_id, $value_array, $attr) = @_; | |||
1786 | ||||
1787 | return $sth->set_err($DBI::stderr, "Value for parameter $p_id must be a scalar or an arrayref, not a ".ref($value_array)) | |||
1788 | if defined $value_array and ref $value_array and ref $value_array ne 'ARRAY'; | |||
1789 | ||||
1790 | return $sth->set_err($DBI::stderr, "Can't use named placeholder '$p_id' for non-driver supported bind_param_array") | |||
1791 | unless DBI::looks_like_number($p_id); # because we rely on execute(@ary) here | |||
1792 | ||||
1793 | return $sth->set_err($DBI::stderr, "Placeholder '$p_id' is out of range") | |||
1794 | if $p_id <= 0; # can't easily/reliably test for too big | |||
1795 | ||||
1796 | # get/create arrayref to hold params | |||
1797 | my $hash_of_arrays = $sth->{ParamArrays} ||= { }; | |||
1798 | ||||
1799 | # If the bind has attribs then we rely on the driver conforming to | |||
1800 | # the DBI spec in that a single bind_param() call with those attribs | |||
1801 | # makes them 'sticky' and apply to all later execute(@values) calls. | |||
1802 | # Since we only call bind_param() if we're given attribs then | |||
1803 | # applications using drivers that don't support bind_param can still | |||
1804 | # use bind_param_array() so long as they don't pass any attribs. | |||
1805 | ||||
1806 | $$hash_of_arrays{$p_id} = $value_array; | |||
1807 | return $sth->bind_param($p_id, undef, $attr) | |||
1808 | if $attr; | |||
1809 | 1; | |||
1810 | } | |||
1811 | ||||
1812 | sub bind_param_inout_array { | |||
1813 | my $sth = shift; | |||
1814 | # XXX not supported so we just call bind_param_array instead | |||
1815 | # and then return an error | |||
1816 | my ($p_num, $value_array, $attr) = @_; | |||
1817 | $sth->bind_param_array($p_num, $value_array, $attr); | |||
1818 | return $sth->set_err($DBI::stderr, "bind_param_inout_array not supported"); | |||
1819 | } | |||
1820 | ||||
1821 | sub bind_columns { | |||
1822 | my $sth = shift; | |||
1823 | my $fields = $sth->FETCH('NUM_OF_FIELDS') || 0; | |||
1824 | if ($fields <= 0 && !$sth->{Active}) { | |||
1825 | return $sth->set_err($DBI::stderr, "Statement has no result columns to bind" | |||
1826 | ." (perhaps you need to successfully call execute first)"); | |||
1827 | } | |||
1828 | # Backwards compatibility for old-style call with attribute hash | |||
1829 | # ref as first arg. Skip arg if undef or a hash ref. | |||
1830 | my $attr; | |||
1831 | $attr = shift if !defined $_[0] or ref($_[0]) eq 'HASH'; | |||
1832 | ||||
1833 | my $idx = 0; | |||
1834 | $sth->bind_col(++$idx, shift, $attr) or return | |||
1835 | while (@_ and $idx < $fields); | |||
1836 | ||||
1837 | return $sth->set_err($DBI::stderr, "bind_columns called with ".($idx+@_)." values but $fields are needed") | |||
1838 | if @_ or $idx != $fields; | |||
1839 | ||||
1840 | return 1; | |||
1841 | } | |||
1842 | ||||
1843 | sub execute_array { | |||
1844 | my $sth = shift; | |||
1845 | my ($attr, @array_of_arrays) = @_; | |||
1846 | my $NUM_OF_PARAMS = $sth->FETCH('NUM_OF_PARAMS'); # may be undef at this point | |||
1847 | ||||
1848 | # get tuple status array or hash attribute | |||
1849 | my $tuple_sts = $attr->{ArrayTupleStatus}; | |||
1850 | return $sth->set_err($DBI::stderr, "ArrayTupleStatus attribute must be an arrayref") | |||
1851 | if $tuple_sts and ref $tuple_sts ne 'ARRAY'; | |||
1852 | ||||
1853 | # bind all supplied arrays | |||
1854 | if (@array_of_arrays) { | |||
1855 | $sth->{ParamArrays} = { }; # clear out old params | |||
1856 | return $sth->set_err($DBI::stderr, | |||
1857 | @array_of_arrays." bind values supplied but $NUM_OF_PARAMS expected") | |||
1858 | if defined ($NUM_OF_PARAMS) && @array_of_arrays != $NUM_OF_PARAMS; | |||
1859 | $sth->bind_param_array($_, $array_of_arrays[$_-1]) or return | |||
1860 | foreach (1..@array_of_arrays); | |||
1861 | } | |||
1862 | ||||
1863 | my $fetch_tuple_sub; | |||
1864 | ||||
1865 | if ($fetch_tuple_sub = $attr->{ArrayTupleFetch}) { # fetch on demand | |||
1866 | ||||
1867 | return $sth->set_err($DBI::stderr, | |||
1868 | "Can't use both ArrayTupleFetch and explicit bind values") | |||
1869 | if @array_of_arrays; # previous bind_param_array calls will simply be ignored | |||
1870 | ||||
1871 | if (UNIVERSAL::isa($fetch_tuple_sub,'DBI::st')) { | |||
1872 | my $fetch_sth = $fetch_tuple_sub; | |||
1873 | return $sth->set_err($DBI::stderr, | |||
1874 | "ArrayTupleFetch sth is not Active, need to execute() it first") | |||
1875 | unless $fetch_sth->{Active}; | |||
1876 | # check column count match to give more friendly message | |||
1877 | my $NUM_OF_FIELDS = $fetch_sth->{NUM_OF_FIELDS}; | |||
1878 | return $sth->set_err($DBI::stderr, | |||
1879 | "$NUM_OF_FIELDS columns from ArrayTupleFetch sth but $NUM_OF_PARAMS expected") | |||
1880 | if defined($NUM_OF_FIELDS) && defined($NUM_OF_PARAMS) | |||
1881 | && $NUM_OF_FIELDS != $NUM_OF_PARAMS; | |||
1882 | $fetch_tuple_sub = sub { $fetch_sth->fetchrow_arrayref }; | |||
1883 | } | |||
1884 | elsif (!UNIVERSAL::isa($fetch_tuple_sub,'CODE')) { | |||
1885 | return $sth->set_err($DBI::stderr, "ArrayTupleFetch '$fetch_tuple_sub' is not a code ref or statement handle"); | |||
1886 | } | |||
1887 | ||||
1888 | } | |||
1889 | else { | |||
1890 | my $NUM_OF_PARAMS_given = keys %{ $sth->{ParamArrays} || {} }; | |||
1891 | return $sth->set_err($DBI::stderr, | |||
1892 | "$NUM_OF_PARAMS_given bind values supplied but $NUM_OF_PARAMS expected") | |||
1893 | if defined($NUM_OF_PARAMS) && $NUM_OF_PARAMS != $NUM_OF_PARAMS_given; | |||
1894 | ||||
1895 | # get the length of a bound array | |||
1896 | my $maxlen; | |||
1897 | my %hash_of_arrays = %{$sth->{ParamArrays}}; | |||
1898 | foreach (keys(%hash_of_arrays)) { | |||
1899 | my $ary = $hash_of_arrays{$_}; | |||
1900 | next unless ref $ary eq 'ARRAY'; | |||
1901 | $maxlen = @$ary if !$maxlen || @$ary > $maxlen; | |||
1902 | } | |||
1903 | # if there are no arrays then execute scalars once | |||
1904 | $maxlen = 1 unless defined $maxlen; | |||
1905 | my @bind_ids = 1..keys(%hash_of_arrays); | |||
1906 | ||||
1907 | my $tuple_idx = 0; | |||
1908 | $fetch_tuple_sub = sub { | |||
1909 | return if $tuple_idx >= $maxlen; | |||
1910 | my @tuple = map { | |||
1911 | my $a = $hash_of_arrays{$_}; | |||
1912 | ref($a) ? $a->[$tuple_idx] : $a | |||
1913 | } @bind_ids; | |||
1914 | ++$tuple_idx; | |||
1915 | return \@tuple; | |||
1916 | }; | |||
1917 | } | |||
1918 | # pass thru the callers scalar or list context | |||
1919 | return $sth->execute_for_fetch($fetch_tuple_sub, $tuple_sts); | |||
1920 | } | |||
1921 | ||||
1922 | sub execute_for_fetch { | |||
1923 | my ($sth, $fetch_tuple_sub, $tuple_status) = @_; | |||
1924 | # start with empty status array | |||
1925 | ($tuple_status) ? @$tuple_status = () : $tuple_status = []; | |||
1926 | ||||
1927 | my $rc_total = 0; | |||
1928 | my $err_count; | |||
1929 | while ( my $tuple = &$fetch_tuple_sub() ) { | |||
1930 | if ( my $rc = $sth->execute(@$tuple) ) { | |||
1931 | push @$tuple_status, $rc; | |||
1932 | $rc_total = ($rc >= 0 && $rc_total >= 0) ? $rc_total + $rc : -1; | |||
1933 | } | |||
1934 | else { | |||
1935 | $err_count++; | |||
1936 | push @$tuple_status, [ $sth->err, $sth->errstr, $sth->state ]; | |||
1937 | # XXX drivers implementing execute_for_fetch could opt to "last;" here | |||
1938 | # if they know the error code means no further executes will work. | |||
1939 | } | |||
1940 | } | |||
1941 | my $tuples = @$tuple_status; | |||
1942 | return $sth->set_err($DBI::stderr, "executing $tuples generated $err_count errors") | |||
1943 | if $err_count; | |||
1944 | $tuples ||= "0E0"; | |||
1945 | return $tuples unless wantarray; | |||
1946 | return ($tuples, $rc_total); | |||
1947 | } | |||
1948 | ||||
1949 | ||||
1950 | sub fetchall_arrayref { # ALSO IN Driver.xst | |||
1951 | my ($sth, $slice, $max_rows) = @_; | |||
1952 | ||||
1953 | # when batch fetching with $max_rows were very likely to try to | |||
1954 | # fetch the 'next batch' after the previous batch returned | |||
1955 | # <=$max_rows. So don't treat that as an error. | |||
1956 | return undef if $max_rows and not $sth->FETCH('Active'); | |||
1957 | ||||
1958 | my $mode = ref($slice) || 'ARRAY'; | |||
1959 | my @rows; | |||
1960 | my $row; | |||
1961 | if ($mode eq 'ARRAY') { | |||
1962 | # we copy the array here because fetch (currently) always | |||
1963 | # returns the same array ref. XXX | |||
1964 | if ($slice && @$slice) { | |||
1965 | $max_rows = -1 unless defined $max_rows; | |||
1966 | push @rows, [ @{$row}[ @$slice] ] | |||
1967 | while($max_rows-- and $row = $sth->fetch); | |||
1968 | } | |||
1969 | elsif (defined $max_rows) { | |||
1970 | push @rows, [ @$row ] | |||
1971 | while($max_rows-- and $row = $sth->fetch); | |||
1972 | } | |||
1973 | else { | |||
1974 | push @rows, [ @$row ] while($row = $sth->fetch); | |||
1975 | } | |||
1976 | } | |||
1977 | elsif ($mode eq 'HASH') { | |||
1978 | $max_rows = -1 unless defined $max_rows; | |||
1979 | if (keys %$slice) { | |||
1980 | my @o_keys = keys %$slice; | |||
1981 | my @i_keys = map { lc } keys %$slice; | |||
1982 | # XXX this could be made faster by pre-binding a local hash | |||
1983 | # using bind_columns and then copying it per row | |||
1984 | while ($max_rows-- and $row = $sth->fetchrow_hashref('NAME_lc')) { | |||
1985 | my %hash; | |||
1986 | @hash{@o_keys} = @{$row}{@i_keys}; | |||
1987 | push @rows, \%hash; | |||
1988 | } | |||
1989 | } | |||
1990 | else { | |||
1991 | # XXX assumes new ref each fetchhash | |||
1992 | push @rows, $row | |||
1993 | while ($max_rows-- and $row = $sth->fetchrow_hashref()); | |||
1994 | } | |||
1995 | } | |||
1996 | else { Carp::croak("fetchall_arrayref($mode) invalid") } | |||
1997 | return \@rows; | |||
1998 | } | |||
1999 | ||||
2000 | sub fetchall_hashref { | |||
2001 | my ($sth, $key_field) = @_; | |||
2002 | ||||
2003 | my $hash_key_name = $sth->{FetchHashKeyName} || 'NAME'; | |||
2004 | my $names_hash = $sth->FETCH("${hash_key_name}_hash"); | |||
2005 | my @key_fields = (ref $key_field) ? @$key_field : ($key_field); | |||
2006 | my @key_indexes; | |||
2007 | my $num_of_fields = $sth->FETCH('NUM_OF_FIELDS'); | |||
2008 | foreach (@key_fields) { | |||
2009 | my $index = $names_hash->{$_}; # perl index not column | |||
2010 | $index = $_ - 1 if !defined $index && DBI::looks_like_number($_) && $_>=1 && $_ <= $num_of_fields; | |||
2011 | return $sth->set_err($DBI::stderr, "Field '$_' does not exist (not one of @{[keys %$names_hash]})") | |||
2012 | unless defined $index; | |||
2013 | push @key_indexes, $index; | |||
2014 | } | |||
2015 | my $rows = {}; | |||
2016 | my $NAME = $sth->FETCH($hash_key_name); | |||
2017 | my @row = (undef) x $num_of_fields; | |||
2018 | $sth->bind_columns(\(@row)); | |||
2019 | while ($sth->fetch) { | |||
2020 | my $ref = $rows; | |||
2021 | $ref = $ref->{$row[$_]} ||= {} for @key_indexes; | |||
2022 | @{$ref}{@$NAME} = @row; | |||
2023 | } | |||
2024 | return $rows; | |||
2025 | } | |||
2026 | ||||
2027 | *dump_results = \&DBI::dump_results; | |||
2028 | ||||
2029 | sub blob_copy_to_file { # returns length or undef on error | |||
2030 | my($self, $field, $filename_or_handleref, $blocksize) = @_; | |||
2031 | my $fh = $filename_or_handleref; | |||
2032 | my($len, $buf) = (0, ""); | |||
2033 | $blocksize ||= 512; # not too ambitious | |||
2034 | local(*FH); | |||
2035 | unless(ref $fh) { | |||
2036 | open(FH, ">$fh") || return undef; | |||
2037 | $fh = \*FH; | |||
2038 | } | |||
2039 | while(defined($self->blob_read($field, $len, $blocksize, \$buf))) { | |||
2040 | print $fh $buf; | |||
2041 | $len += length $buf; | |||
2042 | } | |||
2043 | close(FH); | |||
2044 | $len; | |||
2045 | } | |||
2046 | ||||
2047 | sub more_results { | |||
2048 | shift->{syb_more_results}; # handy grandfathering | |||
2049 | } | |||
2050 | ||||
2051 | } | |||
2052 | ||||
2053 | 4 | 7.0e-6 | 1.7e-6 | unless ($DBI::PurePerl) { # See install_driver |
2054 | 1 | 7.0e-6 | 7.0e-6 | { @DBD::_mem::dr::ISA = qw(DBD::_mem::common); } |
2055 | 1 | 5.0e-6 | 5.0e-6 | { @DBD::_mem::db::ISA = qw(DBD::_mem::common); } |
2056 | 1 | 5.0e-6 | 5.0e-6 | { @DBD::_mem::st::ISA = qw(DBD::_mem::common); } |
2057 | # DBD::_mem::common::DESTROY is implemented in DBI.xs | |||
2058 | } | |||
2059 | ||||
2060 | 1 | 0.00016 | 0.00016 | 1; |
2061 | __END__ | |||
2062 | ||||
2063 | =head1 DESCRIPTION | |||
2064 | ||||
2065 | The DBI is a database access module for the Perl programming language. It defines | |||
2066 | a set of methods, variables, and conventions that provide a consistent | |||
2067 | database interface, independent of the actual database being used. | |||
2068 | ||||
2069 | It is important to remember that the DBI is just an interface. | |||
2070 | The DBI is a layer | |||
2071 | of "glue" between an application and one or more database I<driver> | |||
2072 | modules. It is the driver modules which do most of the real work. The DBI | |||
2073 | provides a standard interface and framework for the drivers to operate | |||
2074 | within. | |||
2075 | ||||
2076 | ||||
2077 | =head2 Architecture of a DBI Application | |||
2078 | ||||
2079 | |<- Scope of DBI ->| | |||
2080 | .-. .--------------. .-------------. | |||
2081 | .-------. | |---| XYZ Driver |---| XYZ Engine | | |||
2082 | | Perl | | | `--------------' `-------------' | |||
2083 | | script| |A| |D| .--------------. .-------------. | |||
2084 | | using |--|P|--|B|---|Oracle Driver |---|Oracle Engine| | |||
2085 | | DBI | |I| |I| `--------------' `-------------' | |||
2086 | | API | | |... | |||
2087 | |methods| | |... Other drivers | |||
2088 | `-------' | |... | |||
2089 | `-' | |||
2090 | ||||
2091 | The API, or Application Programming Interface, defines the | |||
2092 | call interface and variables for Perl scripts to use. The API | |||
2093 | is implemented by the Perl DBI extension. | |||
2094 | ||||
2095 | The DBI "dispatches" the method calls to the appropriate driver for | |||
2096 | actual execution. The DBI is also responsible for the dynamic loading | |||
2097 | of drivers, error checking and handling, providing default | |||
2098 | implementations for methods, and many other non-database specific duties. | |||
2099 | ||||
2100 | Each driver | |||
2101 | contains implementations of the DBI methods using the | |||
2102 | private interface functions of the corresponding database engine. Only authors | |||
2103 | of sophisticated/multi-database applications or generic library | |||
2104 | functions need be concerned with drivers. | |||
2105 | ||||
2106 | =head2 Notation and Conventions | |||
2107 | ||||
2108 | The following conventions are used in this document: | |||
2109 | ||||
2110 | $dbh Database handle object | |||
2111 | $sth Statement handle object | |||
2112 | $drh Driver handle object (rarely seen or used in applications) | |||
2113 | $h Any of the handle types above ($dbh, $sth, or $drh) | |||
2114 | $rc General Return Code (boolean: true=ok, false=error) | |||
2115 | $rv General Return Value (typically an integer) | |||
2116 | @ary List of values returned from the database, typically a row of data | |||
2117 | $rows Number of rows processed (if available, else -1) | |||
2118 | $fh A filehandle | |||
2119 | undef NULL values are represented by undefined values in Perl | |||
2120 | \%attr Reference to a hash of attribute values passed to methods | |||
2121 | ||||
2122 | Note that Perl will automatically destroy database and statement handle objects | |||
2123 | if all references to them are deleted. | |||
2124 | ||||
2125 | ||||
2126 | =head2 Outline Usage | |||
2127 | ||||
2128 | To use DBI, | |||
2129 | first you need to load the DBI module: | |||
2130 | ||||
2131 | use DBI; | |||
2132 | use strict; | |||
2133 | ||||
2134 | (The C<use strict;> isn't required but is strongly recommended.) | |||
2135 | ||||
2136 | Then you need to L</connect> to your data source and get a I<handle> for that | |||
2137 | connection: | |||
2138 | ||||
2139 | $dbh = DBI->connect($dsn, $user, $password, | |||
2140 | { RaiseError => 1, AutoCommit => 0 }); | |||
2141 | ||||
2142 | Since connecting can be expensive, you generally just connect at the | |||
2143 | start of your program and disconnect at the end. | |||
2144 | ||||
2145 | Explicitly defining the required C<AutoCommit> behaviour is strongly | |||
2146 | recommended and may become mandatory in a later version. This | |||
2147 | determines whether changes are automatically committed to the | |||
2148 | database when executed, or need to be explicitly committed later. | |||
2149 | ||||
2150 | The DBI allows an application to "prepare" statements for later | |||
2151 | execution. A prepared statement is identified by a statement handle | |||
2152 | held in a Perl variable. | |||
2153 | We'll call the Perl variable C<$sth> in our examples. | |||
2154 | ||||
2155 | The typical method call sequence for a C<SELECT> statement is: | |||
2156 | ||||
2157 | prepare, | |||
2158 | execute, fetch, fetch, ... | |||
2159 | execute, fetch, fetch, ... | |||
2160 | execute, fetch, fetch, ... | |||
2161 | ||||
2162 | for example: | |||
2163 | ||||
2164 | $sth = $dbh->prepare("SELECT foo, bar FROM table WHERE baz=?"); | |||
2165 | ||||
2166 | $sth->execute( $baz ); | |||
2167 | ||||
2168 | while ( @row = $sth->fetchrow_array ) { | |||
2169 | print "@row\n"; | |||
2170 | } | |||
2171 | ||||
2172 | The typical method call sequence for a I<non>-C<SELECT> statement is: | |||
2173 | ||||
2174 | prepare, | |||
2175 | execute, | |||
2176 | execute, | |||
2177 | execute. | |||
2178 | ||||
2179 | for example: | |||
2180 | ||||
2181 | $sth = $dbh->prepare("INSERT INTO table(foo,bar,baz) VALUES (?,?,?)"); | |||
2182 | ||||
2183 | while(<CSV>) { | |||
2184 | chomp; | |||
2185 | my ($foo,$bar,$baz) = split /,/; | |||
2186 | $sth->execute( $foo, $bar, $baz ); | |||
2187 | } | |||
2188 | ||||
2189 | The C<do()> method can be used for non repeated I<non>-C<SELECT> statement | |||
2190 | (or with drivers that don't support placeholders): | |||
2191 | ||||
2192 | $rows_affected = $dbh->do("UPDATE your_table SET foo = foo + 1"); | |||
2193 | ||||
2194 | To commit your changes to the database (when L</AutoCommit> is off): | |||
2195 | ||||
2196 | $dbh->commit; # or call $dbh->rollback; to undo changes | |||
2197 | ||||
2198 | Finally, when you have finished working with the data source, you should | |||
2199 | L</disconnect> from it: | |||
2200 | ||||
2201 | $dbh->disconnect; | |||
2202 | ||||
2203 | ||||
2204 | =head2 General Interface Rules & Caveats | |||
2205 | ||||
2206 | The DBI does not have a concept of a "current session". Every session | |||
2207 | has a handle object (i.e., a C<$dbh>) returned from the C<connect> method. | |||
2208 | That handle object is used to invoke database related methods. | |||
2209 | ||||
2210 | Most data is returned to the Perl script as strings. (Null values are | |||
2211 | returned as C<undef>.) This allows arbitrary precision numeric data to be | |||
2212 | handled without loss of accuracy. Beware that Perl may not preserve | |||
2213 | the same accuracy when the string is used as a number. | |||
2214 | ||||
2215 | Dates and times are returned as character strings in the current | |||
2216 | default format of the corresponding database engine. Time zone effects | |||
2217 | are database/driver dependent. | |||
2218 | ||||
2219 | Perl supports binary data in Perl strings, and the DBI will pass binary | |||
2220 | data to and from the driver without change. It is up to the driver | |||
2221 | implementors to decide how they wish to handle such binary data. | |||
2222 | ||||
2223 | Perl supports two kinds of strings: unicode (utf8 internally) and non-unicode | |||
2224 | (defaults to iso-8859-1 if forced to assume an encoding). Drivers should | |||
2225 | accept both kinds of strings and, if required, convert them to the character | |||
2226 | set of the database being used. Similarly, when fetching from the database | |||
2227 | character data that isn't iso-8859-1 the driver should convert it into utf8. | |||
2228 | ||||
2229 | Multiple SQL statements may not be combined in a single statement | |||
2230 | handle (C<$sth>), although some databases and drivers do support this | |||
2231 | (notably Sybase and SQL Server). | |||
2232 | ||||
2233 | Non-sequential record reads are not supported in this version of the DBI. | |||
2234 | In other words, records can only be fetched in the order that the | |||
2235 | database returned them, and once fetched they are forgotten. | |||
2236 | ||||
2237 | Positioned updates and deletes are not directly supported by the DBI. | |||
2238 | See the description of the C<CursorName> attribute for an alternative. | |||
2239 | ||||
2240 | Individual driver implementors are free to provide any private | |||
2241 | functions and/or handle attributes that they feel are useful. | |||
2242 | Private driver functions can be invoked using the DBI C<func()> method. | |||
2243 | Private driver attributes are accessed just like standard attributes. | |||
2244 | ||||
2245 | Many methods have an optional C<\%attr> parameter which can be used to | |||
2246 | pass information to the driver implementing the method. Except where | |||
2247 | specifically documented, the C<\%attr> parameter can only be used to pass | |||
2248 | driver specific hints. In general, you can ignore C<\%attr> parameters | |||
2249 | or pass it as C<undef>. | |||
2250 | ||||
2251 | ||||
2252 | =head2 Naming Conventions and Name Space | |||
2253 | ||||
2254 | The DBI package and all packages below it (C<DBI::*>) are reserved for | |||
2255 | use by the DBI. Extensions and related modules use the C<DBIx::> | |||
2256 | namespace (see L<http://www.perl.com/CPAN/modules/by-module/DBIx/>). | |||
2257 | Package names beginning with C<DBD::> are reserved for use | |||
2258 | by DBI database drivers. All environment variables used by the DBI | |||
2259 | or by individual DBDs begin with "C<DBI_>" or "C<DBD_>". | |||
2260 | ||||
2261 | The letter case used for attribute names is significant and plays an | |||
2262 | important part in the portability of DBI scripts. The case of the | |||
2263 | attribute name is used to signify who defined the meaning of that name | |||
2264 | and its values. | |||
2265 | ||||
2266 | Case of name Has a meaning defined by | |||
2267 | ------------ ------------------------ | |||
2268 | UPPER_CASE Standards, e.g., X/Open, ISO SQL92 etc (portable) | |||
2269 | MixedCase DBI API (portable), underscores are not used. | |||
2270 | lower_case Driver or database engine specific (non-portable) | |||
2271 | ||||
2272 | It is of the utmost importance that Driver developers only use | |||
2273 | lowercase attribute names when defining private attributes. Private | |||
2274 | attribute names must be prefixed with the driver name or suitable | |||
2275 | abbreviation (e.g., "C<ora_>" for Oracle, "C<ing_>" for Ingres, etc). | |||
2276 | ||||
2277 | ||||
2278 | =head2 SQL - A Query Language | |||
2279 | ||||
2280 | Most DBI drivers require applications to use a dialect of SQL | |||
2281 | (Structured Query Language) to interact with the database engine. | |||
2282 | The L</"Standards Reference Information"> section provides links | |||
2283 | to useful information about SQL. | |||
2284 | ||||
2285 | The DBI itself does not mandate or require any particular language to | |||
2286 | be used; it is language independent. In ODBC terms, the DBI is in | |||
2287 | "pass-thru" mode, although individual drivers might not be. The only requirement | |||
2288 | is that queries and other statements must be expressed as a single | |||
2289 | string of characters passed as the first argument to the L</prepare> or | |||
2290 | L</do> methods. | |||
2291 | ||||
2292 | For an interesting diversion on the I<real> history of RDBMS and SQL, | |||
2293 | from the people who made it happen, see: | |||
2294 | ||||
2295 | http://ftp.digital.com/pub/DEC/SRC/technical-notes/SRC-1997-018-html/sqlr95.html | |||
2296 | ||||
2297 | Follow the "Full Contents" then "Intergalactic dataspeak" links for the | |||
2298 | SQL history. | |||
2299 | ||||
2300 | =head2 Placeholders and Bind Values | |||
2301 | ||||
2302 | Some drivers support placeholders and bind values. | |||
2303 | I<Placeholders>, also called parameter markers, are used to indicate | |||
2304 | values in a database statement that will be supplied later, | |||
2305 | before the prepared statement is executed. For example, an application | |||
2306 | might use the following to insert a row of data into the SALES table: | |||
2307 | ||||
2308 | INSERT INTO sales (product_code, qty, price) VALUES (?, ?, ?) | |||
2309 | ||||
2310 | or the following, to select the description for a product: | |||
2311 | ||||
2312 | SELECT description FROM products WHERE product_code = ? | |||
2313 | ||||
2314 | The C<?> characters are the placeholders. The association of actual | |||
2315 | values with placeholders is known as I<binding>, and the values are | |||
2316 | referred to as I<bind values>. | |||
2317 | ||||
2318 | Note that the C<?> is not enclosed in quotation marks, even when the | |||
2319 | placeholder represents a string. Some drivers also allow placeholders | |||
2320 | like C<:>I<name> and C<:>I<n> (e.g., C<:1>, C<:2>, and so on) | |||
2321 | in addition to C<?>, but their use is not portable. | |||
2322 | ||||
2323 | With most drivers, placeholders can't be used for any element of a | |||
2324 | statement that would prevent the database server from validating the | |||
2325 | statement and creating a query execution plan for it. For example: | |||
2326 | ||||
2327 | "SELECT name, age FROM ?" # wrong (will probably fail) | |||
2328 | "SELECT name, ? FROM people" # wrong (but may not 'fail') | |||
2329 | ||||
2330 | Also, placeholders can only represent single scalar values. | |||
2331 | For example, the following | |||
2332 | statement won't work as expected for more than one value: | |||
2333 | ||||
2334 | "SELECT name, age FROM people WHERE name IN (?)" # wrong | |||
2335 | "SELECT name, age FROM people WHERE name IN (?,?)" # two names | |||
2336 | ||||
2337 | When using placeholders with the SQL C<LIKE> qualifier, you must | |||
2338 | remember that the placeholder substitutes for the whole string. | |||
2339 | So you should use "C<... LIKE ? ...>" and include any wildcard | |||
2340 | characters in the value that you bind to the placeholder. | |||
2341 | ||||
2342 | B<NULL Values> | |||
2343 | ||||
2344 | Undefined values, or C<undef>, are used to indicate NULL values. | |||
2345 | You can insert and update columns with a NULL value as you would a | |||
2346 | non-NULL value. These examples insert and update the column | |||
2347 | C<age> with a NULL value: | |||
2348 | ||||
2349 | $sth = $dbh->prepare(qq{ | |||
2350 | INSERT INTO people (fullname, age) VALUES (?, ?) | |||
2351 | }); | |||
2352 | $sth->execute("Joe Bloggs", undef); | |||
2353 | ||||
2354 | $sth = $dbh->prepare(qq{ | |||
2355 | UPDATE people SET age = ? WHERE fullname = ? | |||
2356 | }); | |||
2357 | $sth->execute(undef, "Joe Bloggs"); | |||
2358 | ||||
2359 | However, care must be taken when trying to use NULL values in a | |||
2360 | C<WHERE> clause. Consider: | |||
2361 | ||||
2362 | SELECT fullname FROM people WHERE age = ? | |||
2363 | ||||
2364 | Binding an C<undef> (NULL) to the placeholder will I<not> select rows | |||
2365 | which have a NULL C<age>! At least for database engines that | |||
2366 | conform to the SQL standard. Refer to the SQL manual for your database | |||
2367 | engine or any SQL book for the reasons for this. To explicitly select | |||
2368 | NULLs you have to say "C<WHERE age IS NULL>". | |||
2369 | ||||
2370 | A common issue is to have a code fragment handle a value that could be | |||
2371 | either C<defined> or C<undef> (non-NULL or NULL) at runtime. | |||
2372 | A simple technique is to prepare the appropriate statement as needed, | |||
2373 | and substitute the placeholder for non-NULL cases: | |||
2374 | ||||
2375 | $sql_clause = defined $age? "age = ?" : "age IS NULL"; | |||
2376 | $sth = $dbh->prepare(qq{ | |||
2377 | SELECT fullname FROM people WHERE $sql_clause | |||
2378 | }); | |||
2379 | $sth->execute(defined $age ? $age : ()); | |||
2380 | ||||
2381 | The following technique illustrates qualifying a C<WHERE> clause with | |||
2382 | several columns, whose associated values (C<defined> or C<undef>) are | |||
2383 | in a hash %h: | |||
2384 | ||||
2385 | for my $col ("age", "phone", "email") { | |||
2386 | if (defined $h{$col}) { | |||
2387 | push @sql_qual, "$col = ?"; | |||
2388 | push @sql_bind, $h{$col}; | |||
2389 | } | |||
2390 | else { | |||
2391 | push @sql_qual, "$col IS NULL"; | |||
2392 | } | |||
2393 | } | |||
2394 | $sql_clause = join(" AND ", @sql_qual); | |||
2395 | $sth = $dbh->prepare(qq{ | |||
2396 | SELECT fullname FROM people WHERE $sql_clause | |||
2397 | }); | |||
2398 | $sth->execute(@sql_bind); | |||
2399 | ||||
2400 | The techniques above call prepare for the SQL statement with each call to | |||
2401 | execute. Because calls to prepare() can be expensive, performance | |||
2402 | can suffer when an application iterates many times over statements | |||
2403 | like the above. | |||
2404 | ||||
2405 | A better solution is a single C<WHERE> clause that supports both | |||
2406 | NULL and non-NULL comparisons. Its SQL statement would need to be | |||
2407 | prepared only once for all cases, thus improving performance. | |||
2408 | Several examples of C<WHERE> clauses that support this are presented | |||
2409 | below. But each example lacks portability, robustness, or simplicity. | |||
2410 | Whether an example is supported on your database engine depends on | |||
2411 | what SQL extensions it provides, and where it supports the C<?> | |||
2412 | placeholder in a statement. | |||
2413 | ||||
2414 | 0) age = ? | |||
2415 | 1) NVL(age, xx) = NVL(?, xx) | |||
2416 | 2) ISNULL(age, xx) = ISNULL(?, xx) | |||
2417 | 3) DECODE(age, ?, 1, 0) = 1 | |||
2418 | 4) age = ? OR (age IS NULL AND ? IS NULL) | |||
2419 | 5) age = ? OR (age IS NULL AND SP_ISNULL(?) = 1) | |||
2420 | 6) age = ? OR (age IS NULL AND ? = 1) | |||
2421 | ||||
2422 | Statements formed with the above C<WHERE> clauses require execute | |||
2423 | statements as follows. The arguments are required, whether their | |||
2424 | values are C<defined> or C<undef>. | |||
2425 | ||||
2426 | 0,1,2,3) $sth->execute($age); | |||
2427 | 4,5) $sth->execute($age, $age); | |||
2428 | 6) $sth->execute($age, defined($age) ? 0 : 1); | |||
2429 | ||||
2430 | Example 0 should not work (as mentioned earlier), but may work on | |||
2431 | a few database engines anyway (e.g. Sybase). Example 0 is part | |||
2432 | of examples 4, 5, and 6, so if example 0 works, these other | |||
2433 | examples may work, even if the engine does not properly support | |||
2434 | the right hand side of the C<OR> expression. | |||
2435 | ||||
2436 | Examples 1 and 2 are not robust: they require that you provide a | |||
2437 | valid column value xx (e.g. '~') which is not present in any row. | |||
2438 | That means you must have some notion of what data won't be stored | |||
2439 | in the column, and expect clients to adhere to that. | |||
2440 | ||||
2441 | Example 5 requires that you provide a stored procedure (SP_ISNULL | |||
2442 | in this example) that acts as a function: it checks whether a value | |||
2443 | is null, and returns 1 if it is, or 0 if not. | |||
2444 | ||||
2445 | Example 6, the least simple, is probably the most portable, i.e., it | |||
2446 | should work with with most, if not all, database engines. | |||
2447 | ||||
2448 | Here is a table that indicates which examples above are known to | |||
2449 | work on various database engines: | |||
2450 | ||||
2451 | -----Examples------ | |||
2452 | 0 1 2 3 4 5 6 | |||
2453 | - - - - - - - | |||
2454 | Oracle 9 N Y N Y Y ? Y | |||
2455 | Informix IDS 9 N N N Y N Y Y | |||
2456 | MS SQL N N Y N Y ? Y | |||
2457 | Sybase Y N N N N N Y | |||
2458 | AnyData,DBM,CSV Y N N N Y Y* Y | |||
2459 | SQLite 3.3 N N N N Y N N | |||
2460 | ||||
2461 | * Works only because Example 0 works. | |||
2462 | ||||
2463 | DBI provides a sample perl script that will test the examples above | |||
2464 | on your database engine and tell you which ones work. It is located | |||
2465 | in the F<ex/> subdirectory of the DBI source distribution, or here: | |||
2466 | L<http://svn.perl.org/modules/dbi/trunk/ex/perl_dbi_nulls_test.pl> | |||
2467 | Please use the script to help us fill-in and maintain this table. | |||
2468 | ||||
2469 | B<Performance> | |||
2470 | ||||
2471 | Without using placeholders, the insert statement shown previously would have to | |||
2472 | contain the literal values to be inserted and would have to be | |||
2473 | re-prepared and re-executed for each row. With placeholders, the insert | |||
2474 | statement only needs to be prepared once. The bind values for each row | |||
2475 | can be given to the C<execute> method each time it's called. By avoiding | |||
2476 | the need to re-prepare the statement for each row, the application | |||
2477 | typically runs many times faster. Here's an example: | |||
2478 | ||||
2479 | my $sth = $dbh->prepare(q{ | |||
2480 | INSERT INTO sales (product_code, qty, price) VALUES (?, ?, ?) | |||
2481 | }) or die $dbh->errstr; | |||
2482 | while (<>) { | |||
2483 | chomp; | |||
2484 | my ($product_code, $qty, $price) = split /,/; | |||
2485 | $sth->execute($product_code, $qty, $price) or die $dbh->errstr; | |||
2486 | } | |||
2487 | $dbh->commit or die $dbh->errstr; | |||
2488 | ||||
2489 | See L</execute> and L</bind_param> for more details. | |||
2490 | ||||
2491 | The C<q{...}> style quoting used in this example avoids clashing with | |||
2492 | quotes that may be used in the SQL statement. Use the double-quote like | |||
2493 | C<qq{...}> operator if you want to interpolate variables into the string. | |||
2494 | See L<perlop/"Quote and Quote-like Operators"> for more details. | |||
2495 | ||||
2496 | See also the L</bind_columns> method, which is used to associate Perl | |||
2497 | variables with the output columns of a C<SELECT> statement. | |||
2498 | ||||
2499 | =head1 THE DBI PACKAGE AND CLASS | |||
2500 | ||||
2501 | In this section, we cover the DBI class methods, utility functions, | |||
2502 | and the dynamic attributes associated with generic DBI handles. | |||
2503 | ||||
2504 | =head2 DBI Constants | |||
2505 | ||||
2506 | Constants representing the values of the SQL standard types can be | |||
2507 | imported individually by name, or all together by importing the | |||
2508 | special C<:sql_types> tag. | |||
2509 | ||||
2510 | The names and values of all the defined SQL standard types can be | |||
2511 | produced like this: | |||
2512 | ||||
2513 | foreach (@{ $DBI::EXPORT_TAGS{sql_types} }) { | |||
2514 | printf "%s=%d\n", $_, &{"DBI::$_"}; | |||
2515 | } | |||
2516 | ||||
2517 | These constants are defined by SQL/CLI, ODBC or both. | |||
2518 | C<SQL_BIGINT> is (currently) omitted, because SQL/CLI and ODBC provide | |||
2519 | conflicting codes. | |||
2520 | ||||
2521 | See the L</type_info>, L</type_info_all>, and L</bind_param> methods | |||
2522 | for possible uses. | |||
2523 | ||||
2524 | Note that just because the DBI defines a named constant for a given | |||
2525 | data type doesn't mean that drivers will support that data type. | |||
2526 | ||||
2527 | ||||
2528 | =head2 DBI Class Methods | |||
2529 | ||||
2530 | The following methods are provided by the DBI class: | |||
2531 | ||||
2532 | =head3 C<parse_dsn> | |||
2533 | ||||
2534 | ($scheme, $driver, $attr_string, $attr_hash, $driver_dsn) = DBI->parse_dsn($dsn) | |||
2535 | or die "Can't parse DBI DSN '$dsn'"; | |||
2536 | ||||
2537 | Breaks apart a DBI Data Source Name (DSN) and returns the individual | |||
2538 | parts. If $dsn doesn't contain a valid DSN then parse_dsn() returns | |||
2539 | an empty list. | |||
2540 | ||||
2541 | $scheme is the first part of the DSN and is currently always 'dbi'. | |||
2542 | $driver is the driver name, possibly defaulted to $ENV{DBI_DRIVER}, | |||
2543 | and may be undefined. $attr_string is the contents of the optional attribute | |||
2544 | string, which may be undefined. If $attr_string is not empty then $attr_hash | |||
2545 | is a reference to a hash containing the parsed attribute names and values. | |||
2546 | $driver_dsn is the last part of the DBI DSN string. For example: | |||
2547 | ||||
2548 | ($scheme, $driver, $attr_string, $attr_hash, $driver_dsn) | |||
2549 | = DBI->parse_dsn("DBI:MyDriver(RaiseError=>1):db=test;port=42"); | |||
2550 | $scheme = 'dbi'; | |||
2551 | $driver = 'MyDriver'; | |||
2552 | $attr_string = 'RaiseError=>1'; | |||
2553 | $attr_hash = { 'RaiseError' => '1' }; | |||
2554 | $driver_dsn = 'db=test;port=42'; | |||
2555 | ||||
2556 | The parse_dsn() method was added in DBI 1.43. | |||
2557 | ||||
2558 | =head3 C<connect> | |||
2559 | ||||
2560 | $dbh = DBI->connect($data_source, $username, $password) | |||
2561 | or die $DBI::errstr; | |||
2562 | $dbh = DBI->connect($data_source, $username, $password, \%attr) | |||
2563 | or die $DBI::errstr; | |||
2564 | ||||
2565 | Establishes a database connection, or session, to the requested C<$data_source>. | |||
2566 | Returns a database handle object if the connection succeeds. Use | |||
2567 | C<$dbh-E<gt>disconnect> to terminate the connection. | |||
2568 | ||||
2569 | If the connect fails (see below), it returns C<undef> and sets both C<$DBI::err> | |||
2570 | and C<$DBI::errstr>. (It does I<not> explicitly set C<$!>.) You should generally | |||
2571 | test the return status of C<connect> and C<print $DBI::errstr> if it has failed. | |||
2572 | ||||
2573 | Multiple simultaneous connections to multiple databases through multiple | |||
2574 | drivers can be made via the DBI. Simply make one C<connect> call for each | |||
2575 | database and keep a copy of each returned database handle. | |||
2576 | ||||
2577 | The C<$data_source> value must begin with "C<dbi:>I<driver_name>C<:>". | |||
2578 | The I<driver_name> specifies the driver that will be used to make the | |||
2579 | connection. (Letter case is significant.) | |||
2580 | ||||
2581 | As a convenience, if the C<$data_source> parameter is undefined or empty, | |||
2582 | the DBI will substitute the value of the environment variable C<DBI_DSN>. | |||
2583 | If just the I<driver_name> part is empty (i.e., the C<$data_source> | |||
2584 | prefix is "C<dbi::>"), the environment variable C<DBI_DRIVER> is | |||
2585 | used. If neither variable is set, then C<connect> dies. | |||
2586 | ||||
2587 | Examples of C<$data_source> values are: | |||
2588 | ||||
2589 | dbi:DriverName:database_name | |||
2590 | dbi:DriverName:database_name@hostname:port | |||
2591 | dbi:DriverName:database=database_name;host=hostname;port=port | |||
2592 | ||||
2593 | There is I<no standard> for the text following the driver name. Each | |||
2594 | driver is free to use whatever syntax it wants. The only requirement the | |||
2595 | DBI makes is that all the information is supplied in a single string. | |||
2596 | You must consult the documentation for the drivers you are using for a | |||
2597 | description of the syntax they require. | |||
2598 | ||||
2599 | It is recommended that drivers support the ODBC style, shown in the | |||
2600 | last example above. It is also recommended that that they support the | |||
2601 | three common names 'C<host>', 'C<port>', and 'C<database>' (plus 'C<db>' | |||
2602 | as an alias for C<database>). This simplifies automatic construction | |||
2603 | of basic DSNs: C<"dbi:$driver:database=$db;host=$host;port=$port">. | |||
2604 | Drivers should aim to 'do something reasonable' when given a DSN | |||
2605 | in this form, but if any part is meaningless for that driver (such | |||
2606 | as 'port' for Informix) it should generate an error if that part | |||
2607 | is not empty. | |||
2608 | ||||
2609 | If the environment variable C<DBI_AUTOPROXY> is defined (and the | |||
2610 | driver in C<$data_source> is not "C<Proxy>") then the connect request | |||
2611 | will automatically be changed to: | |||
2612 | ||||
2613 | $ENV{DBI_AUTOPROXY};dsn=$data_source | |||
2614 | ||||
2615 | C<DBI_AUTOPROXY> is typically set as "C<dbi:Proxy:hostname=...;port=...>". | |||
2616 | If $ENV{DBI_AUTOPROXY} doesn't begin with 'C<dbi:>' then "dbi:Proxy:" | |||
2617 | will be prepended to it first. See the DBD::Proxy documentation | |||
2618 | for more details. | |||
2619 | ||||
2620 | If C<$username> or C<$password> are undefined (rather than just empty), | |||
2621 | then the DBI will substitute the values of the C<DBI_USER> and C<DBI_PASS> | |||
2622 | environment variables, respectively. The DBI will warn if the | |||
2623 | environment variables are not defined. However, the everyday use | |||
2624 | of these environment variables is not recommended for security | |||
2625 | reasons. The mechanism is primarily intended to simplify testing. | |||
2626 | See below for alternative way to specify the username and password. | |||
2627 | ||||
2628 | C<DBI-E<gt>connect> automatically installs the driver if it has not been | |||
2629 | installed yet. Driver installation either returns a valid driver | |||
2630 | handle, or it I<dies> with an error message that includes the string | |||
2631 | "C<install_driver>" and the underlying problem. So C<DBI-E<gt>connect> | |||
2632 | will die | |||
2633 | on a driver installation failure and will only return C<undef> on a | |||
2634 | connect failure, in which case C<$DBI::errstr> will hold the error message. | |||
2635 | Use C<eval { ... }> if you need to catch the "C<install_driver>" error. | |||
2636 | ||||
2637 | The C<$data_source> argument (with the "C<dbi:...:>" prefix removed) and the | |||
2638 | C<$username> and C<$password> arguments are then passed to the driver for | |||
2639 | processing. The DBI does not define any interpretation for the | |||
2640 | contents of these fields. The driver is free to interpret the | |||
2641 | C<$data_source>, C<$username>, and C<$password> fields in any way, and supply | |||
2642 | whatever defaults are appropriate for the engine being accessed. | |||
2643 | (Oracle, for example, uses the ORACLE_SID and TWO_TASK environment | |||
2644 | variables if no C<$data_source> is specified.) | |||
2645 | ||||
2646 | The C<AutoCommit> and C<PrintError> attributes for each connection | |||
2647 | default to "on". (See L</AutoCommit> and L</PrintError> for more information.) | |||
2648 | However, it is strongly recommended that you explicitly define C<AutoCommit> | |||
2649 | rather than rely on the default. The C<PrintWarn> attribute defaults to | |||
2650 | on if $^W is true, i.e., perl is running with warnings enabled. | |||
2651 | ||||
2652 | The C<\%attr> parameter can be used to alter the default settings of | |||
2653 | C<PrintError>, C<RaiseError>, C<AutoCommit>, and other attributes. For example: | |||
2654 | ||||
2655 | $dbh = DBI->connect($data_source, $user, $pass, { | |||
2656 | PrintError => 0, | |||
2657 | AutoCommit => 0 | |||
2658 | }); | |||
2659 | ||||
2660 | The username and password can also be specified using the attributes | |||
2661 | C<Username> and C<Password>, in which case they take precedence | |||
2662 | over the C<$username> and C<$password> parameters. | |||
2663 | ||||
2664 | You can also define connection attribute values within the C<$data_source> | |||
2665 | parameter. For example: | |||
2666 | ||||
2667 | dbi:DriverName(PrintWarn=>1,PrintError=>0,Taint=>1):... | |||
2668 | ||||
2669 | Individual attributes values specified in this way take precedence over | |||
2670 | any conflicting values specified via the C<\%attr> parameter to C<connect>. | |||
2671 | ||||
2672 | The C<dbi_connect_method> attribute can be used to specify which driver | |||
2673 | method should be called to establish the connection. The only useful | |||
2674 | values are 'connect', 'connect_cached', or some specialized case like | |||
2675 | 'Apache::DBI::connect' (which is automatically the default when running | |||
2676 | within Apache). | |||
2677 | ||||
2678 | Where possible, each session (C<$dbh>) is independent from the transactions | |||
2679 | in other sessions. This is useful when you need to hold cursors open | |||
2680 | across transactions--for example, if you use one session for your long lifespan | |||
2681 | cursors (typically read-only) and another for your short update | |||
2682 | transactions. | |||
2683 | ||||
2684 | For compatibility with old DBI scripts, the driver can be specified by | |||
2685 | passing its name as the fourth argument to C<connect> (instead of C<\%attr>): | |||
2686 | ||||
2687 | $dbh = DBI->connect($data_source, $user, $pass, $driver); | |||
2688 | ||||
2689 | In this "old-style" form of C<connect>, the C<$data_source> should not start | |||
2690 | with "C<dbi:driver_name:>". (If it does, the embedded driver_name | |||
2691 | will be ignored). Also note that in this older form of C<connect>, | |||
2692 | the C<$dbh-E<gt>{AutoCommit}> attribute is I<undefined>, the | |||
2693 | C<$dbh-E<gt>{PrintError}> attribute is off, and the old C<DBI_DBNAME> | |||
2694 | environment variable is | |||
2695 | checked if C<DBI_DSN> is not defined. Beware that this "old-style" | |||
2696 | C<connect> will soon be withdrawn in a future version of DBI. | |||
2697 | ||||
2698 | =head3 C<connect_cached> | |||
2699 | ||||
2700 | $dbh = DBI->connect_cached($data_source, $username, $password) | |||
2701 | or die $DBI::errstr; | |||
2702 | $dbh = DBI->connect_cached($data_source, $username, $password, \%attr) | |||
2703 | or die $DBI::errstr; | |||
2704 | ||||
2705 | C<connect_cached> is like L</connect>, except that the database handle | |||
2706 | returned is also | |||
2707 | stored in a hash associated with the given parameters. If another call | |||
2708 | is made to C<connect_cached> with the same parameter values, then the | |||
2709 | corresponding cached C<$dbh> will be returned if it is still valid. | |||
2710 | The cached database handle is replaced with a new connection if it | |||
2711 | has been disconnected or if the C<ping> method fails. | |||
2712 | ||||
2713 | That the behaviour of this method differs in several respects from the | |||
2714 | behaviour of persistent connections implemented by Apache::DBI. | |||
2715 | However, if Apache::DBI is loaded then C<connect_cached> will use it. | |||
2716 | ||||
2717 | Caching connections can be useful in some applications, but it can | |||
2718 | also cause problems, such as too many connections, and so should | |||
2719 | be used with care. In particular, avoid changing the attributes of | |||
2720 | a database handle created via connect_cached() because it will affect | |||
2721 | other code that may be using the same handle. | |||
2722 | ||||
2723 | Where multiple separate parts of a program are using connect_cached() | |||
2724 | to connect to the same database with the same (initial) attributes | |||
2725 | it is a good idea to add a private attribute to the connect_cached() | |||
2726 | call to effectively limit the scope of the caching. For example: | |||
2727 | ||||
2728 | DBI->connect_cached(..., { private_foo_cachekey => "Bar", ... }); | |||
2729 | ||||
2730 | Handles returned from that connect_cached() call will only be returned | |||
2731 | by other connect_cached() call elsewhere in the code if those other | |||
2732 | calls also pass in the same attribute values, including the private one. | |||
2733 | (I've used C<private_foo_cachekey> here as an example, you can use | |||
2734 | any attribute name with a C<private_> prefix.) | |||
2735 | ||||
2736 | Taking that one step further, you can limit a particular connect_cached() | |||
2737 | call to return handles unique to that one place in the code by setting the | |||
2738 | private attribute to a unique value for that place: | |||
2739 | ||||
2740 | DBI->connect_cached(..., { private_foo_cachekey => __FILE__.__LINE__, ... }); | |||
2741 | ||||
2742 | By using a private attribute you still get connection caching for | |||
2743 | the individual calls to connect_cached() but, by making separate | |||
2744 | database conections for separate parts of the code, the database | |||
2745 | handles are isolated from any attribute changes made to other handles. | |||
2746 | ||||
2747 | The cache can be accessed (and cleared) via the L</CachedKids> attribute: | |||
2748 | ||||
2749 | my $CachedKids_hashref = $dbh->{Driver}->{CachedKids}; | |||
2750 | %$CachedKids_hashref = () if $CachedKids_hashref; | |||
2751 | ||||
2752 | ||||
2753 | =head3 C<available_drivers> | |||
2754 | ||||
2755 | @ary = DBI->available_drivers; | |||
2756 | @ary = DBI->available_drivers($quiet); | |||
2757 | ||||
2758 | Returns a list of all available drivers by searching for C<DBD::*> modules | |||
2759 | through the directories in C<@INC>. By default, a warning is given if | |||
2760 | some drivers are hidden by others of the same name in earlier | |||
2761 | directories. Passing a true value for C<$quiet> will inhibit the warning. | |||
2762 | ||||
2763 | =head3 C<installed_drivers> | |||
2764 | ||||
2765 | %drivers = DBI->installed_drivers(); | |||
2766 | ||||
2767 | Returns a list of driver name and driver handle pairs for all drivers | |||
2768 | 'installed' (loaded) into the current process. The driver name does not | |||
2769 | include the 'DBD::' prefix. | |||
2770 | ||||
2771 | To get a list of all drivers available in your perl instalation you can use | |||
2772 | L</available_drivers>. | |||
2773 | ||||
2774 | Added in DBI 1.49. | |||
2775 | ||||
2776 | =head3 C<installed_versions> | |||
2777 | ||||
2778 | DBI->installed_versions; | |||
2779 | @ary = DBI->installed_versions; | |||
2780 | %hash = DBI->installed_versions; | |||
2781 | ||||
2782 | Calls available_drivers() and attempts to load each of them in turn | |||
2783 | using install_driver(). For each load that succeeds the driver | |||
2784 | name and version number are added to a hash. When running under | |||
2785 | L<DBI::PurePerl> drivers which appear not be pure-perl are ignored. | |||
2786 | ||||
2787 | When called in array context the list of successfully loaded drivers | |||
2788 | is returned (without the 'DBD::' prefix). | |||
2789 | ||||
2790 | When called in scalar context a reference to the hash is returned | |||
2791 | and the hash will also contain other entries for the C<DBI> version, | |||
2792 | C<OS> name, etc. | |||
2793 | ||||
2794 | When called in a void context the installed_versions() method will | |||
2795 | print out a formatted list of the hash contents, one per line. | |||
2796 | ||||
2797 | Due to the potentially high memory cost and unknown risks of loading | |||
2798 | in an unknown number of drivers that just happen to be installed | |||
2799 | on the system, this method is not recommended for general use. | |||
2800 | Use available_drivers() instead. | |||
2801 | ||||
2802 | The installed_versions() method is primarily intended as a quick | |||
2803 | way to see from the command line what's installed. For example: | |||
2804 | ||||
2805 | perl -MDBI -e 'DBI->installed_versions' | |||
2806 | ||||
2807 | The installed_versions() method was added in DBI 1.38. | |||
2808 | ||||
2809 | =head3 C<data_sources> | |||
2810 | ||||
2811 | @ary = DBI->data_sources($driver); | |||
2812 | @ary = DBI->data_sources($driver, \%attr); | |||
2813 | ||||
2814 | Returns a list of data sources (databases) available via the named | |||
2815 | driver. If C<$driver> is empty or C<undef>, then the value of the | |||
2816 | C<DBI_DRIVER> environment variable is used. | |||
2817 | ||||
2818 | The driver will be loaded if it hasn't been already. Note that if the | |||
2819 | driver loading fails then data_sources() I<dies> with an error message | |||
2820 | that includes the string "C<install_driver>" and the underlying problem. | |||
2821 | ||||
2822 | Data sources are returned in a form suitable for passing to the | |||
2823 | L</connect> method (that is, they will include the "C<dbi:$driver:>" prefix). | |||
2824 | ||||
2825 | Note that many drivers have no way of knowing what data sources might | |||
2826 | be available for it. These drivers return an empty or incomplete list | |||
2827 | or may require driver-specific attributes. | |||
2828 | ||||
2829 | There is also a data_sources() method defined for database handles. | |||
2830 | ||||
2831 | ||||
2832 | =head3 C<trace> | |||
2833 | ||||
2834 | DBI->trace($trace_setting) | |||
2835 | DBI->trace($trace_setting, $trace_filename) | |||
2836 | DBI->trace($trace_setting, $trace_filehandle) | |||
2837 | $trace_setting = DBI->trace; | |||
2838 | ||||
2839 | The C<DBI-E<gt>trace> method sets the I<global default> trace | |||
2840 | settings and returns the I<previous> trace settings. It can also | |||
2841 | be used to change where the trace output is sent. | |||
2842 | ||||
2843 | There's a similar method, C<$h-E<gt>trace>, which sets the trace | |||
2844 | settings for the specific handle it's called on. | |||
2845 | ||||
2846 | See the L</TRACING> section for full details about the DBI's powerful | |||
2847 | tracing facilities. | |||
2848 | ||||
2849 | ||||
2850 | ||||
2851 | =head2 DBI Utility Functions | |||
2852 | ||||
2853 | In addition to the DBI methods listed in the previous section, | |||
2854 | the DBI package also provides several utility functions. | |||
2855 | ||||
2856 | These can be imported into your code by listing them in | |||
2857 | the C<use> statement. For example: | |||
2858 | ||||
2859 | use DBI qw(neat data_diff); | |||
2860 | ||||
2861 | Alternatively, all these utility functions (except hash) can be | |||
2862 | imported using the C<:utils> import tag. For example: | |||
2863 | ||||
2864 | use DBI qw(:utils); | |||
2865 | ||||
2866 | =head3 C<data_string_desc> | |||
2867 | ||||
2868 | $description = data_string_desc($string); | |||
2869 | ||||
2870 | Returns an informal description of the string. For example: | |||
2871 | ||||
2872 | UTF8 off, ASCII, 42 characters 42 bytes | |||
2873 | UTF8 off, non-ASCII, 42 characters 42 bytes | |||
2874 | UTF8 on, non-ASCII, 4 characters 6 bytes | |||
2875 | UTF8 on but INVALID encoding, non-ASCII, 4 characters 6 bytes | |||
2876 | UTF8 off, undef | |||
2877 | ||||
2878 | The initial C<UTF8> on/off refers to Perl's internal SvUTF8 flag. | |||
2879 | If $string has the SvUTF8 flag set but the sequence of bytes it | |||
2880 | contains are not a valid UTF-8 encoding then data_string_desc() | |||
2881 | will report C<UTF8 on but INVALID encoding>. | |||
2882 | ||||
2883 | The C<ASCII> vs C<non-ASCII> portion shows C<ASCII> if I<all> the | |||
2884 | characters in the string are ASCII (have code points <= 127). | |||
2885 | ||||
2886 | The data_string_desc() function was added in DBI 1.46. | |||
2887 | ||||
2888 | =head3 C<data_string_diff> | |||
2889 | ||||
2890 | $diff = data_string_diff($a, $b); | |||
2891 | ||||
2892 | Returns an informal description of the first character difference | |||
2893 | between the strings. If both $a and $b contain the same sequence | |||
2894 | of characters then data_string_diff() returns an empty string. | |||
2895 | For example: | |||
2896 | ||||
2897 | Params a & b Result | |||
2898 | ------------ ------ | |||
2899 | 'aaa', 'aaa' '' | |||
2900 | 'aaa', 'abc' 'Strings differ at index 2: a[2]=a, b[2]=b' | |||
2901 | 'aaa', undef 'String b is undef, string a has 3 characters' | |||
2902 | 'aaa', 'aa' 'String b truncated after 2 characters' | |||
2903 | ||||
2904 | Unicode characters are reported in C<\x{XXXX}> format. Unicode | |||
2905 | code points in the range U+0800 to U+08FF are unassigned and most | |||
2906 | likely to occur due to double-encoding. Characters in this range | |||
2907 | are reported as C<\x{08XX}='C'> where C<C> is the corresponding | |||
2908 | latin-1 character. | |||
2909 | ||||
2910 | The data_string_diff() function only considers logical I<characters> | |||
2911 | and not the underlying encoding. See L</data_diff> for an alternative. | |||
2912 | ||||
2913 | The data_string_diff() function was added in DBI 1.46. | |||
2914 | ||||
2915 | =head3 C<data_diff> | |||
2916 | ||||
2917 | $diff = data_diff($a, $b); | |||
2918 | $diff = data_diff($a, $b, $logical); | |||
2919 | ||||
2920 | Returns an informal description of the difference between two strings. | |||
2921 | It calls L</data_string_desc> and L</data_string_diff> | |||
2922 | and returns the combined results as a multi-line string. | |||
2923 | ||||
2924 | For example, C<data_diff("abc", "ab\x{263a}")> will return: | |||
2925 | ||||
2926 | a: UTF8 off, ASCII, 3 characters 3 bytes | |||
2927 | b: UTF8 on, non-ASCII, 3 characters 5 bytes | |||
2928 | Strings differ at index 2: a[2]=c, b[2]=\x{263A} | |||
2929 | ||||
2930 | If $a and $b are identical in both the characters they contain I<and> | |||
2931 | their physical encoding then data_diff() returns an empty string. | |||
2932 | If $logical is true then physical encoding differences are ignored | |||
2933 | (but are still reported if there is a difference in the characters). | |||
2934 | ||||
2935 | The data_diff() function was added in DBI 1.46. | |||
2936 | ||||
2937 | =head3 C<neat> | |||
2938 | ||||
2939 | $str = neat($value); | |||
2940 | $str = neat($value, $maxlen); | |||
2941 | ||||
2942 | Return a string containing a neat (and tidy) representation of the | |||
2943 | supplied value. | |||
2944 | ||||
2945 | Strings will be quoted, although internal quotes will I<not> be escaped. | |||
2946 | Values known to be numeric will be unquoted. Undefined (NULL) values | |||
2947 | will be shown as C<undef> (without quotes). | |||
2948 | ||||
2949 | If the string is flagged internally as utf8 then double quotes will | |||
2950 | be used, otherwise single quotes are used and unprintable characters | |||
2951 | will be replaced by dot (.). | |||
2952 | ||||
2953 | For result strings longer than C<$maxlen> the result string will be | |||
2954 | truncated to C<$maxlen-4> and "C<...'>" will be appended. If C<$maxlen> is 0 | |||
2955 | or C<undef>, it defaults to C<$DBI::neat_maxlen> which, in turn, defaults to 400. | |||
2956 | ||||
2957 | This function is designed to format values for human consumption. | |||
2958 | It is used internally by the DBI for L</trace> output. It should | |||
2959 | typically I<not> be used for formatting values for database use. | |||
2960 | (See also L</quote>.) | |||
2961 | ||||
2962 | =head3 C<neat_list> | |||
2963 | ||||
2964 | $str = neat_list(\@listref, $maxlen, $field_sep); | |||
2965 | ||||
2966 | Calls C<neat> on each element of the list and returns a string | |||
2967 | containing the results joined with C<$field_sep>. C<$field_sep> defaults | |||
2968 | to C<", ">. | |||
2969 | ||||
2970 | =head3 C<looks_like_number> | |||
2971 | ||||
2972 | @bool = looks_like_number(@array); | |||
2973 | ||||
2974 | Returns true for each element that looks like a number. | |||
2975 | Returns false for each element that does not look like a number. | |||
2976 | Returns C<undef> for each element that is undefined or empty. | |||
2977 | ||||
2978 | =head3 C<hash> | |||
2979 | ||||
2980 | $hash_value = DBI::hash($buffer, $type); | |||
2981 | ||||
2982 | Return a 32-bit integer 'hash' value corresponding to the contents of $buffer. | |||
2983 | The $type parameter selects which kind of hash algorithm should be used. | |||
2984 | ||||
2985 | For the technically curious, type 0 (which is the default if $type | |||
2986 | isn't specified) is based on the Perl 5.1 hash except that the value | |||
2987 | is forced to be negative (for obscure historical reasons). | |||
2988 | Type 1 is the better "Fowler / Noll / Vo" (FNV) hash. See | |||
2989 | L<http://www.isthe.com/chongo/tech/comp/fnv/> for more information. | |||
2990 | Both types are implemented in C and are very fast. | |||
2991 | ||||
2992 | This function doesn't have much to do with databases, except that | |||
2993 | it can be handy to store hash values in a database. | |||
2994 | ||||
2995 | ||||
2996 | =head2 DBI Dynamic Attributes | |||
2997 | ||||
2998 | Dynamic attributes are always associated with the I<last handle used> | |||
2999 | (that handle is represented by C<$h> in the descriptions below). | |||
3000 | ||||
3001 | Where an attribute is equivalent to a method call, then refer to | |||
3002 | the method call for all related documentation. | |||
3003 | ||||
3004 | Warning: these attributes are provided as a convenience but they | |||
3005 | do have limitations. Specifically, they have a short lifespan: | |||
3006 | because they are associated with | |||
3007 | the last handle used, they should only be used I<immediately> after | |||
3008 | calling the method that "sets" them. | |||
3009 | If in any doubt, use the corresponding method call. | |||
3010 | ||||
3011 | =head3 C<$DBI::err> | |||
3012 | ||||
3013 | Equivalent to C<$h-E<gt>err>. | |||
3014 | ||||
3015 | =head3 C<$DBI::errstr> | |||
3016 | ||||
3017 | Equivalent to C<$h-E<gt>errstr>. | |||
3018 | ||||
3019 | =head3 C<$DBI::state> | |||
3020 | ||||
3021 | Equivalent to C<$h-E<gt>state>. | |||
3022 | ||||
3023 | =head3 C<$DBI::rows> | |||
3024 | ||||
3025 | Equivalent to C<$h-E<gt>rows>. Please refer to the documentation | |||
3026 | for the L</rows> method. | |||
3027 | ||||
3028 | =head3 C<$DBI::lasth> | |||
3029 | ||||
3030 | Returns the DBI object handle used for the most recent DBI method call. | |||
3031 | If the last DBI method call was a DESTROY then $DBI::lasth will return | |||
3032 | the handle of the parent of the destroyed handle, if there is one. | |||
3033 | ||||
3034 | ||||
3035 | =head1 METHODS COMMON TO ALL HANDLES | |||
3036 | ||||
3037 | The following methods can be used by all types of DBI handles. | |||
3038 | ||||
3039 | =head3 C<err> | |||
3040 | ||||
3041 | $rv = $h->err; | |||
3042 | ||||
3043 | Returns the I<native> database engine error code from the last driver | |||
3044 | method called. The code is typically an integer but you should not | |||
3045 | assume that. | |||
3046 | ||||
3047 | The DBI resets $h->err to undef before almost all DBI method calls, so the | |||
3048 | value only has a short lifespan. Also, for most drivers, the statement | |||
3049 | handles share the same error variable as the parent database handle, | |||
3050 | so calling a method on one handle may reset the error on the | |||
3051 | related handles. | |||
3052 | ||||
3053 | (Methods which don't reset err before being called include err() and errstr(), | |||
3054 | obviously, state(), rows(), func(), trace(), trace_msg(), ping(), and the | |||
3055 | tied hash attribute FETCH() and STORE() methods.) | |||
3056 | ||||
3057 | If you need to test for specific error conditions I<and> have your program be | |||
3058 | portable to different database engines, then you'll need to determine what the | |||
3059 | corresponding error codes are for all those engines and test for all of them. | |||
3060 | ||||
3061 | The DBI uses the value of $DBI::stderr as the C<err> value for internal errors. | |||
3062 | Drivers should also do likewise. The default value for $DBI::stderr is 2000000000. | |||
3063 | ||||
3064 | A driver may return C<0> from err() to indicate a warning condition | |||
3065 | after a method call. Similarly, a driver may return an empty string | |||
3066 | to indicate a 'success with information' condition. In both these | |||
3067 | cases the value is false but not undef. The errstr() and state() | |||
3068 | methods may be used to retrieve extra information in these cases. | |||
3069 | ||||
3070 | See L</set_err> for more information. | |||
3071 | ||||
3072 | =head3 C<errstr> | |||
3073 | ||||
3074 | $str = $h->errstr; | |||
3075 | ||||
3076 | Returns the native database engine error message from the last DBI | |||
3077 | method called. This has the same lifespan issues as the L</err> method | |||
3078 | described above. | |||
3079 | ||||
3080 | The returned string may contain multiple messages separated by | |||
3081 | newline characters. | |||
3082 | ||||
3083 | The errstr() method should not be used to test for errors, use err() | |||
3084 | for that, because drivers may return 'success with information' or | |||
3085 | warning messages via errstr() for methods that have not 'failed'. | |||
3086 | ||||
3087 | See L</set_err> for more information. | |||
3088 | ||||
3089 | =head3 C<state> | |||
3090 | ||||
3091 | $str = $h->state; | |||
3092 | ||||
3093 | Returns a state code in the standard SQLSTATE five character format. | |||
3094 | Note that the specific success code C<00000> is translated to any empty string | |||
3095 | (false). If the driver does not support SQLSTATE (and most don't), | |||
3096 | then state() will return C<S1000> (General Error) for all errors. | |||
3097 | ||||
3098 | The driver is free to return any value via C<state>, e.g., warning | |||
3099 | codes, even if it has not declared an error by returning a true value | |||
3100 | via the L</err> method described above. | |||
3101 | ||||
3102 | The state() method should not be used to test for errors, use err() | |||
3103 | for that, because drivers may return a 'success with information' or | |||
3104 | warning state code via state() for methods that have not 'failed'. | |||
3105 | ||||
3106 | =head3 C<set_err> | |||
3107 | ||||
3108 | $rv = $h->set_err($err, $errstr); | |||
3109 | $rv = $h->set_err($err, $errstr, $state); | |||
3110 | $rv = $h->set_err($err, $errstr, $state, $method); | |||
3111 | $rv = $h->set_err($err, $errstr, $state, $method, $rv); | |||
3112 | ||||
3113 | Set the C<err>, C<errstr>, and C<state> values for the handle. | |||
3114 | This method is typically only used by DBI drivers and DBI subclasses. | |||
3115 | ||||
3116 | If the L</HandleSetErr> attribute holds a reference to a subroutine | |||
3117 | it is called first. The subroutine can alter the $err, $errstr, $state, | |||
3118 | and $method values. See L</HandleSetErr> for full details. | |||
3119 | If the subroutine returns a true value then the handle C<err>, | |||
3120 | C<errstr>, and C<state> values are not altered and set_err() returns | |||
3121 | an empty list (it normally returns $rv which defaults to undef, see below). | |||
3122 | ||||
3123 | Setting C<err> to a I<true> value indicates an error and will trigger | |||
3124 | the normal DBI error handling mechanisms, such as C<RaiseError> and | |||
3125 | C<HandleError>, if they are enabled, when execution returns from | |||
3126 | the DBI back to the application. | |||
3127 | ||||
3128 | Setting C<err> to C<""> indicates an 'information' state, and setting | |||
3129 | it to C<"0"> indicates a 'warning' state. Setting C<err> to C<undef> | |||
3130 | also sets C<errstr> to undef, and C<state> to C<"">, irrespective | |||
3131 | of the values of the $errstr and $state parameters. | |||
3132 | ||||
3133 | The $method parameter provides an alternate method name for the | |||
3134 | C<RaiseError>/C<PrintError>/C<PrintWarn> error string instead of | |||
3135 | the fairly unhelpful 'C<set_err>'. | |||
3136 | ||||
3137 | The C<set_err> method normally returns undef. The $rv parameter | |||
3138 | provides an alternate return value. | |||
3139 | ||||
3140 | Some special rules apply if the C<err> or C<errstr> | |||
3141 | values for the handle are I<already> set... | |||
3142 | ||||
3143 | If C<errstr> is true then: "C< [err was %s now %s]>" is appended if $err is | |||
3144 | true and C<err> is already true and the new err value differs from the original | |||
3145 | one. Similarly "C< [state was %s now %s]>" is appended if $state is true and C<state> is | |||
3146 | already true and the new state value differs from the original one. Finally | |||
3147 | "C<\n>" and the new $errstr are appended if $errstr differs from the existing | |||
3148 | errstr value. Obviously the C<%s>'s above are replaced by the corresponding values. | |||
3149 | ||||
3150 | The handle C<err> value is set to $err if: $err is true; or handle | |||
3151 | C<err> value is undef; or $err is defined and the length is greater | |||
3152 | than the handle C<err> length. The effect is that an 'information' | |||
3153 | state only overrides undef; a 'warning' overrides undef or 'information', | |||
3154 | and an 'error' state overrides anything. | |||
3155 | ||||
3156 | The handle C<state> value is set to $state if $state is true and | |||
3157 | the handle C<err> value was set (by the rules above). | |||
3158 | ||||
3159 | Support for warning and information states was added in DBI 1.41. | |||
3160 | ||||
3161 | =head3 C<trace> | |||
3162 | ||||
3163 | $h->trace($trace_settings); | |||
3164 | $h->trace($trace_settings, $trace_filename); | |||
3165 | $trace_settings = $h->trace; | |||
3166 | ||||
3167 | The trace() method is used to alter the trace settings for a handle | |||
3168 | (and any future children of that handle). It can also be used to | |||
3169 | change where the trace output is sent. | |||
3170 | ||||
3171 | There's a similar method, C<DBI-E<gt>trace>, which sets the global | |||
3172 | default trace settings. | |||
3173 | ||||
3174 | See the L</TRACING> section for full details about the DBI's powerful | |||
3175 | tracing facilities. | |||
3176 | ||||
3177 | =head3 C<trace_msg> | |||
3178 | ||||
3179 | $h->trace_msg($message_text); | |||
3180 | $h->trace_msg($message_text, $min_level); | |||
3181 | ||||
3182 | Writes C<$message_text> to the trace file if the trace level is | |||
3183 | greater than or equal to $min_level (which defaults to 1). | |||
3184 | Can also be called as C<DBI-E<gt>trace_msg($msg)>. | |||
3185 | ||||
3186 | See L</TRACING> for more details. | |||
3187 | ||||
3188 | =head3 C<func> | |||
3189 | ||||
3190 | $h->func(@func_arguments, $func_name) or die ...; | |||
3191 | ||||
3192 | The C<func> method can be used to call private non-standard and | |||
3193 | non-portable methods implemented by the driver. Note that the function | |||
3194 | name is given as the I<last> argument. | |||
3195 | ||||
3196 | It's also important to note that the func() method does not clear | |||
3197 | a previous error ($DBI::err etc.) and it does not trigger automatic | |||
3198 | error detection (RaiseError etc.) so you must check the return | |||
3199 | status and/or $h->err to detect errors. | |||
3200 | ||||
3201 | (This method is not directly related to calling stored procedures. | |||
3202 | Calling stored procedures is currently not defined by the DBI. | |||
3203 | Some drivers, such as DBD::Oracle, support it in non-portable ways. | |||
3204 | See driver documentation for more details.) | |||
3205 | ||||
3206 | See also install_method() in L<DBI::DBD> for how you can avoid needing to | |||
3207 | use func() and gain direct access to driver-private methods. | |||
3208 | ||||
3209 | =head3 C<can> | |||
3210 | ||||
3211 | $is_implemented = $h->can($method_name); | |||
3212 | ||||
3213 | Returns true if $method_name is implemented by the driver or a | |||
3214 | default method is provided by the DBI. | |||
3215 | It returns false where a driver hasn't implemented a method and the | |||
3216 | default method is provided by the DBI is just an empty stub. | |||
3217 | ||||
3218 | =head3 C<parse_trace_flags> | |||
3219 | ||||
3220 | $trace_settings_integer = $h->parse_trace_flags($trace_settings); | |||
3221 | ||||
3222 | Parses a string containing trace settings and returns the corresponding | |||
3223 | integer value used internally by the DBI and drivers. | |||
3224 | ||||
3225 | The $trace_settings argument is a string containing a trace level | |||
3226 | between 0 and 15 and/or trace flag names separated by vertical bar | |||
3227 | ("C<|>") or comma ("C<,>") characters. For example: C<"SQL|3|foo">. | |||
3228 | ||||
3229 | It uses the parse_trace_flag() method, described below, to process | |||
3230 | the individual trage flag names. | |||
3231 | ||||
3232 | The parse_trace_flags() method was added in DBI 1.42. | |||
3233 | ||||
3234 | =head3 C<parse_trace_flag> | |||
3235 | ||||
3236 | $bit_flag = $h->parse_trace_flag($trace_flag_name); | |||
3237 | ||||
3238 | Returns the bit flag corresponding to the trace flag name in | |||
3239 | $trace_flag_name. Drivers are expected to override this method and | |||
3240 | check if $trace_flag_name is a driver specific trace flags and, if | |||
3241 | not, then call the DBIs default parse_trace_flag(). | |||
3242 | ||||
3243 | The parse_trace_flag() method was added in DBI 1.42. | |||
3244 | ||||
3245 | =head3 C<private_attribute_info> | |||
3246 | ||||
3247 | $hash_ref = $h->private_attribute_info(); | |||
3248 | ||||
3249 | Returns a reference to a hash whose keys are the names of driver-private | |||
3250 | attributes available for the kind of handle (driver, database, statement) | |||
3251 | that the method was called on. | |||
3252 | ||||
3253 | For example, the return value when called with a DBD::Sybase $dbh could look like this: | |||
3254 | ||||
3255 | { | |||
3256 | syb_dynamic_supported => undef, | |||
3257 | syb_oc_version => undef, | |||
3258 | syb_server_version => undef, | |||
3259 | syb_server_version_string => undef, | |||
3260 | } | |||
3261 | ||||
3262 | and when called with a DBD::Sybase $sth they could look like this: | |||
3263 | ||||
3264 | { | |||
3265 | syb_types => undef, | |||
3266 | syb_proc_status => undef, | |||
3267 | syb_result_type => undef, | |||
3268 | } | |||
3269 | ||||
3270 | The values should be undef. Meanings may be assigned to particular values in future. | |||
3271 | ||||
3272 | =head3 C<swap_inner_handle> | |||
3273 | ||||
3274 | $rc = $h1->swap_inner_handle( $h2 ); | |||
3275 | $rc = $h1->swap_inner_handle( $h2, $allow_reparent ); | |||
3276 | ||||
3277 | Brain transplants for handles. You don't need to know about this | |||
3278 | unless you want to become a handle surgeon. | |||
3279 | ||||
3280 | A DBI handle is a reference to a tied hash. A tied hash has an | |||
3281 | I<inner> hash that actually holds the contents. The swap_inner_handle() | |||
3282 | method swaps the inner hashes between two handles. The $h1 and $h2 | |||
3283 | handles still point to the same tied hashes, but what those hashes | |||
3284 | are tied to has been swapped. In effect $h1 I<becomes> $h2 and | |||
3285 | vice-versa. This is powerful stuff, expect problems. Use with care. | |||
3286 | ||||
3287 | As a small safety measure, the two handles, $h1 and $h2, have to | |||
3288 | share the same parent unless $allow_reparent is true. | |||
3289 | ||||
3290 | The swap_inner_handle() method was added in DBI 1.44. | |||
3291 | ||||
3292 | Here's a quick kind of 'diagram' as a worked example to help think about what's | |||
3293 | happening: | |||
3294 | ||||
3295 | Original state: | |||
3296 | dbh1o -> dbh1i | |||
3297 | sthAo -> sthAi(dbh1i) | |||
3298 | dbh2o -> dbh2i | |||
3299 | ||||
3300 | swap_inner_handle dbh1o with dbh2o: | |||
3301 | dbh2o -> dbh1i | |||
3302 | sthAo -> sthAi(dbh1i) | |||
3303 | dbh1o -> dbh2i | |||
3304 | ||||
3305 | create new sth from dbh1o: | |||
3306 | dbh2o -> dbh1i | |||
3307 | sthAo -> sthAi(dbh1i) | |||
3308 | dbh1o -> dbh2i | |||
3309 | sthBo -> sthBi(dbh2i) | |||
3310 | ||||
3311 | swap_inner_handle sthAo with sthBo: | |||
3312 | dbh2o -> dbh1i | |||
3313 | sthBo -> sthAi(dbh1i) | |||
3314 | dbh1o -> dbh2i | |||
3315 | sthAo -> sthBi(dbh2i) | |||
3316 | ||||
3317 | ||||
3318 | =head1 ATTRIBUTES COMMON TO ALL HANDLES | |||
3319 | ||||
3320 | These attributes are common to all types of DBI handles. | |||
3321 | ||||
3322 | Some attributes are inherited by child handles. That is, the value | |||
3323 | of an inherited attribute in a newly created statement handle is the | |||
3324 | same as the value in the parent database handle. Changes to attributes | |||
3325 | in the new statement handle do not affect the parent database handle | |||
3326 | and changes to the database handle do not affect existing statement | |||
3327 | handles, only future ones. | |||
3328 | ||||
3329 | Attempting to set or get the value of an unknown attribute generates a warning, | |||
3330 | except for private driver specific attributes (which all have names | |||
3331 | starting with a lowercase letter). | |||
3332 | ||||
3333 | Example: | |||
3334 | ||||
3335 | $h->{AttributeName} = ...; # set/write | |||
3336 | ... = $h->{AttributeName}; # get/read | |||
3337 | ||||
3338 | =head3 C<Warn> (boolean, inherited) | |||
3339 | ||||
3340 | The C<Warn> attribute enables useful warnings for certain bad | |||
3341 | practices. It is enabled by default and should only be disabled in | |||
3342 | rare circumstances. Since warnings are generated using the Perl | |||
3343 | C<warn> function, they can be intercepted using the Perl C<$SIG{__WARN__}> | |||
3344 | hook. | |||
3345 | ||||
3346 | The C<Warn> attribute is not related to the C<PrintWarn> attribute. | |||
3347 | ||||
3348 | =head3 C<Active> (boolean, read-only) | |||
3349 | ||||
3350 | The C<Active> attribute is true if the handle object is "active". This is rarely used in | |||
3351 | applications. The exact meaning of active is somewhat vague at the | |||
3352 | moment. For a database handle it typically means that the handle is | |||
3353 | connected to a database (C<$dbh-E<gt>disconnect> sets C<Active> off). For | |||
3354 | a statement handle it typically means that the handle is a C<SELECT> | |||
3355 | that may have more data to fetch. (Fetching all the data or calling C<$sth-E<gt>finish> | |||
3356 | sets C<Active> off.) | |||
3357 | ||||
3358 | =head3 C<Executed> (boolean) | |||
3359 | ||||
3360 | The C<Executed> attribute is true if the handle object has been "executed". | |||
3361 | Currently only the $dbh do() method and the $sth execute(), execute_array(), | |||
3362 | and execute_for_fetch() methods set the C<Executed> attribute. | |||
3363 | ||||
3364 | When it's set on a handle it is also set on the parent handle at the | |||
3365 | same time. So calling execute() on a $sth also sets the C<Executed> | |||
3366 | attribute on the parent $dbh. | |||
3367 | ||||
3368 | The C<Executed> attribute for a database handle is cleared by the commit() and | |||
3369 | rollback() methods (even if they fail). The C<Executed> attribute of a | |||
3370 | statement handle is not cleared by the DBI under any circumstances and so acts | |||
3371 | as a permanent record of whether the statement handle was ever used. | |||
3372 | ||||
3373 | The C<Executed> attribute was added in DBI 1.41. | |||
3374 | ||||
3375 | =head3 C<Kids> (integer, read-only) | |||
3376 | ||||
3377 | For a driver handle, C<Kids> is the number of currently existing database | |||
3378 | handles that were created from that driver handle. For a database | |||
3379 | handle, C<Kids> is the number of currently existing statement handles that | |||
3380 | were created from that database handle. | |||
3381 | For a statement handle, the value is zero. | |||
3382 | ||||
3383 | =head3 C<ActiveKids> (integer, read-only) | |||
3384 | ||||
3385 | Like C<Kids>, but only counting those that are C<Active> (as above). | |||
3386 | ||||
3387 | =head3 C<CachedKids> (hash ref) | |||
3388 | ||||
3389 | For a database handle, C<CachedKids> returns a reference to the cache (hash) of | |||
3390 | statement handles created by the L</prepare_cached> method. For a | |||
3391 | driver handle, returns a reference to the cache (hash) of | |||
3392 | database handles created by the L</connect_cached> method. | |||
3393 | ||||
3394 | =head3 C<Type> (scalar, read-only) | |||
3395 | ||||
3396 | The C<Type> attribute identifies the type of a DBI handle. Returns | |||
3397 | "dr" for driver handles, "db" for database handles and "st" for | |||
3398 | statement handles. | |||
3399 | ||||
3400 | =head3 C<ChildHandles> (array ref) | |||
3401 | ||||
3402 | The ChildHandles attribute contains a reference to an array of all the | |||
3403 | handles created by this handle which are still accessible. The | |||
3404 | contents of the array are weak-refs and will become undef when the | |||
3405 | handle goes out of scope. | |||
3406 | ||||
3407 | C<ChildHandles> returns undef if your perl version does not support weak | |||
3408 | references (check the L<Scalar::Util|Scalar::Util> module). The referenced | |||
3409 | array returned should be treated as read-only. | |||
3410 | ||||
3411 | For example, to enumerate all driver handles, database handles and | |||
3412 | statement handles: | |||
3413 | ||||
3414 | sub show_child_handles { | |||
3415 | my ($h, $level) = @_; | |||
3416 | printf "%sh %s %s\n", $h->{Type}, "\t" x $level, $h; | |||
3417 | show_child_handles($_, $level + 1) | |||
3418 | for (grep { defined } @{$h->{ChildHandles}}); | |||
3419 | } | |||
3420 | ||||
3421 | my %drivers = DBI->installed_drivers(); | |||
3422 | show_child_handles($_, 0) for (values %drivers); | |||
3423 | ||||
3424 | =head3 C<CompatMode> (boolean, inherited) | |||
3425 | ||||
3426 | The C<CompatMode> attribute is used by emulation layers (such as | |||
3427 | Oraperl) to enable compatible behaviour in the underlying driver | |||
3428 | (e.g., DBD::Oracle) for this handle. Not normally set by application code. | |||
3429 | ||||
3430 | It also has the effect of disabling the 'quick FETCH' of attribute | |||
3431 | values from the handles attribute cache. So all attribute values | |||
3432 | are handled by the drivers own FETCH method. This makes them slightly | |||
3433 | slower but is useful for special-purpose drivers like DBD::Multiplex. | |||
3434 | ||||
3435 | =head3 C<InactiveDestroy> (boolean) | |||
3436 | ||||
3437 | The default value, false, means a handle will be fully destroyed | |||
3438 | as normal when the last reference to it is removed, just as you'd expect. | |||
3439 | ||||
3440 | If set true then the handle will be treated by the DESTROY as if it was no | |||
3441 | longer Active, and so the I<database engine> related effects of DESTROYing a | |||
3442 | handle will be skipped. | |||
3443 | ||||
3444 | Think of the name as meaning 'treat the handle as not-Active in the DESTROY | |||
3445 | method'. | |||
3446 | ||||
3447 | For a database handle, this attribute does not disable an I<explicit> | |||
3448 | call to the disconnect method, only the implicit call from DESTROY | |||
3449 | that happens if the handle is still marked as C<Active>. | |||
3450 | ||||
3451 | This attribute is specifically designed for use in Unix applications | |||
3452 | that "fork" child processes. Either the parent or the child process, | |||
3453 | but not both, should set C<InactiveDestroy> true on all their shared handles. | |||
3454 | (Note that some databases, including Oracle, don't support passing a | |||
3455 | database connection across a fork.) | |||
3456 | ||||
3457 | To help tracing applications using fork the process id is shown in | |||
3458 | the trace log whenever a DBI or handle trace() method is called. | |||
3459 | The process id also shown for I<every> method call if the DBI trace | |||
3460 | level (not handle trace level) is set high enough to show the trace | |||
3461 | from the DBI's method dispatcher, e.g. >= 9. | |||
3462 | ||||
3463 | =head3 C<PrintWarn> (boolean, inherited) | |||
3464 | ||||
3465 | The C<PrintWarn> attribute controls the printing of warnings recorded | |||
3466 | by the driver. When set to a true value the DBI will check method | |||
3467 | calls to see if a warning condition has been set. If so, the DBI | |||
3468 | will effectively do a C<warn("$class $method warning: $DBI::errstr")> | |||
3469 | where C<$class> is the driver class and C<$method> is the name of | |||
3470 | the method which failed. E.g., | |||
3471 | ||||
3472 | DBD::Oracle::db execute warning: ... warning text here ... | |||
3473 | ||||
3474 | By default, C<DBI-E<gt>connect> sets C<PrintWarn> "on" if $^W is true, | |||
3475 | i.e., perl is running with warnings enabled. | |||
3476 | ||||
3477 | If desired, the warnings can be caught and processed using a C<$SIG{__WARN__}> | |||
3478 | handler or modules like CGI::Carp and CGI::ErrorWrap. | |||
3479 | ||||
3480 | See also L</set_err> for how warnings are recorded and L</HandleSetErr> | |||
3481 | for how to influence it. | |||
3482 | ||||
3483 | Fetching the full details of warnings can require an extra round-trip | |||
3484 | to the database server for some drivers. In which case the driver | |||
3485 | may opt to only fetch the full details of warnings if the C<PrintWarn> | |||
3486 | attribute is true. If C<PrintWarn> is false then these drivers should | |||
3487 | still indicate the fact that there were warnings by setting the | |||
3488 | warning string to, for example: "3 warnings". | |||
3489 | ||||
3490 | =head3 C<PrintError> (boolean, inherited) | |||
3491 | ||||
3492 | The C<PrintError> attribute can be used to force errors to generate warnings (using | |||
3493 | C<warn>) in addition to returning error codes in the normal way. When set | |||
3494 | "on", any method which results in an error occuring will cause the DBI to | |||
3495 | effectively do a C<warn("$class $method failed: $DBI::errstr")> where C<$class> | |||
3496 | is the driver class and C<$method> is the name of the method which failed. E.g., | |||
3497 | ||||
3498 | DBD::Oracle::db prepare failed: ... error text here ... | |||
3499 | ||||
3500 | By default, C<DBI-E<gt>connect> sets C<PrintError> "on". | |||
3501 | ||||
3502 | If desired, the warnings can be caught and processed using a C<$SIG{__WARN__}> | |||
3503 | handler or modules like CGI::Carp and CGI::ErrorWrap. | |||
3504 | ||||
3505 | =head3 C<RaiseError> (boolean, inherited) | |||
3506 | ||||
3507 | The C<RaiseError> attribute can be used to force errors to raise exceptions rather | |||
3508 | than simply return error codes in the normal way. It is "off" by default. | |||
3509 | When set "on", any method which results in an error will cause | |||
3510 | the DBI to effectively do a C<die("$class $method failed: $DBI::errstr")>, | |||
3511 | where C<$class> is the driver class and C<$method> is the name of the method | |||
3512 | that failed. E.g., | |||
3513 | ||||
3514 | DBD::Oracle::db prepare failed: ... error text here ... | |||
3515 | ||||
3516 | If you turn C<RaiseError> on then you'd normally turn C<PrintError> off. | |||
3517 | If C<PrintError> is also on, then the C<PrintError> is done first (naturally). | |||
3518 | ||||
3519 | Typically C<RaiseError> is used in conjunction with C<eval { ... }> | |||
3520 | to catch the exception that's been thrown and followed by an | |||
3521 | C<if ($@) { ... }> block to handle the caught exception. | |||
3522 | For example: | |||
3523 | ||||
3524 | eval { | |||
3525 | ... | |||
3526 | $sth->execute(); | |||
3527 | ... | |||
3528 | }; | |||
3529 | if ($@) { | |||
3530 | # $sth->err and $DBI::err will be true if error was from DBI | |||
3531 | warn $@; # print the error | |||
3532 | ... # do whatever you need to deal with the error | |||
3533 | } | |||
3534 | ||||
3535 | In that eval block the $DBI::lasth variable can be useful for | |||
3536 | diagnosis and reporting if you can't be sure which handle triggered | |||
3537 | the error. For example, $DBI::lasth->{Type} and $DBI::lasth->{Statement}. | |||
3538 | ||||
3539 | See also L</Transactions>. | |||
3540 | ||||
3541 | If you want to temporarily turn C<RaiseError> off (inside a library function | |||
3542 | that is likely to fail, for example), the recommended way is like this: | |||
3543 | ||||
3544 | { | |||
3545 | local $h->{RaiseError}; # localize and turn off for this block | |||
3546 | ... | |||
3547 | } | |||
3548 | ||||
3549 | The original value will automatically and reliably be restored by Perl, | |||
3550 | regardless of how the block is exited. | |||
3551 | The same logic applies to other attributes, including C<PrintError>. | |||
3552 | ||||
3553 | =head3 C<HandleError> (code ref, inherited) | |||
3554 | ||||
3555 | The C<HandleError> attribute can be used to provide your own alternative behaviour | |||
3556 | in case of errors. If set to a reference to a subroutine then that | |||
3557 | subroutine is called when an error is detected (at the same point that | |||
3558 | C<RaiseError> and C<PrintError> are handled). | |||
3559 | ||||
3560 | The subroutine is called with three parameters: the error message | |||
3561 | string that C<RaiseError> and C<PrintError> would use, | |||
3562 | the DBI handle being used, and the first value being returned by | |||
3563 | the method that failed (typically undef). | |||
3564 | ||||
3565 | If the subroutine returns a false value then the C<RaiseError> | |||
3566 | and/or C<PrintError> attributes are checked and acted upon as normal. | |||
3567 | ||||
3568 | For example, to C<die> with a full stack trace for any error: | |||
3569 | ||||
3570 | use Carp; | |||
3571 | $h->{HandleError} = sub { confess(shift) }; | |||
3572 | ||||
3573 | Or to turn errors into exceptions: | |||
3574 | ||||
3575 | use Exception; # or your own favourite exception module | |||
3576 | $h->{HandleError} = sub { Exception->new('DBI')->raise($_[0]) }; | |||
3577 | ||||
3578 | It is possible to 'stack' multiple HandleError handlers by using | |||
3579 | closures: | |||
3580 | ||||
3581 | sub your_subroutine { | |||
3582 | my $previous_handler = $h->{HandleError}; | |||
3583 | $h->{HandleError} = sub { | |||
3584 | return 1 if $previous_handler and &$previous_handler(@_); | |||
3585 | ... your code here ... | |||
3586 | }; | |||
3587 | } | |||
3588 | ||||
3589 | Using a C<my> inside a subroutine to store the previous C<HandleError> | |||
3590 | value is important. See L<perlsub> and L<perlref> for more information | |||
3591 | about I<closures>. | |||
3592 | ||||
3593 | It is possible for C<HandleError> to alter the error message that | |||
3594 | will be used by C<RaiseError> and C<PrintError> if it returns false. | |||
3595 | It can do that by altering the value of $_[0]. This example appends | |||
3596 | a stack trace to all errors and, unlike the previous example using | |||
3597 | Carp::confess, this will work C<PrintError> as well as C<RaiseError>: | |||
3598 | ||||
3599 | $h->{HandleError} = sub { $_[0]=Carp::longmess($_[0]); 0; }; | |||
3600 | ||||
3601 | It is also possible for C<HandleError> to hide an error, to a limited | |||
3602 | degree, by using L</set_err> to reset $DBI::err and $DBI::errstr, | |||
3603 | and altering the return value of the failed method. For example: | |||
3604 | ||||
3605 | $h->{HandleError} = sub { | |||
3606 | return 0 unless $_[0] =~ /^\S+ fetchrow_arrayref failed:/; | |||
3607 | return 0 unless $_[1]->err == 1234; # the error to 'hide' | |||
3608 | $h->set_err(undef,undef); # turn off the error | |||
3609 | $_[2] = [ ... ]; # supply alternative return value | |||
3610 | return 1; | |||
3611 | }; | |||
3612 | ||||
3613 | This only works for methods which return a single value and is hard | |||
3614 | to make reliable (avoiding infinite loops, for example) and so isn't | |||
3615 | recommended for general use! If you find a I<good> use for it then | |||
3616 | please let me know. | |||
3617 | ||||
3618 | =head3 C<HandleSetErr> (code ref, inherited) | |||
3619 | ||||
3620 | The C<HandleSetErr> attribute can be used to intercept | |||
3621 | the setting of handle C<err>, C<errstr>, and C<state> values. | |||
3622 | If set to a reference to a subroutine then that subroutine is called | |||
3623 | whenever set_err() is called, typically by the driver or a subclass. | |||
3624 | ||||
3625 | The subroutine is called with five arguments, the first five that | |||
3626 | were passed to set_err(): the handle, the C<err>, C<errstr>, and | |||
3627 | C<state> values being set, and the method name. These can be altered | |||
3628 | by changing the values in the @_ array. The return value affects | |||
3629 | set_err() behaviour, see L</set_err> for details. | |||
3630 | ||||
3631 | It is possible to 'stack' multiple HandleSetErr handlers by using | |||
3632 | closures. See L</HandleError> for an example. | |||
3633 | ||||
3634 | The C<HandleSetErr> and C<HandleError> subroutines differ in subtle | |||
3635 | but significant ways. HandleError is only invoked at the point where | |||
3636 | the DBI is about to return to the application with C<err> set true. | |||
3637 | It's not invoked by the failure of a method that's been called by | |||
3638 | another DBI method. HandleSetErr, on the other hand, is called | |||
3639 | whenever set_err() is called with a defined C<err> value, even if false. | |||
3640 | So it's not just for errors, despite the name, but also warn and info states. | |||
3641 | The set_err() method, and thus HandleSetErr, may be called multiple | |||
3642 | times within a method and is usually invoked from deep within driver code. | |||
3643 | ||||
3644 | In theory a driver can use the return value from HandleSetErr via | |||
3645 | set_err() to decide whether to continue or not. If set_err() returns | |||
3646 | an empty list, indicating that the HandleSetErr code has 'handled' | |||
3647 | the 'error', the driver could then continue instead of failing (if | |||
3648 | that's a reasonable thing to do). This isn't excepted to be | |||
3649 | common and any such cases should be clearly marked in the driver | |||
3650 | documentation and discussed on the dbi-dev mailing list. | |||
3651 | ||||
3652 | The C<HandleSetErr> attribute was added in DBI 1.41. | |||
3653 | ||||
3654 | =head3 C<ErrCount> (unsigned integer) | |||
3655 | ||||
3656 | The C<ErrCount> attribute is incremented whenever the set_err() | |||
3657 | method records an error. It isn't incremented by warnings or | |||
3658 | information states. It is not reset by the DBI at any time. | |||
3659 | ||||
3660 | The C<ErrCount> attribute was added in DBI 1.41. Older drivers may | |||
3661 | not have been updated to use set_err() to record errors and so this | |||
3662 | attribute may not be incremented when using them. | |||
3663 | ||||
3664 | ||||
3665 | =head3 C<ShowErrorStatement> (boolean, inherited) | |||
3666 | ||||
3667 | The C<ShowErrorStatement> attribute can be used to cause the relevant | |||
3668 | Statement text to be appended to the error messages generated by | |||
3669 | the C<RaiseError>, C<PrintError>, and C<PrintWarn> attributes. | |||
3670 | Only applies to errors on statement handles | |||
3671 | plus the prepare(), do(), and the various C<select*()> database handle methods. | |||
3672 | (The exact format of the appended text is subject to change.) | |||
3673 | ||||
3674 | If C<$h-E<gt>{ParamValues}> returns a hash reference of parameter | |||
3675 | (placeholder) values then those are formatted and appended to the | |||
3676 | end of the Statement text in the error message. | |||
3677 | ||||
3678 | =head3 C<TraceLevel> (integer, inherited) | |||
3679 | ||||
3680 | The C<TraceLevel> attribute can be used as an alternative to the | |||
3681 | L</trace> method to set the DBI trace level and trace flags for a | |||
3682 | specific handle. See L</TRACING> for more details. | |||
3683 | ||||
3684 | The C<TraceLevel> attribute is especially useful combined with | |||
3685 | C<local> to alter the trace settings for just a single block of code. | |||
3686 | ||||
3687 | =head3 C<FetchHashKeyName> (string, inherited) | |||
3688 | ||||
3689 | The C<FetchHashKeyName> attribute is used to specify whether the fetchrow_hashref() | |||
3690 | method should perform case conversion on the field names used for | |||
3691 | the hash keys. For historical reasons it defaults to 'C<NAME>' but | |||
3692 | it is recommended to set it to 'C<NAME_lc>' (convert to lower case) | |||
3693 | or 'C<NAME_uc>' (convert to upper case) according to your preference. | |||
3694 | It can only be set for driver and database handles. For statement | |||
3695 | handles the value is frozen when prepare() is called. | |||
3696 | ||||
3697 | ||||
3698 | =head3 C<ChopBlanks> (boolean, inherited) | |||
3699 | ||||
3700 | The C<ChopBlanks> attribute can be used to control the trimming of trailing space | |||
3701 | characters from fixed width character (CHAR) fields. No other field | |||
3702 | types are affected, even where field values have trailing spaces. | |||
3703 | ||||
3704 | The default is false (although it is possible that the default may change). | |||
3705 | Applications that need specific behaviour should set the attribute as | |||
3706 | needed. | |||
3707 | ||||
3708 | Drivers are not required to support this attribute, but any driver which | |||
3709 | does not support it must arrange to return C<undef> as the attribute value. | |||
3710 | ||||
3711 | ||||
3712 | =head3 C<LongReadLen> (unsigned integer, inherited) | |||
3713 | ||||
3714 | The C<LongReadLen> attribute may be used to control the maximum | |||
3715 | length of 'long' type fields (LONG, BLOB, CLOB, MEMO, etc.) which the driver will | |||
3716 | read from the database automatically when it fetches each row of data. | |||
3717 | ||||
3718 | The C<LongReadLen> attribute only relates to fetching and reading | |||
3719 | long values; it is not involved in inserting or updating them. | |||
3720 | ||||
3721 | A value of 0 means not to automatically fetch any long data. | |||
3722 | Drivers may return undef or an empty string for long fields when | |||
3723 | C<LongReadLen> is 0. | |||
3724 | ||||
3725 | The default is typically 0 (zero) or 80 bytes but may vary between drivers. | |||
3726 | Applications fetching long fields should set this value to slightly | |||
3727 | larger than the longest long field value to be fetched. | |||
3728 | ||||
3729 | Some databases return some long types encoded as pairs of hex digits. | |||
3730 | For these types, C<LongReadLen> relates to the underlying data | |||
3731 | length and not the doubled-up length of the encoded string. | |||
3732 | ||||
3733 | Changing the value of C<LongReadLen> for a statement handle after it | |||
3734 | has been C<prepare>'d will typically have no effect, so it's common to | |||
3735 | set C<LongReadLen> on the C<$dbh> before calling C<prepare>. | |||
3736 | ||||
3737 | For most drivers the value used here has a direct effect on the | |||
3738 | memory used by the statement handle while it's active, so don't be | |||
3739 | too generous. If you can't be sure what value to use you could | |||
3740 | execute an extra select statement to determine the longest value. | |||
3741 | For example: | |||
3742 | ||||
3743 | $dbh->{LongReadLen} = $dbh->selectrow_array(qq{ | |||
3744 | SELECT MAX(OCTET_LENGTH(long_column_name)) | |||
3745 | FROM table WHERE ... | |||
3746 | }); | |||
3747 | $sth = $dbh->prepare(qq{ | |||
3748 | SELECT long_column_name, ... FROM table WHERE ... | |||
3749 | }); | |||
3750 | ||||
3751 | You may need to take extra care if the table can be modified between | |||
3752 | the first select and the second being executed. You may also need to | |||
3753 | use a different function if OCTET_LENGTH() does not work for long | |||
3754 | types in your database. For example, for Sybase use DATALENGTH() and | |||
3755 | for Oracle use LENGTHB(). | |||
3756 | ||||
3757 | See also L</LongTruncOk> for information on truncation of long types. | |||
3758 | ||||
3759 | =head3 C<LongTruncOk> (boolean, inherited) | |||
3760 | ||||
3761 | The C<LongTruncOk> attribute may be used to control the effect of | |||
3762 | fetching a long field value which has been truncated (typically | |||
3763 | because it's longer than the value of the C<LongReadLen> attribute). | |||
3764 | ||||
3765 | By default, C<LongTruncOk> is false and so fetching a long value that | |||
3766 | needs to be truncated will cause the fetch to fail. | |||
3767 | (Applications should always be sure to | |||
3768 | check for errors after a fetch loop in case an error, such as a divide | |||
3769 | by zero or long field truncation, caused the fetch to terminate | |||
3770 | prematurely.) | |||
3771 | ||||
3772 | If a fetch fails due to a long field truncation when C<LongTruncOk> is | |||
3773 | false, many drivers will allow you to continue fetching further rows. | |||
3774 | ||||
3775 | See also L</LongReadLen>. | |||
3776 | ||||
3777 | =head3 C<TaintIn> (boolean, inherited) | |||
3778 | ||||
3779 | If the C<TaintIn> attribute is set to a true value I<and> Perl is running in | |||
3780 | taint mode (e.g., started with the C<-T> option), then all the arguments | |||
3781 | to most DBI method calls are checked for being tainted. I<This may change.> | |||
3782 | ||||
3783 | The attribute defaults to off, even if Perl is in taint mode. | |||
3784 | See L<perlsec> for more about taint mode. If Perl is not | |||
3785 | running in taint mode, this attribute has no effect. | |||
3786 | ||||
3787 | When fetching data that you trust you can turn off the TaintIn attribute, | |||
3788 | for that statement handle, for the duration of the fetch loop. | |||
3789 | ||||
3790 | The C<TaintIn> attribute was added in DBI 1.31. | |||
3791 | ||||
3792 | =head3 C<TaintOut> (boolean, inherited) | |||
3793 | ||||
3794 | If the C<TaintOut> attribute is set to a true value I<and> Perl is running in | |||
3795 | taint mode (e.g., started with the C<-T> option), then most data fetched | |||
3796 | from the database is considered tainted. I<This may change.> | |||
3797 | ||||
3798 | The attribute defaults to off, even if Perl is in taint mode. | |||
3799 | See L<perlsec> for more about taint mode. If Perl is not | |||
3800 | running in taint mode, this attribute has no effect. | |||
3801 | ||||
3802 | When fetching data that you trust you can turn off the TaintOut attribute, | |||
3803 | for that statement handle, for the duration of the fetch loop. | |||
3804 | ||||
3805 | Currently only fetched data is tainted. It is possible that the results | |||
3806 | of other DBI method calls, and the value of fetched attributes, may | |||
3807 | also be tainted in future versions. That change may well break your | |||
3808 | applications unless you take great care now. If you use DBI Taint mode, | |||
3809 | please report your experience and any suggestions for changes. | |||
3810 | ||||
3811 | The C<TaintOut> attribute was added in DBI 1.31. | |||
3812 | ||||
3813 | =head3 C<Taint> (boolean, inherited) | |||
3814 | ||||
3815 | The C<Taint> attribute is a shortcut for L</TaintIn> and L</TaintOut> (it is also present | |||
3816 | for backwards compatibility). | |||
3817 | ||||
3818 | Setting this attribute sets both L</TaintIn> and L</TaintOut>, and retrieving | |||
3819 | it returns a true value if and only if L</TaintIn> and L</TaintOut> are | |||
3820 | both set to true values. | |||
3821 | ||||
3822 | =head3 C<Profile> (inherited) | |||
3823 | ||||
3824 | The C<Profile> attribute enables the collection and reporting of method call timing statistics. | |||
3825 | See the L<DBI::Profile> module documentation for I<much> more detail. | |||
3826 | ||||
3827 | The C<Profile> attribute was added in DBI 1.24. | |||
3828 | ||||
3829 | =head3 C<ReadOnly> (boolean, inherited) | |||
3830 | ||||
3831 | An application can set the C<ReadOnly> attribute of a handle to a true value to | |||
3832 | indicate that it will not be attempting to make any changes using that handle | |||
3833 | or any children of it. | |||
3834 | ||||
3835 | Note that the exact definition of 'read only' is rather fuzzy. | |||
3836 | For more details see the documentation for the driver you're using. | |||
3837 | ||||
3838 | If the driver can make the handle truly read-only (by issuing a statement like | |||
3839 | "C<set transaction read only>" as needed, for example) then it should. | |||
3840 | Otherwise the attribute is simply advisory. | |||
3841 | ||||
3842 | A driver can set the C<ReadOnly> attribute itself to indicate that the data it | |||
3843 | is connected to cannot be changed for some reason. | |||
3844 | ||||
3845 | Library modules and proxy drivers can use the attribute to influence their behavior. | |||
3846 | For example, the DBD::Gofer driver considers the C<ReadOnly> attribute when | |||
3847 | making a decison about whether to retry an operation that failed. | |||
3848 | ||||
3849 | The attribute should be set to 1 or 0 (or undef). Other values are reserved. | |||
3850 | ||||
3851 | =head3 C<private_your_module_name_*> | |||
3852 | ||||
3853 | The DBI provides a way to store extra information in a DBI handle as | |||
3854 | "private" attributes. The DBI will allow you to store and retrieve any | |||
3855 | attribute which has a name starting with "C<private_>". | |||
3856 | ||||
3857 | It is I<strongly> recommended that you use just I<one> private | |||
3858 | attribute (e.g., use a hash ref) I<and> give it a long and unambiguous | |||
3859 | name that includes the module or application name that the attribute | |||
3860 | relates to (e.g., "C<private_YourFullModuleName_thingy>"). | |||
3861 | ||||
3862 | Because of the way the Perl tie mechanism works you cannot reliably | |||
3863 | use the C<||=> operator directly to initialise the attribute, like this: | |||
3864 | ||||
3865 | my $foo = $dbh->{private_yourmodname_foo} ||= { ... }; # WRONG | |||
3866 | ||||
3867 | you should use a two step approach like this: | |||
3868 | ||||
3869 | my $foo = $dbh->{private_yourmodname_foo}; | |||
3870 | $foo ||= $dbh->{private_yourmodname_foo} = { ... }; | |||
3871 | ||||
3872 | This attribute is primarily of interest to people sub-classing DBI, | |||
3873 | or for applications to piggy-back extra information onto DBI handles. | |||
3874 | ||||
3875 | =head1 DBI DATABASE HANDLE OBJECTS | |||
3876 | ||||
3877 | This section covers the methods and attributes associated with | |||
3878 | database handles. | |||
3879 | ||||
3880 | =head2 Database Handle Methods | |||
3881 | ||||
3882 | The following methods are specified for DBI database handles: | |||
3883 | ||||
3884 | =head3 C<clone> | |||
3885 | ||||
3886 | $new_dbh = $dbh->clone(); | |||
3887 | $new_dbh = $dbh->clone(\%attr); | |||
3888 | ||||
3889 | The C<clone> method duplicates the $dbh connection by connecting | |||
3890 | with the same parameters ($dsn, $user, $password) as originally used. | |||
3891 | ||||
3892 | The attributes for the cloned connect are the same as those used | |||
3893 | for the original connect, with some other attribute merged over | |||
3894 | them depending on the \%attr parameter. | |||
3895 | ||||
3896 | If \%attr is given then the attributes it contains are merged into | |||
3897 | the original attributes and override any with the same names. | |||
3898 | Effectively the same as doing: | |||
3899 | ||||
3900 | %attribues_used = ( %original_attributes, %attr ); | |||
3901 | ||||
3902 | If \%attr is not given then it defaults to a hash containing all | |||
3903 | the attributes in the attribute cache of $dbh excluding any non-code | |||
3904 | references, plus the main boolean attributes (RaiseError, PrintError, | |||
3905 | AutoCommit, etc.). This behaviour is subject to change. | |||
3906 | ||||
3907 | The clone method can be used even if the database handle is disconnected. | |||
3908 | ||||
3909 | The C<clone> method was added in DBI 1.33. It is very new and likely | |||
3910 | to change. | |||
3911 | ||||
3912 | =head3 C<data_sources> | |||
3913 | ||||
3914 | @ary = $dbh->data_sources(); | |||
3915 | @ary = $dbh->data_sources(\%attr); | |||
3916 | ||||
3917 | Returns a list of data sources (databases) available via the $dbh | |||
3918 | driver's data_sources() method, plus any extra data sources that | |||
3919 | the driver can discover via the connected $dbh. Typically the extra | |||
3920 | data sources are other databases managed by the same server process | |||
3921 | that the $dbh is connected to. | |||
3922 | ||||
3923 | Data sources are returned in a form suitable for passing to the | |||
3924 | L</connect> method (that is, they will include the "C<dbi:$driver:>" prefix). | |||
3925 | ||||
3926 | The data_sources() method, for a $dbh, was added in DBI 1.38. | |||
3927 | ||||
3928 | =head3 C<do> | |||
3929 | ||||
3930 | $rows = $dbh->do($statement) or die $dbh->errstr; | |||
3931 | $rows = $dbh->do($statement, \%attr) or die $dbh->errstr; | |||
3932 | $rows = $dbh->do($statement, \%attr, @bind_values) or die ... | |||
3933 | ||||
3934 | Prepare and execute a single statement. Returns the number of rows | |||
3935 | affected or C<undef> on error. A return value of C<-1> means the | |||
3936 | number of rows is not known, not applicable, or not available. | |||
3937 | ||||
3938 | This method is typically most useful for I<non>-C<SELECT> statements that | |||
3939 | either cannot be prepared in advance (due to a limitation of the | |||
3940 | driver) or do not need to be executed repeatedly. It should not | |||
3941 | be used for C<SELECT> statements because it does not return a statement | |||
3942 | handle (so you can't fetch any data). | |||
3943 | ||||
3944 | The default C<do> method is logically similar to: | |||
3945 | ||||
3946 | sub do { | |||
3947 | my($dbh, $statement, $attr, @bind_values) = @_; | |||
3948 | my $sth = $dbh->prepare($statement, $attr) or return undef; | |||
3949 | $sth->execute(@bind_values) or return undef; | |||
3950 | my $rows = $sth->rows; | |||
3951 | ($rows == 0) ? "0E0" : $rows; # always return true if no error | |||
3952 | } | |||
3953 | ||||
3954 | For example: | |||
3955 | ||||
3956 | my $rows_deleted = $dbh->do(q{ | |||
3957 | DELETE FROM table | |||
3958 | WHERE status = ? | |||
3959 | }, undef, 'DONE') or die $dbh->errstr; | |||
3960 | ||||
3961 | Using placeholders and C<@bind_values> with the C<do> method can be | |||
3962 | useful because it avoids the need to correctly quote any variables | |||
3963 | in the C<$statement>. But if you'll be executing the statement many | |||
3964 | times then it's more efficient to C<prepare> it once and call | |||
3965 | C<execute> many times instead. | |||
3966 | ||||
3967 | The C<q{...}> style quoting used in this example avoids clashing with | |||
3968 | quotes that may be used in the SQL statement. Use the double-quote-like | |||
3969 | C<qq{...}> operator if you want to interpolate variables into the string. | |||
3970 | See L<perlop/"Quote and Quote-like Operators"> for more details. | |||
3971 | ||||
3972 | =head3 C<last_insert_id> | |||
3973 | ||||
3974 | $rv = $dbh->last_insert_id($catalog, $schema, $table, $field); | |||
3975 | $rv = $dbh->last_insert_id($catalog, $schema, $table, $field, \%attr); | |||
3976 | ||||
3977 | Returns a value 'identifying' the row just inserted, if possible. | |||
3978 | Typically this would be a value assigned by the database server | |||
3979 | to a column with an I<auto_increment> or I<serial> type. | |||
3980 | Returns undef if the driver does not support the method or can't | |||
3981 | determine the value. | |||
3982 | ||||
3983 | The $catalog, $schema, $table, and $field parameters may be required | |||
3984 | for some drivers (see below). If you don't know the parameter values | |||
3985 | and your driver does not need them, then use C<undef> for each. | |||
3986 | ||||
3987 | There are several caveats to be aware of with this method if you want | |||
3988 | to use it for portable applications: | |||
3989 | ||||
3990 | B<*> For some drivers the value may only available immediately after | |||
3991 | the insert statement has executed (e.g., mysql, Informix). | |||
3992 | ||||
3993 | B<*> For some drivers the $catalog, $schema, $table, and $field parameters | |||
3994 | are required, for others they are ignored (e.g., mysql). | |||
3995 | ||||
3996 | B<*> Drivers may return an indeterminate value if no insert has | |||
3997 | been performed yet. | |||
3998 | ||||
3999 | B<*> For some drivers the value may only be available if placeholders | |||
4000 | have I<not> been used (e.g., Sybase, MS SQL). In this case the value | |||
4001 | returned would be from the last non-placeholder insert statement. | |||
4002 | ||||
4003 | B<*> Some drivers may need driver-specific hints about how to get | |||
4004 | the value. For example, being told the name of the database 'sequence' | |||
4005 | object that holds the value. Any such hints are passed as driver-specific | |||
4006 | attributes in the \%attr parameter. | |||
4007 | ||||
4008 | B<*> If the underlying database offers nothing better, then some | |||
4009 | drivers may attempt to implement this method by executing | |||
4010 | "C<select max($field) from $table>". Drivers using any approach | |||
4011 | like this should issue a warning if C<AutoCommit> is true because | |||
4012 | it is generally unsafe - another process may have modified the table | |||
4013 | between your insert and the select. For situations where you know | |||
4014 | it is safe, such as when you have locked the table, you can silence | |||
4015 | the warning by passing C<Warn> => 0 in \%attr. | |||
4016 | ||||
4017 | B<*> If no insert has been performed yet, or the last insert failed, | |||
4018 | then the value is implementation defined. | |||
4019 | ||||
4020 | Given all the caveats above, it's clear that this method must be | |||
4021 | used with care. | |||
4022 | ||||
4023 | The C<last_insert_id> method was added in DBI 1.38. | |||
4024 | ||||
4025 | =head3 C<selectrow_array> | |||
4026 | ||||
4027 | @row_ary = $dbh->selectrow_array($statement); | |||
4028 | @row_ary = $dbh->selectrow_array($statement, \%attr); | |||
4029 | @row_ary = $dbh->selectrow_array($statement, \%attr, @bind_values); | |||
4030 | ||||
4031 | This utility method combines L</prepare>, L</execute> and | |||
4032 | L</fetchrow_array> into a single call. If called in a list context, it | |||
4033 | returns the first row of data from the statement. The C<$statement> | |||
4034 | parameter can be a previously prepared statement handle, in which case | |||
4035 | the C<prepare> is skipped. | |||
4036 | ||||
4037 | If any method fails, and L</RaiseError> is not set, C<selectrow_array> | |||
4038 | will return an empty list. | |||
4039 | ||||
4040 | If called in a scalar context for a statement handle that has more | |||
4041 | than one column, it is undefined whether the driver will return | |||
4042 | the value of the first column or the last. So don't do that. | |||
4043 | Also, in a scalar context, an C<undef> is returned if there are no | |||
4044 | more rows or if an error occurred. That C<undef> can't be distinguished | |||
4045 | from an C<undef> returned because the first field value was NULL. | |||
4046 | For these reasons you should exercise some caution if you use | |||
4047 | C<selectrow_array> in a scalar context, or just don't do that. | |||
4048 | ||||
4049 | ||||
4050 | =head3 C<selectrow_arrayref> | |||
4051 | ||||
4052 | $ary_ref = $dbh->selectrow_arrayref($statement); | |||
4053 | $ary_ref = $dbh->selectrow_arrayref($statement, \%attr); | |||
4054 | $ary_ref = $dbh->selectrow_arrayref($statement, \%attr, @bind_values); | |||
4055 | ||||
4056 | This utility method combines L</prepare>, L</execute> and | |||
4057 | L</fetchrow_arrayref> into a single call. It returns the first row of | |||
4058 | data from the statement. The C<$statement> parameter can be a previously | |||
4059 | prepared statement handle, in which case the C<prepare> is skipped. | |||
4060 | ||||
4061 | If any method fails, and L</RaiseError> is not set, C<selectrow_array> | |||
4062 | will return undef. | |||
4063 | ||||
4064 | ||||
4065 | =head3 C<selectrow_hashref> | |||
4066 | ||||
4067 | $hash_ref = $dbh->selectrow_hashref($statement); | |||
4068 | $hash_ref = $dbh->selectrow_hashref($statement, \%attr); | |||
4069 | $hash_ref = $dbh->selectrow_hashref($statement, \%attr, @bind_values); | |||
4070 | ||||
4071 | This utility method combines L</prepare>, L</execute> and | |||
4072 | L</fetchrow_hashref> into a single call. It returns the first row of | |||
4073 | data from the statement. The C<$statement> parameter can be a previously | |||
4074 | prepared statement handle, in which case the C<prepare> is skipped. | |||
4075 | ||||
4076 | If any method fails, and L</RaiseError> is not set, C<selectrow_hashref> | |||
4077 | will return undef. | |||
4078 | ||||
4079 | ||||
4080 | =head3 C<selectall_arrayref> | |||
4081 | ||||
4082 | $ary_ref = $dbh->selectall_arrayref($statement); | |||
4083 | $ary_ref = $dbh->selectall_arrayref($statement, \%attr); | |||
4084 | $ary_ref = $dbh->selectall_arrayref($statement, \%attr, @bind_values); | |||
4085 | ||||
4086 | This utility method combines L</prepare>, L</execute> and | |||
4087 | L</fetchall_arrayref> into a single call. It returns a reference to an | |||
4088 | array containing a reference to an array (or hash, see below) for each row of | |||
4089 | data fetched. | |||
4090 | ||||
4091 | The C<$statement> parameter can be a previously prepared statement handle, | |||
4092 | in which case the C<prepare> is skipped. This is recommended if the | |||
4093 | statement is going to be executed many times. | |||
4094 | ||||
4095 | If L</RaiseError> is not set and any method except C<fetchall_arrayref> | |||
4096 | fails then C<selectall_arrayref> will return C<undef>; if | |||
4097 | C<fetchall_arrayref> fails then it will return with whatever data | |||
4098 | has been fetched thus far. You should check C<$sth-E<gt>err> | |||
4099 | afterwards (or use the C<RaiseError> attribute) to discover if the data is | |||
4100 | complete or was truncated due to an error. | |||
4101 | ||||
4102 | The L</fetchall_arrayref> method called by C<selectall_arrayref> | |||
4103 | supports a $max_rows parameter. You can specify a value for $max_rows | |||
4104 | by including a 'C<MaxRows>' attribute in \%attr. In which case finish() | |||
4105 | is called for you after fetchall_arrayref() returns. | |||
4106 | ||||
4107 | The L</fetchall_arrayref> method called by C<selectall_arrayref> | |||
4108 | also supports a $slice parameter. You can specify a value for $slice by | |||
4109 | including a 'C<Slice>' or 'C<Columns>' attribute in \%attr. The only | |||
4110 | difference between the two is that if C<Slice> is not defined and | |||
4111 | C<Columns> is an array ref, then the array is assumed to contain column | |||
4112 | index values (which count from 1), rather than perl array index values. | |||
4113 | In which case the array is copied and each value decremented before | |||
4114 | passing to C</fetchall_arrayref>. | |||
4115 | ||||
4116 | You may often want to fetch an array of rows where each row is stored as a | |||
4117 | hash. That can be done simple using: | |||
4118 | ||||
4119 | my $emps = $dbh->selectall_arrayref( | |||
4120 | "SELECT ename FROM emp ORDER BY ename", | |||
4121 | { Slice => {} } | |||
4122 | ); | |||
4123 | foreach my $emp ( @$emps ) { | |||
4124 | print "Employee: $emp->{ename}\n"; | |||
4125 | } | |||
4126 | ||||
4127 | Or, to fetch into an array instead of an array ref: | |||
4128 | ||||
4129 | @result = @{ $dbh->selectall_arrayref($sql, { Slice => {} }) }; | |||
4130 | ||||
4131 | See L</fetchall_arrayref> method for more details. | |||
4132 | ||||
4133 | =head3 C<selectall_hashref> | |||
4134 | ||||
4135 | $hash_ref = $dbh->selectall_hashref($statement, $key_field); | |||
4136 | $hash_ref = $dbh->selectall_hashref($statement, $key_field, \%attr); | |||
4137 | $hash_ref = $dbh->selectall_hashref($statement, $key_field, \%attr, @bind_values); | |||
4138 | ||||
4139 | This utility method combines L</prepare>, L</execute> and | |||
4140 | L</fetchall_hashref> into a single call. It returns a reference to a | |||
4141 | hash containing one entry, at most, for each row, as returned by fetchall_hashref(). | |||
4142 | ||||
4143 | The C<$statement> parameter can be a previously prepared statement handle, | |||
4144 | in which case the C<prepare> is skipped. This is recommended if the | |||
4145 | statement is going to be executed many times. | |||
4146 | ||||
4147 | The C<$key_field> parameter defines which column, or columns, are used as keys | |||
4148 | in the returned hash. It can either be the name of a single field, or a | |||
4149 | reference to an array containing multiple field names. Using multiple names | |||
4150 | yields a tree of nested hashes. | |||
4151 | ||||
4152 | If a row has the same key as an earlier row then it replaces the earlier row. | |||
4153 | ||||
4154 | If any method except C<fetchrow_hashref> fails, and L</RaiseError> is not set, | |||
4155 | C<selectall_hashref> will return C<undef>. If C<fetchrow_hashref> fails and | |||
4156 | L</RaiseError> is not set, then it will return with whatever data it | |||
4157 | has fetched thus far. $DBI::err should be checked to catch that. | |||
4158 | ||||
4159 | See fetchall_hashref() for more details. | |||
4160 | ||||
4161 | =head3 C<selectcol_arrayref> | |||
4162 | ||||
4163 | $ary_ref = $dbh->selectcol_arrayref($statement); | |||
4164 | $ary_ref = $dbh->selectcol_arrayref($statement, \%attr); | |||
4165 | $ary_ref = $dbh->selectcol_arrayref($statement, \%attr, @bind_values); | |||
4166 | ||||
4167 | This utility method combines L</prepare>, L</execute>, and fetching one | |||
4168 | column from all the rows, into a single call. It returns a reference to | |||
4169 | an array containing the values of the first column from each row. | |||
4170 | ||||
4171 | The C<$statement> parameter can be a previously prepared statement handle, | |||
4172 | in which case the C<prepare> is skipped. This is recommended if the | |||
4173 | statement is going to be executed many times. | |||
4174 | ||||
4175 | If any method except C<fetch> fails, and L</RaiseError> is not set, | |||
4176 | C<selectcol_arrayref> will return C<undef>. If C<fetch> fails and | |||
4177 | L</RaiseError> is not set, then it will return with whatever data it | |||
4178 | has fetched thus far. $DBI::err should be checked to catch that. | |||
4179 | ||||
4180 | The C<selectcol_arrayref> method defaults to pushing a single column | |||
4181 | value (the first) from each row into the result array. However, it can | |||
4182 | also push another column, or even multiple columns per row, into the | |||
4183 | result array. This behaviour can be specified via a 'C<Columns>' | |||
4184 | attribute which must be a ref to an array containing the column number | |||
4185 | or numbers to use. For example: | |||
4186 | ||||
4187 | # get array of id and name pairs: | |||
4188 | my $ary_ref = $dbh->selectcol_arrayref("select id, name from table", { Columns=>[1,2] }); | |||
4189 | my %hash = @$ary_ref; # build hash from key-value pairs so $hash{$id} => name | |||
4190 | ||||
4191 | You can specify a maximum number of rows to fetch by including a | |||
4192 | 'C<MaxRows>' attribute in \%attr. | |||
4193 | ||||
4194 | =head3 C<prepare> | |||
4195 | ||||
4196 | $sth = $dbh->prepare($statement) or die $dbh->errstr; | |||
4197 | $sth = $dbh->prepare($statement, \%attr) or die $dbh->errstr; | |||
4198 | ||||
4199 | Prepares a statement for later execution by the database | |||
4200 | engine and returns a reference to a statement handle object. | |||
4201 | ||||
4202 | The returned statement handle can be used to get attributes of the | |||
4203 | statement and invoke the L</execute> method. See L</Statement Handle Methods>. | |||
4204 | ||||
4205 | Drivers for engines without the concept of preparing a | |||
4206 | statement will typically just store the statement in the returned | |||
4207 | handle and process it when C<$sth-E<gt>execute> is called. Such drivers are | |||
4208 | unlikely to give much useful information about the | |||
4209 | statement, such as C<$sth-E<gt>{NUM_OF_FIELDS}>, until after C<$sth-E<gt>execute> | |||
4210 | has been called. Portable applications should take this into account. | |||
4211 | ||||
4212 | In general, DBI drivers do not parse the contents of the statement | |||
4213 | (other than simply counting any L</Placeholders>). The statement is | |||
4214 | passed directly to the database engine, sometimes known as pass-thru | |||
4215 | mode. This has advantages and disadvantages. On the plus side, you can | |||
4216 | access all the functionality of the engine being used. On the downside, | |||
4217 | you're limited if you're using a simple engine, and you need to take extra care if | |||
4218 | writing applications intended to be portable between engines. | |||
4219 | ||||
4220 | Portable applications should not assume that a new statement can be | |||
4221 | prepared and/or executed while still fetching results from a previous | |||
4222 | statement. | |||
4223 | ||||
4224 | Some command-line SQL tools use statement terminators, like a semicolon, | |||
4225 | to indicate the end of a statement. Such terminators should not normally | |||
4226 | be used with the DBI. | |||
4227 | ||||
4228 | ||||
4229 | =head3 C<prepare_cached> | |||
4230 | ||||
4231 | $sth = $dbh->prepare_cached($statement) | |||
4232 | $sth = $dbh->prepare_cached($statement, \%attr) | |||
4233 | $sth = $dbh->prepare_cached($statement, \%attr, $if_active) | |||
4234 | ||||
4235 | Like L</prepare> except that the statement handle returned will be | |||
4236 | stored in a hash associated with the C<$dbh>. If another call is made to | |||
4237 | C<prepare_cached> with the same C<$statement> and C<%attr> parameter values, | |||
4238 | then the corresponding cached C<$sth> will be returned without contacting the | |||
4239 | database server. | |||
4240 | ||||
4241 | The C<$if_active> parameter lets you adjust the behaviour if an | |||
4242 | already cached statement handle is still Active. There are several | |||
4243 | alternatives: | |||
4244 | ||||
4245 | =over 4 | |||
4246 | ||||
4247 | =item B<0>: A warning will be generated, and finish() will be called on | |||
4248 | the statement handle before it is returned. This is the default | |||
4249 | behaviour if $if_active is not passed. | |||
4250 | ||||
4251 | =item B<1>: finish() will be called on the statement handle, but the | |||
4252 | warning is suppressed. | |||
4253 | ||||
4254 | =item B<2>: Disables any checking. | |||
4255 | ||||
4256 | =item B<3>: The existing active statement handle will be removed from the | |||
4257 | cache and a new statement handle prepared and cached in its place. | |||
4258 | This is the safest option because it doesn't affect the state of the | |||
4259 | old handle, it just removes it from the cache. [Added in DBI 1.40] | |||
4260 | ||||
4261 | =back | |||
4262 | ||||
4263 | Here are some examples of C<prepare_cached>: | |||
4264 | ||||
4265 | sub insert_hash { | |||
4266 | my ($table, $field_values) = @_; | |||
4267 | # sort to keep field order, and thus sql, stable for prepare_cached | |||
4268 | my @fields = sort keys %$field_values; | |||
4269 | my @values = @{$field_values}{@fields}; | |||
4270 | my $sql = sprintf "insert into %s (%s) values (%s)", | |||
4271 | $table, join(",", @fields), join(",", ("?")x@fields); | |||
4272 | my $sth = $dbh->prepare_cached($sql); | |||
4273 | return $sth->execute(@values); | |||
4274 | } | |||
4275 | ||||
4276 | sub search_hash { | |||
4277 | my ($table, $field_values) = @_; | |||
4278 | # sort to keep field order, and thus sql, stable for prepare_cached | |||
4279 | my @fields = sort keys %$field_values; | |||
4280 | my @values = @{$field_values}{@fields}; | |||
4281 | my $qualifier = ""; | |||
4282 | $qualifier = "where ".join(" and ", map { "$_=?" } @fields) if @fields; | |||
4283 | $sth = $dbh->prepare_cached("SELECT * FROM $table $qualifier"); | |||
4284 | return $dbh->selectall_arrayref($sth, {}, @values); | |||
4285 | } | |||
4286 | ||||
4287 | I<Caveat emptor:> This caching can be useful in some applications, | |||
4288 | but it can also cause problems and should be used with care. Here | |||
4289 | is a contrived case where caching would cause a significant problem: | |||
4290 | ||||
4291 | my $sth = $dbh->prepare_cached('SELECT * FROM foo WHERE bar=?'); | |||
4292 | $sth->execute(...); | |||
4293 | while (my $data = $sth->fetchrow_hashref) { | |||
4294 | ||||
4295 | # later, in some other code called within the loop... | |||
4296 | my $sth2 = $dbh->prepare_cached('SELECT * FROM foo WHERE bar=?'); | |||
4297 | $sth2->execute(...); | |||
4298 | while (my $data2 = $sth2->fetchrow_arrayref) { | |||
4299 | do_stuff(...); | |||
4300 | } | |||
4301 | } | |||
4302 | ||||
4303 | In this example, since both handles are preparing the exact same statement, | |||
4304 | C<$sth2> will not be its own statement handle, but a duplicate of C<$sth> | |||
4305 | returned from the cache. The results will certainly not be what you expect. | |||
4306 | Typically the the inner fetch loop will work normally, fetching all | |||
4307 | the records and terminating when there are no more, but now $sth | |||
4308 | is the same as $sth2 the outer fetch loop will also terminate. | |||
4309 | ||||
4310 | You'll know if you run into this problem because prepare_cached() | |||
4311 | will generate a warning by default (when $if_active is false). | |||
4312 | ||||
4313 | The cache used by prepare_cached() is keyed by both the statement | |||
4314 | and any attributes so you can also avoid this issue by doing something | |||
4315 | like: | |||
4316 | ||||
4317 | $sth = $dbh->prepare_cached("...", { dbi_dummy => __FILE__.__LINE__ }); | |||
4318 | ||||
4319 | which will ensure that prepare_cached only returns statements cached | |||
4320 | by that line of code in that source file. | |||
4321 | ||||
4322 | If you'd like the cache to managed intelligently, you can tie the | |||
4323 | hashref returned by C<CachedKids> to an appropriate caching module, | |||
4324 | such as L<Tie::Cache::LRU>: | |||
4325 | ||||
4326 | my $cache; | |||
4327 | tie %$cache, 'Tie::Cache::LRU', 500; | |||
4328 | $dbh->{CachedKids} = $cache; | |||
4329 | ||||
4330 | =head3 C<commit> | |||
4331 | ||||
4332 | $rc = $dbh->commit or die $dbh->errstr; | |||
4333 | ||||
4334 | Commit (make permanent) the most recent series of database changes | |||
4335 | if the database supports transactions and AutoCommit is off. | |||
4336 | ||||
4337 | If C<AutoCommit> is on, then calling | |||
4338 | C<commit> will issue a "commit ineffective with AutoCommit" warning. | |||
4339 | ||||
4340 | See also L</Transactions> in the L</FURTHER INFORMATION> section below. | |||
4341 | ||||
4342 | =head3 C<rollback> | |||
4343 | ||||
4344 | $rc = $dbh->rollback or die $dbh->errstr; | |||
4345 | ||||
4346 | Rollback (undo) the most recent series of uncommitted database | |||
4347 | changes if the database supports transactions and AutoCommit is off. | |||
4348 | ||||
4349 | If C<AutoCommit> is on, then calling | |||
4350 | C<rollback> will issue a "rollback ineffective with AutoCommit" warning. | |||
4351 | ||||
4352 | See also L</Transactions> in the L</FURTHER INFORMATION> section below. | |||
4353 | ||||
4354 | =head3 C<begin_work> | |||
4355 | ||||
4356 | $rc = $dbh->begin_work or die $dbh->errstr; | |||
4357 | ||||
4358 | Enable transactions (by turning C<AutoCommit> off) until the next call | |||
4359 | to C<commit> or C<rollback>. After the next C<commit> or C<rollback>, | |||
4360 | C<AutoCommit> will automatically be turned on again. | |||
4361 | ||||
4362 | If C<AutoCommit> is already off when C<begin_work> is called then | |||
4363 | it does nothing except return an error. If the driver does not support | |||
4364 | transactions then when C<begin_work> attempts to set C<AutoCommit> off | |||
4365 | the driver will trigger a fatal error. | |||
4366 | ||||
4367 | See also L</Transactions> in the L</FURTHER INFORMATION> section below. | |||
4368 | ||||
4369 | ||||
4370 | =head3 C<disconnect> | |||
4371 | ||||
4372 | $rc = $dbh->disconnect or warn $dbh->errstr; | |||
4373 | ||||
4374 | Disconnects the database from the database handle. C<disconnect> is typically only used | |||
4375 | before exiting the program. The handle is of little use after disconnecting. | |||
4376 | ||||
4377 | The transaction behaviour of the C<disconnect> method is, sadly, | |||
4378 | undefined. Some database systems (such as Oracle and Ingres) will | |||
4379 | automatically commit any outstanding changes, but others (such as | |||
4380 | Informix) will rollback any outstanding changes. Applications not | |||
4381 | using C<AutoCommit> should explicitly call C<commit> or C<rollback> before | |||
4382 | calling C<disconnect>. | |||
4383 | ||||
4384 | The database is automatically disconnected by the C<DESTROY> method if | |||
4385 | still connected when there are no longer any references to the handle. | |||
4386 | The C<DESTROY> method for each driver should implicitly call C<rollback> to | |||
4387 | undo any uncommitted changes. This is vital behaviour to ensure that | |||
4388 | incomplete transactions don't get committed simply because Perl calls | |||
4389 | C<DESTROY> on every object before exiting. Also, do not rely on the order | |||
4390 | of object destruction during "global destruction", as it is undefined. | |||
4391 | ||||
4392 | Generally, if you want your changes to be commited or rolled back when | |||
4393 | you disconnect, then you should explicitly call L</commit> or L</rollback> | |||
4394 | before disconnecting. | |||
4395 | ||||
4396 | If you disconnect from a database while you still have active | |||
4397 | statement handles (e.g., SELECT statement handles that may have | |||
4398 | more data to fetch), you will get a warning. The warning may indicate | |||
4399 | that a fetch loop terminated early, perhaps due to an uncaught error. | |||
4400 | To avoid the warning call the C<finish> method on the active handles. | |||
4401 | ||||
4402 | ||||
4403 | =head3 C<ping> | |||
4404 | ||||
4405 | $rc = $dbh->ping; | |||
4406 | ||||
4407 | Attempts to determine, in a reasonably efficient way, if the database | |||
4408 | server is still running and the connection to it is still working. | |||
4409 | Individual drivers should implement this function in the most suitable | |||
4410 | manner for their database engine. | |||
4411 | ||||
4412 | The current I<default> implementation always returns true without | |||
4413 | actually doing anything. Actually, it returns "C<0 but true>" which is | |||
4414 | true but zero. That way you can tell if the return value is genuine or | |||
4415 | just the default. Drivers should override this method with one that | |||
4416 | does the right thing for their type of database. | |||
4417 | ||||
4418 | Few applications would have direct use for this method. See the specialized | |||
4419 | Apache::DBI module for one example usage. | |||
4420 | ||||
4421 | ||||
4422 | =head3 C<get_info> | |||
4423 | ||||
4424 | $value = $dbh->get_info( $info_type ); | |||
4425 | ||||
4426 | Returns information about the implementation, i.e. driver and data | |||
4427 | source capabilities, restrictions etc. It returns C<undef> for | |||
4428 | unknown or unimplemented information types. For example: | |||
4429 | ||||
4430 | $database_version = $dbh->get_info( 18 ); # SQL_DBMS_VER | |||
4431 | $max_select_tables = $dbh->get_info( 106 ); # SQL_MAXIMUM_TABLES_IN_SELECT | |||
4432 | ||||
4433 | See L</"Standards Reference Information"> for more detailed information | |||
4434 | about the information types and their meanings and possible return values. | |||
4435 | ||||
4436 | The DBI::Const::GetInfoType module exports a %GetInfoType hash that | |||
4437 | can be used to map info type names to numbers. For example: | |||
4438 | ||||
4439 | $database_version = $dbh->get_info( $GetInfoType{SQL_DBMS_VER} ); | |||
4440 | ||||
4441 | The names are a merging of the ANSI and ODBC standards (which differ | |||
4442 | in some cases). See L<DBI::Const::GetInfoType> for more details. | |||
4443 | ||||
4444 | Because some DBI methods make use of get_info(), drivers are strongly | |||
4445 | encouraged to support I<at least> the following very minimal set | |||
4446 | of information types to ensure the DBI itself works properly: | |||
4447 | ||||
4448 | Type Name Example A Example B | |||
4449 | ---- -------------------------- ------------ ---------------- | |||
4450 | 17 SQL_DBMS_NAME 'ACCESS' 'Oracle' | |||
4451 | 18 SQL_DBMS_VER '03.50.0000' '08.01.0721 ...' | |||
4452 | 29 SQL_IDENTIFIER_QUOTE_CHAR '`' '"' | |||
4453 | 41 SQL_CATALOG_NAME_SEPARATOR '.' '@' | |||
4454 | 114 SQL_CATALOG_LOCATION 1 2 | |||
4455 | ||||
4456 | =head3 C<table_info> | |||
4457 | ||||
4458 | $sth = $dbh->table_info( $catalog, $schema, $table, $type ); | |||
4459 | $sth = $dbh->table_info( $catalog, $schema, $table, $type, \%attr ); | |||
4460 | ||||
4461 | # then $sth->fetchall_arrayref or $sth->fetchall_hashref etc | |||
4462 | ||||
4463 | Returns an active statement handle that can be used to fetch | |||
4464 | information about tables and views that exist in the database. | |||
4465 | ||||
4466 | The arguments $catalog, $schema and $table may accept search patterns | |||
4467 | according to the database/driver, for example: $table = '%FOO%'; | |||
4468 | Remember that the underscore character ('C<_>') is a search pattern | |||
4469 | that means match any character, so 'FOO_%' is the same as 'FOO%' | |||
4470 | and 'FOO_BAR%' will match names like 'FOO1BAR'. | |||
4471 | ||||
4472 | The value of $type is a comma-separated list of one or more types of | |||
4473 | tables to be returned in the result set. Each value may optionally be | |||
4474 | quoted, e.g.: | |||
4475 | ||||
4476 | $type = "TABLE"; | |||
4477 | $type = "'TABLE','VIEW'"; | |||
4478 | ||||
4479 | In addition the following special cases may also be supported by some drivers: | |||
4480 | ||||
4481 | =over 4 | |||
4482 | ||||
4483 | =item * | |||
4484 | If the value of $catalog is '%' and $schema and $table name | |||
4485 | are empty strings, the result set contains a list of catalog names. | |||
4486 | For example: | |||
4487 | ||||
4488 | $sth = $dbh->table_info('%', '', ''); | |||
4489 | ||||
4490 | =item * | |||
4491 | If the value of $schema is '%' and $catalog and $table are empty | |||
4492 | strings, the result set contains a list of schema names. | |||
4493 | ||||
4494 | =item * | |||
4495 | If the value of $type is '%' and $catalog, $schema, and $table are all | |||
4496 | empty strings, the result set contains a list of table types. | |||
4497 | ||||
4498 | =back | |||
4499 | ||||
4500 | If your driver doesn't support one or more of the selection filter | |||
4501 | parameters then you may get back more than you asked for and can | |||
4502 | do the filtering yourself. | |||
4503 | ||||
4504 | This method can be expensive, and can return a large amount of data. | |||
4505 | (For example, small Oracle installation returns over 2000 rows.) | |||
4506 | So it's a good idea to use the filters to limit the data as much as possible. | |||
4507 | ||||
4508 | The statement handle returned has at least the following fields in the | |||
4509 | order show below. Other fields, after these, may also be present. | |||
4510 | ||||
4511 | B<TABLE_CAT>: Table catalog identifier. This field is NULL (C<undef>) if not | |||
4512 | applicable to the data source, which is usually the case. This field | |||
4513 | is empty if not applicable to the table. | |||
4514 | ||||
4515 | B<TABLE_SCHEM>: The name of the schema containing the TABLE_NAME value. | |||
4516 | This field is NULL (C<undef>) if not applicable to data source, and | |||
4517 | empty if not applicable to the table. | |||
4518 | ||||
4519 | B<TABLE_NAME>: Name of the table (or view, synonym, etc). | |||
4520 | ||||
4521 | B<TABLE_TYPE>: One of the following: "TABLE", "VIEW", "SYSTEM TABLE", | |||
4522 | "GLOBAL TEMPORARY", "LOCAL TEMPORARY", "ALIAS", "SYNONYM" or a type | |||
4523 | identifier that is specific to the data | |||
4524 | source. | |||
4525 | ||||
4526 | B<REMARKS>: A description of the table. May be NULL (C<undef>). | |||
4527 | ||||
4528 | Note that C<table_info> might not return records for all tables. | |||
4529 | Applications can use any valid table regardless of whether it's | |||
4530 | returned by C<table_info>. | |||
4531 | ||||
4532 | See also L</tables>, L</"Catalog Methods"> and | |||
4533 | L</"Standards Reference Information">. | |||
4534 | ||||
4535 | =head3 C<column_info> | |||
4536 | ||||
4537 | $sth = $dbh->column_info( $catalog, $schema, $table, $column ); | |||
4538 | ||||
4539 | # then $sth->fetchall_arrayref or $sth->fetchall_hashref etc | |||
4540 | ||||
4541 | Returns an active statement handle that can be used to fetch | |||
4542 | information about columns in specified tables. | |||
4543 | ||||
4544 | The arguments $schema, $table and $column may accept search patterns | |||
4545 | according to the database/driver, for example: $table = '%FOO%'; | |||
4546 | ||||
4547 | Note: The support for the selection criteria is driver specific. If the | |||
4548 | driver doesn't support one or more of them then you may get back more | |||
4549 | than you asked for and can do the filtering yourself. | |||
4550 | ||||
4551 | If the arguments don't match any tables then you'll still get a statement | |||
4552 | handle, it'll just return no rows. | |||
4553 | ||||
4554 | The statement handle returned has at least the following fields in the | |||
4555 | order shown below. Other fields, after these, may also be present. | |||
4556 | ||||
4557 | B<TABLE_CAT>: The catalog identifier. | |||
4558 | This field is NULL (C<undef>) if not applicable to the data source, | |||
4559 | which is often the case. This field is empty if not applicable to the | |||
4560 | table. | |||
4561 | ||||
4562 | B<TABLE_SCHEM>: The schema identifier. | |||
4563 | This field is NULL (C<undef>) if not applicable to the data source, | |||
4564 | and empty if not applicable to the table. | |||
4565 | ||||
4566 | B<TABLE_NAME>: The table identifier. | |||
4567 | Note: A driver may provide column metadata not only for base tables, but | |||
4568 | also for derived objects like SYNONYMS etc. | |||
4569 | ||||
4570 | B<COLUMN_NAME>: The column identifier. | |||
4571 | ||||
4572 | B<DATA_TYPE>: The concise data type code. | |||
4573 | ||||
4574 | B<TYPE_NAME>: A data source dependent data type name. | |||
4575 | ||||
4576 | B<COLUMN_SIZE>: The column size. | |||
4577 | This is the maximum length in characters for character data types, | |||
4578 | the number of digits or bits for numeric data types or the length | |||
4579 | in the representation of temporal types. | |||
4580 | See the relevant specifications for detailed information. | |||
4581 | ||||
4582 | B<BUFFER_LENGTH>: The length in bytes of transferred data. | |||
4583 | ||||
4584 | B<DECIMAL_DIGITS>: The total number of significant digits to the right of | |||
4585 | the decimal point. | |||
4586 | ||||
4587 | B<NUM_PREC_RADIX>: The radix for numeric precision. | |||
4588 | The value is 10 or 2 for numeric data types and NULL (C<undef>) if not | |||
4589 | applicable. | |||
4590 | ||||
4591 | B<NULLABLE>: Indicates if a column can accept NULLs. | |||
4592 | The following values are defined: | |||
4593 | ||||
4594 | SQL_NO_NULLS 0 | |||
4595 | SQL_NULLABLE 1 | |||
4596 | SQL_NULLABLE_UNKNOWN 2 | |||
4597 | ||||
4598 | B<REMARKS>: A description of the column. | |||
4599 | ||||
4600 | B<COLUMN_DEF>: The default value of the column. | |||
4601 | ||||
4602 | B<SQL_DATA_TYPE>: The SQL data type. | |||
4603 | ||||
4604 | B<SQL_DATETIME_SUB>: The subtype code for datetime and interval data types. | |||
4605 | ||||
4606 | B<CHAR_OCTET_LENGTH>: The maximum length in bytes of a character or binary | |||
4607 | data type column. | |||
4608 | ||||
4609 | B<ORDINAL_POSITION>: The column sequence number (starting with 1). | |||
4610 | ||||
4611 | B<IS_NULLABLE>: Indicates if the column can accept NULLs. | |||
4612 | Possible values are: 'NO', 'YES' and ''. | |||
4613 | ||||
4614 | SQL/CLI defines the following additional columns: | |||
4615 | ||||
4616 | CHAR_SET_CAT | |||
4617 | CHAR_SET_SCHEM | |||
4618 | CHAR_SET_NAME | |||
4619 | COLLATION_CAT | |||
4620 | COLLATION_SCHEM | |||
4621 | COLLATION_NAME | |||
4622 | UDT_CAT | |||
4623 | UDT_SCHEM | |||
4624 | UDT_NAME | |||
4625 | DOMAIN_CAT | |||
4626 | DOMAIN_SCHEM | |||
4627 | DOMAIN_NAME | |||
4628 | SCOPE_CAT | |||
4629 | SCOPE_SCHEM | |||
4630 | SCOPE_NAME | |||
4631 | MAX_CARDINALITY | |||
4632 | DTD_IDENTIFIER | |||
4633 | IS_SELF_REF | |||
4634 | ||||
4635 | Drivers capable of supplying any of those values should do so in | |||
4636 | the corresponding column and supply undef values for the others. | |||
4637 | ||||
4638 | Drivers wishing to provide extra database/driver specific information | |||
4639 | should do so in extra columns beyond all those listed above, and | |||
4640 | use lowercase field names with the driver-specific prefix (i.e., | |||
4641 | 'ora_...'). Applications accessing such fields should do so by name | |||
4642 | and not by column number. | |||
4643 | ||||
4644 | The result set is ordered by TABLE_CAT, TABLE_SCHEM, TABLE_NAME | |||
4645 | and ORDINAL_POSITION. | |||
4646 | ||||
4647 | Note: There is some overlap with statement attributes (in perl) and | |||
4648 | SQLDescribeCol (in ODBC). However, SQLColumns provides more metadata. | |||
4649 | ||||
4650 | See also L</"Catalog Methods"> and L</"Standards Reference Information">. | |||
4651 | ||||
4652 | =head3 C<primary_key_info> | |||
4653 | ||||
4654 | $sth = $dbh->primary_key_info( $catalog, $schema, $table ); | |||
4655 | ||||
4656 | # then $sth->fetchall_arrayref or $sth->fetchall_hashref etc | |||
4657 | ||||
4658 | Returns an active statement handle that can be used to fetch information | |||
4659 | about columns that make up the primary key for a table. | |||
4660 | The arguments don't accept search patterns (unlike table_info()). | |||
4661 | ||||
4662 | The statement handle will return one row per column, ordered by | |||
4663 | TABLE_CAT, TABLE_SCHEM, TABLE_NAME, and KEY_SEQ. | |||
4664 | If there is no primary key then the statement handle will fetch no rows. | |||
4665 | ||||
4666 | Note: The support for the selection criteria, such as $catalog, is | |||
4667 | driver specific. If the driver doesn't support catalogs and/or | |||
4668 | schemas, it may ignore these criteria. | |||
4669 | ||||
4670 | The statement handle returned has at least the following fields in the | |||
4671 | order shown below. Other fields, after these, may also be present. | |||
4672 | ||||
4673 | B<TABLE_CAT>: The catalog identifier. | |||
4674 | This field is NULL (C<undef>) if not applicable to the data source, | |||
4675 | which is often the case. This field is empty if not applicable to the | |||
4676 | table. | |||
4677 | ||||
4678 | B<TABLE_SCHEM>: The schema identifier. | |||
4679 | This field is NULL (C<undef>) if not applicable to the data source, | |||
4680 | and empty if not applicable to the table. | |||
4681 | ||||
4682 | B<TABLE_NAME>: The table identifier. | |||
4683 | ||||
4684 | B<COLUMN_NAME>: The column identifier. | |||
4685 | ||||
4686 | B<KEY_SEQ>: The column sequence number (starting with 1). | |||
4687 | Note: This field is named B<ORDINAL_POSITION> in SQL/CLI. | |||
4688 | ||||
4689 | B<PK_NAME>: The primary key constraint identifier. | |||
4690 | This field is NULL (C<undef>) if not applicable to the data source. | |||
4691 | ||||
4692 | See also L</"Catalog Methods"> and L</"Standards Reference Information">. | |||
4693 | ||||
4694 | =head3 C<primary_key> | |||
4695 | ||||
4696 | @key_column_names = $dbh->primary_key( $catalog, $schema, $table ); | |||
4697 | ||||
4698 | Simple interface to the primary_key_info() method. Returns a list of | |||
4699 | the column names that comprise the primary key of the specified table. | |||
4700 | The list is in primary key column sequence order. | |||
4701 | If there is no primary key then an empty list is returned. | |||
4702 | ||||
4703 | =head3 C<foreign_key_info> | |||
4704 | ||||
4705 | $sth = $dbh->foreign_key_info( $pk_catalog, $pk_schema, $pk_table | |||
4706 | , $fk_catalog, $fk_schema, $fk_table ); | |||
4707 | ||||
4708 | $sth = $dbh->foreign_key_info( $pk_catalog, $pk_schema, $pk_table | |||
4709 | , $fk_catalog, $fk_schema, $fk_table | |||
4710 | , \%attr ); | |||
4711 | ||||
4712 | # then $sth->fetchall_arrayref or $sth->fetchall_hashref etc | |||
4713 | ||||
4714 | Returns an active statement handle that can be used to fetch information | |||
4715 | about foreign keys in and/or referencing the specified table(s). | |||
4716 | The arguments don't accept search patterns (unlike table_info()). | |||
4717 | ||||
4718 | C<$pk_catalog>, C<$pk_schema>, C<$pk_table> | |||
4719 | identify the primary (unique) key table (B<PKT>). | |||
4720 | ||||
4721 | C<$fk_catalog>, C<$fk_schema>, C<$fk_table> | |||
4722 | identify the foreign key table (B<FKT>). | |||
4723 | ||||
4724 | If both B<PKT> and B<FKT> are given, the function returns the foreign key, if | |||
4725 | any, in table B<FKT> that refers to the primary (unique) key of table B<PKT>. | |||
4726 | (Note: In SQL/CLI, the result is implementation-defined.) | |||
4727 | ||||
4728 | If only B<PKT> is given, then the result set contains the primary key | |||
4729 | of that table and all foreign keys that refer to it. | |||
4730 | ||||
4731 | If only B<FKT> is given, then the result set contains all foreign keys | |||
4732 | in that table and the primary keys to which they refer. | |||
4733 | (Note: In SQL/CLI, the result includes unique keys too.) | |||
4734 | ||||
4735 | For example: | |||
4736 | ||||
4737 | $sth = $dbh->foreign_key_info( undef, $user, 'master'); | |||
4738 | $sth = $dbh->foreign_key_info( undef, undef, undef , undef, $user, 'detail'); | |||
4739 | $sth = $dbh->foreign_key_info( undef, $user, 'master', undef, $user, 'detail'); | |||
4740 | ||||
4741 | # then $sth->fetchall_arrayref or $sth->fetchall_hashref etc | |||
4742 | ||||
4743 | Note: The support for the selection criteria, such as C<$catalog>, is | |||
4744 | driver specific. If the driver doesn't support catalogs and/or | |||
4745 | schemas, it may ignore these criteria. | |||
4746 | ||||
4747 | The statement handle returned has the following fields in the order shown below. | |||
4748 | Because ODBC never includes unique keys, they define different columns in the | |||
4749 | result set than SQL/CLI. SQL/CLI column names are shown in parentheses. | |||
4750 | ||||
4751 | B<PKTABLE_CAT ( UK_TABLE_CAT )>: | |||
4752 | The primary (unique) key table catalog identifier. | |||
4753 | This field is NULL (C<undef>) if not applicable to the data source, | |||
4754 | which is often the case. This field is empty if not applicable to the | |||
4755 | table. | |||
4756 | ||||
4757 | B<PKTABLE_SCHEM ( UK_TABLE_SCHEM )>: | |||
4758 | The primary (unique) key table schema identifier. | |||
4759 | This field is NULL (C<undef>) if not applicable to the data source, | |||
4760 | and empty if not applicable to the table. | |||
4761 | ||||
4762 | B<PKTABLE_NAME ( UK_TABLE_NAME )>: | |||
4763 | The primary (unique) key table identifier. | |||
4764 | ||||
4765 | B<PKCOLUMN_NAME (UK_COLUMN_NAME )>: | |||
4766 | The primary (unique) key column identifier. | |||
4767 | ||||
4768 | B<FKTABLE_CAT ( FK_TABLE_CAT )>: | |||
4769 | The foreign key table catalog identifier. | |||
4770 | This field is NULL (C<undef>) if not applicable to the data source, | |||
4771 | which is often the case. This field is empty if not applicable to the | |||
4772 | table. | |||
4773 | ||||
4774 | B<FKTABLE_SCHEM ( FK_TABLE_SCHEM )>: | |||
4775 | The foreign key table schema identifier. | |||
4776 | This field is NULL (C<undef>) if not applicable to the data source, | |||
4777 | and empty if not applicable to the table. | |||
4778 | ||||
4779 | B<FKTABLE_NAME ( FK_TABLE_NAME )>: | |||
4780 | The foreign key table identifier. | |||
4781 | ||||
4782 | B<FKCOLUMN_NAME ( FK_COLUMN_NAME )>: | |||
4783 | The foreign key column identifier. | |||
4784 | ||||
4785 | B<KEY_SEQ ( ORDINAL_POSITION )>: | |||
4786 | The column sequence number (starting with 1). | |||
4787 | ||||
4788 | B<UPDATE_RULE ( UPDATE_RULE )>: | |||
4789 | The referential action for the UPDATE rule. | |||
4790 | The following codes are defined: | |||
4791 | ||||
4792 | CASCADE 0 | |||
4793 | RESTRICT 1 | |||
4794 | SET NULL 2 | |||
4795 | NO ACTION 3 | |||
4796 | SET DEFAULT 4 | |||
4797 | ||||
4798 | B<DELETE_RULE ( DELETE_RULE )>: | |||
4799 | The referential action for the DELETE rule. | |||
4800 | The codes are the same as for UPDATE_RULE. | |||
4801 | ||||
4802 | B<FK_NAME ( FK_NAME )>: | |||
4803 | The foreign key name. | |||
4804 | ||||
4805 | B<PK_NAME ( UK_NAME )>: | |||
4806 | The primary (unique) key name. | |||
4807 | ||||
4808 | B<DEFERRABILITY ( DEFERABILITY )>: | |||
4809 | The deferrability of the foreign key constraint. | |||
4810 | The following codes are defined: | |||
4811 | ||||
4812 | INITIALLY DEFERRED 5 | |||
4813 | INITIALLY IMMEDIATE 6 | |||
4814 | NOT DEFERRABLE 7 | |||
4815 | ||||
4816 | B< ( UNIQUE_OR_PRIMARY )>: | |||
4817 | This column is necessary if a driver includes all candidate (i.e. primary and | |||
4818 | alternate) keys in the result set (as specified by SQL/CLI). | |||
4819 | The value of this column is UNIQUE if the foreign key references an alternate | |||
4820 | key and PRIMARY if the foreign key references a primary key, or it | |||
4821 | may be undefined if the driver doesn't have access to the information. | |||
4822 | ||||
4823 | See also L</"Catalog Methods"> and L</"Standards Reference Information">. | |||
4824 | ||||
4825 | =head3 C<statistics_info> | |||
4826 | ||||
4827 | B<Warning:> This method is experimental and may change. | |||
4828 | ||||
4829 | $sth = $dbh->statistics_info( $catalog, $schema, $table, $unique_only, $quick ); | |||
4830 | ||||
4831 | # then $sth->fetchall_arrayref or $sth->fetchall_hashref etc | |||
4832 | ||||
4833 | Returns an active statement handle that can be used to fetch statistical | |||
4834 | information about a table and its indexes. | |||
4835 | ||||
4836 | The arguments don't accept search patterns (unlike L</table_info>). | |||
4837 | ||||
4838 | If the boolean argument $unique_only is true, only UNIQUE indexes will be | |||
4839 | returned in the result set, otherwise all indexes will be returned. | |||
4840 | ||||
4841 | If the boolean argument $quick is set, the actual statistical information | |||
4842 | columns (CARDINALITY and PAGES) will only be returned if they are readily | |||
4843 | available from the server, and might not be current. Some databases may | |||
4844 | return stale statistics or no statistics at all with this flag set. | |||
4845 | ||||
4846 | The statement handle will return at most one row per column name per index, | |||
4847 | plus at most one row for the entire table itself, ordered by NON_UNIQUE, TYPE, | |||
4848 | INDEX_QUALIFIER, INDEX_NAME, and ORDINAL_POSITION. | |||
4849 | ||||
4850 | Note: The support for the selection criteria, such as $catalog, is | |||
4851 | driver specific. If the driver doesn't support catalogs and/or | |||
4852 | schemas, it may ignore these criteria. | |||
4853 | ||||
4854 | The statement handle returned has at least the following fields in the | |||
4855 | order shown below. Other fields, after these, may also be present. | |||
4856 | ||||
4857 | B<TABLE_CAT>: The catalog identifier. | |||
4858 | This field is NULL (C<undef>) if not applicable to the data source, | |||
4859 | which is often the case. This field is empty if not applicable to the | |||
4860 | table. | |||
4861 | ||||
4862 | B<TABLE_SCHEM>: The schema identifier. | |||
4863 | This field is NULL (C<undef>) if not applicable to the data source, | |||
4864 | and empty if not applicable to the table. | |||
4865 | ||||
4866 | B<TABLE_NAME>: The table identifier. | |||
4867 | ||||
4868 | B<NON_UNIQUE>: Unique index indicator. | |||
4869 | Returns 0 for unique indexes, 1 for non-unique indexes | |||
4870 | ||||
4871 | B<INDEX_QUALIFIER>: Index qualifier identifier. | |||
4872 | The identifier that is used to qualify the index name when doing a | |||
4873 | C<DROP INDEX>; NULL (C<undef>) is returned if an index qualifier is not | |||
4874 | supported by the data source. | |||
4875 | If a non-NULL (defined) value is returned in this column, it must be used | |||
4876 | to qualify the index name on a C<DROP INDEX> statement; otherwise, | |||
4877 | the TABLE_SCHEM should be used to qualify the index name. | |||
4878 | ||||
4879 | B<INDEX_NAME>: The index identifier. | |||
4880 | ||||
4881 | B<TYPE>: The type of information being returned. Can be any of the | |||
4882 | following values: 'table', 'btree', 'clustered', 'content', 'hashed', | |||
4883 | or 'other'. | |||
4884 | ||||
4885 | In the case that this field is 'table', all fields | |||
4886 | other than TABLE_CAT, TABLE_SCHEM, TABLE_NAME, TYPE, | |||
4887 | CARDINALITY, and PAGES will be NULL (C<undef>). | |||
4888 | ||||
4889 | B<ORDINAL_POSITION>: Column sequence number (starting with 1). | |||
4890 | ||||
4891 | B<COLUMN_NAME>: The column identifier. | |||
4892 | ||||
4893 | B<ASC_OR_DESC>: Column sort sequence. | |||
4894 | C<A> for Ascending, C<D> for Descending, or NULL (C<undef>) if | |||
4895 | not supported for this index. | |||
4896 | ||||
4897 | B<CARDINALITY>: Cardinality of the table or index. | |||
4898 | For indexes, this is the number of unique values in the index. | |||
4899 | For tables, this is the number of rows in the table. | |||
4900 | If not supported, the value will be NULL (C<undef>). | |||
4901 | ||||
4902 | B<PAGES>: Number of storage pages used by this table or index. | |||
4903 | If not supported, the value will be NULL (C<undef>). | |||
4904 | ||||
4905 | B<FILTER_CONDITION>: The index filter condition as a string. | |||
4906 | If the index is not a filtered index, or it cannot be determined | |||
4907 | whether the index is a filtered index, this value is NULL (C<undef>). | |||
4908 | If the index is a filtered index, but the filter condition | |||
4909 | cannot be determined, this value is the empty string C<''>. | |||
4910 | Otherwise it will be the literal filter condition as a string, | |||
4911 | such as C<SALARY <= 4500>. | |||
4912 | ||||
4913 | See also L</"Catalog Methods"> and L</"Standards Reference Information">. | |||
4914 | ||||
4915 | =head3 C<tables> | |||
4916 | ||||
4917 | @names = $dbh->tables( $catalog, $schema, $table, $type ); | |||
4918 | @names = $dbh->tables; # deprecated | |||
4919 | ||||
4920 | Simple interface to table_info(). Returns a list of matching | |||
4921 | table names, possibly including a catalog/schema prefix. | |||
4922 | ||||
4923 | See L</table_info> for a description of the parameters. | |||
4924 | ||||
4925 | If C<$dbh-E<gt>get_info(29)> returns true (29 is SQL_IDENTIFIER_QUOTE_CHAR) | |||
4926 | then the table names are constructed and quoted by L</quote_identifier> | |||
4927 | to ensure they are usable even if they contain whitespace or reserved | |||
4928 | words etc. This means that the table names returned will include | |||
4929 | quote characters. | |||
4930 | ||||
4931 | =head3 C<type_info_all> | |||
4932 | ||||
4933 | $type_info_all = $dbh->type_info_all; | |||
4934 | ||||
4935 | Returns a reference to an array which holds information about each data | |||
4936 | type variant supported by the database and driver. The array and its | |||
4937 | contents should be treated as read-only. | |||
4938 | ||||
4939 | The first item is a reference to an 'index' hash of C<Name =>E<gt> C<Index> pairs. | |||
4940 | The items following that are references to arrays, one per supported data | |||
4941 | type variant. The leading index hash defines the names and order of the | |||
4942 | fields within the arrays that follow it. | |||
4943 | For example: | |||
4944 | ||||
4945 | $type_info_all = [ | |||
4946 | { TYPE_NAME => 0, | |||
4947 | DATA_TYPE => 1, | |||
4948 | COLUMN_SIZE => 2, # was PRECISION originally | |||
4949 | LITERAL_PREFIX => 3, | |||
4950 | LITERAL_SUFFIX => 4, | |||
4951 | CREATE_PARAMS => 5, | |||
4952 | NULLABLE => 6, | |||
4953 | CASE_SENSITIVE => 7, | |||
4954 | SEARCHABLE => 8, | |||
4955 | UNSIGNED_ATTRIBUTE=> 9, | |||
4956 | FIXED_PREC_SCALE => 10, # was MONEY originally | |||
4957 | AUTO_UNIQUE_VALUE => 11, # was AUTO_INCREMENT originally | |||
4958 | LOCAL_TYPE_NAME => 12, | |||
4959 | MINIMUM_SCALE => 13, | |||
4960 | MAXIMUM_SCALE => 14, | |||
4961 | SQL_DATA_TYPE => 15, | |||
4962 | SQL_DATETIME_SUB => 16, | |||
4963 | NUM_PREC_RADIX => 17, | |||
4964 | INTERVAL_PRECISION=> 18, | |||
4965 | }, | |||
4966 | [ 'VARCHAR', SQL_VARCHAR, | |||
4967 | undef, "'","'", undef,0, 1,1,0,0,0,undef,1,255, undef | |||
4968 | ], | |||
4969 | [ 'INTEGER', SQL_INTEGER, | |||
4970 | undef, "", "", undef,0, 0,1,0,0,0,undef,0, 0, 10 | |||
4971 | ], | |||
4972 | ]; | |||
4973 | ||||
4974 | More than one row may have the same value in the C<DATA_TYPE> | |||
4975 | field if there are different ways to spell the type name and/or there | |||
4976 | are variants of the type with different attributes (e.g., with and | |||
4977 | without C<AUTO_UNIQUE_VALUE> set, with and without C<UNSIGNED_ATTRIBUTE>, etc). | |||
4978 | ||||
4979 | The rows are ordered by C<DATA_TYPE> first and then by how closely each | |||
4980 | type maps to the corresponding ODBC SQL data type, closest first. | |||
4981 | ||||
4982 | The meaning of the fields is described in the documentation for | |||
4983 | the L</type_info> method. | |||
4984 | ||||
4985 | An 'index' hash is provided so you don't need to rely on index | |||
4986 | values defined above. However, using DBD::ODBC with some old ODBC | |||
4987 | drivers may return older names, shown as comments in the example above. | |||
4988 | Another issue with the index hash is that the lettercase of the | |||
4989 | keys is not defined. It is usually uppercase, as show here, but | |||
4990 | drivers may return names with any lettercase. | |||
4991 | ||||
4992 | Drivers are also free to return extra driver-specific columns of | |||
4993 | information - though it's recommended that they start at column | |||
4994 | index 50 to leave room for expansion of the DBI/ODBC specification. | |||
4995 | ||||
4996 | The type_info_all() method is not normally used directly. | |||
4997 | The L</type_info> method provides a more usable and useful interface | |||
4998 | to the data. | |||
4999 | ||||
5000 | =head3 C<type_info> | |||
5001 | ||||
5002 | @type_info = $dbh->type_info($data_type); | |||
5003 | ||||
5004 | Returns a list of hash references holding information about one or more | |||
5005 | variants of $data_type. The list is ordered by C<DATA_TYPE> first and | |||
5006 | then by how closely each type maps to the corresponding ODBC SQL data | |||
5007 | type, closest first. If called in a scalar context then only the first | |||
5008 | (best) element is returned. | |||
5009 | ||||
5010 | If $data_type is undefined or C<SQL_ALL_TYPES>, then the list will | |||
5011 | contain hashes for all data type variants supported by the database and driver. | |||
5012 | ||||
5013 | If $data_type is an array reference then C<type_info> returns the | |||
5014 | information for the I<first> type in the array that has any matches. | |||
5015 | ||||
5016 | The keys of the hash follow the same letter case conventions as the | |||
5017 | rest of the DBI (see L</Naming Conventions and Name Space>). The | |||
5018 | following uppercase items should always exist, though may be undef: | |||
5019 | ||||
5020 | =over 4 | |||
5021 | ||||
5022 | =item TYPE_NAME (string) | |||
5023 | ||||
5024 | Data type name for use in CREATE TABLE statements etc. | |||
5025 | ||||
5026 | =item DATA_TYPE (integer) | |||
5027 | ||||
5028 | SQL data type number. | |||
5029 | ||||
5030 | =item COLUMN_SIZE (integer) | |||
5031 | ||||
5032 | For numeric types, this is either the total number of digits (if the | |||
5033 | NUM_PREC_RADIX value is 10) or the total number of bits allowed in the | |||
5034 | column (if NUM_PREC_RADIX is 2). | |||
5035 | ||||
5036 | For string types, this is the maximum size of the string in characters. | |||
5037 | ||||
5038 | For date and interval types, this is the maximum number of characters | |||
5039 | needed to display the value. | |||
5040 | ||||
5041 | =item LITERAL_PREFIX (string) | |||
5042 | ||||
5043 | Characters used to prefix a literal. A typical prefix is "C<'>" for characters, | |||
5044 | or possibly "C<0x>" for binary values passed as hexadecimal. NULL (C<undef>) is | |||
5045 | returned for data types for which this is not applicable. | |||
5046 | ||||
5047 | ||||
5048 | =item LITERAL_SUFFIX (string) | |||
5049 | ||||
5050 | Characters used to suffix a literal. Typically "C<'>" for characters. | |||
5051 | NULL (C<undef>) is returned for data types where this is not applicable. | |||
5052 | ||||
5053 | =item CREATE_PARAMS (string) | |||
5054 | ||||
5055 | Parameter names for data type definition. For example, C<CREATE_PARAMS> for a | |||
5056 | C<DECIMAL> would be "C<precision,scale>" if the DECIMAL type should be | |||
5057 | declared as C<DECIMAL(>I<precision,scale>C<)> where I<precision> and I<scale> | |||
5058 | are integer values. For a C<VARCHAR> it would be "C<max length>". | |||
5059 | NULL (C<undef>) is returned for data types for which this is not applicable. | |||
5060 | ||||
5061 | =item NULLABLE (integer) | |||
5062 | ||||
5063 | Indicates whether the data type accepts a NULL value: | |||
5064 | C<0> or an empty string = no, C<1> = yes, C<2> = unknown. | |||
5065 | ||||
5066 | =item CASE_SENSITIVE (boolean) | |||
5067 | ||||
5068 | Indicates whether the data type is case sensitive in collations and | |||
5069 | comparisons. | |||
5070 | ||||
5071 | =item SEARCHABLE (integer) | |||
5072 | ||||
5073 | Indicates how the data type can be used in a WHERE clause, as | |||
5074 | follows: | |||
5075 | ||||
5076 | 0 - Cannot be used in a WHERE clause | |||
5077 | 1 - Only with a LIKE predicate | |||
5078 | 2 - All comparison operators except LIKE | |||
5079 | 3 - Can be used in a WHERE clause with any comparison operator | |||
5080 | ||||
5081 | =item UNSIGNED_ATTRIBUTE (boolean) | |||
5082 | ||||
5083 | Indicates whether the data type is unsigned. NULL (C<undef>) is returned | |||
5084 | for data types for which this is not applicable. | |||
5085 | ||||
5086 | =item FIXED_PREC_SCALE (boolean) | |||
5087 | ||||
5088 | Indicates whether the data type always has the same precision and scale | |||
5089 | (such as a money type). NULL (C<undef>) is returned for data types | |||
5090 | for which | |||
5091 | this is not applicable. | |||
5092 | ||||
5093 | =item AUTO_UNIQUE_VALUE (boolean) | |||
5094 | ||||
5095 | Indicates whether a column of this data type is automatically set to a | |||
5096 | unique value whenever a new row is inserted. NULL (C<undef>) is returned | |||
5097 | for data types for which this is not applicable. | |||
5098 | ||||
5099 | =item LOCAL_TYPE_NAME (string) | |||
5100 | ||||
5101 | Localized version of the C<TYPE_NAME> for use in dialog with users. | |||
5102 | NULL (C<undef>) is returned if a localized name is not available (in which | |||
5103 | case C<TYPE_NAME> should be used). | |||
5104 | ||||
5105 | =item MINIMUM_SCALE (integer) | |||
5106 | ||||
5107 | The minimum scale of the data type. If a data type has a fixed scale, | |||
5108 | then C<MAXIMUM_SCALE> holds the same value. NULL (C<undef>) is returned for | |||
5109 | data types for which this is not applicable. | |||
5110 | ||||
5111 | =item MAXIMUM_SCALE (integer) | |||
5112 | ||||
5113 | The maximum scale of the data type. If a data type has a fixed scale, | |||
5114 | then C<MINIMUM_SCALE> holds the same value. NULL (C<undef>) is returned for | |||
5115 | data types for which this is not applicable. | |||
5116 | ||||
5117 | =item SQL_DATA_TYPE (integer) | |||
5118 | ||||
5119 | This column is the same as the C<DATA_TYPE> column, except for interval | |||
5120 | and datetime data types. For interval and datetime data types, the | |||
5121 | C<SQL_DATA_TYPE> field will return C<SQL_INTERVAL> or C<SQL_DATETIME>, and the | |||
5122 | C<SQL_DATETIME_SUB> field below will return the subcode for the specific | |||
5123 | interval or datetime data type. If this field is NULL, then the driver | |||
5124 | does not support or report on interval or datetime subtypes. | |||
5125 | ||||
5126 | =item SQL_DATETIME_SUB (integer) | |||
5127 | ||||
5128 | For interval or datetime data types, where the C<SQL_DATA_TYPE> | |||
5129 | field above is C<SQL_INTERVAL> or C<SQL_DATETIME>, this field will | |||
5130 | hold the I<subcode> for the specific interval or datetime data type. | |||
5131 | Otherwise it will be NULL (C<undef>). | |||
5132 | ||||
5133 | Although not mentioned explicitly in the standards, it seems there | |||
5134 | is a simple relationship between these values: | |||
5135 | ||||
5136 | DATA_TYPE == (10 * SQL_DATA_TYPE) + SQL_DATETIME_SUB | |||
5137 | ||||
5138 | =item NUM_PREC_RADIX (integer) | |||
5139 | ||||
5140 | The radix value of the data type. For approximate numeric types, | |||
5141 | C<NUM_PREC_RADIX> | |||
5142 | contains the value 2 and C<COLUMN_SIZE> holds the number of bits. For | |||
5143 | exact numeric types, C<NUM_PREC_RADIX> contains the value 10 and C<COLUMN_SIZE> holds | |||
5144 | the number of decimal digits. NULL (C<undef>) is returned either for data types | |||
5145 | for which this is not applicable or if the driver cannot report this information. | |||
5146 | ||||
5147 | =item INTERVAL_PRECISION (integer) | |||
5148 | ||||
5149 | The interval leading precision for interval types. NULL is returned | |||
5150 | either for data types for which this is not applicable or if the driver | |||
5151 | cannot report this information. | |||
5152 | ||||
5153 | =back | |||
5154 | ||||
5155 | For example, to find the type name for the fields in a select statement | |||
5156 | you can do: | |||
5157 | ||||
5158 | @names = map { scalar $dbh->type_info($_)->{TYPE_NAME} } @{ $sth->{TYPE} } | |||
5159 | ||||
5160 | Since DBI and ODBC drivers vary in how they map their types into the | |||
5161 | ISO standard types you may need to search for more than one type. | |||
5162 | Here's an example looking for a usable type to store a date: | |||
5163 | ||||
5164 | $my_date_type = $dbh->type_info( [ SQL_DATE, SQL_TIMESTAMP ] ); | |||
5165 | ||||
5166 | Similarly, to more reliably find a type to store small integers, you could | |||
5167 | use a list starting with C<SQL_SMALLINT>, C<SQL_INTEGER>, C<SQL_DECIMAL>, etc. | |||
5168 | ||||
5169 | See also L</"Standards Reference Information">. | |||
5170 | ||||
5171 | ||||
5172 | =head3 C<quote> | |||
5173 | ||||
5174 | $sql = $dbh->quote($value); | |||
5175 | $sql = $dbh->quote($value, $data_type); | |||
5176 | ||||
5177 | Quote a string literal for use as a literal value in an SQL statement, | |||
5178 | by escaping any special characters (such as quotation marks) | |||
5179 | contained within the string and adding the required type of outer | |||
5180 | quotation marks. | |||
5181 | ||||
5182 | $sql = sprintf "SELECT foo FROM bar WHERE baz = %s", | |||
5183 | $dbh->quote("Don't"); | |||
5184 | ||||
5185 | For most database types, quote would return C<'Don''t'> (including the | |||
5186 | outer quotation marks). | |||
5187 | ||||
5188 | An undefined C<$value> value will be returned as the string C<NULL> (without | |||
5189 | single quotation marks) to match how NULLs are represented in SQL. | |||
5190 | ||||
5191 | If C<$data_type> is supplied, it is used to try to determine the required | |||
5192 | quoting behaviour by using the information returned by L</type_info>. | |||
5193 | As a special case, the standard numeric types are optimized to return | |||
5194 | C<$value> without calling C<type_info>. | |||
5195 | ||||
5196 | Quote will probably I<not> be able to deal with all possible input | |||
5197 | (such as binary data or data containing newlines), and is not related in | |||
5198 | any way with escaping or quoting shell meta-characters. | |||
5199 | ||||
5200 | It is valid for the quote() method to return an SQL expression that | |||
5201 | evaluates to the desired string. For example: | |||
5202 | ||||
5203 | $quoted = $dbh->quote("one\ntwo\0three") | |||
5204 | ||||
5205 | may return something like: | |||
5206 | ||||
5207 | CONCAT('one', CHAR(12), 'two', CHAR(0), 'three') | |||
5208 | ||||
5209 | The quote() method should I<not> be used with L</"Placeholders and | |||
5210 | Bind Values">. | |||
5211 | ||||
5212 | =head3 C<quote_identifier> | |||
5213 | ||||
5214 | $sql = $dbh->quote_identifier( $name ); | |||
5215 | $sql = $dbh->quote_identifier( $catalog, $schema, $table, \%attr ); | |||
5216 | ||||
5217 | Quote an identifier (table name etc.) for use in an SQL statement, | |||
5218 | by escaping any special characters (such as double quotation marks) | |||
5219 | it contains and adding the required type of outer quotation marks. | |||
5220 | ||||
5221 | Undefined names are ignored and the remainder are quoted and then | |||
5222 | joined together, typically with a dot (C<.>) character. For example: | |||
5223 | ||||
5224 | $id = $dbh->quote_identifier( undef, 'Her schema', 'My table' ); | |||
5225 | ||||
5226 | would, for most database types, return C<"Her schema"."My table"> | |||
5227 | (including all the double quotation marks). | |||
5228 | ||||
5229 | If three names are supplied then the first is assumed to be a | |||
5230 | catalog name and special rules may be applied based on what L</get_info> | |||
5231 | returns for SQL_CATALOG_NAME_SEPARATOR (41) and SQL_CATALOG_LOCATION (114). | |||
5232 | For example, for Oracle: | |||
5233 | ||||
5234 | $id = $dbh->quote_identifier( 'link', 'schema', 'table' ); | |||
5235 | ||||
5236 | would return C<"schema"."table"@"link">. | |||
5237 | ||||
5238 | =head3 C<take_imp_data> | |||
5239 | ||||
5240 | $imp_data = $dbh->take_imp_data; | |||
5241 | ||||
5242 | Leaves the $dbh in an almost dead, zombie-like, state and returns | |||
5243 | a binary string of raw implementation data from the driver which | |||
5244 | describes the current database connection. Effectively it detaches | |||
5245 | the underlying database API connection data from the DBI handle. | |||
5246 | After calling take_imp_data(), all other methods except C<DESTROY> | |||
5247 | will generate a warning and return undef. | |||
5248 | ||||
5249 | Why would you want to do this? You don't, forget I even mentioned it. | |||
5250 | Unless, that is, you're implementing something advanced like a | |||
5251 | multi-threaded connection pool. See L<DBI::Pool>. | |||
5252 | ||||
5253 | The returned $imp_data can be passed as a C<dbi_imp_data> attribute | |||
5254 | to a later connect() call, even in a separate thread in the same | |||
5255 | process, where the driver can use it to 'adopt' the existing | |||
5256 | connection that the implementation data was taken from. | |||
5257 | ||||
5258 | Some things to keep in mind... | |||
5259 | ||||
5260 | B<*> the $imp_data holds the only reference to the underlying | |||
5261 | database API connection data. That connection is still 'live' and | |||
5262 | won't be cleaned up properly unless the $imp_data is used to create | |||
5263 | a new $dbh which is then allowed to disconnect() normally. | |||
5264 | ||||
5265 | B<*> using the same $imp_data to create more than one other new | |||
5266 | $dbh at a time may well lead to unpleasant problems. Don't do that. | |||
5267 | ||||
5268 | Any child statement handles are effectively destroyed when take_imp_data() is | |||
5269 | called. | |||
5270 | ||||
5271 | The C<take_imp_data> method was added in DBI 1.36 but wasn't useful till 1.49. | |||
5272 | ||||
5273 | ||||
5274 | =head2 Database Handle Attributes | |||
5275 | ||||
5276 | This section describes attributes specific to database handles. | |||
5277 | ||||
5278 | Changes to these database handle attributes do not affect any other | |||
5279 | existing or future database handles. | |||
5280 | ||||
5281 | Attempting to set or get the value of an unknown attribute generates a warning, | |||
5282 | except for private driver-specific attributes (which all have names | |||
5283 | starting with a lowercase letter). | |||
5284 | ||||
5285 | Example: | |||
5286 | ||||
5287 | $h->{AutoCommit} = ...; # set/write | |||
5288 | ... = $h->{AutoCommit}; # get/read | |||
5289 | ||||
5290 | =head3 C<AutoCommit> (boolean) | |||
5291 | ||||
5292 | If true, then database changes cannot be rolled-back (undone). If false, | |||
5293 | then database changes automatically occur within a "transaction", which | |||
5294 | must either be committed or rolled back using the C<commit> or C<rollback> | |||
5295 | methods. | |||
5296 | ||||
5297 | Drivers should always default to C<AutoCommit> mode (an unfortunate | |||
5298 | choice largely forced on the DBI by ODBC and JDBC conventions.) | |||
5299 | ||||
5300 | Attempting to set C<AutoCommit> to an unsupported value is a fatal error. | |||
5301 | This is an important feature of the DBI. Applications that need | |||
5302 | full transaction behaviour can set C<$dbh-E<gt>{AutoCommit} = 0> (or | |||
5303 | set C<AutoCommit> to 0 via L</connect>) | |||
5304 | without having to check that the value was assigned successfully. | |||
5305 | ||||
5306 | For the purposes of this description, we can divide databases into three | |||
5307 | categories: | |||
5308 | ||||
5309 | Databases which don't support transactions at all. | |||
5310 | Databases in which a transaction is always active. | |||
5311 | Databases in which a transaction must be explicitly started (C<'BEGIN WORK'>). | |||
5312 | ||||
5313 | B<* Databases which don't support transactions at all> | |||
5314 | ||||
5315 | For these databases, attempting to turn C<AutoCommit> off is a fatal error. | |||
5316 | C<commit> and C<rollback> both issue warnings about being ineffective while | |||
5317 | C<AutoCommit> is in effect. | |||
5318 | ||||
5319 | B<* Databases in which a transaction is always active> | |||
5320 | ||||
5321 | These are typically mainstream commercial relational databases with | |||
5322 | "ANSI standard" transaction behaviour. | |||
5323 | If C<AutoCommit> is off, then changes to the database won't have any | |||
5324 | lasting effect unless L</commit> is called (but see also | |||
5325 | L</disconnect>). If L</rollback> is called then any changes since the | |||
5326 | last commit are undone. | |||
5327 | ||||
5328 | If C<AutoCommit> is on, then the effect is the same as if the DBI | |||
5329 | called C<commit> automatically after every successful database | |||
5330 | operation. So calling C<commit> or C<rollback> explicitly while | |||
5331 | C<AutoCommit> is on would be ineffective because the changes would | |||
5332 | have already been commited. | |||
5333 | ||||
5334 | Changing C<AutoCommit> from off to on will trigger a L</commit>. | |||
5335 | ||||
5336 | For databases which don't support a specific auto-commit mode, the | |||
5337 | driver has to commit each statement automatically using an explicit | |||
5338 | C<COMMIT> after it completes successfully (and roll it back using an | |||
5339 | explicit C<ROLLBACK> if it fails). The error information reported to the | |||
5340 | application will correspond to the statement which was executed, unless | |||
5341 | it succeeded and the commit or rollback failed. | |||
5342 | ||||
5343 | B<* Databases in which a transaction must be explicitly started> | |||
5344 | ||||
5345 | For these databases, the intention is to have them act like databases in | |||
5346 | which a transaction is always active (as described above). | |||
5347 | ||||
5348 | To do this, the driver will automatically begin an explicit transaction | |||
5349 | when C<AutoCommit> is turned off, or after a L</commit> or | |||
5350 | L</rollback> (or when the application issues the next database | |||
5351 | operation after one of those events). | |||
5352 | ||||
5353 | In this way, the application does not have to treat these databases | |||
5354 | as a special case. | |||
5355 | ||||
5356 | See L</commit>, L</disconnect> and L</Transactions> for other important | |||
5357 | notes about transactions. | |||
5358 | ||||
5359 | ||||
5360 | =head3 C<Driver> (handle) | |||
5361 | ||||
5362 | Holds the handle of the parent driver. The only recommended use for this | |||
5363 | is to find the name of the driver using: | |||
5364 | ||||
5365 | $dbh->{Driver}->{Name} | |||
5366 | ||||
5367 | ||||
5368 | =head3 C<Name> (string) | |||
5369 | ||||
5370 | Holds the "name" of the database. Usually (and recommended to be) the | |||
5371 | same as the "C<dbi:DriverName:...>" string used to connect to the database, | |||
5372 | but with the leading "C<dbi:DriverName:>" removed. | |||
5373 | ||||
5374 | ||||
5375 | =head3 C<Statement> (string, read-only) | |||
5376 | ||||
5377 | Returns the statement string passed to the most recent L</prepare> method | |||
5378 | called in this database handle, even if that method failed. This is especially | |||
5379 | useful where C<RaiseError> is enabled and the exception handler checks $@ | |||
5380 | and sees that a 'prepare' method call failed. | |||
5381 | ||||
5382 | ||||
5383 | =head3 C<RowCacheSize> (integer) | |||
5384 | ||||
5385 | A hint to the driver indicating the size of the local row cache that the | |||
5386 | application would like the driver to use for future C<SELECT> statements. | |||
5387 | If a row cache is not implemented, then setting C<RowCacheSize> is ignored | |||
5388 | and getting the value returns C<undef>. | |||
5389 | ||||
5390 | Some C<RowCacheSize> values have special meaning, as follows: | |||
5391 | ||||
5392 | 0 - Automatically determine a reasonable cache size for each C<SELECT> | |||
5393 | 1 - Disable the local row cache | |||
5394 | >1 - Cache this many rows | |||
5395 | <0 - Cache as many rows that will fit into this much memory for each C<SELECT>. | |||
5396 | ||||
5397 | Note that large cache sizes may require a very large amount of memory | |||
5398 | (I<cached rows * maximum size of row>). Also, a large cache will cause | |||
5399 | a longer delay not only for the first fetch, but also whenever the | |||
5400 | cache needs refilling. | |||
5401 | ||||
5402 | See also the L</RowsInCache> statement handle attribute. | |||
5403 | ||||
5404 | =head3 C<Username> (string) | |||
5405 | ||||
5406 | Returns the username used to connect to the database. | |||
5407 | ||||
5408 | ||||
5409 | =head1 DBI STATEMENT HANDLE OBJECTS | |||
5410 | ||||
5411 | This section lists the methods and attributes associated with DBI | |||
5412 | statement handles. | |||
5413 | ||||
5414 | =head2 Statement Handle Methods | |||
5415 | ||||
5416 | The DBI defines the following methods for use on DBI statement handles: | |||
5417 | ||||
5418 | =head3 C<bind_param> | |||
5419 | ||||
5420 | $sth->bind_param($p_num, $bind_value) | |||
5421 | $sth->bind_param($p_num, $bind_value, \%attr) | |||
5422 | $sth->bind_param($p_num, $bind_value, $bind_type) | |||
5423 | ||||
5424 | The C<bind_param> method takes a copy of $bind_value and associates it | |||
5425 | (binds it) with a placeholder, identified by $p_num, embedded in | |||
5426 | the prepared statement. Placeholders are indicated with question | |||
5427 | mark character (C<?>). For example: | |||
5428 | ||||
5429 | $dbh->{RaiseError} = 1; # save having to check each method call | |||
5430 | $sth = $dbh->prepare("SELECT name, age FROM people WHERE name LIKE ?"); | |||
5431 | $sth->bind_param(1, "John%"); # placeholders are numbered from 1 | |||
5432 | $sth->execute; | |||
5433 | DBI::dump_results($sth); | |||
5434 | ||||
5435 | See L</"Placeholders and Bind Values"> for more information. | |||
5436 | ||||
5437 | ||||
5438 | B<Data Types for Placeholders> | |||
5439 | ||||
5440 | The C<\%attr> parameter can be used to hint at the data type the | |||
5441 | placeholder should have. This is rarely needed. Typically, the driver is only | |||
5442 | interested in knowing if the placeholder should be bound as a number or a string. | |||
5443 | ||||
5444 | $sth->bind_param(1, $value, { TYPE => SQL_INTEGER }); | |||
5445 | ||||
5446 | As a short-cut for the common case, the data type can be passed | |||
5447 | directly, in place of the C<\%attr> hash reference. This example is | |||
5448 | equivalent to the one above: | |||
5449 | ||||
5450 | $sth->bind_param(1, $value, SQL_INTEGER); | |||
5451 | ||||
5452 | The C<TYPE> value indicates the standard (non-driver-specific) type for | |||
5453 | this parameter. To specify the driver-specific type, the driver may | |||
5454 | support a driver-specific attribute, such as C<{ ora_type =E<gt> 97 }>. | |||
5455 | ||||
5456 | The SQL_INTEGER and other related constants can be imported using | |||
5457 | ||||
5458 | use DBI qw(:sql_types); | |||
5459 | ||||
5460 | See L</"DBI Constants"> for more information. | |||
5461 | ||||
5462 | The data type for a placeholder cannot be changed after the first | |||
5463 | C<bind_param> call. In fact the whole \%attr parameter is 'sticky' | |||
5464 | in the sense that a driver only needs to consider the \%attr parameter | |||
5465 | for the first call, for a given $sth and parameter. After that the driver | |||
5466 | may ignore the \%attr parameter for that placeholder. | |||
5467 | ||||
5468 | Perl only has string and number scalar data types. All database types | |||
5469 | that aren't numbers are bound as strings and must be in a format the | |||
5470 | database will understand except where the bind_param() TYPE attribute | |||
5471 | specifies a type that implies a particular format. For example, given: | |||
5472 | ||||
5473 | $sth->bind_param(1, $value, SQL_DATETIME); | |||
5474 | ||||
5475 | the driver should expect $value to be in the ODBC standard SQL_DATETIME | |||
5476 | format, which is 'YYYY-MM-DD HH:MM:SS'. Similarly for SQL_DATE, SQL_TIME etc. | |||
5477 | ||||
5478 | As an alternative to specifying the data type in the C<bind_param> call, | |||
5479 | you can let the driver pass the value as the default type (C<VARCHAR>). | |||
5480 | You can then use an SQL function to convert the type within the statement. | |||
5481 | For example: | |||
5482 | ||||
5483 | INSERT INTO price(code, price) VALUES (?, CONVERT(MONEY,?)) | |||
5484 | ||||
5485 | The C<CONVERT> function used here is just an example. The actual function | |||
5486 | and syntax will vary between different databases and is non-portable. | |||
5487 | ||||
5488 | See also L</"Placeholders and Bind Values"> for more information. | |||
5489 | ||||
5490 | ||||
5491 | =head3 C<bind_param_inout> | |||
5492 | ||||
5493 | $rc = $sth->bind_param_inout($p_num, \$bind_value, $max_len) or die $sth->errstr; | |||
5494 | $rv = $sth->bind_param_inout($p_num, \$bind_value, $max_len, \%attr) or ... | |||
5495 | $rv = $sth->bind_param_inout($p_num, \$bind_value, $max_len, $bind_type) or ... | |||
5496 | ||||
5497 | This method acts like L</bind_param>, but also enables values to be | |||
5498 | updated by the statement. The statement is typically | |||
5499 | a call to a stored procedure. The C<$bind_value> must be passed as a | |||
5500 | reference to the actual value to be used. | |||
5501 | ||||
5502 | Note that unlike L</bind_param>, the C<$bind_value> variable is not | |||
5503 | copied when C<bind_param_inout> is called. Instead, the value in the | |||
5504 | variable is read at the time L</execute> is called. | |||
5505 | ||||
5506 | The additional C<$max_len> parameter specifies the minimum amount of | |||
5507 | memory to allocate to C<$bind_value> for the new value. If the value | |||
5508 | returned from the database is too | |||
5509 | big to fit, then the execution should fail. If unsure what value to use, | |||
5510 | pick a generous length, i.e., a length larger than the longest value that would ever be | |||
5511 | returned. The only cost of using a larger value than needed is wasted memory. | |||
5512 | ||||
5513 | Undefined values or C<undef> are used to indicate null values. | |||
5514 | See also L</"Placeholders and Bind Values"> for more information. | |||
5515 | ||||
5516 | ||||
5517 | =head3 C<bind_param_array> | |||
5518 | ||||
5519 | $rc = $sth->bind_param_array($p_num, $array_ref_or_value) | |||
5520 | $rc = $sth->bind_param_array($p_num, $array_ref_or_value, \%attr) | |||
5521 | $rc = $sth->bind_param_array($p_num, $array_ref_or_value, $bind_type) | |||
5522 | ||||
5523 | The C<bind_param_array> method is used to bind an array of values | |||
5524 | to a placeholder embedded in the prepared statement which is to be executed | |||
5525 | with L</execute_array>. For example: | |||
5526 | ||||
5527 | $dbh->{RaiseError} = 1; # save having to check each method call | |||
5528 | $sth = $dbh->prepare("INSERT INTO staff (first_name, last_name, dept) VALUES(?, ?, ?)"); | |||
5529 | $sth->bind_param_array(1, [ 'John', 'Mary', 'Tim' ]); | |||
5530 | $sth->bind_param_array(2, [ 'Booth', 'Todd', 'Robinson' ]); | |||
5531 | $sth->bind_param_array(3, "SALES"); # scalar will be reused for each row | |||
5532 | $sth->execute_array( { ArrayTupleStatus => \my @tuple_status } ); | |||
5533 | ||||
5534 | The C<%attr> ($bind_type) argument is the same as defined for L</bind_param>. | |||
5535 | Refer to L</bind_param> for general details on using placeholders. | |||
5536 | ||||
5537 | (Note that bind_param_array() can I<not> be used to expand a | |||
5538 | placeholder into a list of values for a statement like "SELECT foo | |||
5539 | WHERE bar IN (?)". A placeholder can only ever represent one value | |||
5540 | per execution.) | |||
5541 | ||||
5542 | Scalar values, including C<undef>, may also be bound by | |||
5543 | C<bind_param_array>. In which case the same value will be used for each | |||
5544 | L</execute> call. Driver-specific implementations may behave | |||
5545 | differently, e.g., when binding to a stored procedure call, some | |||
5546 | databases may permit mixing scalars and arrays as arguments. | |||
5547 | ||||
5548 | The default implementation provided by DBI (for drivers that have | |||
5549 | not implemented array binding) is to iteratively call L</execute> for | |||
5550 | each parameter tuple provided in the bound arrays. Drivers may | |||
5551 | provide more optimized implementations using whatever bulk operation | |||
5552 | support the database API provides. The default driver behaviour should | |||
5553 | match the default DBI behaviour, but always consult your driver | |||
5554 | documentation as there may be driver specific issues to consider. | |||
5555 | ||||
5556 | Note that the default implementation currently only supports non-data | |||
5557 | returning statements (INSERT, UPDATE, but not SELECT). Also, | |||
5558 | C<bind_param_array> and L</bind_param> cannot be mixed in the same | |||
5559 | statement execution, and C<bind_param_array> must be used with | |||
5560 | L</execute_array>; using C<bind_param_array> will have no effect | |||
5561 | for L</execute>. | |||
5562 | ||||
5563 | The C<bind_param_array> method was added in DBI 1.22. | |||
5564 | ||||
5565 | =head3 C<execute> | |||
5566 | ||||
5567 | $rv = $sth->execute or die $sth->errstr; | |||
5568 | $rv = $sth->execute(@bind_values) or die $sth->errstr; | |||
5569 | ||||
5570 | Perform whatever processing is necessary to execute the prepared | |||
5571 | statement. An C<undef> is returned if an error occurs. A successful | |||
5572 | C<execute> always returns true regardless of the number of rows affected, | |||
5573 | even if it's zero (see below). It is always important to check the | |||
5574 | return status of C<execute> (and most other DBI methods) for errors | |||
5575 | if you're not using L</RaiseError>. | |||
5576 | ||||
5577 | For a I<non>-C<SELECT> statement, C<execute> returns the number of rows | |||
5578 | affected, if known. If no rows were affected, then C<execute> returns | |||
5579 | "C<0E0>", which Perl will treat as 0 but will regard as true. Note that it | |||
5580 | is I<not> an error for no rows to be affected by a statement. If the | |||
5581 | number of rows affected is not known, then C<execute> returns -1. | |||
5582 | ||||
5583 | For C<SELECT> statements, execute simply "starts" the query within the | |||
5584 | database engine. Use one of the fetch methods to retrieve the data after | |||
5585 | calling C<execute>. The C<execute> method does I<not> return the number of | |||
5586 | rows that will be returned by the query (because most databases can't | |||
5587 | tell in advance), it simply returns a true value. | |||
5588 | ||||
5589 | You can tell if the statement was a C<SELECT> statement by checking if | |||
5590 | C<$sth-E<gt>{NUM_OF_FIELDS}> is greater than zero after calling C<execute>. | |||
5591 | ||||
5592 | If any arguments are given, then C<execute> will effectively call | |||
5593 | L</bind_param> for each value before executing the statement. Values | |||
5594 | bound in this way are usually treated as C<SQL_VARCHAR> types unless | |||
5595 | the driver can determine the correct type (which is rare), or unless | |||
5596 | C<bind_param> (or C<bind_param_inout>) has already been used to | |||
5597 | specify the type. | |||
5598 | ||||
5599 | If execute() is called on a statement handle that's still active | |||
5600 | ($sth->{Active} is true) then it should effectively call finish() | |||
5601 | to tidy up the previous execution results before starting this new | |||
5602 | execution. | |||
5603 | ||||
5604 | =head3 C<execute_array> | |||
5605 | ||||
5606 | $tuples = $sth->execute_array(\%attr) or die $sth->errstr; | |||
5607 | $tuples = $sth->execute_array(\%attr, @bind_values) or die $sth->errstr; | |||
5608 | ||||
5609 | ($tuples, $rows) = $sth->execute_array(\%attr) or die $sth->errstr; | |||
5610 | ($tuples, $rows) = $sth->execute_array(\%attr, @bind_values) or die $sth->errstr; | |||
5611 | ||||
5612 | Execute the prepared statement once for each parameter tuple | |||
5613 | (group of values) provided either in the @bind_values, or by prior | |||
5614 | calls to L</bind_param_array>, or via a reference passed in \%attr. | |||
5615 | ||||
5616 | When called in scalar context the execute_array() method returns the | |||
5617 | number of tuples executed, or C<undef> if an error occured. Like | |||
5618 | execute(), a successful execute_array() always returns true regardless | |||
5619 | of the number of tuples executed, even if it's zero. If there were any | |||
5620 | errors the ArrayTupleStatus array can be used to discover which tuples | |||
5621 | failed and with what errors. | |||
5622 | ||||
5623 | When called in list context the execute_array() method returns two scalars; | |||
5624 | $tuples is the same as calling execute_array() in scalar context and $rows is | |||
5625 | the sum of the number of rows affected for each tuple, if available or | |||
5626 | -1 if the driver cannot determine this. | |||
5627 | If you are doing an update operation the returned rows affected may not be what | |||
5628 | you expect if, for instance, one or more of the tuples affected the same row | |||
5629 | multiple times. Some drivers may not yet support list context, in which case | |||
5630 | $rows will be undef, or may not be able to provide the number of rows affected | |||
5631 | when performing this batch operation, in which case $rows will be -1. | |||
5632 | ||||
5633 | Bind values for the tuples to be executed may be supplied row-wise | |||
5634 | by an C<ArrayTupleFetch> attribute, or else column-wise in the | |||
5635 | C<@bind_values> argument, or else column-wise by prior calls to | |||
5636 | L</bind_param_array>. | |||
5637 | ||||
5638 | Where column-wise binding is used (via the C<@bind_values> argument | |||
5639 | or calls to bind_param_array()) the maximum number of elements in | |||
5640 | any one of the bound value arrays determines the number of tuples | |||
5641 | executed. Placeholders with fewer values in their parameter arrays | |||
5642 | are treated as if padded with undef (NULL) values. | |||
5643 | ||||
5644 | If a scalar value is bound, instead of an array reference, it is | |||
5645 | treated as a I<variable> length array with all elements having the | |||
5646 | same value. It's does not influence the number of tuples executed, | |||
5647 | so if all bound arrays have zero elements then zero tuples will | |||
5648 | be executed. If I<all> bound values are scalars then one tuple | |||
5649 | will be executed, making execute_array() act just like execute(). | |||
5650 | ||||
5651 | The C<ArrayTupleFetch> attribute can be used to specify a reference | |||
5652 | to a subroutine that will be called to provide the bind values for | |||
5653 | each tuple execution. The subroutine should return an reference to | |||
5654 | an array which contains the appropriate number of bind values, or | |||
5655 | return an undef if there is no more data to execute. | |||
5656 | ||||
5657 | As a convienience, the C<ArrayTupleFetch> attribute can also be | |||
5658 | used to specify a statement handle. In which case the fetchrow_arrayref() | |||
5659 | method will be called on the given statement handle in order to | |||
5660 | provide the bind values for each tuple execution. | |||
5661 | ||||
5662 | The values specified via bind_param_array() or the @bind_values | |||
5663 | parameter may be either scalars, or arrayrefs. If any C<@bind_values> | |||
5664 | are given, then C<execute_array> will effectively call L</bind_param_array> | |||
5665 | for each value before executing the statement. Values bound in | |||
5666 | this way are usually treated as C<SQL_VARCHAR> types unless the | |||
5667 | driver can determine the correct type (which is rare), or unless | |||
5668 | C<bind_param>, C<bind_param_inout>, C<bind_param_array>, or | |||
5669 | C<bind_param_inout_array> has already been used to specify the type. | |||
5670 | See L</bind_param_array> for details. | |||
5671 | ||||
5672 | The C<ArrayTupleStatus> attribute can be used to specify a | |||
5673 | reference to an array which will receive the execute status of each | |||
5674 | executed parameter tuple. Note the C<ArrayTupleStatus> attribute was | |||
5675 | mandatory until DBI 1.38. | |||
5676 | ||||
5677 | For tuples which are successfully executed, the element at the same | |||
5678 | ordinal position in the status array is the resulting rowcount. | |||
5679 | If the execution of a tuple causes an error, then the corresponding | |||
5680 | status array element will be set to a reference to an array containing | |||
5681 | the error code and error string set by the failed execution. | |||
5682 | ||||
5683 | If B<any> tuple execution returns an error, C<execute_array> will | |||
5684 | return C<undef>. In that case, the application should inspect the | |||
5685 | status array to determine which parameter tuples failed. | |||
5686 | Some databases may not continue executing tuples beyond the first | |||
5687 | failure. In this case the status array will either hold fewer | |||
5688 | elements, or the elements beyond the failure will be undef. | |||
5689 | ||||
5690 | If all parameter tuples are successfully executed, C<execute_array> | |||
5691 | returns the number tuples executed. If no tuples were executed, | |||
5692 | then execute_array() returns "C<0E0>", just like execute() does, | |||
5693 | which Perl will treat as 0 but will regard as true. | |||
5694 | ||||
5695 | For example: | |||
5696 | ||||
5697 | $sth = $dbh->prepare("INSERT INTO staff (first_name, last_name) VALUES (?, ?)"); | |||
5698 | my $tuples = $sth->execute_array( | |||
5699 | { ArrayTupleStatus => \my @tuple_status }, | |||
5700 | \@first_names, | |||
5701 | \@last_names, | |||
5702 | ); | |||
5703 | if ($tuples) { | |||
5704 | print "Successfully inserted $tuples records\n"; | |||
5705 | } | |||
5706 | else { | |||
5707 | for my $tuple (0..@last_names-1) { | |||
5708 | my $status = $tuple_status[$tuple]; | |||
5709 | $status = [0, "Skipped"] unless defined $status; | |||
5710 | next unless ref $status; | |||
5711 | printf "Failed to insert (%s, %s): %s\n", | |||
5712 | $first_names[$tuple], $last_names[$tuple], $status->[1]; | |||
5713 | } | |||
5714 | } | |||
5715 | ||||
5716 | Support for data returning statements such as SELECT is driver-specific | |||
5717 | and subject to change. At present, the default implementation | |||
5718 | provided by DBI only supports non-data returning statements. | |||
5719 | ||||
5720 | Transaction semantics when using array binding are driver and | |||
5721 | database specific. If C<AutoCommit> is on, the default DBI | |||
5722 | implementation will cause each parameter tuple to be inidividually | |||
5723 | committed (or rolled back in the event of an error). If C<AutoCommit> | |||
5724 | is off, the application is responsible for explicitly committing | |||
5725 | the entire set of bound parameter tuples. Note that different | |||
5726 | drivers and databases may have different behaviours when some | |||
5727 | parameter tuples cause failures. In some cases, the driver or | |||
5728 | database may automatically rollback the effect of all prior parameter | |||
5729 | tuples that succeeded in the transaction; other drivers or databases | |||
5730 | may retain the effect of prior successfully executed parameter | |||
5731 | tuples. Be sure to check your driver and database for its specific | |||
5732 | behaviour. | |||
5733 | ||||
5734 | Note that, in general, performance will usually be better with | |||
5735 | C<AutoCommit> turned off, and using explicit C<commit> after each | |||
5736 | C<execute_array> call. | |||
5737 | ||||
5738 | The C<execute_array> method was added in DBI 1.22, and ArrayTupleFetch | |||
5739 | was added in 1.36. | |||
5740 | ||||
5741 | =head3 C<execute_for_fetch> | |||
5742 | ||||
5743 | $tuples = $sth->execute_for_fetch($fetch_tuple_sub); | |||
5744 | $tuples = $sth->execute_for_fetch($fetch_tuple_sub, \@tuple_status); | |||
5745 | ||||
5746 | ($tuples, $rows) = $sth->execute_for_fetch($fetch_tuple_sub); | |||
5747 | ($tuples, $rows) = $sth->execute_for_fetch($fetch_tuple_sub, \@tuple_status); | |||
5748 | ||||
5749 | The execute_for_fetch() method is used to perform bulk operations | |||
5750 | and is most often used via the execute_array() method, not directly. | |||
5751 | ||||
5752 | The fetch subroutine, referenced by $fetch_tuple_sub, is expected | |||
5753 | to return a reference to an array (known as a 'tuple') or undef. | |||
5754 | ||||
5755 | The execute_for_fetch() method calls $fetch_tuple_sub, without any | |||
5756 | parameters, until it returns a false value. Each tuple returned is | |||
5757 | used to provide bind values for an $sth->execute(@$tuple) call. | |||
5758 | ||||
5759 | In scalar context execute_for_fetch() returns C<undef> if there were any | |||
5760 | errors and the number of tuples executed otherwise. Like execute() and | |||
5761 | execute_array() a zero is returned as "0E0" so execute_for_fetch() is | |||
5762 | only false on error. If there were any errors the @tuple_status array | |||
5763 | can be used to discover which tuples failed and with what errors. | |||
5764 | ||||
5765 | When called in list context execute_for_fetch() returns two scalars; | |||
5766 | $tuples is the same as calling execute_for_fetch() in scalar context and $rows is | |||
5767 | the sum of the number of rows affected for each tuple, if available or -1 | |||
5768 | if the driver cannot determine this. | |||
5769 | If you are doing an update operation the returned rows affected may not be what | |||
5770 | you expect if, for instance, one or more of the tuples affected the same row | |||
5771 | multiple times. Some drivers may not yet support list context, in which case | |||
5772 | $rows will be undef, or may not be able to provide the number of rows affected | |||
5773 | when performing this batch operation, in which case $rows will be -1. | |||
5774 | ||||
5775 | If \@tuple_status is passed then the execute_for_fetch method uses | |||
5776 | it to return status information. The tuple_status array holds one | |||
5777 | element per tuple. If the corresponding execute() did not fail then | |||
5778 | the element holds the return value from execute(), which is typically | |||
5779 | a row count. If the execute() did fail then the element holds a | |||
5780 | reference to an array containing ($sth->err, $sth->errstr, $sth->state). | |||
5781 | ||||
5782 | If the driver detects an error that it knows means no further tuples can be | |||
5783 | executed then it may return, with an error status, even though $fetch_tuple_sub | |||
5784 | may still have more tuples to be executed. | |||
5785 | ||||
5786 | Although each tuple returned by $fetch_tuple_sub is effectively used | |||
5787 | to call $sth->execute(@$tuple_array_ref) the exact timing may vary. | |||
5788 | Drivers are free to accumulate sets of tuples to pass to the | |||
5789 | database server in bulk group operations for more efficient execution. | |||
5790 | However, the $fetch_tuple_sub is specifically allowed to return | |||
5791 | the same array reference each time (which is what fetchrow_arrayref() | |||
5792 | usually does). | |||
5793 | ||||
5794 | For example: | |||
5795 | ||||
5796 | my $sel = $dbh1->prepare("select foo, bar from table1"); | |||
5797 | $sel->execute; | |||
5798 | ||||
5799 | my $ins = $dbh2->prepare("insert into table2 (foo, bar) values (?,?)"); | |||
5800 | my $fetch_tuple_sub = sub { $sel->fetchrow_arrayref }; | |||
5801 | ||||
5802 | my @tuple_status; | |||
5803 | $rc = $ins->execute_for_fetch($fetch_tuple_sub, \@tuple_status); | |||
5804 | my @errors = grep { ref $_ } @tuple_status; | |||
5805 | ||||
5806 | Similarly, if you already have an array containing the data rows | |||
5807 | to be processed you'd use a subroutine to shift off and return | |||
5808 | each array ref in turn: | |||
5809 | ||||
5810 | $ins->execute_for_fetch( sub { shift @array_of_arrays }, \@tuple_status); | |||
5811 | ||||
5812 | The C<execute_for_fetch> method was added in DBI 1.38. | |||
5813 | ||||
5814 | ||||
5815 | =head3 C<fetchrow_arrayref> | |||
5816 | ||||
5817 | $ary_ref = $sth->fetchrow_arrayref; | |||
5818 | $ary_ref = $sth->fetch; # alias | |||
5819 | ||||
5820 | Fetches the next row of data and returns a reference to an array | |||
5821 | holding the field values. Null fields are returned as C<undef> | |||
5822 | values in the array. | |||
5823 | This is the fastest way to fetch data, particularly if used with | |||
5824 | C<$sth-E<gt>bind_columns>. | |||
5825 | ||||
5826 | If there are no more rows or if an error occurs, then C<fetchrow_arrayref> | |||
5827 | returns an C<undef>. You should check C<$sth-E<gt>err> afterwards (or use the | |||
5828 | C<RaiseError> attribute) to discover if the C<undef> returned was due to an | |||
5829 | error. | |||
5830 | ||||
5831 | Note that the same array reference is returned for each fetch, so don't | |||
5832 | store the reference and then use it after a later fetch. Also, the | |||
5833 | elements of the array are also reused for each row, so take care if you | |||
5834 | want to take a reference to an element. See also L</bind_columns>. | |||
5835 | ||||
5836 | =head3 C<fetchrow_array> | |||
5837 | ||||
5838 | @ary = $sth->fetchrow_array; | |||
5839 | ||||
5840 | An alternative to C<fetchrow_arrayref>. Fetches the next row of data | |||
5841 | and returns it as a list containing the field values. Null fields | |||
5842 | are returned as C<undef> values in the list. | |||
5843 | ||||
5844 | If there are no more rows or if an error occurs, then C<fetchrow_array> | |||
5845 | returns an empty list. You should check C<$sth-E<gt>err> afterwards (or use | |||
5846 | the C<RaiseError> attribute) to discover if the empty list returned was | |||
5847 | due to an error. | |||
5848 | ||||
5849 | If called in a scalar context for a statement handle that has more | |||
5850 | than one column, it is undefined whether the driver will return | |||
5851 | the value of the first column or the last. So don't do that. | |||
5852 | Also, in a scalar context, an C<undef> is returned if there are no | |||
5853 | more rows or if an error occurred. That C<undef> can't be distinguished | |||
5854 | from an C<undef> returned because the first field value was NULL. | |||
5855 | For these reasons you should exercise some caution if you use | |||
5856 | C<fetchrow_array> in a scalar context. | |||
5857 | ||||
5858 | =head3 C<fetchrow_hashref> | |||
5859 | ||||
5860 | $hash_ref = $sth->fetchrow_hashref; | |||
5861 | $hash_ref = $sth->fetchrow_hashref($name); | |||
5862 | ||||
5863 | An alternative to C<fetchrow_arrayref>. Fetches the next row of data | |||
5864 | and returns it as a reference to a hash containing field name and field | |||
5865 | value pairs. Null fields are returned as C<undef> values in the hash. | |||
5866 | ||||
5867 | If there are no more rows or if an error occurs, then C<fetchrow_hashref> | |||
5868 | returns an C<undef>. You should check C<$sth-E<gt>err> afterwards (or use the | |||
5869 | C<RaiseError> attribute) to discover if the C<undef> returned was due to an | |||
5870 | error. | |||
5871 | ||||
5872 | The optional C<$name> parameter specifies the name of the statement handle | |||
5873 | attribute. For historical reasons it defaults to "C<NAME>", however using either | |||
5874 | "C<NAME_lc>" or "C<NAME_uc>" is recomended for portability. | |||
5875 | ||||
5876 | The keys of the hash are the same names returned by C<$sth-E<gt>{$name}>. If | |||
5877 | more than one field has the same name, there will only be one entry in | |||
5878 | the returned hash for those fields. | |||
5879 | ||||
5880 | Because of the extra work C<fetchrow_hashref> and Perl have to perform, it | |||
5881 | is not as efficient as C<fetchrow_arrayref> or C<fetchrow_array>. | |||
5882 | ||||
5883 | By default a reference to a new hash is returned for each row. | |||
5884 | It is likely that a future version of the DBI will support an | |||
5885 | attribute which will enable the same hash to be reused for each | |||
5886 | row. This will give a significant performance boost, but it won't | |||
5887 | be enabled by default because of the risk of breaking old code. | |||
5888 | ||||
5889 | ||||
5890 | =head3 C<fetchall_arrayref> | |||
5891 | ||||
5892 | $tbl_ary_ref = $sth->fetchall_arrayref; | |||
5893 | $tbl_ary_ref = $sth->fetchall_arrayref( $slice ); | |||
5894 | $tbl_ary_ref = $sth->fetchall_arrayref( $slice, $max_rows ); | |||
5895 | ||||
5896 | The C<fetchall_arrayref> method can be used to fetch all the data to be | |||
5897 | returned from a prepared and executed statement handle. It returns a | |||
5898 | reference to an array that contains one reference per row. | |||
5899 | ||||
5900 | If there are no rows to return, C<fetchall_arrayref> returns a reference | |||
5901 | to an empty array. If an error occurs, C<fetchall_arrayref> returns the | |||
5902 | data fetched thus far, which may be none. You should check C<$sth-E<gt>err> | |||
5903 | afterwards (or use the C<RaiseError> attribute) to discover if the data is | |||
5904 | complete or was truncated due to an error. | |||
5905 | ||||
5906 | If $slice is an array reference, C<fetchall_arrayref> uses L</fetchrow_arrayref> | |||
5907 | to fetch each row as an array ref. If the $slice array is not empty | |||
5908 | then it is used as a slice to select individual columns by perl array | |||
5909 | index number (starting at 0, unlike column and parameter numbers which | |||
5910 | start at 1). | |||
5911 | ||||
5912 | With no parameters, or if $slice is undefined, C<fetchall_arrayref> | |||
5913 | acts as if passed an empty array ref. | |||
5914 | ||||
5915 | If $slice is a hash reference, C<fetchall_arrayref> uses L</fetchrow_hashref> | |||
5916 | to fetch each row as a hash reference. If the $slice hash is empty then | |||
5917 | fetchrow_hashref() is simply called in a tight loop and the keys in the hashes | |||
5918 | have whatever name lettercase is returned by default from fetchrow_hashref. | |||
5919 | (See L</FetchHashKeyName> attribute.) If the $slice hash is not | |||
5920 | empty, then it is used as a slice to select individual columns by | |||
5921 | name. The values of the hash should be set to 1. The key names | |||
5922 | of the returned hashes match the letter case of the names in the | |||
5923 | parameter hash, regardless of the L</FetchHashKeyName> attribute. | |||
5924 | ||||
5925 | For example, to fetch just the first column of every row: | |||
5926 | ||||
5927 | $tbl_ary_ref = $sth->fetchall_arrayref([0]); | |||
5928 | ||||
5929 | To fetch the second to last and last column of every row: | |||
5930 | ||||
5931 | $tbl_ary_ref = $sth->fetchall_arrayref([-2,-1]); | |||
5932 | ||||
5933 | To fetch all fields of every row as a hash ref: | |||
5934 | ||||
5935 | $tbl_ary_ref = $sth->fetchall_arrayref({}); | |||
5936 | ||||
5937 | To fetch only the fields called "foo" and "bar" of every row as a hash ref | |||
5938 | (with keys named "foo" and "BAR"): | |||
5939 | ||||
5940 | $tbl_ary_ref = $sth->fetchall_arrayref({ foo=>1, BAR=>1 }); | |||
5941 | ||||
5942 | The first two examples return a reference to an array of array refs. | |||
5943 | The third and forth return a reference to an array of hash refs. | |||
5944 | ||||
5945 | If $max_rows is defined and greater than or equal to zero then it | |||
5946 | is used to limit the number of rows fetched before returning. | |||
5947 | fetchall_arrayref() can then be called again to fetch more rows. | |||
5948 | This is especially useful when you need the better performance of | |||
5949 | fetchall_arrayref() but don't have enough memory to fetch and return | |||
5950 | all the rows in one go. | |||
5951 | ||||
5952 | Here's an example (assumes RaiseError is enabled): | |||
5953 | ||||
5954 | my $rows = []; # cache for batches of rows | |||
5955 | while( my $row = ( shift(@$rows) || # get row from cache, or reload cache: | |||
5956 | shift(@{$rows=$sth->fetchall_arrayref(undef,10_000)||[]}) ) | |||
5957 | ) { | |||
5958 | ... | |||
5959 | } | |||
5960 | ||||
5961 | That I<might> be the fastest way to fetch and process lots of rows using the DBI, | |||
5962 | but it depends on the relative cost of method calls vs memory allocation. | |||
5963 | ||||
5964 | A standard C<while> loop with column binding is often faster because | |||
5965 | the cost of allocating memory for the batch of rows is greater than | |||
5966 | the saving by reducing method calls. It's possible that the DBI may | |||
5967 | provide a way to reuse the memory of a previous batch in future, which | |||
5968 | would then shift the balance back towards fetchall_arrayref(). | |||
5969 | ||||
5970 | ||||
5971 | =head3 C<fetchall_hashref> | |||
5972 | ||||
5973 | $hash_ref = $sth->fetchall_hashref($key_field); | |||
5974 | ||||
5975 | The C<fetchall_hashref> method can be used to fetch all the data to be | |||
5976 | returned from a prepared and executed statement handle. It returns a reference | |||
5977 | to a hash containing a key for each distinct value of the $key_field column | |||
5978 | that was fetched. For each key the corresponding value is a reference to a hash | |||
5979 | containing all the selected columns and their values, as returned by fetchrow_hashref(). | |||
5980 | ||||
5981 | If there are no rows to return, C<fetchall_hashref> returns a reference | |||
5982 | to an empty hash. If an error occurs, C<fetchall_hashref> returns the | |||
5983 | data fetched thus far, which may be none. You should check | |||
5984 | C<$sth-E<gt>err> afterwards (or use the C<RaiseError> attribute) to | |||
5985 | discover if the data is complete or was truncated due to an error. | |||
5986 | ||||
5987 | The $key_field parameter provides the name of the field that holds the | |||
5988 | value to be used for the key for the returned hash. For example: | |||
5989 | ||||
5990 | $dbh->{FetchHashKeyName} = 'NAME_lc'; | |||
5991 | $sth = $dbh->prepare("SELECT FOO, BAR, ID, NAME, BAZ FROM TABLE"); | |||
5992 | $sth->execute; | |||
5993 | $hash_ref = $sth->fetchall_hashref('id'); | |||
5994 | print "Name for id 42 is $hash_ref->{42}->{name}\n"; | |||
5995 | ||||
5996 | The $key_field parameter can also be specified as an integer column | |||
5997 | number (counting from 1). If $key_field doesn't match any column in | |||
5998 | the statement, as a name first then as a number, then an error is | |||
5999 | returned. | |||
6000 | ||||
6001 | For queries returing more than one 'key' column, you can specify | |||
6002 | multiple column names by passing $key_field as a reference to an | |||
6003 | array containing one or more key column names (or index numbers). | |||
6004 | For example: | |||
6005 | ||||
6006 | $sth = $dbh->prepare("SELECT foo, bar, baz FROM table"); | |||
6007 | $sth->execute; | |||
6008 | $hash_ref = $sth->fetchall_hashref( [ qw(foo bar) ] ); | |||
6009 | print "For foo 42 and bar 38, baz is $hash_ref->{42}->{38}->{baz}\n"; | |||
6010 | ||||
6011 | The fetchall_hashref() method is normally used only where the key | |||
6012 | fields values for each row are unique. If multiple rows are returned | |||
6013 | with the same values for the key fields then later rows overwrite | |||
6014 | earlier ones. | |||
6015 | ||||
6016 | =head3 C<finish> | |||
6017 | ||||
6018 | $rc = $sth->finish; | |||
6019 | ||||
6020 | Indicate that no more data will be fetched from this statement handle | |||
6021 | before it is either executed again or destroyed. The C<finish> method | |||
6022 | is rarely needed, and frequently overused, but can sometimes be | |||
6023 | helpful in a few very specific situations to allow the server to free | |||
6024 | up resources (such as sort buffers). | |||
6025 | ||||
6026 | When all the data has been fetched from a C<SELECT> statement, the | |||
6027 | driver should automatically call C<finish> for you. So you should | |||
6028 | I<not> normally need to call it explicitly I<except> when you know | |||
6029 | that you've not fetched all the data from a statement handle. | |||
6030 | The most common example is when you only want to fetch one row, | |||
6031 | but in that case the C<selectrow_*> methods are usually better anyway. | |||
6032 | Adding calls to C<finish> after each fetch loop is a common mistake, | |||
6033 | don't do it, it can mask genuine problems like uncaught fetch errors. | |||
6034 | ||||
6035 | Consider a query like: | |||
6036 | ||||
6037 | SELECT foo FROM table WHERE bar=? ORDER BY foo | |||
6038 | ||||
6039 | where you want to select just the first (smallest) "foo" value from a | |||
6040 | very large table. When executed, the database server will have to use | |||
6041 | temporary buffer space to store the sorted rows. If, after executing | |||
6042 | the handle and selecting one row, the handle won't be re-executed for | |||
6043 | some time and won't be destroyed, the C<finish> method can be used to tell | |||
6044 | the server that the buffer space can be freed. | |||
6045 | ||||
6046 | Calling C<finish> resets the L</Active> attribute for the statement. It | |||
6047 | may also make some statement handle attributes (such as C<NAME> and C<TYPE>) | |||
6048 | unavailable if they have not already been accessed (and thus cached). | |||
6049 | ||||
6050 | The C<finish> method does not affect the transaction status of the | |||
6051 | database connection. It has nothing to do with transactions. It's mostly an | |||
6052 | internal "housekeeping" method that is rarely needed. | |||
6053 | See also L</disconnect> and the L</Active> attribute. | |||
6054 | ||||
6055 | The C<finish> method should have been called C<discard_pending_rows>. | |||
6056 | ||||
6057 | ||||
6058 | =head3 C<rows> | |||
6059 | ||||
6060 | $rv = $sth->rows; | |||
6061 | ||||
6062 | Returns the number of rows affected by the last row affecting command, | |||
6063 | or -1 if the number of rows is not known or not available. | |||
6064 | ||||
6065 | Generally, you can only rely on a row count after a I<non>-C<SELECT> | |||
6066 | C<execute> (for some specific operations like C<UPDATE> and C<DELETE>), or | |||
6067 | after fetching all the rows of a C<SELECT> statement. | |||
6068 | ||||
6069 | For C<SELECT> statements, it is generally not possible to know how many | |||
6070 | rows will be returned except by fetching them all. Some drivers will | |||
6071 | return the number of rows the application has fetched so far, but | |||
6072 | others may return -1 until all rows have been fetched. So use of the | |||
6073 | C<rows> method or C<$DBI::rows> with C<SELECT> statements is not | |||
6074 | recommended. | |||
6075 | ||||
6076 | One alternative method to get a row count for a C<SELECT> is to execute a | |||
6077 | "SELECT COUNT(*) FROM ..." SQL statement with the same "..." as your | |||
6078 | query and then fetch the row count from that. | |||
6079 | ||||
6080 | ||||
6081 | =head3 C<bind_col> | |||
6082 | ||||
6083 | $rc = $sth->bind_col($column_number, \$var_to_bind); | |||
6084 | $rc = $sth->bind_col($column_number, \$var_to_bind, \%attr ); | |||
6085 | $rc = $sth->bind_col($column_number, \$var_to_bind, $bind_type ); | |||
6086 | ||||
6087 | Binds a Perl variable and/or some attributes to an output column | |||
6088 | (field) of a C<SELECT> statement. Column numbers count up from 1. | |||
6089 | You do not need to bind output columns in order to fetch data. | |||
6090 | For maximum portability between drivers, bind_col() should be called | |||
6091 | after execute() and not before. | |||
6092 | See also C<bind_columns> for an example. | |||
6093 | ||||
6094 | The binding is performed at a low level using Perl aliasing. | |||
6095 | Whenever a row is fetched from the database $var_to_bind appears | |||
6096 | to be automatically updated simply because it now refers to the same | |||
6097 | memory location as the corresponding column value. This makes using | |||
6098 | bound variables very efficient. | |||
6099 | Binding a tied variable doesn't work, currently. | |||
6100 | ||||
6101 | The L</bind_param> method | |||
6102 | performs a similar, but opposite, function for input variables. | |||
6103 | ||||
6104 | B<Data Types for Column Binding> | |||
6105 | ||||
6106 | The C<\%attr> parameter can be used to hint at the data type | |||
6107 | formatting the column should have. For example, you can use: | |||
6108 | ||||
6109 | $sth->bind_col(1, undef, { TYPE => SQL_DATETIME }); | |||
6110 | ||||
6111 | to specify that you'd like the column (which presumably is some | |||
6112 | kind of datetime type) to be returned in the standard format for | |||
6113 | SQL_DATETIME, which is 'YYYY-MM-DD HH:MM:SS', rather than the | |||
6114 | native formatting the database would normally use. | |||
6115 | ||||
6116 | There's no $var_to_bind in that example to emphasize the point | |||
6117 | that bind_col() works on the underlying column value and not just | |||
6118 | a particular bound variable. | |||
6119 | ||||
6120 | As a short-cut for the common case, the data type can be passed | |||
6121 | directly, in place of the C<\%attr> hash reference. This example is | |||
6122 | equivalent to the one above: | |||
6123 | ||||
6124 | $sth->bind_col(1, undef, SQL_DATETIME); | |||
6125 | ||||
6126 | The C<TYPE> value indicates the standard (non-driver-specific) type for | |||
6127 | this parameter. To specify the driver-specific type, the driver may | |||
6128 | support a driver-specific attribute, such as C<{ ora_type =E<gt> 97 }>. | |||
6129 | ||||
6130 | The SQL_DATETIME and other related constants can be imported using | |||
6131 | ||||
6132 | use DBI qw(:sql_types); | |||
6133 | ||||
6134 | See L</"DBI Constants"> for more information. | |||
6135 | ||||
6136 | The data type for a bind variable cannot be changed after the first | |||
6137 | C<bind_col> call. In fact the whole \%attr parameter is 'sticky' | |||
6138 | in the sense that a driver only needs to consider the \%attr parameter | |||
6139 | for the first call for a given $sth and column. | |||
6140 | ||||
6141 | The TYPE attribute for bind_col() was first specified in DBI 1.41. | |||
6142 | ||||
6143 | ||||
6144 | =head3 C<bind_columns> | |||
6145 | ||||
6146 | $rc = $sth->bind_columns(@list_of_refs_to_vars_to_bind); | |||
6147 | ||||
6148 | Calls L</bind_col> for each column of the C<SELECT> statement. | |||
6149 | ||||
6150 | The list of references should have the same number of elements as the number of | |||
6151 | columns in the C<SELECT> statement. If it doesn't then C<bind_columns> will | |||
6152 | bind the elements given, upto the number of columns, and then return an error. | |||
6153 | ||||
6154 | For maximum portability between drivers, bind_columns() should be called | |||
6155 | after execute() and not before. | |||
6156 | ||||
6157 | For example: | |||
6158 | ||||
6159 | $dbh->{RaiseError} = 1; # do this, or check every call for errors | |||
6160 | $sth = $dbh->prepare(q{ SELECT region, sales FROM sales_by_region }); | |||
6161 | $sth->execute; | |||
6162 | my ($region, $sales); | |||
6163 | ||||
6164 | # Bind Perl variables to columns: | |||
6165 | $rv = $sth->bind_columns(\$region, \$sales); | |||
6166 | ||||
6167 | # you can also use Perl's \(...) syntax (see perlref docs): | |||
6168 | # $sth->bind_columns(\($region, $sales)); | |||
6169 | ||||
6170 | # Column binding is the most efficient way to fetch data | |||
6171 | while ($sth->fetch) { | |||
6172 | print "$region: $sales\n"; | |||
6173 | } | |||
6174 | ||||
6175 | For compatibility with old scripts, the first parameter will be | |||
6176 | ignored if it is C<undef> or a hash reference. | |||
6177 | ||||
6178 | Here's a more fancy example that binds columns to the values I<inside> | |||
6179 | a hash (thanks to H.Merijn Brand): | |||
6180 | ||||
6181 | $sth->execute; | |||
6182 | my %row; | |||
6183 | $sth->bind_columns( \( @row{ @{$sth->{NAME_lc} } } )); | |||
6184 | while ($sth->fetch) { | |||
6185 | print "$row{region}: $row{sales}\n"; | |||
6186 | } | |||
6187 | ||||
6188 | ||||
6189 | =head3 C<dump_results> | |||
6190 | ||||
6191 | $rows = $sth->dump_results($maxlen, $lsep, $fsep, $fh); | |||
6192 | ||||
6193 | Fetches all the rows from C<$sth>, calls C<DBI::neat_list> for each row, and | |||
6194 | prints the results to C<$fh> (defaults to C<STDOUT>) separated by C<$lsep> | |||
6195 | (default C<"\n">). C<$fsep> defaults to C<", "> and C<$maxlen> defaults to 35. | |||
6196 | ||||
6197 | This method is designed as a handy utility for prototyping and | |||
6198 | testing queries. Since it uses L</neat_list> to | |||
6199 | format and edit the string for reading by humans, it is not recomended | |||
6200 | for data transfer applications. | |||
6201 | ||||
6202 | ||||
6203 | =head2 Statement Handle Attributes | |||
6204 | ||||
6205 | This section describes attributes specific to statement handles. Most | |||
6206 | of these attributes are read-only. | |||
6207 | ||||
6208 | Changes to these statement handle attributes do not affect any other | |||
6209 | existing or future statement handles. | |||
6210 | ||||
6211 | Attempting to set or get the value of an unknown attribute generates a warning, | |||
6212 | except for private driver specific attributes (which all have names | |||
6213 | starting with a lowercase letter). | |||
6214 | ||||
6215 | Example: | |||
6216 | ||||
6217 | ... = $h->{NUM_OF_FIELDS}; # get/read | |||
6218 | ||||
6219 | Some drivers cannot provide valid values for some or all of these | |||
6220 | attributes until after C<$sth-E<gt>execute> has been successfully | |||
6221 | called. Typically the attribute will be C<undef> in these situations. | |||
6222 | ||||
6223 | Some attributes, like NAME, are not appropriate to some types of | |||
6224 | statement, like SELECT. Typically the attribute will be C<undef> | |||
6225 | in these situations. | |||
6226 | ||||
6227 | For drivers which support stored procedures and multiple result sets | |||
6228 | (see L</more_results>) these attributes relate to the I<current> result set. | |||
6229 | ||||
6230 | See also L</finish> to learn more about the effect it | |||
6231 | may have on some attributes. | |||
6232 | ||||
6233 | =head3 C<NUM_OF_FIELDS> (integer, read-only) | |||
6234 | ||||
6235 | Number of fields (columns) in the data the prepared statement may return. | |||
6236 | Statements that don't return rows of data, like C<DELETE> and C<CREATE> | |||
6237 | set C<NUM_OF_FIELDS> to 0 (though it may be undef in some drivers). | |||
6238 | ||||
6239 | ||||
6240 | =head3 C<NUM_OF_PARAMS> (integer, read-only) | |||
6241 | ||||
6242 | The number of parameters (placeholders) in the prepared statement. | |||
6243 | See SUBSTITUTION VARIABLES below for more details. | |||
6244 | ||||
6245 | ||||
6246 | =head3 C<NAME> (array-ref, read-only) | |||
6247 | ||||
6248 | Returns a reference to an array of field names for each column. The | |||
6249 | names may contain spaces but should not be truncated or have any | |||
6250 | trailing space. Note that the names have the letter case (upper, lower | |||
6251 | or mixed) as returned by the driver being used. Portable applications | |||
6252 | should use L</NAME_lc> or L</NAME_uc>. | |||
6253 | ||||
6254 | print "First column name: $sth->{NAME}->[0]\n"; | |||
6255 | ||||
6256 | =head3 C<NAME_lc> (array-ref, read-only) | |||
6257 | ||||
6258 | Like L</NAME> but always returns lowercase names. | |||
6259 | ||||
6260 | =head3 C<NAME_uc> (array-ref, read-only) | |||
6261 | ||||
6262 | Like L</NAME> but always returns uppercase names. | |||
6263 | ||||
6264 | =head3 C<NAME_hash> (hash-ref, read-only) | |||
6265 | ||||
6266 | =head3 C<NAME_lc_hash> (hash-ref, read-only) | |||
6267 | ||||
6268 | =head3 C<NAME_uc_hash> (hash-ref, read-only) | |||
6269 | ||||
6270 | The C<NAME_hash>, C<NAME_lc_hash>, and C<NAME_uc_hash> attributes | |||
6271 | return column name information as a reference to a hash. | |||
6272 | ||||
6273 | The keys of the hash are the names of the columns. The letter case of | |||
6274 | the keys corresponds to the letter case returned by the C<NAME>, | |||
6275 | C<NAME_lc>, and C<NAME_uc> attributes respectively (as described above). | |||
6276 | ||||
6277 | The value of each hash entry is the perl index number of the | |||
6278 | corresponding column (counting from 0). For example: | |||
6279 | ||||
6280 | $sth = $dbh->prepare("select Id, Name from table"); | |||
6281 | $sth->execute; | |||
6282 | @row = $sth->fetchrow_array; | |||
6283 | print "Name $row[ $sth->{NAME_lc_hash}{name} ]\n"; | |||
6284 | ||||
6285 | ||||
6286 | =head3 C<TYPE> (array-ref, read-only) | |||
6287 | ||||
6288 | Returns a reference to an array of integer values for each | |||
6289 | column. The value indicates the data type of the corresponding column. | |||
6290 | ||||
6291 | The values correspond to the international standards (ANSI X3.135 | |||
6292 | and ISO/IEC 9075) which, in general terms, means ODBC. Driver-specific | |||
6293 | types that don't exactly match standard types should generally return | |||
6294 | the same values as an ODBC driver supplied by the makers of the | |||
6295 | database. That might include private type numbers in ranges the vendor | |||
6296 | has officially registered with the ISO working group: | |||
6297 | ||||
6298 | ftp://sqlstandards.org/SC32/SQL_Registry/ | |||
6299 | ||||
6300 | Where there's no vendor-supplied ODBC driver to be compatible with, | |||
6301 | the DBI driver can use type numbers in the range that is now | |||
6302 | officially reserved for use by the DBI: -9999 to -9000. | |||
6303 | ||||
6304 | All possible values for C<TYPE> should have at least one entry in the | |||
6305 | output of the C<type_info_all> method (see L</type_info_all>). | |||
6306 | ||||
6307 | =head3 C<PRECISION> (array-ref, read-only) | |||
6308 | ||||
6309 | Returns a reference to an array of integer values for each column. | |||
6310 | ||||
6311 | For numeric columns, the value is the maximum number of digits | |||
6312 | (without considering a sign character or decimal point). Note that | |||
6313 | the "display size" for floating point types (REAL, FLOAT, DOUBLE) | |||
6314 | can be up to 7 characters greater than the precision (for the | |||
6315 | sign + decimal point + the letter E + a sign + 2 or 3 digits). | |||
6316 | ||||
6317 | For any character type column the value is the OCTET_LENGTH, | |||
6318 | in other words the number of bytes, not characters. | |||
6319 | ||||
6320 | (More recent standards refer to this as COLUMN_SIZE but we stick | |||
6321 | with PRECISION for backwards compatibility.) | |||
6322 | ||||
6323 | =head3 C<SCALE> (array-ref, read-only) | |||
6324 | ||||
6325 | Returns a reference to an array of integer values for each column. | |||
6326 | NULL (C<undef>) values indicate columns where scale is not applicable. | |||
6327 | ||||
6328 | =head3 C<NULLABLE> (array-ref, read-only) | |||
6329 | ||||
6330 | Returns a reference to an array indicating the possibility of each | |||
6331 | column returning a null. Possible values are C<0> | |||
6332 | (or an empty string) = no, C<1> = yes, C<2> = unknown. | |||
6333 | ||||
6334 | print "First column may return NULL\n" if $sth->{NULLABLE}->[0]; | |||
6335 | ||||
6336 | ||||
6337 | =head3 C<CursorName> (string, read-only) | |||
6338 | ||||
6339 | Returns the name of the cursor associated with the statement handle, if | |||
6340 | available. If not available or if the database driver does not support the | |||
6341 | C<"where current of ..."> SQL syntax, then it returns C<undef>. | |||
6342 | ||||
6343 | ||||
6344 | =head3 C<Database> (dbh, read-only) | |||
6345 | ||||
6346 | Returns the parent $dbh of the statement handle. | |||
6347 | ||||
6348 | ||||
6349 | =head3 C<ParamValues> (hash ref, read-only) | |||
6350 | ||||
6351 | Returns a reference to a hash containing the values currently bound | |||
6352 | to placeholders. The keys of the hash are the 'names' of the | |||
6353 | placeholders, typically integers starting at 1. Returns undef if | |||
6354 | not supported by the driver. | |||
6355 | ||||
6356 | See L</ShowErrorStatement> for an example of how this is used. | |||
6357 | ||||
6358 | If the driver supports C<ParamValues> but no values have been bound | |||
6359 | yet then the driver should return a hash with placeholders names | |||
6360 | in the keys but all the values undef, but some drivers may return | |||
6361 | a ref to an empty hash. | |||
6362 | ||||
6363 | It is possible that the values in the hash returned by C<ParamValues> | |||
6364 | are not I<exactly> the same as those passed to bind_param() or execute(). | |||
6365 | The driver may have slightly modified values in some way based on the | |||
6366 | TYPE the value was bound with. For example a floating point value | |||
6367 | bound as an SQL_INTEGER type may be returned as an integer. | |||
6368 | The values returned by C<ParamValues> can be passed to another | |||
6369 | bind_param() method with the same TYPE and will be seen by the | |||
6370 | database as the same value. | |||
6371 | ||||
6372 | It is also possible that the keys in the hash returned by C<ParamValues> | |||
6373 | are not exactly the same as those implied by the prepared statement. | |||
6374 | For example, DBD::Oracle translates 'C<?>' placeholders into 'C<:pN>' | |||
6375 | where N is a sequence number starting at 1. | |||
6376 | ||||
6377 | The C<ParamValues> attribute was added in DBI 1.28. | |||
6378 | ||||
6379 | =head3 C<ParamArrays> (hash ref, read-only) | |||
6380 | ||||
6381 | Returns a reference to a hash containing the values currently bound to | |||
6382 | placeholders with L</execute_array> or L</bind_param_array>. The | |||
6383 | keys of the hash are the 'names' of the placeholders, typically | |||
6384 | integers starting at 1. Returns undef if not supported by the driver | |||
6385 | or no arrays of parameters are bound. | |||
6386 | ||||
6387 | Each key value is an array reference containing a list of the bound | |||
6388 | parameters for that column. | |||
6389 | ||||
6390 | For example: | |||
6391 | ||||
6392 | $sth = $dbh->prepare("INSERT INTO staff (id, name) values (?,?)"); | |||
6393 | $sth->execute_array({},[1,2], ['fred','dave']); | |||
6394 | if ($sth->{ParamArrays}) { | |||
6395 | foreach $param (keys %{$sth->{ParamArrays}}) { | |||
6396 | printf "Parameters for %s : %s\n", $param, | |||
6397 | join(",", @{$sth->{ParamArrays}->{$param}}); | |||
6398 | } | |||
6399 | } | |||
6400 | ||||
6401 | It is possible that the values in the hash returned by C<ParamArrays> | |||
6402 | are not I<exactly> the same as those passed to L</bind_param_array> or | |||
6403 | L</execute_array>. The driver may have slightly modified values in some | |||
6404 | way based on the TYPE the value was bound with. For example a floating | |||
6405 | point value bound as an SQL_INTEGER type may be returned as an | |||
6406 | integer. | |||
6407 | ||||
6408 | It is also possible that the keys in the hash returned by | |||
6409 | C<ParamArrays> are not exactly the same as those implied by the | |||
6410 | prepared statement. For example, DBD::Oracle translates 'C<?>' | |||
6411 | placeholders into 'C<:pN>' where N is a sequence number starting at 1. | |||
6412 | ||||
6413 | =head3 C<ParamTypes> (hash ref, read-only) | |||
6414 | ||||
6415 | Returns a reference to a hash containing the type information | |||
6416 | currently bound to placeholders. The keys of the hash are the | |||
6417 | 'names' of the placeholders: either integers starting at 1, or, | |||
6418 | for drivers that support named placeholders, the actual parameter | |||
6419 | name string. The hash values are hashrefs of type information in | |||
6420 | the same form as that provided to the various bind_param() methods | |||
6421 | (See L</bind_param> for the format and values), | |||
6422 | plus anything else that was passed as the third argument to bind_param(). | |||
6423 | Returns undef if not supported by the driver. | |||
6424 | ||||
6425 | If the driver supports C<ParamTypes>, but no values have been bound | |||
6426 | yet, then the driver should return a hash with the placeholder name | |||
6427 | keys, but all the values undef; however, some drivers may return | |||
6428 | a ref to an empty hash, or, alternately, may provide type | |||
6429 | information supplied by the database (only a few databases can do that). | |||
6430 | ||||
6431 | It is possible that the values in the hash returned by C<ParamTypes> | |||
6432 | are not I<exactly> the same as those passed to bind_param() or execute(). | |||
6433 | The driver may have modified the type information in some way based | |||
6434 | on the bound values, other hints provided by the prepare()'d | |||
6435 | SQL statement, or alternate type mappings required by the driver or target | |||
6436 | database system. | |||
6437 | ||||
6438 | It is also possible that the keys in the hash returned by C<ParamTypes> | |||
6439 | are not exactly the same as those implied by the prepared statement. | |||
6440 | For example, DBD::Oracle translates 'C<?>' placeholders into 'C<:pN>' | |||
6441 | where N is a sequence number starting at 1. | |||
6442 | ||||
6443 | The C<ParamTypes> attribute was added in DBI 1.49. Implementation | |||
6444 | is the responsibility of individual drivers; the DBI layer default | |||
6445 | implementation simply returns undef. | |||
6446 | ||||
6447 | ||||
6448 | =head3 C<Statement> (string, read-only) | |||
6449 | ||||
6450 | Returns the statement string passed to the L</prepare> method. | |||
6451 | ||||
6452 | ||||
6453 | =head3 C<RowsInCache> (integer, read-only) | |||
6454 | ||||
6455 | If the driver supports a local row cache for C<SELECT> statements, then | |||
6456 | this attribute holds the number of un-fetched rows in the cache. If the | |||
6457 | driver doesn't, then it returns C<undef>. Note that some drivers pre-fetch | |||
6458 | rows on execute, whereas others wait till the first fetch. | |||
6459 | ||||
6460 | See also the L</RowCacheSize> database handle attribute. | |||
6461 | ||||
6462 | =head1 FURTHER INFORMATION | |||
6463 | ||||
6464 | =head2 Catalog Methods | |||
6465 | ||||
6466 | An application can retrieve metadata information from the DBMS by issuing | |||
6467 | appropriate queries on the views of the Information Schema. Unfortunately, | |||
6468 | C<INFORMATION_SCHEMA> views are seldom supported by the DBMS. | |||
6469 | Special methods (catalog methods) are available to return result sets | |||
6470 | for a small but important portion of that metadata: | |||
6471 | ||||
6472 | column_info | |||
6473 | foreign_key_info | |||
6474 | primary_key_info | |||
6475 | table_info | |||
6476 | statistics_info | |||
6477 | ||||
6478 | All catalog methods accept arguments in order to restrict the result sets. | |||
6479 | Passing C<undef> to an optional argument does not constrain the search for | |||
6480 | that argument. | |||
6481 | However, an empty string ('') is treated as a regular search criteria | |||
6482 | and will only match an empty value. | |||
6483 | ||||
6484 | B<Note>: SQL/CLI and ODBC differ in the handling of empty strings. An | |||
6485 | empty string will not restrict the result set in SQL/CLI. | |||
6486 | ||||
6487 | Most arguments in the catalog methods accept only I<ordinary values>, e.g. | |||
6488 | the arguments of C<primary_key_info()>. | |||
6489 | Such arguments are treated as a literal string, i.e. the case is significant | |||
6490 | and quote characters are taken literally. | |||
6491 | ||||
6492 | Some arguments in the catalog methods accept I<search patterns> (strings | |||
6493 | containing '_' and/or '%'), e.g. the C<$table> argument of C<column_info()>. | |||
6494 | Passing '%' is equivalent to leaving the argument C<undef>. | |||
6495 | ||||
6496 | B<Caveat>: The underscore ('_') is valid and often used in SQL identifiers. | |||
6497 | Passing such a value to a search pattern argument may return more rows than | |||
6498 | expected! | |||
6499 | To include pattern characters as literals, they must be preceded by an | |||
6500 | escape character which can be achieved with | |||
6501 | ||||
6502 | $esc = $dbh->get_info( 14 ); # SQL_SEARCH_PATTERN_ESCAPE | |||
6503 | $search_pattern =~ s/([_%])/$esc$1/g; | |||
6504 | ||||
6505 | The ODBC and SQL/CLI specifications define a way to change the default | |||
6506 | behaviour described above: All arguments (except I<list value arguments>) | |||
6507 | are treated as I<identifier> if the C<SQL_ATTR_METADATA_ID> attribute is | |||
6508 | set to C<SQL_TRUE>. | |||
6509 | I<Quoted identifiers> are very similar to I<ordinary values>, i.e. their | |||
6510 | body (the string within the quotes) is interpreted literally. | |||
6511 | I<Unquoted identifiers> are compared in UPPERCASE. | |||
6512 | ||||
6513 | The DBI (currently) does not support the C<SQL_ATTR_METADATA_ID> attribute, | |||
6514 | i.e. it behaves like an ODBC driver where C<SQL_ATTR_METADATA_ID> is set to | |||
6515 | C<SQL_FALSE>. | |||
6516 | ||||
6517 | ||||
6518 | =head2 Transactions | |||
6519 | ||||
6520 | Transactions are a fundamental part of any robust database system. They | |||
6521 | protect against errors and database corruption by ensuring that sets of | |||
6522 | related changes to the database take place in atomic (indivisible, | |||
6523 | all-or-nothing) units. | |||
6524 | ||||
6525 | This section applies to databases that support transactions and where | |||
6526 | C<AutoCommit> is off. See L</AutoCommit> for details of using C<AutoCommit> | |||
6527 | with various types of databases. | |||
6528 | ||||
6529 | The recommended way to implement robust transactions in Perl | |||
6530 | applications is to use C<RaiseError> and S<C<eval { ... }>> | |||
6531 | (which is very fast, unlike S<C<eval "...">>). For example: | |||
6532 | ||||
6533 | $dbh->{AutoCommit} = 0; # enable transactions, if possible | |||
6534 | $dbh->{RaiseError} = 1; | |||
6535 | eval { | |||
6536 | foo(...) # do lots of work here | |||
6537 | bar(...) # including inserts | |||
6538 | baz(...) # and updates | |||
6539 | $dbh->commit; # commit the changes if we get this far | |||
6540 | }; | |||
6541 | if ($@) { | |||
6542 | warn "Transaction aborted because $@"; | |||
6543 | # now rollback to undo the incomplete changes | |||
6544 | # but do it in an eval{} as it may also fail | |||
6545 | eval { $dbh->rollback }; | |||
6546 | # add other application on-error-clean-up code here | |||
6547 | } | |||
6548 | ||||
6549 | If the C<RaiseError> attribute is not set, then DBI calls would need to be | |||
6550 | manually checked for errors, typically like this: | |||
6551 | ||||
6552 | $h->method(@args) or die $h->errstr; | |||
6553 | ||||
6554 | With C<RaiseError> set, the DBI will automatically C<die> if any DBI method | |||
6555 | call on that handle (or a child handle) fails, so you don't have to | |||
6556 | test the return value of each method call. See L</RaiseError> for more | |||
6557 | details. | |||
6558 | ||||
6559 | A major advantage of the C<eval> approach is that the transaction will be | |||
6560 | properly rolled back if I<any> code (not just DBI calls) in the inner | |||
6561 | application dies for any reason. The major advantage of using the | |||
6562 | C<$h-E<gt>{RaiseError}> attribute is that all DBI calls will be checked | |||
6563 | automatically. Both techniques are strongly recommended. | |||
6564 | ||||
6565 | After calling C<commit> or C<rollback> many drivers will not let you | |||
6566 | fetch from a previously active C<SELECT> statement handle that's a child | |||
6567 | of the same database handle. A typical way round this is to connect the | |||
6568 | the database twice and use one connection for C<SELECT> statements. | |||
6569 | ||||
6570 | See L</AutoCommit> and L</disconnect> for other important information | |||
6571 | about transactions. | |||
6572 | ||||
6573 | ||||
6574 | =head2 Handling BLOB / LONG / Memo Fields | |||
6575 | ||||
6576 | Many databases support "blob" (binary large objects), "long", or similar | |||
6577 | datatypes for holding very long strings or large amounts of binary | |||
6578 | data in a single field. Some databases support variable length long | |||
6579 | values over 2,000,000,000 bytes in length. | |||
6580 | ||||
6581 | Since values of that size can't usually be held in memory, and because | |||
6582 | databases can't usually know in advance the length of the longest long | |||
6583 | that will be returned from a C<SELECT> statement (unlike other data | |||
6584 | types), some special handling is required. | |||
6585 | ||||
6586 | In this situation, the value of the C<$h-E<gt>{LongReadLen}> | |||
6587 | attribute is used to determine how much buffer space to allocate | |||
6588 | when fetching such fields. The C<$h-E<gt>{LongTruncOk}> attribute | |||
6589 | is used to determine how to behave if a fetched value can't fit | |||
6590 | into the buffer. | |||
6591 | ||||
6592 | See the description of L</LongReadLen> for more information. | |||
6593 | ||||
6594 | When trying to insert long or binary values, placeholders should be used | |||
6595 | since there are often limits on the maximum size of an C<INSERT> | |||
6596 | statement and the L</quote> method generally can't cope with binary | |||
6597 | data. See L</Placeholders and Bind Values>. | |||
6598 | ||||
6599 | ||||
6600 | =head2 Simple Examples | |||
6601 | ||||
6602 | Here's a complete example program to select and fetch some data: | |||
6603 | ||||
6604 | my $data_source = "dbi::DriverName:db_name"; | |||
6605 | my $dbh = DBI->connect($data_source, $user, $password) | |||
6606 | or die "Can't connect to $data_source: $DBI::errstr"; | |||
6607 | ||||
6608 | my $sth = $dbh->prepare( q{ | |||
6609 | SELECT name, phone | |||
6610 | FROM mytelbook | |||
6611 | }) or die "Can't prepare statement: $DBI::errstr"; | |||
6612 | ||||
6613 | my $rc = $sth->execute | |||
6614 | or die "Can't execute statement: $DBI::errstr"; | |||
6615 | ||||
6616 | print "Query will return $sth->{NUM_OF_FIELDS} fields.\n\n"; | |||
6617 | print "Field names: @{ $sth->{NAME} }\n"; | |||
6618 | ||||
6619 | while (($name, $phone) = $sth->fetchrow_array) { | |||
6620 | print "$name: $phone\n"; | |||
6621 | } | |||
6622 | # check for problems which may have terminated the fetch early | |||
6623 | die $sth->errstr if $sth->err; | |||
6624 | ||||
6625 | $dbh->disconnect; | |||
6626 | ||||
6627 | Here's a complete example program to insert some data from a file. | |||
6628 | (This example uses C<RaiseError> to avoid needing to check each call). | |||
6629 | ||||
6630 | my $dbh = DBI->connect("dbi:DriverName:db_name", $user, $password, { | |||
6631 | RaiseError => 1, AutoCommit => 0 | |||
6632 | }); | |||
6633 | ||||
6634 | my $sth = $dbh->prepare( q{ | |||
6635 | INSERT INTO table (name, phone) VALUES (?, ?) | |||
6636 | }); | |||
6637 | ||||
6638 | open FH, "<phone.csv" or die "Unable to open phone.csv: $!"; | |||
6639 | while (<FH>) { | |||
6640 | chomp; | |||
6641 | my ($name, $phone) = split /,/; | |||
6642 | $sth->execute($name, $phone); | |||
6643 | } | |||
6644 | close FH; | |||
6645 | ||||
6646 | $dbh->commit; | |||
6647 | $dbh->disconnect; | |||
6648 | ||||
6649 | Here's how to convert fetched NULLs (undefined values) into empty strings: | |||
6650 | ||||
6651 | while($row = $sth->fetchrow_arrayref) { | |||
6652 | # this is a fast and simple way to deal with nulls: | |||
6653 | foreach (@$row) { $_ = '' unless defined } | |||
6654 | print "@$row\n"; | |||
6655 | } | |||
6656 | ||||
6657 | The C<q{...}> style quoting used in these examples avoids clashing with | |||
6658 | quotes that may be used in the SQL statement. Use the double-quote like | |||
6659 | C<qq{...}> operator if you want to interpolate variables into the string. | |||
6660 | See L<perlop/"Quote and Quote-like Operators"> for more details. | |||
6661 | ||||
6662 | =head2 Threads and Thread Safety | |||
6663 | ||||
6664 | Perl 5.7 and later support a new threading model called iThreads. | |||
6665 | (The old "5.005 style" threads are not supported by the DBI.) | |||
6666 | ||||
6667 | In the iThreads model each thread has it's own copy of the perl | |||
6668 | interpreter. When a new thread is created the original perl | |||
6669 | interpreter is 'cloned' to create a new copy for the new thread. | |||
6670 | ||||
6671 | If the DBI and drivers are loaded and handles created before the | |||
6672 | thread is created then it will get a cloned copy of the DBI, the | |||
6673 | drivers and the handles. | |||
6674 | ||||
6675 | However, the internal pointer data within the handles will refer | |||
6676 | to the DBI and drivers in the original interpreter. Using those | |||
6677 | handles in the new interpreter thread is not safe, so the DBI detects | |||
6678 | this and croaks on any method call using handles that don't belong | |||
6679 | to the current thread (except for DESTROY). | |||
6680 | ||||
6681 | Because of this (possibly temporary) restriction, newly created | |||
6682 | threads must make their own connctions to the database. Handles | |||
6683 | can't be shared across threads. | |||
6684 | ||||
6685 | But BEWARE, some underlying database APIs (the code the DBD driver | |||
6686 | uses to talk to the database, often supplied by the database vendor) | |||
6687 | are not thread safe. If it's not thread safe, then allowing more | |||
6688 | than one thread to enter the code at the same time may cause | |||
6689 | subtle/serious problems. In some cases allowing more than | |||
6690 | one thread to enter the code, even if I<not> at the same time, | |||
6691 | can cause problems. You have been warned. | |||
6692 | ||||
6693 | Using DBI with perl threads is not yet recommended for production | |||
6694 | environments. For more information see | |||
6695 | L<http://www.perlmonks.org/index.pl?node_id=288022> | |||
6696 | ||||
6697 | Note: There is a bug in perl 5.8.2 when configured with threads | |||
6698 | and debugging enabled (bug #24463) which causes a DBI test to fail. | |||
6699 | ||||
6700 | =head2 Signal Handling and Canceling Operations | |||
6701 | ||||
6702 | [The following only applies to systems with unix-like signal handling. | |||
6703 | I'd welcome additions for other systems, especially Windows.] | |||
6704 | ||||
6705 | The first thing to say is that signal handling in Perl versions less | |||
6706 | than 5.8 is I<not> safe. There is always a small risk of Perl | |||
6707 | crashing and/or core dumping when, or after, handling a signal | |||
6708 | because the signal could arrive and be handled while internal data | |||
6709 | structures are being changed. If the signal handling code | |||
6710 | used those same internal data structures it could cause all manner | |||
6711 | of subtle and not-so-subtle problems. The risk was reduced with | |||
6712 | 5.4.4 but was still present in all perls up through 5.8.0. | |||
6713 | ||||
6714 | Beginning in perl 5.8.0 perl implements 'safe' signal handling if | |||
6715 | your system has the POSIX sigaction() routine. Now when a signal | |||
6716 | is delivered perl just makes a note of it but does I<not> run the | |||
6717 | %SIG handler. The handling is 'defered' until a 'safe' moment. | |||
6718 | ||||
6719 | Although this change made signal handling safe, it also lead to | |||
6720 | a problem with signals being defered for longer than you'd like. | |||
6721 | If a signal arrived while executing a system call, such as waiting | |||
6722 | for data on a network connection, the signal is noted and then the | |||
6723 | system call that was executing returns with an EINTR error code | |||
6724 | to indicate that it was interrupted. All fine so far. | |||
6725 | ||||
6726 | The problem comes when the code that made the system call sees the | |||
6727 | EINTR code and decides it's going to call it again. Perl doesn't | |||
6728 | do that, but database code sometimes does. If that happens then the | |||
6729 | signal handler doesn't get called untill later. Maybe much later. | |||
6730 | ||||
6731 | Fortunately there are ways around this which we'll discuss below. | |||
6732 | Unfortunately they make signals unsafe again. | |||
6733 | ||||
6734 | The two most common uses of signals in relation to the DBI are for | |||
6735 | canceling operations when the user types Ctrl-C (interrupt), and for | |||
6736 | implementing a timeout using C<alarm()> and C<$SIG{ALRM}>. | |||
6737 | ||||
6738 | =over 4 | |||
6739 | ||||
6740 | =item Cancel | |||
6741 | ||||
6742 | The DBI provides a C<cancel> method for statement handles. The | |||
6743 | C<cancel> method should abort the current operation and is designed | |||
6744 | to be called from a signal handler. For example: | |||
6745 | ||||
6746 | $SIG{INT} = sub { $sth->cancel }; | |||
6747 | ||||
6748 | However, few drivers implement this (the DBI provides a default | |||
6749 | method that just returns C<undef>) and, even if implemented, there | |||
6750 | is still a possibility that the statement handle, and even the | |||
6751 | parent database handle, will not be usable afterwards. | |||
6752 | ||||
6753 | If C<cancel> returns true, then it has successfully | |||
6754 | invoked the database engine's own cancel function. If it returns false, | |||
6755 | then C<cancel> failed. If it returns C<undef>, then the database | |||
6756 | driver does not have cancel implemented - very few do. | |||
6757 | ||||
6758 | =item Timeout | |||
6759 | ||||
6760 | The traditional way to implement a timeout is to set C<$SIG{ALRM}> | |||
6761 | to refer to some code that will be executed when an ALRM signal | |||
6762 | arrives and then to call alarm($seconds) to schedule an ALRM signal | |||
6763 | to be delivered $seconds in the future. For example: | |||
6764 | ||||
6765 | eval { | |||
6766 | local $SIG{ALRM} = sub { die "TIMEOUT\n" }; | |||
6767 | alarm($seconds); | |||
6768 | ... code to execute with timeout here ... | |||
6769 | alarm(0); # cancel alarm (if code ran fast) | |||
6770 | }; | |||
6771 | alarm(0); # cancel alarm (if eval failed) | |||
6772 | if ( $@ eq "TIMEOUT\n" ) { ... } | |||
6773 | ||||
6774 | Unfortunately, as described above, this won't always work as expected, | |||
6775 | depending on your perl version and the underlying database code. | |||
6776 | ||||
6777 | With Oracle for instance (DBD::Oracle), if the system which hosts | |||
6778 | the database is down the DBI->connect() call will hang for several | |||
6779 | minutes before returning an error. | |||
6780 | ||||
6781 | =back | |||
6782 | ||||
6783 | The solution on these systems is to use the C<POSIX::sigaction()> | |||
6784 | routine to gain low level access to how the signal handler is installed. | |||
6785 | ||||
6786 | The code would look something like this (for the DBD-Oracle connect()): | |||
6787 | ||||
6788 | use POSIX ':signal_h'; | |||
6789 | ||||
6790 | my $mask = POSIX::SigSet->new( SIGALRM ); # signals to mask in the handler | |||
6791 | my $action = POSIX::SigAction->new( | |||
6792 | sub { die "connect timeout" }, # the handler code ref | |||
6793 | $mask, | |||
6794 | # not using (perl 5.8.2 and later) 'safe' switch or sa_flags | |||
6795 | ); | |||
6796 | my $oldaction = POSIX::SigAction->new(); | |||
6797 | sigaction( 'ALRM', $action, $oldaction ); | |||
6798 | my $dbh; | |||
6799 | eval { | |||
6800 | alarm(5); # seconds before time out | |||
6801 | $dbh = DBI->connect("dbi:Oracle:$dsn" ... ); | |||
6802 | alarm(0); # cancel alarm (if connect worked fast) | |||
6803 | }; | |||
6804 | alarm(0); # cancel alarm (if eval failed) | |||
6805 | sigaction( 'ALRM', $oldaction ); # restore original signal handler | |||
6806 | if ( $@ ) .... | |||
6807 | ||||
6808 | Similar techniques can be used for canceling statement execution. | |||
6809 | ||||
6810 | Unfortunately, this solution is somewhat messy, and it does I<not> work with | |||
6811 | perl versions less than perl 5.8 where C<POSIX::sigaction()> appears to be broken. | |||
6812 | ||||
6813 | For a cleaner implementation that works across perl versions, see Lincoln Baxter's | |||
6814 | Sys::SigAction module at L<http://search.cpan.org/~lbaxter/Sys-SigAction/>. | |||
6815 | The documentation for Sys::SigAction includes an longer discussion | |||
6816 | of this problem, and a DBD::Oracle test script. | |||
6817 | ||||
6818 | Be sure to read all the signal handling sections of the L<perlipc> manual. | |||
6819 | ||||
6820 | And finally, two more points to keep firmly in mind. Firstly, | |||
6821 | remember that what we've done here is essentially revert to old | |||
6822 | style I<unsafe> handling of these signals. So do as little as | |||
6823 | possible in the handler. Ideally just die(). Secondly, the handles | |||
6824 | in use at the time the signal is handled may not be safe to use | |||
6825 | afterwards. | |||
6826 | ||||
6827 | ||||
6828 | =head2 Subclassing the DBI | |||
6829 | ||||
6830 | DBI can be subclassed and extended just like any other object | |||
6831 | oriented module. Before we talk about how to do that, it's important | |||
6832 | to be clear about the various DBI classes and how they work together. | |||
6833 | ||||
6834 | By default C<$dbh = DBI-E<gt>connect(...)> returns a $dbh blessed | |||
6835 | into the C<DBI::db> class. And the C<$dbh-E<gt>prepare> method | |||
6836 | returns an $sth blessed into the C<DBI::st> class (actually it | |||
6837 | simply changes the last four characters of the calling handle class | |||
6838 | to be C<::st>). | |||
6839 | ||||
6840 | The leading 'C<DBI>' is known as the 'root class' and the extra | |||
6841 | 'C<::db>' or 'C<::st>' are the 'handle type suffixes'. If you want | |||
6842 | to subclass the DBI you'll need to put your overriding methods into | |||
6843 | the appropriate classes. For example, if you want to use a root class | |||
6844 | of C<MySubDBI> and override the do(), prepare() and execute() methods, | |||
6845 | then your do() and prepare() methods should be in the C<MySubDBI::db> | |||
6846 | class and the execute() method should be in the C<MySubDBI::st> class. | |||
6847 | ||||
6848 | To setup the inheritance hierarchy the @ISA variable in C<MySubDBI::db> | |||
6849 | should include C<DBI::db> and the @ISA variable in C<MySubDBI::st> | |||
6850 | should include C<DBI::st>. The C<MySubDBI> root class itself isn't | |||
6851 | currently used for anything visible and so, apart from setting @ISA | |||
6852 | to include C<DBI>, it can be left empty. | |||
6853 | ||||
6854 | So, having put your overriding methods into the right classes, and | |||
6855 | setup the inheritance hierarchy, how do you get the DBI to use them? | |||
6856 | You have two choices, either a static method call using the name | |||
6857 | of your subclass: | |||
6858 | ||||
6859 | $dbh = MySubDBI->connect(...); | |||
6860 | ||||
6861 | or specifying a C<RootClass> attribute: | |||
6862 | ||||
6863 | $dbh = DBI->connect(..., { RootClass => 'MySubDBI' }); | |||
6864 | ||||
6865 | If both forms are used then the attribute takes precedence. | |||
6866 | ||||
6867 | The only differences between the two are that using an explicit | |||
6868 | RootClass attribute will a) make the DBI automatically attempt to load | |||
6869 | a module by that name if the class doesn't exist, and b) won't call | |||
6870 | your MySubDBI::connect() method, if you have one. | |||
6871 | ||||
6872 | When subclassing is being used then, after a successful new | |||
6873 | connect, the DBI->connect method automatically calls: | |||
6874 | ||||
6875 | $dbh->connected($dsn, $user, $pass, \%attr); | |||
6876 | ||||
6877 | The default method does nothing. The call is made just to simplify | |||
6878 | any post-connection setup that your subclass may want to perform. | |||
6879 | The parameters are the same as passed to DBI->connect. | |||
6880 | If your subclass supplies a connected method, it should be part of the | |||
6881 | MySubDBI::db package. | |||
6882 | ||||
6883 | One more thing to note: you must let the DBI do the handle creation. If you | |||
6884 | want to override the connect() method in your *::dr class then it must still | |||
6885 | call SUPER::connect to get a $dbh to work with. Similarly, an overridden | |||
6886 | prepare() method in *::db must still call SUPER::prepare to get a $sth. | |||
6887 | If you try to create your own handles using bless() then you'll find the DBI | |||
6888 | will reject them with an "is not a DBI handle (has no magic)" error. | |||
6889 | ||||
6890 | Here's a brief example of a DBI subclass. A more thorough example | |||
6891 | can be found in F<t/subclass.t> in the DBI distribution. | |||
6892 | ||||
6893 | package MySubDBI; | |||
6894 | ||||
6895 | use strict; | |||
6896 | ||||
6897 | use DBI; | |||
6898 | use vars qw(@ISA); | |||
6899 | @ISA = qw(DBI); | |||
6900 | ||||
6901 | package MySubDBI::db; | |||
6902 | use vars qw(@ISA); | |||
6903 | @ISA = qw(DBI::db); | |||
6904 | ||||
6905 | sub prepare { | |||
6906 | my ($dbh, @args) = @_; | |||
6907 | my $sth = $dbh->SUPER::prepare(@args) | |||
6908 | or return; | |||
6909 | $sth->{private_mysubdbi_info} = { foo => 'bar' }; | |||
6910 | return $sth; | |||
6911 | } | |||
6912 | ||||
6913 | package MySubDBI::st; | |||
6914 | use vars qw(@ISA); | |||
6915 | @ISA = qw(DBI::st); | |||
6916 | ||||
6917 | sub fetch { | |||
6918 | my ($sth, @args) = @_; | |||
6919 | my $row = $sth->SUPER::fetch(@args) | |||
6920 | or return; | |||
6921 | do_something_magical_with_row_data($row) | |||
6922 | or return $sth->set_err(1234, "The magic failed", undef, "fetch"); | |||
6923 | return $row; | |||
6924 | } | |||
6925 | ||||
6926 | When calling a SUPER::method that returns a handle, be careful to | |||
6927 | check the return value before trying to do other things with it in | |||
6928 | your overridden method. This is especially important if you want to | |||
6929 | set a hash attribute on the handle, as Perl's autovivification will | |||
6930 | bite you by (in)conveniently creating an unblessed hashref, which your | |||
6931 | method will then return with usually baffling results later on like | |||
6932 | the error "dbih_getcom handle HASH(0xa4451a8) is not a DBI handle (has | |||
6933 | no magic". It's best to check right after the call and return undef | |||
6934 | immediately on error, just like DBI would and just like the example | |||
6935 | above. | |||
6936 | ||||
6937 | If your method needs to record an error it should call the set_err() | |||
6938 | method with the error code and error string, as shown in the example | |||
6939 | above. The error code and error string will be recorded in the | |||
6940 | handle and available via C<$h-E<gt>err> and C<$DBI::errstr> etc. | |||
6941 | The set_err() method always returns an undef or empty list as | |||
6942 | approriate. Since your method should nearly always return an undef | |||
6943 | or empty list as soon as an error is detected it's handy to simply | |||
6944 | return what set_err() returns, as shown in the example above. | |||
6945 | ||||
6946 | If the handle has C<RaiseError>, C<PrintError>, or C<HandleError> | |||
6947 | etc. set then the set_err() method will honour them. This means | |||
6948 | that if C<RaiseError> is set then set_err() won't return in the | |||
6949 | normal way but will 'throw an exception' that can be caught with | |||
6950 | an C<eval> block. | |||
6951 | ||||
6952 | You can stash private data into DBI handles | |||
6953 | via C<$h-E<gt>{private_..._*}>. See the entry under L</ATTRIBUTES | |||
6954 | COMMON TO ALL HANDLES> for info and important caveats. | |||
6955 | ||||
6956 | ||||
6957 | =head1 TRACING | |||
6958 | ||||
6959 | The DBI has a powerful tracing mechanism built in. It enables you | |||
6960 | to see what's going on 'behind the scenes', both within the DBI and | |||
6961 | the drivers you're using. | |||
6962 | ||||
6963 | =head2 Trace Settings | |||
6964 | ||||
6965 | Which details are written to the trace output is controlled by a | |||
6966 | combination of a I<trace level>, an integer from 0 to 15, and a set | |||
6967 | of I<trace flags> that are either on or off. Together these are known | |||
6968 | as the I<trace settings> and are stored together in a single integer. | |||
6969 | For normal use you only need to set the trace level, and generally | |||
6970 | only to a value between 1 and 4. | |||
6971 | ||||
6972 | Each handle has it's own trace settings, and so does the DBI. | |||
6973 | When you call a method the DBI merges the handles settings into its | |||
6974 | own for the duration of the call: the trace flags of the handle are | |||
6975 | OR'd into the trace flags of the DBI, and if the handle has a higher | |||
6976 | trace level then the DBI trace level is raised to match it. | |||
6977 | The previous DBI trace setings are restored when the called method | |||
6978 | returns. | |||
6979 | ||||
6980 | =head2 Trace Levels | |||
6981 | ||||
6982 | Trace I<levels> are as follows: | |||
6983 | ||||
6984 | 0 - Trace disabled. | |||
6985 | 1 - Trace DBI method calls returning with results or errors. | |||
6986 | 2 - Trace method entry with parameters and returning with results. | |||
6987 | 3 - As above, adding some high-level information from the driver | |||
6988 | and some internal information from the DBI. | |||
6989 | 4 - As above, adding more detailed information from the driver. | |||
6990 | 5 to 15 - As above but with more and more obscure information. | |||
6991 | ||||
6992 | Trace level 1 is best for a simple overview of what's happening. | |||
6993 | Trace level 2 is a good choice for general purpose tracing. | |||
6994 | Levels 3 and above are best reserved for investigating a specific | |||
6995 | problem, when you need to see "inside" the driver and DBI. | |||
6996 | ||||
6997 | The trace output is detailed and typically very useful. Much of the | |||
6998 | trace output is formatted using the L</neat> function, so strings | |||
6999 | in the trace output may be edited and truncated by that function. | |||
7000 | ||||
7001 | =head2 Trace Flags | |||
7002 | ||||
7003 | Trace I<flags> are used to enable tracing of specific activities | |||
7004 | within the DBI and drivers. The DBI defines some trace flags and | |||
7005 | drivers can define others. DBI trace flag names begin with a capital | |||
7006 | letter and driver specific names begin with a lowercase letter, as | |||
7007 | usual. | |||
7008 | ||||
7009 | Curently the DBI only defines two trace flags: | |||
7010 | ||||
7011 | ALL - turn on all DBI and driver flags (not recommended) | |||
7012 | SQL - trace SQL statements executed (not yet implemented) | |||
7013 | ||||
7014 | The L</parse_trace_flags> and L</parse_trace_flag> methods are used | |||
7015 | to convert trace flag names into the coresponding integer bit flags. | |||
7016 | ||||
7017 | =head2 Enabling Trace | |||
7018 | ||||
7019 | The C<$h-E<gt>trace> method sets the trace settings for a handle | |||
7020 | and C<DBI-E<gt>trace> does the same for the DBI. | |||
7021 | ||||
7022 | In addition to the L</trace> method, you can enable the same trace | |||
7023 | information, and direct the output to a file, by setting the | |||
7024 | C<DBI_TRACE> environment variable before starting Perl. | |||
7025 | See L</DBI_TRACE> for more information. | |||
7026 | ||||
7027 | Finally, you can set, or get, the trace settings for a handle using | |||
7028 | the C<TraceLevel> attribute. | |||
7029 | ||||
7030 | All of those methods use parse_trace_flags() and so allow you set | |||
7031 | both the trace level and multiple trace flags by using a string | |||
7032 | containing the trace level and/or flag names separated by vertical | |||
7033 | bar ("C<|>") or comma ("C<,>") characters. For example: | |||
7034 | ||||
7035 | local $h->{TraceLevel} = "3|SQL|foo"; | |||
7036 | ||||
7037 | =head2 Trace Output | |||
7038 | ||||
7039 | Initially trace output is written to C<STDERR>. Both the | |||
7040 | C<$h-E<gt>trace> and C<DBI-E<gt>trace> methods take an optional | |||
7041 | $trace_file parameter, which may be either the name of a file to be | |||
7042 | openned by DBI in append mode, or a reference to an existing writable | |||
7043 | (possibly layered) filehandle. If $trace_file is a filename, | |||
7044 | and can be opened in append mode, or $trace_file is a writable | |||
7045 | filehandle, then I<all> trace output (currently including that from | |||
7046 | other handles) is redirected to that file. A warning is generated | |||
7047 | if $trace_file can't be opened or is not writable. | |||
7048 | ||||
7049 | Further calls to trace() without $trace_file do not alter where | |||
7050 | the trace output is sent. If $trace_file is undefined, then | |||
7051 | trace output is sent to C<STDERR> and, if the prior trace was openned with | |||
7052 | $trace_file as a filename, the previous trace file is closed; if $trace_file was | |||
7053 | a filehandle, the filehandle is B<not> closed. | |||
7054 | ||||
7055 | B<NOTE>: If $trace_file is specified as a filehandle, the filehandle | |||
7056 | should not be closed until all DBI operations are completed, or the | |||
7057 | application has reset the trace file via another call to | |||
7058 | C<trace()> that changes the trace file. | |||
7059 | ||||
7060 | =head2 Tracing to Layered Filehandles | |||
7061 | ||||
7062 | B<NOTE>: | |||
7063 | ||||
7064 | =over 4 | |||
7065 | ||||
7066 | =item * | |||
7067 | Tied filehandles are not currently supported, as | |||
7068 | tie operations are not available to the PerlIO | |||
7069 | methods used by the DBI. | |||
7070 | ||||
7071 | =item * | |||
7072 | PerlIO layer support requires Perl version 5.8 or higher. | |||
7073 | ||||
7074 | =back | |||
7075 | ||||
7076 | As of version 5.8, Perl provides the ability to layer various | |||
7077 | "disciplines" on an open filehandle via the L<PerlIO> module. | |||
7078 | ||||
7079 | A simple example of using PerlIO layers is to use a scalar as the output: | |||
7080 | ||||
7081 | my $scalar = ''; | |||
7082 | open( my $fh, "+>:scalar", \$scalar ); | |||
7083 | $dbh->trace( 2, $fh ); | |||
7084 | ||||
7085 | Now all trace output is simply appended to $scalar. | |||
7086 | ||||
7087 | A more complex application of tracing to a layered filehandle is the | |||
7088 | use of a custom layer (I<Refer to >L<Perlio::via> I<for details | |||
7089 | on creating custom PerlIO layers.>). Consider an application with the | |||
7090 | following logger module: | |||
7091 | ||||
7092 | package MyFancyLogger; | |||
7093 | ||||
7094 | sub new | |||
7095 | { | |||
7096 | my $self = {}; | |||
7097 | my $fh; | |||
7098 | open $fh, '>', 'fancylog.log'; | |||
7099 | $self->{_fh} = $fh; | |||
7100 | $self->{_buf} = ''; | |||
7101 | return bless $self, shift; | |||
7102 | } | |||
7103 | ||||
7104 | sub log | |||
7105 | { | |||
7106 | my $self = shift; | |||
7107 | return unless exists $self->{_fh}; | |||
7108 | my $fh = $self->{_fh}; | |||
7109 | $self->{_buf} .= shift; | |||
7110 | # | |||
7111 | # DBI feeds us pieces at a time, so accumulate a complete line | |||
7112 | # before outputing | |||
7113 | # | |||
7114 | print $fh "At ", scalar localtime(), ':', $self->{_buf}, "\n" and | |||
7115 | $self->{_buf} = '' | |||
7116 | if $self->{_buf}=~tr/\n//; | |||
7117 | } | |||
7118 | ||||
7119 | sub close { | |||
7120 | my $self = shift; | |||
7121 | return unless exists $self->{_fh}; | |||
7122 | my $fh = $self->{_fh}; | |||
7123 | print $fh "At ", scalar localtime(), ':', $self->{_buf}, "\n" and | |||
7124 | $self->{_buf} = '' | |||
7125 | if $self->{_buf}; | |||
7126 | close $fh; | |||
7127 | delete $self->{_fh}; | |||
7128 | } | |||
7129 | ||||
7130 | 1; | |||
7131 | ||||
7132 | To redirect DBI traces to this logger requires creating | |||
7133 | a package for the layer: | |||
7134 | ||||
7135 | package PerlIO::via::MyFancyLogLayer; | |||
7136 | ||||
7137 | sub PUSHED | |||
7138 | { | |||
7139 | my ($class,$mode,$fh) = @_; | |||
7140 | my $logger; | |||
7141 | return bless \$logger,$class; | |||
7142 | } | |||
7143 | ||||
7144 | sub OPEN { | |||
7145 | my ($self, $path, $mode, $fh) = @_; | |||
7146 | # | |||
7147 | # $path is actually our logger object | |||
7148 | # | |||
7149 | $$self = $path; | |||
7150 | return 1; | |||
7151 | } | |||
7152 | ||||
7153 | sub WRITE | |||
7154 | { | |||
7155 | my ($self, $buf, $fh) = @_; | |||
7156 | $$self->log($buf); | |||
7157 | return length($buf); | |||
7158 | } | |||
7159 | ||||
7160 | sub CLOSE { | |||
7161 | my $self = shift; | |||
7162 | $$self->close(); | |||
7163 | return 0; | |||
7164 | } | |||
7165 | ||||
7166 | 1; | |||
7167 | ||||
7168 | ||||
7169 | The application can then cause DBI traces to be routed to the | |||
7170 | logger using | |||
7171 | ||||
7172 | use PerlIO::via::MyFancyLogLayer; | |||
7173 | ||||
7174 | open my $fh, '>:via(MyFancyLogLayer)', MyFancyLogger->new(); | |||
7175 | ||||
7176 | $dbh->trace('SQL', $fh); | |||
7177 | ||||
7178 | Now all trace output will be processed by MyFancyLogger's | |||
7179 | log() method. | |||
7180 | ||||
7181 | =head2 Trace Content | |||
7182 | ||||
7183 | Many of the values embeded in trace output are formatted using the neat() | |||
7184 | utility function. This means they may be quoted, sanitized, and possibly | |||
7185 | truncated if longer than C<$DBI::neat_maxlen>. See L</neat> for more details. | |||
7186 | ||||
7187 | =head2 Tracing Tips | |||
7188 | ||||
7189 | You can add tracing to your own application code using the L</trace_msg> method. | |||
7190 | ||||
7191 | It can sometimes be handy to compare trace files from two different runs of the | |||
7192 | same script. However using a tool like C<diff> on the original log output | |||
7193 | doesn't work well because the trace file is full of object addresses that may | |||
7194 | differ on each run. | |||
7195 | ||||
7196 | The DBI includes a handy utility called dbilogstrip that can be used to | |||
7197 | 'normalize' the log content. It can be used as a filter like this: | |||
7198 | ||||
7199 | DBI_TRACE=2 perl yourscript.pl ...args1... 2>&1 | dbilogstrip > dbitrace1.log | |||
7200 | DBI_TRACE=2 perl yourscript.pl ...args2... 2>&1 | dbilogstrip > dbitrace2.log | |||
7201 | diff -u dbitrace1.log dbitrace2.log | |||
7202 | ||||
7203 | See L<dbilogstrip> for more information. | |||
7204 | ||||
7205 | =head1 DBI ENVIRONMENT VARIABLES | |||
7206 | ||||
7207 | The DBI module recognizes a number of environment variables, but most of | |||
7208 | them should not be used most of the time. | |||
7209 | It is better to be explicit about what you are doing to avoid the need | |||
7210 | for environment variables, especially in a web serving system where web | |||
7211 | servers are stingy about which environment variables are available. | |||
7212 | ||||
7213 | =head2 DBI_DSN | |||
7214 | ||||
7215 | The DBI_DSN environment variable is used by DBI->connect if you do not | |||
7216 | specify a data source when you issue the connect. | |||
7217 | It should have a format such as "dbi:Driver:databasename". | |||
7218 | ||||
7219 | =head2 DBI_DRIVER | |||
7220 | ||||
7221 | The DBI_DRIVER environment variable is used to fill in the database | |||
7222 | driver name in DBI->connect if the data source string starts "dbi::" | |||
7223 | (thereby omitting the driver). | |||
7224 | If DBI_DSN omits the driver name, DBI_DRIVER can fill the gap. | |||
7225 | ||||
7226 | =head2 DBI_AUTOPROXY | |||
7227 | ||||
7228 | The DBI_AUTOPROXY environment variable takes a string value that starts | |||
7229 | "dbi:Proxy:" and is typically followed by "hostname=...;port=...". | |||
7230 | It is used to alter the behaviour of DBI->connect. | |||
7231 | For full details, see DBI::Proxy documentation. | |||
7232 | ||||
7233 | =head2 DBI_USER | |||
7234 | ||||
7235 | The DBI_USER environment variable takes a string value that is used as | |||
7236 | the user name if the DBI->connect call is given undef (as distinct from | |||
7237 | an empty string) as the username argument. | |||
7238 | Be wary of the security implications of using this. | |||
7239 | ||||
7240 | =head2 DBI_PASS | |||
7241 | ||||
7242 | The DBI_PASS environment variable takes a string value that is used as | |||
7243 | the password if the DBI->connect call is given undef (as distinct from | |||
7244 | an empty string) as the password argument. | |||
7245 | Be extra wary of the security implications of using this. | |||
7246 | ||||
7247 | =head2 DBI_DBNAME (obsolete) | |||
7248 | ||||
7249 | The DBI_DBNAME environment variable takes a string value that is used only when the | |||
7250 | obsolescent style of DBI->connect (with driver name as fourth parameter) is used, and | |||
7251 | when no value is provided for the first (database name) argument. | |||
7252 | ||||
7253 | =head2 DBI_TRACE | |||
7254 | ||||
7255 | The DBI_TRACE environment variable specifies the global default | |||
7256 | trace settings for the DBI at startup. Can also be used to direct | |||
7257 | trace output to a file. When the DBI is loaded it does: | |||
7258 | ||||
7259 | DBI->trace(split /=/, $ENV{DBI_TRACE}, 2) if $ENV{DBI_TRACE}; | |||
7260 | ||||
7261 | So if C<DBI_TRACE> contains an "C<=>" character then what follows | |||
7262 | it is used as the name of the file to append the trace to. | |||
7263 | ||||
7264 | output appended to that file. If the name begins with a number | |||
7265 | followed by an equal sign (C<=>), then the number and the equal sign are | |||
7266 | stripped off from the name, and the number is used to set the trace | |||
7267 | level. For example: | |||
7268 | ||||
7269 | DBI_TRACE=1=dbitrace.log perl your_test_script.pl | |||
7270 | ||||
7271 | On Unix-like systems using a Bourne-like shell, you can do this easily | |||
7272 | on the command line: | |||
7273 | ||||
7274 | DBI_TRACE=2 perl your_test_script.pl | |||
7275 | ||||
7276 | See L</TRACING> for more information. | |||
7277 | ||||
7278 | =head2 PERL_DBI_DEBUG (obsolete) | |||
7279 | ||||
7280 | An old variable that should no longer be used; equivalent to DBI_TRACE. | |||
7281 | ||||
7282 | =head2 DBI_PROFILE | |||
7283 | ||||
7284 | The DBI_PROFILE environment variable can be used to enable profiling | |||
7285 | of DBI method calls. See L<DBI::Profile> for more information. | |||
7286 | ||||
7287 | =head2 DBI_PUREPERL | |||
7288 | ||||
7289 | The DBI_PUREPERL environment variable can be used to enable the | |||
7290 | use of DBI::PurePerl. See L<DBI::PurePerl> for more information. | |||
7291 | ||||
7292 | =head1 WARNING AND ERROR MESSAGES | |||
7293 | ||||
7294 | =head2 Fatal Errors | |||
7295 | ||||
7296 | =over 4 | |||
7297 | ||||
7298 | =item Can't call method "prepare" without a package or object reference | |||
7299 | ||||
7300 | The C<$dbh> handle you're using to call C<prepare> is probably undefined because | |||
7301 | the preceding C<connect> failed. You should always check the return status of | |||
7302 | DBI methods, or use the L</RaiseError> attribute. | |||
7303 | ||||
7304 | =item Can't call method "execute" without a package or object reference | |||
7305 | ||||
7306 | The C<$sth> handle you're using to call C<execute> is probably undefined because | |||
7307 | the preceeding C<prepare> failed. You should always check the return status of | |||
7308 | DBI methods, or use the L</RaiseError> attribute. | |||
7309 | ||||
7310 | =item DBI/DBD internal version mismatch | |||
7311 | ||||
7312 | The DBD driver module was built with a different version of DBI than | |||
7313 | the one currently being used. You should rebuild the DBD module under | |||
7314 | the current version of DBI. | |||
7315 | ||||
7316 | (Some rare platforms require "static linking". On those platforms, there | |||
7317 | may be an old DBI or DBD driver version actually embedded in the Perl | |||
7318 | executable being used.) | |||
7319 | ||||
7320 | =item DBD driver has not implemented the AutoCommit attribute | |||
7321 | ||||
7322 | The DBD driver implementation is incomplete. Consult the author. | |||
7323 | ||||
7324 | =item Can't [sg]et %s->{%s}: unrecognised attribute | |||
7325 | ||||
7326 | You attempted to set or get an unknown attribute of a handle. Make | |||
7327 | sure you have spelled the attribute name correctly; case is significant | |||
7328 | (e.g., "Autocommit" is not the same as "AutoCommit"). | |||
7329 | ||||
7330 | =back | |||
7331 | ||||
7332 | =head1 Pure-Perl DBI | |||
7333 | ||||
7334 | A pure-perl emulation of the DBI is included in the distribution | |||
7335 | for people using pure-perl drivers who, for whatever reason, can't | |||
7336 | install the compiled DBI. See L<DBI::PurePerl>. | |||
7337 | ||||
7338 | =head1 SEE ALSO | |||
7339 | ||||
7340 | =head2 Driver and Database Documentation | |||
7341 | ||||
7342 | Refer to the documentation for the DBD driver that you are using. | |||
7343 | ||||
7344 | Refer to the SQL Language Reference Manual for the database engine that you are using. | |||
7345 | ||||
7346 | =head2 ODBC and SQL/CLI Standards Reference Information | |||
7347 | ||||
7348 | More detailed information about the semantics of certain DBI methods | |||
7349 | that are based on ODBC and SQL/CLI standards is available on-line | |||
7350 | via microsoft.com, for ODBC, and www.jtc1sc32.org for the SQL/CLI | |||
7351 | standard: | |||
7352 | ||||
7353 | DBI method ODBC function SQL/CLI Working Draft | |||
7354 | ---------- ------------- --------------------- | |||
7355 | column_info SQLColumns Page 124 | |||
7356 | foreign_key_info SQLForeignKeys Page 163 | |||
7357 | get_info SQLGetInfo Page 214 | |||
7358 | primary_key_info SQLPrimaryKeys Page 254 | |||
7359 | table_info SQLTables Page 294 | |||
7360 | type_info SQLGetTypeInfo Page 239 | |||
7361 | statistics_info SQLStatistics | |||
7362 | ||||
7363 | For example, for ODBC information on SQLColumns you'd visit: | |||
7364 | ||||
7365 | http://msdn.microsoft.com/library/en-us/odbc/htm/odbcsqlcolumns.asp | |||
7366 | ||||
7367 | If that URL ceases to work then use the MSDN search facility at: | |||
7368 | ||||
7369 | http://search.microsoft.com/us/dev/ | |||
7370 | ||||
7371 | and search for C<SQLColumns returns> using the exact phrase option. | |||
7372 | The link you want will probably just be called C<SQLColumns> and will | |||
7373 | be part of the Data Access SDK. | |||
7374 | ||||
7375 | And for SQL/CLI standard information on SQLColumns you'd read page 124 of | |||
7376 | the (very large) SQL/CLI Working Draft available from: | |||
7377 | ||||
7378 | http://jtc1sc32.org/doc/N0701-0750/32N0744T.pdf | |||
7379 | ||||
7380 | =head2 Standards Reference Information | |||
7381 | ||||
7382 | A hyperlinked, browsable version of the BNF syntax for SQL92 (plus | |||
7383 | Oracle 7 SQL and PL/SQL) is available here: | |||
7384 | ||||
7385 | http://cui.unige.ch/db-research/Enseignement/analyseinfo/SQL92/BNFindex.html | |||
7386 | ||||
7387 | A BNF syntax for SQL3 is available here: | |||
7388 | ||||
7389 | http://www.sqlstandards.org/SC32/WG3/Progression_Documents/Informal_working_drafts/iso-9075-2-1999.bnf | |||
7390 | ||||
7391 | The following links provide further useful information about SQL. | |||
7392 | Some of these are rather dated now but may still be useful. | |||
7393 | ||||
7394 | http://www.jcc.com/SQLPages/jccs_sql.htm | |||
7395 | http://www.contrib.andrew.cmu.edu/~shadow/sql.html | |||
7396 | http://www.altavista.com/query?q=sql+tutorial | |||
7397 | ||||
7398 | ||||
7399 | =head2 Books and Articles | |||
7400 | ||||
7401 | Programming the Perl DBI, by Alligator Descartes and Tim Bunce. | |||
7402 | L<http://books.perl.org/book/154> | |||
7403 | ||||
7404 | Programming Perl 3rd Ed. by Larry Wall, Tom Christiansen & Jon Orwant. | |||
7405 | L<http://books.perl.org/book/134> | |||
7406 | ||||
7407 | Learning Perl by Randal Schwartz. | |||
7408 | L<http://books.perl.org/book/101> | |||
7409 | ||||
7410 | Details of many other books related to perl can be found at L<http://books.perl.org> | |||
7411 | ||||
7412 | =head2 Perl Modules | |||
7413 | ||||
7414 | Index of DBI related modules available from CPAN: | |||
7415 | ||||
7416 | http://search.cpan.org/search?mode=module&query=DBIx%3A%3A | |||
7417 | http://search.cpan.org/search?mode=doc&query=DBI | |||
7418 | ||||
7419 | For a good comparison of RDBMS-OO mappers and some OO-RDBMS mappers | |||
7420 | (including Class::DBI, Alzabo, and DBIx::RecordSet in the former | |||
7421 | category and Tangram and SPOPS in the latter) see the Perl | |||
7422 | Object-Oriented Persistence project pages at: | |||
7423 | ||||
7424 | http://poop.sourceforge.net | |||
7425 | ||||
7426 | A similar page for Java toolkits can be found at: | |||
7427 | ||||
7428 | http://c2.com/cgi-bin/wiki?ObjectRelationalToolComparison | |||
7429 | ||||
7430 | =head2 Mailing List | |||
7431 | ||||
7432 | The I<dbi-users> mailing list is the primary means of communication among | |||
7433 | users of the DBI and its related modules. For details send email to: | |||
7434 | ||||
7435 | dbi-users-help@perl.org | |||
7436 | ||||
7437 | There are typically between 700 and 900 messages per month. You have | |||
7438 | to subscribe in order to be able to post. However you can opt for a | |||
7439 | 'post-only' subscription. | |||
7440 | ||||
7441 | Mailing list archives (of variable quality) are held at: | |||
7442 | ||||
7443 | http://groups.google.com/groups?group=perl.dbi.users | |||
7444 | http://www.xray.mpe.mpg.de/mailing-lists/dbi/ | |||
7445 | http://www.mail-archive.com/dbi-users%40perl.org/ | |||
7446 | ||||
7447 | =head2 Assorted Related WWW Links | |||
7448 | ||||
7449 | The DBI "Home Page": | |||
7450 | ||||
7451 | http://dbi.perl.org/ | |||
7452 | ||||
7453 | Other DBI related links: | |||
7454 | ||||
7455 | http://tegan.deltanet.com/~phlip/DBUIdoc.html | |||
7456 | http://dc.pm.org/perl_db.html | |||
7457 | http://wdvl.com/Authoring/DB/Intro/toc.html | |||
7458 | http://www.hotwired.com/webmonkey/backend/tutorials/tutorial1.html | |||
7459 | http://bumppo.net/lists/macperl/1999/06/msg00197.html | |||
7460 | http://gmax.oltrelinux.com/dbirecipes.html | |||
7461 | ||||
7462 | Other database related links: | |||
7463 | ||||
7464 | http://www.jcc.com/sql_stnd.html | |||
7465 | http://cuiwww.unige.ch/OSG/info/FreeDB/FreeDB.home.html | |||
7466 | http://www.connectionstrings.com/ | |||
7467 | ||||
7468 | Security, especially the "SQL Injection" attack: | |||
7469 | ||||
7470 | http://www.ngssoftware.com/research/papers.html | |||
7471 | http://www.ngssoftware.com/papers/advanced_sql_injection.pdf | |||
7472 | http://www.ngssoftware.com/papers/more_advanced_sql_injection.pdf | |||
7473 | http://www.esecurityplanet.com/trends/article.php/2243461 | |||
7474 | http://www.spidynamics.com/papers/SQLInjectionWhitePaper.pdf | |||
7475 | http://www.imperva.com/application_defense_center/white_papers/blind_sql_server_injection.html | |||
7476 | http://online.securityfocus.com/infocus/1644 | |||
7477 | ||||
7478 | Commercial and Data Warehouse Links | |||
7479 | ||||
7480 | http://www.dwinfocenter.org | |||
7481 | http://www.datawarehouse.com | |||
7482 | http://www.datamining.org | |||
7483 | http://www.olapcouncil.org | |||
7484 | http://www.idwa.org | |||
7485 | http://www.knowledgecenters.org/dwcenter.asp | |||
7486 | ||||
7487 | Recommended Perl Programming Links | |||
7488 | ||||
7489 | http://language.perl.com/style/ | |||
7490 | ||||
7491 | ||||
7492 | =head2 FAQ | |||
7493 | ||||
7494 | See L<http://faq.dbi-support.com/> | |||
7495 | ||||
7496 | =head1 AUTHORS | |||
7497 | ||||
7498 | DBI by Tim Bunce, L<http://www.tim.bunce.name> | |||
7499 | ||||
7500 | This pod text by Tim Bunce, J. Douglas Dunlop, Jonathan Leffler and others. | |||
7501 | Perl by Larry Wall and the C<perl5-porters>. | |||
7502 | ||||
7503 | =head1 COPYRIGHT | |||
7504 | ||||
7505 | The DBI module is Copyright (c) 1994-2004 Tim Bunce. Ireland. | |||
7506 | All rights reserved. | |||
7507 | ||||
7508 | You may distribute under the terms of either the GNU General Public | |||
7509 | License or the Artistic License, as specified in the Perl README file. | |||
7510 | ||||
7511 | =head1 SUPPORT / WARRANTY | |||
7512 | ||||
7513 | The DBI is free Open Source software. IT COMES WITHOUT WARRANTY OF ANY KIND. | |||
7514 | ||||
7515 | =head2 Support | |||
7516 | ||||
7517 | My consulting company, Data Plan Services, offers annual and | |||
7518 | multi-annual support contracts for the DBI. These provide sustained | |||
7519 | support for DBI development, and sustained value for you in return. | |||
7520 | Contact me for details. | |||
7521 | ||||
7522 | =head2 Sponsor Enhancements | |||
7523 | ||||
7524 | The DBI Roadmap is available at L<http://search.cpan.org/~timb/DBI/Roadmap.pod> | |||
7525 | ||||
7526 | If your company would benefit from a specific new DBI feature, | |||
7527 | please consider sponsoring its development. Work is performed | |||
7528 | rapidly, and usually on a fixed-price payment-on-delivery basis. | |||
7529 | Contact me for details. | |||
7530 | ||||
7531 | Using such targeted financing allows you to contribute to DBI | |||
7532 | development, and rapidly get something specific and valuable in return. | |||
7533 | ||||
7534 | =head1 ACKNOWLEDGEMENTS | |||
7535 | ||||
7536 | I would like to acknowledge the valuable contributions of the many | |||
7537 | people I have worked with on the DBI project, especially in the early | |||
7538 | years (1992-1994). In no particular order: Kevin Stock, Buzz Moschetti, | |||
7539 | Kurt Andersen, Ted Lemon, William Hails, Garth Kennedy, Michael Peppler, | |||
7540 | Neil S. Briscoe, Jeff Urlwin, David J. Hughes, Jeff Stander, | |||
7541 | Forrest D Whitcher, Larry Wall, Jeff Fried, Roy Johnson, Paul Hudson, | |||
7542 | Georg Rehfeld, Steve Sizemore, Ron Pool, Jon Meek, Tom Christiansen, | |||
7543 | Steve Baumgarten, Randal Schwartz, and a whole lot more. | |||
7544 | ||||
7545 | Then, of course, there are the poor souls who have struggled through | |||
7546 | untold and undocumented obstacles to actually implement DBI drivers. | |||
7547 | Among their ranks are Jochen Wiedmann, Alligator Descartes, Jonathan | |||
7548 | Leffler, Jeff Urlwin, Michael Peppler, Henrik Tougaard, Edwin Pratomo, | |||
7549 | Davide Migliavacca, Jan Pazdziora, Peter Haworth, Edmund Mergl, Steve | |||
7550 | Williams, Thomas Lowery, and Phlip Plumlee. Without them, the DBI would | |||
7551 | not be the practical reality it is today. I'm also especially grateful | |||
7552 | to Alligator Descartes for starting work on the first edition of the | |||
7553 | "Programming the Perl DBI" book and letting me jump on board. | |||
7554 | ||||
7555 | The DBI and DBD::Oracle were originally developed while I was Technical | |||
7556 | Director (CTO) of Ingeneering in the UK (L<http://www.ig.co.uk>) (formerly known as the | |||
7557 | Paul Ingram Group). So I'd especially like to thank Paul for his generosity | |||
7558 | and vision in supporting this work for many years. | |||
7559 | ||||
7560 | A couple of specific DBI features have been sponsored by enlightened companies: | |||
7561 | ||||
7562 | The development of the swap_inner_handle() method was sponsored by BizRate.com (L<http://BizRate.com>) | |||
7563 | ||||
7564 | The development of DBD::Gofer and related modules was sponsored by | |||
7565 | Shopzilla.com (L<http://Shopzilla.com>), where I currently work. | |||
7566 | ||||
7567 | ||||
7568 | =head1 CONTRIBUTING | |||
7569 | ||||
7570 | As you can see above, many people have contributed to the DBI and | |||
7571 | drivers in many ways over many years. | |||
7572 | ||||
7573 | If you'd like to help then see L<http://dbi.perl.org/contributing> | |||
7574 | and L<http://search.cpan.org/~timb/DBI/Roadmap.pod> | |||
7575 | ||||
7576 | If you'd like the DBI to do something new or different then a good way | |||
7577 | to make that happen is to do it yourself and send me a patch to the | |||
7578 | source code that shows the changes. (But read "Speak before you patch" | |||
7579 | below.) | |||
7580 | ||||
7581 | =head2 Browsing the source code repository | |||
7582 | ||||
7583 | Use http://svn.perl.org/modules/dbi/trunk (basic) | |||
7584 | or http://svn.perl.org/viewcvs/modules/ (more useful) | |||
7585 | ||||
7586 | =head2 How to create a patch using Subversion | |||
7587 | ||||
7588 | The DBI source code is maintained using Subversion (a replacement | |||
7589 | for CVS, see L<http://subversion.tigris.org/>). To access the source | |||
7590 | you'll need to install a Subversion client. Then, to get the source | |||
7591 | code, do: | |||
7592 | ||||
7593 | svn checkout http://svn.perl.org/modules/dbi/trunk | |||
7594 | ||||
7595 | If it prompts for a username and password use your perl.org account | |||
7596 | if you have one, else just 'guest' and 'guest'. The source code will | |||
7597 | be in a new subdirectory called C<trunk>. | |||
7598 | ||||
7599 | To keep informed about changes to the source you can send an empty email | |||
7600 | to svn-commit-modules-dbi-subscribe@perl.org after which you'll get an email | |||
7601 | with the change log message and diff of each change checked-in to the source. | |||
7602 | ||||
7603 | After making your changes you can generate a patch file, but before | |||
7604 | you do, make sure your source is still upto date using: | |||
7605 | ||||
7606 | svn update | |||
7607 | ||||
7608 | If you get any conflicts reported you'll need to fix them first. | |||
7609 | Then generate the patch file from within the C<trunk> directory using: | |||
7610 | ||||
7611 | svn diff > foo.patch | |||
7612 | ||||
7613 | Read the patch file, as a sanity check, and then email it to dbi-dev@perl.org. | |||
7614 | ||||
7615 | =head2 How to create a patch without Subversion | |||
7616 | ||||
7617 | Unpack a fresh copy of the distribution: | |||
7618 | ||||
7619 | tar xfz DBI-1.40.tar.gz | |||
7620 | ||||
7621 | Rename the newly created top level directory: | |||
7622 | ||||
7623 | mv DBI-1.40 DBI-1.40.your_foo | |||
7624 | ||||
7625 | Edit the contents of DBI-1.40.your_foo/* till it does what you want. | |||
7626 | ||||
7627 | Test your changes and then remove all temporary files: | |||
7628 | ||||
7629 | make test && make distclean | |||
7630 | ||||
7631 | Go back to the directory you originally unpacked the distribution: | |||
7632 | ||||
7633 | cd .. | |||
7634 | ||||
7635 | Unpack I<another> copy of the original distribution you started with: | |||
7636 | ||||
7637 | tar xfz DBI-1.40.tar.gz | |||
7638 | ||||
7639 | Then create a patch file by performing a recursive C<diff> on the two | |||
7640 | top level directories: | |||
7641 | ||||
7642 | diff -r -u DBI-1.40 DBI-1.40.your_foo > DBI-1.40.your_foo.patch | |||
7643 | ||||
7644 | =head2 Speak before you patch | |||
7645 | ||||
7646 | For anything non-trivial or possibly controversial it's a good idea | |||
7647 | to discuss (on dbi-dev@perl.org) the changes you propose before | |||
7648 | actually spending time working on them. Otherwise you run the risk | |||
7649 | of them being rejected because they don't fit into some larger plans | |||
7650 | you may not be aware of. | |||
7651 | ||||
7652 | =head1 TRANSLATIONS | |||
7653 | ||||
7654 | A German translation of this manual (possibly slightly out of date) is | |||
7655 | available, thanks to O'Reilly, at: | |||
7656 | ||||
7657 | http://www.oreilly.de/catalog/perldbiger/ | |||
7658 | ||||
7659 | Some other translations: | |||
7660 | ||||
7661 | http://cronopio.net/perl/ - Spanish | |||
7662 | http://member.nifty.ne.jp/hippo2000/dbimemo.htm - Japanese | |||
7663 | ||||
7664 | ||||
7665 | =head1 TRAINING | |||
7666 | ||||
7667 | References to DBI related training resources. No recommendation implied. | |||
7668 | ||||
7669 | http://www.treepax.co.uk/ | |||
7670 | http://www.keller.com/dbweb/ | |||
7671 | ||||
7672 | (If you offer professional DBI related training services, | |||
7673 | please send me your details so I can add them here.) | |||
7674 | ||||
7675 | =head1 OTHER RELATED WORK AND PERL MODULES | |||
7676 | ||||
7677 | =over 4 | |||
7678 | ||||
7679 | =item Apache::DBI by E.Mergl@bawue.de | |||
7680 | ||||
7681 | To be used with the Apache daemon together with an embedded Perl | |||
7682 | interpreter like C<mod_perl>. Establishes a database connection which | |||
7683 | remains open for the lifetime of the HTTP daemon. This way the CGI | |||
7684 | connect and disconnect for every database access becomes superfluous. | |||
7685 | ||||
7686 | =item SQL Parser | |||
7687 | ||||
7688 | See also the L<SQL::Statement> module, SQL parser and engine. | |||
7689 | ||||
7690 | =back | |||
7691 | ||||
7692 | =cut | |||
# spent 12µs within DBD::_::common::trace_msg which was called
# once (12µs+0) by DBI::END at line 505 of /wise/base/static/lib/perl5/site_perl/5.10.0/x86_64-linux-thread-multi/DBI.pm | ||||
# spent 622µs within DBI::_install_method which was called 87 times, avg 7µs/call:
# 87 times (622µs+0) at line 488 of /wise/base/static/lib/perl5/site_perl/5.10.0/x86_64-linux-thread-multi/DBI.pm, avg 7µs/call | ||||
# spent 219µs within DBI::_new_handle which was called 5 times, avg 44µs/call:
# 3 times (121µs+0) by DBI::_new_sth at line 1251 of /wise/base/static/lib/perl5/site_perl/5.10.0/x86_64-linux-thread-multi/DBI.pm, avg 40µs/call
# once (61µs+0) by DBI::_new_drh at line 1211 of /wise/base/static/lib/perl5/site_perl/5.10.0/x86_64-linux-thread-multi/DBI.pm
# once (37µs+0) by DBI::_new_dbh at line 1241 of /wise/base/static/lib/perl5/site_perl/5.10.0/x86_64-linux-thread-multi/DBI.pm | ||||
# spent 418µs within DBI::bootstrap which was called
# once (418µs+0) by DynaLoader::bootstrap at line 226 of /opt/wise/lib/perl5/5.10.0/x86_64-linux-thread-multi/DynaLoader.pm |