File | /project/perl/lib/DBI.pm |
Statements Executed | 1251 |
Statement Execution Time | 67.4ms |
Calls | P | F | Exclusive Time |
Inclusive Time |
Subroutine |
---|---|---|---|---|---|
12 | 1 | 2 | 280ms | 280ms | execute (xsub) | DBI::st::
1 | 1 | 1 | 25.2ms | 30.0ms | _load_class | DBI::
1 | 1 | 1 | 16.3ms | 31.2ms | install_driver | DBI::
462 | 1 | 2 | 4.20ms | 4.20ms | fetchrow_arrayref (xsub) | DBI::st::
31 | 31 | 1 | 3.05ms | 4.99ms | install_method | DBD::_::common::
117 | 2 | 2 | 2.45ms | 2.45ms | _install_method (xsub) | DBI::
14 | 3 | 1 | 1.54ms | 2.23ms | _new_handle | DBI::
1 | 1 | 1 | 820µs | 106ms | __ANON__[:692] | DBI::
14 | 1 | 2 | 694µs | 694µs | _setup_handle (xsub) | DBI::
12 | 1 | 1 | 688µs | 2.53ms | _new_sth | DBI::
112 | 1 | 2 | 535µs | 535µs | CORE:match (opcode) | DBI::
62 | 2 | 2 | 515µs | 515µs | CORE:match (opcode) | DBD::_::common::
2 | 2 | 1 | 427µs | 541µs | setup_driver | DBI::
1 | 1 | 2 | 402µs | 402µs | bootstrap (xsub) | DBI::
1 | 1 | 1 | 351µs | 138ms | connect | DBI::
9 | 4 | 3 | 287µs | 287µs | fetchrow_array (xsub) | DBI::st::
1 | 1 | 1 | 154µs | 161µs | _set_isa | DBI::
11 | 5 | 3 | 137µs | 137µs | finish (xsub) | DBI::st::
1 | 1 | 2 | 126µs | 155µs | bind_columns (xsub) | DBI::st::
1 | 1 | 1 | 78µs | 278µs | _new_dbh | DBI::
1 | 1 | 1 | 77µs | 271µs | _new_drh | DBI::
1 | 1 | 1 | 71µs | 84µs | _rebless | DBI::
2 | 1 | 2 | 70µs | 70µs | fetchall_arrayref (xsub) | DBI::st::
1 | 1 | 1 | 69µs | 138ms | connect_cached | DBI::
1 | 1 | 1 | 63µs | 98µs | disconnect_all | DBI::
3 | 3 | 2 | 37µs | 37µs | CORE:subst (opcode) | DBI::
4 | 4 | 2 | 32µs | 32µs | trace_msg (xsub) | DBD::_::common::
1 | 1 | 2 | 29µs | 29µs | CORE:sort (opcode) | DBD::_::dr::
1 | 1 | 2 | 14µs | 14µs | bind_col (xsub) | DBI::st::
1 | 1 | 2 | 13µs | 13µs | _handles (xsub) | DBI::
1 | 1 | 2 | 7µs | 7µs | SQL_INTEGER (xsub) | DBI::
1 | 1 | 2 | 6µs | 6µs | SQL_DECIMAL (xsub) | DBI::
1 | 1 | 2 | 6µs | 6µs | SQL_DOUBLE (xsub) | DBI::
1 | 1 | 2 | 6µs | 6µs | SQL_FLOAT (xsub) | DBI::
1 | 1 | 2 | 6µs | 6µs | SQL_REAL (xsub) | DBI::
1 | 1 | 2 | 6µs | 6µs | SQL_SMALLINT (xsub) | DBI::
1 | 1 | 2 | 5µs | 5µs | SQL_NUMERIC (xsub) | DBI::
0 | 0 | 0 | 0s | 0s | CLONE | DBD::Switch::dr::
0 | 0 | 0 | 0s | 0s | FETCH | DBD::Switch::dr::
0 | 0 | 0 | 0s | 0s | STORE | DBD::Switch::dr::
0 | 0 | 0 | 0s | 0s | driver | DBD::Switch::dr::
0 | 0 | 0 | 0s | 0s | BEGIN | DBD::_::common::
0 | 0 | 0 | 0s | 0s | CLEAR | DBD::_::common::
0 | 0 | 0 | 0s | 0s | EXISTS | DBD::_::common::
0 | 0 | 0 | 0s | 0s | FIRSTKEY | DBD::_::common::
0 | 0 | 0 | 0s | 0s | NEXTKEY | DBD::_::common::
0 | 0 | 0 | 0s | 0s | _not_impl | DBD::_::common::
0 | 0 | 0 | 0s | 0s | parse_trace_flag | DBD::_::common::
0 | 0 | 0 | 0s | 0s | parse_trace_flags | DBD::_::common::
0 | 0 | 0 | 0s | 0s | private_attribute_info | DBD::_::common::
0 | 0 | 0 | 0s | 0s | BEGIN | DBD::_::db::
0 | 0 | 0 | 0s | 0s | _do_selectrow | DBD::_::db::
0 | 0 | 0 | 0s | 0s | begin_work | DBD::_::db::
0 | 0 | 0 | 0s | 0s | clone | DBD::_::db::
0 | 0 | 0 | 0s | 0s | data_sources | DBD::_::db::
0 | 0 | 0 | 0s | 0s | do | DBD::_::db::
0 | 0 | 0 | 0s | 0s | ping | DBD::_::db::
0 | 0 | 0 | 0s | 0s | prepare_cached | DBD::_::db::
0 | 0 | 0 | 0s | 0s | primary_key | DBD::_::db::
0 | 0 | 0 | 0s | 0s | quote | DBD::_::db::
0 | 0 | 0 | 0s | 0s | quote_identifier | DBD::_::db::
0 | 0 | 0 | 0s | 0s | rows | DBD::_::db::
0 | 0 | 0 | 0s | 0s | selectall_arrayref | DBD::_::db::
0 | 0 | 0 | 0s | 0s | selectall_hashref | DBD::_::db::
0 | 0 | 0 | 0s | 0s | selectcol_arrayref | DBD::_::db::
0 | 0 | 0 | 0s | 0s | selectrow_array | DBD::_::db::
0 | 0 | 0 | 0s | 0s | selectrow_arrayref | DBD::_::db::
0 | 0 | 0 | 0s | 0s | selectrow_hashref | DBD::_::db::
0 | 0 | 0 | 0s | 0s | tables | DBD::_::db::
0 | 0 | 0 | 0s | 0s | type_info | DBD::_::db::
0 | 0 | 0 | 0s | 0s | BEGIN | DBD::_::dr::
0 | 0 | 0 | 0s | 0s | connect | DBD::_::dr::
0 | 0 | 0 | 0s | 0s | connect_cached | DBD::_::dr::
0 | 0 | 0 | 0s | 0s | default_user | DBD::_::dr::
0 | 0 | 0 | 0s | 0s | BEGIN | DBD::_::st::
0 | 0 | 0 | 0s | 0s | __ANON__[:1891] | DBD::_::st::
0 | 0 | 0 | 0s | 0s | __ANON__[:1925] | DBD::_::st::
0 | 0 | 0 | 0s | 0s | bind_columns | DBD::_::st::
0 | 0 | 0 | 0s | 0s | bind_param | DBD::_::st::
0 | 0 | 0 | 0s | 0s | bind_param_array | DBD::_::st::
0 | 0 | 0 | 0s | 0s | bind_param_inout_array | DBD::_::st::
0 | 0 | 0 | 0s | 0s | blob_copy_to_file | DBD::_::st::
0 | 0 | 0 | 0s | 0s | execute_array | DBD::_::st::
0 | 0 | 0 | 0s | 0s | execute_for_fetch | DBD::_::st::
0 | 0 | 0 | 0s | 0s | fetchall_arrayref | DBD::_::st::
0 | 0 | 0 | 0s | 0s | fetchall_hashref | DBD::_::st::
0 | 0 | 0 | 0s | 0s | more_results | DBD::_::st::
0 | 0 | 0 | 0s | 0s | BEGIN | DBI::
0 | 0 | 0 | 0s | 0s | CLONE | DBI::
0 | 0 | 0 | 0s | 0s | STORE | DBI::DBI_tie::
0 | 0 | 0 | 0s | 0s | TIEHASH | DBI::DBI_tie::
0 | 0 | 0 | 0s | 0s | END | DBI::
0 | 0 | 0 | 0s | 0s | __ANON__[:1076] | DBI::
0 | 0 | 0 | 0s | 0s | __ANON__[:1110] | DBI::
0 | 0 | 0 | 0s | 0s | __ANON__[:1111] | DBI::
0 | 0 | 0 | 0s | 0s | __ANON__[:985] | DBI::
0 | 0 | 0 | 0s | 0s | _dbtype_names | DBI::
0 | 0 | 0 | 0s | 0s | _rebless_dbtype_subclass | DBI::
0 | 0 | 0 | 0s | 0s | available_drivers | DBI::
0 | 0 | 0 | 0s | 0s | connect_test_perf | DBI::
0 | 0 | 0 | 0s | 0s | data_diff | DBI::
0 | 0 | 0 | 0s | 0s | data_sources | DBI::
0 | 0 | 0 | 0s | 0s | data_string_desc | DBI::
0 | 0 | 0 | 0s | 0s | data_string_diff | DBI::
0 | 0 | 0 | 0s | 0s | disconnect | DBI::
0 | 0 | 0 | 0s | 0s | dump_dbd_registry | DBI::
0 | 0 | 0 | 0s | 0s | dump_results | DBI::
0 | 0 | 0 | 0s | 0s | err | DBI::
0 | 0 | 0 | 0s | 0s | errstr | DBI::
0 | 0 | 0 | 0s | 0s | init_rootclass | DBI::
0 | 0 | 0 | 0s | 0s | installed_drivers | DBI::
0 | 0 | 0 | 0s | 0s | installed_versions | DBI::
0 | 0 | 0 | 0s | 0s | neat_list | DBI::
0 | 0 | 0 | 0s | 0s | parse_dsn | DBI::
0 | 0 | 0 | 0s | 0s | TIEHASH | DBI::st::
0 | 0 | 0 | 0s | 0s | STORE | DBI::var::
0 | 0 | 0 | 0s | 0s | TIESCALAR | DBI::var::
Line | State ments |
Time on line |
Calls | Time in subs |
Code |
---|---|---|---|---|---|
1 | # $Id: DBI.pm 9152 2007-02-22 01:44:25Z 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 | 5µs | require 5.006_00; | ||
10 | |||||
11 | BEGIN { | ||||
12 | 1 | 8µs | $DBI::VERSION = "1.54"; # ==> ALSO update the version in the pod text below! | ||
13 | 1 | 113µs | } | ||
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 can get help | ||||
87 | on subscribing and using the list by emailing I<dbi-users-help@perl.org>. | ||||
88 | |||||
89 | To help you make the best use of the dbi-users mailing list, | ||||
90 | and any other lists or forums you may use, I I<strongly> | ||||
91 | recommend that you read "How To Ask Questions The Smart Way" | ||||
92 | by Eric Raymond: L<http://www.catb.org/~esr/faqs/smart-questions.html>. | ||||
93 | |||||
94 | If you think you've found a bug then please also read | ||||
95 | "How to Report Bugs Effectively" by Simon Tatham: | ||||
96 | L<http://www.chiark.greenend.org.uk/~sgtatham/bugs.html>. | ||||
97 | |||||
98 | The DBI home page at L<http://dbi.perl.org/> is always worth a visit | ||||
99 | and includes an FAQ and links to other resources. | ||||
100 | |||||
101 | Before asking any questions, reread this document, consult the | ||||
102 | archives and read the DBI FAQ. The archives are listed | ||||
103 | at the end of this document and on the DBI home page. | ||||
104 | An FAQ is installed as a L<DBI::FAQ> module so | ||||
105 | you can read it by executing C<perldoc DBI::FAQ>. | ||||
106 | However the DBI::FAQ module is currently (2004) outdated relative | ||||
107 | to the online FAQ on the DBI home page. | ||||
108 | |||||
109 | This document often uses terms like I<references>, I<objects>, | ||||
110 | I<methods>. If you're not familar with those terms then it would | ||||
111 | be a good idea to read at least the following perl manuals first: | ||||
112 | L<perlreftut>, L<perldsc>, L<perllol>, and L<perlboot>. | ||||
113 | |||||
114 | Please note that Tim Bunce does not maintain the mailing lists or the | ||||
115 | web page (generous volunteers do that). So please don't send mail | ||||
116 | directly to him; he just doesn't have the time to answer questions | ||||
117 | personally. The I<dbi-users> mailing list has lots of experienced | ||||
118 | people who should be able to help you if you need it. If you do email | ||||
119 | Tim he's very likely to just forward it to the mailing list. | ||||
120 | |||||
121 | =head2 NOTES | ||||
122 | |||||
123 | This is the DBI specification that corresponds to the DBI version 1.54 | ||||
124 | ($Revision: 9152 $). | ||||
125 | |||||
126 | The DBI is evolving at a steady pace, so it's good to check that | ||||
127 | you have the latest copy. | ||||
128 | |||||
129 | The significant user-visible changes in each release are documented | ||||
130 | in the L<DBI::Changes> module so you can read them by executing | ||||
131 | C<perldoc DBI::Changes>. | ||||
132 | |||||
133 | Some DBI changes require changes in the drivers, but the drivers | ||||
134 | can take some time to catch up. Newer versions of the DBI have | ||||
135 | added features that may not yet be supported by the drivers you | ||||
136 | use. Talk to the authors of your drivers if you need a new feature | ||||
137 | that's not yet supported. | ||||
138 | |||||
139 | Features added after DBI 1.21 (February 2002) are marked in the | ||||
140 | text with the version number of the DBI release they first appeared in. | ||||
141 | |||||
142 | Extensions to the DBI API often use the C<DBIx::*> namespace. | ||||
143 | See L</Naming Conventions and Name Space>. DBI extension modules | ||||
144 | can be found at L<http://search.cpan.org/search?mode=module&query=DBIx>. | ||||
145 | And all modules related to the DBI can be found at | ||||
146 | L<http://search.cpan.org/search?query=DBI&mode=all>. | ||||
147 | |||||
148 | =cut | ||||
149 | |||||
150 | # The POD text continues at the end of the file. | ||||
151 | |||||
152 | |||||
153 | package DBI; | ||||
154 | |||||
155 | 3 | 48µs | use Carp(); | ||
156 | 3 | 302µs | use DynaLoader (); | ||
157 | 3 | 553µs | use Exporter (); | ||
158 | |||||
159 | BEGIN { | ||||
160 | 1 | 12µs | @ISA = qw(Exporter DynaLoader); | ||
161 | |||||
162 | # Make some utility functions available if asked for | ||||
163 | 1 | 5µs | @EXPORT = (); # we export nothing by default | ||
164 | 1 | 5µs | @EXPORT_OK = qw(%DBI %DBI_methods hash); # also populated by export_ok_tags: | ||
165 | 1 | 40µs | %EXPORT_TAGS = ( | ||
166 | sql_types => [ qw( | ||||
167 | SQL_GUID | ||||
168 | SQL_WLONGVARCHAR | ||||
169 | SQL_WVARCHAR | ||||
170 | SQL_WCHAR | ||||
171 | SQL_BIGINT | ||||
172 | SQL_BIT | ||||
173 | SQL_TINYINT | ||||
174 | SQL_LONGVARBINARY | ||||
175 | SQL_VARBINARY | ||||
176 | SQL_BINARY | ||||
177 | SQL_LONGVARCHAR | ||||
178 | SQL_UNKNOWN_TYPE | ||||
179 | SQL_ALL_TYPES | ||||
180 | SQL_CHAR | ||||
181 | SQL_NUMERIC | ||||
182 | SQL_DECIMAL | ||||
183 | SQL_INTEGER | ||||
184 | SQL_SMALLINT | ||||
185 | SQL_FLOAT | ||||
186 | SQL_REAL | ||||
187 | SQL_DOUBLE | ||||
188 | SQL_DATETIME | ||||
189 | SQL_DATE | ||||
190 | SQL_INTERVAL | ||||
191 | SQL_TIME | ||||
192 | SQL_TIMESTAMP | ||||
193 | SQL_VARCHAR | ||||
194 | SQL_BOOLEAN | ||||
195 | SQL_UDT | ||||
196 | SQL_UDT_LOCATOR | ||||
197 | SQL_ROW | ||||
198 | SQL_REF | ||||
199 | SQL_BLOB | ||||
200 | SQL_BLOB_LOCATOR | ||||
201 | SQL_CLOB | ||||
202 | SQL_CLOB_LOCATOR | ||||
203 | SQL_ARRAY | ||||
204 | SQL_ARRAY_LOCATOR | ||||
205 | SQL_MULTISET | ||||
206 | SQL_MULTISET_LOCATOR | ||||
207 | SQL_TYPE_DATE | ||||
208 | SQL_TYPE_TIME | ||||
209 | SQL_TYPE_TIMESTAMP | ||||
210 | SQL_TYPE_TIME_WITH_TIMEZONE | ||||
211 | SQL_TYPE_TIMESTAMP_WITH_TIMEZONE | ||||
212 | SQL_INTERVAL_YEAR | ||||
213 | SQL_INTERVAL_MONTH | ||||
214 | SQL_INTERVAL_DAY | ||||
215 | SQL_INTERVAL_HOUR | ||||
216 | SQL_INTERVAL_MINUTE | ||||
217 | SQL_INTERVAL_SECOND | ||||
218 | SQL_INTERVAL_YEAR_TO_MONTH | ||||
219 | SQL_INTERVAL_DAY_TO_HOUR | ||||
220 | SQL_INTERVAL_DAY_TO_MINUTE | ||||
221 | SQL_INTERVAL_DAY_TO_SECOND | ||||
222 | SQL_INTERVAL_HOUR_TO_MINUTE | ||||
223 | SQL_INTERVAL_HOUR_TO_SECOND | ||||
224 | SQL_INTERVAL_MINUTE_TO_SECOND | ||||
225 | ) ], | ||||
226 | sql_cursor_types => [ qw( | ||||
227 | SQL_CURSOR_FORWARD_ONLY | ||||
228 | SQL_CURSOR_KEYSET_DRIVEN | ||||
229 | SQL_CURSOR_DYNAMIC | ||||
230 | SQL_CURSOR_STATIC | ||||
231 | SQL_CURSOR_TYPE_DEFAULT | ||||
232 | ) ], # for ODBC cursor types | ||||
233 | utils => [ qw( | ||||
234 | neat neat_list $neat_maxlen dump_results looks_like_number | ||||
235 | data_string_diff data_string_desc data_diff | ||||
236 | ) ], | ||||
237 | profile => [ qw( | ||||
238 | dbi_profile dbi_profile_merge dbi_time | ||||
239 | ) ], # notionally "in" DBI::Profile and normally imported from there | ||||
240 | ); | ||||
241 | |||||
242 | 1 | 5µs | $DBI::dbi_debug = 0; | ||
243 | 1 | 4µs | $DBI::neat_maxlen = 400; | ||
244 | |||||
245 | # If you get an error here like "Can't find loadable object ..." | ||||
246 | # then you haven't installed the DBI correctly. Read the README | ||||
247 | # then install it again. | ||||
248 | 1 | 13µs | if ( $ENV{DBI_PUREPERL} ) { | ||
249 | eval { bootstrap DBI } if $ENV{DBI_PUREPERL} == 1; | ||||
250 | require DBI::PurePerl if $@ or $ENV{DBI_PUREPERL} >= 2; | ||||
251 | $DBI::PurePerl ||= 0; # just to silence "only used once" warnings | ||||
252 | } | ||||
253 | else { | ||||
254 | 1 | 34µs | 1 | 1.31ms | bootstrap DBI; # spent 1.31ms making 1 call to DynaLoader::bootstrap |
255 | } | ||||
256 | |||||
257 | 113 | 2.35ms | 112 | 535µs | $EXPORT_TAGS{preparse_flags} = [ grep { /^DBIpp_\w\w_/ } keys %{__PACKAGE__."::"} ]; # spent 535µs making 112 calls to DBI::CORE:match, avg 5µs/call |
258 | |||||
259 | 1 | 22µs | 1 | 3.60ms | Exporter::export_ok_tags(keys %EXPORT_TAGS); # spent 3.60ms making 1 call to Exporter::export_ok_tags |
260 | |||||
261 | 1 | 138µs | } | ||
262 | |||||
263 | # Alias some handle methods to also be DBI class methods | ||||
264 | 1 | 13µs | for (qw(trace_msg set_err parse_trace_flag parse_trace_flags)) { | ||
265 | 3 | 139µs | 1 | 25µs | no strict; # spent 25µs making 1 call to strict::unimport |
266 | 4 | 72µs | *$_ = \&{"DBD::_::common::$_"}; | ||
267 | } | ||||
268 | |||||
269 | 3 | 2.70ms | 1 | 21µs | use strict; # spent 21µs making 1 call to strict::import |
270 | |||||
271 | 1 | 7µs | DBI->trace(split /=/, $ENV{DBI_TRACE}, 2) if $ENV{DBI_TRACE}; | ||
272 | |||||
273 | 1 | 5µs | $DBI::connect_via ||= "connect"; | ||
274 | |||||
275 | # check if user wants a persistent database connection ( Apache + mod_perl ) | ||||
276 | 1 | 5µs | if ($INC{'Apache/DBI.pm'} && $ENV{MOD_PERL}) { | ||
277 | $DBI::connect_via = "Apache::DBI::connect"; | ||||
278 | DBI->trace_msg("DBI connect via $DBI::connect_via in $INC{'Apache/DBI.pm'}\n"); | ||||
279 | } | ||||
280 | |||||
281 | # check for weaken support, used by ChildHandles | ||||
282 | 1 | 11µs | my $HAS_WEAKEN = eval { | ||
283 | 1 | 239µs | require Scalar::Util; | ||
284 | # this will croak() if this Scalar::Util doesn't have a working weaken(). | ||||
285 | 1 | 42µs | 1 | 15µs | Scalar::Util::weaken( \my $test ); # same test as in t/72childhandles.t # spent 15µs making 1 call to Scalar::Util::weaken |
286 | 1 | 7µs | 1; | ||
287 | }; | ||||
288 | |||||
289 | 1 | 6µs | %DBI::installed_drh = (); # maps driver names to installed driver handles | ||
290 | sub installed_drivers { %DBI::installed_drh } | ||||
291 | |||||
292 | # Setup special DBI dynamic variables. See DBI::var::FETCH for details. | ||||
293 | # These are dynamically associated with the last handle used. | ||||
294 | 1 | 22µs | tie $DBI::err, 'DBI::var', '*err'; # special case: referenced via IHA list | ||
295 | 1 | 12µs | tie $DBI::state, 'DBI::var', '"state'; # special case: referenced via IHA list | ||
296 | 1 | 11µs | tie $DBI::lasth, 'DBI::var', '!lasth'; # special case: return boolean | ||
297 | 1 | 36µs | tie $DBI::errstr, 'DBI::var', '&errstr'; # call &errstr in last used pkg | ||
298 | 1 | 12µs | tie $DBI::rows, 'DBI::var', '&rows'; # call &rows in last used pkg | ||
299 | 10 | 53µs | sub DBI::var::TIESCALAR{ my $var = $_[1]; bless \$var, 'DBI::var'; } | ||
300 | sub DBI::var::STORE { Carp::croak("Can't modify \$DBI::${$_[0]} special variable") } | ||||
301 | |||||
302 | { # used to catch DBI->{Attrib} mistake | ||||
303 | 2 | 16µs | sub DBI::DBI_tie::TIEHASH { bless {} } | ||
304 | sub DBI::DBI_tie::STORE { Carp::carp("DBI->{$_[1]} is invalid syntax (you probably want \$h->{$_[1]})");} | ||||
305 | 1 | 9µs | *DBI::DBI_tie::FETCH = \&DBI::DBI_tie::STORE; | ||
306 | } | ||||
307 | 1 | 17µs | tie %DBI::DBI => 'DBI::DBI_tie'; | ||
308 | |||||
309 | # --- Driver Specific Prefix Registry --- | ||||
310 | |||||
311 | 1 | 112µs | my $dbd_prefix_registry = { | ||
312 | ad_ => { class => 'DBD::AnyData', }, | ||||
313 | ado_ => { class => 'DBD::ADO', }, | ||||
314 | amzn_ => { class => 'DBD::Amazon', }, | ||||
315 | best_ => { class => 'DBD::BestWins', }, | ||||
316 | csv_ => { class => 'DBD::CSV', }, | ||||
317 | db2_ => { class => 'DBD::DB2', }, | ||||
318 | dbi_ => { class => 'DBI', }, | ||||
319 | dbm_ => { class => 'DBD::DBM', }, | ||||
320 | df_ => { class => 'DBD::DF', }, | ||||
321 | f_ => { class => 'DBD::File', }, | ||||
322 | file_ => { class => 'DBD::TextFile', }, | ||||
323 | go_ => { class => 'DBD::Gofer', }, | ||||
324 | ib_ => { class => 'DBD::InterBase', }, | ||||
325 | ing_ => { class => 'DBD::Ingres', }, | ||||
326 | ix_ => { class => 'DBD::Informix', }, | ||||
327 | jdbc_ => { class => 'DBD::JDBC', }, | ||||
328 | monetdb_ => { class => 'DBD::monetdb', }, | ||||
329 | msql_ => { class => 'DBD::mSQL', }, | ||||
330 | mysql_ => { class => 'DBD::mysql', }, | ||||
331 | mx_ => { class => 'DBD::Multiplex', }, | ||||
332 | nullp_ => { class => 'DBD::NullP', }, | ||||
333 | odbc_ => { class => 'DBD::ODBC', }, | ||||
334 | ora_ => { class => 'DBD::Oracle', }, | ||||
335 | pg_ => { class => 'DBD::Pg', }, | ||||
336 | plb_ => { class => 'DBD::Plibdata', }, | ||||
337 | proxy_ => { class => 'DBD::Proxy', }, | ||||
338 | rdb_ => { class => 'DBD::RDB', }, | ||||
339 | sapdb_ => { class => 'DBD::SAP_DB', }, | ||||
340 | solid_ => { class => 'DBD::Solid', }, | ||||
341 | sponge_ => { class => 'DBD::Sponge', }, | ||||
342 | sql_ => { class => 'SQL::Statement', }, | ||||
343 | syb_ => { class => 'DBD::Sybase', }, | ||||
344 | tdat_ => { class => 'DBD::Teradata', }, | ||||
345 | tmpl_ => { class => 'DBD::Template', }, | ||||
346 | tmplss_ => { class => 'DBD::TemplateSS', }, | ||||
347 | tuber_ => { class => 'DBD::Tuber', }, | ||||
348 | uni_ => { class => 'DBD::Unify', }, | ||||
349 | wmi_ => { class => 'DBD::WMI', }, | ||||
350 | x_ => { }, # for private use | ||||
351 | xbase_ => { class => 'DBD::XBase', }, | ||||
352 | xl_ => { class => 'DBD::Excel', }, | ||||
353 | yaswi_ => { class => 'DBD::Yaswi', }, | ||||
354 | }; | ||||
355 | |||||
356 | sub dump_dbd_registry { | ||||
357 | require Data::Dumper; | ||||
358 | local $Data::Dumper::Sortkeys=1; | ||||
359 | local $Data::Dumper::Indent=1; | ||||
360 | print Data::Dumper->Dump([$dbd_prefix_registry], [qw($dbd_prefix_registry)]); | ||||
361 | } | ||||
362 | |||||
363 | # --- Dynamically create the DBI Standard Interface | ||||
364 | |||||
365 | 1 | 7µs | my $keeperr = { O=>0x0004 }; | ||
366 | |||||
367 | 1 | 223µs | %DBI::DBI_methods = ( # Define the DBI interface methods per class: | ||
368 | |||||
369 | common => { # Interface methods common to all DBI handle classes | ||||
370 | 'DESTROY' => $keeperr, | ||||
371 | 'CLEAR' => $keeperr, | ||||
372 | 'EXISTS' => $keeperr, | ||||
373 | 'FETCH' => { O=>0x0404 }, | ||||
374 | 'FIRSTKEY' => $keeperr, | ||||
375 | 'NEXTKEY' => $keeperr, | ||||
376 | 'STORE' => { O=>0x0418 | 0x4 }, | ||||
377 | _not_impl => undef, | ||||
378 | can => { O=>0x0100 }, # special case, see dispatch | ||||
379 | debug => { U =>[1,2,'[$debug_level]'], O=>0x0004 }, # old name for trace | ||||
380 | dump_handle => { U =>[1,3,'[$message [, $level]]'], O=>0x0004 }, | ||||
381 | err => $keeperr, | ||||
382 | errstr => $keeperr, | ||||
383 | state => $keeperr, | ||||
384 | func => { O=>0x0006 }, | ||||
385 | parse_trace_flag => { U =>[2,2,'$name'], O=>0x0404, T=>8 }, | ||||
386 | parse_trace_flags => { U =>[2,2,'$flags'], O=>0x0404, T=>8 }, | ||||
387 | private_data => { U =>[1,1], O=>0x0004 }, | ||||
388 | set_err => { U =>[3,6,'$err, $errmsg [, $state, $method, $rv]'], O=>0x0010 }, | ||||
389 | trace => { U =>[1,3,'[$trace_level, [$filename]]'], O=>0x0004 }, | ||||
390 | trace_msg => { U =>[2,3,'$message_text [, $min_level ]' ], O=>0x0004, T=>8 }, | ||||
391 | swap_inner_handle => { U =>[2,3,'$h [, $allow_reparent ]'] }, | ||||
392 | private_attribute_info => { }, | ||||
393 | }, | ||||
394 | dr => { # Database Driver Interface | ||||
395 | 'connect' => { U =>[1,5,'[$db [,$user [,$passwd [,\%attr]]]]'], H=>3, O=>0x8000 }, | ||||
396 | 'connect_cached'=>{U=>[1,5,'[$db [,$user [,$passwd [,\%attr]]]]'], H=>3, O=>0x8000 }, | ||||
397 | 'disconnect_all'=>{ U =>[1,1], O=>0x0800 }, | ||||
398 | data_sources => { U =>[1,2,'[\%attr]' ], O=>0x0800 }, | ||||
399 | default_user => { U =>[3,4,'$user, $pass [, \%attr]' ] }, | ||||
400 | }, | ||||
401 | db => { # Database Session Class Interface | ||||
402 | data_sources => { U =>[1,2,'[\%attr]' ], O=>0x0200 }, | ||||
403 | take_imp_data => { U =>[1,1], }, | ||||
404 | clone => { U =>[1,2,'[\%attr]'] }, | ||||
405 | connected => { U =>[1,0], O => 0x0004 }, | ||||
406 | begin_work => { U =>[1,2,'[ \%attr ]'], O=>0x0400 }, | ||||
407 | commit => { U =>[1,1], O=>0x0480|0x0800 }, | ||||
408 | rollback => { U =>[1,1], O=>0x0480|0x0800 }, | ||||
409 | 'do' => { U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'], O=>0x3200 }, | ||||
410 | last_insert_id => { U =>[5,6,'$catalog, $schema, $table_name, $field_name [, \%attr ]'], O=>0x2800 }, | ||||
411 | preparse => { }, # XXX | ||||
412 | prepare => { U =>[2,3,'$statement [, \%attr]'], O=>0xA200 }, | ||||
413 | prepare_cached => { U =>[2,4,'$statement [, \%attr [, $if_active ] ]'], O=>0xA200 }, | ||||
414 | selectrow_array => { U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'], O=>0x2000 }, | ||||
415 | selectrow_arrayref=>{U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'], O=>0x2000 }, | ||||
416 | selectrow_hashref=>{ U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'], O=>0x2000 }, | ||||
417 | selectall_arrayref=>{U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'], O=>0x2000 }, | ||||
418 | selectall_hashref=>{ U =>[3,0,'$statement, $keyfield [, \%attr [, @bind_params ] ]'], O=>0x2000 }, | ||||
419 | selectcol_arrayref=>{U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'], O=>0x2000 }, | ||||
420 | ping => { U =>[1,1], O=>0x0404 }, | ||||
421 | disconnect => { U =>[1,1], O=>0x0400|0x0800 }, | ||||
422 | quote => { U =>[2,3, '$string [, $data_type ]' ], O=>0x0430 }, | ||||
423 | quote_identifier=> { U =>[2,6, '$name [, ...] [, \%attr ]' ], O=>0x0430 }, | ||||
424 | rows => $keeperr, | ||||
425 | |||||
426 | tables => { U =>[1,6,'$catalog, $schema, $table, $type [, \%attr ]' ], O=>0x2200 }, | ||||
427 | table_info => { U =>[1,6,'$catalog, $schema, $table, $type [, \%attr ]' ], O=>0x2200|0x8800 }, | ||||
428 | column_info => { U =>[5,6,'$catalog, $schema, $table, $column [, \%attr ]'],O=>0x2200|0x8800 }, | ||||
429 | primary_key_info=> { U =>[4,5,'$catalog, $schema, $table [, \%attr ]' ], O=>0x2200|0x8800 }, | ||||
430 | primary_key => { U =>[4,5,'$catalog, $schema, $table [, \%attr ]' ], O=>0x2200 }, | ||||
431 | foreign_key_info=> { U =>[7,8,'$pk_catalog, $pk_schema, $pk_table, $fk_catalog, $fk_schema, $fk_table [, \%attr ]' ], O=>0x2200|0x8800 }, | ||||
432 | statistics_info => { U =>[6,7,'$catalog, $schema, $table, $unique_only, $quick, [, \%attr ]' ], O=>0x2200|0x8800 }, | ||||
433 | type_info_all => { U =>[1,1], O=>0x2200|0x0800 }, | ||||
434 | type_info => { U =>[1,2,'$data_type'], O=>0x2200 }, | ||||
435 | get_info => { U =>[2,2,'$info_type'], O=>0x2200|0x0800 }, | ||||
436 | }, | ||||
437 | st => { # Statement Class Interface | ||||
438 | bind_col => { U =>[3,4,'$column, \\$var [, \%attr]'] }, | ||||
439 | bind_columns => { U =>[2,0,'\\$var1 [, \\$var2, ...]'] }, | ||||
440 | bind_param => { U =>[3,4,'$parameter, $var [, \%attr]'] }, | ||||
441 | bind_param_inout=> { U =>[4,5,'$parameter, \\$var, $maxlen, [, \%attr]'] }, | ||||
442 | execute => { U =>[1,0,'[@args]'], O=>0x1040 }, | ||||
443 | |||||
444 | bind_param_array => { U =>[3,4,'$parameter, $var [, \%attr]'] }, | ||||
445 | bind_param_inout_array => { U =>[4,5,'$parameter, \\@var, $maxlen, [, \%attr]'] }, | ||||
446 | execute_array => { U =>[2,0,'\\%attribs [, @args]'], O=>0x1040|0x4000 }, | ||||
447 | execute_for_fetch => { U =>[2,3,'$fetch_sub [, $tuple_status]'], O=>0x1040|0x4000 }, | ||||
448 | |||||
449 | fetch => undef, # alias for fetchrow_arrayref | ||||
450 | fetchrow_arrayref => undef, | ||||
451 | fetchrow_hashref => undef, | ||||
452 | fetchrow_array => undef, | ||||
453 | fetchrow => undef, # old alias for fetchrow_array | ||||
454 | |||||
455 | fetchall_arrayref => { U =>[1,3, '[ $slice [, $max_rows]]'] }, | ||||
456 | fetchall_hashref => { U =>[2,2,'$key_field'] }, | ||||
457 | |||||
458 | blob_read => { U =>[4,5,'$field, $offset, $len [, \\$buf [, $bufoffset]]'] }, | ||||
459 | blob_copy_to_file => { U =>[3,3,'$field, $filename_or_handleref'] }, | ||||
460 | dump_results => { U =>[1,5,'$maxfieldlen, $linesep, $fieldsep, $filehandle'] }, | ||||
461 | more_results => { U =>[1,1] }, | ||||
462 | finish => { U =>[1,1] }, | ||||
463 | cancel => { U =>[1,1], O=>0x0800 }, | ||||
464 | rows => $keeperr, | ||||
465 | |||||
466 | _get_fbav => undef, | ||||
467 | _set_fbav => { T=>6 }, | ||||
468 | }, | ||||
469 | ); | ||||
470 | |||||
471 | 1 | 14µs | while ( my ($class, $meths) = each %DBI::DBI_methods ) { | ||
472 | 4 | 30µs | my $ima_trace = 0+($ENV{DBI_IMA_TRACE}||0); | ||
473 | 4 | 65µs | while ( my ($method, $info) = each %$meths ) { | ||
474 | 86 | 485µs | my $fullmeth = "DBI::${class}::$method"; | ||
475 | 86 | 372µs | if ($DBI::dbi_debug >= 15) { # quick hack to list DBI methods | ||
476 | # and optionally filter by IMA flags | ||||
477 | my $O = $info->{O}||0; | ||||
478 | printf "0x%04x %-20s\n", $O, $fullmeth | ||||
479 | unless $ima_trace && !($O & $ima_trace); | ||||
480 | } | ||||
481 | 86 | 2.79ms | 86 | 1.03ms | DBI->_install_method($fullmeth, 'DBI.pm', $info); # spent 1.03ms making 86 calls to DBI::_install_method, avg 12µs/call |
482 | } | ||||
483 | } | ||||
484 | |||||
485 | { | ||||
486 | 1 | 9µs | package DBI::common; | ||
487 | 1 | 9µs | @DBI::dr::ISA = ('DBI::common'); | ||
488 | 1 | 6µs | @DBI::db::ISA = ('DBI::common'); | ||
489 | 1 | 6µs | @DBI::st::ISA = ('DBI::common'); | ||
490 | } | ||||
491 | |||||
492 | # End of init code | ||||
493 | |||||
494 | |||||
495 | END { | ||||
496 | 1 | 7µs | return unless defined &DBI::trace_msg; # return unless bootstrap'd ok | ||
497 | 1 | 18µs | local ($!,$?); | ||
498 | 1 | 46µs | 1 | 11µs | DBI->trace_msg(" -- DBI::END\n", 2); # spent 11µs making 1 call to DBD::_::common::trace_msg |
499 | # Let drivers know why we are calling disconnect_all: | ||||
500 | 1 | 6µs | $DBI::PERL_ENDING = $DBI::PERL_ENDING = 1; # avoid typo warning | ||
501 | 1 | 29µs | 1 | 98µs | DBI->disconnect_all() if %DBI::installed_drh; # spent 98µs making 1 call to DBI::disconnect_all |
502 | } | ||||
503 | |||||
504 | |||||
505 | sub CLONE { | ||||
506 | my $olddbis = $DBI::_dbistate; | ||||
507 | _clone_dbis() unless $DBI::PurePerl; # clone the DBIS structure | ||||
508 | DBI->trace_msg(sprintf "CLONE DBI for new thread %s\n", | ||||
509 | $DBI::PurePerl ? "" : sprintf("(dbis %x -> %x)",$olddbis, $DBI::_dbistate)); | ||||
510 | while ( my ($driver, $drh) = each %DBI::installed_drh) { | ||||
511 | 3 | 1.84ms | 1 | 103µs | no strict 'refs'; # spent 103µs making 1 call to strict::unimport |
512 | next if defined &{"DBD::${driver}::CLONE"}; | ||||
513 | warn("$driver has no driver CLONE() function so is unsafe threaded\n"); | ||||
514 | } | ||||
515 | %DBI::installed_drh = (); # clear loaded drivers so they have a chance to reinitialize | ||||
516 | } | ||||
517 | |||||
518 | sub parse_dsn { | ||||
519 | my ($class, $dsn) = @_; | ||||
520 | $dsn =~ s/^(dbi):(\w*?)(?:\((.*?)\))?://i or return; | ||||
521 | my ($scheme, $driver, $attr, $attr_hash) = (lc($1), $2, $3); | ||||
522 | $driver ||= $ENV{DBI_DRIVER} || ''; | ||||
523 | $attr_hash = { split /\s*=>?\s*|\s*,\s*/, $attr, -1 } if $attr; | ||||
524 | return ($scheme, $driver, $attr, $attr_hash, $dsn); | ||||
525 | } | ||||
526 | |||||
527 | |||||
528 | # --- The DBI->connect Front Door methods | ||||
529 | |||||
530 | # spent 138ms (69µs+138) within DBI::connect_cached which was called
# once (69µs+138ms) by Ima::DBI::__ANON__[/project/perl/lib/Ima/DBI.pm:316] at line 312 of Ima/DBI.pm | ||||
531 | # For library code using connect_cached() with mod_perl | ||||
532 | # we redirect those calls to Apache::DBI::connect() as well | ||||
533 | 1 | 8µs | my ($class, $dsn, $user, $pass, $attr) = @_; | ||
534 | 1 | 6µs | my $dbi_connect_method = ($DBI::connect_via eq "Apache::DBI::connect") | ||
535 | ? 'Apache::DBI::connect' : 'connect_cached'; | ||||
536 | 1 | 24µs | $attr = { | ||
537 | $attr ? %$attr : (), # clone, don't modify callers data | ||||
538 | dbi_connect_method => $dbi_connect_method, | ||||
539 | }; | ||||
540 | 1 | 30µs | 1 | 138ms | return $class->connect($dsn, $user, $pass, $attr); # spent 138ms making 1 call to DBI::connect |
541 | } | ||||
542 | |||||
543 | # spent 138ms (351µs+137) within DBI::connect which was called
# once (351µs+137ms) by DBI::connect_cached at line 540 | ||||
544 | 1 | 6µs | my $class = shift; | ||
545 | 1 | 9µs | my ($dsn, $user, $pass, $attr, $old_driver) = my @orig_args = @_; | ||
546 | 1 | 4µs | my $driver; | ||
547 | |||||
548 | 1 | 6µs | if ($attr and !ref($attr)) { # switch $old_driver<->$attr if called in old style | ||
549 | Carp::carp("DBI->connect using 'old-style' syntax is deprecated and will be an error in future versions"); | ||||
550 | ($old_driver, $attr) = ($attr, $old_driver); | ||||
551 | } | ||||
552 | |||||
553 | 1 | 5µs | my $connect_meth = $attr->{dbi_connect_method}; | ||
554 | 1 | 4µs | $connect_meth ||= $DBI::connect_via; # fallback to default | ||
555 | |||||
556 | 1 | 5µs | $dsn ||= $ENV{DBI_DSN} || $ENV{DBI_DBNAME} || '' unless $old_driver; | ||
557 | |||||
558 | 1 | 5µs | if ($DBI::dbi_debug) { | ||
559 | local $^W = 0; | ||||
560 | pop @_ if $connect_meth ne 'connect'; | ||||
561 | my @args = @_; $args[2] = '****'; # hide password | ||||
562 | DBI->trace_msg(" -> $class->$connect_meth(".join(", ",@args).")\n"); | ||||
563 | } | ||||
564 | 1 | 6µs | Carp::croak('Usage: $class->connect([$dsn [,$user [,$passwd [,\%attr]]]])') | ||
565 | if (ref $old_driver or ($attr and not ref $attr) or ref $pass); | ||||
566 | |||||
567 | # extract dbi:driver prefix from $dsn into $1 | ||||
568 | 1 | 47µs | 1 | 18µs | $dsn =~ s/^dbi:(\w*?)(?:\((.*?)\))?://i # spent 18µs making 1 call to DBI::CORE:subst |
569 | or '' =~ /()/; # ensure $1 etc are empty if match fails | ||||
570 | 1 | 10µs | my $driver_attrib_spec = $2 || ''; | ||
571 | |||||
572 | # Set $driver. Old style driver, if specified, overrides new dsn style. | ||||
573 | 1 | 9µs | $driver = $old_driver || $1 || $ENV{DBI_DRIVER} | ||
574 | or Carp::croak("Can't connect to data source $dsn, no database driver specified " | ||||
575 | ."and DBI_DSN env var not set"); | ||||
576 | |||||
577 | 1 | 5µs | my $proxy; | ||
578 | 1 | 6µs | if ($ENV{DBI_AUTOPROXY} && $driver ne 'Proxy' && $driver ne 'Sponge' && $driver ne 'Switch') { | ||
579 | my $dbi_autoproxy = $ENV{DBI_AUTOPROXY}; | ||||
580 | $proxy = 'Proxy'; | ||||
581 | if ($dbi_autoproxy =~ s/^dbi:(\w*?)(?:\((.*?)\))?://i) { | ||||
582 | $proxy = $1; | ||||
583 | $driver_attrib_spec = join ",", | ||||
584 | ($driver_attrib_spec) ? $driver_attrib_spec : (), | ||||
585 | ($2 ) ? $2 : (); | ||||
586 | } | ||||
587 | $dsn = "$dbi_autoproxy;dsn=dbi:$driver:$dsn"; | ||||
588 | $driver = $proxy; | ||||
589 | DBI->trace_msg(" DBI_AUTOPROXY: dbi:$driver($driver_attrib_spec):$dsn\n"); | ||||
590 | } | ||||
591 | # avoid recursion if proxy calls DBI->connect itself | ||||
592 | 1 | 9µs | local $ENV{DBI_AUTOPROXY}; | ||
593 | |||||
594 | 1 | 5µs | my %attributes; # take a copy we can delete from | ||
595 | 1 | 13µs | if ($old_driver) { | ||
596 | %attributes = %$attr if $attr; | ||||
597 | } | ||||
598 | else { # new-style connect so new default semantics | ||||
599 | 1 | 27µs | %attributes = ( | ||
600 | PrintError => 1, | ||||
601 | AutoCommit => 1, | ||||
602 | ref $attr ? %$attr : (), | ||||
603 | # attributes in DSN take precedence over \%attr connect parameter | ||||
604 | $driver_attrib_spec ? (split /\s*=>?\s*|\s*,\s*/, $driver_attrib_spec, -1) : (), | ||||
605 | ); | ||||
606 | } | ||||
607 | 1 | 5µs | $attr = \%attributes; # now set $attr to refer to our local copy | ||
608 | |||||
609 | 1 | 23µs | 1 | 31.2ms | my $drh = $DBI::installed_drh{$driver} || $class->install_driver($driver) # spent 31.2ms making 1 call to DBI::install_driver |
610 | or die "panic: $class->install_driver($driver) failed"; | ||||
611 | |||||
612 | # attributes in DSN take precedence over \%attr connect parameter | ||||
613 | 1 | 7µs | $user = $attr->{Username} if defined $attr->{Username}; | ||
614 | 1 | 4µs | $pass = delete $attr->{Password} if defined $attr->{Password}; | ||
615 | 1 | 5µs | if ( !(defined $user && defined $pass) ) { | ||
616 | ($user, $pass) = $drh->default_user($user, $pass, $attr); | ||||
617 | } | ||||
618 | 1 | 7µs | $attr->{Username} = $user; # force the Username to be the actual one used | ||
619 | |||||
620 | # spent 106ms (820µs+105) within DBI::__ANON__[/project/perl/lib/DBI.pm:692] which was called
# once (820µs+105ms) by DBI::connect at line 694 | ||||
621 | 1 | 6µs | my ($old_dbh, $override_attr) = @_; | ||
622 | |||||
623 | #use Data::Dumper; | ||||
624 | #warn "connect_closure: ".Data::Dumper::Dumper([$attr,\%attributes, $override_attr]); | ||||
625 | |||||
626 | 1 | 5µs | my $dbh; | ||
627 | 1 | 79µs | 1 | 74.9ms | unless ($dbh = $drh->$connect_meth($dsn, $user, $pass, $attr)) { # spent 74.9ms making 1 call to DBI::dr::connect_cached |
628 | $user = '' if !defined $user; | ||||
629 | $dsn = '' if !defined $dsn; | ||||
630 | # $drh->errstr isn't safe here because $dbh->DESTROY may not have | ||||
631 | # been called yet and so the dbh errstr would not have been copied | ||||
632 | # up to the drh errstr. Certainly true for connect_cached! | ||||
633 | my $errstr = $DBI::errstr; | ||||
634 | $errstr = '(no error string)' if !defined $errstr; | ||||
635 | my $msg = "$class connect('$dsn','$user',...) failed: $errstr"; | ||||
636 | DBI->trace_msg(" $msg\n"); | ||||
637 | # XXX HandleWarn | ||||
638 | unless ($attr->{HandleError} && $attr->{HandleError}->($msg, $drh, $dbh)) { | ||||
639 | Carp::croak($msg) if $attr->{RaiseError}; | ||||
640 | Carp::carp ($msg) if $attr->{PrintError}; | ||||
641 | } | ||||
642 | $! = 0; # for the daft people who do DBI->connect(...) || die "$!"; | ||||
643 | return $dbh; # normally undef, but HandleError could change it | ||||
644 | } | ||||
645 | |||||
646 | # merge any attribute overrides but don't change $attr itself (for closure) | ||||
647 | 1 | 29µs | my $apply = { ($override_attr) ? (%$attr, %$override_attr ) : %$attr }; | ||
648 | |||||
649 | # handle basic RootClass subclassing: | ||||
650 | 1 | 6µs | my $rebless_class = $apply->{RootClass} || ($class ne 'DBI' ? $class : ''); | ||
651 | 1 | 9µs | if ($rebless_class) { | ||
652 | 3 | 1.49ms | 1 | 102µs | no strict 'refs'; # spent 102µs making 1 call to strict::unimport |
653 | 1 | 9µs | if ($apply->{RootClass}) { # explicit attribute (ie not static methd call class) | ||
654 | 1 | 5µs | delete $apply->{RootClass}; | ||
655 | 1 | 19µs | 1 | 30.0ms | DBI::_load_class($rebless_class, 0); # spent 30.0ms making 1 call to DBI::_load_class |
656 | } | ||||
657 | 1 | 20µs | unless (@{"$rebless_class\::db::ISA"} && @{"$rebless_class\::st::ISA"}) { | ||
658 | Carp::carp("DBI subclasses '$rebless_class\::db' and ::st are not setup, RootClass ignored"); | ||||
659 | $rebless_class = undef; | ||||
660 | $class = 'DBI'; | ||||
661 | } | ||||
662 | else { | ||||
663 | 1 | 61µs | 1 | 21µs | $dbh->{RootClass} = $rebless_class; # $dbh->STORE called via plain DBI::db # spent 21µs making 1 call to DBI::common::STORE |
664 | 1 | 21µs | 1 | 161µs | DBI::_set_isa([$rebless_class], 'DBI'); # sets up both '::db' and '::st' # spent 161µs making 1 call to DBI::_set_isa |
665 | 1 | 18µs | 1 | 84µs | DBI::_rebless($dbh, $rebless_class); # appends '::db' # spent 84µs making 1 call to DBI::_rebless |
666 | } | ||||
667 | } | ||||
668 | |||||
669 | 1 | 15µs | if (%$apply) { | ||
670 | |||||
671 | 1 | 6µs | if ($apply->{DbTypeSubclass}) { | ||
672 | my $DbTypeSubclass = delete $apply->{DbTypeSubclass}; | ||||
673 | DBI::_rebless_dbtype_subclass($dbh, $rebless_class||$class, $DbTypeSubclass); | ||||
674 | } | ||||
675 | 1 | 4µs | my $a; | ||
676 | 1 | 15µs | foreach $a (qw(Profile RaiseError PrintError AutoCommit)) { # do these first | ||
677 | 4 | 20µs | next unless exists $apply->{$a}; | ||
678 | 3 | 139µs | 3 | 48µs | $dbh->{$a} = delete $apply->{$a}; # spent 48µs making 3 calls to DBI::common::STORE, avg 16µs/call |
679 | } | ||||
680 | 1 | 16µs | while ( my ($a, $v) = each %$apply) { | ||
681 | 14 | 478µs | 14 | 121µs | eval { $dbh->{$a} = $v } or $@ && warn $@; # spent 66µs making 7 calls to DBI::common::STORE, avg 9µs/call
# spent 55µs making 7 calls to DBI::common::FETCH, avg 8µs/call |
682 | } | ||||
683 | } | ||||
684 | |||||
685 | # confirm to driver (ie if subclassed) that we've connected sucessfully | ||||
686 | # and finished the attribute setup. pass in the original arguments | ||||
687 | 1 | 53µs | 1 | 24µs | $dbh->connected(@orig_args); #if ref $dbh ne 'DBI::db' or $proxy; # spent 24µs making 1 call to DBI::db::connected |
688 | |||||
689 | 1 | 5µs | DBI->trace_msg(" <- connect= $dbh\n") if $DBI::dbi_debug; | ||
690 | |||||
691 | 1 | 23µs | return $dbh; | ||
692 | 1 | 30µs | }; | ||
693 | |||||
694 | 1 | 19µs | 1 | 106ms | my $dbh = &$connect_closure(undef, undef); # spent 106ms making 1 call to DBI::__ANON__[DBI.pm:692] |
695 | |||||
696 | 1 | 36µs | 1 | 12µs | $dbh->{dbi_connect_closure} = $connect_closure if $dbh; # spent 12µs making 1 call to DBI::common::STORE |
697 | |||||
698 | 1 | 26µs | return $dbh; | ||
699 | } | ||||
700 | |||||
701 | |||||
702 | # spent 98µs (63+35) within DBI::disconnect_all which was called
# once (63µs+35µs) by DBI::END at line 501 | ||||
703 | 1 | 4µs | keys %DBI::installed_drh; # reset iterator | ||
704 | 1 | 27µs | while ( my ($name, $drh) = each %DBI::installed_drh ) { | ||
705 | 1 | 70µs | 1 | 35µs | $drh->disconnect_all() if ref $drh; # spent 35µs making 1 call to DBI::dr::disconnect_all |
706 | } | ||||
707 | } | ||||
708 | |||||
709 | |||||
710 | sub disconnect { # a regular beginners bug | ||||
711 | Carp::croak("DBI->disconnect is not a DBI method (read the DBI manual)"); | ||||
712 | } | ||||
713 | |||||
714 | |||||
715 | # spent 31.2ms (16.3+14.9) within DBI::install_driver which was called
# once (16.3ms+14.9ms) by DBI::connect at line 609 | ||||
716 | 1 | 5µs | my $class = shift; | ||
717 | 1 | 5µs | my($driver, $attr) = @_; | ||
718 | 1 | 4µs | my $drh; | ||
719 | |||||
720 | 1 | 5µs | $driver ||= $ENV{DBI_DRIVER} || ''; | ||
721 | |||||
722 | # allow driver to be specified as a 'dbi:driver:' string | ||||
723 | 1 | 35µs | 1 | 5µs | $driver = $1 if $driver =~ s/^DBI:(.*?)://i; # spent 5µs making 1 call to DBI::CORE:subst |
724 | |||||
725 | 1 | 6µs | Carp::croak("usage: $class->install_driver(\$driver [, \%attr])") | ||
726 | unless ($driver and @_<=3); | ||||
727 | |||||
728 | # already installed | ||||
729 | 1 | 5µs | return $drh if $drh = $DBI::installed_drh{$driver}; | ||
730 | |||||
731 | 1 | 5µs | $class->trace_msg(" -> $class->install_driver($driver" | ||
732 | .") for $^O perl=$] pid=$$ ruid=$< euid=$>\n") | ||||
733 | if $DBI::dbi_debug; | ||||
734 | |||||
735 | # --- load the code | ||||
736 | 1 | 6µs | my $driver_class = "DBD::$driver"; | ||
737 | 1 | 288µs | eval qq{package # hide from PAUSE | ||
738 | DBI::_firesafe; # just in case | ||||
739 | require $driver_class; # load the driver | ||||
740 | }; | ||||
741 | 1 | 5µs | if ($@) { | ||
742 | my $err = $@; | ||||
743 | my $advice = ""; | ||||
744 | if ($err =~ /Can't find loadable object/) { | ||||
745 | $advice = "Perhaps DBD::$driver was statically linked into a new perl binary." | ||||
746 | ."\nIn which case you need to use that new perl binary." | ||||
747 | ."\nOr perhaps only the .pm file was installed but not the shared object file." | ||||
748 | } | ||||
749 | elsif ($err =~ /Can't locate.*?DBD\/$driver\.pm in \@INC/) { | ||||
750 | my @drv = $class->available_drivers(1); | ||||
751 | $advice = "Perhaps the DBD::$driver perl module hasn't been fully installed,\n" | ||||
752 | ."or perhaps the capitalisation of '$driver' isn't right.\n" | ||||
753 | ."Available drivers: ".join(", ", @drv)."."; | ||||
754 | } | ||||
755 | elsif ($err =~ /Can't load .*? for module DBD::/) { | ||||
756 | $advice = "Perhaps a required shared library or dll isn't installed where expected"; | ||||
757 | } | ||||
758 | elsif ($err =~ /Can't locate .*? in \@INC/) { | ||||
759 | $advice = "Perhaps a module that DBD::$driver requires hasn't been fully installed"; | ||||
760 | } | ||||
761 | Carp::croak("install_driver($driver) failed: $err$advice\n"); | ||||
762 | } | ||||
763 | 1 | 5µs | if ($DBI::dbi_debug) { | ||
764 | 3 | 609µs | 1 | 102µs | no strict 'refs'; # spent 102µs making 1 call to strict::unimport |
765 | (my $driver_file = $driver_class) =~ s/::/\//g; | ||||
766 | my $dbd_ver = ${"$driver_class\::VERSION"} || "undef"; | ||||
767 | $class->trace_msg(" install_driver: $driver_class version $dbd_ver" | ||||
768 | ." loaded from $INC{qq($driver_file.pm)}\n"); | ||||
769 | } | ||||
770 | |||||
771 | # --- do some behind-the-scenes checks and setups on the driver | ||||
772 | 1 | 46µs | 1 | 274µs | $class->setup_driver($driver_class); # spent 274µs making 1 call to DBI::setup_driver |
773 | |||||
774 | # --- run the driver function | ||||
775 | 2 | 33µs | 1 | 6.27ms | $drh = eval { $driver_class->driver($attr || {}) }; # spent 6.27ms making 1 call to DBD::Pg::driver |
776 | 1 | 8µs | unless ($drh && ref $drh && !$@) { | ||
777 | my $advice = ""; | ||||
778 | # catch people on case in-sensitive systems using the wrong case | ||||
779 | $advice = "\nPerhaps the capitalisation of DBD '$driver' isn't right." | ||||
780 | if $@ =~ /locate object method/; | ||||
781 | Carp::croak("$driver_class initialisation failed: $@$advice"); | ||||
782 | } | ||||
783 | |||||
784 | 1 | 7µs | $DBI::installed_drh{$driver} = $drh; | ||
785 | 1 | 5µs | $class->trace_msg(" <- install_driver= $drh\n") if $DBI::dbi_debug; | ||
786 | 1 | 53µs | $drh; | ||
787 | } | ||||
788 | |||||
789 | 1 | 8µs | *driver = \&install_driver; # currently an alias, may change | ||
790 | |||||
791 | |||||
792 | sub setup_driver { | ||||
793 | 2 | 13µs | my ($class, $driver_class) = @_; | ||
794 | 2 | 9µs | my $type; | ||
795 | 2 | 48µs | foreach $type (qw(dr db st)){ | ||
796 | 6 | 35µs | my $class = $driver_class."::$type"; | ||
797 | 3 | 519µs | 1 | 98µs | no strict 'refs'; # spent 98µs making 1 call to strict::unimport |
798 | 6 | 201µs | 6 | 62µs | push @{"${class}::ISA"}, "DBD::_::$type" # spent 62µs making 6 calls to UNIVERSAL::isa, avg 10µs/call |
799 | unless UNIVERSAL::isa($class, "DBD::_::$type"); | ||||
800 | 6 | 28µs | my $mem_class = "DBD::_mem::$type"; | ||
801 | 6 | 216µs | 6 | 52µs | push @{"${class}_mem::ISA"}, $mem_class # spent 52µs making 6 calls to UNIVERSAL::isa, avg 9µs/call |
802 | unless UNIVERSAL::isa("${class}_mem", $mem_class) | ||||
803 | or $DBI::PurePerl; | ||||
804 | } | ||||
805 | } | ||||
806 | |||||
807 | |||||
808 | # spent 84µs (71+13) within DBI::_rebless which was called
# once (71µs+13µs) by DBI::__ANON__[/project/perl/lib/DBI.pm:692] at line 665 | ||||
809 | 1 | 6µs | my $dbh = shift; | ||
810 | 1 | 33µs | 1 | 13µs | my ($outer, $inner) = DBI::_handles($dbh); # spent 13µs making 1 call to DBI::_handles |
811 | 1 | 7µs | my $class = shift(@_).'::db'; | ||
812 | 1 | 23µs | bless $inner => $class; | ||
813 | 1 | 19µs | bless $outer => $class; # outer last for return | ||
814 | } | ||||
815 | |||||
816 | |||||
817 | # spent 161µs (154+7) within DBI::_set_isa which was called
# once (154µs+7µs) by DBI::__ANON__[/project/perl/lib/DBI.pm:692] at line 664 | ||||
818 | 1 | 5µs | my ($classes, $topclass) = @_; | ||
819 | 1 | 31µs | 1 | 7µs | my $trace = DBI->trace_msg(" _set_isa([@$classes])\n"); # spent 7µs making 1 call to DBD::_::common::trace_msg |
820 | 1 | 37µs | foreach my $suffix ('::db','::st') { | ||
821 | 2 | 9µs | my $previous = $topclass || 'DBI'; # trees are rooted here | ||
822 | 2 | 28µs | foreach my $class (@$classes) { | ||
823 | 2 | 12µs | my $base_class = $previous.$suffix; | ||
824 | 2 | 11µs | my $sub_class = $class.$suffix; | ||
825 | 2 | 10µs | my $sub_class_isa = "${sub_class}::ISA"; | ||
826 | 3 | 1.17ms | 1 | 92µs | no strict 'refs'; # spent 92µs making 1 call to strict::unimport |
827 | 2 | 13µs | if (@$sub_class_isa) { | ||
828 | DBI->trace_msg(" $sub_class_isa skipped (already set to @$sub_class_isa)\n") | ||||
829 | if $trace; | ||||
830 | } | ||||
831 | else { | ||||
832 | @$sub_class_isa = ($base_class) unless @$sub_class_isa; | ||||
833 | DBI->trace_msg(" $sub_class_isa = $base_class\n") | ||||
834 | if $trace; | ||||
835 | } | ||||
836 | 2 | 21µs | $previous = $class; | ||
837 | } | ||||
838 | } | ||||
839 | } | ||||
840 | |||||
841 | |||||
842 | sub _rebless_dbtype_subclass { | ||||
843 | my ($dbh, $rootclass, $DbTypeSubclass) = @_; | ||||
844 | # determine the db type names for class hierarchy | ||||
845 | my @hierarchy = DBI::_dbtype_names($dbh, $DbTypeSubclass); | ||||
846 | # add the rootclass prefix to each ('DBI::' or 'MyDBI::' etc) | ||||
847 | $_ = $rootclass.'::'.$_ foreach (@hierarchy); | ||||
848 | # load the modules from the 'top down' | ||||
849 | DBI::_load_class($_, 1) foreach (reverse @hierarchy); | ||||
850 | # setup class hierarchy if needed, does both '::db' and '::st' | ||||
851 | DBI::_set_isa(\@hierarchy, $rootclass); | ||||
852 | # finally bless the handle into the subclass | ||||
853 | DBI::_rebless($dbh, $hierarchy[0]); | ||||
854 | } | ||||
855 | |||||
856 | |||||
857 | sub _dbtype_names { # list dbtypes for hierarchy, ie Informix=>ADO=>ODBC | ||||
858 | my ($dbh, $DbTypeSubclass) = @_; | ||||
859 | |||||
860 | if ($DbTypeSubclass && $DbTypeSubclass ne '1' && ref $DbTypeSubclass ne 'CODE') { | ||||
861 | # treat $DbTypeSubclass as a comma separated list of names | ||||
862 | my @dbtypes = split /\s*,\s*/, $DbTypeSubclass; | ||||
863 | $dbh->trace_msg(" DbTypeSubclass($DbTypeSubclass)=@dbtypes (explicit)\n"); | ||||
864 | return @dbtypes; | ||||
865 | } | ||||
866 | |||||
867 | # XXX will call $dbh->get_info(17) (=SQL_DBMS_NAME) in future? | ||||
868 | |||||
869 | my $driver = $dbh->{Driver}->{Name}; | ||||
870 | if ( $driver eq 'Proxy' ) { | ||||
871 | # XXX Looking into the internals of DBD::Proxy is questionable! | ||||
872 | ($driver) = $dbh->{proxy_client}->{application} =~ /^DBI:(.+?):/i | ||||
873 | or die "Can't determine driver name from proxy"; | ||||
874 | } | ||||
875 | |||||
876 | my @dbtypes = (ucfirst($driver)); | ||||
877 | if ($driver eq 'ODBC' || $driver eq 'ADO') { | ||||
878 | # XXX will move these out and make extensible later: | ||||
879 | my $_dbtype_name_regexp = 'Oracle'; # eg 'Oracle|Foo|Bar' | ||||
880 | my %_dbtype_name_map = ( | ||||
881 | 'Microsoft SQL Server' => 'MSSQL', | ||||
882 | 'SQL Server' => 'Sybase', | ||||
883 | 'Adaptive Server Anywhere' => 'ASAny', | ||||
884 | 'ADABAS D' => 'AdabasD', | ||||
885 | ); | ||||
886 | |||||
887 | my $name; | ||||
888 | $name = $dbh->func(17, 'GetInfo') # SQL_DBMS_NAME | ||||
889 | if $driver eq 'ODBC'; | ||||
890 | $name = $dbh->{ado_conn}->Properties->Item('DBMS Name')->Value | ||||
891 | if $driver eq 'ADO'; | ||||
892 | die "Can't determine driver name! ($DBI::errstr)\n" | ||||
893 | unless $name; | ||||
894 | |||||
895 | my $dbtype; | ||||
896 | if ($_dbtype_name_map{$name}) { | ||||
897 | $dbtype = $_dbtype_name_map{$name}; | ||||
898 | } | ||||
899 | else { | ||||
900 | if ($name =~ /($_dbtype_name_regexp)/) { | ||||
901 | $dbtype = lc($1); | ||||
902 | } | ||||
903 | else { # generic mangling for other names: | ||||
904 | $dbtype = lc($name); | ||||
905 | } | ||||
906 | $dbtype =~ s/\b(\w)/\U$1/g; | ||||
907 | $dbtype =~ s/\W+/_/g; | ||||
908 | } | ||||
909 | # add ODBC 'behind' ADO | ||||
910 | push @dbtypes, 'ODBC' if $driver eq 'ADO'; | ||||
911 | # add discovered dbtype in front of ADO/ODBC | ||||
912 | unshift @dbtypes, $dbtype; | ||||
913 | } | ||||
914 | @dbtypes = &$DbTypeSubclass($dbh, \@dbtypes) | ||||
915 | if (ref $DbTypeSubclass eq 'CODE'); | ||||
916 | $dbh->trace_msg(" DbTypeSubclass($DbTypeSubclass)=@dbtypes\n"); | ||||
917 | return @dbtypes; | ||||
918 | } | ||||
919 | |||||
920 | # spent 30.0ms (25.2+4.80) within DBI::_load_class which was called
# once (25.2ms+4.80ms) by DBI::__ANON__[/project/perl/lib/DBI.pm:692] at line 655 | ||||
921 | 1 | 6µs | my ($load_class, $missing_ok) = @_; | ||
922 | 1 | 46µs | 1 | 8µs | DBI->trace_msg(" _load_class($load_class, $missing_ok)\n", 2); # spent 8µs making 1 call to DBD::_::common::trace_msg |
923 | 3 | 1.06ms | 1 | 98µs | no strict 'refs'; # spent 98µs making 1 call to strict::unimport |
924 | 1 | 16µs | return 1 if @{"$load_class\::ISA"}; # already loaded/exists | ||
925 | 1 | 38µs | 1 | 14µs | (my $module = $load_class) =~ s!::!/!g; # spent 14µs making 1 call to DBI::CORE:subst |
926 | 1 | 23µs | 1 | 6µs | DBI->trace_msg(" _load_class require $module\n", 2); # spent 6µs making 1 call to DBD::_::common::trace_msg |
927 | 2 | 23.4ms | eval { require "$module.pm"; }; | ||
928 | 1 | 29µs | return 1 unless $@; | ||
929 | return 0 if $missing_ok && $@ =~ /^Can't locate \Q$module.pm\E/; | ||||
930 | die $@; | ||||
931 | } | ||||
932 | |||||
933 | |||||
934 | sub init_rootclass { # deprecated | ||||
935 | return 1; | ||||
936 | } | ||||
937 | |||||
938 | |||||
939 | 1 | 7µs | *internal = \&DBD::Switch::dr::driver; | ||
940 | |||||
941 | |||||
942 | sub available_drivers { | ||||
943 | my($quiet) = @_; | ||||
944 | my(@drivers, $d, $f); | ||||
945 | local(*DBI::DIR, $@); | ||||
946 | my(%seen_dir, %seen_dbd); | ||||
947 | my $haveFileSpec = eval { require File::Spec }; | ||||
948 | foreach $d (@INC){ | ||||
949 | chomp($d); # Perl 5 beta 3 bug in #!./perl -Ilib from Test::Harness | ||||
950 | my $dbd_dir = | ||||
951 | ($haveFileSpec ? File::Spec->catdir($d, 'DBD') : "$d/DBD"); | ||||
952 | next unless -d $dbd_dir; | ||||
953 | next if $seen_dir{$d}; | ||||
954 | $seen_dir{$d} = 1; | ||||
955 | # XXX we have a problem here with case insensitive file systems | ||||
956 | # XXX since we can't tell what case must be used when loading. | ||||
957 | opendir(DBI::DIR, $dbd_dir) || Carp::carp "opendir $dbd_dir: $!\n"; | ||||
958 | foreach $f (readdir(DBI::DIR)){ | ||||
959 | next unless $f =~ s/\.pm$//; | ||||
960 | next if $f eq 'NullP'; | ||||
961 | if ($seen_dbd{$f}){ | ||||
962 | Carp::carp "DBD::$f in $d is hidden by DBD::$f in $seen_dbd{$f}\n" | ||||
963 | unless $quiet; | ||||
964 | } else { | ||||
965 | push(@drivers, $f); | ||||
966 | } | ||||
967 | $seen_dbd{$f} = $d; | ||||
968 | } | ||||
969 | closedir(DBI::DIR); | ||||
970 | } | ||||
971 | |||||
972 | # "return sort @drivers" will not DWIM in scalar context. | ||||
973 | return wantarray ? sort @drivers : @drivers; | ||||
974 | } | ||||
975 | |||||
976 | sub installed_versions { | ||||
977 | my ($class, $quiet) = @_; | ||||
978 | my %error; | ||||
979 | my %version = ( DBI => $DBI::VERSION ); | ||||
980 | $version{"DBI::PurePerl"} = $DBI::PurePerl::VERSION | ||||
981 | if $DBI::PurePerl; | ||||
982 | for my $driver ($class->available_drivers($quiet)) { | ||||
983 | next if $DBI::PurePerl && grep { -d "$_/auto/DBD/$driver" } @INC; | ||||
984 | my $drh = eval { | ||||
985 | local $SIG{__WARN__} = sub {}; | ||||
986 | $class->install_driver($driver); | ||||
987 | }; | ||||
988 | ($error{"DBD::$driver"}=$@),next if $@; | ||||
989 | 3 | 4.60ms | 1 | 99µs | no strict 'refs'; # spent 99µs making 1 call to strict::unimport |
990 | my $vers = ${"DBD::$driver" . '::VERSION'}; | ||||
991 | $version{"DBD::$driver"} = $vers || '?'; | ||||
992 | } | ||||
993 | if (wantarray) { | ||||
994 | return map { m/^DBD::(\w+)/ ? ($1) : () } sort keys %version; | ||||
995 | } | ||||
996 | if (!defined wantarray) { # void context | ||||
997 | require Config; # add more detail | ||||
998 | $version{OS} = "$^O\t($Config::Config{osvers})"; | ||||
999 | $version{Perl} = "$]\t($Config::Config{archname})"; | ||||
1000 | $version{$_} = (($error{$_} =~ s/ \(\@INC.*//s),$error{$_}) | ||||
1001 | for keys %error; | ||||
1002 | printf " %-16s: %s\n",$_,$version{$_} | ||||
1003 | for reverse sort keys %version; | ||||
1004 | } | ||||
1005 | return \%version; | ||||
1006 | } | ||||
1007 | |||||
1008 | |||||
1009 | sub data_sources { | ||||
1010 | my ($class, $driver, @other) = @_; | ||||
1011 | my $drh = $class->install_driver($driver); | ||||
1012 | my @ds = $drh->data_sources(@other); | ||||
1013 | return @ds; | ||||
1014 | } | ||||
1015 | |||||
1016 | |||||
1017 | sub neat_list { | ||||
1018 | my ($listref, $maxlen, $sep) = @_; | ||||
1019 | $maxlen = 0 unless defined $maxlen; # 0 == use internal default | ||||
1020 | $sep = ", " unless defined $sep; | ||||
1021 | join($sep, map { neat($_,$maxlen) } @$listref); | ||||
1022 | } | ||||
1023 | |||||
1024 | |||||
1025 | sub dump_results { # also aliased as a method in DBD::_::st | ||||
1026 | my ($sth, $maxlen, $lsep, $fsep, $fh) = @_; | ||||
1027 | return 0 unless $sth; | ||||
1028 | $maxlen ||= 35; | ||||
1029 | $lsep ||= "\n"; | ||||
1030 | $fh ||= \*STDOUT; | ||||
1031 | my $rows = 0; | ||||
1032 | my $ref; | ||||
1033 | while($ref = $sth->fetch) { | ||||
1034 | print $fh $lsep if $rows++ and $lsep; | ||||
1035 | my $str = neat_list($ref,$maxlen,$fsep); | ||||
1036 | print $fh $str; # done on two lines to avoid 5.003 errors | ||||
1037 | } | ||||
1038 | print $fh "\n$rows rows".($DBI::err ? " ($DBI::err: $DBI::errstr)" : "")."\n"; | ||||
1039 | $rows; | ||||
1040 | } | ||||
1041 | |||||
1042 | |||||
1043 | sub data_diff { | ||||
1044 | my ($a, $b, $logical) = @_; | ||||
1045 | |||||
1046 | my $diff = data_string_diff($a, $b); | ||||
1047 | return "" if $logical and !$diff; | ||||
1048 | |||||
1049 | my $a_desc = data_string_desc($a); | ||||
1050 | my $b_desc = data_string_desc($b); | ||||
1051 | return "" if !$diff and $a_desc eq $b_desc; | ||||
1052 | |||||
1053 | $diff ||= "Strings contain the same sequence of characters" | ||||
1054 | if length($a); | ||||
1055 | $diff .= "\n" if $diff; | ||||
1056 | return "a: $a_desc\nb: $b_desc\n$diff"; | ||||
1057 | } | ||||
1058 | |||||
1059 | |||||
1060 | sub data_string_diff { | ||||
1061 | # Compares 'logical' characters, not bytes, so a latin1 string and an | ||||
1062 | # an equivalent unicode string will compare as equal even though their | ||||
1063 | # byte encodings are different. | ||||
1064 | my ($a, $b) = @_; | ||||
1065 | unless (defined $a and defined $b) { # one undef | ||||
1066 | return "" | ||||
1067 | if !defined $a and !defined $b; | ||||
1068 | return "String a is undef, string b has ".length($b)." characters" | ||||
1069 | if !defined $a; | ||||
1070 | return "String b is undef, string a has ".length($a)." characters" | ||||
1071 | if !defined $b; | ||||
1072 | } | ||||
1073 | |||||
1074 | require utf8; | ||||
1075 | # hack to cater for perl 5.6 | ||||
1076 | *utf8::is_utf8 = sub { (DBI::neat(shift)=~/^"/) } unless defined &utf8::is_utf8; | ||||
1077 | |||||
1078 | my @a_chars = (utf8::is_utf8($a)) ? unpack("U*", $a) : unpack("C*", $a); | ||||
1079 | my @b_chars = (utf8::is_utf8($b)) ? unpack("U*", $b) : unpack("C*", $b); | ||||
1080 | my $i = 0; | ||||
1081 | while (@a_chars && @b_chars) { | ||||
1082 | ++$i, shift(@a_chars), shift(@b_chars), next | ||||
1083 | if $a_chars[0] == $b_chars[0];# compare ordinal values | ||||
1084 | my @desc = map { | ||||
1085 | $_ > 255 ? # if wide character... | ||||
1086 | sprintf("\\x{%04X}", $_) : # \x{...} | ||||
1087 | chr($_) =~ /[[:cntrl:]]/ ? # else if control character ... | ||||
1088 | sprintf("\\x%02X", $_) : # \x.. | ||||
1089 | chr($_) # else as themselves | ||||
1090 | } ($a_chars[0], $b_chars[0]); | ||||
1091 | # highlight probable double-encoding? | ||||
1092 | foreach my $c ( @desc ) { | ||||
1093 | next unless $c =~ m/\\x\{08(..)}/; | ||||
1094 | $c .= "='" .chr(hex($1)) ."'" | ||||
1095 | } | ||||
1096 | return sprintf "Strings differ at index $i: a[$i]=$desc[0], b[$i]=$desc[1]"; | ||||
1097 | } | ||||
1098 | return "String a truncated after $i characters" if @b_chars; | ||||
1099 | return "String b truncated after $i characters" if @a_chars; | ||||
1100 | return ""; | ||||
1101 | } | ||||
1102 | |||||
1103 | |||||
1104 | sub data_string_desc { # describe a data string | ||||
1105 | my ($a) = @_; | ||||
1106 | require bytes; | ||||
1107 | require utf8; | ||||
1108 | |||||
1109 | # hacks to cater for perl 5.6 | ||||
1110 | *utf8::is_utf8 = sub { (DBI::neat(shift)=~/^"/) } unless defined &utf8::is_utf8; | ||||
1111 | *utf8::valid = sub { 1 } unless defined &utf8::valid; | ||||
1112 | |||||
1113 | # Give sufficient info to help diagnose at least these kinds of situations: | ||||
1114 | # - valid UTF8 byte sequence but UTF8 flag not set | ||||
1115 | # (might be ascii so also need to check for hibit to make it worthwhile) | ||||
1116 | # - UTF8 flag set but invalid UTF8 byte sequence | ||||
1117 | # could do better here, but this'll do for now | ||||
1118 | my $utf8 = sprintf "UTF8 %s%s", | ||||
1119 | utf8::is_utf8($a) ? "on" : "off", | ||||
1120 | utf8::valid($a||'') ? "" : " but INVALID encoding"; | ||||
1121 | return "$utf8, undef" unless defined $a; | ||||
1122 | my $is_ascii = $a =~ m/^[\000-\177]*$/; | ||||
1123 | return sprintf "%s, %s, %d characters %d bytes", | ||||
1124 | $utf8, $is_ascii ? "ASCII" : "non-ASCII", | ||||
1125 | length($a), bytes::length($a); | ||||
1126 | } | ||||
1127 | |||||
1128 | |||||
1129 | sub connect_test_perf { | ||||
1130 | my($class, $dsn,$dbuser,$dbpass, $attr) = @_; | ||||
1131 | Carp::croak("connect_test_perf needs hash ref as fourth arg") unless ref $attr; | ||||
1132 | # these are non standard attributes just for this special method | ||||
1133 | my $loops ||= $attr->{dbi_loops} || 5; | ||||
1134 | my $par ||= $attr->{dbi_par} || 1; # parallelism | ||||
1135 | my $verb ||= $attr->{dbi_verb} || 1; | ||||
1136 | print "$dsn: testing $loops sets of $par connections:\n"; | ||||
1137 | require Benchmark; | ||||
1138 | require "FileHandle.pm"; # don't let toke.c create empty FileHandle package | ||||
1139 | $| = 1; | ||||
1140 | my $t0 = new Benchmark; # not currently used | ||||
1141 | my $drh = $class->install_driver($dsn) or Carp::croak("Can't install $dsn driver\n"); | ||||
1142 | my $t1 = new Benchmark; | ||||
1143 | my $loop; | ||||
1144 | for $loop (1..$loops) { | ||||
1145 | my @cons; | ||||
1146 | print "Connecting... " if $verb; | ||||
1147 | for (1..$par) { | ||||
1148 | print "$_ "; | ||||
1149 | push @cons, ($drh->connect($dsn,$dbuser,$dbpass) | ||||
1150 | or Carp::croak("Can't connect # $_: $DBI::errstr\n")); | ||||
1151 | } | ||||
1152 | print "\nDisconnecting...\n" if $verb; | ||||
1153 | for (@cons) { | ||||
1154 | $_->disconnect or warn "bad disconnect $DBI::errstr" | ||||
1155 | } | ||||
1156 | } | ||||
1157 | my $t2 = new Benchmark; | ||||
1158 | my $td = Benchmark::timediff($t2, $t1); | ||||
1159 | printf "Made %2d connections in %s\n", $loops*$par, Benchmark::timestr($td); | ||||
1160 | print "\n"; | ||||
1161 | return $td; | ||||
1162 | } | ||||
1163 | |||||
1164 | |||||
1165 | # Help people doing DBI->errstr, might even document it one day | ||||
1166 | # XXX probably best moved to cheaper XS code | ||||
1167 | sub err { $DBI::err } | ||||
1168 | sub errstr { $DBI::errstr } | ||||
1169 | |||||
1170 | |||||
1171 | # --- Private Internal Function for Creating New DBI Handles | ||||
1172 | |||||
1173 | sub _new_handle { | ||||
1174 | 14 | 100µs | my ($class, $parent, $attr, $imp_data, $imp_class) = @_; | ||
1175 | |||||
1176 | 14 | 118µs | Carp::croak('Usage: DBI::_new_handle' | ||
1177 | .'($class_name, parent_handle, \%attr, $imp_data)'."\n" | ||||
1178 | .'got: ('.join(", ",$class, $parent, $attr, $imp_data).")\n") | ||||
1179 | unless (@_ == 5 and (!$parent or ref $parent) | ||||
1180 | and ref $attr eq 'HASH' | ||||
1181 | and $imp_class); | ||||
1182 | |||||
1183 | 14 | 91µs | $attr->{ImplementorClass} = $imp_class | ||
1184 | or Carp::croak("_new_handle($class): 'ImplementorClass' attribute not given"); | ||||
1185 | |||||
1186 | 14 | 77µs | DBI->trace_msg(" New $class (for $imp_class, parent=$parent, id=".($imp_data||'').")\n") | ||
1187 | if $DBI::dbi_debug >= 3; | ||||
1188 | |||||
1189 | # This is how we create a DBI style Object: | ||||
1190 | 14 | 69µs | my (%hash, $i, $h); | ||
1191 | 14 | 279µs | $i = tie %hash, $class, $attr; # ref to inner hash (for driver) | ||
1192 | 14 | 95µs | $h = bless \%hash, $class; # ref to outer hash (for application) | ||
1193 | # The above tie and bless may migrate down into _setup_handle()... | ||||
1194 | # Now add magic so DBI method dispatch works | ||||
1195 | 14 | 950µs | 14 | 694µs | DBI::_setup_handle($h, $imp_class, $parent, $imp_data); # spent 694µs making 14 calls to DBI::_setup_handle, avg 50µs/call |
1196 | |||||
1197 | 14 | 226µs | return $h unless wantarray; | ||
1198 | 2 | 37µs | ($h, $i); | ||
1199 | } | ||||
1200 | # XXX minimum constructors for the tie's (alias to XS version) | ||||
1201 | 14 | 222µs | sub DBI::st::TIEHASH { bless $_[1] => $_[0] }; | ||
1202 | 1 | 5µs | *DBI::dr::TIEHASH = \&DBI::st::TIEHASH; | ||
1203 | 1 | 4µs | *DBI::db::TIEHASH = \&DBI::st::TIEHASH; | ||
1204 | |||||
1205 | |||||
1206 | # These three special constructors are called by the drivers | ||||
1207 | # The way they are called is likely to change. | ||||
1208 | |||||
1209 | 1 | 4µs | my $profile; | ||
1210 | |||||
1211 | # spent 271µs (77+194) within DBI::_new_drh which was called
# once (77µs+194µs) by DBD::Pg::driver at line 113 of DBD/Pg.pm | ||||
1212 | 1 | 6µs | my ($class, $initial_attr, $imp_data) = @_; | ||
1213 | # Provide default storage for State,Err and Errstr. | ||||
1214 | # Note that these are shared by all child handles by default! XXX | ||||
1215 | # State must be undef to get automatic faking in DBI::var::FETCH | ||||
1216 | 1 | 6µs | my ($h_state_store, $h_err_store, $h_errstr_store) = (undef, 0, ''); | ||
1217 | 1 | 21µs | my $attr = { | ||
1218 | # these attributes get copied down to child handles by default | ||||
1219 | 'State' => \$h_state_store, # Holder for DBI::state | ||||
1220 | 'Err' => \$h_err_store, # Holder for DBI::err | ||||
1221 | 'Errstr' => \$h_errstr_store, # Holder for DBI::errstr | ||||
1222 | 'TraceLevel' => 0, | ||||
1223 | FetchHashKeyName=> 'NAME', | ||||
1224 | %$initial_attr, | ||||
1225 | }; | ||||
1226 | 1 | 20µs | 1 | 194µs | my ($h, $i) = _new_handle('DBI::dr', '', $attr, $imp_data, $class); # spent 194µs making 1 call to DBI::_new_handle |
1227 | |||||
1228 | # XXX DBI_PROFILE unless DBI::PurePerl because for some reason | ||||
1229 | # it kills the t/zz_*_pp.t tests (they silently exit early) | ||||
1230 | 1 | 8µs | if ($ENV{DBI_PROFILE} && !$DBI::PurePerl) { | ||
1231 | # The profile object created here when the first driver is loaded | ||||
1232 | # is shared by all drivers so we end up with just one set of profile | ||||
1233 | # data and thus the 'total time in DBI' is really the true total. | ||||
1234 | if (!$profile) { # first time | ||||
1235 | $h->{Profile} = $ENV{DBI_PROFILE}; | ||||
1236 | $profile = $h->{Profile}; | ||||
1237 | } | ||||
1238 | else { | ||||
1239 | $h->{Profile} = $profile; | ||||
1240 | } | ||||
1241 | } | ||||
1242 | 1 | 47µs | return $h unless wantarray; | ||
1243 | ($h, $i); | ||||
1244 | } | ||||
1245 | |||||
1246 | # spent 278µs (78+200) within DBI::_new_dbh which was called
# once (78µs+200µs) by DBI::dr::connect at line 216 of DBD/Pg.pm | ||||
1247 | 1 | 6µs | my ($drh, $attr, $imp_data) = @_; | ||
1248 | 1 | 7µs | my $imp_class = $drh->{ImplementorClass} | ||
1249 | or Carp::croak("DBI _new_dbh: $drh has no ImplementorClass"); | ||||
1250 | 1 | 9µs | substr($imp_class,-4,4) = '::db'; | ||
1251 | 1 | 5µs | my $app_class = ref $drh; | ||
1252 | 1 | 5µs | substr($app_class,-4,4) = '::db'; | ||
1253 | 1 | 6µs | $attr->{Err} ||= \my $err; | ||
1254 | 1 | 4µs | $attr->{Errstr} ||= \my $errstr; | ||
1255 | 1 | 5µs | $attr->{State} ||= \my $state; | ||
1256 | 1 | 29µs | 1 | 200µs | _new_handle($app_class, $drh, $attr, $imp_data, $imp_class); # spent 200µs making 1 call to DBI::_new_handle |
1257 | } | ||||
1258 | |||||
1259 | # spent 2.53ms (688µs+1.84) within DBI::_new_sth which was called 12 times, avg 211µs/call:
# 12 times (688µs+1.84ms) by DBI::db::prepare at line 263 of DBD/Pg.pm, avg 211µs/call | ||||
1260 | 12 | 60µs | my ($dbh, $attr, $imp_data) = @_; | ||
1261 | 12 | 80µs | my $imp_class = $dbh->{ImplementorClass} | ||
1262 | or Carp::croak("DBI _new_sth: $dbh has no ImplementorClass"); | ||||
1263 | 12 | 105µs | substr($imp_class,-4,4) = '::st'; | ||
1264 | 12 | 65µs | my $app_class = ref $dbh; | ||
1265 | 12 | 64µs | substr($app_class,-4,4) = '::st'; | ||
1266 | 12 | 298µs | 12 | 1.84ms | _new_handle($app_class, $dbh, $attr, $imp_data, $imp_class); # spent 1.84ms making 12 calls to DBI::_new_handle, avg 153µs/call |
1267 | } | ||||
1268 | |||||
1269 | |||||
1270 | # end of DBI package | ||||
1271 | |||||
1272 | |||||
1273 | |||||
1274 | # -------------------------------------------------------------------- | ||||
1275 | # === The internal DBI Switch pseudo 'driver' class === | ||||
1276 | |||||
1277 | 1 | 8µs | { package # hide from PAUSE | ||
1278 | DBD::Switch::dr; | ||||
1279 | 1 | 19µs | 1 | 267µs | DBI->setup_driver('DBD::Switch'); # sets up @ISA # spent 267µs making 1 call to DBI::setup_driver |
1280 | |||||
1281 | 1 | 5µs | $DBD::Switch::dr::imp_data_size = 0; | ||
1282 | 1 | 4µs | $DBD::Switch::dr::imp_data_size = 0; # avoid typo warning | ||
1283 | 1 | 4µs | my $drh; | ||
1284 | |||||
1285 | sub driver { | ||||
1286 | return $drh if $drh; # a package global | ||||
1287 | |||||
1288 | my $inner; | ||||
1289 | ($drh, $inner) = DBI::_new_drh('DBD::Switch::dr', { | ||||
1290 | 'Name' => 'Switch', | ||||
1291 | 'Version' => $DBI::VERSION, | ||||
1292 | 'Attribution' => "DBI $DBI::VERSION by Tim Bunce", | ||||
1293 | }); | ||||
1294 | Carp::croak("DBD::Switch init failed!") unless ($drh && $inner); | ||||
1295 | return $drh; | ||||
1296 | } | ||||
1297 | sub CLONE { | ||||
1298 | undef $drh; | ||||
1299 | } | ||||
1300 | |||||
1301 | sub FETCH { | ||||
1302 | my($drh, $key) = @_; | ||||
1303 | return DBI->trace if $key eq 'DebugDispatch'; | ||||
1304 | return undef if $key eq 'DebugLog'; # not worth fetching, sorry | ||||
1305 | return $drh->DBD::_::dr::FETCH($key); | ||||
1306 | undef; | ||||
1307 | } | ||||
1308 | sub STORE { | ||||
1309 | my($drh, $key, $value) = @_; | ||||
1310 | if ($key eq 'DebugDispatch') { | ||||
1311 | DBI->trace($value); | ||||
1312 | } elsif ($key eq 'DebugLog') { | ||||
1313 | DBI->trace(-1, $value); | ||||
1314 | } else { | ||||
1315 | $drh->DBD::_::dr::STORE($key, $value); | ||||
1316 | } | ||||
1317 | } | ||||
1318 | } | ||||
1319 | |||||
1320 | |||||
1321 | # -------------------------------------------------------------------- | ||||
1322 | # === OPTIONAL MINIMAL BASE CLASSES FOR DBI SUBCLASSES === | ||||
1323 | |||||
1324 | # We only define default methods for harmless functions. | ||||
1325 | # We don't, for example, define a DBD::_::st::prepare() | ||||
1326 | |||||
1327 | 1 | 8µs | { package # hide from PAUSE | ||
1328 | DBD::_::common; # ====== Common base class methods ====== | ||||
1329 | 3 | 1.22ms | 1 | 24µs | use strict; # spent 24µs making 1 call to strict::import |
1330 | |||||
1331 | # methods common to all handle types: | ||||
1332 | |||||
1333 | sub _not_impl { | ||||
1334 | my ($h, $method) = @_; | ||||
1335 | $h->trace_msg("Driver does not implement the $method method.\n"); | ||||
1336 | return; # empty list / undef | ||||
1337 | } | ||||
1338 | |||||
1339 | # generic TIEHASH default methods: | ||||
1340 | sub FIRSTKEY { } | ||||
1341 | sub NEXTKEY { } | ||||
1342 | sub EXISTS { defined($_[0]->FETCH($_[1])) } # XXX undef? | ||||
1343 | sub CLEAR { Carp::carp "Can't CLEAR $_[0] (DBI)" } | ||||
1344 | |||||
1345 | 1 | 7µs | *dump_handle = \&DBI::dump_handle; | ||
1346 | |||||
1347 | # spent 4.99ms (3.05+1.94) within DBD::_::common::install_method which was called 31 times, avg 161µs/call:
# once (109µs+934µs) by DBD::Pg::driver at line 151 of DBD/Pg.pm
# once (132µs+43µs) by DBD::Pg::driver at line 123 of DBD/Pg.pm
# once (109µs+39µs) by DBD::Pg::driver at line 152 of DBD/Pg.pm
# once (114µs+33µs) by DBD::Pg::driver at line 124 of DBD/Pg.pm
# once (113µs+34µs) by DBD::Pg::driver at line 134 of DBD/Pg.pm
# once (111µs+33µs) by DBD::Pg::driver at line 155 of DBD/Pg.pm
# once (113µs+31µs) by DBD::Pg::driver at line 144 of DBD/Pg.pm
# once (95µs+45µs) by DBD::Pg::driver at line 149 of DBD/Pg.pm
# once (106µs+33µs) by DBD::Pg::driver at line 150 of DBD/Pg.pm
# once (99µs+37µs) by DBD::Pg::driver at line 147 of DBD/Pg.pm
# once (101µs+33µs) by DBD::Pg::driver at line 139 of DBD/Pg.pm
# once (91µs+41µs) by DBD::Pg::driver at line 154 of DBD/Pg.pm
# once (94µs+36µs) by DBD::Pg::driver at line 136 of DBD/Pg.pm
# once (98µs+32µs) by DBD::Pg::driver at line 126 of DBD/Pg.pm
# once (94µs+33µs) by DBD::Pg::driver at line 146 of DBD/Pg.pm
# once (92µs+34µs) by DBD::Pg::driver at line 127 of DBD/Pg.pm
# once (92µs+34µs) by DBD::Pg::driver at line 125 of DBD/Pg.pm
# once (94µs+31µs) by DBD::Pg::driver at line 130 of DBD/Pg.pm
# once (93µs+32µs) by DBD::Pg::driver at line 142 of DBD/Pg.pm
# once (93µs+32µs) by DBD::Pg::driver at line 133 of DBD/Pg.pm
# once (95µs+30µs) by DBD::Pg::driver at line 132 of DBD/Pg.pm
# once (93µs+31µs) by DBD::Pg::driver at line 128 of DBD/Pg.pm
# once (92µs+32µs) by DBD::Pg::driver at line 138 of DBD/Pg.pm
# once (90µs+34µs) by DBD::Pg::driver at line 148 of DBD/Pg.pm
# once (94µs+29µs) by DBD::Pg::driver at line 129 of DBD/Pg.pm
# once (92µs+31µs) by DBD::Pg::driver at line 153 of DBD/Pg.pm
# once (92µs+31µs) by DBD::Pg::driver at line 137 of DBD/Pg.pm
# once (91µs+32µs) by DBD::Pg::driver at line 140 of DBD/Pg.pm
# once (91µs+31µs) by DBD::Pg::driver at line 143 of DBD/Pg.pm
# once (90µs+30µs) by DBD::Pg::driver at line 131 of DBD/Pg.pm
# once (88µs+29µs) by DBD::Pg::driver at line 135 of DBD/Pg.pm | ||||
1348 | # special class method called directly by apps and/or drivers | ||||
1349 | # to install new methods into the DBI dispatcher | ||||
1350 | # DBD::Foo::db->install_method("foo_mumble", { usage => [...], options => '...' }); | ||||
1351 | 31 | 187µs | my ($class, $method, $attr) = @_; | ||
1352 | 31 | 709µs | 31 | 275µs | Carp::croak("Class '$class' must begin with DBD:: and end with ::db or ::st") # spent 275µs making 31 calls to DBD::_::common::CORE:match, avg 9µs/call |
1353 | unless $class =~ /^DBD::(\w+)::(dr|db|st)$/; | ||||
1354 | 31 | 260µs | my ($driver, $subtype) = ($1, $2); | ||
1355 | 31 | 588µs | 31 | 240µs | Carp::croak("invalid method name '$method'") # spent 240µs making 31 calls to DBD::_::common::CORE:match, avg 8µs/call |
1356 | unless $method =~ m/^([a-z]+_)\w+$/; | ||||
1357 | 31 | 173µs | my $prefix = $1; | ||
1358 | 31 | 164µs | my $reg_info = $dbd_prefix_registry->{$prefix}; | ||
1359 | 31 | 133µs | Carp::carp("method name prefix '$prefix' is not associated with a registered driver") unless $reg_info; | ||
1360 | 31 | 234µs | my %attr = %{$attr||{}}; # copy so we can edit | ||
1361 | # XXX reformat $attr as needed for _install_method | ||||
1362 | 31 | 263µs | my ($caller_pkg, $filename, $line) = caller; | ||
1363 | 31 | 2.39ms | 31 | 1.43ms | DBI->_install_method("DBI::${subtype}::$method", "$filename at line $line", \%attr); # spent 1.43ms making 31 calls to DBI::_install_method, avg 46µs/call |
1364 | } | ||||
1365 | |||||
1366 | sub parse_trace_flags { | ||||
1367 | my ($h, $spec) = @_; | ||||
1368 | my $level = 0; | ||||
1369 | my $flags = 0; | ||||
1370 | my @unknown; | ||||
1371 | for my $word (split /\s*[|&,]\s*/, $spec) { | ||||
1372 | if (DBI::looks_like_number($word) && $word <= 0xF && $word >= 0) { | ||||
1373 | $level = $word; | ||||
1374 | } elsif ($word eq 'ALL') { | ||||
1375 | $flags = 0x7FFFFFFF; # XXX last bit causes negative headaches | ||||
1376 | last; | ||||
1377 | } elsif (my $flag = $h->parse_trace_flag($word)) { | ||||
1378 | $flags |= $flag; | ||||
1379 | } | ||||
1380 | else { | ||||
1381 | push @unknown, $word; | ||||
1382 | } | ||||
1383 | } | ||||
1384 | if (@unknown && (ref $h ? $h->FETCH('Warn') : 1)) { | ||||
1385 | Carp::carp("$h->parse_trace_flags($spec) ignored unknown trace flags: ". | ||||
1386 | join(" ", map { DBI::neat($_) } @unknown)); | ||||
1387 | } | ||||
1388 | $flags |= $level; | ||||
1389 | return $flags; | ||||
1390 | } | ||||
1391 | |||||
1392 | sub parse_trace_flag { | ||||
1393 | my ($h, $name) = @_; | ||||
1394 | # 0xddDDDDrL (driver, DBI, reserved, Level) | ||||
1395 | return 0x00000100 if $name eq 'SQL'; | ||||
1396 | return; | ||||
1397 | } | ||||
1398 | |||||
1399 | sub private_attribute_info { | ||||
1400 | return undef; | ||||
1401 | } | ||||
1402 | |||||
1403 | } | ||||
1404 | |||||
1405 | |||||
1406 | 1 | 8µs | { package # hide from PAUSE | ||
1407 | DBD::_::dr; # ====== DRIVER ====== | ||||
1408 | 1 | 7µs | @DBD::_::dr::ISA = qw(DBD::_::common); | ||
1409 | 3 | 734µs | 1 | 24µs | use strict; # spent 24µs making 1 call to strict::import |
1410 | |||||
1411 | sub default_user { | ||||
1412 | my ($drh, $user, $pass, $attr) = @_; | ||||
1413 | $user = $ENV{DBI_USER} unless defined $user; | ||||
1414 | $pass = $ENV{DBI_PASS} unless defined $pass; | ||||
1415 | return ($user, $pass); | ||||
1416 | } | ||||
1417 | |||||
1418 | sub connect { # normally overridden, but a handy default | ||||
1419 | my ($drh, $dsn, $user, $auth) = @_; | ||||
1420 | my ($this) = DBI::_new_dbh($drh, { | ||||
1421 | 'Name' => $dsn, | ||||
1422 | }); | ||||
1423 | # XXX debatable as there's no "server side" here | ||||
1424 | # (and now many uses would trigger warnings on DESTROY) | ||||
1425 | # $this->STORE(Active => 1); | ||||
1426 | # so drivers should set it in their own connect | ||||
1427 | $this; | ||||
1428 | } | ||||
1429 | |||||
1430 | |||||
1431 | sub connect_cached { | ||||
1432 | 1 | 5µs | my $drh = shift; | ||
1433 | 1 | 7µs | my ($dsn, $user, $auth, $attr)= @_; | ||
1434 | |||||
1435 | # Needs support at dbh level to clear cache before complaining about | ||||
1436 | # active children. The XS template code does this. Drivers not using | ||||
1437 | # the template must handle clearing the cache themselves. | ||||
1438 | 1 | 59µs | 1 | 26µs | my $cache = $drh->FETCH('CachedKids'); # spent 26µs making 1 call to DBI::common::FETCH |
1439 | 1 | 50µs | 1 | 23µs | $drh->STORE('CachedKids', $cache = {}) unless $cache; # spent 23µs making 1 call to DBI::common::STORE |
1440 | |||||
1441 | 1 | 71µs | 1 | 29µs | my @attr_keys = $attr ? sort keys %$attr : (); # spent 29µs making 1 call to DBD::_::dr::CORE:sort |
1442 | 2 | 19µs | my $key = do { local $^W; # silence undef warnings | ||
1443 | 1 | 26µs | join "~~", $dsn, $user||'', $auth||'', $attr ? (@attr_keys,@{$attr}{@attr_keys}) : () | ||
1444 | }; | ||||
1445 | 1 | 5µs | my $dbh = $cache->{$key}; | ||
1446 | 1 | 5µs | my $cb = $attr->{Callbacks}; # take care not to autovivify | ||
1447 | 1 | 5µs | if ($dbh && $dbh->FETCH('Active') && eval { $dbh->ping }) { | ||
1448 | # If the caller has provided a callback then call it | ||||
1449 | if ($cb and $cb = $cb->{"connect_cached.reused"}) { | ||||
1450 | local $_ = "connect_cached.reused"; | ||||
1451 | $cb->($dbh, $dsn, $user, $auth, $attr); | ||||
1452 | } | ||||
1453 | return $dbh; | ||||
1454 | } | ||||
1455 | |||||
1456 | # If the caller has provided a callback then call it | ||||
1457 | 1 | 4µs | if ($cb and $cb = $cb->{"connect_cached.new"}) { | ||
1458 | local $_ = "connect_cached.new"; | ||||
1459 | $cb->($dbh, $dsn, $user, $auth, $attr); | ||||
1460 | } | ||||
1461 | |||||
1462 | 1 | 46µs | 1 | 74.6ms | $dbh = $drh->connect(@_); # spent 74.6ms making 1 call to DBI::dr::connect |
1463 | 1 | 7µs | $cache->{$key} = $dbh; # replace prev entry, even if connect failed | ||
1464 | 1 | 9µs | return $dbh; | ||
1465 | } | ||||
1466 | |||||
1467 | } | ||||
1468 | |||||
1469 | |||||
1470 | 1 | 9µs | { package # hide from PAUSE | ||
1471 | DBD::_::db; # ====== DATABASE ====== | ||||
1472 | 1 | 6µs | @DBD::_::db::ISA = qw(DBD::_::common); | ||
1473 | 3 | 3.68ms | 1 | 24µs | use strict; # spent 24µs making 1 call to strict::import |
1474 | |||||
1475 | sub clone { | ||||
1476 | my ($old_dbh, $attr) = @_; | ||||
1477 | my $closure = $old_dbh->{dbi_connect_closure} or return; | ||||
1478 | unless ($attr) { | ||||
1479 | # copy attributes visible in the attribute cache | ||||
1480 | keys %$old_dbh; # reset iterator | ||||
1481 | while ( my ($k, $v) = each %$old_dbh ) { | ||||
1482 | # ignore non-code refs, i.e., caches, handles, Err etc | ||||
1483 | next if ref $v && ref $v ne 'CODE'; # HandleError etc | ||||
1484 | $attr->{$k} = $v; | ||||
1485 | } | ||||
1486 | # explicitly set attributes which are unlikely to be in the | ||||
1487 | # attribute cache, i.e., boolean's and some others | ||||
1488 | $attr->{$_} = $old_dbh->FETCH($_) for (qw( | ||||
1489 | AutoCommit ChopBlanks InactiveDestroy | ||||
1490 | LongTruncOk PrintError PrintWarn Profile RaiseError | ||||
1491 | ShowErrorStatement TaintIn TaintOut | ||||
1492 | )); | ||||
1493 | } | ||||
1494 | # use Data::Dumper; warn Dumper([$old_dbh, $attr]); | ||||
1495 | my $new_dbh = &$closure($old_dbh, $attr); | ||||
1496 | unless ($new_dbh) { | ||||
1497 | # need to copy err/errstr from driver back into $old_dbh | ||||
1498 | my $drh = $old_dbh->{Driver}; | ||||
1499 | return $old_dbh->set_err($drh->err, $drh->errstr, $drh->state); | ||||
1500 | } | ||||
1501 | return $new_dbh; | ||||
1502 | } | ||||
1503 | |||||
1504 | sub quote_identifier { | ||||
1505 | my ($dbh, @id) = @_; | ||||
1506 | my $attr = (@id > 3 && ref($id[-1])) ? pop @id : undef; | ||||
1507 | |||||
1508 | my $info = $dbh->{dbi_quote_identifier_cache} ||= [ | ||||
1509 | $dbh->get_info(29) || '"', # SQL_IDENTIFIER_QUOTE_CHAR | ||||
1510 | $dbh->get_info(41) || '.', # SQL_CATALOG_NAME_SEPARATOR | ||||
1511 | $dbh->get_info(114) || 1, # SQL_CATALOG_LOCATION | ||||
1512 | ]; | ||||
1513 | |||||
1514 | my $quote = $info->[0]; | ||||
1515 | foreach (@id) { # quote the elements | ||||
1516 | next unless defined; | ||||
1517 | s/$quote/$quote$quote/g; # escape embedded quotes | ||||
1518 | $_ = qq{$quote$_$quote}; | ||||
1519 | } | ||||
1520 | |||||
1521 | # strip out catalog if present for special handling | ||||
1522 | my $catalog = (@id >= 3) ? shift @id : undef; | ||||
1523 | |||||
1524 | # join the dots, ignoring any null/undef elements (ie schema) | ||||
1525 | my $quoted_id = join '.', grep { defined } @id; | ||||
1526 | |||||
1527 | if ($catalog) { # add catalog correctly | ||||
1528 | $quoted_id = ($info->[2] == 2) # SQL_CL_END | ||||
1529 | ? $quoted_id . $info->[1] . $catalog | ||||
1530 | : $catalog . $info->[1] . $quoted_id; | ||||
1531 | } | ||||
1532 | return $quoted_id; | ||||
1533 | } | ||||
1534 | |||||
1535 | sub quote { | ||||
1536 | my ($dbh, $str, $data_type) = @_; | ||||
1537 | |||||
1538 | return "NULL" unless defined $str; | ||||
1539 | unless ($data_type) { | ||||
1540 | $str =~ s/'/''/g; # ISO SQL2 | ||||
1541 | return "'$str'"; | ||||
1542 | } | ||||
1543 | |||||
1544 | my $dbi_literal_quote_cache = $dbh->{'dbi_literal_quote_cache'} ||= [ {} , {} ]; | ||||
1545 | my ($prefixes, $suffixes) = @$dbi_literal_quote_cache; | ||||
1546 | |||||
1547 | my $lp = $prefixes->{$data_type}; | ||||
1548 | my $ls = $suffixes->{$data_type}; | ||||
1549 | |||||
1550 | if ( ! defined $lp || ! defined $ls ) { | ||||
1551 | my $ti = $dbh->type_info($data_type); | ||||
1552 | $lp = $prefixes->{$data_type} = $ti ? $ti->{LITERAL_PREFIX} || "" : "'"; | ||||
1553 | $ls = $suffixes->{$data_type} = $ti ? $ti->{LITERAL_SUFFIX} || "" : "'"; | ||||
1554 | } | ||||
1555 | return $str unless $lp || $ls; # no quoting required | ||||
1556 | |||||
1557 | # XXX don't know what the standard says about escaping | ||||
1558 | # in the 'general case' (where $lp != "'"). | ||||
1559 | # So we just do this and hope: | ||||
1560 | $str =~ s/$lp/$lp$lp/g | ||||
1561 | if $lp && $lp eq $ls && ($lp eq "'" || $lp eq '"'); | ||||
1562 | return "$lp$str$ls"; | ||||
1563 | } | ||||
1564 | |||||
1565 | sub rows { -1 } # here so $DBI::rows 'works' after using $dbh | ||||
1566 | |||||
1567 | sub do { | ||||
1568 | my($dbh, $statement, $attr, @params) = @_; | ||||
1569 | my $sth = $dbh->prepare($statement, $attr) or return undef; | ||||
1570 | $sth->execute(@params) or return undef; | ||||
1571 | my $rows = $sth->rows; | ||||
1572 | ($rows == 0) ? "0E0" : $rows; | ||||
1573 | } | ||||
1574 | |||||
1575 | sub _do_selectrow { | ||||
1576 | my ($method, $dbh, $stmt, $attr, @bind) = @_; | ||||
1577 | my $sth = ((ref $stmt) ? $stmt : $dbh->prepare($stmt, $attr)) | ||||
1578 | or return; | ||||
1579 | $sth->execute(@bind) | ||||
1580 | or return; | ||||
1581 | my $row = $sth->$method() | ||||
1582 | and $sth->finish; | ||||
1583 | return $row; | ||||
1584 | } | ||||
1585 | |||||
1586 | sub selectrow_hashref { return _do_selectrow('fetchrow_hashref', @_); } | ||||
1587 | |||||
1588 | # XXX selectrow_array/ref also have C implementations in Driver.xst | ||||
1589 | sub selectrow_arrayref { return _do_selectrow('fetchrow_arrayref', @_); } | ||||
1590 | sub selectrow_array { | ||||
1591 | my $row = _do_selectrow('fetchrow_arrayref', @_) or return; | ||||
1592 | return $row->[0] unless wantarray; | ||||
1593 | return @$row; | ||||
1594 | } | ||||
1595 | |||||
1596 | # XXX selectall_arrayref also has C implementation in Driver.xst | ||||
1597 | # which fallsback to this if a slice is given | ||||
1598 | sub selectall_arrayref { | ||||
1599 | my ($dbh, $stmt, $attr, @bind) = @_; | ||||
1600 | my $sth = (ref $stmt) ? $stmt : $dbh->prepare($stmt, $attr) | ||||
1601 | or return; | ||||
1602 | $sth->execute(@bind) || return; | ||||
1603 | my $slice = $attr->{Slice}; # typically undef, else hash or array ref | ||||
1604 | if (!$slice and $slice=$attr->{Columns}) { | ||||
1605 | if (ref $slice eq 'ARRAY') { # map col idx to perl array idx | ||||
1606 | $slice = [ @{$attr->{Columns}} ]; # take a copy | ||||
1607 | for (@$slice) { $_-- } | ||||
1608 | } | ||||
1609 | } | ||||
1610 | my $rows = $sth->fetchall_arrayref($slice, my $MaxRows = $attr->{MaxRows}); | ||||
1611 | $sth->finish if defined $MaxRows; | ||||
1612 | return $rows; | ||||
1613 | } | ||||
1614 | |||||
1615 | sub selectall_hashref { | ||||
1616 | my ($dbh, $stmt, $key_field, $attr, @bind) = @_; | ||||
1617 | my $sth = (ref $stmt) ? $stmt : $dbh->prepare($stmt, $attr); | ||||
1618 | return unless $sth; | ||||
1619 | $sth->execute(@bind) || return; | ||||
1620 | return $sth->fetchall_hashref($key_field); | ||||
1621 | } | ||||
1622 | |||||
1623 | sub selectcol_arrayref { | ||||
1624 | my ($dbh, $stmt, $attr, @bind) = @_; | ||||
1625 | my $sth = (ref $stmt) ? $stmt : $dbh->prepare($stmt, $attr); | ||||
1626 | return unless $sth; | ||||
1627 | $sth->execute(@bind) || return; | ||||
1628 | my @columns = ($attr->{Columns}) ? @{$attr->{Columns}} : (1); | ||||
1629 | my @values = (undef) x @columns; | ||||
1630 | my $idx = 0; | ||||
1631 | for (@columns) { | ||||
1632 | $sth->bind_col($_, \$values[$idx++]) || return; | ||||
1633 | } | ||||
1634 | my @col; | ||||
1635 | if (my $max = $attr->{MaxRows}) { | ||||
1636 | push @col, @values while @col<$max && $sth->fetch; | ||||
1637 | } | ||||
1638 | else { | ||||
1639 | push @col, @values while $sth->fetch; | ||||
1640 | } | ||||
1641 | return \@col; | ||||
1642 | } | ||||
1643 | |||||
1644 | sub prepare_cached { | ||||
1645 | 2 | 15µs | my ($dbh, $statement, $attr, $if_active) = @_; | ||
1646 | # Needs support at dbh level to clear cache before complaining about | ||||
1647 | # active children. The XS template code does this. Drivers not using | ||||
1648 | # the template must handle clearing the cache themselves. | ||||
1649 | 2 | 75µs | 2 | 30µs | my $cache = $dbh->FETCH('CachedKids'); # spent 30µs making 2 calls to DBI::common::FETCH, avg 15µs/call |
1650 | 2 | 43µs | 1 | 14µs | $dbh->STORE('CachedKids', $cache = {}) unless $cache; # spent 14µs making 1 call to DBI::common::STORE |
1651 | 2 | 11µs | my @attr_keys = ($attr) ? sort keys %$attr : (); | ||
1652 | 2 | 10µs | my $key = ($attr) ? join("~~", $statement, @attr_keys, @{$attr}{@attr_keys}) : $statement; | ||
1653 | 2 | 10µs | my $sth = $cache->{$key}; | ||
1654 | 2 | 9µs | if ($sth) { | ||
1655 | return $sth unless $sth->FETCH('Active'); | ||||
1656 | Carp::carp("prepare_cached($statement) statement handle $sth still Active") | ||||
1657 | unless ($if_active ||= 0); | ||||
1658 | $sth->finish if $if_active <= 1; | ||||
1659 | return $sth if $if_active <= 2; | ||||
1660 | } | ||||
1661 | 2 | 76µs | 2 | 651µs | $sth = $dbh->prepare($statement, $attr); # spent 651µs making 2 calls to DBI::db::prepare, avg 326µs/call |
1662 | 2 | 15µs | $cache->{$key} = $sth if $sth; | ||
1663 | 2 | 14µs | return $sth; | ||
1664 | } | ||||
1665 | |||||
1666 | sub ping { | ||||
1667 | my $dbh = shift; | ||||
1668 | $dbh->_not_impl('ping'); | ||||
1669 | # "0 but true" is a special kind of true 0 that is used here so | ||||
1670 | # applications can check if the ping was a real ping or not | ||||
1671 | ($dbh->FETCH('Active')) ? "0 but true" : 0; | ||||
1672 | } | ||||
1673 | |||||
1674 | sub begin_work { | ||||
1675 | my $dbh = shift; | ||||
1676 | return $dbh->set_err(1, "Already in a transaction") | ||||
1677 | unless $dbh->FETCH('AutoCommit'); | ||||
1678 | $dbh->STORE('AutoCommit', 0); # will croak if driver doesn't support it | ||||
1679 | $dbh->STORE('BegunWork', 1); # trigger post commit/rollback action | ||||
1680 | return 1; | ||||
1681 | } | ||||
1682 | |||||
1683 | sub primary_key { | ||||
1684 | my ($dbh, @args) = @_; | ||||
1685 | my $sth = $dbh->primary_key_info(@args) or return; | ||||
1686 | my ($row, @col); | ||||
1687 | push @col, $row->[3] while ($row = $sth->fetch); | ||||
1688 | Carp::croak("primary_key method not called in list context") | ||||
1689 | unless wantarray; # leave us some elbow room | ||||
1690 | return @col; | ||||
1691 | } | ||||
1692 | |||||
1693 | sub tables { | ||||
1694 | my ($dbh, @args) = @_; | ||||
1695 | my $sth = $dbh->table_info(@args[0,1,2,3,4]) or return; | ||||
1696 | my $tables = $sth->fetchall_arrayref or return; | ||||
1697 | my @tables; | ||||
1698 | if ($dbh->get_info(29)) { # SQL_IDENTIFIER_QUOTE_CHAR | ||||
1699 | @tables = map { $dbh->quote_identifier( @{$_}[0,1,2] ) } @$tables; | ||||
1700 | } | ||||
1701 | else { # temporary old style hack (yeach) | ||||
1702 | @tables = map { | ||||
1703 | my $name = $_->[2]; | ||||
1704 | if ($_->[1]) { | ||||
1705 | my $schema = $_->[1]; | ||||
1706 | # a sad hack (mostly for Informix I recall) | ||||
1707 | my $quote = ($schema eq uc($schema)) ? '' : '"'; | ||||
1708 | $name = "$quote$schema$quote.$name" | ||||
1709 | } | ||||
1710 | $name; | ||||
1711 | } @$tables; | ||||
1712 | } | ||||
1713 | return @tables; | ||||
1714 | } | ||||
1715 | |||||
1716 | sub type_info { # this should be sufficient for all drivers | ||||
1717 | my ($dbh, $data_type) = @_; | ||||
1718 | my $idx_hash; | ||||
1719 | my $tia = $dbh->{dbi_type_info_row_cache}; | ||||
1720 | if ($tia) { | ||||
1721 | $idx_hash = $dbh->{dbi_type_info_idx_cache}; | ||||
1722 | } | ||||
1723 | else { | ||||
1724 | my $temp = $dbh->type_info_all; | ||||
1725 | return unless $temp && @$temp; | ||||
1726 | # we cache here because type_info_all may be expensive to call | ||||
1727 | # (and we take a copy so the following shift can't corrupt | ||||
1728 | # the data that may be returned by future calls to type_info_all) | ||||
1729 | $tia = $dbh->{dbi_type_info_row_cache} = [ @$temp ]; | ||||
1730 | $idx_hash = $dbh->{dbi_type_info_idx_cache} = shift @$tia; | ||||
1731 | } | ||||
1732 | |||||
1733 | my $dt_idx = $idx_hash->{DATA_TYPE} || $idx_hash->{data_type}; | ||||
1734 | Carp::croak("type_info_all returned non-standard DATA_TYPE index value ($dt_idx != 1)") | ||||
1735 | if $dt_idx && $dt_idx != 1; | ||||
1736 | |||||
1737 | # --- simple DATA_TYPE match filter | ||||
1738 | my @ti; | ||||
1739 | my @data_type_list = (ref $data_type) ? @$data_type : ($data_type); | ||||
1740 | foreach $data_type (@data_type_list) { | ||||
1741 | if (defined($data_type) && $data_type != DBI::SQL_ALL_TYPES()) { | ||||
1742 | push @ti, grep { $_->[$dt_idx] == $data_type } @$tia; | ||||
1743 | } | ||||
1744 | else { # SQL_ALL_TYPES | ||||
1745 | push @ti, @$tia; | ||||
1746 | } | ||||
1747 | last if @ti; # found at least one match | ||||
1748 | } | ||||
1749 | |||||
1750 | # --- format results into list of hash refs | ||||
1751 | my $idx_fields = keys %$idx_hash; | ||||
1752 | my @idx_names = map { uc($_) } keys %$idx_hash; | ||||
1753 | my @idx_values = values %$idx_hash; | ||||
1754 | Carp::croak "type_info_all result has $idx_fields keys but ".(@{$ti[0]})." fields" | ||||
1755 | if @ti && @{$ti[0]} != $idx_fields; | ||||
1756 | my @out = map { | ||||
1757 | my %h; @h{@idx_names} = @{$_}[ @idx_values ]; \%h; | ||||
1758 | } @ti; | ||||
1759 | return $out[0] unless wantarray; | ||||
1760 | return @out; | ||||
1761 | } | ||||
1762 | |||||
1763 | sub data_sources { | ||||
1764 | my ($dbh, @other) = @_; | ||||
1765 | my $drh = $dbh->{Driver}; # XXX proxy issues? | ||||
1766 | return $drh->data_sources(@other); | ||||
1767 | } | ||||
1768 | |||||
1769 | } | ||||
1770 | |||||
1771 | |||||
1772 | 1 | 9µs | { package # hide from PAUSE | ||
1773 | DBD::_::st; # ====== STATEMENT ====== | ||||
1774 | 1 | 6µs | @DBD::_::st::ISA = qw(DBD::_::common); | ||
1775 | 3 | 3.28ms | 1 | 25µs | use strict; # spent 25µs making 1 call to strict::import |
1776 | |||||
1777 | sub bind_param { Carp::croak("Can't bind_param, not implement by driver") } | ||||
1778 | |||||
1779 | # | ||||
1780 | # ******************************************************** | ||||
1781 | # | ||||
1782 | # BEGIN ARRAY BINDING | ||||
1783 | # | ||||
1784 | # Array binding support for drivers which don't support | ||||
1785 | # array binding, but have sufficient interfaces to fake it. | ||||
1786 | # NOTE: mixing scalars and arrayrefs requires using bind_param_array | ||||
1787 | # for *all* params...unless we modify bind_param for the default | ||||
1788 | # case... | ||||
1789 | # | ||||
1790 | # 2002-Apr-10 D. Arnold | ||||
1791 | |||||
1792 | sub bind_param_array { | ||||
1793 | my $sth = shift; | ||||
1794 | my ($p_id, $value_array, $attr) = @_; | ||||
1795 | |||||
1796 | return $sth->set_err(1, "Value for parameter $p_id must be a scalar or an arrayref, not a ".ref($value_array)) | ||||
1797 | if defined $value_array and ref $value_array and ref $value_array ne 'ARRAY'; | ||||
1798 | |||||
1799 | return $sth->set_err(1, "Can't use named placeholder '$p_id' for non-driver supported bind_param_array") | ||||
1800 | unless DBI::looks_like_number($p_id); # because we rely on execute(@ary) here | ||||
1801 | |||||
1802 | return $sth->set_err(1, "Placeholder '$p_id' is out of range") | ||||
1803 | if $p_id <= 0; # can't easily/reliably test for too big | ||||
1804 | |||||
1805 | # get/create arrayref to hold params | ||||
1806 | my $hash_of_arrays = $sth->{ParamArrays} ||= { }; | ||||
1807 | |||||
1808 | # If the bind has attribs then we rely on the driver conforming to | ||||
1809 | # the DBI spec in that a single bind_param() call with those attribs | ||||
1810 | # makes them 'sticky' and apply to all later execute(@values) calls. | ||||
1811 | # Since we only call bind_param() if we're given attribs then | ||||
1812 | # applications using drivers that don't support bind_param can still | ||||
1813 | # use bind_param_array() so long as they don't pass any attribs. | ||||
1814 | |||||
1815 | $$hash_of_arrays{$p_id} = $value_array; | ||||
1816 | return $sth->bind_param($p_id, undef, $attr) | ||||
1817 | if $attr; | ||||
1818 | 1; | ||||
1819 | } | ||||
1820 | |||||
1821 | sub bind_param_inout_array { | ||||
1822 | my $sth = shift; | ||||
1823 | # XXX not supported so we just call bind_param_array instead | ||||
1824 | # and then return an error | ||||
1825 | my ($p_num, $value_array, $attr) = @_; | ||||
1826 | $sth->bind_param_array($p_num, $value_array, $attr); | ||||
1827 | return $sth->set_err(1, "bind_param_inout_array not supported"); | ||||
1828 | } | ||||
1829 | |||||
1830 | sub bind_columns { | ||||
1831 | 1 | 7µs | my $sth = shift; | ||
1832 | 1 | 34µs | 1 | 15µs | my $fields = $sth->FETCH('NUM_OF_FIELDS') || 0; # spent 15µs making 1 call to DBI::common::FETCH |
1833 | 1 | 6µs | if ($fields <= 0 && !$sth->{Active}) { | ||
1834 | return $sth->set_err(1, "Statement has no result columns to bind" | ||||
1835 | ." (perhaps you need to successfully call execute first)"); | ||||
1836 | } | ||||
1837 | # Backwards compatibility for old-style call with attribute hash | ||||
1838 | # ref as first arg. Skip arg if undef or a hash ref. | ||||
1839 | 1 | 5µs | my $attr; | ||
1840 | 1 | 7µs | $attr = shift if !defined $_[0] or ref($_[0]) eq 'HASH'; | ||
1841 | |||||
1842 | 1 | 4µs | my $idx = 0; | ||
1843 | 1 | 56µs | 1 | 14µs | $sth->bind_col(++$idx, shift, $attr) or return # spent 14µs making 1 call to DBI::st::bind_col |
1844 | while (@_ and $idx < $fields); | ||||
1845 | |||||
1846 | 1 | 5µs | return $sth->set_err(1, "bind_columns called with ".($idx+@_)." values but $fields are needed") | ||
1847 | if @_ or $idx != $fields; | ||||
1848 | |||||
1849 | 1 | 6µs | return 1; | ||
1850 | } | ||||
1851 | |||||
1852 | sub execute_array { | ||||
1853 | my $sth = shift; | ||||
1854 | my ($attr, @array_of_arrays) = @_; | ||||
1855 | my $NUM_OF_PARAMS = $sth->FETCH('NUM_OF_PARAMS'); # may be undef at this point | ||||
1856 | |||||
1857 | # get tuple status array or hash attribute | ||||
1858 | my $tuple_sts = $attr->{ArrayTupleStatus}; | ||||
1859 | return $sth->set_err(1, "ArrayTupleStatus attribute must be an arrayref") | ||||
1860 | if $tuple_sts and ref $tuple_sts ne 'ARRAY'; | ||||
1861 | |||||
1862 | # bind all supplied arrays | ||||
1863 | if (@array_of_arrays) { | ||||
1864 | $sth->{ParamArrays} = { }; # clear out old params | ||||
1865 | return $sth->set_err(1, | ||||
1866 | @array_of_arrays." bind values supplied but $NUM_OF_PARAMS expected") | ||||
1867 | if defined ($NUM_OF_PARAMS) && @array_of_arrays != $NUM_OF_PARAMS; | ||||
1868 | $sth->bind_param_array($_, $array_of_arrays[$_-1]) or return | ||||
1869 | foreach (1..@array_of_arrays); | ||||
1870 | } | ||||
1871 | |||||
1872 | my $fetch_tuple_sub; | ||||
1873 | |||||
1874 | if ($fetch_tuple_sub = $attr->{ArrayTupleFetch}) { # fetch on demand | ||||
1875 | |||||
1876 | return $sth->set_err(1, | ||||
1877 | "Can't use both ArrayTupleFetch and explicit bind values") | ||||
1878 | if @array_of_arrays; # previous bind_param_array calls will simply be ignored | ||||
1879 | |||||
1880 | if (UNIVERSAL::isa($fetch_tuple_sub,'DBI::st')) { | ||||
1881 | my $fetch_sth = $fetch_tuple_sub; | ||||
1882 | return $sth->set_err(1, | ||||
1883 | "ArrayTupleFetch sth is not Active, need to execute() it first") | ||||
1884 | unless $fetch_sth->{Active}; | ||||
1885 | # check column count match to give more friendly message | ||||
1886 | my $NUM_OF_FIELDS = $fetch_sth->{NUM_OF_FIELDS}; | ||||
1887 | return $sth->set_err(1, | ||||
1888 | "$NUM_OF_FIELDS columns from ArrayTupleFetch sth but $NUM_OF_PARAMS expected") | ||||
1889 | if defined($NUM_OF_FIELDS) && defined($NUM_OF_PARAMS) | ||||
1890 | && $NUM_OF_FIELDS != $NUM_OF_PARAMS; | ||||
1891 | $fetch_tuple_sub = sub { $fetch_sth->fetchrow_arrayref }; | ||||
1892 | } | ||||
1893 | elsif (!UNIVERSAL::isa($fetch_tuple_sub,'CODE')) { | ||||
1894 | return $sth->set_err(1, "ArrayTupleFetch '$fetch_tuple_sub' is not a code ref or statement handle"); | ||||
1895 | } | ||||
1896 | |||||
1897 | } | ||||
1898 | else { | ||||
1899 | my $NUM_OF_PARAMS_given = keys %{ $sth->{ParamArrays} || {} }; | ||||
1900 | return $sth->set_err(1, | ||||
1901 | "$NUM_OF_PARAMS_given bind values supplied but $NUM_OF_PARAMS expected") | ||||
1902 | if defined($NUM_OF_PARAMS) && $NUM_OF_PARAMS != $NUM_OF_PARAMS_given; | ||||
1903 | |||||
1904 | # get the length of a bound array | ||||
1905 | my $maxlen; | ||||
1906 | my %hash_of_arrays = %{$sth->{ParamArrays}}; | ||||
1907 | foreach (keys(%hash_of_arrays)) { | ||||
1908 | my $ary = $hash_of_arrays{$_}; | ||||
1909 | next unless ref $ary eq 'ARRAY'; | ||||
1910 | $maxlen = @$ary if !$maxlen || @$ary > $maxlen; | ||||
1911 | } | ||||
1912 | # if there are no arrays then execute scalars once | ||||
1913 | $maxlen = 1 unless defined $maxlen; | ||||
1914 | my @bind_ids = 1..keys(%hash_of_arrays); | ||||
1915 | |||||
1916 | my $tuple_idx = 0; | ||||
1917 | $fetch_tuple_sub = sub { | ||||
1918 | return if $tuple_idx >= $maxlen; | ||||
1919 | my @tuple = map { | ||||
1920 | my $a = $hash_of_arrays{$_}; | ||||
1921 | ref($a) ? $a->[$tuple_idx] : $a | ||||
1922 | } @bind_ids; | ||||
1923 | ++$tuple_idx; | ||||
1924 | return \@tuple; | ||||
1925 | }; | ||||
1926 | } | ||||
1927 | # pass thru the callers scalar or list context | ||||
1928 | return $sth->execute_for_fetch($fetch_tuple_sub, $tuple_sts); | ||||
1929 | } | ||||
1930 | |||||
1931 | sub execute_for_fetch { | ||||
1932 | my ($sth, $fetch_tuple_sub, $tuple_status) = @_; | ||||
1933 | # start with empty status array | ||||
1934 | ($tuple_status) ? @$tuple_status = () : $tuple_status = []; | ||||
1935 | |||||
1936 | my $rc_total = 0; | ||||
1937 | my ($err_count, %errstr_cache); | ||||
1938 | while ( my $tuple = &$fetch_tuple_sub() ) { | ||||
1939 | if ( my $rc = $sth->execute(@$tuple) ) { | ||||
1940 | push @$tuple_status, $rc; | ||||
1941 | $rc_total = ($rc >= 0 && $rc_total >= 0) ? $rc_total + $rc : -1; | ||||
1942 | } | ||||
1943 | else { | ||||
1944 | $err_count++; | ||||
1945 | my $err = $sth->err; | ||||
1946 | push @$tuple_status, [ $err, $errstr_cache{$err} ||= $sth->errstr, $sth->state ]; | ||||
1947 | # XXX drivers implementing execute_for_fetch could opt to "last;" here | ||||
1948 | # if the know the error code means no further executes will work. | ||||
1949 | } | ||||
1950 | } | ||||
1951 | my $tuples = @$tuple_status; | ||||
1952 | return $sth->set_err(1, "executing $tuples generated $err_count errors") | ||||
1953 | if $err_count; | ||||
1954 | $tuples ||= "0E0"; | ||||
1955 | return $tuples unless wantarray; | ||||
1956 | return ($tuples, $rc_total); | ||||
1957 | } | ||||
1958 | |||||
1959 | |||||
1960 | sub fetchall_arrayref { # ALSO IN Driver.xst | ||||
1961 | my ($sth, $slice, $max_rows) = @_; | ||||
1962 | $max_rows = -1 unless defined $max_rows; | ||||
1963 | my $mode = ref($slice) || 'ARRAY'; | ||||
1964 | my @rows; | ||||
1965 | my $row; | ||||
1966 | if ($mode eq 'ARRAY') { | ||||
1967 | # we copy the array here because fetch (currently) always | ||||
1968 | # returns the same array ref. XXX | ||||
1969 | if ($slice && @$slice) { | ||||
1970 | $max_rows = -1 unless defined $max_rows; | ||||
1971 | push @rows, [ @{$row}[ @$slice] ] | ||||
1972 | while($max_rows-- and $row = $sth->fetch); | ||||
1973 | } | ||||
1974 | elsif (defined $max_rows) { | ||||
1975 | $max_rows = -1 unless defined $max_rows; | ||||
1976 | push @rows, [ @$row ] | ||||
1977 | while($max_rows-- and $row = $sth->fetch); | ||||
1978 | } | ||||
1979 | else { | ||||
1980 | push @rows, [ @$row ] while($row = $sth->fetch); | ||||
1981 | } | ||||
1982 | } | ||||
1983 | elsif ($mode eq 'HASH') { | ||||
1984 | $max_rows = -1 unless defined $max_rows; | ||||
1985 | if (keys %$slice) { | ||||
1986 | my @o_keys = keys %$slice; | ||||
1987 | my @i_keys = map { lc } keys %$slice; | ||||
1988 | while ($max_rows-- and $row = $sth->fetchrow_hashref('NAME_lc')) { | ||||
1989 | my %hash; | ||||
1990 | @hash{@o_keys} = @{$row}{@i_keys}; | ||||
1991 | push @rows, \%hash; | ||||
1992 | } | ||||
1993 | } | ||||
1994 | else { | ||||
1995 | # XXX assumes new ref each fetchhash | ||||
1996 | push @rows, $row | ||||
1997 | while ($max_rows-- and $row = $sth->fetchrow_hashref()); | ||||
1998 | } | ||||
1999 | } | ||||
2000 | else { Carp::croak("fetchall_arrayref($mode) invalid") } | ||||
2001 | return \@rows; | ||||
2002 | } | ||||
2003 | |||||
2004 | sub fetchall_hashref { | ||||
2005 | my ($sth, $key_field) = @_; | ||||
2006 | |||||
2007 | my $hash_key_name = $sth->{FetchHashKeyName} || 'NAME'; | ||||
2008 | my $names_hash = $sth->FETCH("${hash_key_name}_hash"); | ||||
2009 | my @key_fields = (ref $key_field) ? @$key_field : ($key_field); | ||||
2010 | my @key_indexes; | ||||
2011 | my $num_of_fields = $sth->FETCH('NUM_OF_FIELDS'); | ||||
2012 | foreach (@key_fields) { | ||||
2013 | my $index = $names_hash->{$_}; # perl index not column | ||||
2014 | $index = $_ - 1 if !defined $index && DBI::looks_like_number($_) && $_>=1 && $_ <= $num_of_fields; | ||||
2015 | return $sth->set_err(1, "Field '$_' does not exist (not one of @{[keys %$names_hash]})") | ||||
2016 | unless defined $index; | ||||
2017 | push @key_indexes, $index; | ||||
2018 | } | ||||
2019 | my $rows = {}; | ||||
2020 | my $NAME = $sth->FETCH($hash_key_name); | ||||
2021 | my @row = (undef) x $num_of_fields; | ||||
2022 | $sth->bind_columns(\(@row)); | ||||
2023 | while ($sth->fetch) { | ||||
2024 | my $ref = $rows; | ||||
2025 | $ref = $ref->{$row[$_]} ||= {} for @key_indexes; | ||||
2026 | @{$ref}{@$NAME} = @row; | ||||
2027 | } | ||||
2028 | return $rows; | ||||
2029 | } | ||||
2030 | |||||
2031 | 1 | 6µs | *dump_results = \&DBI::dump_results; | ||
2032 | |||||
2033 | sub blob_copy_to_file { # returns length or undef on error | ||||
2034 | my($self, $field, $filename_or_handleref, $blocksize) = @_; | ||||
2035 | my $fh = $filename_or_handleref; | ||||
2036 | my($len, $buf) = (0, ""); | ||||
2037 | $blocksize ||= 512; # not too ambitious | ||||
2038 | local(*FH); | ||||
2039 | unless(ref $fh) { | ||||
2040 | open(FH, ">$fh") || return undef; | ||||
2041 | $fh = \*FH; | ||||
2042 | } | ||||
2043 | while(defined($self->blob_read($field, $len, $blocksize, \$buf))) { | ||||
2044 | print $fh $buf; | ||||
2045 | $len += length $buf; | ||||
2046 | } | ||||
2047 | close(FH); | ||||
2048 | $len; | ||||
2049 | } | ||||
2050 | |||||
2051 | sub more_results { | ||||
2052 | shift->{syb_more_results}; # handy grandfathering | ||||
2053 | } | ||||
2054 | |||||
2055 | } | ||||
2056 | |||||
2057 | 1 | 9µs | unless ($DBI::PurePerl) { # See install_driver | ||
2058 | 2 | 14µs | { @DBD::_mem::dr::ISA = qw(DBD::_mem::common); } | ||
2059 | 2 | 13µs | { @DBD::_mem::db::ISA = qw(DBD::_mem::common); } | ||
2060 | 2 | 14µs | { @DBD::_mem::st::ISA = qw(DBD::_mem::common); } | ||
2061 | # DBD::_mem::common::DESTROY is implemented in DBI.xs | ||||
2062 | } | ||||
2063 | |||||
2064 | 1 | 296µs | 1; | ||
2065 | __END__ | ||||
2066 | |||||
2067 | =head1 DESCRIPTION | ||||
2068 | |||||
2069 | The DBI is a database access module for the Perl programming language. It defines | ||||
2070 | a set of methods, variables, and conventions that provide a consistent | ||||
2071 | database interface, independent of the actual database being used. | ||||
2072 | |||||
2073 | It is important to remember that the DBI is just an interface. | ||||
2074 | The DBI is a layer | ||||
2075 | of "glue" between an application and one or more database I<driver> | ||||
2076 | modules. It is the driver modules which do most of the real work. The DBI | ||||
2077 | provides a standard interface and framework for the drivers to operate | ||||
2078 | within. | ||||
2079 | |||||
2080 | |||||
2081 | =head2 Architecture of a DBI Application | ||||
2082 | |||||
2083 | |<- Scope of DBI ->| | ||||
2084 | .-. .--------------. .-------------. | ||||
2085 | .-------. | |---| XYZ Driver |---| XYZ Engine | | ||||
2086 | | Perl | | | `--------------' `-------------' | ||||
2087 | | script| |A| |D| .--------------. .-------------. | ||||
2088 | | using |--|P|--|B|---|Oracle Driver |---|Oracle Engine| | ||||
2089 | | DBI | |I| |I| `--------------' `-------------' | ||||
2090 | | API | | |... | ||||
2091 | |methods| | |... Other drivers | ||||
2092 | `-------' | |... | ||||
2093 | `-' | ||||
2094 | |||||
2095 | The API, or Application Programming Interface, defines the | ||||
2096 | call interface and variables for Perl scripts to use. The API | ||||
2097 | is implemented by the Perl DBI extension. | ||||
2098 | |||||
2099 | The DBI "dispatches" the method calls to the appropriate driver for | ||||
2100 | actual execution. The DBI is also responsible for the dynamic loading | ||||
2101 | of drivers, error checking and handling, providing default | ||||
2102 | implementations for methods, and many other non-database specific duties. | ||||
2103 | |||||
2104 | Each driver | ||||
2105 | contains implementations of the DBI methods using the | ||||
2106 | private interface functions of the corresponding database engine. Only authors | ||||
2107 | of sophisticated/multi-database applications or generic library | ||||
2108 | functions need be concerned with drivers. | ||||
2109 | |||||
2110 | =head2 Notation and Conventions | ||||
2111 | |||||
2112 | The following conventions are used in this document: | ||||
2113 | |||||
2114 | $dbh Database handle object | ||||
2115 | $sth Statement handle object | ||||
2116 | $drh Driver handle object (rarely seen or used in applications) | ||||
2117 | $h Any of the handle types above ($dbh, $sth, or $drh) | ||||
2118 | $rc General Return Code (boolean: true=ok, false=error) | ||||
2119 | $rv General Return Value (typically an integer) | ||||
2120 | @ary List of values returned from the database, typically a row of data | ||||
2121 | $rows Number of rows processed (if available, else -1) | ||||
2122 | $fh A filehandle | ||||
2123 | undef NULL values are represented by undefined values in Perl | ||||
2124 | \%attr Reference to a hash of attribute values passed to methods | ||||
2125 | |||||
2126 | Note that Perl will automatically destroy database and statement handle objects | ||||
2127 | if all references to them are deleted. | ||||
2128 | |||||
2129 | |||||
2130 | =head2 Outline Usage | ||||
2131 | |||||
2132 | To use DBI, | ||||
2133 | first you need to load the DBI module: | ||||
2134 | |||||
2135 | use DBI; | ||||
2136 | use strict; | ||||
2137 | |||||
2138 | (The C<use strict;> isn't required but is strongly recommended.) | ||||
2139 | |||||
2140 | Then you need to L</connect> to your data source and get a I<handle> for that | ||||
2141 | connection: | ||||
2142 | |||||
2143 | $dbh = DBI->connect($dsn, $user, $password, | ||||
2144 | { RaiseError => 1, AutoCommit => 0 }); | ||||
2145 | |||||
2146 | Since connecting can be expensive, you generally just connect at the | ||||
2147 | start of your program and disconnect at the end. | ||||
2148 | |||||
2149 | Explicitly defining the required C<AutoCommit> behaviour is strongly | ||||
2150 | recommended and may become mandatory in a later version. This | ||||
2151 | determines whether changes are automatically committed to the | ||||
2152 | database when executed, or need to be explicitly committed later. | ||||
2153 | |||||
2154 | The DBI allows an application to "prepare" statements for later | ||||
2155 | execution. A prepared statement is identified by a statement handle | ||||
2156 | held in a Perl variable. | ||||
2157 | We'll call the Perl variable C<$sth> in our examples. | ||||
2158 | |||||
2159 | The typical method call sequence for a C<SELECT> statement is: | ||||
2160 | |||||
2161 | prepare, | ||||
2162 | execute, fetch, fetch, ... | ||||
2163 | execute, fetch, fetch, ... | ||||
2164 | execute, fetch, fetch, ... | ||||
2165 | |||||
2166 | for example: | ||||
2167 | |||||
2168 | $sth = $dbh->prepare("SELECT foo, bar FROM table WHERE baz=?"); | ||||
2169 | |||||
2170 | $sth->execute( $baz ); | ||||
2171 | |||||
2172 | while ( @row = $sth->fetchrow_array ) { | ||||
2173 | print "@row\n"; | ||||
2174 | } | ||||
2175 | |||||
2176 | The typical method call sequence for a I<non>-C<SELECT> statement is: | ||||
2177 | |||||
2178 | prepare, | ||||
2179 | execute, | ||||
2180 | execute, | ||||
2181 | execute. | ||||
2182 | |||||
2183 | for example: | ||||
2184 | |||||
2185 | $sth = $dbh->prepare("INSERT INTO table(foo,bar,baz) VALUES (?,?,?)"); | ||||
2186 | |||||
2187 | while(<CSV>) { | ||||
2188 | chomp; | ||||
2189 | my ($foo,$bar,$baz) = split /,/; | ||||
2190 | $sth->execute( $foo, $bar, $baz ); | ||||
2191 | } | ||||
2192 | |||||
2193 | The C<do()> method can be used for non repeated I<non>-C<SELECT> statement | ||||
2194 | (or with drivers that don't support placeholders): | ||||
2195 | |||||
2196 | $rows_affected = $dbh->do("UPDATE your_table SET foo = foo + 1"); | ||||
2197 | |||||
2198 | To commit your changes to the database (when L</AutoCommit> is off): | ||||
2199 | |||||
2200 | $dbh->commit; # or call $dbh->rollback; to undo changes | ||||
2201 | |||||
2202 | Finally, when you have finished working with the data source, you should | ||||
2203 | L</disconnect> from it: | ||||
2204 | |||||
2205 | $dbh->disconnect; | ||||
2206 | |||||
2207 | |||||
2208 | =head2 General Interface Rules & Caveats | ||||
2209 | |||||
2210 | The DBI does not have a concept of a "current session". Every session | ||||
2211 | has a handle object (i.e., a C<$dbh>) returned from the C<connect> method. | ||||
2212 | That handle object is used to invoke database related methods. | ||||
2213 | |||||
2214 | Most data is returned to the Perl script as strings. (Null values are | ||||
2215 | returned as C<undef>.) This allows arbitrary precision numeric data to be | ||||
2216 | handled without loss of accuracy. Beware that Perl may not preserve | ||||
2217 | the same accuracy when the string is used as a number. | ||||
2218 | |||||
2219 | Dates and times are returned as character strings in the current | ||||
2220 | default format of the corresponding database engine. Time zone effects | ||||
2221 | are database/driver dependent. | ||||
2222 | |||||
2223 | Perl supports binary data in Perl strings, and the DBI will pass binary | ||||
2224 | data to and from the driver without change. It is up to the driver | ||||
2225 | implementors to decide how they wish to handle such binary data. | ||||
2226 | |||||
2227 | Perl supports two kinds of strings: unicode (utf8 internally) and non-unicode | ||||
2228 | (defaults to iso-8859-1 if forced to assume an encoding). Drivers should | ||||
2229 | accept both kinds of strings and, if required, convert them to the character | ||||
2230 | set of the database being used. Similarly, when fetching from the database | ||||
2231 | character data that isn't iso-8859-1 the driver should convert it into utf8. | ||||
2232 | |||||
2233 | Multiple SQL statements may not be combined in a single statement | ||||
2234 | handle (C<$sth>), although some databases and drivers do support this | ||||
2235 | (notably Sybase and SQL Server). | ||||
2236 | |||||
2237 | Non-sequential record reads are not supported in this version of the DBI. | ||||
2238 | In other words, records can only be fetched in the order that the | ||||
2239 | database returned them, and once fetched they are forgotten. | ||||
2240 | |||||
2241 | Positioned updates and deletes are not directly supported by the DBI. | ||||
2242 | See the description of the C<CursorName> attribute for an alternative. | ||||
2243 | |||||
2244 | Individual driver implementors are free to provide any private | ||||
2245 | functions and/or handle attributes that they feel are useful. | ||||
2246 | Private driver functions can be invoked using the DBI C<func()> method. | ||||
2247 | Private driver attributes are accessed just like standard attributes. | ||||
2248 | |||||
2249 | Many methods have an optional C<\%attr> parameter which can be used to | ||||
2250 | pass information to the driver implementing the method. Except where | ||||
2251 | specifically documented, the C<\%attr> parameter can only be used to pass | ||||
2252 | driver specific hints. In general, you can ignore C<\%attr> parameters | ||||
2253 | or pass it as C<undef>. | ||||
2254 | |||||
2255 | |||||
2256 | =head2 Naming Conventions and Name Space | ||||
2257 | |||||
2258 | The DBI package and all packages below it (C<DBI::*>) are reserved for | ||||
2259 | use by the DBI. Extensions and related modules use the C<DBIx::> | ||||
2260 | namespace (see L<http://www.perl.com/CPAN/modules/by-module/DBIx/>). | ||||
2261 | Package names beginning with C<DBD::> are reserved for use | ||||
2262 | by DBI database drivers. All environment variables used by the DBI | ||||
2263 | or by individual DBDs begin with "C<DBI_>" or "C<DBD_>". | ||||
2264 | |||||
2265 | The letter case used for attribute names is significant and plays an | ||||
2266 | important part in the portability of DBI scripts. The case of the | ||||
2267 | attribute name is used to signify who defined the meaning of that name | ||||
2268 | and its values. | ||||
2269 | |||||
2270 | Case of name Has a meaning defined by | ||||
2271 | ------------ ------------------------ | ||||
2272 | UPPER_CASE Standards, e.g., X/Open, ISO SQL92 etc (portable) | ||||
2273 | MixedCase DBI API (portable), underscores are not used. | ||||
2274 | lower_case Driver or database engine specific (non-portable) | ||||
2275 | |||||
2276 | It is of the utmost importance that Driver developers only use | ||||
2277 | lowercase attribute names when defining private attributes. Private | ||||
2278 | attribute names must be prefixed with the driver name or suitable | ||||
2279 | abbreviation (e.g., "C<ora_>" for Oracle, "C<ing_>" for Ingres, etc). | ||||
2280 | |||||
2281 | |||||
2282 | =head2 SQL - A Query Language | ||||
2283 | |||||
2284 | Most DBI drivers require applications to use a dialect of SQL | ||||
2285 | (Structured Query Language) to interact with the database engine. | ||||
2286 | The L</"Standards Reference Information"> section provides links | ||||
2287 | to useful information about SQL. | ||||
2288 | |||||
2289 | The DBI itself does not mandate or require any particular language to | ||||
2290 | be used; it is language independent. In ODBC terms, the DBI is in | ||||
2291 | "pass-thru" mode, although individual drivers might not be. The only requirement | ||||
2292 | is that queries and other statements must be expressed as a single | ||||
2293 | string of characters passed as the first argument to the L</prepare> or | ||||
2294 | L</do> methods. | ||||
2295 | |||||
2296 | For an interesting diversion on the I<real> history of RDBMS and SQL, | ||||
2297 | from the people who made it happen, see: | ||||
2298 | |||||
2299 | http://ftp.digital.com/pub/DEC/SRC/technical-notes/SRC-1997-018-html/sqlr95.html | ||||
2300 | |||||
2301 | Follow the "Full Contents" then "Intergalactic dataspeak" links for the | ||||
2302 | SQL history. | ||||
2303 | |||||
2304 | =head2 Placeholders and Bind Values | ||||
2305 | |||||
2306 | Some drivers support placeholders and bind values. | ||||
2307 | I<Placeholders>, also called parameter markers, are used to indicate | ||||
2308 | values in a database statement that will be supplied later, | ||||
2309 | before the prepared statement is executed. For example, an application | ||||
2310 | might use the following to insert a row of data into the SALES table: | ||||
2311 | |||||
2312 | INSERT INTO sales (product_code, qty, price) VALUES (?, ?, ?) | ||||
2313 | |||||
2314 | or the following, to select the description for a product: | ||||
2315 | |||||
2316 | SELECT description FROM products WHERE product_code = ? | ||||
2317 | |||||
2318 | The C<?> characters are the placeholders. The association of actual | ||||
2319 | values with placeholders is known as I<binding>, and the values are | ||||
2320 | referred to as I<bind values>. | ||||
2321 | |||||
2322 | Note that the C<?> is not enclosed in quotation marks, even when the | ||||
2323 | placeholder represents a string. Some drivers also allow placeholders | ||||
2324 | like C<:>I<name> and C<:>I<n> (e.g., C<:1>, C<:2>, and so on) | ||||
2325 | in addition to C<?>, but their use is not portable. | ||||
2326 | |||||
2327 | With most drivers, placeholders can't be used for any element of a | ||||
2328 | statement that would prevent the database server from validating the | ||||
2329 | statement and creating a query execution plan for it. For example: | ||||
2330 | |||||
2331 | "SELECT name, age FROM ?" # wrong (will probably fail) | ||||
2332 | "SELECT name, ? FROM people" # wrong (but may not 'fail') | ||||
2333 | |||||
2334 | Also, placeholders can only represent single scalar values. | ||||
2335 | For example, the following | ||||
2336 | statement won't work as expected for more than one value: | ||||
2337 | |||||
2338 | "SELECT name, age FROM people WHERE name IN (?)" # wrong | ||||
2339 | "SELECT name, age FROM people WHERE name IN (?,?)" # two names | ||||
2340 | |||||
2341 | When using placeholders with the SQL C<LIKE> qualifier, you must | ||||
2342 | remember that the placeholder substitutes for the whole string. | ||||
2343 | So you should use "C<... LIKE ? ...>" and include any wildcard | ||||
2344 | characters in the value that you bind to the placeholder. | ||||
2345 | |||||
2346 | B<NULL Values> | ||||
2347 | |||||
2348 | Undefined values, or C<undef>, are used to indicate NULL values. | ||||
2349 | You can insert and update columns with a NULL value as you would a | ||||
2350 | non-NULL value. These examples insert and update the column | ||||
2351 | C<age> with a NULL value: | ||||
2352 | |||||
2353 | $sth = $dbh->prepare(qq{ | ||||
2354 | INSERT INTO people (fullname, age) VALUES (?, ?) | ||||
2355 | }); | ||||
2356 | $sth->execute("Joe Bloggs", undef); | ||||
2357 | |||||
2358 | $sth = $dbh->prepare(qq{ | ||||
2359 | UPDATE people SET age = ? WHERE fullname = ? | ||||
2360 | }); | ||||
2361 | $sth->execute(undef, "Joe Bloggs"); | ||||
2362 | |||||
2363 | However, care must be taken when trying to use NULL values in a | ||||
2364 | C<WHERE> clause. Consider: | ||||
2365 | |||||
2366 | SELECT fullname FROM people WHERE age = ? | ||||
2367 | |||||
2368 | Binding an C<undef> (NULL) to the placeholder will I<not> select rows | ||||
2369 | which have a NULL C<age>! At least for database engines that | ||||
2370 | conform to the SQL standard. Refer to the SQL manual for your database | ||||
2371 | engine or any SQL book for the reasons for this. To explicitly select | ||||
2372 | NULLs you have to say "C<WHERE age IS NULL>". | ||||
2373 | |||||
2374 | A common issue is to have a code fragment handle a value that could be | ||||
2375 | either C<defined> or C<undef> (non-NULL or NULL) at runtime. | ||||
2376 | A simple technique is to prepare the appropriate statement as needed, | ||||
2377 | and substitute the placeholder for non-NULL cases: | ||||
2378 | |||||
2379 | $sql_clause = defined $age? "age = ?" : "age IS NULL"; | ||||
2380 | $sth = $dbh->prepare(qq{ | ||||
2381 | SELECT fullname FROM people WHERE $sql_clause | ||||
2382 | }); | ||||
2383 | $sth->execute(defined $age ? $age : ()); | ||||
2384 | |||||
2385 | The following technique illustrates qualifying a C<WHERE> clause with | ||||
2386 | several columns, whose associated values (C<defined> or C<undef>) are | ||||
2387 | in a hash %h: | ||||
2388 | |||||
2389 | for my $col ("age", "phone", "email") { | ||||
2390 | if (defined $h{$col}) { | ||||
2391 | push @sql_qual, "$col = ?"; | ||||
2392 | push @sql_bind, $h{$col}; | ||||
2393 | } | ||||
2394 | else { | ||||
2395 | push @sql_qual, "$col IS NULL"; | ||||
2396 | } | ||||
2397 | } | ||||
2398 | $sql_clause = join(" AND ", @sql_qual); | ||||
2399 | $sth = $dbh->prepare(qq{ | ||||
2400 | SELECT fullname FROM people WHERE $sql_clause | ||||
2401 | }); | ||||
2402 | $sth->execute(@sql_bind); | ||||
2403 | |||||
2404 | The techniques above call prepare for the SQL statement with each call to | ||||
2405 | execute. Because calls to prepare() can be expensive, performance | ||||
2406 | can suffer when an application iterates many times over statements | ||||
2407 | like the above. | ||||
2408 | |||||
2409 | A better solution is a single C<WHERE> clause that supports both | ||||
2410 | NULL and non-NULL comparisons. Its SQL statement would need to be | ||||
2411 | prepared only once for all cases, thus improving performance. | ||||
2412 | Several examples of C<WHERE> clauses that support this are presented | ||||
2413 | below. But each example lacks portability, robustness, or simplicity. | ||||
2414 | Whether an example is supported on your database engine depends on | ||||
2415 | what SQL extensions it provides, and where it supports the C<?> | ||||
2416 | placeholder in a statement. | ||||
2417 | |||||
2418 | 0) age = ? | ||||
2419 | 1) NVL(age, xx) = NVL(?, xx) | ||||
2420 | 2) ISNULL(age, xx) = ISNULL(?, xx) | ||||
2421 | 3) DECODE(age, ?, 1, 0) = 1 | ||||
2422 | 4) age = ? OR (age IS NULL AND ? IS NULL) | ||||
2423 | 5) age = ? OR (age IS NULL AND SP_ISNULL(?) = 1) | ||||
2424 | 6) age = ? OR (age IS NULL AND ? = 1) | ||||
2425 | |||||
2426 | Statements formed with the above C<WHERE> clauses require execute | ||||
2427 | statements as follows. The arguments are required, whether their | ||||
2428 | values are C<defined> or C<undef>. | ||||
2429 | |||||
2430 | 0,1,2,3) $sth->execute($age); | ||||
2431 | 4,5) $sth->execute($age, $age); | ||||
2432 | 6) $sth->execute($age, defined($age) ? 0 : 1); | ||||
2433 | |||||
2434 | Example 0 should not work (as mentioned earlier), but may work on | ||||
2435 | a few database engines anyway (e.g. Sybase). Example 0 is part | ||||
2436 | of examples 4, 5, and 6, so if example 0 works, these other | ||||
2437 | examples may work, even if the engine does not properly support | ||||
2438 | the right hand side of the C<OR> expression. | ||||
2439 | |||||
2440 | Examples 1 and 2 are not robust: they require that you provide a | ||||
2441 | valid column value xx (e.g. '~') which is not present in any row. | ||||
2442 | That means you must have some notion of what data won't be stored | ||||
2443 | in the column, and expect clients to adhere to that. | ||||
2444 | |||||
2445 | Example 5 requires that you provide a stored procedure (SP_ISNULL | ||||
2446 | in this example) that acts as a function: it checks whether a value | ||||
2447 | is null, and returns 1 if it is, or 0 if not. | ||||
2448 | |||||
2449 | Example 6, the least simple, is probably the most portable, i.e., it | ||||
2450 | should work with with most, if not all, database engines. | ||||
2451 | |||||
2452 | Here is a table that indicates which examples above are known to | ||||
2453 | work on various database engines: | ||||
2454 | |||||
2455 | -----Examples------ | ||||
2456 | 0 1 2 3 4 5 6 | ||||
2457 | - - - - - - - | ||||
2458 | Oracle 9 N Y N Y Y ? Y | ||||
2459 | Informix IDS 9 N N N Y N Y Y | ||||
2460 | MS SQL N N Y N Y ? Y | ||||
2461 | Sybase Y N N N N N Y | ||||
2462 | AnyData,DBM,CSV Y N N N Y Y* Y | ||||
2463 | |||||
2464 | * Works only because Example 0 works. | ||||
2465 | |||||
2466 | DBI provides a sample perl script that will test the examples above | ||||
2467 | on your database engine and tell you which ones work. It is located | ||||
2468 | in the F<ex/> subdirectory of the DBI source distribution, or here: | ||||
2469 | L<http://svn.perl.org/modules/dbi/trunk/ex/perl_dbi_nulls_test.pl> | ||||
2470 | Please use the script to help us fill-in and maintain this table. | ||||
2471 | |||||
2472 | B<Performance> | ||||
2473 | |||||
2474 | Without using placeholders, the insert statement shown previously would have to | ||||
2475 | contain the literal values to be inserted and would have to be | ||||
2476 | re-prepared and re-executed for each row. With placeholders, the insert | ||||
2477 | statement only needs to be prepared once. The bind values for each row | ||||
2478 | can be given to the C<execute> method each time it's called. By avoiding | ||||
2479 | the need to re-prepare the statement for each row, the application | ||||
2480 | typically runs many times faster. Here's an example: | ||||
2481 | |||||
2482 | my $sth = $dbh->prepare(q{ | ||||
2483 | INSERT INTO sales (product_code, qty, price) VALUES (?, ?, ?) | ||||
2484 | }) or die $dbh->errstr; | ||||
2485 | while (<>) { | ||||
2486 | chomp; | ||||
2487 | my ($product_code, $qty, $price) = split /,/; | ||||
2488 | $sth->execute($product_code, $qty, $price) or die $dbh->errstr; | ||||
2489 | } | ||||
2490 | $dbh->commit or die $dbh->errstr; | ||||
2491 | |||||
2492 | See L</execute> and L</bind_param> for more details. | ||||
2493 | |||||
2494 | The C<q{...}> style quoting used in this example avoids clashing with | ||||
2495 | quotes that may be used in the SQL statement. Use the double-quote like | ||||
2496 | C<qq{...}> operator if you want to interpolate variables into the string. | ||||
2497 | See L<perlop/"Quote and Quote-like Operators"> for more details. | ||||
2498 | |||||
2499 | See also the L</bind_columns> method, which is used to associate Perl | ||||
2500 | variables with the output columns of a C<SELECT> statement. | ||||
2501 | |||||
2502 | =head1 THE DBI PACKAGE AND CLASS | ||||
2503 | |||||
2504 | In this section, we cover the DBI class methods, utility functions, | ||||
2505 | and the dynamic attributes associated with generic DBI handles. | ||||
2506 | |||||
2507 | =head2 DBI Constants | ||||
2508 | |||||
2509 | Constants representing the values of the SQL standard types can be | ||||
2510 | imported individually by name, or all together by importing the | ||||
2511 | special C<:sql_types> tag. | ||||
2512 | |||||
2513 | The names and values of all the defined SQL standard types can be | ||||
2514 | produced like this: | ||||
2515 | |||||
2516 | foreach (@{ $DBI::EXPORT_TAGS{sql_types} }) { | ||||
2517 | printf "%s=%d\n", $_, &{"DBI::$_"}; | ||||
2518 | } | ||||
2519 | |||||
2520 | These constants are defined by SQL/CLI, ODBC or both. | ||||
2521 | C<SQL_BIGINT> is (currently) omitted, because SQL/CLI and ODBC provide | ||||
2522 | conflicting codes. | ||||
2523 | |||||
2524 | See the L</type_info>, L</type_info_all>, and L</bind_param> methods | ||||
2525 | for possible uses. | ||||
2526 | |||||
2527 | Note that just because the DBI defines a named constant for a given | ||||
2528 | data type doesn't mean that drivers will support that data type. | ||||
2529 | |||||
2530 | |||||
2531 | =head2 DBI Class Methods | ||||
2532 | |||||
2533 | The following methods are provided by the DBI class: | ||||
2534 | |||||
2535 | =over 4 | ||||
2536 | |||||
2537 | =item C<parse_dsn> | ||||
2538 | |||||
2539 | ($scheme, $driver, $attr_string, $attr_hash, $driver_dsn) = DBI->parse_dsn($dsn) | ||||
2540 | or die "Can't parse DBI DSN '$dsn'"; | ||||
2541 | |||||
2542 | Breaks apart a DBI Data Source Name (DSN) and returns the individual | ||||
2543 | parts. If $dsn doesn't contain a valid DSN then parse_dsn() returns | ||||
2544 | an empty list. | ||||
2545 | |||||
2546 | $scheme is the first part of the DSN and is currently always 'dbi'. | ||||
2547 | $driver is the driver name, possibly defaulted to $ENV{DBI_DRIVER}, | ||||
2548 | and may be undefined. $attr_string is the contents of the optional attribute | ||||
2549 | string, which may be undefined. If $attr_string is not empty then $attr_hash | ||||
2550 | is a reference to a hash containing the parsed attribute names and values. | ||||
2551 | $driver_dsn is the last part of the DBI DSN string. For example: | ||||
2552 | |||||
2553 | ($scheme, $driver, $attr_string, $attr_hash, $driver_dsn) | ||||
2554 | = DBI->parse_dsn("DBI:MyDriver(RaiseError=>1):db=test;port=42"); | ||||
2555 | $scheme = 'dbi'; | ||||
2556 | $driver = 'MyDriver'; | ||||
2557 | $attr_string = 'RaiseError=>1'; | ||||
2558 | $attr_hash = { 'RaiseError' => '1' }; | ||||
2559 | $driver_dsn = 'db=test;port=42'; | ||||
2560 | |||||
2561 | The parse_dsn() method was added in DBI 1.43. | ||||
2562 | |||||
2563 | =item C<connect> | ||||
2564 | |||||
2565 | $dbh = DBI->connect($data_source, $username, $password) | ||||
2566 | or die $DBI::errstr; | ||||
2567 | $dbh = DBI->connect($data_source, $username, $password, \%attr) | ||||
2568 | or die $DBI::errstr; | ||||
2569 | |||||
2570 | Establishes a database connection, or session, to the requested C<$data_source>. | ||||
2571 | Returns a database handle object if the connection succeeds. Use | ||||
2572 | C<$dbh-E<gt>disconnect> to terminate the connection. | ||||
2573 | |||||
2574 | If the connect fails (see below), it returns C<undef> and sets both C<$DBI::err> | ||||
2575 | and C<$DBI::errstr>. (It does I<not> explicitly set C<$!>.) You should generally | ||||
2576 | test the return status of C<connect> and C<print $DBI::errstr> if it has failed. | ||||
2577 | |||||
2578 | Multiple simultaneous connections to multiple databases through multiple | ||||
2579 | drivers can be made via the DBI. Simply make one C<connect> call for each | ||||
2580 | database and keep a copy of each returned database handle. | ||||
2581 | |||||
2582 | The C<$data_source> value must begin with "C<dbi:>I<driver_name>C<:>". | ||||
2583 | The I<driver_name> specifies the driver that will be used to make the | ||||
2584 | connection. (Letter case is significant.) | ||||
2585 | |||||
2586 | As a convenience, if the C<$data_source> parameter is undefined or empty, | ||||
2587 | the DBI will substitute the value of the environment variable C<DBI_DSN>. | ||||
2588 | If just the I<driver_name> part is empty (i.e., the C<$data_source> | ||||
2589 | prefix is "C<dbi::>"), the environment variable C<DBI_DRIVER> is | ||||
2590 | used. If neither variable is set, then C<connect> dies. | ||||
2591 | |||||
2592 | Examples of C<$data_source> values are: | ||||
2593 | |||||
2594 | dbi:DriverName:database_name | ||||
2595 | dbi:DriverName:database_name@hostname:port | ||||
2596 | dbi:DriverName:database=database_name;host=hostname;port=port | ||||
2597 | |||||
2598 | There is I<no standard> for the text following the driver name. Each | ||||
2599 | driver is free to use whatever syntax it wants. The only requirement the | ||||
2600 | DBI makes is that all the information is supplied in a single string. | ||||
2601 | You must consult the documentation for the drivers you are using for a | ||||
2602 | description of the syntax they require. | ||||
2603 | |||||
2604 | It is recommended that drivers support the ODBC style, shown in the | ||||
2605 | last example above. It is also recommended that that they support the | ||||
2606 | three common names 'C<host>', 'C<port>', and 'C<database>' (plus 'C<db>' | ||||
2607 | as an alias for C<database>). This simplifies automatic construction | ||||
2608 | of basic DSNs: C<"dbi:$driver:database=$db;host=$host;port=$port">. | ||||
2609 | Drivers should aim to 'do something reasonable' when given a DSN | ||||
2610 | in this form, but if any part is meaningless for that driver (such | ||||
2611 | as 'port' for Informix) it should generate an error if that part | ||||
2612 | is not empty. | ||||
2613 | |||||
2614 | If the environment variable C<DBI_AUTOPROXY> is defined (and the | ||||
2615 | driver in C<$data_source> is not "C<Proxy>") then the connect request | ||||
2616 | will automatically be changed to: | ||||
2617 | |||||
2618 | $ENV{DBI_AUTOPROXY};dsn=$data_source | ||||
2619 | |||||
2620 | C<DBI_AUTOPROXY> is typically set as "C<dbi:Proxy:hostname=...;port=...>". | ||||
2621 | If $ENV{DBI_AUTOPROXY} doesn't begin with 'C<dbi:>' then "dbi:Proxy:" | ||||
2622 | will be prepended to it first. See the DBD::Proxy documentation | ||||
2623 | for more details. | ||||
2624 | |||||
2625 | If C<$username> or C<$password> are undefined (rather than just empty), | ||||
2626 | then the DBI will substitute the values of the C<DBI_USER> and C<DBI_PASS> | ||||
2627 | environment variables, respectively. The DBI will warn if the | ||||
2628 | environment variables are not defined. However, the everyday use | ||||
2629 | of these environment variables is not recommended for security | ||||
2630 | reasons. The mechanism is primarily intended to simplify testing. | ||||
2631 | See below for alternative way to specify the username and password. | ||||
2632 | |||||
2633 | C<DBI-E<gt>connect> automatically installs the driver if it has not been | ||||
2634 | installed yet. Driver installation either returns a valid driver | ||||
2635 | handle, or it I<dies> with an error message that includes the string | ||||
2636 | "C<install_driver>" and the underlying problem. So C<DBI-E<gt>connect> | ||||
2637 | will die | ||||
2638 | on a driver installation failure and will only return C<undef> on a | ||||
2639 | connect failure, in which case C<$DBI::errstr> will hold the error message. | ||||
2640 | Use C<eval { ... }> if you need to catch the "C<install_driver>" error. | ||||
2641 | |||||
2642 | The C<$data_source> argument (with the "C<dbi:...:>" prefix removed) and the | ||||
2643 | C<$username> and C<$password> arguments are then passed to the driver for | ||||
2644 | processing. The DBI does not define any interpretation for the | ||||
2645 | contents of these fields. The driver is free to interpret the | ||||
2646 | C<$data_source>, C<$username>, and C<$password> fields in any way, and supply | ||||
2647 | whatever defaults are appropriate for the engine being accessed. | ||||
2648 | (Oracle, for example, uses the ORACLE_SID and TWO_TASK environment | ||||
2649 | variables if no C<$data_source> is specified.) | ||||
2650 | |||||
2651 | The C<AutoCommit> and C<PrintError> attributes for each connection | ||||
2652 | default to "on". (See L</AutoCommit> and L</PrintError> for more information.) | ||||
2653 | However, it is strongly recommended that you explicitly define C<AutoCommit> | ||||
2654 | rather than rely on the default. The C<PrintWarn> attribute defaults to | ||||
2655 | on if $^W is true, i.e., perl is running with warnings enabled. | ||||
2656 | |||||
2657 | The C<\%attr> parameter can be used to alter the default settings of | ||||
2658 | C<PrintError>, C<RaiseError>, C<AutoCommit>, and other attributes. For example: | ||||
2659 | |||||
2660 | $dbh = DBI->connect($data_source, $user, $pass, { | ||||
2661 | PrintError => 0, | ||||
2662 | AutoCommit => 0 | ||||
2663 | }); | ||||
2664 | |||||
2665 | The username and password can also be specified using the attributes | ||||
2666 | C<Username> and C<Password>, in which case they take precedence | ||||
2667 | over the C<$username> and C<$password> parameters. | ||||
2668 | |||||
2669 | You can also define connection attribute values within the C<$data_source> | ||||
2670 | parameter. For example: | ||||
2671 | |||||
2672 | dbi:DriverName(PrintWarn=>1,PrintError=>0,Taint=>1):... | ||||
2673 | |||||
2674 | Individual attributes values specified in this way take precedence over | ||||
2675 | any conflicting values specified via the C<\%attr> parameter to C<connect>. | ||||
2676 | |||||
2677 | The C<dbi_connect_method> attribute can be used to specify which driver | ||||
2678 | method should be called to establish the connection. The only useful | ||||
2679 | values are 'connect', 'connect_cached', or some specialized case like | ||||
2680 | 'Apache::DBI::connect' (which is automatically the default when running | ||||
2681 | within Apache). | ||||
2682 | |||||
2683 | Where possible, each session (C<$dbh>) is independent from the transactions | ||||
2684 | in other sessions. This is useful when you need to hold cursors open | ||||
2685 | across transactions--for example, if you use one session for your long lifespan | ||||
2686 | cursors (typically read-only) and another for your short update | ||||
2687 | transactions. | ||||
2688 | |||||
2689 | For compatibility with old DBI scripts, the driver can be specified by | ||||
2690 | passing its name as the fourth argument to C<connect> (instead of C<\%attr>): | ||||
2691 | |||||
2692 | $dbh = DBI->connect($data_source, $user, $pass, $driver); | ||||
2693 | |||||
2694 | In this "old-style" form of C<connect>, the C<$data_source> should not start | ||||
2695 | with "C<dbi:driver_name:>". (If it does, the embedded driver_name | ||||
2696 | will be ignored). Also note that in this older form of C<connect>, | ||||
2697 | the C<$dbh-E<gt>{AutoCommit}> attribute is I<undefined>, the | ||||
2698 | C<$dbh-E<gt>{PrintError}> attribute is off, and the old C<DBI_DBNAME> | ||||
2699 | environment variable is | ||||
2700 | checked if C<DBI_DSN> is not defined. Beware that this "old-style" | ||||
2701 | C<connect> will soon be withdrawn in a future version of DBI. | ||||
2702 | |||||
2703 | =item C<connect_cached> | ||||
2704 | |||||
2705 | $dbh = DBI->connect_cached($data_source, $username, $password) | ||||
2706 | or die $DBI::errstr; | ||||
2707 | $dbh = DBI->connect_cached($data_source, $username, $password, \%attr) | ||||
2708 | or die $DBI::errstr; | ||||
2709 | |||||
2710 | C<connect_cached> is like L</connect>, except that the database handle | ||||
2711 | returned is also | ||||
2712 | stored in a hash associated with the given parameters. If another call | ||||
2713 | is made to C<connect_cached> with the same parameter values, then the | ||||
2714 | corresponding cached C<$dbh> will be returned if it is still valid. | ||||
2715 | The cached database handle is replaced with a new connection if it | ||||
2716 | has been disconnected or if the C<ping> method fails. | ||||
2717 | |||||
2718 | That the behaviour of this method differs in several respects from the | ||||
2719 | behaviour of persistent connections implemented by Apache::DBI. | ||||
2720 | However, if Apache::DBI is loaded then C<connect_cached> will use it. | ||||
2721 | |||||
2722 | Caching connections can be useful in some applications, but it can | ||||
2723 | also cause problems, such as too many connections, and so should | ||||
2724 | be used with care. In particular, avoid changing the attributes of | ||||
2725 | a database handle created via connect_cached() because it will affect | ||||
2726 | other code that may be using the same handle. | ||||
2727 | |||||
2728 | Where multiple separate parts of a program are using connect_cached() | ||||
2729 | to connect to the same database with the same (initial) attributes | ||||
2730 | it is a good idea to add a private attribute to the connect_cached() | ||||
2731 | call to effectively limit the scope of the caching. For example: | ||||
2732 | |||||
2733 | DBI->connect_cached(..., { private_foo_cachekey => "Bar", ... }); | ||||
2734 | |||||
2735 | Handles returned from that connect_cached() call will only be returned | ||||
2736 | by other connect_cached() call elsewhere in the code if those other | ||||
2737 | calls also pass in the same attribute values, including the private one. | ||||
2738 | (I've used C<private_foo_cachekey> here as an example, you can use | ||||
2739 | any attribute name with a C<private_> prefix.) | ||||
2740 | |||||
2741 | Taking that one step further, you can limit a particular connect_cached() | ||||
2742 | call to return handles unique to that one place in the code by setting the | ||||
2743 | private attribute to a unique value for that place: | ||||
2744 | |||||
2745 | DBI->connect_cached(..., { private_foo_cachekey => __FILE__.__LINE__, ... }); | ||||
2746 | |||||
2747 | By using a private attribute you still get connection caching for | ||||
2748 | the individual calls to connect_cached() but, by making separate | ||||
2749 | database conections for separate parts of the code, the database | ||||
2750 | handles are isolated from any attribute changes made to other handles. | ||||
2751 | |||||
2752 | The cache can be accessed (and cleared) via the L</CachedKids> attribute: | ||||
2753 | |||||
2754 | my $CachedKids_hashref = $dbh->{Driver}->{CachedKids}; | ||||
2755 | %$CachedKids_hashref = () if $CachedKids_hashref; | ||||
2756 | |||||
2757 | |||||
2758 | =item C<available_drivers> | ||||
2759 | |||||
2760 | @ary = DBI->available_drivers; | ||||
2761 | @ary = DBI->available_drivers($quiet); | ||||
2762 | |||||
2763 | Returns a list of all available drivers by searching for C<DBD::*> modules | ||||
2764 | through the directories in C<@INC>. By default, a warning is given if | ||||
2765 | some drivers are hidden by others of the same name in earlier | ||||
2766 | directories. Passing a true value for C<$quiet> will inhibit the warning. | ||||
2767 | |||||
2768 | =item C<installed_drivers> | ||||
2769 | |||||
2770 | %drivers = DBI->installed_drivers(); | ||||
2771 | |||||
2772 | Returns a list of driver name and driver handle pairs for all drivers | ||||
2773 | 'installed' (loaded) into the current process. The driver name does not | ||||
2774 | include the 'DBD::' prefix. | ||||
2775 | |||||
2776 | To get a list of all drivers available in your perl instalation you can use | ||||
2777 | L</available_drivers>. | ||||
2778 | |||||
2779 | Added in DBI 1.49. | ||||
2780 | |||||
2781 | =item C<installed_versions> | ||||
2782 | |||||
2783 | DBI->installed_versions; | ||||
2784 | @ary = DBI->installed_versions; | ||||
2785 | %hash = DBI->installed_versions; | ||||
2786 | |||||
2787 | Calls available_drivers() and attempts to load each of them in turn | ||||
2788 | using install_driver(). For each load that succeeds the driver | ||||
2789 | name and version number are added to a hash. When running under | ||||
2790 | L<DBI::PurePerl> drivers which appear not be pure-perl are ignored. | ||||
2791 | |||||
2792 | When called in array context the list of successfully loaded drivers | ||||
2793 | is returned (without the 'DBD::' prefix). | ||||
2794 | |||||
2795 | When called in scalar context a reference to the hash is returned | ||||
2796 | and the hash will also contain other entries for the C<DBI> version, | ||||
2797 | C<OS> name, etc. | ||||
2798 | |||||
2799 | When called in a void context the installed_versions() method will | ||||
2800 | print out a formatted list of the hash contents, one per line. | ||||
2801 | |||||
2802 | Due to the potentially high memory cost and unknown risks of loading | ||||
2803 | in an unknown number of drivers that just happen to be installed | ||||
2804 | on the system, this method is not recommended for general use. | ||||
2805 | Use available_drivers() instead. | ||||
2806 | |||||
2807 | The installed_versions() method is primarily intended as a quick | ||||
2808 | way to see from the command line what's installed. For example: | ||||
2809 | |||||
2810 | perl -MDBI -e 'DBI->installed_versions' | ||||
2811 | |||||
2812 | The installed_versions() method was added in DBI 1.38. | ||||
2813 | |||||
2814 | =item C<data_sources> | ||||
2815 | |||||
2816 | @ary = DBI->data_sources($driver); | ||||
2817 | @ary = DBI->data_sources($driver, \%attr); | ||||
2818 | |||||
2819 | Returns a list of data sources (databases) available via the named | ||||
2820 | driver. If C<$driver> is empty or C<undef>, then the value of the | ||||
2821 | C<DBI_DRIVER> environment variable is used. | ||||
2822 | |||||
2823 | The driver will be loaded if it hasn't been already. Note that if the | ||||
2824 | driver loading fails then data_sources() I<dies> with an error message | ||||
2825 | that includes the string "C<install_driver>" and the underlying problem. | ||||
2826 | |||||
2827 | Data sources are returned in a form suitable for passing to the | ||||
2828 | L</connect> method (that is, they will include the "C<dbi:$driver:>" prefix). | ||||
2829 | |||||
2830 | Note that many drivers have no way of knowing what data sources might | ||||
2831 | be available for it. These drivers return an empty or incomplete list | ||||
2832 | or may require driver-specific attributes. | ||||
2833 | |||||
2834 | There is also a data_sources() method defined for database handles. | ||||
2835 | |||||
2836 | |||||
2837 | =item C<trace> | ||||
2838 | |||||
2839 | DBI->trace($trace_setting) | ||||
2840 | DBI->trace($trace_setting, $trace_filename) | ||||
2841 | DBI->trace($trace_setting, $trace_filehandle) | ||||
2842 | $trace_setting = DBI->trace; | ||||
2843 | |||||
2844 | The C<DBI-E<gt>trace> method sets the I<global default> trace | ||||
2845 | settings and returns the I<previous> trace settings. It can also | ||||
2846 | be used to change where the trace output is sent. | ||||
2847 | |||||
2848 | There's a similar method, C<$h-E<gt>trace>, which sets the trace | ||||
2849 | settings for the specific handle it's called on. | ||||
2850 | |||||
2851 | See the L</TRACING> section for full details about the DBI's powerful | ||||
2852 | tracing facilities. | ||||
2853 | |||||
2854 | =back | ||||
2855 | |||||
2856 | |||||
2857 | =head2 DBI Utility Functions | ||||
2858 | |||||
2859 | In addition to the DBI methods listed in the previous section, | ||||
2860 | the DBI package also provides several utility functions. | ||||
2861 | |||||
2862 | These can be imported into your code by listing them in | ||||
2863 | the C<use> statement. For example: | ||||
2864 | |||||
2865 | use DBI qw(neat data_diff); | ||||
2866 | |||||
2867 | Alternatively, all these utility functions (except hash) can be | ||||
2868 | imported using the C<:utils> import tag. For example: | ||||
2869 | |||||
2870 | use DBI qw(:utils); | ||||
2871 | |||||
2872 | =over 4 | ||||
2873 | |||||
2874 | =item C<data_string_desc> | ||||
2875 | |||||
2876 | $description = data_string_desc($string); | ||||
2877 | |||||
2878 | Returns an informal description of the string. For example: | ||||
2879 | |||||
2880 | UTF8 off, ASCII, 42 characters 42 bytes | ||||
2881 | UTF8 off, non-ASCII, 42 characters 42 bytes | ||||
2882 | UTF8 on, non-ASCII, 4 characters 6 bytes | ||||
2883 | UTF8 on but INVALID encoding, non-ASCII, 4 characters 6 bytes | ||||
2884 | UTF8 off, undef | ||||
2885 | |||||
2886 | The initial C<UTF8> on/off refers to Perl's internal SvUTF8 flag. | ||||
2887 | If $string has the SvUTF8 flag set but the sequence of bytes it | ||||
2888 | contains are not a valid UTF-8 encoding then data_string_desc() | ||||
2889 | will report C<UTF8 on but INVALID encoding>. | ||||
2890 | |||||
2891 | The C<ASCII> vs C<non-ASCII> portion shows C<ASCII> if I<all> the | ||||
2892 | characters in the string are ASCII (have code points <= 127). | ||||
2893 | |||||
2894 | The data_string_desc() function was added in DBI 1.46. | ||||
2895 | |||||
2896 | =item C<data_string_diff> | ||||
2897 | |||||
2898 | $diff = data_string_diff($a, $b); | ||||
2899 | |||||
2900 | Returns an informal description of the first character difference | ||||
2901 | between the strings. If both $a and $b contain the same sequence | ||||
2902 | of characters then data_string_diff() returns an empty string. | ||||
2903 | For example: | ||||
2904 | |||||
2905 | Params a & b Result | ||||
2906 | ------------ ------ | ||||
2907 | 'aaa', 'aaa' '' | ||||
2908 | 'aaa', 'abc' 'Strings differ at index 2: a[2]=a, b[2]=b' | ||||
2909 | 'aaa', undef 'String b is undef, string a has 3 characters' | ||||
2910 | 'aaa', 'aa' 'String b truncated after 2 characters' | ||||
2911 | |||||
2912 | Unicode characters are reported in C<\x{XXXX}> format. Unicode | ||||
2913 | code points in the range U+0800 to U+08FF are unassigned and most | ||||
2914 | likely to occur due to double-encoding. Characters in this range | ||||
2915 | are reported as C<\x{08XX}='C'> where C<C> is the corresponding | ||||
2916 | latin-1 character. | ||||
2917 | |||||
2918 | The data_string_diff() function only considers logical I<characters> | ||||
2919 | and not the underlying encoding. See L</data_diff> for an alternative. | ||||
2920 | |||||
2921 | The data_string_diff() function was added in DBI 1.46. | ||||
2922 | |||||
2923 | =item C<data_diff> | ||||
2924 | |||||
2925 | $diff = data_diff($a, $b); | ||||
2926 | $diff = data_diff($a, $b, $logical); | ||||
2927 | |||||
2928 | Returns an informal description of the difference between two strings. | ||||
2929 | It calls L</data_string_desc> and L</data_string_diff> | ||||
2930 | and returns the combined results as a multi-line string. | ||||
2931 | |||||
2932 | For example, C<data_diff("abc", "ab\x{263a}")> will return: | ||||
2933 | |||||
2934 | a: UTF8 off, ASCII, 3 characters 3 bytes | ||||
2935 | b: UTF8 on, non-ASCII, 3 characters 5 bytes | ||||
2936 | Strings differ at index 2: a[2]=c, b[2]=\x{263A} | ||||
2937 | |||||
2938 | If $a and $b are identical in both the characters they contain I<and> | ||||
2939 | their physical encoding then data_diff() returns an empty string. | ||||
2940 | If $logical is true then physical encoding differences are ignored | ||||
2941 | (but are still reported if there is a difference in the characters). | ||||
2942 | |||||
2943 | The data_diff() function was added in DBI 1.46. | ||||
2944 | |||||
2945 | =item C<neat> | ||||
2946 | |||||
2947 | $str = neat($value); | ||||
2948 | $str = neat($value, $maxlen); | ||||
2949 | |||||
2950 | Return a string containing a neat (and tidy) representation of the | ||||
2951 | supplied value. | ||||
2952 | |||||
2953 | Strings will be quoted, although internal quotes will I<not> be escaped. | ||||
2954 | Values known to be numeric will be unquoted. Undefined (NULL) values | ||||
2955 | will be shown as C<undef> (without quotes). | ||||
2956 | |||||
2957 | If the string is flagged internally as utf8 then double quotes will | ||||
2958 | be used, otherwise single quotes are used and unprintable characters | ||||
2959 | will be replaced by dot (.). | ||||
2960 | |||||
2961 | For result strings longer than C<$maxlen> the result string will be | ||||
2962 | truncated to C<$maxlen-4> and "C<...'>" will be appended. If C<$maxlen> is 0 | ||||
2963 | or C<undef>, it defaults to C<$DBI::neat_maxlen> which, in turn, defaults to 400. | ||||
2964 | |||||
2965 | This function is designed to format values for human consumption. | ||||
2966 | It is used internally by the DBI for L</trace> output. It should | ||||
2967 | typically I<not> be used for formatting values for database use. | ||||
2968 | (See also L</quote>.) | ||||
2969 | |||||
2970 | =item C<neat_list> | ||||
2971 | |||||
2972 | $str = neat_list(\@listref, $maxlen, $field_sep); | ||||
2973 | |||||
2974 | Calls C<neat> on each element of the list and returns a string | ||||
2975 | containing the results joined with C<$field_sep>. C<$field_sep> defaults | ||||
2976 | to C<", ">. | ||||
2977 | |||||
2978 | =item C<looks_like_number> | ||||
2979 | |||||
2980 | @bool = looks_like_number(@array); | ||||
2981 | |||||
2982 | Returns true for each element that looks like a number. | ||||
2983 | Returns false for each element that does not look like a number. | ||||
2984 | Returns C<undef> for each element that is undefined or empty. | ||||
2985 | |||||
2986 | =item C<hash> | ||||
2987 | |||||
2988 | $hash_value = DBI::hash($buffer, $type); | ||||
2989 | |||||
2990 | Return a 32-bit integer 'hash' value corresponding to the contents of $buffer. | ||||
2991 | The $type parameter selects which kind of hash algorithm should be used. | ||||
2992 | |||||
2993 | For the technically curious, type 0 (which is the default if $type | ||||
2994 | isn't specified) is based on the Perl 5.1 hash except that the value | ||||
2995 | is forced to be negative (for obscure historical reasons). | ||||
2996 | Type 1 is the better "Fowler / Noll / Vo" (FNV) hash. See | ||||
2997 | L<http://www.isthe.com/chongo/tech/comp/fnv/> for more information. | ||||
2998 | Both types are implemented in C and are very fast. | ||||
2999 | |||||
3000 | This function doesn't have much to do with databases, except that | ||||
3001 | it can be handy to store hash values in a database. | ||||
3002 | |||||
3003 | =back | ||||
3004 | |||||
3005 | |||||
3006 | =head2 DBI Dynamic Attributes | ||||
3007 | |||||
3008 | Dynamic attributes are always associated with the I<last handle used> | ||||
3009 | (that handle is represented by C<$h> in the descriptions below). | ||||
3010 | |||||
3011 | Where an attribute is equivalent to a method call, then refer to | ||||
3012 | the method call for all related documentation. | ||||
3013 | |||||
3014 | Warning: these attributes are provided as a convenience but they | ||||
3015 | do have limitations. Specifically, they have a short lifespan: | ||||
3016 | because they are associated with | ||||
3017 | the last handle used, they should only be used I<immediately> after | ||||
3018 | calling the method that "sets" them. | ||||
3019 | If in any doubt, use the corresponding method call. | ||||
3020 | |||||
3021 | =over 4 | ||||
3022 | |||||
3023 | =item C<$DBI::err> | ||||
3024 | |||||
3025 | Equivalent to C<$h-E<gt>err>. | ||||
3026 | |||||
3027 | =item C<$DBI::errstr> | ||||
3028 | |||||
3029 | Equivalent to C<$h-E<gt>errstr>. | ||||
3030 | |||||
3031 | =item C<$DBI::state> | ||||
3032 | |||||
3033 | Equivalent to C<$h-E<gt>state>. | ||||
3034 | |||||
3035 | =item C<$DBI::rows> | ||||
3036 | |||||
3037 | Equivalent to C<$h-E<gt>rows>. Please refer to the documentation | ||||
3038 | for the L</rows> method. | ||||
3039 | |||||
3040 | =item C<$DBI::lasth> | ||||
3041 | |||||
3042 | Returns the DBI object handle used for the most recent DBI method call. | ||||
3043 | If the last DBI method call was a DESTROY then $DBI::lasth will return | ||||
3044 | the handle of the parent of the destroyed handle, if there is one. | ||||
3045 | |||||
3046 | =back | ||||
3047 | |||||
3048 | |||||
3049 | =head1 METHODS COMMON TO ALL HANDLES | ||||
3050 | |||||
3051 | The following methods can be used by all types of DBI handles. | ||||
3052 | |||||
3053 | =over 4 | ||||
3054 | |||||
3055 | =item C<err> | ||||
3056 | |||||
3057 | $rv = $h->err; | ||||
3058 | |||||
3059 | Returns the I<native> database engine error code from the last driver | ||||
3060 | method called. The code is typically an integer but you should not | ||||
3061 | assume that. | ||||
3062 | |||||
3063 | The DBI resets $h->err to undef before almost all DBI method calls, so the | ||||
3064 | value only has a short lifespan. Also, for most drivers, the statement | ||||
3065 | handles share the same error variable as the parent database handle, | ||||
3066 | so calling a method on one handle may reset the error on the | ||||
3067 | related handles. | ||||
3068 | |||||
3069 | (Methods which don't reset err before being called include err() and errstr(), | ||||
3070 | obviously, state(), rows(), func(), trace(), trace_msg(), ping(), and the | ||||
3071 | tied hash attribute FETCH() and STORE() methods.) | ||||
3072 | |||||
3073 | If you need to test for specific error conditions I<and> have your program be | ||||
3074 | portable to different database engines, then you'll need to determine what the | ||||
3075 | corresponding error codes are for all those engines and test for all of them. | ||||
3076 | |||||
3077 | A driver may return C<0> from err() to indicate a warning condition | ||||
3078 | after a method call. Similarly, a driver may return an empty string | ||||
3079 | to indicate a 'success with information' condition. In both these | ||||
3080 | cases the value is false but not undef. The errstr() and state() | ||||
3081 | methods may be used to retrieve extra information in these cases. | ||||
3082 | |||||
3083 | See L</set_err> for more information. | ||||
3084 | |||||
3085 | =item C<errstr> | ||||
3086 | |||||
3087 | $str = $h->errstr; | ||||
3088 | |||||
3089 | Returns the native database engine error message from the last DBI | ||||
3090 | method called. This has the same lifespan issues as the L</err> method | ||||
3091 | described above. | ||||
3092 | |||||
3093 | The returned string may contain multiple messages separated by | ||||
3094 | newline characters. | ||||
3095 | |||||
3096 | The errstr() method should not be used to test for errors, use err() | ||||
3097 | for that, because drivers may return 'success with information' or | ||||
3098 | warning messages via errstr() for methods that have not 'failed'. | ||||
3099 | |||||
3100 | See L</set_err> for more information. | ||||
3101 | |||||
3102 | =item C<state> | ||||
3103 | |||||
3104 | $str = $h->state; | ||||
3105 | |||||
3106 | Returns a state code in the standard SQLSTATE five character format. | ||||
3107 | Note that the specific success code C<00000> is translated to any empty string | ||||
3108 | (false). If the driver does not support SQLSTATE (and most don't), | ||||
3109 | then state will return C<S1000> (General Error) for all errors. | ||||
3110 | |||||
3111 | The driver is free to return any value via C<state>, e.g., warning | ||||
3112 | codes, even if it has not declared an error by returning a true value | ||||
3113 | via the L</err> method described above. | ||||
3114 | |||||
3115 | The state() method should not be used to test for errors, use err() | ||||
3116 | for that, because drivers may return a 'success with information' or | ||||
3117 | warning state code via errstr() for methods that have not 'failed'. | ||||
3118 | |||||
3119 | =item C<set_err> | ||||
3120 | |||||
3121 | $rv = $h->set_err($err, $errstr); | ||||
3122 | $rv = $h->set_err($err, $errstr, $state); | ||||
3123 | $rv = $h->set_err($err, $errstr, $state, $method); | ||||
3124 | $rv = $h->set_err($err, $errstr, $state, $method, $rv); | ||||
3125 | |||||
3126 | Set the C<err>, C<errstr>, and C<state> values for the handle. | ||||
3127 | This method is typically only used by DBI drivers and DBI subclasses. | ||||
3128 | |||||
3129 | If the L</HandleSetErr> attribute holds a reference to a subroutine | ||||
3130 | it is called first. The subroutine can alter the $err, $errstr, $state, | ||||
3131 | and $method values. See L</HandleSetErr> for full details. | ||||
3132 | If the subroutine returns a true value then the handle C<err>, | ||||
3133 | C<errstr>, and C<state> values are not altered and set_err() returns | ||||
3134 | an empty list (it normally returns $rv which defaults to undef, see below). | ||||
3135 | |||||
3136 | Setting C<err> to a I<true> value indicates an error and will trigger | ||||
3137 | the normal DBI error handling mechanisms, such as C<RaiseError> and | ||||
3138 | C<HandleError>, if they are enabled, when execution returns from | ||||
3139 | the DBI back to the application. | ||||
3140 | |||||
3141 | Setting C<err> to C<""> indicates an 'information' state, and setting | ||||
3142 | it to C<"0"> indicates a 'warning' state. Setting C<err> to C<undef> | ||||
3143 | also sets C<errstr> to undef, and C<state> to C<"">, irrespective | ||||
3144 | of the values of the $errstr and $state parameters. | ||||
3145 | |||||
3146 | The $method parameter provides an alternate method name for the | ||||
3147 | C<RaiseError>/C<PrintError>/C<PrintWarn> error string instead of | ||||
3148 | the fairly unhelpful 'C<set_err>'. | ||||
3149 | |||||
3150 | The C<set_err> method normally returns undef. The $rv parameter | ||||
3151 | provides an alternate return value. | ||||
3152 | |||||
3153 | Some special rules apply if the C<err> or C<errstr> | ||||
3154 | values for the handle are I<already> set... | ||||
3155 | |||||
3156 | If C<errstr> is true then: "C< [err was %s now %s]>" is appended if $err is | ||||
3157 | true and C<err> is already true and the new err value differs from the original | ||||
3158 | one. Similarly "C< [state was %s now %s]>" is appended if $state is true and C<state> is | ||||
3159 | already true and the new state value differs from the original one. Finally | ||||
3160 | "C<\n>" and the new $errstr are appended if $errstr differs from the existing | ||||
3161 | errstr value. Obviously the C<%s>'s above are replaced by the corresponding values. | ||||
3162 | |||||
3163 | The handle C<err> value is set to $err if: $err is true; or handle | ||||
3164 | C<err> value is undef; or $err is defined and the length is greater | ||||
3165 | than the handle C<err> length. The effect is that an 'information' | ||||
3166 | state only overrides undef; a 'warning' overrides undef or 'information', | ||||
3167 | and an 'error' state overrides anything. | ||||
3168 | |||||
3169 | The handle C<state> value is set to $state if $state is true and | ||||
3170 | the handle C<err> value was set (by the rules above). | ||||
3171 | |||||
3172 | Support for warning and information states was added in DBI 1.41. | ||||
3173 | |||||
3174 | =item C<trace> | ||||
3175 | |||||
3176 | $h->trace($trace_settings); | ||||
3177 | $h->trace($trace_settings, $trace_filename); | ||||
3178 | $trace_settings = $h->trace; | ||||
3179 | |||||
3180 | The trace() method is used to alter the trace settings for a handle | ||||
3181 | (and any future children of that handle). It can also be used to | ||||
3182 | change where the trace output is sent. | ||||
3183 | |||||
3184 | There's a similar method, C<DBI-E<gt>trace>, which sets the global | ||||
3185 | default trace settings. | ||||
3186 | |||||
3187 | See the L</TRACING> section for full details about the DBI's powerful | ||||
3188 | tracing facilities. | ||||
3189 | |||||
3190 | =item C<trace_msg> | ||||
3191 | |||||
3192 | $h->trace_msg($message_text); | ||||
3193 | $h->trace_msg($message_text, $min_level); | ||||
3194 | |||||
3195 | Writes C<$message_text> to the trace file if the trace level is | ||||
3196 | greater than or equal to $min_level (which defaults to 1). | ||||
3197 | Can also be called as C<DBI-E<gt>trace_msg($msg)>. | ||||
3198 | |||||
3199 | See L</TRACING> for more details. | ||||
3200 | |||||
3201 | =item C<func> | ||||
3202 | |||||
3203 | $h->func(@func_arguments, $func_name) or die ...; | ||||
3204 | |||||
3205 | The C<func> method can be used to call private non-standard and | ||||
3206 | non-portable methods implemented by the driver. Note that the function | ||||
3207 | name is given as the I<last> argument. | ||||
3208 | |||||
3209 | It's also important to note that the func() method does not clear | ||||
3210 | a previous error ($DBI::err etc.) and it does not trigger automatic | ||||
3211 | error detection (RaiseError etc.) so you must check the return | ||||
3212 | status and/or $h->err to detect errors. | ||||
3213 | |||||
3214 | (This method is not directly related to calling stored procedures. | ||||
3215 | Calling stored procedures is currently not defined by the DBI. | ||||
3216 | Some drivers, such as DBD::Oracle, support it in non-portable ways. | ||||
3217 | See driver documentation for more details.) | ||||
3218 | |||||
3219 | See also L</install_method> for how you can avoid needing to | ||||
3220 | use func() and gain. | ||||
3221 | |||||
3222 | =item C<can> | ||||
3223 | |||||
3224 | $is_implemented = $h->can($method_name); | ||||
3225 | |||||
3226 | Returns true if $method_name is implemented by the driver or a | ||||
3227 | default method is provided by the DBI. | ||||
3228 | It returns false where a driver hasn't implemented a method and the | ||||
3229 | default method is provided by the DBI is just an empty stub. | ||||
3230 | |||||
3231 | =item C<parse_trace_flags> | ||||
3232 | |||||
3233 | $trace_settings_integer = $h->parse_trace_flags($trace_settings); | ||||
3234 | |||||
3235 | Parses a string containing trace settings and returns the corresponding | ||||
3236 | integer value used internally by the DBI and drivers. | ||||
3237 | |||||
3238 | The $trace_settings argument is a string containing a trace level | ||||
3239 | between 0 and 15 and/or trace flag names separated by vertical bar | ||||
3240 | ("C<|>") or comma ("C<,>") characters. For example: C<"SQL|3|foo">. | ||||
3241 | |||||
3242 | It uses the parse_trace_flag() method, described below, to process | ||||
3243 | the individual trage flag names. | ||||
3244 | |||||
3245 | The parse_trace_flags() method was added in DBI 1.42. | ||||
3246 | |||||
3247 | =item C<parse_trace_flag> | ||||
3248 | |||||
3249 | $bit_flag = $h->parse_trace_flag($trace_flag_name); | ||||
3250 | |||||
3251 | Returns the bit flag corresponding to the trace flag name in | ||||
3252 | $trace_flag_name. Drivers are expected to override this method and | ||||
3253 | check if $trace_flag_name is a driver specific trace flags and, if | ||||
3254 | not, then call the DBIs default parse_trace_flag(). | ||||
3255 | |||||
3256 | The parse_trace_flag() method was added in DBI 1.42. | ||||
3257 | |||||
3258 | =item C<private_attribute_info> | ||||
3259 | |||||
3260 | $hash_ref = $h->private_attribute_info(); | ||||
3261 | |||||
3262 | Returns a reference to a hash whose keys are the names of driver-private | ||||
3263 | attributes available for that kind of handle (driver, database, statement). | ||||
3264 | (The values should be undef. Meanings may be assigned to particular values in future.) | ||||
3265 | |||||
3266 | =item C<swap_inner_handle> | ||||
3267 | |||||
3268 | $rc = $h1->swap_inner_handle( $h2 ); | ||||
3269 | $rc = $h1->swap_inner_handle( $h2, $allow_reparent ); | ||||
3270 | |||||
3271 | Brain transplants for handles. You don't need to know about this | ||||
3272 | unless you want to become a handle surgeon. | ||||
3273 | |||||
3274 | A DBI handle is a reference to a tied hash. A tied hash has an | ||||
3275 | I<inner> hash that actually holds the contents. The swap_inner_handle() | ||||
3276 | method swaps the inner hashes between two handles. The $h1 and $h2 | ||||
3277 | handles still point to the same tied hashes, but what those hashes | ||||
3278 | are tied to has been swapped. In effect $h1 I<becomes> $h2 and | ||||
3279 | vice-versa. This is powerful stuff, expect problems. Use with care. | ||||
3280 | |||||
3281 | As a small safety measure, the two handles, $h1 and $h2, have to | ||||
3282 | share the same parent unless $allow_reparent is true. | ||||
3283 | |||||
3284 | The swap_inner_handle() method was added in DBI 1.44. | ||||
3285 | |||||
3286 | Here's a quick kind of 'diagram' as a worked example to help think about what's | ||||
3287 | happening: | ||||
3288 | |||||
3289 | Original state: | ||||
3290 | dbh1o -> dbh1i | ||||
3291 | sthAo -> sthAi(dbh1i) | ||||
3292 | dbh2o -> dbh2i | ||||
3293 | |||||
3294 | swap_inner_handle dbh1o with dbh2o: | ||||
3295 | dbh2o -> dbh1i | ||||
3296 | sthAo -> sthAi(dbh1i) | ||||
3297 | dbh1o -> dbh2i | ||||
3298 | |||||
3299 | create new sth from dbh1o: | ||||
3300 | dbh2o -> dbh1i | ||||
3301 | sthAo -> sthAi(dbh1i) | ||||
3302 | dbh1o -> dbh2i | ||||
3303 | sthBo -> sthBi(dbh2i) | ||||
3304 | |||||
3305 | swap_inner_handle sthAo with sthBo: | ||||
3306 | dbh2o -> dbh1i | ||||
3307 | sthBo -> sthAi(dbh1i) | ||||
3308 | dbh1o -> dbh2i | ||||
3309 | sthAo -> sthBi(dbh2i) | ||||
3310 | |||||
3311 | =back | ||||
3312 | |||||
3313 | |||||
3314 | =head1 ATTRIBUTES COMMON TO ALL HANDLES | ||||
3315 | |||||
3316 | These attributes are common to all types of DBI handles. | ||||
3317 | |||||
3318 | Some attributes are inherited by child handles. That is, the value | ||||
3319 | of an inherited attribute in a newly created statement handle is the | ||||
3320 | same as the value in the parent database handle. Changes to attributes | ||||
3321 | in the new statement handle do not affect the parent database handle | ||||
3322 | and changes to the database handle do not affect existing statement | ||||
3323 | handles, only future ones. | ||||
3324 | |||||
3325 | Attempting to set or get the value of an unknown attribute generates a warning, | ||||
3326 | except for private driver specific attributes (which all have names | ||||
3327 | starting with a lowercase letter). | ||||
3328 | |||||
3329 | Example: | ||||
3330 | |||||
3331 | $h->{AttributeName} = ...; # set/write | ||||
3332 | ... = $h->{AttributeName}; # get/read | ||||
3333 | |||||
3334 | =over 4 | ||||
3335 | |||||
3336 | =item C<Warn> (boolean, inherited) | ||||
3337 | |||||
3338 | The C<Warn> attribute enables useful warnings for certain bad | ||||
3339 | practices. It is enabled by default and should only be disabled in | ||||
3340 | rare circumstances. Since warnings are generated using the Perl | ||||
3341 | C<warn> function, they can be intercepted using the Perl C<$SIG{__WARN__}> | ||||
3342 | hook. | ||||
3343 | |||||
3344 | The C<Warn> attribute is not related to the C<PrintWarn> attribute. | ||||
3345 | |||||
3346 | =item C<Active> (boolean, read-only) | ||||
3347 | |||||
3348 | The C<Active> attribute is true if the handle object is "active". This is rarely used in | ||||
3349 | applications. The exact meaning of active is somewhat vague at the | ||||
3350 | moment. For a database handle it typically means that the handle is | ||||
3351 | connected to a database (C<$dbh-E<gt>disconnect> sets C<Active> off). For | ||||
3352 | a statement handle it typically means that the handle is a C<SELECT> | ||||
3353 | that may have more data to fetch. (Fetching all the data or calling C<$sth-E<gt>finish> | ||||
3354 | sets C<Active> off.) | ||||
3355 | |||||
3356 | =item C<Executed> (boolean) | ||||
3357 | |||||
3358 | The C<Executed> attribute is true if the handle object has been "executed". | ||||
3359 | Currently only the $dbh do() method and the $sth execute(), execute_array(), | ||||
3360 | and execute_for_fetch() methods set the C<Executed> attribute. | ||||
3361 | |||||
3362 | When it's set on a handle it is also set on the parent handle at the | ||||
3363 | same time. So calling execute() on a $sth also sets the C<Executed> | ||||
3364 | attribute on the parent $dbh. | ||||
3365 | |||||
3366 | The C<Executed> attribute for a database handle is cleared by the | ||||
3367 | commit() and rollback() methods. The C<Executed> attribute of a | ||||
3368 | statement handle is not cleared by the DBI under any circumstances | ||||
3369 | and so acts as a permanent record of whether the statement handle | ||||
3370 | was ever used. | ||||
3371 | |||||
3372 | The C<Executed> attribute was added in DBI 1.41. | ||||
3373 | |||||
3374 | =item C<Kids> (integer, read-only) | ||||
3375 | |||||
3376 | For a driver handle, C<Kids> is the number of currently existing database | ||||
3377 | handles that were created from that driver handle. For a database | ||||
3378 | handle, C<Kids> is the number of currently existing statement handles that | ||||
3379 | were created from that database handle. | ||||
3380 | For a statement handle, the value is zero. | ||||
3381 | |||||
3382 | =item C<ActiveKids> (integer, read-only) | ||||
3383 | |||||
3384 | Like C<Kids>, but only counting those that are C<Active> (as above). | ||||
3385 | |||||
3386 | =item C<CachedKids> (hash ref) | ||||
3387 | |||||
3388 | For a database handle, C<CachedKids> returns a reference to the cache (hash) of | ||||
3389 | statement handles created by the L</prepare_cached> method. For a | ||||
3390 | driver handle, returns a reference to the cache (hash) of | ||||
3391 | database handles created by the L</connect_cached> method. | ||||
3392 | |||||
3393 | =item C<Type> (scalar, read-only) | ||||
3394 | |||||
3395 | The C<Type> attribute identifies the type of a DBI handle. Returns | ||||
3396 | "dr" for driver handles, "db" for database handles and "st" for | ||||
3397 | statement handles. | ||||
3398 | |||||
3399 | =item C<ChildHandles> (array ref) | ||||
3400 | |||||
3401 | The ChildHandles attribute contains a reference to an array of all the | ||||
3402 | handles created by this handle which are still accessible. The | ||||
3403 | contents of the array are weak-refs and will become undef when the | ||||
3404 | handle goes out of scope. | ||||
3405 | |||||
3406 | C<ChildHandles> returns undef if your perl version does not support weak | ||||
3407 | references (check the L<Scalar::Util|Scalar::Util> module). The referenced | ||||
3408 | array returned should be treated as read-only. | ||||
3409 | |||||
3410 | For example, to enumerate all driver handles, database handles and | ||||
3411 | statement handles: | ||||
3412 | |||||
3413 | sub show_child_handles { | ||||
3414 | my ($h, $level) = @_; | ||||
3415 | $level ||= 0; | ||||
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($_) for (values %drivers); | ||||
3423 | |||||
3424 | =item 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 | =item 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 | =item 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 | =item 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 | =item 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 | =item 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 | =item 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 | =item 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 | =item 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 | =item 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 | =item 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 | =item 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 | =item 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) 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 | =item 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 | =item 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 | =item 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 | =item 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 | =item 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 | =item C<private_your_module_name_*> | ||||
3830 | |||||
3831 | The DBI provides a way to store extra information in a DBI handle as | ||||
3832 | "private" attributes. The DBI will allow you to store and retrieve any | ||||
3833 | attribute which has a name starting with "C<private_>". | ||||
3834 | |||||
3835 | It is I<strongly> recommended that you use just I<one> private | ||||
3836 | attribute (e.g., use a hash ref) I<and> give it a long and unambiguous | ||||
3837 | name that includes the module or application name that the attribute | ||||
3838 | relates to (e.g., "C<private_YourFullModuleName_thingy>"). | ||||
3839 | |||||
3840 | Because of the way the Perl tie mechanism works you cannot reliably | ||||
3841 | use the C<||=> operator directly to initialise the attribute, like this: | ||||
3842 | |||||
3843 | my $foo = $dbh->{private_yourmodname_foo} ||= { ... }; # WRONG | ||||
3844 | |||||
3845 | you should use a two step approach like this: | ||||
3846 | |||||
3847 | my $foo = $dbh->{private_yourmodname_foo}; | ||||
3848 | $foo ||= $dbh->{private_yourmodname_foo} = { ... }; | ||||
3849 | |||||
3850 | This attribute is primarily of interest to people sub-classing DBI. | ||||
3851 | |||||
3852 | =back | ||||
3853 | |||||
3854 | |||||
3855 | =head1 DBI DATABASE HANDLE OBJECTS | ||||
3856 | |||||
3857 | This section covers the methods and attributes associated with | ||||
3858 | database handles. | ||||
3859 | |||||
3860 | =head2 Database Handle Methods | ||||
3861 | |||||
3862 | The following methods are specified for DBI database handles: | ||||
3863 | |||||
3864 | =over 4 | ||||
3865 | |||||
3866 | =item C<clone> | ||||
3867 | |||||
3868 | $new_dbh = $dbh->clone(); | ||||
3869 | $new_dbh = $dbh->clone(\%attr); | ||||
3870 | |||||
3871 | The C<clone> method duplicates the $dbh connection by connecting | ||||
3872 | with the same parameters ($dsn, $user, $password) as originally used. | ||||
3873 | |||||
3874 | The attributes for the cloned connect are the same as those used | ||||
3875 | for the original connect, with some other attribute merged over | ||||
3876 | them depending on the \%attr parameter. | ||||
3877 | |||||
3878 | If \%attr is given then the attributes it contains are merged into | ||||
3879 | the original attributes and override any with the same names. | ||||
3880 | Effectively the same as doing: | ||||
3881 | |||||
3882 | %attribues_used = ( %original_attributes, %attr ); | ||||
3883 | |||||
3884 | If \%attr is not given then it defaults to a hash containing all | ||||
3885 | the attributes in the attribute cache of $dbh excluding any non-code | ||||
3886 | references, plus the main boolean attributes (RaiseError, PrintError, | ||||
3887 | AutoCommit, etc.). This behaviour is subject to change. | ||||
3888 | |||||
3889 | The clone method can be used even if the database handle is disconnected. | ||||
3890 | |||||
3891 | The C<clone> method was added in DBI 1.33. It is very new and likely | ||||
3892 | to change. | ||||
3893 | |||||
3894 | =item C<data_sources> | ||||
3895 | |||||
3896 | @ary = $dbh->data_sources(); | ||||
3897 | @ary = $dbh->data_sources(\%attr); | ||||
3898 | |||||
3899 | Returns a list of data sources (databases) available via the $dbh | ||||
3900 | driver's data_sources() method, plus any extra data sources that | ||||
3901 | the driver can discover via the connected $dbh. Typically the extra | ||||
3902 | data sources are other databases managed by the same server process | ||||
3903 | that the $dbh is connected to. | ||||
3904 | |||||
3905 | Data sources are returned in a form suitable for passing to the | ||||
3906 | L</connect> method (that is, they will include the "C<dbi:$driver:>" prefix). | ||||
3907 | |||||
3908 | The data_sources() method, for a $dbh, was added in DBI 1.38. | ||||
3909 | |||||
3910 | =item C<do> | ||||
3911 | |||||
3912 | $rows = $dbh->do($statement) or die $dbh->errstr; | ||||
3913 | $rows = $dbh->do($statement, \%attr) or die $dbh->errstr; | ||||
3914 | $rows = $dbh->do($statement, \%attr, @bind_values) or die ... | ||||
3915 | |||||
3916 | Prepare and execute a single statement. Returns the number of rows | ||||
3917 | affected or C<undef> on error. A return value of C<-1> means the | ||||
3918 | number of rows is not known, not applicable, or not available. | ||||
3919 | |||||
3920 | This method is typically most useful for I<non>-C<SELECT> statements that | ||||
3921 | either cannot be prepared in advance (due to a limitation of the | ||||
3922 | driver) or do not need to be executed repeatedly. It should not | ||||
3923 | be used for C<SELECT> statements because it does not return a statement | ||||
3924 | handle (so you can't fetch any data). | ||||
3925 | |||||
3926 | The default C<do> method is logically similar to: | ||||
3927 | |||||
3928 | sub do { | ||||
3929 | my($dbh, $statement, $attr, @bind_values) = @_; | ||||
3930 | my $sth = $dbh->prepare($statement, $attr) or return undef; | ||||
3931 | $sth->execute(@bind_values) or return undef; | ||||
3932 | my $rows = $sth->rows; | ||||
3933 | ($rows == 0) ? "0E0" : $rows; # always return true if no error | ||||
3934 | } | ||||
3935 | |||||
3936 | For example: | ||||
3937 | |||||
3938 | my $rows_deleted = $dbh->do(q{ | ||||
3939 | DELETE FROM table | ||||
3940 | WHERE status = ? | ||||
3941 | }, undef, 'DONE') or die $dbh->errstr; | ||||
3942 | |||||
3943 | Using placeholders and C<@bind_values> with the C<do> method can be | ||||
3944 | useful because it avoids the need to correctly quote any variables | ||||
3945 | in the C<$statement>. But if you'll be executing the statement many | ||||
3946 | times then it's more efficient to C<prepare> it once and call | ||||
3947 | C<execute> many times instead. | ||||
3948 | |||||
3949 | The C<q{...}> style quoting used in this example avoids clashing with | ||||
3950 | quotes that may be used in the SQL statement. Use the double-quote-like | ||||
3951 | C<qq{...}> operator if you want to interpolate variables into the string. | ||||
3952 | See L<perlop/"Quote and Quote-like Operators"> for more details. | ||||
3953 | |||||
3954 | =item C<last_insert_id> | ||||
3955 | |||||
3956 | $rv = $dbh->last_insert_id($catalog, $schema, $table, $field); | ||||
3957 | $rv = $dbh->last_insert_id($catalog, $schema, $table, $field, \%attr); | ||||
3958 | |||||
3959 | Returns a value 'identifying' the row just inserted, if possible. | ||||
3960 | Typically this would be a value assigned by the database server | ||||
3961 | to a column with an I<auto_increment> or I<serial> type. | ||||
3962 | Returns undef if the driver does not support the method or can't | ||||
3963 | determine the value. | ||||
3964 | |||||
3965 | The $catalog, $schema, $table, and $field parameters may be required | ||||
3966 | for some drivers (see below). If you don't know the parameter values | ||||
3967 | and your driver does not need them, then use C<undef> for each. | ||||
3968 | |||||
3969 | There are several caveats to be aware of with this method if you want | ||||
3970 | to use it for portable applications: | ||||
3971 | |||||
3972 | B<*> For some drivers the value may only available immediately after | ||||
3973 | the insert statement has executed (e.g., mysql, Informix). | ||||
3974 | |||||
3975 | B<*> For some drivers the $catalog, $schema, $table, and $field parameters | ||||
3976 | are required, for others they are ignored (e.g., mysql). | ||||
3977 | |||||
3978 | B<*> Drivers may return an indeterminate value if no insert has | ||||
3979 | been performed yet. | ||||
3980 | |||||
3981 | B<*> For some drivers the value may only be available if placeholders | ||||
3982 | have I<not> been used (e.g., Sybase, MS SQL). In this case the value | ||||
3983 | returned would be from the last non-placeholder insert statement. | ||||
3984 | |||||
3985 | B<*> Some drivers may need driver-specific hints about how to get | ||||
3986 | the value. For example, being told the name of the database 'sequence' | ||||
3987 | object that holds the value. Any such hints are passed as driver-specific | ||||
3988 | attributes in the \%attr parameter. | ||||
3989 | |||||
3990 | B<*> If the underlying database offers nothing better, then some | ||||
3991 | drivers may attempt to implement this method by executing | ||||
3992 | "C<select max($field) from $table>". Drivers using any approach | ||||
3993 | like this should issue a warning if C<AutoCommit> is true because | ||||
3994 | it is generally unsafe - another process may have modified the table | ||||
3995 | between your insert and the select. For situations where you know | ||||
3996 | it is safe, such as when you have locked the table, you can silence | ||||
3997 | the warning by passing C<Warn> => 0 in \%attr. | ||||
3998 | |||||
3999 | B<*> If no insert has been performed yet, or the last insert failed, | ||||
4000 | then the value is implementation defined. | ||||
4001 | |||||
4002 | Given all the caveats above, it's clear that this method must be | ||||
4003 | used with care. | ||||
4004 | |||||
4005 | The C<last_insert_id> method was added in DBI 1.38. | ||||
4006 | |||||
4007 | =item C<selectrow_array> | ||||
4008 | |||||
4009 | @row_ary = $dbh->selectrow_array($statement); | ||||
4010 | @row_ary = $dbh->selectrow_array($statement, \%attr); | ||||
4011 | @row_ary = $dbh->selectrow_array($statement, \%attr, @bind_values); | ||||
4012 | |||||
4013 | This utility method combines L</prepare>, L</execute> and | ||||
4014 | L</fetchrow_array> into a single call. If called in a list context, it | ||||
4015 | returns the first row of data from the statement. The C<$statement> | ||||
4016 | parameter can be a previously prepared statement handle, in which case | ||||
4017 | the C<prepare> is skipped. | ||||
4018 | |||||
4019 | If any method fails, and L</RaiseError> is not set, C<selectrow_array> | ||||
4020 | will return an empty list. | ||||
4021 | |||||
4022 | If called in a scalar context for a statement handle that has more | ||||
4023 | than one column, it is undefined whether the driver will return | ||||
4024 | the value of the first column or the last. So don't do that. | ||||
4025 | Also, in a scalar context, an C<undef> is returned if there are no | ||||
4026 | more rows or if an error occurred. That C<undef> can't be distinguished | ||||
4027 | from an C<undef> returned because the first field value was NULL. | ||||
4028 | For these reasons you should exercise some caution if you use | ||||
4029 | C<selectrow_array> in a scalar context, or just don't do that. | ||||
4030 | |||||
4031 | |||||
4032 | =item C<selectrow_arrayref> | ||||
4033 | |||||
4034 | $ary_ref = $dbh->selectrow_arrayref($statement); | ||||
4035 | $ary_ref = $dbh->selectrow_arrayref($statement, \%attr); | ||||
4036 | $ary_ref = $dbh->selectrow_arrayref($statement, \%attr, @bind_values); | ||||
4037 | |||||
4038 | This utility method combines L</prepare>, L</execute> and | ||||
4039 | L</fetchrow_arrayref> into a single call. It returns the first row of | ||||
4040 | data from the statement. The C<$statement> parameter can be a previously | ||||
4041 | prepared statement handle, in which case the C<prepare> is skipped. | ||||
4042 | |||||
4043 | If any method fails, and L</RaiseError> is not set, C<selectrow_array> | ||||
4044 | will return undef. | ||||
4045 | |||||
4046 | |||||
4047 | =item C<selectrow_hashref> | ||||
4048 | |||||
4049 | $hash_ref = $dbh->selectrow_hashref($statement); | ||||
4050 | $hash_ref = $dbh->selectrow_hashref($statement, \%attr); | ||||
4051 | $hash_ref = $dbh->selectrow_hashref($statement, \%attr, @bind_values); | ||||
4052 | |||||
4053 | This utility method combines L</prepare>, L</execute> and | ||||
4054 | L</fetchrow_hashref> into a single call. It returns the first row of | ||||
4055 | data from the statement. The C<$statement> parameter can be a previously | ||||
4056 | prepared statement handle, in which case the C<prepare> is skipped. | ||||
4057 | |||||
4058 | If any method fails, and L</RaiseError> is not set, C<selectrow_hashref> | ||||
4059 | will return undef. | ||||
4060 | |||||
4061 | |||||
4062 | =item C<selectall_arrayref> | ||||
4063 | |||||
4064 | $ary_ref = $dbh->selectall_arrayref($statement); | ||||
4065 | $ary_ref = $dbh->selectall_arrayref($statement, \%attr); | ||||
4066 | $ary_ref = $dbh->selectall_arrayref($statement, \%attr, @bind_values); | ||||
4067 | |||||
4068 | This utility method combines L</prepare>, L</execute> and | ||||
4069 | L</fetchall_arrayref> into a single call. It returns a reference to an | ||||
4070 | array containing a reference to an array (or hash, see below) for each row of | ||||
4071 | data fetched. | ||||
4072 | |||||
4073 | The C<$statement> parameter can be a previously prepared statement handle, | ||||
4074 | in which case the C<prepare> is skipped. This is recommended if the | ||||
4075 | statement is going to be executed many times. | ||||
4076 | |||||
4077 | If L</RaiseError> is not set and any method except C<fetchall_arrayref> | ||||
4078 | fails then C<selectall_arrayref> will return C<undef>; if | ||||
4079 | C<fetchall_arrayref> fails then it will return with whatever data | ||||
4080 | has been fetched thus far. You should check C<$sth-E<gt>err> | ||||
4081 | afterwards (or use the C<RaiseError> attribute) to discover if the data is | ||||
4082 | complete or was truncated due to an error. | ||||
4083 | |||||
4084 | The L</fetchall_arrayref> method called by C<selectall_arrayref> | ||||
4085 | supports a $max_rows parameter. You can specify a value for $max_rows | ||||
4086 | by including a 'C<MaxRows>' attribute in \%attr. In which case finish() | ||||
4087 | is called for you after fetchall_arrayref() returns. | ||||
4088 | |||||
4089 | The L</fetchall_arrayref> method called by C<selectall_arrayref> | ||||
4090 | also supports a $slice parameter. You can specify a value for $slice by | ||||
4091 | including a 'C<Slice>' or 'C<Columns>' attribute in \%attr. The only | ||||
4092 | difference between the two is that if C<Slice> is not defined and | ||||
4093 | C<Columns> is an array ref, then the array is assumed to contain column | ||||
4094 | index values (which count from 1), rather than perl array index values. | ||||
4095 | In which case the array is copied and each value decremented before | ||||
4096 | passing to C</fetchall_arrayref>. | ||||
4097 | |||||
4098 | You may often want to fetch an array of rows where each row is stored as a | ||||
4099 | hash. That can be done simple using: | ||||
4100 | |||||
4101 | my $emps = $dbh->selectall_arrayref( | ||||
4102 | "SELECT ename FROM emp ORDER BY ename", | ||||
4103 | { Slice => {} } | ||||
4104 | ); | ||||
4105 | foreach my $emp ( @$emps ) { | ||||
4106 | print "Employee: $emp->{ename}\n"; | ||||
4107 | } | ||||
4108 | |||||
4109 | Or, to fetch into an array instead of an array ref: | ||||
4110 | |||||
4111 | @result = @{ $dbh->selectall_arrayref($sql, { Slice => {} }) }; | ||||
4112 | |||||
4113 | See L</fetchall_arrayref> method for more details. | ||||
4114 | |||||
4115 | =item C<selectall_hashref> | ||||
4116 | |||||
4117 | $hash_ref = $dbh->selectall_hashref($statement, $key_field); | ||||
4118 | $hash_ref = $dbh->selectall_hashref($statement, $key_field, \%attr); | ||||
4119 | $hash_ref = $dbh->selectall_hashref($statement, $key_field, \%attr, @bind_values); | ||||
4120 | |||||
4121 | This utility method combines L</prepare>, L</execute> and | ||||
4122 | L</fetchall_hashref> into a single call. It returns a reference to a | ||||
4123 | hash containing one entry, at most, for each row, as returned by fetchall_hashref(). | ||||
4124 | |||||
4125 | The C<$statement> parameter can be a previously prepared statement handle, | ||||
4126 | in which case the C<prepare> is skipped. This is recommended if the | ||||
4127 | statement is going to be executed many times. | ||||
4128 | |||||
4129 | The C<$key_field> parameter defines which column, or columns, are used as keys | ||||
4130 | in the returned hash. It can either be the name of a single field, or a | ||||
4131 | reference to an array containing multiple field names. Using multiple names | ||||
4132 | yields a tree of nested hashes. | ||||
4133 | |||||
4134 | If a row has the same key as an earlier row then it replaces the earlier row. | ||||
4135 | |||||
4136 | If any method except C<fetchrow_hashref> fails, and L</RaiseError> is not set, | ||||
4137 | C<selectall_hashref> will return C<undef>. If C<fetchrow_hashref> fails and | ||||
4138 | L</RaiseError> is not set, then it will return with whatever data it | ||||
4139 | has fetched thus far. $DBI::err should be checked to catch that. | ||||
4140 | |||||
4141 | See fetchall_hashref() for more details. | ||||
4142 | |||||
4143 | =item C<selectcol_arrayref> | ||||
4144 | |||||
4145 | $ary_ref = $dbh->selectcol_arrayref($statement); | ||||
4146 | $ary_ref = $dbh->selectcol_arrayref($statement, \%attr); | ||||
4147 | $ary_ref = $dbh->selectcol_arrayref($statement, \%attr, @bind_values); | ||||
4148 | |||||
4149 | This utility method combines L</prepare>, L</execute>, and fetching one | ||||
4150 | column from all the rows, into a single call. It returns a reference to | ||||
4151 | an array containing the values of the first column from each row. | ||||
4152 | |||||
4153 | The C<$statement> parameter can be a previously prepared statement handle, | ||||
4154 | in which case the C<prepare> is skipped. This is recommended if the | ||||
4155 | statement is going to be executed many times. | ||||
4156 | |||||
4157 | If any method except C<fetch> fails, and L</RaiseError> is not set, | ||||
4158 | C<selectcol_arrayref> will return C<undef>. If C<fetch> fails and | ||||
4159 | L</RaiseError> is not set, then it will return with whatever data it | ||||
4160 | has fetched thus far. $DBI::err should be checked to catch that. | ||||
4161 | |||||
4162 | The C<selectcol_arrayref> method defaults to pushing a single column | ||||
4163 | value (the first) from each row into the result array. However, it can | ||||
4164 | also push another column, or even multiple columns per row, into the | ||||
4165 | result array. This behaviour can be specified via a 'C<Columns>' | ||||
4166 | attribute which must be a ref to an array containing the column number | ||||
4167 | or numbers to use. For example: | ||||
4168 | |||||
4169 | # get array of id and name pairs: | ||||
4170 | my $ary_ref = $dbh->selectcol_arrayref("select id, name from table", { Columns=>[1,2] }); | ||||
4171 | my %hash = @$ary_ref; # build hash from key-value pairs so $hash{$id} => name | ||||
4172 | |||||
4173 | You can specify a maximum number of rows to fetch by including a | ||||
4174 | 'C<MaxRows>' attribute in \%attr. | ||||
4175 | |||||
4176 | =item C<prepare> | ||||
4177 | |||||
4178 | $sth = $dbh->prepare($statement) or die $dbh->errstr; | ||||
4179 | $sth = $dbh->prepare($statement, \%attr) or die $dbh->errstr; | ||||
4180 | |||||
4181 | Prepares a statement for later execution by the database | ||||
4182 | engine and returns a reference to a statement handle object. | ||||
4183 | |||||
4184 | The returned statement handle can be used to get attributes of the | ||||
4185 | statement and invoke the L</execute> method. See L</Statement Handle Methods>. | ||||
4186 | |||||
4187 | Drivers for engines without the concept of preparing a | ||||
4188 | statement will typically just store the statement in the returned | ||||
4189 | handle and process it when C<$sth-E<gt>execute> is called. Such drivers are | ||||
4190 | unlikely to give much useful information about the | ||||
4191 | statement, such as C<$sth-E<gt>{NUM_OF_FIELDS}>, until after C<$sth-E<gt>execute> | ||||
4192 | has been called. Portable applications should take this into account. | ||||
4193 | |||||
4194 | In general, DBI drivers do not parse the contents of the statement | ||||
4195 | (other than simply counting any L</Placeholders>). The statement is | ||||
4196 | passed directly to the database engine, sometimes known as pass-thru | ||||
4197 | mode. This has advantages and disadvantages. On the plus side, you can | ||||
4198 | access all the functionality of the engine being used. On the downside, | ||||
4199 | you're limited if you're using a simple engine, and you need to take extra care if | ||||
4200 | writing applications intended to be portable between engines. | ||||
4201 | |||||
4202 | Portable applications should not assume that a new statement can be | ||||
4203 | prepared and/or executed while still fetching results from a previous | ||||
4204 | statement. | ||||
4205 | |||||
4206 | Some command-line SQL tools use statement terminators, like a semicolon, | ||||
4207 | to indicate the end of a statement. Such terminators should not normally | ||||
4208 | be used with the DBI. | ||||
4209 | |||||
4210 | |||||
4211 | =item C<prepare_cached> | ||||
4212 | |||||
4213 | $sth = $dbh->prepare_cached($statement) | ||||
4214 | $sth = $dbh->prepare_cached($statement, \%attr) | ||||
4215 | $sth = $dbh->prepare_cached($statement, \%attr, $if_active) | ||||
4216 | |||||
4217 | Like L</prepare> except that the statement handle returned will be | ||||
4218 | stored in a hash associated with the C<$dbh>. If another call is made to | ||||
4219 | C<prepare_cached> with the same C<$statement> and C<%attr> parameter values, | ||||
4220 | then the corresponding cached C<$sth> will be returned without contacting the | ||||
4221 | database server. | ||||
4222 | |||||
4223 | The C<$if_active> parameter lets you adjust the behaviour if an | ||||
4224 | already cached statement handle is still Active. There are several | ||||
4225 | alternatives: | ||||
4226 | |||||
4227 | =over 4 | ||||
4228 | |||||
4229 | =item B<0>: A warning will be generated, and finish() will be called on | ||||
4230 | the statement handle before it is returned. This is the default | ||||
4231 | behaviour if $if_active is not passed. | ||||
4232 | |||||
4233 | =item B<1>: finish() will be called on the statement handle, but the | ||||
4234 | warning is suppressed. | ||||
4235 | |||||
4236 | =item B<2>: Disables any checking. | ||||
4237 | |||||
4238 | =item B<3>: The existing active statement handle will be removed from the | ||||
4239 | cache and a new statement handle prepared and cached in its place. | ||||
4240 | This is the safest option because it doesn't affect the state of the | ||||
4241 | old handle, it just removes it from the cache. [Added in DBI 1.40] | ||||
4242 | |||||
4243 | =back | ||||
4244 | |||||
4245 | Here are some examples of C<prepare_cached>: | ||||
4246 | |||||
4247 | sub insert_hash { | ||||
4248 | my ($table, $field_values) = @_; | ||||
4249 | # sort to keep field order, and thus sql, stable for prepare_cached | ||||
4250 | my @fields = sort keys %$field_values; | ||||
4251 | my @values = @{$field_values}{@fields}; | ||||
4252 | my $sql = sprintf "insert into %s (%s) values (%s)", | ||||
4253 | $table, join(",", @fields), join(",", ("?")x@fields); | ||||
4254 | my $sth = $dbh->prepare_cached($sql); | ||||
4255 | return $sth->execute(@values); | ||||
4256 | } | ||||
4257 | |||||
4258 | sub search_hash { | ||||
4259 | my ($table, $field_values) = @_; | ||||
4260 | # sort to keep field order, and thus sql, stable for prepare_cached | ||||
4261 | my @fields = sort keys %$field_values; | ||||
4262 | my @values = @{$field_values}{@fields}; | ||||
4263 | my $qualifier = ""; | ||||
4264 | $qualifier = "where ".join(" and ", map { "$_=?" } @fields) if @fields; | ||||
4265 | $sth = $dbh->prepare_cached("SELECT * FROM $table $qualifier"); | ||||
4266 | return $dbh->selectall_arrayref($sth, {}, @values); | ||||
4267 | } | ||||
4268 | |||||
4269 | I<Caveat emptor:> This caching can be useful in some applications, | ||||
4270 | but it can also cause problems and should be used with care. Here | ||||
4271 | is a contrived case where caching would cause a significant problem: | ||||
4272 | |||||
4273 | my $sth = $dbh->prepare_cached('SELECT * FROM foo WHERE bar=?'); | ||||
4274 | $sth->execute(...); | ||||
4275 | while (my $data = $sth->fetchrow_hashref) { | ||||
4276 | |||||
4277 | # later, in some other code called within the loop... | ||||
4278 | my $sth2 = $dbh->prepare_cached('SELECT * FROM foo WHERE bar=?'); | ||||
4279 | $sth2->execute(...); | ||||
4280 | while (my $data2 = $sth2->fetchrow_arrayref) { | ||||
4281 | do_stuff(...); | ||||
4282 | } | ||||
4283 | } | ||||
4284 | |||||
4285 | In this example, since both handles are preparing the exact same statement, | ||||
4286 | C<$sth2> will not be its own statement handle, but a duplicate of C<$sth> | ||||
4287 | returned from the cache. The results will certainly not be what you expect. | ||||
4288 | Typically the the inner fetch loop will work normally, fetching all | ||||
4289 | the records and terminating when there are no more, but now $sth | ||||
4290 | is the same as $sth2 the outer fetch loop will also terminate. | ||||
4291 | |||||
4292 | You'll know if you run into this problem because prepare_cached() | ||||
4293 | will generate a warning by default (when $if_active is false). | ||||
4294 | |||||
4295 | The cache used by prepare_cached() is keyed by both the statement | ||||
4296 | and any attributes so you can also avoid this issue by doing something | ||||
4297 | like: | ||||
4298 | |||||
4299 | $sth = $dbh->prepare_cached("...", { dbi_dummy => __FILE__.__LINE__ }); | ||||
4300 | |||||
4301 | which will ensure that prepare_cached only returns statements cached | ||||
4302 | by that line of code in that source file. | ||||
4303 | |||||
4304 | If you'd like the cache to managed intelligently, you can tie the | ||||
4305 | hashref returned by C<CachedKids> to an appropriate caching module, | ||||
4306 | such as L<Tie::Cache::LRU>: | ||||
4307 | |||||
4308 | my $cache = $dbh->{CachedKids}; | ||||
4309 | tie %$cache, 'Tie::Cache::LRU', 500; | ||||
4310 | |||||
4311 | =item C<commit> | ||||
4312 | |||||
4313 | $rc = $dbh->commit or die $dbh->errstr; | ||||
4314 | |||||
4315 | Commit (make permanent) the most recent series of database changes | ||||
4316 | if the database supports transactions and AutoCommit is off. | ||||
4317 | |||||
4318 | If C<AutoCommit> is on, then calling | ||||
4319 | C<commit> will issue a "commit ineffective with AutoCommit" warning. | ||||
4320 | |||||
4321 | See also L</Transactions> in the L</FURTHER INFORMATION> section below. | ||||
4322 | |||||
4323 | =item C<rollback> | ||||
4324 | |||||
4325 | $rc = $dbh->rollback or die $dbh->errstr; | ||||
4326 | |||||
4327 | Rollback (undo) the most recent series of uncommitted database | ||||
4328 | changes if the database supports transactions and AutoCommit is off. | ||||
4329 | |||||
4330 | If C<AutoCommit> is on, then calling | ||||
4331 | C<rollback> will issue a "rollback ineffective with AutoCommit" warning. | ||||
4332 | |||||
4333 | See also L</Transactions> in the L</FURTHER INFORMATION> section below. | ||||
4334 | |||||
4335 | =item C<begin_work> | ||||
4336 | |||||
4337 | $rc = $dbh->begin_work or die $dbh->errstr; | ||||
4338 | |||||
4339 | Enable transactions (by turning C<AutoCommit> off) until the next call | ||||
4340 | to C<commit> or C<rollback>. After the next C<commit> or C<rollback>, | ||||
4341 | C<AutoCommit> will automatically be turned on again. | ||||
4342 | |||||
4343 | If C<AutoCommit> is already off when C<begin_work> is called then | ||||
4344 | it does nothing except return an error. If the driver does not support | ||||
4345 | transactions then when C<begin_work> attempts to set C<AutoCommit> off | ||||
4346 | the driver will trigger a fatal error. | ||||
4347 | |||||
4348 | See also L</Transactions> in the L</FURTHER INFORMATION> section below. | ||||
4349 | |||||
4350 | |||||
4351 | =item C<disconnect> | ||||
4352 | |||||
4353 | $rc = $dbh->disconnect or warn $dbh->errstr; | ||||
4354 | |||||
4355 | Disconnects the database from the database handle. C<disconnect> is typically only used | ||||
4356 | before exiting the program. The handle is of little use after disconnecting. | ||||
4357 | |||||
4358 | The transaction behaviour of the C<disconnect> method is, sadly, | ||||
4359 | undefined. Some database systems (such as Oracle and Ingres) will | ||||
4360 | automatically commit any outstanding changes, but others (such as | ||||
4361 | Informix) will rollback any outstanding changes. Applications not | ||||
4362 | using C<AutoCommit> should explicitly call C<commit> or C<rollback> before | ||||
4363 | calling C<disconnect>. | ||||
4364 | |||||
4365 | The database is automatically disconnected by the C<DESTROY> method if | ||||
4366 | still connected when there are no longer any references to the handle. | ||||
4367 | The C<DESTROY> method for each driver should implicitly call C<rollback> to | ||||
4368 | undo any uncommitted changes. This is vital behaviour to ensure that | ||||
4369 | incomplete transactions don't get committed simply because Perl calls | ||||
4370 | C<DESTROY> on every object before exiting. Also, do not rely on the order | ||||
4371 | of object destruction during "global destruction", as it is undefined. | ||||
4372 | |||||
4373 | Generally, if you want your changes to be commited or rolled back when | ||||
4374 | you disconnect, then you should explicitly call L</commit> or L</rollback> | ||||
4375 | before disconnecting. | ||||
4376 | |||||
4377 | If you disconnect from a database while you still have active | ||||
4378 | statement handles (e.g., SELECT statement handles that may have | ||||
4379 | more data to fetch), you will get a warning. The warning may indicate | ||||
4380 | that a fetch loop terminated early, perhaps due to an uncaught error. | ||||
4381 | To avoid the warning call the C<finish> method on the active handles. | ||||
4382 | |||||
4383 | |||||
4384 | =item C<ping> | ||||
4385 | |||||
4386 | $rc = $dbh->ping; | ||||
4387 | |||||
4388 | Attempts to determine, in a reasonably efficient way, if the database | ||||
4389 | server is still running and the connection to it is still working. | ||||
4390 | Individual drivers should implement this function in the most suitable | ||||
4391 | manner for their database engine. | ||||
4392 | |||||
4393 | The current I<default> implementation always returns true without | ||||
4394 | actually doing anything. Actually, it returns "C<0 but true>" which is | ||||
4395 | true but zero. That way you can tell if the return value is genuine or | ||||
4396 | just the default. Drivers should override this method with one that | ||||
4397 | does the right thing for their type of database. | ||||
4398 | |||||
4399 | Few applications would have direct use for this method. See the specialized | ||||
4400 | Apache::DBI module for one example usage. | ||||
4401 | |||||
4402 | |||||
4403 | =item C<get_info> | ||||
4404 | |||||
4405 | $value = $dbh->get_info( $info_type ); | ||||
4406 | |||||
4407 | Returns information about the implementation, i.e. driver and data | ||||
4408 | source capabilities, restrictions etc. It returns C<undef> for | ||||
4409 | unknown or unimplemented information types. For example: | ||||
4410 | |||||
4411 | $database_version = $dbh->get_info( 18 ); # SQL_DBMS_VER | ||||
4412 | $max_select_tables = $dbh->get_info( 106 ); # SQL_MAXIMUM_TABLES_IN_SELECT | ||||
4413 | |||||
4414 | See L</"Standards Reference Information"> for more detailed information | ||||
4415 | about the information types and their meanings and possible return values. | ||||
4416 | |||||
4417 | The DBI::Const::GetInfoType module exports a %GetInfoType hash that | ||||
4418 | can be used to map info type names to numbers. For example: | ||||
4419 | |||||
4420 | $database_version = $dbh->get_info( $GetInfoType{SQL_DBMS_VER} ); | ||||
4421 | |||||
4422 | The names are a merging of the ANSI and ODBC standards (which differ | ||||
4423 | in some cases). See L<DBI::Const::GetInfoType> for more details. | ||||
4424 | |||||
4425 | Because some DBI methods make use of get_info(), drivers are strongly | ||||
4426 | encouraged to support I<at least> the following very minimal set | ||||
4427 | of information types to ensure the DBI itself works properly: | ||||
4428 | |||||
4429 | Type Name Example A Example B | ||||
4430 | ---- -------------------------- ------------ ---------------- | ||||
4431 | 17 SQL_DBMS_NAME 'ACCESS' 'Oracle' | ||||
4432 | 18 SQL_DBMS_VER '03.50.0000' '08.01.0721 ...' | ||||
4433 | 29 SQL_IDENTIFIER_QUOTE_CHAR '`' '"' | ||||
4434 | 41 SQL_CATALOG_NAME_SEPARATOR '.' '@' | ||||
4435 | 114 SQL_CATALOG_LOCATION 1 2 | ||||
4436 | |||||
4437 | =item C<table_info> | ||||
4438 | |||||
4439 | $sth = $dbh->table_info( $catalog, $schema, $table, $type ); | ||||
4440 | $sth = $dbh->table_info( $catalog, $schema, $table, $type, \%attr ); | ||||
4441 | |||||
4442 | # then $sth->fetchall_arrayref or $sth->fetchall_hashref etc | ||||
4443 | |||||
4444 | Returns an active statement handle that can be used to fetch | ||||
4445 | information about tables and views that exist in the database. | ||||
4446 | |||||
4447 | The arguments $catalog, $schema and $table may accept search patterns | ||||
4448 | according to the database/driver, for example: $table = '%FOO%'; | ||||
4449 | Remember that the underscore character ('C<_>') is a search pattern | ||||
4450 | that means match any character, so 'FOO_%' is the same as 'FOO%' | ||||
4451 | and 'FOO_BAR%' will match names like 'FOO1BAR'. | ||||
4452 | |||||
4453 | The value of $type is a comma-separated list of one or more types of | ||||
4454 | tables to be returned in the result set. Each value may optionally be | ||||
4455 | quoted, e.g.: | ||||
4456 | |||||
4457 | $type = "TABLE"; | ||||
4458 | $type = "'TABLE','VIEW'"; | ||||
4459 | |||||
4460 | In addition the following special cases may also be supported by some drivers: | ||||
4461 | |||||
4462 | =over 4 | ||||
4463 | |||||
4464 | =item * | ||||
4465 | If the value of $catalog is '%' and $schema and $table name | ||||
4466 | are empty strings, the result set contains a list of catalog names. | ||||
4467 | For example: | ||||
4468 | |||||
4469 | $sth = $dbh->table_info('%', '', ''); | ||||
4470 | |||||
4471 | =item * | ||||
4472 | If the value of $schema is '%' and $catalog and $table are empty | ||||
4473 | strings, the result set contains a list of schema names. | ||||
4474 | |||||
4475 | =item * | ||||
4476 | If the value of $type is '%' and $catalog, $schema, and $table are all | ||||
4477 | empty strings, the result set contains a list of table types. | ||||
4478 | |||||
4479 | =back | ||||
4480 | |||||
4481 | If your driver doesn't support one or more of the selection filter | ||||
4482 | parameters then you may get back more than you asked for and can | ||||
4483 | do the filtering yourself. | ||||
4484 | |||||
4485 | This method can be expensive, and can return a large amount of data. | ||||
4486 | (For example, small Oracle installation returns over 2000 rows.) | ||||
4487 | So it's a good idea to use the filters to limit the data as much as possible. | ||||
4488 | |||||
4489 | The statement handle returned has at least the following fields in the | ||||
4490 | order show below. Other fields, after these, may also be present. | ||||
4491 | |||||
4492 | B<TABLE_CAT>: Table catalog identifier. This field is NULL (C<undef>) if not | ||||
4493 | applicable to the data source, which is usually the case. This field | ||||
4494 | is empty if not applicable to the table. | ||||
4495 | |||||
4496 | B<TABLE_SCHEM>: The name of the schema containing the TABLE_NAME value. | ||||
4497 | This field is NULL (C<undef>) if not applicable to data source, and | ||||
4498 | empty if not applicable to the table. | ||||
4499 | |||||
4500 | B<TABLE_NAME>: Name of the table (or view, synonym, etc). | ||||
4501 | |||||
4502 | B<TABLE_TYPE>: One of the following: "TABLE", "VIEW", "SYSTEM TABLE", | ||||
4503 | "GLOBAL TEMPORARY", "LOCAL TEMPORARY", "ALIAS", "SYNONYM" or a type | ||||
4504 | identifier that is specific to the data | ||||
4505 | source. | ||||
4506 | |||||
4507 | B<REMARKS>: A description of the table. May be NULL (C<undef>). | ||||
4508 | |||||
4509 | Note that C<table_info> might not return records for all tables. | ||||
4510 | Applications can use any valid table regardless of whether it's | ||||
4511 | returned by C<table_info>. | ||||
4512 | |||||
4513 | See also L</tables>, L</"Catalog Methods"> and | ||||
4514 | L</"Standards Reference Information">. | ||||
4515 | |||||
4516 | =item C<column_info> | ||||
4517 | |||||
4518 | $sth = $dbh->column_info( $catalog, $schema, $table, $column ); | ||||
4519 | |||||
4520 | # then $sth->fetchall_arrayref or $sth->fetchall_hashref etc | ||||
4521 | |||||
4522 | Returns an active statement handle that can be used to fetch | ||||
4523 | information about columns in specified tables. | ||||
4524 | |||||
4525 | The arguments $schema, $table and $column may accept search patterns | ||||
4526 | according to the database/driver, for example: $table = '%FOO%'; | ||||
4527 | |||||
4528 | Note: The support for the selection criteria is driver specific. If the | ||||
4529 | driver doesn't support one or more of them then you may get back more | ||||
4530 | than you asked for and can do the filtering yourself. | ||||
4531 | |||||
4532 | If the arguments don't match any tables then you'll still get a statement | ||||
4533 | handle, it'll just return no rows. | ||||
4534 | |||||
4535 | The statement handle returned has at least the following fields in the | ||||
4536 | order shown below. Other fields, after these, may also be present. | ||||
4537 | |||||
4538 | B<TABLE_CAT>: The catalog identifier. | ||||
4539 | This field is NULL (C<undef>) if not applicable to the data source, | ||||
4540 | which is often the case. This field is empty if not applicable to the | ||||
4541 | table. | ||||
4542 | |||||
4543 | B<TABLE_SCHEM>: The schema identifier. | ||||
4544 | This field is NULL (C<undef>) if not applicable to the data source, | ||||
4545 | and empty if not applicable to the table. | ||||
4546 | |||||
4547 | B<TABLE_NAME>: The table identifier. | ||||
4548 | Note: A driver may provide column metadata not only for base tables, but | ||||
4549 | also for derived objects like SYNONYMS etc. | ||||
4550 | |||||
4551 | B<COLUMN_NAME>: The column identifier. | ||||
4552 | |||||
4553 | B<DATA_TYPE>: The concise data type code. | ||||
4554 | |||||
4555 | B<TYPE_NAME>: A data source dependent data type name. | ||||
4556 | |||||
4557 | B<COLUMN_SIZE>: The column size. | ||||
4558 | This is the maximum length in characters for character data types, | ||||
4559 | the number of digits or bits for numeric data types or the length | ||||
4560 | in the representation of temporal types. | ||||
4561 | See the relevant specifications for detailed information. | ||||
4562 | |||||
4563 | B<BUFFER_LENGTH>: The length in bytes of transferred data. | ||||
4564 | |||||
4565 | B<DECIMAL_DIGITS>: The total number of significant digits to the right of | ||||
4566 | the decimal point. | ||||
4567 | |||||
4568 | B<NUM_PREC_RADIX>: The radix for numeric precision. | ||||
4569 | The value is 10 or 2 for numeric data types and NULL (C<undef>) if not | ||||
4570 | applicable. | ||||
4571 | |||||
4572 | B<NULLABLE>: Indicates if a column can accept NULLs. | ||||
4573 | The following values are defined: | ||||
4574 | |||||
4575 | SQL_NO_NULLS 0 | ||||
4576 | SQL_NULLABLE 1 | ||||
4577 | SQL_NULLABLE_UNKNOWN 2 | ||||
4578 | |||||
4579 | B<REMARKS>: A description of the column. | ||||
4580 | |||||
4581 | B<COLUMN_DEF>: The default value of the column. | ||||
4582 | |||||
4583 | B<SQL_DATA_TYPE>: The SQL data type. | ||||
4584 | |||||
4585 | B<SQL_DATETIME_SUB>: The subtype code for datetime and interval data types. | ||||
4586 | |||||
4587 | B<CHAR_OCTET_LENGTH>: The maximum length in bytes of a character or binary | ||||
4588 | data type column. | ||||
4589 | |||||
4590 | B<ORDINAL_POSITION>: The column sequence number (starting with 1). | ||||
4591 | |||||
4592 | B<IS_NULLABLE>: Indicates if the column can accept NULLs. | ||||
4593 | Possible values are: 'NO', 'YES' and ''. | ||||
4594 | |||||
4595 | SQL/CLI defines the following additional columns: | ||||
4596 | |||||
4597 | CHAR_SET_CAT | ||||
4598 | CHAR_SET_SCHEM | ||||
4599 | CHAR_SET_NAME | ||||
4600 | COLLATION_CAT | ||||
4601 | COLLATION_SCHEM | ||||
4602 | COLLATION_NAME | ||||
4603 | UDT_CAT | ||||
4604 | UDT_SCHEM | ||||
4605 | UDT_NAME | ||||
4606 | DOMAIN_CAT | ||||
4607 | DOMAIN_SCHEM | ||||
4608 | DOMAIN_NAME | ||||
4609 | SCOPE_CAT | ||||
4610 | SCOPE_SCHEM | ||||
4611 | SCOPE_NAME | ||||
4612 | MAX_CARDINALITY | ||||
4613 | DTD_IDENTIFIER | ||||
4614 | IS_SELF_REF | ||||
4615 | |||||
4616 | Drivers capable of supplying any of those values should do so in | ||||
4617 | the corresponding column and supply undef values for the others. | ||||
4618 | |||||
4619 | Drivers wishing to provide extra database/driver specific information | ||||
4620 | should do so in extra columns beyond all those listed above, and | ||||
4621 | use lowercase field names with the driver-specific prefix (i.e., | ||||
4622 | 'ora_...'). Applications accessing such fields should do so by name | ||||
4623 | and not by column number. | ||||
4624 | |||||
4625 | The result set is ordered by TABLE_CAT, TABLE_SCHEM, TABLE_NAME | ||||
4626 | and ORDINAL_POSITION. | ||||
4627 | |||||
4628 | Note: There is some overlap with statement attributes (in perl) and | ||||
4629 | SQLDescribeCol (in ODBC). However, SQLColumns provides more metadata. | ||||
4630 | |||||
4631 | See also L</"Catalog Methods"> and L</"Standards Reference Information">. | ||||
4632 | |||||
4633 | =item C<primary_key_info> | ||||
4634 | |||||
4635 | $sth = $dbh->primary_key_info( $catalog, $schema, $table ); | ||||
4636 | |||||
4637 | # then $sth->fetchall_arrayref or $sth->fetchall_hashref etc | ||||
4638 | |||||
4639 | Returns an active statement handle that can be used to fetch information | ||||
4640 | about columns that make up the primary key for a table. | ||||
4641 | The arguments don't accept search patterns (unlike table_info()). | ||||
4642 | |||||
4643 | The statement handle will return one row per column, ordered by | ||||
4644 | TABLE_CAT, TABLE_SCHEM, TABLE_NAME, and KEY_SEQ. | ||||
4645 | If there is no primary key then the statement handle will fetch no rows. | ||||
4646 | |||||
4647 | Note: The support for the selection criteria, such as $catalog, is | ||||
4648 | driver specific. If the driver doesn't support catalogs and/or | ||||
4649 | schemas, it may ignore these criteria. | ||||
4650 | |||||
4651 | The statement handle returned has at least the following fields in the | ||||
4652 | order shown below. Other fields, after these, may also be present. | ||||
4653 | |||||
4654 | B<TABLE_CAT>: The catalog identifier. | ||||
4655 | This field is NULL (C<undef>) if not applicable to the data source, | ||||
4656 | which is often the case. This field is empty if not applicable to the | ||||
4657 | table. | ||||
4658 | |||||
4659 | B<TABLE_SCHEM>: The schema identifier. | ||||
4660 | This field is NULL (C<undef>) if not applicable to the data source, | ||||
4661 | and empty if not applicable to the table. | ||||
4662 | |||||
4663 | B<TABLE_NAME>: The table identifier. | ||||
4664 | |||||
4665 | B<COLUMN_NAME>: The column identifier. | ||||
4666 | |||||
4667 | B<KEY_SEQ>: The column sequence number (starting with 1). | ||||
4668 | Note: This field is named B<ORDINAL_POSITION> in SQL/CLI. | ||||
4669 | |||||
4670 | B<PK_NAME>: The primary key constraint identifier. | ||||
4671 | This field is NULL (C<undef>) if not applicable to the data source. | ||||
4672 | |||||
4673 | See also L</"Catalog Methods"> and L</"Standards Reference Information">. | ||||
4674 | |||||
4675 | =item C<primary_key> | ||||
4676 | |||||
4677 | @key_column_names = $dbh->primary_key( $catalog, $schema, $table ); | ||||
4678 | |||||
4679 | Simple interface to the primary_key_info() method. Returns a list of | ||||
4680 | the column names that comprise the primary key of the specified table. | ||||
4681 | The list is in primary key column sequence order. | ||||
4682 | If there is no primary key then an empty list is returned. | ||||
4683 | |||||
4684 | =item C<foreign_key_info> | ||||
4685 | |||||
4686 | $sth = $dbh->foreign_key_info( $pk_catalog, $pk_schema, $pk_table | ||||
4687 | , $fk_catalog, $fk_schema, $fk_table ); | ||||
4688 | |||||
4689 | $sth = $dbh->foreign_key_info( $pk_catalog, $pk_schema, $pk_table | ||||
4690 | , $fk_catalog, $fk_schema, $fk_table | ||||
4691 | , \%attr ); | ||||
4692 | |||||
4693 | # then $sth->fetchall_arrayref or $sth->fetchall_hashref etc | ||||
4694 | |||||
4695 | Returns an active statement handle that can be used to fetch information | ||||
4696 | about foreign keys in and/or referencing the specified table(s). | ||||
4697 | The arguments don't accept search patterns (unlike table_info()). | ||||
4698 | |||||
4699 | C<$pk_catalog>, C<$pk_schema>, C<$pk_table> | ||||
4700 | identify the primary (unique) key table (B<PKT>). | ||||
4701 | |||||
4702 | C<$fk_catalog>, C<$fk_schema>, C<$fk_table> | ||||
4703 | identify the foreign key table (B<FKT>). | ||||
4704 | |||||
4705 | If both B<PKT> and B<FKT> are given, the function returns the foreign key, if | ||||
4706 | any, in table B<FKT> that refers to the primary (unique) key of table B<PKT>. | ||||
4707 | (Note: In SQL/CLI, the result is implementation-defined.) | ||||
4708 | |||||
4709 | If only B<PKT> is given, then the result set contains the primary key | ||||
4710 | of that table and all foreign keys that refer to it. | ||||
4711 | |||||
4712 | If only B<FKT> is given, then the result set contains all foreign keys | ||||
4713 | in that table and the primary keys to which they refer. | ||||
4714 | (Note: In SQL/CLI, the result includes unique keys too.) | ||||
4715 | |||||
4716 | For example: | ||||
4717 | |||||
4718 | $sth = $dbh->foreign_key_info( undef, $user, 'master'); | ||||
4719 | $sth = $dbh->foreign_key_info( undef, undef, undef , undef, $user, 'detail'); | ||||
4720 | $sth = $dbh->foreign_key_info( undef, $user, 'master', undef, $user, 'detail'); | ||||
4721 | |||||
4722 | # then $sth->fetchall_arrayref or $sth->fetchall_hashref etc | ||||
4723 | |||||
4724 | Note: The support for the selection criteria, such as C<$catalog>, is | ||||
4725 | driver specific. If the driver doesn't support catalogs and/or | ||||
4726 | schemas, it may ignore these criteria. | ||||
4727 | |||||
4728 | The statement handle returned has the following fields in the order shown below. | ||||
4729 | Because ODBC never includes unique keys, they define different columns in the | ||||
4730 | result set than SQL/CLI. SQL/CLI column names are shown in parentheses. | ||||
4731 | |||||
4732 | B<PKTABLE_CAT ( UK_TABLE_CAT )>: | ||||
4733 | The primary (unique) key table catalog identifier. | ||||
4734 | This field is NULL (C<undef>) if not applicable to the data source, | ||||
4735 | which is often the case. This field is empty if not applicable to the | ||||
4736 | table. | ||||
4737 | |||||
4738 | B<PKTABLE_SCHEM ( UK_TABLE_SCHEM )>: | ||||
4739 | The primary (unique) key table schema identifier. | ||||
4740 | This field is NULL (C<undef>) if not applicable to the data source, | ||||
4741 | and empty if not applicable to the table. | ||||
4742 | |||||
4743 | B<PKTABLE_NAME ( UK_TABLE_NAME )>: | ||||
4744 | The primary (unique) key table identifier. | ||||
4745 | |||||
4746 | B<PKCOLUMN_NAME (UK_COLUMN_NAME )>: | ||||
4747 | The primary (unique) key column identifier. | ||||
4748 | |||||
4749 | B<FKTABLE_CAT ( FK_TABLE_CAT )>: | ||||
4750 | The foreign key table catalog identifier. | ||||
4751 | This field is NULL (C<undef>) if not applicable to the data source, | ||||
4752 | which is often the case. This field is empty if not applicable to the | ||||
4753 | table. | ||||
4754 | |||||
4755 | B<FKTABLE_SCHEM ( FK_TABLE_SCHEM )>: | ||||
4756 | The foreign key table schema identifier. | ||||
4757 | This field is NULL (C<undef>) if not applicable to the data source, | ||||
4758 | and empty if not applicable to the table. | ||||
4759 | |||||
4760 | B<FKTABLE_NAME ( FK_TABLE_NAME )>: | ||||
4761 | The foreign key table identifier. | ||||
4762 | |||||
4763 | B<FKCOLUMN_NAME ( FK_COLUMN_NAME )>: | ||||
4764 | The foreign key column identifier. | ||||
4765 | |||||
4766 | B<KEY_SEQ ( ORDINAL_POSITION )>: | ||||
4767 | The column sequence number (starting with 1). | ||||
4768 | |||||
4769 | B<UPDATE_RULE ( UPDATE_RULE )>: | ||||
4770 | The referential action for the UPDATE rule. | ||||
4771 | The following codes are defined: | ||||
4772 | |||||
4773 | CASCADE 0 | ||||
4774 | RESTRICT 1 | ||||
4775 | SET NULL 2 | ||||
4776 | NO ACTION 3 | ||||
4777 | SET DEFAULT 4 | ||||
4778 | |||||
4779 | B<DELETE_RULE ( DELETE_RULE )>: | ||||
4780 | The referential action for the DELETE rule. | ||||
4781 | The codes are the same as for UPDATE_RULE. | ||||
4782 | |||||
4783 | B<FK_NAME ( FK_NAME )>: | ||||
4784 | The foreign key name. | ||||
4785 | |||||
4786 | B<PK_NAME ( UK_NAME )>: | ||||
4787 | The primary (unique) key name. | ||||
4788 | |||||
4789 | B<DEFERRABILITY ( DEFERABILITY )>: | ||||
4790 | The deferrability of the foreign key constraint. | ||||
4791 | The following codes are defined: | ||||
4792 | |||||
4793 | INITIALLY DEFERRED 5 | ||||
4794 | INITIALLY IMMEDIATE 6 | ||||
4795 | NOT DEFERRABLE 7 | ||||
4796 | |||||
4797 | B< ( UNIQUE_OR_PRIMARY )>: | ||||
4798 | This column is necessary if a driver includes all candidate (i.e. primary and | ||||
4799 | alternate) keys in the result set (as specified by SQL/CLI). | ||||
4800 | The value of this column is UNIQUE if the foreign key references an alternate | ||||
4801 | key and PRIMARY if the foreign key references a primary key, or it | ||||
4802 | may be undefined if the driver doesn't have access to the information. | ||||
4803 | |||||
4804 | See also L</"Catalog Methods"> and L</"Standards Reference Information">. | ||||
4805 | |||||
4806 | =item C<statistics_info> | ||||
4807 | |||||
4808 | B<Warning:> This method is experimental and may change. | ||||
4809 | |||||
4810 | $sth = $dbh->statistics_info( $catalog, $schema, $table, $unique_only, $quick ); | ||||
4811 | |||||
4812 | # then $sth->fetchall_arrayref or $sth->fetchall_hashref etc | ||||
4813 | |||||
4814 | Returns an active statement handle that can be used to fetch statistical | ||||
4815 | information about a table and its indexes. | ||||
4816 | |||||
4817 | The arguments don't accept search patterns (unlike L</table_info>). | ||||
4818 | |||||
4819 | If the boolean argument $unique_only is true, only UNIQUE indexes will be | ||||
4820 | returned in the result set, otherwise all indexes will be returned. | ||||
4821 | |||||
4822 | If the boolean argument $quick is set, the actual statistical information | ||||
4823 | columns (CARDINALITY and PAGES) will only be returned if they are readily | ||||
4824 | available from the server, and might not be current. Some databases may | ||||
4825 | return stale statistics or no statistics at all with this flag set. | ||||
4826 | |||||
4827 | The statement handle will return at most one row per column name per index, | ||||
4828 | plus at most one row for the entire table itself, ordered by NON_UNIQUE, TYPE, | ||||
4829 | INDEX_QUALIFIER, INDEX_NAME, and ORDINAL_POSITION. | ||||
4830 | |||||
4831 | Note: The support for the selection criteria, such as $catalog, is | ||||
4832 | driver specific. If the driver doesn't support catalogs and/or | ||||
4833 | schemas, it may ignore these criteria. | ||||
4834 | |||||
4835 | The statement handle returned has at least the following fields in the | ||||
4836 | order shown below. Other fields, after these, may also be present. | ||||
4837 | |||||
4838 | B<TABLE_CAT>: The catalog identifier. | ||||
4839 | This field is NULL (C<undef>) if not applicable to the data source, | ||||
4840 | which is often the case. This field is empty if not applicable to the | ||||
4841 | table. | ||||
4842 | |||||
4843 | B<TABLE_SCHEM>: The schema identifier. | ||||
4844 | This field is NULL (C<undef>) if not applicable to the data source, | ||||
4845 | and empty if not applicable to the table. | ||||
4846 | |||||
4847 | B<TABLE_NAME>: The table identifier. | ||||
4848 | |||||
4849 | B<NON_UNIQUE>: Unique index indicator. | ||||
4850 | Returns 0 for unique indexes, 1 for non-unique indexes | ||||
4851 | |||||
4852 | B<INDEX_QUALIFIER>: Index qualifier identifier. | ||||
4853 | The identifier that is used to qualify the index name when doing a | ||||
4854 | C<DROP INDEX>; NULL (C<undef>) is returned if an index qualifier is not | ||||
4855 | supported by the data source. | ||||
4856 | If a non-NULL (defined) value is returned in this column, it must be used | ||||
4857 | to qualify the index name on a C<DROP INDEX> statement; otherwise, | ||||
4858 | the TABLE_SCHEM should be used to qualify the index name. | ||||
4859 | |||||
4860 | B<INDEX_NAME>: The index identifier. | ||||
4861 | |||||
4862 | B<TYPE>: The type of information being returned. Can be any of the | ||||
4863 | following values: 'table', 'btree', 'clustered', 'content', 'hashed', | ||||
4864 | or 'other'. | ||||
4865 | |||||
4866 | In the case that this field is 'table', all fields | ||||
4867 | other than TABLE_CAT, TABLE_SCHEM, TABLE_NAME, TYPE, | ||||
4868 | CARDINALITY, and PAGES will be NULL (C<undef>). | ||||
4869 | |||||
4870 | B<ORDINAL_POSITION>: Column sequence number (starting with 1). | ||||
4871 | |||||
4872 | B<COLUMN_NAME>: The column identifier. | ||||
4873 | |||||
4874 | B<ASC_OR_DESC>: Column sort sequence. | ||||
4875 | C<A> for Ascending, C<D> for Descending, or NULL (C<undef>) if | ||||
4876 | not supported for this index. | ||||
4877 | |||||
4878 | B<CARDINALITY>: Cardinality of the table or index. | ||||
4879 | For indexes, this is the number of unique values in the index. | ||||
4880 | For tables, this is the number of rows in the table. | ||||
4881 | If not supported, the value will be NULL (C<undef>). | ||||
4882 | |||||
4883 | B<PAGES>: Number of storage pages used by this table or index. | ||||
4884 | If not supported, the value will be NULL (C<undef>). | ||||
4885 | |||||
4886 | B<FILTER_CONDITION>: The index filter condition as a string. | ||||
4887 | If the index is not a filtered index, or it cannot be determined | ||||
4888 | whether the index is a filtered index, this value is NULL (C<undef>). | ||||
4889 | If the index is a filtered index, but the filter condition | ||||
4890 | cannot be determined, this value is the empty string C<''>. | ||||
4891 | Otherwise it will be the literal filter condition as a string, | ||||
4892 | such as C<SALARY <= 4500>. | ||||
4893 | |||||
4894 | See also L</"Catalog Methods"> and L</"Standards Reference Information">. | ||||
4895 | |||||
4896 | =item C<tables> | ||||
4897 | |||||
4898 | @names = $dbh->tables( $catalog, $schema, $table, $type ); | ||||
4899 | @names = $dbh->tables; # deprecated | ||||
4900 | |||||
4901 | Simple interface to table_info(). Returns a list of matching | ||||
4902 | table names, possibly including a catalog/schema prefix. | ||||
4903 | |||||
4904 | See L</table_info> for a description of the parameters. | ||||
4905 | |||||
4906 | If C<$dbh-E<gt>get_info(29)> returns true (29 is SQL_IDENTIFIER_QUOTE_CHAR) | ||||
4907 | then the table names are constructed and quoted by L</quote_identifier> | ||||
4908 | to ensure they are usable even if they contain whitespace or reserved | ||||
4909 | words etc. This means that the table names returned will include | ||||
4910 | quote characters. | ||||
4911 | |||||
4912 | =item C<type_info_all> | ||||
4913 | |||||
4914 | $type_info_all = $dbh->type_info_all; | ||||
4915 | |||||
4916 | Returns a reference to an array which holds information about each data | ||||
4917 | type variant supported by the database and driver. The array and its | ||||
4918 | contents should be treated as read-only. | ||||
4919 | |||||
4920 | The first item is a reference to an 'index' hash of C<Name =>E<gt> C<Index> pairs. | ||||
4921 | The items following that are references to arrays, one per supported data | ||||
4922 | type variant. The leading index hash defines the names and order of the | ||||
4923 | fields within the arrays that follow it. | ||||
4924 | For example: | ||||
4925 | |||||
4926 | $type_info_all = [ | ||||
4927 | { TYPE_NAME => 0, | ||||
4928 | DATA_TYPE => 1, | ||||
4929 | COLUMN_SIZE => 2, # was PRECISION originally | ||||
4930 | LITERAL_PREFIX => 3, | ||||
4931 | LITERAL_SUFFIX => 4, | ||||
4932 | CREATE_PARAMS => 5, | ||||
4933 | NULLABLE => 6, | ||||
4934 | CASE_SENSITIVE => 7, | ||||
4935 | SEARCHABLE => 8, | ||||
4936 | UNSIGNED_ATTRIBUTE=> 9, | ||||
4937 | FIXED_PREC_SCALE => 10, # was MONEY originally | ||||
4938 | AUTO_UNIQUE_VALUE => 11, # was AUTO_INCREMENT originally | ||||
4939 | LOCAL_TYPE_NAME => 12, | ||||
4940 | MINIMUM_SCALE => 13, | ||||
4941 | MAXIMUM_SCALE => 14, | ||||
4942 | SQL_DATA_TYPE => 15, | ||||
4943 | SQL_DATETIME_SUB => 16, | ||||
4944 | NUM_PREC_RADIX => 17, | ||||
4945 | INTERVAL_PRECISION=> 18, | ||||
4946 | }, | ||||
4947 | [ 'VARCHAR', SQL_VARCHAR, | ||||
4948 | undef, "'","'", undef,0, 1,1,0,0,0,undef,1,255, undef | ||||
4949 | ], | ||||
4950 | [ 'INTEGER', SQL_INTEGER, | ||||
4951 | undef, "", "", undef,0, 0,1,0,0,0,undef,0, 0, 10 | ||||
4952 | ], | ||||
4953 | ]; | ||||
4954 | |||||
4955 | More than one row may have the same value in the C<DATA_TYPE> | ||||
4956 | field if there are different ways to spell the type name and/or there | ||||
4957 | are variants of the type with different attributes (e.g., with and | ||||
4958 | without C<AUTO_UNIQUE_VALUE> set, with and without C<UNSIGNED_ATTRIBUTE>, etc). | ||||
4959 | |||||
4960 | The rows are ordered by C<DATA_TYPE> first and then by how closely each | ||||
4961 | type maps to the corresponding ODBC SQL data type, closest first. | ||||
4962 | |||||
4963 | The meaning of the fields is described in the documentation for | ||||
4964 | the L</type_info> method. | ||||
4965 | |||||
4966 | An 'index' hash is provided so you don't need to rely on index | ||||
4967 | values defined above. However, using DBD::ODBC with some old ODBC | ||||
4968 | drivers may return older names, shown as comments in the example above. | ||||
4969 | Another issue with the index hash is that the lettercase of the | ||||
4970 | keys is not defined. It is usually uppercase, as show here, but | ||||
4971 | drivers may return names with any lettercase. | ||||
4972 | |||||
4973 | Drivers are also free to return extra driver-specific columns of | ||||
4974 | information - though it's recommended that they start at column | ||||
4975 | index 50 to leave room for expansion of the DBI/ODBC specification. | ||||
4976 | |||||
4977 | The type_info_all() method is not normally used directly. | ||||
4978 | The L</type_info> method provides a more usable and useful interface | ||||
4979 | to the data. | ||||
4980 | |||||
4981 | =item C<type_info> | ||||
4982 | |||||
4983 | @type_info = $dbh->type_info($data_type); | ||||
4984 | |||||
4985 | Returns a list of hash references holding information about one or more | ||||
4986 | variants of $data_type. The list is ordered by C<DATA_TYPE> first and | ||||
4987 | then by how closely each type maps to the corresponding ODBC SQL data | ||||
4988 | type, closest first. If called in a scalar context then only the first | ||||
4989 | (best) element is returned. | ||||
4990 | |||||
4991 | If $data_type is undefined or C<SQL_ALL_TYPES>, then the list will | ||||
4992 | contain hashes for all data type variants supported by the database and driver. | ||||
4993 | |||||
4994 | If $data_type is an array reference then C<type_info> returns the | ||||
4995 | information for the I<first> type in the array that has any matches. | ||||
4996 | |||||
4997 | The keys of the hash follow the same letter case conventions as the | ||||
4998 | rest of the DBI (see L</Naming Conventions and Name Space>). The | ||||
4999 | following uppercase items should always exist, though may be undef: | ||||
5000 | |||||
5001 | =over 4 | ||||
5002 | |||||
5003 | =item TYPE_NAME (string) | ||||
5004 | |||||
5005 | Data type name for use in CREATE TABLE statements etc. | ||||
5006 | |||||
5007 | =item DATA_TYPE (integer) | ||||
5008 | |||||
5009 | SQL data type number. | ||||
5010 | |||||
5011 | =item COLUMN_SIZE (integer) | ||||
5012 | |||||
5013 | For numeric types, this is either the total number of digits (if the | ||||
5014 | NUM_PREC_RADIX value is 10) or the total number of bits allowed in the | ||||
5015 | column (if NUM_PREC_RADIX is 2). | ||||
5016 | |||||
5017 | For string types, this is the maximum size of the string in characters. | ||||
5018 | |||||
5019 | For date and interval types, this is the maximum number of characters | ||||
5020 | needed to display the value. | ||||
5021 | |||||
5022 | =item LITERAL_PREFIX (string) | ||||
5023 | |||||
5024 | Characters used to prefix a literal. A typical prefix is "C<'>" for characters, | ||||
5025 | or possibly "C<0x>" for binary values passed as hexadecimal. NULL (C<undef>) is | ||||
5026 | returned for data types for which this is not applicable. | ||||
5027 | |||||
5028 | |||||
5029 | =item LITERAL_SUFFIX (string) | ||||
5030 | |||||
5031 | Characters used to suffix a literal. Typically "C<'>" for characters. | ||||
5032 | NULL (C<undef>) is returned for data types where this is not applicable. | ||||
5033 | |||||
5034 | =item CREATE_PARAMS (string) | ||||
5035 | |||||
5036 | Parameter names for data type definition. For example, C<CREATE_PARAMS> for a | ||||
5037 | C<DECIMAL> would be "C<precision,scale>" if the DECIMAL type should be | ||||
5038 | declared as C<DECIMAL(>I<precision,scale>C<)> where I<precision> and I<scale> | ||||
5039 | are integer values. For a C<VARCHAR> it would be "C<max length>". | ||||
5040 | NULL (C<undef>) is returned for data types for which this is not applicable. | ||||
5041 | |||||
5042 | =item NULLABLE (integer) | ||||
5043 | |||||
5044 | Indicates whether the data type accepts a NULL value: | ||||
5045 | C<0> or an empty string = no, C<1> = yes, C<2> = unknown. | ||||
5046 | |||||
5047 | =item CASE_SENSITIVE (boolean) | ||||
5048 | |||||
5049 | Indicates whether the data type is case sensitive in collations and | ||||
5050 | comparisons. | ||||
5051 | |||||
5052 | =item SEARCHABLE (integer) | ||||
5053 | |||||
5054 | Indicates how the data type can be used in a WHERE clause, as | ||||
5055 | follows: | ||||
5056 | |||||
5057 | 0 - Cannot be used in a WHERE clause | ||||
5058 | 1 - Only with a LIKE predicate | ||||
5059 | 2 - All comparison operators except LIKE | ||||
5060 | 3 - Can be used in a WHERE clause with any comparison operator | ||||
5061 | |||||
5062 | =item UNSIGNED_ATTRIBUTE (boolean) | ||||
5063 | |||||
5064 | Indicates whether the data type is unsigned. NULL (C<undef>) is returned | ||||
5065 | for data types for which this is not applicable. | ||||
5066 | |||||
5067 | =item FIXED_PREC_SCALE (boolean) | ||||
5068 | |||||
5069 | Indicates whether the data type always has the same precision and scale | ||||
5070 | (such as a money type). NULL (C<undef>) is returned for data types | ||||
5071 | for which | ||||
5072 | this is not applicable. | ||||
5073 | |||||
5074 | =item AUTO_UNIQUE_VALUE (boolean) | ||||
5075 | |||||
5076 | Indicates whether a column of this data type is automatically set to a | ||||
5077 | unique value whenever a new row is inserted. NULL (C<undef>) is returned | ||||
5078 | for data types for which this is not applicable. | ||||
5079 | |||||
5080 | =item LOCAL_TYPE_NAME (string) | ||||
5081 | |||||
5082 | Localized version of the C<TYPE_NAME> for use in dialog with users. | ||||
5083 | NULL (C<undef>) is returned if a localized name is not available (in which | ||||
5084 | case C<TYPE_NAME> should be used). | ||||
5085 | |||||
5086 | =item MINIMUM_SCALE (integer) | ||||
5087 | |||||
5088 | The minimum scale of the data type. If a data type has a fixed scale, | ||||
5089 | then C<MAXIMUM_SCALE> holds the same value. NULL (C<undef>) is returned for | ||||
5090 | data types for which this is not applicable. | ||||
5091 | |||||
5092 | =item MAXIMUM_SCALE (integer) | ||||
5093 | |||||
5094 | The maximum scale of the data type. If a data type has a fixed scale, | ||||
5095 | then C<MINIMUM_SCALE> holds the same value. NULL (C<undef>) is returned for | ||||
5096 | data types for which this is not applicable. | ||||
5097 | |||||
5098 | =item SQL_DATA_TYPE (integer) | ||||
5099 | |||||
5100 | This column is the same as the C<DATA_TYPE> column, except for interval | ||||
5101 | and datetime data types. For interval and datetime data types, the | ||||
5102 | C<SQL_DATA_TYPE> field will return C<SQL_INTERVAL> or C<SQL_DATETIME>, and the | ||||
5103 | C<SQL_DATETIME_SUB> field below will return the subcode for the specific | ||||
5104 | interval or datetime data type. If this field is NULL, then the driver | ||||
5105 | does not support or report on interval or datetime subtypes. | ||||
5106 | |||||
5107 | =item SQL_DATETIME_SUB (integer) | ||||
5108 | |||||
5109 | For interval or datetime data types, where the C<SQL_DATA_TYPE> | ||||
5110 | field above is C<SQL_INTERVAL> or C<SQL_DATETIME>, this field will | ||||
5111 | hold the I<subcode> for the specific interval or datetime data type. | ||||
5112 | Otherwise it will be NULL (C<undef>). | ||||
5113 | |||||
5114 | Although not mentioned explicitly in the standards, it seems there | ||||
5115 | is a simple relationship between these values: | ||||
5116 | |||||
5117 | DATA_TYPE == (10 * SQL_DATA_TYPE) + SQL_DATETIME_SUB | ||||
5118 | |||||
5119 | =item NUM_PREC_RADIX (integer) | ||||
5120 | |||||
5121 | The radix value of the data type. For approximate numeric types, | ||||
5122 | C<NUM_PREC_RADIX> | ||||
5123 | contains the value 2 and C<COLUMN_SIZE> holds the number of bits. For | ||||
5124 | exact numeric types, C<NUM_PREC_RADIX> contains the value 10 and C<COLUMN_SIZE> holds | ||||
5125 | the number of decimal digits. NULL (C<undef>) is returned either for data types | ||||
5126 | for which this is not applicable or if the driver cannot report this information. | ||||
5127 | |||||
5128 | =item INTERVAL_PRECISION (integer) | ||||
5129 | |||||
5130 | The interval leading precision for interval types. NULL is returned | ||||
5131 | either for data types for which this is not applicable or if the driver | ||||
5132 | cannot report this information. | ||||
5133 | |||||
5134 | =back | ||||
5135 | |||||
5136 | For example, to find the type name for the fields in a select statement | ||||
5137 | you can do: | ||||
5138 | |||||
5139 | @names = map { scalar $dbh->type_info($_)->{TYPE_NAME} } @{ $sth->{TYPE} } | ||||
5140 | |||||
5141 | Since DBI and ODBC drivers vary in how they map their types into the | ||||
5142 | ISO standard types you may need to search for more than one type. | ||||
5143 | Here's an example looking for a usable type to store a date: | ||||
5144 | |||||
5145 | $my_date_type = $dbh->type_info( [ SQL_DATE, SQL_TIMESTAMP ] ); | ||||
5146 | |||||
5147 | Similarly, to more reliably find a type to store small integers, you could | ||||
5148 | use a list starting with C<SQL_SMALLINT>, C<SQL_INTEGER>, C<SQL_DECIMAL>, etc. | ||||
5149 | |||||
5150 | See also L</"Standards Reference Information">. | ||||
5151 | |||||
5152 | |||||
5153 | =item C<quote> | ||||
5154 | |||||
5155 | $sql = $dbh->quote($value); | ||||
5156 | $sql = $dbh->quote($value, $data_type); | ||||
5157 | |||||
5158 | Quote a string literal for use as a literal value in an SQL statement, | ||||
5159 | by escaping any special characters (such as quotation marks) | ||||
5160 | contained within the string and adding the required type of outer | ||||
5161 | quotation marks. | ||||
5162 | |||||
5163 | $sql = sprintf "SELECT foo FROM bar WHERE baz = %s", | ||||
5164 | $dbh->quote("Don't"); | ||||
5165 | |||||
5166 | For most database types, quote would return C<'Don''t'> (including the | ||||
5167 | outer quotation marks). | ||||
5168 | |||||
5169 | An undefined C<$value> value will be returned as the string C<NULL> (without | ||||
5170 | single quotation marks) to match how NULLs are represented in SQL. | ||||
5171 | |||||
5172 | If C<$data_type> is supplied, it is used to try to determine the required | ||||
5173 | quoting behaviour by using the information returned by L</type_info>. | ||||
5174 | As a special case, the standard numeric types are optimized to return | ||||
5175 | C<$value> without calling C<type_info>. | ||||
5176 | |||||
5177 | Quote will probably I<not> be able to deal with all possible input | ||||
5178 | (such as binary data or data containing newlines), and is not related in | ||||
5179 | any way with escaping or quoting shell meta-characters. | ||||
5180 | |||||
5181 | It is valid for the quote() method to return an SQL expression that | ||||
5182 | evaluates to the desired string. For example: | ||||
5183 | |||||
5184 | $quoted = $dbh->quote("one\ntwo\0three") | ||||
5185 | |||||
5186 | may return something like: | ||||
5187 | |||||
5188 | CONCAT('one', CHAR(12), 'two', CHAR(0), 'three') | ||||
5189 | |||||
5190 | The quote() method should I<not> be used with L</"Placeholders and | ||||
5191 | Bind Values">. | ||||
5192 | |||||
5193 | =item C<quote_identifier> | ||||
5194 | |||||
5195 | $sql = $dbh->quote_identifier( $name ); | ||||
5196 | $sql = $dbh->quote_identifier( $catalog, $schema, $table, \%attr ); | ||||
5197 | |||||
5198 | Quote an identifier (table name etc.) for use in an SQL statement, | ||||
5199 | by escaping any special characters (such as double quotation marks) | ||||
5200 | it contains and adding the required type of outer quotation marks. | ||||
5201 | |||||
5202 | Undefined names are ignored and the remainder are quoted and then | ||||
5203 | joined together, typically with a dot (C<.>) character. For example: | ||||
5204 | |||||
5205 | $id = $dbh->quote_identifier( undef, 'Her schema', 'My table' ); | ||||
5206 | |||||
5207 | would, for most database types, return C<"Her schema"."My table"> | ||||
5208 | (including all the double quotation marks). | ||||
5209 | |||||
5210 | If three names are supplied then the first is assumed to be a | ||||
5211 | catalog name and special rules may be applied based on what L</get_info> | ||||
5212 | returns for SQL_CATALOG_NAME_SEPARATOR (41) and SQL_CATALOG_LOCATION (114). | ||||
5213 | For example, for Oracle: | ||||
5214 | |||||
5215 | $id = $dbh->quote_identifier( 'link', 'schema', 'table' ); | ||||
5216 | |||||
5217 | would return C<"schema"."table"@"link">. | ||||
5218 | |||||
5219 | =item C<take_imp_data> | ||||
5220 | |||||
5221 | $imp_data = $dbh->take_imp_data; | ||||
5222 | |||||
5223 | Leaves the $dbh in an almost dead, zombie-like, state and returns | ||||
5224 | a binary string of raw implementation data from the driver which | ||||
5225 | describes the current database connection. Effectively it detaches | ||||
5226 | the underlying database API connection data from the DBI handle. | ||||
5227 | After calling take_imp_data(), all other methods except C<DESTROY> | ||||
5228 | will generate a warning and return undef. | ||||
5229 | |||||
5230 | Why would you want to do this? You don't, forget I even mentioned it. | ||||
5231 | Unless, that is, you're implementing something advanced like a | ||||
5232 | multi-threaded connection pool. See L<DBI::Pool>. | ||||
5233 | |||||
5234 | The returned $imp_data can be passed as a C<dbi_imp_data> attribute | ||||
5235 | to a later connect() call, even in a separate thread in the same | ||||
5236 | process, where the driver can use it to 'adopt' the existing | ||||
5237 | connection that the implementation data was taken from. | ||||
5238 | |||||
5239 | Some things to keep in mind... | ||||
5240 | |||||
5241 | B<*> the $imp_data holds the only reference to the underlying | ||||
5242 | database API connection data. That connection is still 'live' and | ||||
5243 | won't be cleaned up properly unless the $imp_data is used to create | ||||
5244 | a new $dbh which is then allowed to disconnect() normally. | ||||
5245 | |||||
5246 | B<*> using the same $imp_data to create more than one other new | ||||
5247 | $dbh at a time may well lead to unpleasant problems. Don't do that. | ||||
5248 | |||||
5249 | Any child statement handles are effectively destroyed when take_imp_data() is | ||||
5250 | called. | ||||
5251 | |||||
5252 | The C<take_imp_data> method was added in DBI 1.36 but wasn't useful till 1.49. | ||||
5253 | |||||
5254 | =back | ||||
5255 | |||||
5256 | |||||
5257 | =head2 Database Handle Attributes | ||||
5258 | |||||
5259 | This section describes attributes specific to database handles. | ||||
5260 | |||||
5261 | Changes to these database handle attributes do not affect any other | ||||
5262 | existing or future database handles. | ||||
5263 | |||||
5264 | Attempting to set or get the value of an unknown attribute generates a warning, | ||||
5265 | except for private driver-specific attributes (which all have names | ||||
5266 | starting with a lowercase letter). | ||||
5267 | |||||
5268 | Example: | ||||
5269 | |||||
5270 | $h->{AutoCommit} = ...; # set/write | ||||
5271 | ... = $h->{AutoCommit}; # get/read | ||||
5272 | |||||
5273 | =over 4 | ||||
5274 | |||||
5275 | =item C<AutoCommit> (boolean) | ||||
5276 | |||||
5277 | If true, then database changes cannot be rolled-back (undone). If false, | ||||
5278 | then database changes automatically occur within a "transaction", which | ||||
5279 | must either be committed or rolled back using the C<commit> or C<rollback> | ||||
5280 | methods. | ||||
5281 | |||||
5282 | Drivers should always default to C<AutoCommit> mode (an unfortunate | ||||
5283 | choice largely forced on the DBI by ODBC and JDBC conventions.) | ||||
5284 | |||||
5285 | Attempting to set C<AutoCommit> to an unsupported value is a fatal error. | ||||
5286 | This is an important feature of the DBI. Applications that need | ||||
5287 | full transaction behaviour can set C<$dbh-E<gt>{AutoCommit} = 0> (or | ||||
5288 | set C<AutoCommit> to 0 via L</connect>) | ||||
5289 | without having to check that the value was assigned successfully. | ||||
5290 | |||||
5291 | For the purposes of this description, we can divide databases into three | ||||
5292 | categories: | ||||
5293 | |||||
5294 | Databases which don't support transactions at all. | ||||
5295 | Databases in which a transaction is always active. | ||||
5296 | Databases in which a transaction must be explicitly started (C<'BEGIN WORK'>). | ||||
5297 | |||||
5298 | B<* Databases which don't support transactions at all> | ||||
5299 | |||||
5300 | For these databases, attempting to turn C<AutoCommit> off is a fatal error. | ||||
5301 | C<commit> and C<rollback> both issue warnings about being ineffective while | ||||
5302 | C<AutoCommit> is in effect. | ||||
5303 | |||||
5304 | B<* Databases in which a transaction is always active> | ||||
5305 | |||||
5306 | These are typically mainstream commercial relational databases with | ||||
5307 | "ANSI standard" transaction behaviour. | ||||
5308 | If C<AutoCommit> is off, then changes to the database won't have any | ||||
5309 | lasting effect unless L</commit> is called (but see also | ||||
5310 | L</disconnect>). If L</rollback> is called then any changes since the | ||||
5311 | last commit are undone. | ||||
5312 | |||||
5313 | If C<AutoCommit> is on, then the effect is the same as if the DBI | ||||
5314 | called C<commit> automatically after every successful database | ||||
5315 | operation. So calling C<commit> or C<rollback> explicitly while | ||||
5316 | C<AutoCommit> is on would be ineffective because the changes would | ||||
5317 | have already been commited. | ||||
5318 | |||||
5319 | Changing C<AutoCommit> from off to on will trigger a L</commit>. | ||||
5320 | |||||
5321 | For databases which don't support a specific auto-commit mode, the | ||||
5322 | driver has to commit each statement automatically using an explicit | ||||
5323 | C<COMMIT> after it completes successfully (and roll it back using an | ||||
5324 | explicit C<ROLLBACK> if it fails). The error information reported to the | ||||
5325 | application will correspond to the statement which was executed, unless | ||||
5326 | it succeeded and the commit or rollback failed. | ||||
5327 | |||||
5328 | B<* Databases in which a transaction must be explicitly started> | ||||
5329 | |||||
5330 | For these databases, the intention is to have them act like databases in | ||||
5331 | which a transaction is always active (as described above). | ||||
5332 | |||||
5333 | To do this, the driver will automatically begin an explicit transaction | ||||
5334 | when C<AutoCommit> is turned off, or after a L</commit> or | ||||
5335 | L</rollback> (or when the application issues the next database | ||||
5336 | operation after one of those events). | ||||
5337 | |||||
5338 | In this way, the application does not have to treat these databases | ||||
5339 | as a special case. | ||||
5340 | |||||
5341 | See L</commit>, L</disconnect> and L</Transactions> for other important | ||||
5342 | notes about transactions. | ||||
5343 | |||||
5344 | |||||
5345 | =item C<Driver> (handle) | ||||
5346 | |||||
5347 | Holds the handle of the parent driver. The only recommended use for this | ||||
5348 | is to find the name of the driver using: | ||||
5349 | |||||
5350 | $dbh->{Driver}->{Name} | ||||
5351 | |||||
5352 | |||||
5353 | =item C<Name> (string) | ||||
5354 | |||||
5355 | Holds the "name" of the database. Usually (and recommended to be) the | ||||
5356 | same as the "C<dbi:DriverName:...>" string used to connect to the database, | ||||
5357 | but with the leading "C<dbi:DriverName:>" removed. | ||||
5358 | |||||
5359 | |||||
5360 | =item C<Statement> (string, read-only) | ||||
5361 | |||||
5362 | Returns the statement string passed to the most recent L</prepare> method | ||||
5363 | called in this database handle, even if that method failed. This is especially | ||||
5364 | useful where C<RaiseError> is enabled and the exception handler checks $@ | ||||
5365 | and sees that a 'prepare' method call failed. | ||||
5366 | |||||
5367 | |||||
5368 | =item C<RowCacheSize> (integer) | ||||
5369 | |||||
5370 | A hint to the driver indicating the size of the local row cache that the | ||||
5371 | application would like the driver to use for future C<SELECT> statements. | ||||
5372 | If a row cache is not implemented, then setting C<RowCacheSize> is ignored | ||||
5373 | and getting the value returns C<undef>. | ||||
5374 | |||||
5375 | Some C<RowCacheSize> values have special meaning, as follows: | ||||
5376 | |||||
5377 | 0 - Automatically determine a reasonable cache size for each C<SELECT> | ||||
5378 | 1 - Disable the local row cache | ||||
5379 | >1 - Cache this many rows | ||||
5380 | <0 - Cache as many rows that will fit into this much memory for each C<SELECT>. | ||||
5381 | |||||
5382 | Note that large cache sizes may require a very large amount of memory | ||||
5383 | (I<cached rows * maximum size of row>). Also, a large cache will cause | ||||
5384 | a longer delay not only for the first fetch, but also whenever the | ||||
5385 | cache needs refilling. | ||||
5386 | |||||
5387 | See also the L</RowsInCache> statement handle attribute. | ||||
5388 | |||||
5389 | =item C<Username> (string) | ||||
5390 | |||||
5391 | Returns the username used to connect to the database. | ||||
5392 | |||||
5393 | |||||
5394 | =back | ||||
5395 | |||||
5396 | |||||
5397 | =head1 DBI STATEMENT HANDLE OBJECTS | ||||
5398 | |||||
5399 | This section lists the methods and attributes associated with DBI | ||||
5400 | statement handles. | ||||
5401 | |||||
5402 | =head2 Statement Handle Methods | ||||
5403 | |||||
5404 | The DBI defines the following methods for use on DBI statement handles: | ||||
5405 | |||||
5406 | =over 4 | ||||
5407 | |||||
5408 | =item C<bind_param> | ||||
5409 | |||||
5410 | $sth->bind_param($p_num, $bind_value) | ||||
5411 | $sth->bind_param($p_num, $bind_value, \%attr) | ||||
5412 | $sth->bind_param($p_num, $bind_value, $bind_type) | ||||
5413 | |||||
5414 | The C<bind_param> method takes a copy of $bind_value and associates it | ||||
5415 | (binds it) with a placeholder, identified by $p_num, embedded in | ||||
5416 | the prepared statement. Placeholders are indicated with question | ||||
5417 | mark character (C<?>). For example: | ||||
5418 | |||||
5419 | $dbh->{RaiseError} = 1; # save having to check each method call | ||||
5420 | $sth = $dbh->prepare("SELECT name, age FROM people WHERE name LIKE ?"); | ||||
5421 | $sth->bind_param(1, "John%"); # placeholders are numbered from 1 | ||||
5422 | $sth->execute; | ||||
5423 | DBI::dump_results($sth); | ||||
5424 | |||||
5425 | See L</"Placeholders and Bind Values"> for more information. | ||||
5426 | |||||
5427 | |||||
5428 | B<Data Types for Placeholders> | ||||
5429 | |||||
5430 | The C<\%attr> parameter can be used to hint at the data type the | ||||
5431 | placeholder should have. This is rarely needed. Typically, the driver is only | ||||
5432 | interested in knowing if the placeholder should be bound as a number or a string. | ||||
5433 | |||||
5434 | $sth->bind_param(1, $value, { TYPE => SQL_INTEGER }); | ||||
5435 | |||||
5436 | As a short-cut for the common case, the data type can be passed | ||||
5437 | directly, in place of the C<\%attr> hash reference. This example is | ||||
5438 | equivalent to the one above: | ||||
5439 | |||||
5440 | $sth->bind_param(1, $value, SQL_INTEGER); | ||||
5441 | |||||
5442 | The C<TYPE> value indicates the standard (non-driver-specific) type for | ||||
5443 | this parameter. To specify the driver-specific type, the driver may | ||||
5444 | support a driver-specific attribute, such as C<{ ora_type =E<gt> 97 }>. | ||||
5445 | |||||
5446 | The SQL_INTEGER and other related constants can be imported using | ||||
5447 | |||||
5448 | use DBI qw(:sql_types); | ||||
5449 | |||||
5450 | See L</"DBI Constants"> for more information. | ||||
5451 | |||||
5452 | The data type for a placeholder cannot be changed after the first | ||||
5453 | C<bind_param> call. In fact the whole \%attr parameter is 'sticky' | ||||
5454 | in the sense that a driver only needs to consider the \%attr parameter | ||||
5455 | for the first call, for a given $sth and parameter. After that the driver | ||||
5456 | may ignore the \%attr parameter for that placeholder. | ||||
5457 | |||||
5458 | Perl only has string and number scalar data types. All database types | ||||
5459 | that aren't numbers are bound as strings and must be in a format the | ||||
5460 | database will understand except where the bind_param() TYPE attribute | ||||
5461 | specifies a type that implies a particular format. For example, given: | ||||
5462 | |||||
5463 | $sth->bind_param(1, $value, SQL_DATETIME); | ||||
5464 | |||||
5465 | the driver should expect $value to be in the ODBC standard SQL_DATETIME | ||||
5466 | format, which is 'YYYY-MM-DD HH:MM:SS'. Similarly for SQL_DATE, SQL_TIME etc. | ||||
5467 | |||||
5468 | As an alternative to specifying the data type in the C<bind_param> call, | ||||
5469 | you can let the driver pass the value as the default type (C<VARCHAR>). | ||||
5470 | You can then use an SQL function to convert the type within the statement. | ||||
5471 | For example: | ||||
5472 | |||||
5473 | INSERT INTO price(code, price) VALUES (?, CONVERT(MONEY,?)) | ||||
5474 | |||||
5475 | The C<CONVERT> function used here is just an example. The actual function | ||||
5476 | and syntax will vary between different databases and is non-portable. | ||||
5477 | |||||
5478 | See also L</"Placeholders and Bind Values"> for more information. | ||||
5479 | |||||
5480 | |||||
5481 | =item C<bind_param_inout> | ||||
5482 | |||||
5483 | $rc = $sth->bind_param_inout($p_num, \$bind_value, $max_len) or die $sth->errstr; | ||||
5484 | $rv = $sth->bind_param_inout($p_num, \$bind_value, $max_len, \%attr) or ... | ||||
5485 | $rv = $sth->bind_param_inout($p_num, \$bind_value, $max_len, $bind_type) or ... | ||||
5486 | |||||
5487 | This method acts like L</bind_param>, but also enables values to be | ||||
5488 | updated by the statement. The statement is typically | ||||
5489 | a call to a stored procedure. The C<$bind_value> must be passed as a | ||||
5490 | reference to the actual value to be used. | ||||
5491 | |||||
5492 | Note that unlike L</bind_param>, the C<$bind_value> variable is not | ||||
5493 | copied when C<bind_param_inout> is called. Instead, the value in the | ||||
5494 | variable is read at the time L</execute> is called. | ||||
5495 | |||||
5496 | The additional C<$max_len> parameter specifies the minimum amount of | ||||
5497 | memory to allocate to C<$bind_value> for the new value. If the value | ||||
5498 | returned from the database is too | ||||
5499 | big to fit, then the execution should fail. If unsure what value to use, | ||||
5500 | pick a generous length, i.e., a length larger than the longest value that would ever be | ||||
5501 | returned. The only cost of using a larger value than needed is wasted memory. | ||||
5502 | |||||
5503 | Undefined values or C<undef> are used to indicate null values. | ||||
5504 | See also L</"Placeholders and Bind Values"> for more information. | ||||
5505 | |||||
5506 | |||||
5507 | =item C<bind_param_array> | ||||
5508 | |||||
5509 | $rc = $sth->bind_param_array($p_num, $array_ref_or_value) | ||||
5510 | $rc = $sth->bind_param_array($p_num, $array_ref_or_value, \%attr) | ||||
5511 | $rc = $sth->bind_param_array($p_num, $array_ref_or_value, $bind_type) | ||||
5512 | |||||
5513 | The C<bind_param_array> method is used to bind an array of values | ||||
5514 | to a placeholder embedded in the prepared statement which is to be executed | ||||
5515 | with L</execute_array>. For example: | ||||
5516 | |||||
5517 | $dbh->{RaiseError} = 1; # save having to check each method call | ||||
5518 | $sth = $dbh->prepare("INSERT INTO staff (first_name, last_name, dept) VALUES(?, ?, ?)"); | ||||
5519 | $sth->bind_param_array(1, [ 'John', 'Mary', 'Tim' ]); | ||||
5520 | $sth->bind_param_array(2, [ 'Booth', 'Todd', 'Robinson' ]); | ||||
5521 | $sth->bind_param_array(3, "SALES"); # scalar will be reused for each row | ||||
5522 | $sth->execute_array( { ArrayTupleStatus => \my @tuple_status } ); | ||||
5523 | |||||
5524 | The C<%attr> ($bind_type) argument is the same as defined for L</bind_param>. | ||||
5525 | Refer to L</bind_param> for general details on using placeholders. | ||||
5526 | |||||
5527 | (Note that bind_param_array() can I<not> be used to expand a | ||||
5528 | placeholder into a list of values for a statement like "SELECT foo | ||||
5529 | WHERE bar IN (?)". A placeholder can only ever represent one value | ||||
5530 | per execution.) | ||||
5531 | |||||
5532 | Scalar values, including C<undef>, may also be bound by | ||||
5533 | C<bind_param_array>. In which case the same value will be used for each | ||||
5534 | L</execute> call. Driver-specific implementations may behave | ||||
5535 | differently, e.g., when binding to a stored procedure call, some | ||||
5536 | databases may permit mixing scalars and arrays as arguments. | ||||
5537 | |||||
5538 | The default implementation provided by DBI (for drivers that have | ||||
5539 | not implemented array binding) is to iteratively call L</execute> for | ||||
5540 | each parameter tuple provided in the bound arrays. Drivers may | ||||
5541 | provide more optimized implementations using whatever bulk operation | ||||
5542 | support the database API provides. The default driver behaviour should | ||||
5543 | match the default DBI behaviour, but always consult your driver | ||||
5544 | documentation as there may be driver specific issues to consider. | ||||
5545 | |||||
5546 | Note that the default implementation currently only supports non-data | ||||
5547 | returning statements (INSERT, UPDATE, but not SELECT). Also, | ||||
5548 | C<bind_param_array> and L</bind_param> cannot be mixed in the same | ||||
5549 | statement execution, and C<bind_param_array> must be used with | ||||
5550 | L</execute_array>; using C<bind_param_array> will have no effect | ||||
5551 | for L</execute>. | ||||
5552 | |||||
5553 | The C<bind_param_array> method was added in DBI 1.22. | ||||
5554 | |||||
5555 | =item C<execute> | ||||
5556 | |||||
5557 | $rv = $sth->execute or die $sth->errstr; | ||||
5558 | $rv = $sth->execute(@bind_values) or die $sth->errstr; | ||||
5559 | |||||
5560 | Perform whatever processing is necessary to execute the prepared | ||||
5561 | statement. An C<undef> is returned if an error occurs. A successful | ||||
5562 | C<execute> always returns true regardless of the number of rows affected, | ||||
5563 | even if it's zero (see below). It is always important to check the | ||||
5564 | return status of C<execute> (and most other DBI methods) for errors | ||||
5565 | if you're not using L</RaiseError>. | ||||
5566 | |||||
5567 | For a I<non>-C<SELECT> statement, C<execute> returns the number of rows | ||||
5568 | affected, if known. If no rows were affected, then C<execute> returns | ||||
5569 | "C<0E0>", which Perl will treat as 0 but will regard as true. Note that it | ||||
5570 | is I<not> an error for no rows to be affected by a statement. If the | ||||
5571 | number of rows affected is not known, then C<execute> returns -1. | ||||
5572 | |||||
5573 | For C<SELECT> statements, execute simply "starts" the query within the | ||||
5574 | database engine. Use one of the fetch methods to retrieve the data after | ||||
5575 | calling C<execute>. The C<execute> method does I<not> return the number of | ||||
5576 | rows that will be returned by the query (because most databases can't | ||||
5577 | tell in advance), it simply returns a true value. | ||||
5578 | |||||
5579 | You can tell if the statement was a C<SELECT> statement by checking if | ||||
5580 | C<$sth-E<gt>{NUM_OF_FIELDS}> is greater than zero after calling C<execute>. | ||||
5581 | |||||
5582 | If any arguments are given, then C<execute> will effectively call | ||||
5583 | L</bind_param> for each value before executing the statement. Values | ||||
5584 | bound in this way are usually treated as C<SQL_VARCHAR> types unless | ||||
5585 | the driver can determine the correct type (which is rare), or unless | ||||
5586 | C<bind_param> (or C<bind_param_inout>) has already been used to | ||||
5587 | specify the type. | ||||
5588 | |||||
5589 | If execute() is called on a statement handle that's still active | ||||
5590 | ($sth->{Active} is true) then it should effectively call finish() | ||||
5591 | to tidy up the previous execution results before starting this new | ||||
5592 | execution. | ||||
5593 | |||||
5594 | =item C<execute_array> | ||||
5595 | |||||
5596 | $tuples = $sth->execute_array(\%attr) or die $sth->errstr; | ||||
5597 | $tuples = $sth->execute_array(\%attr, @bind_values) or die $sth->errstr; | ||||
5598 | |||||
5599 | ($tuples, $rows) = $sth->execute_array(\%attr) or die $sth->errstr; | ||||
5600 | ($tuples, $rows) = $sth->execute_array(\%attr, @bind_values) or die $sth->errstr; | ||||
5601 | |||||
5602 | Execute the prepared statement once for each parameter tuple | ||||
5603 | (group of values) provided either in the @bind_values, or by prior | ||||
5604 | calls to L</bind_param_array>, or via a reference passed in \%attr. | ||||
5605 | |||||
5606 | When called in scalar context the execute_array() method returns the | ||||
5607 | number of tuples executed, or C<undef> if an error occured. Like | ||||
5608 | execute(), a successful execute_array() always returns true regardless | ||||
5609 | of the number of tuples executed, even if it's zero. If there were any | ||||
5610 | errors the ArrayTupleStatus array can be used to discover which tuples | ||||
5611 | failed and with what errors. | ||||
5612 | |||||
5613 | When called in list context the execute_array() method returns two scalars; | ||||
5614 | $tuples is the same as calling execute_array() in scalar context and $rows is | ||||
5615 | the sum of the number of rows affected for each tuple, if available or | ||||
5616 | -1 if the driver cannot determine this. | ||||
5617 | If you are doing an update operation the returned rows affected may not be what | ||||
5618 | you expect if, for instance, one or more of the tuples affected the same row | ||||
5619 | multiple times. Some drivers may not yet support list context, in which case | ||||
5620 | $rows will be undef, or may not be able to provide the number of rows affected | ||||
5621 | when performing this batch operation, in which case $rows will be -1. | ||||
5622 | |||||
5623 | Bind values for the tuples to be executed may be supplied row-wise | ||||
5624 | by an C<ArrayTupleFetch> attribute, or else column-wise in the | ||||
5625 | C<@bind_values> argument, or else column-wise by prior calls to | ||||
5626 | L</bind_param_array>. | ||||
5627 | |||||
5628 | Where column-wise binding is used (via the C<@bind_values> argument | ||||
5629 | or calls to bind_param_array()) the maximum number of elements in | ||||
5630 | any one of the bound value arrays determines the number of tuples | ||||
5631 | executed. Placeholders with fewer values in their parameter arrays | ||||
5632 | are treated as if padded with undef (NULL) values. | ||||
5633 | |||||
5634 | If a scalar value is bound, instead of an array reference, it is | ||||
5635 | treated as a I<variable> length array with all elements having the | ||||
5636 | same value. It's does not influence the number of tuples executed, | ||||
5637 | so if all bound arrays have zero elements then zero tuples will | ||||
5638 | be executed. If I<all> bound values are scalars then one tuple | ||||
5639 | will be executed, making execute_array() act just like execute(). | ||||
5640 | |||||
5641 | The C<ArrayTupleFetch> attribute can be used to specify a reference | ||||
5642 | to a subroutine that will be called to provide the bind values for | ||||
5643 | each tuple execution. The subroutine should return an reference to | ||||
5644 | an array which contains the appropriate number of bind values, or | ||||
5645 | return an undef if there is no more data to execute. | ||||
5646 | |||||
5647 | As a convienience, the C<ArrayTupleFetch> attribute can also be | ||||
5648 | used to specify a statement handle. In which case the fetchrow_arrayref() | ||||
5649 | method will be called on the given statement handle in order to | ||||
5650 | provide the bind values for each tuple execution. | ||||
5651 | |||||
5652 | The values specified via bind_param_array() or the @bind_values | ||||
5653 | parameter may be either scalars, or arrayrefs. If any C<@bind_values> | ||||
5654 | are given, then C<execute_array> will effectively call L</bind_param_array> | ||||
5655 | for each value before executing the statement. Values bound in | ||||
5656 | this way are usually treated as C<SQL_VARCHAR> types unless the | ||||
5657 | driver can determine the correct type (which is rare), or unless | ||||
5658 | C<bind_param>, C<bind_param_inout>, C<bind_param_array>, or | ||||
5659 | C<bind_param_inout_array> has already been used to specify the type. | ||||
5660 | See L</bind_param_array> for details. | ||||
5661 | |||||
5662 | The C<ArrayTupleStatus> attribute can be used to specify a | ||||
5663 | reference to an array which will receive the execute status of each | ||||
5664 | executed parameter tuple. Note the C<ArrayTupleStatus> attribute was | ||||
5665 | mandatory until DBI 1.38. | ||||
5666 | |||||
5667 | For tuples which are successfully executed, the element at the same | ||||
5668 | ordinal position in the status array is the resulting rowcount. | ||||
5669 | If the execution of a tuple causes an error, then the corresponding | ||||
5670 | status array element will be set to a reference to an array containing | ||||
5671 | the error code and error string set by the failed execution. | ||||
5672 | |||||
5673 | If B<any> tuple execution returns an error, C<execute_array> will | ||||
5674 | return C<undef>. In that case, the application should inspect the | ||||
5675 | status array to determine which parameter tuples failed. | ||||
5676 | Some databases may not continue executing tuples beyond the first | ||||
5677 | failure. In this case the status array will either hold fewer | ||||
5678 | elements, or the elements beyond the failure will be undef. | ||||
5679 | |||||
5680 | If all parameter tuples are successfully executed, C<execute_array> | ||||
5681 | returns the number tuples executed. If no tuples were executed, | ||||
5682 | then execute_array() returns "C<0E0>", just like execute() does, | ||||
5683 | which Perl will treat as 0 but will regard as true. | ||||
5684 | |||||
5685 | For example: | ||||
5686 | |||||
5687 | $sth = $dbh->prepare("INSERT INTO staff (first_name, last_name) VALUES (?, ?)"); | ||||
5688 | my $tuples = $sth->execute_array( | ||||
5689 | { ArrayTupleStatus => \my @tuple_status }, | ||||
5690 | \@first_names, | ||||
5691 | \@last_names, | ||||
5692 | ); | ||||
5693 | if ($tuples) { | ||||
5694 | print "Successfully inserted $tuples records\n"; | ||||
5695 | } | ||||
5696 | else { | ||||
5697 | for my $tuple (0..@last_names-1) { | ||||
5698 | my $status = $tuple_status[$tuple]; | ||||
5699 | $status = [0, "Skipped"] unless defined $status; | ||||
5700 | next unless ref $status; | ||||
5701 | printf "Failed to insert (%s, %s): %s\n", | ||||
5702 | $first_names[$tuple], $last_names[$tuple], $status->[1]; | ||||
5703 | } | ||||
5704 | } | ||||
5705 | |||||
5706 | Support for data returning statements such as SELECT is driver-specific | ||||
5707 | and subject to change. At present, the default implementation | ||||
5708 | provided by DBI only supports non-data returning statements. | ||||
5709 | |||||
5710 | Transaction semantics when using array binding are driver and | ||||
5711 | database specific. If C<AutoCommit> is on, the default DBI | ||||
5712 | implementation will cause each parameter tuple to be inidividually | ||||
5713 | committed (or rolled back in the event of an error). If C<AutoCommit> | ||||
5714 | is off, the application is responsible for explicitly committing | ||||
5715 | the entire set of bound parameter tuples. Note that different | ||||
5716 | drivers and databases may have different behaviours when some | ||||
5717 | parameter tuples cause failures. In some cases, the driver or | ||||
5718 | database may automatically rollback the effect of all prior parameter | ||||
5719 | tuples that succeeded in the transaction; other drivers or databases | ||||
5720 | may retain the effect of prior successfully executed parameter | ||||
5721 | tuples. Be sure to check your driver and database for its specific | ||||
5722 | behaviour. | ||||
5723 | |||||
5724 | Note that, in general, performance will usually be better with | ||||
5725 | C<AutoCommit> turned off, and using explicit C<commit> after each | ||||
5726 | C<execute_array> call. | ||||
5727 | |||||
5728 | The C<execute_array> method was added in DBI 1.22, and ArrayTupleFetch | ||||
5729 | was added in 1.36. | ||||
5730 | |||||
5731 | =item C<execute_for_fetch> | ||||
5732 | |||||
5733 | $tuples = $sth->execute_for_fetch($fetch_tuple_sub); | ||||
5734 | $tuples = $sth->execute_for_fetch($fetch_tuple_sub, \@tuple_status); | ||||
5735 | |||||
5736 | ($tuples, $rows) = $sth->execute_for_fetch($fetch_tuple_sub); | ||||
5737 | ($tuples, $rows) = $sth->execute_for_fetch($fetch_tuple_sub, \@tuple_status); | ||||
5738 | |||||
5739 | The execute_for_fetch() method is used to perform bulk operations | ||||
5740 | and is most often used via the execute_array() method, not directly. | ||||
5741 | |||||
5742 | The fetch subroutine, referenced by $fetch_tuple_sub, is expected | ||||
5743 | to return a reference to an array (known as a 'tuple') or undef. | ||||
5744 | |||||
5745 | The execute_for_fetch() method calls $fetch_tuple_sub, without any | ||||
5746 | parameters, until it returns a false value. Each tuple returned is | ||||
5747 | used to provide bind values for an $sth->execute(@$tuple) call. | ||||
5748 | |||||
5749 | In scalar context execute_for_fetch() returns C<undef> if there were any | ||||
5750 | errors and the number of tuples executed otherwise. Like execute() and | ||||
5751 | execute_array() a zero is returned as "0E0" so execute_for_fetch() is | ||||
5752 | only false on error. If there were any errors the @tuple_status array | ||||
5753 | can be used to discover which tuples failed and with what errors. | ||||
5754 | |||||
5755 | When called in list context execute_for_fetch() returns two scalars; | ||||
5756 | $tuples is the same as calling execute_for_fetch() in scalar context and $rows is | ||||
5757 | the sum of the number of rows affected for each tuple, if available or -1 | ||||
5758 | if the driver cannot determine this. | ||||
5759 | If you are doing an update operation the returned rows affected may not be what | ||||
5760 | you expect if, for instance, one or more of the tuples affected the same row | ||||
5761 | multiple times. Some drivers may not yet support list context, in which case | ||||
5762 | $rows will be undef, or may not be able to provide the number of rows affected | ||||
5763 | when performing this batch operation, in which case $rows will be -1. | ||||
5764 | |||||
5765 | If \@tuple_status is passed then the execute_for_fetch method uses | ||||
5766 | it to return status information. The tuple_status array holds one | ||||
5767 | element per tuple. If the corresponding execute() did not fail then | ||||
5768 | the element holds the return value from execute(), which is typically | ||||
5769 | a row count. If the execute() did fail then the element holds a | ||||
5770 | reference to an array containing ($sth->err, $sth->errstr, $sth->state). | ||||
5771 | |||||
5772 | If the driver detects an error that it knows means no further tuples can be | ||||
5773 | executed then it may return, with an error status, even though $fetch_tuple_sub | ||||
5774 | may still have more tuples to be executed. | ||||
5775 | |||||
5776 | Although each tuple returned by $fetch_tuple_sub is effectively used | ||||
5777 | to call $sth->execute(@$tuple_array_ref) the exact timing may vary. | ||||
5778 | Drivers are free to accumulate sets of tuples to pass to the | ||||
5779 | database server in bulk group operations for more efficient execution. | ||||
5780 | However, the $fetch_tuple_sub is specifically allowed to return | ||||
5781 | the same array reference each time (which is what fetchrow_arrayref() | ||||
5782 | usually does). | ||||
5783 | |||||
5784 | For example: | ||||
5785 | |||||
5786 | my $sel = $dbh1->prepare("select foo, bar from table1"); | ||||
5787 | $sel->execute; | ||||
5788 | |||||
5789 | my $ins = $dbh2->prepare("insert into table2 (foo, bar) values (?,?)"); | ||||
5790 | my $fetch_tuple_sub = sub { $sel->fetchrow_arrayref }; | ||||
5791 | |||||
5792 | my @tuple_status; | ||||
5793 | $rc = $ins->execute_for_fetch($fetch_tuple_sub, \@tuple_status); | ||||
5794 | my @errors = grep { ref $_ } @tuple_status; | ||||
5795 | |||||
5796 | Similarly, if you already have an array containing the data rows | ||||
5797 | to be processed you'd use a subroutine to shift off and return | ||||
5798 | each array ref in turn: | ||||
5799 | |||||
5800 | $ins->execute_for_fetch( sub { shift @array_of_arrays }, \@tuple_status); | ||||
5801 | |||||
5802 | The C<execute_for_fetch> method was added in DBI 1.38. | ||||
5803 | |||||
5804 | |||||
5805 | =item C<fetchrow_arrayref> | ||||
5806 | |||||
5807 | $ary_ref = $sth->fetchrow_arrayref; | ||||
5808 | $ary_ref = $sth->fetch; # alias | ||||
5809 | |||||
5810 | Fetches the next row of data and returns a reference to an array | ||||
5811 | holding the field values. Null fields are returned as C<undef> | ||||
5812 | values in the array. | ||||
5813 | This is the fastest way to fetch data, particularly if used with | ||||
5814 | C<$sth-E<gt>bind_columns>. | ||||
5815 | |||||
5816 | If there are no more rows or if an error occurs, then C<fetchrow_arrayref> | ||||
5817 | returns an C<undef>. You should check C<$sth-E<gt>err> afterwards (or use the | ||||
5818 | C<RaiseError> attribute) to discover if the C<undef> returned was due to an | ||||
5819 | error. | ||||
5820 | |||||
5821 | Note that the same array reference is returned for each fetch, so don't | ||||
5822 | store the reference and then use it after a later fetch. Also, the | ||||
5823 | elements of the array are also reused for each row, so take care if you | ||||
5824 | want to take a reference to an element. See also L</bind_columns>. | ||||
5825 | |||||
5826 | =item C<fetchrow_array> | ||||
5827 | |||||
5828 | @ary = $sth->fetchrow_array; | ||||
5829 | |||||
5830 | An alternative to C<fetchrow_arrayref>. Fetches the next row of data | ||||
5831 | and returns it as a list containing the field values. Null fields | ||||
5832 | are returned as C<undef> values in the list. | ||||
5833 | |||||
5834 | If there are no more rows or if an error occurs, then C<fetchrow_array> | ||||
5835 | returns an empty list. You should check C<$sth-E<gt>err> afterwards (or use | ||||
5836 | the C<RaiseError> attribute) to discover if the empty list returned was | ||||
5837 | due to an error. | ||||
5838 | |||||
5839 | If called in a scalar context for a statement handle that has more | ||||
5840 | than one column, it is undefined whether the driver will return | ||||
5841 | the value of the first column or the last. So don't do that. | ||||
5842 | Also, in a scalar context, an C<undef> is returned if there are no | ||||
5843 | more rows or if an error occurred. That C<undef> can't be distinguished | ||||
5844 | from an C<undef> returned because the first field value was NULL. | ||||
5845 | For these reasons you should exercise some caution if you use | ||||
5846 | C<fetchrow_array> in a scalar context. | ||||
5847 | |||||
5848 | =item C<fetchrow_hashref> | ||||
5849 | |||||
5850 | $hash_ref = $sth->fetchrow_hashref; | ||||
5851 | $hash_ref = $sth->fetchrow_hashref($name); | ||||
5852 | |||||
5853 | An alternative to C<fetchrow_arrayref>. Fetches the next row of data | ||||
5854 | and returns it as a reference to a hash containing field name and field | ||||
5855 | value pairs. Null fields are returned as C<undef> values in the hash. | ||||
5856 | |||||
5857 | If there are no more rows or if an error occurs, then C<fetchrow_hashref> | ||||
5858 | returns an C<undef>. You should check C<$sth-E<gt>err> afterwards (or use the | ||||
5859 | C<RaiseError> attribute) to discover if the C<undef> returned was due to an | ||||
5860 | error. | ||||
5861 | |||||
5862 | The optional C<$name> parameter specifies the name of the statement handle | ||||
5863 | attribute. For historical reasons it defaults to "C<NAME>", however using either | ||||
5864 | "C<NAME_lc>" or "C<NAME_uc>" is recomended for portability. | ||||
5865 | |||||
5866 | The keys of the hash are the same names returned by C<$sth-E<gt>{$name}>. If | ||||
5867 | more than one field has the same name, there will only be one entry in | ||||
5868 | the returned hash for those fields. | ||||
5869 | |||||
5870 | Because of the extra work C<fetchrow_hashref> and Perl have to perform, it | ||||
5871 | is not as efficient as C<fetchrow_arrayref> or C<fetchrow_array>. | ||||
5872 | |||||
5873 | By default a reference to a new hash is returned for each row. | ||||
5874 | It is likely that a future version of the DBI will support an | ||||
5875 | attribute which will enable the same hash to be reused for each | ||||
5876 | row. This will give a significant performance boost, but it won't | ||||
5877 | be enabled by default because of the risk of breaking old code. | ||||
5878 | |||||
5879 | |||||
5880 | =item C<fetchall_arrayref> | ||||
5881 | |||||
5882 | $tbl_ary_ref = $sth->fetchall_arrayref; | ||||
5883 | $tbl_ary_ref = $sth->fetchall_arrayref( $slice ); | ||||
5884 | $tbl_ary_ref = $sth->fetchall_arrayref( $slice, $max_rows ); | ||||
5885 | |||||
5886 | The C<fetchall_arrayref> method can be used to fetch all the data to be | ||||
5887 | returned from a prepared and executed statement handle. It returns a | ||||
5888 | reference to an array that contains one reference per row. | ||||
5889 | |||||
5890 | If there are no rows to return, C<fetchall_arrayref> returns a reference | ||||
5891 | to an empty array. If an error occurs, C<fetchall_arrayref> returns the | ||||
5892 | data fetched thus far, which may be none. You should check C<$sth-E<gt>err> | ||||
5893 | afterwards (or use the C<RaiseError> attribute) to discover if the data is | ||||
5894 | complete or was truncated due to an error. | ||||
5895 | |||||
5896 | If $slice is an array reference, C<fetchall_arrayref> uses L</fetchrow_arrayref> | ||||
5897 | to fetch each row as an array ref. If the $slice array is not empty | ||||
5898 | then it is used as a slice to select individual columns by perl array | ||||
5899 | index number (starting at 0, unlike column and parameter numbers which | ||||
5900 | start at 1). | ||||
5901 | |||||
5902 | With no parameters, or if $slice is undefined, C<fetchall_arrayref> | ||||
5903 | acts as if passed an empty array ref. | ||||
5904 | |||||
5905 | If $slice is a hash reference, C<fetchall_arrayref> uses L</fetchrow_hashref> | ||||
5906 | to fetch each row as a hash reference. If the $slice hash is empty then | ||||
5907 | fetchrow_hashref() is simply called in a tight loop and the keys in the hashes | ||||
5908 | have whatever name lettercase is returned by default from fetchrow_hashref. | ||||
5909 | (See L</FetchHashKeyName> attribute.) If the $slice hash is not | ||||
5910 | empty, then it is used as a slice to select individual columns by | ||||
5911 | name. The values of the hash should be set to 1. The key names | ||||
5912 | of the returned hashes match the letter case of the names in the | ||||
5913 | parameter hash, regardless of the L</FetchHashKeyName> attribute. | ||||
5914 | |||||
5915 | For example, to fetch just the first column of every row: | ||||
5916 | |||||
5917 | $tbl_ary_ref = $sth->fetchall_arrayref([0]); | ||||
5918 | |||||
5919 | To fetch the second to last and last column of every row: | ||||
5920 | |||||
5921 | $tbl_ary_ref = $sth->fetchall_arrayref([-2,-1]); | ||||
5922 | |||||
5923 | To fetch all fields of every row as a hash ref: | ||||
5924 | |||||
5925 | $tbl_ary_ref = $sth->fetchall_arrayref({}); | ||||
5926 | |||||
5927 | To fetch only the fields called "foo" and "bar" of every row as a hash ref | ||||
5928 | (with keys named "foo" and "BAR"): | ||||
5929 | |||||
5930 | $tbl_ary_ref = $sth->fetchall_arrayref({ foo=>1, BAR=>1 }); | ||||
5931 | |||||
5932 | The first two examples return a reference to an array of array refs. | ||||
5933 | The third and forth return a reference to an array of hash refs. | ||||
5934 | |||||
5935 | If $max_rows is defined and greater than or equal to zero then it | ||||
5936 | is used to limit the number of rows fetched before returning. | ||||
5937 | fetchall_arrayref() can then be called again to fetch more rows. | ||||
5938 | This is especially useful when you need the better performance of | ||||
5939 | fetchall_arrayref() but don't have enough memory to fetch and return | ||||
5940 | all the rows in one go. Here's an example: | ||||
5941 | |||||
5942 | my $rows = []; # cache for batches of rows | ||||
5943 | while( my $row = ( shift(@$rows) || # get row from cache, or reload cache: | ||||
5944 | shift(@{$rows=$sth->fetchall_arrayref(undef,10_000)||[]}) ) | ||||
5945 | ) { | ||||
5946 | ... | ||||
5947 | } | ||||
5948 | |||||
5949 | That can be the fastest way to fetch and process lots of rows using the DBI, | ||||
5950 | but it depends on the relative cost of method calls vs memory allocation. | ||||
5951 | |||||
5952 | A standard C<while> loop with column binding is often faster because | ||||
5953 | the cost of allocating memory for the batch of rows is greater than | ||||
5954 | the saving by reducing method calls. It's possible that the DBI may | ||||
5955 | provide a way to reuse the memory of a previous batch in future, which | ||||
5956 | would then shift the balance back towards fetchall_arrayref(). | ||||
5957 | |||||
5958 | |||||
5959 | =item C<fetchall_hashref> | ||||
5960 | |||||
5961 | $hash_ref = $sth->fetchall_hashref($key_field); | ||||
5962 | |||||
5963 | The C<fetchall_hashref> method can be used to fetch all the data to be | ||||
5964 | returned from a prepared and executed statement handle. It returns a reference | ||||
5965 | to a hash containing a key for each distinct value of the $key_field column | ||||
5966 | that was fetched. For each key the corresponding value is a reference to a hash | ||||
5967 | containing all the selected columns and their values, as returned by fetchrow_hashref(). | ||||
5968 | |||||
5969 | If there are no rows to return, C<fetchall_hashref> returns a reference | ||||
5970 | to an empty hash. If an error occurs, C<fetchall_hashref> returns the | ||||
5971 | data fetched thus far, which may be none. You should check | ||||
5972 | C<$sth-E<gt>err> afterwards (or use the C<RaiseError> attribute) to | ||||
5973 | discover if the data is complete or was truncated due to an error. | ||||
5974 | |||||
5975 | The $key_field parameter provides the name of the field that holds the | ||||
5976 | value to be used for the key for the returned hash. For example: | ||||
5977 | |||||
5978 | $dbh->{FetchHashKeyName} = 'NAME_lc'; | ||||
5979 | $sth = $dbh->prepare("SELECT FOO, BAR, ID, NAME, BAZ FROM TABLE"); | ||||
5980 | $sth->execute; | ||||
5981 | $hash_ref = $sth->fetchall_hashref('id'); | ||||
5982 | print "Name for id 42 is $hash_ref->{42}->{name}\n"; | ||||
5983 | |||||
5984 | The $key_field parameter can also be specified as an integer column | ||||
5985 | number (counting from 1). If $key_field doesn't match any column in | ||||
5986 | the statement, as a name first then as a number, then an error is | ||||
5987 | returned. | ||||
5988 | |||||
5989 | For queries returing more than one 'key' column, you can specify | ||||
5990 | multiple column names by passing $key_field as a reference to an | ||||
5991 | array containing one or more key column names (or index numbers). | ||||
5992 | For example: | ||||
5993 | |||||
5994 | $sth = $dbh->prepare("SELECT foo, bar, baz FROM table"); | ||||
5995 | $sth->execute; | ||||
5996 | $hash_ref = $sth->fetchall_hashref( [ qw(foo bar) ] ); | ||||
5997 | print "For foo 42 and bar 38, baz is $hash_ref->{42}->{38}->{baz}\n"; | ||||
5998 | |||||
5999 | The fetchall_hashref() method is normally used only where the key | ||||
6000 | fields values for each row are unique. If multiple rows are returned | ||||
6001 | with the same values for the key fields then later rows overwrite | ||||
6002 | earlier ones. | ||||
6003 | |||||
6004 | =item C<finish> | ||||
6005 | |||||
6006 | $rc = $sth->finish; | ||||
6007 | |||||
6008 | Indicate that no more data will be fetched from this statement handle | ||||
6009 | before it is either executed again or destroyed. The C<finish> method | ||||
6010 | is rarely needed, and frequently overused, but can sometimes be | ||||
6011 | helpful in a few very specific situations to allow the server to free | ||||
6012 | up resources (such as sort buffers). | ||||
6013 | |||||
6014 | When all the data has been fetched from a C<SELECT> statement, the | ||||
6015 | driver should automatically call C<finish> for you. So you should | ||||
6016 | I<not> normally need to call it explicitly I<except> when you know | ||||
6017 | that you've not fetched all the data from a statement handle. | ||||
6018 | The most common example is when you only want to fetch one row, | ||||
6019 | but in that case the C<selectrow_*> methods are usually better anyway. | ||||
6020 | Adding calls to C<finish> after each fetch loop is a common mistake, | ||||
6021 | don't do it, it can mask genuine problems like uncaught fetch errors. | ||||
6022 | |||||
6023 | Consider a query like: | ||||
6024 | |||||
6025 | SELECT foo FROM table WHERE bar=? ORDER BY foo | ||||
6026 | |||||
6027 | where you want to select just the first (smallest) "foo" value from a | ||||
6028 | very large table. When executed, the database server will have to use | ||||
6029 | temporary buffer space to store the sorted rows. If, after executing | ||||
6030 | the handle and selecting one row, the handle won't be re-executed for | ||||
6031 | some time and won't be destroyed, the C<finish> method can be used to tell | ||||
6032 | the server that the buffer space can be freed. | ||||
6033 | |||||
6034 | Calling C<finish> resets the L</Active> attribute for the statement. It | ||||
6035 | may also make some statement handle attributes (such as C<NAME> and C<TYPE>) | ||||
6036 | unavailable if they have not already been accessed (and thus cached). | ||||
6037 | |||||
6038 | The C<finish> method does not affect the transaction status of the | ||||
6039 | database connection. It has nothing to do with transactions. It's mostly an | ||||
6040 | internal "housekeeping" method that is rarely needed. | ||||
6041 | See also L</disconnect> and the L</Active> attribute. | ||||
6042 | |||||
6043 | The C<finish> method should have been called C<discard_pending_rows>. | ||||
6044 | |||||
6045 | |||||
6046 | =item C<rows> | ||||
6047 | |||||
6048 | $rv = $sth->rows; | ||||
6049 | |||||
6050 | Returns the number of rows affected by the last row affecting command, | ||||
6051 | or -1 if the number of rows is not known or not available. | ||||
6052 | |||||
6053 | Generally, you can only rely on a row count after a I<non>-C<SELECT> | ||||
6054 | C<execute> (for some specific operations like C<UPDATE> and C<DELETE>), or | ||||
6055 | after fetching all the rows of a C<SELECT> statement. | ||||
6056 | |||||
6057 | For C<SELECT> statements, it is generally not possible to know how many | ||||
6058 | rows will be returned except by fetching them all. Some drivers will | ||||
6059 | return the number of rows the application has fetched so far, but | ||||
6060 | others may return -1 until all rows have been fetched. So use of the | ||||
6061 | C<rows> method or C<$DBI::rows> with C<SELECT> statements is not | ||||
6062 | recommended. | ||||
6063 | |||||
6064 | One alternative method to get a row count for a C<SELECT> is to execute a | ||||
6065 | "SELECT COUNT(*) FROM ..." SQL statement with the same "..." as your | ||||
6066 | query and then fetch the row count from that. | ||||
6067 | |||||
6068 | |||||
6069 | =item C<bind_col> | ||||
6070 | |||||
6071 | $rc = $sth->bind_col($column_number, \$var_to_bind); | ||||
6072 | $rc = $sth->bind_col($column_number, \$var_to_bind, \%attr ); | ||||
6073 | $rc = $sth->bind_col($column_number, \$var_to_bind, $bind_type ); | ||||
6074 | |||||
6075 | Binds a Perl variable and/or some attributes to an output column | ||||
6076 | (field) of a C<SELECT> statement. Column numbers count up from 1. | ||||
6077 | You do not need to bind output columns in order to fetch data. | ||||
6078 | For maximum portability between drivers, bind_col() should be called | ||||
6079 | after execute() and not before. | ||||
6080 | See also C<bind_columns> for an example. | ||||
6081 | |||||
6082 | The binding is performed at a low level using Perl aliasing. | ||||
6083 | Whenever a row is fetched from the database $var_to_bind appears | ||||
6084 | to be automatically updated simply because it now refers to the same | ||||
6085 | memory location as the corresponding column value. This makes using | ||||
6086 | bound variables very efficient. | ||||
6087 | Binding a tied variable doesn't work, currently. | ||||
6088 | |||||
6089 | The L</bind_param> method | ||||
6090 | performs a similar, but opposite, function for input variables. | ||||
6091 | |||||
6092 | B<Data Types for Column Binding> | ||||
6093 | |||||
6094 | The C<\%attr> parameter can be used to hint at the data type | ||||
6095 | formatting the column should have. For example, you can use: | ||||
6096 | |||||
6097 | $sth->bind_col(1, undef, { TYPE => SQL_DATETIME }); | ||||
6098 | |||||
6099 | to specify that you'd like the column (which presumably is some | ||||
6100 | kind of datetime type) to be returned in the standard format for | ||||
6101 | SQL_DATETIME, which is 'YYYY-MM-DD HH:MM:SS', rather than the | ||||
6102 | native formatting the database would normally use. | ||||
6103 | |||||
6104 | There's no $var_to_bind in that example to emphasize the point | ||||
6105 | that bind_col() works on the underlying column value and not just | ||||
6106 | a particular bound variable. | ||||
6107 | |||||
6108 | As a short-cut for the common case, the data type can be passed | ||||
6109 | directly, in place of the C<\%attr> hash reference. This example is | ||||
6110 | equivalent to the one above: | ||||
6111 | |||||
6112 | $sth->bind_col(1, undef, SQL_DATETIME); | ||||
6113 | |||||
6114 | The C<TYPE> value indicates the standard (non-driver-specific) type for | ||||
6115 | this parameter. To specify the driver-specific type, the driver may | ||||
6116 | support a driver-specific attribute, such as C<{ ora_type =E<gt> 97 }>. | ||||
6117 | |||||
6118 | The SQL_DATETIME and other related constants can be imported using | ||||
6119 | |||||
6120 | use DBI qw(:sql_types); | ||||
6121 | |||||
6122 | See L</"DBI Constants"> for more information. | ||||
6123 | |||||
6124 | The data type for a bind variable cannot be changed after the first | ||||
6125 | C<bind_col> call. In fact the whole \%attr parameter is 'sticky' | ||||
6126 | in the sense that a driver only needs to consider the \%attr parameter | ||||
6127 | for the first call for a given $sth and column. | ||||
6128 | |||||
6129 | The TYPE attribute for bind_col() was first specified in DBI 1.41. | ||||
6130 | |||||
6131 | |||||
6132 | =item C<bind_columns> | ||||
6133 | |||||
6134 | $rc = $sth->bind_columns(@list_of_refs_to_vars_to_bind); | ||||
6135 | |||||
6136 | Calls L</bind_col> for each column of the C<SELECT> statement. | ||||
6137 | |||||
6138 | The list of references should have the same number of elements as the number of | ||||
6139 | columns in the C<SELECT> statement. If it doesn't then C<bind_columns> will | ||||
6140 | bind the elements given, upto the number of columns, and then return an error. | ||||
6141 | |||||
6142 | For maximum portability between drivers, bind_columns() should be called | ||||
6143 | after execute() and not before. | ||||
6144 | |||||
6145 | For example: | ||||
6146 | |||||
6147 | $dbh->{RaiseError} = 1; # do this, or check every call for errors | ||||
6148 | $sth = $dbh->prepare(q{ SELECT region, sales FROM sales_by_region }); | ||||
6149 | $sth->execute; | ||||
6150 | my ($region, $sales); | ||||
6151 | |||||
6152 | # Bind Perl variables to columns: | ||||
6153 | $rv = $sth->bind_columns(\$region, \$sales); | ||||
6154 | |||||
6155 | # you can also use Perl's \(...) syntax (see perlref docs): | ||||
6156 | # $sth->bind_columns(\($region, $sales)); | ||||
6157 | |||||
6158 | # Column binding is the most efficient way to fetch data | ||||
6159 | while ($sth->fetch) { | ||||
6160 | print "$region: $sales\n"; | ||||
6161 | } | ||||
6162 | |||||
6163 | For compatibility with old scripts, the first parameter will be | ||||
6164 | ignored if it is C<undef> or a hash reference. | ||||
6165 | |||||
6166 | Here's a more fancy example that binds columns to the values I<inside> | ||||
6167 | a hash (thanks to H.Merijn Brand): | ||||
6168 | |||||
6169 | $sth->execute; | ||||
6170 | my %row; | ||||
6171 | $sth->bind_columns( \( @row{ @{$sth->{NAME_lc} } } )); | ||||
6172 | while ($sth->fetch) { | ||||
6173 | print "$row{region}: $row{sales}\n"; | ||||
6174 | } | ||||
6175 | |||||
6176 | |||||
6177 | =item C<dump_results> | ||||
6178 | |||||
6179 | $rows = $sth->dump_results($maxlen, $lsep, $fsep, $fh); | ||||
6180 | |||||
6181 | Fetches all the rows from C<$sth>, calls C<DBI::neat_list> for each row, and | ||||
6182 | prints the results to C<$fh> (defaults to C<STDOUT>) separated by C<$lsep> | ||||
6183 | (default C<"\n">). C<$fsep> defaults to C<", "> and C<$maxlen> defaults to 35. | ||||
6184 | |||||
6185 | This method is designed as a handy utility for prototyping and | ||||
6186 | testing queries. Since it uses L</neat_list> to | ||||
6187 | format and edit the string for reading by humans, it is not recomended | ||||
6188 | for data transfer applications. | ||||
6189 | |||||
6190 | =back | ||||
6191 | |||||
6192 | |||||
6193 | =head2 Statement Handle Attributes | ||||
6194 | |||||
6195 | This section describes attributes specific to statement handles. Most | ||||
6196 | of these attributes are read-only. | ||||
6197 | |||||
6198 | Changes to these statement handle attributes do not affect any other | ||||
6199 | existing or future statement handles. | ||||
6200 | |||||
6201 | Attempting to set or get the value of an unknown attribute generates a warning, | ||||
6202 | except for private driver specific attributes (which all have names | ||||
6203 | starting with a lowercase letter). | ||||
6204 | |||||
6205 | Example: | ||||
6206 | |||||
6207 | ... = $h->{NUM_OF_FIELDS}; # get/read | ||||
6208 | |||||
6209 | Some drivers cannot provide valid values for some or all of these | ||||
6210 | attributes until after C<$sth-E<gt>execute> has been successfully | ||||
6211 | called. Typically the attribute will be C<undef> in these situations. | ||||
6212 | |||||
6213 | Some attributes, like NAME, are not appropriate to some types of | ||||
6214 | statement, like SELECT. Typically the attribute will be C<undef> | ||||
6215 | in these situations. | ||||
6216 | |||||
6217 | See also L</finish> to learn more about the effect it | ||||
6218 | may have on some attributes. | ||||
6219 | |||||
6220 | =over 4 | ||||
6221 | |||||
6222 | =item C<NUM_OF_FIELDS> (integer, read-only) | ||||
6223 | |||||
6224 | Number of fields (columns) in the data the prepared statement may return. | ||||
6225 | Statements that don't return rows of data, like C<DELETE> and C<CREATE> | ||||
6226 | set C<NUM_OF_FIELDS> to 0 (though it may be undef in some drivers). | ||||
6227 | |||||
6228 | |||||
6229 | =item C<NUM_OF_PARAMS> (integer, read-only) | ||||
6230 | |||||
6231 | The number of parameters (placeholders) in the prepared statement. | ||||
6232 | See SUBSTITUTION VARIABLES below for more details. | ||||
6233 | |||||
6234 | |||||
6235 | =item C<NAME> (array-ref, read-only) | ||||
6236 | |||||
6237 | Returns a reference to an array of field names for each column. The | ||||
6238 | names may contain spaces but should not be truncated or have any | ||||
6239 | trailing space. Note that the names have the letter case (upper, lower | ||||
6240 | or mixed) as returned by the driver being used. Portable applications | ||||
6241 | should use L</NAME_lc> or L</NAME_uc>. | ||||
6242 | |||||
6243 | print "First column name: $sth->{NAME}->[0]\n"; | ||||
6244 | |||||
6245 | =item C<NAME_lc> (array-ref, read-only) | ||||
6246 | |||||
6247 | Like L</NAME> but always returns lowercase names. | ||||
6248 | |||||
6249 | =item C<NAME_uc> (array-ref, read-only) | ||||
6250 | |||||
6251 | Like L</NAME> but always returns uppercase names. | ||||
6252 | |||||
6253 | =item C<NAME_hash> (hash-ref, read-only) | ||||
6254 | |||||
6255 | =item C<NAME_lc_hash> (hash-ref, read-only) | ||||
6256 | |||||
6257 | =item C<NAME_uc_hash> (hash-ref, read-only) | ||||
6258 | |||||
6259 | The C<NAME_hash>, C<NAME_lc_hash>, and C<NAME_uc_hash> attributes | ||||
6260 | return column name information as a reference to a hash. | ||||
6261 | |||||
6262 | The keys of the hash are the names of the columns. The letter case of | ||||
6263 | the keys corresponds to the letter case returned by the C<NAME>, | ||||
6264 | C<NAME_lc>, and C<NAME_uc> attributes respectively (as described above). | ||||
6265 | |||||
6266 | The value of each hash entry is the perl index number of the | ||||
6267 | corresponding column (counting from 0). For example: | ||||
6268 | |||||
6269 | $sth = $dbh->prepare("select Id, Name from table"); | ||||
6270 | $sth->execute; | ||||
6271 | @row = $sth->fetchrow_array; | ||||
6272 | print "Name $row[ $sth->{NAME_lc_hash}{name} ]\n"; | ||||
6273 | |||||
6274 | |||||
6275 | =item C<TYPE> (array-ref, read-only) | ||||
6276 | |||||
6277 | Returns a reference to an array of integer values for each | ||||
6278 | column. The value indicates the data type of the corresponding column. | ||||
6279 | |||||
6280 | The values correspond to the international standards (ANSI X3.135 | ||||
6281 | and ISO/IEC 9075) which, in general terms, means ODBC. Driver-specific | ||||
6282 | types that don't exactly match standard types should generally return | ||||
6283 | the same values as an ODBC driver supplied by the makers of the | ||||
6284 | database. That might include private type numbers in ranges the vendor | ||||
6285 | has officially registered with the ISO working group: | ||||
6286 | |||||
6287 | ftp://sqlstandards.org/SC32/SQL_Registry/ | ||||
6288 | |||||
6289 | Where there's no vendor-supplied ODBC driver to be compatible with, | ||||
6290 | the DBI driver can use type numbers in the range that is now | ||||
6291 | officially reserved for use by the DBI: -9999 to -9000. | ||||
6292 | |||||
6293 | All possible values for C<TYPE> should have at least one entry in the | ||||
6294 | output of the C<type_info_all> method (see L</type_info_all>). | ||||
6295 | |||||
6296 | =item C<PRECISION> (array-ref, read-only) | ||||
6297 | |||||
6298 | Returns a reference to an array of integer values for each column. | ||||
6299 | |||||
6300 | For numeric columns, the value is the maximum number of digits | ||||
6301 | (without considering a sign character or decimal point). Note that | ||||
6302 | the "display size" for floating point types (REAL, FLOAT, DOUBLE) | ||||
6303 | can be up to 7 characters greater than the precision (for the | ||||
6304 | sign + decimal point + the letter E + a sign + 2 or 3 digits). | ||||
6305 | |||||
6306 | For any character type column the value is the OCTET_LENGTH, | ||||
6307 | in other words the number of bytes, not characters. | ||||
6308 | |||||
6309 | (More recent standards refer to this as COLUMN_SIZE but we stick | ||||
6310 | with PRECISION for backwards compatibility.) | ||||
6311 | |||||
6312 | =item C<SCALE> (array-ref, read-only) | ||||
6313 | |||||
6314 | Returns a reference to an array of integer values for each column. | ||||
6315 | NULL (C<undef>) values indicate columns where scale is not applicable. | ||||
6316 | |||||
6317 | =item C<NULLABLE> (array-ref, read-only) | ||||
6318 | |||||
6319 | Returns a reference to an array indicating the possibility of each | ||||
6320 | column returning a null. Possible values are C<0> | ||||
6321 | (or an empty string) = no, C<1> = yes, C<2> = unknown. | ||||
6322 | |||||
6323 | print "First column may return NULL\n" if $sth->{NULLABLE}->[0]; | ||||
6324 | |||||
6325 | |||||
6326 | =item C<CursorName> (string, read-only) | ||||
6327 | |||||
6328 | Returns the name of the cursor associated with the statement handle, if | ||||
6329 | available. If not available or if the database driver does not support the | ||||
6330 | C<"where current of ..."> SQL syntax, then it returns C<undef>. | ||||
6331 | |||||
6332 | |||||
6333 | =item C<Database> (dbh, read-only) | ||||
6334 | |||||
6335 | Returns the parent $dbh of the statement handle. | ||||
6336 | |||||
6337 | |||||
6338 | =item C<ParamValues> (hash ref, read-only) | ||||
6339 | |||||
6340 | Returns a reference to a hash containing the values currently bound | ||||
6341 | to placeholders. The keys of the hash are the 'names' of the | ||||
6342 | placeholders, typically integers starting at 1. Returns undef if | ||||
6343 | not supported by the driver. | ||||
6344 | |||||
6345 | See L</ShowErrorStatement> for an example of how this is used. | ||||
6346 | |||||
6347 | If the driver supports C<ParamValues> but no values have been bound | ||||
6348 | yet then the driver should return a hash with placeholders names | ||||
6349 | in the keys but all the values undef, but some drivers may return | ||||
6350 | a ref to an empty hash. | ||||
6351 | |||||
6352 | It is possible that the values in the hash returned by C<ParamValues> | ||||
6353 | are not I<exactly> the same as those passed to bind_param() or execute(). | ||||
6354 | The driver may have slightly modified values in some way based on the | ||||
6355 | TYPE the value was bound with. For example a floating point value | ||||
6356 | bound as an SQL_INTEGER type may be returned as an integer. | ||||
6357 | The values returned by C<ParamValues> can be passed to another | ||||
6358 | bind_param() method with the same TYPE and will be seen by the | ||||
6359 | database as the same value. | ||||
6360 | |||||
6361 | It is also possible that the keys in the hash returned by C<ParamValues> | ||||
6362 | are not exactly the same as those implied by the prepared statement. | ||||
6363 | For example, DBD::Oracle translates 'C<?>' placeholders into 'C<:pN>' | ||||
6364 | where N is a sequence number starting at 1. | ||||
6365 | |||||
6366 | The C<ParamValues> attribute was added in DBI 1.28. | ||||
6367 | |||||
6368 | =item C<ParamArrays> (hash ref, read-only) | ||||
6369 | |||||
6370 | Returns a reference to a hash containing the values currently bound to | ||||
6371 | placeholders with L</execute_array> or L</bind_param_array>. The | ||||
6372 | keys of the hash are the 'names' of the placeholders, typically | ||||
6373 | integers starting at 1. Returns undef if not supported by the driver | ||||
6374 | or no arrays of parameters are bound. | ||||
6375 | |||||
6376 | Each key value is an array reference containing a list of the bound | ||||
6377 | parameters for that column. | ||||
6378 | |||||
6379 | For example: | ||||
6380 | |||||
6381 | $sth = $dbh->prepare("INSERT INTO staff (id, name) values (?,?)"); | ||||
6382 | $sth->execute_array({},[1,2], ['fred','dave']); | ||||
6383 | if ($sth->{ParamArrays}) { | ||||
6384 | foreach $param (keys %{$sth->{ParamArrays}}) { | ||||
6385 | printf "Parameters for %s : %s\n", $param, | ||||
6386 | join(",", @{$sth->{ParamArrays}->{$param}}); | ||||
6387 | } | ||||
6388 | } | ||||
6389 | |||||
6390 | It is possible that the values in the hash returned by C<ParamArrays> | ||||
6391 | are not I<exactly> the same as those passed to L</bind_param_array> or | ||||
6392 | L</execute_array>. The driver may have slightly modified values in some | ||||
6393 | way based on the TYPE the value was bound with. For example a floating | ||||
6394 | point value bound as an SQL_INTEGER type may be returned as an | ||||
6395 | integer. | ||||
6396 | |||||
6397 | It is also possible that the keys in the hash returned by | ||||
6398 | C<ParamArrays> are not exactly the same as those implied by the | ||||
6399 | prepared statement. For example, DBD::Oracle translates 'C<?>' | ||||
6400 | placeholders into 'C<:pN>' where N is a sequence number starting at 1. | ||||
6401 | |||||
6402 | =item C<ParamTypes> (hash ref, read-only) | ||||
6403 | |||||
6404 | Returns a reference to a hash containing the type information | ||||
6405 | currently bound to placeholders. The keys of the hash are the | ||||
6406 | 'names' of the placeholders: either integers starting at 1, or, | ||||
6407 | for drivers that support named placeholders, the actual parameter | ||||
6408 | name string. The hash values are hashrefs of type information in | ||||
6409 | the same form as that provided to the various bind_param() methods | ||||
6410 | (See L</"Data Types for Placeholders"> for the format and values), | ||||
6411 | plus anything else that was passed as the third argument to bind_param(). | ||||
6412 | Returns undef if not supported by the driver. | ||||
6413 | |||||
6414 | If the driver supports C<ParamTypes>, but no values have been bound | ||||
6415 | yet, then the driver should return a hash with the placeholder name | ||||
6416 | keys, but all the values undef; however, some drivers may return | ||||
6417 | a ref to an empty hash, or, alternately, may provide type | ||||
6418 | information supplied by the database (only a few databases can do that). | ||||
6419 | |||||
6420 | It is possible that the values in the hash returned by C<ParamTypes> | ||||
6421 | are not I<exactly> the same as those passed to bind_param() or execute(). | ||||
6422 | The driver may have modified the type information in some way based | ||||
6423 | on the bound values, other hints provided by the prepare()'d | ||||
6424 | SQL statement, or alternate type mappings required by the driver or target | ||||
6425 | database system. | ||||
6426 | |||||
6427 | It is also possible that the keys in the hash returned by C<ParamTypes> | ||||
6428 | are not exactly the same as those implied by the prepared statement. | ||||
6429 | For example, DBD::Oracle translates 'C<?>' placeholders into 'C<:pN>' | ||||
6430 | where N is a sequence number starting at 1. | ||||
6431 | |||||
6432 | The C<ParamTypes> attribute was added in DBI 1.49. Implementation | ||||
6433 | is the responsibility of individual drivers; the DBI layer default | ||||
6434 | implementation simply returns undef. | ||||
6435 | |||||
6436 | |||||
6437 | =item C<Statement> (string, read-only) | ||||
6438 | |||||
6439 | Returns the statement string passed to the L</prepare> method. | ||||
6440 | |||||
6441 | |||||
6442 | =item C<RowsInCache> (integer, read-only) | ||||
6443 | |||||
6444 | If the driver supports a local row cache for C<SELECT> statements, then | ||||
6445 | this attribute holds the number of un-fetched rows in the cache. If the | ||||
6446 | driver doesn't, then it returns C<undef>. Note that some drivers pre-fetch | ||||
6447 | rows on execute, whereas others wait till the first fetch. | ||||
6448 | |||||
6449 | See also the L</RowCacheSize> database handle attribute. | ||||
6450 | |||||
6451 | =back | ||||
6452 | |||||
6453 | =head1 OTHER METHODS | ||||
6454 | |||||
6455 | =over 4 | ||||
6456 | |||||
6457 | =item C<install_method> | ||||
6458 | |||||
6459 | DBD::Foo::db->install_method($method_name, \%attr); | ||||
6460 | |||||
6461 | Installs the driver-private method named by $method_name into the | ||||
6462 | DBI method dispatcher so it can be called directly, avoiding the | ||||
6463 | need to use the func() method. | ||||
6464 | |||||
6465 | It is called as a static method on the driver class to which the | ||||
6466 | method belongs. The method name must begin with the corresponding | ||||
6467 | registered driver-private prefix. For example, for DBD::Oracle | ||||
6468 | $method_name must being with 'C<ora_>', and for DBD::AnyData it | ||||
6469 | must begin with 'C<ad_>'. | ||||
6470 | |||||
6471 | The attributes can be used to provide fine control over how the DBI | ||||
6472 | dispatcher handles the dispatching of the method. However, at this | ||||
6473 | point, it's undocumented and very liable to change. (Volunteers to | ||||
6474 | polish up and document the interface are very welcome to get in | ||||
6475 | touch via dbi-dev@perl.org) | ||||
6476 | |||||
6477 | Methods installed using install_method default to the standard error | ||||
6478 | handling behaviour for DBI methods: clearing err and errstr before | ||||
6479 | calling the method, and checking for errors to trigger RaiseError | ||||
6480 | etc. on return. This differs from the default behaviour of func(). | ||||
6481 | |||||
6482 | Note for driver authors: The DBD::Foo::xx->install_method call won't | ||||
6483 | work until the class-hierarchy has been setup. Normally the DBI | ||||
6484 | looks after that just after the driver is loaded. This means | ||||
6485 | install_method() can't be called at the time the driver is loaded | ||||
6486 | unless the class-hierarchy is set up first. The way to do that is | ||||
6487 | to call the setup_driver() method: | ||||
6488 | |||||
6489 | DBI->setup_driver('DBD::Foo'); | ||||
6490 | |||||
6491 | before using install_method(). | ||||
6492 | |||||
6493 | |||||
6494 | =back | ||||
6495 | |||||
6496 | =head1 FURTHER INFORMATION | ||||
6497 | |||||
6498 | =head2 Catalog Methods | ||||
6499 | |||||
6500 | An application can retrieve metadata information from the DBMS by issuing | ||||
6501 | appropriate queries on the views of the Information Schema. Unfortunately, | ||||
6502 | C<INFORMATION_SCHEMA> views are seldom supported by the DBMS. | ||||
6503 | Special methods (catalog methods) are available to return result sets | ||||
6504 | for a small but important portion of that metadata: | ||||
6505 | |||||
6506 | column_info | ||||
6507 | foreign_key_info | ||||
6508 | primary_key_info | ||||
6509 | table_info | ||||
6510 | statistics_info | ||||
6511 | |||||
6512 | All catalog methods accept arguments in order to restrict the result sets. | ||||
6513 | Passing C<undef> to an optional argument does not constrain the search for | ||||
6514 | that argument. | ||||
6515 | However, an empty string ('') is treated as a regular search criteria | ||||
6516 | and will only match an empty value. | ||||
6517 | |||||
6518 | B<Note>: SQL/CLI and ODBC differ in the handling of empty strings. An | ||||
6519 | empty string will not restrict the result set in SQL/CLI. | ||||
6520 | |||||
6521 | Most arguments in the catalog methods accept only I<ordinary values>, e.g. | ||||
6522 | the arguments of C<primary_key_info()>. | ||||
6523 | Such arguments are treated as a literal string, i.e. the case is significant | ||||
6524 | and quote characters are taken literally. | ||||
6525 | |||||
6526 | Some arguments in the catalog methods accept I<search patterns> (strings | ||||
6527 | containing '_' and/or '%'), e.g. the C<$table> argument of C<column_info()>. | ||||
6528 | Passing '%' is equivalent to leaving the argument C<undef>. | ||||
6529 | |||||
6530 | B<Caveat>: The underscore ('_') is valid and often used in SQL identifiers. | ||||
6531 | Passing such a value to a search pattern argument may return more rows than | ||||
6532 | expected! | ||||
6533 | To include pattern characters as literals, they must be preceded by an | ||||
6534 | escape character which can be achieved with | ||||
6535 | |||||
6536 | $esc = $dbh->get_info( 14 ); # SQL_SEARCH_PATTERN_ESCAPE | ||||
6537 | $search_pattern =~ s/([_%])/$esc$1/g; | ||||
6538 | |||||
6539 | The ODBC and SQL/CLI specifications define a way to change the default | ||||
6540 | behaviour described above: All arguments (except I<list value arguments>) | ||||
6541 | are treated as I<identifier> if the C<SQL_ATTR_METADATA_ID> attribute is | ||||
6542 | set to C<SQL_TRUE>. | ||||
6543 | I<Quoted identifiers> are very similar to I<ordinary values>, i.e. their | ||||
6544 | body (the string within the quotes) is interpreted literally. | ||||
6545 | I<Unquoted identifiers> are compared in UPPERCASE. | ||||
6546 | |||||
6547 | The DBI (currently) does not support the C<SQL_ATTR_METADATA_ID> attribute, | ||||
6548 | i.e. it behaves like an ODBC driver where C<SQL_ATTR_METADATA_ID> is set to | ||||
6549 | C<SQL_FALSE>. | ||||
6550 | |||||
6551 | |||||
6552 | =head2 Transactions | ||||
6553 | |||||
6554 | Transactions are a fundamental part of any robust database system. They | ||||
6555 | protect against errors and database corruption by ensuring that sets of | ||||
6556 | related changes to the database take place in atomic (indivisible, | ||||
6557 | all-or-nothing) units. | ||||
6558 | |||||
6559 | This section applies to databases that support transactions and where | ||||
6560 | C<AutoCommit> is off. See L</AutoCommit> for details of using C<AutoCommit> | ||||
6561 | with various types of databases. | ||||
6562 | |||||
6563 | The recommended way to implement robust transactions in Perl | ||||
6564 | applications is to use C<RaiseError> and S<C<eval { ... }>> | ||||
6565 | (which is very fast, unlike S<C<eval "...">>). For example: | ||||
6566 | |||||
6567 | $dbh->{AutoCommit} = 0; # enable transactions, if possible | ||||
6568 | $dbh->{RaiseError} = 1; | ||||
6569 | eval { | ||||
6570 | foo(...) # do lots of work here | ||||
6571 | bar(...) # including inserts | ||||
6572 | baz(...) # and updates | ||||
6573 | $dbh->commit; # commit the changes if we get this far | ||||
6574 | }; | ||||
6575 | if ($@) { | ||||
6576 | warn "Transaction aborted because $@"; | ||||
6577 | # now rollback to undo the incomplete changes | ||||
6578 | # but do it in an eval{} as it may also fail | ||||
6579 | eval { $dbh->rollback }; | ||||
6580 | # add other application on-error-clean-up code here | ||||
6581 | } | ||||
6582 | |||||
6583 | If the C<RaiseError> attribute is not set, then DBI calls would need to be | ||||
6584 | manually checked for errors, typically like this: | ||||
6585 | |||||
6586 | $h->method(@args) or die $h->errstr; | ||||
6587 | |||||
6588 | With C<RaiseError> set, the DBI will automatically C<die> if any DBI method | ||||
6589 | call on that handle (or a child handle) fails, so you don't have to | ||||
6590 | test the return value of each method call. See L</RaiseError> for more | ||||
6591 | details. | ||||
6592 | |||||
6593 | A major advantage of the C<eval> approach is that the transaction will be | ||||
6594 | properly rolled back if I<any> code (not just DBI calls) in the inner | ||||
6595 | application dies for any reason. The major advantage of using the | ||||
6596 | C<$h-E<gt>{RaiseError}> attribute is that all DBI calls will be checked | ||||
6597 | automatically. Both techniques are strongly recommended. | ||||
6598 | |||||
6599 | After calling C<commit> or C<rollback> many drivers will not let you | ||||
6600 | fetch from a previously active C<SELECT> statement handle that's a child | ||||
6601 | of the same database handle. A typical way round this is to connect the | ||||
6602 | the database twice and use one connection for C<SELECT> statements. | ||||
6603 | |||||
6604 | See L</AutoCommit> and L</disconnect> for other important information | ||||
6605 | about transactions. | ||||
6606 | |||||
6607 | |||||
6608 | =head2 Handling BLOB / LONG / Memo Fields | ||||
6609 | |||||
6610 | Many databases support "blob" (binary large objects), "long", or similar | ||||
6611 | datatypes for holding very long strings or large amounts of binary | ||||
6612 | data in a single field. Some databases support variable length long | ||||
6613 | values over 2,000,000,000 bytes in length. | ||||
6614 | |||||
6615 | Since values of that size can't usually be held in memory, and because | ||||
6616 | databases can't usually know in advance the length of the longest long | ||||
6617 | that will be returned from a C<SELECT> statement (unlike other data | ||||
6618 | types), some special handling is required. | ||||
6619 | |||||
6620 | In this situation, the value of the C<$h-E<gt>{LongReadLen}> | ||||
6621 | attribute is used to determine how much buffer space to allocate | ||||
6622 | when fetching such fields. The C<$h-E<gt>{LongTruncOk}> attribute | ||||
6623 | is used to determine how to behave if a fetched value can't fit | ||||
6624 | into the buffer. | ||||
6625 | |||||
6626 | See the description of L</LongReadLen> for more information. | ||||
6627 | |||||
6628 | When trying to insert long or binary values, placeholders should be used | ||||
6629 | since there are often limits on the maximum size of an C<INSERT> | ||||
6630 | statement and the L</quote> method generally can't cope with binary | ||||
6631 | data. See L</Placeholders and Bind Values>. | ||||
6632 | |||||
6633 | |||||
6634 | =head2 Simple Examples | ||||
6635 | |||||
6636 | Here's a complete example program to select and fetch some data: | ||||
6637 | |||||
6638 | my $data_source = "dbi::DriverName:db_name"; | ||||
6639 | my $dbh = DBI->connect($data_source, $user, $password) | ||||
6640 | or die "Can't connect to $data_source: $DBI::errstr"; | ||||
6641 | |||||
6642 | my $sth = $dbh->prepare( q{ | ||||
6643 | SELECT name, phone | ||||
6644 | FROM mytelbook | ||||
6645 | }) or die "Can't prepare statement: $DBI::errstr"; | ||||
6646 | |||||
6647 | my $rc = $sth->execute | ||||
6648 | or die "Can't execute statement: $DBI::errstr"; | ||||
6649 | |||||
6650 | print "Query will return $sth->{NUM_OF_FIELDS} fields.\n\n"; | ||||
6651 | print "Field names: @{ $sth->{NAME} }\n"; | ||||
6652 | |||||
6653 | while (($name, $phone) = $sth->fetchrow_array) { | ||||
6654 | print "$name: $phone\n"; | ||||
6655 | } | ||||
6656 | # check for problems which may have terminated the fetch early | ||||
6657 | die $sth->errstr if $sth->err; | ||||
6658 | |||||
6659 | $dbh->disconnect; | ||||
6660 | |||||
6661 | Here's a complete example program to insert some data from a file. | ||||
6662 | (This example uses C<RaiseError> to avoid needing to check each call). | ||||
6663 | |||||
6664 | my $dbh = DBI->connect("dbi:DriverName:db_name", $user, $password, { | ||||
6665 | RaiseError => 1, AutoCommit => 0 | ||||
6666 | }); | ||||
6667 | |||||
6668 | my $sth = $dbh->prepare( q{ | ||||
6669 | INSERT INTO table (name, phone) VALUES (?, ?) | ||||
6670 | }); | ||||
6671 | |||||
6672 | open FH, "<phone.csv" or die "Unable to open phone.csv: $!"; | ||||
6673 | while (<FH>) { | ||||
6674 | chomp; | ||||
6675 | my ($name, $phone) = split /,/; | ||||
6676 | $sth->execute($name, $phone); | ||||
6677 | } | ||||
6678 | close FH; | ||||
6679 | |||||
6680 | $dbh->commit; | ||||
6681 | $dbh->disconnect; | ||||
6682 | |||||
6683 | Here's how to convert fetched NULLs (undefined values) into empty strings: | ||||
6684 | |||||
6685 | while($row = $sth->fetchrow_arrayref) { | ||||
6686 | # this is a fast and simple way to deal with nulls: | ||||
6687 | foreach (@$row) { $_ = '' unless defined } | ||||
6688 | print "@$row\n"; | ||||
6689 | } | ||||
6690 | |||||
6691 | The C<q{...}> style quoting used in these examples avoids clashing with | ||||
6692 | quotes that may be used in the SQL statement. Use the double-quote like | ||||
6693 | C<qq{...}> operator if you want to interpolate variables into the string. | ||||
6694 | See L<perlop/"Quote and Quote-like Operators"> for more details. | ||||
6695 | |||||
6696 | =head2 Threads and Thread Safety | ||||
6697 | |||||
6698 | Perl 5.7 and later support a new threading model called iThreads. | ||||
6699 | (The old "5.005 style" threads are not supported by the DBI.) | ||||
6700 | |||||
6701 | In the iThreads model each thread has it's own copy of the perl | ||||
6702 | interpreter. When a new thread is created the original perl | ||||
6703 | interpreter is 'cloned' to create a new copy for the new thread. | ||||
6704 | |||||
6705 | If the DBI and drivers are loaded and handles created before the | ||||
6706 | thread is created then it will get a cloned copy of the DBI, the | ||||
6707 | drivers and the handles. | ||||
6708 | |||||
6709 | However, the internal pointer data within the handles will refer | ||||
6710 | to the DBI and drivers in the original interpreter. Using those | ||||
6711 | handles in the new interpreter thread is not safe, so the DBI detects | ||||
6712 | this and croaks on any method call using handles that don't belong | ||||
6713 | to the current thread (except for DESTROY). | ||||
6714 | |||||
6715 | Because of this (possibly temporary) restriction, newly created | ||||
6716 | threads must make their own connctions to the database. Handles | ||||
6717 | can't be shared across threads. | ||||
6718 | |||||
6719 | But BEWARE, some underlying database APIs (the code the DBD driver | ||||
6720 | uses to talk to the database, often supplied by the database vendor) | ||||
6721 | are not thread safe. If it's not thread safe, then allowing more | ||||
6722 | than one thread to enter the code at the same time may cause | ||||
6723 | subtle/serious problems. In some cases allowing more than | ||||
6724 | one thread to enter the code, even if I<not> at the same time, | ||||
6725 | can cause problems. You have been warned. | ||||
6726 | |||||
6727 | Using DBI with perl threads is not yet recommended for production | ||||
6728 | environments. For more information see | ||||
6729 | L<http://www.perlmonks.org/index.pl?node_id=288022> | ||||
6730 | |||||
6731 | Note: There is a bug in perl 5.8.2 when configured with threads | ||||
6732 | and debugging enabled (bug #24463) which causes a DBI test to fail. | ||||
6733 | |||||
6734 | =head2 Signal Handling and Canceling Operations | ||||
6735 | |||||
6736 | [The following only applies to systems with unix-like signal handling. | ||||
6737 | I'd welcome additions for other systems, especially Windows.] | ||||
6738 | |||||
6739 | The first thing to say is that signal handling in Perl versions less | ||||
6740 | than 5.8 is I<not> safe. There is always a small risk of Perl | ||||
6741 | crashing and/or core dumping when, or after, handling a signal | ||||
6742 | because the signal could arrive and be handled while internal data | ||||
6743 | structures are being changed. If the signal handling code | ||||
6744 | used those same internal data structures it could cause all manner | ||||
6745 | of subtle and not-so-subtle problems. The risk was reduced with | ||||
6746 | 5.4.4 but was still present in all perls up through 5.8.0. | ||||
6747 | |||||
6748 | Beginning in perl 5.8.0 perl implements 'safe' signal handling if | ||||
6749 | your system has the POSIX sigaction() routine. Now when a signal | ||||
6750 | is delivered perl just makes a note of it but does I<not> run the | ||||
6751 | %SIG handler. The handling is 'defered' until a 'safe' moment. | ||||
6752 | |||||
6753 | Although this change made signal handling safe, it also lead to | ||||
6754 | a problem with signals being defered for longer than you'd like. | ||||
6755 | If a signal arrived while executing a system call, such as waiting | ||||
6756 | for data on a network connection, the signal is noted and then the | ||||
6757 | system call that was executing returns with an EINTR error code | ||||
6758 | to indicate that it was interrupted. All fine so far. | ||||
6759 | |||||
6760 | The problem comes when the code that made the system call sees the | ||||
6761 | EINTR code and decides it's going to call it again. Perl doesn't | ||||
6762 | do that, but database code sometimes does. If that happens then the | ||||
6763 | signal handler doesn't get called untill later. Maybe much later. | ||||
6764 | |||||
6765 | Fortunately there are ways around this which we'll discuss below. | ||||
6766 | Unfortunately they make signals unsafe again. | ||||
6767 | |||||
6768 | The two most common uses of signals in relation to the DBI are for | ||||
6769 | canceling operations when the user types Ctrl-C (interrupt), and for | ||||
6770 | implementing a timeout using C<alarm()> and C<$SIG{ALRM}>. | ||||
6771 | |||||
6772 | =over 4 | ||||
6773 | |||||
6774 | =item Cancel | ||||
6775 | |||||
6776 | The DBI provides a C<cancel> method for statement handles. The | ||||
6777 | C<cancel> method should abort the current operation and is designed | ||||
6778 | to be called from a signal handler. For example: | ||||
6779 | |||||
6780 | $SIG{INT} = sub { $sth->cancel }; | ||||
6781 | |||||
6782 | However, few drivers implement this (the DBI provides a default | ||||
6783 | method that just returns C<undef>) and, even if implemented, there | ||||
6784 | is still a possibility that the statement handle, and even the | ||||
6785 | parent database handle, will not be usable afterwards. | ||||
6786 | |||||
6787 | If C<cancel> returns true, then it has successfully | ||||
6788 | invoked the database engine's own cancel function. If it returns false, | ||||
6789 | then C<cancel> failed. If it returns C<undef>, then the database | ||||
6790 | driver does not have cancel implemented. | ||||
6791 | |||||
6792 | =item Timeout | ||||
6793 | |||||
6794 | The traditional way to implement a timeout is to set C<$SIG{ALRM}> | ||||
6795 | to refer to some code that will be executed when an ALRM signal | ||||
6796 | arrives and then to call alarm($seconds) to schedule an ALRM signal | ||||
6797 | to be delivered $seconds in the future. For example: | ||||
6798 | |||||
6799 | eval { | ||||
6800 | local $SIG{ALRM} = sub { die "TIMEOUT\n" }; | ||||
6801 | alarm($seconds); | ||||
6802 | ... code to execute with timeout here ... | ||||
6803 | alarm(0); # cancel alarm (if code ran fast) | ||||
6804 | }; | ||||
6805 | alarm(0); # cancel alarm (if eval failed) | ||||
6806 | if ( $@ eq "TIMEOUT" ) { ... } | ||||
6807 | |||||
6808 | Unfortunately, as described above, this won't always work as expected, | ||||
6809 | depending on your perl version and the underlying database code. | ||||
6810 | |||||
6811 | With Oracle for instance (DBD::Oracle), if the system which hosts | ||||
6812 | the database is down the DBI->connect() call will hang for several | ||||
6813 | minutes before returning an error. | ||||
6814 | |||||
6815 | =back | ||||
6816 | |||||
6817 | The solution on these systems is to use the C<POSIX::sigaction()> | ||||
6818 | routine to gain low level access to how the signal handler is installed. | ||||
6819 | |||||
6820 | The code would look something like this (for the DBD-Oracle connect()): | ||||
6821 | |||||
6822 | use POSIX ':signal_h'; | ||||
6823 | |||||
6824 | my $mask = POSIX::SigSet->new( SIGALRM ); # signals to mask in the handler | ||||
6825 | my $action = POSIX::SigAction->new( | ||||
6826 | sub { die "connect timeout" }, # the handler code ref | ||||
6827 | $mask, | ||||
6828 | # not using (perl 5.8.2 and later) 'safe' switch or sa_flags | ||||
6829 | ); | ||||
6830 | my $oldaction = POSIX::SigAction->new(); | ||||
6831 | sigaction( 'ALRM', $action, $oldaction ); | ||||
6832 | my $dbh; | ||||
6833 | eval { | ||||
6834 | alarm(5); # seconds before time out | ||||
6835 | $dbh = DBI->connect("dbi:Oracle:$dsn" ... ); | ||||
6836 | alarm(0); # cancel alarm (if connect worked fast) | ||||
6837 | }; | ||||
6838 | alarm(0); # cancel alarm (if eval failed) | ||||
6839 | sigaction( 'ALRM', $oldaction ); # restore original signal handler | ||||
6840 | if ( $@ ) .... | ||||
6841 | |||||
6842 | Similar techniques can be used for canceling statement execution. | ||||
6843 | |||||
6844 | Unfortunately, this solution is somewhat messy, and it does I<not> work with | ||||
6845 | perl versions less than perl 5.8 where C<POSIX::sigaction()> appears to be broken. | ||||
6846 | |||||
6847 | For a cleaner implementation that works across perl versions, see Lincoln Baxter's | ||||
6848 | Sys::SigAction module at L<http://search.cpan.org/~lbaxter/Sys-SigAction/>. | ||||
6849 | The documentation for Sys::SigAction includes an longer discussion | ||||
6850 | of this problem, and a DBD::Oracle test script. | ||||
6851 | |||||
6852 | Be sure to read all the signal handling sections of the L<perlipc> manual. | ||||
6853 | |||||
6854 | And finally, two more points to keep firmly in mind. Firstly, | ||||
6855 | remember that what we've done here is essentially revert to old | ||||
6856 | style I<unsafe> handling of these signals. So do as little as | ||||
6857 | possible in the handler. Ideally just die(). Secondly, the handles | ||||
6858 | in use at the time the signal is handled may not be safe to use | ||||
6859 | afterwards. | ||||
6860 | |||||
6861 | |||||
6862 | =head2 Subclassing the DBI | ||||
6863 | |||||
6864 | DBI can be subclassed and extended just like any other object | ||||
6865 | oriented module. Before we talk about how to do that, it's important | ||||
6866 | to be clear about the various DBI classes and how they work together. | ||||
6867 | |||||
6868 | By default C<$dbh = DBI-E<gt>connect(...)> returns a $dbh blessed | ||||
6869 | into the C<DBI::db> class. And the C<$dbh-E<gt>prepare> method | ||||
6870 | returns an $sth blessed into the C<DBI::st> class (actually it | ||||
6871 | simply changes the last four characters of the calling handle class | ||||
6872 | to be C<::st>). | ||||
6873 | |||||
6874 | The leading 'C<DBI>' is known as the 'root class' and the extra | ||||
6875 | 'C<::db>' or 'C<::st>' are the 'handle type suffixes'. If you want | ||||
6876 | to subclass the DBI you'll need to put your overriding methods into | ||||
6877 | the appropriate classes. For example, if you want to use a root class | ||||
6878 | of C<MySubDBI> and override the do(), prepare() and execute() methods, | ||||
6879 | then your do() and prepare() methods should be in the C<MySubDBI::db> | ||||
6880 | class and the execute() method should be in the C<MySubDBI::st> class. | ||||
6881 | |||||
6882 | To setup the inheritance hierarchy the @ISA variable in C<MySubDBI::db> | ||||
6883 | should include C<DBI::db> and the @ISA variable in C<MySubDBI::st> | ||||
6884 | should include C<DBI::st>. The C<MySubDBI> root class itself isn't | ||||
6885 | currently used for anything visible and so, apart from setting @ISA | ||||
6886 | to include C<DBI>, it can be left empty. | ||||
6887 | |||||
6888 | So, having put your overriding methods into the right classes, and | ||||
6889 | setup the inheritance hierarchy, how do you get the DBI to use them? | ||||
6890 | You have two choices, either a static method call using the name | ||||
6891 | of your subclass: | ||||
6892 | |||||
6893 | $dbh = MySubDBI->connect(...); | ||||
6894 | |||||
6895 | or specifying a C<RootClass> attribute: | ||||
6896 | |||||
6897 | $dbh = DBI->connect(..., { RootClass => 'MySubDBI' }); | ||||
6898 | |||||
6899 | If both forms are used then the attribute takes precedence. | ||||
6900 | |||||
6901 | The only differences between the two are that using an explicit | ||||
6902 | RootClass attribute will a) make the DBI automatically attempt to load | ||||
6903 | a module by that name if the class doesn't exist, and b) won't call | ||||
6904 | your MySubDBI::connect() method, if you have one. | ||||
6905 | |||||
6906 | When subclassing is being used then, after a successful new | ||||
6907 | connect, the DBI->connect method automatically calls: | ||||
6908 | |||||
6909 | $dbh->connected($dsn, $user, $pass, \%attr); | ||||
6910 | |||||
6911 | The default method does nothing. The call is made just to simplify | ||||
6912 | any post-connection setup that your subclass may want to perform. | ||||
6913 | The parameters are the same as passed to DBI->connect. | ||||
6914 | If your subclass supplies a connected method, it should be part of the | ||||
6915 | MySubDBI::db package. | ||||
6916 | |||||
6917 | One more thing to note: you must let the DBI do the handle creation. If you | ||||
6918 | want to override the connect() method in your *::dr class then it must still | ||||
6919 | call SUPER::connect to get a $dbh to work with. Similarly, an overridden | ||||
6920 | prepare() method in *::db must still call SUPER::prepare to get a $sth. | ||||
6921 | If you try to create your own handles using bless() then you'll find the DBI | ||||
6922 | will reject them with an "is not a DBI handle (has no magic)" error. | ||||
6923 | |||||
6924 | Here's a brief example of a DBI subclass. A more thorough example | ||||
6925 | can be found in F<t/subclass.t> in the DBI distribution. | ||||
6926 | |||||
6927 | package MySubDBI; | ||||
6928 | |||||
6929 | use strict; | ||||
6930 | |||||
6931 | use DBI; | ||||
6932 | use vars qw(@ISA); | ||||
6933 | @ISA = qw(DBI); | ||||
6934 | |||||
6935 | package MySubDBI::db; | ||||
6936 | use vars qw(@ISA); | ||||
6937 | @ISA = qw(DBI::db); | ||||
6938 | |||||
6939 | sub prepare { | ||||
6940 | my ($dbh, @args) = @_; | ||||
6941 | my $sth = $dbh->SUPER::prepare(@args) | ||||
6942 | or return; | ||||
6943 | $sth->{private_mysubdbi_info} = { foo => 'bar' }; | ||||
6944 | return $sth; | ||||
6945 | } | ||||
6946 | |||||
6947 | package MySubDBI::st; | ||||
6948 | use vars qw(@ISA); | ||||
6949 | @ISA = qw(DBI::st); | ||||
6950 | |||||
6951 | sub fetch { | ||||
6952 | my ($sth, @args) = @_; | ||||
6953 | my $row = $sth->SUPER::fetch(@args) | ||||
6954 | or return; | ||||
6955 | do_something_magical_with_row_data($row) | ||||
6956 | or return $sth->set_err(1234, "The magic failed", undef, "fetch"); | ||||
6957 | return $row; | ||||
6958 | } | ||||
6959 | |||||
6960 | When calling a SUPER::method that returns a handle, be careful to | ||||
6961 | check the return value before trying to do other things with it in | ||||
6962 | your overridden method. This is especially important if you want to | ||||
6963 | set a hash attribute on the handle, as Perl's autovivification will | ||||
6964 | bite you by (in)conveniently creating an unblessed hashref, which your | ||||
6965 | method will then return with usually baffling results later on like | ||||
6966 | the error "dbih_getcom handle HASH(0xa4451a8) is not a DBI handle (has | ||||
6967 | no magic". It's best to check right after the call and return undef | ||||
6968 | immediately on error, just like DBI would and just like the example | ||||
6969 | above. | ||||
6970 | |||||
6971 | If your method needs to record an error it should call the set_err() | ||||
6972 | method with the error code and error string, as shown in the example | ||||
6973 | above. The error code and error string will be recorded in the | ||||
6974 | handle and available via C<$h-E<gt>err> and C<$DBI::errstr> etc. | ||||
6975 | The set_err() method always returns an undef or empty list as | ||||
6976 | approriate. Since your method should nearly always return an undef | ||||
6977 | or empty list as soon as an error is detected it's handy to simply | ||||
6978 | return what set_err() returns, as shown in the example above. | ||||
6979 | |||||
6980 | If the handle has C<RaiseError>, C<PrintError>, or C<HandleError> | ||||
6981 | etc. set then the set_err() method will honour them. This means | ||||
6982 | that if C<RaiseError> is set then set_err() won't return in the | ||||
6983 | normal way but will 'throw an exception' that can be caught with | ||||
6984 | an C<eval> block. | ||||
6985 | |||||
6986 | You can stash private data into DBI handles | ||||
6987 | via C<$h-E<gt>{private_..._*}>. See the entry under L</ATTRIBUTES | ||||
6988 | COMMON TO ALL HANDLES> for info and important caveats. | ||||
6989 | |||||
6990 | |||||
6991 | =head1 TRACING | ||||
6992 | |||||
6993 | The DBI has a powerful tracing mechanism built in. It enables you | ||||
6994 | to see what's going on 'behind the scenes', both within the DBI and | ||||
6995 | the drivers you're using. | ||||
6996 | |||||
6997 | =head2 Trace Settings | ||||
6998 | |||||
6999 | Which details are written to the trace output is controlled by a | ||||
7000 | combination of a I<trace level>, an integer from 0 to 15, and a set | ||||
7001 | of I<trace flags> that are either on or off. Together these are known | ||||
7002 | as the I<trace settings> and are stored together in a single integer. | ||||
7003 | For normal use you only need to set the trace level, and generally | ||||
7004 | only to a value between 1 and 4. | ||||
7005 | |||||
7006 | Each handle has it's own trace settings, and so does the DBI. | ||||
7007 | When you call a method the DBI merges the handles settings into its | ||||
7008 | own for the duration of the call: the trace flags of the handle are | ||||
7009 | OR'd into the trace flags of the DBI, and if the handle has a higher | ||||
7010 | trace level then the DBI trace level is raised to match it. | ||||
7011 | The previous DBI trace setings are restored when the called method | ||||
7012 | returns. | ||||
7013 | |||||
7014 | =head2 Trace Levels | ||||
7015 | |||||
7016 | Trace I<levels> are as follows: | ||||
7017 | |||||
7018 | 0 - Trace disabled. | ||||
7019 | 1 - Trace DBI method calls returning with results or errors. | ||||
7020 | 2 - Trace method entry with parameters and returning with results. | ||||
7021 | 3 - As above, adding some high-level information from the driver | ||||
7022 | and some internal information from the DBI. | ||||
7023 | 4 - As above, adding more detailed information from the driver. | ||||
7024 | 5 to 15 - As above but with more and more obscure information. | ||||
7025 | |||||
7026 | Trace level 1 is best for a simple overview of what's happening. | ||||
7027 | Trace level 2 is a good choice for general purpose tracing. | ||||
7028 | Levels 3 and above are best reserved for investigating a specific | ||||
7029 | problem, when you need to see "inside" the driver and DBI. | ||||
7030 | |||||
7031 | The trace output is detailed and typically very useful. Much of the | ||||
7032 | trace output is formatted using the L</neat> function, so strings | ||||
7033 | in the trace output may be edited and truncated by that function. | ||||
7034 | |||||
7035 | =head2 Trace Flags | ||||
7036 | |||||
7037 | Trace I<flags> are used to enable tracing of specific activities | ||||
7038 | within the DBI and drivers. The DBI defines some trace flags and | ||||
7039 | drivers can define others. DBI trace flag names begin with a capital | ||||
7040 | letter and driver specific names begin with a lowercase letter, as | ||||
7041 | usual. | ||||
7042 | |||||
7043 | Curently the DBI only defines two trace flags: | ||||
7044 | |||||
7045 | ALL - turn on all DBI and driver flags (not recommended) | ||||
7046 | SQL - trace SQL statements executed (not yet implemented) | ||||
7047 | |||||
7048 | The L</parse_trace_flags> and L</parse_trace_flag> methods are used | ||||
7049 | to convert trace flag names into the coresponding integer bit flags. | ||||
7050 | |||||
7051 | =head2 Enabling Trace | ||||
7052 | |||||
7053 | The C<$h-E<gt>trace> method sets the trace settings for a handle | ||||
7054 | and C<DBI-E<gt>trace> does the same for the DBI. | ||||
7055 | |||||
7056 | In addition to the L</trace> method, you can enable the same trace | ||||
7057 | information, and direct the output to a file, by setting the | ||||
7058 | C<DBI_TRACE> environment variable before starting Perl. | ||||
7059 | See L</DBI_TRACE> for more information. | ||||
7060 | |||||
7061 | Finally, you can set, or get, the trace settings for a handle using | ||||
7062 | the C<TraceLevel> attribute. | ||||
7063 | |||||
7064 | All of those methods use parse_trace_flags() and so allow you set | ||||
7065 | both the trace level and multiple trace flags by using a string | ||||
7066 | containing the trace level and/or flag names separated by vertical | ||||
7067 | bar ("C<|>") or comma ("C<,>") characters. For example: | ||||
7068 | |||||
7069 | local $h->{TraceLevel} = "3|SQL|foo"; | ||||
7070 | |||||
7071 | =head2 Trace Output | ||||
7072 | |||||
7073 | Initially trace output is written to C<STDERR>. Both the | ||||
7074 | C<$h-E<gt>trace> and C<DBI-E<gt>trace> methods take an optional | ||||
7075 | $trace_file parameter, which may be either the name of a file to be | ||||
7076 | openned by DBI in append mode, or a reference to an existing writable | ||||
7077 | (possibly layered) filehandle. If $trace_file is a filename, | ||||
7078 | and can be opened in append mode, or $trace_file is a writable | ||||
7079 | filehandle, then I<all> trace output (currently including that from | ||||
7080 | other handles) is redirected to that file. A warning is generated | ||||
7081 | if $trace_file can't be opened or is not writable. | ||||
7082 | |||||
7083 | Further calls to trace() without $trace_file do not alter where | ||||
7084 | the trace output is sent. If $trace_file is undefined, then | ||||
7085 | trace output is sent to C<STDERR> and, if the prior trace was openned with | ||||
7086 | $trace_file as a filename, the previous trace file is closed; if $trace_file was | ||||
7087 | a filehandle, the filehandle is B<not> closed. | ||||
7088 | |||||
7089 | B<NOTE>: If $trace_file is specified as a filehandle, the filehandle | ||||
7090 | should not be closed until all DBI operations are completed, or the | ||||
7091 | application has reset the trace file via another call to | ||||
7092 | C<trace()> that changes the trace file. | ||||
7093 | |||||
7094 | =head2 Tracing to Layered Filehandles | ||||
7095 | |||||
7096 | B<NOTE>: | ||||
7097 | |||||
7098 | =over 4 | ||||
7099 | |||||
7100 | =item * | ||||
7101 | Tied filehandles are not currently supported, as | ||||
7102 | tie operations are not available to the PerlIO | ||||
7103 | methods used by the DBI. | ||||
7104 | |||||
7105 | =item * | ||||
7106 | PerlIO layer support requires Perl version 5.8 or higher. | ||||
7107 | |||||
7108 | =back | ||||
7109 | |||||
7110 | As of version 5.8, Perl provides the ability to layer various | ||||
7111 | "disciplines" on an open filehandle via the L<PerlIO> module. | ||||
7112 | |||||
7113 | A simple example of using PerlIO layers is to use a scalar as the output: | ||||
7114 | |||||
7115 | my $scalar = ''; | ||||
7116 | open( my $fh, "+>:scalar", \$scalar ); | ||||
7117 | $dbh->trace( 2, $fh ); | ||||
7118 | |||||
7119 | Now all trace output is simply appended to $scalar. | ||||
7120 | |||||
7121 | A more complex application of tracing to a layered filehandle is the | ||||
7122 | use of a custom layer (I<Refer to >L<Perlio::via> I<for details | ||||
7123 | on creating custom PerlIO layers.>). Consider an application with the | ||||
7124 | following logger module: | ||||
7125 | |||||
7126 | package MyFancyLogger; | ||||
7127 | |||||
7128 | sub new | ||||
7129 | { | ||||
7130 | my $self = {}; | ||||
7131 | my $fh; | ||||
7132 | open $fh, '>', 'fancylog.log'; | ||||
7133 | $self->{_fh} = $fh; | ||||
7134 | $self->{_buf} = ''; | ||||
7135 | return bless $self, shift; | ||||
7136 | } | ||||
7137 | |||||
7138 | sub log | ||||
7139 | { | ||||
7140 | my $self = shift; | ||||
7141 | return unless exists $self->{_fh}; | ||||
7142 | my $fh = $self->{_fh}; | ||||
7143 | $self->{_buf} .= shift; | ||||
7144 | # | ||||
7145 | # DBI feeds us pieces at a time, so accumulate a complete line | ||||
7146 | # before outputing | ||||
7147 | # | ||||
7148 | print $fh "At ", scalar localtime(), ':', $self->{_buf}, "\n" and | ||||
7149 | $self->{_buf} = '' | ||||
7150 | if $self->{_buf}=~tr/\n//; | ||||
7151 | } | ||||
7152 | |||||
7153 | sub close { | ||||
7154 | my $self = shift; | ||||
7155 | return unless exists $self->{_fh}; | ||||
7156 | my $fh = $self->{_fh}; | ||||
7157 | print $fh "At ", scalar localtime(), ':', $self->{_buf}, "\n" and | ||||
7158 | $self->{_buf} = '' | ||||
7159 | if $self->{_buf}; | ||||
7160 | close $fh; | ||||
7161 | delete $self->{_fh}; | ||||
7162 | } | ||||
7163 | |||||
7164 | 1; | ||||
7165 | |||||
7166 | To redirect DBI traces to this logger requires creating | ||||
7167 | a package for the layer: | ||||
7168 | |||||
7169 | package PerlIO::via::MyFancyLogLayer; | ||||
7170 | |||||
7171 | sub PUSHED | ||||
7172 | { | ||||
7173 | my ($class,$mode,$fh) = @_; | ||||
7174 | my $logger; | ||||
7175 | return bless \$logger,$class; | ||||
7176 | } | ||||
7177 | |||||
7178 | sub OPEN { | ||||
7179 | my ($self, $path, $mode, $fh) = @_; | ||||
7180 | # | ||||
7181 | # $path is actually our logger object | ||||
7182 | # | ||||
7183 | $$self = $path; | ||||
7184 | return 1; | ||||
7185 | } | ||||
7186 | |||||
7187 | sub WRITE | ||||
7188 | { | ||||
7189 | my ($self, $buf, $fh) = @_; | ||||
7190 | $$self->log($buf); | ||||
7191 | return length($buf); | ||||
7192 | } | ||||
7193 | |||||
7194 | sub CLOSE { | ||||
7195 | my $self = shift; | ||||
7196 | $$self->close(); | ||||
7197 | return 0; | ||||
7198 | } | ||||
7199 | |||||
7200 | 1; | ||||
7201 | |||||
7202 | |||||
7203 | The application can then cause DBI traces to be routed to the | ||||
7204 | logger using | ||||
7205 | |||||
7206 | use PerlIO::via::MyFancyLogLayer; | ||||
7207 | |||||
7208 | open my $fh, '>:via(MyFancyLogLayer)', MyFancyLogger->new(); | ||||
7209 | |||||
7210 | $dbh->trace('SQL', $fh); | ||||
7211 | |||||
7212 | Now all trace output will be processed by MyFancyLogger's | ||||
7213 | log() method. | ||||
7214 | |||||
7215 | =head2 Trace Content | ||||
7216 | |||||
7217 | Many of the values embeded in trace output are formatted using the neat() | ||||
7218 | utility function. This means they may be quoted, sanitized, and possibly | ||||
7219 | truncated if longer than C<$DBI::neat_maxlen>. See L</neat> for more details. | ||||
7220 | |||||
7221 | =head2 Tracing Tips | ||||
7222 | |||||
7223 | You can add tracing to your own application code using the | ||||
7224 | L</trace_msg> method. | ||||
7225 | |||||
7226 | It can sometimes be handy to compare trace files from two different | ||||
7227 | runs of the same script. However using a tool like C<diff> doesn't work | ||||
7228 | well because the trace file is full of object addresses that may | ||||
7229 | differ each run. Here's a handy little command to strip those out: | ||||
7230 | |||||
7231 | perl -pe 's/\b0x[\da-f]{6,}/0xNNNN/gi; s/\b[\da-f]{6,}/<long number>/gi' | ||||
7232 | |||||
7233 | |||||
7234 | =head1 DBI ENVIRONMENT VARIABLES | ||||
7235 | |||||
7236 | The DBI module recognizes a number of environment variables, but most of | ||||
7237 | them should not be used most of the time. | ||||
7238 | It is better to be explicit about what you are doing to avoid the need | ||||
7239 | for environment variables, especially in a web serving system where web | ||||
7240 | servers are stingy about which environment variables are available. | ||||
7241 | |||||
7242 | =head2 DBI_DSN | ||||
7243 | |||||
7244 | The DBI_DSN environment variable is used by DBI->connect if you do not | ||||
7245 | specify a data source when you issue the connect. | ||||
7246 | It should have a format such as "dbi:Driver:databasename". | ||||
7247 | |||||
7248 | =head2 DBI_DRIVER | ||||
7249 | |||||
7250 | The DBI_DRIVER environment variable is used to fill in the database | ||||
7251 | driver name in DBI->connect if the data source string starts "dbi::" | ||||
7252 | (thereby omitting the driver). | ||||
7253 | If DBI_DSN omits the driver name, DBI_DRIVER can fill the gap. | ||||
7254 | |||||
7255 | =head2 DBI_AUTOPROXY | ||||
7256 | |||||
7257 | The DBI_AUTOPROXY environment variable takes a string value that starts | ||||
7258 | "dbi:Proxy:" and is typically followed by "hostname=...;port=...". | ||||
7259 | It is used to alter the behaviour of DBI->connect. | ||||
7260 | For full details, see DBI::Proxy documentation. | ||||
7261 | |||||
7262 | =head2 DBI_USER | ||||
7263 | |||||
7264 | The DBI_USER environment variable takes a string value that is used as | ||||
7265 | the user name if the DBI->connect call is given undef (as distinct from | ||||
7266 | an empty string) as the username argument. | ||||
7267 | Be wary of the security implications of using this. | ||||
7268 | |||||
7269 | =head2 DBI_PASS | ||||
7270 | |||||
7271 | The DBI_PASS environment variable takes a string value that is used as | ||||
7272 | the password if the DBI->connect call is given undef (as distinct from | ||||
7273 | an empty string) as the password argument. | ||||
7274 | Be extra wary of the security implications of using this. | ||||
7275 | |||||
7276 | =head2 DBI_DBNAME (obsolete) | ||||
7277 | |||||
7278 | The DBI_DBNAME environment variable takes a string value that is used only when the | ||||
7279 | obsolescent style of DBI->connect (with driver name as fourth parameter) is used, and | ||||
7280 | when no value is provided for the first (database name) argument. | ||||
7281 | |||||
7282 | =head2 DBI_TRACE | ||||
7283 | |||||
7284 | The DBI_TRACE environment variable specifies the global default | ||||
7285 | trace settings for the DBI at startup. Can also be used to direct | ||||
7286 | trace output to a file. When the DBI is loaded it does: | ||||
7287 | |||||
7288 | DBI->trace(split /=/, $ENV{DBI_TRACE}, 2) if $ENV{DBI_TRACE}; | ||||
7289 | |||||
7290 | So if C<DBI_TRACE> contains an "C<=>" character then what follows | ||||
7291 | it is used as the name of the file to append the trace to. | ||||
7292 | |||||
7293 | output appended to that file. If the name begins with a number | ||||
7294 | followed by an equal sign (C<=>), then the number and the equal sign are | ||||
7295 | stripped off from the name, and the number is used to set the trace | ||||
7296 | level. For example: | ||||
7297 | |||||
7298 | DBI_TRACE=1=dbitrace.log perl your_test_script.pl | ||||
7299 | |||||
7300 | On Unix-like systems using a Bourne-like shell, you can do this easily | ||||
7301 | on the command line: | ||||
7302 | |||||
7303 | DBI_TRACE=2 perl your_test_script.pl | ||||
7304 | |||||
7305 | See L</TRACING> for more information. | ||||
7306 | |||||
7307 | =head2 PERL_DBI_DEBUG (obsolete) | ||||
7308 | |||||
7309 | An old variable that should no longer be used; equivalent to DBI_TRACE. | ||||
7310 | |||||
7311 | =head2 DBI_PROFILE | ||||
7312 | |||||
7313 | The DBI_PROFILE environment variable can be used to enable profiling | ||||
7314 | of DBI method calls. See L<DBI::Profile> for more information. | ||||
7315 | |||||
7316 | =head2 DBI_PUREPERL | ||||
7317 | |||||
7318 | The DBI_PUREPERL environment variable can be used to enable the | ||||
7319 | use of DBI::PurePerl. See L<DBI::PurePerl> for more information. | ||||
7320 | |||||
7321 | =head1 WARNING AND ERROR MESSAGES | ||||
7322 | |||||
7323 | =head2 Fatal Errors | ||||
7324 | |||||
7325 | =over 4 | ||||
7326 | |||||
7327 | =item Can't call method "prepare" without a package or object reference | ||||
7328 | |||||
7329 | The C<$dbh> handle you're using to call C<prepare> is probably undefined because | ||||
7330 | the preceding C<connect> failed. You should always check the return status of | ||||
7331 | DBI methods, or use the L</RaiseError> attribute. | ||||
7332 | |||||
7333 | =item Can't call method "execute" without a package or object reference | ||||
7334 | |||||
7335 | The C<$sth> handle you're using to call C<execute> is probably undefined because | ||||
7336 | the preceeding C<prepare> failed. You should always check the return status of | ||||
7337 | DBI methods, or use the L</RaiseError> attribute. | ||||
7338 | |||||
7339 | =item DBI/DBD internal version mismatch | ||||
7340 | |||||
7341 | The DBD driver module was built with a different version of DBI than | ||||
7342 | the one currently being used. You should rebuild the DBD module under | ||||
7343 | the current version of DBI. | ||||
7344 | |||||
7345 | (Some rare platforms require "static linking". On those platforms, there | ||||
7346 | may be an old DBI or DBD driver version actually embedded in the Perl | ||||
7347 | executable being used.) | ||||
7348 | |||||
7349 | =item DBD driver has not implemented the AutoCommit attribute | ||||
7350 | |||||
7351 | The DBD driver implementation is incomplete. Consult the author. | ||||
7352 | |||||
7353 | =item Can't [sg]et %s->{%s}: unrecognised attribute | ||||
7354 | |||||
7355 | You attempted to set or get an unknown attribute of a handle. Make | ||||
7356 | sure you have spelled the attribute name correctly; case is significant | ||||
7357 | (e.g., "Autocommit" is not the same as "AutoCommit"). | ||||
7358 | |||||
7359 | =back | ||||
7360 | |||||
7361 | =head1 Pure-Perl DBI | ||||
7362 | |||||
7363 | A pure-perl emulation of the DBI is included in the distribution | ||||
7364 | for people using pure-perl drivers who, for whatever reason, can't | ||||
7365 | install the compiled DBI. See L<DBI::PurePerl>. | ||||
7366 | |||||
7367 | =head1 SEE ALSO | ||||
7368 | |||||
7369 | =head2 Driver and Database Documentation | ||||
7370 | |||||
7371 | Refer to the documentation for the DBD driver that you are using. | ||||
7372 | |||||
7373 | Refer to the SQL Language Reference Manual for the database engine that you are using. | ||||
7374 | |||||
7375 | =head2 ODBC and SQL/CLI Standards Reference Information | ||||
7376 | |||||
7377 | More detailed information about the semantics of certain DBI methods | ||||
7378 | that are based on ODBC and SQL/CLI standards is available on-line | ||||
7379 | via microsoft.com, for ODBC, and www.jtc1sc32.org for the SQL/CLI | ||||
7380 | standard: | ||||
7381 | |||||
7382 | DBI method ODBC function SQL/CLI Working Draft | ||||
7383 | ---------- ------------- --------------------- | ||||
7384 | column_info SQLColumns Page 124 | ||||
7385 | foreign_key_info SQLForeignKeys Page 163 | ||||
7386 | get_info SQLGetInfo Page 214 | ||||
7387 | primary_key_info SQLPrimaryKeys Page 254 | ||||
7388 | table_info SQLTables Page 294 | ||||
7389 | type_info SQLGetTypeInfo Page 239 | ||||
7390 | statistics_info SQLStatistics | ||||
7391 | |||||
7392 | For example, for ODBC information on SQLColumns you'd visit: | ||||
7393 | |||||
7394 | http://msdn.microsoft.com/library/en-us/odbc/htm/odbcsqlcolumns.asp | ||||
7395 | |||||
7396 | If that URL ceases to work then use the MSDN search facility at: | ||||
7397 | |||||
7398 | http://search.microsoft.com/us/dev/ | ||||
7399 | |||||
7400 | and search for C<SQLColumns returns> using the exact phrase option. | ||||
7401 | The link you want will probably just be called C<SQLColumns> and will | ||||
7402 | be part of the Data Access SDK. | ||||
7403 | |||||
7404 | And for SQL/CLI standard information on SQLColumns you'd read page 124 of | ||||
7405 | the (very large) SQL/CLI Working Draft available from: | ||||
7406 | |||||
7407 | http://jtc1sc32.org/doc/N0701-0750/32N0744T.pdf | ||||
7408 | |||||
7409 | =head2 Standards Reference Information | ||||
7410 | |||||
7411 | A hyperlinked, browsable version of the BNF syntax for SQL92 (plus | ||||
7412 | Oracle 7 SQL and PL/SQL) is available here: | ||||
7413 | |||||
7414 | http://cui.unige.ch/db-research/Enseignement/analyseinfo/SQL92/BNFindex.html | ||||
7415 | |||||
7416 | A BNF syntax for SQL3 is available here: | ||||
7417 | |||||
7418 | http://www.sqlstandards.org/SC32/WG3/Progression_Documents/Informal_working_drafts/iso-9075-2-1999.bnf | ||||
7419 | |||||
7420 | The following links provide further useful information about SQL. | ||||
7421 | Some of these are rather dated now but may still be useful. | ||||
7422 | |||||
7423 | http://www.jcc.com/SQLPages/jccs_sql.htm | ||||
7424 | http://www.contrib.andrew.cmu.edu/~shadow/sql.html | ||||
7425 | http://www.altavista.com/query?q=sql+tutorial | ||||
7426 | |||||
7427 | |||||
7428 | =head2 Books and Articles | ||||
7429 | |||||
7430 | Programming the Perl DBI, by Alligator Descartes and Tim Bunce. | ||||
7431 | L<http://books.perl.org/book/154> | ||||
7432 | |||||
7433 | Programming Perl 3rd Ed. by Larry Wall, Tom Christiansen & Jon Orwant. | ||||
7434 | L<http://books.perl.org/book/134> | ||||
7435 | |||||
7436 | Learning Perl by Randal Schwartz. | ||||
7437 | L<http://books.perl.org/book/101> | ||||
7438 | |||||
7439 | Details of many other books related to perl can be found at L<http://books.perl.org> | ||||
7440 | |||||
7441 | =head2 Perl Modules | ||||
7442 | |||||
7443 | Index of DBI related modules available from CPAN: | ||||
7444 | |||||
7445 | http://search.cpan.org/search?mode=module&query=DBIx%3A%3A | ||||
7446 | http://search.cpan.org/search?mode=doc&query=DBI | ||||
7447 | |||||
7448 | For a good comparison of RDBMS-OO mappers and some OO-RDBMS mappers | ||||
7449 | (including Class::DBI, Alzabo, and DBIx::RecordSet in the former | ||||
7450 | category and Tangram and SPOPS in the latter) see the Perl | ||||
7451 | Object-Oriented Persistence project pages at: | ||||
7452 | |||||
7453 | http://poop.sourceforge.net | ||||
7454 | |||||
7455 | A similar page for Java toolkits can be found at: | ||||
7456 | |||||
7457 | http://c2.com/cgi-bin/wiki?ObjectRelationalToolComparison | ||||
7458 | |||||
7459 | =head2 Mailing List | ||||
7460 | |||||
7461 | The I<dbi-users> mailing list is the primary means of communication among | ||||
7462 | users of the DBI and its related modules. For details send email to: | ||||
7463 | |||||
7464 | dbi-users-help@perl.org | ||||
7465 | |||||
7466 | There are typically between 700 and 900 messages per month. You have | ||||
7467 | to subscribe in order to be able to post. However you can opt for a | ||||
7468 | 'post-only' subscription. | ||||
7469 | |||||
7470 | Mailing list archives (of variable quality) are held at: | ||||
7471 | |||||
7472 | http://groups.google.com/groups?group=perl.dbi.users | ||||
7473 | http://www.xray.mpe.mpg.de/mailing-lists/dbi/ | ||||
7474 | http://www.mail-archive.com/dbi-users%40perl.org/ | ||||
7475 | |||||
7476 | =head2 Assorted Related WWW Links | ||||
7477 | |||||
7478 | The DBI "Home Page": | ||||
7479 | |||||
7480 | http://dbi.perl.org/ | ||||
7481 | |||||
7482 | Other DBI related links: | ||||
7483 | |||||
7484 | http://tegan.deltanet.com/~phlip/DBUIdoc.html | ||||
7485 | http://dc.pm.org/perl_db.html | ||||
7486 | http://wdvl.com/Authoring/DB/Intro/toc.html | ||||
7487 | http://www.hotwired.com/webmonkey/backend/tutorials/tutorial1.html | ||||
7488 | http://bumppo.net/lists/macperl/1999/06/msg00197.html | ||||
7489 | http://gmax.oltrelinux.com/dbirecipes.html | ||||
7490 | |||||
7491 | Other database related links: | ||||
7492 | |||||
7493 | http://www.jcc.com/sql_stnd.html | ||||
7494 | http://cuiwww.unige.ch/OSG/info/FreeDB/FreeDB.home.html | ||||
7495 | http://www.connectionstrings.com/ | ||||
7496 | |||||
7497 | Security, especially the "SQL Injection" attack: | ||||
7498 | |||||
7499 | http://www.ngssoftware.com/research/papers.html | ||||
7500 | http://www.ngssoftware.com/papers/advanced_sql_injection.pdf | ||||
7501 | http://www.ngssoftware.com/papers/more_advanced_sql_injection.pdf | ||||
7502 | http://www.esecurityplanet.com/trends/article.php/2243461 | ||||
7503 | http://www.spidynamics.com/papers/SQLInjectionWhitePaper.pdf | ||||
7504 | http://www.imperva.com/application_defense_center/white_papers/blind_sql_server_injection.html | ||||
7505 | http://online.securityfocus.com/infocus/1644 | ||||
7506 | |||||
7507 | Commercial and Data Warehouse Links | ||||
7508 | |||||
7509 | http://www.dwinfocenter.org | ||||
7510 | http://www.datawarehouse.com | ||||
7511 | http://www.datamining.org | ||||
7512 | http://www.olapcouncil.org | ||||
7513 | http://www.idwa.org | ||||
7514 | http://www.knowledgecenters.org/dwcenter.asp | ||||
7515 | |||||
7516 | Recommended Perl Programming Links | ||||
7517 | |||||
7518 | http://language.perl.com/style/ | ||||
7519 | |||||
7520 | |||||
7521 | =head2 FAQ | ||||
7522 | |||||
7523 | Please also read the DBI FAQ which is installed as a DBI::FAQ module. | ||||
7524 | You can use I<perldoc> to read it by executing the C<perldoc DBI::FAQ> command. | ||||
7525 | |||||
7526 | =head1 AUTHORS | ||||
7527 | |||||
7528 | DBI by Tim Bunce, L<http://www.linkedin.com/in/timbunce> | ||||
7529 | |||||
7530 | This pod text by Tim Bunce, J. Douglas Dunlop, Jonathan Leffler and others. | ||||
7531 | Perl by Larry Wall and the C<perl5-porters>. | ||||
7532 | |||||
7533 | =head1 COPYRIGHT | ||||
7534 | |||||
7535 | The DBI module is Copyright (c) 1994-2004 Tim Bunce. Ireland. | ||||
7536 | All rights reserved. | ||||
7537 | |||||
7538 | You may distribute under the terms of either the GNU General Public | ||||
7539 | License or the Artistic License, as specified in the Perl README file. | ||||
7540 | |||||
7541 | =head1 SUPPORT / WARRANTY | ||||
7542 | |||||
7543 | The DBI is free Open Source software. IT COMES WITHOUT WARRANTY OF ANY KIND. | ||||
7544 | |||||
7545 | =head2 Support | ||||
7546 | |||||
7547 | My consulting company, Data Plan Services, offers annual and | ||||
7548 | multi-annual support contracts for the DBI. These provide sustained | ||||
7549 | support for DBI development, and sustained value for you in return. | ||||
7550 | Contact me for details. | ||||
7551 | |||||
7552 | =head2 Sponsor Enhancements | ||||
7553 | |||||
7554 | The DBI Roadmap is available at L<http://search.cpan.org/~timb/DBI/Roadmap.pod> | ||||
7555 | |||||
7556 | If your company would benefit from a specific new DBI feature, | ||||
7557 | please consider sponsoring its development. Work is performed | ||||
7558 | rapidly, and usually on a fixed-price payment-on-delivery basis. | ||||
7559 | Contact me for details. | ||||
7560 | |||||
7561 | Using such targeted financing allows you to contribute to DBI | ||||
7562 | development, and rapidly get something specific and valuable in return. | ||||
7563 | |||||
7564 | =head1 ACKNOWLEDGEMENTS | ||||
7565 | |||||
7566 | I would like to acknowledge the valuable contributions of the many | ||||
7567 | people I have worked with on the DBI project, especially in the early | ||||
7568 | years (1992-1994). In no particular order: Kevin Stock, Buzz Moschetti, | ||||
7569 | Kurt Andersen, Ted Lemon, William Hails, Garth Kennedy, Michael Peppler, | ||||
7570 | Neil S. Briscoe, Jeff Urlwin, David J. Hughes, Jeff Stander, | ||||
7571 | Forrest D Whitcher, Larry Wall, Jeff Fried, Roy Johnson, Paul Hudson, | ||||
7572 | Georg Rehfeld, Steve Sizemore, Ron Pool, Jon Meek, Tom Christiansen, | ||||
7573 | Steve Baumgarten, Randal Schwartz, and a whole lot more. | ||||
7574 | |||||
7575 | Then, of course, there are the poor souls who have struggled through | ||||
7576 | untold and undocumented obstacles to actually implement DBI drivers. | ||||
7577 | Among their ranks are Jochen Wiedmann, Alligator Descartes, Jonathan | ||||
7578 | Leffler, Jeff Urlwin, Michael Peppler, Henrik Tougaard, Edwin Pratomo, | ||||
7579 | Davide Migliavacca, Jan Pazdziora, Peter Haworth, Edmund Mergl, Steve | ||||
7580 | Williams, Thomas Lowery, and Phlip Plumlee. Without them, the DBI would | ||||
7581 | not be the practical reality it is today. I'm also especially grateful | ||||
7582 | to Alligator Descartes for starting work on the first edition of the | ||||
7583 | "Programming the Perl DBI" book and letting me jump on board. | ||||
7584 | |||||
7585 | The DBI and DBD::Oracle were originally developed while I was Technical | ||||
7586 | Director (CTO) of Ingeneering in the UK (L<http://www.ig.co.uk>) (formerly known as the | ||||
7587 | Paul Ingram Group). So I'd especially like to thank Paul for his generosity | ||||
7588 | and vision in supporting this work for many years. | ||||
7589 | |||||
7590 | A couple of specific DBI features have been sponsored by enlightened companies: | ||||
7591 | |||||
7592 | The development of the swap_inner_handle() method was sponsored by BizRate.com (L<http://BizRate.com>) | ||||
7593 | |||||
7594 | The development of DBD::Gofer and related modules was sponsored by | ||||
7595 | Shopzilla.com (L<http://Shopzilla.com>), where I currently work. | ||||
7596 | |||||
7597 | |||||
7598 | =head1 CONTRIBUTING | ||||
7599 | |||||
7600 | As you can see above, many people have contributed to the DBI and | ||||
7601 | drivers in many ways over many years. | ||||
7602 | |||||
7603 | If you'd like to help then see L<http://dbi.perl.org/contributing> | ||||
7604 | and L<http://search.cpan.org/~timb/DBI/Roadmap.pod> | ||||
7605 | |||||
7606 | If you'd like the DBI to do something new or different then a good way | ||||
7607 | to make that happen is to do it yourself and send me a patch to the | ||||
7608 | source code that shows the changes. (But read "Speak before you patch" | ||||
7609 | below.) | ||||
7610 | |||||
7611 | =head2 Browsing the source code repository | ||||
7612 | |||||
7613 | Use http://svn.perl.org/modules/dbi/trunk (basic) | ||||
7614 | or http://svn.perl.org/viewcvs/modules/ (more useful) | ||||
7615 | |||||
7616 | =head2 How to create a patch using Subversion | ||||
7617 | |||||
7618 | The DBI source code is maintained using Subversion (a replacement | ||||
7619 | for CVS, see L<http://subversion.tigris.org/>). To access the source | ||||
7620 | you'll need to install a Subversion client. Then, to get the source | ||||
7621 | code, do: | ||||
7622 | |||||
7623 | svn checkout http://svn.perl.org/modules/dbi/trunk | ||||
7624 | |||||
7625 | If it prompts for a username and password use your perl.org account | ||||
7626 | if you have one, else just 'guest' and 'guest'. The source code will | ||||
7627 | be in a new subdirectory called C<trunk>. | ||||
7628 | |||||
7629 | To keep informed about changes to the source you can send an empty email | ||||
7630 | to svn-commit-modules-dbi-subscribe@perl.org after which you'll get an email | ||||
7631 | with the change log message and diff of each change checked-in to the source. | ||||
7632 | |||||
7633 | After making your changes you can generate a patch file, but before | ||||
7634 | you do, make sure your source is still upto date using: | ||||
7635 | |||||
7636 | svn update | ||||
7637 | |||||
7638 | If you get any conflicts reported you'll need to fix them first. | ||||
7639 | Then generate the patch file from within the C<trunk> directory using: | ||||
7640 | |||||
7641 | svn diff > foo.patch | ||||
7642 | |||||
7643 | Read the patch file, as a sanity check, and then email it to dbi-dev@perl.org. | ||||
7644 | |||||
7645 | =head2 How to create a patch without Subversion | ||||
7646 | |||||
7647 | Unpack a fresh copy of the distribution: | ||||
7648 | |||||
7649 | tar xfz DBI-1.40.tar.gz | ||||
7650 | |||||
7651 | Rename the newly created top level directory: | ||||
7652 | |||||
7653 | mv DBI-1.40 DBI-1.40.your_foo | ||||
7654 | |||||
7655 | Edit the contents of DBI-1.40.your_foo/* till it does what you want. | ||||
7656 | |||||
7657 | Test your changes and then remove all temporary files: | ||||
7658 | |||||
7659 | make test && make distclean | ||||
7660 | |||||
7661 | Go back to the directory you originally unpacked the distribution: | ||||
7662 | |||||
7663 | cd .. | ||||
7664 | |||||
7665 | Unpack I<another> copy of the original distribution you started with: | ||||
7666 | |||||
7667 | tar xfz DBI-1.40.tar.gz | ||||
7668 | |||||
7669 | Then create a patch file by performing a recursive C<diff> on the two | ||||
7670 | top level directories: | ||||
7671 | |||||
7672 | diff -r -u DBI-1.40 DBI-1.40.your_foo > DBI-1.40.your_foo.patch | ||||
7673 | |||||
7674 | =head2 Speak before you patch | ||||
7675 | |||||
7676 | For anything non-trivial or possibly controversial it's a good idea | ||||
7677 | to discuss (on dbi-dev@perl.org) the changes you propose before | ||||
7678 | actually spending time working on them. Otherwise you run the risk | ||||
7679 | of them being rejected because they don't fit into some larger plans | ||||
7680 | you may not be aware of. | ||||
7681 | |||||
7682 | =head1 TRANSLATIONS | ||||
7683 | |||||
7684 | A German translation of this manual (possibly slightly out of date) is | ||||
7685 | available, thanks to O'Reilly, at: | ||||
7686 | |||||
7687 | http://www.oreilly.de/catalog/perldbiger/ | ||||
7688 | |||||
7689 | Some other translations: | ||||
7690 | |||||
7691 | http://cronopio.net/perl/ - Spanish | ||||
7692 | http://member.nifty.ne.jp/hippo2000/dbimemo.htm - Japanese | ||||
7693 | |||||
7694 | |||||
7695 | =head1 TRAINING | ||||
7696 | |||||
7697 | References to DBI related training resources. No recommendation implied. | ||||
7698 | |||||
7699 | http://www.treepax.co.uk/ | ||||
7700 | http://www.keller.com/dbweb/ | ||||
7701 | |||||
7702 | (If you offer professional DBI related training services, | ||||
7703 | please send me your details so I can add them here.) | ||||
7704 | |||||
7705 | =head1 OTHER RELATED WORK AND PERL MODULES | ||||
7706 | |||||
7707 | =over 4 | ||||
7708 | |||||
7709 | =item Apache::DBI by E.Mergl@bawue.de | ||||
7710 | |||||
7711 | To be used with the Apache daemon together with an embedded Perl | ||||
7712 | interpreter like C<mod_perl>. Establishes a database connection which | ||||
7713 | remains open for the lifetime of the HTTP daemon. This way the CGI | ||||
7714 | connect and disconnect for every database access becomes superfluous. | ||||
7715 | |||||
7716 | =item SQL Parser | ||||
7717 | |||||
7718 | See also the L<SQL::Statement> module, SQL parser and engine. | ||||
7719 | |||||
7720 | =back | ||||
7721 | |||||
7722 | =cut | ||||
# spent 515µs within DBD::_::common::CORE:match which was called 62 times, avg 8µs/call:
# 31 times (275µs+0s) by DBD::_::common::install_method at line 1352 of DBI.pm, avg 9µs/call
# 31 times (240µs+0s) by DBD::_::common::install_method at line 1355 of DBI.pm, avg 8µs/call | |||||
# spent 32µs within DBD::_::common::trace_msg which was called 4 times, avg 8µs/call:
# once (11µs+0s) by DBI::END at line 498 of DBI.pm
# once (8µs+0s) by DBI::_load_class at line 922 of DBI.pm
# once (7µs+0s) by DBI::_set_isa at line 819 of DBI.pm
# once (6µs+0s) by DBI::_load_class at line 926 of DBI.pm | |||||
# spent 29µs within DBD::_::dr::CORE:sort which was called
# once (29µs+0s) by DBI::dr::connect_cached at line 1441 of DBI.pm | |||||
# spent 535µs within DBI::CORE:match which was called 112 times, avg 5µs/call:
# 112 times (535µs+0s) by base::import at line 257 of DBI.pm, avg 5µs/call | |||||
# spent 37µs within DBI::CORE:subst which was called 3 times, avg 12µs/call:
# once (18µs+0s) by DBI::connect at line 568 of DBI.pm
# once (14µs+0s) by DBI::_load_class at line 925 of DBI.pm
# once (5µs+0s) by DBI::install_driver at line 723 of DBI.pm | |||||
# spent 6µs within DBI::SQL_DECIMAL which was called
# once (6µs+0s) by DBI::install_driver at line 1375 of DBD/Pg.pm | |||||
# spent 6µs within DBI::SQL_DOUBLE which was called
# once (6µs+0s) by DBI::install_driver at line 1375 of DBD/Pg.pm | |||||
# spent 6µs within DBI::SQL_FLOAT which was called
# once (6µs+0s) by DBI::install_driver at line 1375 of DBD/Pg.pm | |||||
# spent 7µs within DBI::SQL_INTEGER which was called
# once (7µs+0s) by DBI::install_driver at line 1375 of DBD/Pg.pm | |||||
# spent 5µs within DBI::SQL_NUMERIC which was called
# once (5µs+0s) by DBI::install_driver at line 1375 of DBD/Pg.pm | |||||
# spent 6µs within DBI::SQL_REAL which was called
# once (6µs+0s) by DBI::install_driver at line 1375 of DBD/Pg.pm | |||||
# spent 6µs within DBI::SQL_SMALLINT which was called
# once (6µs+0s) by DBI::install_driver at line 1375 of DBD/Pg.pm | |||||
# spent 13µs within DBI::_handles which was called
# once (13µs+0s) by DBI::_rebless at line 810 of DBI.pm | |||||
# spent 2.45ms within DBI::_install_method which was called 117 times, avg 21µs/call:
# 86 times (1.03ms+0s) by base::import at line 481 of DBI.pm, avg 12µs/call
# 31 times (1.43ms+0s) by DBD::_::common::install_method at line 1363 of DBI.pm, avg 46µs/call | |||||
# spent 694µs within DBI::_setup_handle which was called 14 times, avg 50µs/call:
# 14 times (694µs+0s) by DBI::_new_handle at line 1195 of DBI.pm, avg 50µs/call | |||||
# spent 402µs within DBI::bootstrap which was called
# once (402µs+0s) by DynaLoader::bootstrap at line 253 of DynaLoader.pm | |||||
# spent 14µs within DBI::st::bind_col which was called
# once (14µs+0s) by DBI::st::bind_columns at line 1843 of DBI.pm | |||||
# spent 155µs (126+29) within DBI::st::bind_columns which was called
# once (126µs+29µs) by Class::DBI::sth_to_objects at line 1140 of Class/DBI.pm | |||||
# spent 280ms within DBI::st::execute which was called 12 times, avg 23.3ms/call:
# 12 times (280ms+0s) by DBIx::ContextualFetch::st::_untaint_execute at line 52 of DBIx/ContextualFetch.pm, avg 23.3ms/call | |||||
# spent 70µs within DBI::st::fetchall_arrayref which was called 2 times, avg 35µs/call:
# 2 times (70µs+0s) by Class::DBI::Pg::set_up_table at line 38 of Class/DBI/Pg.pm, avg 35µs/call | |||||
# spent 287µs within DBI::st::fetchrow_array which was called 9 times, avg 32µs/call:
# 4 times (116µs+0s) by Class::DBI::Pg::pg_version at line 93 of Class/DBI/Pg.pm, avg 29µs/call
# 2 times (36µs+0s) by Class::DBI::Pg::set_up_table at line 49 of Class/DBI/Pg.pm, avg 18µs/call
# 2 times (35µs+0s) by Class::DBI::Pg::set_up_table at line 26 of Class/DBI/Pg.pm, avg 18µs/call
# once (100µs+0s) by DBIx::ContextualFetch::st::select_row at line 88 of DBIx/ContextualFetch.pm | |||||
# spent 4.20ms within DBI::st::fetchrow_arrayref which was called 462 times, avg 9µs/call:
# 462 times (4.20ms+0s) by DBIx::ContextualFetch::st::fetch at line 60 of DBIx/ContextualFetch.pm, avg 9µs/call | |||||
# spent 137µs within DBI::st::finish which was called 11 times, avg 12µs/call:
# 4 times (55µs+0s) by Class::DBI::Pg::pg_version at line 94 of Class/DBI/Pg.pm, avg 14µs/call
# 2 times (24µs+0s) by Class::DBI::Pg::set_up_table at line 27 of Class/DBI/Pg.pm, avg 12µs/call
# 2 times (23µs+0s) by Class::DBI::Pg::set_up_table at line 50 of Class/DBI/Pg.pm, avg 12µs/call
# 2 times (19µs+0s) by Class::DBI::Pg::set_up_table at line 39 of Class/DBI/Pg.pm, avg 10µs/call
# once (16µs+0s) by DBIx::ContextualFetch::st::select_row at line 89 of DBIx/ContextualFetch.pm |