| File | /usr/lib/perl5/DBI.pm |
| Statements Executed | 3697 |
| Total Time | 0.0290601999999999 seconds |
| Calls | P | F | Exclusive Time |
Inclusive Time |
Subroutine |
|---|---|---|---|---|---|
| 509 | 3 | 2 | 9.07ms | 9.07ms | DBI::_new_handle(xsub) |
| 1 | 1 | 1 | 8.81ms | 11.5ms | DBI::install_driver |
| 507 | 1 | 1 | 5.52ms | 14.5ms | DBI::_new_sth |
| 88 | 1 | 2 | 581µs | 581µs | DBI::_install_method(xsub) |
| 1 | 1 | 2 | 326µs | 326µs | DBI::bootstrap(xsub) |
| 2 | 2 | 1 | 179µs | 240µs | DBI::setup_driver |
| 1 | 1 | 1 | 113µs | 18.7ms | DBI::connect |
| 1 | 1 | 1 | 71µs | 3.57ms | DBI::__ANON__[:704] |
| 1 | 1 | 1 | 25µs | 90µs | DBD::_::st::fetchall_arrayref |
| 1 | 1 | 1 | 23µs | 61µs | DBI::_new_dbh |
| 1 | 1 | 1 | 23µs | 88µs | DBI::_new_drh |
| 1 | 1 | 1 | 16µs | 39µs | DBI::disconnect_all |
| 1 | 1 | 2 | 16µs | 16µs | DBD::_::common::trace_msg(xsub) |
| 0 | 0 | 0 | 0s | 0s | DBD::Switch::dr::CLONE |
| 0 | 0 | 0 | 0s | 0s | DBD::Switch::dr::FETCH |
| 0 | 0 | 0 | 0s | 0s | DBD::Switch::dr::STORE |
| 0 | 0 | 0 | 0s | 0s | DBD::Switch::dr::driver |
| 0 | 0 | 0 | 0s | 0s | DBD::_::common::BEGIN |
| 0 | 0 | 0 | 0s | 0s | DBD::_::common::CLEAR |
| 0 | 0 | 0 | 0s | 0s | DBD::_::common::EXISTS |
| 0 | 0 | 0 | 0s | 0s | DBD::_::common::FETCH_many |
| 0 | 0 | 0 | 0s | 0s | DBD::_::common::FIRSTKEY |
| 0 | 0 | 0 | 0s | 0s | DBD::_::common::NEXTKEY |
| 0 | 0 | 0 | 0s | 0s | DBD::_::common::_not_impl |
| 0 | 0 | 0 | 0s | 0s | DBD::_::common::install_method |
| 0 | 0 | 0 | 0s | 0s | DBD::_::common::parse_trace_flag |
| 0 | 0 | 0 | 0s | 0s | DBD::_::common::parse_trace_flags |
| 0 | 0 | 0 | 0s | 0s | DBD::_::common::private_attribute_info |
| 0 | 0 | 0 | 0s | 0s | DBD::_::db::BEGIN |
| 0 | 0 | 0 | 0s | 0s | DBD::_::db::_do_selectrow |
| 0 | 0 | 0 | 0s | 0s | DBD::_::db::begin_work |
| 0 | 0 | 0 | 0s | 0s | DBD::_::db::clone |
| 0 | 0 | 0 | 0s | 0s | DBD::_::db::data_sources |
| 0 | 0 | 0 | 0s | 0s | DBD::_::db::do |
| 0 | 0 | 0 | 0s | 0s | DBD::_::db::ping |
| 0 | 0 | 0 | 0s | 0s | DBD::_::db::prepare_cached |
| 0 | 0 | 0 | 0s | 0s | DBD::_::db::primary_key |
| 0 | 0 | 0 | 0s | 0s | DBD::_::db::quote |
| 0 | 0 | 0 | 0s | 0s | DBD::_::db::quote_identifier |
| 0 | 0 | 0 | 0s | 0s | DBD::_::db::rows |
| 0 | 0 | 0 | 0s | 0s | DBD::_::db::selectall_arrayref |
| 0 | 0 | 0 | 0s | 0s | DBD::_::db::selectall_hashref |
| 0 | 0 | 0 | 0s | 0s | DBD::_::db::selectcol_arrayref |
| 0 | 0 | 0 | 0s | 0s | DBD::_::db::selectrow_array |
| 0 | 0 | 0 | 0s | 0s | DBD::_::db::selectrow_arrayref |
| 0 | 0 | 0 | 0s | 0s | DBD::_::db::selectrow_hashref |
| 0 | 0 | 0 | 0s | 0s | DBD::_::db::tables |
| 0 | 0 | 0 | 0s | 0s | DBD::_::db::type_info |
| 0 | 0 | 0 | 0s | 0s | DBD::_::dr::BEGIN |
| 0 | 0 | 0 | 0s | 0s | DBD::_::dr::connect |
| 0 | 0 | 0 | 0s | 0s | DBD::_::dr::connect_cached |
| 0 | 0 | 0 | 0s | 0s | DBD::_::dr::default_user |
| 0 | 0 | 0 | 0s | 0s | DBD::_::st::BEGIN |
| 0 | 0 | 0 | 0s | 0s | DBD::_::st::__ANON__[:1887] |
| 0 | 0 | 0 | 0s | 0s | DBD::_::st::__ANON__[:1921] |
| 0 | 0 | 0 | 0s | 0s | DBD::_::st::bind_columns |
| 0 | 0 | 0 | 0s | 0s | DBD::_::st::bind_param |
| 0 | 0 | 0 | 0s | 0s | DBD::_::st::bind_param_array |
| 0 | 0 | 0 | 0s | 0s | DBD::_::st::bind_param_inout_array |
| 0 | 0 | 0 | 0s | 0s | DBD::_::st::blob_copy_to_file |
| 0 | 0 | 0 | 0s | 0s | DBD::_::st::execute_array |
| 0 | 0 | 0 | 0s | 0s | DBD::_::st::execute_for_fetch |
| 0 | 0 | 0 | 0s | 0s | DBD::_::st::fetchall_hashref |
| 0 | 0 | 0 | 0s | 0s | DBD::_::st::more_results |
| 0 | 0 | 0 | 0s | 0s | DBI::BEGIN |
| 0 | 0 | 0 | 0s | 0s | DBI::CLONE |
| 0 | 0 | 0 | 0s | 0s | DBI::DBI_tie::STORE |
| 0 | 0 | 0 | 0s | 0s | DBI::DBI_tie::TIEHASH |
| 0 | 0 | 0 | 0s | 0s | DBI::END |
| 0 | 0 | 0 | 0s | 0s | DBI::__ANON__[:1089] |
| 0 | 0 | 0 | 0s | 0s | DBI::__ANON__[:1123] |
| 0 | 0 | 0 | 0s | 0s | DBI::__ANON__[:1124] |
| 0 | 0 | 0 | 0s | 0s | DBI::__ANON__[:998] |
| 0 | 0 | 0 | 0s | 0s | DBI::_dbtype_names |
| 0 | 0 | 0 | 0s | 0s | DBI::_load_class |
| 0 | 0 | 0 | 0s | 0s | DBI::_rebless |
| 0 | 0 | 0 | 0s | 0s | DBI::_rebless_dbtype_subclass |
| 0 | 0 | 0 | 0s | 0s | DBI::_set_isa |
| 0 | 0 | 0 | 0s | 0s | DBI::available_drivers |
| 0 | 0 | 0 | 0s | 0s | DBI::connect_cached |
| 0 | 0 | 0 | 0s | 0s | DBI::connect_test_perf |
| 0 | 0 | 0 | 0s | 0s | DBI::data_diff |
| 0 | 0 | 0 | 0s | 0s | DBI::data_sources |
| 0 | 0 | 0 | 0s | 0s | DBI::data_string_desc |
| 0 | 0 | 0 | 0s | 0s | DBI::data_string_diff |
| 0 | 0 | 0 | 0s | 0s | DBI::disconnect |
| 0 | 0 | 0 | 0s | 0s | DBI::dump_dbd_registry |
| 0 | 0 | 0 | 0s | 0s | DBI::dump_results |
| 0 | 0 | 0 | 0s | 0s | DBI::err |
| 0 | 0 | 0 | 0s | 0s | DBI::errstr |
| 0 | 0 | 0 | 0s | 0s | DBI::init_rootclass |
| 0 | 0 | 0 | 0s | 0s | DBI::installed_drivers |
| 0 | 0 | 0 | 0s | 0s | DBI::installed_methods |
| 0 | 0 | 0 | 0s | 0s | DBI::installed_versions |
| 0 | 0 | 0 | 0s | 0s | DBI::neat_list |
| 0 | 0 | 0 | 0s | 0s | DBI::parse_dsn |
| 0 | 0 | 0 | 0s | 0s | DBI::var::STORE |
| 0 | 0 | 0 | 0s | 0s | DBI::var::TIESCALAR |
| Line | Stmts. | Exclusive Time | Avg. | Code |
|---|---|---|---|---|
| 1 | # $Id: DBI.pm 11570 2008-07-22 21:45:16Z timbo $ | |||
| 2 | # vim: ts=8:sw=4:noet | |||
| 3 | # | |||
| 4 | # Copyright (c) 1994-2008 Tim Bunce Ireland | |||
| 5 | # | |||
| 6 | # See COPYRIGHT section in pod text below for usage and distribution rights. | |||
| 7 | # | |||
| 8 | ||||
| 9 | 1 | 31µs | 31µs | require 5.006_00; |
| 10 | ||||
| 11 | BEGIN { | |||
| 12 | 1 | 1µs | 1µs | $DBI::VERSION = "1.607"; # ==> ALSO update the version in the pod text below! |
| 13 | 1 | 60µs | 60µ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 don't have to subscribe | |||
| 87 | to the list in order to post, though I'd recommend it. You can get help on | |||
| 88 | subscribing and using the list by emailing I<dbi-users-help@perl.org>. | |||
| 89 | ||||
| 90 | I don't recommend the DBI cpanform (at http://www.cpanforum.com/dist/DBI) | |||
| 91 | because relatively few people read it compared with dbi-users@perl.org. | |||
| 92 | ||||
| 93 | To help you make the best use of the dbi-users mailing list, | |||
| 94 | and any other lists or forums you may use, I I<strongly> | |||
| 95 | recommend that you read "How To Ask Questions The Smart Way" | |||
| 96 | by Eric Raymond: L<http://www.catb.org/~esr/faqs/smart-questions.html>. | |||
| 97 | ||||
| 98 | If you think you've found a bug then please also read | |||
| 99 | "How to Report Bugs Effectively" by Simon Tatham: | |||
| 100 | L<http://www.chiark.greenend.org.uk/~sgtatham/bugs.html>. | |||
| 101 | ||||
| 102 | The DBI home page at L<http://dbi.perl.org/> and the DBI FAQ | |||
| 103 | at L<http://faq.dbi-support.com/> are always worth a visit. | |||
| 104 | They include links to other resources. | |||
| 105 | ||||
| 106 | Before asking any questions, reread this document, consult the | |||
| 107 | archives and read the DBI FAQ. The archives are listed | |||
| 108 | at the end of this document and on the DBI home page. | |||
| 109 | ||||
| 110 | This document often uses terms like I<references>, I<objects>, | |||
| 111 | I<methods>. If you're not familar with those terms then it would | |||
| 112 | be a good idea to read at least the following perl manuals first: | |||
| 113 | L<perlreftut>, L<perldsc>, L<perllol>, and L<perlboot>. | |||
| 114 | ||||
| 115 | Please note that Tim Bunce does not maintain the mailing lists or the | |||
| 116 | web page (generous volunteers do that). So please don't send mail | |||
| 117 | directly to him; he just doesn't have the time to answer questions | |||
| 118 | personally. The I<dbi-users> mailing list has lots of experienced | |||
| 119 | people who should be able to help you if you need it. If you do email | |||
| 120 | Tim he's very likely to just forward it to the mailing list. | |||
| 121 | ||||
| 122 | =head2 NOTES | |||
| 123 | ||||
| 124 | This is the DBI specification that corresponds to the DBI version 1.607 | |||
| 125 | ($Revision: 11570 $). | |||
| 126 | ||||
| 127 | The DBI is evolving at a steady pace, so it's good to check that | |||
| 128 | you have the latest copy. | |||
| 129 | ||||
| 130 | The significant user-visible changes in each release are documented | |||
| 131 | in the L<DBI::Changes> module so you can read them by executing | |||
| 132 | C<perldoc DBI::Changes>. | |||
| 133 | ||||
| 134 | Some DBI changes require changes in the drivers, but the drivers | |||
| 135 | can take some time to catch up. Newer versions of the DBI have | |||
| 136 | added features that may not yet be supported by the drivers you | |||
| 137 | use. Talk to the authors of your drivers if you need a new feature | |||
| 138 | that's not yet supported. | |||
| 139 | ||||
| 140 | Features added after DBI 1.21 (February 2002) are marked in the | |||
| 141 | text with the version number of the DBI release they first appeared in. | |||
| 142 | ||||
| 143 | Extensions to the DBI API often use the C<DBIx::*> namespace. | |||
| 144 | See L</Naming Conventions and Name Space>. DBI extension modules | |||
| 145 | can be found at L<http://search.cpan.org/search?mode=module&query=DBIx>. | |||
| 146 | And all modules related to the DBI can be found at | |||
| 147 | L<http://search.cpan.org/search?query=DBI&mode=all>. | |||
| 148 | ||||
| 149 | =cut | |||
| 150 | ||||
| 151 | # The POD text continues at the end of the file. | |||
| 152 | ||||
| 153 | ||||
| 154 | package DBI; | |||
| 155 | ||||
| 156 | 3 | 18µs | 6µs | use Carp(); |
| 157 | 3 | 125µs | 42µs | use DynaLoader (); |
| 158 | 3 | 250µs | 83µs | use Exporter (); |
| 159 | ||||
| 160 | BEGIN { | |||
| 161 | 128 | 141µs | 1µs | @ISA = qw(Exporter DynaLoader); |
| 162 | ||||
| 163 | # Make some utility functions available if asked for | |||
| 164 | @EXPORT = (); # we export nothing by default | |||
| 165 | @EXPORT_OK = qw(%DBI %DBI_methods hash); # also populated by export_ok_tags: | |||
| 166 | %EXPORT_TAGS = ( | |||
| 167 | sql_types => [ qw( | |||
| 168 | SQL_GUID | |||
| 169 | SQL_WLONGVARCHAR | |||
| 170 | SQL_WVARCHAR | |||
| 171 | SQL_WCHAR | |||
| 172 | SQL_BIGINT | |||
| 173 | SQL_BIT | |||
| 174 | SQL_TINYINT | |||
| 175 | SQL_LONGVARBINARY | |||
| 176 | SQL_VARBINARY | |||
| 177 | SQL_BINARY | |||
| 178 | SQL_LONGVARCHAR | |||
| 179 | SQL_UNKNOWN_TYPE | |||
| 180 | SQL_ALL_TYPES | |||
| 181 | SQL_CHAR | |||
| 182 | SQL_NUMERIC | |||
| 183 | SQL_DECIMAL | |||
| 184 | SQL_INTEGER | |||
| 185 | SQL_SMALLINT | |||
| 186 | SQL_FLOAT | |||
| 187 | SQL_REAL | |||
| 188 | SQL_DOUBLE | |||
| 189 | SQL_DATETIME | |||
| 190 | SQL_DATE | |||
| 191 | SQL_INTERVAL | |||
| 192 | SQL_TIME | |||
| 193 | SQL_TIMESTAMP | |||
| 194 | SQL_VARCHAR | |||
| 195 | SQL_BOOLEAN | |||
| 196 | SQL_UDT | |||
| 197 | SQL_UDT_LOCATOR | |||
| 198 | SQL_ROW | |||
| 199 | SQL_REF | |||
| 200 | SQL_BLOB | |||
| 201 | SQL_BLOB_LOCATOR | |||
| 202 | SQL_CLOB | |||
| 203 | SQL_CLOB_LOCATOR | |||
| 204 | SQL_ARRAY | |||
| 205 | SQL_ARRAY_LOCATOR | |||
| 206 | SQL_MULTISET | |||
| 207 | SQL_MULTISET_LOCATOR | |||
| 208 | SQL_TYPE_DATE | |||
| 209 | SQL_TYPE_TIME | |||
| 210 | SQL_TYPE_TIMESTAMP | |||
| 211 | SQL_TYPE_TIME_WITH_TIMEZONE | |||
| 212 | SQL_TYPE_TIMESTAMP_WITH_TIMEZONE | |||
| 213 | SQL_INTERVAL_YEAR | |||
| 214 | SQL_INTERVAL_MONTH | |||
| 215 | SQL_INTERVAL_DAY | |||
| 216 | SQL_INTERVAL_HOUR | |||
| 217 | SQL_INTERVAL_MINUTE | |||
| 218 | SQL_INTERVAL_SECOND | |||
| 219 | SQL_INTERVAL_YEAR_TO_MONTH | |||
| 220 | SQL_INTERVAL_DAY_TO_HOUR | |||
| 221 | SQL_INTERVAL_DAY_TO_MINUTE | |||
| 222 | SQL_INTERVAL_DAY_TO_SECOND | |||
| 223 | SQL_INTERVAL_HOUR_TO_MINUTE | |||
| 224 | SQL_INTERVAL_HOUR_TO_SECOND | |||
| 225 | SQL_INTERVAL_MINUTE_TO_SECOND | |||
| 226 | ) ], | |||
| 227 | sql_cursor_types => [ qw( | |||
| 228 | SQL_CURSOR_FORWARD_ONLY | |||
| 229 | SQL_CURSOR_KEYSET_DRIVEN | |||
| 230 | SQL_CURSOR_DYNAMIC | |||
| 231 | SQL_CURSOR_STATIC | |||
| 232 | SQL_CURSOR_TYPE_DEFAULT | |||
| 233 | ) ], # for ODBC cursor types | |||
| 234 | utils => [ qw( | |||
| 235 | neat neat_list $neat_maxlen dump_results looks_like_number | |||
| 236 | data_string_diff data_string_desc data_diff | |||
| 237 | ) ], | |||
| 238 | profile => [ qw( | |||
| 239 | dbi_profile dbi_profile_merge dbi_profile_merge_nodes dbi_time | |||
| 240 | ) ], # notionally "in" DBI::Profile and normally imported from there | |||
| 241 | ); | |||
| 242 | ||||
| 243 | $DBI::dbi_debug = 0; | |||
| 244 | $DBI::neat_maxlen = 1000; | |||
| 245 | $DBI::stderr = 2_000_000_000; # a very round number below 2**31 | |||
| 246 | ||||
| 247 | # If you get an error here like "Can't find loadable object ..." | |||
| 248 | # then you haven't installed the DBI correctly. Read the README | |||
| 249 | # then install it again. | |||
| 250 | if ( $ENV{DBI_PUREPERL} ) { | |||
| 251 | eval { bootstrap DBI } if $ENV{DBI_PUREPERL} == 1; | |||
| 252 | require DBI::PurePerl if $@ or $ENV{DBI_PUREPERL} >= 2; | |||
| 253 | $DBI::PurePerl ||= 0; # just to silence "only used once" warnings | |||
| 254 | } | |||
| 255 | else { | |||
| 256 | bootstrap DBI; # spent 580µs making 1 call to DynaLoader::bootstrap | |||
| 257 | } | |||
| 258 | ||||
| 259 | $EXPORT_TAGS{preparse_flags} = [ grep { /^DBIpp_\w\w_/ } keys %{__PACKAGE__."::"} ]; | |||
| 260 | ||||
| 261 | Exporter::export_ok_tags(keys %EXPORT_TAGS); # spent 1.91ms making 1 call to Exporter::export_ok_tags | |||
| 262 | ||||
| 263 | 1 | 73µs | 73µs | } |
| 264 | ||||
| 265 | # Alias some handle methods to also be DBI class methods | |||
| 266 | 1 | 2µs | 2µs | for (qw(trace_msg set_err parse_trace_flag parse_trace_flags)) { |
| 267 | 3 | 51µs | 17µs | no strict; # spent 9µs making 1 call to strict::unimport |
| 268 | 4 | 18µs | 5µs | *$_ = \&{"DBD::_::common::$_"}; |
| 269 | } | |||
| 270 | ||||
| 271 | 3 | 1.35ms | 451µs | use strict; # spent 7µs making 1 call to strict::import |
| 272 | ||||
| 273 | 1 | 1µs | 1µs | DBI->trace(split /=/, $ENV{DBI_TRACE}, 2) if $ENV{DBI_TRACE}; |
| 274 | ||||
| 275 | 1 | 500ns | 500ns | $DBI::connect_via ||= "connect"; |
| 276 | ||||
| 277 | # check if user wants a persistent database connection ( Apache + mod_perl ) | |||
| 278 | 1 | 500ns | 500ns | if ($INC{'Apache/DBI.pm'} && $ENV{MOD_PERL}) { |
| 279 | $DBI::connect_via = "Apache::DBI::connect"; | |||
| 280 | DBI->trace_msg("DBI connect via $DBI::connect_via in $INC{'Apache/DBI.pm'}\n"); | |||
| 281 | } | |||
| 282 | ||||
| 283 | # check for weaken support, used by ChildHandles | |||
| 284 | 1 | 900ns | 900ns | my $HAS_WEAKEN = eval { |
| 285 | 1 | 118µs | 118µs | require Scalar::Util; |
| 286 | # this will croak() if this Scalar::Util doesn't have a working weaken(). | |||
| 287 | 1 | 13µs | 13µs | Scalar::Util::weaken( \my $test ); # same test as in t/72childhandles.t # spent 12µs making 1 call to Scalar::Util::weaken |
| 288 | 1 | 2µs | 2µs | 1; |
| 289 | }; | |||
| 290 | ||||
| 291 | 1 | 1µs | 1µs | %DBI::installed_drh = (); # maps driver names to installed driver handles |
| 292 | sub installed_drivers { %DBI::installed_drh } | |||
| 293 | 1 | 500ns | 500ns | %DBI::installed_methods = (); # XXX undocumented, may change |
| 294 | sub installed_methods { %DBI::installed_methods } | |||
| 295 | ||||
| 296 | # Setup special DBI dynamic variables. See DBI::var::FETCH for details. | |||
| 297 | # These are dynamically associated with the last handle used. | |||
| 298 | 1 | 5µs | 5µs | tie $DBI::err, 'DBI::var', '*err'; # special case: referenced via IHA list |
| 299 | 1 | 2µs | 2µs | tie $DBI::state, 'DBI::var', '"state'; # special case: referenced via IHA list |
| 300 | 1 | 2µs | 2µs | tie $DBI::lasth, 'DBI::var', '!lasth'; # special case: return boolean |
| 301 | 1 | 1µs | 1µs | tie $DBI::errstr, 'DBI::var', '&errstr'; # call &errstr in last used pkg |
| 302 | 1 | 2µs | 2µs | tie $DBI::rows, 'DBI::var', '&rows'; # call &rows in last used pkg |
| 303 | 10 | 15µs | 1µs | sub DBI::var::TIESCALAR{ my $var = $_[1]; bless \$var, 'DBI::var'; } |
| 304 | sub DBI::var::STORE { Carp::croak("Can't modify \$DBI::${$_[0]} special variable") } | |||
| 305 | ||||
| 306 | { # used to catch DBI->{Attrib} mistake | |||
| 307 | 2 | 9µs | 5µs | sub DBI::DBI_tie::TIEHASH { bless {} } |
| 308 | sub DBI::DBI_tie::STORE { Carp::carp("DBI->{$_[1]} is invalid syntax (you probably want \$h->{$_[1]})");} | |||
| 309 | 1 | 2µs | 2µs | *DBI::DBI_tie::FETCH = \&DBI::DBI_tie::STORE; |
| 310 | } | |||
| 311 | 1 | 3µs | 3µs | tie %DBI::DBI => 'DBI::DBI_tie'; |
| 312 | ||||
| 313 | # --- Driver Specific Prefix Registry --- | |||
| 314 | ||||
| 315 | 1 | 45µs | 45µs | my $dbd_prefix_registry = { |
| 316 | ad_ => { class => 'DBD::AnyData', }, | |||
| 317 | ado_ => { class => 'DBD::ADO', }, | |||
| 318 | amzn_ => { class => 'DBD::Amazon', }, | |||
| 319 | best_ => { class => 'DBD::BestWins', }, | |||
| 320 | csv_ => { class => 'DBD::CSV', }, | |||
| 321 | db2_ => { class => 'DBD::DB2', }, | |||
| 322 | dbi_ => { class => 'DBI', }, | |||
| 323 | dbm_ => { class => 'DBD::DBM', }, | |||
| 324 | df_ => { class => 'DBD::DF', }, | |||
| 325 | f_ => { class => 'DBD::File', }, | |||
| 326 | file_ => { class => 'DBD::TextFile', }, | |||
| 327 | go_ => { class => 'DBD::Gofer', }, | |||
| 328 | ib_ => { class => 'DBD::InterBase', }, | |||
| 329 | ing_ => { class => 'DBD::Ingres', }, | |||
| 330 | ix_ => { class => 'DBD::Informix', }, | |||
| 331 | jdbc_ => { class => 'DBD::JDBC', }, | |||
| 332 | monetdb_ => { class => 'DBD::monetdb', }, | |||
| 333 | msql_ => { class => 'DBD::mSQL', }, | |||
| 334 | mvsftp_ => { class => 'DBD::MVS_FTPSQL', }, | |||
| 335 | mysql_ => { class => 'DBD::mysql', }, | |||
| 336 | mx_ => { class => 'DBD::Multiplex', }, | |||
| 337 | nullp_ => { class => 'DBD::NullP', }, | |||
| 338 | odbc_ => { class => 'DBD::ODBC', }, | |||
| 339 | ora_ => { class => 'DBD::Oracle', }, | |||
| 340 | pg_ => { class => 'DBD::Pg', }, | |||
| 341 | plb_ => { class => 'DBD::Plibdata', }, | |||
| 342 | proxy_ => { class => 'DBD::Proxy', }, | |||
| 343 | rdb_ => { class => 'DBD::RDB', }, | |||
| 344 | sapdb_ => { class => 'DBD::SAP_DB', }, | |||
| 345 | solid_ => { class => 'DBD::Solid', }, | |||
| 346 | sponge_ => { class => 'DBD::Sponge', }, | |||
| 347 | sql_ => { class => 'SQL::Statement', }, | |||
| 348 | syb_ => { class => 'DBD::Sybase', }, | |||
| 349 | tdat_ => { class => 'DBD::Teradata', }, | |||
| 350 | tmpl_ => { class => 'DBD::Template', }, | |||
| 351 | tmplss_ => { class => 'DBD::TemplateSS', }, | |||
| 352 | tuber_ => { class => 'DBD::Tuber', }, | |||
| 353 | uni_ => { class => 'DBD::Unify', }, | |||
| 354 | vt_ => { class => 'DBD::Vt', }, | |||
| 355 | wmi_ => { class => 'DBD::WMI', }, | |||
| 356 | x_ => { }, # for private use | |||
| 357 | xbase_ => { class => 'DBD::XBase', }, | |||
| 358 | xl_ => { class => 'DBD::Excel', }, | |||
| 359 | yaswi_ => { class => 'DBD::Yaswi', }, | |||
| 360 | }; | |||
| 361 | ||||
| 362 | sub dump_dbd_registry { | |||
| 363 | require Data::Dumper; | |||
| 364 | local $Data::Dumper::Sortkeys=1; | |||
| 365 | local $Data::Dumper::Indent=1; | |||
| 366 | print Data::Dumper->Dump([$dbd_prefix_registry], [qw($dbd_prefix_registry)]); | |||
| 367 | } | |||
| 368 | ||||
| 369 | # --- Dynamically create the DBI Standard Interface | |||
| 370 | ||||
| 371 | 1 | 1µs | 1µs | my $keeperr = { O=>0x0004 }; |
| 372 | ||||
| 373 | 1 | 139µs | 139µs | %DBI::DBI_methods = ( # Define the DBI interface methods per class: |
| 374 | ||||
| 375 | common => { # Interface methods common to all DBI handle classes | |||
| 376 | 'DESTROY' => { O=>0x004|0x10000 }, | |||
| 377 | 'CLEAR' => $keeperr, | |||
| 378 | 'EXISTS' => $keeperr, | |||
| 379 | 'FETCH' => { O=>0x0404 }, | |||
| 380 | 'FETCH_many' => { O=>0x0404 }, | |||
| 381 | 'FIRSTKEY' => $keeperr, | |||
| 382 | 'NEXTKEY' => $keeperr, | |||
| 383 | 'STORE' => { O=>0x0418 | 0x4 }, | |||
| 384 | _not_impl => undef, | |||
| 385 | can => { O=>0x0100 }, # special case, see dispatch | |||
| 386 | debug => { U =>[1,2,'[$debug_level]'], O=>0x0004 }, # old name for trace | |||
| 387 | dump_handle => { U =>[1,3,'[$message [, $level]]'], O=>0x0004 }, | |||
| 388 | err => $keeperr, | |||
| 389 | errstr => $keeperr, | |||
| 390 | state => $keeperr, | |||
| 391 | func => { O=>0x0006 }, | |||
| 392 | parse_trace_flag => { U =>[2,2,'$name'], O=>0x0404, T=>8 }, | |||
| 393 | parse_trace_flags => { U =>[2,2,'$flags'], O=>0x0404, T=>8 }, | |||
| 394 | private_data => { U =>[1,1], O=>0x0004 }, | |||
| 395 | set_err => { U =>[3,6,'$err, $errmsg [, $state, $method, $rv]'], O=>0x0010 }, | |||
| 396 | trace => { U =>[1,3,'[$trace_level, [$filename]]'], O=>0x0004 }, | |||
| 397 | trace_msg => { U =>[2,3,'$message_text [, $min_level ]' ], O=>0x0004, T=>8 }, | |||
| 398 | swap_inner_handle => { U =>[2,3,'$h [, $allow_reparent ]'] }, | |||
| 399 | private_attribute_info => { }, | |||
| 400 | }, | |||
| 401 | dr => { # Database Driver Interface | |||
| 402 | 'connect' => { U =>[1,5,'[$db [,$user [,$passwd [,\%attr]]]]'], H=>3, O=>0x8000 }, | |||
| 403 | 'connect_cached'=>{U=>[1,5,'[$db [,$user [,$passwd [,\%attr]]]]'], H=>3, O=>0x8000 }, | |||
| 404 | 'disconnect_all'=>{ U =>[1,1], O=>0x0800 }, | |||
| 405 | data_sources => { U =>[1,2,'[\%attr]' ], O=>0x0800 }, | |||
| 406 | default_user => { U =>[3,4,'$user, $pass [, \%attr]' ] }, | |||
| 407 | dbixs_revision => $keeperr, | |||
| 408 | }, | |||
| 409 | db => { # Database Session Class Interface | |||
| 410 | data_sources => { U =>[1,2,'[\%attr]' ], O=>0x0200 }, | |||
| 411 | take_imp_data => { U =>[1,1], O=>0x10000 }, | |||
| 412 | clone => { U =>[1,2,'[\%attr]'] }, | |||
| 413 | connected => { U =>[1,0], O => 0x0004 }, | |||
| 414 | begin_work => { U =>[1,2,'[ \%attr ]'], O=>0x0400 }, | |||
| 415 | commit => { U =>[1,1], O=>0x0480|0x0800 }, | |||
| 416 | rollback => { U =>[1,1], O=>0x0480|0x0800 }, | |||
| 417 | 'do' => { U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'], O=>0x3200 }, | |||
| 418 | last_insert_id => { U =>[5,6,'$catalog, $schema, $table_name, $field_name [, \%attr ]'], O=>0x2800 }, | |||
| 419 | preparse => { }, # XXX | |||
| 420 | prepare => { U =>[2,3,'$statement [, \%attr]'], O=>0xA200 }, | |||
| 421 | prepare_cached => { U =>[2,4,'$statement [, \%attr [, $if_active ] ]'], O=>0xA200 }, | |||
| 422 | selectrow_array => { U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'], O=>0x2000 }, | |||
| 423 | selectrow_arrayref=>{U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'], O=>0x2000 }, | |||
| 424 | selectrow_hashref=>{ U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'], O=>0x2000 }, | |||
| 425 | selectall_arrayref=>{U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'], O=>0x2000 }, | |||
| 426 | selectall_hashref=>{ U =>[3,0,'$statement, $keyfield [, \%attr [, @bind_params ] ]'], O=>0x2000 }, | |||
| 427 | selectcol_arrayref=>{U =>[2,0,'$statement [, \%attr [, @bind_params ] ]'], O=>0x2000 }, | |||
| 428 | ping => { U =>[1,1], O=>0x0404 }, | |||
| 429 | disconnect => { U =>[1,1], O=>0x0400|0x0800|0x10000 }, | |||
| 430 | quote => { U =>[2,3, '$string [, $data_type ]' ], O=>0x0430 }, | |||
| 431 | quote_identifier=> { U =>[2,6, '$name [, ...] [, \%attr ]' ], O=>0x0430 }, | |||
| 432 | rows => $keeperr, | |||
| 433 | ||||
| 434 | tables => { U =>[1,6,'$catalog, $schema, $table, $type [, \%attr ]' ], O=>0x2200 }, | |||
| 435 | table_info => { U =>[1,6,'$catalog, $schema, $table, $type [, \%attr ]' ], O=>0x2200|0x8800 }, | |||
| 436 | column_info => { U =>[5,6,'$catalog, $schema, $table, $column [, \%attr ]'],O=>0x2200|0x8800 }, | |||
| 437 | primary_key_info=> { U =>[4,5,'$catalog, $schema, $table [, \%attr ]' ], O=>0x2200|0x8800 }, | |||
| 438 | primary_key => { U =>[4,5,'$catalog, $schema, $table [, \%attr ]' ], O=>0x2200 }, | |||
| 439 | foreign_key_info=> { U =>[7,8,'$pk_catalog, $pk_schema, $pk_table, $fk_catalog, $fk_schema, $fk_table [, \%attr ]' ], O=>0x2200|0x8800 }, | |||
| 440 | statistics_info => { U =>[6,7,'$catalog, $schema, $table, $unique_only, $quick, [, \%attr ]' ], O=>0x2200|0x8800 }, | |||
| 441 | type_info_all => { U =>[1,1], O=>0x2200|0x0800 }, | |||
| 442 | type_info => { U =>[1,2,'$data_type'], O=>0x2200 }, | |||
| 443 | get_info => { U =>[2,2,'$info_type'], O=>0x2200|0x0800 }, | |||
| 444 | }, | |||
| 445 | st => { # Statement Class Interface | |||
| 446 | bind_col => { U =>[3,4,'$column, \\$var [, \%attr]'] }, | |||
| 447 | bind_columns => { U =>[2,0,'\\$var1 [, \\$var2, ...]'] }, | |||
| 448 | bind_param => { U =>[3,4,'$parameter, $var [, \%attr]'] }, | |||
| 449 | bind_param_inout=> { U =>[4,5,'$parameter, \\$var, $maxlen, [, \%attr]'] }, | |||
| 450 | execute => { U =>[1,0,'[@args]'], O=>0x1040 }, | |||
| 451 | ||||
| 452 | bind_param_array => { U =>[3,4,'$parameter, $var [, \%attr]'] }, | |||
| 453 | bind_param_inout_array => { U =>[4,5,'$parameter, \\@var, $maxlen, [, \%attr]'] }, | |||
| 454 | execute_array => { U =>[2,0,'\\%attribs [, @args]'], O=>0x1040|0x4000 }, | |||
| 455 | execute_for_fetch => { U =>[2,3,'$fetch_sub [, $tuple_status]'], O=>0x1040|0x4000 }, | |||
| 456 | ||||
| 457 | fetch => undef, # alias for fetchrow_arrayref | |||
| 458 | fetchrow_arrayref => undef, | |||
| 459 | fetchrow_hashref => undef, | |||
| 460 | fetchrow_array => undef, | |||
| 461 | fetchrow => undef, # old alias for fetchrow_array | |||
| 462 | ||||
| 463 | fetchall_arrayref => { U =>[1,3, '[ $slice [, $max_rows]]'] }, | |||
| 464 | fetchall_hashref => { U =>[2,2,'$key_field'] }, | |||
| 465 | ||||
| 466 | blob_read => { U =>[4,5,'$field, $offset, $len [, \\$buf [, $bufoffset]]'] }, | |||
| 467 | blob_copy_to_file => { U =>[3,3,'$field, $filename_or_handleref'] }, | |||
| 468 | dump_results => { U =>[1,5,'$maxfieldlen, $linesep, $fieldsep, $filehandle'] }, | |||
| 469 | more_results => { U =>[1,1] }, | |||
| 470 | finish => { U =>[1,1] }, | |||
| 471 | cancel => { U =>[1,1], O=>0x0800 }, | |||
| 472 | rows => $keeperr, | |||
| 473 | ||||
| 474 | _get_fbav => undef, | |||
| 475 | _set_fbav => { T=>6 }, | |||
| 476 | }, | |||
| 477 | ); | |||
| 478 | ||||
| 479 | 1 | 9µs | 9µs | while ( my ($class, $meths) = each %DBI::DBI_methods ) { |
| 480 | 4 | 5µs | 1µs | my $ima_trace = 0+($ENV{DBI_IMA_TRACE}||0); |
| 481 | 4 | 194µs | 49µs | while ( my ($method, $info) = each %$meths ) { |
| 482 | 88 | 60µs | 681ns | my $fullmeth = "DBI::${class}::$method"; |
| 483 | 88 | 23µs | 259ns | if ($DBI::dbi_debug >= 15) { # quick hack to list DBI methods |
| 484 | # and optionally filter by IMA flags | |||
| 485 | my $O = $info->{O}||0; | |||
| 486 | printf "0x%04x %-20s\n", $O, $fullmeth | |||
| 487 | unless $ima_trace && !($O & $ima_trace); | |||
| 488 | } | |||
| 489 | 88 | 689µs | 8µs | DBI->_install_method($fullmeth, 'DBI.pm', $info); # spent 581µs making 88 calls to DBI::_install_method, avg 7µs/call |
| 490 | } | |||
| 491 | } | |||
| 492 | ||||
| 493 | { | |||
| 494 | 1 | 1µs | 1µs | package DBI::common; |
| 495 | 1 | 8µs | 8µs | @DBI::dr::ISA = ('DBI::common'); |
| 496 | 1 | 4µs | 4µs | @DBI::db::ISA = ('DBI::common'); |
| 497 | 1 | 3µs | 3µs | @DBI::st::ISA = ('DBI::common'); |
| 498 | } | |||
| 499 | ||||
| 500 | # End of init code | |||
| 501 | ||||
| 502 | ||||
| 503 | END { | |||
| 504 | 5 | 42µs | 8µs | return unless defined &DBI::trace_msg; # return unless bootstrap'd ok |
| 505 | local ($!,$?); | |||
| 506 | DBI->trace_msg(sprintf(" -- DBI::END (\$\@: %s, \$!: %s)\n", $@||'', $!||''), 2); # spent 16µs making 1 call to DBD::_::common::trace_msg | |||
| 507 | # Let drivers know why we are calling disconnect_all: | |||
| 508 | $DBI::PERL_ENDING = $DBI::PERL_ENDING = 1; # avoid typo warning | |||
| 509 | DBI->disconnect_all() if %DBI::installed_drh; # spent 39µs making 1 call to DBI::disconnect_all | |||
| 510 | } | |||
| 511 | ||||
| 512 | ||||
| 513 | sub CLONE { | |||
| 514 | my $olddbis = $DBI::_dbistate; | |||
| 515 | _clone_dbis() unless $DBI::PurePerl; # clone the DBIS structure | |||
| 516 | DBI->trace_msg(sprintf "CLONE DBI for new thread %s\n", | |||
| 517 | $DBI::PurePerl ? "" : sprintf("(dbis %x -> %x)",$olddbis, $DBI::_dbistate)); | |||
| 518 | while ( my ($driver, $drh) = each %DBI::installed_drh) { | |||
| 519 | 3 | 1.02ms | 338µs | no strict 'refs'; # spent 26µs making 1 call to strict::unimport |
| 520 | next if defined &{"DBD::${driver}::CLONE"}; | |||
| 521 | warn("$driver has no driver CLONE() function so is unsafe threaded\n"); | |||
| 522 | } | |||
| 523 | %DBI::installed_drh = (); # clear loaded drivers so they have a chance to reinitialize | |||
| 524 | } | |||
| 525 | ||||
| 526 | sub parse_dsn { | |||
| 527 | my ($class, $dsn) = @_; | |||
| 528 | $dsn =~ s/^(dbi):(\w*?)(?:\((.*?)\))?://i or return; | |||
| 529 | my ($scheme, $driver, $attr, $attr_hash) = (lc($1), $2, $3); | |||
| 530 | $driver ||= $ENV{DBI_DRIVER} || ''; | |||
| 531 | $attr_hash = { split /\s*=>?\s*|\s*,\s*/, $attr, -1 } if $attr; | |||
| 532 | return ($scheme, $driver, $attr, $attr_hash, $dsn); | |||
| 533 | } | |||
| 534 | ||||
| 535 | ||||
| 536 | # --- The DBI->connect Front Door methods | |||
| 537 | ||||
| 538 | sub connect_cached { | |||
| 539 | # For library code using connect_cached() with mod_perl | |||
| 540 | # we redirect those calls to Apache::DBI::connect() as well | |||
| 541 | my ($class, $dsn, $user, $pass, $attr) = @_; | |||
| 542 | my $dbi_connect_method = ($DBI::connect_via eq "Apache::DBI::connect") | |||
| 543 | ? 'Apache::DBI::connect' : 'connect_cached'; | |||
| 544 | $attr = { | |||
| 545 | $attr ? %$attr : (), # clone, don't modify callers data | |||
| 546 | dbi_connect_method => $dbi_connect_method, | |||
| 547 | }; | |||
| 548 | return $class->connect($dsn, $user, $pass, $attr); | |||
| 549 | } | |||
| 550 | ||||
| 551 | # spent 18.7ms (113µs+18.6) within DBI::connect which was called
# once (113µs+18.6ms) by C4::Context::_new_dbh at line 693 of /home/chris/git/koha.git/C4/Context.pm | |||
| 552 | 29 | 122µs | 4µs | my $class = shift; |
| 553 | my ($dsn, $user, $pass, $attr, $old_driver) = my @orig_args = @_; | |||
| 554 | my $driver; | |||
| 555 | ||||
| 556 | if ($attr and !ref($attr)) { # switch $old_driver<->$attr if called in old style | |||
| 557 | Carp::carp("DBI->connect using 'old-style' syntax is deprecated and will be an error in future versions"); | |||
| 558 | ($old_driver, $attr) = ($attr, $old_driver); | |||
| 559 | } | |||
| 560 | ||||
| 561 | my $connect_meth = $attr->{dbi_connect_method}; | |||
| 562 | $connect_meth ||= $DBI::connect_via; # fallback to default | |||
| 563 | ||||
| 564 | $dsn ||= $ENV{DBI_DSN} || $ENV{DBI_DBNAME} || '' unless $old_driver; | |||
| 565 | ||||
| 566 | if ($DBI::dbi_debug) { | |||
| 567 | local $^W = 0; | |||
| 568 | pop @_ if $connect_meth ne 'connect'; | |||
| 569 | my @args = @_; $args[2] = '****'; # hide password | |||
| 570 | DBI->trace_msg(" -> $class->$connect_meth(".join(", ",@args).")\n"); | |||
| 571 | } | |||
| 572 | Carp::croak('Usage: $class->connect([$dsn [,$user [,$passwd [,\%attr]]]])') | |||
| 573 | if (ref $old_driver or ($attr and not ref $attr) or ref $pass); | |||
| 574 | ||||
| 575 | # extract dbi:driver prefix from $dsn into $1 | |||
| 576 | 1 | 18µs | 18µs | $dsn =~ s/^dbi:(\w*?)(?:\((.*?)\))?://i # spent 3.54ms making 1 call to utf8::SWASHNEW |
| 577 | or '' =~ /()/; # ensure $1 etc are empty if match fails | |||
| 578 | my $driver_attrib_spec = $2 || ''; | |||
| 579 | ||||
| 580 | # Set $driver. Old style driver, if specified, overrides new dsn style. | |||
| 581 | $driver = $old_driver || $1 || $ENV{DBI_DRIVER} | |||
| 582 | or Carp::croak("Can't connect to data source '$dsn' " | |||
| 583 | ."because I can't work out what driver to use " | |||
| 584 | ."(it doesn't seem to contain a 'dbi:driver:' prefix " | |||
| 585 | ."and the DBI_DRIVER env var is not set)"); | |||
| 586 | ||||
| 587 | my $proxy; | |||
| 588 | if ($ENV{DBI_AUTOPROXY} && $driver ne 'Proxy' && $driver ne 'Sponge' && $driver ne 'Switch') { | |||
| 589 | my $dbi_autoproxy = $ENV{DBI_AUTOPROXY}; | |||
| 590 | $proxy = 'Proxy'; | |||
| 591 | if ($dbi_autoproxy =~ s/^dbi:(\w*?)(?:\((.*?)\))?://i) { | |||
| 592 | $proxy = $1; | |||
| 593 | $driver_attrib_spec = join ",", | |||
| 594 | ($driver_attrib_spec) ? $driver_attrib_spec : (), | |||
| 595 | ($2 ) ? $2 : (); | |||
| 596 | } | |||
| 597 | $dsn = "$dbi_autoproxy;dsn=dbi:$driver:$dsn"; | |||
| 598 | $driver = $proxy; | |||
| 599 | DBI->trace_msg(" DBI_AUTOPROXY: dbi:$driver($driver_attrib_spec):$dsn\n"); | |||
| 600 | } | |||
| 601 | # avoid recursion if proxy calls DBI->connect itself | |||
| 602 | local $ENV{DBI_AUTOPROXY}; | |||
| 603 | ||||
| 604 | my %attributes; # take a copy we can delete from | |||
| 605 | if ($old_driver) { | |||
| 606 | %attributes = %$attr if $attr; | |||
| 607 | } | |||
| 608 | else { # new-style connect so new default semantics | |||
| 609 | %attributes = ( | |||
| 610 | PrintError => 1, | |||
| 611 | AutoCommit => 1, | |||
| 612 | ref $attr ? %$attr : (), | |||
| 613 | # attributes in DSN take precedence over \%attr connect parameter | |||
| 614 | $driver_attrib_spec ? (split /\s*=>?\s*|\s*,\s*/, $driver_attrib_spec, -1) : (), | |||
| 615 | ); | |||
| 616 | } | |||
| 617 | $attr = \%attributes; # now set $attr to refer to our local copy | |||
| 618 | ||||
| 619 | my $drh = $DBI::installed_drh{$driver} || $class->install_driver($driver) # spent 11.5ms making 1 call to DBI::install_driver | |||
| 620 | or die "panic: $class->install_driver($driver) failed"; | |||
| 621 | ||||
| 622 | # attributes in DSN take precedence over \%attr connect parameter | |||
| 623 | $user = $attr->{Username} if defined $attr->{Username}; | |||
| 624 | $pass = $attr->{Password} if defined $attr->{Password}; | |||
| 625 | delete $attr->{Password}; # always delete Password as closure stores it securely | |||
| 626 | if ( !(defined $user && defined $pass) ) { | |||
| 627 | ($user, $pass) = $drh->default_user($user, $pass, $attr); | |||
| 628 | } | |||
| 629 | $attr->{Username} = $user; # force the Username to be the actual one used | |||
| 630 | ||||
| 631 | # spent 3.57ms (71µs+3.50) within DBI::__ANON__[/usr/lib/perl5/DBI.pm:704] which was called
# once (71µs+3.50ms) by DBI::connect at line 706 | |||
| 632 | 22 | 224µs | 10µs | my ($old_dbh, $override_attr) = @_; |
| 633 | ||||
| 634 | #use Data::Dumper; | |||
| 635 | #warn "connect_closure: ".Data::Dumper::Dumper([$attr,\%attributes, $override_attr]); | |||
| 636 | ||||
| 637 | my $dbh; | |||
| 638 | 1 | 15µs | 15µs | unless ($dbh = $drh->$connect_meth($dsn, $user, $pass, $attr)) { # spent 3.36ms making 1 call to DBI::dr::connect |
| 639 | $user = '' if !defined $user; | |||
| 640 | $dsn = '' if !defined $dsn; | |||
| 641 | # $drh->errstr isn't safe here because $dbh->DESTROY may not have | |||
| 642 | # been called yet and so the dbh errstr would not have been copied | |||
| 643 | # up to the drh errstr. Certainly true for connect_cached! | |||
| 644 | my $errstr = $DBI::errstr; | |||
| 645 | # Getting '(no error string)' here is a symptom of a ref loop | |||
| 646 | $errstr = '(no error string)' if !defined $errstr; | |||
| 647 | my $msg = "$class connect('$dsn','$user',...) failed: $errstr"; | |||
| 648 | DBI->trace_msg(" $msg\n"); | |||
| 649 | # XXX HandleWarn | |||
| 650 | unless ($attr->{HandleError} && $attr->{HandleError}->($msg, $drh, $dbh)) { | |||
| 651 | Carp::croak($msg) if $attr->{RaiseError}; | |||
| 652 | Carp::carp ($msg) if $attr->{PrintError}; | |||
| 653 | } | |||
| 654 | $! = 0; # for the daft people who do DBI->connect(...) || die "$!"; | |||
| 655 | return $dbh; # normally undef, but HandleError could change it | |||
| 656 | } | |||
| 657 | ||||
| 658 | # merge any attribute overrides but don't change $attr itself (for closure) | |||
| 659 | my $apply = { ($override_attr) ? (%$attr, %$override_attr ) : %$attr }; | |||
| 660 | ||||
| 661 | # handle basic RootClass subclassing: | |||
| 662 | my $rebless_class = $apply->{RootClass} || ($class ne 'DBI' ? $class : ''); | |||
| 663 | if ($rebless_class) { | |||
| 664 | 3 | 804µs | 268µs | no strict 'refs'; # spent 18µs making 1 call to strict::unimport |
| 665 | if ($apply->{RootClass}) { # explicit attribute (ie not static methd call class) | |||
| 666 | delete $apply->{RootClass}; | |||
| 667 | DBI::_load_class($rebless_class, 0); | |||
| 668 | } | |||
| 669 | unless (@{"$rebless_class\::db::ISA"} && @{"$rebless_class\::st::ISA"}) { | |||
| 670 | Carp::carp("DBI subclasses '$rebless_class\::db' and ::st are not setup, RootClass ignored"); | |||
| 671 | $rebless_class = undef; | |||
| 672 | $class = 'DBI'; | |||
| 673 | } | |||
| 674 | else { | |||
| 675 | $dbh->{RootClass} = $rebless_class; # $dbh->STORE called via plain DBI::db | |||
| 676 | DBI::_set_isa([$rebless_class], 'DBI'); # sets up both '::db' and '::st' | |||
| 677 | DBI::_rebless($dbh, $rebless_class); # appends '::db' | |||
| 678 | } | |||
| 679 | } | |||
| 680 | ||||
| 681 | if (%$apply) { | |||
| 682 | ||||
| 683 | if ($apply->{DbTypeSubclass}) { | |||
| 684 | my $DbTypeSubclass = delete $apply->{DbTypeSubclass}; | |||
| 685 | DBI::_rebless_dbtype_subclass($dbh, $rebless_class||$class, $DbTypeSubclass); | |||
| 686 | } | |||
| 687 | my $a; | |||
| 688 | foreach $a (qw(Profile RaiseError PrintError AutoCommit)) { # do these first | |||
| 689 | next unless exists $apply->{$a}; | |||
| 690 | $dbh->{$a} = delete $apply->{$a}; # spent 108µs making 2 calls to DBI::common::STORE, avg 54µs/call | |||
| 691 | } | |||
| 692 | while ( my ($a, $v) = each %$apply) { | |||
| 693 | eval { $dbh->{$a} = $v } or $@ && warn $@; # spent 13µs making 1 call to DBI::common::STORE
# spent 10µs making 1 call to DBI::common::FETCH | |||
| 694 | } | |||
| 695 | } | |||
| 696 | ||||
| 697 | # confirm to driver (ie if subclassed) that we've connected sucessfully | |||
| 698 | # and finished the attribute setup. pass in the original arguments | |||
| 699 | $dbh->connected(@orig_args); #if ref $dbh ne 'DBI::db' or $proxy; # spent 14µs making 1 call to DBI::db::connected | |||
| 700 | ||||
| 701 | DBI->trace_msg(" <- connect= $dbh\n") if $DBI::dbi_debug; | |||
| 702 | ||||
| 703 | return $dbh; | |||
| 704 | }; | |||
| 705 | ||||
| 706 | my $dbh = &$connect_closure(undef, undef); # spent 3.57ms making 1 call to DBI::__ANON__[/usr/lib/perl5/DBI.pm:704] | |||
| 707 | ||||
| 708 | $dbh->{dbi_connect_closure} = $connect_closure if $dbh; # spent 11µs making 1 call to DBI::common::STORE | |||
| 709 | ||||
| 710 | return $dbh; | |||
| 711 | } | |||
| 712 | ||||
| 713 | ||||
| 714 | # spent 39µs (16+23) within DBI::disconnect_all which was called
# once (16µs+23µs) by DBI::END at line 509 | |||
| 715 | 2 | 33µs | 17µs | keys %DBI::installed_drh; # reset iterator |
| 716 | while ( my ($name, $drh) = each %DBI::installed_drh ) { # spent 23µs making 1 call to DBI::dr::disconnect_all | |||
| 717 | $drh->disconnect_all() if ref $drh; | |||
| 718 | } | |||
| 719 | } | |||
| 720 | ||||
| 721 | ||||
| 722 | sub disconnect { # a regular beginners bug | |||
| 723 | Carp::croak("DBI->disconnect is not a DBI method (read the DBI manual)"); | |||
| 724 | } | |||
| 725 | ||||
| 726 | ||||
| 727 | # spent 11.5ms (8.81+2.69) within DBI::install_driver which was called
# once (8.81ms+2.69ms) by DBI::connect at line 619 | |||
| 728 | 19 | 80µs | 4µs | my $class = shift; |
| 729 | my($driver, $attr) = @_; | |||
| 730 | my $drh; | |||
| 731 | ||||
| 732 | $driver ||= $ENV{DBI_DRIVER} || ''; | |||
| 733 | ||||
| 734 | # allow driver to be specified as a 'dbi:driver:' string | |||
| 735 | $driver = $1 if $driver =~ s/^DBI:(.*?)://i; | |||
| 736 | ||||
| 737 | Carp::croak("usage: $class->install_driver(\$driver [, \%attr])") | |||
| 738 | unless ($driver and @_<=3); | |||
| 739 | ||||
| 740 | # already installed | |||
| 741 | return $drh if $drh = $DBI::installed_drh{$driver}; | |||
| 742 | ||||
| 743 | $class->trace_msg(" -> $class->install_driver($driver" | |||
| 744 | .") for $^O perl=$] pid=$$ ruid=$< euid=$>\n") | |||
| 745 | if $DBI::dbi_debug; | |||
| 746 | ||||
| 747 | # --- load the code | |||
| 748 | my $driver_class = "DBD::$driver"; | |||
| 749 | 1 | 106µs | 106µs | eval qq{package # hide from PAUSE |
| 750 | DBI::_firesafe; # just in case | |||
| 751 | require $driver_class; # load the driver | |||
| 752 | }; | |||
| 753 | if ($@) { | |||
| 754 | my $err = $@; | |||
| 755 | my $advice = ""; | |||
| 756 | if ($err =~ /Can't find loadable object/) { | |||
| 757 | $advice = "Perhaps DBD::$driver was statically linked into a new perl binary." | |||
| 758 | ."\nIn which case you need to use that new perl binary." | |||
| 759 | ."\nOr perhaps only the .pm file was installed but not the shared object file." | |||
| 760 | } | |||
| 761 | elsif ($err =~ /Can't locate.*?DBD\/$driver\.pm in \@INC/) { | |||
| 762 | my @drv = $class->available_drivers(1); | |||
| 763 | $advice = "Perhaps the DBD::$driver perl module hasn't been fully installed,\n" | |||
| 764 | ."or perhaps the capitalisation of '$driver' isn't right.\n" | |||
| 765 | ."Available drivers: ".join(", ", @drv)."."; | |||
| 766 | } | |||
| 767 | elsif ($err =~ /Can't load .*? for module DBD::/) { | |||
| 768 | $advice = "Perhaps a required shared library or dll isn't installed where expected"; | |||
| 769 | } | |||
| 770 | elsif ($err =~ /Can't locate .*? in \@INC/) { | |||
| 771 | $advice = "Perhaps a module that DBD::$driver requires hasn't been fully installed"; | |||
| 772 | } | |||
| 773 | Carp::croak("install_driver($driver) failed: $err$advice\n"); | |||
| 774 | } | |||
| 775 | if ($DBI::dbi_debug) { | |||
| 776 | 3 | 339µs | 113µs | no strict 'refs'; # spent 18µs making 1 call to strict::unimport |
| 777 | (my $driver_file = $driver_class) =~ s/::/\//g; | |||
| 778 | my $dbd_ver = ${"$driver_class\::VERSION"} || "undef"; | |||
| 779 | $class->trace_msg(" install_driver: $driver_class version $dbd_ver" | |||
| 780 | ." loaded from $INC{qq($driver_file.pm)}\n"); | |||
| 781 | } | |||
| 782 | ||||
| 783 | # --- do some behind-the-scenes checks and setups on the driver | |||
| 784 | $class->setup_driver($driver_class); # spent 121µs making 1 call to DBI::setup_driver | |||
| 785 | ||||
| 786 | # --- run the driver function | |||
| 787 | $drh = eval { $driver_class->driver($attr || {}) }; # spent 106µs making 1 call to DBD::mysql::driver | |||
| 788 | unless ($drh && ref $drh && !$@) { | |||
| 789 | my $advice = ""; | |||
| 790 | $@ ||= "$driver_class->driver didn't return a handle"; | |||
| 791 | # catch people on case in-sensitive systems using the wrong case | |||
| 792 | $advice = "\nPerhaps the capitalisation of DBD '$driver' isn't right." | |||
| 793 | if $@ =~ /locate object method/; | |||
| 794 | Carp::croak("$driver_class initialisation failed: $@$advice"); | |||
| 795 | } | |||
| 796 | ||||
| 797 | $DBI::installed_drh{$driver} = $drh; | |||
| 798 | $class->trace_msg(" <- install_driver= $drh\n") if $DBI::dbi_debug; | |||
| 799 | $drh; | |||
| 800 | } | |||
| 801 | ||||
| 802 | 1 | 2µs | 2µs | *driver = \&install_driver; # currently an alias, may change |
| 803 | ||||
| 804 | ||||
| 805 | sub setup_driver { | |||
| 806 | 30 | 227µs | 8µs | my ($class, $driver_class) = @_; |
| 807 | my $type; | |||
| 808 | foreach $type (qw(dr db st)){ | |||
| 809 | my $class = $driver_class."::$type"; | |||
| 810 | 3 | 273µs | 91µs | no strict 'refs'; # spent 18µs making 1 call to strict::unimport |
| 811 | push @{"${class}::ISA"}, "DBD::_::$type" # spent 38µs making 6 calls to UNIVERSAL::isa, avg 6µs/call | |||
| 812 | unless UNIVERSAL::isa($class, "DBD::_::$type"); | |||
| 813 | my $mem_class = "DBD::_mem::$type"; | |||
| 814 | push @{"${class}_mem::ISA"}, $mem_class # spent 22µs making 6 calls to UNIVERSAL::isa, avg 4µs/call | |||
| 815 | unless UNIVERSAL::isa("${class}_mem", $mem_class) | |||
| 816 | or $DBI::PurePerl; | |||
| 817 | } | |||
| 818 | } | |||
| 819 | ||||
| 820 | ||||
| 821 | sub _rebless { | |||
| 822 | my $dbh = shift; | |||
| 823 | my ($outer, $inner) = DBI::_handles($dbh); | |||
| 824 | my $class = shift(@_).'::db'; | |||
| 825 | bless $inner => $class; | |||
| 826 | bless $outer => $class; # outer last for return | |||
| 827 | } | |||
| 828 | ||||
| 829 | ||||
| 830 | sub _set_isa { | |||
| 831 | my ($classes, $topclass) = @_; | |||
| 832 | my $trace = DBI->trace_msg(" _set_isa([@$classes])\n"); | |||
| 833 | foreach my $suffix ('::db','::st') { | |||
| 834 | my $previous = $topclass || 'DBI'; # trees are rooted here | |||
| 835 | foreach my $class (@$classes) { | |||
| 836 | my $base_class = $previous.$suffix; | |||
| 837 | my $sub_class = $class.$suffix; | |||
| 838 | my $sub_class_isa = "${sub_class}::ISA"; | |||
| 839 | 3 | 658µs | 219µs | no strict 'refs'; # spent 34µs making 1 call to strict::unimport |
| 840 | if (@$sub_class_isa) { | |||
| 841 | DBI->trace_msg(" $sub_class_isa skipped (already set to @$sub_class_isa)\n") | |||
| 842 | if $trace; | |||
| 843 | } | |||
| 844 | else { | |||
| 845 | @$sub_class_isa = ($base_class) unless @$sub_class_isa; | |||
| 846 | DBI->trace_msg(" $sub_class_isa = $base_class\n") | |||
| 847 | if $trace; | |||
| 848 | } | |||
| 849 | $previous = $class; | |||
| 850 | } | |||
| 851 | } | |||
| 852 | } | |||
| 853 | ||||
| 854 | ||||
| 855 | sub _rebless_dbtype_subclass { | |||
| 856 | my ($dbh, $rootclass, $DbTypeSubclass) = @_; | |||
| 857 | # determine the db type names for class hierarchy | |||
| 858 | my @hierarchy = DBI::_dbtype_names($dbh, $DbTypeSubclass); | |||
| 859 | # add the rootclass prefix to each ('DBI::' or 'MyDBI::' etc) | |||
| 860 | $_ = $rootclass.'::'.$_ foreach (@hierarchy); | |||
| 861 | # load the modules from the 'top down' | |||
| 862 | DBI::_load_class($_, 1) foreach (reverse @hierarchy); | |||
| 863 | # setup class hierarchy if needed, does both '::db' and '::st' | |||
| 864 | DBI::_set_isa(\@hierarchy, $rootclass); | |||
| 865 | # finally bless the handle into the subclass | |||
| 866 | DBI::_rebless($dbh, $hierarchy[0]); | |||
| 867 | } | |||
| 868 | ||||
| 869 | ||||
| 870 | sub _dbtype_names { # list dbtypes for hierarchy, ie Informix=>ADO=>ODBC | |||
| 871 | my ($dbh, $DbTypeSubclass) = @_; | |||
| 872 | ||||
| 873 | if ($DbTypeSubclass && $DbTypeSubclass ne '1' && ref $DbTypeSubclass ne 'CODE') { | |||
| 874 | # treat $DbTypeSubclass as a comma separated list of names | |||
| 875 | my @dbtypes = split /\s*,\s*/, $DbTypeSubclass; | |||
| 876 | $dbh->trace_msg(" DbTypeSubclass($DbTypeSubclass)=@dbtypes (explicit)\n"); | |||
| 877 | return @dbtypes; | |||
| 878 | } | |||
| 879 | ||||
| 880 | # XXX will call $dbh->get_info(17) (=SQL_DBMS_NAME) in future? | |||
| 881 | ||||
| 882 | my $driver = $dbh->{Driver}->{Name}; | |||
| 883 | if ( $driver eq 'Proxy' ) { | |||
| 884 | # XXX Looking into the internals of DBD::Proxy is questionable! | |||
| 885 | ($driver) = $dbh->{proxy_client}->{application} =~ /^DBI:(.+?):/i | |||
| 886 | or die "Can't determine driver name from proxy"; | |||
| 887 | } | |||
| 888 | ||||
| 889 | my @dbtypes = (ucfirst($driver)); | |||
| 890 | if ($driver eq 'ODBC' || $driver eq 'ADO') { | |||
| 891 | # XXX will move these out and make extensible later: | |||
| 892 | my $_dbtype_name_regexp = 'Oracle'; # eg 'Oracle|Foo|Bar' | |||
| 893 | my %_dbtype_name_map = ( | |||
| 894 | 'Microsoft SQL Server' => 'MSSQL', | |||
| 895 | 'SQL Server' => 'Sybase', | |||
| 896 | 'Adaptive Server Anywhere' => 'ASAny', | |||
| 897 | 'ADABAS D' => 'AdabasD', | |||
| 898 | ); | |||
| 899 | ||||
| 900 | my $name; | |||
| 901 | $name = $dbh->func(17, 'GetInfo') # SQL_DBMS_NAME | |||
| 902 | if $driver eq 'ODBC'; | |||
| 903 | $name = $dbh->{ado_conn}->Properties->Item('DBMS Name')->Value | |||
| 904 | if $driver eq 'ADO'; | |||
| 905 | die "Can't determine driver name! ($DBI::errstr)\n" | |||
| 906 | unless $name; | |||
| 907 | ||||
| 908 | my $dbtype; | |||
| 909 | if ($_dbtype_name_map{$name}) { | |||
| 910 | $dbtype = $_dbtype_name_map{$name}; | |||
| 911 | } | |||
| 912 | else { | |||
| 913 | if ($name =~ /($_dbtype_name_regexp)/) { | |||
| 914 | $dbtype = lc($1); | |||
| 915 | } | |||
| 916 | else { # generic mangling for other names: | |||
| 917 | $dbtype = lc($name); | |||
| 918 | } | |||
| 919 | $dbtype =~ s/\b(\w)/\U$1/g; | |||
| 920 | $dbtype =~ s/\W+/_/g; | |||
| 921 | } | |||
| 922 | # add ODBC 'behind' ADO | |||
| 923 | push @dbtypes, 'ODBC' if $driver eq 'ADO'; | |||
| 924 | # add discovered dbtype in front of ADO/ODBC | |||
| 925 | unshift @dbtypes, $dbtype; | |||
| 926 | } | |||
| 927 | @dbtypes = &$DbTypeSubclass($dbh, \@dbtypes) | |||
| 928 | if (ref $DbTypeSubclass eq 'CODE'); | |||
| 929 | $dbh->trace_msg(" DbTypeSubclass($DbTypeSubclass)=@dbtypes\n"); | |||
| 930 | return @dbtypes; | |||
| 931 | } | |||
| 932 | ||||
| 933 | sub _load_class { | |||
| 934 | my ($load_class, $missing_ok) = @_; | |||
| 935 | DBI->trace_msg(" _load_class($load_class, $missing_ok)\n", 2); | |||
| 936 | 3 | 567µs | 189µs | no strict 'refs'; # spent 18µs making 1 call to strict::unimport |
| 937 | return 1 if @{"$load_class\::ISA"}; # already loaded/exists | |||
| 938 | (my $module = $load_class) =~ s!::!/!g; | |||
| 939 | DBI->trace_msg(" _load_class require $module\n", 2); | |||
| 940 | eval { require "$module.pm"; }; | |||
| 941 | return 1 unless $@; | |||
| 942 | return 0 if $missing_ok && $@ =~ /^Can't locate \Q$module.pm\E/; | |||
| 943 | die $@; | |||
| 944 | } | |||
| 945 | ||||
| 946 | ||||
| 947 | sub init_rootclass { # deprecated | |||
| 948 | return 1; | |||
| 949 | } | |||
| 950 | ||||
| 951 | ||||
| 952 | 1 | 1µs | 1µs | *internal = \&DBD::Switch::dr::driver; |
| 953 | ||||
| 954 | ||||
| 955 | sub available_drivers { | |||
| 956 | my($quiet) = @_; | |||
| 957 | my(@drivers, $d, $f); | |||
| 958 | local(*DBI::DIR, $@); | |||
| 959 | my(%seen_dir, %seen_dbd); | |||
| 960 | my $haveFileSpec = eval { require File::Spec }; | |||
| 961 | foreach $d (@INC){ | |||
| 962 | chomp($d); # Perl 5 beta 3 bug in #!./perl -Ilib from Test::Harness | |||
| 963 | my $dbd_dir = | |||
| 964 | ($haveFileSpec ? File::Spec->catdir($d, 'DBD') : "$d/DBD"); | |||
| 965 | next unless -d $dbd_dir; | |||
| 966 | next if $seen_dir{$d}; | |||
| 967 | $seen_dir{$d} = 1; | |||
| 968 | # XXX we have a problem here with case insensitive file systems | |||
| 969 | # XXX since we can't tell what case must be used when loading. | |||
| 970 | opendir(DBI::DIR, $dbd_dir) || Carp::carp "opendir $dbd_dir: $!\n"; | |||
| 971 | foreach $f (readdir(DBI::DIR)){ | |||
| 972 | next unless $f =~ s/\.pm$//; | |||
| 973 | next if $f eq 'NullP'; | |||
| 974 | if ($seen_dbd{$f}){ | |||
| 975 | Carp::carp "DBD::$f in $d is hidden by DBD::$f in $seen_dbd{$f}\n" | |||
| 976 | unless $quiet; | |||
| 977 | } else { | |||
| 978 | push(@drivers, $f); | |||
| 979 | } | |||
| 980 | $seen_dbd{$f} = $d; | |||
| 981 | } | |||
| 982 | closedir(DBI::DIR); | |||
| 983 | } | |||
| 984 | ||||
| 985 | # "return sort @drivers" will not DWIM in scalar context. | |||
| 986 | return wantarray ? sort @drivers : @drivers; | |||
| 987 | } | |||
| 988 | ||||
| 989 | sub installed_versions { | |||
| 990 | my ($class, $quiet) = @_; | |||
| 991 | my %error; | |||
| 992 | my %version = ( DBI => $DBI::VERSION ); | |||
| 993 | $version{"DBI::PurePerl"} = $DBI::PurePerl::VERSION | |||
| 994 | if $DBI::PurePerl; | |||
| 995 | for my $driver ($class->available_drivers($quiet)) { | |||
| 996 | next if $DBI::PurePerl && grep { -d "$_/auto/DBD/$driver" } @INC; | |||
| 997 | my $drh = eval { | |||
| 998 | local $SIG{__WARN__} = sub {}; | |||
| 999 | $class->install_driver($driver); | |||
| 1000 | }; | |||
| 1001 | ($error{"DBD::$driver"}=$@),next if $@; | |||
| 1002 | 3 | 2.24ms | 747µs | no strict 'refs'; # spent 17µs making 1 call to strict::unimport |
| 1003 | my $vers = ${"DBD::$driver" . '::VERSION'}; | |||
| 1004 | $version{"DBD::$driver"} = $vers || '?'; | |||
| 1005 | } | |||
| 1006 | if (wantarray) { | |||
| 1007 | return map { m/^DBD::(\w+)/ ? ($1) : () } sort keys %version; | |||
| 1008 | } | |||
| 1009 | if (!defined wantarray) { # void context | |||
| 1010 | require Config; # add more detail | |||
| 1011 | $version{OS} = "$^O\t($Config::Config{osvers})"; | |||
| 1012 | $version{Perl} = "$]\t($Config::Config{archname})"; | |||
| 1013 | $version{$_} = (($error{$_} =~ s/ \(\@INC.*//s),$error{$_}) | |||
| 1014 | for keys %error; | |||
| 1015 | printf " %-16s: %s\n",$_,$version{$_} | |||
| 1016 | for reverse sort keys %version; | |||
| 1017 | } | |||
| 1018 | return \%version; | |||
| 1019 | } | |||
| 1020 | ||||
| 1021 | ||||
| 1022 | sub data_sources { | |||
| 1023 | my ($class, $driver, @other) = @_; | |||
| 1024 | my $drh = $class->install_driver($driver); | |||
| 1025 | my @ds = $drh->data_sources(@other); | |||
| 1026 | return @ds; | |||
| 1027 | } | |||
| 1028 | ||||
| 1029 | ||||
| 1030 | sub neat_list { | |||
| 1031 | my ($listref, $maxlen, $sep) = @_; | |||
| 1032 | $maxlen = 0 unless defined $maxlen; # 0 == use internal default | |||
| 1033 | $sep = ", " unless defined $sep; | |||
| 1034 | join($sep, map { neat($_,$maxlen) } @$listref); | |||
| 1035 | } | |||
| 1036 | ||||
| 1037 | ||||
| 1038 | sub dump_results { # also aliased as a method in DBD::_::st | |||
| 1039 | my ($sth, $maxlen, $lsep, $fsep, $fh) = @_; | |||
| 1040 | return 0 unless $sth; | |||
| 1041 | $maxlen ||= 35; | |||
| 1042 | $lsep ||= "\n"; | |||
| 1043 | $fh ||= \*STDOUT; | |||
| 1044 | my $rows = 0; | |||
| 1045 | my $ref; | |||
| 1046 | while($ref = $sth->fetch) { | |||
| 1047 | print $fh $lsep if $rows++ and $lsep; | |||
| 1048 | my $str = neat_list($ref,$maxlen,$fsep); | |||
| 1049 | print $fh $str; # done on two lines to avoid 5.003 errors | |||
| 1050 | } | |||
| 1051 | print $fh "\n$rows rows".($DBI::err ? " ($DBI::err: $DBI::errstr)" : "")."\n"; | |||
| 1052 | $rows; | |||
| 1053 | } | |||
| 1054 | ||||
| 1055 | ||||
| 1056 | sub data_diff { | |||
| 1057 | my ($a, $b, $logical) = @_; | |||
| 1058 | ||||
| 1059 | my $diff = data_string_diff($a, $b); | |||
| 1060 | return "" if $logical and !$diff; | |||
| 1061 | ||||
| 1062 | my $a_desc = data_string_desc($a); | |||
| 1063 | my $b_desc = data_string_desc($b); | |||
| 1064 | return "" if !$diff and $a_desc eq $b_desc; | |||
| 1065 | ||||
| 1066 | $diff ||= "Strings contain the same sequence of characters" | |||
| 1067 | if length($a); | |||
| 1068 | $diff .= "\n" if $diff; | |||
| 1069 | return "a: $a_desc\nb: $b_desc\n$diff"; | |||
| 1070 | } | |||
| 1071 | ||||
| 1072 | ||||
| 1073 | sub data_string_diff { | |||
| 1074 | # Compares 'logical' characters, not bytes, so a latin1 string and an | |||
| 1075 | # an equivalent unicode string will compare as equal even though their | |||
| 1076 | # byte encodings are different. | |||
| 1077 | my ($a, $b) = @_; | |||
| 1078 | unless (defined $a and defined $b) { # one undef | |||
| 1079 | return "" | |||
| 1080 | if !defined $a and !defined $b; | |||
| 1081 | return "String a is undef, string b has ".length($b)." characters" | |||
| 1082 | if !defined $a; | |||
| 1083 | return "String b is undef, string a has ".length($a)." characters" | |||
| 1084 | if !defined $b; | |||
| 1085 | } | |||
| 1086 | ||||
| 1087 | require utf8; | |||
| 1088 | # hack to cater for perl 5.6 | |||
| 1089 | *utf8::is_utf8 = sub { (DBI::neat(shift)=~/^"/) } unless defined &utf8::is_utf8; | |||
| 1090 | ||||
| 1091 | my @a_chars = (utf8::is_utf8($a)) ? unpack("U*", $a) : unpack("C*", $a); | |||
| 1092 | my @b_chars = (utf8::is_utf8($b)) ? unpack("U*", $b) : unpack("C*", $b); | |||
| 1093 | my $i = 0; | |||
| 1094 | while (@a_chars && @b_chars) { | |||
| 1095 | ++$i, shift(@a_chars), shift(@b_chars), next | |||
| 1096 | if $a_chars[0] == $b_chars[0];# compare ordinal values | |||
| 1097 | my @desc = map { | |||
| 1098 | $_ > 255 ? # if wide character... | |||
| 1099 | sprintf("\\x{%04X}", $_) : # \x{...} | |||
| 1100 | chr($_) =~ /[[:cntrl:]]/ ? # else if control character ... | |||
| 1101 | sprintf("\\x%02X", $_) : # \x.. | |||
| 1102 | chr($_) # else as themselves | |||
| 1103 | } ($a_chars[0], $b_chars[0]); | |||
| 1104 | # highlight probable double-encoding? | |||
| 1105 | foreach my $c ( @desc ) { | |||
| 1106 | next unless $c =~ m/\\x\{08(..)}/; | |||
| 1107 | $c .= "='" .chr(hex($1)) ."'" | |||
| 1108 | } | |||
| 1109 | return sprintf "Strings differ at index $i: a[$i]=$desc[0], b[$i]=$desc[1]"; | |||
| 1110 | } | |||
| 1111 | return "String a truncated after $i characters" if @b_chars; | |||
| 1112 | return "String b truncated after $i characters" if @a_chars; | |||
| 1113 | return ""; | |||
| 1114 | } | |||
| 1115 | ||||
| 1116 | ||||
| 1117 | sub data_string_desc { # describe a data string | |||
| 1118 | my ($a) = @_; | |||
| 1119 | require bytes; | |||
| 1120 | require utf8; | |||
| 1121 | ||||
| 1122 | # hacks to cater for perl 5.6 | |||
| 1123 | *utf8::is_utf8 = sub { (DBI::neat(shift)=~/^"/) } unless defined &utf8::is_utf8; | |||
| 1124 | *utf8::valid = sub { 1 } unless defined &utf8::valid; | |||
| 1125 | ||||
| 1126 | # Give sufficient info to help diagnose at least these kinds of situations: | |||
| 1127 | # - valid UTF8 byte sequence but UTF8 flag not set | |||
| 1128 | # (might be ascii so also need to check for hibit to make it worthwhile) | |||
| 1129 | # - UTF8 flag set but invalid UTF8 byte sequence | |||
| 1130 | # could do better here, but this'll do for now | |||
| 1131 | my $utf8 = sprintf "UTF8 %s%s", | |||
| 1132 | utf8::is_utf8($a) ? "on" : "off", | |||
| 1133 | utf8::valid($a||'') ? "" : " but INVALID encoding"; | |||
| 1134 | return "$utf8, undef" unless defined $a; | |||
| 1135 | my $is_ascii = $a =~ m/^[\000-\177]*$/; | |||
| 1136 | return sprintf "%s, %s, %d characters %d bytes", | |||
| 1137 | $utf8, $is_ascii ? "ASCII" : "non-ASCII", | |||
| 1138 | length($a), bytes::length($a); | |||
| 1139 | } | |||
| 1140 | ||||
| 1141 | ||||
| 1142 | sub connect_test_perf { | |||
| 1143 | my($class, $dsn,$dbuser,$dbpass, $attr) = @_; | |||
| 1144 | Carp::croak("connect_test_perf needs hash ref as fourth arg") unless ref $attr; | |||
| 1145 | # these are non standard attributes just for this special method | |||
| 1146 | my $loops ||= $attr->{dbi_loops} || 5; | |||
| 1147 | my $par ||= $attr->{dbi_par} || 1; # parallelism | |||
| 1148 | my $verb ||= $attr->{dbi_verb} || 1; | |||
| 1149 | my $meth ||= $attr->{dbi_meth} || 'connect'; | |||
| 1150 | print "$dsn: testing $loops sets of $par connections:\n"; | |||
| 1151 | require "FileHandle.pm"; # don't let toke.c create empty FileHandle package | |||
| 1152 | local $| = 1; | |||
| 1153 | my $drh = $class->install_driver($dsn) or Carp::croak("Can't install $dsn driver\n"); | |||
| 1154 | # test the connection and warm up caches etc | |||
| 1155 | $drh->connect($dsn,$dbuser,$dbpass) or Carp::croak("connect failed: $DBI::errstr"); | |||
| 1156 | my $t1 = dbi_time(); | |||
| 1157 | my $loop; | |||
| 1158 | for $loop (1..$loops) { | |||
| 1159 | my @cons; | |||
| 1160 | print "Connecting... " if $verb; | |||
| 1161 | for (1..$par) { | |||
| 1162 | print "$_ "; | |||
| 1163 | push @cons, ($drh->connect($dsn,$dbuser,$dbpass) | |||
| 1164 | or Carp::croak("connect failed: $DBI::errstr\n")); | |||
| 1165 | } | |||
| 1166 | print "\nDisconnecting...\n" if $verb; | |||
| 1167 | for (@cons) { | |||
| 1168 | $_->disconnect or warn "disconnect failed: $DBI::errstr" | |||
| 1169 | } | |||
| 1170 | } | |||
| 1171 | my $t2 = dbi_time(); | |||
| 1172 | my $td = $t2 - $t1; | |||
| 1173 | printf "$meth %d and disconnect them, %d times: %.4fs / %d = %.4fs\n", | |||
| 1174 | $par, $loops, $td, $loops*$par, $td/($loops*$par); | |||
| 1175 | return $td; | |||
| 1176 | } | |||
| 1177 | ||||
| 1178 | ||||
| 1179 | # Help people doing DBI->errstr, might even document it one day | |||
| 1180 | # XXX probably best moved to cheaper XS code if this gets documented | |||
| 1181 | sub err { $DBI::err } | |||
| 1182 | sub errstr { $DBI::errstr } | |||
| 1183 | ||||
| 1184 | ||||
| 1185 | # --- Private Internal Function for Creating New DBI Handles | |||
| 1186 | ||||
| 1187 | # XXX move to PurePerl? | |||
| 1188 | 1 | 1µs | 1µs | *DBI::dr::TIEHASH = \&DBI::st::TIEHASH; |
| 1189 | 1 | 900ns | 900ns | *DBI::db::TIEHASH = \&DBI::st::TIEHASH; |
| 1190 | ||||
| 1191 | ||||
| 1192 | # These three special constructors are called by the drivers | |||
| 1193 | # The way they are called is likely to change. | |||
| 1194 | ||||
| 1195 | 1 | 200ns | 200ns | our $shared_profile; |
| 1196 | ||||
| 1197 | # spent 88µs (23+64) within DBI::_new_drh which was called
# once (23µs+64µs) by DBD::mysql::driver at line 28 of /usr/lib/perl5/DBD/mysql.pm | |||
| 1198 | 6 | 82µs | 14µs | my ($class, $initial_attr, $imp_data) = @_; |
| 1199 | # Provide default storage for State,Err and Errstr. | |||
| 1200 | # Note that these are shared by all child handles by default! XXX | |||
| 1201 | # State must be undef to get automatic faking in DBI::var::FETCH | |||
| 1202 | my ($h_state_store, $h_err_store, $h_errstr_store) = (undef, 0, ''); | |||
| 1203 | my $attr = { | |||
| 1204 | # these attributes get copied down to child handles by default | |||
| 1205 | 'State' => \$h_state_store, # Holder for DBI::state | |||
| 1206 | 'Err' => \$h_err_store, # Holder for DBI::err | |||
| 1207 | 'Errstr' => \$h_errstr_store, # Holder for DBI::errstr | |||
| 1208 | 'TraceLevel' => 0, | |||
| 1209 | FetchHashKeyName=> 'NAME', | |||
| 1210 | %$initial_attr, | |||
| 1211 | }; | |||
| 1212 | my ($h, $i) = _new_handle('DBI::dr', '', $attr, $imp_data, $class); # spent 64µs making 1 call to DBI::_new_handle | |||
| 1213 | ||||
| 1214 | # XXX DBI_PROFILE unless DBI::PurePerl because for some reason | |||
| 1215 | # it kills the t/zz_*_pp.t tests (they silently exit early) | |||
| 1216 | if ($ENV{DBI_PROFILE} && !$DBI::PurePerl) { | |||
| 1217 | # The profile object created here when the first driver is loaded | |||
| 1218 | # is shared by all drivers so we end up with just one set of profile | |||
| 1219 | # data and thus the 'total time in DBI' is really the true total. | |||
| 1220 | if (!$shared_profile) { # first time | |||
| 1221 | $h->{Profile} = $ENV{DBI_PROFILE}; | |||
| 1222 | $shared_profile = $h->{Profile}; | |||
| 1223 | } | |||
| 1224 | else { | |||
| 1225 | $h->{Profile} = $shared_profile; | |||
| 1226 | } | |||
| 1227 | } | |||
| 1228 | return $h unless wantarray; | |||
| 1229 | ($h, $i); | |||
| 1230 | } | |||
| 1231 | ||||
| 1232 | # spent 61µs (23+37) within DBI::_new_dbh which was called
# once (23µs+37µs) by DBD::mysql::dr::connect at line 133 of /usr/lib/perl5/DBD/mysql.pm | |||
| 1233 | 9 | 54µs | 6µs | my ($drh, $attr, $imp_data) = @_; |
| 1234 | my $imp_class = $drh->{ImplementorClass} | |||
| 1235 | or Carp::croak("DBI _new_dbh: $drh has no ImplementorClass"); | |||
| 1236 | substr($imp_class,-4,4) = '::db'; | |||
| 1237 | my $app_class = ref $drh; | |||
| 1238 | substr($app_class,-4,4) = '::db'; | |||
| 1239 | $attr->{Err} ||= \my $err; | |||
| 1240 | $attr->{Errstr} ||= \my $errstr; | |||
| 1241 | $attr->{State} ||= \my $state; | |||
| 1242 | _new_handle($app_class, $drh, $attr, $imp_data, $imp_class); # spent 37µs making 1 call to DBI::_new_handle | |||
| 1243 | } | |||
| 1244 | ||||
| 1245 | # spent 14.5ms (5.52+8.97) within DBI::_new_sth which was called 507 times, avg 29µs/call:
# 507 times (5.52ms+8.97ms) by DBD::mysql::db::prepare at line 221 of /usr/lib/perl5/DBD/mysql.pm, avg 29µs/call | |||
| 1246 | 3042 | 13.1ms | 4µs | my ($dbh, $attr, $imp_data) = @_; |
| 1247 | my $imp_class = $dbh->{ImplementorClass} | |||
| 1248 | or Carp::croak("DBI _new_sth: $dbh has no ImplementorClass"); | |||
| 1249 | substr($imp_class,-4,4) = '::st'; | |||
| 1250 | my $app_class = ref $dbh; | |||
| 1251 | substr($app_class,-4,4) = '::st'; | |||
| 1252 | _new_handle($app_class, $dbh, $attr, $imp_data, $imp_class); # spent 8.97ms making 507 calls to DBI::_new_handle, avg 18µs/call | |||
| 1253 | } | |||
| 1254 | ||||
| 1255 | ||||
| 1256 | # end of DBI package | |||
| 1257 | ||||
| 1258 | ||||
| 1259 | ||||
| 1260 | # -------------------------------------------------------------------- | |||
| 1261 | # === The internal DBI Switch pseudo 'driver' class === | |||
| 1262 | ||||
| 1263 | 1 | 600ns | 600ns | { package # hide from PAUSE |
| 1264 | DBD::Switch::dr; | |||
| 1265 | 1 | 8µs | 8µs | DBI->setup_driver('DBD::Switch'); # sets up @ISA # spent 119µs making 1 call to DBI::setup_driver |
| 1266 | ||||
| 1267 | 1 | 300ns | 300ns | $DBD::Switch::dr::imp_data_size = 0; |
| 1268 | 1 | 200ns | 200ns | $DBD::Switch::dr::imp_data_size = 0; # avoid typo warning |
| 1269 | 1 | 400ns | 400ns | my $drh; |
| 1270 | ||||
| 1271 | sub driver { | |||
| 1272 | return $drh if $drh; # a package global | |||
| 1273 | ||||
| 1274 | my $inner; | |||
| 1275 | ($drh, $inner) = DBI::_new_drh('DBD::Switch::dr', { | |||
| 1276 | 'Name' => 'Switch', | |||
| 1277 | 'Version' => $DBI::VERSION, | |||
| 1278 | 'Attribution' => "DBI $DBI::VERSION by Tim Bunce", | |||
| 1279 | }); | |||
| 1280 | Carp::croak("DBD::Switch init failed!") unless ($drh && $inner); | |||
| 1281 | return $drh; | |||
| 1282 | } | |||
| 1283 | sub CLONE { | |||
| 1284 | undef $drh; | |||
| 1285 | } | |||
| 1286 | ||||
| 1287 | sub FETCH { | |||
| 1288 | my($drh, $key) = @_; | |||
| 1289 | return DBI->trace if $key eq 'DebugDispatch'; | |||
| 1290 | return undef if $key eq 'DebugLog'; # not worth fetching, sorry | |||
| 1291 | return $drh->DBD::_::dr::FETCH($key); | |||
| 1292 | undef; | |||
| 1293 | } | |||
| 1294 | sub STORE { | |||
| 1295 | my($drh, $key, $value) = @_; | |||
| 1296 | if ($key eq 'DebugDispatch') { | |||
| 1297 | DBI->trace($value); | |||
| 1298 | } elsif ($key eq 'DebugLog') { | |||
| 1299 | DBI->trace(-1, $value); | |||
| 1300 | } else { | |||
| 1301 | $drh->DBD::_::dr::STORE($key, $value); | |||
| 1302 | } | |||
| 1303 | } | |||
| 1304 | } | |||
| 1305 | ||||
| 1306 | ||||
| 1307 | # -------------------------------------------------------------------- | |||
| 1308 | # === OPTIONAL MINIMAL BASE CLASSES FOR DBI SUBCLASSES === | |||
| 1309 | ||||
| 1310 | # We only define default methods for harmless functions. | |||
| 1311 | # We don't, for example, define a DBD::_::st::prepare() | |||
| 1312 | ||||
| 1313 | 1 | 800ns | 800ns | { package # hide from PAUSE |
| 1314 | DBD::_::common; # ====== Common base class methods ====== | |||
| 1315 | 3 | 748µs | 249µs | use strict; # spent 11µs making 1 call to strict::import |
| 1316 | ||||
| 1317 | # methods common to all handle types: | |||
| 1318 | ||||
| 1319 | sub _not_impl { | |||
| 1320 | my ($h, $method) = @_; | |||
| 1321 | $h->trace_msg("Driver does not implement the $method method.\n"); | |||
| 1322 | return; # empty list / undef | |||
| 1323 | } | |||
| 1324 | ||||
| 1325 | # generic TIEHASH default methods: | |||
| 1326 | sub FIRSTKEY { } | |||
| 1327 | sub NEXTKEY { } | |||
| 1328 | sub EXISTS { defined($_[0]->FETCH($_[1])) } # XXX undef? | |||
| 1329 | sub CLEAR { Carp::carp "Can't CLEAR $_[0] (DBI)" } | |||
| 1330 | ||||
| 1331 | sub FETCH_many { # XXX should move to C one day | |||
| 1332 | my $h = shift; | |||
| 1333 | return map { $h->FETCH($_) } @_; | |||
| 1334 | } | |||
| 1335 | ||||
| 1336 | 1 | 2µs | 2µs | *dump_handle = \&DBI::dump_handle; |
| 1337 | ||||
| 1338 | sub install_method { | |||
| 1339 | # special class method called directly by apps and/or drivers | |||
| 1340 | # to install new methods into the DBI dispatcher | |||
| 1341 | # DBD::Foo::db->install_method("foo_mumble", { usage => [...], options => '...' }); | |||
| 1342 | my ($class, $method, $attr) = @_; | |||
| 1343 | Carp::croak("Class '$class' must begin with DBD:: and end with ::db or ::st") | |||
| 1344 | unless $class =~ /^DBD::(\w+)::(dr|db|st)$/; | |||
| 1345 | my ($driver, $subtype) = ($1, $2); | |||
| 1346 | Carp::croak("invalid method name '$method'") | |||
| 1347 | unless $method =~ m/^([a-z]+_)\w+$/; | |||
| 1348 | my $prefix = $1; | |||
| 1349 | my $reg_info = $dbd_prefix_registry->{$prefix}; | |||
| 1350 | Carp::carp("method name prefix '$prefix' is not associated with a registered driver") unless $reg_info; | |||
| 1351 | ||||
| 1352 | my $full_method = "DBI::${subtype}::$method"; | |||
| 1353 | $DBI::installed_methods{$full_method} = $attr; | |||
| 1354 | ||||
| 1355 | my (undef, $filename, $line) = caller; | |||
| 1356 | # XXX reformat $attr as needed for _install_method | |||
| 1357 | my %attr = %{$attr||{}}; # copy so we can edit | |||
| 1358 | DBI->_install_method("DBI::${subtype}::$method", "$filename at line $line", \%attr); | |||
| 1359 | } | |||
| 1360 | ||||
| 1361 | sub parse_trace_flags { | |||
| 1362 | my ($h, $spec) = @_; | |||
| 1363 | my $level = 0; | |||
| 1364 | my $flags = 0; | |||
| 1365 | my @unknown; | |||
| 1366 | for my $word (split /\s*[|&,]\s*/, $spec) { | |||
| 1367 | if (DBI::looks_like_number($word) && $word <= 0xF && $word >= 0) { | |||
| 1368 | $level = $word; | |||
| 1369 | } elsif ($word eq 'ALL') { | |||
| 1370 | $flags = 0x7FFFFFFF; # XXX last bit causes negative headaches | |||
| 1371 | last; | |||
| 1372 | } elsif (my $flag = $h->parse_trace_flag($word)) { | |||
| 1373 | $flags |= $flag; | |||
| 1374 | } | |||
| 1375 | else { | |||
| 1376 | push @unknown, $word; | |||
| 1377 | } | |||
| 1378 | } | |||
| 1379 | if (@unknown && (ref $h ? $h->FETCH('Warn') : 1)) { | |||
| 1380 | Carp::carp("$h->parse_trace_flags($spec) ignored unknown trace flags: ". | |||
| 1381 | join(" ", map { DBI::neat($_) } @unknown)); | |||
| 1382 | } | |||
| 1383 | $flags |= $level; | |||
| 1384 | return $flags; | |||
| 1385 | } | |||
| 1386 | ||||
| 1387 | sub parse_trace_flag { | |||
| 1388 | my ($h, $name) = @_; | |||
| 1389 | # 0xddDDDDrL (driver, DBI, reserved, Level) | |||
| 1390 | return 0x00000100 if $name eq 'SQL'; | |||
| 1391 | return; | |||
| 1392 | } | |||
| 1393 | ||||
| 1394 | sub private_attribute_info { | |||
| 1395 | return undef; | |||
| 1396 | } | |||
| 1397 | ||||
| 1398 | } | |||
| 1399 | ||||
| 1400 | ||||
| 1401 | 1 | 1µs | 1µs | { package # hide from PAUSE |
| 1402 | DBD::_::dr; # ====== DRIVER ====== | |||
| 1403 | 1 | 8µs | 8µs | @DBD::_::dr::ISA = qw(DBD::_::common); |
| 1404 | 3 | 403µs | 134µs | use strict; # spent 10µs making 1 call to strict::import |
| 1405 | ||||
| 1406 | sub default_user { | |||
| 1407 | my ($drh, $user, $pass, $attr) = @_; | |||
| 1408 | $user = $ENV{DBI_USER} unless defined $user; | |||
| 1409 | $pass = $ENV{DBI_PASS} unless defined $pass; | |||
| 1410 | return ($user, $pass); | |||
| 1411 | } | |||
| 1412 | ||||
| 1413 | sub connect { # normally overridden, but a handy default | |||
| 1414 | my ($drh, $dsn, $user, $auth) = @_; | |||
| 1415 | my ($this) = DBI::_new_dbh($drh, { | |||
| 1416 | 'Name' => $dsn, | |||
| 1417 | }); | |||
| 1418 | # XXX debatable as there's no "server side" here | |||
| 1419 | # (and now many uses would trigger warnings on DESTROY) | |||
| 1420 | # $this->STORE(Active => 1); | |||
| 1421 | # so drivers should set it in their own connect | |||
| 1422 | $this; | |||
| 1423 | } | |||
| 1424 | ||||
| 1425 | ||||
| 1426 | sub connect_cached { | |||
| 1427 | my $drh = shift; | |||
| 1428 | my ($dsn, $user, $auth, $attr) = @_; | |||
| 1429 | ||||
| 1430 | my $cache = $drh->{CachedKids} ||= {}; | |||
| 1431 | my $key = do { local $^W; | |||
| 1432 | join "!\001", $dsn, $user, $auth, DBI::_concat_hash_sorted($attr, "=\001", ",\001", 0, 0) | |||
| 1433 | }; | |||
| 1434 | my $dbh = $cache->{$key}; | |||
| 1435 | $drh->trace_msg(sprintf(" connect_cached: key '$key', cached dbh $dbh\n", DBI::neat($key), DBI::neat($dbh))) | |||
| 1436 | if $DBI::dbi_debug >= 4; | |||
| 1437 | ||||
| 1438 | my $cb = $attr->{Callbacks}; # take care not to autovivify | |||
| 1439 | if ($dbh && $dbh->FETCH('Active') && eval { $dbh->ping }) { | |||
| 1440 | # If the caller has provided a callback then call it | |||
| 1441 | if ($cb and $cb = $cb->{"connect_cached.reused"}) { | |||
| 1442 | local $_ = "connect_cached.reused"; | |||
| 1443 | $cb->($dbh, $dsn, $user, $auth, $attr); | |||
| 1444 | } | |||
| 1445 | return $dbh; | |||
| 1446 | } | |||
| 1447 | ||||
| 1448 | # If the caller has provided a callback then call it | |||
| 1449 | if ($cb and $cb = $cb->{"connect_cached.new"}) { | |||
| 1450 | local $_ = "connect_cached.new"; | |||
| 1451 | $cb->($dbh, $dsn, $user, $auth, $attr); | |||
| 1452 | } | |||
| 1453 | ||||
| 1454 | $dbh = $drh->connect(@_); | |||
| 1455 | $cache->{$key} = $dbh; # replace prev entry, even if connect failed | |||
| 1456 | return $dbh; | |||
| 1457 | } | |||
| 1458 | ||||
| 1459 | } | |||
| 1460 | ||||
| 1461 | ||||
| 1462 | 1 | 700ns | 700ns | { package # hide from PAUSE |
| 1463 | DBD::_::db; # ====== DATABASE ====== | |||
| 1464 | 1 | 5µs | 5µs | @DBD::_::db::ISA = qw(DBD::_::common); |
| 1465 | 3 | 2.07ms | 690µs | use strict; # spent 12µs making 1 call to strict::import |
| 1466 | ||||
| 1467 | sub clone { | |||
| 1468 | my ($old_dbh, $attr) = @_; | |||
| 1469 | my $closure = $old_dbh->{dbi_connect_closure} or return; | |||
| 1470 | unless ($attr) { | |||
| 1471 | # copy attributes visible in the attribute cache | |||
| 1472 | keys %$old_dbh; # reset iterator | |||
| 1473 | while ( my ($k, $v) = each %$old_dbh ) { | |||
| 1474 | # ignore non-code refs, i.e., caches, handles, Err etc | |||
| 1475 | next if ref $v && ref $v ne 'CODE'; # HandleError etc | |||
| 1476 | $attr->{$k} = $v; | |||
| 1477 | } | |||
| 1478 | # explicitly set attributes which are unlikely to be in the | |||
| 1479 | # attribute cache, i.e., boolean's and some others | |||
| 1480 | $attr->{$_} = $old_dbh->FETCH($_) for (qw( | |||
| 1481 | AutoCommit ChopBlanks InactiveDestroy | |||
| 1482 | LongTruncOk PrintError PrintWarn Profile RaiseError | |||
| 1483 | ShowErrorStatement TaintIn TaintOut | |||
| 1484 | )); | |||
| 1485 | } | |||
| 1486 | # use Data::Dumper; warn Dumper([$old_dbh, $attr]); | |||
| 1487 | my $new_dbh = &$closure($old_dbh, $attr); | |||
| 1488 | unless ($new_dbh) { | |||
| 1489 | # need to copy err/errstr from driver back into $old_dbh | |||
| 1490 | my $drh = $old_dbh->{Driver}; | |||
| 1491 | return $old_dbh->set_err($drh->err, $drh->errstr, $drh->state); | |||
| 1492 | } | |||
| 1493 | return $new_dbh; | |||
| 1494 | } | |||
| 1495 | ||||
| 1496 | sub quote_identifier { | |||
| 1497 | my ($dbh, @id) = @_; | |||
| 1498 | my $attr = (@id > 3 && ref($id[-1])) ? pop @id : undef; | |||
| 1499 | ||||
| 1500 | my $info = $dbh->{dbi_quote_identifier_cache} ||= [ | |||
| 1501 | $dbh->get_info(29) || '"', # SQL_IDENTIFIER_QUOTE_CHAR | |||
| 1502 | $dbh->get_info(41) || '.', # SQL_CATALOG_NAME_SEPARATOR | |||
| 1503 | $dbh->get_info(114) || 1, # SQL_CATALOG_LOCATION | |||
| 1504 | ]; | |||
| 1505 | ||||
| 1506 | my $quote = $info->[0]; | |||
| 1507 | foreach (@id) { # quote the elements | |||
| 1508 | next unless defined; | |||
| 1509 | s/$quote/$quote$quote/g; # escape embedded quotes | |||
| 1510 | $_ = qq{$quote$_$quote}; | |||
| 1511 | } | |||
| 1512 | ||||
| 1513 | # strip out catalog if present for special handling | |||
| 1514 | my $catalog = (@id >= 3) ? shift @id : undef; | |||
| 1515 | ||||
| 1516 | # join the dots, ignoring any null/undef elements (ie schema) | |||
| 1517 | my $quoted_id = join '.', grep { defined } @id; | |||
| 1518 | ||||
| 1519 | if ($catalog) { # add catalog correctly | |||
| 1520 | $quoted_id = ($info->[2] == 2) # SQL_CL_END | |||
| 1521 | ? $quoted_id . $info->[1] . $catalog | |||
| 1522 | : $catalog . $info->[1] . $quoted_id; | |||
| 1523 | } | |||
| 1524 | return $quoted_id; | |||
| 1525 | } | |||
| 1526 | ||||
| 1527 | sub quote { | |||
| 1528 | my ($dbh, $str, $data_type) = @_; | |||
| 1529 | ||||
| 1530 | return "NULL" unless defined $str; | |||
| 1531 | unless ($data_type) { | |||
| 1532 | $str =~ s/'/''/g; # ISO SQL2 | |||
| 1533 | return "'$str'"; | |||
| 1534 | } | |||
| 1535 | ||||
| 1536 | my $dbi_literal_quote_cache = $dbh->{'dbi_literal_quote_cache'} ||= [ {} , {} ]; | |||
| 1537 | my ($prefixes, $suffixes) = @$dbi_literal_quote_cache; | |||
| 1538 | ||||
| 1539 | my $lp = $prefixes->{$data_type}; | |||
| 1540 | my $ls = $suffixes->{$data_type}; | |||
| 1541 | ||||
| 1542 | if ( ! defined $lp || ! defined $ls ) { | |||
| 1543 | my $ti = $dbh->type_info($data_type); | |||
| 1544 | $lp = $prefixes->{$data_type} = $ti ? $ti->{LITERAL_PREFIX} || "" : "'"; | |||
| 1545 | $ls = $suffixes->{$data_type} = $ti ? $ti->{LITERAL_SUFFIX} || "" : "'"; | |||
| 1546 | } | |||
| 1547 | return $str unless $lp || $ls; # no quoting required | |||
| 1548 | ||||
| 1549 | # XXX don't know what the standard says about escaping | |||
| 1550 | # in the 'general case' (where $lp != "'"). | |||
| 1551 | # So we just do this and hope: | |||
| 1552 | $str =~ s/$lp/$lp$lp/g | |||
| 1553 | if $lp && $lp eq $ls && ($lp eq "'" || $lp eq '"'); | |||
| 1554 | return "$lp$str$ls"; | |||
| 1555 | } | |||
| 1556 | ||||
| 1557 | sub rows { -1 } # here so $DBI::rows 'works' after using $dbh | |||
| 1558 | ||||
| 1559 | sub do { | |||
| 1560 | my($dbh, $statement, $attr, @params) = @_; | |||
| 1561 | my $sth = $dbh->prepare($statement, $attr) or return undef; | |||
| 1562 | $sth->execute(@params) or return undef; | |||
| 1563 | my $rows = $sth->rows; | |||
| 1564 | ($rows == 0) ? "0E0" : $rows; | |||
| 1565 | } | |||
| 1566 | ||||
| 1567 | sub _do_selectrow { | |||
| 1568 | my ($method, $dbh, $stmt, $attr, @bind) = @_; | |||
| 1569 | my $sth = ((ref $stmt) ? $stmt : $dbh->prepare($stmt, $attr)) | |||
| 1570 | or return; | |||
| 1571 | $sth->execute(@bind) | |||
| 1572 | or return; | |||
| 1573 | my $row = $sth->$method() | |||
| 1574 | and $sth->finish; | |||
| 1575 | return $row; | |||
| 1576 | } | |||
| 1577 | ||||
| 1578 | sub selectrow_hashref { return _do_selectrow('fetchrow_hashref', @_); } | |||
| 1579 | ||||
| 1580 | # XXX selectrow_array/ref also have C implementations in Driver.xst | |||
| 1581 | sub selectrow_arrayref { return _do_selectrow('fetchrow_arrayref', @_); } | |||
| 1582 | sub selectrow_array { | |||
| 1583 | my $row = _do_selectrow('fetchrow_arrayref', @_) or return; | |||
| 1584 | return $row->[0] unless wantarray; | |||
| 1585 | return @$row; | |||
| 1586 | } | |||
| 1587 | ||||
| 1588 | # XXX selectall_arrayref also has C implementation in Driver.xst | |||
| 1589 | # which fallsback to this if a slice is given | |||
| 1590 | sub selectall_arrayref { | |||
| 1591 | my ($dbh, $stmt, $attr, @bind) = @_; | |||
| 1592 | my $sth = (ref $stmt) ? $stmt : $dbh->prepare($stmt, $attr) | |||
| 1593 | or return; | |||
| 1594 | $sth->execute(@bind) || return; | |||
| 1595 | my $slice = $attr->{Slice}; # typically undef, else hash or array ref | |||
| 1596 | if (!$slice and $slice=$attr->{Columns}) { | |||
| 1597 | if (ref $slice eq 'ARRAY') { # map col idx to perl array idx | |||
| 1598 | $slice = [ @{$attr->{Columns}} ]; # take a copy | |||
| 1599 | for (@$slice) { $_-- } | |||
| 1600 | } | |||
| 1601 | } | |||
| 1602 | my $rows = $sth->fetchall_arrayref($slice, my $MaxRows = $attr->{MaxRows}); | |||
| 1603 | $sth->finish if defined $MaxRows; | |||
| 1604 | return $rows; | |||
| 1605 | } | |||
| 1606 | ||||
| 1607 | sub selectall_hashref { | |||
| 1608 | my ($dbh, $stmt, $key_field, $attr, @bind) = @_; | |||
| 1609 | my $sth = (ref $stmt) ? $stmt : $dbh->prepare($stmt, $attr); | |||
| 1610 | return unless $sth; | |||
| 1611 | $sth->execute(@bind) || return; | |||
| 1612 | return $sth->fetchall_hashref($key_field); | |||
| 1613 | } | |||
| 1614 | ||||
| 1615 | sub selectcol_arrayref { | |||
| 1616 | my ($dbh, $stmt, $attr, @bind) = @_; | |||
| 1617 | my $sth = (ref $stmt) ? $stmt : $dbh->prepare($stmt, $attr); | |||
| 1618 | return unless $sth; | |||
| 1619 | $sth->execute(@bind) || return; | |||
| 1620 | my @columns = ($attr->{Columns}) ? @{$attr->{Columns}} : (1); | |||
| 1621 | my @values = (undef) x @columns; | |||
| 1622 | my $idx = 0; | |||
| 1623 | for (@columns) { | |||
| 1624 | $sth->bind_col($_, \$values[$idx++]) || return; | |||
| 1625 | } | |||
| 1626 | my @col; | |||
| 1627 | if (my $max = $attr->{MaxRows}) { | |||
| 1628 | push @col, @values while @col<$max && $sth->fetch; | |||
| 1629 | } | |||
| 1630 | else { | |||
| 1631 | push @col, @values while $sth->fetch; | |||
| 1632 | } | |||
| 1633 | return \@col; | |||
| 1634 | } | |||
| 1635 | ||||
| 1636 | sub prepare_cached { | |||
| 1637 | my ($dbh, $statement, $attr, $if_active) = @_; | |||
| 1638 | ||||
| 1639 | # Needs support at dbh level to clear cache before complaining about | |||
| 1640 | # active children. The XS template code does this. Drivers not using | |||
| 1641 | # the template must handle clearing the cache themselves. | |||
| 1642 | my $cache = $dbh->{CachedKids} ||= {}; | |||
| 1643 | my $key = do { local $^W; | |||
| 1644 | join "!\001", $statement, DBI::_concat_hash_sorted($attr, "=\001", ",\001", 0, 0) | |||
| 1645 | }; | |||
| 1646 | my $sth = $cache->{$key}; | |||
| 1647 | ||||
| 1648 | if ($sth) { | |||
| 1649 | return $sth unless $sth->FETCH('Active'); | |||
| 1650 | Carp::carp("prepare_cached($statement) statement handle $sth still Active") | |||
| 1651 | unless ($if_active ||= 0); | |||
| 1652 | $sth->finish if $if_active <= 1; | |||
| 1653 | return $sth if $if_active <= 2; | |||
| 1654 | } | |||
| 1655 | ||||
| 1656 | $sth = $dbh->prepare($statement, $attr); | |||
| 1657 | $cache->{$key} = $sth if $sth; | |||
| 1658 | ||||
| 1659 | return $sth; | |||
| 1660 | } | |||
| 1661 | ||||
| 1662 | sub ping { | |||
| 1663 | my $dbh = shift; | |||
| 1664 | $dbh->_not_impl('ping'); | |||
| 1665 | # "0 but true" is a special kind of true 0 that is used here so | |||
| 1666 | # applications can check if the ping was a real ping or not | |||
| 1667 | ($dbh->FETCH('Active')) ? "0 but true" : 0; | |||
| 1668 | } | |||
| 1669 | ||||
| 1670 | sub begin_work { | |||
| 1671 | my $dbh = shift; | |||
| 1672 | return $dbh->set_err($DBI::stderr, "Already in a transaction") | |||
| 1673 | unless $dbh->FETCH('AutoCommit'); | |||
| 1674 | $dbh->STORE('AutoCommit', 0); # will croak if driver doesn't support it | |||
| 1675 | $dbh->STORE('BegunWork', 1); # trigger post commit/rollback action | |||
| 1676 | return 1; | |||
| 1677 | } | |||
| 1678 | ||||
| 1679 | sub primary_key { | |||
| 1680 | my ($dbh, @args) = @_; | |||
| 1681 | my $sth = $dbh->primary_key_info(@args) or return; | |||
| 1682 | my ($row, @col); | |||
| 1683 | push @col, $row->[3] while ($row = $sth->fetch); | |||
| 1684 | Carp::croak("primary_key method not called in list context") | |||
| 1685 | unless wantarray; # leave us some elbow room | |||
| 1686 | return @col; | |||
| 1687 | } | |||
| 1688 | ||||
| 1689 | sub tables { | |||
| 1690 | my ($dbh, @args) = @_; | |||
| 1691 | my $sth = $dbh->table_info(@args[0,1,2,3,4]) or return; | |||
| 1692 | my $tables = $sth->fetchall_arrayref or return; | |||
| 1693 | my @tables; | |||
| 1694 | if ($dbh->get_info(29)) { # SQL_IDENTIFIER_QUOTE_CHAR | |||
| 1695 | @tables = map { $dbh->quote_identifier( @{$_}[0,1,2] ) } @$tables; | |||
| 1696 | } | |||
| 1697 | else { # temporary old style hack (yeach) | |||
| 1698 | @tables = map { | |||
| 1699 | my $name = $_->[2]; | |||
| 1700 | if ($_->[1]) { | |||
| 1701 | my $schema = $_->[1]; | |||
| 1702 | # a sad hack (mostly for Informix I recall) | |||
| 1703 | my $quote = ($schema eq uc($schema)) ? '' : '"'; | |||
| 1704 | $name = "$quote$schema$quote.$name" | |||
| 1705 | } | |||
| 1706 | $name; | |||
| 1707 | } @$tables; | |||
| 1708 | } | |||
| 1709 | return @tables; | |||
| 1710 | } | |||
| 1711 | ||||
| 1712 | sub type_info { # this should be sufficient for all drivers | |||
| 1713 | my ($dbh, $data_type) = @_; | |||
| 1714 | my $idx_hash; | |||
| 1715 | my $tia = $dbh->{dbi_type_info_row_cache}; | |||
| 1716 | if ($tia) { | |||
| 1717 | $idx_hash = $dbh->{dbi_type_info_idx_cache}; | |||
| 1718 | } | |||
| 1719 | else { | |||
| 1720 | my $temp = $dbh->type_info_all; | |||
| 1721 | return unless $temp && @$temp; | |||
| 1722 | # we cache here because type_info_all may be expensive to call | |||
| 1723 | # (and we take a copy so the following shift can't corrupt | |||
| 1724 | # the data that may be returned by future calls to type_info_all) | |||
| 1725 | $tia = $dbh->{dbi_type_info_row_cache} = [ @$temp ]; | |||
| 1726 | $idx_hash = $dbh->{dbi_type_info_idx_cache} = shift @$tia; | |||
| 1727 | } | |||
| 1728 | ||||
| 1729 | my $dt_idx = $idx_hash->{DATA_TYPE} || $idx_hash->{data_type}; | |||
| 1730 | Carp::croak("type_info_all returned non-standard DATA_TYPE index value ($dt_idx != 1)") | |||
| 1731 | if $dt_idx && $dt_idx != 1; | |||
| 1732 | ||||
| 1733 | # --- simple DATA_TYPE match filter | |||
| 1734 | my @ti; | |||
| 1735 | my @data_type_list = (ref $data_type) ? @$data_type : ($data_type); | |||
| 1736 | foreach $data_type (@data_type_list) { | |||
| 1737 | if (defined($data_type) && $data_type != DBI::SQL_ALL_TYPES()) { | |||
| 1738 | push @ti, grep { $_->[$dt_idx] == $data_type } @$tia; | |||
| 1739 | } | |||
| 1740 | else { # SQL_ALL_TYPES | |||
| 1741 | push @ti, @$tia; | |||
| 1742 | } | |||
| 1743 | last if @ti; # found at least one match | |||
| 1744 | } | |||
| 1745 | ||||
| 1746 | # --- format results into list of hash refs | |||
| 1747 | my $idx_fields = keys %$idx_hash; | |||
| 1748 | my @idx_names = map { uc($_) } keys %$idx_hash; | |||
| 1749 | my @idx_values = values %$idx_hash; | |||
| 1750 | Carp::croak "type_info_all result has $idx_fields keys but ".(@{$ti[0]})." fields" | |||
| 1751 | if @ti && @{$ti[0]} != $idx_fields; | |||
| 1752 | my @out = map { | |||
| 1753 | my %h; @h{@idx_names} = @{$_}[ @idx_values ]; \%h; | |||
| 1754 | } @ti; | |||
| 1755 | return $out[0] unless wantarray; | |||
| 1756 | return @out; | |||
| 1757 | } | |||
| 1758 | ||||
| 1759 | sub data_sources { | |||
| 1760 | my ($dbh, @other) = @_; | |||
| 1761 | my $drh = $dbh->{Driver}; # XXX proxy issues? | |||
| 1762 | return $drh->data_sources(@other); | |||
| 1763 | } | |||
| 1764 | ||||
| 1765 | } | |||
| 1766 | ||||
| 1767 | ||||
| 1768 | 1 | 900ns | 900ns | { package # hide from PAUSE |
| 1769 | DBD::_::st; # ====== STATEMENT ====== | |||
| 1770 | 1 | 5µs | 5µs | @DBD::_::st::ISA = qw(DBD::_::common); |
| 1771 | 3 | 2.02ms | 674µs | use strict; # spent 9µs making 1 call to strict::import |
| 1772 | ||||
| 1773 | sub bind_param { Carp::croak("Can't bind_param, not implement by driver") } | |||
| 1774 | ||||
| 1775 | # | |||
| 1776 | # ******************************************************** | |||
| 1777 | # | |||
| 1778 | # BEGIN ARRAY BINDING | |||
| 1779 | # | |||
| 1780 | # Array binding support for drivers which don't support | |||
| 1781 | # array binding, but have sufficient interfaces to fake it. | |||
| 1782 | # NOTE: mixing scalars and arrayrefs requires using bind_param_array | |||
| 1783 | # for *all* params...unless we modify bind_param for the default | |||
| 1784 | # case... | |||
| 1785 | # | |||
| 1786 | # 2002-Apr-10 D. Arnold | |||
| 1787 | ||||
| 1788 | sub bind_param_array { | |||
| 1789 | my $sth = shift; | |||
| 1790 | my ($p_id, $value_array, $attr) = @_; | |||
| 1791 | ||||
| 1792 | return $sth->set_err($DBI::stderr, "Value for parameter $p_id must be a scalar or an arrayref, not a ".ref($value_array)) | |||
| 1793 | if defined $value_array and ref $value_array and ref $value_array ne 'ARRAY'; | |||
| 1794 | ||||
| 1795 | return $sth->set_err($DBI::stderr, "Can't use named placeholder '$p_id' for non-driver supported bind_param_array") | |||
| 1796 | unless DBI::looks_like_number($p_id); # because we rely on execute(@ary) here | |||
| 1797 | ||||
| 1798 | return $sth->set_err($DBI::stderr, "Placeholder '$p_id' is out of range") | |||
| 1799 | if $p_id <= 0; # can't easily/reliably test for too big | |||
| 1800 | ||||
| 1801 | # get/create arrayref to hold params | |||
| 1802 | my $hash_of_arrays = $sth->{ParamArrays} ||= { }; | |||
| 1803 | ||||
| 1804 | # If the bind has attribs then we rely on the driver conforming to | |||
| 1805 | # the DBI spec in that a single bind_param() call with those attribs | |||
| 1806 | # makes them 'sticky' and apply to all later execute(@values) calls. | |||
| 1807 | # Since we only call bind_param() if we're given attribs then | |||
| 1808 | # applications using drivers that don't support bind_param can still | |||
| 1809 | # use bind_param_array() so long as they don't pass any attribs. | |||
| 1810 | ||||
| 1811 | $$hash_of_arrays{$p_id} = $value_array; | |||
| 1812 | return $sth->bind_param($p_id, undef, $attr) | |||
| 1813 | if $attr; | |||
| 1814 | 1; | |||
| 1815 | } | |||
| 1816 | ||||
| 1817 | sub bind_param_inout_array { | |||
| 1818 | my $sth = shift; | |||
| 1819 | # XXX not supported so we just call bind_param_array instead | |||
| 1820 | # and then return an error | |||
| 1821 | my ($p_num, $value_array, $attr) = @_; | |||
| 1822 | $sth->bind_param_array($p_num, $value_array, $attr); | |||
| 1823 | return $sth->set_err($DBI::stderr, "bind_param_inout_array not supported"); | |||
| 1824 | } | |||
| 1825 | ||||
| 1826 | sub bind_columns { | |||
| 1827 | my $sth = shift; | |||
| 1828 | my $fields = $sth->FETCH('NUM_OF_FIELDS') || 0; | |||
| 1829 | if ($fields <= 0 && !$sth->{Active}) { | |||
| 1830 | return $sth->set_err($DBI::stderr, "Statement has no result columns to bind" | |||
| 1831 | ." (perhaps you need to successfully call execute first)"); | |||
| 1832 | } | |||
| 1833 | # Backwards compatibility for old-style call with attribute hash | |||
| 1834 | # ref as first arg. Skip arg if undef or a hash ref. | |||
| 1835 | my $attr; | |||
| 1836 | $attr = shift if !defined $_[0] or ref($_[0]) eq 'HASH'; | |||
| 1837 | ||||
| 1838 | my $idx = 0; | |||
| 1839 | $sth->bind_col(++$idx, shift, $attr) or return | |||
| 1840 | while (@_ and $idx < $fields); | |||
| 1841 | ||||
| 1842 | return $sth->set_err($DBI::stderr, "bind_columns called with ".($idx+@_)." values but $fields are needed") | |||
| 1843 | if @_ or $idx != $fields; | |||
| 1844 | ||||
| 1845 | return 1; | |||
| 1846 | } | |||
| 1847 | ||||
| 1848 | sub execute_array { | |||
| 1849 | my $sth = shift; | |||
| 1850 | my ($attr, @array_of_arrays) = @_; | |||
| 1851 | my $NUM_OF_PARAMS = $sth->FETCH('NUM_OF_PARAMS'); # may be undef at this point | |||
| 1852 | ||||
| 1853 | # get tuple status array or hash attribute | |||
| 1854 | my $tuple_sts = $attr->{ArrayTupleStatus}; | |||
| 1855 | return $sth->set_err($DBI::stderr, "ArrayTupleStatus attribute must be an arrayref") | |||
| 1856 | if $tuple_sts and ref $tuple_sts ne 'ARRAY'; | |||
| 1857 | ||||
| 1858 | # bind all supplied arrays | |||
| 1859 | if (@array_of_arrays) { | |||
| 1860 | $sth->{ParamArrays} = { }; # clear out old params | |||
| 1861 | return $sth->set_err($DBI::stderr, | |||
| 1862 | @array_of_arrays." bind values supplied but $NUM_OF_PARAMS expected") | |||
| 1863 | if defined ($NUM_OF_PARAMS) && @array_of_arrays != $NUM_OF_PARAMS; | |||
| 1864 | $sth->bind_param_array($_, $array_of_arrays[$_-1]) or return | |||
| 1865 | foreach (1..@array_of_arrays); | |||
| 1866 | } | |||
| 1867 | ||||
| 1868 | my $fetch_tuple_sub; | |||
| 1869 | ||||
| 1870 | if ($fetch_tuple_sub = $attr->{ArrayTupleFetch}) { # fetch on demand | |||
| 1871 | ||||
| 1872 | return $sth->set_err($DBI::stderr, | |||
| 1873 | "Can't use both ArrayTupleFetch and explicit bind values") | |||
| 1874 | if @array_of_arrays; # previous bind_param_array calls will simply be ignored | |||
| 1875 | ||||
| 1876 | if (UNIVERSAL::isa($fetch_tuple_sub,'DBI::st')) { | |||
| 1877 | my $fetch_sth = $fetch_tuple_sub; | |||
| 1878 | return $sth->set_err($DBI::stderr, | |||
| 1879 | "ArrayTupleFetch sth is not Active, need to execute() it first") | |||
| 1880 | unless $fetch_sth->{Active}; | |||
| 1881 | # check column count match to give more friendly message | |||
| 1882 | my $NUM_OF_FIELDS = $fetch_sth->{NUM_OF_FIELDS}; | |||
| 1883 | return $sth->set_err($DBI::stderr, | |||
| 1884 | "$NUM_OF_FIELDS columns from ArrayTupleFetch sth but $NUM_OF_PARAMS expected") | |||
| 1885 | if defined($NUM_OF_FIELDS) && defined($NUM_OF_PARAMS) | |||
| 1886 | && $NUM_OF_FIELDS != $NUM_OF_PARAMS; | |||
| 1887 | $fetch_tuple_sub = sub { $fetch_sth->fetchrow_arrayref }; | |||
| 1888 | } | |||
| 1889 | elsif (!UNIVERSAL::isa($fetch_tuple_sub,'CODE')) { | |||
| 1890 | return $sth->set_err($DBI::stderr, "ArrayTupleFetch '$fetch_tuple_sub' is not a code ref or statement handle"); | |||
| 1891 | } | |||
| 1892 | ||||
| 1893 | } | |||
| 1894 | else { | |||
| 1895 | my $NUM_OF_PARAMS_given = keys %{ $sth->{ParamArrays} || {} }; | |||
| 1896 | return $sth->set_err($DBI::stderr, | |||
| 1897 | "$NUM_OF_PARAMS_given bind values supplied but $NUM_OF_PARAMS expected") | |||
| 1898 | if defined($NUM_OF_PARAMS) && $NUM_OF_PARAMS != $NUM_OF_PARAMS_given; | |||
| 1899 | ||||
| 1900 | # get the length of a bound array | |||
| 1901 | my $maxlen; | |||
| 1902 | my %hash_of_arrays = %{$sth->{ParamArrays}}; | |||
| 1903 | foreach (keys(%hash_of_arrays)) { | |||
| 1904 | my $ary = $hash_of_arrays{$_}; | |||
| 1905 | next unless ref $ary eq 'ARRAY'; | |||
| 1906 | $maxlen = @$ary if !$maxlen || @$ary > $maxlen; | |||
| 1907 | } | |||
| 1908 | # if there are no arrays then execute scalars once | |||
| 1909 | $maxlen = 1 unless defined $maxlen; | |||
| 1910 | my @bind_ids = 1..keys(%hash_of_arrays); | |||
| 1911 | ||||
| 1912 | my $tuple_idx = 0; | |||
| 1913 | $fetch_tuple_sub = sub { | |||
| 1914 | return if $tuple_idx >= $maxlen; | |||
| 1915 | my @tuple = map { | |||
| 1916 | my $a = $hash_of_arrays{$_}; | |||
| 1917 | ref($a) ? $a->[$tuple_idx] : $a | |||
| 1918 | } @bind_ids; | |||
| 1919 | ++$tuple_idx; | |||
| 1920 | return \@tuple; | |||
| 1921 | }; | |||
| 1922 | } | |||
| 1923 | # pass thru the callers scalar or list context | |||
| 1924 | return $sth->execute_for_fetch($fetch_tuple_sub, $tuple_sts); | |||
| 1925 | } | |||
| 1926 | ||||
| 1927 | sub execute_for_fetch { | |||
| 1928 | my ($sth, $fetch_tuple_sub, $tuple_status) = @_; | |||
| 1929 | # start with empty status array | |||
| 1930 | ($tuple_status) ? @$tuple_status = () : $tuple_status = []; | |||
| 1931 | ||||
| 1932 | my $rc_total = 0; | |||
| 1933 | my $err_count; | |||
| 1934 | while ( my $tuple = &$fetch_tuple_sub() ) { | |||
| 1935 | if ( my $rc = $sth->execute(@$tuple) ) { | |||
| 1936 | push @$tuple_status, $rc; | |||
| 1937 | $rc_total = ($rc >= 0 && $rc_total >= 0) ? $rc_total + $rc : -1; | |||
| 1938 | } | |||
| 1939 | else { | |||
| 1940 | $err_count++; | |||
| 1941 | push @$tuple_status, [ $sth->err, $sth->errstr, $sth->state ]; | |||
| 1942 | # XXX drivers implementing execute_for_fetch could opt to "last;" here | |||
| 1943 | # if they know the error code means no further executes will work. | |||
| 1944 | } | |||
| 1945 | } | |||
| 1946 | my $tuples = @$tuple_status; | |||
| 1947 | return $sth->set_err($DBI::stderr, "executing $tuples generated $err_count errors") | |||
| 1948 | if $err_count; | |||
| 1949 | $tuples ||= "0E0"; | |||
| 1950 | return $tuples unless wantarray; | |||
| 1951 | return ($tuples, $rc_total); | |||
| 1952 | } | |||
| 1953 | ||||
| 1954 | ||||
| 1955 | # spent 90µs (25+65) within DBD::_::st::fetchall_arrayref which was called
# once (25µs+65µs) by C4::VirtualShelves::GetRecentShelves at line 212 of /home/chris/git/koha.git/C4/VirtualShelves.pm | |||
| 1956 | 10 | 82µs | 8µs | my ($sth, $slice, $max_rows) = @_; |
| 1957 | ||||
| 1958 | # when batch fetching with $max_rows were very likely to try to | |||
| 1959 | # fetch the 'next batch' after the previous batch returned | |||
| 1960 | # <=$max_rows. So don't treat that as an error. | |||
| 1961 | return undef if $max_rows and not $sth->FETCH('Active'); | |||
| 1962 | ||||
| 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 | push @rows, [ @$row ] | |||
| 1976 | while($max_rows-- and $row = $sth->fetch); | |||
| 1977 | } | |||
| 1978 | else { | |||
| 1979 | push @rows, [ @$row ] while($row = $sth->fetch); | |||
| 1980 | } | |||
| 1981 | } | |||
| 1982 | elsif ($mode eq 'HASH') { | |||
| 1983 | $max_rows = -1 unless defined $max_rows; | |||
| 1984 | if (keys %$slice) { | |||
| 1985 | my @o_keys = keys %$slice; | |||
| 1986 | my @i_keys = map { lc } keys %$slice; | |||
| 1987 | # XXX this could be made faster by pre-binding a local hash | |||
| 1988 | # using bind_columns and then copying it per row | |||
| 1989 | while ($max_rows-- and $row = $sth->fetchrow_hashref('NAME_lc')) { | |||
| 1990 | my %hash; | |||
| 1991 | @hash{@o_keys} = @{$row}{@i_keys}; | |||
| 1992 | push @rows, \%hash; | |||
| 1993 | } | |||
| 1994 | } | |||
| 1995 | else { | |||
| 1996 | # XXX assumes new ref each fetchhash | |||
| 1997 | push @rows, $row # spent 65µs making 2 calls to DBI::st::fetchrow_hashref, avg 32µs/call
# spent 20µs making 2 calls to DBI::common::FETCH, avg 10µs/call
# spent 18µs making 2 calls to DBI::st::fetch, avg 9µs/call | |||
| 1998 | while ($max_rows-- and $row = $sth->fetchrow_hashref()); | |||
| 1999 | } | |||
| 2000 | } | |||
| 2001 | else { Carp::croak("fetchall_arrayref($mode) invalid") } | |||
| 2002 | return \@rows; | |||
| 2003 | } | |||
| 2004 | ||||
| 2005 | sub fetchall_hashref { | |||
| 2006 | my ($sth, $key_field) = @_; | |||
| 2007 | ||||
| 2008 | my $hash_key_name = $sth->{FetchHashKeyName} || 'NAME'; | |||
| 2009 | my $names_hash = $sth->FETCH("${hash_key_name}_hash"); | |||
| 2010 | my @key_fields = (ref $key_field) ? @$key_field : ($key_field); | |||
| 2011 | my @key_indexes; | |||
| 2012 | my $num_of_fields = $sth->FETCH('NUM_OF_FIELDS'); | |||
| 2013 | foreach (@key_fields) { | |||
| 2014 | my $index = $names_hash->{$_}; # perl index not column | |||
| 2015 | $index = $_ - 1 if !defined $index && DBI::looks_like_number($_) && $_>=1 && $_ <= $num_of_fields; | |||
| 2016 | return $sth->set_err($DBI::stderr, "Field '$_' does not exist (not one of @{[keys %$names_hash]})") | |||
| 2017 | unless defined $index; | |||
| 2018 | push @key_indexes, $index; | |||
| 2019 | } | |||
| 2020 | my $rows = {}; | |||
| 2021 | my $NAME = $sth->FETCH($hash_key_name); | |||
| 2022 | my @row = (undef) x $num_of_fields; | |||
| 2023 | $sth->bind_columns(\(@row)); | |||
| 2024 | while ($sth->fetch) { | |||
| 2025 | my $ref = $rows; | |||
| 2026 | $ref = $ref->{$row[$_]} ||= {} for @key_indexes; | |||
| 2027 | @{$ref}{@$NAME} = @row; | |||
| 2028 | } | |||
| 2029 | return $rows; | |||
| 2030 | } | |||
| 2031 | ||||
| 2032 | 1 | 2µs | 2µs | *dump_results = \&DBI::dump_results; |
| 2033 | ||||
| 2034 | sub blob_copy_to_file { # returns length or undef on error | |||
| 2035 | my($self, $field, $filename_or_handleref, $blocksize) = @_; | |||
| 2036 | my $fh = $filename_or_handleref; | |||
| 2037 | my($len, $buf) = (0, ""); | |||
| 2038 | $blocksize ||= 512; # not too ambitious | |||
| 2039 | local(*FH); | |||
| 2040 | unless(ref $fh) { | |||
| 2041 | open(FH, ">$fh") || return undef; | |||
| 2042 | $fh = \*FH; | |||
| 2043 | } | |||
| 2044 | while(defined($self->blob_read($field, $len, $blocksize, \$buf))) { | |||
| 2045 | print $fh $buf; | |||
| 2046 | $len += length $buf; | |||
| 2047 | } | |||
| 2048 | close(FH); | |||
| 2049 | $len; | |||
| 2050 | } | |||
| 2051 | ||||
| 2052 | sub more_results { | |||
| 2053 | shift->{syb_more_results}; # handy grandfathering | |||
| 2054 | } | |||
| 2055 | ||||
| 2056 | } | |||
| 2057 | ||||
| 2058 | 1 | 1µs | 1µs | unless ($DBI::PurePerl) { # See install_driver |
| 2059 | 2 | 8µs | 4µs | { @DBD::_mem::dr::ISA = qw(DBD::_mem::common); } |
| 2060 | 2 | 6µs | 3µs | { @DBD::_mem::db::ISA = qw(DBD::_mem::common); } |
| 2061 | 2 | 5µs | 3µs | { @DBD::_mem::st::ISA = qw(DBD::_mem::common); } |
| 2062 | # DBD::_mem::common::DESTROY is implemented in DBI.xs | |||
| 2063 | } | |||
| 2064 | ||||
| 2065 | 1 | 153µs | 153µs | 1; |
| 2066 | __END__ | |||
| 2067 | ||||
| 2068 | =head1 DESCRIPTION | |||
| 2069 | ||||
| 2070 | The DBI is a database access module for the Perl programming language. It defines | |||
| 2071 | a set of methods, variables, and conventions that provide a consistent | |||
| 2072 | database interface, independent of the actual database being used. | |||
| 2073 | ||||
| 2074 | It is important to remember that the DBI is just an interface. | |||
| 2075 | The DBI is a layer | |||
| 2076 | of "glue" between an application and one or more database I<driver> | |||
| 2077 | modules. It is the driver modules which do most of the real work. The DBI | |||
| 2078 | provides a standard interface and framework for the drivers to operate | |||
| 2079 | within. | |||
| 2080 | ||||
| 2081 | ||||
| 2082 | =head2 Architecture of a DBI Application | |||
| 2083 | ||||
| 2084 | |<- Scope of DBI ->| | |||
| 2085 | .-. .--------------. .-------------. | |||
| 2086 | .-------. | |---| XYZ Driver |---| XYZ Engine | | |||
| 2087 | | Perl | | | `--------------' `-------------' | |||
| 2088 | | script| |A| |D| .--------------. .-------------. | |||
| 2089 | | using |--|P|--|B|---|Oracle Driver |---|Oracle Engine| | |||
| 2090 | | DBI | |I| |I| `--------------' `-------------' | |||
| 2091 | | API | | |... | |||
| 2092 | |methods| | |... Other drivers | |||
| 2093 | `-------' | |... | |||
| 2094 | `-' | |||
| 2095 | ||||
| 2096 | The API, or Application Programming Interface, defines the | |||
| 2097 | call interface and variables for Perl scripts to use. The API | |||
| 2098 | is implemented by the Perl DBI extension. | |||
| 2099 | ||||
| 2100 | The DBI "dispatches" the method calls to the appropriate driver for | |||
| 2101 | actual execution. The DBI is also responsible for the dynamic loading | |||
| 2102 | of drivers, error checking and handling, providing default | |||
| 2103 | implementations for methods, and many other non-database specific duties. | |||
| 2104 | ||||
| 2105 | Each driver | |||
| 2106 | contains implementations of the DBI methods using the | |||
| 2107 | private interface functions of the corresponding database engine. Only authors | |||
| 2108 | of sophisticated/multi-database applications or generic library | |||
| 2109 | functions need be concerned with drivers. | |||
| 2110 | ||||
| 2111 | =head2 Notation and Conventions | |||
| 2112 | ||||
| 2113 | The following conventions are used in this document: | |||
| 2114 | ||||
| 2115 | $dbh Database handle object | |||
| 2116 | $sth Statement handle object | |||
| 2117 | $drh Driver handle object (rarely seen or used in applications) | |||
| 2118 | $h Any of the handle types above ($dbh, $sth, or $drh) | |||
| 2119 | $rc General Return Code (boolean: true=ok, false=error) | |||
| 2120 | $rv General Return Value (typically an integer) | |||
| 2121 | @ary List of values returned from the database, typically a row of data | |||
| 2122 | $rows Number of rows processed (if available, else -1) | |||
| 2123 | $fh A filehandle | |||
| 2124 | undef NULL values are represented by undefined values in Perl | |||
| 2125 | \%attr Reference to a hash of attribute values passed to methods | |||
| 2126 | ||||
| 2127 | Note that Perl will automatically destroy database and statement handle objects | |||
| 2128 | if all references to them are deleted. | |||
| 2129 | ||||
| 2130 | ||||
| 2131 | =head2 Outline Usage | |||
| 2132 | ||||
| 2133 | To use DBI, | |||
| 2134 | first you need to load the DBI module: | |||
| 2135 | ||||
| 2136 | use DBI; | |||
| 2137 | use strict; | |||
| 2138 | ||||
| 2139 | (The C<use strict;> isn't required but is strongly recommended.) | |||
| 2140 | ||||
| 2141 | Then you need to L</connect> to your data source and get a I<handle> for that | |||
| 2142 | connection: | |||
| 2143 | ||||
| 2144 | $dbh = DBI->connect($dsn, $user, $password, | |||
| 2145 | { RaiseError => 1, AutoCommit => 0 }); | |||
| 2146 | ||||
| 2147 | Since connecting can be expensive, you generally just connect at the | |||
| 2148 | start of your program and disconnect at the end. | |||
| 2149 | ||||
| 2150 | Explicitly defining the required C<AutoCommit> behaviour is strongly | |||
| 2151 | recommended and may become mandatory in a later version. This | |||
| 2152 | determines whether changes are automatically committed to the | |||
| 2153 | database when executed, or need to be explicitly committed later. | |||
| 2154 | ||||
| 2155 | The DBI allows an application to "prepare" statements for later | |||
| 2156 | execution. A prepared statement is identified by a statement handle | |||
| 2157 | held in a Perl variable. | |||
| 2158 | We'll call the Perl variable C<$sth> in our examples. | |||
| 2159 | ||||
| 2160 | The typical method call sequence for a C<SELECT> statement is: | |||
| 2161 | ||||
| 2162 | prepare, | |||
| 2163 | execute, fetch, fetch, ... | |||
| 2164 | execute, fetch, fetch, ... | |||
| 2165 | execute, fetch, fetch, ... | |||
| 2166 | ||||
| 2167 | for example: | |||
| 2168 | ||||
| 2169 | $sth = $dbh->prepare("SELECT foo, bar FROM table WHERE baz=?"); | |||
| 2170 | ||||
| 2171 | $sth->execute( $baz ); | |||
| 2172 | ||||
| 2173 | while ( @row = $sth->fetchrow_array ) { | |||
| 2174 | print "@row\n"; | |||
| 2175 | } | |||
| 2176 | ||||
| 2177 | The typical method call sequence for a I<non>-C<SELECT> statement is: | |||
| 2178 | ||||
| 2179 | prepare, | |||
| 2180 | execute, | |||
| 2181 | execute, | |||
| 2182 | execute. | |||
| 2183 | ||||
| 2184 | for example: | |||
| 2185 | ||||
| 2186 | $sth = $dbh->prepare("INSERT INTO table(foo,bar,baz) VALUES (?,?,?)"); | |||
| 2187 | ||||
| 2188 | while(<CSV>) { | |||
| 2189 | chomp; | |||
| 2190 | my ($foo,$bar,$baz) = split /,/; | |||
| 2191 | $sth->execute( $foo, $bar, $baz ); | |||
| 2192 | } | |||
| 2193 | ||||
| 2194 | The C<do()> method can be used for non repeated I<non>-C<SELECT> statement | |||
| 2195 | (or with drivers that don't support placeholders): | |||
| 2196 | ||||
| 2197 | $rows_affected = $dbh->do("UPDATE your_table SET foo = foo + 1"); | |||
| 2198 | ||||
| 2199 | To commit your changes to the database (when L</AutoCommit> is off): | |||
| 2200 | ||||
| 2201 | $dbh->commit; # or call $dbh->rollback; to undo changes | |||
| 2202 | ||||
| 2203 | Finally, when you have finished working with the data source, you should | |||
| 2204 | L</disconnect> from it: | |||
| 2205 | ||||
| 2206 | $dbh->disconnect; | |||
| 2207 | ||||
| 2208 | ||||
| 2209 | =head2 General Interface Rules & Caveats | |||
| 2210 | ||||
| 2211 | The DBI does not have a concept of a "current session". Every session | |||
| 2212 | has a handle object (i.e., a C<$dbh>) returned from the C<connect> method. | |||
| 2213 | That handle object is used to invoke database related methods. | |||
| 2214 | ||||
| 2215 | Most data is returned to the Perl script as strings. (Null values are | |||
| 2216 | returned as C<undef>.) This allows arbitrary precision numeric data to be | |||
| 2217 | handled without loss of accuracy. Beware that Perl may not preserve | |||
| 2218 | the same accuracy when the string is used as a number. | |||
| 2219 | ||||
| 2220 | Dates and times are returned as character strings in the current | |||
| 2221 | default format of the corresponding database engine. Time zone effects | |||
| 2222 | are database/driver dependent. | |||
| 2223 | ||||
| 2224 | Perl supports binary data in Perl strings, and the DBI will pass binary | |||
| 2225 | data to and from the driver without change. It is up to the driver | |||
| 2226 | implementors to decide how they wish to handle such binary data. | |||
| 2227 | ||||
| 2228 | Perl supports two kinds of strings: unicode (utf8 internally) and non-unicode | |||
| 2229 | (defaults to iso-8859-1 if forced to assume an encoding). Drivers should | |||
| 2230 | accept both kinds of strings and, if required, convert them to the character | |||
| 2231 | set of the database being used. Similarly, when fetching from the database | |||
| 2232 | character data that isn't iso-8859-1 the driver should convert it into utf8. | |||
| 2233 | ||||
| 2234 | Multiple SQL statements may not be combined in a single statement | |||
| 2235 | handle (C<$sth>), although some databases and drivers do support this | |||
| 2236 | (notably Sybase and SQL Server). | |||
| 2237 | ||||
| 2238 | Non-sequential record reads are not supported in this version of the DBI. | |||
| 2239 | In other words, records can only be fetched in the order that the | |||
| 2240 | database returned them, and once fetched they are forgotten. | |||
| 2241 | ||||
| 2242 | Positioned updates and deletes are not directly supported by the DBI. | |||
| 2243 | See the description of the C<CursorName> attribute for an alternative. | |||
| 2244 | ||||
| 2245 | Individual driver implementors are free to provide any private | |||
| 2246 | functions and/or handle attributes that they feel are useful. | |||
| 2247 | Private driver functions can be invoked using the DBI C<func()> method. | |||
| 2248 | Private driver attributes are accessed just like standard attributes. | |||
| 2249 | ||||
| 2250 | Many methods have an optional C<\%attr> parameter which can be used to | |||
| 2251 | pass information to the driver implementing the method. Except where | |||
| 2252 | specifically documented, the C<\%attr> parameter can only be used to pass | |||
| 2253 | driver specific hints. In general, you can ignore C<\%attr> parameters | |||
| 2254 | or pass it as C<undef>. | |||
| 2255 | ||||
| 2256 | ||||
| 2257 | =head2 Naming Conventions and Name Space | |||
| 2258 | ||||
| 2259 | The DBI package and all packages below it (C<DBI::*>) are reserved for | |||
| 2260 | use by the DBI. Extensions and related modules use the C<DBIx::> | |||
| 2261 | namespace (see L<http://www.perl.com/CPAN/modules/by-module/DBIx/>). | |||
| 2262 | Package names beginning with C<DBD::> are reserved for use | |||
| 2263 | by DBI database drivers. All environment variables used by the DBI | |||
| 2264 | or by individual DBDs begin with "C<DBI_>" or "C<DBD_>". | |||
| 2265 | ||||
| 2266 | The letter case used for attribute names is significant and plays an | |||
| 2267 | important part in the portability of DBI scripts. The case of the | |||
| 2268 | attribute name is used to signify who defined the meaning of that name | |||
| 2269 | and its values. | |||
| 2270 | ||||
| 2271 | Case of name Has a meaning defined by | |||
| 2272 | ------------ ------------------------ | |||
| 2273 | UPPER_CASE Standards, e.g., X/Open, ISO SQL92 etc (portable) | |||
| 2274 | MixedCase DBI API (portable), underscores are not used. | |||
| 2275 | lower_case Driver or database engine specific (non-portable) | |||
| 2276 | ||||
| 2277 | It is of the utmost importance that Driver developers only use | |||
| 2278 | lowercase attribute names when defining private attributes. Private | |||
| 2279 | attribute names must be prefixed with the driver name or suitable | |||
| 2280 | abbreviation (e.g., "C<ora_>" for Oracle, "C<ing_>" for Ingres, etc). | |||
| 2281 | ||||
| 2282 | ||||
| 2283 | =head2 SQL - A Query Language | |||
| 2284 | ||||
| 2285 | Most DBI drivers require applications to use a dialect of SQL | |||
| 2286 | (Structured Query Language) to interact with the database engine. | |||
| 2287 | The L</"Standards Reference Information"> section provides links | |||
| 2288 | to useful information about SQL. | |||
| 2289 | ||||
| 2290 | The DBI itself does not mandate or require any particular language to | |||
| 2291 | be used; it is language independent. In ODBC terms, the DBI is in | |||
| 2292 | "pass-thru" mode, although individual drivers might not be. The only requirement | |||
| 2293 | is that queries and other statements must be expressed as a single | |||
| 2294 | string of characters passed as the first argument to the L</prepare> or | |||
| 2295 | L</do> methods. | |||
| 2296 | ||||
| 2297 | For an interesting diversion on the I<real> history of RDBMS and SQL, | |||
| 2298 | from the people who made it happen, see: | |||
| 2299 | ||||
| 2300 | http://ftp.digital.com/pub/DEC/SRC/technical-notes/SRC-1997-018-html/sqlr95.html | |||
| 2301 | ||||
| 2302 | Follow the "Full Contents" then "Intergalactic dataspeak" links for the | |||
| 2303 | SQL history. | |||
| 2304 | ||||
| 2305 | =head2 Placeholders and Bind Values | |||
| 2306 | ||||
| 2307 | Some drivers support placeholders and bind values. | |||
| 2308 | I<Placeholders>, also called parameter markers, are used to indicate | |||
| 2309 | values in a database statement that will be supplied later, | |||
| 2310 | before the prepared statement is executed. For example, an application | |||
| 2311 | might use the following to insert a row of data into the SALES table: | |||
| 2312 | ||||
| 2313 | INSERT INTO sales (product_code, qty, price) VALUES (?, ?, ?) | |||
| 2314 | ||||
| 2315 | or the following, to select the description for a product: | |||
| 2316 | ||||
| 2317 | SELECT description FROM products WHERE product_code = ? | |||
| 2318 | ||||
| 2319 | The C<?> characters are the placeholders. The association of actual | |||
| 2320 | values with placeholders is known as I<binding>, and the values are | |||
| 2321 | referred to as I<bind values>. | |||
| 2322 | Note that the C<?> is not enclosed in quotation marks, even when the | |||
| 2323 | placeholder represents a string. | |||
| 2324 | ||||
| 2325 | Some drivers also allow placeholders like C<:>I<name> and C<:>I<N> (e.g., | |||
| 2326 | C<:1>, C<:2>, and so on) in addition to C<?>, but their use is not portable. | |||
| 2327 | ||||
| 2328 | If the C<:>I<N> form of placeholder is supported by the driver you're using, | |||
| 2329 | then you should be able to use either L</bind_param> or L</execute> to bind | |||
| 2330 | values. Check your driver documentation. | |||
| 2331 | ||||
| 2332 | With most drivers, placeholders can't be used for any element of a | |||
| 2333 | statement that would prevent the database server from validating the | |||
| 2334 | statement and creating a query execution plan for it. For example: | |||
| 2335 | ||||
| 2336 | "SELECT name, age FROM ?" # wrong (will probably fail) | |||
| 2337 | "SELECT name, ? FROM people" # wrong (but may not 'fail') | |||
| 2338 | ||||
| 2339 | Also, placeholders can only represent single scalar values. | |||
| 2340 | For example, the following | |||
| 2341 | statement won't work as expected for more than one value: | |||
| 2342 | ||||
| 2343 | "SELECT name, age FROM people WHERE name IN (?)" # wrong | |||
| 2344 | "SELECT name, age FROM people WHERE name IN (?,?)" # two names | |||
| 2345 | ||||
| 2346 | When using placeholders with the SQL C<LIKE> qualifier, you must | |||
| 2347 | remember that the placeholder substitutes for the whole string. | |||
| 2348 | So you should use "C<... LIKE ? ...>" and include any wildcard | |||
| 2349 | characters in the value that you bind to the placeholder. | |||
| 2350 | ||||
| 2351 | B<NULL Values> | |||
| 2352 | ||||
| 2353 | Undefined values, or C<undef>, are used to indicate NULL values. | |||
| 2354 | You can insert and update columns with a NULL value as you would a | |||
| 2355 | non-NULL value. These examples insert and update the column | |||
| 2356 | C<age> with a NULL value: | |||
| 2357 | ||||
| 2358 | $sth = $dbh->prepare(qq{ | |||
| 2359 | INSERT INTO people (fullname, age) VALUES (?, ?) | |||
| 2360 | }); | |||
| 2361 | $sth->execute("Joe Bloggs", undef); | |||
| 2362 | ||||
| 2363 | $sth = $dbh->prepare(qq{ | |||
| 2364 | UPDATE people SET age = ? WHERE fullname = ? | |||
| 2365 | }); | |||
| 2366 | $sth->execute(undef, "Joe Bloggs"); | |||
| 2367 | ||||
| 2368 | However, care must be taken when trying to use NULL values in a | |||
| 2369 | C<WHERE> clause. Consider: | |||
| 2370 | ||||
| 2371 | SELECT fullname FROM people WHERE age = ? | |||
| 2372 | ||||
| 2373 | Binding an C<undef> (NULL) to the placeholder will I<not> select rows | |||
| 2374 | which have a NULL C<age>! At least for database engines that | |||
| 2375 | conform to the SQL standard. Refer to the SQL manual for your database | |||
| 2376 | engine or any SQL book for the reasons for this. To explicitly select | |||
| 2377 | NULLs you have to say "C<WHERE age IS NULL>". | |||
| 2378 | ||||
| 2379 | A common issue is to have a code fragment handle a value that could be | |||
| 2380 | either C<defined> or C<undef> (non-NULL or NULL) at runtime. | |||
| 2381 | A simple technique is to prepare the appropriate statement as needed, | |||
| 2382 | and substitute the placeholder for non-NULL cases: | |||
| 2383 | ||||
| 2384 | $sql_clause = defined $age? "age = ?" : "age IS NULL"; | |||
| 2385 | $sth = $dbh->prepare(qq{ | |||
| 2386 | SELECT fullname FROM people WHERE $sql_clause | |||
| 2387 | }); | |||
| 2388 | $sth->execute(defined $age ? $age : ()); | |||
| 2389 | ||||
| 2390 | The following technique illustrates qualifying a C<WHERE> clause with | |||
| 2391 | several columns, whose associated values (C<defined> or C<undef>) are | |||
| 2392 | in a hash %h: | |||
| 2393 | ||||
| 2394 | for my $col ("age", "phone", "email") { | |||
| 2395 | if (defined $h{$col}) { | |||
| 2396 | push @sql_qual, "$col = ?"; | |||
| 2397 | push @sql_bind, $h{$col}; | |||
| 2398 | } | |||
| 2399 | else { | |||
| 2400 | push @sql_qual, "$col IS NULL"; | |||
| 2401 | } | |||
| 2402 | } | |||
| 2403 | $sql_clause = join(" AND ", @sql_qual); | |||
| 2404 | $sth = $dbh->prepare(qq{ | |||
| 2405 | SELECT fullname FROM people WHERE $sql_clause | |||
| 2406 | }); | |||
| 2407 | $sth->execute(@sql_bind); | |||
| 2408 | ||||
| 2409 | The techniques above call prepare for the SQL statement with each call to | |||
| 2410 | execute. Because calls to prepare() can be expensive, performance | |||
| 2411 | can suffer when an application iterates many times over statements | |||
| 2412 | like the above. | |||
| 2413 | ||||
| 2414 | A better solution is a single C<WHERE> clause that supports both | |||
| 2415 | NULL and non-NULL comparisons. Its SQL statement would need to be | |||
| 2416 | prepared only once for all cases, thus improving performance. | |||
| 2417 | Several examples of C<WHERE> clauses that support this are presented | |||
| 2418 | below. But each example lacks portability, robustness, or simplicity. | |||
| 2419 | Whether an example is supported on your database engine depends on | |||
| 2420 | what SQL extensions it provides, and where it supports the C<?> | |||
| 2421 | placeholder in a statement. | |||
| 2422 | ||||
| 2423 | 0) age = ? | |||
| 2424 | 1) NVL(age, xx) = NVL(?, xx) | |||
| 2425 | 2) ISNULL(age, xx) = ISNULL(?, xx) | |||
| 2426 | 3) DECODE(age, ?, 1, 0) = 1 | |||
| 2427 | 4) age = ? OR (age IS NULL AND ? IS NULL) | |||
| 2428 | 5) age = ? OR (age IS NULL AND SP_ISNULL(?) = 1) | |||
| 2429 | 6) age = ? OR (age IS NULL AND ? = 1) | |||
| 2430 | ||||
| 2431 | Statements formed with the above C<WHERE> clauses require execute | |||
| 2432 | statements as follows. The arguments are required, whether their | |||
| 2433 | values are C<defined> or C<undef>. | |||
| 2434 | ||||
| 2435 | 0,1,2,3) $sth->execute($age); | |||
| 2436 | 4,5) $sth->execute($age, $age); | |||
| 2437 | 6) $sth->execute($age, defined($age) ? 0 : 1); | |||
| 2438 | ||||
| 2439 | Example 0 should not work (as mentioned earlier), but may work on | |||
| 2440 | a few database engines anyway (e.g. Sybase). Example 0 is part | |||
| 2441 | of examples 4, 5, and 6, so if example 0 works, these other | |||
| 2442 | examples may work, even if the engine does not properly support | |||
| 2443 | the right hand side of the C<OR> expression. | |||
| 2444 | ||||
| 2445 | Examples 1 and 2 are not robust: they require that you provide a | |||
| 2446 | valid column value xx (e.g. '~') which is not present in any row. | |||
| 2447 | That means you must have some notion of what data won't be stored | |||
| 2448 | in the column, and expect clients to adhere to that. | |||
| 2449 | ||||
| 2450 | Example 5 requires that you provide a stored procedure (SP_ISNULL | |||
| 2451 | in this example) that acts as a function: it checks whether a value | |||
| 2452 | is null, and returns 1 if it is, or 0 if not. | |||
| 2453 | ||||
| 2454 | Example 6, the least simple, is probably the most portable, i.e., it | |||
| 2455 | should work with with most, if not all, database engines. | |||
| 2456 | ||||
| 2457 | Here is a table that indicates which examples above are known to | |||
| 2458 | work on various database engines: | |||
| 2459 | ||||
| 2460 | -----Examples------ | |||
| 2461 | 0 1 2 3 4 5 6 | |||
| 2462 | - - - - - - - | |||
| 2463 | Oracle 9 N Y N Y Y ? Y | |||
| 2464 | Informix IDS 9 N N N Y N Y Y | |||
| 2465 | MS SQL N N Y N Y ? Y | |||
| 2466 | Sybase Y N N N N N Y | |||
| 2467 | AnyData,DBM,CSV Y N N N Y Y* Y | |||
| 2468 | SQLite 3.3 N N N N Y N N | |||
| 2469 | ||||
| 2470 | * Works only because Example 0 works. | |||
| 2471 | ||||
| 2472 | DBI provides a sample perl script that will test the examples above | |||
| 2473 | on your database engine and tell you which ones work. It is located | |||
| 2474 | in the F<ex/> subdirectory of the DBI source distribution, or here: | |||
| 2475 | L<http://svn.perl.org/modules/dbi/trunk/ex/perl_dbi_nulls_test.pl> | |||
| 2476 | Please use the script to help us fill-in and maintain this table. | |||
| 2477 | ||||
| 2478 | B<Performance> | |||
| 2479 | ||||
| 2480 | Without using placeholders, the insert statement shown previously would have to | |||
| 2481 | contain the literal values to be inserted and would have to be | |||
| 2482 | re-prepared and re-executed for each row. With placeholders, the insert | |||
| 2483 | statement only needs to be prepared once. The bind values for each row | |||
| 2484 | can be given to the C<execute> method each time it's called. By avoiding | |||
| 2485 | the need to re-prepare the statement for each row, the application | |||
| 2486 | typically runs many times faster. Here's an example: | |||
| 2487 | ||||
| 2488 | my $sth = $dbh->prepare(q{ | |||
| 2489 | INSERT INTO sales (product_code, qty, price) VALUES (?, ?, ?) | |||
| 2490 | }) or die $dbh->errstr; | |||
| 2491 | while (<>) { | |||
| 2492 | chomp; | |||
| 2493 | my ($product_code, $qty, $price) = split /,/; | |||
| 2494 | $sth->execute($product_code, $qty, $price) or die $dbh->errstr; | |||
| 2495 | } | |||
| 2496 | $dbh->commit or die $dbh->errstr; | |||
| 2497 | ||||
| 2498 | See L</execute> and L</bind_param> for more details. | |||
| 2499 | ||||
| 2500 | The C<q{...}> style quoting used in this example avoids clashing with | |||
| 2501 | quotes that may be used in the SQL statement. Use the double-quote like | |||
| 2502 | C<qq{...}> operator if you want to interpolate variables into the string. | |||
| 2503 | See L<perlop/"Quote and Quote-like Operators"> for more details. | |||
| 2504 | ||||
| 2505 | See also the L</bind_columns> method, which is used to associate Perl | |||
| 2506 | variables with the output columns of a C<SELECT> statement. | |||
| 2507 | ||||
| 2508 | =head1 THE DBI PACKAGE AND CLASS | |||
| 2509 | ||||
| 2510 | In this section, we cover the DBI class methods, utility functions, | |||
| 2511 | and the dynamic attributes associated with generic DBI handles. | |||
| 2512 | ||||
| 2513 | =head2 DBI Constants | |||
| 2514 | ||||
| 2515 | Constants representing the values of the SQL standard types can be | |||
| 2516 | imported individually by name, or all together by importing the | |||
| 2517 | special C<:sql_types> tag. | |||
| 2518 | ||||
| 2519 | The names and values of all the defined SQL standard types can be | |||
| 2520 | produced like this: | |||
| 2521 | ||||
| 2522 | foreach (@{ $DBI::EXPORT_TAGS{sql_types} }) { | |||
| 2523 | printf "%s=%d\n", $_, &{"DBI::$_"}; | |||
| 2524 | } | |||
| 2525 | ||||
| 2526 | These constants are defined by SQL/CLI, ODBC or both. | |||
| 2527 | C<SQL_BIGINT> is (currently) omitted, because SQL/CLI and ODBC provide | |||
| 2528 | conflicting codes. | |||
| 2529 | ||||
| 2530 | See the L</type_info>, L</type_info_all>, and L</bind_param> methods | |||
| 2531 | for possible uses. | |||
| 2532 | ||||
| 2533 | Note that just because the DBI defines a named constant for a given | |||
| 2534 | data type doesn't mean that drivers will support that data type. | |||
| 2535 | ||||
| 2536 | ||||
| 2537 | =head2 DBI Class Methods | |||
| 2538 | ||||
| 2539 | The following methods are provided by the DBI class: | |||
| 2540 | ||||
| 2541 | =head3 C<parse_dsn> | |||
| 2542 | ||||
| 2543 | ($scheme, $driver, $attr_string, $attr_hash, $driver_dsn) = DBI->parse_dsn($dsn) | |||
| 2544 | or die "Can't parse DBI DSN '$dsn'"; | |||
| 2545 | ||||
| 2546 | Breaks apart a DBI Data Source Name (DSN) and returns the individual | |||
| 2547 | parts. If $dsn doesn't contain a valid DSN then parse_dsn() returns | |||
| 2548 | an empty list. | |||
| 2549 | ||||
| 2550 | $scheme is the first part of the DSN and is currently always 'dbi'. | |||
| 2551 | $driver is the driver name, possibly defaulted to $ENV{DBI_DRIVER}, | |||
| 2552 | and may be undefined. $attr_string is the contents of the optional attribute | |||
| 2553 | string, which may be undefined. If $attr_string is not empty then $attr_hash | |||
| 2554 | is a reference to a hash containing the parsed attribute names and values. | |||
| 2555 | $driver_dsn is the last part of the DBI DSN string. For example: | |||
| 2556 | ||||
| 2557 | ($scheme, $driver, $attr_string, $attr_hash, $driver_dsn) | |||
| 2558 | = DBI->parse_dsn("DBI:MyDriver(RaiseError=>1):db=test;port=42"); | |||
| 2559 | $scheme = 'dbi'; | |||
| 2560 | $driver = 'MyDriver'; | |||
| 2561 | $attr_string = 'RaiseError=>1'; | |||
| 2562 | $attr_hash = { 'RaiseError' => '1' }; | |||
| 2563 | $driver_dsn = 'db=test;port=42'; | |||
| 2564 | ||||
| 2565 | The parse_dsn() method was added in DBI 1.43. | |||
| 2566 | ||||
| 2567 | =head3 C<connect> | |||
| 2568 | ||||
| 2569 | $dbh = DBI->connect($data_source, $username, $password) | |||
| 2570 | or die $DBI::errstr; | |||
| 2571 | $dbh = DBI->connect($data_source, $username, $password, \%attr) | |||
| 2572 | or die $DBI::errstr; | |||
| 2573 | ||||
| 2574 | Establishes a database connection, or session, to the requested C<$data_source>. | |||
| 2575 | Returns a database handle object if the connection succeeds. Use | |||
| 2576 | C<$dbh-E<gt>disconnect> to terminate the connection. | |||
| 2577 | ||||
| 2578 | If the connect fails (see below), it returns C<undef> and sets both C<$DBI::err> | |||
| 2579 | and C<$DBI::errstr>. (It does I<not> explicitly set C<$!>.) You should generally | |||
| 2580 | test the return status of C<connect> and C<print $DBI::errstr> if it has failed. | |||
| 2581 | ||||
| 2582 | Multiple simultaneous connections to multiple databases through multiple | |||
| 2583 | drivers can be made via the DBI. Simply make one C<connect> call for each | |||
| 2584 | database and keep a copy of each returned database handle. | |||
| 2585 | ||||
| 2586 | The C<$data_source> value must begin with "C<dbi:>I<driver_name>C<:>". | |||
| 2587 | The I<driver_name> specifies the driver that will be used to make the | |||
| 2588 | connection. (Letter case is significant.) | |||
| 2589 | ||||
| 2590 | As a convenience, if the C<$data_source> parameter is undefined or empty, | |||
| 2591 | the DBI will substitute the value of the environment variable C<DBI_DSN>. | |||
| 2592 | If just the I<driver_name> part is empty (i.e., the C<$data_source> | |||
| 2593 | prefix is "C<dbi::>"), the environment variable C<DBI_DRIVER> is | |||
| 2594 | used. If neither variable is set, then C<connect> dies. | |||
| 2595 | ||||
| 2596 | Examples of C<$data_source> values are: | |||
| 2597 | ||||
| 2598 | dbi:DriverName:database_name | |||
| 2599 | dbi:DriverName:database_name@hostname:port | |||
| 2600 | dbi:DriverName:database=database_name;host=hostname;port=port | |||
| 2601 | ||||
| 2602 | There is I<no standard> for the text following the driver name. Each | |||
| 2603 | driver is free to use whatever syntax it wants. The only requirement the | |||
| 2604 | DBI makes is that all the information is supplied in a single string. | |||
| 2605 | You must consult the documentation for the drivers you are using for a | |||
| 2606 | description of the syntax they require. | |||
| 2607 | ||||
| 2608 | It is recommended that drivers support the ODBC style, shown in the | |||
| 2609 | last example above. It is also recommended that that they support the | |||
| 2610 | three common names 'C<host>', 'C<port>', and 'C<database>' (plus 'C<db>' | |||
| 2611 | as an alias for C<database>). This simplifies automatic construction | |||
| 2612 | of basic DSNs: C<"dbi:$driver:database=$db;host=$host;port=$port">. | |||
| 2613 | Drivers should aim to 'do something reasonable' when given a DSN | |||
| 2614 | in this form, but if any part is meaningless for that driver (such | |||
| 2615 | as 'port' for Informix) it should generate an error if that part | |||
| 2616 | is not empty. | |||
| 2617 | ||||
| 2618 | If the environment variable C<DBI_AUTOPROXY> is defined (and the | |||
| 2619 | driver in C<$data_source> is not "C<Proxy>") then the connect request | |||
| 2620 | will automatically be changed to: | |||
| 2621 | ||||
| 2622 | $ENV{DBI_AUTOPROXY};dsn=$data_source | |||
| 2623 | ||||
| 2624 | C<DBI_AUTOPROXY> is typically set as "C<dbi:Proxy:hostname=...;port=...>". | |||
| 2625 | If $ENV{DBI_AUTOPROXY} doesn't begin with 'C<dbi:>' then "dbi:Proxy:" | |||
| 2626 | will be prepended to it first. See the DBD::Proxy documentation | |||
| 2627 | for more details. | |||
| 2628 | ||||
| 2629 | If C<$username> or C<$password> are undefined (rather than just empty), | |||
| 2630 | then the DBI will substitute the values of the C<DBI_USER> and C<DBI_PASS> | |||
| 2631 | environment variables, respectively. The DBI will warn if the | |||
| 2632 | environment variables are not defined. However, the everyday use | |||
| 2633 | of these environment variables is not recommended for security | |||
| 2634 | reasons. The mechanism is primarily intended to simplify testing. | |||
| 2635 | See below for alternative way to specify the username and password. | |||
| 2636 | ||||
| 2637 | C<DBI-E<gt>connect> automatically installs the driver if it has not been | |||
| 2638 | installed yet. Driver installation either returns a valid driver | |||
| 2639 | handle, or it I<dies> with an error message that includes the string | |||
| 2640 | "C<install_driver>" and the underlying problem. So C<DBI-E<gt>connect> | |||
| 2641 | will die | |||
| 2642 | on a driver installation failure and will only return C<undef> on a | |||
| 2643 | connect failure, in which case C<$DBI::errstr> will hold the error message. | |||
| 2644 | Use C<eval { ... }> if you need to catch the "C<install_driver>" error. | |||
| 2645 | ||||
| 2646 | The C<$data_source> argument (with the "C<dbi:...:>" prefix removed) and the | |||
| 2647 | C<$username> and C<$password> arguments are then passed to the driver for | |||
| 2648 | processing. The DBI does not define any interpretation for the | |||
| 2649 | contents of these fields. The driver is free to interpret the | |||
| 2650 | C<$data_source>, C<$username>, and C<$password> fields in any way, and supply | |||
| 2651 | whatever defaults are appropriate for the engine being accessed. | |||
| 2652 | (Oracle, for example, uses the ORACLE_SID and TWO_TASK environment | |||
| 2653 | variables if no C<$data_source> is specified.) | |||
| 2654 | ||||
| 2655 | The C<AutoCommit> and C<PrintError> attributes for each connection | |||
| 2656 | default to "on". (See L</AutoCommit> and L</PrintError> for more information.) | |||
| 2657 | However, it is strongly recommended that you explicitly define C<AutoCommit> | |||
| 2658 | rather than rely on the default. The C<PrintWarn> attribute defaults to | |||
| 2659 | on if $^W is true, i.e., perl is running with warnings enabled. | |||
| 2660 | ||||
| 2661 | The C<\%attr> parameter can be used to alter the default settings of | |||
| 2662 | C<PrintError>, C<RaiseError>, C<AutoCommit>, and other attributes. For example: | |||
| 2663 | ||||
| 2664 | $dbh = DBI->connect($data_source, $user, $pass, { | |||
| 2665 | PrintError => 0, | |||
| 2666 | AutoCommit => 0 | |||
| 2667 | }); | |||
| 2668 | ||||
| 2669 | The username and password can also be specified using the attributes | |||
| 2670 | C<Username> and C<Password>, in which case they take precedence | |||
| 2671 | over the C<$username> and C<$password> parameters. | |||
| 2672 | ||||
| 2673 | You can also define connection attribute values within the C<$data_source> | |||
| 2674 | parameter. For example: | |||
| 2675 | ||||
| 2676 | dbi:DriverName(PrintWarn=>1,PrintError=>0,Taint=>1):... | |||
| 2677 | ||||
| 2678 | Individual attributes values specified in this way take precedence over | |||
| 2679 | any conflicting values specified via the C<\%attr> parameter to C<connect>. | |||
| 2680 | ||||
| 2681 | The C<dbi_connect_method> attribute can be used to specify which driver | |||
| 2682 | method should be called to establish the connection. The only useful | |||
| 2683 | values are 'connect', 'connect_cached', or some specialized case like | |||
| 2684 | 'Apache::DBI::connect' (which is automatically the default when running | |||
| 2685 | within Apache). | |||
| 2686 | ||||
| 2687 | Where possible, each session (C<$dbh>) is independent from the transactions | |||
| 2688 | in other sessions. This is useful when you need to hold cursors open | |||
| 2689 | across transactions--for example, if you use one session for your long lifespan | |||
| 2690 | cursors (typically read-only) and another for your short update | |||
| 2691 | transactions. | |||
| 2692 | ||||
| 2693 | For compatibility with old DBI scripts, the driver can be specified by | |||
| 2694 | passing its name as the fourth argument to C<connect> (instead of C<\%attr>): | |||
| 2695 | ||||
| 2696 | $dbh = DBI->connect($data_source, $user, $pass, $driver); | |||
| 2697 | ||||
| 2698 | In this "old-style" form of C<connect>, the C<$data_source> should not start | |||
| 2699 | with "C<dbi:driver_name:>". (If it does, the embedded driver_name | |||
| 2700 | will be ignored). Also note that in this older form of C<connect>, | |||
| 2701 | the C<$dbh-E<gt>{AutoCommit}> attribute is I<undefined>, the | |||
| 2702 | C<$dbh-E<gt>{PrintError}> attribute is off, and the old C<DBI_DBNAME> | |||
| 2703 | environment variable is | |||
| 2704 | checked if C<DBI_DSN> is not defined. Beware that this "old-style" | |||
| 2705 | C<connect> will soon be withdrawn in a future version of DBI. | |||
| 2706 | ||||
| 2707 | =head3 C<connect_cached> | |||
| 2708 | ||||
| 2709 | $dbh = DBI->connect_cached($data_source, $username, $password) | |||
| 2710 | or die $DBI::errstr; | |||
| 2711 | $dbh = DBI->connect_cached($data_source, $username, $password, \%attr) | |||
| 2712 | or die $DBI::errstr; | |||
| 2713 | ||||
| 2714 | C<connect_cached> is like L</connect>, except that the database handle | |||
| 2715 | returned is also | |||
| 2716 | stored in a hash associated with the given parameters. If another call | |||
| 2717 | is made to C<connect_cached> with the same parameter values, then the | |||
| 2718 | corresponding cached C<$dbh> will be returned if it is still valid. | |||
| 2719 | The cached database handle is replaced with a new connection if it | |||
| 2720 | has been disconnected or if the C<ping> method fails. | |||
| 2721 | ||||
| 2722 | That the behaviour of this method differs in several respects from the | |||
| 2723 | behaviour of persistent connections implemented by Apache::DBI. | |||
| 2724 | However, if Apache::DBI is loaded then C<connect_cached> will use it. | |||
| 2725 | ||||
| 2726 | Caching connections can be useful in some applications, but it can | |||
| 2727 | also cause problems, such as too many connections, and so should | |||
| 2728 | be used with care. In particular, avoid changing the attributes of | |||
| 2729 | a database handle created via connect_cached() because it will affect | |||
| 2730 | other code that may be using the same handle. | |||
| 2731 | ||||
| 2732 | Where multiple separate parts of a program are using connect_cached() | |||
| 2733 | to connect to the same database with the same (initial) attributes | |||
| 2734 | it is a good idea to add a private attribute to the connect_cached() | |||
| 2735 | call to effectively limit the scope of the caching. For example: | |||
| 2736 | ||||
| 2737 | DBI->connect_cached(..., { private_foo_cachekey => "Bar", ... }); | |||
| 2738 | ||||
| 2739 | Handles returned from that connect_cached() call will only be returned | |||
| 2740 | by other connect_cached() call elsewhere in the code if those other | |||
| 2741 | calls also pass in the same attribute values, including the private one. | |||
| 2742 | (I've used C<private_foo_cachekey> here as an example, you can use | |||
| 2743 | any attribute name with a C<private_> prefix.) | |||
| 2744 | ||||
| 2745 | Taking that one step further, you can limit a particular connect_cached() | |||
| 2746 | call to return handles unique to that one place in the code by setting the | |||
| 2747 | private attribute to a unique value for that place: | |||
| 2748 | ||||
| 2749 | DBI->connect_cached(..., { private_foo_cachekey => __FILE__.__LINE__, ... }); | |||
| 2750 | ||||
| 2751 | By using a private attribute you still get connection caching for | |||
| 2752 | the individual calls to connect_cached() but, by making separate | |||
| 2753 | database conections for separate parts of the code, the database | |||
| 2754 | handles are isolated from any attribute changes made to other handles. | |||
| 2755 | ||||
| 2756 | The cache can be accessed (and cleared) via the L</CachedKids> attribute: | |||
| 2757 | ||||
| 2758 | my $CachedKids_hashref = $dbh->{Driver}->{CachedKids}; | |||
| 2759 | %$CachedKids_hashref = () if $CachedKids_hashref; | |||
| 2760 | ||||
| 2761 | ||||
| 2762 | =head3 C<available_drivers> | |||
| 2763 | ||||
| 2764 | @ary = DBI->available_drivers; | |||
| 2765 | @ary = DBI->available_drivers($quiet); | |||
| 2766 | ||||
| 2767 | Returns a list of all available drivers by searching for C<DBD::*> modules | |||
| 2768 | through the directories in C<@INC>. By default, a warning is given if | |||
| 2769 | some drivers are hidden by others of the same name in earlier | |||
| 2770 | directories. Passing a true value for C<$quiet> will inhibit the warning. | |||
| 2771 | ||||
| 2772 | =head3 C<installed_drivers> | |||
| 2773 | ||||
| 2774 | %drivers = DBI->installed_drivers(); | |||
| 2775 | ||||
| 2776 | Returns a list of driver name and driver handle pairs for all drivers | |||
| 2777 | 'installed' (loaded) into the current process. The driver name does not | |||
| 2778 | include the 'DBD::' prefix. | |||
| 2779 | ||||
| 2780 | To get a list of all drivers available in your perl instalation you can use | |||
| 2781 | L</available_drivers>. | |||
| 2782 | ||||
| 2783 | Added in DBI 1.49. | |||
| 2784 | ||||
| 2785 | =head3 C<installed_versions> | |||
| 2786 | ||||
| 2787 | DBI->installed_versions; | |||
| 2788 | @ary = DBI->installed_versions; | |||
| 2789 | %hash = DBI->installed_versions; | |||
| 2790 | ||||
| 2791 | Calls available_drivers() and attempts to load each of them in turn | |||
| 2792 | using install_driver(). For each load that succeeds the driver | |||
| 2793 | name and version number are added to a hash. When running under | |||
| 2794 | L<DBI::PurePerl> drivers which appear not be pure-perl are ignored. | |||
| 2795 | ||||
| 2796 | When called in array context the list of successfully loaded drivers | |||
| 2797 | is returned (without the 'DBD::' prefix). | |||
| 2798 | ||||
| 2799 | When called in scalar context a reference to the hash is returned | |||
| 2800 | and the hash will also contain other entries for the C<DBI> version, | |||
| 2801 | C<OS> name, etc. | |||
| 2802 | ||||
| 2803 | When called in a void context the installed_versions() method will | |||
| 2804 | print out a formatted list of the hash contents, one per line. | |||
| 2805 | ||||
| 2806 | Due to the potentially high memory cost and unknown risks of loading | |||
| 2807 | in an unknown number of drivers that just happen to be installed | |||
| 2808 | on the system, this method is not recommended for general use. | |||
| 2809 | Use available_drivers() instead. | |||
| 2810 | ||||
| 2811 | The installed_versions() method is primarily intended as a quick | |||
| 2812 | way to see from the command line what's installed. For example: | |||
| 2813 | ||||
| 2814 | perl -MDBI -e 'DBI->installed_versions' | |||
| 2815 | ||||
| 2816 | The installed_versions() method was added in DBI 1.38. | |||
| 2817 | ||||
| 2818 | =head3 C<data_sources> | |||
| 2819 | ||||
| 2820 | @ary = DBI->data_sources($driver); | |||
| 2821 | @ary = DBI->data_sources($driver, \%attr); | |||
| 2822 | ||||
| 2823 | Returns a list of data sources (databases) available via the named | |||
| 2824 | driver. If C<$driver> is empty or C<undef>, then the value of the | |||
| 2825 | C<DBI_DRIVER> environment variable is used. | |||
| 2826 | ||||
| 2827 | The driver will be loaded if it hasn't been already. Note that if the | |||
| 2828 | driver loading fails then data_sources() I<dies> with an error message | |||
| 2829 | that includes the string "C<install_driver>" and the underlying problem. | |||
| 2830 | ||||
| 2831 | Data sources are returned in a form suitable for passing to the | |||
| 2832 | L</connect> method (that is, they will include the "C<dbi:$driver:>" prefix). | |||
| 2833 | ||||
| 2834 | Note that many drivers have no way of knowing what data sources might | |||
| 2835 | be available for it. These drivers return an empty or incomplete list | |||
| 2836 | or may require driver-specific attributes. | |||
| 2837 | ||||
| 2838 | There is also a data_sources() method defined for database handles. | |||
| 2839 | ||||
| 2840 | ||||
| 2841 | =head3 C<trace> | |||
| 2842 | ||||
| 2843 | DBI->trace($trace_setting) | |||
| 2844 | DBI->trace($trace_setting, $trace_filename) | |||
| 2845 | DBI->trace($trace_setting, $trace_filehandle) | |||
| 2846 | $trace_setting = DBI->trace; | |||
| 2847 | ||||
| 2848 | The C<DBI-E<gt>trace> method sets the I<global default> trace | |||
| 2849 | settings and returns the I<previous> trace settings. It can also | |||
| 2850 | be used to change where the trace output is sent. | |||
| 2851 | ||||
| 2852 | There's a similar method, C<$h-E<gt>trace>, which sets the trace | |||
| 2853 | settings for the specific handle it's called on. | |||
| 2854 | ||||
| 2855 | See the L</TRACING> section for full details about the DBI's powerful | |||
| 2856 | tracing facilities. | |||
| 2857 | ||||
| 2858 | ||||
| 2859 | ||||
| 2860 | =head2 DBI Utility Functions | |||
| 2861 | ||||
| 2862 | In addition to the DBI methods listed in the previous section, | |||
| 2863 | the DBI package also provides several utility functions. | |||
| 2864 | ||||
| 2865 | These can be imported into your code by listing them in | |||
| 2866 | the C<use> statement. For example: | |||
| 2867 | ||||
| 2868 | use DBI qw(neat data_diff); | |||
| 2869 | ||||
| 2870 | Alternatively, all these utility functions (except hash) can be | |||
| 2871 | imported using the C<:utils> import tag. For example: | |||
| 2872 | ||||
| 2873 | use DBI qw(:utils); | |||
| 2874 | ||||
| 2875 | =head3 C<data_string_desc> | |||
| 2876 | ||||
| 2877 | $description = data_string_desc($string); | |||
| 2878 | ||||
| 2879 | Returns an informal description of the string. For example: | |||
| 2880 | ||||
| 2881 | UTF8 off, ASCII, 42 characters 42 bytes | |||
| 2882 | UTF8 off, non-ASCII, 42 characters 42 bytes | |||
| 2883 | UTF8 on, non-ASCII, 4 characters 6 bytes | |||
| 2884 | UTF8 on but INVALID encoding, non-ASCII, 4 characters 6 bytes | |||
| 2885 | UTF8 off, undef | |||
| 2886 | ||||
| 2887 | The initial C<UTF8> on/off refers to Perl's internal SvUTF8 flag. | |||
| 2888 | If $string has the SvUTF8 flag set but the sequence of bytes it | |||
| 2889 | contains are not a valid UTF-8 encoding then data_string_desc() | |||
| 2890 | will report C<UTF8 on but INVALID encoding>. | |||
| 2891 | ||||
| 2892 | The C<ASCII> vs C<non-ASCII> portion shows C<ASCII> if I<all> the | |||
| 2893 | characters in the string are ASCII (have code points <= 127). | |||
| 2894 | ||||
| 2895 | The data_string_desc() function was added in DBI 1.46. | |||
| 2896 | ||||
| 2897 | =head3 C<data_string_diff> | |||
| 2898 | ||||
| 2899 | $diff = data_string_diff($a, $b); | |||
| 2900 | ||||
| 2901 | Returns an informal description of the first character difference | |||
| 2902 | between the strings. If both $a and $b contain the same sequence | |||
| 2903 | of characters then data_string_diff() returns an empty string. | |||
| 2904 | For example: | |||
| 2905 | ||||
| 2906 | Params a & b Result | |||
| 2907 | ------------ ------ | |||
| 2908 | 'aaa', 'aaa' '' | |||
| 2909 | 'aaa', 'abc' 'Strings differ at index 2: a[2]=a, b[2]=b' | |||
| 2910 | 'aaa', undef 'String b is undef, string a has 3 characters' | |||
| 2911 | 'aaa', 'aa' 'String b truncated after 2 characters' | |||
| 2912 | ||||
| 2913 | Unicode characters are reported in C<\x{XXXX}> format. Unicode | |||
| 2914 | code points in the range U+0800 to U+08FF are unassigned and most | |||
| 2915 | likely to occur due to double-encoding. Characters in this range | |||
| 2916 | are reported as C<\x{08XX}='C'> where C<C> is the corresponding | |||
| 2917 | latin-1 character. | |||
| 2918 | ||||
| 2919 | The data_string_diff() function only considers logical I<characters> | |||
| 2920 | and not the underlying encoding. See L</data_diff> for an alternative. | |||
| 2921 | ||||
| 2922 | The data_string_diff() function was added in DBI 1.46. | |||
| 2923 | ||||
| 2924 | =head3 C<data_diff> | |||
| 2925 | ||||
| 2926 | $diff = data_diff($a, $b); | |||
| 2927 | $diff = data_diff($a, $b, $logical); | |||
| 2928 | ||||
| 2929 | Returns an informal description of the difference between two strings. | |||
| 2930 | It calls L</data_string_desc> and L</data_string_diff> | |||
| 2931 | and returns the combined results as a multi-line string. | |||
| 2932 | ||||
| 2933 | For example, C<data_diff("abc", "ab\x{263a}")> will return: | |||
| 2934 | ||||
| 2935 | a: UTF8 off, ASCII, 3 characters 3 bytes | |||
| 2936 | b: UTF8 on, non-ASCII, 3 characters 5 bytes | |||
| 2937 | Strings differ at index 2: a[2]=c, b[2]=\x{263A} | |||
| 2938 | ||||
| 2939 | If $a and $b are identical in both the characters they contain I<and> | |||
| 2940 | their physical encoding then data_diff() returns an empty string. | |||
| 2941 | If $logical is true then physical encoding differences are ignored | |||
| 2942 | (but are still reported if there is a difference in the characters). | |||
| 2943 | ||||
| 2944 | The data_diff() function was added in DBI 1.46. | |||
| 2945 | ||||
| 2946 | =head3 C<neat> | |||
| 2947 | ||||
| 2948 | $str = neat($value); | |||
| 2949 | $str = neat($value, $maxlen); | |||
| 2950 | ||||
| 2951 | Return a string containing a neat (and tidy) representation of the | |||
| 2952 | supplied value. | |||
| 2953 | ||||
| 2954 | Strings will be quoted, although internal quotes will I<not> be escaped. | |||
| 2955 | Values known to be numeric will be unquoted. Undefined (NULL) values | |||
| 2956 | will be shown as C<undef> (without quotes). | |||
| 2957 | ||||
| 2958 | If the string is flagged internally as utf8 then double quotes will | |||
| 2959 | be used, otherwise single quotes are used and unprintable characters | |||
| 2960 | will be replaced by dot (.). | |||
| 2961 | ||||
| 2962 | For result strings longer than C<$maxlen> the result string will be | |||
| 2963 | truncated to C<$maxlen-4> and "C<...'>" will be appended. If C<$maxlen> is 0 | |||
| 2964 | or C<undef>, it defaults to C<$DBI::neat_maxlen> which, in turn, defaults to 400. | |||
| 2965 | ||||
| 2966 | This function is designed to format values for human consumption. | |||
| 2967 | It is used internally by the DBI for L</trace> output. It should | |||
| 2968 | typically I<not> be used for formatting values for database use. | |||
| 2969 | (See also L</quote>.) | |||
| 2970 | ||||
| 2971 | =head3 C<neat_list> | |||
| 2972 | ||||
| 2973 | $str = neat_list(\@listref, $maxlen, $field_sep); | |||
| 2974 | ||||
| 2975 | Calls C<neat> on each element of the list and returns a string | |||
| 2976 | containing the results joined with C<$field_sep>. C<$field_sep> defaults | |||
| 2977 | to C<", ">. | |||
| 2978 | ||||
| 2979 | =head3 C<looks_like_number> | |||
| 2980 | ||||
| 2981 | @bool = looks_like_number(@array); | |||
| 2982 | ||||
| 2983 | Returns true for each element that looks like a number. | |||
| 2984 | Returns false for each element that does not look like a number. | |||
| 2985 | Returns C<undef> for each element that is undefined or empty. | |||
| 2986 | ||||
| 2987 | =head3 C<hash> | |||
| 2988 | ||||
| 2989 | $hash_value = DBI::hash($buffer, $type); | |||
| 2990 | ||||
| 2991 | Return a 32-bit integer 'hash' value corresponding to the contents of $buffer. | |||
| 2992 | The $type parameter selects which kind of hash algorithm should be used. | |||
| 2993 | ||||
| 2994 | For the technically curious, type 0 (which is the default if $type | |||
| 2995 | isn't specified) is based on the Perl 5.1 hash except that the value | |||
| 2996 | is forced to be negative (for obscure historical reasons). | |||
| 2997 | Type 1 is the better "Fowler / Noll / Vo" (FNV) hash. See | |||
| 2998 | L<http://www.isthe.com/chongo/tech/comp/fnv/> for more information. | |||
| 2999 | Both types are implemented in C and are very fast. | |||
| 3000 | ||||
| 3001 | This function doesn't have much to do with databases, except that | |||
| 3002 | it can be handy to store hash values in a database. | |||
| 3003 | ||||
| 3004 | ||||
| 3005 | =head2 DBI Dynamic Attributes | |||
| 3006 | ||||
| 3007 | Dynamic attributes are always associated with the I<last handle used> | |||
| 3008 | (that handle is represented by C<$h> in the descriptions below). | |||
| 3009 | ||||
| 3010 | Where an attribute is equivalent to a method call, then refer to | |||
| 3011 | the method call for all related documentation. | |||
| 3012 | ||||
| 3013 | Warning: these attributes are provided as a convenience but they | |||
| 3014 | do have limitations. Specifically, they have a short lifespan: | |||
| 3015 | because they are associated with | |||
| 3016 | the last handle used, they should only be used I<immediately> after | |||
| 3017 | calling the method that "sets" them. | |||
| 3018 | If in any doubt, use the corresponding method call. | |||
| 3019 | ||||
| 3020 | =head3 C<$DBI::err> | |||
| 3021 | ||||
| 3022 | Equivalent to C<$h-E<gt>err>. | |||
| 3023 | ||||
| 3024 | =head3 C<$DBI::errstr> | |||
| 3025 | ||||
| 3026 | Equivalent to C<$h-E<gt>errstr>. | |||
| 3027 | ||||
| 3028 | =head3 C<$DBI::state> | |||
| 3029 | ||||
| 3030 | Equivalent to C<$h-E<gt>state>. | |||
| 3031 | ||||
| 3032 | =head3 C<$DBI::rows> | |||
| 3033 | ||||
| 3034 | Equivalent to C<$h-E<gt>rows>. Please refer to the documentation | |||
| 3035 | for the L</rows> method. | |||
| 3036 | ||||
| 3037 | =head3 C<$DBI::lasth> | |||
| 3038 | ||||
| 3039 | Returns the DBI object handle used for the most recent DBI method call. | |||
| 3040 | If the last DBI method call was a DESTROY then $DBI::lasth will return | |||
| 3041 | the handle of the parent of the destroyed handle, if there is one. | |||
| 3042 | ||||
| 3043 | ||||
| 3044 | =head1 METHODS COMMON TO ALL HANDLES | |||
| 3045 | ||||
| 3046 | The following methods can be used by all types of DBI handles. | |||
| 3047 | ||||
| 3048 | =head3 C<err> | |||
| 3049 | ||||
| 3050 | $rv = $h->err; | |||
| 3051 | ||||
| 3052 | Returns the I<native> database engine error code from the last driver | |||
| 3053 | method called. The code is typically an integer but you should not | |||
| 3054 | assume that. | |||
| 3055 | ||||
| 3056 | The DBI resets $h->err to undef before almost all DBI method calls, so the | |||
| 3057 | value only has a short lifespan. Also, for most drivers, the statement | |||
| 3058 | handles share the same error variable as the parent database handle, | |||
| 3059 | so calling a method on one handle may reset the error on the | |||
| 3060 | related handles. | |||
| 3061 | ||||
| 3062 | (Methods which don't reset err before being called include err() and errstr(), | |||
| 3063 | obviously, state(), rows(), func(), trace(), trace_msg(), ping(), and the | |||
| 3064 | tied hash attribute FETCH() and STORE() methods.) | |||
| 3065 | ||||
| 3066 | If you need to test for specific error conditions I<and> have your program be | |||
| 3067 | portable to different database engines, then you'll need to determine what the | |||
| 3068 | corresponding error codes are for all those engines and test for all of them. | |||
| 3069 | ||||
| 3070 | The DBI uses the value of $DBI::stderr as the C<err> value for internal errors. | |||
| 3071 | Drivers should also do likewise. The default value for $DBI::stderr is 2000000000. | |||
| 3072 | ||||
| 3073 | A driver may return C<0> from err() to indicate a warning condition | |||
| 3074 | after a method call. Similarly, a driver may return an empty string | |||
| 3075 | to indicate a 'success with information' condition. In both these | |||
| 3076 | cases the value is false but not undef. The errstr() and state() | |||
| 3077 | methods may be used to retrieve extra information in these cases. | |||
| 3078 | ||||
| 3079 | See L</set_err> for more information. | |||
| 3080 | ||||
| 3081 | =head3 C<errstr> | |||
| 3082 | ||||
| 3083 | $str = $h->errstr; | |||
| 3084 | ||||
| 3085 | Returns the native database engine error message from the last DBI | |||
| 3086 | method called. This has the same lifespan issues as the L</err> method | |||
| 3087 | described above. | |||
| 3088 | ||||
| 3089 | The returned string may contain multiple messages separated by | |||
| 3090 | newline characters. | |||
| 3091 | ||||
| 3092 | The errstr() method should not be used to test for errors, use err() | |||
| 3093 | for that, because drivers may return 'success with information' or | |||
| 3094 | warning messages via errstr() for methods that have not 'failed'. | |||
| 3095 | ||||
| 3096 | See L</set_err> for more information. | |||
| 3097 | ||||
| 3098 | =head3 C<state> | |||
| 3099 | ||||
| 3100 | $str = $h->state; | |||
| 3101 | ||||
| 3102 | Returns a state code in the standard SQLSTATE five character format. | |||
| 3103 | Note that the specific success code C<00000> is translated to any empty string | |||
| 3104 | (false). If the driver does not support SQLSTATE (and most don't), | |||
| 3105 | then state() will return C<S1000> (General Error) for all errors. | |||
| 3106 | ||||
| 3107 | The driver is free to return any value via C<state>, e.g., warning | |||
| 3108 | codes, even if it has not declared an error by returning a true value | |||
| 3109 | via the L</err> method described above. | |||
| 3110 | ||||
| 3111 | The state() method should not be used to test for errors, use err() | |||
| 3112 | for that, because drivers may return a 'success with information' or | |||
| 3113 | warning state code via state() for methods that have not 'failed'. | |||
| 3114 | ||||
| 3115 | =head3 C<set_err> | |||
| 3116 | ||||
| 3117 | $rv = $h->set_err($err, $errstr); | |||
| 3118 | $rv = $h->set_err($err, $errstr, $state); | |||
| 3119 | $rv = $h->set_err($err, $errstr, $state, $method); | |||
| 3120 | $rv = $h->set_err($err, $errstr, $state, $method, $rv); | |||
| 3121 | ||||
| 3122 | Set the C<err>, C<errstr>, and C<state> values for the handle. | |||
| 3123 | This method is typically only used by DBI drivers and DBI subclasses. | |||
| 3124 | ||||
| 3125 | If the L</HandleSetErr> attribute holds a reference to a subroutine | |||
| 3126 | it is called first. The subroutine can alter the $err, $errstr, $state, | |||
| 3127 | and $method values. See L</HandleSetErr> for full details. | |||
| 3128 | If the subroutine returns a true value then the handle C<err>, | |||
| 3129 | C<errstr>, and C<state> values are not altered and set_err() returns | |||
| 3130 | an empty list (it normally returns $rv which defaults to undef, see below). | |||
| 3131 | ||||
| 3132 | Setting C<err> to a I<true> value indicates an error and will trigger | |||
| 3133 | the normal DBI error handling mechanisms, such as C<RaiseError> and | |||
| 3134 | C<HandleError>, if they are enabled, when execution returns from | |||
| 3135 | the DBI back to the application. | |||
| 3136 | ||||
| 3137 | Setting C<err> to C<""> indicates an 'information' state, and setting | |||
| 3138 | it to C<"0"> indicates a 'warning' state. Setting C<err> to C<undef> | |||
| 3139 | also sets C<errstr> to undef, and C<state> to C<"">, irrespective | |||
| 3140 | of the values of the $errstr and $state parameters. | |||
| 3141 | ||||
| 3142 | The $method parameter provides an alternate method name for the | |||
| 3143 | C<RaiseError>/C<PrintError>/C<PrintWarn> error string instead of | |||
| 3144 | the fairly unhelpful 'C<set_err>'. | |||
| 3145 | ||||
| 3146 | The C<set_err> method normally returns undef. The $rv parameter | |||
| 3147 | provides an alternate return value. | |||
| 3148 | ||||
| 3149 | Some special rules apply if the C<err> or C<errstr> | |||
| 3150 | values for the handle are I<already> set... | |||
| 3151 | ||||
| 3152 | If C<errstr> is true then: "C< [err was %s now %s]>" is appended if $err is | |||
| 3153 | true and C<err> is already true and the new err value differs from the original | |||
| 3154 | one. Similarly "C< [state was %s now %s]>" is appended if $state is true and C<state> is | |||
| 3155 | already true and the new state value differs from the original one. Finally | |||
| 3156 | "C<\n>" and the new $errstr are appended if $errstr differs from the existing | |||
| 3157 | errstr value. Obviously the C<%s>'s above are replaced by the corresponding values. | |||
| 3158 | ||||
| 3159 | The handle C<err> value is set to $err if: $err is true; or handle | |||
| 3160 | C<err> value is undef; or $err is defined and the length is greater | |||
| 3161 | than the handle C<err> length. The effect is that an 'information' | |||
| 3162 | state only overrides undef; a 'warning' overrides undef or 'information', | |||
| 3163 | and an 'error' state overrides anything. | |||
| 3164 | ||||
| 3165 | The handle C<state> value is set to $state if $state is true and | |||
| 3166 | the handle C<err> value was set (by the rules above). | |||
| 3167 | ||||
| 3168 | Support for warning and information states was added in DBI 1.41. | |||
| 3169 | ||||
| 3170 | =head3 C<trace> | |||
| 3171 | ||||
| 3172 | $h->trace($trace_settings); | |||
| 3173 | $h->trace($trace_settings, $trace_filename); | |||
| 3174 | $trace_settings = $h->trace; | |||
| 3175 | ||||
| 3176 | The trace() method is used to alter the trace settings for a handle | |||
| 3177 | (and any future children of that handle). It can also be used to | |||
| 3178 | change where the trace output is sent. | |||
| 3179 | ||||
| 3180 | There's a similar method, C<DBI-E<gt>trace>, which sets the global | |||
| 3181 | default trace settings. | |||
| 3182 | ||||
| 3183 | See the L</TRACING> section for full details about the DBI's powerful | |||
| 3184 | tracing facilities. | |||
| 3185 | ||||
| 3186 | =head3 C<trace_msg> | |||
| 3187 | ||||
| 3188 | $h->trace_msg($message_text); | |||
| 3189 | $h->trace_msg($message_text, $min_level); | |||
| 3190 | ||||
| 3191 | Writes C<$message_text> to the trace file if the trace level is | |||
| 3192 | greater than or equal to $min_level (which defaults to 1). | |||
| 3193 | Can also be called as C<DBI-E<gt>trace_msg($msg)>. | |||
| 3194 | ||||
| 3195 | See L</TRACING> for more details. | |||
| 3196 | ||||
| 3197 | =head3 C<func> | |||
| 3198 | ||||
| 3199 | $h->func(@func_arguments, $func_name) or die ...; | |||
| 3200 | ||||
| 3201 | The C<func> method can be used to call private non-standard and | |||
| 3202 | non-portable methods implemented by the driver. Note that the function | |||
| 3203 | name is given as the I<last> argument. | |||
| 3204 | ||||
| 3205 | It's also important to note that the func() method does not clear | |||
| 3206 | a previous error ($DBI::err etc.) and it does not trigger automatic | |||
| 3207 | error detection (RaiseError etc.) so you must check the return | |||
| 3208 | status and/or $h->err to detect errors. | |||
| 3209 | ||||
| 3210 | (This method is not directly related to calling stored procedures. | |||
| 3211 | Calling stored procedures is currently not defined by the DBI. | |||
| 3212 | Some drivers, such as DBD::Oracle, support it in non-portable ways. | |||
| 3213 | See driver documentation for more details.) | |||
| 3214 | ||||
| 3215 | See also install_method() in L<DBI::DBD> for how you can avoid needing to | |||
| 3216 | use func() and gain direct access to driver-private methods. | |||
| 3217 | ||||
| 3218 | =head3 C<can> | |||
| 3219 | ||||
| 3220 | $is_implemented = $h->can($method_name); | |||
| 3221 | ||||
| 3222 | Returns true if $method_name is implemented by the driver or a | |||
| 3223 | default method is provided by the DBI. | |||
| 3224 | It returns false where a driver hasn't implemented a method and the | |||
| 3225 | default method is provided by the DBI is just an empty stub. | |||
| 3226 | ||||
| 3227 | =head3 C<parse_trace_flags> | |||
| 3228 | ||||
| 3229 | $trace_settings_integer = $h->parse_trace_flags($trace_settings); | |||
| 3230 | ||||
| 3231 | Parses a string containing trace settings and returns the corresponding | |||
| 3232 | integer value used internally by the DBI and drivers. | |||
| 3233 | ||||
| 3234 | The $trace_settings argument is a string containing a trace level | |||
| 3235 | between 0 and 15 and/or trace flag names separated by vertical bar | |||
| 3236 | ("C<|>") or comma ("C<,>") characters. For example: C<"SQL|3|foo">. | |||
| 3237 | ||||
| 3238 | It uses the parse_trace_flag() method, described below, to process | |||
| 3239 | the individual trage flag names. | |||
| 3240 | ||||
| 3241 | The parse_trace_flags() method was added in DBI 1.42. | |||
| 3242 | ||||
| 3243 | =head3 C<parse_trace_flag> | |||
| 3244 | ||||
| 3245 | $bit_flag = $h->parse_trace_flag($trace_flag_name); | |||
| 3246 | ||||
| 3247 | Returns the bit flag corresponding to the trace flag name in | |||
| 3248 | $trace_flag_name. Drivers are expected to override this method and | |||
| 3249 | check if $trace_flag_name is a driver specific trace flags and, if | |||
| 3250 | not, then call the DBIs default parse_trace_flag(). | |||
| 3251 | ||||
| 3252 | The parse_trace_flag() method was added in DBI 1.42. | |||
| 3253 | ||||
| 3254 | =head3 C<private_attribute_info> | |||
| 3255 | ||||
| 3256 | $hash_ref = $h->private_attribute_info(); | |||
| 3257 | ||||
| 3258 | Returns a reference to a hash whose keys are the names of driver-private | |||
| 3259 | attributes available for the kind of handle (driver, database, statement) | |||
| 3260 | that the method was called on. | |||
| 3261 | ||||
| 3262 | For example, the return value when called with a DBD::Sybase $dbh could look like this: | |||
| 3263 | ||||
| 3264 | { | |||
| 3265 | syb_dynamic_supported => undef, | |||
| 3266 | syb_oc_version => undef, | |||
| 3267 | syb_server_version => undef, | |||
| 3268 | syb_server_version_string => undef, | |||
| 3269 | } | |||
| 3270 | ||||
| 3271 | and when called with a DBD::Sybase $sth they could look like this: | |||
| 3272 | ||||
| 3273 | { | |||
| 3274 | syb_types => undef, | |||
| 3275 | syb_proc_status => undef, | |||
| 3276 | syb_result_type => undef, | |||
| 3277 | } | |||
| 3278 | ||||
| 3279 | The values should be undef. Meanings may be assigned to particular values in future. | |||
| 3280 | ||||
| 3281 | =head3 C<swap_inner_handle> | |||
| 3282 | ||||
| 3283 | $rc = $h1->swap_inner_handle( $h2 ); | |||
| 3284 | $rc = $h1->swap_inner_handle( $h2, $allow_reparent ); | |||
| 3285 | ||||
| 3286 | Brain transplants for handles. You don't need to know about this | |||
| 3287 | unless you want to become a handle surgeon. | |||
| 3288 | ||||
| 3289 | A DBI handle is a reference to a tied hash. A tied hash has an | |||
| 3290 | I<inner> hash that actually holds the contents. The swap_inner_handle() | |||
| 3291 | method swaps the inner hashes between two handles. The $h1 and $h2 | |||
| 3292 | handles still point to the same tied hashes, but what those hashes | |||
| 3293 | are tied to has been swapped. In effect $h1 I<becomes> $h2 and | |||
| 3294 | vice-versa. This is powerful stuff, expect problems. Use with care. | |||
| 3295 | ||||
| 3296 | As a small safety measure, the two handles, $h1 and $h2, have to | |||
| 3297 | share the same parent unless $allow_reparent is true. | |||
| 3298 | ||||
| 3299 | The swap_inner_handle() method was added in DBI 1.44. | |||
| 3300 | ||||
| 3301 | Here's a quick kind of 'diagram' as a worked example to help think about what's | |||
| 3302 | happening: | |||
| 3303 | ||||
| 3304 | Original state: | |||
| 3305 | dbh1o -> dbh1i | |||
| 3306 | sthAo -> sthAi(dbh1i) | |||
| 3307 | dbh2o -> dbh2i | |||
| 3308 | ||||
| 3309 | swap_inner_handle dbh1o with dbh2o: | |||
| 3310 | dbh2o -> dbh1i | |||
| 3311 | sthAo -> sthAi(dbh1i) | |||
| 3312 | dbh1o -> dbh2i | |||
| 3313 | ||||
| 3314 | create new sth from dbh1o: | |||
| 3315 | dbh2o -> dbh1i | |||
| 3316 | sthAo -> sthAi(dbh1i) | |||
| 3317 | dbh1o -> dbh2i | |||
| 3318 | sthBo -> sthBi(dbh2i) | |||
| 3319 | ||||
| 3320 | swap_inner_handle sthAo with sthBo: | |||
| 3321 | dbh2o -> dbh1i | |||
| 3322 | sthBo -> sthAi(dbh1i) | |||
| 3323 | dbh1o -> dbh2i | |||
| 3324 | sthAo -> sthBi(dbh2i) | |||
| 3325 | ||||
| 3326 | ||||
| 3327 | =head1 ATTRIBUTES COMMON TO ALL HANDLES | |||
| 3328 | ||||
| 3329 | These attributes are common to all types of DBI handles. | |||
| 3330 | ||||
| 3331 | Some attributes are inherited by child handles. That is, the value | |||
| 3332 | of an inherited attribute in a newly created statement handle is the | |||
| 3333 | same as the value in the parent database handle. Changes to attributes | |||
| 3334 | in the new statement handle do not affect the parent database handle | |||
| 3335 | and changes to the database handle do not affect existing statement | |||
| 3336 | handles, only future ones. | |||
| 3337 | ||||
| 3338 | Attempting to set or get the value of an unknown attribute generates a warning, | |||
| 3339 | except for private driver specific attributes (which all have names | |||
| 3340 | starting with a lowercase letter). | |||
| 3341 | ||||
| 3342 | Example: | |||
| 3343 | ||||
| 3344 | $h->{AttributeName} = ...; # set/write | |||
| 3345 | ... = $h->{AttributeName}; # get/read | |||
| 3346 | ||||
| 3347 | =head3 C<Warn> (boolean, inherited) | |||
| 3348 | ||||
| 3349 | The C<Warn> attribute enables useful warnings for certain bad | |||
| 3350 | practices. It is enabled by default and should only be disabled in | |||
| 3351 | rare circumstances. Since warnings are generated using the Perl | |||
| 3352 | C<warn> function, they can be intercepted using the Perl C<$SIG{__WARN__}> | |||
| 3353 | hook. | |||
| 3354 | ||||
| 3355 | The C<Warn> attribute is not related to the C<PrintWarn> attribute. | |||
| 3356 | ||||
| 3357 | =head3 C<Active> (boolean, read-only) | |||
| 3358 | ||||
| 3359 | The C<Active> attribute is true if the handle object is "active". This is rarely used in | |||
| 3360 | applications. The exact meaning of active is somewhat vague at the | |||
| 3361 | moment. For a database handle it typically means that the handle is | |||
| 3362 | connected to a database (C<$dbh-E<gt>disconnect> sets C<Active> off). For | |||
| 3363 | a statement handle it typically means that the handle is a C<SELECT> | |||
| 3364 | that may have more data to fetch. (Fetching all the data or calling C<$sth-E<gt>finish> | |||
| 3365 | sets C<Active> off.) | |||
| 3366 | ||||
| 3367 | =head3 C<Executed> (boolean) | |||
| 3368 | ||||
| 3369 | The C<Executed> attribute is true if the handle object has been "executed". | |||
| 3370 | Currently only the $dbh do() method and the $sth execute(), execute_array(), | |||
| 3371 | and execute_for_fetch() methods set the C<Executed> attribute. | |||
| 3372 | ||||
| 3373 | When it's set on a handle it is also set on the parent handle at the | |||
| 3374 | same time. So calling execute() on a $sth also sets the C<Executed> | |||
| 3375 | attribute on the parent $dbh. | |||
| 3376 | ||||
| 3377 | The C<Executed> attribute for a database handle is cleared by the commit() and | |||
| 3378 | rollback() methods (even if they fail). The C<Executed> attribute of a | |||
| 3379 | statement handle is not cleared by the DBI under any circumstances and so acts | |||
| 3380 | as a permanent record of whether the statement handle was ever used. | |||
| 3381 | ||||
| 3382 | The C<Executed> attribute was added in DBI 1.41. | |||
| 3383 | ||||
| 3384 | =head3 C<Kids> (integer, read-only) | |||
| 3385 | ||||
| 3386 | For a driver handle, C<Kids> is the number of currently existing database | |||
| 3387 | handles that were created from that driver handle. For a database | |||
| 3388 | handle, C<Kids> is the number of currently existing statement handles that | |||
| 3389 | were created from that database handle. | |||
| 3390 | For a statement handle, the value is zero. | |||
| 3391 | ||||
| 3392 | =head3 C<ActiveKids> (integer, read-only) | |||
| 3393 | ||||
| 3394 | Like C<Kids>, but only counting those that are C<Active> (as above). | |||
| 3395 | ||||
| 3396 | =head3 C<CachedKids> (hash ref) | |||
| 3397 | ||||
| 3398 | For a database handle, C<CachedKids> returns a reference to the cache (hash) of | |||
| 3399 | statement handles created by the L</prepare_cached> method. For a | |||
| 3400 | driver handle, returns a reference to the cache (hash) of | |||
| 3401 | database handles created by the L</connect_cached> method. | |||
| 3402 | ||||
| 3403 | =head3 C<Type> (scalar, read-only) | |||
| 3404 | ||||
| 3405 | The C<Type> attribute identifies the type of a DBI handle. Returns | |||
| 3406 | "dr" for driver handles, "db" for database handles and "st" for | |||
| 3407 | statement handles. | |||
| 3408 | ||||
| 3409 | =head3 C<ChildHandles> (array ref) | |||
| 3410 | ||||
| 3411 | The ChildHandles attribute contains a reference to an array of all the | |||
| 3412 | handles created by this handle which are still accessible. The | |||
| 3413 | contents of the array are weak-refs and will become undef when the | |||
| 3414 | handle goes out of scope. | |||
| 3415 | ||||
| 3416 | C<ChildHandles> returns undef if your perl version does not support weak | |||
| 3417 | references (check the L<Scalar::Util|Scalar::Util> module). The referenced | |||
| 3418 | array returned should be treated as read-only. | |||
| 3419 | ||||
| 3420 | For example, to enumerate all driver handles, database handles and | |||
| 3421 | statement handles: | |||
| 3422 | ||||
| 3423 | sub show_child_handles { | |||
| 3424 | my ($h, $level) = @_; | |||
| 3425 | printf "%sh %s %s\n", $h->{Type}, "\t" x $level, $h; | |||
| 3426 | show_child_handles($_, $level + 1) | |||
| 3427 | for (grep { defined } @{$h->{ChildHandles}}); | |||
| 3428 | } | |||
| 3429 | ||||
| 3430 | my %drivers = DBI->installed_drivers(); | |||
| 3431 | show_child_handles($_, 0) for (values %drivers); | |||
| 3432 | ||||
| 3433 | =head3 C<CompatMode> (boolean, inherited) | |||
| 3434 | ||||
| 3435 | The C<CompatMode> attribute is used by emulation layers (such as | |||
| 3436 | Oraperl) to enable compatible behaviour in the underlying driver | |||
| 3437 | (e.g., DBD::Oracle) for this handle. Not normally set by application code. | |||
| 3438 | ||||
| 3439 | It also has the effect of disabling the 'quick FETCH' of attribute | |||
| 3440 | values from the handles attribute cache. So all attribute values | |||
| 3441 | are handled by the drivers own FETCH method. This makes them slightly | |||
| 3442 | slower but is useful for special-purpose drivers like DBD::Multiplex. | |||
| 3443 | ||||
| 3444 | =head3 C<InactiveDestroy> (boolean) | |||
| 3445 | ||||
| 3446 | The default value, false, means a handle will be fully destroyed | |||
| 3447 | as normal when the last reference to it is removed, just as you'd expect. | |||
| 3448 | ||||
| 3449 | If set true then the handle will be treated by the DESTROY as if it was no | |||
| 3450 | longer Active, and so the I<database engine> related effects of DESTROYing a | |||
| 3451 | handle will be skipped. | |||
| 3452 | ||||
| 3453 | Think of the name as meaning 'treat the handle as not-Active in the DESTROY | |||
| 3454 | method'. | |||
| 3455 | ||||
| 3456 | For a database handle, this attribute does not disable an I<explicit> | |||
| 3457 | call to the disconnect method, only the implicit call from DESTROY | |||
| 3458 | that happens if the handle is still marked as C<Active>. | |||
| 3459 | ||||
| 3460 | This attribute is specifically designed for use in Unix applications | |||
| 3461 | that "fork" child processes. Either the parent or the child process, | |||
| 3462 | but not both, should set C<InactiveDestroy> true on all their shared handles. | |||
| 3463 | (Note that some databases, including Oracle, don't support passing a | |||
| 3464 | database connection across a fork.) | |||
| 3465 | ||||
| 3466 | To help tracing applications using fork the process id is shown in | |||
| 3467 | the trace log whenever a DBI or handle trace() method is called. | |||
| 3468 | The process id also shown for I<every> method call if the DBI trace | |||
| 3469 | level (not handle trace level) is set high enough to show the trace | |||
| 3470 | from the DBI's method dispatcher, e.g. >= 9. | |||
| 3471 | ||||
| 3472 | =head3 C<PrintWarn> (boolean, inherited) | |||
| 3473 | ||||
| 3474 | The C<PrintWarn> attribute controls the printing of warnings recorded | |||
| 3475 | by the driver. When set to a true value the DBI will check method | |||
| 3476 | calls to see if a warning condition has been set. If so, the DBI | |||
| 3477 | will effectively do a C<warn("$class $method warning: $DBI::errstr")> | |||
| 3478 | where C<$class> is the driver class and C<$method> is the name of | |||
| 3479 | the method which failed. E.g., | |||
| 3480 | ||||
| 3481 | DBD::Oracle::db execute warning: ... warning text here ... | |||
| 3482 | ||||
| 3483 | By default, C<DBI-E<gt>connect> sets C<PrintWarn> "on" if $^W is true, | |||
| 3484 | i.e., perl is running with warnings enabled. | |||
| 3485 | ||||
| 3486 | If desired, the warnings can be caught and processed using a C<$SIG{__WARN__}> | |||
| 3487 | handler or modules like CGI::Carp and CGI::ErrorWrap. | |||
| 3488 | ||||
| 3489 | See also L</set_err> for how warnings are recorded and L</HandleSetErr> | |||
| 3490 | for how to influence it. | |||
| 3491 | ||||
| 3492 | Fetching the full details of warnings can require an extra round-trip | |||
| 3493 | to the database server for some drivers. In which case the driver | |||
| 3494 | may opt to only fetch the full details of warnings if the C<PrintWarn> | |||
| 3495 | attribute is true. If C<PrintWarn> is false then these drivers should | |||
| 3496 | still indicate the fact that there were warnings by setting the | |||
| 3497 | warning string to, for example: "3 warnings". | |||
| 3498 | ||||
| 3499 | =head3 C<PrintError> (boolean, inherited) | |||
| 3500 | ||||
| 3501 | The C<PrintError> attribute can be used to force errors to generate warnings (using | |||
| 3502 | C<warn>) in addition to returning error codes in the normal way. When set | |||
| 3503 | "on", any method which results in an error occuring will cause the DBI to | |||
| 3504 | effectively do a C<warn("$class $method failed: $DBI::errstr")> where C<$class> | |||
| 3505 | is the driver class and C<$method> is the name of the method which failed. E.g., | |||
| 3506 | ||||
| 3507 | DBD::Oracle::db prepare failed: ... error text here ... | |||
| 3508 | ||||
| 3509 | By default, C<DBI-E<gt>connect> sets C<PrintError> "on". | |||
| 3510 | ||||
| 3511 | If desired, the warnings can be caught and processed using a C<$SIG{__WARN__}> | |||
| 3512 | handler or modules like CGI::Carp and CGI::ErrorWrap. | |||
| 3513 | ||||
| 3514 | =head3 C<RaiseError> (boolean, inherited) | |||
| 3515 | ||||
| 3516 | The C<RaiseError> attribute can be used to force errors to raise exceptions rather | |||
| 3517 | than simply return error codes in the normal way. It is "off" by default. | |||
| 3518 | When set "on", any method which results in an error will cause | |||
| 3519 | the DBI to effectively do a C<die("$class $method failed: $DBI::errstr")>, | |||
| 3520 | where C<$class> is the driver class and C<$method> is the name of the method | |||
| 3521 | that failed. E.g., | |||
| 3522 | ||||
| 3523 | DBD::Oracle::db prepare failed: ... error text here ... | |||
| 3524 | ||||
| 3525 | If you turn C<RaiseError> on then you'd normally turn C<PrintError> off. | |||
| 3526 | If C<PrintError> is also on, then the C<PrintError> is done first (naturally). | |||
| 3527 | ||||
| 3528 | Typically C<RaiseError> is used in conjunction with C<eval { ... }> | |||
| 3529 | to catch the exception that's been thrown and followed by an | |||
| 3530 | C<if ($@) { ... }> block to handle the caught exception. | |||
| 3531 | For example: | |||
| 3532 | ||||
| 3533 | eval { | |||
| 3534 | ... | |||
| 3535 | $sth->execute(); | |||
| 3536 | ... | |||
| 3537 | }; | |||
| 3538 | if ($@) { | |||
| 3539 | # $sth->err and $DBI::err will be true if error was from DBI | |||
| 3540 | warn $@; # print the error | |||
| 3541 | ... # do whatever you need to deal with the error | |||
| 3542 | } | |||
| 3543 | ||||
| 3544 | In that eval block the $DBI::lasth variable can be useful for | |||
| 3545 | diagnosis and reporting if you can't be sure which handle triggered | |||
| 3546 | the error. For example, $DBI::lasth->{Type} and $DBI::lasth->{Statement}. | |||
| 3547 | ||||
| 3548 | See also L</Transactions>. | |||
| 3549 | ||||
| 3550 | If you want to temporarily turn C<RaiseError> off (inside a library function | |||
| 3551 | that is likely to fail, for example), the recommended way is like this: | |||
| 3552 | ||||
| 3553 | { | |||
| 3554 | local $h->{RaiseError}; # localize and turn off for this block | |||
| 3555 | ... | |||
| 3556 | } | |||
| 3557 | ||||
| 3558 | The original value will automatically and reliably be restored by Perl, | |||
| 3559 | regardless of how the block is exited. | |||
| 3560 | The same logic applies to other attributes, including C<PrintError>. | |||
| 3561 | ||||
| 3562 | =head3 C<HandleError> (code ref, inherited) | |||
| 3563 | ||||
| 3564 | The C<HandleError> attribute can be used to provide your own alternative behaviour | |||
| 3565 | in case of errors. If set to a reference to a subroutine then that | |||
| 3566 | subroutine is called when an error is detected (at the same point that | |||
| 3567 | C<RaiseError> and C<PrintError> are handled). | |||
| 3568 | ||||
| 3569 | The subroutine is called with three parameters: the error message | |||
| 3570 | string that C<RaiseError> and C<PrintError> would use, | |||
| 3571 | the DBI handle being used, and the first value being returned by | |||
| 3572 | the method that failed (typically undef). | |||
| 3573 | ||||
| 3574 | If the subroutine returns a false value then the C<RaiseError> | |||
| 3575 | and/or C<PrintError> attributes are checked and acted upon as normal. | |||
| 3576 | ||||
| 3577 | For example, to C<die> with a full stack trace for any error: | |||
| 3578 | ||||
| 3579 | use Carp; | |||
| 3580 | $h->{HandleError} = sub { confess(shift) }; | |||
| 3581 | ||||
| 3582 | Or to turn errors into exceptions: | |||
| 3583 | ||||
| 3584 | use Exception; # or your own favourite exception module | |||
| 3585 | $h->{HandleError} = sub { Exception->new('DBI')->raise($_[0]) }; | |||
| 3586 | ||||
| 3587 | It is possible to 'stack' multiple HandleError handlers by using | |||
| 3588 | closures: | |||
| 3589 | ||||
| 3590 | sub your_subroutine { | |||
| 3591 | my $previous_handler = $h->{HandleError}; | |||
| 3592 | $h->{HandleError} = sub { | |||
| 3593 | return 1 if $previous_handler and &$previous_handler(@_); | |||
| 3594 | ... your code here ... | |||
| 3595 | }; | |||
| 3596 | } | |||
| 3597 | ||||
| 3598 | Using a C<my> inside a subroutine to store the previous C<HandleError> | |||
| 3599 | value is important. See L<perlsub> and L<perlref> for more information | |||
| 3600 | about I<closures>. | |||
| 3601 | ||||
| 3602 | It is possible for C<HandleError> to alter the error message that | |||
| 3603 | will be used by C<RaiseError> and C<PrintError> if it returns false. | |||
| 3604 | It can do that by altering the value of $_[0]. This example appends | |||
| 3605 | a stack trace to all errors and, unlike the previous example using | |||
| 3606 | Carp::confess, this will work C<PrintError> as well as C<RaiseError>: | |||
| 3607 | ||||
| 3608 | $h->{HandleError} = sub { $_[0]=Carp::longmess($_[0]); 0; }; | |||
| 3609 | ||||
| 3610 | It is also possible for C<HandleError> to hide an error, to a limited | |||
| 3611 | degree, by using L</set_err> to reset $DBI::err and $DBI::errstr, | |||
| 3612 | and altering the return value of the failed method. For example: | |||
| 3613 | ||||
| 3614 | $h->{HandleError} = sub { | |||
| 3615 | return 0 unless $_[0] =~ /^\S+ fetchrow_arrayref failed:/; | |||
| 3616 | return 0 unless $_[1]->err == 1234; # the error to 'hide' | |||
| 3617 | $h->set_err(undef,undef); # turn off the error | |||
| 3618 | $_[2] = [ ... ]; # supply alternative return value | |||
| 3619 | return 1; | |||
| 3620 | }; | |||
| 3621 | ||||
| 3622 | This only works for methods which return a single value and is hard | |||
| 3623 | to make reliable (avoiding infinite loops, for example) and so isn't | |||
| 3624 | recommended for general use! If you find a I<good> use for it then | |||
| 3625 | please let me know. | |||
| 3626 | ||||
| 3627 | =head3 C<HandleSetErr> (code ref, inherited) | |||
| 3628 | ||||
| 3629 | The C<HandleSetErr> attribute can be used to intercept | |||
| 3630 | the setting of handle C<err>, C<errstr>, and C<state> values. | |||
| 3631 | If set to a reference to a subroutine then that subroutine is called | |||
| 3632 | whenever set_err() is called, typically by the driver or a subclass. | |||
| 3633 | ||||
| 3634 | The subroutine is called with five arguments, the first five that | |||
| 3635 | were passed to set_err(): the handle, the C<err>, C<errstr>, and | |||
| 3636 | C<state> values being set, and the method name. These can be altered | |||
| 3637 | by changing the values in the @_ array. The return value affects | |||
| 3638 | set_err() behaviour, see L</set_err> for details. | |||
| 3639 | ||||
| 3640 | It is possible to 'stack' multiple HandleSetErr handlers by using | |||
| 3641 | closures. See L</HandleError> for an example. | |||
| 3642 | ||||
| 3643 | The C<HandleSetErr> and C<HandleError> subroutines differ in subtle | |||
| 3644 | but significant ways. HandleError is only invoked at the point where | |||
| 3645 | the DBI is about to return to the application with C<err> set true. | |||
| 3646 | It's not invoked by the failure of a method that's been called by | |||
| 3647 | another DBI method. HandleSetErr, on the other hand, is called | |||
| 3648 | whenever set_err() is called with a defined C<err> value, even if false. | |||
| 3649 | So it's not just for errors, despite the name, but also warn and info states. | |||
| 3650 | The set_err() method, and thus HandleSetErr, may be called multiple | |||
| 3651 | times within a method and is usually invoked from deep within driver code. | |||
| 3652 | ||||
| 3653 | In theory a driver can use the return value from HandleSetErr via | |||
| 3654 | set_err() to decide whether to continue or not. If set_err() returns | |||
| 3655 | an empty list, indicating that the HandleSetErr code has 'handled' | |||
| 3656 | the 'error', the driver could then continue instead of failing (if | |||
| 3657 | that's a reasonable thing to do). This isn't excepted to be | |||
| 3658 | common and any such cases should be clearly marked in the driver | |||
| 3659 | documentation and discussed on the dbi-dev mailing list. | |||
| 3660 | ||||
| 3661 | The C<HandleSetErr> attribute was added in DBI 1.41. | |||
| 3662 | ||||
| 3663 | =head3 C<ErrCount> (unsigned integer) | |||
| 3664 | ||||
| 3665 | The C<ErrCount> attribute is incremented whenever the set_err() | |||
| 3666 | method records an error. It isn't incremented by warnings or | |||
| 3667 | information states. It is not reset by the DBI at any time. | |||
| 3668 | ||||
| 3669 | The C<ErrCount> attribute was added in DBI 1.41. Older drivers may | |||
| 3670 | not have been updated to use set_err() to record errors and so this | |||
| 3671 | attribute may not be incremented when using them. | |||
| 3672 | ||||
| 3673 | ||||
| 3674 | =head3 C<ShowErrorStatement> (boolean, inherited) | |||
| 3675 | ||||
| 3676 | The C<ShowErrorStatement> attribute can be used to cause the relevant | |||
| 3677 | Statement text to be appended to the error messages generated by | |||
| 3678 | the C<RaiseError>, C<PrintError>, and C<PrintWarn> attributes. | |||
| 3679 | Only applies to errors on statement handles | |||
| 3680 | plus the prepare(), do(), and the various C<select*()> database handle methods. | |||
| 3681 | (The exact format of the appended text is subject to change.) | |||
| 3682 | ||||
| 3683 | If C<$h-E<gt>{ParamValues}> returns a hash reference of parameter | |||
| 3684 | (placeholder) values then those are formatted and appended to the | |||
| 3685 | end of the Statement text in the error message. | |||
| 3686 | ||||
| 3687 | =head3 C<TraceLevel> (integer, inherited) | |||
| 3688 | ||||
| 3689 | The C<TraceLevel> attribute can be used as an alternative to the | |||
| 3690 | L</trace> method to set the DBI trace level and trace flags for a | |||
| 3691 | specific handle. See L</TRACING> for more details. | |||
| 3692 | ||||
| 3693 | The C<TraceLevel> attribute is especially useful combined with | |||
| 3694 | C<local> to alter the trace settings for just a single block of code. | |||
| 3695 | ||||
| 3696 | =head3 C<FetchHashKeyName> (string, inherited) | |||
| 3697 | ||||
| 3698 | The C<FetchHashKeyName> attribute is used to specify whether the fetchrow_hashref() | |||
| 3699 | method should perform case conversion on the field names used for | |||
| 3700 | the hash keys. For historical reasons it defaults to 'C<NAME>' but | |||
| 3701 | it is recommended to set it to 'C<NAME_lc>' (convert to lower case) | |||
| 3702 | or 'C<NAME_uc>' (convert to upper case) according to your preference. | |||
| 3703 | It can only be set for driver and database handles. For statement | |||
| 3704 | handles the value is frozen when prepare() is called. | |||
| 3705 | ||||
| 3706 | ||||
| 3707 | =head3 C<ChopBlanks> (boolean, inherited) | |||
| 3708 | ||||
| 3709 | The C<ChopBlanks> attribute can be used to control the trimming of trailing space | |||
| 3710 | characters from fixed width character (CHAR) fields. No other field | |||
| 3711 | types are affected, even where field values have trailing spaces. | |||
| 3712 | ||||
| 3713 | The default is false (although it is possible that the default may change). | |||
| 3714 | Applications that need specific behaviour should set the attribute as | |||
| 3715 | needed. | |||
| 3716 | ||||
| 3717 | Drivers are not required to support this attribute, but any driver which | |||
| 3718 | does not support it must arrange to return C<undef> as the attribute value. | |||
| 3719 | ||||
| 3720 | ||||
| 3721 | =head3 C<LongReadLen> (unsigned integer, inherited) | |||
| 3722 | ||||
| 3723 | The C<LongReadLen> attribute may be used to control the maximum | |||
| 3724 | length of 'long' type fields (LONG, BLOB, CLOB, MEMO, etc.) which the driver will | |||
| 3725 | read from the database automatically when it fetches each row of data. | |||
| 3726 | ||||
| 3727 | The C<LongReadLen> attribute only relates to fetching and reading | |||
| 3728 | long values; it is not involved in inserting or updating them. | |||
| 3729 | ||||
| 3730 | A value of 0 means not to automatically fetch any long data. | |||
| 3731 | Drivers may return undef or an empty string for long fields when | |||
| 3732 | C<LongReadLen> is 0. | |||
| 3733 | ||||
| 3734 | The default is typically 0 (zero) or 80 bytes but may vary between drivers. | |||
| 3735 | Applications fetching long fields should set this value to slightly | |||
| 3736 | larger than the longest long field value to be fetched. | |||
| 3737 | ||||
| 3738 | Some databases return some long types encoded as pairs of hex digits. | |||
| 3739 | For these types, C<LongReadLen> relates to the underlying data | |||
| 3740 | length and not the doubled-up length of the encoded string. | |||
| 3741 | ||||
| 3742 | Changing the value of C<LongReadLen> for a statement handle after it | |||
| 3743 | has been C<prepare>'d will typically have no effect, so it's common to | |||
| 3744 | set C<LongReadLen> on the C<$dbh> before calling C<prepare>. | |||
| 3745 | ||||
| 3746 | For most drivers the value used here has a direct effect on the | |||
| 3747 | memory used by the statement handle while it's active, so don't be | |||
| 3748 | too generous. If you can't be sure what value to use you could | |||
| 3749 | execute an extra select statement to determine the longest value. | |||
| 3750 | For example: | |||
| 3751 | ||||
| 3752 | $dbh->{LongReadLen} = $dbh->selectrow_array(qq{ | |||
| 3753 | SELECT MAX(OCTET_LENGTH(long_column_name)) | |||
| 3754 | FROM table WHERE ... | |||
| 3755 | }); | |||
| 3756 | $sth = $dbh->prepare(qq{ | |||
| 3757 | SELECT long_column_name, ... FROM table WHERE ... | |||
| 3758 | }); | |||
| 3759 | ||||
| 3760 | You may need to take extra care if the table can be modified between | |||
| 3761 | the first select and the second being executed. You may also need to | |||
| 3762 | use a different function if OCTET_LENGTH() does not work for long | |||
| 3763 | types in your database. For example, for Sybase use DATALENGTH() and | |||
| 3764 | for Oracle use LENGTHB(). | |||
| 3765 | ||||
| 3766 | See also L</LongTruncOk> for information on truncation of long types. | |||
| 3767 | ||||
| 3768 | =head3 C<LongTruncOk> (boolean, inherited) | |||
| 3769 | ||||
| 3770 | The C<LongTruncOk> attribute may be used to control the effect of | |||
| 3771 | fetching a long field value which has been truncated (typically | |||
| 3772 | because it's longer than the value of the C<LongReadLen> attribute). | |||
| 3773 | ||||
| 3774 | By default, C<LongTruncOk> is false and so fetching a long value that | |||
| 3775 | needs to be truncated will cause the fetch to fail. | |||
| 3776 | (Applications should always be sure to | |||
| 3777 | check for errors after a fetch loop in case an error, such as a divide | |||
| 3778 | by zero or long field truncation, caused the fetch to terminate | |||
| 3779 | prematurely.) | |||
| 3780 | ||||
| 3781 | If a fetch fails due to a long field truncation when C<LongTruncOk> is | |||
| 3782 | false, many drivers will allow you to continue fetching further rows. | |||
| 3783 | ||||
| 3784 | See also L</LongReadLen>. | |||
| 3785 | ||||
| 3786 | =head3 C<TaintIn> (boolean, inherited) | |||
| 3787 | ||||
| 3788 | If the C<TaintIn> attribute is set to a true value I<and> Perl is running in | |||
| 3789 | taint mode (e.g., started with the C<-T> option), then all the arguments | |||
| 3790 | to most DBI method calls are checked for being tainted. I<This may change.> | |||
| 3791 | ||||
| 3792 | The attribute defaults to off, even if Perl is in taint mode. | |||
| 3793 | See L<perlsec> for more about taint mode. If Perl is not | |||
| 3794 | running in taint mode, this attribute has no effect. | |||
| 3795 | ||||
| 3796 | When fetching data that you trust you can turn off the TaintIn attribute, | |||
| 3797 | for that statement handle, for the duration of the fetch loop. | |||
| 3798 | ||||
| 3799 | The C<TaintIn> attribute was added in DBI 1.31. | |||
| 3800 | ||||
| 3801 | =head3 C<TaintOut> (boolean, inherited) | |||
| 3802 | ||||
| 3803 | If the C<TaintOut> attribute is set to a true value I<and> Perl is running in | |||
| 3804 | taint mode (e.g., started with the C<-T> option), then most data fetched | |||
| 3805 | from the database is considered tainted. I<This may change.> | |||
| 3806 | ||||
| 3807 | The attribute defaults to off, even if Perl is in taint mode. | |||
| 3808 | See L<perlsec> for more about taint mode. If Perl is not | |||
| 3809 | running in taint mode, this attribute has no effect. | |||
| 3810 | ||||
| 3811 | When fetching data that you trust you can turn off the TaintOut attribute, | |||
| 3812 | for that statement handle, for the duration of the fetch loop. | |||
| 3813 | ||||
| 3814 | Currently only fetched data is tainted. It is possible that the results | |||
| 3815 | of other DBI method calls, and the value of fetched attributes, may | |||
| 3816 | also be tainted in future versions. That change may well break your | |||
| 3817 | applications unless you take great care now. If you use DBI Taint mode, | |||
| 3818 | please report your experience and any suggestions for changes. | |||
| 3819 | ||||
| 3820 | The C<TaintOut> attribute was added in DBI 1.31. | |||
| 3821 | ||||
| 3822 | =head3 C<Taint> (boolean, inherited) | |||
| 3823 | ||||
| 3824 | The C<Taint> attribute is a shortcut for L</TaintIn> and L</TaintOut> (it is also present | |||
| 3825 | for backwards compatibility). | |||
| 3826 | ||||
| 3827 | Setting this attribute sets both L</TaintIn> and L</TaintOut>, and retrieving | |||
| 3828 | it returns a true value if and only if L</TaintIn> and L</TaintOut> are | |||
| 3829 | both set to true values. | |||
| 3830 | ||||
| 3831 | =head3 C<Profile> (inherited) | |||
| 3832 | ||||
| 3833 | The C<Profile> attribute enables the collection and reporting of method call timing statistics. | |||
| 3834 | See the L<DBI::Profile> module documentation for I<much> more detail. | |||
| 3835 | ||||
| 3836 | The C<Profile> attribute was added in DBI 1.24. | |||
| 3837 | ||||
| 3838 | =head3 C<ReadOnly> (boolean, inherited) | |||
| 3839 | ||||
| 3840 | An application can set the C<ReadOnly> attribute of a handle to a true value to | |||
| 3841 | indicate that it will not be attempting to make any changes using that handle | |||
| 3842 | or any children of it. | |||
| 3843 | ||||
| 3844 | Note that the exact definition of 'read only' is rather fuzzy. | |||
| 3845 | For more details see the documentation for the driver you're using. | |||
| 3846 | ||||
| 3847 | If the driver can make the handle truly read-only then it should | |||
| 3848 | (unless doing so would have unpleasant side effect, like changing the | |||
| 3849 | consistency level from per-statement to per-session). | |||
| 3850 | Otherwise the attribute is simply advisory. | |||
| 3851 | ||||
| 3852 | A driver can set the C<ReadOnly> attribute itself to indicate that the data it | |||
| 3853 | is connected to cannot be changed for some reason. | |||
| 3854 | ||||
| 3855 | Library modules and proxy drivers can use the attribute to influence their behavior. | |||
| 3856 | For example, the DBD::Gofer driver considers the C<ReadOnly> attribute when | |||
| 3857 | making a decison about whether to retry an operation that failed. | |||
| 3858 | ||||
| 3859 | The attribute should be set to 1 or 0 (or undef). Other values are reserved. | |||
| 3860 | ||||
| 3861 | =head3 C<private_your_module_name_*> | |||
| 3862 | ||||
| 3863 | The DBI provides a way to store extra information in a DBI handle as | |||
| 3864 | "private" attributes. The DBI will allow you to store and retrieve any | |||
| 3865 | attribute which has a name starting with "C<private_>". | |||
| 3866 | ||||
| 3867 | It is I<strongly> recommended that you use just I<one> private | |||
| 3868 | attribute (e.g., use a hash ref) I<and> give it a long and unambiguous | |||
| 3869 | name that includes the module or application name that the attribute | |||
| 3870 | relates to (e.g., "C<private_YourFullModuleName_thingy>"). | |||
| 3871 | ||||
| 3872 | Because of the way the Perl tie mechanism works you cannot reliably | |||
| 3873 | use the C<||=> operator directly to initialise the attribute, like this: | |||
| 3874 | ||||
| 3875 | my $foo = $dbh->{private_yourmodname_foo} ||= { ... }; # WRONG | |||
| 3876 | ||||
| 3877 | you should use a two step approach like this: | |||
| 3878 | ||||
| 3879 | my $foo = $dbh->{private_yourmodname_foo}; | |||
| 3880 | $foo ||= $dbh->{private_yourmodname_foo} = { ... }; | |||
| 3881 | ||||
| 3882 | This attribute is primarily of interest to people sub-classing DBI, | |||
| 3883 | or for applications to piggy-back extra information onto DBI handles. | |||
| 3884 | ||||
| 3885 | =head1 DBI DATABASE HANDLE OBJECTS | |||
| 3886 | ||||
| 3887 | This section covers the methods and attributes associated with | |||
| 3888 | database handles. | |||
| 3889 | ||||
| 3890 | =head2 Database Handle Methods | |||
| 3891 | ||||
| 3892 | The following methods are specified for DBI database handles: | |||
| 3893 | ||||
| 3894 | =head3 C<clone> | |||
| 3895 | ||||
| 3896 | $new_dbh = $dbh->clone(); | |||
| 3897 | $new_dbh = $dbh->clone(\%attr); | |||
| 3898 | ||||
| 3899 | The C<clone> method duplicates the $dbh connection by connecting | |||
| 3900 | with the same parameters ($dsn, $user, $password) as originally used. | |||
| 3901 | ||||
| 3902 | The attributes for the cloned connect are the same as those used | |||
| 3903 | for the original connect, with some other attribute merged over | |||
| 3904 | them depending on the \%attr parameter. | |||
| 3905 | ||||
| 3906 | If \%attr is given then the attributes it contains are merged into | |||
| 3907 | the original attributes and override any with the same names. | |||
| 3908 | Effectively the same as doing: | |||
| 3909 | ||||
| 3910 | %attribues_used = ( %original_attributes, %attr ); | |||
| 3911 | ||||
| 3912 | If \%attr is not given then it defaults to a hash containing all | |||
| 3913 | the attributes in the attribute cache of $dbh excluding any non-code | |||
| 3914 | references, plus the main boolean attributes (RaiseError, PrintError, | |||
| 3915 | AutoCommit, etc.). This behaviour is subject to change. | |||
| 3916 | ||||
| 3917 | The clone method can be used even if the database handle is disconnected. | |||
| 3918 | ||||
| 3919 | The C<clone> method was added in DBI 1.33. It is very new and likely | |||
| 3920 | to change. | |||
| 3921 | ||||
| 3922 | =head3 C<data_sources> | |||
| 3923 | ||||
| 3924 | @ary = $dbh->data_sources(); | |||
| 3925 | @ary = $dbh->data_sources(\%attr); | |||
| 3926 | ||||
| 3927 | Returns a list of data sources (databases) available via the $dbh | |||
| 3928 | driver's data_sources() method, plus any extra data sources that | |||
| 3929 | the driver can discover via the connected $dbh. Typically the extra | |||
| 3930 | data sources are other databases managed by the same server process | |||
| 3931 | that the $dbh is connected to. | |||
| 3932 | ||||
| 3933 | Data sources are returned in a form suitable for passing to the | |||
| 3934 | L</connect> method (that is, they will include the "C<dbi:$driver:>" prefix). | |||
| 3935 | ||||
| 3936 | The data_sources() method, for a $dbh, was added in DBI 1.38. | |||
| 3937 | ||||
| 3938 | =head3 C<do> | |||
| 3939 | ||||
| 3940 | $rows = $dbh->do($statement) or die $dbh->errstr; | |||
| 3941 | $rows = $dbh->do($statement, \%attr) or die $dbh->errstr; | |||
| 3942 | $rows = $dbh->do($statement, \%attr, @bind_values) or die ... | |||
| 3943 | ||||
| 3944 | Prepare and execute a single statement. Returns the number of rows | |||
| 3945 | affected or C<undef> on error. A return value of C<-1> means the | |||
| 3946 | number of rows is not known, not applicable, or not available. | |||
| 3947 | ||||
| 3948 | This method is typically most useful for I<non>-C<SELECT> statements that | |||
| 3949 | either cannot be prepared in advance (due to a limitation of the | |||
| 3950 | driver) or do not need to be executed repeatedly. It should not | |||
| 3951 | be used for C<SELECT> statements because it does not return a statement | |||
| 3952 | handle (so you can't fetch any data). | |||
| 3953 | ||||
| 3954 | The default C<do> method is logically similar to: | |||
| 3955 | ||||
| 3956 | sub do { | |||
| 3957 | my($dbh, $statement, $attr, @bind_values) = @_; | |||
| 3958 | my $sth = $dbh->prepare($statement, $attr) or return undef; | |||
| 3959 | $sth->execute(@bind_values) or return undef; | |||
| 3960 | my $rows = $sth->rows; | |||
| 3961 | ($rows == 0) ? "0E0" : $rows; # always return true if no error | |||
| 3962 | } | |||
| 3963 | ||||
| 3964 | For example: | |||
| 3965 | ||||
| 3966 | my $rows_deleted = $dbh->do(q{ | |||
| 3967 | DELETE FROM table | |||
| 3968 | WHERE status = ? | |||
| 3969 | }, undef, 'DONE') or die $dbh->errstr; | |||
| 3970 | ||||
| 3971 | Using placeholders and C<@bind_values> with the C<do> method can be | |||
| 3972 | useful because it avoids the need to correctly quote any variables | |||
| 3973 | in the C<$statement>. But if you'll be executing the statement many | |||
| 3974 | times then it's more efficient to C<prepare> it once and call | |||
| 3975 | C<execute> many times instead. | |||
| 3976 | ||||
| 3977 | The C<q{...}> style quoting used in this example avoids clashing with | |||
| 3978 | quotes that may be used in the SQL statement. Use the double-quote-like | |||
| 3979 | C<qq{...}> operator if you want to interpolate variables into the string. | |||
| 3980 | See L<perlop/"Quote and Quote-like Operators"> for more details. | |||
| 3981 | ||||
| 3982 | =head3 C<last_insert_id> | |||
| 3983 | ||||
| 3984 | $rv = $dbh->last_insert_id($catalog, $schema, $table, $field); | |||
| 3985 | $rv = $dbh->last_insert_id($catalog, $schema, $table, $field, \%attr); | |||
| 3986 | ||||
| 3987 | Returns a value 'identifying' the row just inserted, if possible. | |||
| 3988 | Typically this would be a value assigned by the database server | |||
| 3989 | to a column with an I<auto_increment> or I<serial> type. | |||
| 3990 | Returns undef if the driver does not support the method or can't | |||
| 3991 | determine the value. | |||
| 3992 | ||||
| 3993 | The $catalog, $schema, $table, and $field parameters may be required | |||
| 3994 | for some drivers (see below). If you don't know the parameter values | |||
| 3995 | and your driver does not need them, then use C<undef> for each. | |||
| 3996 | ||||
| 3997 | There are several caveats to be aware of with this method if you want | |||
| 3998 | to use it for portable applications: | |||
| 3999 | ||||
| 4000 | B<*> For some drivers the value may only available immediately after | |||
| 4001 | the insert statement has executed (e.g., mysql, Informix). | |||
| 4002 | ||||
| 4003 | B<*> For some drivers the $catalog, $schema, $table, and $field parameters | |||
| 4004 | are required, for others they are ignored (e.g., mysql). | |||
| 4005 | ||||
| 4006 | B<*> Drivers may return an indeterminate value if no insert has | |||
| 4007 | been performed yet. | |||
| 4008 | ||||
| 4009 | B<*> For some drivers the value may only be available if placeholders | |||
| 4010 | have I<not> been used (e.g., Sybase, MS SQL). In this case the value | |||
| 4011 | returned would be from the last non-placeholder insert statement. | |||
| 4012 | ||||
| 4013 | B<*> Some drivers may need driver-specific hints about how to get | |||
| 4014 | the value. For example, being told the name of the database 'sequence' | |||
| 4015 | object that holds the value. Any such hints are passed as driver-specific | |||
| 4016 | attributes in the \%attr parameter. | |||
| 4017 | ||||
| 4018 | B<*> If the underlying database offers nothing better, then some | |||
| 4019 | drivers may attempt to implement this method by executing | |||
| 4020 | "C<select max($field) from $table>". Drivers using any approach | |||
| 4021 | like this should issue a warning if C<AutoCommit> is true because | |||
| 4022 | it is generally unsafe - another process may have modified the table | |||
| 4023 | between your insert and the select. For situations where you know | |||
| 4024 | it is safe, such as when you have locked the table, you can silence | |||
| 4025 | the warning by passing C<Warn> => 0 in \%attr. | |||
| 4026 | ||||
| 4027 | B<*> If no insert has been performed yet, or the last insert failed, | |||
| 4028 | then the value is implementation defined. | |||
| 4029 | ||||
| 4030 | Given all the caveats above, it's clear that this method must be | |||
| 4031 | used with care. | |||
| 4032 | ||||
| 4033 | The C<last_insert_id> method was added in DBI 1.38. | |||
| 4034 | ||||
| 4035 | =head3 C<selectrow_array> | |||
| 4036 | ||||
| 4037 | @row_ary = $dbh->selectrow_array($statement); | |||
| 4038 | @row_ary = $dbh->selectrow_array($statement, \%attr); | |||
| 4039 | @row_ary = $dbh->selectrow_array($statement, \%attr, @bind_values); | |||
| 4040 | ||||
| 4041 | This utility method combines L</prepare>, L</execute> and | |||
| 4042 | L</fetchrow_array> into a single call. If called in a list context, it | |||
| 4043 | returns the first row of data from the statement. The C<$statement> | |||
| 4044 | parameter can be a previously prepared statement handle, in which case | |||
| 4045 | the C<prepare> is skipped. | |||
| 4046 | ||||
| 4047 | If any method fails, and L</RaiseError> is not set, C<selectrow_array> | |||
| 4048 | will return an empty list. | |||
| 4049 | ||||
| 4050 | If called in a scalar context for a statement handle that has more | |||
| 4051 | than one column, it is undefined whether the driver will return | |||
| 4052 | the value of the first column or the last. So don't do that. | |||
| 4053 | Also, in a scalar context, an C<undef> is returned if there are no | |||
| 4054 | more rows or if an error occurred. That C<undef> can't be distinguished | |||
| 4055 | from an C<undef> returned because the first field value was NULL. | |||
| 4056 | For these reasons you should exercise some caution if you use | |||
| 4057 | C<selectrow_array> in a scalar context, or just don't do that. | |||
| 4058 | ||||
| 4059 | ||||
| 4060 | =head3 C<selectrow_arrayref> | |||
| 4061 | ||||
| 4062 | $ary_ref = $dbh->selectrow_arrayref($statement); | |||
| 4063 | $ary_ref = $dbh->selectrow_arrayref($statement, \%attr); | |||
| 4064 | $ary_ref = $dbh->selectrow_arrayref($statement, \%attr, @bind_values); | |||
| 4065 | ||||
| 4066 | This utility method combines L</prepare>, L</execute> and | |||
| 4067 | L</fetchrow_arrayref> into a single call. It returns the first row of | |||
| 4068 | data from the statement. The C<$statement> parameter can be a previously | |||
| 4069 | prepared statement handle, in which case the C<prepare> is skipped. | |||
| 4070 | ||||
| 4071 | If any method fails, and L</RaiseError> is not set, C<selectrow_array> | |||
| 4072 | will return undef. | |||
| 4073 | ||||
| 4074 | ||||
| 4075 | =head3 C<selectrow_hashref> | |||
| 4076 | ||||
| 4077 | $hash_ref = $dbh->selectrow_hashref($statement); | |||
| 4078 | $hash_ref = $dbh->selectrow_hashref($statement, \%attr); | |||
| 4079 | $hash_ref = $dbh->selectrow_hashref($statement, \%attr, @bind_values); | |||
| 4080 | ||||
| 4081 | This utility method combines L</prepare>, L</execute> and | |||
| 4082 | L</fetchrow_hashref> into a single call. It returns the first row of | |||
| 4083 | data from the statement. The C<$statement> parameter can be a previously | |||
| 4084 | prepared statement handle, in which case the C<prepare> is skipped. | |||
| 4085 | ||||
| 4086 | If any method fails, and L</RaiseError> is not set, C<selectrow_hashref> | |||
| 4087 | will return undef. | |||
| 4088 | ||||
| 4089 | ||||
| 4090 | =head3 C<selectall_arrayref> | |||
| 4091 | ||||
| 4092 | $ary_ref = $dbh->selectall_arrayref($statement); | |||
| 4093 | $ary_ref = $dbh->selectall_arrayref($statement, \%attr); | |||
| 4094 | $ary_ref = $dbh->selectall_arrayref($statement, \%attr, @bind_values); | |||
| 4095 | ||||
| 4096 | This utility method combines L</prepare>, L</execute> and | |||
| 4097 | L</fetchall_arrayref> into a single call. It returns a reference to an | |||
| 4098 | array containing a reference to an array (or hash, see below) for each row of | |||
| 4099 | data fetched. | |||
| 4100 | ||||
| 4101 | The C<$statement> parameter can be a previously prepared statement handle, | |||
| 4102 | in which case the C<prepare> is skipped. This is recommended if the | |||
| 4103 | statement is going to be executed many times. | |||
| 4104 | ||||
| 4105 | If L</RaiseError> is not set and any method except C<fetchall_arrayref> | |||
| 4106 | fails then C<selectall_arrayref> will return C<undef>; if | |||
| 4107 | C<fetchall_arrayref> fails then it will return with whatever data | |||
| 4108 | has been fetched thus far. You should check C<$sth-E<gt>err> | |||
| 4109 | afterwards (or use the C<RaiseError> attribute) to discover if the data is | |||
| 4110 | complete or was truncated due to an error. | |||
| 4111 | ||||
| 4112 | The L</fetchall_arrayref> method called by C<selectall_arrayref> | |||
| 4113 | supports a $max_rows parameter. You can specify a value for $max_rows | |||
| 4114 | by including a 'C<MaxRows>' attribute in \%attr. In which case finish() | |||
| 4115 | is called for you after fetchall_arrayref() returns. | |||
| 4116 | ||||
| 4117 | The L</fetchall_arrayref> method called by C<selectall_arrayref> | |||
| 4118 | also supports a $slice parameter. You can specify a value for $slice by | |||
| 4119 | including a 'C<Slice>' or 'C<Columns>' attribute in \%attr. The only | |||
| 4120 | difference between the two is that if C<Slice> is not defined and | |||
| 4121 | C<Columns> is an array ref, then the array is assumed to contain column | |||
| 4122 | index values (which count from 1), rather than perl array index values. | |||
| 4123 | In which case the array is copied and each value decremented before | |||
| 4124 | passing to C</fetchall_arrayref>. | |||
| 4125 | ||||
| 4126 | You may often want to fetch an array of rows where each row is stored as a | |||
| 4127 | hash. That can be done simple using: | |||
| 4128 | ||||
| 4129 | my $emps = $dbh->selectall_arrayref( | |||
| 4130 | "SELECT ename FROM emp ORDER BY ename", | |||
| 4131 | { Slice => {} } | |||
| 4132 | ); | |||
| 4133 | foreach my $emp ( @$emps ) { | |||
| 4134 | print "Employee: $emp->{ename}\n"; | |||
| 4135 | } | |||
| 4136 | ||||
| 4137 | Or, to fetch into an array instead of an array ref: | |||
| 4138 | ||||
| 4139 | @result = @{ $dbh->selectall_arrayref($sql, { Slice => {} }) }; | |||
| 4140 | ||||
| 4141 | See L</fetchall_arrayref> method for more details. | |||
| 4142 | ||||
| 4143 | =head3 C<selectall_hashref> | |||
| 4144 | ||||
| 4145 | $hash_ref = $dbh->selectall_hashref($statement, $key_field); | |||
| 4146 | $hash_ref = $dbh->selectall_hashref($statement, $key_field, \%attr); | |||
| 4147 | $hash_ref = $dbh->selectall_hashref($statement, $key_field, \%attr, @bind_values); | |||
| 4148 | ||||
| 4149 | This utility method combines L</prepare>, L</execute> and | |||
| 4150 | L</fetchall_hashref> into a single call. It returns a reference to a | |||
| 4151 | hash containing one entry, at most, for each row, as returned by fetchall_hashref(). | |||
| 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 | The C<$key_field> parameter defines which column, or columns, are used as keys | |||
| 4158 | in the returned hash. It can either be the name of a single field, or a | |||
| 4159 | reference to an array containing multiple field names. Using multiple names | |||
| 4160 | yields a tree of nested hashes. | |||
| 4161 | ||||
| 4162 | If a row has the same key as an earlier row then it replaces the earlier row. | |||
| 4163 | ||||
| 4164 | If any method except C<fetchrow_hashref> fails, and L</RaiseError> is not set, | |||
| 4165 | C<selectall_hashref> will return C<undef>. If C<fetchrow_hashref> fails and | |||
| 4166 | L</RaiseError> is not set, then it will return with whatever data it | |||
| 4167 | has fetched thus far. $DBI::err should be checked to catch that. | |||
| 4168 | ||||
| 4169 | See fetchall_hashref() for more details. | |||
| 4170 | ||||
| 4171 | =head3 C<selectcol_arrayref> | |||
| 4172 | ||||
| 4173 | $ary_ref = $dbh->selectcol_arrayref($statement); | |||
| 4174 | $ary_ref = $dbh->selectcol_arrayref($statement, \%attr); | |||
| 4175 | $ary_ref = $dbh->selectcol_arrayref($statement, \%attr, @bind_values); | |||
| 4176 | ||||
| 4177 | This utility method combines L</prepare>, L</execute>, and fetching one | |||
| 4178 | column from all the rows, into a single call. It returns a reference to | |||
| 4179 | an array containing the values of the first column from each row. | |||
| 4180 | ||||
| 4181 | The C<$statement> parameter can be a previously prepared statement handle, | |||
| 4182 | in which case the C<prepare> is skipped. This is recommended if the | |||
| 4183 | statement is going to be executed many times. | |||
| 4184 | ||||
| 4185 | If any method except C<fetch> fails, and L</RaiseError> is not set, | |||
| 4186 | C<selectcol_arrayref> will return C<undef>. If C<fetch> fails and | |||
| 4187 | L</RaiseError> is not set, then it will return with whatever data it | |||
| 4188 | has fetched thus far. $DBI::err should be checked to catch that. | |||
| 4189 | ||||
| 4190 | The C<selectcol_arrayref> method defaults to pushing a single column | |||
| 4191 | value (the first) from each row into the result array. However, it can | |||
| 4192 | also push another column, or even multiple columns per row, into the | |||
| 4193 | result array. This behaviour can be specified via a 'C<Columns>' | |||
| 4194 | attribute which must be a ref to an array containing the column number | |||
| 4195 | or numbers to use. For example: | |||
| 4196 | ||||
| 4197 | # get array of id and name pairs: | |||
| 4198 | my $ary_ref = $dbh->selectcol_arrayref("select id, name from table", { Columns=>[1,2] }); | |||
| 4199 | my %hash = @$ary_ref; # build hash from key-value pairs so $hash{$id} => name | |||
| 4200 | ||||
| 4201 | You can specify a maximum number of rows to fetch by including a | |||
| 4202 | 'C<MaxRows>' attribute in \%attr. | |||
| 4203 | ||||
| 4204 | =head3 C<prepare> | |||
| 4205 | ||||
| 4206 | $sth = $dbh->prepare($statement) or die $dbh->errstr; | |||
| 4207 | $sth = $dbh->prepare($statement, \%attr) or die $dbh->errstr; | |||
| 4208 | ||||
| 4209 | Prepares a statement for later execution by the database | |||
| 4210 | engine and returns a reference to a statement handle object. | |||
| 4211 | ||||
| 4212 | The returned statement handle can be used to get attributes of the | |||
| 4213 | statement and invoke the L</execute> method. See L</Statement Handle Methods>. | |||
| 4214 | ||||
| 4215 | Drivers for engines without the concept of preparing a | |||
| 4216 | statement will typically just store the statement in the returned | |||
| 4217 | handle and process it when C<$sth-E<gt>execute> is called. Such drivers are | |||
| 4218 | unlikely to give much useful information about the | |||
| 4219 | statement, such as C<$sth-E<gt>{NUM_OF_FIELDS}>, until after C<$sth-E<gt>execute> | |||
| 4220 | has been called. Portable applications should take this into account. | |||
| 4221 | ||||
| 4222 | In general, DBI drivers do not parse the contents of the statement | |||
| 4223 | (other than simply counting any L</Placeholders>). The statement is | |||
| 4224 | passed directly to the database engine, sometimes known as pass-thru | |||
| 4225 | mode. This has advantages and disadvantages. On the plus side, you can | |||
| 4226 | access all the functionality of the engine being used. On the downside, | |||
| 4227 | you're limited if you're using a simple engine, and you need to take extra care if | |||
| 4228 | writing applications intended to be portable between engines. | |||
| 4229 | ||||
| 4230 | Portable applications should not assume that a new statement can be | |||
| 4231 | prepared and/or executed while still fetching results from a previous | |||
| 4232 | statement. | |||
| 4233 | ||||
| 4234 | Some command-line SQL tools use statement terminators, like a semicolon, | |||
| 4235 | to indicate the end of a statement. Such terminators should not normally | |||
| 4236 | be used with the DBI. | |||
| 4237 | ||||
| 4238 | ||||
| 4239 | =head3 C<prepare_cached> | |||
| 4240 | ||||
| 4241 | $sth = $dbh->prepare_cached($statement) | |||
| 4242 | $sth = $dbh->prepare_cached($statement, \%attr) | |||
| 4243 | $sth = $dbh->prepare_cached($statement, \%attr, $if_active) | |||
| 4244 | ||||
| 4245 | Like L</prepare> except that the statement handle returned will be | |||
| 4246 | stored in a hash associated with the C<$dbh>. If another call is made to | |||
| 4247 | C<prepare_cached> with the same C<$statement> and C<%attr> parameter values, | |||
| 4248 | then the corresponding cached C<$sth> will be returned without contacting the | |||
| 4249 | database server. | |||
| 4250 | ||||
| 4251 | The C<$if_active> parameter lets you adjust the behaviour if an | |||
| 4252 | already cached statement handle is still Active. There are several | |||
| 4253 | alternatives: | |||
| 4254 | ||||
| 4255 | =over 4 | |||
| 4256 | ||||
| 4257 | =item B<0>: A warning will be generated, and finish() will be called on | |||
| 4258 | the statement handle before it is returned. This is the default | |||
| 4259 | behaviour if $if_active is not passed. | |||
| 4260 | ||||
| 4261 | =item B<1>: finish() will be called on the statement handle, but the | |||
| 4262 | warning is suppressed. | |||
| 4263 | ||||
| 4264 | =item B<2>: Disables any checking. | |||
| 4265 | ||||
| 4266 | =item B<3>: The existing active statement handle will be removed from the | |||
| 4267 | cache and a new statement handle prepared and cached in its place. | |||
| 4268 | This is the safest option because it doesn't affect the state of the | |||
| 4269 | old handle, it just removes it from the cache. [Added in DBI 1.40] | |||
| 4270 | ||||
| 4271 | =back | |||
| 4272 | ||||
| 4273 | Here are some examples of C<prepare_cached>: | |||
| 4274 | ||||
| 4275 | sub insert_hash { | |||
| 4276 | my ($table, $field_values) = @_; | |||
| 4277 | # sort to keep field order, and thus sql, stable for prepare_cached | |||
| 4278 | my @fields = sort keys %$field_values; | |||
| 4279 | my @values = @{$field_values}{@fields}; | |||
| 4280 | my $sql = sprintf "insert into %s (%s) values (%s)", | |||
| 4281 | $table, join(",", @fields), join(",", ("?")x@fields); | |||
| 4282 | my $sth = $dbh->prepare_cached($sql); | |||
| 4283 | return $sth->execute(@values); | |||
| 4284 | } | |||
| 4285 | ||||
| 4286 | sub search_hash { | |||
| 4287 | my ($table, $field_values) = @_; | |||
| 4288 | # sort to keep field order, and thus sql, stable for prepare_cached | |||
| 4289 | my @fields = sort keys %$field_values; | |||
| 4290 | my @values = @{$field_values}{@fields}; | |||
| 4291 | my $qualifier = ""; | |||
| 4292 | $qualifier = "where ".join(" and ", map { "$_=?" } @fields) if @fields; | |||
| 4293 | $sth = $dbh->prepare_cached("SELECT * FROM $table $qualifier"); | |||
| 4294 | return $dbh->selectall_arrayref($sth, {}, @values); | |||
| 4295 | } | |||
| 4296 | ||||
| 4297 | I<Caveat emptor:> This caching can be useful in some applications, | |||
| 4298 | but it can also cause problems and should be used with care. Here | |||
| 4299 | is a contrived case where caching would cause a significant problem: | |||
| 4300 | ||||
| 4301 | my $sth = $dbh->prepare_cached('SELECT * FROM foo WHERE bar=?'); | |||
| 4302 | $sth->execute(...); | |||
| 4303 | while (my $data = $sth->fetchrow_hashref) { | |||
| 4304 | ||||
| 4305 | # later, in some other code called within the loop... | |||
| 4306 | my $sth2 = $dbh->prepare_cached('SELECT * FROM foo WHERE bar=?'); | |||
| 4307 | $sth2->execute(...); | |||
| 4308 | while (my $data2 = $sth2->fetchrow_arrayref) { | |||
| 4309 | do_stuff(...); | |||
| 4310 | } | |||
| 4311 | } | |||
| 4312 | ||||
| 4313 | In this example, since both handles are preparing the exact same statement, | |||
| 4314 | C<$sth2> will not be its own statement handle, but a duplicate of C<$sth> | |||
| 4315 | returned from the cache. The results will certainly not be what you expect. | |||
| 4316 | Typically the the inner fetch loop will work normally, fetching all | |||
| 4317 | the records and terminating when there are no more, but now $sth | |||
| 4318 | is the same as $sth2 the outer fetch loop will also terminate. | |||
| 4319 | ||||
| 4320 | You'll know if you run into this problem because prepare_cached() | |||
| 4321 | will generate a warning by default (when $if_active is false). | |||
| 4322 | ||||
| 4323 | The cache used by prepare_cached() is keyed by both the statement | |||
| 4324 | and any attributes so you can also avoid this issue by doing something | |||
| 4325 | like: | |||
| 4326 | ||||
| 4327 | $sth = $dbh->prepare_cached("...", { dbi_dummy => __FILE__.__LINE__ }); | |||
| 4328 | ||||
| 4329 | which will ensure that prepare_cached only returns statements cached | |||
| 4330 | by that line of code in that source file. | |||
| 4331 | ||||
| 4332 | If you'd like the cache to managed intelligently, you can tie the | |||
| 4333 | hashref returned by C<CachedKids> to an appropriate caching module, | |||
| 4334 | such as L<Tie::Cache::LRU>: | |||
| 4335 | ||||
| 4336 | my $cache; | |||
| 4337 | tie %$cache, 'Tie::Cache::LRU', 500; | |||
| 4338 | $dbh->{CachedKids} = $cache; | |||
| 4339 | ||||
| 4340 | =head3 C<commit> | |||
| 4341 | ||||
| 4342 | $rc = $dbh->commit or die $dbh->errstr; | |||
| 4343 | ||||
| 4344 | Commit (make permanent) the most recent series of database changes | |||
| 4345 | if the database supports transactions and AutoCommit is off. | |||
| 4346 | ||||
| 4347 | If C<AutoCommit> is on, then calling | |||
| 4348 | C<commit> will issue a "commit ineffective with AutoCommit" warning. | |||
| 4349 | ||||
| 4350 | See also L</Transactions> in the L</FURTHER INFORMATION> section below. | |||
| 4351 | ||||
| 4352 | =head3 C<rollback> | |||
| 4353 | ||||
| 4354 | $rc = $dbh->rollback or die $dbh->errstr; | |||
| 4355 | ||||
| 4356 | Rollback (undo) the most recent series of uncommitted database | |||
| 4357 | changes if the database supports transactions and AutoCommit is off. | |||
| 4358 | ||||
| 4359 | If C<AutoCommit> is on, then calling | |||
| 4360 | C<rollback> will issue a "rollback ineffective with AutoCommit" warning. | |||
| 4361 | ||||
| 4362 | See also L</Transactions> in the L</FURTHER INFORMATION> section below. | |||
| 4363 | ||||
| 4364 | =head3 C<begin_work> | |||
| 4365 | ||||
| 4366 | $rc = $dbh->begin_work or die $dbh->errstr; | |||
| 4367 | ||||
| 4368 | Enable transactions (by turning C<AutoCommit> off) until the next call | |||
| 4369 | to C<commit> or C<rollback>. After the next C<commit> or C<rollback>, | |||
| 4370 | C<AutoCommit> will automatically be turned on again. | |||
| 4371 | ||||
| 4372 | If C<AutoCommit> is already off when C<begin_work> is called then | |||
| 4373 | it does nothing except return an error. If the driver does not support | |||
| 4374 | transactions then when C<begin_work> attempts to set C<AutoCommit> off | |||
| 4375 | the driver will trigger a fatal error. | |||
| 4376 | ||||
| 4377 | See also L</Transactions> in the L</FURTHER INFORMATION> section below. | |||
| 4378 | ||||
| 4379 | ||||
| 4380 | =head3 C<disconnect> | |||
| 4381 | ||||
| 4382 | $rc = $dbh->disconnect or warn $dbh->errstr; | |||
| 4383 | ||||
| 4384 | Disconnects the database from the database handle. C<disconnect> is typically only used | |||
| 4385 | before exiting the program. The handle is of little use after disconnecting. | |||
| 4386 | ||||
| 4387 | The transaction behaviour of the C<disconnect> method is, sadly, | |||
| 4388 | undefined. Some database systems (such as Oracle and Ingres) will | |||
| 4389 | automatically commit any outstanding changes, but others (such as | |||
| 4390 | Informix) will rollback any outstanding changes. Applications not | |||
| 4391 | using C<AutoCommit> should explicitly call C<commit> or C<rollback> before | |||
| 4392 | calling C<disconnect>. | |||
| 4393 | ||||
| 4394 | The database is automatically disconnected by the C<DESTROY> method if | |||
| 4395 | still connected when there are no longer any references to the handle. | |||
| 4396 | The C<DESTROY> method for each driver should implicitly call C<rollback> to | |||
| 4397 | undo any uncommitted changes. This is vital behaviour to ensure that | |||
| 4398 | incomplete transactions don't get committed simply because Perl calls | |||
| 4399 | C<DESTROY> on every object before exiting. Also, do not rely on the order | |||
| 4400 | of object destruction during "global destruction", as it is undefined. | |||
| 4401 | ||||
| 4402 | Generally, if you want your changes to be commited or rolled back when | |||
| 4403 | you disconnect, then you should explicitly call L</commit> or L</rollback> | |||
| 4404 | before disconnecting. | |||
| 4405 | ||||
| 4406 | If you disconnect from a database while you still have active | |||
| 4407 | statement handles (e.g., SELECT statement handles that may have | |||
| 4408 | more data to fetch), you will get a warning. The warning may indicate | |||
| 4409 | that a fetch loop terminated early, perhaps due to an uncaught error. | |||
| 4410 | To avoid the warning call the C<finish> method on the active handles. | |||
| 4411 | ||||
| 4412 | ||||
| 4413 | =head3 C<ping> | |||
| 4414 | ||||
| 4415 | $rc = $dbh->ping; | |||
| 4416 | ||||
| 4417 | Attempts to determine, in a reasonably efficient way, if the database | |||
| 4418 | server is still running and the connection to it is still working. | |||
| 4419 | Individual drivers should implement this function in the most suitable | |||
| 4420 | manner for their database engine. | |||
| 4421 | ||||
| 4422 | The current I<default> implementation always returns true without | |||
| 4423 | actually doing anything. Actually, it returns "C<0 but true>" which is | |||
| 4424 | true but zero. That way you can tell if the return value is genuine or | |||
| 4425 | just the default. Drivers should override this method with one that | |||
| 4426 | does the right thing for their type of database. | |||
| 4427 | ||||
| 4428 | Few applications would have direct use for this method. See the specialized | |||
| 4429 | Apache::DBI module for one example usage. | |||
| 4430 | ||||
| 4431 | ||||
| 4432 | =head3 C<get_info> | |||
| 4433 | ||||
| 4434 | $value = $dbh->get_info( $info_type ); | |||
| 4435 | ||||
| 4436 | Returns information about the implementation, i.e. driver and data | |||
| 4437 | source capabilities, restrictions etc. It returns C<undef> for | |||
| 4438 | unknown or unimplemented information types. For example: | |||
| 4439 | ||||
| 4440 | $database_version = $dbh->get_info( 18 ); # SQL_DBMS_VER | |||
| 4441 | $max_select_tables = $dbh->get_info( 106 ); # SQL_MAXIMUM_TABLES_IN_SELECT | |||
| 4442 | ||||
| 4443 | See L</"Standards Reference Information"> for more detailed information | |||
| 4444 | about the information types and their meanings and possible return values. | |||
| 4445 | ||||
| 4446 | The DBI::Const::GetInfoType module exports a %GetInfoType hash that | |||
| 4447 | can be used to map info type names to numbers. For example: | |||
| 4448 | ||||
| 4449 | $database_version = $dbh->get_info( $GetInfoType{SQL_DBMS_VER} ); | |||
| 4450 | ||||
| 4451 | The names are a merging of the ANSI and ODBC standards (which differ | |||
| 4452 | in some cases). See L<DBI::Const::GetInfoType> for more details. | |||
| 4453 | ||||
| 4454 | Because some DBI methods make use of get_info(), drivers are strongly | |||
| 4455 | encouraged to support I<at least> the following very minimal set | |||
| 4456 | of information types to ensure the DBI itself works properly: | |||
| 4457 | ||||
| 4458 | Type Name Example A Example B | |||
| 4459 | ---- -------------------------- ------------ ---------------- | |||
| 4460 | 17 SQL_DBMS_NAME 'ACCESS' 'Oracle' | |||
| 4461 | 18 SQL_DBMS_VER '03.50.0000' '08.01.0721 ...' | |||
| 4462 | 29 SQL_IDENTIFIER_QUOTE_CHAR '`' '"' | |||
| 4463 | 41 SQL_CATALOG_NAME_SEPARATOR '.' '@' | |||
| 4464 | 114 SQL_CATALOG_LOCATION 1 2 | |||
| 4465 | ||||
| 4466 | =head3 C<table_info> | |||
| 4467 | ||||
| 4468 | $sth = $dbh->table_info( $catalog, $schema, $table, $type ); | |||
| 4469 | $sth = $dbh->table_info( $catalog, $schema, $table, $type, \%attr ); | |||
| 4470 | ||||
| 4471 | # then $sth->fetchall_arrayref or $sth->fetchall_hashref etc | |||
| 4472 | ||||
| 4473 | Returns an active statement handle that can be used to fetch | |||
| 4474 | information about tables and views that exist in the database. | |||
| 4475 | ||||
| 4476 | The arguments $catalog, $schema and $table may accept search patterns | |||
| 4477 | according to the database/driver, for example: $table = '%FOO%'; | |||
| 4478 | Remember that the underscore character ('C<_>') is a search pattern | |||
| 4479 | that means match any character, so 'FOO_%' is the same as 'FOO%' | |||
| 4480 | and 'FOO_BAR%' will match names like 'FOO1BAR'. | |||
| 4481 | ||||
| 4482 | The value of $type is a comma-separated list of one or more types of | |||
| 4483 | tables to be returned in the result set. Each value may optionally be | |||
| 4484 | quoted, e.g.: | |||
| 4485 | ||||
| 4486 | $type = "TABLE"; | |||
| 4487 | $type = "'TABLE','VIEW'"; | |||
| 4488 | ||||
| 4489 | In addition the following special cases may also be supported by some drivers: | |||
| 4490 | ||||
| 4491 | =over 4 | |||
| 4492 | ||||
| 4493 | =item * | |||
| 4494 | If the value of $catalog is '%' and $schema and $table name | |||
| 4495 | are empty strings, the result set contains a list of catalog names. | |||
| 4496 | For example: | |||
| 4497 | ||||
| 4498 | $sth = $dbh->table_info('%', '', ''); | |||
| 4499 | ||||
| 4500 | =item * | |||
| 4501 | If the value of $schema is '%' and $catalog and $table are empty | |||
| 4502 | strings, the result set contains a list of schema names. | |||
| 4503 | ||||
| 4504 | =item * | |||
| 4505 | If the value of $type is '%' and $catalog, $schema, and $table are all | |||
| 4506 | empty strings, the result set contains a list of table types. | |||
| 4507 | ||||
| 4508 | =back | |||
| 4509 | ||||
| 4510 | If your driver doesn't support one or more of the selection filter | |||
| 4511 | parameters then you may get back more than you asked for and can | |||
| 4512 | do the filtering yourself. | |||
| 4513 | ||||
| 4514 | This method can be expensive, and can return a large amount of data. | |||
| 4515 | (For example, small Oracle installation returns over 2000 rows.) | |||
| 4516 | So it's a good idea to use the filters to limit the data as much as possible. | |||
| 4517 | ||||
| 4518 | The statement handle returned has at least the following fields in the | |||
| 4519 | order show below. Other fields, after these, may also be present. | |||
| 4520 | ||||
| 4521 | B<TABLE_CAT>: Table catalog identifier. This field is NULL (C<undef>) if not | |||
| 4522 | applicable to the data source, which is usually the case. This field | |||
| 4523 | is empty if not applicable to the table. | |||
| 4524 | ||||
| 4525 | B<TABLE_SCHEM>: The name of the schema containing the TABLE_NAME value. | |||
| 4526 | This field is NULL (C<undef>) if not applicable to data source, and | |||
| 4527 | empty if not applicable to the table. | |||
| 4528 | ||||
| 4529 | B<TABLE_NAME>: Name of the table (or view, synonym, etc). | |||
| 4530 | ||||
| 4531 | B<TABLE_TYPE>: One of the following: "TABLE", "VIEW", "SYSTEM TABLE", | |||
| 4532 | "GLOBAL TEMPORARY", "LOCAL TEMPORARY", "ALIAS", "SYNONYM" or a type | |||
| 4533 | identifier that is specific to the data | |||
| 4534 | source. | |||
| 4535 | ||||
| 4536 | B<REMARKS>: A description of the table. May be NULL (C<undef>). | |||
| 4537 | ||||
| 4538 | Note that C<table_info> might not return records for all tables. | |||
| 4539 | Applications can use any valid table regardless of whether it's | |||
| 4540 | returned by C<table_info>. | |||
| 4541 | ||||
| 4542 | See also L</tables>, L</"Catalog Methods"> and | |||
| 4543 | L</"Standards Reference Information">. | |||
| 4544 | ||||
| 4545 | =head3 C<column_info> | |||
| 4546 | ||||
| 4547 | $sth = $dbh->column_info( $catalog, $schema, $table, $column ); | |||
| 4548 | ||||
| 4549 | # then $sth->fetchall_arrayref or $sth->fetchall_hashref etc | |||
| 4550 | ||||
| 4551 | Returns an active statement handle that can be used to fetch | |||
| 4552 | information about columns in specified tables. | |||
| 4553 | ||||
| 4554 | The arguments $schema, $table and $column may accept search patterns | |||
| 4555 | according to the database/driver, for example: $table = '%FOO%'; | |||
| 4556 | ||||
| 4557 | Note: The support for the selection criteria is driver specific. If the | |||
| 4558 | driver doesn't support one or more of them then you may get back more | |||
| 4559 | than you asked for and can do the filtering yourself. | |||
| 4560 | ||||
| 4561 | If the arguments don't match any tables then you'll still get a statement | |||
| 4562 | handle, it'll just return no rows. | |||
| 4563 | ||||
| 4564 | The statement handle returned has at least the following fields in the | |||
| 4565 | order shown below. Other fields, after these, may also be present. | |||
| 4566 | ||||
| 4567 | B<TABLE_CAT>: The catalog identifier. | |||
| 4568 | This field is NULL (C<undef>) if not applicable to the data source, | |||
| 4569 | which is often the case. This field is empty if not applicable to the | |||
| 4570 | table. | |||
| 4571 | ||||
| 4572 | B<TABLE_SCHEM>: The schema identifier. | |||
| 4573 | This field is NULL (C<undef>) if not applicable to the data source, | |||
| 4574 | and empty if not applicable to the table. | |||
| 4575 | ||||
| 4576 | B<TABLE_NAME>: The table identifier. | |||
| 4577 | Note: A driver may provide column metadata not only for base tables, but | |||
| 4578 | also for derived objects like SYNONYMS etc. | |||
| 4579 | ||||
| 4580 | B<COLUMN_NAME>: The column identifier. | |||
| 4581 | ||||
| 4582 | B<DATA_TYPE>: The concise data type code. | |||
| 4583 | ||||
| 4584 | B<TYPE_NAME>: A data source dependent data type name. | |||
| 4585 | ||||
| 4586 | B<COLUMN_SIZE>: The column size. | |||
| 4587 | This is the maximum length in characters for character data types, | |||
| 4588 | the number of digits or bits for numeric data types or the length | |||
| 4589 | in the representation of temporal types. | |||
| 4590 | See the relevant specifications for detailed information. | |||
| 4591 | ||||
| 4592 | B<BUFFER_LENGTH>: The length in bytes of transferred data. | |||
| 4593 | ||||
| 4594 | B<DECIMAL_DIGITS>: The total number of significant digits to the right of | |||
| 4595 | the decimal point. | |||
| 4596 | ||||
| 4597 | B<NUM_PREC_RADIX>: The radix for numeric precision. | |||
| 4598 | The value is 10 or 2 for numeric data types and NULL (C<undef>) if not | |||
| 4599 | applicable. | |||
| 4600 | ||||
| 4601 | B<NULLABLE>: Indicates if a column can accept NULLs. | |||
| 4602 | The following values are defined: | |||
| 4603 | ||||
| 4604 | SQL_NO_NULLS 0 | |||
| 4605 | SQL_NULLABLE 1 | |||
| 4606 | SQL_NULLABLE_UNKNOWN 2 | |||
| 4607 | ||||
| 4608 | B<REMARKS>: A description of the column. | |||
| 4609 | ||||
| 4610 | B<COLUMN_DEF>: The default value of the column. | |||
| 4611 | ||||
| 4612 | B<SQL_DATA_TYPE>: The SQL data type. | |||
| 4613 | ||||
| 4614 | B<SQL_DATETIME_SUB>: The subtype code for datetime and interval data types. | |||
| 4615 | ||||
| 4616 | B<CHAR_OCTET_LENGTH>: The maximum length in bytes of a character or binary | |||
| 4617 | data type column. | |||
| 4618 | ||||
| 4619 | B<ORDINAL_POSITION>: The column sequence number (starting with 1). | |||
| 4620 | ||||
| 4621 | B<IS_NULLABLE>: Indicates if the column can accept NULLs. | |||
| 4622 | Possible values are: 'NO', 'YES' and ''. | |||
| 4623 | ||||
| 4624 | SQL/CLI defines the following additional columns: | |||
| 4625 | ||||
| 4626 | CHAR_SET_CAT | |||
| 4627 | CHAR_SET_SCHEM | |||
| 4628 | CHAR_SET_NAME | |||
| 4629 | COLLATION_CAT | |||
| 4630 | COLLATION_SCHEM | |||
| 4631 | COLLATION_NAME | |||
| 4632 | UDT_CAT | |||
| 4633 | UDT_SCHEM | |||
| 4634 | UDT_NAME | |||
| 4635 | DOMAIN_CAT | |||
| 4636 | DOMAIN_SCHEM | |||
| 4637 | DOMAIN_NAME | |||
| 4638 | SCOPE_CAT | |||
| 4639 | SCOPE_SCHEM | |||
| 4640 | SCOPE_NAME | |||
| 4641 | MAX_CARDINALITY | |||
| 4642 | DTD_IDENTIFIER | |||
| 4643 | IS_SELF_REF | |||
| 4644 | ||||
| 4645 | Drivers capable of supplying any of those values should do so in | |||
| 4646 | the corresponding column and supply undef values for the others. | |||
| 4647 | ||||
| 4648 | Drivers wishing to provide extra database/driver specific information | |||
| 4649 | should do so in extra columns beyond all those listed above, and | |||
| 4650 | use lowercase field names with the driver-specific prefix (i.e., | |||
| 4651 | 'ora_...'). Applications accessing such fields should do so by name | |||
| 4652 | and not by column number. | |||
| 4653 | ||||
| 4654 | The result set is ordered by TABLE_CAT, TABLE_SCHEM, TABLE_NAME | |||
| 4655 | and ORDINAL_POSITION. | |||
| 4656 | ||||
| 4657 | Note: There is some overlap with statement attributes (in perl) and | |||
| 4658 | SQLDescribeCol (in ODBC). However, SQLColumns provides more metadata. | |||
| 4659 | ||||
| 4660 | See also L</"Catalog Methods"> and L</"Standards Reference Information">. | |||
| 4661 | ||||
| 4662 | =head3 C<primary_key_info> | |||
| 4663 | ||||
| 4664 | $sth = $dbh->primary_key_info( $catalog, $schema, $table ); | |||
| 4665 | ||||
| 4666 | # then $sth->fetchall_arrayref or $sth->fetchall_hashref etc | |||
| 4667 | ||||
| 4668 | Returns an active statement handle that can be used to fetch information | |||
| 4669 | about columns that make up the primary key for a table. | |||
| 4670 | The arguments don't accept search patterns (unlike table_info()). | |||
| 4671 | ||||
| 4672 | The statement handle will return one row per column, ordered by | |||
| 4673 | TABLE_CAT, TABLE_SCHEM, TABLE_NAME, and KEY_SEQ. | |||
| 4674 | If there is no primary key then the statement handle will fetch no rows. | |||
| 4675 | ||||
| 4676 | Note: The support for the selection criteria, such as $catalog, is | |||
| 4677 | driver specific. If the driver doesn't support catalogs and/or | |||
| 4678 | schemas, it may ignore these criteria. | |||
| 4679 | ||||
| 4680 | The statement handle returned has at least the following fields in the | |||
| 4681 | order shown below. Other fields, after these, may also be present. | |||
| 4682 | ||||
| 4683 | B<TABLE_CAT>: The catalog identifier. | |||
| 4684 | This field is NULL (C<undef>) if not applicable to the data source, | |||
| 4685 | which is often the case. This field is empty if not applicable to the | |||
| 4686 | table. | |||
| 4687 | ||||
| 4688 | B<TABLE_SCHEM>: The schema identifier. | |||
| 4689 | This field is NULL (C<undef>) if not applicable to the data source, | |||
| 4690 | and empty if not applicable to the table. | |||
| 4691 | ||||
| 4692 | B<TABLE_NAME>: The table identifier. | |||
| 4693 | ||||
| 4694 | B<COLUMN_NAME>: The column identifier. | |||
| 4695 | ||||
| 4696 | B<KEY_SEQ>: The column sequence number (starting with 1). | |||
| 4697 | Note: This field is named B<ORDINAL_POSITION> in SQL/CLI. | |||
| 4698 | ||||
| 4699 | B<PK_NAME>: The primary key constraint identifier. | |||
| 4700 | This field is NULL (C<undef>) if not applicable to the data source. | |||
| 4701 | ||||
| 4702 | See also L</"Catalog Methods"> and L</"Standards Reference Information">. | |||
| 4703 | ||||
| 4704 | =head3 C<primary_key> | |||
| 4705 | ||||
| 4706 | @key_column_names = $dbh->primary_key( $catalog, $schema, $table ); | |||
| 4707 | ||||
| 4708 | Simple interface to the primary_key_info() method. Returns a list of | |||
| 4709 | the column names that comprise the primary key of the specified table. | |||
| 4710 | The list is in primary key column sequence order. | |||
| 4711 | If there is no primary key then an empty list is returned. | |||
| 4712 | ||||
| 4713 | =head3 C<foreign_key_info> | |||
| 4714 | ||||
| 4715 | $sth = $dbh->foreign_key_info( $pk_catalog, $pk_schema, $pk_table | |||
| 4716 | , $fk_catalog, $fk_schema, $fk_table ); | |||
| 4717 | ||||
| 4718 | $sth = $dbh->foreign_key_info( $pk_catalog, $pk_schema, $pk_table | |||
| 4719 | , $fk_catalog, $fk_schema, $fk_table | |||
| 4720 | , \%attr ); | |||
| 4721 | ||||
| 4722 | # then $sth->fetchall_arrayref or $sth->fetchall_hashref etc | |||
| 4723 | ||||
| 4724 | Returns an active statement handle that can be used to fetch information | |||
| 4725 | about foreign keys in and/or referencing the specified table(s). | |||
| 4726 | The arguments don't accept search patterns (unlike table_info()). | |||
| 4727 | ||||
| 4728 | C<$pk_catalog>, C<$pk_schema>, C<$pk_table> | |||
| 4729 | identify the primary (unique) key table (B<PKT>). | |||
| 4730 | ||||
| 4731 | C<$fk_catalog>, C<$fk_schema>, C<$fk_table> | |||
| 4732 | identify the foreign key table (B<FKT>). | |||
| 4733 | ||||
| 4734 | If both B<PKT> and B<FKT> are given, the function returns the foreign key, if | |||
| 4735 | any, in table B<FKT> that refers to the primary (unique) key of table B<PKT>. | |||
| 4736 | (Note: In SQL/CLI, the result is implementation-defined.) | |||
| 4737 | ||||
| 4738 | If only B<PKT> is given, then the result set contains the primary key | |||
| 4739 | of that table and all foreign keys that refer to it. | |||
| 4740 | ||||
| 4741 | If only B<FKT> is given, then the result set contains all foreign keys | |||
| 4742 | in that table and the primary keys to which they refer. | |||
| 4743 | (Note: In SQL/CLI, the result includes unique keys too.) | |||
| 4744 | ||||
| 4745 | For example: | |||
| 4746 | ||||
| 4747 | $sth = $dbh->foreign_key_info( undef, $user, 'master'); | |||
| 4748 | $sth = $dbh->foreign_key_info( undef, undef, undef , undef, $user, 'detail'); | |||
| 4749 | $sth = $dbh->foreign_key_info( undef, $user, 'master', undef, $user, 'detail'); | |||
| 4750 | ||||
| 4751 | # then $sth->fetchall_arrayref or $sth->fetchall_hashref etc | |||
| 4752 | ||||
| 4753 | Note: The support for the selection criteria, such as C<$catalog>, is | |||
| 4754 | driver specific. If the driver doesn't support catalogs and/or | |||
| 4755 | schemas, it may ignore these criteria. | |||
| 4756 | ||||
| 4757 | The statement handle returned has the following fields in the order shown below. | |||
| 4758 | Because ODBC never includes unique keys, they define different columns in the | |||
| 4759 | result set than SQL/CLI. SQL/CLI column names are shown in parentheses. | |||
| 4760 | ||||
| 4761 | B<PKTABLE_CAT ( UK_TABLE_CAT )>: | |||
| 4762 | The primary (unique) key table catalog identifier. | |||
| 4763 | This field is NULL (C<undef>) if not applicable to the data source, | |||
| 4764 | which is often the case. This field is empty if not applicable to the | |||
| 4765 | table. | |||
| 4766 | ||||
| 4767 | B<PKTABLE_SCHEM ( UK_TABLE_SCHEM )>: | |||
| 4768 | The primary (unique) key table schema identifier. | |||
| 4769 | This field is NULL (C<undef>) if not applicable to the data source, | |||
| 4770 | and empty if not applicable to the table. | |||
| 4771 | ||||
| 4772 | B<PKTABLE_NAME ( UK_TABLE_NAME )>: | |||
| 4773 | The primary (unique) key table identifier. | |||
| 4774 | ||||
| 4775 | B<PKCOLUMN_NAME (UK_COLUMN_NAME )>: | |||
| 4776 | The primary (unique) key column identifier. | |||
| 4777 | ||||
| 4778 | B<FKTABLE_CAT ( FK_TABLE_CAT )>: | |||
| 4779 | The foreign key table catalog identifier. | |||
| 4780 | This field is NULL (C<undef>) if not applicable to the data source, | |||
| 4781 | which is often the case. This field is empty if not applicable to the | |||
| 4782 | table. | |||
| 4783 | ||||
| 4784 | B<FKTABLE_SCHEM ( FK_TABLE_SCHEM )>: | |||
| 4785 | The foreign key table schema identifier. | |||
| 4786 | This field is NULL (C<undef>) if not applicable to the data source, | |||
| 4787 | and empty if not applicable to the table. | |||
| 4788 | ||||
| 4789 | B<FKTABLE_NAME ( FK_TABLE_NAME )>: | |||
| 4790 | The foreign key table identifier. | |||
| 4791 | ||||
| 4792 | B<FKCOLUMN_NAME ( FK_COLUMN_NAME )>: | |||
| 4793 | The foreign key column identifier. | |||
| 4794 | ||||
| 4795 | B<KEY_SEQ ( ORDINAL_POSITION )>: | |||
| 4796 | The column sequence number (starting with 1). | |||
| 4797 | ||||
| 4798 | B<UPDATE_RULE ( UPDATE_RULE )>: | |||
| 4799 | The referential action for the UPDATE rule. | |||
| 4800 | The following codes are defined: | |||
| 4801 | ||||
| 4802 | CASCADE 0 | |||
| 4803 | RESTRICT 1 | |||
| 4804 | SET NULL 2 | |||
| 4805 | NO ACTION 3 | |||
| 4806 | SET DEFAULT 4 | |||
| 4807 | ||||
| 4808 | B<DELETE_RULE ( DELETE_RULE )>: | |||
| 4809 | The referential action for the DELETE rule. | |||
| 4810 | The codes are the same as for UPDATE_RULE. | |||
| 4811 | ||||
| 4812 | B<FK_NAME ( FK_NAME )>: | |||
| 4813 | The foreign key name. | |||
| 4814 | ||||
| 4815 | B<PK_NAME ( UK_NAME )>: | |||
| 4816 | The primary (unique) key name. | |||
| 4817 | ||||
| 4818 | B<DEFERRABILITY ( DEFERABILITY )>: | |||
| 4819 | The deferrability of the foreign key constraint. | |||
| 4820 | The following codes are defined: | |||
| 4821 | ||||
| 4822 | INITIALLY DEFERRED 5 | |||
| 4823 | INITIALLY IMMEDIATE 6 | |||
| 4824 | NOT DEFERRABLE 7 | |||
| 4825 | ||||
| 4826 | B< ( UNIQUE_OR_PRIMARY )>: | |||
| 4827 | This column is necessary if a driver includes all candidate (i.e. primary and | |||
| 4828 | alternate) keys in the result set (as specified by SQL/CLI). | |||
| 4829 | The value of this column is UNIQUE if the foreign key references an alternate | |||
| 4830 | key and PRIMARY if the foreign key references a primary key, or it | |||
| 4831 | may be undefined if the driver doesn't have access to the information. | |||
| 4832 | ||||
| 4833 | See also L</"Catalog Methods"> and L</"Standards Reference Information">. | |||
| 4834 | ||||
| 4835 | =head3 C<statistics_info> | |||
| 4836 | ||||
| 4837 | B<Warning:> This method is experimental and may change. | |||
| 4838 | ||||
| 4839 | $sth = $dbh->statistics_info( $catalog, $schema, $table, $unique_only, $quick ); | |||
| 4840 | ||||
| 4841 | # then $sth->fetchall_arrayref or $sth->fetchall_hashref etc | |||
| 4842 | ||||
| 4843 | Returns an active statement handle that can be used to fetch statistical | |||
| 4844 | information about a table and its indexes. | |||
| 4845 | ||||
| 4846 | The arguments don't accept search patterns (unlike L</table_info>). | |||
| 4847 | ||||
| 4848 | If the boolean argument $unique_only is true, only UNIQUE indexes will be | |||
| 4849 | returned in the result set, otherwise all indexes will be returned. | |||
| 4850 | ||||
| 4851 | If the boolean argument $quick is set, the actual statistical information | |||
| 4852 | columns (CARDINALITY and PAGES) will only be returned if they are readily | |||
| 4853 | available from the server, and might not be current. Some databases may | |||
| 4854 | return stale statistics or no statistics at all with this flag set. | |||
| 4855 | ||||
| 4856 | The statement handle will return at most one row per column name per index, | |||
| 4857 | plus at most one row for the entire table itself, ordered by NON_UNIQUE, TYPE, | |||
| 4858 | INDEX_QUALIFIER, INDEX_NAME, and ORDINAL_POSITION. | |||
| 4859 | ||||
| 4860 | Note: The support for the selection criteria, such as $catalog, is | |||
| 4861 | driver specific. If the driver doesn't support catalogs and/or | |||
| 4862 | schemas, it may ignore these criteria. | |||
| 4863 | ||||
| 4864 | The statement handle returned has at least the following fields in the | |||
| 4865 | order shown below. Other fields, after these, may also be present. | |||
| 4866 | ||||
| 4867 | B<TABLE_CAT>: The catalog identifier. | |||
| 4868 | This field is NULL (C<undef>) if not applicable to the data source, | |||
| 4869 | which is often the case. This field is empty if not applicable to the | |||
| 4870 | table. | |||
| 4871 | ||||
| 4872 | B<TABLE_SCHEM>: The schema identifier. | |||
| 4873 | This field is NULL (C<undef>) if not applicable to the data source, | |||
| 4874 | and empty if not applicable to the table. | |||
| 4875 | ||||
| 4876 | B<TABLE_NAME>: The table identifier. | |||
| 4877 | ||||
| 4878 | B<NON_UNIQUE>: Unique index indicator. | |||
| 4879 | Returns 0 for unique indexes, 1 for non-unique indexes | |||
| 4880 | ||||
| 4881 | B<INDEX_QUALIFIER>: Index qualifier identifier. | |||
| 4882 | The identifier that is used to qualify the index name when doing a | |||
| 4883 | C<DROP INDEX>; NULL (C<undef>) is returned if an index qualifier is not | |||
| 4884 | supported by the data source. | |||
| 4885 | If a non-NULL (defined) value is returned in this column, it must be used | |||
| 4886 | to qualify the index name on a C<DROP INDEX> statement; otherwise, | |||
| 4887 | the TABLE_SCHEM should be used to qualify the index name. | |||
| 4888 | ||||
| 4889 | B<INDEX_NAME>: The index identifier. | |||
| 4890 | ||||
| 4891 | B<TYPE>: The type of information being returned. Can be any of the | |||
| 4892 | following values: 'table', 'btree', 'clustered', 'content', 'hashed', | |||
| 4893 | or 'other'. | |||
| 4894 | ||||
| 4895 | In the case that this field is 'table', all fields | |||
| 4896 | other than TABLE_CAT, TABLE_SCHEM, TABLE_NAME, TYPE, | |||
| 4897 | CARDINALITY, and PAGES will be NULL (C<undef>). | |||
| 4898 | ||||
| 4899 | B<ORDINAL_POSITION>: Column sequence number (starting with 1). | |||
| 4900 | ||||
| 4901 | B<COLUMN_NAME>: The column identifier. | |||
| 4902 | ||||
| 4903 | B<ASC_OR_DESC>: Column sort sequence. | |||
| 4904 | C<A> for Ascending, C<D> for Descending, or NULL (C<undef>) if | |||
| 4905 | not supported for this index. | |||
| 4906 | ||||
| 4907 | B<CARDINALITY>: Cardinality of the table or index. | |||
| 4908 | For indexes, this is the number of unique values in the index. | |||
| 4909 | For tables, this is the number of rows in the table. | |||
| 4910 | If not supported, the value will be NULL (C<undef>). | |||
| 4911 | ||||
| 4912 | B<PAGES>: Number of storage pages used by this table or index. | |||
| 4913 | If not supported, the value will be NULL (C<undef>). | |||
| 4914 | ||||
| 4915 | B<FILTER_CONDITION>: The index filter condition as a string. | |||
| 4916 | If the index is not a filtered index, or it cannot be determined | |||
| 4917 | whether the index is a filtered index, this value is NULL (C<undef>). | |||
| 4918 | If the index is a filtered index, but the filter condition | |||
| 4919 | cannot be determined, this value is the empty string C<''>. | |||
| 4920 | Otherwise it will be the literal filter condition as a string, | |||
| 4921 | such as C<SALARY <= 4500>. | |||
| 4922 | ||||
| 4923 | See also L</"Catalog Methods"> and L</"Standards Reference Information">. | |||
| 4924 | ||||
| 4925 | =head3 C<tables> | |||
| 4926 | ||||
| 4927 | @names = $dbh->tables( $catalog, $schema, $table, $type ); | |||
| 4928 | @names = $dbh->tables; # deprecated | |||
| 4929 | ||||
| 4930 | Simple interface to table_info(). Returns a list of matching | |||
| 4931 | table names, possibly including a catalog/schema prefix. | |||
| 4932 | ||||
| 4933 | See L</table_info> for a description of the parameters. | |||
| 4934 | ||||
| 4935 | If C<$dbh-E<gt>get_info(29)> returns true (29 is SQL_IDENTIFIER_QUOTE_CHAR) | |||
| 4936 | then the table names are constructed and quoted by L</quote_identifier> | |||
| 4937 | to ensure they are usable even if they contain whitespace or reserved | |||
| 4938 | words etc. This means that the table names returned will include | |||
| 4939 | quote characters. | |||
| 4940 | ||||
| 4941 | =head3 C<type_info_all> | |||
| 4942 | ||||
| 4943 | $type_info_all = $dbh->type_info_all; | |||
| 4944 | ||||
| 4945 | Returns a reference to an array which holds information about each data | |||
| 4946 | type variant supported by the database and driver. The array and its | |||
| 4947 | contents should be treated as read-only. | |||
| 4948 | ||||
| 4949 | The first item is a reference to an 'index' hash of C<Name =>E<gt> C<Index> pairs. | |||
| 4950 | The items following that are references to arrays, one per supported data | |||
| 4951 | type variant. The leading index hash defines the names and order of the | |||
| 4952 | fields within the arrays that follow it. | |||
| 4953 | For example: | |||
| 4954 | ||||
| 4955 | $type_info_all = [ | |||
| 4956 | { TYPE_NAME => 0, | |||
| 4957 | DATA_TYPE => 1, | |||
| 4958 | COLUMN_SIZE => 2, # was PRECISION originally | |||
| 4959 | LITERAL_PREFIX => 3, | |||
| 4960 | LITERAL_SUFFIX => 4, | |||
| 4961 | CREATE_PARAMS => 5, | |||
| 4962 | NULLABLE => 6, | |||
| 4963 | CASE_SENSITIVE => 7, | |||
| 4964 | SEARCHABLE => 8, | |||
| 4965 | UNSIGNED_ATTRIBUTE=> 9, | |||
| 4966 | FIXED_PREC_SCALE => 10, # was MONEY originally | |||
| 4967 | AUTO_UNIQUE_VALUE => 11, # was AUTO_INCREMENT originally | |||
| 4968 | LOCAL_TYPE_NAME => 12, | |||
| 4969 | MINIMUM_SCALE => 13, | |||
| 4970 | MAXIMUM_SCALE => 14, | |||
| 4971 | SQL_DATA_TYPE => 15, | |||
| 4972 | SQL_DATETIME_SUB => 16, | |||
| 4973 | NUM_PREC_RADIX => 17, | |||
| 4974 | INTERVAL_PRECISION=> 18, | |||
| 4975 | }, | |||
| 4976 | [ 'VARCHAR', SQL_VARCHAR, | |||
| 4977 | undef, "'","'", undef,0, 1,1,0,0,0,undef,1,255, undef | |||
| 4978 | ], | |||
| 4979 | [ 'INTEGER', SQL_INTEGER, | |||
| 4980 | undef, "", "", undef,0, 0,1,0,0,0,undef,0, 0, 10 | |||
| 4981 | ], | |||
| 4982 | ]; | |||
| 4983 | ||||
| 4984 | More than one row may have the same value in the C<DATA_TYPE> | |||
| 4985 | field if there are different ways to spell the type name and/or there | |||
| 4986 | are variants of the type with different attributes (e.g., with and | |||
| 4987 | without C<AUTO_UNIQUE_VALUE> set, with and without C<UNSIGNED_ATTRIBUTE>, etc). | |||
| 4988 | ||||
| 4989 | The rows are ordered by C<DATA_TYPE> first and then by how closely each | |||
| 4990 | type maps to the corresponding ODBC SQL data type, closest first. | |||
| 4991 | ||||
| 4992 | The meaning of the fields is described in the documentation for | |||
| 4993 | the L</type_info> method. | |||
| 4994 | ||||
| 4995 | An 'index' hash is provided so you don't need to rely on index | |||
| 4996 | values defined above. However, using DBD::ODBC with some old ODBC | |||
| 4997 | drivers may return older names, shown as comments in the example above. | |||
| 4998 | Another issue with the index hash is that the lettercase of the | |||
| 4999 | keys is not defined. It is usually uppercase, as show here, but | |||
| 5000 | drivers may return names with any lettercase. | |||
| 5001 | ||||
| 5002 | Drivers are also free to return extra driver-specific columns of | |||
| 5003 | information - though it's recommended that they start at column | |||
| 5004 | index 50 to leave room for expansion of the DBI/ODBC specification. | |||
| 5005 | ||||
| 5006 | The type_info_all() method is not normally used directly. | |||
| 5007 | The L</type_info> method provides a more usable and useful interface | |||
| 5008 | to the data. | |||
| 5009 | ||||
| 5010 | =head3 C<type_info> | |||
| 5011 | ||||
| 5012 | @type_info = $dbh->type_info($data_type); | |||
| 5013 | ||||
| 5014 | Returns a list of hash references holding information about one or more | |||
| 5015 | variants of $data_type. The list is ordered by C<DATA_TYPE> first and | |||
| 5016 | then by how closely each type maps to the corresponding ODBC SQL data | |||
| 5017 | type, closest first. If called in a scalar context then only the first | |||
| 5018 | (best) element is returned. | |||
| 5019 | ||||
| 5020 | If $data_type is undefined or C<SQL_ALL_TYPES>, then the list will | |||
| 5021 | contain hashes for all data type variants supported by the database and driver. | |||
| 5022 | ||||
| 5023 | If $data_type is an array reference then C<type_info> returns the | |||
| 5024 | information for the I<first> type in the array that has any matches. | |||
| 5025 | ||||
| 5026 | The keys of the hash follow the same letter case conventions as the | |||
| 5027 | rest of the DBI (see L</Naming Conventions and Name Space>). The | |||
| 5028 | following uppercase items should always exist, though may be undef: | |||
| 5029 | ||||
| 5030 | =over 4 | |||
| 5031 | ||||
| 5032 | =item TYPE_NAME (string) | |||
| 5033 | ||||
| 5034 | Data type name for use in CREATE TABLE statements etc. | |||
| 5035 | ||||
| 5036 | =item DATA_TYPE (integer) | |||
| 5037 | ||||
| 5038 | SQL data type number. | |||
| 5039 | ||||
| 5040 | =item COLUMN_SIZE (integer) | |||
| 5041 | ||||
| 5042 | For numeric types, this is either the total number of digits (if the | |||
| 5043 | NUM_PREC_RADIX value is 10) or the total number of bits allowed in the | |||
| 5044 | column (if NUM_PREC_RADIX is 2). | |||
| 5045 | ||||
| 5046 | For string types, this is the maximum size of the string in characters. | |||
| 5047 | ||||
| 5048 | For date and interval types, this is the maximum number of characters | |||
| 5049 | needed to display the value. | |||
| 5050 | ||||
| 5051 | =item LITERAL_PREFIX (string) | |||
| 5052 | ||||
| 5053 | Characters used to prefix a literal. A typical prefix is "C<'>" for characters, | |||
| 5054 | or possibly "C<0x>" for binary values passed as hexadecimal. NULL (C<undef>) is | |||
| 5055 | returned for data types for which this is not applicable. | |||
| 5056 | ||||
| 5057 | ||||
| 5058 | =item LITERAL_SUFFIX (string) | |||
| 5059 | ||||
| 5060 | Characters used to suffix a literal. Typically "C<'>" for characters. | |||
| 5061 | NULL (C<undef>) is returned for data types where this is not applicable. | |||
| 5062 | ||||
| 5063 | =item CREATE_PARAMS (string) | |||
| 5064 | ||||
| 5065 | Parameter names for data type definition. For example, C<CREATE_PARAMS> for a | |||
| 5066 | C<DECIMAL> would be "C<precision,scale>" if the DECIMAL type should be | |||
| 5067 | declared as C<DECIMAL(>I<precision,scale>C<)> where I<precision> and I<scale> | |||
| 5068 | are integer values. For a C<VARCHAR> it would be "C<max length>". | |||
| 5069 | NULL (C<undef>) is returned for data types for which this is not applicable. | |||
| 5070 | ||||
| 5071 | =item NULLABLE (integer) | |||
| 5072 | ||||
| 5073 | Indicates whether the data type accepts a NULL value: | |||
| 5074 | C<0> or an empty string = no, C<1> = yes, C<2> = unknown. | |||
| 5075 | ||||
| 5076 | =item CASE_SENSITIVE (boolean) | |||
| 5077 | ||||
| 5078 | Indicates whether the data type is case sensitive in collations and | |||
| 5079 | comparisons. | |||
| 5080 | ||||
| 5081 | =item SEARCHABLE (integer) | |||
| 5082 | ||||
| 5083 | Indicates how the data type can be used in a WHERE clause, as | |||
| 5084 | follows: | |||
| 5085 | ||||
| 5086 | 0 - Cannot be used in a WHERE clause | |||
| 5087 | 1 - Only with a LIKE predicate | |||
| 5088 | 2 - All comparison operators except LIKE | |||
| 5089 | 3 - Can be used in a WHERE clause with any comparison operator | |||
| 5090 | ||||
| 5091 | =item UNSIGNED_ATTRIBUTE (boolean) | |||
| 5092 | ||||
| 5093 | Indicates whether the data type is unsigned. NULL (C<undef>) is returned | |||
| 5094 | for data types for which this is not applicable. | |||
| 5095 | ||||
| 5096 | =item FIXED_PREC_SCALE (boolean) | |||
| 5097 | ||||
| 5098 | Indicates whether the data type always has the same precision and scale | |||
| 5099 | (such as a money type). NULL (C<undef>) is returned for data types | |||
| 5100 | for which | |||
| 5101 | this is not applicable. | |||
| 5102 | ||||
| 5103 | =item AUTO_UNIQUE_VALUE (boolean) | |||
| 5104 | ||||
| 5105 | Indicates whether a column of this data type is automatically set to a | |||
| 5106 | unique value whenever a new row is inserted. NULL (C<undef>) is returned | |||
| 5107 | for data types for which this is not applicable. | |||
| 5108 | ||||
| 5109 | =item LOCAL_TYPE_NAME (string) | |||
| 5110 | ||||
| 5111 | Localized version of the C<TYPE_NAME> for use in dialog with users. | |||
| 5112 | NULL (C<undef>) is returned if a localized name is not available (in which | |||
| 5113 | case C<TYPE_NAME> should be used). | |||
| 5114 | ||||
| 5115 | =item MINIMUM_SCALE (integer) | |||
| 5116 | ||||
| 5117 | The minimum scale of the data type. If a data type has a fixed scale, | |||
| 5118 | then C<MAXIMUM_SCALE> holds the same value. NULL (C<undef>) is returned for | |||
| 5119 | data types for which this is not applicable. | |||
| 5120 | ||||
| 5121 | =item MAXIMUM_SCALE (integer) | |||
| 5122 | ||||
| 5123 | The maximum scale of the data type. If a data type has a fixed scale, | |||
| 5124 | then C<MINIMUM_SCALE> holds the same value. NULL (C<undef>) is returned for | |||
| 5125 | data types for which this is not applicable. | |||
| 5126 | ||||
| 5127 | =item SQL_DATA_TYPE (integer) | |||
| 5128 | ||||
| 5129 | This column is the same as the C<DATA_TYPE> column, except for interval | |||
| 5130 | and datetime data types. For interval and datetime data types, the | |||
| 5131 | C<SQL_DATA_TYPE> field will return C<SQL_INTERVAL> or C<SQL_DATETIME>, and the | |||
| 5132 | C<SQL_DATETIME_SUB> field below will return the subcode for the specific | |||
| 5133 | interval or datetime data type. If this field is NULL, then the driver | |||
| 5134 | does not support or report on interval or datetime subtypes. | |||
| 5135 | ||||
| 5136 | =item SQL_DATETIME_SUB (integer) | |||
| 5137 | ||||
| 5138 | For interval or datetime data types, where the C<SQL_DATA_TYPE> | |||
| 5139 | field above is C<SQL_INTERVAL> or C<SQL_DATETIME>, this field will | |||
| 5140 | hold the I<subcode> for the specific interval or datetime data type. | |||
| 5141 | Otherwise it will be NULL (C<undef>). | |||
| 5142 | ||||
| 5143 | Although not mentioned explicitly in the standards, it seems there | |||
| 5144 | is a simple relationship between these values: | |||
| 5145 | ||||
| 5146 | DATA_TYPE == (10 * SQL_DATA_TYPE) + SQL_DATETIME_SUB | |||
| 5147 | ||||
| 5148 | =item NUM_PREC_RADIX (integer) | |||
| 5149 | ||||
| 5150 | The radix value of the data type. For approximate numeric types, | |||
| 5151 | C<NUM_PREC_RADIX> | |||
| 5152 | contains the value 2 and C<COLUMN_SIZE> holds the number of bits. For | |||
| 5153 | exact numeric types, C<NUM_PREC_RADIX> contains the value 10 and C<COLUMN_SIZE> holds | |||
| 5154 | the number of decimal digits. NULL (C<undef>) is returned either for data types | |||
| 5155 | for which this is not applicable or if the driver cannot report this information. | |||
| 5156 | ||||
| 5157 | =item INTERVAL_PRECISION (integer) | |||
| 5158 | ||||
| 5159 | The interval leading precision for interval types. NULL is returned | |||
| 5160 | either for data types for which this is not applicable or if the driver | |||
| 5161 | cannot report this information. | |||
| 5162 | ||||
| 5163 | =back | |||
| 5164 | ||||
| 5165 | For example, to find the type name for the fields in a select statement | |||
| 5166 | you can do: | |||
| 5167 | ||||
| 5168 | @names = map { scalar $dbh->type_info($_)->{TYPE_NAME} } @{ $sth->{TYPE} } | |||
| 5169 | ||||
| 5170 | Since DBI and ODBC drivers vary in how they map their types into the | |||
| 5171 | ISO standard types you may need to search for more than one type. | |||
| 5172 | Here's an example looking for a usable type to store a date: | |||
| 5173 | ||||
| 5174 | $my_date_type = $dbh->type_info( [ SQL_DATE, SQL_TIMESTAMP ] ); | |||
| 5175 | ||||
| 5176 | Similarly, to more reliably find a type to store small integers, you could | |||
| 5177 | use a list starting with C<SQL_SMALLINT>, C<SQL_INTEGER>, C<SQL_DECIMAL>, etc. | |||
| 5178 | ||||
| 5179 | See also L</"Standards Reference Information">. | |||
| 5180 | ||||
| 5181 | ||||
| 5182 | =head3 C<quote> | |||
| 5183 | ||||
| 5184 | $sql = $dbh->quote($value); | |||
| 5185 | $sql = $dbh->quote($value, $data_type); | |||
| 5186 | ||||
| 5187 | Quote a string literal for use as a literal value in an SQL statement, | |||
| 5188 | by escaping any special characters (such as quotation marks) | |||
| 5189 | contained within the string and adding the required type of outer | |||
| 5190 | quotation marks. | |||
| 5191 | ||||
| 5192 | $sql = sprintf "SELECT foo FROM bar WHERE baz = %s", | |||
| 5193 | $dbh->quote("Don't"); | |||
| 5194 | ||||
| 5195 | For most database types, at least those that conform to SQL standards, quote | |||
| 5196 | would return C<'Don''t'> (including the outer quotation marks). For others it | |||
| 5197 | may return something like C<'Don\'t'> | |||
| 5198 | ||||
| 5199 | An undefined C<$value> value will be returned as the string C<NULL> (without | |||
| 5200 | single quotation marks) to match how NULLs are represented in SQL. | |||
| 5201 | ||||
| 5202 | If C<$data_type> is supplied, it is used to try to determine the required | |||
| 5203 | quoting behaviour by using the information returned by L</type_info>. | |||
| 5204 | As a special case, the standard numeric types are optimized to return | |||
| 5205 | C<$value> without calling C<type_info>. | |||
| 5206 | ||||
| 5207 | Quote will probably I<not> be able to deal with all possible input | |||
| 5208 | (such as binary data or data containing newlines), and is not related in | |||
| 5209 | any way with escaping or quoting shell meta-characters. | |||
| 5210 | ||||
| 5211 | It is valid for the quote() method to return an SQL expression that | |||
| 5212 | evaluates to the desired string. For example: | |||
| 5213 | ||||
| 5214 | $quoted = $dbh->quote("one\ntwo\0three") | |||
| 5215 | ||||
| 5216 | may return something like: | |||
| 5217 | ||||
| 5218 | CONCAT('one', CHAR(12), 'two', CHAR(0), 'three') | |||
| 5219 | ||||
| 5220 | The quote() method should I<not> be used with L</"Placeholders and | |||
| 5221 | Bind Values">. | |||
| 5222 | ||||
| 5223 | =head3 C<quote_identifier> | |||
| 5224 | ||||
| 5225 | $sql = $dbh->quote_identifier( $name ); | |||
| 5226 | $sql = $dbh->quote_identifier( $catalog, $schema, $table, \%attr ); | |||
| 5227 | ||||
| 5228 | Quote an identifier (table name etc.) for use in an SQL statement, | |||
| 5229 | by escaping any special characters (such as double quotation marks) | |||
| 5230 | it contains and adding the required type of outer quotation marks. | |||
| 5231 | ||||
| 5232 | Undefined names are ignored and the remainder are quoted and then | |||
| 5233 | joined together, typically with a dot (C<.>) character. For example: | |||
| 5234 | ||||
| 5235 | $id = $dbh->quote_identifier( undef, 'Her schema', 'My table' ); | |||
| 5236 | ||||
| 5237 | would, for most database types, return C<"Her schema"."My table"> | |||
| 5238 | (including all the double quotation marks). | |||
| 5239 | ||||
| 5240 | If three names are supplied then the first is assumed to be a | |||
| 5241 | catalog name and special rules may be applied based on what L</get_info> | |||
| 5242 | returns for SQL_CATALOG_NAME_SEPARATOR (41) and SQL_CATALOG_LOCATION (114). | |||
| 5243 | For example, for Oracle: | |||
| 5244 | ||||
| 5245 | $id = $dbh->quote_identifier( 'link', 'schema', 'table' ); | |||
| 5246 | ||||
| 5247 | would return C<"schema"."table"@"link">. | |||
| 5248 | ||||
| 5249 | =head3 C<take_imp_data> | |||
| 5250 | ||||
| 5251 | $imp_data = $dbh->take_imp_data; | |||
| 5252 | ||||
| 5253 | Leaves the $dbh in an almost dead, zombie-like, state and returns | |||
| 5254 | a binary string of raw implementation data from the driver which | |||
| 5255 | describes the current database connection. Effectively it detaches | |||
| 5256 | the underlying database API connection data from the DBI handle. | |||
| 5257 | After calling take_imp_data(), all other methods except C<DESTROY> | |||
| 5258 | will generate a warning and return undef. | |||
| 5259 | ||||
| 5260 | Why would you want to do this? You don't, forget I even mentioned it. | |||
| 5261 | Unless, that is, you're implementing something advanced like a | |||
| 5262 | multi-threaded connection pool. See L<DBI::Pool>. | |||
| 5263 | ||||
| 5264 | The returned $imp_data can be passed as a C<dbi_imp_data> attribute | |||
| 5265 | to a later connect() call, even in a separate thread in the same | |||
| 5266 | process, where the driver can use it to 'adopt' the existing | |||
| 5267 | connection that the implementation data was taken from. | |||
| 5268 | ||||
| 5269 | Some things to keep in mind... | |||
| 5270 | ||||
| 5271 | B<*> the $imp_data holds the only reference to the underlying | |||
| 5272 | database API connection data. That connection is still 'live' and | |||
| 5273 | won't be cleaned up properly unless the $imp_data is used to create | |||
| 5274 | a new $dbh which is then allowed to disconnect() normally. | |||
| 5275 | ||||
| 5276 | B<*> using the same $imp_data to create more than one other new | |||
| 5277 | $dbh at a time may well lead to unpleasant problems. Don't do that. | |||
| 5278 | ||||
| 5279 | Any child statement handles are effectively destroyed when take_imp_data() is | |||
| 5280 | called. | |||
| 5281 | ||||
| 5282 | The C<take_imp_data> method was added in DBI 1.36 but wasn't useful till 1.49. | |||
| 5283 | ||||
| 5284 | ||||
| 5285 | =head2 Database Handle Attributes | |||
| 5286 | ||||
| 5287 | This section describes attributes specific to database handles. | |||
| 5288 | ||||
| 5289 | Changes to these database handle attributes do not affect any other | |||
| 5290 | existing or future database handles. | |||
| 5291 | ||||
| 5292 | Attempting to set or get the value of an unknown attribute generates a warning, | |||
| 5293 | except for private driver-specific attributes (which all have names | |||
| 5294 | starting with a lowercase letter). | |||
| 5295 | ||||
| 5296 | Example: | |||
| 5297 | ||||
| 5298 | $h->{AutoCommit} = ...; # set/write | |||
| 5299 | ... = $h->{AutoCommit}; # get/read | |||
| 5300 | ||||
| 5301 | =head3 C<AutoCommit> (boolean) | |||
| 5302 | ||||
| 5303 | If true, then database changes cannot be rolled-back (undone). If false, | |||
| 5304 | then database changes automatically occur within a "transaction", which | |||
| 5305 | must either be committed or rolled back using the C<commit> or C<rollback> | |||
| 5306 | methods. | |||
| 5307 | ||||
| 5308 | Drivers should always default to C<AutoCommit> mode (an unfortunate | |||
| 5309 | choice largely forced on the DBI by ODBC and JDBC conventions.) | |||
| 5310 | ||||
| 5311 | Attempting to set C<AutoCommit> to an unsupported value is a fatal error. | |||
| 5312 | This is an important feature of the DBI. Applications that need | |||
| 5313 | full transaction behaviour can set C<$dbh-E<gt>{AutoCommit} = 0> (or | |||
| 5314 | set C<AutoCommit> to 0 via L</connect>) | |||
| 5315 | without having to check that the value was assigned successfully. | |||
| 5316 | ||||
| 5317 | For the purposes of this description, we can divide databases into three | |||
| 5318 | categories: | |||
| 5319 | ||||
| 5320 | Databases which don't support transactions at all. | |||
| 5321 | Databases in which a transaction is always active. | |||
| 5322 | Databases in which a transaction must be explicitly started (C<'BEGIN WORK'>). | |||
| 5323 | ||||
| 5324 | B<* Databases which don't support transactions at all> | |||
| 5325 | ||||
| 5326 | For these databases, attempting to turn C<AutoCommit> off is a fatal error. | |||
| 5327 | C<commit> and C<rollback> both issue warnings about being ineffective while | |||
| 5328 | C<AutoCommit> is in effect. | |||
| 5329 | ||||
| 5330 | B<* Databases in which a transaction is always active> | |||
| 5331 | ||||
| 5332 | These are typically mainstream commercial relational databases with | |||
| 5333 | "ANSI standard" transaction behaviour. | |||
| 5334 | If C<AutoCommit> is off, then changes to the database won't have any | |||
| 5335 | lasting effect unless L</commit> is called (but see also | |||
| 5336 | L</disconnect>). If L</rollback> is called then any changes since the | |||
| 5337 | last commit are undone. | |||
| 5338 | ||||
| 5339 | If C<AutoCommit> is on, then the effect is the same as if the DBI | |||
| 5340 | called C<commit> automatically after every successful database | |||
| 5341 | operation. So calling C<commit> or C<rollback> explicitly while | |||
| 5342 | C<AutoCommit> is on would be ineffective because the changes would | |||
| 5343 | have already been commited. | |||
| 5344 | ||||
| 5345 | Changing C<AutoCommit> from off to on will trigger a L</commit>. | |||
| 5346 | ||||
| 5347 | For databases which don't support a specific auto-commit mode, the | |||
| 5348 | driver has to commit each statement automatically using an explicit | |||
| 5349 | C<COMMIT> after it completes successfully (and roll it back using an | |||
| 5350 | explicit C<ROLLBACK> if it fails). The error information reported to the | |||
| 5351 | application will correspond to the statement which was executed, unless | |||
| 5352 | it succeeded and the commit or rollback failed. | |||
| 5353 | ||||
| 5354 | B<* Databases in which a transaction must be explicitly started> | |||
| 5355 | ||||
| 5356 | For these databases, the intention is to have them act like databases in | |||
| 5357 | which a transaction is always active (as described above). | |||
| 5358 | ||||
| 5359 | To do this, the driver will automatically begin an explicit transaction | |||
| 5360 | when C<AutoCommit> is turned off, or after a L</commit> or | |||
| 5361 | L</rollback> (or when the application issues the next database | |||
| 5362 | operation after one of those events). | |||
| 5363 | ||||
| 5364 | In this way, the application does not have to treat these databases | |||
| 5365 | as a special case. | |||
| 5366 | ||||
| 5367 | See L</commit>, L</disconnect> and L</Transactions> for other important | |||
| 5368 | notes about transactions. | |||
| 5369 | ||||
| 5370 | ||||
| 5371 | =head3 C<Driver> (handle) | |||
| 5372 | ||||
| 5373 | Holds the handle of the parent driver. The only recommended use for this | |||
| 5374 | is to find the name of the driver using: | |||
| 5375 | ||||
| 5376 | $dbh->{Driver}->{Name} | |||
| 5377 | ||||
| 5378 | ||||
| 5379 | =head3 C<Name> (string) | |||
| 5380 | ||||
| 5381 | Holds the "name" of the database. Usually (and recommended to be) the | |||
| 5382 | same as the "C<dbi:DriverName:...>" string used to connect to the database, | |||
| 5383 | but with the leading "C<dbi:DriverName:>" removed. | |||
| 5384 | ||||
| 5385 | ||||
| 5386 | =head3 C<Statement> (string, read-only) | |||
| 5387 | ||||
| 5388 | Returns the statement string passed to the most recent L</prepare> method | |||
| 5389 | called in this database handle, even if that method failed. This is especially | |||
| 5390 | useful where C<RaiseError> is enabled and the exception handler checks $@ | |||
| 5391 | and sees that a 'prepare' method call failed. | |||
| 5392 | ||||
| 5393 | ||||
| 5394 | =head3 C<RowCacheSize> (integer) | |||
| 5395 | ||||
| 5396 | A hint to the driver indicating the size of the local row cache that the | |||
| 5397 | application would like the driver to use for future C<SELECT> statements. | |||
| 5398 | If a row cache is not implemented, then setting C<RowCacheSize> is ignored | |||
| 5399 | and getting the value returns C<undef>. | |||
| 5400 | ||||
| 5401 | Some C<RowCacheSize> values have special meaning, as follows: | |||
| 5402 | ||||
| 5403 | 0 - Automatically determine a reasonable cache size for each C<SELECT> | |||
| 5404 | 1 - Disable the local row cache | |||
| 5405 | >1 - Cache this many rows | |||
| 5406 | <0 - Cache as many rows that will fit into this much memory for each C<SELECT>. | |||
| 5407 | ||||
| 5408 | Note that large cache sizes may require a very large amount of memory | |||
| 5409 | (I<cached rows * maximum size of row>). Also, a large cache will cause | |||
| 5410 | a longer delay not only for the first fetch, but also whenever the | |||
| 5411 | cache needs refilling. | |||
| 5412 | ||||
| 5413 | See also the L</RowsInCache> statement handle attribute. | |||
| 5414 | ||||
| 5415 | =head3 C<Username> (string) | |||
| 5416 | ||||
| 5417 | Returns the username used to connect to the database. | |||
| 5418 | ||||
| 5419 | ||||
| 5420 | =head1 DBI STATEMENT HANDLE OBJECTS | |||
| 5421 | ||||
| 5422 | This section lists the methods and attributes associated with DBI | |||
| 5423 | statement handles. | |||
| 5424 | ||||
| 5425 | =head2 Statement Handle Methods | |||
| 5426 | ||||
| 5427 | The DBI defines the following methods for use on DBI statement handles: | |||
| 5428 | ||||
| 5429 | =head3 C<bind_param> | |||
| 5430 | ||||
| 5431 | $sth->bind_param($p_num, $bind_value) | |||
| 5432 | $sth->bind_param($p_num, $bind_value, \%attr) | |||
| 5433 | $sth->bind_param($p_num, $bind_value, $bind_type) | |||
| 5434 | ||||
| 5435 | The C<bind_param> method takes a copy of $bind_value and associates it | |||
| 5436 | (binds it) with a placeholder, identified by $p_num, embedded in | |||
| 5437 | the prepared statement. Placeholders are indicated with question | |||
| 5438 | mark character (C<?>). For example: | |||
| 5439 | ||||
| 5440 | $dbh->{RaiseError} = 1; # save having to check each method call | |||
| 5441 | $sth = $dbh->prepare("SELECT name, age FROM people WHERE name LIKE ?"); | |||
| 5442 | $sth->bind_param(1, "John%"); # placeholders are numbered from 1 | |||
| 5443 | $sth->execute; | |||
| 5444 | DBI::dump_results($sth); | |||
| 5445 | ||||
| 5446 | See L</"Placeholders and Bind Values"> for more information. | |||
| 5447 | ||||
| 5448 | ||||
| 5449 | B<Data Types for Placeholders> | |||
| 5450 | ||||
| 5451 | The C<\%attr> parameter can be used to hint at the data type the | |||
| 5452 | placeholder should have. This is rarely needed. Typically, the driver is only | |||
| 5453 | interested in knowing if the placeholder should be bound as a number or a string. | |||
| 5454 | ||||
| 5455 | $sth->bind_param(1, $value, { TYPE => SQL_INTEGER }); | |||
| 5456 | ||||
| 5457 | As a short-cut for the common case, the data type can be passed | |||
| 5458 | directly, in place of the C<\%attr> hash reference. This example is | |||
| 5459 | equivalent to the one above: | |||
| 5460 | ||||
| 5461 | $sth->bind_param(1, $value, SQL_INTEGER); | |||
| 5462 | ||||
| 5463 | The C<TYPE> value indicates the standard (non-driver-specific) type for | |||
| 5464 | this parameter. To specify the driver-specific type, the driver may | |||
| 5465 | support a driver-specific attribute, such as C<{ ora_type =E<gt> 97 }>. | |||
| 5466 | ||||
| 5467 | The SQL_INTEGER and other related constants can be imported using | |||
| 5468 | ||||
| 5469 | use DBI qw(:sql_types); | |||
| 5470 | ||||
| 5471 | See L</"DBI Constants"> for more information. | |||
| 5472 | ||||
| 5473 | The data type for a placeholder cannot be changed after the first | |||
| 5474 | C<bind_param> call. In fact the whole \%attr parameter is 'sticky' | |||
| 5475 | in the sense that a driver only needs to consider the \%attr parameter | |||
| 5476 | for the first call, for a given $sth and parameter. After that the driver | |||
| 5477 | may ignore the \%attr parameter for that placeholder. | |||
| 5478 | ||||
| 5479 | Perl only has string and number scalar data types. All database types | |||
| 5480 | that aren't numbers are bound as strings and must be in a format the | |||
| 5481 | database will understand except where the bind_param() TYPE attribute | |||
| 5482 | specifies a type that implies a particular format. For example, given: | |||
| 5483 | ||||
| 5484 | $sth->bind_param(1, $value, SQL_DATETIME); | |||
| 5485 | ||||
| 5486 | the driver should expect $value to be in the ODBC standard SQL_DATETIME | |||
| 5487 | format, which is 'YYYY-MM-DD HH:MM:SS'. Similarly for SQL_DATE, SQL_TIME etc. | |||
| 5488 | ||||
| 5489 | As an alternative to specifying the data type in the C<bind_param> call, | |||
| 5490 | you can let the driver pass the value as the default type (C<VARCHAR>). | |||
| 5491 | You can then use an SQL function to convert the type within the statement. | |||
| 5492 | For example: | |||
| 5493 | ||||
| 5494 | INSERT INTO price(code, price) VALUES (?, CONVERT(MONEY,?)) | |||
| 5495 | ||||
| 5496 | The C<CONVERT> function used here is just an example. The actual function | |||
| 5497 | and syntax will vary between different databases and is non-portable. | |||
| 5498 | ||||
| 5499 | See also L</"Placeholders and Bind Values"> for more information. | |||
| 5500 | ||||
| 5501 | ||||
| 5502 | =head3 C<bind_param_inout> | |||
| 5503 | ||||
| 5504 | $rc = $sth->bind_param_inout($p_num, \$bind_value, $max_len) or die $sth->errstr; | |||
| 5505 | $rv = $sth->bind_param_inout($p_num, \$bind_value, $max_len, \%attr) or ... | |||
| 5506 | $rv = $sth->bind_param_inout($p_num, \$bind_value, $max_len, $bind_type) or ... | |||
| 5507 | ||||
| 5508 | This method acts like L</bind_param>, but also enables values to be | |||
| 5509 | updated by the statement. The statement is typically | |||
| 5510 | a call to a stored procedure. The C<$bind_value> must be passed as a | |||
| 5511 | reference to the actual value to be used. | |||
| 5512 | ||||
| 5513 | Note that unlike L</bind_param>, the C<$bind_value> variable is not | |||
| 5514 | copied when C<bind_param_inout> is called. Instead, the value in the | |||
| 5515 | variable is read at the time L</execute> is called. | |||
| 5516 | ||||
| 5517 | The additional C<$max_len> parameter specifies the minimum amount of | |||
| 5518 | memory to allocate to C<$bind_value> for the new value. If the value | |||
| 5519 | returned from the database is too | |||
| 5520 | big to fit, then the execution should fail. If unsure what value to use, | |||
| 5521 | pick a generous length, i.e., a length larger than the longest value that would ever be | |||
| 5522 | returned. The only cost of using a larger value than needed is wasted memory. | |||
| 5523 | ||||
| 5524 | Undefined values or C<undef> are used to indicate null values. | |||
| 5525 | See also L</"Placeholders and Bind Values"> for more information. | |||
| 5526 | ||||
| 5527 | ||||
| 5528 | =head3 C<bind_param_array> | |||
| 5529 | ||||
| 5530 | $rc = $sth->bind_param_array($p_num, $array_ref_or_value) | |||
| 5531 | $rc = $sth->bind_param_array($p_num, $array_ref_or_value, \%attr) | |||
| 5532 | $rc = $sth->bind_param_array($p_num, $array_ref_or_value, $bind_type) | |||
| 5533 | ||||
| 5534 | The C<bind_param_array> method is used to bind an array of values | |||
| 5535 | to a placeholder embedded in the prepared statement which is to be executed | |||
| 5536 | with L</execute_array>. For example: | |||
| 5537 | ||||
| 5538 | $dbh->{RaiseError} = 1; # save having to check each method call | |||
| 5539 | $sth = $dbh->prepare("INSERT INTO staff (first_name, last_name, dept) VALUES(?, ?, ?)"); | |||
| 5540 | $sth->bind_param_array(1, [ 'John', 'Mary', 'Tim' ]); | |||
| 5541 | $sth->bind_param_array(2, [ 'Booth', 'Todd', 'Robinson' ]); | |||
| 5542 | $sth->bind_param_array(3, "SALES"); # scalar will be reused for each row | |||
| 5543 | $sth->execute_array( { ArrayTupleStatus => \my @tuple_status } ); | |||
| 5544 | ||||
| 5545 | The C<%attr> ($bind_type) argument is the same as defined for L</bind_param>. | |||
| 5546 | Refer to L</bind_param> for general details on using placeholders. | |||
| 5547 | ||||
| 5548 | (Note that bind_param_array() can I<not> be used to expand a | |||
| 5549 | placeholder into a list of values for a statement like "SELECT foo | |||
| 5550 | WHERE bar IN (?)". A placeholder can only ever represent one value | |||
| 5551 | per execution.) | |||
| 5552 | ||||
| 5553 | Scalar values, including C<undef>, may also be bound by | |||
| 5554 | C<bind_param_array>. In which case the same value will be used for each | |||
| 5555 | L</execute> call. Driver-specific implementations may behave | |||
| 5556 | differently, e.g., when binding to a stored procedure call, some | |||
| 5557 | databases may permit mixing scalars and arrays as arguments. | |||
| 5558 | ||||
| 5559 | The default implementation provided by DBI (for drivers that have | |||
| 5560 | not implemented array binding) is to iteratively call L</execute> for | |||
| 5561 | each parameter tuple provided in the bound arrays. Drivers may | |||
| 5562 | provide more optimized implementations using whatever bulk operation | |||
| 5563 | support the database API provides. The default driver behaviour should | |||
| 5564 | match the default DBI behaviour, but always consult your driver | |||
| 5565 | documentation as there may be driver specific issues to consider. | |||
| 5566 | ||||
| 5567 | Note that the default implementation currently only supports non-data | |||
| 5568 | returning statements (INSERT, UPDATE, but not SELECT). Also, | |||
| 5569 | C<bind_param_array> and L</bind_param> cannot be mixed in the same | |||
| 5570 | statement execution, and C<bind_param_array> must be used with | |||
| 5571 | L</execute_array>; using C<bind_param_array> will have no effect | |||
| 5572 | for L</execute>. | |||
| 5573 | ||||
| 5574 | The C<bind_param_array> method was added in DBI 1.22. | |||
| 5575 | ||||
| 5576 | =head3 C<execute> | |||
| 5577 | ||||
| 5578 | $rv = $sth->execute or die $sth->errstr; | |||
| 5579 | $rv = $sth->execute(@bind_values) or die $sth->errstr; | |||
| 5580 | ||||
| 5581 | Perform whatever processing is necessary to execute the prepared | |||
| 5582 | statement. An C<undef> is returned if an error occurs. A successful | |||
| 5583 | C<execute> always returns true regardless of the number of rows affected, | |||
| 5584 | even if it's zero (see below). It is always important to check the | |||
| 5585 | return status of C<execute> (and most other DBI methods) for errors | |||
| 5586 | if you're not using L</RaiseError>. | |||
| 5587 | ||||
| 5588 | For a I<non>-C<SELECT> statement, C<execute> returns the number of rows | |||
| 5589 | affected, if known. If no rows were affected, then C<execute> returns | |||
| 5590 | "C<0E0>", which Perl will treat as 0 but will regard as true. Note that it | |||
| 5591 | is I<not> an error for no rows to be affected by a statement. If the | |||
| 5592 | number of rows affected is not known, then C<execute> returns -1. | |||
| 5593 | ||||
| 5594 | For C<SELECT> statements, execute simply "starts" the query within the | |||
| 5595 | database engine. Use one of the fetch methods to retrieve the data after | |||
| 5596 | calling C<execute>. The C<execute> method does I<not> return the number of | |||
| 5597 | rows that will be returned by the query (because most databases can't | |||
| 5598 | tell in advance), it simply returns a true value. | |||
| 5599 | ||||
| 5600 | You can tell if the statement was a C<SELECT> statement by checking if | |||
| 5601 | C<$sth-E<gt>{NUM_OF_FIELDS}> is greater than zero after calling C<execute>. | |||
| 5602 | ||||
| 5603 | If any arguments are given, then C<execute> will effectively call | |||
| 5604 | L</bind_param> for each value before executing the statement. Values | |||
| 5605 | bound in this way are usually treated as C<SQL_VARCHAR> types unless | |||
| 5606 | the driver can determine the correct type (which is rare), or unless | |||
| 5607 | C<bind_param> (or C<bind_param_inout>) has already been used to | |||
| 5608 | specify the type. | |||
| 5609 | ||||
| 5610 | Note that passing C<execute> an empty array is the same as passing no arguments | |||
| 5611 | at all, which will execute the statement with previously bound values. | |||
| 5612 | That's probably not what you want. | |||
| 5613 | ||||
| 5614 | If execute() is called on a statement handle that's still active | |||
| 5615 | ($sth->{Active} is true) then it should effectively call finish() | |||
| 5616 | to tidy up the previous execution results before starting this new | |||
| 5617 | execution. | |||
| 5618 | ||||
| 5619 | =head3 C<execute_array> | |||
| 5620 | ||||
| 5621 | $tuples = $sth->execute_array(\%attr) or die $sth->errstr; | |||
| 5622 | $tuples = $sth->execute_array(\%attr, @bind_values) or die $sth->errstr; | |||
| 5623 | ||||
| 5624 | ($tuples, $rows) = $sth->execute_array(\%attr) or die $sth->errstr; | |||
| 5625 | ($tuples, $rows) = $sth->execute_array(\%attr, @bind_values) or die $sth->errstr; | |||
| 5626 | ||||
| 5627 | Execute the prepared statement once for each parameter tuple | |||
| 5628 | (group of values) provided either in the @bind_values, or by prior | |||
| 5629 | calls to L</bind_param_array>, or via a reference passed in \%attr. | |||
| 5630 | ||||
| 5631 | When called in scalar context the execute_array() method returns the | |||
| 5632 | number of tuples executed, or C<undef> if an error occured. Like | |||
| 5633 | execute(), a successful execute_array() always returns true regardless | |||
| 5634 | of the number of tuples executed, even if it's zero. If there were any | |||
| 5635 | errors the ArrayTupleStatus array can be used to discover which tuples | |||
| 5636 | failed and with what errors. | |||
| 5637 | ||||
| 5638 | When called in list context the execute_array() method returns two scalars; | |||
| 5639 | $tuples is the same as calling execute_array() in scalar context and $rows is | |||
| 5640 | the sum of the number of rows affected for each tuple, if available or | |||
| 5641 | -1 if the driver cannot determine this. | |||
| 5642 | If you are doing an update operation the returned rows affected may not be what | |||
| 5643 | you expect if, for instance, one or more of the tuples affected the same row | |||
| 5644 | multiple times. Some drivers may not yet support list context, in which case | |||
| 5645 | $rows will be undef, or may not be able to provide the number of rows affected | |||
| 5646 | when performing this batch operation, in which case $rows will be -1. | |||
| 5647 | ||||
| 5648 | Bind values for the tuples to be executed may be supplied row-wise | |||
| 5649 | by an C<ArrayTupleFetch> attribute, or else column-wise in the | |||
| 5650 | C<@bind_values> argument, or else column-wise by prior calls to | |||
| 5651 | L</bind_param_array>. | |||
| 5652 | ||||
| 5653 | Where column-wise binding is used (via the C<@bind_values> argument | |||
| 5654 | or calls to bind_param_array()) the maximum number of elements in | |||
| 5655 | any one of the bound value arrays determines the number of tuples | |||
| 5656 | executed. Placeholders with fewer values in their parameter arrays | |||
| 5657 | are treated as if padded with undef (NULL) values. | |||
| 5658 | ||||
| 5659 | If a scalar value is bound, instead of an array reference, it is | |||
| 5660 | treated as a I<variable> length array with all elements having the | |||
| 5661 | same value. It's does not influence the number of tuples executed, | |||
| 5662 | so if all bound arrays have zero elements then zero tuples will | |||
| 5663 | be executed. If I<all> bound values are scalars then one tuple | |||
| 5664 | will be executed, making execute_array() act just like execute(). | |||
| 5665 | ||||
| 5666 | The C<ArrayTupleFetch> attribute can be used to specify a reference | |||
| 5667 | to a subroutine that will be called to provide the bind values for | |||
| 5668 | each tuple execution. The subroutine should return an reference to | |||
| 5669 | an array which contains the appropriate number of bind values, or | |||
| 5670 | return an undef if there is no more data to execute. | |||
| 5671 | ||||
| 5672 | As a convienience, the C<ArrayTupleFetch> attribute can also be | |||
| 5673 | used to specify a statement handle. In which case the fetchrow_arrayref() | |||
| 5674 | method will be called on the given statement handle in order to | |||
| 5675 | provide the bind values for each tuple execution. | |||
| 5676 | ||||
| 5677 | The values specified via bind_param_array() or the @bind_values | |||
| 5678 | parameter may be either scalars, or arrayrefs. If any C<@bind_values> | |||
| 5679 | are given, then C<execute_array> will effectively call L</bind_param_array> | |||
| 5680 | for each value before executing the statement. Values bound in | |||
| 5681 | this way are usually treated as C<SQL_VARCHAR> types unless the | |||
| 5682 | driver can determine the correct type (which is rare), or unless | |||
| 5683 | C<bind_param>, C<bind_param_inout>, C<bind_param_array>, or | |||
| 5684 | C<bind_param_inout_array> has already been used to specify the type. | |||
| 5685 | See L</bind_param_array> for details. | |||
| 5686 | ||||
| 5687 | The C<ArrayTupleStatus> attribute can be used to specify a | |||
| 5688 | reference to an array which will receive the execute status of each | |||
| 5689 | executed parameter tuple. Note the C<ArrayTupleStatus> attribute was | |||
| 5690 | mandatory until DBI 1.38. | |||
| 5691 | ||||
| 5692 | For tuples which are successfully executed, the element at the same | |||
| 5693 | ordinal position in the status array is the resulting rowcount. | |||
| 5694 | If the execution of a tuple causes an error, then the corresponding | |||
| 5695 | status array element will be set to a reference to an array containing | |||
| 5696 | the error code and error string set by the failed execution. | |||
| 5697 | ||||
| 5698 | If B<any> tuple execution returns an error, C<execute_array> will | |||
| 5699 | return C<undef>. In that case, the application should inspect the | |||
| 5700 | status array to determine which parameter tuples failed. | |||
| 5701 | Some databases may not continue executing tuples beyond the first | |||
| 5702 | failure. In this case the status array will either hold fewer | |||
| 5703 | elements, or the elements beyond the failure will be undef. | |||
| 5704 | ||||
| 5705 | If all parameter tuples are successfully executed, C<execute_array> | |||
| 5706 | returns the number tuples executed. If no tuples were executed, | |||
| 5707 | then execute_array() returns "C<0E0>", just like execute() does, | |||
| 5708 | which Perl will treat as 0 but will regard as true. | |||
| 5709 | ||||
| 5710 | For example: | |||
| 5711 | ||||
| 5712 | $sth = $dbh->prepare("INSERT INTO staff (first_name, last_name) VALUES (?, ?)"); | |||
| 5713 | my $tuples = $sth->execute_array( | |||
| 5714 | { ArrayTupleStatus => \my @tuple_status }, | |||
| 5715 | \@first_names, | |||
| 5716 | \@last_names, | |||
| 5717 | ); | |||
| 5718 | if ($tuples) { | |||
| 5719 | print "Successfully inserted $tuples records\n"; | |||
| 5720 | } | |||
| 5721 | else { | |||
| 5722 | for my $tuple (0..@last_names-1) { | |||
| 5723 | my $status = $tuple_status[$tuple]; | |||
| 5724 | $status = [0, "Skipped"] unless defined $status; | |||
| 5725 | next unless ref $status; | |||
| 5726 | printf "Failed to insert (%s, %s): %s\n", | |||
| 5727 | $first_names[$tuple], $last_names[$tuple], $status->[1]; | |||
| 5728 | } | |||
| 5729 | } | |||
| 5730 | ||||
| 5731 | Support for data returning statements such as SELECT is driver-specific | |||
| 5732 | and subject to change. At present, the default implementation | |||
| 5733 | provided by DBI only supports non-data returning statements. | |||
| 5734 | ||||
| 5735 | Transaction semantics when using array binding are driver and | |||
| 5736 | database specific. If C<AutoCommit> is on, the default DBI | |||
| 5737 | implementation will cause each parameter tuple to be inidividually | |||
| 5738 | committed (or rolled back in the event of an error). If C<AutoCommit> | |||
| 5739 | is off, the application is responsible for explicitly committing | |||
| 5740 | the entire set of bound parameter tuples. Note that different | |||
| 5741 | drivers and databases may have different behaviours when some | |||
| 5742 | parameter tuples cause failures. In some cases, the driver or | |||
| 5743 | database may automatically rollback the effect of all prior parameter | |||
| 5744 | tuples that succeeded in the transaction; other drivers or databases | |||
| 5745 | may retain the effect of prior successfully executed parameter | |||
| 5746 | tuples. Be sure to check your driver and database for its specific | |||
| 5747 | behaviour. | |||
| 5748 | ||||
| 5749 | Note that, in general, performance will usually be better with | |||
| 5750 | C<AutoCommit> turned off, and using explicit C<commit> after each | |||
| 5751 | C<execute_array> call. | |||
| 5752 | ||||
| 5753 | The C<execute_array> method was added in DBI 1.22, and ArrayTupleFetch | |||
| 5754 | was added in 1.36. | |||
| 5755 | ||||
| 5756 | =head3 C<execute_for_fetch> | |||
| 5757 | ||||
| 5758 | $tuples = $sth->execute_for_fetch($fetch_tuple_sub); | |||
| 5759 | $tuples = $sth->execute_for_fetch($fetch_tuple_sub, \@tuple_status); | |||
| 5760 | ||||
| 5761 | ($tuples, $rows) = $sth->execute_for_fetch($fetch_tuple_sub); | |||
| 5762 | ($tuples, $rows) = $sth->execute_for_fetch($fetch_tuple_sub, \@tuple_status); | |||
| 5763 | ||||
| 5764 | The execute_for_fetch() method is used to perform bulk operations | |||
| 5765 | and is most often used via the execute_array() method, not directly. | |||
| 5766 | ||||
| 5767 | The fetch subroutine, referenced by $fetch_tuple_sub, is expected | |||
| 5768 | to return a reference to an array (known as a 'tuple') or undef. | |||
| 5769 | ||||
| 5770 | The execute_for_fetch() method calls $fetch_tuple_sub, without any | |||
| 5771 | parameters, until it returns a false value. Each tuple returned is | |||
| 5772 | used to provide bind values for an $sth->execute(@$tuple) call. | |||
| 5773 | ||||
| 5774 | In scalar context execute_for_fetch() returns C<undef> if there were any | |||
| 5775 | errors and the number of tuples executed otherwise. Like execute() and | |||
| 5776 | execute_array() a zero is returned as "0E0" so execute_for_fetch() is | |||
| 5777 | only false on error. If there were any errors the @tuple_status array | |||
| 5778 | can be used to discover which tuples failed and with what errors. | |||
| 5779 | ||||
| 5780 | When called in list context execute_for_fetch() returns two scalars; | |||
| 5781 | $tuples is the same as calling execute_for_fetch() in scalar context and $rows is | |||
| 5782 | the sum of the number of rows affected for each tuple, if available or -1 | |||
| 5783 | if the driver cannot determine this. | |||
| 5784 | If you are doing an update operation the returned rows affected may not be what | |||
| 5785 | you expect if, for instance, one or more of the tuples affected the same row | |||
| 5786 | multiple times. Some drivers may not yet support list context, in which case | |||
| 5787 | $rows will be undef, or may not be able to provide the number of rows affected | |||
| 5788 | when performing this batch operation, in which case $rows will be -1. | |||
| 5789 | ||||
| 5790 | If \@tuple_status is passed then the execute_for_fetch method uses | |||
| 5791 | it to return status information. The tuple_status array holds one | |||
| 5792 | element per tuple. If the corresponding execute() did not fail then | |||
| 5793 | the element holds the return value from execute(), which is typically | |||
| 5794 | a row count. If the execute() did fail then the element holds a | |||
| 5795 | reference to an array containing ($sth->err, $sth->errstr, $sth->state). | |||
| 5796 | ||||
| 5797 | If the driver detects an error that it knows means no further tuples can be | |||
| 5798 | executed then it may return, with an error status, even though $fetch_tuple_sub | |||
| 5799 | may still have more tuples to be executed. | |||
| 5800 | ||||
| 5801 | Although each tuple returned by $fetch_tuple_sub is effectively used | |||
| 5802 | to call $sth->execute(@$tuple_array_ref) the exact timing may vary. | |||
| 5803 | Drivers are free to accumulate sets of tuples to pass to the | |||
| 5804 | database server in bulk group operations for more efficient execution. | |||
| 5805 | However, the $fetch_tuple_sub is specifically allowed to return | |||
| 5806 | the same array reference each time (which is what fetchrow_arrayref() | |||
| 5807 | usually does). | |||
| 5808 | ||||
| 5809 | For example: | |||
| 5810 | ||||
| 5811 | my $sel = $dbh1->prepare("select foo, bar from table1"); | |||
| 5812 | $sel->execute; | |||
| 5813 | ||||
| 5814 | my $ins = $dbh2->prepare("insert into table2 (foo, bar) values (?,?)"); | |||
| 5815 | my $fetch_tuple_sub = sub { $sel->fetchrow_arrayref }; | |||
| 5816 | ||||
| 5817 | my @tuple_status; | |||
| 5818 | $rc = $ins->execute_for_fetch($fetch_tuple_sub, \@tuple_status); | |||
| 5819 | my @errors = grep { ref $_ } @tuple_status; | |||
| 5820 | ||||
| 5821 | Similarly, if you already have an array containing the data rows | |||
| 5822 | to be processed you'd use a subroutine to shift off and return | |||
| 5823 | each array ref in turn: | |||
| 5824 | ||||
| 5825 | $ins->execute_for_fetch( sub { shift @array_of_arrays }, \@tuple_status); | |||
| 5826 | ||||
| 5827 | The C<execute_for_fetch> method was added in DBI 1.38. | |||
| 5828 | ||||
| 5829 | ||||
| 5830 | =head3 C<fetchrow_arrayref> | |||
| 5831 | ||||
| 5832 | $ary_ref = $sth->fetchrow_arrayref; | |||
| 5833 | $ary_ref = $sth->fetch; # alias | |||
| 5834 | ||||
| 5835 | Fetches the next row of data and returns a reference to an array | |||
| 5836 | holding the field values. Null fields are returned as C<undef> | |||
| 5837 | values in the array. | |||
| 5838 | This is the fastest way to fetch data, particularly if used with | |||
| 5839 | C<$sth-E<gt>bind_columns>. | |||
| 5840 | ||||
| 5841 | If there are no more rows or if an error occurs, then C<fetchrow_arrayref> | |||
| 5842 | returns an C<undef>. You should check C<$sth-E<gt>err> afterwards (or use the | |||
| 5843 | C<RaiseError> attribute) to discover if the C<undef> returned was due to an | |||
| 5844 | error. | |||
| 5845 | ||||
| 5846 | Note that the same array reference is returned for each fetch, so don't | |||
| 5847 | store the reference and then use it after a later fetch. Also, the | |||
| 5848 | elements of the array are also reused for each row, so take care if you | |||
| 5849 | want to take a reference to an element. See also L</bind_columns>. | |||
| 5850 | ||||
| 5851 | =head3 C<fetchrow_array> | |||
| 5852 | ||||
| 5853 | @ary = $sth->fetchrow_array; | |||
| 5854 | ||||
| 5855 | An alternative to C<fetchrow_arrayref>. Fetches the next row of data | |||
| 5856 | and returns it as a list containing the field values. Null fields | |||
| 5857 | are returned as C<undef> values in the list. | |||
| 5858 | ||||
| 5859 | If there are no more rows or if an error occurs, then C<fetchrow_array> | |||
| 5860 | returns an empty list. You should check C<$sth-E<gt>err> afterwards (or use | |||
| 5861 | the C<RaiseError> attribute) to discover if the empty list returned was | |||
| 5862 | due to an error. | |||
| 5863 | ||||
| 5864 | If called in a scalar context for a statement handle that has more | |||
| 5865 | than one column, it is undefined whether the driver will return | |||
| 5866 | the value of the first column or the last. So don't do that. | |||
| 5867 | Also, in a scalar context, an C<undef> is returned if there are no | |||
| 5868 | more rows or if an error occurred. That C<undef> can't be distinguished | |||
| 5869 | from an C<undef> returned because the first field value was NULL. | |||
| 5870 | For these reasons you should exercise some caution if you use | |||
| 5871 | C<fetchrow_array> in a scalar context. | |||
| 5872 | ||||
| 5873 | =head3 C<fetchrow_hashref> | |||
| 5874 | ||||
| 5875 | $hash_ref = $sth->fetchrow_hashref; | |||
| 5876 | $hash_ref = $sth->fetchrow_hashref($name); | |||
| 5877 | ||||
| 5878 | An alternative to C<fetchrow_arrayref>. Fetches the next row of data | |||
| 5879 | and returns it as a reference to a hash containing field name and field | |||
| 5880 | value pairs. Null fields are returned as C<undef> values in the hash. | |||
| 5881 | ||||
| 5882 | If there are no more rows or if an error occurs, then C<fetchrow_hashref> | |||
| 5883 | returns an C<undef>. You should check C<$sth-E<gt>err> afterwards (or use the | |||
| 5884 | C<RaiseError> attribute) to discover if the C<undef> returned was due to an | |||
| 5885 | error. | |||
| 5886 | ||||
| 5887 | The optional C<$name> parameter specifies the name of the statement handle | |||
| 5888 | attribute. For historical reasons it defaults to "C<NAME>", however using either | |||
| 5889 | "C<NAME_lc>" or "C<NAME_uc>" is recomended for portability. | |||
| 5890 | ||||
| 5891 | The keys of the hash are the same names returned by C<$sth-E<gt>{$name}>. If | |||
| 5892 | more than one field has the same name, there will only be one entry in | |||
| 5893 | the returned hash for those fields. | |||
| 5894 | ||||
| 5895 | Because of the extra work C<fetchrow_hashref> and Perl have to perform, it | |||
| 5896 | is not as efficient as C<fetchrow_arrayref> or C<fetchrow_array>. | |||
| 5897 | ||||
| 5898 | By default a reference to a new hash is returned for each row. | |||
| 5899 | It is likely that a future version of the DBI will support an | |||
| 5900 | attribute which will enable the same hash to be reused for each | |||
| 5901 | row. This will give a significant performance boost, but it won't | |||
| 5902 | be enabled by default because of the risk of breaking old code. | |||
| 5903 | ||||
| 5904 | ||||
| 5905 | =head3 C<fetchall_arrayref> | |||
| 5906 | ||||
| 5907 | $tbl_ary_ref = $sth->fetchall_arrayref; | |||
| 5908 | $tbl_ary_ref = $sth->fetchall_arrayref( $slice ); | |||
| 5909 | $tbl_ary_ref = $sth->fetchall_arrayref( $slice, $max_rows ); | |||
| 5910 | ||||
| 5911 | The C<fetchall_arrayref> method can be used to fetch all the data to be | |||
| 5912 | returned from a prepared and executed statement handle. It returns a | |||
| 5913 | reference to an array that contains one reference per row. | |||
| 5914 | ||||
| 5915 | If there are no rows to return, C<fetchall_arrayref> returns a reference | |||
| 5916 | to an empty array. If an error occurs, C<fetchall_arrayref> returns the | |||
| 5917 | data fetched thus far, which may be none. You should check C<$sth-E<gt>err> | |||
| 5918 | afterwards (or use the C<RaiseError> attribute) to discover if the data is | |||
| 5919 | complete or was truncated due to an error. | |||
| 5920 | ||||
| 5921 | If $slice is an array reference, C<fetchall_arrayref> uses L</fetchrow_arrayref> | |||
| 5922 | to fetch each row as an array ref. If the $slice array is not empty | |||
| 5923 | then it is used as a slice to select individual columns by perl array | |||
| 5924 | index number (starting at 0, unlike column and parameter numbers which | |||
| 5925 | start at 1). | |||
| 5926 | ||||
| 5927 | With no parameters, or if $slice is undefined, C<fetchall_arrayref> | |||
| 5928 | acts as if passed an empty array ref. | |||
| 5929 | ||||
| 5930 | If $slice is a hash reference, C<fetchall_arrayref> uses L</fetchrow_hashref> | |||
| 5931 | to fetch each row as a hash reference. If the $slice hash is empty then | |||
| 5932 | fetchrow_hashref() is simply called in a tight loop and the keys in the hashes | |||
| 5933 | have whatever name lettercase is returned by default from fetchrow_hashref. | |||
| 5934 | (See L</FetchHashKeyName> attribute.) If the $slice hash is not | |||
| 5935 | empty, then it is used as a slice to select individual columns by | |||
| 5936 | name. The values of the hash should be set to 1. The key names | |||
| 5937 | of the returned hashes match the letter case of the names in the | |||
| 5938 | parameter hash, regardless of the L</FetchHashKeyName> attribute. | |||
| 5939 | ||||
| 5940 | For example, to fetch just the first column of every row: | |||
| 5941 | ||||
| 5942 | $tbl_ary_ref = $sth->fetchall_arrayref([0]); | |||
| 5943 | ||||
| 5944 | To fetch the second to last and last column of every row: | |||
| 5945 | ||||
| 5946 | $tbl_ary_ref = $sth->fetchall_arrayref([-2,-1]); | |||
| 5947 | ||||
| 5948 | To fetch all fields of every row as a hash ref: | |||
| 5949 | ||||
| 5950 | $tbl_ary_ref = $sth->fetchall_arrayref({}); | |||
| 5951 | ||||
| 5952 | To fetch only the fields called "foo" and "bar" of every row as a hash ref | |||
| 5953 | (with keys named "foo" and "BAR"): | |||
| 5954 | ||||
| 5955 | $tbl_ary_ref = $sth->fetchall_arrayref({ foo=>1, BAR=>1 }); | |||
| 5956 | ||||
| 5957 | The first two examples return a reference to an array of array refs. | |||
| 5958 | The third and forth return a reference to an array of hash refs. | |||
| 5959 | ||||
| 5960 | If $max_rows is defined and greater than or equal to zero then it | |||
| 5961 | is used to limit the number of rows fetched before returning. | |||
| 5962 | fetchall_arrayref() can then be called again to fetch more rows. | |||
| 5963 | This is especially useful when you need the better performance of | |||
| 5964 | fetchall_arrayref() but don't have enough memory to fetch and return | |||
| 5965 | all the rows in one go. | |||
| 5966 | ||||
| 5967 | Here's an example (assumes RaiseError is enabled): | |||
| 5968 | ||||
| 5969 | my $rows = []; # cache for batches of rows | |||
| 5970 | while( my $row = ( shift(@$rows) || # get row from cache, or reload cache: | |||
| 5971 | shift(@{$rows=$sth->fetchall_arrayref(undef,10_000)||[]}) ) | |||
| 5972 | ) { | |||
| 5973 | ... | |||
| 5974 | } | |||
| 5975 | ||||
| 5976 | That I<might> be the fastest way to fetch and process lots of rows using the DBI, | |||
| 5977 | but it depends on the relative cost of method calls vs memory allocation. | |||
| 5978 | ||||
| 5979 | A standard C<while> loop with column binding is often faster because | |||
| 5980 | the cost of allocating memory for the batch of rows is greater than | |||
| 5981 | the saving by reducing method calls. It's possible that the DBI may | |||
| 5982 | provide a way to reuse the memory of a previous batch in future, which | |||
| 5983 | would then shift the balance back towards fetchall_arrayref(). | |||
| 5984 | ||||
| 5985 | ||||
| 5986 | =head3 C<fetchall_hashref> | |||
| 5987 | ||||
| 5988 | $hash_ref = $sth->fetchall_hashref($key_field); | |||
| 5989 | ||||
| 5990 | The C<fetchall_hashref> method can be used to fetch all the data to be | |||
| 5991 | returned from a prepared and executed statement handle. It returns a reference | |||
| 5992 | to a hash containing a key for each distinct value of the $key_field column | |||
| 5993 | that was fetched. For each key the corresponding value is a reference to a hash | |||
| 5994 | containing all the selected columns and their values, as returned by fetchrow_hashref(). | |||
| 5995 | ||||
| 5996 | If there are no rows to return, C<fetchall_hashref> returns a reference | |||
| 5997 | to an empty hash. If an error occurs, C<fetchall_hashref> returns the | |||
| 5998 | data fetched thus far, which may be none. You should check | |||
| 5999 | C<$sth-E<gt>err> afterwards (or use the C<RaiseError> attribute) to | |||
| 6000 | discover if the data is complete or was truncated due to an error. | |||
| 6001 | ||||
| 6002 | The $key_field parameter provides the name of the field that holds the | |||
| 6003 | value to be used for the key for the returned hash. For example: | |||
| 6004 | ||||
| 6005 | $dbh->{FetchHashKeyName} = 'NAME_lc'; | |||
| 6006 | $sth = $dbh->prepare("SELECT FOO, BAR, ID, NAME, BAZ FROM TABLE"); | |||
| 6007 | $sth->execute; | |||
| 6008 | $hash_ref = $sth->fetchall_hashref('id'); | |||
| 6009 | print "Name for id 42 is $hash_ref->{42}->{name}\n"; | |||
| 6010 | ||||
| 6011 | The $key_field parameter can also be specified as an integer column | |||
| 6012 | number (counting from 1). If $key_field doesn't match any column in | |||
| 6013 | the statement, as a name first then as a number, then an error is | |||
| 6014 | returned. | |||
| 6015 | ||||
| 6016 | For queries returing more than one 'key' column, you can specify | |||
| 6017 | multiple column names by passing $key_field as a reference to an | |||
| 6018 | array containing one or more key column names (or index numbers). | |||
| 6019 | For example: | |||
| 6020 | ||||
| 6021 | $sth = $dbh->prepare("SELECT foo, bar, baz FROM table"); | |||
| 6022 | $sth->execute; | |||
| 6023 | $hash_ref = $sth->fetchall_hashref( [ qw(foo bar) ] ); | |||
| 6024 | print "For foo 42 and bar 38, baz is $hash_ref->{42}->{38}->{baz}\n"; | |||
| 6025 | ||||
| 6026 | The fetchall_hashref() method is normally used only where the key | |||
| 6027 | fields values for each row are unique. If multiple rows are returned | |||
| 6028 | with the same values for the key fields then later rows overwrite | |||
| 6029 | earlier ones. | |||
| 6030 | ||||
| 6031 | =head3 C<finish> | |||
| 6032 | ||||
| 6033 | $rc = $sth->finish; | |||
| 6034 | ||||
| 6035 | Indicate that no more data will be fetched from this statement handle | |||
| 6036 | before it is either executed again or destroyed. The C<finish> method | |||
| 6037 | is rarely needed, and frequently overused, but can sometimes be | |||
| 6038 | helpful in a few very specific situations to allow the server to free | |||
| 6039 | up resources (such as sort buffers). | |||
| 6040 | ||||
| 6041 | When all the data has been fetched from a C<SELECT> statement, the | |||
| 6042 | driver should automatically call C<finish> for you. So you should | |||
| 6043 | I<not> normally need to call it explicitly I<except> when you know | |||
| 6044 | that you've not fetched all the data from a statement handle. | |||
| 6045 | The most common example is when you only want to fetch one row, | |||
| 6046 | but in that case the C<selectrow_*> methods are usually better anyway. | |||
| 6047 | Adding calls to C<finish> after each fetch loop is a common mistake, | |||
| 6048 | don't do it, it can mask genuine problems like uncaught fetch errors. | |||
| 6049 | ||||
| 6050 | Consider a query like: | |||
| 6051 | ||||
| 6052 | SELECT foo FROM table WHERE bar=? ORDER BY foo | |||
| 6053 | ||||
| 6054 | where you want to select just the first (smallest) "foo" value from a | |||
| 6055 | very large table. When executed, the database server will have to use | |||
| 6056 | temporary buffer space to store the sorted rows. If, after executing | |||
| 6057 | the handle and selecting one row, the handle won't be re-executed for | |||
| 6058 | some time and won't be destroyed, the C<finish> method can be used to tell | |||
| 6059 | the server that the buffer space can be freed. | |||
| 6060 | ||||
| 6061 | Calling C<finish> resets the L</Active> attribute for the statement. It | |||
| 6062 | may also make some statement handle attributes (such as C<NAME> and C<TYPE>) | |||
| 6063 | unavailable if they have not already been accessed (and thus cached). | |||
| 6064 | ||||
| 6065 | The C<finish> method does not affect the transaction status of the | |||
| 6066 | database connection. It has nothing to do with transactions. It's mostly an | |||
| 6067 | internal "housekeeping" method that is rarely needed. | |||
| 6068 | See also L</disconnect> and the L</Active> attribute. | |||
| 6069 | ||||
| 6070 | The C<finish> method should have been called C<discard_pending_rows>. | |||
| 6071 | ||||
| 6072 | ||||
| 6073 | =head3 C<rows> | |||
| 6074 | ||||
| 6075 | $rv = $sth->rows; | |||
| 6076 | ||||
| 6077 | Returns the number of rows affected by the last row affecting command, | |||
| 6078 | or -1 if the number of rows is not known or not available. | |||
| 6079 | ||||
| 6080 | Generally, you can only rely on a row count after a I<non>-C<SELECT> | |||
| 6081 | C<execute> (for some specific operations like C<UPDATE> and C<DELETE>), or | |||
| 6082 | after fetching all the rows of a C<SELECT> statement. | |||
| 6083 | ||||
| 6084 | For C<SELECT> statements, it is generally not possible to know how many | |||
| 6085 | rows will be returned except by fetching them all. Some drivers will | |||
| 6086 | return the number of rows the application has fetched so far, but | |||
| 6087 | others may return -1 until all rows have been fetched. So use of the | |||
| 6088 | C<rows> method or C<$DBI::rows> with C<SELECT> statements is not | |||
| 6089 | recommended. | |||
| 6090 | ||||
| 6091 | One alternative method to get a row count for a C<SELECT> is to execute a | |||
| 6092 | "SELECT COUNT(*) FROM ..." SQL statement with the same "..." as your | |||
| 6093 | query and then fetch the row count from that. | |||
| 6094 | ||||
| 6095 | ||||
| 6096 | =head3 C<bind_col> | |||
| 6097 | ||||
| 6098 | $rc = $sth->bind_col($column_number, \$var_to_bind); | |||
| 6099 | $rc = $sth->bind_col($column_number, \$var_to_bind, \%attr ); | |||
| 6100 | $rc = $sth->bind_col($column_number, \$var_to_bind, $bind_type ); | |||
| 6101 | ||||
| 6102 | Binds a Perl variable and/or some attributes to an output column | |||
| 6103 | (field) of a C<SELECT> statement. Column numbers count up from 1. | |||
| 6104 | You do not need to bind output columns in order to fetch data. | |||
| 6105 | For maximum portability between drivers, bind_col() should be called | |||
| 6106 | after execute() and not before. | |||
| 6107 | See also C<bind_columns> for an example. | |||
| 6108 | ||||
| 6109 | The binding is performed at a low level using Perl aliasing. | |||
| 6110 | Whenever a row is fetched from the database $var_to_bind appears | |||
| 6111 | to be automatically updated simply because it now refers to the same | |||
| 6112 | memory location as the corresponding column value. This makes using | |||
| 6113 | bound variables very efficient. | |||
| 6114 | Binding a tied variable doesn't work, currently. | |||
| 6115 | ||||
| 6116 | The L</bind_param> method | |||
| 6117 | performs a similar, but opposite, function for input variables. | |||
| 6118 | ||||
| 6119 | B<Data Types for Column Binding> | |||
| 6120 | ||||
| 6121 | The C<\%attr> parameter can be used to hint at the data type | |||
| 6122 | formatting the column should have. For example, you can use: | |||
| 6123 | ||||
| 6124 | $sth->bind_col(1, undef, { TYPE => SQL_DATETIME }); | |||
| 6125 | ||||
| 6126 | to specify that you'd like the column (which presumably is some | |||
| 6127 | kind of datetime type) to be returned in the standard format for | |||
| 6128 | SQL_DATETIME, which is 'YYYY-MM-DD HH:MM:SS', rather than the | |||
| 6129 | native formatting the database would normally use. | |||
| 6130 | ||||
| 6131 | There's no $var_to_bind in that example to emphasize the point | |||
| 6132 | that bind_col() works on the underlying column value and not just | |||
| 6133 | a particular bound variable. | |||
| 6134 | ||||
| 6135 | As a short-cut for the common case, the data type can be passed | |||
| 6136 | directly, in place of the C<\%attr> hash reference. This example is | |||
| 6137 | equivalent to the one above: | |||
| 6138 | ||||
| 6139 | $sth->bind_col(1, undef, SQL_DATETIME); | |||
| 6140 | ||||
| 6141 | The C<TYPE> value indicates the standard (non-driver-specific) type for | |||
| 6142 | this parameter. To specify the driver-specific type, the driver may | |||
| 6143 | support a driver-specific attribute, such as C<{ ora_type =E<gt> 97 }>. | |||
| 6144 | ||||
| 6145 | The SQL_DATETIME and other related constants can be imported using | |||
| 6146 | ||||
| 6147 | use DBI qw(:sql_types); | |||
| 6148 | ||||
| 6149 | See L</"DBI Constants"> for more information. | |||
| 6150 | ||||
| 6151 | The data type for a bind variable cannot be changed after the first | |||
| 6152 | C<bind_col> call. In fact the whole \%attr parameter is 'sticky' | |||
| 6153 | in the sense that a driver only needs to consider the \%attr parameter | |||
| 6154 | for the first call for a given $sth and column. | |||
| 6155 | ||||
| 6156 | The TYPE attribute for bind_col() was first specified in DBI 1.41. | |||
| 6157 | ||||
| 6158 | ||||
| 6159 | =head3 C<bind_columns> | |||
| 6160 | ||||
| 6161 | $rc = $sth->bind_columns(@list_of_refs_to_vars_to_bind); | |||
| 6162 | ||||
| 6163 | Calls L</bind_col> for each column of the C<SELECT> statement. | |||
| 6164 | ||||
| 6165 | The list of references should have the same number of elements as the number of | |||
| 6166 | columns in the C<SELECT> statement. If it doesn't then C<bind_columns> will | |||
| 6167 | bind the elements given, upto the number of columns, and then return an error. | |||
| 6168 | ||||
| 6169 | For maximum portability between drivers, bind_columns() should be called | |||
| 6170 | after execute() and not before. | |||
| 6171 | ||||
| 6172 | For example: | |||
| 6173 | ||||
| 6174 | $dbh->{RaiseError} = 1; # do this, or check every call for errors | |||
| 6175 | $sth = $dbh->prepare(q{ SELECT region, sales FROM sales_by_region }); | |||
| 6176 | $sth->execute; | |||
| 6177 | my ($region, $sales); | |||
| 6178 | ||||
| 6179 | # Bind Perl variables to columns: | |||
| 6180 | $rv = $sth->bind_columns(\$region, \$sales); | |||
| 6181 | ||||
| 6182 | # you can also use Perl's \(...) syntax (see perlref docs): | |||
| 6183 | # $sth->bind_columns(\($region, $sales)); | |||
| 6184 | ||||
| 6185 | # Column binding is the most efficient way to fetch data | |||
| 6186 | while ($sth->fetch) { | |||
| 6187 | print "$region: $sales\n"; | |||
| 6188 | } | |||
| 6189 | ||||
| 6190 | For compatibility with old scripts, the first parameter will be | |||
| 6191 | ignored if it is C<undef> or a hash reference. | |||
| 6192 | ||||
| 6193 | Here's a more fancy example that binds columns to the values I<inside> | |||
| 6194 | a hash (thanks to H.Merijn Brand): | |||
| 6195 | ||||
| 6196 | $sth->execute; | |||
| 6197 | my %row; | |||
| 6198 | $sth->bind_columns( \( @row{ @{$sth->{NAME_lc} } } )); | |||
| 6199 | while ($sth->fetch) { | |||
| 6200 | print "$row{region}: $row{sales}\n"; | |||
| 6201 | } | |||
| 6202 | ||||
| 6203 | ||||
| 6204 | =head3 C<dump_results> | |||
| 6205 | ||||
| 6206 | $rows = $sth->dump_results($maxlen, $lsep, $fsep, $fh); | |||
| 6207 | ||||
| 6208 | Fetches all the rows from C<$sth>, calls C<DBI::neat_list> for each row, and | |||
| 6209 | prints the results to C<$fh> (defaults to C<STDOUT>) separated by C<$lsep> | |||
| 6210 | (default C<"\n">). C<$fsep> defaults to C<", "> and C<$maxlen> defaults to 35. | |||
| 6211 | ||||
| 6212 | This method is designed as a handy utility for prototyping and | |||
| 6213 | testing queries. Since it uses L</neat_list> to | |||
| 6214 | format and edit the string for reading by humans, it is not recomended | |||
| 6215 | for data transfer applications. | |||
| 6216 | ||||
| 6217 | ||||
| 6218 | =head2 Statement Handle Attributes | |||
| 6219 | ||||
| 6220 | This section describes attributes specific to statement handles. Most | |||
| 6221 | of these attributes are read-only. | |||
| 6222 | ||||
| 6223 | Changes to these statement handle attributes do not affect any other | |||
| 6224 | existing or future statement handles. | |||
| 6225 | ||||
| 6226 | Attempting to set or get the value of an unknown attribute generates a warning, | |||
| 6227 | except for private driver specific attributes (which all have names | |||
| 6228 | starting with a lowercase letter). | |||
| 6229 | ||||
| 6230 | Example: | |||
| 6231 | ||||
| 6232 | ... = $h->{NUM_OF_FIELDS}; # get/read | |||
| 6233 | ||||
| 6234 | Some drivers cannot provide valid values for some or all of these | |||
| 6235 | attributes until after C<$sth-E<gt>execute> has been successfully | |||
| 6236 | called. Typically the attribute will be C<undef> in these situations. | |||
| 6237 | ||||
| 6238 | Some attributes, like NAME, are not appropriate to some types of | |||
| 6239 | statement, like SELECT. Typically the attribute will be C<undef> | |||
| 6240 | in these situations. | |||
| 6241 | ||||
| 6242 | For drivers which support stored procedures and multiple result sets | |||
| 6243 | (see L</more_results>) these attributes relate to the I<current> result set. | |||
| 6244 | ||||
| 6245 | See also L</finish> to learn more about the effect it | |||
| 6246 | may have on some attributes. | |||
| 6247 | ||||
| 6248 | =head3 C<NUM_OF_FIELDS> (integer, read-only) | |||
| 6249 | ||||
| 6250 | Number of fields (columns) in the data the prepared statement may return. | |||
| 6251 | Statements that don't return rows of data, like C<DELETE> and C<CREATE> | |||
| 6252 | set C<NUM_OF_FIELDS> to 0 (though it may be undef in some drivers). | |||
| 6253 | ||||
| 6254 | ||||
| 6255 | =head3 C<NUM_OF_PARAMS> (integer, read-only) | |||
| 6256 | ||||
| 6257 | The number of parameters (placeholders) in the prepared statement. | |||
| 6258 | See SUBSTITUTION VARIABLES below for more details. | |||
| 6259 | ||||
| 6260 | ||||
| 6261 | =head3 C<NAME> (array-ref, read-only) | |||
| 6262 | ||||
| 6263 | Returns a reference to an array of field names for each column. The | |||
| 6264 | names may contain spaces but should not be truncated or have any | |||
| 6265 | trailing space. Note that the names have the letter case (upper, lower | |||
| 6266 | or mixed) as returned by the driver being used. Portable applications | |||
| 6267 | should use L</NAME_lc> or L</NAME_uc>. | |||
| 6268 | ||||
| 6269 | print "First column name: $sth->{NAME}->[0]\n"; | |||
| 6270 | ||||
| 6271 | =head3 C<NAME_lc> (array-ref, read-only) | |||
| 6272 | ||||
| 6273 | Like L</NAME> but always returns lowercase names. | |||
| 6274 | ||||
| 6275 | =head3 C<NAME_uc> (array-ref, read-only) | |||
| 6276 | ||||
| 6277 | Like L</NAME> but always returns uppercase names. | |||
| 6278 | ||||
| 6279 | =head3 C<NAME_hash> (hash-ref, read-only) | |||
| 6280 | ||||
| 6281 | =head3 C<NAME_lc_hash> (hash-ref, read-only) | |||
| 6282 | ||||
| 6283 | =head3 C<NAME_uc_hash> (hash-ref, read-only) | |||
| 6284 | ||||
| 6285 | The C<NAME_hash>, C<NAME_lc_hash>, and C<NAME_uc_hash> attributes | |||
| 6286 | return column name information as a reference to a hash. | |||
| 6287 | ||||
| 6288 | The keys of the hash are the names of the columns. The letter case of | |||
| 6289 | the keys corresponds to the letter case returned by the C<NAME>, | |||
| 6290 | C<NAME_lc>, and C<NAME_uc> attributes respectively (as described above). | |||
| 6291 | ||||
| 6292 | The value of each hash entry is the perl index number of the | |||
| 6293 | corresponding column (counting from 0). For example: | |||
| 6294 | ||||
| 6295 | $sth = $dbh->prepare("select Id, Name from table"); | |||
| 6296 | $sth->execute; | |||
| 6297 | @row = $sth->fetchrow_array; | |||
| 6298 | print "Name $row[ $sth->{NAME_lc_hash}{name} ]\n"; | |||
| 6299 | ||||
| 6300 | ||||
| 6301 | =head3 C<TYPE> (array-ref, read-only) | |||
| 6302 | ||||
| 6303 | Returns a reference to an array of integer values for each | |||
| 6304 | column. The value indicates the data type of the corresponding column. | |||
| 6305 | ||||
| 6306 | The values correspond to the international standards (ANSI X3.135 | |||
| 6307 | and ISO/IEC 9075) which, in general terms, means ODBC. Driver-specific | |||
| 6308 | types that don't exactly match standard types should generally return | |||
| 6309 | the same values as an ODBC driver supplied by the makers of the | |||
| 6310 | database. That might include private type numbers in ranges the vendor | |||
| 6311 | has officially registered with the ISO working group: | |||
| 6312 | ||||
| 6313 | ftp://sqlstandards.org/SC32/SQL_Registry/ | |||
| 6314 | ||||
| 6315 | Where there's no vendor-supplied ODBC driver to be compatible with, | |||
| 6316 | the DBI driver can use type numbers in the range that is now | |||
| 6317 | officially reserved for use by the DBI: -9999 to -9000. | |||
| 6318 | ||||
| 6319 | All possible values for C<TYPE> should have at least one entry in the | |||
| 6320 | output of the C<type_info_all> method (see L</type_info_all>). | |||
| 6321 | ||||
| 6322 | =head3 C<PRECISION> (array-ref, read-only) | |||
| 6323 | ||||
| 6324 | Returns a reference to an array of integer values for each column. | |||
| 6325 | ||||
| 6326 | For numeric columns, the value is the maximum number of digits | |||
| 6327 | (without considering a sign character or decimal point). Note that | |||
| 6328 | the "display size" for floating point types (REAL, FLOAT, DOUBLE) | |||
| 6329 | can be up to 7 characters greater than the precision (for the | |||
| 6330 | sign + decimal point + the letter E + a sign + 2 or 3 digits). | |||
| 6331 | ||||
| 6332 | For any character type column the value is the OCTET_LENGTH, | |||
| 6333 | in other words the number of bytes, not characters. | |||
| 6334 | ||||
| 6335 | (More recent standards refer to this as COLUMN_SIZE but we stick | |||
| 6336 | with PRECISION for backwards compatibility.) | |||
| 6337 | ||||
| 6338 | =head3 C<SCALE> (array-ref, read-only) | |||
| 6339 | ||||
| 6340 | Returns a reference to an array of integer values for each column. | |||
| 6341 | NULL (C<undef>) values indicate columns where scale is not applicable. | |||
| 6342 | ||||
| 6343 | =head3 C<NULLABLE> (array-ref, read-only) | |||
| 6344 | ||||
| 6345 | Returns a reference to an array indicating the possibility of each | |||
| 6346 | column returning a null. Possible values are C<0> | |||
| 6347 | (or an empty string) = no, C<1> = yes, C<2> = unknown. | |||
| 6348 | ||||
| 6349 | print "First column may return NULL\n" if $sth->{NULLABLE}->[0]; | |||
| 6350 | ||||
| 6351 | ||||
| 6352 | =head3 C<CursorName> (string, read-only) | |||
| 6353 | ||||
| 6354 | Returns the name of the cursor associated with the statement handle, if | |||
| 6355 | available. If not available or if the database driver does not support the | |||
| 6356 | C<"where current of ..."> SQL syntax, then it returns C<undef>. | |||
| 6357 | ||||
| 6358 | ||||
| 6359 | =head3 C<Database> (dbh, read-only) | |||
| 6360 | ||||
| 6361 | Returns the parent $dbh of the statement handle. | |||
| 6362 | ||||
| 6363 | ||||
| 6364 | =head3 C<ParamValues> (hash ref, read-only) | |||
| 6365 | ||||
| 6366 | Returns a reference to a hash containing the values currently bound | |||
| 6367 | to placeholders. The keys of the hash are the 'names' of the | |||
| 6368 | placeholders, typically integers starting at 1. Returns undef if | |||
| 6369 | not supported by the driver. | |||
| 6370 | ||||
| 6371 | See L</ShowErrorStatement> for an example of how this is used. | |||
| 6372 | ||||
| 6373 | If the driver supports C<ParamValues> but no values have been bound | |||
| 6374 | yet then the driver should return a hash with placeholders names | |||
| 6375 | in the keys but all the values undef, but some drivers may return | |||
| 6376 | a ref to an empty hash. | |||
| 6377 | ||||
| 6378 | It is possible that the values in the hash returned by C<ParamValues> | |||
| 6379 | are not I<exactly> the same as those passed to bind_param() or execute(). | |||
| 6380 | The driver may have slightly modified values in some way based on the | |||
| 6381 | TYPE the value was bound with. For example a floating point value | |||
| 6382 | bound as an SQL_INTEGER type may be returned as an integer. | |||
| 6383 | The values returned by C<ParamValues> can be passed to another | |||
| 6384 | bind_param() method with the same TYPE and will be seen by the | |||
| 6385 | database as the same value. | |||
| 6386 | ||||
| 6387 | It is also possible that the keys in the hash returned by C<ParamValues> | |||
| 6388 | are not exactly the same as those implied by the prepared statement. | |||
| 6389 | For example, DBD::Oracle translates 'C<?>' placeholders into 'C<:pN>' | |||
| 6390 | where N is a sequence number starting at 1. | |||
| 6391 | ||||
| 6392 | The C<ParamValues> attribute was added in DBI 1.28. | |||
| 6393 | ||||
| 6394 | =head3 C<ParamArrays> (hash ref, read-only) | |||
| 6395 | ||||
| 6396 | Returns a reference to a hash containing the values currently bound to | |||
| 6397 | placeholders with L</execute_array> or L</bind_param_array>. The | |||
| 6398 | keys of the hash are the 'names' of the placeholders, typically | |||
| 6399 | integers starting at 1. Returns undef if not supported by the driver | |||
| 6400 | or no arrays of parameters are bound. | |||
| 6401 | ||||
| 6402 | Each key value is an array reference containing a list of the bound | |||
| 6403 | parameters for that column. | |||
| 6404 | ||||
| 6405 | For example: | |||
| 6406 | ||||
| 6407 | $sth = $dbh->prepare("INSERT INTO staff (id, name) values (?,?)"); | |||
| 6408 | $sth->execute_array({},[1,2], ['fred','dave']); | |||
| 6409 | if ($sth->{ParamArrays}) { | |||
| 6410 | foreach $param (keys %{$sth->{ParamArrays}}) { | |||
| 6411 | printf "Parameters for %s : %s\n", $param, | |||
| 6412 | join(",", @{$sth->{ParamArrays}->{$param}}); | |||
| 6413 | } | |||
| 6414 | } | |||
| 6415 | ||||
| 6416 | It is possible that the values in the hash returned by C<ParamArrays> | |||
| 6417 | are not I<exactly> the same as those passed to L</bind_param_array> or | |||
| 6418 | L</execute_array>. The driver may have slightly modified values in some | |||
| 6419 | way based on the TYPE the value was bound with. For example a floating | |||
| 6420 | point value bound as an SQL_INTEGER type may be returned as an | |||
| 6421 | integer. | |||
| 6422 | ||||
| 6423 | It is also possible that the keys in the hash returned by | |||
| 6424 | C<ParamArrays> are not exactly the same as those implied by the | |||
| 6425 | prepared statement. For example, DBD::Oracle translates 'C<?>' | |||
| 6426 | placeholders into 'C<:pN>' where N is a sequence number starting at 1. | |||
| 6427 | ||||
| 6428 | =head3 C<ParamTypes> (hash ref, read-only) | |||
| 6429 | ||||
| 6430 | Returns a reference to a hash containing the type information | |||
| 6431 | currently bound to placeholders. The keys of the hash are the | |||
| 6432 | 'names' of the placeholders: either integers starting at 1, or, | |||
| 6433 | for drivers that support named placeholders, the actual parameter | |||
| 6434 | name string. The hash values are hashrefs of type information in | |||
| 6435 | the same form as that provided to the various bind_param() methods | |||
| 6436 | (See L</bind_param> for the format and values), | |||
| 6437 | plus anything else that was passed as the third argument to bind_param(). | |||
| 6438 | Returns undef if not supported by the driver. | |||
| 6439 | ||||
| 6440 | If the driver supports C<ParamTypes>, but no values have been bound | |||
| 6441 | yet, then the driver should return a hash with the placeholder name | |||
| 6442 | keys, but all the values undef; however, some drivers may return | |||
| 6443 | a ref to an empty hash, or, alternately, may provide type | |||
| 6444 | information supplied by the database (only a few databases can do that). | |||
| 6445 | ||||
| 6446 | It is possible that the values in the hash returned by C<ParamTypes> | |||
| 6447 | are not I<exactly> the same as those passed to bind_param() or execute(). | |||
| 6448 | The driver may have modified the type information in some way based | |||
| 6449 | on the bound values, other hints provided by the prepare()'d | |||
| 6450 | SQL statement, or alternate type mappings required by the driver or target | |||
| 6451 | database system. | |||
| 6452 | ||||
| 6453 | It is also possible that the keys in the hash returned by C<ParamTypes> | |||
| 6454 | are not exactly the same as those implied by the prepared statement. | |||
| 6455 | For example, DBD::Oracle translates 'C<?>' placeholders into 'C<:pN>' | |||
| 6456 | where N is a sequence number starting at 1. | |||
| 6457 | ||||
| 6458 | The C<ParamTypes> attribute was added in DBI 1.49. Implementation | |||
| 6459 | is the responsibility of individual drivers; the DBI layer default | |||
| 6460 | implementation simply returns undef. | |||
| 6461 | ||||
| 6462 | ||||
| 6463 | =head3 C<Statement> (string, read-only) | |||
| 6464 | ||||
| 6465 | Returns the statement string passed to the L</prepare> method. | |||
| 6466 | ||||
| 6467 | ||||
| 6468 | =head3 C<RowsInCache> (integer, read-only) | |||
| 6469 | ||||
| 6470 | If the driver supports a local row cache for C<SELECT> statements, then | |||
| 6471 | this attribute holds the number of un-fetched rows in the cache. If the | |||
| 6472 | driver doesn't, then it returns C<undef>. Note that some drivers pre-fetch | |||
| 6473 | rows on execute, whereas others wait till the first fetch. | |||
| 6474 | ||||
| 6475 | See also the L</RowCacheSize> database handle attribute. | |||
| 6476 | ||||
| 6477 | =head1 FURTHER INFORMATION | |||
| 6478 | ||||
| 6479 | =head2 Catalog Methods | |||
| 6480 | ||||
| 6481 | An application can retrieve metadata information from the DBMS by issuing | |||
| 6482 | appropriate queries on the views of the Information Schema. Unfortunately, | |||
| 6483 | C<INFORMATION_SCHEMA> views are seldom supported by the DBMS. | |||
| 6484 | Special methods (catalog methods) are available to return result sets | |||
| 6485 | for a small but important portion of that metadata: | |||
| 6486 | ||||
| 6487 | column_info | |||
| 6488 | foreign_key_info | |||
| 6489 | primary_key_info | |||
| 6490 | table_info | |||
| 6491 | statistics_info | |||
| 6492 | ||||
| 6493 | All catalog methods accept arguments in order to restrict the result sets. | |||
| 6494 | Passing C<undef> to an optional argument does not constrain the search for | |||
| 6495 | that argument. | |||
| 6496 | However, an empty string ('') is treated as a regular search criteria | |||
| 6497 | and will only match an empty value. | |||
| 6498 | ||||
| 6499 | B<Note>: SQL/CLI and ODBC differ in the handling of empty strings. An | |||
| 6500 | empty string will not restrict the result set in SQL/CLI. | |||
| 6501 | ||||
| 6502 | Most arguments in the catalog methods accept only I<ordinary values>, e.g. | |||
| 6503 | the arguments of C<primary_key_info()>. | |||
| 6504 | Such arguments are treated as a literal string, i.e. the case is significant | |||
| 6505 | and quote characters are taken literally. | |||
| 6506 | ||||
| 6507 | Some arguments in the catalog methods accept I<search patterns> (strings | |||
| 6508 | containing '_' and/or '%'), e.g. the C<$table> argument of C<column_info()>. | |||
| 6509 | Passing '%' is equivalent to leaving the argument C<undef>. | |||
| 6510 | ||||
| 6511 | B<Caveat>: The underscore ('_') is valid and often used in SQL identifiers. | |||
| 6512 | Passing such a value to a search pattern argument may return more rows than | |||
| 6513 | expected! | |||
| 6514 | To include pattern characters as literals, they must be preceded by an | |||
| 6515 | escape character which can be achieved with | |||
| 6516 | ||||
| 6517 | $esc = $dbh->get_info( 14 ); # SQL_SEARCH_PATTERN_ESCAPE | |||
| 6518 | $search_pattern =~ s/([_%])/$esc$1/g; | |||
| 6519 | ||||
| 6520 | The ODBC and SQL/CLI specifications define a way to change the default | |||
| 6521 | behaviour described above: All arguments (except I<list value arguments>) | |||
| 6522 | are treated as I<identifier> if the C<SQL_ATTR_METADATA_ID> attribute is | |||
| 6523 | set to C<SQL_TRUE>. | |||
| 6524 | I<Quoted identifiers> are very similar to I<ordinary values>, i.e. their | |||
| 6525 | body (the string within the quotes) is interpreted literally. | |||
| 6526 | I<Unquoted identifiers> are compared in UPPERCASE. | |||
| 6527 | ||||
| 6528 | The DBI (currently) does not support the C<SQL_ATTR_METADATA_ID> attribute, | |||
| 6529 | i.e. it behaves like an ODBC driver where C<SQL_ATTR_METADATA_ID> is set to | |||
| 6530 | C<SQL_FALSE>. | |||
| 6531 | ||||
| 6532 | ||||
| 6533 | =head2 Transactions | |||
| 6534 | ||||
| 6535 | Transactions are a fundamental part of any robust database system. They | |||
| 6536 | protect against errors and database corruption by ensuring that sets of | |||
| 6537 | related changes to the database take place in atomic (indivisible, | |||
| 6538 | all-or-nothing) units. | |||
| 6539 | ||||
| 6540 | This section applies to databases that support transactions and where | |||
| 6541 | C<AutoCommit> is off. See L</AutoCommit> for details of using C<AutoCommit> | |||
| 6542 | with various types of databases. | |||
| 6543 | ||||
| 6544 | The recommended way to implement robust transactions in Perl | |||
| 6545 | applications is to use C<RaiseError> and S<C<eval { ... }>> | |||
| 6546 | (which is very fast, unlike S<C<eval "...">>). For example: | |||
| 6547 | ||||
| 6548 | $dbh->{AutoCommit} = 0; # enable transactions, if possible | |||
| 6549 | $dbh->{RaiseError} = 1; | |||
| 6550 | eval { | |||
| 6551 | foo(...) # do lots of work here | |||
| 6552 | bar(...) # including inserts | |||
| 6553 | baz(...) # and updates | |||
| 6554 | $dbh->commit; # commit the changes if we get this far | |||
| 6555 | }; | |||
| 6556 | if ($@) { | |||
| 6557 | warn "Transaction aborted because $@"; | |||
| 6558 | # now rollback to undo the incomplete changes | |||
| 6559 | # but do it in an eval{} as it may also fail | |||
| 6560 | eval { $dbh->rollback }; | |||
| 6561 | # add other application on-error-clean-up code here | |||
| 6562 | } | |||
| 6563 | ||||
| 6564 | If the C<RaiseError> attribute is not set, then DBI calls would need to be | |||
| 6565 | manually checked for errors, typically like this: | |||
| 6566 | ||||
| 6567 | $h->method(@args) or die $h->errstr; | |||
| 6568 | ||||
| 6569 | With C<RaiseError> set, the DBI will automatically C<die> if any DBI method | |||
| 6570 | call on that handle (or a child handle) fails, so you don't have to | |||
| 6571 | test the return value of each method call. See L</RaiseError> for more | |||
| 6572 | details. | |||
| 6573 | ||||
| 6574 | A major advantage of the C<eval> approach is that the transaction will be | |||
| 6575 | properly rolled back if I<any> code (not just DBI calls) in the inner | |||
| 6576 | application dies for any reason. The major advantage of using the | |||
| 6577 | C<$h-E<gt>{RaiseError}> attribute is that all DBI calls will be checked | |||
| 6578 | automatically. Both techniques are strongly recommended. | |||
| 6579 | ||||
| 6580 | After calling C<commit> or C<rollback> many drivers will not let you | |||
| 6581 | fetch from a previously active C<SELECT> statement handle that's a child | |||
| 6582 | of the same database handle. A typical way round this is to connect the | |||
| 6583 | the database twice and use one connection for C<SELECT> statements. | |||
| 6584 | ||||
| 6585 | See L</AutoCommit> and L</disconnect> for other important information | |||
| 6586 | about transactions. | |||
| 6587 | ||||
| 6588 | ||||
| 6589 | =head2 Handling BLOB / LONG / Memo Fields | |||
| 6590 | ||||
| 6591 | Many databases support "blob" (binary large objects), "long", or similar | |||
| 6592 | datatypes for holding very long strings or large amounts of binary | |||
| 6593 | data in a single field. Some databases support variable length long | |||
| 6594 | values over 2,000,000,000 bytes in length. | |||
| 6595 | ||||
| 6596 | Since values of that size can't usually be held in memory, and because | |||
| 6597 | databases can't usually know in advance the length of the longest long | |||
| 6598 | that will be returned from a C<SELECT> statement (unlike other data | |||
| 6599 | types), some special handling is required. | |||
| 6600 | ||||
| 6601 | In this situation, the value of the C<$h-E<gt>{LongReadLen}> | |||
| 6602 | attribute is used to determine how much buffer space to allocate | |||
| 6603 | when fetching such fields. The C<$h-E<gt>{LongTruncOk}> attribute | |||
| 6604 | is used to determine how to behave if a fetched value can't fit | |||
| 6605 | into the buffer. | |||
| 6606 | ||||
| 6607 | See the description of L</LongReadLen> for more information. | |||
| 6608 | ||||
| 6609 | When trying to insert long or binary values, placeholders should be used | |||
| 6610 | since there are often limits on the maximum size of an C<INSERT> | |||
| 6611 | statement and the L</quote> method generally can't cope with binary | |||
| 6612 | data. See L</Placeholders and Bind Values>. | |||
| 6613 | ||||
| 6614 | ||||
| 6615 | =head2 Simple Examples | |||
| 6616 | ||||
| 6617 | Here's a complete example program to select and fetch some data: | |||
| 6618 | ||||
| 6619 | my $data_source = "dbi::DriverName:db_name"; | |||
| 6620 | my $dbh = DBI->connect($data_source, $user, $password) | |||
| 6621 | or die "Can't connect to $data_source: $DBI::errstr"; | |||
| 6622 | ||||
| 6623 | my $sth = $dbh->prepare( q{ | |||
| 6624 | SELECT name, phone | |||
| 6625 | FROM mytelbook | |||
| 6626 | }) or die "Can't prepare statement: $DBI::errstr"; | |||
| 6627 | ||||
| 6628 | my $rc = $sth->execute | |||
| 6629 | or die "Can't execute statement: $DBI::errstr"; | |||
| 6630 | ||||
| 6631 | print "Query will return $sth->{NUM_OF_FIELDS} fields.\n\n"; | |||
| 6632 | print "Field names: @{ $sth->{NAME} }\n"; | |||
| 6633 | ||||
| 6634 | while (($name, $phone) = $sth->fetchrow_array) { | |||
| 6635 | print "$name: $phone\n"; | |||
| 6636 | } | |||
| 6637 | # check for problems which may have terminated the fetch early | |||
| 6638 | die $sth->errstr if $sth->err; | |||
| 6639 | ||||
| 6640 | $dbh->disconnect; | |||
| 6641 | ||||
| 6642 | Here's a complete example program to insert some data from a file. | |||
| 6643 | (This example uses C<RaiseError> to avoid needing to check each call). | |||
| 6644 | ||||
| 6645 | my $dbh = DBI->connect("dbi:DriverName:db_name", $user, $password, { | |||
| 6646 | RaiseError => 1, AutoCommit => 0 | |||
| 6647 | }); | |||
| 6648 | ||||
| 6649 | my $sth = $dbh->prepare( q{ | |||
| 6650 | INSERT INTO table (name, phone) VALUES (?, ?) | |||
| 6651 | }); | |||
| 6652 | ||||
| 6653 | open FH, "<phone.csv" or die "Unable to open phone.csv: $!"; | |||
| 6654 | while (<FH>) { | |||
| 6655 | chomp; | |||
| 6656 | my ($name, $phone) = split /,/; | |||
| 6657 | $sth->execute($name, $phone); | |||
| 6658 | } | |||
| 6659 | close FH; | |||
| 6660 | ||||
| 6661 | $dbh->commit; | |||
| 6662 | $dbh->disconnect; | |||
| 6663 | ||||
| 6664 | Here's how to convert fetched NULLs (undefined values) into empty strings: | |||
| 6665 | ||||
| 6666 | while($row = $sth->fetchrow_arrayref) { | |||
| 6667 | # this is a fast and simple way to deal with nulls: | |||
| 6668 | foreach (@$row) { $_ = '' unless defined } | |||
| 6669 | print "@$row\n"; | |||
| 6670 | } | |||
| 6671 | ||||
| 6672 | The C<q{...}> style quoting used in these examples avoids clashing with | |||
| 6673 | quotes that may be used in the SQL statement. Use the double-quote like | |||
| 6674 | C<qq{...}> operator if you want to interpolate variables into the string. | |||
| 6675 | See L<perlop/"Quote and Quote-like Operators"> for more details. | |||
| 6676 | ||||
| 6677 | =head2 Threads and Thread Safety | |||
| 6678 | ||||
| 6679 | Perl 5.7 and later support a new threading model called iThreads. | |||
| 6680 | (The old "5.005 style" threads are not supported by the DBI.) | |||
| 6681 | ||||
| 6682 | In the iThreads model each thread has it's own copy of the perl | |||
| 6683 | interpreter. When a new thread is created the original perl | |||
| 6684 | interpreter is 'cloned' to create a new copy for the new thread. | |||
| 6685 | ||||
| 6686 | If the DBI and drivers are loaded and handles created before the | |||
| 6687 | thread is created then it will get a cloned copy of the DBI, the | |||
| 6688 | drivers and the handles. | |||
| 6689 | ||||
| 6690 | However, the internal pointer data within the handles will refer | |||
| 6691 | to the DBI and drivers in the original interpreter. Using those | |||
| 6692 | handles in the new interpreter thread is not safe, so the DBI detects | |||
| 6693 | this and croaks on any method call using handles that don't belong | |||
| 6694 | to the current thread (except for DESTROY). | |||
| 6695 | ||||
| 6696 | Because of this (possibly temporary) restriction, newly created | |||
| 6697 | threads must make their own connctions to the database. Handles | |||
| 6698 | can't be shared across threads. | |||
| 6699 | ||||
| 6700 | But BEWARE, some underlying database APIs (the code the DBD driver | |||
| 6701 | uses to talk to the database, often supplied by the database vendor) | |||
| 6702 | are not thread safe. If it's not thread safe, then allowing more | |||
| 6703 | than one thread to enter the code at the same time may cause | |||
| 6704 | subtle/serious problems. In some cases allowing more than | |||
| 6705 | one thread to enter the code, even if I<not> at the same time, | |||
| 6706 | can cause problems. You have been warned. | |||
| 6707 | ||||
| 6708 | Using DBI with perl threads is not yet recommended for production | |||
| 6709 | environments. For more information see | |||
| 6710 | L<http://www.perlmonks.org/index.pl?node_id=288022> | |||
| 6711 | ||||
| 6712 | Note: There is a bug in perl 5.8.2 when configured with threads | |||
| 6713 | and debugging enabled (bug #24463) which causes a DBI test to fail. | |||
| 6714 | ||||
| 6715 | =head2 Signal Handling and Canceling Operations | |||
| 6716 | ||||
| 6717 | [The following only applies to systems with unix-like signal handling. | |||
| 6718 | I'd welcome additions for other systems, especially Windows.] | |||
| 6719 | ||||
| 6720 | The first thing to say is that signal handling in Perl versions less | |||
| 6721 | than 5.8 is I<not> safe. There is always a small risk of Perl | |||
| 6722 | crashing and/or core dumping when, or after, handling a signal | |||
| 6723 | because the signal could arrive and be handled while internal data | |||
| 6724 | structures are being changed. If the signal handling code | |||
| 6725 | used those same internal data structures it could cause all manner | |||
| 6726 | of subtle and not-so-subtle problems. The risk was reduced with | |||
| 6727 | 5.4.4 but was still present in all perls up through 5.8.0. | |||
| 6728 | ||||
| 6729 | Beginning in perl 5.8.0 perl implements 'safe' signal handling if | |||
| 6730 | your system has the POSIX sigaction() routine. Now when a signal | |||
| 6731 | is delivered perl just makes a note of it but does I<not> run the | |||
| 6732 | %SIG handler. The handling is 'defered' until a 'safe' moment. | |||
| 6733 | ||||
| 6734 | Although this change made signal handling safe, it also lead to | |||
| 6735 | a problem with signals being defered for longer than you'd like. | |||
| 6736 | If a signal arrived while executing a system call, such as waiting | |||
| 6737 | for data on a network connection, the signal is noted and then the | |||
| 6738 | system call that was executing returns with an EINTR error code | |||
| 6739 | to indicate that it was interrupted. All fine so far. | |||
| 6740 | ||||
| 6741 | The problem comes when the code that made the system call sees the | |||
| 6742 | EINTR code and decides it's going to call it again. Perl doesn't | |||
| 6743 | do that, but database code sometimes does. If that happens then the | |||
| 6744 | signal handler doesn't get called untill later. Maybe much later. | |||
| 6745 | ||||
| 6746 | Fortunately there are ways around this which we'll discuss below. | |||
| 6747 | Unfortunately they make signals unsafe again. | |||
| 6748 | ||||
| 6749 | The two most common uses of signals in relation to the DBI are for | |||
| 6750 | canceling operations when the user types Ctrl-C (interrupt), and for | |||
| 6751 | implementing a timeout using C<alarm()> and C<$SIG{ALRM}>. | |||
| 6752 | ||||
| 6753 | =over 4 | |||
| 6754 | ||||
| 6755 | =item Cancel | |||
| 6756 | ||||
| 6757 | The DBI provides a C<cancel> method for statement handles. The | |||
| 6758 | C<cancel> method should abort the current operation and is designed | |||
| 6759 | to be called from a signal handler. For example: | |||
| 6760 | ||||
| 6761 | $SIG{INT} = sub { $sth->cancel }; | |||
| 6762 | ||||
| 6763 | However, few drivers implement this (the DBI provides a default | |||
| 6764 | method that just returns C<undef>) and, even if implemented, there | |||
| 6765 | is still a possibility that the statement handle, and even the | |||
| 6766 | parent database handle, will not be usable afterwards. | |||
| 6767 | ||||
| 6768 | If C<cancel> returns true, then it has successfully | |||
| 6769 | invoked the database engine's own cancel function. If it returns false, | |||
| 6770 | then C<cancel> failed. If it returns C<undef>, then the database | |||
| 6771 | driver does not have cancel implemented - very few do. | |||
| 6772 | ||||
| 6773 | =item Timeout | |||
| 6774 | ||||
| 6775 | The traditional way to implement a timeout is to set C<$SIG{ALRM}> | |||
| 6776 | to refer to some code that will be executed when an ALRM signal | |||
| 6777 | arrives and then to call alarm($seconds) to schedule an ALRM signal | |||
| 6778 | to be delivered $seconds in the future. For example: | |||
| 6779 | ||||
| 6780 | eval { | |||
| 6781 | local $SIG{ALRM} = sub { die "TIMEOUT\n" }; | |||
| 6782 | alarm($seconds); | |||
| 6783 | ... code to execute with timeout here ... | |||
| 6784 | alarm(0); # cancel alarm (if code ran fast) | |||
| 6785 | }; | |||
| 6786 | alarm(0); # cancel alarm (if eval failed) | |||
| 6787 | if ( $@ eq "TIMEOUT\n" ) { ... } | |||
| 6788 | ||||
| 6789 | Unfortunately, as described above, this won't always work as expected, | |||
| 6790 | depending on your perl version and the underlying database code. | |||
| 6791 | ||||
| 6792 | With Oracle for instance (DBD::Oracle), if the system which hosts | |||
| 6793 | the database is down the DBI->connect() call will hang for several | |||
| 6794 | minutes before returning an error. | |||
| 6795 | ||||
| 6796 | =back | |||
| 6797 | ||||
| 6798 | The solution on these systems is to use the C<POSIX::sigaction()> | |||
| 6799 | routine to gain low level access to how the signal handler is installed. | |||
| 6800 | ||||
| 6801 | The code would look something like this (for the DBD-Oracle connect()): | |||
| 6802 | ||||
| 6803 | use POSIX ':signal_h'; | |||
| 6804 | ||||
| 6805 | my $mask = POSIX::SigSet->new( SIGALRM ); # signals to mask in the handler | |||
| 6806 | my $action = POSIX::SigAction->new( | |||
| 6807 | sub { die "connect timeout" }, # the handler code ref | |||
| 6808 | $mask, | |||
| 6809 | # not using (perl 5.8.2 and later) 'safe' switch or sa_flags | |||
| 6810 | ); | |||
| 6811 | my $oldaction = POSIX::SigAction->new(); | |||
| 6812 | sigaction( 'ALRM', $action, $oldaction ); | |||
| 6813 | my $dbh; | |||
| 6814 | eval { | |||
| 6815 | alarm(5); # seconds before time out | |||
| 6816 | $dbh = DBI->connect("dbi:Oracle:$dsn" ... ); | |||
| 6817 | alarm(0); # cancel alarm (if connect worked fast) | |||
| 6818 | }; | |||
| 6819 | alarm(0); # cancel alarm (if eval failed) | |||
| 6820 | sigaction( 'ALRM', $oldaction ); # restore original signal handler | |||
| 6821 | if ( $@ ) .... | |||
| 6822 | ||||
| 6823 | Similar techniques can be used for canceling statement execution. | |||
| 6824 | ||||
| 6825 | Unfortunately, this solution is somewhat messy, and it does I<not> work with | |||
| 6826 | perl versions less than perl 5.8 where C<POSIX::sigaction()> appears to be broken. | |||
| 6827 | ||||
| 6828 | For a cleaner implementation that works across perl versions, see Lincoln Baxter's | |||
| 6829 | Sys::SigAction module at L<http://search.cpan.org/~lbaxter/Sys-SigAction/>. | |||
| 6830 | The documentation for Sys::SigAction includes an longer discussion | |||
| 6831 | of this problem, and a DBD::Oracle test script. | |||
| 6832 | ||||
| 6833 | Be sure to read all the signal handling sections of the L<perlipc> manual. | |||
| 6834 | ||||
| 6835 | And finally, two more points to keep firmly in mind. Firstly, | |||
| 6836 | remember that what we've done here is essentially revert to old | |||
| 6837 | style I<unsafe> handling of these signals. So do as little as | |||
| 6838 | possible in the handler. Ideally just die(). Secondly, the handles | |||
| 6839 | in use at the time the signal is handled may not be safe to use | |||
| 6840 | afterwards. | |||
| 6841 | ||||
| 6842 | ||||
| 6843 | =head2 Subclassing the DBI | |||
| 6844 | ||||
| 6845 | DBI can be subclassed and extended just like any other object | |||
| 6846 | oriented module. Before we talk about how to do that, it's important | |||
| 6847 | to be clear about the various DBI classes and how they work together. | |||
| 6848 | ||||
| 6849 | By default C<$dbh = DBI-E<gt>connect(...)> returns a $dbh blessed | |||
| 6850 | into the C<DBI::db> class. And the C<$dbh-E<gt>prepare> method | |||
| 6851 | returns an $sth blessed into the C<DBI::st> class (actually it | |||
| 6852 | simply changes the last four characters of the calling handle class | |||
| 6853 | to be C<::st>). | |||
| 6854 | ||||
| 6855 | The leading 'C<DBI>' is known as the 'root class' and the extra | |||
| 6856 | 'C<::db>' or 'C<::st>' are the 'handle type suffixes'. If you want | |||
| 6857 | to subclass the DBI you'll need to put your overriding methods into | |||
| 6858 | the appropriate classes. For example, if you want to use a root class | |||
| 6859 | of C<MySubDBI> and override the do(), prepare() and execute() methods, | |||
| 6860 | then your do() and prepare() methods should be in the C<MySubDBI::db> | |||
| 6861 | class and the execute() method should be in the C<MySubDBI::st> class. | |||
| 6862 | ||||
| 6863 | To setup the inheritance hierarchy the @ISA variable in C<MySubDBI::db> | |||
| 6864 | should include C<DBI::db> and the @ISA variable in C<MySubDBI::st> | |||
| 6865 | should include C<DBI::st>. The C<MySubDBI> root class itself isn't | |||
| 6866 | currently used for anything visible and so, apart from setting @ISA | |||
| 6867 | to include C<DBI>, it can be left empty. | |||
| 6868 | ||||
| 6869 | So, having put your overriding methods into the right classes, and | |||
| 6870 | setup the inheritance hierarchy, how do you get the DBI to use them? | |||
| 6871 | You have two choices, either a static method call using the name | |||
| 6872 | of your subclass: | |||
| 6873 | ||||
| 6874 | $dbh = MySubDBI->connect(...); | |||
| 6875 | ||||
| 6876 | or specifying a C<RootClass> attribute: | |||
| 6877 | ||||
| 6878 | $dbh = DBI->connect(..., { RootClass => 'MySubDBI' }); | |||
| 6879 | ||||
| 6880 | If both forms are used then the attribute takes precedence. | |||
| 6881 | ||||
| 6882 | The only differences between the two are that using an explicit | |||
| 6883 | RootClass attribute will a) make the DBI automatically attempt to load | |||
| 6884 | a module by that name if the class doesn't exist, and b) won't call | |||
| 6885 | your MySubDBI::connect() method, if you have one. | |||
| 6886 | ||||
| 6887 | When subclassing is being used then, after a successful new | |||
| 6888 | connect, the DBI->connect method automatically calls: | |||
| 6889 | ||||
| 6890 | $dbh->connected($dsn, $user, $pass, \%attr); | |||
| 6891 | ||||
| 6892 | The default method does nothing. The call is made just to simplify | |||
| 6893 | any post-connection setup that your subclass may want to perform. | |||
| 6894 | The parameters are the same as passed to DBI->connect. | |||
| 6895 | If your subclass supplies a connected method, it should be part of the | |||
| 6896 | MySubDBI::db package. | |||
| 6897 | ||||
| 6898 | One more thing to note: you must let the DBI do the handle creation. If you | |||
| 6899 | want to override the connect() method in your *::dr class then it must still | |||
| 6900 | call SUPER::connect to get a $dbh to work with. Similarly, an overridden | |||
| 6901 | prepare() method in *::db must still call SUPER::prepare to get a $sth. | |||
| 6902 | If you try to create your own handles using bless() then you'll find the DBI | |||
| 6903 | will reject them with an "is not a DBI handle (has no magic)" error. | |||
| 6904 | ||||
| 6905 | Here's a brief example of a DBI subclass. A more thorough example | |||
| 6906 | can be found in F<t/subclass.t> in the DBI distribution. | |||
| 6907 | ||||
| 6908 | package MySubDBI; | |||
| 6909 | ||||
| 6910 | use strict; | |||
| 6911 | ||||
| 6912 | use DBI; | |||
| 6913 | use vars qw(@ISA); | |||
| 6914 | @ISA = qw(DBI); | |||
| 6915 | ||||
| 6916 | package MySubDBI::db; | |||
| 6917 | use vars qw(@ISA); | |||
| 6918 | @ISA = qw(DBI::db); | |||
| 6919 | ||||
| 6920 | sub prepare { | |||
| 6921 | my ($dbh, @args) = @_; | |||
| 6922 | my $sth = $dbh->SUPER::prepare(@args) | |||
| 6923 | or return; | |||
| 6924 | $sth->{private_mysubdbi_info} = { foo => 'bar' }; | |||
| 6925 | return $sth; | |||
| 6926 | } | |||
| 6927 | ||||
| 6928 | package MySubDBI::st; | |||
| 6929 | use vars qw(@ISA); | |||
| 6930 | @ISA = qw(DBI::st); | |||
| 6931 | ||||
| 6932 | sub fetch { | |||
| 6933 | my ($sth, @args) = @_; | |||
| 6934 | my $row = $sth->SUPER::fetch(@args) | |||
| 6935 | or return; | |||
| 6936 | do_something_magical_with_row_data($row) | |||
| 6937 | or return $sth->set_err(1234, "The magic failed", undef, "fetch"); | |||
| 6938 | return $row; | |||
| 6939 | } | |||
| 6940 | ||||
| 6941 | When calling a SUPER::method that returns a handle, be careful to | |||
| 6942 | check the return value before trying to do other things with it in | |||
| 6943 | your overridden method. This is especially important if you want to | |||
| 6944 | set a hash attribute on the handle, as Perl's autovivification will | |||
| 6945 | bite you by (in)conveniently creating an unblessed hashref, which your | |||
| 6946 | method will then return with usually baffling results later on like | |||
| 6947 | the error "dbih_getcom handle HASH(0xa4451a8) is not a DBI handle (has | |||
| 6948 | no magic". It's best to check right after the call and return undef | |||
| 6949 | immediately on error, just like DBI would and just like the example | |||
| 6950 | above. | |||
| 6951 | ||||
| 6952 | If your method needs to record an error it should call the set_err() | |||
| 6953 | method with the error code and error string, as shown in the example | |||
| 6954 | above. The error code and error string will be recorded in the | |||
| 6955 | handle and available via C<$h-E<gt>err> and C<$DBI::errstr> etc. | |||
| 6956 | The set_err() method always returns an undef or empty list as | |||
| 6957 | approriate. Since your method should nearly always return an undef | |||
| 6958 | or empty list as soon as an error is detected it's handy to simply | |||
| 6959 | return what set_err() returns, as shown in the example above. | |||
| 6960 | ||||
| 6961 | If the handle has C<RaiseError>, C<PrintError>, or C<HandleError> | |||
| 6962 | etc. set then the set_err() method will honour them. This means | |||
| 6963 | that if C<RaiseError> is set then set_err() won't return in the | |||
| 6964 | normal way but will 'throw an exception' that can be caught with | |||
| 6965 | an C<eval> block. | |||
| 6966 | ||||
| 6967 | You can stash private data into DBI handles | |||
| 6968 | via C<$h-E<gt>{private_..._*}>. See the entry under L</ATTRIBUTES | |||
| 6969 | COMMON TO ALL HANDLES> for info and important caveats. | |||
| 6970 | ||||
| 6971 | ||||
| 6972 | =head1 TRACING | |||
| 6973 | ||||
| 6974 | The DBI has a powerful tracing mechanism built in. It enables you | |||
| 6975 | to see what's going on 'behind the scenes', both within the DBI and | |||
| 6976 | the drivers you're using. | |||
| 6977 | ||||
| 6978 | =head2 Trace Settings | |||
| 6979 | ||||
| 6980 | Which details are written to the trace output is controlled by a | |||
| 6981 | combination of a I<trace level>, an integer from 0 to 15, and a set | |||
| 6982 | of I<trace flags> that are either on or off. Together these are known | |||
| 6983 | as the I<trace settings> and are stored together in a single integer. | |||
| 6984 | For normal use you only need to set the trace level, and generally | |||
| 6985 | only to a value between 1 and 4. | |||
| 6986 | ||||
| 6987 | Each handle has it's own trace settings, and so does the DBI. | |||
| 6988 | When you call a method the DBI merges the handles settings into its | |||
| 6989 | own for the duration of the call: the trace flags of the handle are | |||
| 6990 | OR'd into the trace flags of the DBI, and if the handle has a higher | |||
| 6991 | trace level then the DBI trace level is raised to match it. | |||
| 6992 | The previous DBI trace setings are restored when the called method | |||
| 6993 | returns. | |||
| 6994 | ||||
| 6995 | =head2 Trace Levels | |||
| 6996 | ||||
| 6997 | Trace I<levels> are as follows: | |||
| 6998 | ||||
| 6999 | 0 - Trace disabled. | |||
| 7000 | 1 - Trace top-level DBI method calls returning with results or errors. | |||
| 7001 | 2 - As above, adding tracing of top-level method entry with parameters. | |||
| 7002 | 3 - As above, adding some high-level information from the driver | |||
| 7003 | and some internal information from the DBI. | |||
| 7004 | 4 - As above, adding more detailed information from the driver. | |||
| 7005 | This is the first level to trace all the rows being fetched. | |||
| 7006 | 5 to 15 - As above but with more and more internal information. | |||
| 7007 | ||||
| 7008 | Trace level 1 is best for a simple overview of what's happening. | |||
| 7009 | Trace levels 2 thru 4 a good choice for general purpose tracing. | |||
| 7010 | Levels 5 and above are best reserved for investigating a specific | |||
| 7011 | problem, when you need to see "inside" the driver and DBI. | |||
| 7012 | ||||
| 7013 | The trace output is detailed and typically very useful. Much of the | |||
| 7014 | trace output is formatted using the L</neat> function, so strings | |||
| 7015 | in the trace output may be edited and truncated by that function. | |||
| 7016 | ||||
| 7017 | =head2 Trace Flags | |||
| 7018 | ||||
| 7019 | Trace I<flags> are used to enable tracing of specific activities | |||
| 7020 | within the DBI and drivers. The DBI defines some trace flags and | |||
| 7021 | drivers can define others. DBI trace flag names begin with a capital | |||
| 7022 | letter and driver specific names begin with a lowercase letter, as | |||
| 7023 | usual. | |||
| 7024 | ||||
| 7025 | Curently the DBI only defines two trace flags: | |||
| 7026 | ||||
| 7027 | ALL - turn on all DBI and driver flags (not recommended) | |||
| 7028 | SQL - trace SQL statements executed (not yet implemented) | |||
| 7029 | ||||
| 7030 | The L</parse_trace_flags> and L</parse_trace_flag> methods are used | |||
| 7031 | to convert trace flag names into the coresponding integer bit flags. | |||
| 7032 | ||||
| 7033 | =head2 Enabling Trace | |||
| 7034 | ||||
| 7035 | The C<$h-E<gt>trace> method sets the trace settings for a handle | |||
| 7036 | and C<DBI-E<gt>trace> does the same for the DBI. | |||
| 7037 | ||||
| 7038 | In addition to the L</trace> method, you can enable the same trace | |||
| 7039 | information, and direct the output to a file, by setting the | |||
| 7040 | C<DBI_TRACE> environment variable before starting Perl. | |||
| 7041 | See L</DBI_TRACE> for more information. | |||
| 7042 | ||||
| 7043 | Finally, you can set, or get, the trace settings for a handle using | |||
| 7044 | the C<TraceLevel> attribute. | |||
| 7045 | ||||
| 7046 | All of those methods use parse_trace_flags() and so allow you set | |||
| 7047 | both the trace level and multiple trace flags by using a string | |||
| 7048 | containing the trace level and/or flag names separated by vertical | |||
| 7049 | bar ("C<|>") or comma ("C<,>") characters. For example: | |||
| 7050 | ||||
| 7051 | local $h->{TraceLevel} = "3|SQL|foo"; | |||
| 7052 | ||||
| 7053 | =head2 Trace Output | |||
| 7054 | ||||
| 7055 | Initially trace output is written to C<STDERR>. Both the | |||
| 7056 | C<$h-E<gt>trace> and C<DBI-E<gt>trace> methods take an optional | |||
| 7057 | $trace_file parameter, which may be either the name of a file to be | |||
| 7058 | openned by DBI in append mode, or a reference to an existing writable | |||
| 7059 | (possibly layered) filehandle. If $trace_file is a filename, | |||
| 7060 | and can be opened in append mode, or $trace_file is a writable | |||
| 7061 | filehandle, then I<all> trace output (currently including that from | |||
| 7062 | other handles) is redirected to that file. A warning is generated | |||
| 7063 | if $trace_file can't be opened or is not writable. | |||
| 7064 | ||||
| 7065 | Further calls to trace() without $trace_file do not alter where | |||
| 7066 | the trace output is sent. If $trace_file is undefined, then | |||
| 7067 | trace output is sent to C<STDERR> and, if the prior trace was openned with | |||
| 7068 | $trace_file as a filename, the previous trace file is closed; if $trace_file was | |||
| 7069 | a filehandle, the filehandle is B<not> closed. | |||
| 7070 | ||||
| 7071 | B<NOTE>: If $trace_file is specified as a filehandle, the filehandle | |||
| 7072 | should not be closed until all DBI operations are completed, or the | |||
| 7073 | application has reset the trace file via another call to | |||
| 7074 | C<trace()> that changes the trace file. | |||
| 7075 | ||||
| 7076 | =head2 Tracing to Layered Filehandles | |||
| 7077 | ||||
| 7078 | B<NOTE>: | |||
| 7079 | ||||
| 7080 | =over 4 | |||
| 7081 | ||||
| 7082 | =item * | |||
| 7083 | Tied filehandles are not currently supported, as | |||
| 7084 | tie operations are not available to the PerlIO | |||
| 7085 | methods used by the DBI. | |||
| 7086 | ||||
| 7087 | =item * | |||
| 7088 | PerlIO layer support requires Perl version 5.8 or higher. | |||
| 7089 | ||||
| 7090 | =back | |||
| 7091 | ||||
| 7092 | As of version 5.8, Perl provides the ability to layer various | |||
| 7093 | "disciplines" on an open filehandle via the L<PerlIO> module. | |||
| 7094 | ||||
| 7095 | A simple example of using PerlIO layers is to use a scalar as the output: | |||
| 7096 | ||||
| 7097 | my $scalar = ''; | |||
| 7098 | open( my $fh, "+>:scalar", \$scalar ); | |||
| 7099 | $dbh->trace( 2, $fh ); | |||
| 7100 | ||||
| 7101 | Now all trace output is simply appended to $scalar. | |||
| 7102 | ||||
| 7103 | A more complex application of tracing to a layered filehandle is the | |||
| 7104 | use of a custom layer (I<Refer to >L<Perlio::via> I<for details | |||
| 7105 | on creating custom PerlIO layers.>). Consider an application with the | |||
| 7106 | following logger module: | |||
| 7107 | ||||
| 7108 | package MyFancyLogger; | |||
| 7109 | ||||
| 7110 | sub new | |||
| 7111 | { | |||
| 7112 | my $self = {}; | |||
| 7113 | my $fh; | |||
| 7114 | open $fh, '>', 'fancylog.log'; | |||
| 7115 | $self->{_fh} = $fh; | |||
| 7116 | $self->{_buf} = ''; | |||
| 7117 | return bless $self, shift; | |||
| 7118 | } | |||
| 7119 | ||||
| 7120 | sub log | |||
| 7121 | { | |||
| 7122 | my $self = shift; | |||
| 7123 | return unless exists $self->{_fh}; | |||
| 7124 | my $fh = $self->{_fh}; | |||
| 7125 | $self->{_buf} .= shift; | |||
| 7126 | # | |||
| 7127 | # DBI feeds us pieces at a time, so accumulate a complete line | |||
| 7128 | # before outputing | |||
| 7129 | # | |||
| 7130 | print $fh "At ", scalar localtime(), ':', $self->{_buf}, "\n" and | |||
| 7131 | $self->{_buf} = '' | |||
| 7132 | if $self->{_buf}=~tr/\n//; | |||
| 7133 | } | |||
| 7134 | ||||
| 7135 | sub close { | |||
| 7136 | my $self = shift; | |||
| 7137 | return unless exists $self->{_fh}; | |||
| 7138 | my $fh = $self->{_fh}; | |||
| 7139 | print $fh "At ", scalar localtime(), ':', $self->{_buf}, "\n" and | |||
| 7140 | $self->{_buf} = '' | |||
| 7141 | if $self->{_buf}; | |||
| 7142 | close $fh; | |||
| 7143 | delete $self->{_fh}; | |||
| 7144 | } | |||
| 7145 | ||||
| 7146 | 1; | |||
| 7147 | ||||
| 7148 | To redirect DBI traces to this logger requires creating | |||
| 7149 | a package for the layer: | |||
| 7150 | ||||
| 7151 | package PerlIO::via::MyFancyLogLayer; | |||
| 7152 | ||||
| 7153 | sub PUSHED | |||
| 7154 | { | |||
| 7155 | my ($class,$mode,$fh) = @_; | |||
| 7156 | my $logger; | |||
| 7157 | return bless \$logger,$class; | |||
| 7158 | } | |||
| 7159 | ||||
| 7160 | sub OPEN { | |||
| 7161 | my ($self, $path, $mode, $fh) = @_; | |||
| 7162 | # | |||
| 7163 | # $path is actually our logger object | |||
| 7164 | # | |||
| 7165 | $$self = $path; | |||
| 7166 | return 1; | |||
| 7167 | } | |||
| 7168 | ||||
| 7169 | sub WRITE | |||
| 7170 | { | |||
| 7171 | my ($self, $buf, $fh) = @_; | |||
| 7172 | $$self->log($buf); | |||
| 7173 | return length($buf); | |||
| 7174 | } | |||
| 7175 | ||||
| 7176 | sub CLOSE { | |||
| 7177 | my $self = shift; | |||
| 7178 | $$self->close(); | |||
| 7179 | return 0; | |||
| 7180 | } | |||
| 7181 | ||||
| 7182 | 1; | |||
| 7183 | ||||
| 7184 | ||||
| 7185 | The application can then cause DBI traces to be routed to the | |||
| 7186 | logger using | |||
| 7187 | ||||
| 7188 | use PerlIO::via::MyFancyLogLayer; | |||
| 7189 | ||||
| 7190 | open my $fh, '>:via(MyFancyLogLayer)', MyFancyLogger->new(); | |||
| 7191 | ||||
| 7192 | $dbh->trace('SQL', $fh); | |||
| 7193 | ||||
| 7194 | Now all trace output will be processed by MyFancyLogger's | |||
| 7195 | log() method. | |||
| 7196 | ||||
| 7197 | =head2 Trace Content | |||
| 7198 | ||||
| 7199 | Many of the values embeded in trace output are formatted using the neat() | |||
| 7200 | utility function. This means they may be quoted, sanitized, and possibly | |||
| 7201 | truncated if longer than C<$DBI::neat_maxlen>. See L</neat> for more details. | |||
| 7202 | ||||
| 7203 | =head2 Tracing Tips | |||
| 7204 | ||||
| 7205 | You can add tracing to your own application code using the L</trace_msg> method. | |||
| 7206 | ||||
| 7207 | It can sometimes be handy to compare trace files from two different runs of the | |||
| 7208 | same script. However using a tool like C<diff> on the original log output | |||
| 7209 | doesn't work well because the trace file is full of object addresses that may | |||
| 7210 | differ on each run. | |||
| 7211 | ||||
| 7212 | The DBI includes a handy utility called dbilogstrip that can be used to | |||
| 7213 | 'normalize' the log content. It can be used as a filter like this: | |||
| 7214 | ||||
| 7215 | DBI_TRACE=2 perl yourscript.pl ...args1... 2>&1 | dbilogstrip > dbitrace1.log | |||
| 7216 | DBI_TRACE=2 perl yourscript.pl ...args2... 2>&1 | dbilogstrip > dbitrace2.log | |||
| 7217 | diff -u dbitrace1.log dbitrace2.log | |||
| 7218 | ||||
| 7219 | See L<dbilogstrip> for more information. | |||
| 7220 | ||||
| 7221 | =head1 DBI ENVIRONMENT VARIABLES | |||
| 7222 | ||||
| 7223 | The DBI module recognizes a number of environment variables, but most of | |||
| 7224 | them should not be used most of the time. | |||
| 7225 | It is better to be explicit about what you are doing to avoid the need | |||
| 7226 | for environment variables, especially in a web serving system where web | |||
| 7227 | servers are stingy about which environment variables are available. | |||
| 7228 | ||||
| 7229 | =head2 DBI_DSN | |||
| 7230 | ||||
| 7231 | The DBI_DSN environment variable is used by DBI->connect if you do not | |||
| 7232 | specify a data source when you issue the connect. | |||
| 7233 | It should have a format such as "dbi:Driver:databasename". | |||
| 7234 | ||||
| 7235 | =head2 DBI_DRIVER | |||
| 7236 | ||||
| 7237 | The DBI_DRIVER environment variable is used to fill in the database | |||
| 7238 | driver name in DBI->connect if the data source string starts "dbi::" | |||
| 7239 | (thereby omitting the driver). | |||
| 7240 | If DBI_DSN omits the driver name, DBI_DRIVER can fill the gap. | |||
| 7241 | ||||
| 7242 | =head2 DBI_AUTOPROXY | |||
| 7243 | ||||
| 7244 | The DBI_AUTOPROXY environment variable takes a string value that starts | |||
| 7245 | "dbi:Proxy:" and is typically followed by "hostname=...;port=...". | |||
| 7246 | It is used to alter the behaviour of DBI->connect. | |||
| 7247 | For full details, see DBI::Proxy documentation. | |||
| 7248 | ||||
| 7249 | =head2 DBI_USER | |||
| 7250 | ||||
| 7251 | The DBI_USER environment variable takes a string value that is used as | |||
| 7252 | the user name if the DBI->connect call is given undef (as distinct from | |||
| 7253 | an empty string) as the username argument. | |||
| 7254 | Be wary of the security implications of using this. | |||
| 7255 | ||||
| 7256 | =head2 DBI_PASS | |||
| 7257 | ||||
| 7258 | The DBI_PASS environment variable takes a string value that is used as | |||
| 7259 | the password if the DBI->connect call is given undef (as distinct from | |||
| 7260 | an empty string) as the password argument. | |||
| 7261 | Be extra wary of the security implications of using this. | |||
| 7262 | ||||
| 7263 | =head2 DBI_DBNAME (obsolete) | |||
| 7264 | ||||
| 7265 | The DBI_DBNAME environment variable takes a string value that is used only when the | |||
| 7266 | obsolescent style of DBI->connect (with driver name as fourth parameter) is used, and | |||
| 7267 | when no value is provided for the first (database name) argument. | |||
| 7268 | ||||
| 7269 | =head2 DBI_TRACE | |||
| 7270 | ||||
| 7271 | The DBI_TRACE environment variable specifies the global default | |||
| 7272 | trace settings for the DBI at startup. Can also be used to direct | |||
| 7273 | trace output to a file. When the DBI is loaded it does: | |||
| 7274 | ||||
| 7275 | DBI->trace(split /=/, $ENV{DBI_TRACE}, 2) if $ENV{DBI_TRACE}; | |||
| 7276 | ||||
| 7277 | So if C<DBI_TRACE> contains an "C<=>" character then what follows | |||
| 7278 | it is used as the name of the file to append the trace to. | |||
| 7279 | ||||
| 7280 | output appended to that file. If the name begins with a number | |||
| 7281 | followed by an equal sign (C<=>), then the number and the equal sign are | |||
| 7282 | stripped off from the name, and the number is used to set the trace | |||
| 7283 | level. For example: | |||
| 7284 | ||||
| 7285 | DBI_TRACE=1=dbitrace.log perl your_test_script.pl | |||
| 7286 | ||||
| 7287 | On Unix-like systems using a Bourne-like shell, you can do this easily | |||
| 7288 | on the command line: | |||
| 7289 | ||||
| 7290 | DBI_TRACE=2 perl your_test_script.pl | |||
| 7291 | ||||
| 7292 | See L</TRACING> for more information. | |||
| 7293 | ||||
| 7294 | =head2 PERL_DBI_DEBUG (obsolete) | |||
| 7295 | ||||
| 7296 | An old variable that should no longer be used; equivalent to DBI_TRACE. | |||
| 7297 | ||||
| 7298 | =head2 DBI_PROFILE | |||
| 7299 | ||||
| 7300 | The DBI_PROFILE environment variable can be used to enable profiling | |||
| 7301 | of DBI method calls. See L<DBI::Profile> for more information. | |||
| 7302 | ||||
| 7303 | =head2 DBI_PUREPERL | |||
| 7304 | ||||
| 7305 | The DBI_PUREPERL environment variable can be used to enable the | |||
| 7306 | use of DBI::PurePerl. See L<DBI::PurePerl> for more information. | |||
| 7307 | ||||
| 7308 | =head1 WARNING AND ERROR MESSAGES | |||
| 7309 | ||||
| 7310 | =head2 Fatal Errors | |||
| 7311 | ||||
| 7312 | =over 4 | |||
| 7313 | ||||
| 7314 | =item Can't call method "prepare" without a package or object reference | |||
| 7315 | ||||
| 7316 | The C<$dbh> handle you're using to call C<prepare> is probably undefined because | |||
| 7317 | the preceding C<connect> failed. You should always check the return status of | |||
| 7318 | DBI methods, or use the L</RaiseError> attribute. | |||
| 7319 | ||||
| 7320 | =item Can't call method "execute" without a package or object reference | |||
| 7321 | ||||
| 7322 | The C<$sth> handle you're using to call C<execute> is probably undefined because | |||
| 7323 | the preceeding C<prepare> failed. You should always check the return status of | |||
| 7324 | DBI methods, or use the L</RaiseError> attribute. | |||
| 7325 | ||||
| 7326 | =item DBI/DBD internal version mismatch | |||
| 7327 | ||||
| 7328 | The DBD driver module was built with a different version of DBI than | |||
| 7329 | the one currently being used. You should rebuild the DBD module under | |||
| 7330 | the current version of DBI. | |||
| 7331 | ||||
| 7332 | (Some rare platforms require "static linking". On those platforms, there | |||
| 7333 | may be an old DBI or DBD driver version actually embedded in the Perl | |||
| 7334 | executable being used.) | |||
| 7335 | ||||
| 7336 | =item DBD driver has not implemented the AutoCommit attribute | |||
| 7337 | ||||
| 7338 | The DBD driver implementation is incomplete. Consult the author. | |||
| 7339 | ||||
| 7340 | =item Can't [sg]et %s->{%s}: unrecognised attribute | |||
| 7341 | ||||
| 7342 | You attempted to set or get an unknown attribute of a handle. Make | |||
| 7343 | sure you have spelled the attribute name correctly; case is significant | |||
| 7344 | (e.g., "Autocommit" is not the same as "AutoCommit"). | |||
| 7345 | ||||
| 7346 | =back | |||
| 7347 | ||||
| 7348 | =head1 Pure-Perl DBI | |||
| 7349 | ||||
| 7350 | A pure-perl emulation of the DBI is included in the distribution | |||
| 7351 | for people using pure-perl drivers who, for whatever reason, can't | |||
| 7352 | install the compiled DBI. See L<DBI::PurePerl>. | |||
| 7353 | ||||
| 7354 | =head1 SEE ALSO | |||
| 7355 | ||||
| 7356 | =head2 Driver and Database Documentation | |||
| 7357 | ||||
| 7358 | Refer to the documentation for the DBD driver that you are using. | |||
| 7359 | ||||
| 7360 | Refer to the SQL Language Reference Manual for the database engine that you are using. | |||
| 7361 | ||||
| 7362 | =head2 ODBC and SQL/CLI Standards Reference Information | |||
| 7363 | ||||
| 7364 | More detailed information about the semantics of certain DBI methods | |||
| 7365 | that are based on ODBC and SQL/CLI standards is available on-line | |||
| 7366 | via microsoft.com, for ODBC, and www.jtc1sc32.org for the SQL/CLI | |||
| 7367 | standard: | |||
| 7368 | ||||
| 7369 | DBI method ODBC function SQL/CLI Working Draft | |||
| 7370 | ---------- ------------- --------------------- | |||
| 7371 | column_info SQLColumns Page 124 | |||
| 7372 | foreign_key_info SQLForeignKeys Page 163 | |||
| 7373 | get_info SQLGetInfo Page 214 | |||
| 7374 | primary_key_info SQLPrimaryKeys Page 254 | |||
| 7375 | table_info SQLTables Page 294 | |||
| 7376 | type_info SQLGetTypeInfo Page 239 | |||
| 7377 | statistics_info SQLStatistics | |||
| 7378 | ||||
| 7379 | For example, for ODBC information on SQLColumns you'd visit: | |||
| 7380 | ||||
| 7381 | http://msdn.microsoft.com/library/en-us/odbc/htm/odbcsqlcolumns.asp | |||
| 7382 | ||||
| 7383 | If that URL ceases to work then use the MSDN search facility at: | |||
| 7384 | ||||
| 7385 | http://search.microsoft.com/us/dev/ | |||
| 7386 | ||||
| 7387 | and search for C<SQLColumns returns> using the exact phrase option. | |||
| 7388 | The link you want will probably just be called C<SQLColumns> and will | |||
| 7389 | be part of the Data Access SDK. | |||
| 7390 | ||||
| 7391 | And for SQL/CLI standard information on SQLColumns you'd read page 124 of | |||
| 7392 | the (very large) SQL/CLI Working Draft available from: | |||
| 7393 | ||||
| 7394 | http://jtc1sc32.org/doc/N0701-0750/32N0744T.pdf | |||
| 7395 | ||||
| 7396 | =head2 Standards Reference Information | |||
| 7397 | ||||
| 7398 | A hyperlinked, browsable version of the BNF syntax for SQL92 (plus | |||
| 7399 | Oracle 7 SQL and PL/SQL) is available here: | |||
| 7400 | ||||
| 7401 | http://cui.unige.ch/db-research/Enseignement/analyseinfo/SQL92/BNFindex.html | |||
| 7402 | ||||
| 7403 | A BNF syntax for SQL3 is available here: | |||
| 7404 | ||||
| 7405 | http://www.sqlstandards.org/SC32/WG3/Progression_Documents/Informal_working_drafts/iso-9075-2-1999.bnf | |||
| 7406 | ||||
| 7407 | The following links provide further useful information about SQL. | |||
| 7408 | Some of these are rather dated now but may still be useful. | |||
| 7409 | ||||
| 7410 | http://www.jcc.com/SQLPages/jccs_sql.htm | |||
| 7411 | http://www.contrib.andrew.cmu.edu/~shadow/sql.html | |||
| 7412 | http://www.altavista.com/query?q=sql+tutorial | |||
| 7413 | ||||
| 7414 | ||||
| 7415 | =head2 Books and Articles | |||
| 7416 | ||||
| 7417 | Programming the Perl DBI, by Alligator Descartes and Tim Bunce. | |||
| 7418 | L<http://books.perl.org/book/154> | |||
| 7419 | ||||
| 7420 | Programming Perl 3rd Ed. by Larry Wall, Tom Christiansen & Jon Orwant. | |||
| 7421 | L<http://books.perl.org/book/134> | |||
| 7422 | ||||
| 7423 | Learning Perl by Randal Schwartz. | |||
| 7424 | L<http://books.perl.org/book/101> | |||
| 7425 | ||||
| 7426 | Details of many other books related to perl can be found at L<http://books.perl.org> | |||
| 7427 | ||||
| 7428 | =head2 Perl Modules | |||
| 7429 | ||||
| 7430 | Index of DBI related modules available from CPAN: | |||
| 7431 | ||||
| 7432 | http://search.cpan.org/search?mode=module&query=DBIx%3A%3A | |||
| 7433 | http://search.cpan.org/search?mode=doc&query=DBI | |||
| 7434 | ||||
| 7435 | For a good comparison of RDBMS-OO mappers and some OO-RDBMS mappers | |||
| 7436 | (including Class::DBI, Alzabo, and DBIx::RecordSet in the former | |||
| 7437 | category and Tangram and SPOPS in the latter) see the Perl | |||
| 7438 | Object-Oriented Persistence project pages at: | |||
| 7439 | ||||
| 7440 | http://poop.sourceforge.net | |||
| 7441 | ||||
| 7442 | A similar page for Java toolkits can be found at: | |||
| 7443 | ||||
| 7444 | http://c2.com/cgi-bin/wiki?ObjectRelationalToolComparison | |||
| 7445 | ||||
| 7446 | =head2 Mailing List | |||
| 7447 | ||||
| 7448 | The I<dbi-users> mailing list is the primary means of communication among | |||
| 7449 | users of the DBI and its related modules. For details send email to: | |||
| 7450 | ||||
| 7451 | dbi-users-help@perl.org | |||
| 7452 | ||||
| 7453 | There are typically between 700 and 900 messages per month. You have | |||
| 7454 | to subscribe in order to be able to post. However you can opt for a | |||
| 7455 | 'post-only' subscription. | |||
| 7456 | ||||
| 7457 | Mailing list archives (of variable quality) are held at: | |||
| 7458 | ||||
| 7459 | http://groups.google.com/groups?group=perl.dbi.users | |||
| 7460 | http://www.xray.mpe.mpg.de/mailing-lists/dbi/ | |||
| 7461 | http://www.mail-archive.com/dbi-users%40perl.org/ | |||
| 7462 | ||||
| 7463 | =head2 Assorted Related WWW Links | |||
| 7464 | ||||
| 7465 | The DBI "Home Page": | |||
| 7466 | ||||
| 7467 | http://dbi.perl.org/ | |||
| 7468 | ||||
| 7469 | Other DBI related links: | |||
| 7470 | ||||
| 7471 | http://tegan.deltanet.com/~phlip/DBUIdoc.html | |||
| 7472 | http://dc.pm.org/perl_db.html | |||
| 7473 | http://wdvl.com/Authoring/DB/Intro/toc.html | |||
| 7474 | http://www.hotwired.com/webmonkey/backend/tutorials/tutorial1.html | |||
| 7475 | http://bumppo.net/lists/macperl/1999/06/msg00197.html | |||
| 7476 | http://gmax.oltrelinux.com/dbirecipes.html | |||
| 7477 | ||||
| 7478 | Other database related links: | |||
| 7479 | ||||
| 7480 | http://www.jcc.com/sql_stnd.html | |||
| 7481 | http://cuiwww.unige.ch/OSG/info/FreeDB/FreeDB.home.html | |||
| 7482 | http://www.connectionstrings.com/ | |||
| 7483 | ||||
| 7484 | Security, especially the "SQL Injection" attack: | |||
| 7485 | ||||
| 7486 | http://www.ngssoftware.com/research/papers.html | |||
| 7487 | http://www.ngssoftware.com/papers/advanced_sql_injection.pdf | |||
| 7488 | http://www.ngssoftware.com/papers/more_advanced_sql_injection.pdf | |||
| 7489 | http://www.esecurityplanet.com/trends/article.php/2243461 | |||
| 7490 | http://www.spidynamics.com/papers/SQLInjectionWhitePaper.pdf | |||
| 7491 | http://www.imperva.com/application_defense_center/white_papers/blind_sql_server_injection.html | |||
| 7492 | http://online.securityfocus.com/infocus/1644 | |||
| 7493 | ||||
| 7494 | Commercial and Data Warehouse Links | |||
| 7495 | ||||
| 7496 | http://www.dwinfocenter.org | |||
| 7497 | http://www.datawarehouse.com | |||
| 7498 | http://www.datamining.org | |||
| 7499 | http://www.olapcouncil.org | |||
| 7500 | http://www.idwa.org | |||
| 7501 | http://www.knowledgecenters.org/dwcenter.asp | |||
| 7502 | ||||
| 7503 | Recommended Perl Programming Links | |||
| 7504 | ||||
| 7505 | http://language.perl.com/style/ | |||
| 7506 | ||||
| 7507 | ||||
| 7508 | =head2 FAQ | |||
| 7509 | ||||
| 7510 | See L<http://faq.dbi-support.com/> | |||
| 7511 | ||||
| 7512 | =head1 AUTHORS | |||
| 7513 | ||||
| 7514 | DBI by Tim Bunce, L<http://www.tim.bunce.name> | |||
| 7515 | ||||
| 7516 | This pod text by Tim Bunce, J. Douglas Dunlop, Jonathan Leffler and others. | |||
| 7517 | Perl by Larry Wall and the C<perl5-porters>. | |||
| 7518 | ||||
| 7519 | =head1 COPYRIGHT | |||
| 7520 | ||||
| 7521 | The DBI module is Copyright (c) 1994-2008 Tim Bunce. Ireland. | |||
| 7522 | All rights reserved. | |||
| 7523 | ||||
| 7524 | You may distribute under the terms of either the GNU General Public | |||
| 7525 | License or the Artistic License, as specified in the Perl README file. | |||
| 7526 | ||||
| 7527 | =head1 SUPPORT / WARRANTY | |||
| 7528 | ||||
| 7529 | The DBI is free Open Source software. IT COMES WITHOUT WARRANTY OF ANY KIND. | |||
| 7530 | ||||
| 7531 | =head2 Support | |||
| 7532 | ||||
| 7533 | My consulting company, Data Plan Services, offers annual and | |||
| 7534 | multi-annual support contracts for the DBI. These provide sustained | |||
| 7535 | support for DBI development, and sustained value for you in return. | |||
| 7536 | Contact me for details. | |||
| 7537 | ||||
| 7538 | =head2 Sponsor Enhancements | |||
| 7539 | ||||
| 7540 | The DBI Roadmap is available at L<http://search.cpan.org/~timb/DBI/Roadmap.pod> | |||
| 7541 | ||||
| 7542 | If your company would benefit from a specific new DBI feature, | |||
| 7543 | please consider sponsoring its development. Work is performed | |||
| 7544 | rapidly, and usually on a fixed-price payment-on-delivery basis. | |||
| 7545 | Contact me for details. | |||
| 7546 | ||||
| 7547 | Using such targeted financing allows you to contribute to DBI | |||
| 7548 | development, and rapidly get something specific and valuable in return. | |||
| 7549 | ||||
| 7550 | =head1 ACKNOWLEDGEMENTS | |||
| 7551 | ||||
| 7552 | I would like to acknowledge the valuable contributions of the many | |||
| 7553 | people I have worked with on the DBI project, especially in the early | |||
| 7554 | years (1992-1994). In no particular order: Kevin Stock, Buzz Moschetti, | |||
| 7555 | Kurt Andersen, Ted Lemon, William Hails, Garth Kennedy, Michael Peppler, | |||
| 7556 | Neil S. Briscoe, Jeff Urlwin, David J. Hughes, Jeff Stander, | |||
| 7557 | Forrest D Whitcher, Larry Wall, Jeff Fried, Roy Johnson, Paul Hudson, | |||
| 7558 | Georg Rehfeld, Steve Sizemore, Ron Pool, Jon Meek, Tom Christiansen, | |||
| 7559 | Steve Baumgarten, Randal Schwartz, and a whole lot more. | |||
| 7560 | ||||
| 7561 | Then, of course, there are the poor souls who have struggled through | |||
| 7562 | untold and undocumented obstacles to actually implement DBI drivers. | |||
| 7563 | Among their ranks are Jochen Wiedmann, Alligator Descartes, Jonathan | |||
| 7564 | Leffler, Jeff Urlwin, Michael Peppler, Henrik Tougaard, Edwin Pratomo, | |||
| 7565 | Davide Migliavacca, Jan Pazdziora, Peter Haworth, Edmund Mergl, Steve | |||
| 7566 | Williams, Thomas Lowery, and Phlip Plumlee. Without them, the DBI would | |||
| 7567 | not be the practical reality it is today. I'm also especially grateful | |||
| 7568 | to Alligator Descartes for starting work on the first edition of the | |||
| 7569 | "Programming the Perl DBI" book and letting me jump on board. | |||
| 7570 | ||||
| 7571 | The DBI and DBD::Oracle were originally developed while I was Technical | |||
| 7572 | Director (CTO) of Ingeneering in the UK (L<http://www.ig.co.uk>) (formerly known as the | |||
| 7573 | Paul Ingram Group). So I'd especially like to thank Paul for his generosity | |||
| 7574 | and vision in supporting this work for many years. | |||
| 7575 | ||||
| 7576 | A couple of specific DBI features have been sponsored by enlightened companies: | |||
| 7577 | ||||
| 7578 | The development of the swap_inner_handle() method was sponsored by BizRate.com (L<http://BizRate.com>) | |||
| 7579 | ||||
| 7580 | The development of DBD::Gofer and related modules was sponsored by | |||
| 7581 | Shopzilla.com (L<http://Shopzilla.com>), where I currently work. | |||
| 7582 | ||||
| 7583 | ||||
| 7584 | =head1 CONTRIBUTING | |||
| 7585 | ||||
| 7586 | As you can see above, many people have contributed to the DBI and | |||
| 7587 | drivers in many ways over many years. | |||
| 7588 | ||||
| 7589 | If you'd like to help then see L<http://dbi.perl.org/contributing> | |||
| 7590 | and L<http://search.cpan.org/~timb/DBI/Roadmap.pod> | |||
| 7591 | ||||
| 7592 | If you'd like the DBI to do something new or different then a good way | |||
| 7593 | to make that happen is to do it yourself and send me a patch to the | |||
| 7594 | source code that shows the changes. (But read "Speak before you patch" | |||
| 7595 | below.) | |||
| 7596 | ||||
| 7597 | =head2 Browsing the source code repository | |||
| 7598 | ||||
| 7599 | Use http://svn.perl.org/modules/dbi/trunk (basic) | |||
| 7600 | or http://svn.perl.org/viewcvs/modules/ (more useful) | |||
| 7601 | ||||
| 7602 | =head2 How to create a patch using Subversion | |||
| 7603 | ||||
| 7604 | The DBI source code is maintained using Subversion (a replacement | |||
| 7605 | for CVS, see L<http://subversion.tigris.org/>). To access the source | |||
| 7606 | you'll need to install a Subversion client. Then, to get the source | |||
| 7607 | code, do: | |||
| 7608 | ||||
| 7609 | svn checkout http://svn.perl.org/modules/dbi/trunk | |||
| 7610 | ||||
| 7611 | If it prompts for a username and password use your perl.org account | |||
| 7612 | if you have one, else just 'guest' and 'guest'. The source code will | |||
| 7613 | be in a new subdirectory called C<trunk>. | |||
| 7614 | ||||
| 7615 | To keep informed about changes to the source you can send an empty email | |||
| 7616 | to svn-commit-modules-dbi-subscribe@perl.org after which you'll get an email | |||
| 7617 | with the change log message and diff of each change checked-in to the source. | |||
| 7618 | ||||
| 7619 | After making your changes you can generate a patch file, but before | |||
| 7620 | you do, make sure your source is still upto date using: | |||
| 7621 | ||||
| 7622 | svn update | |||
| 7623 | ||||
| 7624 | If you get any conflicts reported you'll need to fix them first. | |||
| 7625 | Then generate the patch file from within the C<trunk> directory using: | |||
| 7626 | ||||
| 7627 | svn diff > foo.patch | |||
| 7628 | ||||
| 7629 | Read the patch file, as a sanity check, and then email it to dbi-dev@perl.org. | |||
| 7630 | ||||
| 7631 | =head2 How to create a patch without Subversion | |||
| 7632 | ||||
| 7633 | Unpack a fresh copy of the distribution: | |||
| 7634 | ||||
| 7635 | tar xfz DBI-1.40.tar.gz | |||
| 7636 | ||||
| 7637 | Rename the newly created top level directory: | |||
| 7638 | ||||
| 7639 | mv DBI-1.40 DBI-1.40.your_foo | |||
| 7640 | ||||
| 7641 | Edit the contents of DBI-1.40.your_foo/* till it does what you want. | |||
| 7642 | ||||
| 7643 | Test your changes and then remove all temporary files: | |||
| 7644 | ||||
| 7645 | make test && make distclean | |||
| 7646 | ||||
| 7647 | Go back to the directory you originally unpacked the distribution: | |||
| 7648 | ||||
| 7649 | cd .. | |||
| 7650 | ||||
| 7651 | Unpack I<another> copy of the original distribution you started with: | |||
| 7652 | ||||
| 7653 | tar xfz DBI-1.40.tar.gz | |||
| 7654 | ||||
| 7655 | Then create a patch file by performing a recursive C<diff> on the two | |||
| 7656 | top level directories: | |||
| 7657 | ||||
| 7658 | diff -r -u DBI-1.40 DBI-1.40.your_foo > DBI-1.40.your_foo.patch | |||
| 7659 | ||||
| 7660 | =head2 Speak before you patch | |||
| 7661 | ||||
| 7662 | For anything non-trivial or possibly controversial it's a good idea | |||
| 7663 | to discuss (on dbi-dev@perl.org) the changes you propose before | |||
| 7664 | actually spending time working on them. Otherwise you run the risk | |||
| 7665 | of them being rejected because they don't fit into some larger plans | |||
| 7666 | you may not be aware of. | |||
| 7667 | ||||
| 7668 | =head1 TRANSLATIONS | |||
| 7669 | ||||
| 7670 | A German translation of this manual (possibly slightly out of date) is | |||
| 7671 | available, thanks to O'Reilly, at: | |||
| 7672 | ||||
| 7673 | http://www.oreilly.de/catalog/perldbiger/ | |||
| 7674 | ||||
| 7675 | Some other translations: | |||
| 7676 | ||||
| 7677 | http://cronopio.net/perl/ - Spanish | |||
| 7678 | http://member.nifty.ne.jp/hippo2000/dbimemo.htm - Japanese | |||
| 7679 | ||||
| 7680 | ||||
| 7681 | =head1 TRAINING | |||
| 7682 | ||||
| 7683 | References to DBI related training resources. No recommendation implied. | |||
| 7684 | ||||
| 7685 | http://www.treepax.co.uk/ | |||
| 7686 | http://www.keller.com/dbweb/ | |||
| 7687 | ||||
| 7688 | (If you offer professional DBI related training services, | |||
| 7689 | please send me your details so I can add them here.) | |||
| 7690 | ||||
| 7691 | =head1 OTHER RELATED WORK AND PERL MODULES | |||
| 7692 | ||||
| 7693 | =over 4 | |||
| 7694 | ||||
| 7695 | =item Apache::DBI by E.Mergl@bawue.de | |||
| 7696 | ||||
| 7697 | To be used with the Apache daemon together with an embedded Perl | |||
| 7698 | interpreter like C<mod_perl>. Establishes a database connection which | |||
| 7699 | remains open for the lifetime of the HTTP daemon. This way the CGI | |||
| 7700 | connect and disconnect for every database access becomes superfluous. | |||
| 7701 | ||||
| 7702 | =item SQL Parser | |||
| 7703 | ||||
| 7704 | See also the L<SQL::Statement> module, SQL parser and engine. | |||
| 7705 | ||||
| 7706 | =back | |||
| 7707 | ||||
| 7708 | =cut | |||
# spent 16µs within DBD::_::common::trace_msg which was called
# once (16µs+0s) by DBI::END at line 506 of /usr/lib/perl5/DBI.pm | ||||
# spent 581µs within DBI::_install_method which was called 88 times, avg 7µs/call:
# 88 times (581µs+0s) at line 489 of /usr/lib/perl5/DBI.pm, avg 7µs/call | ||||
# spent 9.07ms within DBI::_new_handle which was called 509 times, avg 18µs/call:
# 507 times (8.97ms+0s) by DBI::_new_sth at line 1252 of /usr/lib/perl5/DBI.pm, avg 18µs/call
# once (64µs+0s) by DBI::_new_drh at line 1212 of /usr/lib/perl5/DBI.pm
# once (37µs+0s) by DBI::_new_dbh at line 1242 of /usr/lib/perl5/DBI.pm | ||||
# spent 326µs within DBI::bootstrap which was called
# once (326µs+0s) by DynaLoader::bootstrap at line 219 of /usr/lib/perl/5.10/DynaLoader.pm |